* FusionForge miscellaneous utils
*
* Copyright 1999-2001, VA Linux Systems, Inc.
- * Copyright 2009-2010, Roland Mas, Franck Villaume
+ * Copyright 2009-2011, Roland Mas
+ * Copyright 2009-2011, Franck Villaume - Capgemini
+ * Copyright (c) 2010, 2011
+ * Thorsten Glaser <t.glaser@tarent.de>
+ * Copyright 2010-2011, Alain Peyrat - Alcatel-Lucent
*
- * This file is part of FusionForge.
+ * This file is part of FusionForge. FusionForge is free software;
+ * you can redistribute it and/or modify it under the terms of the
+ * GNU General Public License as published by the Free Software
+ * Foundation; either version 2 of the Licence, or (at your option)
+ * any later version.
*
- * FusionForge is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published
- * by the Free Software Foundation; either version 2 of the License,
- * or (at your option) any later version.
- *
- * FusionForge is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
+ * FusionForge is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
*
- * You should have received a copy of the GNU General Public License
- * along with FusionForge; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- * USA
+ * You should have received a copy of the GNU General Public License along
+ * with FusionForge; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
return "$"."apr1"."$".$salt."$".$tmp;
}
-
+
/**
* is_utf8($string) - utf-8 detection
*
return true;
}
+function util_strip_unprintable(&$data) {
+ if (is_array($data)) {
+ foreach ($data as $key => &$value) {
+ util_strip_unprintable($value);
+ }
+ }
+ else {
+ $data = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $data);
+ }
+ return $data;
+}
+
/**
- * removeCRLF() - remove any Carriage Return-Line Feed from a string.
+ * removeCRLF() - remove any Carriage Return-Line Feed from a string.
* That function is useful to remove the possibility of a CRLF Injection when sending mail
* All the data that we will send should be passed through that function
*
- * @param string The string that we want to empty from any CRLF
+ * @param string The string that we want to empty from any CRLF
*/
function util_remove_CRLF($str) {
return strtr($str, "\015\012", ' ');
if (!$from) {
$from='noreply@'.forge_get_config('web_host');
}
-
+
$charset = _('UTF-8');
if (!$charset) {
"\nContent-type: text/$type; charset=$charset".
"\n\n".
util_convert_body($body, $charset);
-
+
if (!forge_get_config('sendmail_path')){
$sys_sendmail_path="/usr/sbin/sendmail";
}
$name,$charset,"UTF-8")).
"?=";
}
-
+
return $name." <".$email."> ";
}
if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
return $str;
}
-
+
return mb_convert_encoding($str,$charset,"UTF-8");
}
/**
* util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
- * This function requires PHP 4.0.3 or greater
*
* @param string The string to unconvert
* @returns The unconverted string
if ($code <= 0x7F ||
$code >= 0xC0) {
//Here is single byte character
- //or head of multi byte character
+ //or head of multi byte character
return $wrap;
}
//Do not break multi byte character
* @returns The HREF'ed URL
*
*/
-function util_make_links ($data='') {
- if(empty($data)) {
- return $data;
+function util_make_links($data='') {
+ if(empty($data)) {
+ return $data;
}
- $lines = split("\n",$data);
+ $lines = explode("\n", $data);
$newText = "";
- while ( list ($key,$line) = each ($lines)) {
+ while ( list ($key, $line) = each ($lines)) {
// When we come here, we usually have form input
// encoded in entities. Our aim is to NOT include
// angle brackets in the URL
// (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
$line = str_replace('>', "\1", $line);
- $line = eregi_replace("([ \t]|^)www\."," http://www.",$line);
- $text = eregi_replace("([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
- $text = eregi_replace("([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $text);
+ $line = preg_replace( "/([ \t]|^)www\./i", " http://www.", $line);
+ $text = preg_replace( "/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
+ "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
+ $text = preg_replace(
+ "/([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))/i",
+ "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>",
+ $text
+ );
$text = str_replace("\1", '>', $text);
$newText .= $text;
}
* @param array An array of boxes to be pre-checked
*
*/
-function utils_buildcheckboxarray($options,$name,$checked_array) {
- $option_count=count($options);
- $checked_count=count($checked_array);
+function utils_buildcheckboxarray($options, $name, $checked_array) {
+ $option_count = count($options);
+ $checked_count = count($checked_array);
- for ($i=1; $i<=$option_count; $i++) {
+ for ($i = 1; $i <= $option_count; $i++) {
echo '
<br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
- for ($j=0; $j<$checked_count; $j++) {
+ for ($j=0; $j < $checked_count; $j++) {
if ($i == $checked_array[$j]) {
echo ' checked';
}
* Be sure to include HTL_Graphs.php before using this function
*
* @author Tim Perdue tperdue@valinux.com
- * @param int The databse result set ID
- * @param string The title of the graph
+ * @param int The databse result set ID
+ * @param string The title of the graph
*
*/
-Function GraphResult($result,$title) {
- $rows=db_numrows($result);
+function GraphResult($result, $title) {
+ $rows = db_numrows($result);
if ((!$result) || ($rows < 1)) {
echo 'None Found.';
} else {
- $names=array();
- $values=array();
+ $names = array();
+ $values = array();
- for ($j=0; $j<db_numrows($result); $j++) {
+ for ($j=0; $j < db_numrows($result); $j++) {
if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
- $names[$j]= db_result($result, $j, 0);
- $values[$j]= db_result($result, $j, 1);
+ $names[$j] = db_result($result, $j, 0);
+ $values[$j] = db_result($result, $j, 1);
}
}
/*
This is another function detailed below
*/
- GraphIt($names,$values,$title);
+ GraphIt($names, $values, $title);
}
}
* GraphIt() - Build a graph
*
* @author Tim Perdue tperdue@valinux.com
- * @param array An array of names
- * @param array An array of values
- * @param string The title of the graph
+ * @param array An array of names
+ * @param array An array of values
+ * @param string The title of the graph
*
*/
-Function GraphIt($name_string,$value_string,$title) {
+function GraphIt($name_string, $value_string, $title) {
GLOBAL $HTML;
- $counter=count($name_string);
+ $counter = count($name_string);
/*
Can choose any color you wish
*/
- $bars=array();
+ $bars = array();
for ($i = 0; $i < $counter; $i++) {
- $bars[$i]=$HTML->COLOR_LTBACK1;
+ $bars[$i] = $HTML->COLOR_LTBACK1;
}
- $counter=count($value_string);
+ $counter = count($value_string);
/*
Figure the max_value passed in, so scale can be determined
*/
- $max_value=0;
+ $max_value = 0;
for ($i = 0; $i < $counter; $i++) {
if ($value_string[$i] > $max_value) {
- $max_value=$value_string[$i];
+ $max_value = $value_string[$i];
}
}
if ($max_value < 1) {
- $max_value=1;
+ $max_value = 1;
}
/*
I want my graphs all to be 800 pixels wide, so that is my divisor
*/
- $scale=(400/$max_value);
+ $scale = (400/$max_value);
/*
I create a wrapper table around the graph that holds the title
*/
- $title_arr=array();
- $title_arr[]=$title;
+ $title_arr = array();
+ $title_arr[] = $title;
echo $GLOBALS['HTML']->listTableTop ($title_arr);
echo '<tr><td>';
This is the actual call to the HTML_Graphs class
*/
- html_graph($name_string,$value_string,$bars,$vals);
+ html_graph($name_string, $value_string, $bars, $vals);
echo '
</td></tr>
$headersCellData[] = array($fieldName);
}
}
-
+
/* Create the title */
if(strlen($title) > 0) {
$titleCellData = array();
$titleCellData[] = array($title, 'colspan="'.count($headersCellData).'"');
echo $HTML->multiTableRow('', $titleCellData, TRUE);
}
-
+
/* Display the headers */
if($displayHeaders) {
echo $HTML->multiTableRow('', $headersCellData, TRUE);
*
*/
function validate_email ($address) {
- return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address) !== false);
+ if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
+ if ( filter_var($address, FILTER_VALIDATE_EMAIL) ) {
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+ else {
+ if ( preg_match( "/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\.\/0-9=?A-Z^_`a-z{|}~]+$/", $address) ) {
+ return true;
+ } else {
+ return false;
+ }
+ }
}
/**
* @param char Separator
* @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
*/
-function validate_emails ($addresses, $separator=',') {
+function validate_emails($addresses, $separator=',') {
if (strlen($addresses) == 0) return array();
-
+
$emails = explode($separator, $addresses);
$ret = array();
-
+
if (is_array($emails)) {
foreach ($emails as $email) {
$email = trim($email); // This is done so we can validate lists like "a@b.com, c@d.com"
* @returns true on success/false on error
*
*/
-function util_is_valid_filename ($file) {
+function util_is_valid_filename($file) {
//bad char test
- $invalidchars = eregi_replace("[-A-Z0-9+_\. ~]","",$file);
+ $invalidchars = preg_replace("/[-A-Z0-9+_\. ~]/i","",$file);
if (!empty($invalidchars)) {
return false;
* @returns true on success/false on failur
*
*/
-function valid_hostname ($hostname = "xyz") {
+function valid_hostname($hostname = "xyz") {
//bad char test
- $invalidchars = eregi_replace("[-A-Z0-9\.]","",$hostname);
+ $invalidchars = preg_replace("/[-A-Z0-9\.]/i","",$hostname);
if (!empty($invalidchars)) {
return false;
}
//double dot, starts with a . or -
- if (ereg("\.\.",$hostname) || ereg("^\.",$hostname) || ereg("^\-",$hostname)) {
+ if ( preg_match("/\.\./",$hostname) || preg_match("/^\./",$hostname) || preg_match("/^\-/",$hostname) ) {
return false;
}
* @version 1.0
* @param int bytes is the size
* @param bool base10 enable base 10 representation, otherwise
- * default base 2 is used
+ * default base 2 is used
* @param int round number of fractional digits
* @param array labels strings associated to each 2^10 or
* 10^3(base10==true) multiple of base units
*/
-function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array(' bytes', ' KB', ' MB', ' GB')) {
- if ($bytes <= 0 || !is_array($labels) || (count($labels) <= 0)) {
- return null;
+function human_readable_bytes ($bytes, $base10=false, $round=0, $labels=array()) {
+ if ($bytes == 0) {
+ return "0";
+ }
+ if ($bytes < 0) {
+ return "-" . human_readable_bytes(-$bytes, $base10, $round);
}
- $step = $base10 ? 3 : 10;
- $base = $base10 ? 10 : 2;
+ if ($base10) {
+ $labels = array(_('bytes'), _('kB'), _('MB'), _('GB'), _('TB'));
+ $step = 3;
+ $base = 10;
+ } else {
+ $labels = array(_('bytes'), _('KiB'), _('MiB'), _('GiB'), _('TiB'));
+ $step = 10;
+ $base = 2;
+ }
$log = (int)(log10($bytes)/log10($base));
krsort($labels);
foreach ($labels as $p=>$lab) {
if ($log < $pow) {
continue;
}
- if ($lab == " MB" or $lab == " GB") {
+ if ($lab != _("bytes") and $lab != _("kB") and $lab != _("KiB")) {
$round = 2;
}
- $text = round($bytes/pow($base,$pow),$round).$lab;
+ $text = round($bytes/pow($base,$pow),$round) . " " . $lab;
break;
}
return $text;
* @return array array of file names.
*/
function &ls($dir,$filter=false) {
- if (!is_dir ($dir)) {
- $out = array () ;
- return $out ;
- }
- exec('ls -c1 '.$dir,$out);
- if ($filter) {
- for ($i=0; $i<count($out); $i++) {
- if (util_is_valid_filename($out[$i]) && is_file($dir.'/'.$out[$i])) {
- $filtered[]=$out[$i];
+ $out = array();
+
+ if (is_dir($dir) && ($h = opendir($dir))) {
+ while (($f = readdir($h)) !== false) {
+ if ($f[0] == '.')
+ continue;
+ if ($filter) {
+ if (!util_is_valid_filename($f) ||
+ !is_file($dir . "/" . $f))
+ continue;
}
+ $out[] = $f;
}
- return $filtered;
- } else {
- return $out;
+ closedir($h);
}
+ return $out;
}
/**
$chunksize = 1*(1024*1024); // 1MB chunks
$buffer = '';
$byteCounter = 0;
-
+
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
-
+
ob_start () ;
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
return !preg_match('/[^\\/]/',$dir);
}
+/**
+ * util_is_dot_or_dotdot() - Checks if a directory points to . or ..
+ * @param string Directory
+ * @return bool
+ */
+function util_is_dot_or_dotdot($dir) {
+ return preg_match('/^\.\.?$/',trim($dir, '/'));
+}
+
+/**
+ * util_containts_dot_or_dotdot() - Checks if a directory containts . or ..
+ * @param string Directory
+ * @return bool
+ */
+function util_containts_dot_or_dotdot($dir) {
+ foreach (explode('/', $dir) as $sub_dir) {
+ if (util_is_dot_or_dotdot($sub_dir))
+ return true;
+ }
+
+ return false;
+}
+
+/**
+ * util_secure_filename() - Returns a secured file name
+ * @param string Filename
+ * @return string Filename
+ */
+function util_secure_filename($file) {
+ $f = preg_replace("/[^-A-Z0-9_\.]/i", '', $file);
+ if (util_containts_dot_or_dotdot($f))
+ $f = preg_replace("/\./", '_', $f);
+ if (! $f)
+ $f = md5($file);
+ return $f;
+}
+
+/**
+ * util_strip_accents() - Remove accents from given text.
+ * @param string Text
+ * @return string
+ */
+function util_strip_accents($text) {
+ return iconv ('UTF-8', 'US-ASCII//TRANSLIT', $text) ;
+}
+
/**
* Constructs the forge's URL prefix out of forge_get_config('url_prefix')
- *
+ *
* @return string
*/
-function normalized_urlprefix () {
+function normalized_urlprefix() {
$prefix = forge_get_config('url_prefix') ;
- $prefix = ereg_replace ("^/", "", $prefix) ;
- $prefix = ereg_replace ("/$", "", $prefix) ;
+ $prefix = preg_replace ("/^\//", "", $prefix) ;
+ $prefix = preg_replace ("/\/$/", "", $prefix) ;
$prefix = "/$prefix/" ;
- if ($prefix == '//')
+ if ($prefix == '//')
$prefix = '/' ;
return $prefix ;
}
/**
- * Construct full URL from a relative path
- *
- * @param string $path
- * @return string URL
+ * Construct the base URL http[s]://forge_name[:port]
+ *
+ * @return string base URL
*/
-function util_make_url ($path) {
- if (forge_get_config('use_ssl'))
+function util_make_base_url() {
+ if (forge_get_config('use_ssl')) {
$url = "https://" ;
- else
+ } else {
$url = "http://" ;
-
+ }
$url .= forge_get_config('web_host') ;
- $url .= util_make_uri ($path) ;
- return $url ;
+ if (forge_get_config('https_port') && (forge_get_config('https_port') != 443)) {
+ $url .= ":".forge_get_config('https_port') ;
+ }
+ return $url;
+}
+/**
+ * Construct full URL from a relative path
+ *
+ * @param string $path
+ * @return string URL
+ */
+function util_make_url($path = '') {
+ $url = util_make_base_url().util_make_uri($path) ;
+ return $url;
+}
+
+/**
+ * Find the relative URL from full URL, removing http[s]://forge_name[:port]
+ *
+ * @param string URL
+ */
+function util_find_relative_referer($url) {
+ $relative_url = str_replace(util_make_base_url(), '', $url);
+ //now remove previous feedback, error_msg or warning_msg
+ $relative_url = preg_replace('/&error_msg=.*&/', '&', $relative_url);
+ $relative_url = preg_replace('/&warning_msg=.*&/', '&', $relative_url);
+ $relative_url = preg_replace('/&feedback=.*&/', '&', $relative_url);
+ $relative_url = preg_replace('/&error_msg=.*/', '', $relative_url);
+ $relative_url = preg_replace('/&warning_msg=.*/', '', $relative_url);
+ $relative_url = preg_replace('/&feedback=.*/', '', $relative_url);
+ return $relative_url;
}
/**
* Construct proper (relative) URI (prepending prefix)
- *
+ *
* @param string $path
* @return string URI
*/
-function util_make_uri ($path) {
- $path = ereg_replace ("^/", "", $path) ;
- $uri = normalized_urlprefix () ;
- $uri .= $path ;
- return $uri ;
+function util_make_uri($path) {
+ $path = preg_replace('/^\//', '', $path);
+ $uri = normalized_urlprefix();
+ $uri .= $path;
+ return $uri;
}
-function util_make_link ($path, $text, $extra_params=false, $absolute=false) {
- $ep = '' ;
+function util_make_link($path, $text, $extra_params = false, $absolute = false) {
+ global $use_tooltips;
+ $ep = '';
if (is_array($extra_params)) {
foreach ($extra_params as $key => $value) {
- $ep .= "$key=\"$value\" ";
+ if ($key != 'title') {
+ $ep .= "$key=\"$value\" ";
+ }
+ if ($key == 'title' && $use_tooltips) {
+ $ep .= "$key=\"$value\" ";
+ }
}
}
if ($absolute) {
return '<a ' . $ep . 'href="' . $path . '">' . $text . '</a>' ;
} else {
- return '<a ' . $ep . 'href="' . util_make_url ($path) . '">' . $text . '</a>' ;
+ return '<a ' . $ep . 'href="' . util_make_uri($path) . '">' . $text . '</a>' ;
}
}
/**
* Create an HTML link to a user's profile page
- *
+ *
* @param string $username
* @param int $user_id
* @param string $text
return '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>' ;
}
+/**
+ * Display username with link to a user's profile page
+ * and icon face if possible.
+ *
+ * @param string $username
+ * @param int $user_id
+ * @param string $text
+ * @param string $size
+ * @return string
+ */
+function util_display_user($username, $user_id, $text, $size='xs') {
+ // Invoke user_link_with_tooltip plugin
+ $hook_params = array('resource_type' => 'user', 'username' => $username, 'user_id' => $user_id, 'size' => $size, 'user_link' => '');
+ plugin_hook_by_reference('user_link_with_tooltip', $hook_params);
+ if($hook_params['user_link'] != ''){
+ return $hook_params['user_link'];
+ }
+
+ // If no plugin replaced it, then back to default standard link
+
+ // Invoke user_logo plugin (see gravatar plugin for instance)
+ $params = array('user_id' => $user_id, 'size' => $size, 'content' => '');
+ plugin_hook_by_reference('user_logo', $params);
+
+ $url = '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>';
+ if ($params['content']) {
+ return $params['content'].$url.'<div class="new_line"></div>';
+ }
+ return $url;
+}
+
/**
* Create URL for user's profile page
- *
+ *
* @param string $username
* @param int $user_id
* @return string URL
* @param string $text
* @return string
*/
-function util_make_link_g ($groupame, $group_id,$text) {
- return '<a href="' . util_make_url_g ($groupame, $group_id) . '">' . $text . '</a>' ;
+function util_make_link_g ($groupname, $group_id,$text) {
+ $hook_params =array();
+ $hook_params['resource_type'] = 'group';
+ $hook_params['group_name'] = $groupname;
+ $hook_params['group_id'] = $group_id;
+ $hook_params['link_text'] = $text;
+ $hook_params['group_link'] = '';
+ plugin_hook_by_reference('project_link_with_tooltip', $hook_params);
+ if($hook_params['group_link'] != '') {
+ return $hook_params['group_link'];
+ }
+
+ return '<a href="' . util_make_url_g ($groupname, $group_id) . '">' . $text . '</a>' ;
}
/**
* Create URL for a project's page
- *
+ *
* @param string $groupame
* @param int $group_id
* @return string
$response .= $mlFactory->getErrorMessage();
return false;
}
- $mlArray =& $mlFactory->getMailingLists();
+ $mlArray = $mlFactory->getMailingLists();
if ($mlFactory->isError()) {
$response .= $mlFactory->getErrorMessage();
return false;
return false;
}
}
-
+
// Check if a forum with same name already exists
$ff = new ForumFactory($group);
if (!$ff || !is_object($ff) || $ff->isError()) {
$response .= $ff->getErrorMessage();
return false;
}
- $farr =& $ff->getForums();
+ $farr = $ff->getForums();
$prefix = $group->getUnixName() . '-';
for ($j = 0; $j < count($farr); $j++) {
if (is_object($farr[$j])) {
}
}
}
-
+
// Email is available
return true;
}
+/**
+ * Adds the Javascript file to the lits to be used
+ * @param unknown_type $js
+ */
function use_javascript($js) {
return $GLOBALS['HTML']->addJavascript($js);
}
+function use_stylesheet($css, $media='') {
+ return $GLOBALS['HTML']->addStylesheet($css, $media);
+}
+
// array_replace_recursive only appeared in PHP 5.3.0
if (!function_exists('array_replace_recursive')) {
+ /**
+ * Replaces elements from passed arrays into the first array recursively
+ * @param array $a1 The array in which elements are replaced.
+ * @param array $a2 The array from which elements will be extracted.
+ * @return Returns an array, or NULL if an error occurs.
+ */
function array_replace_recursive ($a1, $a2) {
$result = $a1 ;
!isset ($result[$k]) || !is_array ($result[$k])) {
$result[$k] = $v ;
}
-
+
$result[$k] = array_replace_recursive ($result[$k],
$v) ;
}
}
}
+/* get a backtrace as string */
+function debug_string_backtrace() {
+ ob_start();
+ debug_print_backtrace();
+ $trace = ob_get_contents();
+ ob_end_clean();
+
+ // Remove first item from backtrace as it's this function
+ // which is redundant.
+ $trace = preg_replace('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '',
+ $trace, 1);
+
+ // Renumber backtrace items.
+ $trace = preg_replace('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);
+
+ return $trace;
+}
+
+function util_ini_get_bytes($id) {
+ $val = trim(ini_get($id));
+ $last = strtolower($val[strlen($val)-1]);
+ switch ($last) {
+ case 'g':
+ $val *= 1024;
+ case 'm':
+ $val *= 1024;
+ case 'k':
+ $val *= 1024;
+ }
+ return $val;
+}
+
+function util_get_maxuploadfilesize() {
+ $postmax = util_ini_get_bytes('post_max_size');
+ $maxfile = util_ini_get_bytes('upload_max_filesize');
+
+ $postfile = (int)(($postmax * 3) / 4);
+
+ if ($postfile < $maxfile)
+ $postfile = $maxfile;
+
+ return $postfile;
+}
+
+function util_get_compressed_file_extension() {
+ $m = forge_get_config('compression_method');
+ if (preg_match ('/^gzip\b/', $m)) {
+ return '.gz';
+ } elseif (preg_match ('/^bzip2\b/', $m)) {
+ return '.bzip2';
+ } elseif (preg_match ('/^lzma\b/', $m)) {
+ return '.lzma';
+ } elseif (preg_match ('/^xz\b/', $m)) {
+ return '.xz';
+ } elseif (preg_match ('/^cat\b/', $m)) {
+ return '';
+ } else {
+ return '.compressed';
+ }
+}
+
+/* return $1 if $1 is set, ${2:-false} otherwise */
+function util_ifsetor(&$val, $default = false) {
+ return (isset($val) ? $val : $default);
+}
+
+function util_randbytes($num=6) {
+ $b = '';
+
+ // Let's try /dev/urandom first
+ $f = @fopen("/dev/urandom", "rb");
+ if ($f !== FALSE) {
+ $b .= @fread($f, $num);
+ fclose($f);
+ }
+
+ // Hm. No /dev/urandom? Try /dev/random.
+ if (strlen($b) < $num) {
+ $f = @fopen("/dev/random", "rb");
+ if ($f !== FALSE) {
+ $b .= @fread($f, $num);
+ fclose($f);
+ }
+ }
+
+ // Still no luck? Fall back to PHP's built-in PRNG
+ while (strlen($b) < $num) {
+ $b .= uniqid(mt_rand(), true);
+ }
+
+ $b = substr($b, 0, $num);
+ return ($b);
+}
+
+/* maximum: 2^31 - 1 due to PHP weakness */
+function util_randnum($min=0,$max=32767) {
+ $ta = unpack("L", util_randbytes(4));
+ $n = $ta[1] & 0x7FFFFFFF;
+ $v = $n % (1 + $max - $min);
+ return ($min + $v);
+}
+
+// sys_get_temp_dir() is only available for PHP >= 5.2.1
+if ( !function_exists('sys_get_temp_dir')) {
+ function sys_get_temp_dir() {
+ if ($temp=getenv('TMP')) return $temp;
+ if ($temp=getenv('TEMP')) return $temp;
+ if ($temp=getenv('TMPDIR')) return $temp;
+ return '/tmp';
+ }
+}
+
+/* convert '\n' to <br /> or </p><p> */
+function util_pwrap($encoded_string) {
+ return str_replace("<p></p>", "",
+ str_replace("<br /></p>", "</p>",
+ str_replace("<p><br />", "<p>",
+ "<p>" . str_replace("<br /><br />", "</p><p>",
+ implode("<br />", explode("\n",
+ $encoded_string))) . "</p>")));
+}
+function util_ttwrap($encoded_string) {
+ return str_replace("<p><tt></tt></p>", "",
+ str_replace("<br /></tt></p>", "</tt></p>",
+ str_replace("<p><tt><br />", "<p><tt>",
+ "<p><tt>" . str_replace("<br /><br />", "</tt></p><p><tt>",
+ implode("<br />", explode("\n",
+ encoded_string))) . "</tt></p>")));
+}
+
+/* takes a string and returns it HTML encoded, URIs made to hrefs */
+function util_uri_grabber($unencoded_string, $tryaidtid=false) {
+ /* escape all ^A and ^B as ^BX^B and ^BY^B, respectively */
+ $s = str_replace("\x01", "\x02X\x02", str_replace("\x02", "\x02Y\x02",
+ $unencoded_string));
+ /* replace all URIs with ^AURI^A */
+ $s = preg_replace(
+ '|([a-zA-Z][a-zA-Z0-9+.-]*:[#0-9a-zA-Z;/?:@&=+$,_.!~*\'()%-]+)|',
+ "\x01\$1\x01", $s);
+ if (!$s)
+ return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
+ /* encode the string */
+ $s = htmlentities($s, ENT_QUOTES, "UTF-8");
+ /* convert ć^Afoo^Ać to ć<a href="foo">foo</a>ć */
+ $s = preg_replace('|\x01([^\x01]+)\x01|',
+ '<a href="$1">$1</a>', $s);
+ if (!$s)
+ return htmlentities($unencoded_string, ENT_QUOTES, "UTF-8");
+// /* convert [#123] to links if found */
+// if ($tryaidtid)
+// $s = util_tasktracker_links($s);
+ /* convert ^BX^B and ^BY^B back to ^A and ^B, respectively */
+ $s = str_replace("\x02Y\x02", "\x02", str_replace("\x02X\x02", "\x01",
+ $s));
+ /* return the final result */
+ return $s;
+}
+
+/* secure a (possibly already HTML encoded) string */
+function util_html_secure($s) {
+ return htmlentities(html_entity_decode($s, ENT_QUOTES, "UTF-8"),
+ ENT_QUOTES, "UTF-8");
+}
+
+/**
+ * TODO: Enter description here ...
+ * @param unknown_type $script
+ * @param unknown_type $default_content_type
+ * @return Ambiguous
+ */
+function util_negociate_alternate_content_types($script, $default_content_type) {
+
+ // Invoke plugins' hooks 'script_accepted_types' to discover which alternate content types they would accept for /users/...
+ $hook_params = array();
+ $hook_params['script'] = $script;
+ $hook_params['accepted_types'] = array();
+ plugin_hook_by_reference('script_accepted_types', $hook_params);
+ if (count($hook_params['accepted_types'])) {
+ // By default, text/html is accepted
+ $accepted_types = array($default_content_type);
+ $new_accepted_types = $hook_params['accepted_types'];
+ $accepted_types = array_merge($accepted_types, $new_accepted_types);
+
+ // PEAR::HTTP (for negotiateMimeType())
+ require_once('HTTP.php');
+
+ // negociate accepted content-type depending on the preferred ones declared by client
+ $http=new HTTP();
+ $content_type = $http->negotiateMimeType($accepted_types, false);
+ } else {
+ $content_type = $default_content_type;
+ }
+ return $content_type;
+}
+
// Local Variables:
// mode: php
// c-file-style: "bsd"