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, 2012
9 * Thorsten Glaser <t.glaser@tarent.de>
10 * Copyright 2010-2012, Alain Peyrat - Alcatel-Lucent
11 * Copyright 2013, Franck Villaume - TrivialDev
13 * This file is part of FusionForge. FusionForge is free software;
14 * you can redistribute it and/or modify it under the terms of the
15 * GNU General Public License as published by the Free Software
16 * Foundation; either version 2 of the Licence, or (at your option)
19 * FusionForge is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License along
25 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
26 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
30 * htpasswd_apr1_md5($plainpasswd) - generate htpasswd md5 format password
32 * From http://www.php.net/manual/en/function.crypt.php#73619
34 function htpasswd_apr1_md5($plainpasswd) {
35 $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
36 $len = strlen($plainpasswd);
37 $text = $plainpasswd.'$apr1$'.$salt;
38 $bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
40 for ($i = $len; $i > 0; $i -= 16) {
41 $text .= substr($bin, 0, min(16, $i));
43 for ($i = $len; $i > 0; $i >>= 1) {
44 $text .= ($i & 1)? chr(0) : $plainpasswd{0};
46 $bin = pack("H32", md5($text));
47 for ($i = 0; $i < 1000; $i++) {
48 $new = ($i & 1)? $plainpasswd : $bin;
49 if ($i % 3) $new .= $salt;
50 if ($i % 7) $new .= $plainpasswd;
51 $new .= ($i & 1)? $bin : $plainpasswd;
52 $bin = pack("H32", md5($new));
54 for ($i = 0; $i < 5; $i++) {
58 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
60 $tmp = chr(0).chr(0).$bin[11].$tmp;
61 $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
62 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
63 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
64 return "$"."apr1"."$".$salt."$".$tmp;
68 * is_utf8($string) - utf-8 detection
70 * From http://www.php.net/manual/en/function.mb-detect-encoding.php#85294
72 function is_utf8($str) {
76 for($i=0; $i<$len; $i++){
79 if(($c >= 254)) return false;
80 elseif($c >= 252) $bits=6;
81 elseif($c >= 248) $bits=5;
82 elseif($c >= 240) $bits=4;
83 elseif($c >= 224) $bits=3;
84 elseif($c >= 192) $bits=2;
86 if(($i+$bits) > $len) return false;
90 if($b < 128 || $b > 191) return false;
102 function util_strip_unprintable(&$data) {
103 if (is_array($data)) {
104 foreach ($data as $key => &$value) {
105 util_strip_unprintable($value);
108 $data = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $data);
114 * removeCRLF() - remove any Carriage Return-Line Feed from a string.
115 * That function is useful to remove the possibility of a CRLF Injection when sending mail
116 * All the data that we will send should be passed through that function
118 * @param string $str The string that we want to empty from any CRLF
121 function util_remove_CRLF($str) {
122 return strtr($str, "\015\012", ' ');
126 * util_check_fileupload() - determines if a filename is appropriate for upload
128 * @param array $filename The uploaded file as returned by getUploadedFile()
131 function util_check_fileupload($filename) {
133 /* Empty file is a valid file.
134 This is because this function should be called
135 unconditionally at the top of submit action processing
136 and many forms have optional file upload. */
137 if ($filename == 'none' || $filename == '') {
141 /* This should be enough... */
142 if (!is_uploaded_file($filename)) {
145 /* ... but we'd rather be paranoic */
146 if (strstr($filename, '..')) {
149 if (!is_file($filename)) {
152 if (!file_exists($filename)) {
155 if ((dirname($filename) != '/tmp') &&
156 (dirname($filename) != "/var/tmp")) {
163 * util_check_url() - determines if given URL is valid.
165 * Currently, test is very basic, only the protocol is
166 * checked, allowed values are: http, https, ftp.
168 * @param string $url The URL
169 * @return bool true if valid, false if not valid.
171 function util_check_url($url) {
172 return (preg_match('/^(http|https|ftp):\/\//', $url) > 0);
176 * util_send_message() - Send email
177 * This function should be used in place of the PHP mail() function
179 * @param string $to The email recipients address
180 * @param string $subject The email subject
181 * @param string $body The body of the email message
182 * @param string $from The optional email sender address. Defaults to 'noreply@'
183 * @param string $BCC The addresses to blind-carbon-copy this message (comma-separated)
184 * @param string $sendername The optional email sender name. Defaults to ''
185 * @param bool|string $extra_headers
186 * @param bool $send_html_email Whether to send plain text or html email
187 * @param string $CC The addresses to carbon-copy this message (comma-separated)
189 function util_send_message($to, $subject, $body, $from = '', $BCC = '', $sendername = '', $extra_headers = '',
190 $send_html_email = false, $CC = '') {
192 $to = 'noreply@'.forge_get_config('web_host');
195 $from = 'noreply@'.forge_get_config('web_host');
198 $charset = _('UTF-8');
204 if ($extra_headers) {
205 $body2 .= $extra_headers."\n";
208 "\nFrom: ".util_encode_mailaddr($from, $sendername, $charset);
209 if (forge_get_config('bcc_all_emails') != '') {
210 $BCC .= ",".forge_get_config('bcc_all_emails');
213 $body2 .= "\nBCC: $BCC";
216 $body2 .= "\nCC: $CC";
218 $send_html_email? $type = "html" : $type = "plain";
219 $body2 .= "\n".util_encode_mimeheader("Subject", $subject, $charset).
220 "\nContent-type: text/$type; charset=$charset".
222 util_convert_body($body, $charset);
224 if (!forge_get_config('sendmail_path')){
225 $sys_sendmail_path="/usr/sbin/sendmail";
228 $handle = popen(forge_get_config('sendmail_path')." -f'$from' -t -i", 'w');
229 fwrite($handle, $body2);
234 * util_encode_mailaddr() - Encode email address to MIME format
236 * @param string $email The email address
237 * @param string $name The email's owner name
238 * @param string $charset The converting charset
241 function util_encode_mailaddr($email, $name, $charset) {
242 if (function_exists('mb_convert_encoding') && trim($name) != "") {
243 $name = "=?".$charset."?B?".
244 base64_encode(mb_convert_encoding(
245 $name, $charset, "UTF-8")).
249 return $name." <".$email.">";
253 * util_encode_mimeheader() - Encode mimeheader
255 * @param string $headername The name of the header (e.g. "Subject")
256 * @param string $str The email subject
257 * @param string $charset The converting charset (like ISO-2022-JP)
258 * @return string The MIME encoded subject
261 function util_encode_mimeheader($headername, $str, $charset) {
262 if (function_exists('mb_internal_encoding') &&
263 function_exists('mb_encode_mimeheader')) {
264 $x = mb_internal_encoding();
265 mb_internal_encoding("UTF-8");
266 $y = mb_encode_mimeheader($headername.": ".$str,
268 mb_internal_encoding($x);
272 if (!function_exists('mb_convert_encoding')) {
273 return $headername.": ".$str;
276 return $headername.": "."=?".$charset."?B?".
277 base64_encode(mb_convert_encoding(
278 $str, $charset, "UTF-8")).
283 * util_convert_body() - Convert body of the email message
285 * @param string $str The body of the email message
286 * @param string $charset The charset of the email message
287 * @return string The converted body of the email message
290 function util_convert_body($str, $charset) {
291 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
295 return mb_convert_encoding($str, $charset, "UTF-8");
299 * util_handle_message() - a convenience wrapper which sends messages
300 * to an email account
302 * @param array $id_arr array of user_id's from the user table
303 * @param string $subject subject of the message
304 * @param string $body the message body
305 * @param string $extra_emails a comma-separated list of email address
306 * @param string $dummy1 ignored (no longer used)
307 * @param string $from From header
309 function util_handle_message($id_arr, $subject, $body, $extra_emails = '', $dummy1 = '', $from = '') {
312 if (count($id_arr) < 1) {
315 $res = db_query_params('SELECT user_id,email FROM users WHERE user_id = ANY ($1)',
316 array(db_int_array_to_any_clause($id_arr)));
317 $rows = db_numrows($res);
319 for ($i = 0; $i < $rows; $i++) {
320 if (db_result($res, $i, 'user_id') == 100) {
321 // Do not send messages to "Nobody"
324 $address['email'][] = db_result($res,$i,'email');
326 if (isset ($address['email']) && count($address['email']) > 0) {
327 $extra_emails = implode($address['email'], ',').','.$extra_emails;
331 util_send_message('', $subject, $body, $from, $extra_emails);
336 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
338 * @param string $string The string to unconvert
339 * @return string The unconverted string
342 function util_unconvert_htmlspecialchars($string) {
343 return html_entity_decode($string, ENT_QUOTES, "UTF-8");
347 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
349 * @param string $result The result set ID
350 * @param int $col_key The column key
351 * @param int $col_val The optional column value
352 * @return array An associative array
355 function util_result_columns_to_assoc($result, $col_key = 0, $col_val = 1) {
356 $rows = db_numrows($result);
360 for ($i = 0; $i < $rows; $i++) {
361 $arr[db_result($result, $i, $col_key)] = db_result($result, $i, $col_val);
370 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
372 * @param int $result The result set ID
373 * @param int $col The column
377 function &util_result_column_to_array($result, $col = 0) {
379 Takes a result set and turns the optional column into
382 $rows = db_numrows($result);
386 for ($i = 0; $i < $rows; $i++) {
387 $arr[$i] = db_result($result, $i, $col);
396 * util_line_wrap() - Automatically linewrap text
398 * @param string $text The text to wrap
399 * @param int $wrap The number of characters to wrap - Default is 80
400 * @param string $break The line break to use - Default is '\n'
401 * @return string The wrapped text
404 function util_line_wrap($text, $wrap = 80, $break = "\n") {
405 return wordwrap($text, $wrap, $break, false);
409 * util_make_links() - Turn URL's into HREF's.
411 * @param string $data The URL
412 * @return mixed|string The HREF'ed URL
415 function util_make_links($data = '') {
420 for ($i = 0; $i < 5; $i++) {
421 $randPattern = rand(10000, 30000);
422 if (!preg_match("/$randPattern/", $data)) {
429 while(preg_match('/<a [^>]*>[^<]*<\/a>/i', $data, $part)) {
431 $data = preg_replace('/<a [^>]*>[^<]*<\/a>/i', $randPattern, $data, 1);
435 while (preg_match('/<a [^>]*>.*<\/a>/siU', $data, $part)) {
437 $data = preg_replace('/<a [^>]*>.*<\/a>/siU', $randPattern, $data, 1);
439 while (preg_match('/<img [^>]*\/>/siU', $data, $part)) {
441 $data = preg_replace('/<img [^>]*\/>/siU', $randPattern, $data, 1);
443 $data = str_replace('>', "\1", $data);
444 $data = preg_replace("#([ \t]|^)www\.#i", " http://www.", $data);
445 $data = preg_replace("#([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]\#?/&=])#i", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $data);
446 $data = preg_replace("#([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]<\1]*)([[:alnum:]-]))#i", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $data);
447 $data = str_replace("\1", '>', $data);
448 for ($i = 0; $i < count($mem); $i++) {
449 $data = preg_replace("/$randPattern/", $mem[$i], $data, 1);
454 $lines = split("\n", $data);
456 while (list ($key, $line) = each($lines)) {
457 // Do not scan lines if they already have hyperlinks.
458 // Avoid problem with text written with an WYSIWYG HTML editor.
459 if (eregi('<a ([^>]*)>.*</a>', $line, $linePart)) {
460 if (eregi('href="[^"]*"', $linePart[1])) {
466 // Skip </img> tag also
467 if (eregi('<img ([^>]*)/>', $line, $linePart)) {
468 if (eregi('href="[^"]*"', $linePart[1])) {
474 // When we come here, we usually have form input
475 // encoded in entities. Our aim is to NOT include
476 // angle brackets in the URL
477 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
478 $line = str_replace('>', "\1", $line);
479 $line = preg_replace("/([ \t]|^)www\./i", " http://www.", $line);
480 $line = preg_replace("/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
481 "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
482 $line = preg_replace(
483 "/([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))/i",
484 "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>",
487 $line = str_replace("\1", '>', $line);
494 * show_priority_colors_key() - Show the priority colors legend
497 function show_priority_colors_key() {
498 echo '<p><strong> '._('Priority Colors')._(':').'</strong>';
499 for ($i = 1; $i < 6; $i++) {
500 echo ' <span class="priority'.$i.'">'.$i.'</span>';
506 * utils_buildcheckboxarray() - Build a checkbox array
508 * @param int $options Number of options to be in the array
509 * @param string $name The name of the checkboxes
510 * @param array $checked_array An array of boxes to be pre-checked
513 function utils_buildcheckboxarray($options, $name, $checked_array) {
514 $option_count = count($options);
515 $checked_count = count($checked_array);
517 for ($i = 1; $i <= $option_count; $i++) {
519 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
520 for ($j = 0; $j < $checked_count; $j++) {
521 if ($i == $checked_array[$j]) {
525 echo ' /> '.$options[$i];
530 * utils_requiredField() - Adds the required field marker
532 * @return string A string holding the HTML to mark a required field
534 function utils_requiredField() {
535 return '<span class="requiredfield">*</span>';
539 * GraphResult() - Takes a database result set and builds a graph.
540 * The first column should be the name, and the second column should be the values
541 * Be sure to include HTL_Graphs.php before using this function
543 * @author Tim Perdue tperdue@valinux.com
544 * @param int $result The databse result set ID
545 * @param string $title The title of the graph
548 function GraphResult($result, $title) {
549 $rows = db_numrows($result);
551 if ((!$result) || ($rows < 1)) {
557 for ($j = 0; $j < db_numrows($result); $j++) {
558 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '') {
559 $names[$j] = db_result($result, $j, 0);
560 $values[$j] = db_result($result, $j, 1);
565 This is another function detailed below
567 GraphIt($names, $values, $title);
572 * GraphIt() - Build a graph
574 * @author Tim Perdue tperdue@valinux.com
575 * @param array $name_string An array of names
576 * @param array $value_string An array of values
577 * @param string $title The title of the graph
580 function GraphIt($name_string, $value_string, $title) {
583 $counter = count($name_string);
586 Can choose any color you wish
590 for ($i = 0; $i < $counter; $i++) {
591 $bars[$i] = $HTML->COLOR_LTBACK1;
594 $counter = count($value_string);
597 Figure the max_value passed in, so scale can be determined
602 for ($i = 0; $i < $counter; $i++) {
603 if ($value_string[$i] > $max_value) {
604 $max_value = $value_string[$i];
608 if ($max_value < 1) {
613 I want my graphs all to be 800 pixels wide, so that is my divisor
616 $scale = (400/$max_value);
619 I create a wrapper table around the graph that holds the title
622 $title_arr = array();
623 $title_arr[] = $title;
625 echo $GLOBALS['HTML']->listTableTop($title_arr);
628 Create an associate array to pass in. I leave most of it blank
636 'cellspacing' => '0',
654 'doublefcolor'=> '');
657 This is the actual call to the HTML_Graphs class
660 html_graph($name_string, $value_string, $bars, $vals);
664 <!-- end outer graph table -->';
665 echo $GLOBALS['HTML']->listTableBottom();
669 * ShowResultSet() - Show a generic result set
670 * Very simple, plain way to show a generic result set
672 * @param int $result The result set ID
673 * @param string $title The title of the result set
674 * @param bool $linkify The option to turn URL's into links
675 * @param bool $displayHeaders The option to display headers
676 * @param array $headerMapping The db field name -> label mapping
677 * @param array $excludedCols Don't display these cols
679 function ShowResultSet($result, $title = '', $linkify = false, $displayHeaders = true, $headerMapping = array(), $excludedCols = array()) {
680 global $group_id, $HTML;
683 $rows = db_numrows($result);
684 $cols = db_numfields($result);
686 echo '<table class="fullwidth">'."\n";
688 /* Create the headers */
689 $headersCellData = array();
690 $colsToKeep = array();
691 for ($i = 0; $i < $cols; $i++) {
692 $fieldName = db_fieldname($result, $i);
693 if (in_array($fieldName, $excludedCols)) {
697 if (isset($headerMapping[$fieldName])) {
698 if (is_array($headerMapping[$fieldName])) {
699 $headersCellData[] = $headerMapping[$fieldName];
701 $headersCellData[] = array($headerMapping[$fieldName]);
704 $headersCellData[] = array($fieldName);
708 /* Create the title */
709 if (strlen($title) > 0) {
710 $titleCellData = array();
711 $titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
712 echo $HTML->multiTableRow('', $titleCellData, TRUE);
715 /* Display the headers */
716 if ($displayHeaders) {
717 echo $HTML->multiTableRow('', $headersCellData, TRUE);
720 /* Create the rows */
721 for ($j = 0; $j < $rows; $j++) {
722 echo '<tr '.$HTML->boxGetAltRowStyle($j).'>';
723 for ($i = 0; $i < $cols; $i++) {
724 if (in_array($i, $colsToKeep)) {
725 if ($linkify && $i == 0) {
726 $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
728 if ($linkify == "bug_cat") {
729 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
730 } elseif ($linkify == "bug_group") {
731 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
732 } elseif ($linkify == "patch_cat") {
733 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
734 } elseif ($linkify == "support_cat") {
735 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
736 } elseif ($linkify == "pm_project") {
737 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
739 $link = $linkend = '';
742 $link = $linkend = '';
744 echo '<td>'.$link.db_result($result, $j, $i).$linkend.'</td>';
756 * validate_email() - Validate an email address
758 * @param string $address The address string to validate
759 * @return bool true on success/false on error
762 function validate_email($address) {
763 if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
764 if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
770 if (preg_match("/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+$/", $address)) {
779 * validate_emails() - Validate a list of e-mail addresses
781 * @param string $addresses E-mail list
782 * @param string $separator Separator
783 * @return array Array of invalid e-mail addresses (if empty, all addresses are OK)
785 function validate_emails($addresses, $separator = ',') {
786 if (strlen($addresses) == 0) return array();
788 $emails = explode($separator, $addresses);
791 if (is_array($emails)) {
792 foreach ($emails as $email) {
793 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
794 if (!validate_email($email)) $ret[] = $email;
801 * util_is_valid_filename() - Verifies whether a file has a valid filename
803 * @param string $file The file to verify
804 * @return bool true on success/false on error
807 function util_is_valid_filename($file) {
809 $invalidchars = preg_replace("/[-A-Z0-9+_\. ~]/i", "", $file);
811 if (!empty($invalidchars)) {
814 if (strstr($file, '..')) {
823 * util_is_valid_repository_name() - Verifies whether a repository name is valid
825 * @param string $file name to verify
826 * @return bool true on success/false on error
829 function util_is_valid_repository_name ($file) {
831 $invalidchars = preg_replace("/[-A-Z0-9+_\.]/i","",$file);
833 if (!empty($invalidchars)) {
836 if (strstr($file,'..')) {
843 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
845 * @param string $hostname The optional hostname string
846 * @return bool true on success/false on failure
849 function valid_hostname($hostname = "xyz") {
852 $invalidchars = preg_replace("/[-A-Z0-9\.]/i", "", $hostname);
854 if (!empty($invalidchars)) {
858 //double dot, starts with a . or -
859 if (preg_match("/\.\./", $hostname) || preg_match("/^\./", $hostname) || preg_match("/^\-/", $hostname)) {
863 $multipoint = explode(".", $hostname);
865 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
875 * human_readable_bytes() - Translates an integer representing bytes to a human-readable format.
877 * Format file size in a human-readable way
878 * such as "xx Megabytes" or "xx Mo"
880 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
883 * @param int $bytes is the size
884 * @param bool $base10 enable base 10 representation, otherwise default base 2 is used
885 * @param int $round number of fractional digits
886 * @param array $labels strings associated to each 2^10 or 10^3(base10==true) multiple of base units
889 function human_readable_bytes($bytes, $base10 = false, $round = 0, $labels = array()) {
894 return "-".human_readable_bytes(-$bytes, $base10, $round);
897 $labels = array(_('bytes'), _('kB'), _('MB'), _('GB'), _('TB'));
901 $labels = array(_('bytes'), _('KiB'), _('MiB'), _('GiB'), _('TiB'));
905 $log = (int)(log10($bytes)/log10($base));
907 foreach ($labels as $p => $lab) {
912 if ($lab != _("bytes") and $lab != _("kB") and $lab != _("KiB")) {
915 $text = round($bytes/pow($base, $pow), $round)." ".$lab;
922 * ls - lists a specified directory and returns an array of files
923 * @param string $dir the path of the directory to list
924 * @param bool $filter whether to filter out directories and illegal filenames
925 * @return array array of file names.
927 function &ls($dir, $filter = false) {
930 if (is_dir($dir) && ($h = opendir($dir))) {
931 while (($f = readdir($h)) !== false) {
935 if (!util_is_valid_filename($f) ||
936 !is_file($dir."/".$f)
948 * readfile_chunked() - replacement for readfile
950 * @param string $filename The file path
951 * @param bool $returnBytes Whether to return bytes served or just a bool
954 function readfile_chunked($filename, $returnBytes = true) {
955 $chunksize = 1*(1024*1024); // 1MB chunks
959 $handle = fopen($filename, 'rb');
960 if ($handle === false) {
965 while (!feof($handle)) {
966 $buffer = fread($handle, $chunksize);
971 $byteCounter += strlen($buffer);
975 $status = fclose($handle);
976 if ($returnBytes && $status) {
977 return $byteCounter; // return num. bytes delivered like readfile() does.
983 * util_is_root_dir() - Checks if a directory points to the root dir
985 * @param string $dir Directory
988 function util_is_root_dir($dir) {
989 return !preg_match('/[^\\/]/', $dir);
993 * util_is_dot_or_dotdot() - Checks if a directory points to . or ..
995 * @param string $dir Directory
998 function util_is_dot_or_dotdot($dir) {
999 return preg_match('/^\.\.?$/', trim($dir, '/'));
1003 * util_containts_dot_or_dotdot() - Checks if a directory containts . or ..
1005 * @param string $dir Directory
1008 function util_containts_dot_or_dotdot($dir) {
1009 foreach (explode('/', $dir) as $sub_dir) {
1010 if (util_is_dot_or_dotdot($sub_dir))
1018 * util_secure_filename() - Returns a secured file name
1020 * @param string $file Filename
1021 * @return string Filename
1023 function util_secure_filename($file) {
1024 $f = preg_replace("/[^-A-Z0-9_\.]/i", '', $file);
1025 if (util_containts_dot_or_dotdot($f))
1026 $f = preg_replace("/\./", '_', $f);
1033 * util_strip_accents() - Remove accents from given text.
1035 * @param string $text Text
1038 function util_strip_accents($text) {
1039 $find = utf8_decode($text);
1040 $find = strtr($find,
1041 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
1042 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
1043 return utf8_encode($find);
1047 * Constructs the forge's URL prefix out of forge_get_config('url_prefix')
1051 function normalized_urlprefix() {
1052 $prefix = forge_get_config('url_prefix');
1053 $prefix = preg_replace("/^\//", "", $prefix);
1054 $prefix = preg_replace("/\/$/", "", $prefix);
1055 $prefix = "/$prefix/";
1056 if ($prefix == '//')
1062 * Return URL prefix (http:// or https://)
1064 * @param string $prefix (optional) : 'http' or 'https' to force it
1065 * @return string URL prefix
1067 function util_url_prefix($prefix = '') {
1068 if ($prefix == 'http' || $prefix == 'https' ) {
1069 return $prefix . '://';
1072 if (forge_get_config('use_ssl')) {
1081 * Construct the base URL http[s]://forge_name[:port]
1083 * @param string $prefix (optional) : 'http' or 'https' to force it
1084 * @return string base URL
1086 function util_make_base_url($prefix = '') {
1087 $url = util_url_prefix($prefix);
1088 $url .= forge_get_config('web_host');
1089 if (forge_get_config('https_port') && (forge_get_config('https_port') != 443)) {
1090 $url .= ":".forge_get_config('https_port');
1096 * Construct full URL from a relative path
1098 * @param string $path (optional)
1099 * @param string $prefix (optional) : 'http' or 'https' to force it
1100 * @return string URL
1102 function util_make_url($path = '', $prefix = '') {
1103 $url = util_make_base_url($prefix).util_make_uri($path) ;
1108 * Find the relative URL from full URL, removing http[s]://forge_name[:port]
1110 * @param string $url URL
1113 function util_find_relative_referer($url) {
1114 $relative_url = str_replace(util_make_base_url(), '', $url);
1115 //now remove previous feedback, error_msg or warning_msg
1116 $relative_url = preg_replace('/&error_msg=.*&/', '&', $relative_url);
1117 $relative_url = preg_replace('/&warning_msg=.*&/', '&', $relative_url);
1118 $relative_url = preg_replace('/&feedback=.*&/', '&', $relative_url);
1119 $relative_url = preg_replace('/&error_msg=.*/', '', $relative_url);
1120 $relative_url = preg_replace('/&warning_msg=.*/', '', $relative_url);
1121 $relative_url = preg_replace('/&feedback=.*/', '', $relative_url);
1122 return $relative_url;
1126 * Construct proper (relative) URI (prepending prefix)
1128 * @param string $path
1129 * @return string URI
1131 function util_make_uri($path) {
1132 $path = preg_replace('/^\//', '', $path);
1133 $uri = normalized_urlprefix();
1139 * Construct proper (relative) URI from path & text
1141 * @param string $path
1142 * @param string $text
1143 * @param array|bool $extra_params
1144 * @param bool $absolute
1145 * @return string URI
1147 function util_make_link($path, $text, $extra_params = false, $absolute = false) {
1148 global $use_tooltips;
1150 if (is_array($extra_params)) {
1151 foreach ($extra_params as $key => $value) {
1152 if ($key != 'title') {
1153 $ep .= "$key=\"$value\" ";
1155 if ($key == 'title' && $use_tooltips) {
1156 $ep .= "$key=\"$value\" ";
1161 return '<a '.$ep.'href="'.$path.'">'.$text.'</a>';
1163 return '<a '.$ep.'href="'.util_make_uri($path).'">'.$text.'</a>';
1168 * Create an HTML link to a user's profile page
1170 * @param string $username
1171 * @param int $user_id
1172 * @param string $text
1175 function util_make_link_u($username, $user_id, $text) {
1176 return '<a href="'.util_make_url_u($username, $user_id).'">'.$text.'</a>';
1180 * Display username with link to a user's profile page
1181 * and icon face if possible.
1183 * @param string $username
1184 * @param int $user_id
1185 * @param string $text
1186 * @param string $size
1189 function util_display_user($username, $user_id, $text, $size = 'xs') {
1190 // Invoke user_link_with_tooltip plugin
1191 $hook_params = array('resource_type' => 'user', 'username' => $username, 'user_id' => $user_id, 'size' => $size, 'user_link' => '');
1192 plugin_hook_by_reference('user_link_with_tooltip', $hook_params);
1193 if ($hook_params['user_link'] != '') {
1194 return $hook_params['user_link'];
1197 // If no plugin replaced it, then back to default standard link
1199 // Invoke user_logo plugin (see gravatar plugin for instance)
1200 $params = array('user_id' => $user_id, 'size' => $size, 'content' => '');
1201 plugin_hook_by_reference('user_logo', $params);
1203 $url = '<a href="'.util_make_url_u($username, $user_id).'">'.$text.'</a>';
1204 if ($params['content']) {
1205 return $params['content'].$url.'<div class="new_line"></div>';
1211 * Create URL for user's profile page
1213 * @param string $username
1214 * @param int $user_id
1215 * @return string URL
1217 function util_make_url_u($username, $user_id) {
1218 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1219 return util_make_url("/developer/?user_id=$user_id");
1221 return util_make_url("/users/$username/");
1226 * Create a HTML link to a project's page
1228 * @param string $group_name
1229 * @param int $group_id
1230 * @param string $text
1233 function util_make_link_g($group_name, $group_id, $text) {
1234 $hook_params = array();
1235 $hook_params['resource_type'] = 'group';
1236 $hook_params['group_name'] = $group_name;
1237 $hook_params['group_id'] = $group_id;
1238 $hook_params['link_text'] = $text;
1239 $hook_params['group_link'] = '';
1240 plugin_hook_by_reference('project_link_with_tooltip', $hook_params);
1241 if ($hook_params['group_link'] != '') {
1242 return $hook_params['group_link'];
1245 return '<a href="'.util_make_url_g($group_name, $group_id).'">'.$text.'</a>';
1249 * Create URL for a project's page
1251 * @param string $group_name
1252 * @param int $group_id
1255 function util_make_url_g($group_name, $group_id) {
1256 if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
1257 return util_make_url("/project/?group_id=$group_id");
1259 return util_make_url("/projects/$group_name/");
1263 function util_ensure_value_in_set($value, $set) {
1264 if (in_array($value, $set)) {
1272 * @param Group $group
1273 * @param string $email
1274 * @param string $response
1277 function check_email_available($group, $email, &$response) {
1278 // Check if a mailing list with same name already exists
1279 if ($group->usesMail()) {
1280 $mlFactory = new MailingListFactory($group);
1281 if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
1282 $response .= $mlFactory->getErrorMessage();
1285 $mlArray = $mlFactory->getMailingLists();
1286 if ($mlFactory->isError()) {
1287 $response .= $mlFactory->getErrorMessage();
1290 for ($j = 0; $j < count($mlArray); $j++) {
1291 $currentList =& $mlArray[$j];
1292 if ($email == $currentList->getName()) {
1293 $response .= _('Error: a mailing list with the same email address already exists.');
1299 // Check if a forum with same name already exists
1300 if ($group->usesForum()) {
1301 $ff = new ForumFactory($group);
1302 if (!$ff || !is_object($ff) || $ff->isError()) {
1303 $response .= $ff->getErrorMessage();
1306 $farr = $ff->getForums();
1307 $prefix = $group->getUnixName().'-';
1308 for ($j = 0; $j < count($farr); $j++) {
1309 if (is_object($farr[$j])) {
1310 if ($email == $prefix.$farr[$j]->getName()) {
1311 $response .= _('Error: a forum with the same email address already exists.');
1318 // Email is available
1323 * Adds the Javascript file to the list to be used
1326 function use_javascript($js) {
1327 return $GLOBALS['HTML']->addJavascript($js);
1330 function use_stylesheet($css, $media = '') {
1331 return $GLOBALS['HTML']->addStylesheet($css, $media);
1334 // array_replace_recursive only appeared in PHP 5.3.0
1335 if (!function_exists('array_replace_recursive')) {
1337 * Replaces elements from passed arrays into the first array recursively
1338 * @param array $a1 The array in which elements are replaced.
1339 * @param array $a2 The array from which elements will be extracted.
1340 * @return array Returns an array, or NULL if an error occurs.
1342 function array_replace_recursive($a1, $a2) {
1345 if (!is_array($a2)) {
1349 foreach ($a2 as $k => $v) {
1350 if (!is_array($v) ||
1351 !isset($result[$k]) || !is_array($result[$k])) {
1355 $result[$k] = array_replace_recursive($result[$k], $v);
1362 // json_encode only appeared in PHP 5.2.0
1363 if (!function_exists('json_encode')) {
1364 require_once $gfcommon.'include/minijson.php';
1365 function json_encode($a1) {
1366 return minijson_encode($a1);
1370 /* returns an integer from http://forge/foo/bar.php/123 or false */
1371 function util_path_info_last_numeric_component() {
1372 if (!isset($_SERVER['PATH_INFO']))
1376 foreach (str_split($_SERVER['PATH_INFO']) as $x) {
1380 } elseif ($ok == false) {
1381 ; /* need reset using slash */
1382 } elseif ((ord($x) >= 48) && (ord($x) <= 57)) {
1383 $rv = $rv * 10 + ord($x) - 48;
1393 function get_cvs_binary_version() {
1394 $string = `cvs --version 2>/dev/null | grep ^Concurrent.Versions.System.*client/server`;
1395 if (preg_match('/^Concurrent Versions System .CVS. 1.11.[0-9]*/', $string)) {
1397 } elseif (preg_match('/^Concurrent Versions System .CVS. 1.12.[0-9]*/', $string)) {
1404 /* get a backtrace as string */
1405 function debug_string_backtrace() {
1407 debug_print_backtrace();
1408 $trace = ob_get_contents();
1411 // Remove first item from backtrace as it's this function
1412 // which is redundant.
1413 $trace = preg_replace('/^#0\s+'.__FUNCTION__."[^\n]*\n/", '',
1416 // Renumber backtrace items.
1417 $trace = preg_replace('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);
1422 function util_ini_get_bytes($id) {
1423 $val = trim(ini_get($id));
1424 $last = strtolower($val[strlen($val)-1]);
1436 function util_get_maxuploadfilesize() {
1437 $postmax = util_ini_get_bytes('post_max_size');
1438 $maxfile = util_ini_get_bytes('upload_max_filesize');
1440 return min($postmax, $maxfile);
1443 function util_get_compressed_file_extension() {
1444 $m = forge_get_config('compression_method');
1445 if (preg_match('/^gzip\b/', $m)) {
1447 } elseif (preg_match('/^bzip2\b/', $m)) {
1449 } elseif (preg_match('/^lzma\b/', $m)) {
1451 } elseif (preg_match('/^xz\b/', $m)) {
1453 } elseif (preg_match('/^cat\b/', $m)) {
1456 return '.compressed';
1460 /* return $1 if $1 is set, ${2:-false} otherwise */
1461 function util_ifsetor(&$val, $default = false) {
1462 return (isset($val) ? $val : $default);
1465 function util_randbytes($num = 6) {
1468 // Let's try /dev/urandom first
1469 $f = @fopen("/dev/urandom", "rb");
1471 $b .= @fread($f, $num);
1475 // Hm. No /dev/urandom? Try /dev/random.
1476 if (strlen($b) < $num) {
1477 $f = @fopen("/dev/random", "rb");
1479 $b .= @fread($f, $num);
1484 // Still no luck? Fall back to PHP's built-in PRNG
1485 while (strlen($b) < $num) {
1486 $b .= uniqid(mt_rand(), true);
1489 $b = substr($b, 0, $num);
1493 /* maximum: 2^31 - 1 due to PHP weakness */
1494 function util_randnum($min = 0, $max = 32767) {
1495 $ta = unpack("L", util_randbytes(4));
1496 $n = $ta[1] & 0x7FFFFFFF;
1497 $v = $n % (1 + $max - $min);
1501 // sys_get_temp_dir() is only available for PHP >= 5.2.1
1502 if (!function_exists('sys_get_temp_dir')) {
1503 function sys_get_temp_dir() {
1504 if ($temp = getenv('TMP')) return $temp;
1505 if ($temp = getenv('TEMP')) return $temp;
1506 if ($temp = getenv('TMPDIR')) return $temp;
1511 /* convert '\n' to <br /> or </p><p> */
1512 function util_pwrap($encoded_string) {
1513 return str_replace("<p></p>", "",
1514 str_replace("<br /></p>", "</p>",
1515 str_replace("<p><br />", "<p>",
1516 "<p>".str_replace("<br /><br />", "</p><p>",
1517 implode("<br />", explode("\n",
1518 $encoded_string)))."</p>")));
1521 /* takes a string and returns it HTML encoded, URIs made to hrefs */
1522 function util_uri_grabber($unencoded_string, $tryaidtid = false) {
1523 /* escape all ^A and ^B as ^BX^B and ^BY^B, respectively */
1524 $s = str_replace("\x01", "\x02X\x02", str_replace("\x02", "\x02Y\x02",
1525 $unencoded_string));
1526 /* replace all URIs with ^AURI^A */
1528 '|([a-zA-Z][a-zA-Z0-9+.-]*:[#0-9a-zA-Z;/?:@&=+$,_.!~*\'()%-]+)|',
1531 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1532 /* encode the string */
1533 $s = htmlentities($s, ENT_QUOTES, "UTF-8");
1534 /* convert 「^Afoo^A」 to 「<a href="foo">foo</a>」 */
1535 $s = preg_replace('|\x01([^\x01]+)\x01|',
1536 '<a href="$1">$1</a>', $s);
1538 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1539 // /* convert [#123] to links if found */
1541 // $s = util_tasktracker_links($s);
1542 /* convert ^BX^B and ^BY^B back to ^A and ^B, respectively */
1543 $s = str_replace("\x02Y\x02", "\x02", str_replace("\x02X\x02", "\x01",
1545 /* return the final result */
1549 function util_html_encode($s) {
1550 return htmlspecialchars($s, ENT_QUOTES, "UTF-8");
1553 /* secure a (possibly already HTML encoded) string */
1554 function util_html_secure($s) {
1555 return util_html_encode(util_unconvert_htmlspecialchars($s));
1558 /* return integral value (ℕ₀) of passed string if it matches, or false */
1559 function util_nat0(&$s) {
1561 /* unset variable */
1565 if (count($s) == 1) {
1566 /* one-element array */
1567 return util_nat0($s[0]);
1569 /* not one element, or element not at [0] */
1572 if (!is_numeric($s)) {
1578 /* number element of ℕ₀ */
1579 $text = (string)$num;
1581 /* number matches its textual representation */
1584 /* doesn't match, like 0123 or 1.2 or " 1" */
1591 * util_negociate_alternate_content_types() - Manage content-type negociation based on 'script_accepted_types' hooks
1592 * @param string $script
1593 * @param string $default_content_type
1594 * @param string|bool $forced_content_type
1597 function util_negociate_alternate_content_types($script, $default_content_type, $forced_content_type=false) {
1599 $content_type = $default_content_type;
1601 // we can force the content-type to be returned automatically if necessary
1602 if ($forced_content_type) {
1603 // TODO ideally, in this case we could try and apply the negociation to see if it matches
1604 // one provided by the hooks, but negotiateMimeType() doesn't allow this so for the moment,
1605 // we just force it whatever the hooks support
1606 $content_type = $forced_content_type;
1608 // Invoke plugins' hooks 'script_accepted_types' to discover which alternate content types they would accept for /users/...
1609 $hook_params = array();
1610 $hook_params['script'] = $script;
1611 $hook_params['accepted_types'] = array();
1613 plugin_hook_by_reference('script_accepted_types', $hook_params);
1615 if (count($hook_params['accepted_types'])) {
1616 // By default, text/html is accepted
1617 $accepted_types = array($default_content_type);
1618 $new_accepted_types = $hook_params['accepted_types'];
1619 $accepted_types = array_merge($accepted_types, $new_accepted_types);
1621 // PEAR::HTTP (for negotiateMimeType())
1622 require_once 'HTTP.php';
1624 // negociate accepted content-type depending on the preferred ones declared by client
1626 $content_type = $http->negotiateMimeType($accepted_types, false);
1629 return $content_type;
1633 * util_gethref() - Construct a hypertext reference
1635 * @param string $baseurl
1636 * (optional) base URL (absolute or relative);
1637 * urlencoded, but not htmlencoded
1638 * (default (falsy): PHP_SELF)
1639 * @param array $args
1640 * (optional) associative array of unencoded query parameters;
1641 * false values are ignored
1642 * @param bool $ashtml
1643 * (optional) htmlencode the result?
1645 * @param string $sep
1646 * (optional) argument separator ('&' or ';')
1648 * @return string URL, possibly htmlencoded
1650 function util_gethref($baseurl = '', $args = array(), $ashtml = true, $sep = '&') {
1651 $rv = $baseurl? $baseurl : getStringFromServer('PHP_SELF');
1653 foreach ($args as $k => $v) {
1657 $rv .= $pfx.urlencode($k).'='.urlencode($v);
1660 return ($ashtml? util_html_encode($rv) : $rv);
1664 * util_sanitise_multiline_submission() – Convert text to ASCII CR-LF
1666 * @param string $text
1667 * input string to sanitise
1669 * sanitised string: CR, LF or CR-LF converted to CR-LF
1671 function util_sanitise_multiline_submission($text) {
1672 /* convert all CR-LF into LF */
1673 $text = preg_replace("/\015+\012+/m", "\012", $text);
1674 /* convert all CR or LF into CR-LF */
1675 $text = preg_replace("/[\012\015]/m", "\015\012", $text);
1680 function util_is_html($string) {
1681 return (strip_tags(util_unconvert_htmlspecialchars($string)) != $string);
1684 function util_init_messages() {
1685 global $feedback, $warning_msg, $error_msg;
1687 if (PHP_SAPI == 'cli') {
1688 $feedback = $warning_msg = $error_msg = '';
1690 $feedback = getStringFromCookie('feedback', '');
1691 if ($feedback) setcookie('feedback', '', time()-3600, '/');
1693 $warning_msg = getStringFromCookie('warning_msg', '');
1694 if ($warning_msg) setcookie('warning_msg', '', time()-3600, '/');
1696 $error_msg = getStringFromCookie('error_msg', '');
1697 if ($error_msg) setcookie('error_msg', '', time()-3600, '/');
1701 function util_save_messages() {
1702 global $feedback, $warning_msg, $error_msg;
1704 setcookie('feedback', $feedback, time() + 10, '/');
1705 setcookie('warning_msg', $warning_msg, time() + 10, '/');
1706 setcookie('error_msg', $error_msg, time() + 10, '/');
1710 * util_create_file_with_contents() — Securely create (or replace) a file with given contents
1712 * @param string $path Path of the file to be created
1713 * @param string $contents Contents of the file
1715 * @return boolean FALSE on error
1717 function util_create_file_with_contents($path, $contents) {
1718 if (file_exists($path) && !unlink($path)) {
1721 $handle = fopen($path, "x+");
1722 if ($handle == false) {
1725 fwrite($handle, $contents);
1731 * Create a directory in the system temp directory with a hard-to-predict name.
1732 * Does not have the guarantees of the actual BSD libc function or Python tempfile function.
1733 * @param string $suffix Append to the new directory's name
1734 * @param string $prefix Prepend to the new directory's name
1735 * @return string The path of the new directory.
1737 * Mostly taken from https://gist.github.com/1407245 as a "temporary"
1738 * workaround to https://bugs.php.net/bug.php?id=49211
1740 function util_mkdtemp($suffix = '', $prefix = 'tmp') {
1741 $tempdir = sys_get_temp_dir();
1742 for ($i=0; $i<5; $i++) {
1743 $id = strtr(base64_encode(util_randbytes(6)), '+/', '-_');
1744 $path = "{$tempdir}/{$prefix}{$id}{$suffix}";
1745 if (mkdir($path, 0700)) {
1753 * Run a function with only the permissions of a given Unix user
1754 * Function can be an anonymous
1755 * Optional arguments in an array
1756 * @param string Unix user name
1757 * @param function function to run (possibly anonymous)
1758 * @param array parameters
1759 * @return boolean true on success, false on error
1761 function util_sudo_effective_user($username, $function, $params=array()) {
1762 $saved_egid = posix_getegid();
1763 $saved_euid = posix_geteuid();
1765 $userinfo = posix_getpwnam($username);
1766 if ($userinfo === False) {
1769 if (posix_setegid($userinfo['gid']) &&
1770 ($saved_euid != 0 || posix_initgroups($username, $userinfo['gid'])) &&
1771 posix_seteuid($userinfo['uid'])) {
1775 posix_setegid($saved_egid);
1776 posix_seteuid($saved_euid);
1777 if ($saved_euid == 0)
1778 posix_initgroups("root", 0);
1783 // c-file-style: "bsd"