* FusionForge miscellaneous utils
*
* Copyright 1999-2001, VA Linux Systems, Inc.
- * Copyright 2009-2010, Roland Mas
- * Copyright 2009-2010, Franck Villaume - Capgemini
- * Copyright 2010, Thorsten Glaser <t.glaser@tarent.de>
- * Copyright (C) 2010-2011 Alain Peyrat - Alcatel-Lucent
+ * Copyright 2009-2011, Roland Mas
+ * Copyright 2009-2011, Franck Villaume - Capgemini
+ * Copyright (c) 2010, 2011, 2012
+ * Thorsten Glaser <t.glaser@tarent.de>
+ * Copyright 2010-2011, Alain Peyrat - Alcatel-Lucent
*
* This file is part of FusionForge. FusionForge is free software;
* you can redistribute it and/or modify it under the terms of the
"./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");
}
*
*/
function util_unconvert_htmlspecialchars($string) {
- if (strlen($string) < 1) {
- return '';
- } else {
- //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
- $trans = get_html_translation_table(HTML_ENTITIES);
- $trans = array_flip ($trans);
- $str = strtr ($string, $trans);
- return $str;
- }
+ return html_entity_decode($string, ENT_QUOTES, "UTF-8");
}
/**
return $arr;
}
-/**
- * util_wrap_find_space() - Find the first space in a string
- *
- * @param string The string in which to find the space (must be UTF8!)
- * @param int The number of characters to wrap - Default is 80
- * @returns The position of the first space
- *
- */
-function util_wrap_find_space($string,$wrap) {
- //echo"\n";
- $start=$wrap-5;
- $try=1;
- $found=false;
-
- while (!$found) {
- //find the first space starting at $start
- $pos=@strpos($string,' ',$start);
-
- //if that space is too far over, go back and start more to the left
- if (($pos > ($wrap+5)) || !$pos) {
- $try++;
- $start=($wrap-($try*5));
- //if we've gotten so far left , just truncate the line
- if ($start<=20) {
- while ($wrap >= 1) {
- $code = ord(substr($string,$wrap,1));
- if ($code <= 0x7F ||
- $code >= 0xC0) {
- //Here is single byte character
- //or head of multi byte character
- return $wrap;
- }
- //Do not break multi byte character
- $wrap--;
- }
- return $wrap;
- }
- $found=false;
- } else {
- $found=true;
- }
- }
-
- return $pos;
-}
-
/**
* util_line_wrap() - Automatically linewrap text
*
*
*/
function util_line_wrap ($text, $wrap = 80, $break = "\n") {
- $paras = explode("\n", $text);
-
- $result = array();
- $i = 0;
- while ($i < count($paras)) {
- if (strlen($paras[$i]) <= $wrap) {
- $result[] = $paras[$i];
- $i++;
- } else {
- $pos=util_wrap_find_space($paras[$i],$wrap);
-
- $result[] = substr($paras[$i], 0, $pos);
-
- $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
- if ($new != '') {
- $paras[$i] = $new;
- $pos=util_wrap_find_space($paras[$i],$wrap);
- } else {
- $i++;
- }
- }
- }
- return implode($break, $result);
+ return wordwrap($text, $wrap, $break, false);
}
/**
* @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;
+ }
+ $withPattern = 0;
+ for ($i = 0; $i < 5; $i++) {
+ $randPattern = rand(10000, 30000);
+ if (! preg_match("/$randPattern/", $data)) {
+ $withPattern = 1;
+ break;
+ }
+ }
+ if ($withPattern) {
+/*
+ while(preg_match('/<a [^>]*>[^<]*<\/a>/i', $data, $part)) {
+ $mem[] = $part[0];
+ $data = preg_replace('/<a [^>]*>[^<]*<\/a>/i', $randPattern, $data, 1);
+ }
+*/
+ $mem = array();
+ while(preg_match('/<a [^>]*>.*<\/a>/siU', $data, $part)) {
+ $mem[] = $part[0];
+ $data = preg_replace('/<a [^>]*>.*<\/a>/siU', $randPattern, $data, 1);
+ }
+ while(preg_match('/<img [^>]*\/>/siU', $data, $part)) {
+ $mem[] = $part[0];
+ $data = preg_replace('/<img [^>]*\/>/siU', $randPattern, $data, 1);
+ }
+ $data = str_replace('>', "\1", $data);
+ $data = preg_replace("#([ \t]|^)www\.#i"," http://www.",$data);
+ $data = preg_replace("#([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]\#?/&=])#i", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $data);
+ $data = preg_replace("#([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]<\1]*)([[:alnum:]-]))#i", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $data);
+ $data = str_replace("\1", '>', $data);
+ for ($i = 0; $i < count($mem); $i++) {
+ $data = preg_replace("/$randPattern/", $mem[$i], $data, 1);
+ }
+ return($data);
}
- $lines = explode("\n",$data);
+
+ $lines = split("\n",$data);
$newText = "";
- while ( list ($key,$line) = each ($lines)) {
+ while ( list ($key, $line) = each ($lines)) {
+ // Do not scan lines if they already have hyperlinks.
+ // Avoid problem with text written with an WYSIWYG HTML editor.
+ if (eregi('<a ([^>]*)>.*</a>', $line, $linePart)) {
+ if (eregi('href="[^"]*"', $linePart[1])) {
+ $newText .= $line;
+ continue;
+ }
+ }
+
+ // Skip </img> tag also
+ if (eregi('<img ([^>]*)/>', $line, $linePart)) {
+ if (eregi('href="[^"]*"', $linePart[1])) {
+ $newText .= $line;
+ continue;
+ }
+ }
+
// 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 = preg_replace( "/([ \t]|^)www\./i", " http://www.", $line);
- $text = preg_replace( "/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
+ $line = preg_replace("/([ \t]|^)www\./i", " http://www.", $line);
+ $line = preg_replace("/([[:alnum:]]+):\/\/([^[:space:]<\1]*)([[:alnum:]#?\/&=])/i",
"<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
- $text = preg_replace(
+ $line = preg_replace(
"/([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))/i",
"\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>",
- $text
+ $line
);
- $text = str_replace("\1", '>', $text);
- $newText .= $text;
+ $line = str_replace("\1", '>', $line);
+ $newText .= $line;
}
return $newText;
}
*
*/
function show_priority_colors_key() {
- echo '<p /><strong> '._('Priority Colors').':</strong><br />
-
- <table border="0"><tr>';
-
+ echo '<p><strong> '._('Priority Colors')._(':').'</strong>';
for ($i=1; $i<6; $i++) {
- echo '
- <td class="priority'.$i.'">'.$i.'</td>';
+ echo ' <span class="priority'.$i.'">'.$i.'</span>';
}
- echo '</tr></table>';
+ echo '</p>';
}
/**
* @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';
}
}
- echo '> '.$options[$i];
+ echo ' /> '.$options[$i];
}
}
* 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);
+ $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) {
- GLOBAL $HTML;
+ 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>
$rows = db_numrows($result);
$cols = db_numfields($result);
- echo '<table border="0" width="100%">';
+ echo '<table width="100%">';
/* Create the headers */
$headersCellData = array();
$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) {
- 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;
+ 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 = preg_replace("/[-A-Z0-9+_\. ~]/i","",$file);
* @returns true on success/false on failur
*
*/
-function valid_hostname ($hostname = "xyz") {
+function valid_hostname($hostname = "xyz") {
//bad char test
$invalidchars = preg_replace("/[-A-Z0-9\.]/i","",$hostname);
* @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;
$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);
if (util_is_dot_or_dotdot($sub_dir))
return true;
}
-
+
return false;
}
* @return string
*/
function util_strip_accents($text) {
- return iconv ('UTF-8', 'US-ASCII//TRANSLIT', $text) ;
+ $find = utf8_decode($text);
+ $find = strtr($find,
+ utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
+ 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
+ return utf8_encode($find);
}
/**
* 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 = preg_replace ("/^\//", "", $prefix) ;
$prefix = preg_replace ("/\/$/", "", $prefix) ;
$prefix = "/$prefix/" ;
- if ($prefix == '//')
+ if ($prefix == '//')
$prefix = '/' ;
return $prefix ;
}
+/**
+ * Return URL prefix (http:// or https://)
+ *
+ * @param string $prefix (optional) : 'http' or 'https' to force it
+ * @return string URL prefix
+ */
+function util_url_prefix($prefix = '') {
+ if ($prefix == 'http' || $prefix == 'https' ) {
+ return $prefix . '://';
+ }
+ else {
+ if (forge_get_config('use_ssl')) {
+ return "https://";
+ } else {
+ return "http://";
+ }
+ }
+}
+
+/**
+ * Construct the base URL http[s]://forge_name[:port]
+ *
+ * @param string $prefix (optional) : 'http' or 'https' to force it
+ * @return string base URL
+ */
+function util_make_base_url($prefix = '') {
+ $url = util_url_prefix($prefix);
+ $url .= forge_get_config('web_host') ;
+ 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
+ *
+ * @param string $path (optional)
+ * @param string $prefix (optional) : 'http' or 'https' to force it
+ * @return string URL
*/
-function util_make_url ($path) {
- if (forge_get_config('use_ssl')) {
- $url = "https://" ;
- $url .= forge_get_config('web_host') ;
- if (forge_get_config('https_port') != 443) {
- $url .= ":".forge_get_config('https_port') ;
- }
- } else {
- $url = "http://" ;
- $url .= forge_get_config('web_host') ;
- if (forge_get_config('http_port') != 80) {
- $url .= ":".forge_get_config('http_port') ;
- }
- }
- $url .= util_make_uri ($path) ;
- return $url ;
+function util_make_url($path = '', $prefix = '') {
+ $url = util_make_base_url($prefix).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 = preg_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) {
/**
* Create an HTML link to a user's profile page
- *
+ *
* @param string $username
* @param int $user_id
* @param string $text
* @return string
*/
function util_make_link_u ($username, $user_id,$text) {
- return '<a href="' . util_make_url_u ($username, $user_id) . '">' . $text . '</a>' ;
+ 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') {
- $hook_params = array();
- $hook_params['username'] = $username;
- $hook_params['user_id'] = $user_id;
- $hook_params['user_link'] = '';
- plugin_hook_by_reference("user_link_with_tooltip", $hook_params);
+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>';
/**
* 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
return false;
}
}
-
+
// Check if a forum with same name already exists
$ff = new ForumFactory($group);
if (!$ff || !is_object($ff) || $ff->isError()) {
}
}
}
-
+
// Email is available
return true;
}
+/**
+ * Adds the Javascript file to the list to be used
+ * @param string $js
+ */
function use_javascript($js) {
return $GLOBALS['HTML']->addJavascript($js);
}
// 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) ;
}
if ($x == '/') {
$rv = 0;
$ok = true;
- } else if ($ok == false) {
+ } elseif ($ok == false) {
; /* need reset using slash */
- } else if ((ord($x) >= 48) && (ord($x) <= 57)) {
+ } elseif ((ord($x) >= 48) && (ord($x) <= 57)) {
$rv = $rv * 10 + ord($x) - 48;
} else {
$ok = false;
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) {
- $f = fopen("/dev/urandom", "rb");
- $b = fread($f, $num);
- fclose($f);
+ $b = '';
- if (strlen($b) != $num)
- exit_error(_('Internal Error'),
- _('Could not read from random device'));
+ // 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);
}
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) {
$unencoded_string));
/* replace all URIs with ^AURI^A */
$s = preg_replace(
- '|([a-zA-Z][a-zA-Z0-9+.-]*:[#0-9a-zA-Z;/?:@&=+$._!~*\'()%-]+)|',
+ '|([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");
return $s;
}
+function util_html_encode($s) {
+ return htmlspecialchars($s, ENT_QUOTES, "UTF-8");
+}
+
/* 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");
+ return util_html_encode(util_unconvert_htmlspecialchars($s));
+}
+
+/* return integral value (ℕ₀) of passed string if it matches, or false */
+function util_nat0(&$s) {
+ if (!isset($s)) {
+ /* unset variable */
+ return false;
+ }
+ if (is_array($s)) {
+ if (count($s) == 1) {
+ /* one-element array */
+ return util_nat0($s[0]);
+ }
+ /* not one element, or element not at [0] */
+ return false;
+ }
+ if (!is_numeric($s)) {
+ /* not numeric */
+ return false;
+ }
+ $num = (int)$s;
+ if ($num >= 0) {
+ /* number element of ℕ₀ */
+ $text = (string)$num;
+ if ($text == $s) {
+ /* number matches its textual representation */
+ return ($num);
+ }
+ /* doesn't match, like 0123 or 1.2 or " 1" */
+ }
+ /* or negative */
+ return false;
+}
+
+/**
+ * util_negociate_alternate_content_types() - Manage content-type negociation based on 'script_accepted_types' hooks
+ * @param string $script
+ * @param string $default_content_type
+ * @param string $forced_content_type
+ * @return string
+ */
+function util_negociate_alternate_content_types($script, $default_content_type, $forced_content_type=false) {
+
+ $content_type = $default_content_type;
+
+ // we can force the content-type to be returned automaticall if necessary
+ if ($forced_content_type) {
+ // TODO ideally, in this case we could try and apply the negociation to see if it matches
+ // one provided by the hooks, but negotiateMimeType() doesn't allow this so for the moment,
+ // we just force it whatever the hooks support
+ $content_type = $forced_content_type;
+ }
+ else {
+ // 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);
+ }
+ }
+ return $content_type;
}
+/**
+ * util_gethref() - Construct a hypertext reference
+ *
+ * @param string $baseurl
+ * (optional) base URL (absolute or relative);
+ * urlencoded, but not htmlencoded
+ * (default (falsy): PHP_SELF)
+ * @param array $args
+ * (optional) associative array of unencoded query parameters;
+ * false values are ignored
+ * @param bool $ashtml
+ * (optional) htmlencode the result?
+ * (default: true)
+ * @param string $sep
+ * (optional) argument separator ('&' or ';')
+ * (default: '&')
+ * @return string
+ * URL, possibly htmlencoded
+ */
+function util_gethref($baseurl=false, $args=array(), $ashtml=true, $sep='&') {
+ $rv = $baseurl ? $baseurl : getStringFromServer('PHP_SELF');
+ $pfx = '?';
+ foreach ($args as $k => $v) {
+ if ($v === false) {
+ continue;
+ }
+ $rv .= $pfx . urlencode($k) . '=' . urlencode($v);
+ $pfx = $sep;
+ }
+ return ($ashtml ? util_html_encode($rv) : $rv);
+}
+
+/**
+ * util_sanitise_multiline_submission() – Convert text to ASCII CR-LF
+ *
+ * @param string $text
+ * input string to sanitise
+ * @return string
+ * sanitised string: CR, LF or CR-LF converted to CR-LF
+ */
+function util_sanitise_multiline_submission($text) {
+ /* convert all CR-LF into LF */
+ $text = preg_replace("/\015+\012+/m", "\012", $text);
+ /* convert all CR or LF into CR-LF */
+ $text = preg_replace("/[\012\015]/m", "\015\012", $text);
+
+ return $text;
+}
+
+
// Local Variables:
// mode: php
// c-file-style: "bsd"
// End:
-
-?>