3 * FusionForge miscellaneous utils
5 * Copyright 1999-2001, VA Linux Systems, Inc.
6 * Copyright 2009, Roland Mas
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 * is_utf8($string) - utf-8 detection
29 * From http://www.php.net/manual/en/function.mb-detect-encoding.php#85294
31 function is_utf8($str) {
35 for($i=0; $i<$len; $i++){
38 if(($c >= 254)) return false;
39 elseif($c >= 252) $bits=6;
40 elseif($c >= 248) $bits=5;
41 elseif($c >= 240) $bits=4;
42 elseif($c >= 224) $bits=3;
43 elseif($c >= 192) $bits=2;
45 if(($i+$bits) > $len) return false;
49 if($b < 128 || $b > 191) return false;
58 * removeCRLF() - remove any Carriage Return-Line Feed from a string.
59 * That function is useful to remove the possibility of a CRLF Injection when sending mail
60 * All the data that we will send should be passed through that function
62 * @param string The string that we want to empty from any CRLF
64 function util_remove_CRLF($str) {
65 return strtr($str, "\015\012", ' ');
70 * util_check_fileupload() - determines if a filename is appropriate for upload
72 * @param array The uploaded file as returned by getUploadedFile()
74 function util_check_fileupload($filename) {
76 /* Empty file is a valid file.
77 This is because this function should be called
78 unconditionally at the top of submit action processing
79 and many forms have optional file upload. */
80 if ($filename == 'none' || $filename == '') {
84 /* This should be enough... */
85 if (!is_uploaded_file($filename)) {
88 /* ... but we'd rather be paranoic */
89 if (strstr($filename, '..')) {
92 if (!is_file($filename)) {
95 if (!file_exists($filename)) {
98 if ((dirname($filename) != '/tmp') &&
99 (dirname($filename) != "/var/tmp")) {
106 * util_check_url() - determines if given URL is valid.
108 * Currently, test is very basic, only the protocol is
109 * checked, allowed values are: http, https, ftp.
111 * @param string The URL
112 * @return boolean true if valid, false if not valid.
114 function util_check_url($url) {
115 return (preg_match('/^(http|https|ftp):\/\//', $url) > 0);
119 * util_send_message() - Send email
120 * This function should be used in place of the PHP mail() function
122 * @param string The email recipients address
123 * @param string The email subject
124 * @param string The body of the email message
125 * @param string The optional email sender address. Defaults to 'noreply@'
126 * @param string The addresses to blind-carbon-copy this message
127 * @param string The optional email sender name. Defaults to ''
128 * @param boolean Whether to send plain text or html email
131 function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='',$send_html_email=false) {
135 $to='noreply@'.forge_get_config('web_host');
138 $from='noreply@'.forge_get_config('web_host');
142 $charset = _('UTF-8');
148 if ($extra_headers) {
149 $body2 .= $extra_headers."\n";
152 "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset);
153 if (forge_get_config('bcc_all_emails') != '') {
154 $BCC.=",".forge_get_config('bcc_all_emails');
157 $body2 .= "\nBCC: $BCC";
159 $send_html_email?$type="html":$type="plain";
160 $body2 .= "\n".util_encode_mimeheader("Subject", $subject, $charset).
161 "\nContent-type: text/$type; charset=$charset".
163 util_convert_body($body, $charset);
165 if (!forge_get_config('sendmail_path')){
166 $sys_sendmail_path="/usr/sbin/sendmail";
169 $handle = popen(forge_get_config('sendmail_path')." -f'$from' -t -i", 'w');
170 fwrite ($handle, $body2);
175 * util_encode_mailaddr() - Encode email address to MIME format
177 * @param string The email address
178 * @param string The email's owner name
179 * @param string The converting charset
182 function util_encode_mailaddr($email,$name,$charset) {
183 if (function_exists('mb_convert_encoding') && trim($name) != "") {
184 $name = "=?".$charset."?B?".
185 base64_encode(mb_convert_encoding(
186 $name,$charset,"UTF-8")).
190 return $name." <".$email."> ";
194 * util_encode_mimeheader() - Encode mimeheader
196 * @param string The name of the header (e.g. "Subject")
197 * @param string The email subject
198 * @param string The converting charset (like ISO-2022-JP)
199 * @return string The MIME encoded subject
202 function util_encode_mimeheader($headername,$str,$charset) {
203 if (function_exists('mb_internal_encoding') &&
204 function_exists('mb_encode_mimeheader')) {
205 $x = mb_internal_encoding();
206 mb_internal_encoding("UTF-8");
207 $y = mb_encode_mimeheader($headername . ": " . $str,
209 mb_internal_encoding($x);
213 if (!function_exists('mb_convert_encoding')) {
214 return $headername . ": " . $str;
217 return $headername . ": " . "=?".$charset."?B?".
218 base64_encode(mb_convert_encoding(
219 $str,$charset,"UTF-8")).
224 * util_convert_body() - Convert body of the email message
226 * @param string The body of the email message
227 * @param string The charset of the email message
228 * @return string The converted body of the email message
231 function util_convert_body($str,$charset) {
232 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
236 return mb_convert_encoding($str,$charset,"UTF-8");
239 function util_send_jabber($to,$subject,$body) {
240 if (!forge_get_config('use_jabber')) {
243 $JABBER = new Jabber();
244 if (!$JABBER->Connect()) {
245 echo '<br />Unable to connect';
248 //$JABBER->SendAuth();
249 //$JABBER->AccountRegistration();
250 if (!$JABBER->SendAuth()) {
251 echo '<br />Auth Failure';
252 $JABBER->Disconnect();
254 //or die("Couldn't authenticate!");
256 $JABBER->SendPresence(NULL, NULL, "online");
258 $body=htmlspecialchars($body);
259 $to_arr=explode(',',$to);
260 for ($i=0; $i<count($to_arr); $i++) {
262 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
263 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
264 echo '<br />Error Sending to '.$to_arr[$i];
269 $JABBER->CruiseControl(2);
270 $JABBER->Disconnect();
274 * util_handle_message() - a convenience wrapper which sends messages
275 * to either a jabber account or email account or both, depending on
278 * @param array array of user_id's from the user table
279 * @param string subject of the message
280 * @param string the message body
281 * @param string a comma-separated list of email address
282 * @param string a comma-separated list of jabber address
283 * @param string From header
285 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='',$from='') {
288 if (count($id_arr) < 1) {
291 $res = db_query_params ('SELECT user_id,jabber_address,email,jabber_only FROM users WHERE user_id = ANY ($1)',
292 array (db_int_array_to_any_clause ($id_arr))) ;
293 $rows = db_numrows($res) ;
295 for ($i=0; $i<$rows; $i++) {
296 if (db_result($res, $i, 'user_id') == 100) {
297 // Do not send messages to "Nobody"
301 // Build arrays of the jabber address
303 if (db_result($res,$i,'jabber_address')) {
304 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
305 if (db_result($res,$i,'jabber_only') != 1) {
306 $address['email'][]=db_result($res,$i,'email');
309 $address['email'][]=db_result($res,$i,'email');
312 if (isset ($address['email']) && count($address['email']) > 0) {
313 $extra_emails=implode($address['email'],',').',' . $extra_emails;
315 if (isset ($address['jabber_address']) && count($address['jabber_address']) > 0) {
316 $extra_jabbers=implode($address['jabber_address'],',').','.$extra_jabbers;
320 util_send_message('',$subject,$body,$from,$extra_emails);
322 if ($extra_jabbers) {
323 util_send_jabber($extra_jabbers,$subject,$body);
328 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
329 * This function requires PHP 4.0.3 or greater
331 * @param string The string to unconvert
332 * @returns The unconverted string
335 function util_unconvert_htmlspecialchars($string) {
336 if (strlen($string) < 1) {
339 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
340 $trans = get_html_translation_table(HTML_ENTITIES);
341 $trans = array_flip ($trans);
342 $str = strtr ($string, $trans);
348 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
350 * @param string The result set ID
351 * @param int The column key
352 * @param int The optional column value
353 * @returns An associative array
356 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
357 $rows=db_numrows($result);
361 for ($i=0; $i<$rows; $i++) {
362 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
371 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
373 * @param int The result set ID
374 * @param int The column
378 function &util_result_column_to_array($result, $col=0) {
380 Takes a result set and turns the optional column into
383 $rows=db_numrows($result);
387 for ($i=0; $i<$rows; $i++) {
388 $arr[$i]=db_result($result,$i,$col);
397 * util_wrap_find_space() - Find the first space in a string
399 * @param string The string in which to find the space (must be UTF8!)
400 * @param int The number of characters to wrap - Default is 80
401 * @returns The position of the first space
404 function util_wrap_find_space($string,$wrap) {
411 //find the first space starting at $start
412 $pos=@strpos($string,' ',$start);
414 //if that space is too far over, go back and start more to the left
415 if (($pos > ($wrap+5)) || !$pos) {
417 $start=($wrap-($try*5));
418 //if we've gotten so far left , just truncate the line
421 $code = ord(substr($string,$wrap,1));
424 //Here is single byte character
425 //or head of multi byte character
428 //Do not break multi byte character
443 * util_line_wrap() - Automatically linewrap text
445 * @param string The text to wrap
446 * @param int The number of characters to wrap - Default is 80
447 * @param string The line break to use - Default is '\n'
448 * @returns The wrapped text
451 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
452 $paras = explode("\n", $text);
456 while ($i < count($paras)) {
457 if (strlen($paras[$i]) <= $wrap) {
458 $result[] = $paras[$i];
461 $pos=util_wrap_find_space($paras[$i],$wrap);
463 $result[] = substr($paras[$i], 0, $pos);
465 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
468 $pos=util_wrap_find_space($paras[$i],$wrap);
474 return implode($break, $result);
478 * util_make_links() - Turn URL's into HREF's.
480 * @param string The URL
481 * @returns The HREF'ed URL
484 function util_make_links ($data='') {
488 $lines = split("\n",$data);
490 while ( list ($key,$line) = each ($lines)) {
491 // When we come here, we usually have form input
492 // encoded in entities. Our aim is to NOT include
493 // angle brackets in the URL
494 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
495 $line = str_replace('>', "\1", $line);
496 $line = eregi_replace("([ \t]|^)www\."," http://www.",$line);
497 $text = eregi_replace("([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
498 $text = eregi_replace("([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $text);
499 $text = str_replace("\1", '>', $text);
506 * show_priority_colors_key() - Show the priority colors legend
509 function show_priority_colors_key() {
510 echo '<p /><strong> '._('Priority Colors').':</strong><br />
512 <table border="0"><tr>';
514 for ($i=1; $i<6; $i++) {
516 <td class="priority'.$i.'">'.$i.'</td>';
518 echo '</tr></table>';
522 * utils_buildcheckboxarray() - Build a checkbox array
524 * @param int Number of options to be in the array
525 * @param string The name of the checkboxes
526 * @param array An array of boxes to be pre-checked
529 function utils_buildcheckboxarray($options,$name,$checked_array) {
530 $option_count=count($options);
531 $checked_count=count($checked_array);
533 for ($i=1; $i<=$option_count; $i++) {
535 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
536 for ($j=0; $j<$checked_count; $j++) {
537 if ($i == $checked_array[$j]) {
541 echo '> '.$options[$i];
546 * utils_requiredField() - Adds the required field marker
548 * @return a string holding the HTML to mark a required field
550 function utils_requiredField() {
551 return '<span class="requiredfield">*</span>';
555 * GraphResult() - Takes a database result set and builds a graph.
556 * The first column should be the name, and the second column should be the values
557 * Be sure to include HTL_Graphs.php before using this function
559 * @author Tim Perdue tperdue@valinux.com
560 * @param int The databse result set ID
561 * @param string The title of the graph
564 Function GraphResult($result,$title) {
565 $rows=db_numrows($result);
567 if ((!$result) || ($rows < 1)) {
573 for ($j=0; $j<db_numrows($result); $j++) {
574 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
575 $names[$j]= db_result($result, $j, 0);
576 $values[$j]= db_result($result, $j, 1);
581 This is another function detailed below
583 GraphIt($names,$values,$title);
588 * GraphIt() - Build a graph
590 * @author Tim Perdue tperdue@valinux.com
591 * @param array An array of names
592 * @param array An array of values
593 * @param string The title of the graph
596 Function GraphIt($name_string,$value_string,$title) {
599 $counter=count($name_string);
602 Can choose any color you wish
606 for ($i = 0; $i < $counter; $i++) {
607 $bars[$i]=$HTML->COLOR_LTBACK1;
610 $counter=count($value_string);
613 Figure the max_value passed in, so scale can be determined
618 for ($i = 0; $i < $counter; $i++) {
619 if ($value_string[$i] > $max_value) {
620 $max_value=$value_string[$i];
624 if ($max_value < 1) {
629 I want my graphs all to be 800 pixels wide, so that is my divisor
632 $scale=(400/$max_value);
635 I create a wrapper table around the graph that holds the title
641 echo $GLOBALS['HTML']->listTableTop ($title_arr);
644 Create an associate array to pass in. I leave most of it blank
673 This is the actual call to the HTML_Graphs class
676 html_graph($name_string,$value_string,$bars,$vals);
680 <!-- end outer graph table -->';
681 echo $GLOBALS['HTML']->listTableBottom();
685 * ShowResultSet() - Show a generic result set
686 * Very simple, plain way to show a generic result set
688 * @param int The result set ID
689 * @param string The title of the result set
690 * @param bool The option to turn URL's into links
691 * @param bool The option to display headers
692 * @param array The db field name -> label mapping
693 * @param array Don't display these cols
696 function ShowResultSet($result,$title='',$linkify=false,$displayHeaders=true,$headerMapping=array(), $excludedCols=array()) {
697 global $group_id,$HTML;
700 $rows = db_numrows($result);
701 $cols = db_numfields($result);
703 echo '<table border="0" width="100%">';
705 /* Create the headers */
706 $headersCellData = array();
707 $colsToKeep = array();
708 for ($i=0; $i < $cols; $i++) {
709 $fieldName = db_fieldname($result, $i);
710 if(in_array($fieldName, $excludedCols)) {
714 if(isset($headerMapping[$fieldName])) {
715 if(is_array($headerMapping[$fieldName])) {
716 $headersCellData[] = $headerMapping[$fieldName];
718 $headersCellData[] = array($headerMapping[$fieldName]);
722 $headersCellData[] = array($fieldName);
726 /* Create the title */
727 if(strlen($title) > 0) {
728 $titleCellData = array();
729 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
730 echo $HTML->multiTableRow('', $titleCellData, TRUE);
733 /* Display the headers */
734 if($displayHeaders) {
735 echo $HTML->multiTableRow('', $headersCellData, TRUE);
738 /* Create the rows */
739 for ($j = 0; $j < $rows; $j++) {
740 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
741 for ($i = 0; $i < $cols; $i++) {
742 if(in_array($i, $colsToKeep)) {
743 if ($linkify && $i == 0) {
744 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
746 if ($linkify == "bug_cat") {
747 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
748 } else if($linkify == "bug_group") {
749 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
750 } else if($linkify == "patch_cat") {
751 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
752 } else if($linkify == "support_cat") {
753 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
754 } else if($linkify == "pm_project") {
755 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
757 $link = $linkend = '';
760 $link = $linkend = '';
762 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
774 * validate_email() - Validate an email address
776 * @param string The address string to validate
777 * @returns true on success/false on error
780 function validate_email ($address) {
781 return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address) !== false);
785 * validate_emails() - Validate a list of e-mail addresses
787 * @param string E-mail list
788 * @param char Separator
789 * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
791 function validate_emails ($addresses, $separator=',') {
792 if (strlen($addresses) == 0) return array();
794 $emails = explode($separator, $addresses);
797 if (is_array($emails)) {
798 foreach ($emails as $email) {
799 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
800 if (!validate_email($email)) $ret[] = $email;
809 * util_is_valid_filename() - Verifies whether a file has a valid filename
811 * @param string The file to verify
812 * @returns true on success/false on error
815 function util_is_valid_filename ($file) {
817 $invalidchars = eregi_replace("[-A-Z0-9+_\. ~]","",$file);
819 if (!empty($invalidchars)) {
822 if (strstr($file,'..')) {
831 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
833 * @param string The optional hostname string
834 * @returns true on success/false on failur
837 function valid_hostname ($hostname = "xyz") {
840 $invalidchars = eregi_replace("[-A-Z0-9\.]","",$hostname);
842 if (!empty($invalidchars)) {
846 //double dot, starts with a . or -
847 if (ereg("\.\.",$hostname) || ereg("^\.",$hostname) || ereg("^\-",$hostname)) {
851 $multipoint = explode(".",$hostname);
853 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
863 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
865 * Format file size in a human-readable way
866 * such as "xx Megabytes" or "xx Mo"
868 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
870 * @param int bytes is the size
871 * @param bool base10 enable base 10 representation, otherwise
872 * default base 2 is used
873 * @param int round number of fractional digits
874 * @param array labels strings associated to each 2^10 or
875 * 10^3(base10==true) multiple of base units
877 function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array(' bytes', ' KB', ' MB', ' GB')) {
878 if ($bytes <= 0 || !is_array($labels) || (count($labels) <= 0)) {
881 $step = $base10 ? 3 : 10;
882 $base = $base10 ? 10 : 2;
883 $log = (int)(log10($bytes)/log10($base));
885 foreach ($labels as $p=>$lab) {
890 if ($lab == " MB" or $lab == " GB") {
893 $text = round($bytes/pow($base,$pow),$round).$lab;
900 * ls - lists a specified directory and returns an array of files
901 * @param string the path of the directory to list
902 * @param boolean whether to filter out directories and illegal filenames
903 * @return array array of file names.
905 function &ls($dir,$filter=false) {
906 if (!is_dir ($dir)) {
910 exec('ls -c1 '.$dir,$out);
912 for ($i=0; $i<count($out); $i++) {
913 if (util_is_valid_filename($out[$i]) && is_file($dir.'/'.$out[$i])) {
914 $filtered[]=$out[$i];
924 * readfile_chunked() - replacement for readfile
926 * @param string The file path
927 * @param bool Whether to return bytes served or just a bool
930 function readfile_chunked($filename, $returnBytes=true) {
931 $chunksize = 1*(1024*1024); // 1MB chunks
935 $handle = fopen($filename, 'rb');
936 if ($handle === false) {
941 while (!feof($handle)) {
942 $buffer = fread($handle, $chunksize);
947 $byteCounter += strlen($buffer);
951 $status = fclose($handle);
952 if ($returnBytes && $status) {
953 return $byteCounter; // return num. bytes delivered like readfile() does.
959 * util_is_root_dir() - Checks if a directory points to the root dir
960 * @param string Directory
963 function util_is_root_dir($dir) {
964 return !preg_match('/[^\\/]/',$dir);
968 * Constructs the forge's URL prefix out of forge_get_config('url_prefix')
972 function normalized_urlprefix () {
973 $prefix = forge_get_config('url_prefix') ;
974 $prefix = ereg_replace ("^/", "", $prefix) ;
975 $prefix = ereg_replace ("/$", "", $prefix) ;
976 $prefix = "/$prefix/" ;
983 * Construct full URL from a relative path
985 * @param string $path
988 function util_make_url ($path) {
989 if (forge_get_config('use_ssl'))
994 $url .= forge_get_config('web_host') ;
995 $url .= util_make_uri ($path) ;
1000 * Construct proper (relative) URI (prepending prefix)
1002 * @param string $path
1003 * @return string URI
1005 function util_make_uri ($path) {
1006 $path = ereg_replace ("^/", "", $path) ;
1007 $uri = normalized_urlprefix () ;
1012 function util_make_link ($path, $text, $extra_params=false, $absolute=false) {
1014 if (is_array($extra_params)) {
1015 foreach ($extra_params as $key => $value) {
1016 $ep .= "$key=\"$value\" ";
1020 return '<a ' . $ep . 'href="' . $path . '">' . $text . '</a>' ;
1022 return '<a ' . $ep . 'href="' . util_make_url ($path) . '">' . $text . '</a>' ;
1027 * Create an HTML link to a user's profile page
1029 * @param string $username
1030 * @param int $user_id
1031 * @param string $text
1034 function util_make_link_u ($username, $user_id,$text) {
1035 return '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>' ;
1039 * Create URL for user's profile page
1041 * @param string $username
1042 * @param int $user_id
1043 * @return string URL
1045 function util_make_url_u ($username, $user_id) {
1046 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1047 return util_make_url ("/developer/?user_id=$user_id");
1049 return util_make_url ("/users/$username/");
1054 * Create a HTML link to a project's page
1055 * @param string $groupame
1056 * @param int $group_id
1057 * @param string $text
1060 function util_make_link_g ($groupame, $group_id,$text) {
1061 return '<a href="' . util_make_url_g ($groupame, $group_id) . '">' . $text . '</a>' ;
1065 * Create URL for a project's page
1067 * @param string $groupame
1068 * @param int $group_id
1071 function util_make_url_g ($groupame, $group_id) {
1072 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1073 return util_make_url ("/project/?group_id=$group_id");
1075 return util_make_url ("/projects/$groupame/");
1079 function util_ensure_value_in_set ($value, $set) {
1080 if (in_array ($value, $set)) {
1087 function check_email_available($group, $email, &$response) {
1088 // Check if a mailing list with same name already exists
1089 $mlFactory = new MailingListFactory($group);
1090 if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
1091 $response .= $mlFactory->getErrorMessage();
1094 $mlArray =& $mlFactory->getMailingLists();
1095 if ($mlFactory->isError()) {
1096 $response .= $mlFactory->getErrorMessage();
1099 for ($j = 0; $j < count($mlArray); $j++) {
1100 $currentList =& $mlArray[$j];
1101 if ($email == $currentList->getName()) {
1102 $response .= _('Error: a mailing list with the same email address already exists.');
1107 // Check if a forum with same name already exists
1108 $ff = new ForumFactory($group);
1109 if (!$ff || !is_object($ff) || $ff->isError()) {
1110 $response .= $ff->getErrorMessage();
1113 $farr =& $ff->getForums();
1114 $prefix = $group->getUnixName() . '-';
1115 for ($j = 0; $j < count($farr); $j++) {
1116 if (is_object($farr[$j])) {
1117 if ($email == $prefix . $farr[$j]->getName()) {
1118 $response .= _('Error: a forum with the same email address already exists.');
1124 // Email is available
1128 // array_replace_recursive only appeared in PHP 5.3.0
1129 if (!function_exists('array_replace_recursive')) {
1130 function array_replace_recursive ($a1, $a2) {
1133 if (!is_array ($a2)) {
1137 foreach ($a2 as $k => $v) {
1138 if (!is_array ($v) ||
1139 !isset ($result[$k]) || !is_array ($result[$k])) {
1143 $result[$k] = array_replace_recursive ($result[$k],
1151 // json_encode only appeared in PHP 5.2.0
1152 if (!function_exists('json_encode')) {
1153 require_once $gfcommon.'include/minijson.php' ;
1154 function json_encode ($a1) {
1155 return minijson_encode ($a1) ;
1159 /* returns an integer from http://forge/foo/bar.php/123 or false */
1160 function util_path_info_last_numeric_component() {
1161 if (!isset($_SERVER['PATH_INFO']))
1165 foreach (str_split($_SERVER['PATH_INFO']) as $x) {
1169 } else if ($ok == false) {
1170 ; /* need reset using slash */
1171 } else if ((ord($x) >= 48) && (ord($x) <= 57)) {
1172 $rv = $rv * 10 + ord($x) - 48;
1184 // c-file-style: "bsd"