3 * FusionForge miscellaneous utils
5 * Copyright 1999-2001, VA Linux Systems, Inc.
7 * This file is part of FusionForge.
9 * FusionForge is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published
11 * by the Free Software Foundation; either version 2 of the License,
12 * or (at your option) any later version.
14 * FusionForge is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with FusionForge; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
26 * removeCRLF() - remove any Carriage Return-Line Feed from a string.
27 * That function is useful to remove the possibility of a CRLF Injection when sending mail
28 * All the data that we will send should be passed through that function
30 * @param string The string that we want to empty from any CRLF
32 function util_remove_CRLF($str) {
33 return strtr($str, "\015\012", ' ');
38 * util_check_fileupload() - determines if a filename is appropriate for upload
40 * @param array The uploaded file as returned by getUploadedFile()
42 function util_check_fileupload($filename) {
44 /* Empty file is a valid file.
45 This is because this function should be called
46 unconditionally at the top of submit action processing
47 and many forms have optional file upload. */
48 if ($filename == 'none' || $filename == '') {
52 /* This should be enough... */
53 if (!is_uploaded_file($filename)) {
56 /* ... but we'd rather be paranoic */
57 if (strstr($filename, '..')) {
60 if (!is_file($filename)) {
63 if (!file_exists($filename)) {
66 if ((dirname($filename) != '/tmp') &&
67 (dirname($filename) != "/var/tmp")) {
74 * util_send_message() - Send email
75 * This function should be used in place of the PHP mail() function
77 * @param string The email recipients address
78 * @param string The email subject
79 * @param string The body of the email message
80 * @param string The optional email sender address. Defaults to 'noreply@'
81 * @param string The addresses to blind-carbon-copy this message
82 * @param string The optional email sender name. Defaults to ''
83 * @param boolean Whether to send plain text or html email
86 function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='',$send_html_email=false) {
87 global $sys_bcc_all_email_address,$sys_sendmail_path;
90 $to='noreply@'.$GLOBALS['sys_default_domain'];
93 $from='noreply@'.$GLOBALS['sys_default_domain'];
97 $charset = _('UTF-8');
103 if ($extra_headers) {
104 $body2 .= $extra_headers."\n";
107 "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset);
108 if (!empty($sys_bcc_all_email_address)) {
109 $BCC.=",$sys_bcc_all_email_address";
112 $body2 .= "\nBCC: $BCC";
114 $send_html_email?$type="html":$type="plain";
115 $body2 .= "\nSubject: ".util_encode_mimeheader($subject, $charset).
116 "\nContent-type: text/$type; charset=$charset".
118 util_convert_body($body, $charset);
120 if (!$sys_sendmail_path){
121 $sys_sendmail_path="/usr/sbin/sendmail";
124 exec ("/bin/echo ". util_prep_string_for_sendmail($body2) .
125 " | ".$sys_sendmail_path." -f'$from' -t -i > /dev/null 2>&1 &");
126 // WARNING : popen commented code probably brought some trouble, we will use the pipe method as we were before
127 /*if (!$handle = popen($sys_sendmail_path." -f'$from' -t -i", "w")) {
128 echo "<p>Error: cannot run '$sys_sendmail_path' - mail not sent</p>\n";
130 fwrite($handle, util_prep_string_for_sendmail($body2));
136 * util_encode_mailaddr() - Encode email address to MIME format
138 * @param string The email address
139 * @param string The email's owner name
140 * @param string The converting charset
143 function util_encode_mailaddr($email,$name,$charset) {
144 if (function_exists('mb_convert_encoding') && trim($name) != "") {
145 $name = "=?".$charset."?B?".
146 base64_encode(mb_convert_encoding(
147 $name,$charset,"UTF-8")).
151 return $name." <".$email."> ";
155 * util_encode_mimeheader() - Encode mimeheader
157 * @param string The email subject
158 * @param string The converting charset (like ISO-2022-JP)
159 * @return string The MIME encoded subject
162 function util_encode_mimeheader($str,$charset) {
163 if (!function_exists('mb_convert_encoding')) {
167 return "=?".$charset."?B?".
168 base64_encode(mb_convert_encoding(
169 $str,$charset,"UTF-8")).
174 * util_convert_body() - Convert body of the email message
176 * @param string The body of the email message
177 * @param string The charset of the email message
178 * @return string The converted body of the email message
181 function util_convert_body($str,$charset) {
182 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
186 return mb_convert_encoding($str,$charset,"UTF-8");
189 function util_send_jabber($to,$subject,$body) {
190 if (!$GLOBALS['sys_use_jabber']) {
193 $JABBER = new Jabber();
194 if (!$JABBER->Connect()) {
195 echo '<br />Unable to connect';
198 //$JABBER->SendAuth();
199 //$JABBER->AccountRegistration();
200 if (!$JABBER->SendAuth()) {
201 echo '<br />Auth Failure';
202 $JABBER->Disconnect();
204 //or die("Couldn't authenticate!");
206 $JABBER->SendPresence(NULL, NULL, "online");
208 $body=htmlspecialchars($body);
209 $to_arr=explode(',',$to);
210 for ($i=0; $i<count($to_arr); $i++) {
212 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
213 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
214 echo '<br />Error Sending to '.$to_arr[$i];
219 $JABBER->CruiseControl(2);
220 $JABBER->Disconnect();
224 * util_prep_string_for_sendmail() - Prepares a string to be sent by email
226 * @param string The text to be prepared
227 * @returns The prepared text
230 function util_prep_string_for_sendmail($body) {
231 /*$body=str_replace("`","\\`",$body);
232 $body=str_replace("\"","\\\"",$body);
233 $body=str_replace("\$","\\\$",$body);*/
234 $body = escapeshellarg($body);
239 * util_handle_message() - a convenience wrapper which sends messages
240 * to either a jabber account or email account or both, depending on
243 * @param array array of user_id's from the user table
244 * @param string subject of the message
245 * @param string the message body
246 * @param string a comma-separated list of email address
247 * @param string a comma-separated list of jabber address
248 * @param string From header
250 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='',$from='') {
253 if (count($id_arr) < 1) {
256 $res=db_query("SELECT user_id, jabber_address,email,jabber_only
257 FROM users WHERE user_id IN (". implode($id_arr,',') .")");
258 $rows=db_numrows($res);
260 for ($i=0; $i<$rows; $i++) {
261 if (db_result($res, $i, 'user_id') == 100) {
262 // Do not send messages to "Nobody"
266 // Build arrays of the jabber address
268 if (db_result($res,$i,'jabber_address')) {
269 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
270 if (db_result($res,$i,'jabber_only') != 1) {
271 $address['email'][]=db_result($res,$i,'email');
274 $address['email'][]=db_result($res,$i,'email');
277 if (count($address['email']) > 0) {
278 $extra_email1=implode($address['email'],',').',';
280 if (count($address['jabber_address']) > 0) {
281 $extra_jabber1=implode($address['jabber_address'],',').',';
284 if ($extra_email1 || $extra_emails) {
285 util_send_message('',$subject,$body,$from,$extra_email1.$extra_emails);
287 if ($extra_jabber1 || $extra_jabbers) {
288 util_send_jabber($extra_jabber1.$extra_jabbers,$subject,$body);
293 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
294 * This function requires PHP 4.0.3 or greater
296 * @param string The string to unconvert
297 * @returns The unconverted string
300 function util_unconvert_htmlspecialchars($string) {
301 if (strlen($string) < 1) {
304 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
305 $trans = get_html_translation_table(HTML_ENTITIES);
306 $trans = array_flip ($trans);
307 $str = strtr ($string, $trans);
313 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
315 * @param string The result set ID
316 * @param int The column key
317 * @param int The optional column value
318 * @returns An associative array
321 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
322 $rows=db_numrows($result);
326 for ($i=0; $i<$rows; $i++) {
327 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
336 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
338 * @param int The result set ID
339 * @param int The column
343 function &util_result_column_to_array($result, $col=0) {
345 Takes a result set and turns the optional column into
348 $rows=db_numrows($result);
352 for ($i=0; $i<$rows; $i++) {
353 $arr[$i]=db_result($result,$i,$col);
362 * util_wrap_find_space() - Find the first space in a string
364 * @param string The string in which to find the space (must be UTF8!)
365 * @param int The number of characters to wrap - Default is 80
366 * @returns The position of the first space
369 function util_wrap_find_space($string,$wrap) {
376 //find the first space starting at $start
377 $pos=@strpos($string,' ',$start);
379 //if that space is too far over, go back and start more to the left
380 if (($pos > ($wrap+5)) || !$pos) {
382 $start=($wrap-($try*5));
383 //if we've gotten so far left , just truncate the line
386 $code = ord(substr($string,$wrap,1));
389 //Here is single byte character
390 //or head of multi byte character
393 //Do not break multi byte character
408 * util_line_wrap() - Automatically linewrap text
410 * @param string The text to wrap
411 * @param int The number of characters to wrap - Default is 80
412 * @param string The line break to use - Default is '\n'
413 * @returns The wrapped text
416 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
417 $paras = explode("\n", $text);
421 while ($i < count($paras)) {
422 if (strlen($paras[$i]) <= $wrap) {
423 $result[] = $paras[$i];
426 $pos=util_wrap_find_space($paras[$i],$wrap);
428 $result[] = substr($paras[$i], 0, $pos);
430 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
433 $pos=util_wrap_find_space($paras[$i],$wrap);
439 return implode($break, $result);
443 * util_make_links() - Turn URL's into HREF's.
445 * @param string The URL
446 * @returns The HREF'ed URL
449 function util_make_links ($data='') {
453 $lines = split("\n",$data);
455 while ( list ($key,$line) = each ($lines)) {
456 // When we come here, we usually have form input
457 // encoded in entities. Our aim is to NOT include
458 // angle brackets in the URL
459 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
460 $line = str_replace('>', "\1", $line);
461 $line = eregi_replace("([ \t]|^)www\."," http://www.",$line);
462 $text = eregi_replace("([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
463 $text = eregi_replace("([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $text);
464 $text = str_replace("\1", '>', $text);
471 * show_priority_colors_key() - Show the priority colors legend
474 function show_priority_colors_key() {
475 echo '<p /><strong> '._('Priority Colors').':</strong><br />
477 <table border="0"><tr>';
479 for ($i=1; $i<6; $i++) {
481 <td class="priority'.$i.'">'.$i.'</td>';
483 echo '</tr></table>';
487 * utils_buildcheckboxarray() - Build a checkbox array
489 * @param int Number of options to be in the array
490 * @param string The name of the checkboxes
491 * @param array An array of boxes to be pre-checked
494 function utils_buildcheckboxarray($options,$name,$checked_array) {
495 $option_count=count($options);
496 $checked_count=count($checked_array);
498 for ($i=1; $i<=$option_count; $i++) {
500 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
501 for ($j=0; $j<$checked_count; $j++) {
502 if ($i == $checked_array[$j]) {
506 echo '> '.$options[$i];
511 * utils_requiredField() - Adds the required field marker
513 * @return a string holding the HTML to mark a required field
515 function utils_requiredField() {
516 return '<span class="requiredfield">*</span>';
520 * GraphResult() - Takes a database result set and builds a graph.
521 * The first column should be the name, and the second column should be the values
522 * Be sure to include HTL_Graphs.php before using this function
524 * @author Tim Perdue tperdue@valinux.com
525 * @param int The databse result set ID
526 * @param string The title of the graph
529 Function GraphResult($result,$title) {
530 $rows=db_numrows($result);
532 if ((!$result) || ($rows < 1)) {
538 for ($j=0; $j<db_numrows($result); $j++) {
539 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
540 $names[$j]= db_result($result, $j, 0);
541 $values[$j]= db_result($result, $j, 1);
546 This is another function detailed below
548 GraphIt($names,$values,$title);
553 * GraphIt() - Build a graph
555 * @author Tim Perdue tperdue@valinux.com
556 * @param array An array of names
557 * @param array An array of values
558 * @param string The title of the graph
561 Function GraphIt($name_string,$value_string,$title) {
564 $counter=count($name_string);
567 Can choose any color you wish
571 for ($i = 0; $i < $counter; $i++) {
572 $bars[$i]=$HTML->COLOR_LTBACK1;
575 $counter=count($value_string);
578 Figure the max_value passed in, so scale can be determined
583 for ($i = 0; $i < $counter; $i++) {
584 if ($value_string[$i] > $max_value) {
585 $max_value=$value_string[$i];
589 if ($max_value < 1) {
594 I want my graphs all to be 800 pixels wide, so that is my divisor
597 $scale=(400/$max_value);
600 I create a wrapper table around the graph that holds the title
606 echo $GLOBALS['HTML']->listTableTop ($title_arr);
609 Create an associate array to pass in. I leave most of it blank
638 This is the actual call to the HTML_Graphs class
641 html_graph($name_string,$value_string,$bars,$vals);
645 <!-- end outer graph table -->';
646 echo $GLOBALS['HTML']->listTableBottom();
650 * ShowResultSet() - Show a generic result set
651 * Very simple, plain way to show a generic result set
653 * @param int The result set ID
654 * @param string The title of the result set
655 * @param bool The option to turn URL's into links
656 * @param bool The option to display headers
657 * @param array The db field name -> label mapping
658 * @param array Don't display these cols
661 function ShowResultSet($result,$title='',$linkify=false,$displayHeaders=true,$headerMapping=array(), $excludedCols=array()) {
662 global $group_id,$HTML;
665 $rows = db_numrows($result);
666 $cols = db_numfields($result);
668 echo '<table border="0" width="100%">';
670 /* Create the headers */
671 $headersCellData = array();
672 $colsToKeep = array();
673 for ($i=0; $i < $cols; $i++) {
674 $fieldName = db_fieldname($result, $i);
675 if(in_array($fieldName, $excludedCols)) {
679 if(isset($headerMapping[$fieldName])) {
680 if(is_array($headerMapping[$fieldName])) {
681 $headersCellData[] = $headerMapping[$fieldName];
683 $headersCellData[] = array($headerMapping[$fieldName]);
687 $headersCellData[] = array($fieldName);
691 /* Create the title */
692 if(strlen($title) > 0) {
693 $titleCellData = array();
694 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
695 echo $HTML->multiTableRow('', $titleCellData, TRUE);
698 /* Display the headers */
699 if($displayHeaders) {
700 echo $HTML->multiTableRow('', $headersCellData, TRUE);
703 /* Create the rows */
704 for ($j = 0; $j < $rows; $j++) {
705 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
706 for ($i = 0; $i < $cols; $i++) {
707 if(in_array($i, $colsToKeep)) {
708 if ($linkify && $i == 0) {
709 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
711 if ($linkify == "bug_cat") {
712 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
713 } else if($linkify == "bug_group") {
714 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
715 } else if($linkify == "patch_cat") {
716 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
717 } else if($linkify == "support_cat") {
718 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
719 } else if($linkify == "pm_project") {
720 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
722 $link = $linkend = '';
725 $link = $linkend = '';
727 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
739 * validate_email() - Validate an email address
741 * @param string The address string to validate
742 * @returns true on success/false on error
745 function validate_email ($address) {
746 return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address));
750 * validate_emails() - Validate a list of e-mail addresses
752 * @param string E-mail list
753 * @param char Separator
754 * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
756 function validate_emails ($addresses, $separator=',') {
757 if (strlen($addresses) == 0) return array();
759 $emails = explode($separator, $addresses);
762 if (is_array($emails)) {
763 foreach ($emails as $email) {
764 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
765 if (!validate_email($email)) $ret[] = $email;
774 * util_is_valid_filename() - Verifies whether a file has a valid filename
776 * @param string The file to verify
777 * @returns true on success/false on error
780 function util_is_valid_filename ($file) {
782 $invalidchars = eregi_replace("[-A-Z0-9+_\.]","",$file);
784 if (!empty($invalidchars)) {
787 if (strstr($file,'..')) {
796 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
798 * @param string The optional hostname string
799 * @returns true on success/false on failur
802 function valid_hostname ($hostname = "xyz") {
805 $invalidchars = eregi_replace("[-A-Z0-9\.]","",$hostname);
807 if (!empty($invalidchars)) {
811 //double dot, starts with a . or -
812 if (ereg("\.\.",$hostname) || ereg("^\.",$hostname) || ereg("^\-",$hostname)) {
816 $multipoint = explode(".",$hostname);
818 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
828 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
830 * Format file size in a human-readable way
831 * such as "xx Megabytes" or "xx Mo"
833 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
835 * @param int bytes is the size
836 * @param bool base10 enable base 10 representation, otherwise
837 * default base 2 is used
838 * @param int round number of fractional digits
839 * @param array labels strings associated to each 2^10 or
840 * 10^3(base10==true) multiple of base units
842 function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array(' bytes', ' KB', ' MB', ' GB')) {
843 if ($bytes <= 0 || !is_array($labels) || (count($labels) <= 0)) {
846 $step = $base10 ? 3 : 10;
847 $base = $base10 ? 10 : 2;
848 $log = (int)(log10($bytes)/log10($base));
850 foreach ($labels as $p=>$lab) {
855 if ($lab == " MB" or $lab == " GB") {
858 $text = round($bytes/pow($base,$pow),$round).$lab;
865 * ls - lists a specified directory and returns an array of files
866 * @param string the path of the directory to list
867 * @param boolean whether to filter out directories and illegal filenames
868 * @return array array of file names.
870 function &ls($dir,$filter=false) {
871 exec('ls -c1 '.$dir,$out);
873 for ($i=0; $i<count($out); $i++) {
874 if (util_is_valid_filename($out[$i]) && is_file($dir.'/'.$out[$i])) {
875 $filtered[]=$out[$i];
885 * readfile_chunked() - replacement for readfile
887 * @param string The file path
888 * @param bool Whether to return bytes served or just a bool
891 function readfile_chunked($filename, $returnBytes=true) {
892 $chunksize = 1*(1024*1024); // 1MB chunks
896 $handle = fopen($filename, 'rb');
897 if ($handle === false) {
901 while (!feof($handle)) {
902 $buffer = fread($handle, $chunksize);
905 $byteCounter += strlen($buffer);
908 $status = fclose($handle);
909 if ($returnBytes && $status) {
910 return $byteCounter; // return num. bytes delivered like readfile() does.
916 * util_is_root_dir() - Checks if a directory points to the root dir
917 * @param string Directory
920 function util_is_root_dir($dir) {
921 return !preg_match('/[^\\/]/',$dir);
924 function util_make_url ($path) {
925 if ($GLOBALS['sys_use_ssl'])
930 $url .= $GLOBALS['sys_default_domain'] ;
931 $url .= $GLOBALS['sys_urlprefix'] ;
933 $path = ereg_replace ("^/", "", $path) ;
938 function util_make_link ($path, $text, $extra_params=false) {
940 if (is_array($extra_params)) {
941 foreach ($extra_params as $key => $value) {
942 $ep .= "$key=\"$value\" ";
945 return '<a ' . $ep . 'href="' . util_make_url ($path) . '">' . $text . '</a>' ;
948 function util_make_link_u ($username, $user_id,$text) {
949 return '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>' ;
952 function util_make_url_u ($username, $user_id) {
953 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
954 return util_make_url ("/developer/?user_id=$user_id");
956 return util_make_url ("/users/$username/");
960 function util_make_link_g ($groupame, $group_id,$text) {
961 return '<a href="' . util_make_url_g ($groupame, $group_id) . '">' . $text . '</a>' ;
964 function util_make_url_g ($groupame, $group_id) {
965 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
966 return util_make_url ("/project/?group_id=$group_id");
968 return util_make_url ("/projects/$groupame/");
974 // c-file-style: "bsd"