3 * FusionForge miscellaneous utils
5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2009-2011, Roland Mas
7 * Copyright 2009-2011, Franck Villaume - Capgemini
8 * Copyright (c) 2010, 2011, 2012
9 * Thorsten Glaser <t.glaser@tarent.de>
10 * Copyright 2010-2011, Alain Peyrat - Alcatel-Lucent
12 * This file is part of FusionForge. FusionForge is free software;
13 * you can redistribute it and/or modify it under the terms of the
14 * GNU General Public License as published by the Free Software
15 * Foundation; either version 2 of the Licence, or (at your option)
18 * FusionForge is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 * htpasswd_apr1_md5($plainpasswd) - generate htpasswd md5 format password
31 * From http://www.php.net/manual/en/function.crypt.php#73619
33 function htpasswd_apr1_md5($plainpasswd) {
34 $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
35 $len = strlen($plainpasswd);
36 $text = $plainpasswd.'$apr1$'.$salt;
37 $bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
39 for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
40 for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; }
41 $bin = pack("H32", md5($text));
42 for($i = 0; $i < 1000; $i++) {
43 $new = ($i & 1) ? $plainpasswd : $bin;
44 if ($i % 3) $new .= $salt;
45 if ($i % 7) $new .= $plainpasswd;
46 $new .= ($i & 1) ? $bin : $plainpasswd;
47 $bin = pack("H32", md5($new));
49 for ($i = 0; $i < 5; $i++) {
53 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
55 $tmp = chr(0).chr(0).$bin[11].$tmp;
56 $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
57 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
58 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
59 return "$"."apr1"."$".$salt."$".$tmp;
63 * is_utf8($string) - utf-8 detection
65 * From http://www.php.net/manual/en/function.mb-detect-encoding.php#85294
67 function is_utf8($str) {
71 for($i=0; $i<$len; $i++){
74 if(($c >= 254)) return false;
75 elseif($c >= 252) $bits=6;
76 elseif($c >= 248) $bits=5;
77 elseif($c >= 240) $bits=4;
78 elseif($c >= 224) $bits=3;
79 elseif($c >= 192) $bits=2;
81 if(($i+$bits) > $len) return false;
85 if($b < 128 || $b > 191) return false;
93 function util_strip_unprintable(&$data) {
94 if (is_array($data)) {
95 foreach ($data as $key => &$value) {
96 util_strip_unprintable($value);
100 $data = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $data);
106 * removeCRLF() - remove any Carriage Return-Line Feed from a string.
107 * That function is useful to remove the possibility of a CRLF Injection when sending mail
108 * All the data that we will send should be passed through that function
110 * @param string The string that we want to empty from any CRLF
112 function util_remove_CRLF($str) {
113 return strtr($str, "\015\012", ' ');
118 * util_check_fileupload() - determines if a filename is appropriate for upload
120 * @param array The uploaded file as returned by getUploadedFile()
122 function util_check_fileupload($filename) {
124 /* Empty file is a valid file.
125 This is because this function should be called
126 unconditionally at the top of submit action processing
127 and many forms have optional file upload. */
128 if ($filename == 'none' || $filename == '') {
132 /* This should be enough... */
133 if (!is_uploaded_file($filename)) {
136 /* ... but we'd rather be paranoic */
137 if (strstr($filename, '..')) {
140 if (!is_file($filename)) {
143 if (!file_exists($filename)) {
146 if ((dirname($filename) != '/tmp') &&
147 (dirname($filename) != "/var/tmp")) {
154 * util_check_url() - determines if given URL is valid.
156 * Currently, test is very basic, only the protocol is
157 * checked, allowed values are: http, https, ftp.
159 * @param string The URL
160 * @return boolean true if valid, false if not valid.
162 function util_check_url($url) {
163 return (preg_match('/^(http|https|ftp):\/\//', $url) > 0);
167 * util_send_message() - Send email
168 * This function should be used in place of the PHP mail() function
170 * @param string The email recipients address
171 * @param string The email subject
172 * @param string The body of the email message
173 * @param string The optional email sender address. Defaults to 'noreply@'
174 * @param string The addresses to blind-carbon-copy this message
175 * @param string The optional email sender name. Defaults to ''
176 * @param boolean Whether to send plain text or html email
179 function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='',$send_html_email=false) {
183 $to='noreply@'.forge_get_config('web_host');
186 $from='noreply@'.forge_get_config('web_host');
190 $charset = _('UTF-8');
196 if ($extra_headers) {
197 $body2 .= $extra_headers."\n";
200 "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset);
201 if (forge_get_config('bcc_all_emails') != '') {
202 $BCC.=",".forge_get_config('bcc_all_emails');
205 $body2 .= "\nBCC: $BCC";
207 $send_html_email?$type="html":$type="plain";
208 $body2 .= "\n".util_encode_mimeheader("Subject", $subject, $charset).
209 "\nContent-type: text/$type; charset=$charset".
211 util_convert_body($body, $charset);
213 if (!forge_get_config('sendmail_path')){
214 $sys_sendmail_path="/usr/sbin/sendmail";
217 $handle = popen(forge_get_config('sendmail_path')." -f'$from' -t -i", 'w');
218 fwrite ($handle, $body2);
223 * util_encode_mailaddr() - Encode email address to MIME format
225 * @param string The email address
226 * @param string The email's owner name
227 * @param string The converting charset
230 function util_encode_mailaddr($email,$name,$charset) {
231 if (function_exists('mb_convert_encoding') && trim($name) != "") {
232 $name = "=?".$charset."?B?".
233 base64_encode(mb_convert_encoding(
234 $name,$charset,"UTF-8")).
238 return $name." <".$email."> ";
242 * util_encode_mimeheader() - Encode mimeheader
244 * @param string The name of the header (e.g. "Subject")
245 * @param string The email subject
246 * @param string The converting charset (like ISO-2022-JP)
247 * @return string The MIME encoded subject
250 function util_encode_mimeheader($headername,$str,$charset) {
251 if (function_exists('mb_internal_encoding') &&
252 function_exists('mb_encode_mimeheader')) {
253 $x = mb_internal_encoding();
254 mb_internal_encoding("UTF-8");
255 $y = mb_encode_mimeheader($headername . ": " . $str,
257 mb_internal_encoding($x);
261 if (!function_exists('mb_convert_encoding')) {
262 return $headername . ": " . $str;
265 return $headername . ": " . "=?".$charset."?B?".
266 base64_encode(mb_convert_encoding(
267 $str,$charset,"UTF-8")).
272 * util_convert_body() - Convert body of the email message
274 * @param string The body of the email message
275 * @param string The charset of the email message
276 * @return string The converted body of the email message
279 function util_convert_body($str,$charset) {
280 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
284 return mb_convert_encoding($str,$charset,"UTF-8");
287 function util_send_jabber($to,$subject,$body) {
288 if (!forge_get_config('use_jabber')) {
291 $JABBER = new Jabber();
292 if (!$JABBER->Connect()) {
293 echo '<br />Unable to connect';
296 //$JABBER->SendAuth();
297 //$JABBER->AccountRegistration();
298 if (!$JABBER->SendAuth()) {
299 echo '<br />Auth Failure';
300 $JABBER->Disconnect();
302 //or die("Couldn't authenticate!");
304 $JABBER->SendPresence(NULL, NULL, "online");
306 $body=htmlspecialchars($body);
307 $to_arr=explode(',',$to);
308 for ($i=0; $i<count($to_arr); $i++) {
310 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
311 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
312 echo '<br />Error Sending to '.$to_arr[$i];
317 $JABBER->CruiseControl(2);
318 $JABBER->Disconnect();
322 * util_handle_message() - a convenience wrapper which sends messages
323 * to either a jabber account or email account or both, depending on
326 * @param array array of user_id's from the user table
327 * @param string subject of the message
328 * @param string the message body
329 * @param string a comma-separated list of email address
330 * @param string a comma-separated list of jabber address
331 * @param string From header
333 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='',$from='') {
336 if (count($id_arr) < 1) {
339 $res = db_query_params ('SELECT user_id,jabber_address,email,jabber_only FROM users WHERE user_id = ANY ($1)',
340 array (db_int_array_to_any_clause ($id_arr))) ;
341 $rows = db_numrows($res) ;
343 for ($i=0; $i<$rows; $i++) {
344 if (db_result($res, $i, 'user_id') == 100) {
345 // Do not send messages to "Nobody"
349 // Build arrays of the jabber address
351 if (db_result($res,$i,'jabber_address')) {
352 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
353 if (db_result($res,$i,'jabber_only') != 1) {
354 $address['email'][]=db_result($res,$i,'email');
357 $address['email'][]=db_result($res,$i,'email');
360 if (isset ($address['email']) && count($address['email']) > 0) {
361 $extra_emails=implode($address['email'],',').',' . $extra_emails;
363 if (isset ($address['jabber_address']) && count($address['jabber_address']) > 0) {
364 $extra_jabbers=implode($address['jabber_address'],',').','.$extra_jabbers;
368 util_send_message('',$subject,$body,$from,$extra_emails);
370 if ($extra_jabbers) {
371 util_send_jabber($extra_jabbers,$subject,$body);
376 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
378 * @param string The string to unconvert
379 * @returns The unconverted string
382 function util_unconvert_htmlspecialchars($string) {
383 return html_entity_decode($string, ENT_QUOTES, "UTF-8");
387 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
389 * @param string The result set ID
390 * @param int The column key
391 * @param int The optional column value
392 * @returns An associative array
395 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
396 $rows=db_numrows($result);
400 for ($i=0; $i<$rows; $i++) {
401 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
410 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
412 * @param int The result set ID
413 * @param int The column
417 function &util_result_column_to_array($result, $col=0) {
419 Takes a result set and turns the optional column into
422 $rows=db_numrows($result);
426 for ($i=0; $i<$rows; $i++) {
427 $arr[$i]=db_result($result,$i,$col);
436 * util_line_wrap() - Automatically linewrap text
438 * @param string The text to wrap
439 * @param int The number of characters to wrap - Default is 80
440 * @param string The line break to use - Default is '\n'
441 * @returns The wrapped text
444 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
445 return wordwrap($text, $wrap, $break, false);
449 * util_make_links() - Turn URL's into HREF's.
451 * @param string The URL
452 * @returns The HREF'ed URL
455 function util_make_links($data='') {
460 for ($i = 0; $i < 5; $i++) {
461 $randPattern = rand(10000, 30000);
462 if (! preg_match("/$randPattern/", $data)) {
469 while(preg_match('/<a [^>]*>[^<]*<\/a>/i', $data, $part)) {
471 $data = preg_replace('/<a [^>]*>[^<]*<\/a>/i', $randPattern, $data, 1);
475 while(preg_match('/<a [^>]*>.*<\/a>/siU', $data, $part)) {
477 $data = preg_replace('/<a [^>]*>.*<\/a>/siU', $randPattern, $data, 1);
479 while(preg_match('/<img [^>]*\/>/siU', $data, $part)) {
481 $data = preg_replace('/<img [^>]*\/>/siU', $randPattern, $data, 1);
483 $data = str_replace('>', "\1", $data);
484 $data = preg_replace("#([ \t]|^)www\.#i"," http://www.",$data);
485 $data = preg_replace("#([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]\#?/&=])#i", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $data);
486 $data = preg_replace("#([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]<\1]*)([[:alnum:]-]))#i", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $data);
487 $data = str_replace("\1", '>', $data);
488 for ($i = 0; $i < count($mem); $i++) {
489 $data = preg_replace("/$randPattern/", $mem[$i], $data, 1);
494 $lines = split("\n",$data);
496 while ( list ($key, $line) = each ($lines)) {
497 // Do not scan lines if they already have hyperlinks.
498 // Avoid problem with text written with an WYSIWYG HTML editor.
499 if (eregi('<a ([^>]*)>.*</a>', $line, $linePart)) {
500 if (eregi('href="[^"]*"', $linePart[1])) {
506 // Skip </img> tag also
507 if (eregi('<img ([^>]*)/>', $line, $linePart)) {
508 if (eregi('href="[^"]*"', $linePart[1])) {
514 // When we come here, we usually have form input
515 // encoded in entities. Our aim is to NOT include
516 // angle brackets in the URL
517 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
518 $line = str_replace('>', "\1", $line);
519 $line = preg_replace("/([ \t]|^)www\./i", " http://www.", $line);
520 $line = preg_replace("/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
521 "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
522 $line = preg_replace(
523 "/([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))/i",
524 "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>",
527 $line = str_replace("\1", '>', $line);
534 * show_priority_colors_key() - Show the priority colors legend
537 function show_priority_colors_key() {
538 echo '<p><strong> '._('Priority Colors')._(':').'</strong>';
539 for ($i=1; $i<6; $i++) {
540 echo ' <span class="priority'.$i.'">'.$i.'</span>';
546 * utils_buildcheckboxarray() - Build a checkbox array
548 * @param int Number of options to be in the array
549 * @param string The name of the checkboxes
550 * @param array An array of boxes to be pre-checked
553 function utils_buildcheckboxarray($options, $name, $checked_array) {
554 $option_count = count($options);
555 $checked_count = count($checked_array);
557 for ($i = 1; $i <= $option_count; $i++) {
559 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
560 for ($j=0; $j < $checked_count; $j++) {
561 if ($i == $checked_array[$j]) {
565 echo ' /> '.$options[$i];
570 * utils_requiredField() - Adds the required field marker
572 * @return a string holding the HTML to mark a required field
574 function utils_requiredField() {
575 return '<span class="requiredfield">*</span>';
579 * GraphResult() - Takes a database result set and builds a graph.
580 * The first column should be the name, and the second column should be the values
581 * Be sure to include HTL_Graphs.php before using this function
583 * @author Tim Perdue tperdue@valinux.com
584 * @param int The databse result set ID
585 * @param string The title of the graph
588 function GraphResult($result, $title) {
589 $rows = db_numrows($result);
591 if ((!$result) || ($rows < 1)) {
597 for ($j=0; $j < db_numrows($result); $j++) {
598 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
599 $names[$j] = db_result($result, $j, 0);
600 $values[$j] = db_result($result, $j, 1);
605 This is another function detailed below
607 GraphIt($names, $values, $title);
612 * GraphIt() - Build a graph
614 * @author Tim Perdue tperdue@valinux.com
615 * @param array An array of names
616 * @param array An array of values
617 * @param string The title of the graph
620 function GraphIt($name_string, $value_string, $title) {
623 $counter = count($name_string);
626 Can choose any color you wish
630 for ($i = 0; $i < $counter; $i++) {
631 $bars[$i] = $HTML->COLOR_LTBACK1;
634 $counter = count($value_string);
637 Figure the max_value passed in, so scale can be determined
642 for ($i = 0; $i < $counter; $i++) {
643 if ($value_string[$i] > $max_value) {
644 $max_value = $value_string[$i];
648 if ($max_value < 1) {
653 I want my graphs all to be 800 pixels wide, so that is my divisor
656 $scale = (400/$max_value);
659 I create a wrapper table around the graph that holds the title
662 $title_arr = array();
663 $title_arr[] = $title;
665 echo $GLOBALS['HTML']->listTableTop ($title_arr);
668 Create an associate array to pass in. I leave most of it blank
697 This is the actual call to the HTML_Graphs class
700 html_graph($name_string, $value_string, $bars, $vals);
704 <!-- end outer graph table -->';
705 echo $GLOBALS['HTML']->listTableBottom();
709 * ShowResultSet() - Show a generic result set
710 * Very simple, plain way to show a generic result set
712 * @param int The result set ID
713 * @param string The title of the result set
714 * @param bool The option to turn URL's into links
715 * @param bool The option to display headers
716 * @param array The db field name -> label mapping
717 * @param array Don't display these cols
720 function ShowResultSet($result,$title='',$linkify=false,$displayHeaders=true,$headerMapping=array(), $excludedCols=array()) {
721 global $group_id,$HTML;
724 $rows = db_numrows($result);
725 $cols = db_numfields($result);
727 echo '<table width="100%">';
729 /* Create the headers */
730 $headersCellData = array();
731 $colsToKeep = array();
732 for ($i=0; $i < $cols; $i++) {
733 $fieldName = db_fieldname($result, $i);
734 if(in_array($fieldName, $excludedCols)) {
738 if(isset($headerMapping[$fieldName])) {
739 if(is_array($headerMapping[$fieldName])) {
740 $headersCellData[] = $headerMapping[$fieldName];
742 $headersCellData[] = array($headerMapping[$fieldName]);
746 $headersCellData[] = array($fieldName);
750 /* Create the title */
751 if(strlen($title) > 0) {
752 $titleCellData = array();
753 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
754 echo $HTML->multiTableRow('', $titleCellData, TRUE);
757 /* Display the headers */
758 if($displayHeaders) {
759 echo $HTML->multiTableRow('', $headersCellData, TRUE);
762 /* Create the rows */
763 for ($j = 0; $j < $rows; $j++) {
764 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
765 for ($i = 0; $i < $cols; $i++) {
766 if(in_array($i, $colsToKeep)) {
767 if ($linkify && $i == 0) {
768 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
770 if ($linkify == "bug_cat") {
771 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
772 } else if($linkify == "bug_group") {
773 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
774 } else if($linkify == "patch_cat") {
775 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
776 } else if($linkify == "support_cat") {
777 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
778 } else if($linkify == "pm_project") {
779 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
781 $link = $linkend = '';
784 $link = $linkend = '';
786 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
798 * validate_email() - Validate an email address
800 * @param string The address string to validate
801 * @returns true on success/false on error
804 function validate_email ($address) {
805 if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
806 if ( filter_var($address, FILTER_VALIDATE_EMAIL) ) {
814 if ( preg_match( "/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+$/", $address) ) {
823 * validate_emails() - Validate a list of e-mail addresses
825 * @param string E-mail list
826 * @param char Separator
827 * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
829 function validate_emails($addresses, $separator=',') {
830 if (strlen($addresses) == 0) return array();
832 $emails = explode($separator, $addresses);
835 if (is_array($emails)) {
836 foreach ($emails as $email) {
837 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
838 if (!validate_email($email)) $ret[] = $email;
847 * util_is_valid_filename() - Verifies whether a file has a valid filename
849 * @param string The file to verify
850 * @returns true on success/false on error
853 function util_is_valid_filename($file) {
855 $invalidchars = preg_replace("/[-A-Z0-9+_\. ~]/i","",$file);
857 if (!empty($invalidchars)) {
860 if (strstr($file,'..')) {
868 /* util_is_valid_repository_name() - Verifies whether a repository name is valid
870 * @param string The name to verify
871 * @returns true on success/false on error
874 function util_is_valid_repository_name ($file) {
876 $invalidchars = preg_replace("/[-A-Z0-9+_\.]/i","",$file);
878 if (!empty($invalidchars)) {
881 if (strstr($file,'..')) {
888 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
890 * @param string The optional hostname string
891 * @returns true on success/false on failur
894 function valid_hostname($hostname = "xyz") {
897 $invalidchars = preg_replace("/[-A-Z0-9\.]/i","",$hostname);
899 if (!empty($invalidchars)) {
903 //double dot, starts with a . or -
904 if ( preg_match("/\.\./",$hostname) || preg_match("/^\./",$hostname) || preg_match("/^\-/",$hostname) ) {
908 $multipoint = explode(".",$hostname);
910 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
920 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
922 * Format file size in a human-readable way
923 * such as "xx Megabytes" or "xx Mo"
925 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
927 * @param int bytes is the size
928 * @param bool base10 enable base 10 representation, otherwise
929 * default base 2 is used
930 * @param int round number of fractional digits
931 * @param array labels strings associated to each 2^10 or
932 * 10^3(base10==true) multiple of base units
934 function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array()) {
939 return "-" . human_readable_bytes(-$bytes, $base10, $round);
942 $labels = array(_('bytes'), _('kB'), _('MB'), _('GB'), _('TB'));
946 $labels = array(_('bytes'), _('KiB'), _('MiB'), _('GiB'), _('TiB'));
950 $log = (int)(log10($bytes)/log10($base));
952 foreach ($labels as $p=>$lab) {
957 if ($lab != _("bytes") and $lab != _("kB") and $lab != _("KiB")) {
960 $text = round($bytes/pow($base,$pow),$round) . " " . $lab;
967 * ls - lists a specified directory and returns an array of files
968 * @param string the path of the directory to list
969 * @param boolean whether to filter out directories and illegal filenames
970 * @return array array of file names.
972 function &ls($dir,$filter=false) {
975 if (is_dir($dir) && ($h = opendir($dir))) {
976 while (($f = readdir($h)) !== false) {
980 if (!util_is_valid_filename($f) ||
981 !is_file($dir . "/" . $f))
992 * readfile_chunked() - replacement for readfile
994 * @param string The file path
995 * @param bool Whether to return bytes served or just a bool
998 function readfile_chunked($filename, $returnBytes=true) {
999 $chunksize = 1*(1024*1024); // 1MB chunks
1003 $handle = fopen($filename, 'rb');
1004 if ($handle === false) {
1009 while (!feof($handle)) {
1010 $buffer = fread($handle, $chunksize);
1015 $byteCounter += strlen($buffer);
1019 $status = fclose($handle);
1020 if ($returnBytes && $status) {
1021 return $byteCounter; // return num. bytes delivered like readfile() does.
1027 * util_is_root_dir() - Checks if a directory points to the root dir
1028 * @param string Directory
1031 function util_is_root_dir($dir) {
1032 return !preg_match('/[^\\/]/',$dir);
1036 * util_is_dot_or_dotdot() - Checks if a directory points to . or ..
1037 * @param string Directory
1040 function util_is_dot_or_dotdot($dir) {
1041 return preg_match('/^\.\.?$/',trim($dir, '/'));
1045 * util_containts_dot_or_dotdot() - Checks if a directory containts . or ..
1046 * @param string Directory
1049 function util_containts_dot_or_dotdot($dir) {
1050 foreach (explode('/', $dir) as $sub_dir) {
1051 if (util_is_dot_or_dotdot($sub_dir))
1059 * util_secure_filename() - Returns a secured file name
1060 * @param string Filename
1061 * @return string Filename
1063 function util_secure_filename($file) {
1064 $f = preg_replace("/[^-A-Z0-9_\.]/i", '', $file);
1065 if (util_containts_dot_or_dotdot($f))
1066 $f = preg_replace("/\./", '_', $f);
1073 * util_strip_accents() - Remove accents from given text.
1074 * @param string Text
1077 function util_strip_accents($text) {
1078 $find = utf8_decode($text);
1079 $find = strtr($find,
1080 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
1081 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
1082 return utf8_encode($find);
1086 * Constructs the forge's URL prefix out of forge_get_config('url_prefix')
1090 function normalized_urlprefix() {
1091 $prefix = forge_get_config('url_prefix') ;
1092 $prefix = preg_replace ("/^\//", "", $prefix) ;
1093 $prefix = preg_replace ("/\/$/", "", $prefix) ;
1094 $prefix = "/$prefix/" ;
1095 if ($prefix == '//')
1101 * Return URL prefix (http:// or https://)
1103 * @param string $prefix (optional) : 'http' or 'https' to force it
1104 * @return string URL prefix
1106 function util_url_prefix($prefix = '') {
1107 if ($prefix == 'http' || $prefix == 'https' ) {
1108 return $prefix . '://';
1111 if (forge_get_config('use_ssl')) {
1120 * Construct the base URL http[s]://forge_name[:port]
1122 * @param string $prefix (optional) : 'http' or 'https' to force it
1123 * @return string base URL
1125 function util_make_base_url($prefix = '') {
1126 $url = util_url_prefix($prefix);
1127 $url .= forge_get_config('web_host') ;
1128 if (forge_get_config('https_port') && (forge_get_config('https_port') != 443)) {
1129 $url .= ":".forge_get_config('https_port') ;
1135 * Construct full URL from a relative path
1137 * @param string $path (optional)
1138 * @param string $prefix (optional) : 'http' or 'https' to force it
1139 * @return string URL
1141 function util_make_url($path = '', $prefix = '') {
1142 $url = util_make_base_url($prefix).util_make_uri($path) ;
1147 * Find the relative URL from full URL, removing http[s]://forge_name[:port]
1151 function util_find_relative_referer($url) {
1152 $relative_url = str_replace(util_make_base_url(), '', $url);
1153 //now remove previous feedback, error_msg or warning_msg
1154 $relative_url = preg_replace('/&error_msg=.*&/', '&', $relative_url);
1155 $relative_url = preg_replace('/&warning_msg=.*&/', '&', $relative_url);
1156 $relative_url = preg_replace('/&feedback=.*&/', '&', $relative_url);
1157 $relative_url = preg_replace('/&error_msg=.*/', '', $relative_url);
1158 $relative_url = preg_replace('/&warning_msg=.*/', '', $relative_url);
1159 $relative_url = preg_replace('/&feedback=.*/', '', $relative_url);
1160 return $relative_url;
1164 * Construct proper (relative) URI (prepending prefix)
1166 * @param string $path
1167 * @return string URI
1169 function util_make_uri($path) {
1170 $path = preg_replace('/^\//', '', $path);
1171 $uri = normalized_urlprefix();
1176 function util_make_link($path, $text, $extra_params = false, $absolute = false) {
1177 global $use_tooltips;
1179 if (is_array($extra_params)) {
1180 foreach ($extra_params as $key => $value) {
1181 if ($key != 'title') {
1182 $ep .= "$key=\"$value\" ";
1184 if ($key == 'title' && $use_tooltips) {
1185 $ep .= "$key=\"$value\" ";
1190 return '<a ' . $ep . 'href="' . $path . '">' . $text . '</a>' ;
1192 return '<a ' . $ep . 'href="' . util_make_uri($path) . '">' . $text . '</a>' ;
1197 * Create an HTML link to a user's profile page
1199 * @param string $username
1200 * @param int $user_id
1201 * @param string $text
1204 function util_make_link_u ($username, $user_id,$text) {
1205 return '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>';
1209 * Display username with link to a user's profile page
1210 * and icon face if possible.
1212 * @param string $username
1213 * @param int $user_id
1214 * @param string $text
1215 * @param string $size
1218 function util_display_user($username, $user_id, $text, $size='xs') {
1219 // Invoke user_link_with_tooltip plugin
1220 $hook_params = array('resource_type' => 'user', 'username' => $username, 'user_id' => $user_id, 'size' => $size, 'user_link' => '');
1221 plugin_hook_by_reference('user_link_with_tooltip', $hook_params);
1222 if($hook_params['user_link'] != ''){
1223 return $hook_params['user_link'];
1226 // If no plugin replaced it, then back to default standard link
1228 // Invoke user_logo plugin (see gravatar plugin for instance)
1229 $params = array('user_id' => $user_id, 'size' => $size, 'content' => '');
1230 plugin_hook_by_reference('user_logo', $params);
1232 $url = '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>';
1233 if ($params['content']) {
1234 return $params['content'].$url.'<div class="new_line"></div>';
1240 * Create URL for user's profile page
1242 * @param string $username
1243 * @param int $user_id
1244 * @return string URL
1246 function util_make_url_u ($username, $user_id) {
1247 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1248 return util_make_url ("/developer/?user_id=$user_id");
1250 return util_make_url ("/users/$username/");
1255 * Create a HTML link to a project's page
1256 * @param string $groupame
1257 * @param int $group_id
1258 * @param string $text
1261 function util_make_link_g ($groupname, $group_id,$text) {
1262 $hook_params =array();
1263 $hook_params['resource_type'] = 'group';
1264 $hook_params['group_name'] = $groupname;
1265 $hook_params['group_id'] = $group_id;
1266 $hook_params['link_text'] = $text;
1267 $hook_params['group_link'] = '';
1268 plugin_hook_by_reference('project_link_with_tooltip', $hook_params);
1269 if($hook_params['group_link'] != '') {
1270 return $hook_params['group_link'];
1273 return '<a href="' . util_make_url_g ($groupname, $group_id) . '">' . $text . '</a>' ;
1277 * Create URL for a project's page
1279 * @param string $groupame
1280 * @param int $group_id
1283 function util_make_url_g ($groupame, $group_id) {
1284 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1285 return util_make_url ("/project/?group_id=$group_id");
1287 return util_make_url ("/projects/$groupame/");
1291 function util_ensure_value_in_set ($value, $set) {
1292 if (in_array ($value, $set)) {
1299 function check_email_available($group, $email, &$response) {
1300 // Check if a mailing list with same name already exists
1301 $mlFactory = new MailingListFactory($group);
1302 if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
1303 $response .= $mlFactory->getErrorMessage();
1306 $mlArray = $mlFactory->getMailingLists();
1307 if ($mlFactory->isError()) {
1308 $response .= $mlFactory->getErrorMessage();
1311 for ($j = 0; $j < count($mlArray); $j++) {
1312 $currentList =& $mlArray[$j];
1313 if ($email == $currentList->getName()) {
1314 $response .= _('Error: a mailing list with the same email address already exists.');
1319 // Check if a forum with same name already exists
1320 $ff = new ForumFactory($group);
1321 if (!$ff || !is_object($ff) || $ff->isError()) {
1322 $response .= $ff->getErrorMessage();
1325 $farr = $ff->getForums();
1326 $prefix = $group->getUnixName() . '-';
1327 for ($j = 0; $j < count($farr); $j++) {
1328 if (is_object($farr[$j])) {
1329 if ($email == $prefix . $farr[$j]->getName()) {
1330 $response .= _('Error: a forum with the same email address already exists.');
1336 // Email is available
1341 * Adds the Javascript file to the list to be used
1344 function use_javascript($js) {
1345 return $GLOBALS['HTML']->addJavascript($js);
1348 function use_stylesheet($css, $media='') {
1349 return $GLOBALS['HTML']->addStylesheet($css, $media);
1352 // array_replace_recursive only appeared in PHP 5.3.0
1353 if (!function_exists('array_replace_recursive')) {
1355 * Replaces elements from passed arrays into the first array recursively
1356 * @param array $a1 The array in which elements are replaced.
1357 * @param array $a2 The array from which elements will be extracted.
1358 * @return Returns an array, or NULL if an error occurs.
1360 function array_replace_recursive ($a1, $a2) {
1363 if (!is_array ($a2)) {
1367 foreach ($a2 as $k => $v) {
1368 if (!is_array ($v) ||
1369 !isset ($result[$k]) || !is_array ($result[$k])) {
1373 $result[$k] = array_replace_recursive ($result[$k],
1381 // json_encode only appeared in PHP 5.2.0
1382 if (!function_exists('json_encode')) {
1383 require_once $gfcommon.'include/minijson.php' ;
1384 function json_encode ($a1) {
1385 return minijson_encode ($a1) ;
1389 /* returns an integer from http://forge/foo/bar.php/123 or false */
1390 function util_path_info_last_numeric_component() {
1391 if (!isset($_SERVER['PATH_INFO']))
1395 foreach (str_split($_SERVER['PATH_INFO']) as $x) {
1399 } elseif ($ok == false) {
1400 ; /* need reset using slash */
1401 } elseif ((ord($x) >= 48) && (ord($x) <= 57)) {
1402 $rv = $rv * 10 + ord($x) - 48;
1412 function get_cvs_binary_version () {
1413 $string = `cvs --version 2>/dev/null | grep ^Concurrent.Versions.System.*client/server` ;
1414 if (preg_match ('/^Concurrent Versions System .CVS. 1.11.[0-9]*/', $string)) {
1416 } elseif (preg_match ('/^Concurrent Versions System .CVS. 1.12.[0-9]*/', $string)) {
1423 /* get a backtrace as string */
1424 function debug_string_backtrace() {
1426 debug_print_backtrace();
1427 $trace = ob_get_contents();
1430 // Remove first item from backtrace as it's this function
1431 // which is redundant.
1432 $trace = preg_replace('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '',
1435 // Renumber backtrace items.
1436 $trace = preg_replace('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);
1441 function util_ini_get_bytes($id) {
1442 $val = trim(ini_get($id));
1443 $last = strtolower($val[strlen($val)-1]);
1455 function util_get_maxuploadfilesize() {
1456 $postmax = util_ini_get_bytes('post_max_size');
1457 $maxfile = util_ini_get_bytes('upload_max_filesize');
1459 $postfile = (int)(($postmax * 3) / 4);
1461 if ($postfile < $maxfile)
1462 $postfile = $maxfile;
1467 function util_get_compressed_file_extension() {
1468 $m = forge_get_config('compression_method');
1469 if (preg_match ('/^gzip\b/', $m)) {
1471 } elseif (preg_match ('/^bzip2\b/', $m)) {
1473 } elseif (preg_match ('/^lzma\b/', $m)) {
1475 } elseif (preg_match ('/^xz\b/', $m)) {
1477 } elseif (preg_match ('/^cat\b/', $m)) {
1480 return '.compressed';
1484 /* return $1 if $1 is set, ${2:-false} otherwise */
1485 function util_ifsetor(&$val, $default = false) {
1486 return (isset($val) ? $val : $default);
1489 function util_randbytes($num=6) {
1492 // Let's try /dev/urandom first
1493 $f = @fopen("/dev/urandom", "rb");
1495 $b .= @fread($f, $num);
1499 // Hm. No /dev/urandom? Try /dev/random.
1500 if (strlen($b) < $num) {
1501 $f = @fopen("/dev/random", "rb");
1503 $b .= @fread($f, $num);
1508 // Still no luck? Fall back to PHP's built-in PRNG
1509 while (strlen($b) < $num) {
1510 $b .= uniqid(mt_rand(), true);
1513 $b = substr($b, 0, $num);
1517 /* maximum: 2^31 - 1 due to PHP weakness */
1518 function util_randnum($min=0,$max=32767) {
1519 $ta = unpack("L", util_randbytes(4));
1520 $n = $ta[1] & 0x7FFFFFFF;
1521 $v = $n % (1 + $max - $min);
1525 // sys_get_temp_dir() is only available for PHP >= 5.2.1
1526 if ( !function_exists('sys_get_temp_dir')) {
1527 function sys_get_temp_dir() {
1528 if ($temp=getenv('TMP')) return $temp;
1529 if ($temp=getenv('TEMP')) return $temp;
1530 if ($temp=getenv('TMPDIR')) return $temp;
1535 /* convert '\n' to <br /> or </p><p> */
1536 function util_pwrap($encoded_string) {
1537 return str_replace("<p></p>", "",
1538 str_replace("<br /></p>", "</p>",
1539 str_replace("<p><br />", "<p>",
1540 "<p>" . str_replace("<br /><br />", "</p><p>",
1541 implode("<br />", explode("\n",
1542 $encoded_string))) . "</p>")));
1545 /* takes a string and returns it HTML encoded, URIs made to hrefs */
1546 function util_uri_grabber($unencoded_string, $tryaidtid=false) {
1547 /* escape all ^A and ^B as ^BX^B and ^BY^B, respectively */
1548 $s = str_replace("\x01", "\x02X\x02", str_replace("\x02", "\x02Y\x02",
1549 $unencoded_string));
1550 /* replace all URIs with ^AURI^A */
1552 '|([a-zA-Z][a-zA-Z0-9+.-]*:[#0-9a-zA-Z;/?:@&=+$,_.!~*\'()%-]+)|',
1555 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1556 /* encode the string */
1557 $s = htmlentities($s, ENT_QUOTES, "UTF-8");
1558 /* convert 「^Afoo^A」 to 「<a href="foo">foo</a>」 */
1559 $s = preg_replace('|\x01([^\x01]+)\x01|',
1560 '<a href="$1">$1</a>', $s);
1562 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1563 // /* convert [#123] to links if found */
1565 // $s = util_tasktracker_links($s);
1566 /* convert ^BX^B and ^BY^B back to ^A and ^B, respectively */
1567 $s = str_replace("\x02Y\x02", "\x02", str_replace("\x02X\x02", "\x01",
1569 /* return the final result */
1573 function util_html_encode($s) {
1574 return htmlspecialchars($s, ENT_QUOTES, "UTF-8");
1577 /* secure a (possibly already HTML encoded) string */
1578 function util_html_secure($s) {
1579 return util_html_encode(util_unconvert_htmlspecialchars($s));
1582 /* return integral value (ℕ₀) of passed string if it matches, or false */
1583 function util_nat0(&$s) {
1585 /* unset variable */
1589 if (count($s) == 1) {
1590 /* one-element array */
1591 return util_nat0($s[0]);
1593 /* not one element, or element not at [0] */
1596 if (!is_numeric($s)) {
1602 /* number element of ℕ₀ */
1603 $text = (string)$num;
1605 /* number matches its textual representation */
1608 /* doesn't match, like 0123 or 1.2 or " 1" */
1615 * util_negociate_alternate_content_types() - Manage content-type negociation based on 'script_accepted_types' hooks
1616 * @param string $script
1617 * @param string $default_content_type
1618 * @param string $forced_content_type
1621 function util_negociate_alternate_content_types($script, $default_content_type, $forced_content_type=false) {
1623 $content_type = $default_content_type;
1625 // we can force the content-type to be returned automaticall if necessary
1626 if ($forced_content_type) {
1627 // TODO ideally, in this case we could try and apply the negociation to see if it matches
1628 // one provided by the hooks, but negotiateMimeType() doesn't allow this so for the moment,
1629 // we just force it whatever the hooks support
1630 $content_type = $forced_content_type;
1633 // Invoke plugins' hooks 'script_accepted_types' to discover which alternate content types they would accept for /users/...
1634 $hook_params = array();
1635 $hook_params['script'] = $script;
1636 $hook_params['accepted_types'] = array();
1638 plugin_hook_by_reference('script_accepted_types', $hook_params);
1640 if (count($hook_params['accepted_types'])) {
1641 // By default, text/html is accepted
1642 $accepted_types = array($default_content_type);
1643 $new_accepted_types = $hook_params['accepted_types'];
1644 $accepted_types = array_merge($accepted_types, $new_accepted_types);
1646 // PEAR::HTTP (for negotiateMimeType())
1647 require_once 'HTTP.php';
1649 // negociate accepted content-type depending on the preferred ones declared by client
1651 $content_type = $http->negotiateMimeType($accepted_types, false);
1654 return $content_type;
1658 * util_gethref() - Construct a hypertext reference
1660 * @param string $baseurl
1661 * (optional) base URL (absolute or relative);
1662 * urlencoded, but not htmlencoded
1663 * (default (falsy): PHP_SELF)
1664 * @param array $args
1665 * (optional) associative array of unencoded query parameters;
1666 * false values are ignored
1667 * @param bool $ashtml
1668 * (optional) htmlencode the result?
1670 * @param string $sep
1671 * (optional) argument separator ('&' or ';')
1674 * URL, possibly htmlencoded
1676 function util_gethref($baseurl=false, $args=array(), $ashtml=true, $sep='&') {
1677 $rv = $baseurl ? $baseurl : getStringFromServer('PHP_SELF');
1679 foreach ($args as $k => $v) {
1683 $rv .= $pfx . urlencode($k) . '=' . urlencode($v);
1686 return ($ashtml ? util_html_encode($rv) : $rv);
1690 * util_sanitise_multiline_submission() – Convert text to ASCII CR-LF
1692 * @param string $text
1693 * input string to sanitise
1695 * sanitised string: CR, LF or CR-LF converted to CR-LF
1697 function util_sanitise_multiline_submission($text) {
1698 /* convert all CR-LF into LF */
1699 $text = preg_replace("/\015+\012+/m", "\012", $text);
1700 /* convert all CR or LF into CR-LF */
1701 $text = preg_replace("/[\012\015]/m", "\015\012", $text);
1706 function util_is_html($string) {
1707 return (strip_tags(util_unconvert_htmlspecialchars($string)) != $string);
1710 function util_init_messages() {
1711 global $feedback, $warning_msg, $error_msg;
1713 if (PHP_SAPI == 'cli') {
1714 $feedback = $warning_msg = $error_msg = '';
1716 $feedback = getStringFromCookie('feedback', '');
1717 if ($feedback) setcookie('feedback', '', time()-3600, '/');
1719 $warning_msg = getStringFromCookie('warning_msg', '');
1720 if ($warning_msg) setcookie('warning_msg', '', time()-3600, '/');
1722 $error_msg = getStringFromCookie('error_msg', '');
1723 if ($error_msg) setcookie('error_msg', '', time()-3600, '/');
1727 function util_save_messages() {
1728 global $feedback, $warning_msg, $error_msg;
1730 setcookie('feedback', $feedback, time() + 10, '/');
1731 setcookie('warning_msg', $warning_msg, time() + 10, '/');
1732 setcookie('error_msg', $error_msg, time() + 10, '/');
1737 // c-file-style: "bsd"