* Copyright 1999-2001, VA Linux Systems, Inc.
* Copyright 2009-2011, Roland Mas
* Copyright 2009-2011, Franck Villaume - Capgemini
- * Copyright (c) 2010, 2011
+ * Copyright (c) 2010, 2011, 2012
* Thorsten Glaser <t.glaser@tarent.de>
* Copyright 2010-2011, Alain Peyrat - Alcatel-Lucent
+ * Copyright 2013, Franck Villaume - TrivialDev
*
* This file is part of FusionForge. FusionForge is free software;
* you can redistribute it and/or modify it under the terms of the
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.
* That function is useful to remove the possibility of a CRLF Injection when sending mail
*
*/
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);
}
/**
// 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>';
}
/**
echo ' checked';
}
}
- echo '> '.$options[$i];
+ echo ' /> '.$options[$i];
}
}
*
*/
function GraphIt($name_string, $value_string, $title) {
- GLOBAL $HTML;
+ global $HTML;
$counter = count($name_string);
$rows = db_numrows($result);
$cols = db_numfields($result);
- echo '<table border="0" width="100%">';
+ echo '<table width="100%">';
/* Create the headers */
$headersCellData = array();
* @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;
+ }
}
}
* @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;
* @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);
}
/**
}
/**
- * Construct the base URL http[s]://forge_name[:port]
+ * Return URL prefix (http:// or https://)
*
- * @return string base URL
+ * @return string URL prefix
*/
-function util_make_base_url() {
+function util_url_prefix() {
if (forge_get_config('use_ssl')) {
- $url = "https://" ;
+ return "https://";
} else {
- $url = "http://" ;
+ return "http://";
}
+}
+
+/**
+ * Construct the base URL http[s]://forge_name[:port]
+ *
+ * @return string base URL
+ */
+function util_make_base_url() {
+ $url = util_url_prefix();
$url .= forge_get_config('web_host') ;
- if (forge_get_config('https_port') != 443) {
+ 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
*
* @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>';
}
/**
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_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'];
- }
+ $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>' ;
}
function check_email_available($group, $email, &$response) {
// Check if a mailing list with same name already exists
- $mlFactory = new MailingListFactory($group);
- if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
- $response .= $mlFactory->getErrorMessage();
- return false;
- }
- $mlArray = $mlFactory->getMailingLists();
- if ($mlFactory->isError()) {
- $response .= $mlFactory->getErrorMessage();
- return false;
- }
- for ($j = 0; $j < count($mlArray); $j++) {
- $currentList =& $mlArray[$j];
- if ($email == $currentList->getName()) {
- $response .= _('Error: a mailing list with the same email address already exists.');
+ if ($group->usesMail()) {
+ $mlFactory = new MailingListFactory($group);
+ if (!$mlFactory || !is_object($mlFactory) || $mlFactory->isError()) {
+ $response .= $mlFactory->getErrorMessage();
+ return false;
+ }
+ $mlArray = $mlFactory->getMailingLists();
+ if ($mlFactory->isError()) {
+ $response .= $mlFactory->getErrorMessage();
return false;
}
+ for ($j = 0; $j < count($mlArray); $j++) {
+ $currentList =& $mlArray[$j];
+ if ($email == $currentList->getName()) {
+ $response .= _('Error: a mailing list with the same email address already exists.');
+ 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();
- $prefix = $group->getUnixName() . '-';
- for ($j = 0; $j < count($farr); $j++) {
- if (is_object($farr[$j])) {
- if ($email == $prefix . $farr[$j]->getName()) {
- $response .= _('Error: a forum with the same email address already exists.');
- return false;
+ if ($group->usesForum()) {
+ $ff = new ForumFactory($group);
+ if (!$ff || !is_object($ff) || $ff->isError()) {
+ $response .= $ff->getErrorMessage();
+ return false;
+ }
+ $farr = $ff->getForums();
+ $prefix = $group->getUnixName() . '-';
+ for ($j = 0; $j < count($farr); $j++) {
+ if (is_object($farr[$j])) {
+ if ($email == $prefix . $farr[$j]->getName()) {
+ $response .= _('Error: a forum with the same email address already exists.');
+ return false;
+ }
}
}
}
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 an array from an array of arrays of arrays of ... */
-function array_flatten($array) {
- $returnedValue = array();
- foreach ($array as $value) {
- if(is_array($value)) {
- $returnedValue = array_flatten($value);
- } else {
- $returnedValue[] = $value;
+/* 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;
+}
+
+/**
+ * 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;
+}
+
+/**
+ * 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;
+}
+
+/**
+ * util_create_file_with_contents() — Securely create (or replace) a file with given contents
+ *
+ * @param string $path Path of the file to be created
+ * @param string $contents Contents of the file
+ *
+ * @return boolean FALSE on error
+ */
+function util_create_file_with_contents($path, $contents) {
+ if (file_exists($path) && !unlink($path)) {
+ return false;
+ }
+ $handle = fopen($path, "x+");
+ if ($handle == false) {
+ return false;
+ }
+ fwrite($handle, $contents);
+ fclose($handle);
+ return true;
+}
+
+/**
+ * Create a directory in the system temp directory with a hard-to-predict name.
+ * Does not have the guarantees of the actual BSD libc function or Python tempfile function.
+ * @param string $suffix Append to the new directory's name
+ * @param string $prefix Prepend to the new directory's name
+ * @return string The path of the new directory.
+ *
+ * Mostly taken from https://gist.github.com/1407245 as a "temporary"
+ * workaround to https://bugs.php.net/bug.php?id=49211
+ */
+function util_mkdtemp($suffix = '', $prefix = 'tmp') {
+ $tempdir = sys_get_temp_dir();
+ for ($i=0; $i<5; $i++) {
+ $id = strtr(base64_encode(util_randbytes(6)), '+/', '-_');
+ $path = "{$tempdir}/{$prefix}{$id}{$suffix}";
+ if (mkdir($path, 0700)) {
+ return $path;
}
}
- return $returnedValue;
+ return false;
+}
+
+/**
+ * Run a function with only the permissions of a given Unix user
+ * Function can be an anonymous
+ * Optional arguments in an array
+ * @param string Unix user name
+ * @param function function to run (possibly anonymous)
+ * @param array parameters
+ * @return boolean true on success, false on error
+ */
+function util_sudo_effective_user($username, $function, $params=array()) {
+ $saved_egid = posix_getegid();
+ $saved_euid = posix_geteuid();
+
+ $userinfo = posix_getpwnam($username);
+ if ($userinfo === False) {
+ return False;
+ }
+ if (posix_setegid($userinfo['gid']) &&
+ ($saved_euid != 0 || posix_initgroups($username, $userinfo['gid'])) &&
+ posix_seteuid($userinfo['uid'])) {
+ $function($params);
+ }
+
+ posix_setegid($saved_egid);
+ posix_seteuid($saved_euid);
+ if ($saved_euid == 0)
+ posix_initgroups("root", 0);
}
// Local Variables:
// mode: php
// c-file-style: "bsd"
// End:
-
-?>