3 * FusionForge miscellaneous utils
5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2009-2010, Roland Mas
7 * Copyright 2009-2010, Franck Villaume - Capgemini
8 * Copyright 2010, Thorsten Glaser <t.glaser@tarent.de>
9 * Copyright (C) 2010 Alain Peyrat - Alcatel-Lucent
11 * This file is part of FusionForge.
13 * FusionForge is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published
15 * by the Free Software Foundation; either version 2 of the License,
16 * or (at your option) any later version.
18 * FusionForge is distributed in the hope that it will be useful, but
19 * WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with FusionForge; if not, write to the Free Software
25 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
30 * htpasswd_apr1_md5($plainpasswd) - generate htpasswd md5 format password
32 * From http://www.php.net/manual/en/function.crypt.php#73619
34 function htpasswd_apr1_md5($plainpasswd) {
35 $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
36 $len = strlen($plainpasswd);
37 $text = $plainpasswd.'$apr1$'.$salt;
38 $bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
40 for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
41 for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; }
42 $bin = pack("H32", md5($text));
43 for($i = 0; $i < 1000; $i++) {
44 $new = ($i & 1) ? $plainpasswd : $bin;
45 if ($i % 3) $new .= $salt;
46 if ($i % 7) $new .= $plainpasswd;
47 $new .= ($i & 1) ? $bin : $plainpasswd;
48 $bin = pack("H32", md5($new));
50 for ($i = 0; $i < 5; $i++) {
54 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
56 $tmp = chr(0).chr(0).$bin[11].$tmp;
57 $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
58 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
59 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
60 return "$"."apr1"."$".$salt."$".$tmp;
64 * is_utf8($string) - utf-8 detection
66 * From http://www.php.net/manual/en/function.mb-detect-encoding.php#85294
68 function is_utf8($str) {
72 for($i=0; $i<$len; $i++){
75 if(($c >= 254)) return false;
76 elseif($c >= 252) $bits=6;
77 elseif($c >= 248) $bits=5;
78 elseif($c >= 240) $bits=4;
79 elseif($c >= 224) $bits=3;
80 elseif($c >= 192) $bits=2;
82 if(($i+$bits) > $len) return false;
86 if($b < 128 || $b > 191) return false;
95 * removeCRLF() - remove any Carriage Return-Line Feed from a string.
96 * That function is useful to remove the possibility of a CRLF Injection when sending mail
97 * All the data that we will send should be passed through that function
99 * @param string The string that we want to empty from any CRLF
101 function util_remove_CRLF($str) {
102 return strtr($str, "\015\012", ' ');
107 * util_check_fileupload() - determines if a filename is appropriate for upload
109 * @param array The uploaded file as returned by getUploadedFile()
111 function util_check_fileupload($filename) {
113 /* Empty file is a valid file.
114 This is because this function should be called
115 unconditionally at the top of submit action processing
116 and many forms have optional file upload. */
117 if ($filename == 'none' || $filename == '') {
121 /* This should be enough... */
122 if (!is_uploaded_file($filename)) {
125 /* ... but we'd rather be paranoic */
126 if (strstr($filename, '..')) {
129 if (!is_file($filename)) {
132 if (!file_exists($filename)) {
135 if ((dirname($filename) != '/tmp') &&
136 (dirname($filename) != "/var/tmp")) {
143 * util_check_url() - determines if given URL is valid.
145 * Currently, test is very basic, only the protocol is
146 * checked, allowed values are: http, https, ftp.
148 * @param string The URL
149 * @return boolean true if valid, false if not valid.
151 function util_check_url($url) {
152 return (preg_match('/^(http|https|ftp):\/\//', $url) > 0);
156 * util_send_message() - Send email
157 * This function should be used in place of the PHP mail() function
159 * @param string The email recipients address
160 * @param string The email subject
161 * @param string The body of the email message
162 * @param string The optional email sender address. Defaults to 'noreply@'
163 * @param string The addresses to blind-carbon-copy this message
164 * @param string The optional email sender name. Defaults to ''
165 * @param boolean Whether to send plain text or html email
168 function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='',$send_html_email=false) {
172 $to='noreply@'.forge_get_config('web_host');
175 $from='noreply@'.forge_get_config('web_host');
179 $charset = _('UTF-8');
185 if ($extra_headers) {
186 $body2 .= $extra_headers."\n";
189 "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset);
190 if (forge_get_config('bcc_all_emails') != '') {
191 $BCC.=",".forge_get_config('bcc_all_emails');
194 $body2 .= "\nBCC: $BCC";
196 $send_html_email?$type="html":$type="plain";
197 $body2 .= "\n".util_encode_mimeheader("Subject", $subject, $charset).
198 "\nContent-type: text/$type; charset=$charset".
200 util_convert_body($body, $charset);
202 if (!forge_get_config('sendmail_path')){
203 $sys_sendmail_path="/usr/sbin/sendmail";
206 $handle = popen(forge_get_config('sendmail_path')." -f'$from' -t -i", 'w');
207 fwrite ($handle, $body2);
212 * util_encode_mailaddr() - Encode email address to MIME format
214 * @param string The email address
215 * @param string The email's owner name
216 * @param string The converting charset
219 function util_encode_mailaddr($email,$name,$charset) {
220 if (function_exists('mb_convert_encoding') && trim($name) != "") {
221 $name = "=?".$charset."?B?".
222 base64_encode(mb_convert_encoding(
223 $name,$charset,"UTF-8")).
227 return $name." <".$email."> ";
231 * util_encode_mimeheader() - Encode mimeheader
233 * @param string The name of the header (e.g. "Subject")
234 * @param string The email subject
235 * @param string The converting charset (like ISO-2022-JP)
236 * @return string The MIME encoded subject
239 function util_encode_mimeheader($headername,$str,$charset) {
240 if (function_exists('mb_internal_encoding') &&
241 function_exists('mb_encode_mimeheader')) {
242 $x = mb_internal_encoding();
243 mb_internal_encoding("UTF-8");
244 $y = mb_encode_mimeheader($headername . ": " . $str,
246 mb_internal_encoding($x);
250 if (!function_exists('mb_convert_encoding')) {
251 return $headername . ": " . $str;
254 return $headername . ": " . "=?".$charset."?B?".
255 base64_encode(mb_convert_encoding(
256 $str,$charset,"UTF-8")).
261 * util_convert_body() - Convert body of the email message
263 * @param string The body of the email message
264 * @param string The charset of the email message
265 * @return string The converted body of the email message
268 function util_convert_body($str,$charset) {
269 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
273 return mb_convert_encoding($str,$charset,"UTF-8");
276 function util_send_jabber($to,$subject,$body) {
277 if (!forge_get_config('use_jabber')) {
280 $JABBER = new Jabber();
281 if (!$JABBER->Connect()) {
282 echo '<br />Unable to connect';
285 //$JABBER->SendAuth();
286 //$JABBER->AccountRegistration();
287 if (!$JABBER->SendAuth()) {
288 echo '<br />Auth Failure';
289 $JABBER->Disconnect();
291 //or die("Couldn't authenticate!");
293 $JABBER->SendPresence(NULL, NULL, "online");
295 $body=htmlspecialchars($body);
296 $to_arr=explode(',',$to);
297 for ($i=0; $i<count($to_arr); $i++) {
299 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
300 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
301 echo '<br />Error Sending to '.$to_arr[$i];
306 $JABBER->CruiseControl(2);
307 $JABBER->Disconnect();
311 * util_handle_message() - a convenience wrapper which sends messages
312 * to either a jabber account or email account or both, depending on
315 * @param array array of user_id's from the user table
316 * @param string subject of the message
317 * @param string the message body
318 * @param string a comma-separated list of email address
319 * @param string a comma-separated list of jabber address
320 * @param string From header
322 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='',$from='') {
325 if (count($id_arr) < 1) {
328 $res = db_query_params ('SELECT user_id,jabber_address,email,jabber_only FROM users WHERE user_id = ANY ($1)',
329 array (db_int_array_to_any_clause ($id_arr))) ;
330 $rows = db_numrows($res) ;
332 for ($i=0; $i<$rows; $i++) {
333 if (db_result($res, $i, 'user_id') == 100) {
334 // Do not send messages to "Nobody"
338 // Build arrays of the jabber address
340 if (db_result($res,$i,'jabber_address')) {
341 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
342 if (db_result($res,$i,'jabber_only') != 1) {
343 $address['email'][]=db_result($res,$i,'email');
346 $address['email'][]=db_result($res,$i,'email');
349 if (isset ($address['email']) && count($address['email']) > 0) {
350 $extra_emails=implode($address['email'],',').',' . $extra_emails;
352 if (isset ($address['jabber_address']) && count($address['jabber_address']) > 0) {
353 $extra_jabbers=implode($address['jabber_address'],',').','.$extra_jabbers;
357 util_send_message('',$subject,$body,$from,$extra_emails);
359 if ($extra_jabbers) {
360 util_send_jabber($extra_jabbers,$subject,$body);
365 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
367 * @param string The string to unconvert
368 * @returns The unconverted string
371 function util_unconvert_htmlspecialchars($string) {
372 if (strlen($string) < 1) {
375 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
376 $trans = get_html_translation_table(HTML_ENTITIES);
377 $trans = array_flip ($trans);
378 $str = strtr ($string, $trans);
384 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
386 * @param string The result set ID
387 * @param int The column key
388 * @param int The optional column value
389 * @returns An associative array
392 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
393 $rows=db_numrows($result);
397 for ($i=0; $i<$rows; $i++) {
398 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
407 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
409 * @param int The result set ID
410 * @param int The column
414 function &util_result_column_to_array($result, $col=0) {
416 Takes a result set and turns the optional column into
419 $rows=db_numrows($result);
423 for ($i=0; $i<$rows; $i++) {
424 $arr[$i]=db_result($result,$i,$col);
433 * util_wrap_find_space() - Find the first space in a string
435 * @param string The string in which to find the space (must be UTF8!)
436 * @param int The number of characters to wrap - Default is 80
437 * @returns The position of the first space
440 function util_wrap_find_space($string,$wrap) {
447 //find the first space starting at $start
448 $pos=@strpos($string,' ',$start);
450 //if that space is too far over, go back and start more to the left
451 if (($pos > ($wrap+5)) || !$pos) {
453 $start=($wrap-($try*5));
454 //if we've gotten so far left , just truncate the line
457 $code = ord(substr($string,$wrap,1));
460 //Here is single byte character
461 //or head of multi byte character
464 //Do not break multi byte character
479 * util_line_wrap() - Automatically linewrap text
481 * @param string The text to wrap
482 * @param int The number of characters to wrap - Default is 80
483 * @param string The line break to use - Default is '\n'
484 * @returns The wrapped text
487 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
488 $paras = explode("\n", $text);
492 while ($i < count($paras)) {
493 if (strlen($paras[$i]) <= $wrap) {
494 $result[] = $paras[$i];
497 $pos=util_wrap_find_space($paras[$i],$wrap);
499 $result[] = substr($paras[$i], 0, $pos);
501 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
504 $pos=util_wrap_find_space($paras[$i],$wrap);
510 return implode($break, $result);
514 * util_make_links() - Turn URL's into HREF's.
516 * @param string The URL
517 * @returns The HREF'ed URL
520 function util_make_links ($data='') {
524 $lines = explode("\n",$data);
526 while ( list ($key,$line) = each ($lines)) {
527 // When we come here, we usually have form input
528 // encoded in entities. Our aim is to NOT include
529 // angle brackets in the URL
530 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
531 $line = str_replace('>', "\1", $line);
532 $line = preg_replace( "/([ \t]|^)www\./i", " http://www.", $line);
533 $text = preg_replace( "/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
534 "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
535 $text = preg_replace(
536 "/([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))/i",
537 "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>",
540 $text = str_replace("\1", '>', $text);
547 * show_priority_colors_key() - Show the priority colors legend
550 function show_priority_colors_key() {
551 echo '<p /><strong> '._('Priority Colors').':</strong><br />
553 <table border="0"><tr>';
555 for ($i=1; $i<6; $i++) {
557 <td class="priority'.$i.'">'.$i.'</td>';
559 echo '</tr></table>';
563 * utils_buildcheckboxarray() - Build a checkbox array
565 * @param int Number of options to be in the array
566 * @param string The name of the checkboxes
567 * @param array An array of boxes to be pre-checked
570 function utils_buildcheckboxarray($options,$name,$checked_array) {
571 $option_count=count($options);
572 $checked_count=count($checked_array);
574 for ($i=1; $i<=$option_count; $i++) {
576 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
577 for ($j=0; $j<$checked_count; $j++) {
578 if ($i == $checked_array[$j]) {
582 echo '> '.$options[$i];
587 * utils_requiredField() - Adds the required field marker
589 * @return a string holding the HTML to mark a required field
591 function utils_requiredField() {
592 return '<span class="requiredfield">*</span>';
596 * GraphResult() - Takes a database result set and builds a graph.
597 * The first column should be the name, and the second column should be the values
598 * Be sure to include HTL_Graphs.php before using this function
600 * @author Tim Perdue tperdue@valinux.com
601 * @param int The databse result set ID
602 * @param string The title of the graph
605 Function GraphResult($result,$title) {
606 $rows=db_numrows($result);
608 if ((!$result) || ($rows < 1)) {
614 for ($j=0; $j<db_numrows($result); $j++) {
615 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
616 $names[$j]= db_result($result, $j, 0);
617 $values[$j]= db_result($result, $j, 1);
622 This is another function detailed below
624 GraphIt($names,$values,$title);
629 * GraphIt() - Build a graph
631 * @author Tim Perdue tperdue@valinux.com
632 * @param array An array of names
633 * @param array An array of values
634 * @param string The title of the graph
637 Function GraphIt($name_string,$value_string,$title) {
640 $counter=count($name_string);
643 Can choose any color you wish
647 for ($i = 0; $i < $counter; $i++) {
648 $bars[$i]=$HTML->COLOR_LTBACK1;
651 $counter=count($value_string);
654 Figure the max_value passed in, so scale can be determined
659 for ($i = 0; $i < $counter; $i++) {
660 if ($value_string[$i] > $max_value) {
661 $max_value=$value_string[$i];
665 if ($max_value < 1) {
670 I want my graphs all to be 800 pixels wide, so that is my divisor
673 $scale=(400/$max_value);
676 I create a wrapper table around the graph that holds the title
682 echo $GLOBALS['HTML']->listTableTop ($title_arr);
685 Create an associate array to pass in. I leave most of it blank
714 This is the actual call to the HTML_Graphs class
717 html_graph($name_string,$value_string,$bars,$vals);
721 <!-- end outer graph table -->';
722 echo $GLOBALS['HTML']->listTableBottom();
726 * ShowResultSet() - Show a generic result set
727 * Very simple, plain way to show a generic result set
729 * @param int The result set ID
730 * @param string The title of the result set
731 * @param bool The option to turn URL's into links
732 * @param bool The option to display headers
733 * @param array The db field name -> label mapping
734 * @param array Don't display these cols
737 function ShowResultSet($result,$title='',$linkify=false,$displayHeaders=true,$headerMapping=array(), $excludedCols=array()) {
738 global $group_id,$HTML;
741 $rows = db_numrows($result);
742 $cols = db_numfields($result);
744 echo '<table border="0" width="100%">';
746 /* Create the headers */
747 $headersCellData = array();
748 $colsToKeep = array();
749 for ($i=0; $i < $cols; $i++) {
750 $fieldName = db_fieldname($result, $i);
751 if(in_array($fieldName, $excludedCols)) {
755 if(isset($headerMapping[$fieldName])) {
756 if(is_array($headerMapping[$fieldName])) {
757 $headersCellData[] = $headerMapping[$fieldName];
759 $headersCellData[] = array($headerMapping[$fieldName]);
763 $headersCellData[] = array($fieldName);
767 /* Create the title */
768 if(strlen($title) > 0) {
769 $titleCellData = array();
770 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
771 echo $HTML->multiTableRow('', $titleCellData, TRUE);
774 /* Display the headers */
775 if($displayHeaders) {
776 echo $HTML->multiTableRow('', $headersCellData, TRUE);
779 /* Create the rows */
780 for ($j = 0; $j < $rows; $j++) {
781 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
782 for ($i = 0; $i < $cols; $i++) {
783 if(in_array($i, $colsToKeep)) {
784 if ($linkify && $i == 0) {
785 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
787 if ($linkify == "bug_cat") {
788 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
789 } else if($linkify == "bug_group") {
790 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
791 } else if($linkify == "patch_cat") {
792 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
793 } else if($linkify == "support_cat") {
794 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
795 } else if($linkify == "pm_project") {
796 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
798 $link = $linkend = '';
801 $link = $linkend = '';
803 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
815 * validate_email() - Validate an email address
817 * @param string The address string to validate
818 * @returns true on success/false on error
821 function validate_email ($address) {
822 if ( preg_match( "/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+$/", $address) ) {
830 * validate_emails() - Validate a list of e-mail addresses
832 * @param string E-mail list
833 * @param char Separator
834 * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
836 function validate_emails ($addresses, $separator=',') {
837 if (strlen($addresses) == 0) return array();
839 $emails = explode($separator, $addresses);
842 if (is_array($emails)) {
843 foreach ($emails as $email) {
844 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
845 if (!validate_email($email)) $ret[] = $email;
854 * util_is_valid_filename() - Verifies whether a file has a valid filename
856 * @param string The file to verify
857 * @returns true on success/false on error
860 function util_is_valid_filename ($file) {
862 $invalidchars = preg_replace("/[-A-Z0-9+_\. ~]/i","",$file);
864 if (!empty($invalidchars)) {
867 if (strstr($file,'..')) {
876 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
878 * @param string The optional hostname string
879 * @returns true on success/false on failur
882 function valid_hostname ($hostname = "xyz") {
885 $invalidchars = preg_replace("/[-A-Z0-9\.]/i","",$hostname);
887 if (!empty($invalidchars)) {
891 //double dot, starts with a . or -
892 if ( preg_match("/\.\./",$hostname) || preg_match("/^\./",$hostname) || preg_match("/^\-/",$hostname) ) {
896 $multipoint = explode(".",$hostname);
898 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
908 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
910 * Format file size in a human-readable way
911 * such as "xx Megabytes" or "xx Mo"
913 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
915 * @param int bytes is the size
916 * @param bool base10 enable base 10 representation, otherwise
917 * default base 2 is used
918 * @param int round number of fractional digits
919 * @param array labels strings associated to each 2^10 or
920 * 10^3(base10==true) multiple of base units
922 function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array(' bytes', ' KB', ' MB', ' GB')) {
923 if ($bytes <= 0 || !is_array($labels) || (count($labels) <= 0)) {
926 $step = $base10 ? 3 : 10;
927 $base = $base10 ? 10 : 2;
928 $log = (int)(log10($bytes)/log10($base));
930 foreach ($labels as $p=>$lab) {
935 if ($lab == " MB" or $lab == " GB") {
938 $text = round($bytes/pow($base,$pow),$round).$lab;
945 * ls - lists a specified directory and returns an array of files
946 * @param string the path of the directory to list
947 * @param boolean whether to filter out directories and illegal filenames
948 * @return array array of file names.
950 function &ls($dir,$filter=false) {
953 if (is_dir($dir) && ($h = opendir($dir))) {
954 while (($f = readdir($h)) !== false) {
958 if (!util_is_valid_filename($f) ||
959 !is_file($dir . "/" . $f))
970 * readfile_chunked() - replacement for readfile
972 * @param string The file path
973 * @param bool Whether to return bytes served or just a bool
976 function readfile_chunked($filename, $returnBytes=true) {
977 $chunksize = 1*(1024*1024); // 1MB chunks
981 $handle = fopen($filename, 'rb');
982 if ($handle === false) {
987 while (!feof($handle)) {
988 $buffer = fread($handle, $chunksize);
993 $byteCounter += strlen($buffer);
997 $status = fclose($handle);
998 if ($returnBytes && $status) {
999 return $byteCounter; // return num. bytes delivered like readfile() does.
1005 * util_is_root_dir() - Checks if a directory points to the root dir
1006 * @param string Directory
1009 function util_is_root_dir($dir) {
1010 return !preg_match('/[^\\/]/',$dir);
1014 * util_is_dot_or_dotdot() - Checks if a directory points to . or ..
1015 * @param string Directory
1018 function util_is_dot_or_dotdot($dir) {
1019 return preg_match('/^\.\.?$/',trim($dir, '/'));
1023 * util_containts_dot_or_dotdot() - Checks if a directory containts . or ..
1024 * @param string Directory
1027 function util_containts_dot_or_dotdot($dir) {
1028 foreach (explode('/', $dir) as $sub_dir) {
1029 if (util_is_dot_or_dotdot($sub_dir))
1037 * util_secure_filename() - Returns a secured file name
1038 * @param string Filename
1039 * @return string Filename
1041 function util_secure_filename($file) {
1042 $f = preg_replace("/[^-A-Z0-9_\.]/i", '', $file);
1043 if (util_containts_dot_or_dotdot($f))
1044 $f = preg_replace("/\./", '_', $f);
1051 * util_strip_accents() - Remove accents from given text.
1052 * @param string Text
1055 function util_strip_accents($text) {
1056 return iconv ('UTF-8', 'US-ASCII//TRANSLIT', $text) ;
1060 * Constructs the forge's URL prefix out of forge_get_config('url_prefix')
1064 function normalized_urlprefix () {
1065 $prefix = forge_get_config('url_prefix') ;
1066 $prefix = preg_replace ("/^\//", "", $prefix) ;
1067 $prefix = preg_replace ("/\/$/", "", $prefix) ;
1068 $prefix = "/$prefix/" ;
1069 if ($prefix == '//')
1075 * Construct full URL from a relative path
1077 * @param string $path
1078 * @return string URL
1080 function util_make_url ($path) {
1081 if (forge_get_config('use_ssl')) {
1083 $url .= forge_get_config('web_host') ;
1084 if (forge_get_config('https_port') != 443) {
1085 $url .= ":".forge_get_config('https_port') ;
1089 $url .= forge_get_config('web_host') ;
1090 if (forge_get_config('http_port') != 80) {
1091 $url .= ":".forge_get_config('http_port') ;
1094 $url .= util_make_uri ($path) ;
1099 * Construct proper (relative) URI (prepending prefix)
1101 * @param string $path
1102 * @return string URI
1104 function util_make_uri ($path) {
1105 $path = preg_replace ('/^\//', '', $path) ;
1106 $uri = normalized_urlprefix () ;
1111 function util_make_link ($path, $text, $extra_params=false, $absolute=false) {
1113 if (is_array($extra_params)) {
1114 foreach ($extra_params as $key => $value) {
1115 $ep .= "$key=\"$value\" ";
1119 return '<a ' . $ep . 'href="' . $path . '">' . $text . '</a>' ;
1121 return '<a ' . $ep . 'href="' . util_make_uri($path) . '">' . $text . '</a>' ;
1126 * Create an HTML link to a user's profile page
1128 * @param string $username
1129 * @param int $user_id
1130 * @param string $text
1133 function util_make_link_u ($username, $user_id,$text) {
1134 return '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>' ;
1138 * Display username with link to a user's profile page
1139 * and icon face if possible.
1141 * @param string $username
1142 * @param int $user_id
1143 * @param string $text
1144 * @param string $size
1147 function util_display_user($username, $user_id,$text, $size='xs') {
1148 $params = array('user_id' => $user_id, 'size' => $size, 'content' => '');
1149 plugin_hook_by_reference('user_logo', $params);
1150 $url = '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>';
1151 if ($params['content']) {
1152 return $params['content'].$url.'<div class="new_line"></div>';
1158 * Create URL for user's profile page
1160 * @param string $username
1161 * @param int $user_id
1162 * @return string URL
1164 function util_make_url_u ($username, $user_id) {
1165 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1166 return util_make_url ("/developer/?user_id=$user_id");
1168 return util_make_url ("/users/$username/");
1173 * Create a HTML link to a project's page
1174 * @param string $groupame
1175 * @param int $group_id
1176 * @param string $text
1179 function util_make_link_g ($groupame, $group_id,$text) {
1180 return '<a href="' . util_make_url_g ($groupame, $group_id) . '">' . $text . '</a>' ;
1184 * Create URL for a project's page
1186 * @param string $groupame
1187 * @param int $group_id
1190 function util_make_url_g ($groupame, $group_id) {
1191 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1192 return util_make_url ("/project/?group_id=$group_id");
1194 return util_make_url ("/projects/$groupame/");
1198 function util_ensure_value_in_set ($value, $set) {
1199 if (in_array ($value, $set)) {
1206 function check_email_available($group, $email, &$response) {
1207 // Check if a mailing list with same name already exists
1208 $mlFactory = new MailingListFactory($group);
1209 if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
1210 $response .= $mlFactory->getErrorMessage();
1213 $mlArray =& $mlFactory->getMailingLists();
1214 if ($mlFactory->isError()) {
1215 $response .= $mlFactory->getErrorMessage();
1218 for ($j = 0; $j < count($mlArray); $j++) {
1219 $currentList =& $mlArray[$j];
1220 if ($email == $currentList->getName()) {
1221 $response .= _('Error: a mailing list with the same email address already exists.');
1226 // Check if a forum with same name already exists
1227 $ff = new ForumFactory($group);
1228 if (!$ff || !is_object($ff) || $ff->isError()) {
1229 $response .= $ff->getErrorMessage();
1232 $farr =& $ff->getForums();
1233 $prefix = $group->getUnixName() . '-';
1234 for ($j = 0; $j < count($farr); $j++) {
1235 if (is_object($farr[$j])) {
1236 if ($email == $prefix . $farr[$j]->getName()) {
1237 $response .= _('Error: a forum with the same email address already exists.');
1243 // Email is available
1247 function use_javascript($js) {
1248 return $GLOBALS['HTML']->addJavascript($js);
1251 function use_stylesheet($css, $media='') {
1252 return $GLOBALS['HTML']->addStylesheet($css, $media);
1255 // array_replace_recursive only appeared in PHP 5.3.0
1256 if (!function_exists('array_replace_recursive')) {
1257 function array_replace_recursive ($a1, $a2) {
1260 if (!is_array ($a2)) {
1264 foreach ($a2 as $k => $v) {
1265 if (!is_array ($v) ||
1266 !isset ($result[$k]) || !is_array ($result[$k])) {
1270 $result[$k] = array_replace_recursive ($result[$k],
1278 // json_encode only appeared in PHP 5.2.0
1279 if (!function_exists('json_encode')) {
1280 require_once $gfcommon.'include/minijson.php' ;
1281 function json_encode ($a1) {
1282 return minijson_encode ($a1) ;
1286 /* returns an integer from http://forge/foo/bar.php/123 or false */
1287 function util_path_info_last_numeric_component() {
1288 if (!isset($_SERVER['PATH_INFO']))
1292 foreach (str_split($_SERVER['PATH_INFO']) as $x) {
1296 } else if ($ok == false) {
1297 ; /* need reset using slash */
1298 } else if ((ord($x) >= 48) && (ord($x) <= 57)) {
1299 $rv = $rv * 10 + ord($x) - 48;
1309 function get_cvs_binary_version () {
1310 $string = `cvs --version 2>/dev/null | grep ^Concurrent.Versions.System.*client/server` ;
1311 if (preg_match ('/^Concurrent Versions System .CVS. 1.11.[0-9]*/', $string)) {
1313 } elseif (preg_match ('/^Concurrent Versions System .CVS. 1.12.[0-9]*/', $string)) {
1320 /* get a backtrace as string */
1321 function debug_string_backtrace() {
1323 debug_print_backtrace();
1324 $trace = ob_get_contents();
1327 // Remove first item from backtrace as it's this function
1328 // which is redundant.
1329 $trace = preg_replace('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '',
1332 // Renumber backtrace items.
1333 $trace = preg_replace('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);
1338 function util_ini_get_bytes($id) {
1339 $val = trim(ini_get($id));
1340 $last = strtolower($val[strlen($val)-1]);
1352 function util_get_maxuploadfilesize() {
1353 $postmax = util_ini_get_bytes('post_max_size');
1354 $maxfile = util_ini_get_bytes('upload_max_filesize');
1356 $postfile = (int)(($postmax * 3) / 4);
1358 if ($postfile < $maxfile)
1359 $postfile = $maxfile;
1364 function util_randbytes($num=6) {
1365 $f = fopen("/dev/urandom", "rb");
1366 $b = fread($f, $num);
1369 if (strlen($b) != $num)
1370 exit_error(_('Internal Error'),
1371 _('Could not read from random device'));
1376 /* maximum: 2^31 - 1 due to PHP weakness */
1377 function util_randnum($min=0,$max=32767) {
1378 $ta = unpack("L", util_randbytes(4));
1379 $n = $ta[0] & 0x7FFFFFFF;
1380 $v = $n % (1 + $max - $min);
1386 // c-file-style: "bsd"