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 $sys_bcc_all_email_address,$sys_sendmail_path;
92 $to='noreply@'.$GLOBALS['sys_default_domain'];
95 $from='noreply@'.$GLOBALS['sys_default_domain'];
99 $charset = _('UTF-8');
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 = escapeshellarg($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() {
477 echo '<p /><strong> '._('Priority Colors').':</strong><br />
479 <table border="0"><tr>';
481 for ($i=1; $i<6; $i++) {
483 <td class="priority'.$i.'">'.$i.'</td>';
485 echo '</tr></table>';
489 * utils_buildcheckboxarray() - Build a checkbox array
491 * @param int Number of options to be in the array
492 * @param string The name of the checkboxes
493 * @param array An array of boxes to be pre-checked
496 function utils_buildcheckboxarray($options,$name,$checked_array) {
497 $option_count=count($options);
498 $checked_count=count($checked_array);
500 for ($i=1; $i<=$option_count; $i++) {
502 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
503 for ($j=0; $j<$checked_count; $j++) {
504 if ($i == $checked_array[$j]) {
508 echo '> '.$options[$i];
513 * utils_requiredField() - Adds the required field marker
515 * @return a string holding the HTML to mark a required field
517 function utils_requiredField() {
518 return '<span class="requiredfield">*</span>';
522 * GraphResult() - Takes a database result set and builds a graph.
523 * The first column should be the name, and the second column should be the values
524 * Be sure to include HTL_Graphs.php before using this function
526 * @author Tim Perdue tperdue@valinux.com
527 * @param int The databse result set ID
528 * @param string The title of the graph
531 Function GraphResult($result,$title) {
532 $rows=db_numrows($result);
534 if ((!$result) || ($rows < 1)) {
540 for ($j=0; $j<db_numrows($result); $j++) {
541 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
542 $names[$j]= db_result($result, $j, 0);
543 $values[$j]= db_result($result, $j, 1);
548 This is another function detailed below
550 GraphIt($names,$values,$title);
555 * GraphIt() - Build a graph
557 * @author Tim Perdue tperdue@valinux.com
558 * @param array An array of names
559 * @param array An array of values
560 * @param string The title of the graph
563 Function GraphIt($name_string,$value_string,$title) {
566 $counter=count($name_string);
569 Can choose any color you wish
573 for ($i = 0; $i < $counter; $i++) {
574 $bars[$i]=$HTML->COLOR_LTBACK1;
577 $counter=count($value_string);
580 Figure the max_value passed in, so scale can be determined
585 for ($i = 0; $i < $counter; $i++) {
586 if ($value_string[$i] > $max_value) {
587 $max_value=$value_string[$i];
591 if ($max_value < 1) {
596 I want my graphs all to be 800 pixels wide, so that is my divisor
599 $scale=(400/$max_value);
602 I create a wrapper table around the graph that holds the title
608 echo $GLOBALS['HTML']->listTableTop ($title_arr);
611 Create an associate array to pass in. I leave most of it blank
640 This is the actual call to the HTML_Graphs class
643 html_graph($name_string,$value_string,$bars,$vals);
647 <!-- end outer graph table -->';
648 echo $GLOBALS['HTML']->listTableBottom();
652 * ShowResultSet() - Show a generic result set
653 * Very simple, plain way to show a generic result set
655 * @param int The result set ID
656 * @param string The title of the result set
657 * @param bool The option to turn URL's into links
658 * @param bool The option to display headers
659 * @param array The db field name -> label mapping
660 * @param array Don't display these cols
663 function ShowResultSet($result,$title='',$linkify=false,$displayHeaders=true,$headerMapping=array(), $excludedCols=array()) {
664 global $group_id,$HTML;
667 $rows = db_numrows($result);
668 $cols = db_numfields($result);
670 echo '<table border="0" width="100%">';
672 /* Create the headers */
673 $headersCellData = array();
674 $colsToKeep = array();
675 for ($i=0; $i < $cols; $i++) {
676 $fieldName = db_fieldname($result, $i);
677 if(in_array($fieldName, $excludedCols)) {
681 if(isset($headerMapping[$fieldName])) {
682 if(is_array($headerMapping[$fieldName])) {
683 $headersCellData[] = $headerMapping[$fieldName];
685 $headersCellData[] = array($headerMapping[$fieldName]);
689 $headersCellData[] = array($fieldName);
693 /* Create the title */
694 if(strlen($title) > 0) {
695 $titleCellData = array();
696 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
697 echo $HTML->multiTableRow('', $titleCellData, TRUE);
700 /* Display the headers */
701 if($displayHeaders) {
702 echo $HTML->multiTableRow('', $headersCellData, TRUE);
705 /* Create the rows */
706 for ($j = 0; $j < $rows; $j++) {
707 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
708 for ($i = 0; $i < $cols; $i++) {
709 if(in_array($i, $colsToKeep)) {
710 if ($linkify && $i == 0) {
711 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
713 if ($linkify == "bug_cat") {
714 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
715 } else if($linkify == "bug_group") {
716 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
717 } else if($linkify == "patch_cat") {
718 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
719 } else if($linkify == "support_cat") {
720 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
721 } else if($linkify == "pm_project") {
722 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
724 $link = $linkend = '';
727 $link = $linkend = '';
729 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
741 * validate_email() - Validate an email address
743 * @param string The address string to validate
744 * @returns true on success/false on error
747 function validate_email ($address) {
748 return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address));
752 * validate_emails() - Validate a list of e-mail addresses
754 * @param string E-mail list
755 * @param char Separator
756 * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
758 function validate_emails ($addresses, $separator=',') {
759 if (strlen($addresses) == 0) return array();
761 $emails = explode($separator, $addresses);
764 if (is_array($emails)) {
765 foreach ($emails as $email) {
766 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
767 if (!validate_email($email)) $ret[] = $email;
776 * util_is_valid_filename() - Verifies whether a file has a valid filename
778 * @param string The file to verify
779 * @returns true on success/false on error
782 function util_is_valid_filename ($file) {
784 $invalidchars = eregi_replace("[-A-Z0-9+_\.]","",$file);
786 if (!empty($invalidchars)) {
789 if (strstr($file,'..')) {
798 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
800 * @param string The optional hostname string
801 * @returns true on success/false on failur
804 function valid_hostname ($hostname = "xyz") {
807 $invalidchars = eregi_replace("[-A-Z0-9\.]","",$hostname);
809 if (!empty($invalidchars)) {
813 //double dot, starts with a . or -
814 if (ereg("\.\.",$hostname) || ereg("^\.",$hostname) || ereg("^\-",$hostname)) {
818 $multipoint = explode(".",$hostname);
820 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
830 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
832 * Format file size in a human-readable way
833 * such as "xx Megabytes" or "xx Mo"
835 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
837 * @param int bytes is the size
838 * @param bool base10 enable base 10 representation, otherwise
839 * default base 2 is used
840 * @param int round number of fractional digits
841 * @param array labels strings associated to each 2^10 or
842 * 10^3(base10==true) multiple of base units
844 function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array(' bytes', ' KB', ' MB', ' GB')) {
845 if ($bytes <= 0 || !is_array($labels) || (count($labels) <= 0)) {
848 $step = $base10 ? 3 : 10;
849 $base = $base10 ? 10 : 2;
850 $log = (int)(log10($bytes)/log10($base));
852 foreach ($labels as $p=>$lab) {
857 if ($lab == " MB" or $lab == " GB") {
860 $text = round($bytes/pow($base,$pow),$round).$lab;
867 * ls - lists a specified directory and returns an array of files
868 * @param string the path of the directory to list
869 * @param boolean whether to filter out directories and illegal filenames
870 * @return array array of file names.
872 function &ls($dir,$filter=false) {
873 exec('ls -c1 '.$dir,$out);
875 for ($i=0; $i<count($out); $i++) {
876 if (util_is_valid_filename($out[$i]) && is_file($dir.'/'.$out[$i])) {
877 $filtered[]=$out[$i];
887 * readfile_chunked() - replacement for readfile
889 * @param string The file path
890 * @param bool Whether to return bytes served or just a bool
893 function readfile_chunked($filename, $returnBytes=true) {
894 $chunksize = 1*(1024*1024); // 1MB chunks
898 $handle = fopen($filename, 'rb');
899 if ($handle === false) {
903 while (!feof($handle)) {
904 $buffer = fread($handle, $chunksize);
907 $byteCounter += strlen($buffer);
910 $status = fclose($handle);
911 if ($returnBytes && $status) {
912 return $byteCounter; // return num. bytes delivered like readfile() does.
918 * util_is_root_dir() - Checks if a directory points to the root dir
919 * @param string Directory
922 function util_is_root_dir($dir) {
923 return !preg_match('/[^\\/]/',$dir);
926 function util_make_url ($path) {
927 if ($GLOBALS['sys_use_ssl'])
932 $url .= $GLOBALS['sys_default_domain'] ;
933 $url .= $GLOBALS['sys_urlprefix'] ;
935 $path = ereg_replace ("^/", "", $path) ;
940 function util_make_link ($path, $text, $extra_params=false) {
942 if (is_array($extra_params)) {
943 foreach ($extra_params as $key => $value) {
944 $ep .= "$key=\"$value\" ";
947 return '<a ' . $ep . 'href="' . util_make_url ($path) . '">' . $text . '</a>' ;
952 // c-file-style: "bsd"