* 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 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");
}
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
*
*/
function util_make_links($data='') {
- if(empty($data)) {
- return $data;
+ if(empty($data)) {
+ return $data;
}
$lines = explode("\n", $data);
$newText = "";
$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);
* @returns true on success/false on error
*
*/
-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;
+function validate_email ($address) {
+ 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;
+ }
}
}
*/
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"
* @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;
- }
- $step = $base10 ? 3 : 10;
- $base = $base10 ? 10 : 2;
+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);
+ }
+ 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;
}
/**
* Constructs the forge's URL prefix out of forge_get_config('url_prefix')
- *
+ *
* @return string
*/
function normalized_urlprefix() {
$prefix = preg_replace ("/^\//", "", $prefix) ;
$prefix = preg_replace ("/\/$/", "", $prefix) ;
$prefix = "/$prefix/" ;
- if ($prefix == '//')
+ if ($prefix == '//')
$prefix = '/' ;
return $prefix ;
}
+/**
+ * Construct the base URL http[s]://forge_name[:port]
+ *
+ * @return string base URL
+ */
+function util_make_base_url() {
+ if (forge_get_config('use_ssl')) {
+ $url = "https://" ;
+ } else {
+ $url = "http://" ;
+ }
+ $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
+ * @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) ;
+ $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
*/
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
/**
* 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') {
- $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;
+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);
}
// 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) ;
}
function util_get_compressed_file_extension() {
$m = forge_get_config('compression_method');
- if (preg_match ('/^gzip /', $m)) {
+ if (preg_match ('/^gzip\b/', $m)) {
return '.gz';
- } elseif (preg_match ('/^bzip2 /', $m)) {
+ } elseif (preg_match ('/^bzip2\b/', $m)) {
return '.bzip2';
- } elseif (preg_match ('/^lzma /', $m)) {
+ } elseif (preg_match ('/^lzma\b/', $m)) {
return '.lzma';
- } elseif (preg_match ('/^xz /', $m)) {
+ } elseif (preg_match ('/^xz\b/', $m)) {
return '.xz';
- } elseif (preg_match ('/^cat /', $m)) {
+ } 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 = '';
+
+ // 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);
+ }
+ }
- if (strlen($b) != $num)
- exit_error(_('Internal Error'),
- _('Could not read from random device'));
+ // 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);
}
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"