3 * FusionForge miscellaneous utils
5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2009-2010, Roland Mas, Franck Villaume - Capgemini
8 * This file is part of FusionForge.
10 * FusionForge is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published
12 * by the Free Software Foundation; either version 2 of the License,
13 * or (at your option) any later version.
15 * FusionForge is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with FusionForge; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
27 * htpasswd_apr1_md5($plainpasswd) - generate htpasswd md5 format password
29 * From http://www.php.net/manual/en/function.crypt.php#73619
31 function htpasswd_apr1_md5($plainpasswd) {
32 $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
33 $len = strlen($plainpasswd);
34 $text = $plainpasswd.'$apr1$'.$salt;
35 $bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
37 for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
38 for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; }
39 $bin = pack("H32", md5($text));
40 for($i = 0; $i < 1000; $i++) {
41 $new = ($i & 1) ? $plainpasswd : $bin;
42 if ($i % 3) $new .= $salt;
43 if ($i % 7) $new .= $plainpasswd;
44 $new .= ($i & 1) ? $bin : $plainpasswd;
45 $bin = pack("H32", md5($new));
47 for ($i = 0; $i < 5; $i++) {
51 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
53 $tmp = chr(0).chr(0).$bin[11].$tmp;
54 $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
55 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
56 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
57 return "$"."apr1"."$".$salt."$".$tmp;
61 * is_utf8($string) - utf-8 detection
63 * From http://www.php.net/manual/en/function.mb-detect-encoding.php#85294
65 function is_utf8($str) {
69 for($i=0; $i<$len; $i++){
72 if(($c >= 254)) return false;
73 elseif($c >= 252) $bits=6;
74 elseif($c >= 248) $bits=5;
75 elseif($c >= 240) $bits=4;
76 elseif($c >= 224) $bits=3;
77 elseif($c >= 192) $bits=2;
79 if(($i+$bits) > $len) return false;
83 if($b < 128 || $b > 191) return false;
92 * removeCRLF() - remove any Carriage Return-Line Feed from a string.
93 * That function is useful to remove the possibility of a CRLF Injection when sending mail
94 * All the data that we will send should be passed through that function
96 * @param string The string that we want to empty from any CRLF
98 function util_remove_CRLF($str) {
99 return strtr($str, "\015\012", ' ');
104 * util_check_fileupload() - determines if a filename is appropriate for upload
106 * @param array The uploaded file as returned by getUploadedFile()
108 function util_check_fileupload($filename) {
110 /* Empty file is a valid file.
111 This is because this function should be called
112 unconditionally at the top of submit action processing
113 and many forms have optional file upload. */
114 if ($filename == 'none' || $filename == '') {
118 /* This should be enough... */
119 if (!is_uploaded_file($filename)) {
122 /* ... but we'd rather be paranoic */
123 if (strstr($filename, '..')) {
126 if (!is_file($filename)) {
129 if (!file_exists($filename)) {
132 if ((dirname($filename) != '/tmp') &&
133 (dirname($filename) != "/var/tmp")) {
140 * util_check_url() - determines if given URL is valid.
142 * Currently, test is very basic, only the protocol is
143 * checked, allowed values are: http, https, ftp.
145 * @param string The URL
146 * @return boolean true if valid, false if not valid.
148 function util_check_url($url) {
149 return (preg_match('/^(http|https|ftp):\/\//', $url) > 0);
153 * util_send_message() - Send email
154 * This function should be used in place of the PHP mail() function
156 * @param string The email recipients address
157 * @param string The email subject
158 * @param string The body of the email message
159 * @param string The optional email sender address. Defaults to 'noreply@'
160 * @param string The addresses to blind-carbon-copy this message
161 * @param string The optional email sender name. Defaults to ''
162 * @param boolean Whether to send plain text or html email
165 function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='',$send_html_email=false) {
169 $to='noreply@'.forge_get_config('web_host');
172 $from='noreply@'.forge_get_config('web_host');
176 $charset = _('UTF-8');
182 if ($extra_headers) {
183 $body2 .= $extra_headers."\n";
186 "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset);
187 if (forge_get_config('bcc_all_emails') != '') {
188 $BCC.=",".forge_get_config('bcc_all_emails');
191 $body2 .= "\nBCC: $BCC";
193 $send_html_email?$type="html":$type="plain";
194 $body2 .= "\n".util_encode_mimeheader("Subject", $subject, $charset).
195 "\nContent-type: text/$type; charset=$charset".
197 util_convert_body($body, $charset);
199 if (!forge_get_config('sendmail_path')){
200 $sys_sendmail_path="/usr/sbin/sendmail";
203 $handle = popen(forge_get_config('sendmail_path')." -f'$from' -t -i", 'w');
204 fwrite ($handle, $body2);
209 * util_encode_mailaddr() - Encode email address to MIME format
211 * @param string The email address
212 * @param string The email's owner name
213 * @param string The converting charset
216 function util_encode_mailaddr($email,$name,$charset) {
217 if (function_exists('mb_convert_encoding') && trim($name) != "") {
218 $name = "=?".$charset."?B?".
219 base64_encode(mb_convert_encoding(
220 $name,$charset,"UTF-8")).
224 return $name." <".$email."> ";
228 * util_encode_mimeheader() - Encode mimeheader
230 * @param string The name of the header (e.g. "Subject")
231 * @param string The email subject
232 * @param string The converting charset (like ISO-2022-JP)
233 * @return string The MIME encoded subject
236 function util_encode_mimeheader($headername,$str,$charset) {
237 if (function_exists('mb_internal_encoding') &&
238 function_exists('mb_encode_mimeheader')) {
239 $x = mb_internal_encoding();
240 mb_internal_encoding("UTF-8");
241 $y = mb_encode_mimeheader($headername . ": " . $str,
243 mb_internal_encoding($x);
247 if (!function_exists('mb_convert_encoding')) {
248 return $headername . ": " . $str;
251 return $headername . ": " . "=?".$charset."?B?".
252 base64_encode(mb_convert_encoding(
253 $str,$charset,"UTF-8")).
258 * util_convert_body() - Convert body of the email message
260 * @param string The body of the email message
261 * @param string The charset of the email message
262 * @return string The converted body of the email message
265 function util_convert_body($str,$charset) {
266 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
270 return mb_convert_encoding($str,$charset,"UTF-8");
273 function util_send_jabber($to,$subject,$body) {
274 if (!forge_get_config('use_jabber')) {
277 $JABBER = new Jabber();
278 if (!$JABBER->Connect()) {
279 echo '<br />Unable to connect';
282 //$JABBER->SendAuth();
283 //$JABBER->AccountRegistration();
284 if (!$JABBER->SendAuth()) {
285 echo '<br />Auth Failure';
286 $JABBER->Disconnect();
288 //or die("Couldn't authenticate!");
290 $JABBER->SendPresence(NULL, NULL, "online");
292 $body=htmlspecialchars($body);
293 $to_arr=explode(',',$to);
294 for ($i=0; $i<count($to_arr); $i++) {
296 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
297 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
298 echo '<br />Error Sending to '.$to_arr[$i];
303 $JABBER->CruiseControl(2);
304 $JABBER->Disconnect();
308 * util_handle_message() - a convenience wrapper which sends messages
309 * to either a jabber account or email account or both, depending on
312 * @param array array of user_id's from the user table
313 * @param string subject of the message
314 * @param string the message body
315 * @param string a comma-separated list of email address
316 * @param string a comma-separated list of jabber address
317 * @param string From header
319 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='',$from='') {
322 if (count($id_arr) < 1) {
325 $res = db_query_params ('SELECT user_id,jabber_address,email,jabber_only FROM users WHERE user_id = ANY ($1)',
326 array (db_int_array_to_any_clause ($id_arr))) ;
327 $rows = db_numrows($res) ;
329 for ($i=0; $i<$rows; $i++) {
330 if (db_result($res, $i, 'user_id') == 100) {
331 // Do not send messages to "Nobody"
335 // Build arrays of the jabber address
337 if (db_result($res,$i,'jabber_address')) {
338 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
339 if (db_result($res,$i,'jabber_only') != 1) {
340 $address['email'][]=db_result($res,$i,'email');
343 $address['email'][]=db_result($res,$i,'email');
346 if (isset ($address['email']) && count($address['email']) > 0) {
347 $extra_emails=implode($address['email'],',').',' . $extra_emails;
349 if (isset ($address['jabber_address']) && count($address['jabber_address']) > 0) {
350 $extra_jabbers=implode($address['jabber_address'],',').','.$extra_jabbers;
354 util_send_message('',$subject,$body,$from,$extra_emails);
356 if ($extra_jabbers) {
357 util_send_jabber($extra_jabbers,$subject,$body);
362 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
364 * @param string The string to unconvert
365 * @returns The unconverted string
368 function util_unconvert_htmlspecialchars($string) {
369 if (strlen($string) < 1) {
372 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
373 $trans = get_html_translation_table(HTML_ENTITIES);
374 $trans = array_flip ($trans);
375 $str = strtr ($string, $trans);
381 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
383 * @param string The result set ID
384 * @param int The column key
385 * @param int The optional column value
386 * @returns An associative array
389 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
390 $rows=db_numrows($result);
394 for ($i=0; $i<$rows; $i++) {
395 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
404 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
406 * @param int The result set ID
407 * @param int The column
411 function &util_result_column_to_array($result, $col=0) {
413 Takes a result set and turns the optional column into
416 $rows=db_numrows($result);
420 for ($i=0; $i<$rows; $i++) {
421 $arr[$i]=db_result($result,$i,$col);
430 * util_wrap_find_space() - Find the first space in a string
432 * @param string The string in which to find the space (must be UTF8!)
433 * @param int The number of characters to wrap - Default is 80
434 * @returns The position of the first space
437 function util_wrap_find_space($string,$wrap) {
444 //find the first space starting at $start
445 $pos=@strpos($string,' ',$start);
447 //if that space is too far over, go back and start more to the left
448 if (($pos > ($wrap+5)) || !$pos) {
450 $start=($wrap-($try*5));
451 //if we've gotten so far left , just truncate the line
454 $code = ord(substr($string,$wrap,1));
457 //Here is single byte character
458 //or head of multi byte character
461 //Do not break multi byte character
476 * util_line_wrap() - Automatically linewrap text
478 * @param string The text to wrap
479 * @param int The number of characters to wrap - Default is 80
480 * @param string The line break to use - Default is '\n'
481 * @returns The wrapped text
484 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
485 $paras = explode("\n", $text);
489 while ($i < count($paras)) {
490 if (strlen($paras[$i]) <= $wrap) {
491 $result[] = $paras[$i];
494 $pos=util_wrap_find_space($paras[$i],$wrap);
496 $result[] = substr($paras[$i], 0, $pos);
498 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
501 $pos=util_wrap_find_space($paras[$i],$wrap);
507 return implode($break, $result);
511 * util_make_links() - Turn URL's into HREF's.
513 * @param string The URL
514 * @returns The HREF'ed URL
517 function util_make_links ($data='') {
521 $lines = explode("\n",$data);
523 while ( list ($key,$line) = each ($lines)) {
524 // When we come here, we usually have form input
525 // encoded in entities. Our aim is to NOT include
526 // angle brackets in the URL
527 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
528 $line = str_replace('>', "\1", $line);
529 $line = preg_replace( "/([ \t]|^)www\./i", " http://www.", $line);
530 $text = preg_replace( "/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
531 "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
532 $text = preg_replace(
533 "/([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))/i",
534 "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>",
537 $text = str_replace("\1", '>', $text);
544 * show_priority_colors_key() - Show the priority colors legend
547 function show_priority_colors_key() {
548 echo '<p /><strong> '._('Priority Colors').':</strong><br />
550 <table border="0"><tr>';
552 for ($i=1; $i<6; $i++) {
554 <td class="priority'.$i.'">'.$i.'</td>';
556 echo '</tr></table>';
560 * utils_buildcheckboxarray() - Build a checkbox array
562 * @param int Number of options to be in the array
563 * @param string The name of the checkboxes
564 * @param array An array of boxes to be pre-checked
567 function utils_buildcheckboxarray($options,$name,$checked_array) {
568 $option_count=count($options);
569 $checked_count=count($checked_array);
571 for ($i=1; $i<=$option_count; $i++) {
573 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
574 for ($j=0; $j<$checked_count; $j++) {
575 if ($i == $checked_array[$j]) {
579 echo '> '.$options[$i];
584 * utils_requiredField() - Adds the required field marker
586 * @return a string holding the HTML to mark a required field
588 function utils_requiredField() {
589 return '<span class="requiredfield">*</span>';
593 * GraphResult() - Takes a database result set and builds a graph.
594 * The first column should be the name, and the second column should be the values
595 * Be sure to include HTL_Graphs.php before using this function
597 * @author Tim Perdue tperdue@valinux.com
598 * @param int The databse result set ID
599 * @param string The title of the graph
602 Function GraphResult($result,$title) {
603 $rows=db_numrows($result);
605 if ((!$result) || ($rows < 1)) {
611 for ($j=0; $j<db_numrows($result); $j++) {
612 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
613 $names[$j]= db_result($result, $j, 0);
614 $values[$j]= db_result($result, $j, 1);
619 This is another function detailed below
621 GraphIt($names,$values,$title);
626 * GraphIt() - Build a graph
628 * @author Tim Perdue tperdue@valinux.com
629 * @param array An array of names
630 * @param array An array of values
631 * @param string The title of the graph
634 Function GraphIt($name_string,$value_string,$title) {
637 $counter=count($name_string);
640 Can choose any color you wish
644 for ($i = 0; $i < $counter; $i++) {
645 $bars[$i]=$HTML->COLOR_LTBACK1;
648 $counter=count($value_string);
651 Figure the max_value passed in, so scale can be determined
656 for ($i = 0; $i < $counter; $i++) {
657 if ($value_string[$i] > $max_value) {
658 $max_value=$value_string[$i];
662 if ($max_value < 1) {
667 I want my graphs all to be 800 pixels wide, so that is my divisor
670 $scale=(400/$max_value);
673 I create a wrapper table around the graph that holds the title
679 echo $GLOBALS['HTML']->listTableTop ($title_arr);
682 Create an associate array to pass in. I leave most of it blank
711 This is the actual call to the HTML_Graphs class
714 html_graph($name_string,$value_string,$bars,$vals);
718 <!-- end outer graph table -->';
719 echo $GLOBALS['HTML']->listTableBottom();
723 * ShowResultSet() - Show a generic result set
724 * Very simple, plain way to show a generic result set
726 * @param int The result set ID
727 * @param string The title of the result set
728 * @param bool The option to turn URL's into links
729 * @param bool The option to display headers
730 * @param array The db field name -> label mapping
731 * @param array Don't display these cols
734 function ShowResultSet($result,$title='',$linkify=false,$displayHeaders=true,$headerMapping=array(), $excludedCols=array()) {
735 global $group_id,$HTML;
738 $rows = db_numrows($result);
739 $cols = db_numfields($result);
741 echo '<table border="0" width="100%">';
743 /* Create the headers */
744 $headersCellData = array();
745 $colsToKeep = array();
746 for ($i=0; $i < $cols; $i++) {
747 $fieldName = db_fieldname($result, $i);
748 if(in_array($fieldName, $excludedCols)) {
752 if(isset($headerMapping[$fieldName])) {
753 if(is_array($headerMapping[$fieldName])) {
754 $headersCellData[] = $headerMapping[$fieldName];
756 $headersCellData[] = array($headerMapping[$fieldName]);
760 $headersCellData[] = array($fieldName);
764 /* Create the title */
765 if(strlen($title) > 0) {
766 $titleCellData = array();
767 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
768 echo $HTML->multiTableRow('', $titleCellData, TRUE);
771 /* Display the headers */
772 if($displayHeaders) {
773 echo $HTML->multiTableRow('', $headersCellData, TRUE);
776 /* Create the rows */
777 for ($j = 0; $j < $rows; $j++) {
778 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
779 for ($i = 0; $i < $cols; $i++) {
780 if(in_array($i, $colsToKeep)) {
781 if ($linkify && $i == 0) {
782 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
784 if ($linkify == "bug_cat") {
785 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
786 } else if($linkify == "bug_group") {
787 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
788 } else if($linkify == "patch_cat") {
789 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
790 } else if($linkify == "support_cat") {
791 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
792 } else if($linkify == "pm_project") {
793 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
795 $link = $linkend = '';
798 $link = $linkend = '';
800 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
812 * validate_email() - Validate an email address
814 * @param string The address string to validate
815 * @returns true on success/false on error
818 function validate_email ($address) {
819 if ( preg_match( "/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+$/", $address) ) {
827 * validate_emails() - Validate a list of e-mail addresses
829 * @param string E-mail list
830 * @param char Separator
831 * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
833 function validate_emails ($addresses, $separator=',') {
834 if (strlen($addresses) == 0) return array();
836 $emails = explode($separator, $addresses);
839 if (is_array($emails)) {
840 foreach ($emails as $email) {
841 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
842 if (!validate_email($email)) $ret[] = $email;
851 * util_is_valid_filename() - Verifies whether a file has a valid filename
853 * @param string The file to verify
854 * @returns true on success/false on error
857 function util_is_valid_filename ($file) {
859 $invalidchars = preg_replace("/[-A-Z0-9+_\. ~]/i","",$file);
861 if (!empty($invalidchars)) {
864 if (strstr($file,'..')) {
873 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
875 * @param string The optional hostname string
876 * @returns true on success/false on failur
879 function valid_hostname ($hostname = "xyz") {
882 $invalidchars = preg_replace("/[-A-Z0-9\.]/i","",$hostname);
884 if (!empty($invalidchars)) {
888 //double dot, starts with a . or -
889 if ( preg_match("/\.\./",$hostname) || preg_match("/^\./",$hostname) || preg_match("/^\-/",$hostname) ) {
893 $multipoint = explode(".",$hostname);
895 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
905 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
907 * Format file size in a human-readable way
908 * such as "xx Megabytes" or "xx Mo"
910 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
912 * @param int bytes is the size
913 * @param bool base10 enable base 10 representation, otherwise
914 * default base 2 is used
915 * @param int round number of fractional digits
916 * @param array labels strings associated to each 2^10 or
917 * 10^3(base10==true) multiple of base units
919 function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array(' bytes', ' KB', ' MB', ' GB')) {
920 if ($bytes <= 0 || !is_array($labels) || (count($labels) <= 0)) {
923 $step = $base10 ? 3 : 10;
924 $base = $base10 ? 10 : 2;
925 $log = (int)(log10($bytes)/log10($base));
927 foreach ($labels as $p=>$lab) {
932 if ($lab == " MB" or $lab == " GB") {
935 $text = round($bytes/pow($base,$pow),$round).$lab;
942 * ls - lists a specified directory and returns an array of files
943 * @param string the path of the directory to list
944 * @param boolean whether to filter out directories and illegal filenames
945 * @return array array of file names.
947 function &ls($dir,$filter=false) {
948 if (!is_dir ($dir)) {
952 exec('ls -c1 '.$dir,$out);
954 for ($i=0; $i<count($out); $i++) {
955 if (util_is_valid_filename($out[$i]) && is_file($dir.'/'.$out[$i])) {
956 $filtered[]=$out[$i];
966 * readfile_chunked() - replacement for readfile
968 * @param string The file path
969 * @param bool Whether to return bytes served or just a bool
972 function readfile_chunked($filename, $returnBytes=true) {
973 $chunksize = 1*(1024*1024); // 1MB chunks
977 $handle = fopen($filename, 'rb');
978 if ($handle === false) {
983 while (!feof($handle)) {
984 $buffer = fread($handle, $chunksize);
989 $byteCounter += strlen($buffer);
993 $status = fclose($handle);
994 if ($returnBytes && $status) {
995 return $byteCounter; // return num. bytes delivered like readfile() does.
1001 * util_is_root_dir() - Checks if a directory points to the root dir
1002 * @param string Directory
1005 function util_is_root_dir($dir) {
1006 return !preg_match('/[^\\/]/',$dir);
1010 * Constructs the forge's URL prefix out of forge_get_config('url_prefix')
1014 function normalized_urlprefix () {
1015 $prefix = forge_get_config('url_prefix') ;
1016 $prefix = preg_replace ("/^\//", "", $prefix) ;
1017 $prefix = preg_replace ("/\/$/", "", $prefix) ;
1018 $prefix = "/$prefix/" ;
1019 if ($prefix == '//')
1025 * Construct full URL from a relative path
1027 * @param string $path
1028 * @return string URL
1030 function util_make_url ($path) {
1031 if (forge_get_config('use_ssl'))
1036 $url .= forge_get_config('web_host') ;
1037 $url .= util_make_uri ($path) ;
1042 * Construct proper (relative) URI (prepending prefix)
1044 * @param string $path
1045 * @return string URI
1047 function util_make_uri ($path) {
1048 $path = preg_replace ('/^\//', '', $path) ;
1049 $uri = normalized_urlprefix () ;
1054 function util_make_link ($path, $text, $extra_params=false, $absolute=false) {
1056 if (is_array($extra_params)) {
1057 foreach ($extra_params as $key => $value) {
1058 $ep .= "$key=\"$value\" ";
1062 return '<a ' . $ep . 'href="' . $path . '">' . $text . '</a>' ;
1064 return '<a ' . $ep . 'href="' . util_make_url ($path) . '">' . $text . '</a>' ;
1069 * Create an HTML link to a user's profile page
1071 * @param string $username
1072 * @param int $user_id
1073 * @param string $text
1076 function util_make_link_u ($username, $user_id,$text) {
1077 return '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>' ;
1081 * Display username with link to a user's profile page
1082 * and icon face if possible.
1084 * @param string $username
1085 * @param int $user_id
1086 * @param string $text
1087 * @param string $size
1090 function util_display_user($username, $user_id,$text, $size='xs') {
1091 $params = array('user_id' => $user_id, 'size' => $size, 'content' => '');
1092 plugin_hook_by_reference('user_logo', $params);
1093 $url = '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>';
1094 if ($params['content']) {
1095 return $params['content'].$url.'<div class="new_line"></div>';
1101 * Create URL for user's profile page
1103 * @param string $username
1104 * @param int $user_id
1105 * @return string URL
1107 function util_make_url_u ($username, $user_id) {
1108 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1109 return util_make_url ("/developer/?user_id=$user_id");
1111 return util_make_url ("/users/$username/");
1116 * Create a HTML link to a project's page
1117 * @param string $groupame
1118 * @param int $group_id
1119 * @param string $text
1122 function util_make_link_g ($groupame, $group_id,$text) {
1123 return '<a href="' . util_make_url_g ($groupame, $group_id) . '">' . $text . '</a>' ;
1127 * Create URL for a project's page
1129 * @param string $groupame
1130 * @param int $group_id
1133 function util_make_url_g ($groupame, $group_id) {
1134 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1135 return util_make_url ("/project/?group_id=$group_id");
1137 return util_make_url ("/projects/$groupame/");
1141 function util_ensure_value_in_set ($value, $set) {
1142 if (in_array ($value, $set)) {
1149 function check_email_available($group, $email, &$response) {
1150 // Check if a mailing list with same name already exists
1151 $mlFactory = new MailingListFactory($group);
1152 if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
1153 $response .= $mlFactory->getErrorMessage();
1156 $mlArray =& $mlFactory->getMailingLists();
1157 if ($mlFactory->isError()) {
1158 $response .= $mlFactory->getErrorMessage();
1161 for ($j = 0; $j < count($mlArray); $j++) {
1162 $currentList =& $mlArray[$j];
1163 if ($email == $currentList->getName()) {
1164 $response .= _('Error: a mailing list with the same email address already exists.');
1169 // Check if a forum with same name already exists
1170 $ff = new ForumFactory($group);
1171 if (!$ff || !is_object($ff) || $ff->isError()) {
1172 $response .= $ff->getErrorMessage();
1175 $farr =& $ff->getForums();
1176 $prefix = $group->getUnixName() . '-';
1177 for ($j = 0; $j < count($farr); $j++) {
1178 if (is_object($farr[$j])) {
1179 if ($email == $prefix . $farr[$j]->getName()) {
1180 $response .= _('Error: a forum with the same email address already exists.');
1186 // Email is available
1190 function use_javascript($js) {
1191 return $GLOBALS['HTML']->addJavascript($js);
1194 function use_stylesheet($css, $media='') {
1195 return $GLOBALS['HTML']->addStylesheet($css, $media);
1198 // array_replace_recursive only appeared in PHP 5.3.0
1199 if (!function_exists('array_replace_recursive')) {
1200 function array_replace_recursive ($a1, $a2) {
1203 if (!is_array ($a2)) {
1207 foreach ($a2 as $k => $v) {
1208 if (!is_array ($v) ||
1209 !isset ($result[$k]) || !is_array ($result[$k])) {
1213 $result[$k] = array_replace_recursive ($result[$k],
1221 // json_encode only appeared in PHP 5.2.0
1222 if (!function_exists('json_encode')) {
1223 require_once $gfcommon.'include/minijson.php' ;
1224 function json_encode ($a1) {
1225 return minijson_encode ($a1) ;
1229 /* returns an integer from http://forge/foo/bar.php/123 or false */
1230 function util_path_info_last_numeric_component() {
1231 if (!isset($_SERVER['PATH_INFO']))
1235 foreach (str_split($_SERVER['PATH_INFO']) as $x) {
1239 } else if ($ok == false) {
1240 ; /* need reset using slash */
1241 } else if ((ord($x) >= 48) && (ord($x) <= 57)) {
1242 $rv = $rv * 10 + ord($x) - 48;
1252 function get_cvs_binary_version () {
1253 $string = `cvs --version 2>/dev/null | grep ^Concurrent.Versions.System.*client/server` ;
1254 if (preg_match ('/^Concurrent Versions System .CVS. 1.11.[0-9]*/', $string)) {
1256 } elseif (preg_match ('/^Concurrent Versions System .CVS. 1.12.[0-9]*/', $string)) {
1263 /* get a backtrace as string */
1264 function debug_string_backtrace() {
1266 debug_print_backtrace();
1267 $trace = ob_get_contents();
1270 // Remove first item from backtrace as it's this function
1271 // which is redundant.
1272 $trace = preg_replace('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '',
1275 // Renumber backtrace items.
1276 $trace = preg_replace('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);
1283 // c-file-style: "bsd"