3 * utils.php - Misc utils common to all aspects of the site
5 * Copyright 1999-2001 (c) VA Linux Systems
9 * This file is part of GForge.
11 * GForge is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * GForge is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with GForge; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 US
28 * removeCRLF() - remove any Carriage Return-Line Feed from a string.
29 * That function is useful to remove the possibility of a CRLF Injection when sending mail
30 * All the data that we will send should be passed through that function
32 * @param string The string that we want to empty from any CRLF
34 function util_remove_CRLF($str) {
35 return strtr($str, "\015\012", ' ');
40 * util_check_fileupload() - determines if a filename is appropriate for upload
42 * @param array The uploaded file as returned by getUploadedFile()
44 function util_check_fileupload($filename) {
46 /* Empty file is a valid file.
47 This is because this function should be called
48 unconditionally at the top of submit action processing
49 and many forms have optional file upload. */
50 if ($filename == 'none' || $filename == '') {
54 /* This should be enough... */
55 if (!is_uploaded_file($filename)) {
58 /* ... but we'd rather be paranoic */
59 if (strstr($filename, '..')) {
62 if (!is_file($filename)) {
65 if (!file_exists($filename)) {
68 if ((dirname($filename) != '/tmp') &&
69 (dirname($filename) != "/var/tmp")) {
76 * util_send_message() - Send email
77 * This function should be used in place of the PHP mail() function
79 * @param string The email recipients address
80 * @param string The email subject
81 * @param string The body of the email message
82 * @param string The optional email sender address. Defaults to 'noreply@'
83 * @param string The addresses to blind-carbon-copy this message
84 * @param string The optional email sender name. Defaults to ''
85 * @param boolean Whether to send plain text or html email
88 function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='',$send_html_email=false) {
89 global $Language,$sys_bcc_all_email_address,$sys_sendmail_path;
92 $to='noreply@'.$GLOBALS['sys_default_domain'];
95 $from='noreply@'.$GLOBALS['sys_default_domain'];
99 $charset = $Language->getText('conf','mail_charset');
105 if ($extra_headers) {
106 $body2 .= $extra_headers."\n";
109 "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset);
110 if (!empty($sys_bcc_all_email_address)) {
111 $BCC.=",$sys_bcc_all_email_address";
114 $body2 .= "\nBCC: $BCC";
116 $send_html_email?$type="html":$type="plain";
117 $body2 .= "\nSubject: ".util_encode_mimeheader($subject, $charset).
118 "\nContent-type: text/$type; charset=$charset".
120 util_convert_body($body, $charset);
122 if (!$sys_sendmail_path){
123 $sys_sendmail_path="/usr/sbin/sendmail";
126 exec ("/bin/echo \"". util_prep_string_for_sendmail($body2) .
127 "\" | ".$sys_sendmail_path." -f'$from' -t -i > /dev/null 2>&1 &");
128 // WARNING : popen commented code probably brought some trouble, we will use the pipe method as we were before
129 /*if (!$handle = popen($sys_sendmail_path." -f'$from' -t -i", "w")) {
130 echo "<p>Error: cannot run '$sys_sendmail_path' - mail not sent</p>\n";
132 fwrite($handle, util_prep_string_for_sendmail($body2));
138 * util_encode_mailaddr() - Encode email address to MIME format
140 * @param string The email address
141 * @param string The email's owner name
142 * @param string The converting charset
145 function util_encode_mailaddr($email,$name,$charset) {
146 if (function_exists('mb_convert_encoding') && trim($name) != "") {
147 $name = "=?".$charset."?B?".
148 base64_encode(mb_convert_encoding(
149 $name,$charset,"UTF-8")).
153 return $name." <".$email."> ";
157 * util_encode_mimeheader() - Encode mimeheader
159 * @param string The email subject
160 * @param string The converting charset (like ISO-2022-JP)
161 * @return string The MIME encoded subject
164 function util_encode_mimeheader($str,$charset) {
165 if (!function_exists('mb_convert_encoding')) {
169 return "=?".$charset."?B?".
170 base64_encode(mb_convert_encoding(
171 $str,$charset,"UTF-8")).
176 * util_convert_body() - Convert body of the email message
178 * @param string The body of the email message
179 * @param string The charset of the email message
180 * @return string The converted body of the email message
183 function util_convert_body($str,$charset) {
184 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
188 return mb_convert_encoding($str,$charset,"UTF-8");
191 function util_send_jabber($to,$subject,$body) {
192 if (!$GLOBALS['sys_use_jabber']) {
195 $JABBER = new Jabber();
196 if (!$JABBER->Connect()) {
197 echo '<br />Unable to connect';
200 //$JABBER->SendAuth();
201 //$JABBER->AccountRegistration();
202 if (!$JABBER->SendAuth()) {
203 echo '<br />Auth Failure';
204 $JABBER->Disconnect();
206 //or die("Couldn't authenticate!");
208 $JABBER->SendPresence(NULL, NULL, "online");
210 $body=htmlspecialchars($body);
211 $to_arr=explode(',',$to);
212 for ($i=0; $i<count($to_arr); $i++) {
214 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
215 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
216 echo '<br />Error Sending to '.$to_arr[$i];
221 $JABBER->CruiseControl(2);
222 $JABBER->Disconnect();
226 * util_prep_string_for_sendmail() - Prepares a string to be sent by email
228 * @param string The text to be prepared
229 * @returns The prepared text
232 function util_prep_string_for_sendmail($body) {
233 //$body=str_replace("\\","\\\\",$body);
234 $body=str_replace("`","\\`",$body);
235 $body=str_replace("\"","\\\"",$body);
236 $body=str_replace("\$","\\\$",$body);
241 * util_handle_message() - a convenience wrapper which sends messages
242 * to either a jabber account or email account or both, depending on
245 * @param array array of user_id's from the user table
246 * @param string subject of the message
247 * @param string the message body
248 * @param string a comma-separated list of email address
249 * @param string a comma-separated list of jabber address
250 * @param string From header
252 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='',$from='') {
255 if (count($id_arr) < 1) {
258 $res=db_query("SELECT user_id, jabber_address,email,jabber_only
259 FROM users WHERE user_id IN (". implode($id_arr,',') .")");
260 $rows=db_numrows($res);
262 for ($i=0; $i<$rows; $i++) {
263 if (db_result($res, $i, 'user_id') == 100) {
264 // Do not send messages to "Nobody"
268 // Build arrays of the jabber address
270 if (db_result($res,$i,'jabber_address')) {
271 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
272 if (db_result($res,$i,'jabber_only') != 1) {
273 $address['email'][]=db_result($res,$i,'email');
276 $address['email'][]=db_result($res,$i,'email');
279 if (count($address['email']) > 0) {
280 $extra_email1=implode($address['email'],',').',';
282 if (count($address['jabber_address']) > 0) {
283 $extra_jabber1=implode($address['jabber_address'],',').',';
286 if ($extra_email1 || $extra_emails) {
287 util_send_message('',$subject,$body,$from,$extra_email1.$extra_emails);
289 if ($extra_jabber1 || $extra_jabbers) {
290 util_send_jabber($extra_jabber1.$extra_jabbers,$subject,$body);
295 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
296 * This function requires PHP 4.0.3 or greater
298 * @param string The string to unconvert
299 * @returns The unconverted string
302 function util_unconvert_htmlspecialchars($string) {
303 if (strlen($string) < 1) {
306 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
307 $trans = get_html_translation_table(HTML_ENTITIES);
308 $trans = array_flip ($trans);
309 $str = strtr ($string, $trans);
315 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
317 * @param string The result set ID
318 * @param int The column key
319 * @param int The optional column value
320 * @returns An associative array
323 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
324 $rows=db_numrows($result);
328 for ($i=0; $i<$rows; $i++) {
329 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
338 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
340 * @param int The result set ID
341 * @param int The column
345 function &util_result_column_to_array($result, $col=0) {
347 Takes a result set and turns the optional column into
350 $rows=db_numrows($result);
354 for ($i=0; $i<$rows; $i++) {
355 $arr[$i]=db_result($result,$i,$col);
364 * util_wrap_find_space() - Find the first space in a string
366 * @param string The string in which to find the space (must be UTF8!)
367 * @param int The number of characters to wrap - Default is 80
368 * @returns The position of the first space
371 function util_wrap_find_space($string,$wrap) {
378 //find the first space starting at $start
379 $pos=@strpos($string,' ',$start);
381 //if that space is too far over, go back and start more to the left
382 if (($pos > ($wrap+5)) || !$pos) {
384 $start=($wrap-($try*5));
385 //if we've gotten so far left , just truncate the line
388 $code = ord(substr($string,$wrap,1));
391 //Here is single byte character
392 //or head of multi byte character
395 //Do not break multi byte character
410 * util_line_wrap() - Automatically linewrap text
412 * @param string The text to wrap
413 * @param int The number of characters to wrap - Default is 80
414 * @param string The line break to use - Default is '\n'
415 * @returns The wrapped text
418 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
419 $paras = explode("\n", $text);
423 while ($i < count($paras)) {
424 if (strlen($paras[$i]) <= $wrap) {
425 $result[] = $paras[$i];
428 $pos=util_wrap_find_space($paras[$i],$wrap);
430 $result[] = substr($paras[$i], 0, $pos);
432 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
435 $pos=util_wrap_find_space($paras[$i],$wrap);
441 return implode($break, $result);
445 * util_make_links() - Turn URL's into HREF's.
447 * @param string The URL
448 * @returns The HREF'ed URL
451 function util_make_links ($data='') {
455 $lines = split("\n",$data);
457 while ( list ($key,$line) = each ($lines)) {
458 // When we come here, we usually have form input
459 // encoded in entities. Our aim is to NOT include
460 // angle brackets in the URL
461 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
462 $line = str_replace('>', "\1", $line);
463 $line = eregi_replace("([ \t]|^)www\."," http://www.",$line);
464 $text = eregi_replace("([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
465 $text = eregi_replace("([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $text);
466 $text = str_replace("\1", '>', $text);
473 * show_priority_colors_key() - Show the priority colors legend
476 function show_priority_colors_key() {
478 echo '<p /><strong> '.$Language->getText('common_utils','priority_colors').':</strong><br />
480 <table border="0"><tr>';
482 for ($i=1; $i<6; $i++) {
484 <td class="priority'.$i.'">'.$i.'</td>';
486 echo '</tr></table>';
490 * utils_buildcheckboxarray() - Build a checkbox array
492 * @param int Number of options to be in the array
493 * @param string The name of the checkboxes
494 * @param array An array of boxes to be pre-checked
497 function utils_buildcheckboxarray($options,$name,$checked_array) {
498 $option_count=count($options);
499 $checked_count=count($checked_array);
501 for ($i=1; $i<=$option_count; $i++) {
503 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
504 for ($j=0; $j<$checked_count; $j++) {
505 if ($i == $checked_array[$j]) {
509 echo '> '.$options[$i];
514 * utils_requiredField() - Adds the required field marker
516 * @return a string holding the HTML to mark a required field
518 function utils_requiredField() {
519 return '<span class="requiredfield">*</span>';
523 * GraphResult() - Takes a database result set and builds a graph.
524 * The first column should be the name, and the second column should be the values
525 * Be sure to include HTL_Graphs.php before using this function
527 * @author Tim Perdue tperdue@valinux.com
528 * @param int The databse result set ID
529 * @param string The title of the graph
532 Function GraphResult($result,$title) {
533 $rows=db_numrows($result);
535 if ((!$result) || ($rows < 1)) {
541 for ($j=0; $j<db_numrows($result); $j++) {
542 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
543 $names[$j]= db_result($result, $j, 0);
544 $values[$j]= db_result($result, $j, 1);
549 This is another function detailed below
551 GraphIt($names,$values,$title);
556 * GraphIt() - Build a graph
558 * @author Tim Perdue tperdue@valinux.com
559 * @param array An array of names
560 * @param array An array of values
561 * @param string The title of the graph
564 Function GraphIt($name_string,$value_string,$title) {
567 $counter=count($name_string);
570 Can choose any color you wish
574 for ($i = 0; $i < $counter; $i++) {
575 $bars[$i]=$HTML->COLOR_LTBACK1;
578 $counter=count($value_string);
581 Figure the max_value passed in, so scale can be determined
586 for ($i = 0; $i < $counter; $i++) {
587 if ($value_string[$i] > $max_value) {
588 $max_value=$value_string[$i];
592 if ($max_value < 1) {
597 I want my graphs all to be 800 pixels wide, so that is my divisor
600 $scale=(400/$max_value);
603 I create a wrapper table around the graph that holds the title
609 echo $GLOBALS['HTML']->listTableTop ($title_arr);
612 Create an associate array to pass in. I leave most of it blank
641 This is the actual call to the HTML_Graphs class
644 html_graph($name_string,$value_string,$bars,$vals);
648 <!-- end outer graph table -->';
649 echo $GLOBALS['HTML']->listTableBottom();
653 * ShowResultSet() - Show a generic result set
654 * Very simple, plain way to show a generic result set
656 * @param int The result set ID
657 * @param string The title of the result set
658 * @param bool The option to turn URL's into links
659 * @param bool The option to display headers
660 * @param array The db field name -> label mapping
661 * @param array Don't display these cols
664 function ShowResultSet($result,$title='',$linkify=false,$displayHeaders=true,$headerMapping=array(), $excludedCols=array()) {
665 global $group_id,$HTML;
668 $rows = db_numrows($result);
669 $cols = db_numfields($result);
671 echo '<table border="0" width="100%">';
673 /* Create the headers */
674 $headersCellData = array();
675 $colsToKeep = array();
676 for ($i=0; $i < $cols; $i++) {
677 $fieldName = db_fieldname($result, $i);
678 if(in_array($fieldName, $excludedCols)) {
682 if(isset($headerMapping[$fieldName])) {
683 if(is_array($headerMapping[$fieldName])) {
684 $headersCellData[] = $headerMapping[$fieldName];
686 $headersCellData[] = array($headerMapping[$fieldName]);
690 $headersCellData[] = array($fieldName);
694 /* Create the title */
695 if(strlen($title) > 0) {
696 $titleCellData = array();
697 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
698 echo $HTML->multiTableRow('', $titleCellData, TRUE);
701 /* Display the headers */
702 if($displayHeaders) {
703 echo $HTML->multiTableRow('', $headersCellData, TRUE);
706 /* Create the rows */
707 for ($j = 0; $j < $rows; $j++) {
708 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
709 for ($i = 0; $i < $cols; $i++) {
710 if(in_array($i, $colsToKeep)) {
711 if ($linkify && $i == 0) {
712 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
714 if ($linkify == "bug_cat") {
715 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
716 } else if($linkify == "bug_group") {
717 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
718 } else if($linkify == "patch_cat") {
719 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
720 } else if($linkify == "support_cat") {
721 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
722 } else if($linkify == "pm_project") {
723 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
725 $link = $linkend = '';
728 $link = $linkend = '';
730 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
742 * validate_email() - Validate an email address
744 * @param string The address string to validate
745 * @returns true on success/false on error
748 function validate_email ($address) {
749 return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address));
753 * validate_emails() - Validate a list of e-mail addresses
755 * @param string E-mail list
756 * @param char Separator
757 * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
759 function validate_emails ($addresses, $separator=',') {
760 if (strlen($addresses) == 0) return array();
762 $emails = explode($separator, $addresses);
765 if (is_array($emails)) {
766 foreach ($emails as $email) {
767 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
768 if (!validate_email($email)) $ret[] = $email;
777 * util_is_valid_filename() - Verifies whether a file has a valid filename
779 * @param string The file to verify
780 * @returns true on success/false on error
783 function util_is_valid_filename ($file) {
785 $invalidchars = eregi_replace("[-A-Z0-9_\.]","",$file);
787 if (!empty($invalidchars)) {
790 if (strstr($file,'..')) {
799 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
801 * @param string The optional hostname string
802 * @returns true on success/false on failur
805 function valid_hostname ($hostname = "xyz") {
808 $invalidchars = eregi_replace("[-A-Z0-9\.]","",$hostname);
810 if (!empty($invalidchars)) {
814 //double dot, starts with a . or -
815 if (ereg("\.\.",$hostname) || ereg("^\.",$hostname) || ereg("^\-",$hostname)) {
819 $multipoint = explode(".",$hostname);
821 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
831 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
833 * Format file size in a human-readable way
834 * such as "xx Megabytes" or "xx Mo"
836 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
838 * @param int bytes is the size
839 * @param bool base10 enable base 10 representation, otherwise
840 * default base 2 is used
841 * @param int round number of fractional digits
842 * @param array labels strings associated to each 2^10 or
843 * 10^3(base10==true) multiple of base units
845 function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array(' bytes', ' KB', ' MB', ' GB')) {
846 if ($bytes <= 0 || !is_array($labels) || (count($labels) <= 0)) {
849 $step = $base10 ? 3 : 10;
850 $base = $base10 ? 10 : 2;
851 $log = (int)(log10($bytes)/log10($base));
853 foreach ($labels as $p=>$lab) {
861 $text = round($bytes/pow($base,$pow),$round).$lab;
868 * ls - lists a specified directory and returns an array of files
869 * @param string the path of the directory to list
870 * @param boolean whether to filter out directories and illegal filenames
871 * @return array array of file names.
873 function &ls($dir,$filter=false) {
874 exec('ls -c1 '.$dir,$out);
876 for ($i=0; $i<count($out); $i++) {
877 if (util_is_valid_filename($out[$i]) && is_file($dir.'/'.$out[$i])) {
878 $filtered[]=$out[$i];
888 * readfile_chunked() - replacement for readfile
890 * @param string The file path
891 * @param bool Whether to return bytes served or just a bool
894 function readfile_chunked($filename, $returnBytes=true) {
895 $chunksize = 1*(1024*1024); // 1MB chunks
899 $handle = fopen($filename, 'rb');
900 if ($handle === false) {
904 while (!feof($handle)) {
905 $buffer = fread($handle, $chunksize);
908 $byteCounter += strlen($buffer);
911 $status = fclose($handle);
912 if ($returnBytes && $status) {
913 return $byteCounter; // return num. bytes delivered like readfile() does.
919 * util_is_root_dir() - Checks if a directory points to the root dir
920 * @param string Directory
923 function util_is_root_dir($dir) {
924 return !preg_match('/[^\\/]/',$dir);