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;
93 function util_strip_unprintable(&$data) {
94 if (is_array($data)) {
95 foreach ($data as $key => &$value) {
96 util_strip_unprintable($value);
100 $data = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $data);
106 * removeCRLF() - remove any Carriage Return-Line Feed from a string.
107 * That function is useful to remove the possibility of a CRLF Injection when sending mail
108 * All the data that we will send should be passed through that function
110 * @param string The string that we want to empty from any CRLF
112 function util_remove_CRLF($str) {
113 return strtr($str, "\015\012", ' ');
118 * util_check_fileupload() - determines if a filename is appropriate for upload
120 * @param array The uploaded file as returned by getUploadedFile()
122 function util_check_fileupload($filename) {
124 /* Empty file is a valid file.
125 This is because this function should be called
126 unconditionally at the top of submit action processing
127 and many forms have optional file upload. */
128 if ($filename == 'none' || $filename == '') {
132 /* This should be enough... */
133 if (!is_uploaded_file($filename)) {
136 /* ... but we'd rather be paranoic */
137 if (strstr($filename, '..')) {
140 if (!is_file($filename)) {
143 if (!file_exists($filename)) {
146 if ((dirname($filename) != '/tmp') &&
147 (dirname($filename) != "/var/tmp")) {
154 * util_check_url() - determines if given URL is valid.
156 * Currently, test is very basic, only the protocol is
157 * checked, allowed values are: http, https, ftp.
159 * @param string The URL
160 * @return boolean true if valid, false if not valid.
162 function util_check_url($url) {
163 return (preg_match('/^(http|https|ftp):\/\//', $url) > 0);
167 * util_send_message() - Send email
168 * This function should be used in place of the PHP mail() function
170 * @param string The email recipients address
171 * @param string The email subject
172 * @param string The body of the email message
173 * @param string The optional email sender address. Defaults to 'noreply@'
174 * @param string The addresses to blind-carbon-copy this message
175 * @param string The optional email sender name. Defaults to ''
176 * @param boolean Whether to send plain text or html email
179 function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='',$send_html_email=false) {
183 $to='noreply@'.forge_get_config('web_host');
186 $from='noreply@'.forge_get_config('web_host');
190 $charset = _('UTF-8');
196 if ($extra_headers) {
197 $body2 .= $extra_headers."\n";
200 "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset);
201 if (forge_get_config('bcc_all_emails') != '') {
202 $BCC.=",".forge_get_config('bcc_all_emails');
205 $body2 .= "\nBCC: $BCC";
207 $send_html_email?$type="html":$type="plain";
208 $body2 .= "\n".util_encode_mimeheader("Subject", $subject, $charset).
209 "\nContent-type: text/$type; charset=$charset".
211 util_convert_body($body, $charset);
213 if (!forge_get_config('sendmail_path')){
214 $sys_sendmail_path="/usr/sbin/sendmail";
217 $handle = popen(forge_get_config('sendmail_path')." -f'$from' -t -i", 'w');
218 fwrite ($handle, $body2);
223 * util_encode_mailaddr() - Encode email address to MIME format
225 * @param string The email address
226 * @param string The email's owner name
227 * @param string The converting charset
230 function util_encode_mailaddr($email,$name,$charset) {
231 if (function_exists('mb_convert_encoding') && trim($name) != "") {
232 $name = "=?".$charset."?B?".
233 base64_encode(mb_convert_encoding(
234 $name,$charset,"UTF-8")).
238 return $name." <".$email."> ";
242 * util_encode_mimeheader() - Encode mimeheader
244 * @param string The name of the header (e.g. "Subject")
245 * @param string The email subject
246 * @param string The converting charset (like ISO-2022-JP)
247 * @return string The MIME encoded subject
250 function util_encode_mimeheader($headername,$str,$charset) {
251 if (function_exists('mb_internal_encoding') &&
252 function_exists('mb_encode_mimeheader')) {
253 $x = mb_internal_encoding();
254 mb_internal_encoding("UTF-8");
255 $y = mb_encode_mimeheader($headername . ": " . $str,
257 mb_internal_encoding($x);
261 if (!function_exists('mb_convert_encoding')) {
262 return $headername . ": " . $str;
265 return $headername . ": " . "=?".$charset."?B?".
266 base64_encode(mb_convert_encoding(
267 $str,$charset,"UTF-8")).
272 * util_convert_body() - Convert body of the email message
274 * @param string The body of the email message
275 * @param string The charset of the email message
276 * @return string The converted body of the email message
279 function util_convert_body($str,$charset) {
280 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
284 return mb_convert_encoding($str,$charset,"UTF-8");
287 function util_send_jabber($to,$subject,$body) {
288 if (!forge_get_config('use_jabber')) {
291 $JABBER = new Jabber();
292 if (!$JABBER->Connect()) {
293 echo '<br />Unable to connect';
296 //$JABBER->SendAuth();
297 //$JABBER->AccountRegistration();
298 if (!$JABBER->SendAuth()) {
299 echo '<br />Auth Failure';
300 $JABBER->Disconnect();
302 //or die("Couldn't authenticate!");
304 $JABBER->SendPresence(NULL, NULL, "online");
306 $body=htmlspecialchars($body);
307 $to_arr=explode(',',$to);
308 for ($i=0; $i<count($to_arr); $i++) {
310 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
311 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
312 echo '<br />Error Sending to '.$to_arr[$i];
317 $JABBER->CruiseControl(2);
318 $JABBER->Disconnect();
322 * util_handle_message() - a convenience wrapper which sends messages
323 * to either a jabber account or email account or both, depending on
326 * @param array array of user_id's from the user table
327 * @param string subject of the message
328 * @param string the message body
329 * @param string a comma-separated list of email address
330 * @param string a comma-separated list of jabber address
331 * @param string From header
333 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='',$from='') {
336 if (count($id_arr) < 1) {
339 $res = db_query_params ('SELECT user_id,jabber_address,email,jabber_only FROM users WHERE user_id = ANY ($1)',
340 array (db_int_array_to_any_clause ($id_arr))) ;
341 $rows = db_numrows($res) ;
343 for ($i=0; $i<$rows; $i++) {
344 if (db_result($res, $i, 'user_id') == 100) {
345 // Do not send messages to "Nobody"
349 // Build arrays of the jabber address
351 if (db_result($res,$i,'jabber_address')) {
352 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
353 if (db_result($res,$i,'jabber_only') != 1) {
354 $address['email'][]=db_result($res,$i,'email');
357 $address['email'][]=db_result($res,$i,'email');
360 if (isset ($address['email']) && count($address['email']) > 0) {
361 $extra_emails=implode($address['email'],',').',' . $extra_emails;
363 if (isset ($address['jabber_address']) && count($address['jabber_address']) > 0) {
364 $extra_jabbers=implode($address['jabber_address'],',').','.$extra_jabbers;
368 util_send_message('',$subject,$body,$from,$extra_emails);
370 if ($extra_jabbers) {
371 util_send_jabber($extra_jabbers,$subject,$body);
376 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
378 * @param string The string to unconvert
379 * @returns The unconverted string
382 function util_unconvert_htmlspecialchars($string) {
383 if (strlen($string) < 1) {
386 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
387 $trans = get_html_translation_table(HTML_ENTITIES);
388 $trans = array_flip ($trans);
389 $str = strtr ($string, $trans);
395 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
397 * @param string The result set ID
398 * @param int The column key
399 * @param int The optional column value
400 * @returns An associative array
403 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
404 $rows=db_numrows($result);
408 for ($i=0; $i<$rows; $i++) {
409 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
418 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
420 * @param int The result set ID
421 * @param int The column
425 function &util_result_column_to_array($result, $col=0) {
427 Takes a result set and turns the optional column into
430 $rows=db_numrows($result);
434 for ($i=0; $i<$rows; $i++) {
435 $arr[$i]=db_result($result,$i,$col);
444 * util_wrap_find_space() - Find the first space in a string
446 * @param string The string in which to find the space (must be UTF8!)
447 * @param int The number of characters to wrap - Default is 80
448 * @returns The position of the first space
451 function util_wrap_find_space($string,$wrap) {
458 //find the first space starting at $start
459 $pos=@strpos($string,' ',$start);
461 //if that space is too far over, go back and start more to the left
462 if (($pos > ($wrap+5)) || !$pos) {
464 $start=($wrap-($try*5));
465 //if we've gotten so far left , just truncate the line
468 $code = ord(substr($string,$wrap,1));
471 //Here is single byte character
472 //or head of multi byte character
475 //Do not break multi byte character
490 * util_line_wrap() - Automatically linewrap text
492 * @param string The text to wrap
493 * @param int The number of characters to wrap - Default is 80
494 * @param string The line break to use - Default is '\n'
495 * @returns The wrapped text
498 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
499 $paras = explode("\n", $text);
503 while ($i < count($paras)) {
504 if (strlen($paras[$i]) <= $wrap) {
505 $result[] = $paras[$i];
508 $pos=util_wrap_find_space($paras[$i],$wrap);
510 $result[] = substr($paras[$i], 0, $pos);
512 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
515 $pos=util_wrap_find_space($paras[$i],$wrap);
521 return implode($break, $result);
525 * util_make_links() - Turn URL's into HREF's.
527 * @param string The URL
528 * @returns The HREF'ed URL
531 function util_make_links($data='') {
535 $lines = explode("\n", $data);
537 while ( list ($key, $line) = each ($lines)) {
538 // When we come here, we usually have form input
539 // encoded in entities. Our aim is to NOT include
540 // angle brackets in the URL
541 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
542 $line = str_replace('>', "\1", $line);
543 $line = preg_replace( "/([ \t]|^)www\./i", " http://www.", $line);
544 $text = preg_replace( "/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
545 "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
546 $text = preg_replace(
547 "/([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))/i",
548 "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>",
551 $text = str_replace("\1", '>', $text);
558 * show_priority_colors_key() - Show the priority colors legend
561 function show_priority_colors_key() {
562 echo '<p /><strong> '._('Priority Colors').':</strong><br />
566 for ($i=1; $i<6; $i++) {
568 <td class="priority'.$i.'">'.$i.'</td>';
570 echo '</tr></table>';
574 * utils_buildcheckboxarray() - Build a checkbox array
576 * @param int Number of options to be in the array
577 * @param string The name of the checkboxes
578 * @param array An array of boxes to be pre-checked
581 function utils_buildcheckboxarray($options, $name, $checked_array) {
582 $option_count = count($options);
583 $checked_count = count($checked_array);
585 for ($i = 1; $i <= $option_count; $i++) {
587 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
588 for ($j=0; $j < $checked_count; $j++) {
589 if ($i == $checked_array[$j]) {
593 echo '> '.$options[$i];
598 * utils_requiredField() - Adds the required field marker
600 * @return a string holding the HTML to mark a required field
602 function utils_requiredField() {
603 return '<span class="requiredfield">*</span>';
607 * GraphResult() - Takes a database result set and builds a graph.
608 * The first column should be the name, and the second column should be the values
609 * Be sure to include HTL_Graphs.php before using this function
611 * @author Tim Perdue tperdue@valinux.com
612 * @param int The databse result set ID
613 * @param string The title of the graph
616 function GraphResult($result, $title) {
617 $rows = db_numrows($result);
619 if ((!$result) || ($rows < 1)) {
625 for ($j=0; $j < db_numrows($result); $j++) {
626 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
627 $names[$j] = db_result($result, $j, 0);
628 $values[$j] = db_result($result, $j, 1);
633 This is another function detailed below
635 GraphIt($names, $values, $title);
640 * GraphIt() - Build a graph
642 * @author Tim Perdue tperdue@valinux.com
643 * @param array An array of names
644 * @param array An array of values
645 * @param string The title of the graph
648 function GraphIt($name_string, $value_string, $title) {
651 $counter = count($name_string);
654 Can choose any color you wish
658 for ($i = 0; $i < $counter; $i++) {
659 $bars[$i] = $HTML->COLOR_LTBACK1;
662 $counter = count($value_string);
665 Figure the max_value passed in, so scale can be determined
670 for ($i = 0; $i < $counter; $i++) {
671 if ($value_string[$i] > $max_value) {
672 $max_value = $value_string[$i];
676 if ($max_value < 1) {
681 I want my graphs all to be 800 pixels wide, so that is my divisor
684 $scale = (400/$max_value);
687 I create a wrapper table around the graph that holds the title
690 $title_arr = array();
691 $title_arr[] = $title;
693 echo $GLOBALS['HTML']->listTableTop ($title_arr);
696 Create an associate array to pass in. I leave most of it blank
725 This is the actual call to the HTML_Graphs class
728 html_graph($name_string, $value_string, $bars, $vals);
732 <!-- end outer graph table -->';
733 echo $GLOBALS['HTML']->listTableBottom();
737 * ShowResultSet() - Show a generic result set
738 * Very simple, plain way to show a generic result set
740 * @param int The result set ID
741 * @param string The title of the result set
742 * @param bool The option to turn URL's into links
743 * @param bool The option to display headers
744 * @param array The db field name -> label mapping
745 * @param array Don't display these cols
748 function ShowResultSet($result,$title='',$linkify=false,$displayHeaders=true,$headerMapping=array(), $excludedCols=array()) {
749 global $group_id,$HTML;
752 $rows = db_numrows($result);
753 $cols = db_numfields($result);
755 echo '<table width="100%">';
757 /* Create the headers */
758 $headersCellData = array();
759 $colsToKeep = array();
760 for ($i=0; $i < $cols; $i++) {
761 $fieldName = db_fieldname($result, $i);
762 if(in_array($fieldName, $excludedCols)) {
766 if(isset($headerMapping[$fieldName])) {
767 if(is_array($headerMapping[$fieldName])) {
768 $headersCellData[] = $headerMapping[$fieldName];
770 $headersCellData[] = array($headerMapping[$fieldName]);
774 $headersCellData[] = array($fieldName);
778 /* Create the title */
779 if(strlen($title) > 0) {
780 $titleCellData = array();
781 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
782 echo $HTML->multiTableRow('', $titleCellData, TRUE);
785 /* Display the headers */
786 if($displayHeaders) {
787 echo $HTML->multiTableRow('', $headersCellData, TRUE);
790 /* Create the rows */
791 for ($j = 0; $j < $rows; $j++) {
792 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
793 for ($i = 0; $i < $cols; $i++) {
794 if(in_array($i, $colsToKeep)) {
795 if ($linkify && $i == 0) {
796 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
798 if ($linkify == "bug_cat") {
799 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
800 } else if($linkify == "bug_group") {
801 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
802 } else if($linkify == "patch_cat") {
803 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
804 } else if($linkify == "support_cat") {
805 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
806 } else if($linkify == "pm_project") {
807 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
809 $link = $linkend = '';
812 $link = $linkend = '';
814 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
826 * validate_email() - Validate an email address
828 * @param string The address string to validate
829 * @returns true on success/false on error
832 function validate_email ($address) {
833 if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
834 if ( filter_var($address, FILTER_VALIDATE_EMAIL) ) {
842 if ( preg_match( "/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+$/", $address) ) {
851 * validate_emails() - Validate a list of e-mail addresses
853 * @param string E-mail list
854 * @param char Separator
855 * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
857 function validate_emails($addresses, $separator=',') {
858 if (strlen($addresses) == 0) return array();
860 $emails = explode($separator, $addresses);
863 if (is_array($emails)) {
864 foreach ($emails as $email) {
865 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
866 if (!validate_email($email)) $ret[] = $email;
875 * util_is_valid_filename() - Verifies whether a file has a valid filename
877 * @param string The file to verify
878 * @returns true on success/false on error
881 function util_is_valid_filename($file) {
883 $invalidchars = preg_replace("/[-A-Z0-9+_\. ~]/i","",$file);
885 if (!empty($invalidchars)) {
888 if (strstr($file,'..')) {
897 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
899 * @param string The optional hostname string
900 * @returns true on success/false on failur
903 function valid_hostname($hostname = "xyz") {
906 $invalidchars = preg_replace("/[-A-Z0-9\.]/i","",$hostname);
908 if (!empty($invalidchars)) {
912 //double dot, starts with a . or -
913 if ( preg_match("/\.\./",$hostname) || preg_match("/^\./",$hostname) || preg_match("/^\-/",$hostname) ) {
917 $multipoint = explode(".",$hostname);
919 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
929 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
931 * Format file size in a human-readable way
932 * such as "xx Megabytes" or "xx Mo"
934 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
936 * @param int bytes is the size
937 * @param bool base10 enable base 10 representation, otherwise
938 * default base 2 is used
939 * @param int round number of fractional digits
940 * @param array labels strings associated to each 2^10 or
941 * 10^3(base10==true) multiple of base units
943 function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array()) {
948 return "-" . human_readable_bytes(-$bytes, $base10, $round);
951 $labels = array(_('bytes'), _('kB'), _('MB'), _('GB'), _('TB'));
955 $labels = array(_('bytes'), _('KiB'), _('MiB'), _('GiB'), _('TiB'));
959 $log = (int)(log10($bytes)/log10($base));
961 foreach ($labels as $p=>$lab) {
966 if ($lab != _("bytes") and $lab != _("kB") and $lab != _("KiB")) {
969 $text = round($bytes/pow($base,$pow),$round) . " " . $lab;
976 * ls - lists a specified directory and returns an array of files
977 * @param string the path of the directory to list
978 * @param boolean whether to filter out directories and illegal filenames
979 * @return array array of file names.
981 function &ls($dir,$filter=false) {
984 if (is_dir($dir) && ($h = opendir($dir))) {
985 while (($f = readdir($h)) !== false) {
989 if (!util_is_valid_filename($f) ||
990 !is_file($dir . "/" . $f))
1001 * readfile_chunked() - replacement for readfile
1003 * @param string The file path
1004 * @param bool Whether to return bytes served or just a bool
1007 function readfile_chunked($filename, $returnBytes=true) {
1008 $chunksize = 1*(1024*1024); // 1MB chunks
1012 $handle = fopen($filename, 'rb');
1013 if ($handle === false) {
1018 while (!feof($handle)) {
1019 $buffer = fread($handle, $chunksize);
1024 $byteCounter += strlen($buffer);
1028 $status = fclose($handle);
1029 if ($returnBytes && $status) {
1030 return $byteCounter; // return num. bytes delivered like readfile() does.
1036 * util_is_root_dir() - Checks if a directory points to the root dir
1037 * @param string Directory
1040 function util_is_root_dir($dir) {
1041 return !preg_match('/[^\\/]/',$dir);
1045 * util_is_dot_or_dotdot() - Checks if a directory points to . or ..
1046 * @param string Directory
1049 function util_is_dot_or_dotdot($dir) {
1050 return preg_match('/^\.\.?$/',trim($dir, '/'));
1054 * util_containts_dot_or_dotdot() - Checks if a directory containts . or ..
1055 * @param string Directory
1058 function util_containts_dot_or_dotdot($dir) {
1059 foreach (explode('/', $dir) as $sub_dir) {
1060 if (util_is_dot_or_dotdot($sub_dir))
1068 * util_secure_filename() - Returns a secured file name
1069 * @param string Filename
1070 * @return string Filename
1072 function util_secure_filename($file) {
1073 $f = preg_replace("/[^-A-Z0-9_\.]/i", '', $file);
1074 if (util_containts_dot_or_dotdot($f))
1075 $f = preg_replace("/\./", '_', $f);
1082 * util_strip_accents() - Remove accents from given text.
1083 * @param string Text
1086 function util_strip_accents($text) {
1087 return iconv ('UTF-8', 'US-ASCII//TRANSLIT', $text) ;
1091 * Constructs the forge's URL prefix out of forge_get_config('url_prefix')
1095 function normalized_urlprefix() {
1096 $prefix = forge_get_config('url_prefix') ;
1097 $prefix = preg_replace ("/^\//", "", $prefix) ;
1098 $prefix = preg_replace ("/\/$/", "", $prefix) ;
1099 $prefix = "/$prefix/" ;
1100 if ($prefix == '//')
1106 * Construct the base URL http[s]://forge_name[:port]
1108 * @return string base URL
1110 function util_make_base_url() {
1111 if (forge_get_config('use_ssl')) {
1116 $url .= forge_get_config('web_host') ;
1117 if (forge_get_config('https_port') && (forge_get_config('https_port') != 443)) {
1118 $url .= ":".forge_get_config('https_port') ;
1123 * Construct full URL from a relative path
1125 * @param string $path
1126 * @return string URL
1128 function util_make_url($path = '') {
1129 $url = util_make_base_url().util_make_uri($path) ;
1134 * Find the relative URL from full URL, removing http[s]://forge_name[:port]
1138 function util_find_relative_referer($url) {
1139 $relative_url = str_replace(util_make_base_url(), '', $url);
1140 //now remove previous feedback, error_msg or warning_msg
1141 $relative_url = preg_replace('/&error_msg=.*&/', '&', $relative_url);
1142 $relative_url = preg_replace('/&warning_msg=.*&/', '&', $relative_url);
1143 $relative_url = preg_replace('/&feedback=.*&/', '&', $relative_url);
1144 $relative_url = preg_replace('/&error_msg=.*/', '', $relative_url);
1145 $relative_url = preg_replace('/&warning_msg=.*/', '', $relative_url);
1146 $relative_url = preg_replace('/&feedback=.*/', '', $relative_url);
1147 return $relative_url;
1151 * Construct proper (relative) URI (prepending prefix)
1153 * @param string $path
1154 * @return string URI
1156 function util_make_uri($path) {
1157 $path = preg_replace('/^\//', '', $path);
1158 $uri = normalized_urlprefix();
1163 function util_make_link($path, $text, $extra_params = false, $absolute = false) {
1164 global $use_tooltips;
1166 if (is_array($extra_params)) {
1167 foreach ($extra_params as $key => $value) {
1168 if ($key != 'title') {
1169 $ep .= "$key=\"$value\" ";
1171 if ($key == 'title' && $use_tooltips) {
1172 $ep .= "$key=\"$value\" ";
1177 return '<a ' . $ep . 'href="' . $path . '">' . $text . '</a>' ;
1179 return '<a ' . $ep . 'href="' . util_make_uri($path) . '">' . $text . '</a>' ;
1184 * Create an HTML link to a user's profile page
1186 * @param string $username
1187 * @param int $user_id
1188 * @param string $text
1191 function util_make_link_u ($username, $user_id,$text) {
1192 return '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>' ;
1196 * Display username with link to a user's profile page
1197 * and icon face if possible.
1199 * @param string $username
1200 * @param int $user_id
1201 * @param string $text
1202 * @param string $size
1205 function util_display_user($username, $user_id, $text, $size='xs') {
1206 // Invoke user_link_with_tooltip plugin
1207 $hook_params = array('resource_type' => 'user', 'username' => $username, 'user_id' => $user_id, 'size' => $size, 'user_link' => '');
1208 plugin_hook_by_reference('user_link_with_tooltip', $hook_params);
1209 if($hook_params['user_link'] != ''){
1210 return $hook_params['user_link'];
1213 // If no plugin replaced it, then back to default standard link
1215 // Invoke user_logo plugin (see gravatar plugin for instance)
1216 $params = array('user_id' => $user_id, 'size' => $size, 'content' => '');
1217 plugin_hook_by_reference('user_logo', $params);
1219 $url = '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>';
1220 if ($params['content']) {
1221 return $params['content'].$url.'<div class="new_line"></div>';
1227 * Create URL for user's profile page
1229 * @param string $username
1230 * @param int $user_id
1231 * @return string URL
1233 function util_make_url_u ($username, $user_id) {
1234 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1235 return util_make_url ("/developer/?user_id=$user_id");
1237 return util_make_url ("/users/$username/");
1242 * Create a HTML link to a project's page
1243 * @param string $groupame
1244 * @param int $group_id
1245 * @param string $text
1248 function util_make_link_g ($groupname, $group_id,$text) {
1249 $hook_params =array();
1250 $hook_params['resource_type'] = 'group';
1251 $hook_params['group_name'] = $groupname;
1252 $hook_params['group_id'] = $group_id;
1253 $hook_params['link_text'] = $text;
1254 $hook_params['group_link'] = '';
1255 plugin_hook_by_reference('project_link_with_tooltip', $hook_params);
1256 if($hook_params['group_link'] != '') {
1257 return $hook_params['group_link'];
1260 return '<a href="' . util_make_url_g ($groupname, $group_id) . '">' . $text . '</a>' ;
1264 * Create URL for a project's page
1266 * @param string $groupame
1267 * @param int $group_id
1270 function util_make_url_g ($groupame, $group_id) {
1271 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1272 return util_make_url ("/project/?group_id=$group_id");
1274 return util_make_url ("/projects/$groupame/");
1278 function util_ensure_value_in_set ($value, $set) {
1279 if (in_array ($value, $set)) {
1286 function check_email_available($group, $email, &$response) {
1287 // Check if a mailing list with same name already exists
1288 $mlFactory = new MailingListFactory($group);
1289 if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
1290 $response .= $mlFactory->getErrorMessage();
1293 $mlArray = $mlFactory->getMailingLists();
1294 if ($mlFactory->isError()) {
1295 $response .= $mlFactory->getErrorMessage();
1298 for ($j = 0; $j < count($mlArray); $j++) {
1299 $currentList =& $mlArray[$j];
1300 if ($email == $currentList->getName()) {
1301 $response .= _('Error: a mailing list with the same email address already exists.');
1306 // Check if a forum with same name already exists
1307 $ff = new ForumFactory($group);
1308 if (!$ff || !is_object($ff) || $ff->isError()) {
1309 $response .= $ff->getErrorMessage();
1312 $farr = $ff->getForums();
1313 $prefix = $group->getUnixName() . '-';
1314 for ($j = 0; $j < count($farr); $j++) {
1315 if (is_object($farr[$j])) {
1316 if ($email == $prefix . $farr[$j]->getName()) {
1317 $response .= _('Error: a forum with the same email address already exists.');
1323 // Email is available
1328 * Adds the Javascript file to the lits to be used
1329 * @param unknown_type $js
1331 function use_javascript($js) {
1332 return $GLOBALS['HTML']->addJavascript($js);
1335 function use_stylesheet($css, $media='') {
1336 return $GLOBALS['HTML']->addStylesheet($css, $media);
1339 // array_replace_recursive only appeared in PHP 5.3.0
1340 if (!function_exists('array_replace_recursive')) {
1342 * Replaces elements from passed arrays into the first array recursively
1343 * @param array $a1 The array in which elements are replaced.
1344 * @param array $a2 The array from which elements will be extracted.
1345 * @return Returns an array, or NULL if an error occurs.
1347 function array_replace_recursive ($a1, $a2) {
1350 if (!is_array ($a2)) {
1354 foreach ($a2 as $k => $v) {
1355 if (!is_array ($v) ||
1356 !isset ($result[$k]) || !is_array ($result[$k])) {
1360 $result[$k] = array_replace_recursive ($result[$k],
1368 // json_encode only appeared in PHP 5.2.0
1369 if (!function_exists('json_encode')) {
1370 require_once $gfcommon.'include/minijson.php' ;
1371 function json_encode ($a1) {
1372 return minijson_encode ($a1) ;
1376 /* returns an integer from http://forge/foo/bar.php/123 or false */
1377 function util_path_info_last_numeric_component() {
1378 if (!isset($_SERVER['PATH_INFO']))
1382 foreach (str_split($_SERVER['PATH_INFO']) as $x) {
1386 } else if ($ok == false) {
1387 ; /* need reset using slash */
1388 } else if ((ord($x) >= 48) && (ord($x) <= 57)) {
1389 $rv = $rv * 10 + ord($x) - 48;
1399 function get_cvs_binary_version () {
1400 $string = `cvs --version 2>/dev/null | grep ^Concurrent.Versions.System.*client/server` ;
1401 if (preg_match ('/^Concurrent Versions System .CVS. 1.11.[0-9]*/', $string)) {
1403 } elseif (preg_match ('/^Concurrent Versions System .CVS. 1.12.[0-9]*/', $string)) {
1410 /* get a backtrace as string */
1411 function debug_string_backtrace() {
1413 debug_print_backtrace();
1414 $trace = ob_get_contents();
1417 // Remove first item from backtrace as it's this function
1418 // which is redundant.
1419 $trace = preg_replace('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '',
1422 // Renumber backtrace items.
1423 $trace = preg_replace('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);
1428 function util_ini_get_bytes($id) {
1429 $val = trim(ini_get($id));
1430 $last = strtolower($val[strlen($val)-1]);
1442 function util_get_maxuploadfilesize() {
1443 $postmax = util_ini_get_bytes('post_max_size');
1444 $maxfile = util_ini_get_bytes('upload_max_filesize');
1446 $postfile = (int)(($postmax * 3) / 4);
1448 if ($postfile < $maxfile)
1449 $postfile = $maxfile;
1454 function util_get_compressed_file_extension() {
1455 $m = forge_get_config('compression_method');
1456 if (preg_match ('/^gzip\b/', $m)) {
1458 } elseif (preg_match ('/^bzip2\b/', $m)) {
1460 } elseif (preg_match ('/^lzma\b/', $m)) {
1462 } elseif (preg_match ('/^xz\b/', $m)) {
1464 } elseif (preg_match ('/^cat\b/', $m)) {
1467 return '.compressed';
1471 /* return $1 if $1 is set, ${2:-false} otherwise */
1472 function util_ifsetor(&$val, $default = false) {
1473 return (isset($val) ? $val : $default);
1476 function util_randbytes($num=6) {
1479 // Let's try /dev/urandom first
1480 $f = @fopen("/dev/urandom", "rb");
1482 $b .= @fread($f, $num);
1486 // Hm. No /dev/urandom? Try /dev/random.
1487 if (strlen($b) < $num) {
1488 $f = @fopen("/dev/random", "rb");
1490 $b .= @fread($f, $num);
1495 // Still no luck? Fall back to PHP's built-in PRNG
1496 while (strlen($b) < $num) {
1497 $b .= uniqid(mt_rand(), true);
1500 $b = substr($b, 0, $num);
1504 /* maximum: 2^31 - 1 due to PHP weakness */
1505 function util_randnum($min=0,$max=32767) {
1506 $ta = unpack("L", util_randbytes(4));
1507 $n = $ta[1] & 0x7FFFFFFF;
1508 $v = $n % (1 + $max - $min);
1512 // sys_get_temp_dir() is only available for PHP >= 5.2.1
1513 if ( !function_exists('sys_get_temp_dir')) {
1514 function sys_get_temp_dir() {
1515 if ($temp=getenv('TMP')) return $temp;
1516 if ($temp=getenv('TEMP')) return $temp;
1517 if ($temp=getenv('TMPDIR')) return $temp;
1522 /* convert '\n' to <br /> or </p><p> */
1523 function util_pwrap($encoded_string) {
1524 return str_replace("<p></p>", "",
1525 str_replace("<br /></p>", "</p>",
1526 str_replace("<p><br />", "<p>",
1527 "<p>" . str_replace("<br /><br />", "</p><p>",
1528 implode("<br />", explode("\n",
1529 $encoded_string))) . "</p>")));
1531 function util_ttwrap($encoded_string) {
1532 return str_replace("<p><tt></tt></p>", "",
1533 str_replace("<br /></tt></p>", "</tt></p>",
1534 str_replace("<p><tt><br />", "<p><tt>",
1535 "<p><tt>" . str_replace("<br /><br />", "</tt></p><p><tt>",
1536 implode("<br />", explode("\n",
1537 encoded_string))) . "</tt></p>")));
1540 /* takes a string and returns it HTML encoded, URIs made to hrefs */
1541 function util_uri_grabber($unencoded_string, $tryaidtid=false) {
1542 /* escape all ^A and ^B as ^BX^B and ^BY^B, respectively */
1543 $s = str_replace("\x01", "\x02X\x02", str_replace("\x02", "\x02Y\x02",
1544 $unencoded_string));
1545 /* replace all URIs with ^AURI^A */
1547 '|([a-zA-Z][a-zA-Z0-9+.-]*:[#0-9a-zA-Z;/?:@&=+$,_.!~*\'()%-]+)|',
1550 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1551 /* encode the string */
1552 $s = htmlentities($s, ENT_QUOTES, "UTF-8");
1553 /* convert ć^Afoo^Ać to ć<a href="foo">foo</a>ć */
1554 $s = preg_replace('|\x01([^\x01]+)\x01|',
1555 '<a href="$1">$1</a>', $s);
1557 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1558 // /* convert [#123] to links if found */
1560 // $s = util_tasktracker_links($s);
1561 /* convert ^BX^B and ^BY^B back to ^A and ^B, respectively */
1562 $s = str_replace("\x02Y\x02", "\x02", str_replace("\x02X\x02", "\x01",
1564 /* return the final result */
1568 /* secure a (possibly already HTML encoded) string */
1569 function util_html_secure($s) {
1570 return htmlentities(html_entity_decode($s, ENT_QUOTES, "UTF-8"),
1571 ENT_QUOTES, "UTF-8");
1575 * TODO: Enter description here ...
1576 * @param unknown_type $script
1577 * @param unknown_type $default_content_type
1580 function util_negociate_alternate_content_types($script, $default_content_type) {
1582 // Invoke plugins' hooks 'script_accepted_types' to discover which alternate content types they would accept for /users/...
1583 $hook_params = array();
1584 $hook_params['script'] = $script;
1585 $hook_params['accepted_types'] = array();
1586 plugin_hook_by_reference('script_accepted_types', $hook_params);
1587 if (count($hook_params['accepted_types'])) {
1588 // By default, text/html is accepted
1589 $accepted_types = array($default_content_type);
1590 $new_accepted_types = $hook_params['accepted_types'];
1591 $accepted_types = array_merge($accepted_types, $new_accepted_types);
1593 // PEAR::HTTP (for negotiateMimeType())
1594 require_once('HTTP.php');
1596 // negociate accepted content-type depending on the preferred ones declared by client
1598 $content_type = $http->negotiateMimeType($accepted_types, false);
1600 $content_type = $default_content_type;
1602 return $content_type;
1607 // c-file-style: "bsd"