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
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;
94 * removeCRLF() - remove any Carriage Return-Line Feed from a string.
95 * That function is useful to remove the possibility of a CRLF Injection when sending mail
96 * All the data that we will send should be passed through that function
98 * @param string The string that we want to empty from any CRLF
100 function util_remove_CRLF($str) {
101 return strtr($str, "\015\012", ' ');
106 * util_check_fileupload() - determines if a filename is appropriate for upload
108 * @param array The uploaded file as returned by getUploadedFile()
110 function util_check_fileupload($filename) {
112 /* Empty file is a valid file.
113 This is because this function should be called
114 unconditionally at the top of submit action processing
115 and many forms have optional file upload. */
116 if ($filename == 'none' || $filename == '') {
120 /* This should be enough... */
121 if (!is_uploaded_file($filename)) {
124 /* ... but we'd rather be paranoic */
125 if (strstr($filename, '..')) {
128 if (!is_file($filename)) {
131 if (!file_exists($filename)) {
134 if ((dirname($filename) != '/tmp') &&
135 (dirname($filename) != "/var/tmp")) {
142 * util_check_url() - determines if given URL is valid.
144 * Currently, test is very basic, only the protocol is
145 * checked, allowed values are: http, https, ftp.
147 * @param string The URL
148 * @return boolean true if valid, false if not valid.
150 function util_check_url($url) {
151 return (preg_match('/^(http|https|ftp):\/\//', $url) > 0);
155 * util_send_message() - Send email
156 * This function should be used in place of the PHP mail() function
158 * @param string The email recipients address
159 * @param string The email subject
160 * @param string The body of the email message
161 * @param string The optional email sender address. Defaults to 'noreply@'
162 * @param string The addresses to blind-carbon-copy this message
163 * @param string The optional email sender name. Defaults to ''
164 * @param boolean Whether to send plain text or html email
167 function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='',$send_html_email=false) {
171 $to='noreply@'.forge_get_config('web_host');
174 $from='noreply@'.forge_get_config('web_host');
178 $charset = _('UTF-8');
184 if ($extra_headers) {
185 $body2 .= $extra_headers."\n";
188 "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset);
189 if (forge_get_config('bcc_all_emails') != '') {
190 $BCC.=",".forge_get_config('bcc_all_emails');
193 $body2 .= "\nBCC: $BCC";
195 $send_html_email?$type="html":$type="plain";
196 $body2 .= "\n".util_encode_mimeheader("Subject", $subject, $charset).
197 "\nContent-type: text/$type; charset=$charset".
199 util_convert_body($body, $charset);
201 if (!forge_get_config('sendmail_path')){
202 $sys_sendmail_path="/usr/sbin/sendmail";
205 $handle = popen(forge_get_config('sendmail_path')." -f'$from' -t -i", 'w');
206 fwrite ($handle, $body2);
211 * util_encode_mailaddr() - Encode email address to MIME format
213 * @param string The email address
214 * @param string The email's owner name
215 * @param string The converting charset
218 function util_encode_mailaddr($email,$name,$charset) {
219 if (function_exists('mb_convert_encoding') && trim($name) != "") {
220 $name = "=?".$charset."?B?".
221 base64_encode(mb_convert_encoding(
222 $name,$charset,"UTF-8")).
226 return $name." <".$email."> ";
230 * util_encode_mimeheader() - Encode mimeheader
232 * @param string The name of the header (e.g. "Subject")
233 * @param string The email subject
234 * @param string The converting charset (like ISO-2022-JP)
235 * @return string The MIME encoded subject
238 function util_encode_mimeheader($headername,$str,$charset) {
239 if (function_exists('mb_internal_encoding') &&
240 function_exists('mb_encode_mimeheader')) {
241 $x = mb_internal_encoding();
242 mb_internal_encoding("UTF-8");
243 $y = mb_encode_mimeheader($headername . ": " . $str,
245 mb_internal_encoding($x);
249 if (!function_exists('mb_convert_encoding')) {
250 return $headername . ": " . $str;
253 return $headername . ": " . "=?".$charset."?B?".
254 base64_encode(mb_convert_encoding(
255 $str,$charset,"UTF-8")).
260 * util_convert_body() - Convert body of the email message
262 * @param string The body of the email message
263 * @param string The charset of the email message
264 * @return string The converted body of the email message
267 function util_convert_body($str,$charset) {
268 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
272 return mb_convert_encoding($str,$charset,"UTF-8");
275 function util_send_jabber($to,$subject,$body) {
276 if (!forge_get_config('use_jabber')) {
279 $JABBER = new Jabber();
280 if (!$JABBER->Connect()) {
281 echo '<br />Unable to connect';
284 //$JABBER->SendAuth();
285 //$JABBER->AccountRegistration();
286 if (!$JABBER->SendAuth()) {
287 echo '<br />Auth Failure';
288 $JABBER->Disconnect();
290 //or die("Couldn't authenticate!");
292 $JABBER->SendPresence(NULL, NULL, "online");
294 $body=htmlspecialchars($body);
295 $to_arr=explode(',',$to);
296 for ($i=0; $i<count($to_arr); $i++) {
298 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
299 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
300 echo '<br />Error Sending to '.$to_arr[$i];
305 $JABBER->CruiseControl(2);
306 $JABBER->Disconnect();
310 * util_handle_message() - a convenience wrapper which sends messages
311 * to either a jabber account or email account or both, depending on
314 * @param array array of user_id's from the user table
315 * @param string subject of the message
316 * @param string the message body
317 * @param string a comma-separated list of email address
318 * @param string a comma-separated list of jabber address
319 * @param string From header
321 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='',$from='') {
324 if (count($id_arr) < 1) {
327 $res = db_query_params ('SELECT user_id,jabber_address,email,jabber_only FROM users WHERE user_id = ANY ($1)',
328 array (db_int_array_to_any_clause ($id_arr))) ;
329 $rows = db_numrows($res) ;
331 for ($i=0; $i<$rows; $i++) {
332 if (db_result($res, $i, 'user_id') == 100) {
333 // Do not send messages to "Nobody"
337 // Build arrays of the jabber address
339 if (db_result($res,$i,'jabber_address')) {
340 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
341 if (db_result($res,$i,'jabber_only') != 1) {
342 $address['email'][]=db_result($res,$i,'email');
345 $address['email'][]=db_result($res,$i,'email');
348 if (isset ($address['email']) && count($address['email']) > 0) {
349 $extra_emails=implode($address['email'],',').',' . $extra_emails;
351 if (isset ($address['jabber_address']) && count($address['jabber_address']) > 0) {
352 $extra_jabbers=implode($address['jabber_address'],',').','.$extra_jabbers;
356 util_send_message('',$subject,$body,$from,$extra_emails);
358 if ($extra_jabbers) {
359 util_send_jabber($extra_jabbers,$subject,$body);
364 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
366 * @param string The string to unconvert
367 * @returns The unconverted string
370 function util_unconvert_htmlspecialchars($string) {
371 if (strlen($string) < 1) {
374 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
375 $trans = get_html_translation_table(HTML_ENTITIES);
376 $trans = array_flip ($trans);
377 $str = strtr ($string, $trans);
383 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
385 * @param string The result set ID
386 * @param int The column key
387 * @param int The optional column value
388 * @returns An associative array
391 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
392 $rows=db_numrows($result);
396 for ($i=0; $i<$rows; $i++) {
397 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
406 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
408 * @param int The result set ID
409 * @param int The column
413 function &util_result_column_to_array($result, $col=0) {
415 Takes a result set and turns the optional column into
418 $rows=db_numrows($result);
422 for ($i=0; $i<$rows; $i++) {
423 $arr[$i]=db_result($result,$i,$col);
432 * util_wrap_find_space() - Find the first space in a string
434 * @param string The string in which to find the space (must be UTF8!)
435 * @param int The number of characters to wrap - Default is 80
436 * @returns The position of the first space
439 function util_wrap_find_space($string,$wrap) {
446 //find the first space starting at $start
447 $pos=@strpos($string,' ',$start);
449 //if that space is too far over, go back and start more to the left
450 if (($pos > ($wrap+5)) || !$pos) {
452 $start=($wrap-($try*5));
453 //if we've gotten so far left , just truncate the line
456 $code = ord(substr($string,$wrap,1));
459 //Here is single byte character
460 //or head of multi byte character
463 //Do not break multi byte character
478 * util_line_wrap() - Automatically linewrap text
480 * @param string The text to wrap
481 * @param int The number of characters to wrap - Default is 80
482 * @param string The line break to use - Default is '\n'
483 * @returns The wrapped text
486 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
487 $paras = explode("\n", $text);
491 while ($i < count($paras)) {
492 if (strlen($paras[$i]) <= $wrap) {
493 $result[] = $paras[$i];
496 $pos=util_wrap_find_space($paras[$i],$wrap);
498 $result[] = substr($paras[$i], 0, $pos);
500 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
503 $pos=util_wrap_find_space($paras[$i],$wrap);
509 return implode($break, $result);
513 * util_make_links() - Turn URL's into HREF's.
515 * @param string The URL
516 * @returns The HREF'ed URL
519 function util_make_links($data='') {
523 $lines = explode("\n", $data);
525 while ( list ($key, $line) = each ($lines)) {
526 // When we come here, we usually have form input
527 // encoded in entities. Our aim is to NOT include
528 // angle brackets in the URL
529 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
530 $line = str_replace('>', "\1", $line);
531 $line = preg_replace( "/([ \t]|^)www\./i", " http://www.", $line);
532 $text = preg_replace( "/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
533 "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
534 $text = preg_replace(
535 "/([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))/i",
536 "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>",
539 $text = str_replace("\1", '>', $text);
546 * show_priority_colors_key() - Show the priority colors legend
549 function show_priority_colors_key() {
550 echo '<p /><strong> '._('Priority Colors').':</strong><br />
552 <table border="0"><tr>';
554 for ($i=1; $i<6; $i++) {
556 <td class="priority'.$i.'">'.$i.'</td>';
558 echo '</tr></table>';
562 * utils_buildcheckboxarray() - Build a checkbox array
564 * @param int Number of options to be in the array
565 * @param string The name of the checkboxes
566 * @param array An array of boxes to be pre-checked
569 function utils_buildcheckboxarray($options, $name, $checked_array) {
570 $option_count = count($options);
571 $checked_count = count($checked_array);
573 for ($i = 1; $i <= $option_count; $i++) {
575 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
576 for ($j=0; $j < $checked_count; $j++) {
577 if ($i == $checked_array[$j]) {
581 echo '> '.$options[$i];
586 * utils_requiredField() - Adds the required field marker
588 * @return a string holding the HTML to mark a required field
590 function utils_requiredField() {
591 return '<span class="requiredfield">*</span>';
595 * GraphResult() - Takes a database result set and builds a graph.
596 * The first column should be the name, and the second column should be the values
597 * Be sure to include HTL_Graphs.php before using this function
599 * @author Tim Perdue tperdue@valinux.com
600 * @param int The databse result set ID
601 * @param string The title of the graph
604 function GraphResult($result, $title) {
605 $rows = db_numrows($result);
607 if ((!$result) || ($rows < 1)) {
613 for ($j=0; $j < db_numrows($result); $j++) {
614 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
615 $names[$j] = db_result($result, $j, 0);
616 $values[$j] = db_result($result, $j, 1);
621 This is another function detailed below
623 GraphIt($names, $values, $title);
628 * GraphIt() - Build a graph
630 * @author Tim Perdue tperdue@valinux.com
631 * @param array An array of names
632 * @param array An array of values
633 * @param string The title of the graph
636 function GraphIt($name_string, $value_string, $title) {
639 $counter = count($name_string);
642 Can choose any color you wish
646 for ($i = 0; $i < $counter; $i++) {
647 $bars[$i] = $HTML->COLOR_LTBACK1;
650 $counter = count($value_string);
653 Figure the max_value passed in, so scale can be determined
658 for ($i = 0; $i < $counter; $i++) {
659 if ($value_string[$i] > $max_value) {
660 $max_value = $value_string[$i];
664 if ($max_value < 1) {
669 I want my graphs all to be 800 pixels wide, so that is my divisor
672 $scale = (400/$max_value);
675 I create a wrapper table around the graph that holds the title
678 $title_arr = array();
679 $title_arr[] = $title;
681 echo $GLOBALS['HTML']->listTableTop ($title_arr);
684 Create an associate array to pass in. I leave most of it blank
713 This is the actual call to the HTML_Graphs class
716 html_graph($name_string, $value_string, $bars, $vals);
720 <!-- end outer graph table -->';
721 echo $GLOBALS['HTML']->listTableBottom();
725 * ShowResultSet() - Show a generic result set
726 * Very simple, plain way to show a generic result set
728 * @param int The result set ID
729 * @param string The title of the result set
730 * @param bool The option to turn URL's into links
731 * @param bool The option to display headers
732 * @param array The db field name -> label mapping
733 * @param array Don't display these cols
736 function ShowResultSet($result,$title='',$linkify=false,$displayHeaders=true,$headerMapping=array(), $excludedCols=array()) {
737 global $group_id,$HTML;
740 $rows = db_numrows($result);
741 $cols = db_numfields($result);
743 echo '<table border="0" width="100%">';
745 /* Create the headers */
746 $headersCellData = array();
747 $colsToKeep = array();
748 for ($i=0; $i < $cols; $i++) {
749 $fieldName = db_fieldname($result, $i);
750 if(in_array($fieldName, $excludedCols)) {
754 if(isset($headerMapping[$fieldName])) {
755 if(is_array($headerMapping[$fieldName])) {
756 $headersCellData[] = $headerMapping[$fieldName];
758 $headersCellData[] = array($headerMapping[$fieldName]);
762 $headersCellData[] = array($fieldName);
766 /* Create the title */
767 if(strlen($title) > 0) {
768 $titleCellData = array();
769 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
770 echo $HTML->multiTableRow('', $titleCellData, TRUE);
773 /* Display the headers */
774 if($displayHeaders) {
775 echo $HTML->multiTableRow('', $headersCellData, TRUE);
778 /* Create the rows */
779 for ($j = 0; $j < $rows; $j++) {
780 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
781 for ($i = 0; $i < $cols; $i++) {
782 if(in_array($i, $colsToKeep)) {
783 if ($linkify && $i == 0) {
784 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
786 if ($linkify == "bug_cat") {
787 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
788 } else if($linkify == "bug_group") {
789 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
790 } else if($linkify == "patch_cat") {
791 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
792 } else if($linkify == "support_cat") {
793 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
794 } else if($linkify == "pm_project") {
795 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
797 $link = $linkend = '';
800 $link = $linkend = '';
802 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
814 * validate_email() - Validate an email address
816 * @param string The address string to validate
817 * @returns true on success/false on error
820 function validate_email($address) {
821 if ( preg_match( "/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+$/", $address) ) {
829 * validate_emails() - Validate a list of e-mail addresses
831 * @param string E-mail list
832 * @param char Separator
833 * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
835 function validate_emails($addresses, $separator=',') {
836 if (strlen($addresses) == 0) return array();
838 $emails = explode($separator, $addresses);
841 if (is_array($emails)) {
842 foreach ($emails as $email) {
843 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
844 if (!validate_email($email)) $ret[] = $email;
853 * util_is_valid_filename() - Verifies whether a file has a valid filename
855 * @param string The file to verify
856 * @returns true on success/false on error
859 function util_is_valid_filename($file) {
861 $invalidchars = preg_replace("/[-A-Z0-9+_\. ~]/i","",$file);
863 if (!empty($invalidchars)) {
866 if (strstr($file,'..')) {
875 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
877 * @param string The optional hostname string
878 * @returns true on success/false on failur
881 function valid_hostname($hostname = "xyz") {
884 $invalidchars = preg_replace("/[-A-Z0-9\.]/i","",$hostname);
886 if (!empty($invalidchars)) {
890 //double dot, starts with a . or -
891 if ( preg_match("/\.\./",$hostname) || preg_match("/^\./",$hostname) || preg_match("/^\-/",$hostname) ) {
895 $multipoint = explode(".",$hostname);
897 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
907 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
909 * Format file size in a human-readable way
910 * such as "xx Megabytes" or "xx Mo"
912 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
914 * @param int bytes is the size
915 * @param bool base10 enable base 10 representation, otherwise
916 * default base 2 is used
917 * @param int round number of fractional digits
918 * @param array labels strings associated to each 2^10 or
919 * 10^3(base10==true) multiple of base units
921 function human_readable_bytes($bytes, $base10=false, $round=0, $labels=array(' bytes', ' KB', ' MB', ' GB')) {
922 if ($bytes <= 0 || !is_array($labels) || (count($labels) <= 0)) {
925 $step = $base10 ? 3 : 10;
926 $base = $base10 ? 10 : 2;
927 $log = (int)(log10($bytes)/log10($base));
929 foreach ($labels as $p=>$lab) {
934 if ($lab == " MB" or $lab == " GB") {
937 $text = round($bytes/pow($base,$pow),$round).$lab;
944 * ls - lists a specified directory and returns an array of files
945 * @param string the path of the directory to list
946 * @param boolean whether to filter out directories and illegal filenames
947 * @return array array of file names.
949 function &ls($dir,$filter=false) {
952 if (is_dir($dir) && ($h = opendir($dir))) {
953 while (($f = readdir($h)) !== false) {
957 if (!util_is_valid_filename($f) ||
958 !is_file($dir . "/" . $f))
969 * readfile_chunked() - replacement for readfile
971 * @param string The file path
972 * @param bool Whether to return bytes served or just a bool
975 function readfile_chunked($filename, $returnBytes=true) {
976 $chunksize = 1*(1024*1024); // 1MB chunks
980 $handle = fopen($filename, 'rb');
981 if ($handle === false) {
986 while (!feof($handle)) {
987 $buffer = fread($handle, $chunksize);
992 $byteCounter += strlen($buffer);
996 $status = fclose($handle);
997 if ($returnBytes && $status) {
998 return $byteCounter; // return num. bytes delivered like readfile() does.
1004 * util_is_root_dir() - Checks if a directory points to the root dir
1005 * @param string Directory
1008 function util_is_root_dir($dir) {
1009 return !preg_match('/[^\\/]/',$dir);
1013 * util_is_dot_or_dotdot() - Checks if a directory points to . or ..
1014 * @param string Directory
1017 function util_is_dot_or_dotdot($dir) {
1018 return preg_match('/^\.\.?$/',trim($dir, '/'));
1022 * util_containts_dot_or_dotdot() - Checks if a directory containts . or ..
1023 * @param string Directory
1026 function util_containts_dot_or_dotdot($dir) {
1027 foreach (explode('/', $dir) as $sub_dir) {
1028 if (util_is_dot_or_dotdot($sub_dir))
1036 * util_secure_filename() - Returns a secured file name
1037 * @param string Filename
1038 * @return string Filename
1040 function util_secure_filename($file) {
1041 $f = preg_replace("/[^-A-Z0-9_\.]/i", '', $file);
1042 if (util_containts_dot_or_dotdot($f))
1043 $f = preg_replace("/\./", '_', $f);
1050 * util_strip_accents() - Remove accents from given text.
1051 * @param string Text
1054 function util_strip_accents($text) {
1055 return iconv ('UTF-8', 'US-ASCII//TRANSLIT', $text) ;
1059 * Constructs the forge's URL prefix out of forge_get_config('url_prefix')
1063 function normalized_urlprefix() {
1064 $prefix = forge_get_config('url_prefix') ;
1065 $prefix = preg_replace ("/^\//", "", $prefix) ;
1066 $prefix = preg_replace ("/\/$/", "", $prefix) ;
1067 $prefix = "/$prefix/" ;
1068 if ($prefix == '//')
1074 * Construct the base URL http[s]://forge_name[:port]
1076 * @return string base URL
1078 function util_make_base_url() {
1079 if (forge_get_config('use_ssl')) {
1084 $url .= forge_get_config('web_host') ;
1085 if (forge_get_config('https_port') != 443) {
1086 $url .= ":".forge_get_config('https_port') ;
1091 * Construct full URL from a relative path
1093 * @param string $path
1094 * @return string URL
1096 function util_make_url($path = '') {
1097 $url = util_make_base_url().util_make_uri($path) ;
1102 * Find the relative URL from full URL, removing http[s]://forge_name[:port]
1106 function util_find_relative_referer($url) {
1107 $relative_url = str_replace(util_make_base_url(), '', $url);
1108 //now remove previous feedback, error_msg or warning_msg
1109 $relative_url = preg_replace('/&error_msg=.*&/', '&', $relative_url);
1110 $relative_url = preg_replace('/&warning_msg=.*&/', '&', $relative_url);
1111 $relative_url = preg_replace('/&feedback=.*&/', '&', $relative_url);
1112 $relative_url = preg_replace('/&error_msg=.*/', '', $relative_url);
1113 $relative_url = preg_replace('/&warning_msg=.*/', '', $relative_url);
1114 $relative_url = preg_replace('/&feedback=.*/', '', $relative_url);
1115 return $relative_url;
1119 * Construct proper (relative) URI (prepending prefix)
1121 * @param string $path
1122 * @return string URI
1124 function util_make_uri($path) {
1125 $path = preg_replace('/^\//', '', $path);
1126 $uri = normalized_urlprefix();
1131 function util_make_link($path, $text, $extra_params = false, $absolute = false) {
1133 if (session_loggedin()) {
1134 $user = session_get_user();
1135 $use_tooltips = $user->usesTooltips();
1138 if (is_array($extra_params)) {
1139 foreach ($extra_params as $key => $value) {
1140 if ($key != 'title') {
1141 $ep .= "$key=\"$value\" ";
1143 if ($key == 'title' && $use_tooltips) {
1144 $ep .= "$key=\"$value\" ";
1149 return '<a ' . $ep . 'href="' . $path . '">' . $text . '</a>' ;
1151 return '<a ' . $ep . 'href="' . util_make_uri($path) . '">' . $text . '</a>' ;
1156 * Create an HTML link to a user's profile page
1158 * @param string $username
1159 * @param int $user_id
1160 * @param string $text
1163 function util_make_link_u ($username, $user_id,$text) {
1164 return '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>' ;
1168 * Display username with link to a user's profile page
1169 * and icon face if possible.
1171 * @param string $username
1172 * @param int $user_id
1173 * @param string $text
1174 * @param string $size
1177 function util_display_user($username, $user_id, $text, $size='xs') {
1178 // Invoke user_link_with_tooltip plugin
1179 $hook_params = array('resource_type' => 'user', 'username' => $username, 'user_id' => $user_id, 'size' => $size, 'user_link' => '');
1180 plugin_hook_by_reference('user_link_with_tooltip', $hook_params);
1181 if($hook_params['user_link'] != ''){
1182 return $hook_params['user_link'];
1185 // If no plugin replaced it, then back to default standard link
1187 // Invoke user_logo plugin (see gravatar plugin for instance)
1188 $params = array('user_id' => $user_id, 'size' => $size, 'content' => '');
1189 plugin_hook_by_reference('user_logo', $params);
1191 $url = '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>';
1192 if ($params['content']) {
1193 return $params['content'].$url.'<div class="new_line"></div>';
1199 * Create URL for user's profile page
1201 * @param string $username
1202 * @param int $user_id
1203 * @return string URL
1205 function util_make_url_u ($username, $user_id) {
1206 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1207 return util_make_url ("/developer/?user_id=$user_id");
1209 return util_make_url ("/users/$username/");
1214 * Create a HTML link to a project's page
1215 * @param string $groupame
1216 * @param int $group_id
1217 * @param string $text
1220 function util_make_link_g ($groupname, $group_id,$text) {
1221 $hook_params =array();
1222 $hook_params['resource_type'] = 'group';
1223 $hook_params['group_name'] = $groupname;
1224 $hook_params['group_id'] = $group_id;
1225 $hook_params['link_text'] = $text;
1226 $hook_params['group_link'] = '';
1227 plugin_hook_by_reference('project_link_with_tooltip', $hook_params);
1228 if($hook_params['group_link'] != '') {
1229 return $hook_params['group_link'];
1232 return '<a href="' . util_make_url_g ($groupname, $group_id) . '">' . $text . '</a>' ;
1236 * Create URL for a project's page
1238 * @param string $groupame
1239 * @param int $group_id
1242 function util_make_url_g ($groupame, $group_id) {
1243 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1244 return util_make_url ("/project/?group_id=$group_id");
1246 return util_make_url ("/projects/$groupame/");
1250 function util_ensure_value_in_set ($value, $set) {
1251 if (in_array ($value, $set)) {
1258 function check_email_available($group, $email, &$response) {
1259 // Check if a mailing list with same name already exists
1260 $mlFactory = new MailingListFactory($group);
1261 if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
1262 $response .= $mlFactory->getErrorMessage();
1265 $mlArray = $mlFactory->getMailingLists();
1266 if ($mlFactory->isError()) {
1267 $response .= $mlFactory->getErrorMessage();
1270 for ($j = 0; $j < count($mlArray); $j++) {
1271 $currentList =& $mlArray[$j];
1272 if ($email == $currentList->getName()) {
1273 $response .= _('Error: a mailing list with the same email address already exists.');
1278 // Check if a forum with same name already exists
1279 $ff = new ForumFactory($group);
1280 if (!$ff || !is_object($ff) || $ff->isError()) {
1281 $response .= $ff->getErrorMessage();
1284 $farr = $ff->getForums();
1285 $prefix = $group->getUnixName() . '-';
1286 for ($j = 0; $j < count($farr); $j++) {
1287 if (is_object($farr[$j])) {
1288 if ($email == $prefix . $farr[$j]->getName()) {
1289 $response .= _('Error: a forum with the same email address already exists.');
1295 // Email is available
1300 * Adds the Javascript file to the lits to be used
1301 * @param unknown_type $js
1303 function use_javascript($js) {
1304 return $GLOBALS['HTML']->addJavascript($js);
1307 function use_stylesheet($css, $media='') {
1308 return $GLOBALS['HTML']->addStylesheet($css, $media);
1311 // array_replace_recursive only appeared in PHP 5.3.0
1312 if (!function_exists('array_replace_recursive')) {
1314 * Replaces elements from passed arrays into the first array recursively
1315 * @param array $a1 The array in which elements are replaced.
1316 * @param array $a2 The array from which elements will be extracted.
1317 * @return Returns an array, or NULL if an error occurs.
1319 function array_replace_recursive ($a1, $a2) {
1322 if (!is_array ($a2)) {
1326 foreach ($a2 as $k => $v) {
1327 if (!is_array ($v) ||
1328 !isset ($result[$k]) || !is_array ($result[$k])) {
1332 $result[$k] = array_replace_recursive ($result[$k],
1340 // json_encode only appeared in PHP 5.2.0
1341 if (!function_exists('json_encode')) {
1342 require_once $gfcommon.'include/minijson.php' ;
1343 function json_encode ($a1) {
1344 return minijson_encode ($a1) ;
1348 /* returns an integer from http://forge/foo/bar.php/123 or false */
1349 function util_path_info_last_numeric_component() {
1350 if (!isset($_SERVER['PATH_INFO']))
1354 foreach (str_split($_SERVER['PATH_INFO']) as $x) {
1358 } else if ($ok == false) {
1359 ; /* need reset using slash */
1360 } else if ((ord($x) >= 48) && (ord($x) <= 57)) {
1361 $rv = $rv * 10 + ord($x) - 48;
1371 function get_cvs_binary_version () {
1372 $string = `cvs --version 2>/dev/null | grep ^Concurrent.Versions.System.*client/server` ;
1373 if (preg_match ('/^Concurrent Versions System .CVS. 1.11.[0-9]*/', $string)) {
1375 } elseif (preg_match ('/^Concurrent Versions System .CVS. 1.12.[0-9]*/', $string)) {
1382 /* get a backtrace as string */
1383 function debug_string_backtrace() {
1385 debug_print_backtrace();
1386 $trace = ob_get_contents();
1389 // Remove first item from backtrace as it's this function
1390 // which is redundant.
1391 $trace = preg_replace('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '',
1394 // Renumber backtrace items.
1395 $trace = preg_replace('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);
1400 function util_ini_get_bytes($id) {
1401 $val = trim(ini_get($id));
1402 $last = strtolower($val[strlen($val)-1]);
1414 function util_get_maxuploadfilesize() {
1415 $postmax = util_ini_get_bytes('post_max_size');
1416 $maxfile = util_ini_get_bytes('upload_max_filesize');
1418 $postfile = (int)(($postmax * 3) / 4);
1420 if ($postfile < $maxfile)
1421 $postfile = $maxfile;
1426 function util_get_compressed_file_extension() {
1427 $m = forge_get_config('compression_method');
1428 if (preg_match ('/^gzip /', $m)) {
1430 } elseif (preg_match ('/^bzip2 /', $m)) {
1432 } elseif (preg_match ('/^lzma /', $m)) {
1434 } elseif (preg_match ('/^xz /', $m)) {
1436 } elseif (preg_match ('/^cat /', $m)) {
1439 return '.compressed';
1443 /* return $1 if $1 is set, ${2:-false} otherwise */
1444 function util_ifsetor(&$val, $default = false) {
1445 return (isset($val) ? $val : $default);
1448 function util_randbytes($num=6) {
1451 // Let's try /dev/urandom first
1452 $f = @fopen("/dev/urandom", "rb");
1454 $b .= @fread($f, $num);
1458 // Hm. No /dev/urandom? Try /dev/random.
1459 if (strlen($b) < $num) {
1460 $f = @fopen("/dev/random", "rb");
1462 $b .= @fread($f, $num);
1467 // Still no luck? Fall back to PHP's built-in PRNG
1468 while (strlen($b) < $num) {
1469 $b .= uniqid(mt_rand(), true);
1472 $b = substr($b, 0, $num);
1476 /* maximum: 2^31 - 1 due to PHP weakness */
1477 function util_randnum($min=0,$max=32767) {
1478 $ta = unpack("L", util_randbytes(4));
1479 $n = $ta[1] & 0x7FFFFFFF;
1480 $v = $n % (1 + $max - $min);
1484 // sys_get_temp_dir() is only available for PHP >= 5.2.1
1485 if ( !function_exists('sys_get_temp_dir')) {
1486 function sys_get_temp_dir() {
1487 if ($temp=getenv('TMP')) return $temp;
1488 if ($temp=getenv('TEMP')) return $temp;
1489 if ($temp=getenv('TMPDIR')) return $temp;
1494 /* convert '\n' to <br /> or </p><p> */
1495 function util_pwrap($encoded_string) {
1496 return str_replace("<p></p>", "",
1497 str_replace("<br /></p>", "</p>",
1498 str_replace("<p><br />", "<p>",
1499 "<p>" . str_replace("<br /><br />", "</p><p>",
1500 implode("<br />", explode("\n",
1501 $encoded_string))) . "</p>")));
1503 function util_ttwrap($encoded_string) {
1504 return str_replace("<p><tt></tt></p>", "",
1505 str_replace("<br /></tt></p>", "</tt></p>",
1506 str_replace("<p><tt><br />", "<p><tt>",
1507 "<p><tt>" . str_replace("<br /><br />", "</tt></p><p><tt>",
1508 implode("<br />", explode("\n",
1509 encoded_string))) . "</tt></p>")));
1512 /* takes a string and returns it HTML encoded, URIs made to hrefs */
1513 function util_uri_grabber($unencoded_string, $tryaidtid=false) {
1514 /* escape all ^A and ^B as ^BX^B and ^BY^B, respectively */
1515 $s = str_replace("\x01", "\x02X\x02", str_replace("\x02", "\x02Y\x02",
1516 $unencoded_string));
1517 /* replace all URIs with ^AURI^A */
1519 '|([a-zA-Z][a-zA-Z0-9+.-]*:[#0-9a-zA-Z;/?:@&=+$,_.!~*\'()%-]+)|',
1522 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1523 /* encode the string */
1524 $s = htmlentities($s, ENT_QUOTES, "UTF-8");
1525 /* convert ć^Afoo^Ać to ć<a href="foo">foo</a>ć */
1526 $s = preg_replace('|\x01([^\x01]+)\x01|',
1527 '<a href="$1">$1</a>', $s);
1529 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1530 // /* convert [#123] to links if found */
1532 // $s = util_tasktracker_links($s);
1533 /* convert ^BX^B and ^BY^B back to ^A and ^B, respectively */
1534 $s = str_replace("\x02Y\x02", "\x02", str_replace("\x02X\x02", "\x01",
1536 /* return the final result */
1540 /* secure a (possibly already HTML encoded) string */
1541 function util_html_secure($s) {
1542 return htmlentities(html_entity_decode($s, ENT_QUOTES, "UTF-8"),
1543 ENT_QUOTES, "UTF-8");
1548 // c-file-style: "bsd"