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 2010-2012, Thorsten Glaser - Tarent
9 * Copyright 2010-2012, Alain Peyrat - Alcatel-Lucent
10 * Copyright 2013,2016-2018,2021, Franck Villaume - TrivialDev
11 * Copyright 2016, Stéphane-Eymeric Bredthauer - TrivalDev
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 * is_utf8 - utf-8 detection
32 * @param string $str the string to analyze
35 * From http://www.php.net/manual/en/function.mb-detect-encoding.php#85294
37 function is_utf8($str) {
41 for($i=0; $i<$len; $i++){
46 } elseif ($c >= 252) {
48 } elseif ($c >= 248) {
50 } elseif ($c >= 240) {
52 } elseif ($c >= 224) {
54 } elseif ($c >= 192) {
59 if (($i+$bits) > $len) {
65 if ($b < 128 || $b > 191) {
76 * util_strip_unprintable - ???
81 function util_strip_unprintable(&$data) {
82 if (is_array($data)) {
83 foreach ($data as &$value) {
84 util_strip_unprintable($value);
87 $data = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $data);
93 * removeCRLF - remove any Carriage Return-Line Feed from a string.
94 * That function is useful to remove the possibility of a CRLF Injection when sending mail
95 * All the data that we will send should be passed through that function
97 * @param string $str The string that we want to empty from any CRLF
100 function util_remove_CRLF($str) {
101 return strtr($str, "\015\012", ' ');
105 * util_check_fileupload - determines if a filename is appropriate for upload
107 * @param array $filename The uploaded file as returned by getUploadedFile()
110 function util_check_fileupload($filename) {
112 /* Empty file is a valid file.
113 This is because this function should be called
114 unconditionally at the top of submit action processing
115 and many forms have optional file upload. */
116 if ($filename == 'none' || $filename == '') {
120 /* This should be enough... */
121 if (!is_uploaded_file($filename)) {
124 /* ... but we'd rather be paranoid */
125 if (strstr($filename, '..')) {
128 if (!is_file($filename)) {
131 if (!file_exists($filename)) {
134 if ((dirname($filename) != '/tmp') &&
135 (dirname($filename) != "/var/tmp")) {
142 * util_check_url - determines if given URL is valid.
144 * Currently, test is very basic, only the protocol is
145 * checked, allowed values are: http, https, ftp.
147 * @param string $url The URL
148 * @return bool true if valid, false if not valid.
150 function util_check_url($url) {
151 return (preg_match('/^(http|https|ftp):\/\//', $url) > 0);
155 * util_send_message - Send email
156 * This function should be used in place of the PHP mail() function
158 * @param string $to The email recipients address
159 * @param string $subject The email subject
160 * @param string $body The body of the email message
161 * @param string $from The optional email sender address. Defaults to 'noreply@'
162 * @param string $BCC The addresses to blind-carbon-copy this message (comma-separated)
163 * @param string $sendername The optional email sender name. Defaults to ''
164 * @param bool|string $extra_headers
165 * @param bool $send_html_email Whether to send plain text or html email
166 * @param string $CC The addresses to carbon-copy this message (comma-separated)
168 function util_send_message($to, $subject, $body, $from = '', $BCC = '', $sendername = '', $extra_headers = '',
169 $send_html_email = false, $CC = '') {
171 $to = 'noreply@'.forge_get_config('web_host');
174 $from = 'noreply@'.forge_get_config('web_host');
177 $charset = _('UTF-8');
182 $body2 = "Auto-Submitted: auto-generated\n";
183 if ($extra_headers) {
184 $body2 .= $extra_headers."\n";
187 "\nFrom: ".util_encode_mailaddr($from, $sendername, $charset);
188 if (forge_get_config('bcc_all_emails') != '') {
189 $BCC .= ",".forge_get_config('bcc_all_emails');
192 $body2 .= "\nBCC: $BCC";
195 $body2 .= "\nCC: $CC";
197 $send_html_email? $type = "html" : $type = "plain";
198 $body2 .= "\n".util_encode_mimeheader("Subject", $subject, $charset).
199 "\nContent-type: text/$type; charset=$charset".
200 "\nContent-Transfer-Encoding: 8bit".
202 util_convert_body($body, $charset);
204 $handle = popen(forge_get_config('sendmail_path')." -f'$from' -t -i", 'w');
205 fwrite($handle, $body2);
210 * util_encode_mailaddr - Encode email address to MIME format
212 * @param string $email The email address
213 * @param string $name The email's owner name
214 * @param string $charset The converting charset
217 function util_encode_mailaddr($email, $name, $charset) {
218 if (function_exists('mb_convert_encoding') && trim($name) != "") {
219 $name = "=?".$charset."?B?".
220 base64_encode(mb_convert_encoding(
221 $name, $charset, "UTF-8")).
225 return $name." <".$email.">";
229 * util_encode_mimeheader - Encode mimeheader
231 * @param string $headername The name of the header (e.g. "Subject")
232 * @param string $str The email subject
233 * @param string $charset The converting charset (like ISO-2022-JP)
234 * @return string The MIME encoded subject
237 function util_encode_mimeheader($headername, $str, $charset) {
238 if (function_exists('mb_internal_encoding') &&
239 function_exists('mb_encode_mimeheader')) {
240 $x = mb_internal_encoding();
241 mb_internal_encoding("UTF-8");
242 $y = mb_encode_mimeheader($headername.": ".$str,
244 mb_internal_encoding($x);
248 if (!function_exists('mb_convert_encoding')) {
249 return $headername.": ".$str;
252 return $headername.": "."=?".$charset."?B?".
253 base64_encode(mb_convert_encoding(
254 $str, $charset, "UTF-8")).
259 * util_convert_body - Convert body of the email message
261 * @param string $str The body of the email message
262 * @param string $charset The charset of the email message
263 * @return string The converted body of the email message
266 function util_convert_body($str, $charset) {
267 if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
271 return mb_convert_encoding($str, $charset, "UTF-8");
275 * util_handle_message - a convenience wrapper which sends messages
276 * to an email account
278 * @param array $id_arr array of user_id's from the user table
279 * @param string $subject subject of the message
280 * @param string $body the message body
281 * @param string $extra_emails a comma-separated list of email address
282 * @param string $from From header
284 function util_handle_message($id_arr, $subject, $body, $extra_emails = '', $from = '') {
286 if (!empty($id_arr)) {
287 $res = db_query_params('SELECT user_id,email FROM users WHERE user_id = ANY ($1)',
288 array(db_int_array_to_any_clause($id_arr)));
289 $rows = db_numrows($res);
291 for ($i = 0; $i < $rows; $i++) {
292 if (db_result($res, $i, 'user_id') == 100) {
293 // Do not send messages to "Nobody"
296 $address['email'][] = db_result($res,$i,'email');
298 if (isset ($address['email']) && !empty($address['email'])) {
299 $extra_emails = implode($address['email'], ',').','.$extra_emails;
303 util_send_message('', $subject, $body, $from, $extra_emails);
308 * util_unconvert_htmlspecialchars - Unconverts a string converted with htmlspecialchars()
310 * @param string $string The string to unconvert
311 * @return string The unconverted string
314 function util_unconvert_htmlspecialchars($string) {
315 return html_entity_decode($string, ENT_QUOTES, "UTF-8");
319 * util_result_columns_to_assoc - Takes a result set and turns the column pair into an associative array
321 * @param string $result The result set ID
322 * @param int $col_key The column key
323 * @param int $col_val The optional column value
324 * @return array An associative array
327 function util_result_columns_to_assoc($result, $col_key = 0, $col_val = 1) {
329 $rows = db_numrows($result);
332 for ($i = 0; $i < $rows; $i++) {
333 $arr[db_result($result, $i, $col_key)] = db_result($result, $i, $col_val);
340 * util_result_column_to_array - Takes a result set and turns the optional column into an array
342 * @param resource $result The result set
343 * @param int $col The column
347 function &util_result_column_to_array($result, $col = 0) {
349 $rows = db_numrows($result);
352 for ($i = 0; $i < $rows; $i++) {
353 $arr[$i] = db_result($result, $i, $col);
360 * util_line_wrap - Automatically linewrap text
362 * @param string $text The text to wrap
363 * @param int $wrap The number of characters to wrap - Default is 80
364 * @param string $break The line break to use - Default is '\n'
365 * @return string The wrapped text
368 function util_line_wrap($text, $wrap = 80, $break = "\n") {
369 return wordwrap($text, $wrap, $break, false);
373 * util_make_links - Turn URL's into HREF's.
375 * @param string $data The URL
376 * @return mixed|string The HREF'ed URL
379 function util_make_links($data = '') {
384 for ($i = 0; $i < 5; $i++) {
385 $randPattern = rand(10000, 30000);
386 if (!preg_match("/$randPattern/", $data)) {
393 while(preg_match('/<a [^>]*>[^<]*<\/a>/i', $data, $part)) {
395 $data = preg_replace('/<a [^>]*>[^<]*<\/a>/i', $randPattern, $data, 1);
399 while (preg_match('/<a [^>]*>.*<\/a>/siU', $data, $part)) {
401 $data = preg_replace('/<a [^>]*>.*<\/a>/siU', $randPattern, $data, 1);
403 while (preg_match('/<img [^>]*\/>/siU', $data, $part)) {
405 $data = preg_replace('/<img [^>]*\/>/siU', $randPattern, $data, 1);
407 $data = str_replace('>', "\1", $data);
408 $data = preg_replace("#([ \t]|^)www\.#i", " http://www.", $data);
409 $data = preg_replace("#([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]\#?/&=])#i", "<a href=\"\\1://\\2\\3\" target=\"_blank\">\\1://\\2\\3</a>", $data);
410 $data = preg_replace("#([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]<\1]*)([[:alnum:]-]))#i", "\\1<a href=\"mailto:\\2\" target=\"_blank\">\\2</a>", $data);
411 $data = str_replace("\1", '>', $data);
412 for ($i = 0; $i < count($mem); $i++) {
413 $data = preg_replace("/$randPattern/", $mem[$i], $data, 1);
418 $lines = explode("\n", $data);
420 foreach ($lines as $line) {
421 // Do not scan lines if they already have hyperlinks.
422 // Avoid problem with text written with an WYSIWYG HTML editor.
423 if (eregi('<a ([^>]*)>.*</a>', $line, $linePart)) {
424 if (eregi('href="[^"]*"', $linePart[1])) {
430 // Skip </img> tag also
431 if (eregi('<img ([^>]*)/>', $line, $linePart)) {
432 if (eregi('href="[^"]*"', $linePart[1])) {
438 // When we come here, we usually have form input
439 // encoded in entities. Our aim is to NOT include
440 // angle brackets in the URL
441 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
442 $line = str_replace('>', "\1", $line);
443 $line = preg_replace("/([ \t]|^)www\./i", " http://www.", $line);
444 $line = preg_replace("/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
445 "<a href=\"\\1://\\2\\3\" target=\"_blank\">\\1://\\2\\3</a>", $line);
446 $line = preg_replace(
447 "/([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))/i",
448 "\\1<a href=\"mailto:\\2\" target=\"_blank\">\\2</a>",
451 $line = str_replace("\1", '>', $line);
458 * utils_requiredField - Adds the required field marker
460 * @return string A string holding the HTML to mark a required field
462 function utils_requiredField() {
463 return html_e('span', array('class' => 'requiredfield'), '*');
467 * ShowResultSet - Show a generic result set
468 * Very simple, plain way to show a generic result set
470 * @param resource $result The result set ID
471 * @param string $title The title of the result set
472 * @param bool $linkify The option to turn URL's into links
473 * @param bool $displayHeaders The option to display headers
474 * @param array $headerMapping The db field name -> label mapping
475 * @param array $excludedCols Don't display these cols
477 function ShowResultSet($result, $title = '', $linkify = false, $displayHeaders = true, $headerMapping = array(), $excludedCols = array()) {
478 global $group_id, $HTML;
481 $rows = db_numrows($result);
482 $cols = db_numfields($result);
484 echo $HTML->listTableTop();
486 /* Create the headers */
487 $headersCellData = array();
488 $colsToKeep = array();
489 for ($i = 0; $i < $cols; $i++) {
490 $fieldName = db_fieldname($result, $i);
491 if (in_array($fieldName, $excludedCols)) {
495 if (isset($headerMapping[$fieldName])) {
496 if (is_array($headerMapping[$fieldName])) {
497 $headersCellData[] = $headerMapping[$fieldName];
499 $headersCellData[] = array($headerMapping[$fieldName]);
502 $headersCellData[] = array($fieldName);
506 /* Create the title */
507 if (strlen($title) > 0) {
508 $titleCellData = array();
509 $titleCellData[] = array($title, 'colspan' => count($headersCellData));
510 echo $HTML->multiTableRow(array(), $titleCellData, TRUE);
513 /* Display the headers */
514 if ($displayHeaders) {
515 echo $HTML->multiTableRow(array(), $headersCellData, TRUE);
518 /* Create the rows */
519 for ($j = 0; $j < $rows; $j++) {
521 for ($i = 0; $i < $cols; $i++) {
522 if (in_array($i, $colsToKeep)) {
523 if ($linkify && $i == 0) {
524 if ($linkify == "bug_cat") {
525 $linkUrl = util_make_link(getStringFromServer('PHP_SELF').'?group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id'), db_result($result, $j, $i));
526 } elseif ($linkify == "bug_group") {
527 $linkUrl = util_make_link(getStringFromServer('PHP_SELF').'?group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id'), db_result($result, $j, $i));
528 } elseif ($linkify == "patch_cat") {
529 $linkUrl = util_make_link(getStringFromServer('PHP_SELF').'?group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id'), db_result($result, $j, $i));
530 } elseif ($linkify == "support_cat") {
531 $linkUrl = util_make_link(getStringFromServer('PHP_SELF').'?group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id'), db_result($result, $j, $i));
532 } elseif ($linkify == "pm_project") {
533 $linkUrl = util_make_link(getStringFromServer('PHP_SELF').'?group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id'), db_result($result, $j, $i));
535 $linkUrl = db_result($result, $j, $i);
538 $linkUrl = db_result($result, $j, $i);
540 echo '<td>'.$linkUrl.'</td>';
545 echo $HTML->listTableBottom();
552 * validate_email - Validate an email address
554 * @param string $address The address string to validate
555 * @return bool true on success/false on error
558 function validate_email($address) {
559 if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
566 * validate_emails - Validate a list of e-mail addresses
568 * @param string $addresses E-mail list
569 * @param string $separator Separator
570 * @return array Array of invalid e-mail addresses (if empty, all addresses are OK)
572 function validate_emails($addresses, $separator = ',') {
573 if (strlen($addresses) == 0) {
576 $emails = explode($separator, $addresses);
579 if (is_array($emails)) {
580 foreach ($emails as $email) {
581 $email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
582 if (!validate_email($email)) {
591 * util_is_valid_filename - Verifies whether a file has a valid filename
593 * @param string $file The file to verify
594 * @return bool true on success/false on error
597 function util_is_valid_filename($file) {
599 $invalidchars = preg_replace("/[-A-Z0-9+_\. ~]/i", "", $file);
601 if (!empty($invalidchars)) {
604 if (strstr($file, '..')) {
613 * util_is_valid_repository_name - Verifies whether a repository name is valid
615 * @param string $file name to verify
616 * @return bool true on success/false on error
619 function util_is_valid_repository_name ($file) {
621 $invalidchars = preg_replace("/[-A-Z0-9+_\.]/i","",$file);
623 if (!empty($invalidchars)) {
626 if (strstr($file,'..')) {
633 * valid_hostname - Validates a hostname string to make sure it doesn't contain invalid characters
635 * @param string $hostname The optional hostname string
636 * @return bool true on success/false on failure
639 function valid_hostname($hostname = "xyz") {
642 $invalidchars = preg_replace("/[-A-Z0-9\.]/i", "", $hostname);
644 if (!empty($invalidchars)) {
648 //double dot, starts with a . or -
649 if (preg_match("/\.\./", $hostname) || preg_match("/^\./", $hostname) || preg_match("/^\-/", $hostname)) {
653 $multipoint = explode(".", $hostname);
655 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {
665 * human_readable_bytes - Translates an integer representing bytes to a human-readable format.
667 * Format file size in a human-readable way
668 * such as "xx Megabytes" or "xx Mo"
670 * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com>
673 * @param int $bytes is the size
674 * @param bool $base10 enable base 10 representation, otherwise default base 2 is used
675 * @param int $round number of fractional digits
678 function human_readable_bytes($bytes, $base10 = false, $round = 0) {
683 return "-".human_readable_bytes(-$bytes, $base10, $round);
686 $labels = array(_('bytes'), _('kB'), _('MB'), _('GB'), _('TB'));
690 $labels = array(_('bytes'), _('KiB'), _('MiB'), _('GiB'), _('TiB'));
694 $log = (int)(log10($bytes)/log10($base));
696 foreach ($labels as $p => $lab) {
701 if ($lab != _("bytes") and $lab != _("kB") and $lab != _("KiB")) {
704 $text = round($bytes/pow($base, $pow), $round)." ".$lab;
711 * ls - lists a specified directory and returns an array of files
712 * @param string $dir the path of the directory to list
713 * @param bool $filter whether to filter out directories and illegal filenames
714 * @param string|bool $regex filter filename based on this regex
715 * @return array array of file names.
717 function &ls($dir, $filter = false, $regex = false) {
720 if (is_dir($dir) && ($h = opendir($dir))) {
721 while (($f = readdir($h)) !== false) {
726 if (!util_is_valid_filename($f) || !is_file($dir."/".$f)) {
730 if ($regex !== false) {
731 if (!preg_match($regex, $f)) {
743 * readfile_chunked - replacement for readfile
745 * @param string $filename The file path
746 * @param bool $returnBytes Whether to return bytes served or just a bool
749 function readfile_chunked($filename, $returnBytes = true) {
750 $chunksize = 1*(1024*1024); // 1MB chunks
754 $handle = fopen($filename, 'rb');
755 if ($handle === false) {
760 while (!feof($handle)) {
761 $buffer = fread($handle, $chunksize);
766 $byteCounter += strlen($buffer);
770 $status = fclose($handle);
771 if ($returnBytes && $status) {
772 return $byteCounter; // return num. bytes delivered like readfile() does.
778 * util_is_root_dir - Checks if a directory points to the root dir
780 * @param string $dir Directory
783 function util_is_root_dir($dir) {
784 return !preg_match('/[^\\/]/', $dir);
788 * util_is_dot_or_dotdot - Checks if a directory points to . or ..
790 * @param string $dir Directory
793 function util_is_dot_or_dotdot($dir) {
794 return preg_match('/^\.\.?$/', trim($dir, '/'));
798 * util_containts_dot_or_dotdot - Checks if a directory containts . or ..
800 * @param string $dir Directory
803 function util_containts_dot_or_dotdot($dir) {
804 foreach (explode('/', $dir) as $sub_dir) {
805 if (util_is_dot_or_dotdot($sub_dir)) {
813 * util_secure_filename - Returns a secured file name
815 * @param string $file Filename
816 * @return string Filename
818 function util_secure_filename($file) {
819 $f = preg_replace("/[^-A-Z0-9_\.]/i", '', $file);
820 if (util_containts_dot_or_dotdot($f)) {
821 $f = preg_replace("/\./", '_', $f);
830 * util_strip_accents - Remove accents from given text.
832 * @param string $text Text
835 function util_strip_accents($text) {
836 $find = utf8_decode($text);
838 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
839 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
840 return utf8_encode($find);
844 * normalized_urlprefix - Constructs the forge's URL prefix out of forge_get_config('url_prefix')
848 function normalized_urlprefix() {
849 $prefix = forge_get_config('url_prefix');
850 $prefix = preg_replace("/^\//", "", $prefix);
851 $prefix = preg_replace("/\/$/", "", $prefix);
852 $prefix = "/$prefix/";
853 if ($prefix == '//') {
860 * util_url_prefix - Return URL prefix (http:// or https://)
862 * @param string $prefix (optional) : 'http' or 'https' to force it
863 * @return string URL prefix
865 function util_url_prefix($prefix = '') {
866 if ($prefix == 'http' || $prefix == 'https' ) {
867 return $prefix . '://';
869 if (forge_get_config('use_ssl')) {
878 * util_make_base_url - Construct the base URL http[s]://forge_name[:port]
880 * @param string $prefix (optional) : 'http' or 'https' to force it
881 * @return string base URL
883 function util_make_base_url($prefix = '') {
884 $url = util_url_prefix($prefix);
885 $url .= forge_get_config('web_host');
886 if (forge_get_config('use_ssl')) {
887 if (forge_get_config('https_port') && (forge_get_config('https_port') != 443)) {
888 $url .= ":".forge_get_config('https_port');
891 if (forge_get_config('http_port') && (forge_get_config('http_port') != 80)) {
892 $url .= ":".forge_get_config('http_port');
899 * util_make_url - Construct full URL from a relative path
901 * @param string $path (optional)
902 * @param string $prefix (optional) : 'http' or 'https' to force it
905 function util_make_url($path = '', $prefix = '') {
906 return util_make_base_url($prefix).util_make_uri($path);
910 * util_find_relative_referer - Find the relative URL from full URL, removing http[s]://forge_name[:port]
912 * @param string $url URL
915 function util_find_relative_referer($url) {
916 return str_replace(util_make_base_url().normalized_urlprefix(), '', $url);
920 * util_make_uri - Construct proper (relative) URI (prepending prefix)
922 * @param string $path
925 function util_make_uri($path) {
926 $path = preg_replace('/^\//', '', $path);
927 $uri = normalized_urlprefix();
933 * util_make_link - Construct proper URL/URI from path & text
935 * @param string $path
936 * @param string $text
937 * @param array|bool $extra_params
938 * @param bool $absolute
941 function util_make_link($path, $text, $extra_params = false, $absolute = false) {
942 global $use_tooltips;
944 if (is_array($extra_params)) {
945 foreach ($extra_params as $key => $value) {
946 if ($key != 'title') {
947 $attrs[$key] = $value;
949 if ($key == 'title' && $use_tooltips) {
950 $attrs[$key] = $value;
955 $attrs['href'] = $path;
957 $attrs['href'] = util_make_uri($path);
959 return html_e('a', $attrs, $text, true, false);
963 * util_make_link_u - Create an HTML link to a user's profile page
965 * @param string $username
966 * @param int $user_id
967 * @param string $text
970 function util_make_link_u($username, $user_id, $text) {
971 return util_make_link(util_make_url_u($username), $text, false, true);
975 * util_display_user - Display username with link to a user's profile page
976 * and icon face if possible.
978 * @param string $username
979 * @param int $user_id
980 * @param string $text
981 * @param string $size
984 function util_display_user($username, $user_id = 0, $text = '', $size = 'xs') {
985 $user = user_get_object_by_name($username);
986 if (!$user || !is_object($user) || $user->isError() || !$user->isActive()) {
989 if (forge_get_config('restrict_users_visibility')) {
990 if (!session_loggedin()) {
994 $u2gl = $user->getGroupIds();
996 foreach ($u2gl as $u2g) {
997 if (forge_check_perm('project_read', $u2g)) {
1002 if ($seen == false) {
1007 // Invoke user_link_with_tooltip plugin
1008 $hook_params = array('resource_type' => 'user', 'username' => $username, 'user_id' => $user_id, 'size' => $size, 'link_text' => $text, 'user_link' => '');
1009 plugin_hook_by_reference('user_link_with_tooltip', $hook_params);
1010 if ($hook_params['user_link'] != '') {
1011 return html_e('div', array('class' => 'box'), $hook_params['user_link']);
1014 // If no plugin replaced it, then back to default standard link
1016 // Invoke user_logo plugin (see gravatar plugin for instance)
1017 $params = array('user_id' => $user_id, 'size' => $size, 'content' => '');
1018 plugin_hook_by_reference('user_logo', $params);
1020 $url = util_make_link_u($username, $user_id, $text);
1021 if ($params['content']) {
1022 return html_e('div', array('class' => 'box'), $params['content'].' '.$url);
1028 * util_make_url_u - Create URL for user's profile page
1030 * @param string $username
1031 * @return string URL
1033 function util_make_url_u($username) {
1034 return util_make_uri('/users/'.$username.'/');
1038 * util_make_link_g - Create a HTML link to a project's page
1040 * @param string $group_name
1041 * @param int $group_id
1042 * @param string $text
1045 function util_make_link_g($group_name, $group_id, $text) {
1046 $hook_params = array();
1047 $hook_params['resource_type'] = 'group';
1048 $hook_params['group_name'] = $group_name;
1049 $hook_params['group_id'] = $group_id;
1050 $hook_params['link_text'] = $text;
1051 $hook_params['group_link'] = '';
1052 plugin_hook_by_reference('project_link_with_tooltip', $hook_params);
1053 if ($hook_params['group_link'] != '') {
1054 return $hook_params['group_link'];
1057 return html_e('a', array('href' => util_make_url_g($group_name, $group_id)), $text, true);
1061 * util_make_url_g - Create URL for a project's page
1063 * @param string $group_name
1064 * @param int $group_id
1067 function util_make_url_g($group_name, $group_id) {
1068 return util_make_uri('/projects/'.$group_name.'/');
1071 function util_ensure_value_in_set($value, $set) {
1072 if (in_array($value, $set)) {
1080 * check_email_available - ???
1082 * @param Group $group
1083 * @param string $email
1084 * @param string $response
1087 function check_email_available($group, $email, &$response) {
1088 // Check if a mailing list with same name already exists
1089 if ($group->usesMail()) {
1090 $mlFactory = new MailingListFactory($group);
1091 if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
1092 $response .= $mlFactory->getErrorMessage();
1095 $mlArray = $mlFactory->getMailingLists();
1096 if ($mlFactory->isError()) {
1097 $response .= $mlFactory->getErrorMessage();
1100 for ($j = 0; $j < count($mlArray); $j++) {
1101 $currentList =& $mlArray[$j];
1102 if ($email == $currentList->getName()) {
1103 $response .= _('Error: a mailing list with the same email address already exists.');
1109 // Check if a forum with same name already exists
1110 if ($group->usesForum()) {
1111 $ff = new ForumFactory($group);
1112 if (!$ff || !is_object($ff) || $ff->isError()) {
1113 $response .= $ff->getErrorMessage();
1116 $farr = $ff->getForums();
1117 $prefix = $group->getUnixName().'-';
1118 for ($j = 0; $j < count($farr); $j++) {
1119 if (is_object($farr[$j])) {
1120 if ($email == $prefix.$farr[$j]->getName()) {
1121 $response .= _('Error: a forum with the same email address already exists.');
1128 // Email is available
1133 * Adds the Javascript file to the list to be used
1136 function use_javascript($js) {
1137 return $GLOBALS['HTML']->addJavascript($js);
1140 function use_stylesheet($css, $media = '') {
1141 return $GLOBALS['HTML']->addStylesheet($css, $media);
1144 /* returns an integer from http://forge/foo/bar.php/123 or false */
1145 function util_path_info_last_numeric_component() {
1146 if (!isset($_SERVER['PATH_INFO'])) {
1150 foreach (str_split($_SERVER['PATH_INFO']) as $x) {
1154 } elseif ($ok == false) {
1155 /* need reset using slash */
1156 } elseif ((ord($x) >= 48) && (ord($x) <= 57)) {
1157 $rv = $rv * 10 + ord($x) - 48;
1168 function get_cvs_binary_version() {
1169 $string = `cvs --version 2>/dev/null | grep ^Concurrent.Versions.System.*client/server`;
1170 if (preg_match('/^Concurrent Versions System .CVS. 1.11.[0-9]*/', $string)) {
1172 } elseif (preg_match('/^Concurrent Versions System .CVS. 1.12.[0-9]*/', $string)) {
1179 /* get a backtrace as string */
1180 function debug_string_backtrace() {
1182 debug_print_backtrace();
1183 $trace = ob_get_contents();
1186 // Remove first item from backtrace as it's this function
1187 // which is redundant.
1188 $trace = preg_replace('/^#0\s+'.__FUNCTION__."[^\n]*\n/", '', $trace, 1);
1190 // Renumber backtrace items.
1191 $trace = preg_replace_callback('/^#(\d+)/m', function($m) { return '#' . (ltrim($m[0], '#') - 1); }, $trace);
1196 function util_ini_get_bytes($id) {
1197 $val = substr(trim(ini_get($id)), 0, -1);
1198 $last = strtolower($val[strlen($val)-1]);
1210 function util_get_maxuploadfilesize() {
1211 $postmax = util_ini_get_bytes('post_max_size');
1212 $maxfile = util_ini_get_bytes('upload_max_filesize');
1214 return min($postmax, $maxfile);
1217 function util_get_compressed_file_extension() {
1218 $m = forge_get_config('compression_method');
1219 if (preg_match('/^gzip\b/', $m)) {
1221 } elseif (preg_match('/^bzip2\b/', $m)) {
1223 } elseif (preg_match('/^lzma\b/', $m)) {
1225 } elseif (preg_match('/^xz\b/', $m)) {
1227 } elseif (preg_match('/^cat\b/', $m)) {
1230 return '.compressed';
1235 * return $1 if $1 is set, ${2:-false} otherwise
1237 * Shortcomings: may create $$val = NULL in the
1238 * current namespace; see the (rejected – but
1239 * then, with PHP, you know where you stand…)
1240 * https://wiki.php.net/rfc/ifsetor#userland_2
1241 * proposal for details and a (rejected) fix.
1243 * Do not use this function if $val is “magic”,
1244 * for example, an overloaded \ArrayAccess.
1247 * @param bool $default
1250 function util_ifsetor(&$val, $default = false) {
1251 return (isset($val) ? $val : $default);
1254 function util_randbytes($num = 6) {
1257 // Let's try /dev/urandom first
1258 $f = @fopen("/dev/urandom", "rb");
1260 $b .= @fread($f, $num);
1264 // Hm. No /dev/urandom? Try /dev/random.
1265 if (strlen($b) < $num) {
1266 $f = @fopen("/dev/random", "rb");
1268 $b .= @fread($f, $num);
1273 // Still no luck? Fall back to PHP's built-in PRNG
1274 while (strlen($b) < $num) {
1275 $b .= uniqid(mt_rand(), true);
1278 $b = substr($b, 0, $num);
1282 /* maximum: 2^31 - 1 due to PHP weakness */
1283 function util_randnum($min = 0, $max = 32767) {
1284 $ta = unpack("L", util_randbytes(4));
1285 $n = $ta[1] & 0x7FFFFFFF;
1286 $v = $n % (1 + $max - $min);
1290 /* convert '\n' to <br /> or </p><p> */
1291 function util_pwrap($encoded_string) {
1292 return str_replace("<p></p>", "",
1293 str_replace("<br /></p>", "</p>",
1294 str_replace("<p><br />", "<p>",
1295 "<p>".str_replace("<br /><br />", "</p><p>",
1296 implode("<br />", explode("\n",
1297 $encoded_string)))."</p>")));
1300 /* takes a string and returns it HTML encoded, URIs made to hrefs */
1301 function util_uri_grabber($unencoded_string, $tryaidtid = false) {
1302 /* escape all ^A and ^B as ^BX^B and ^BY^B, respectively */
1303 $s = str_replace("\x01", "\x02X\x02", str_replace("\x02", "\x02Y\x02",
1304 $unencoded_string));
1305 /* replace all URIs with ^AURI^A */
1307 '|([a-zA-Z][a-zA-Z0-9+.-]*:[#0-9a-zA-Z;/?:@&=+$,_.!~*\'()%-]+)|',
1310 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1312 /* encode the string */
1313 $s = htmlentities($s, ENT_QUOTES, "UTF-8");
1314 /* convert 「^Afoo^A」 to 「<a href="foo">foo</a>」 */
1315 $s = preg_replace('|\x01([^\x01]+)\x01|',
1316 '<a href="$1">$1</a>', $s);
1318 return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
1320 // /* convert [#123] to links if found */
1322 // $s = util_tasktracker_links($s);
1323 /* convert ^BX^B and ^BY^B back to ^A and ^B, respectively */
1324 $s = str_replace("\x02Y\x02", "\x02", str_replace("\x02X\x02", "\x01",
1326 /* return the final result */
1330 function util_html_encode($s) {
1331 return htmlspecialchars($s, ENT_QUOTES, "UTF-8");
1334 /* secure a (possibly already HTML encoded) string */
1335 function util_html_secure($s) {
1336 return util_html_encode(util_unconvert_htmlspecialchars($s));
1339 /* return integral value (ℕ₀) of passed string if it matches, or false */
1340 function util_nat0(&$s) {
1342 /* unset variable */
1346 if (count($s) == 1) {
1347 /* one-element array */
1348 return util_nat0($s[0]);
1350 /* not one element, or element not at [0] */
1353 if (!is_numeric($s)) {
1359 /* number element of ℕ₀ */
1360 $text = (string)$num;
1362 /* number matches its textual representation */
1365 /* doesn't match, like 0123 or 1.2 or " 1" */
1372 * util_negociate_alternate_content_types() - Manage content-type negociation based on 'script_accepted_types' hooks
1373 * @param string $script
1374 * @param string $default_content_type
1375 * @param string|bool $forced_content_type
1378 function util_negociate_alternate_content_types($script, $default_content_type, $forced_content_type=false) {
1380 $content_type = $default_content_type;
1382 // we can force the content-type to be returned automatically if necessary
1383 if ($forced_content_type) {
1384 // TODO ideally, in this case we could try and apply the negociation to see if it matches
1385 // one provided by the hooks, but negotiateMimeType() doesn't allow this so for the moment,
1386 // we just force it whatever the hooks support
1387 $content_type = $forced_content_type;
1389 // Invoke plugins' hooks 'script_accepted_types' to discover which alternate content types they would accept for /users/...
1390 $hook_params = array();
1391 $hook_params['script'] = $script;
1392 $hook_params['accepted_types'] = array();
1394 plugin_hook_by_reference('script_accepted_types', $hook_params);
1396 if (count($hook_params['accepted_types'])) {
1397 // By default, text/html is accepted
1398 $accepted_types = array($default_content_type);
1399 $new_accepted_types = $hook_params['accepted_types'];
1400 $accepted_types = array_merge($accepted_types, $new_accepted_types);
1402 // PEAR::HTTP (for negotiateMimeType())
1403 require_once 'HTTP.php';
1405 // negociate accepted content-type depending on the preferred ones declared by client
1407 $content_type = $http->negotiateMimeType($accepted_types, false);
1410 return $content_type;
1414 * util_gethref() - Construct a hypertext reference
1416 * @param string $baseurl
1417 * (optional) base URL (absolute or relative);
1418 * urlencoded, but not htmlencoded
1419 * (default (falsy): PHP_SELF)
1420 * @param array $args
1421 * (optional) associative array of unencoded query parameters;
1422 * false values are ignored
1423 * @param bool $ashtml
1424 * (optional) htmlencode the result?
1426 * @param string $sep
1427 * (optional) argument separator ('&' or ';')
1429 * @return string URL, possibly htmlencoded
1431 function util_gethref($baseurl = '', $args = array(), $ashtml = true, $sep = '&') {
1432 $rv = $baseurl? $baseurl : getStringFromServer('PHP_SELF');
1434 foreach ($args as $k => $v) {
1438 $rv .= $pfx.urlencode($k).'='.urlencode($v);
1441 return ($ashtml? util_html_encode($rv) : $rv);
1445 * util_sanitise_multiline_submission() – Convert text to ASCII CR-LF
1447 * @param string $text
1448 * input string to sanitise
1450 * sanitised string: CR, LF or CR-LF converted to CR-LF
1452 function util_sanitise_multiline_submission($text) {
1453 /* convert all CR-LF into LF */
1454 $text = preg_replace("/\015+\012+/m", "\012", $text);
1455 /* convert all CR or LF into CR-LF */
1456 $text = preg_replace("/[\012\015]/m", "\015\012", $text);
1461 function util_is_html($string) {
1462 return (strip_tags(util_unconvert_htmlspecialchars($string)) != $string);
1465 function util_init_messages() {
1466 global $feedback, $warning_msg, $error_msg;
1468 if (PHP_SAPI == 'cli' || !forge_get_config('use_ssl') || !session_issecure()) {
1469 $feedback = $warning_msg = $error_msg = '';
1471 $feedback = getStringFromCookie('feedback', '');
1473 setcookie('feedback', '', time()-3600, '/', '', forge_get_config('use_ssl'), true);
1476 $warning_msg = getStringFromCookie('warning_msg', '');
1478 setcookie('warning_msg', '', time()-3600, '/', '', forge_get_config('use_ssl'), true);
1481 $error_msg = getStringFromCookie('error_msg', '');
1483 setcookie('error_msg', '', time()-3600, '/', '', forge_get_config('use_ssl'), true);
1488 function util_save_messages() {
1489 global $feedback, $warning_msg, $error_msg;
1491 setcookie('feedback', $feedback, time() + 10, '/', '', forge_get_config('use_ssl'), true);
1492 setcookie('warning_msg', $warning_msg, time() + 10, '/', '', forge_get_config('use_ssl'), true);
1493 setcookie('error_msg', $error_msg, time() + 10, '/', '', forge_get_config('use_ssl'), true);
1497 * util_create_file_with_contents() — Securely create (or replace) a file with given contents
1499 * @param string $path Path of the file to be created
1500 * @param string $contents Contents of the file
1502 * @return bool false on error
1504 function util_create_file_with_contents($path, $contents) {
1505 if (file_exists($path) && !unlink($path)) {
1508 $handle = fopen($path, "x+");
1509 if ($handle == false) {
1512 fwrite($handle, $contents);
1518 * Create a directory in the system temp directory with a hard-to-predict name.
1519 * Does not have the guarantees of the actual BSD libc function or Python tempfile function.
1520 * @param string $suffix Append to the new directory's name
1521 * @param string $prefix Prepend to the new directory's name
1522 * @return string The path of the new directory.
1524 * Mostly taken from https://gist.github.com/1407245 as a "temporary"
1525 * workaround to https://bugs.php.net/bug.php?id=49211
1527 function util_mkdtemp($suffix = '', $prefix = 'tmp') {
1528 $tempdir = sys_get_temp_dir();
1529 for ($i=0; $i<5; $i++) {
1530 $id = strtr(base64_encode(util_randbytes(6)), '+/', '-_');
1531 $path = "{$tempdir}/{$prefix}{$id}{$suffix}";
1532 if (mkdir($path, 0700)) {
1540 * Run a function with only the permissions of a given Unix user
1541 * Function can be an anonymous
1542 * Used to rely on posix_seteuid, but standard Bash reverts euid=uid,
1543 * cf. Debian patch "privmode.diff", so using fork&exec
1544 * Optional arguments in an array
1545 * @param string $username Unix user name
1546 * @param function $function function to run (possibly anonymous)
1547 * @param array $params parameters
1548 * @return bool true on success, false on error
1550 function util_sudo_effective_user($username, $function, $params=array()) {
1551 $userinfo = posix_getpwnam($username);
1552 if ($userinfo === false) {
1556 $pid = pcntl_fork();
1561 pcntl_waitpid($pid, $status);
1563 if (posix_setgid($userinfo['gid']) &&
1564 posix_initgroups($username, $userinfo['gid']) &&
1565 posix_setuid($userinfo['uid'])) {
1566 putenv('HOME='.$userinfo['dir']);
1567 call_user_func($function, $params);
1569 //exit(1); // too nice, PHP gracefully quits and closes DB connection
1570 posix_kill(posix_getpid(), 9);
1575 function getselfhref($p = array(), $return_encoded = true) {
1576 global $group_id, $atid, $aid, $is_add;
1577 $p['group_id'] = $group_id;
1582 $p['artifact_id'] = $aid;
1584 return util_gethref(false, $p, $return_encoded);
1588 * getThemeIdFromName()
1590 * @param string $dirname the dirname of the theme
1591 * @return int the theme id
1593 function getThemeIdFromName($dirname) {
1594 $res = db_query_params ('SELECT theme_id FROM themes WHERE dirname=$1',
1596 return db_result($res,0,'theme_id');
1600 * utils_headers_download() - Generate attachment download headers, with security checks around the MIME type
1602 * @param string $filename
1603 * @param string $mimetype
1606 function utils_headers_download($filename, $mimetype, $size) {
1607 /* SECURITY: do not serve content with JavaScript execution (and e.g. cookie theft) */
1608 /* Namely do NOT include: text/html, image/svg+xml, application/pdf... */
1609 /* https://grepular.com/Scalable_Vector_Graphics_and_XSS */
1610 /* https://lists.wikimedia.org/pipermail/mediawiki-announce/2015-March/000175.html */
1611 /* https://www.owasp.org/images/a/ac/PDF_XSS_vulnerability.pdf */
1612 /* https://groups.google.com/forum/#!topic/mozilla.dev.pdf-js/Fyl5RnaUWVc */
1613 /* (PDF theoretically supports JS, not sure how pdf.js deals with that) */
1614 $authorized_inline = ',^(text/plain|image/png|image/jpe?g|image/gif)$,';
1615 /* Disarm XSS-able text/html, and inline common text files (*.c, *.pl...) */
1616 $force_text_plain = ',^(text/html|text/.*|application/x-perl|application/x-ruby)$,';
1618 if (preg_match($force_text_plain, $mimetype)) {
1619 $mimetype = 'text/plain';
1621 if (preg_match($authorized_inline, $mimetype)) {
1622 header('Content-Disposition: inline; filename="' . str_replace('"', '', $filename) . '"');
1623 header('Content-Type: '. $mimetype);
1625 header('Content-Disposition: attachment; filename="' . str_replace('"', '', $filename) . '"');
1626 header('Content-Type: '. $mimetype);
1628 header('Content-Length: ' . $size);
1630 /* Also, make sure browsers such as IE8 don't interpret a non text/html attachment as HTML... */
1631 /* https://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx?Redirected=true */
1632 /* IE6 ignores this, but IE6 users have higher security concerns than this.. */
1633 header('X-Content-Type-Options: nosniff');
1636 function compareObjectName ($a, $b) {
1637 return strcoll($a->getName(),$b->getName()) ;
1641 * compute the differences between two arrays //TODO: looks like array_udiff
1642 * @param array $tab1
1643 * @param array $tab2
1646 function utils_array_diff_names($tab1, $tab2) {
1649 foreach($tab1 as $e1) {
1652 foreach($tab2 as $e2) {
1653 $found = !count(array_diff($e1, $e2));
1666 // c-file-style: "bsd"