<?php
/**
- * utils.php - Misc utils common to all aspects of the site
+ * FusionForge miscellaneous utils
*
- * Copyright 1999-2001 (c) VA Linux Systems
+ * Copyright 1999-2001, VA Linux Systems, Inc.
+ * Copyright 2009, Roland Mas
*
- * @version $Id$
+ * This file is part of FusionForge.
*
- * This file is part of GForge.
- *
- * GForge 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.
- *
- * GForge 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 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.
*
* You should have received a copy of the GNU General Public License
- * along with GForge; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 US
+ * along with FusionForge; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
+ * USA
*/
+/**
+ * is_utf8($string) - utf-8 detection
+ *
+ * From http://www.php.net/manual/en/function.mb-detect-encoding.php#85294
+ */
+function is_utf8($str) {
+ $c=0; $b=0;
+ $bits=0;
+ $len=strlen($str);
+ for($i=0; $i<$len; $i++){
+ $c=ord($str[$i]);
+ if($c > 128){
+ if(($c >= 254)) return false;
+ elseif($c >= 252) $bits=6;
+ elseif($c >= 248) $bits=5;
+ elseif($c >= 240) $bits=4;
+ elseif($c >= 224) $bits=3;
+ elseif($c >= 192) $bits=2;
+ else return false;
+ if(($i+$bits) > $len) return false;
+ while($bits > 1){
+ $i++;
+ $b=ord($str[$i]);
+ if($b < 128 || $b > 191) return false;
+ $bits--;
+ }
+ }
+ }
+ return true;
+}
/**
- * removeCRLF() - remove any Cariage Return-Line Feed from a string.
- * That function is usefull to remove the possibility of a CRLF Injection when sending mail
+ * 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
/**
* util_check_fileupload() - determines if a filename is appropriate for upload
*
- * @param string The name of the file being uploaded
+ * @param array The uploaded file as returned by getUploadedFile()
*/
function util_check_fileupload($filename) {
* @param string The optional email sender address. Defaults to 'noreply@'
* @param string The addresses to blind-carbon-copy this message
* @param string The optional email sender name. Defaults to ''
+ * @param boolean Whether to send plain text or html email
*
*/
-function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='') {
- global $Language;
- global $sys_sendmail_path;
+function util_send_message($to,$subject,$body,$from='',$BCC='',$sendername='',$extra_headers='',$send_html_email=false) {
+ global $sys_bcc_all_email_address,$sys_sendmail_path;
if (!$to) {
$to='noreply@'.$GLOBALS['sys_default_domain'];
if (!$from) {
$from='noreply@'.$GLOBALS['sys_default_domain'];
}
+
- $charset = $Language->getText('conf','mail_charset');
+ $charset = _('UTF-8');
if (!$charset) {
- $charset = 'ISO-8859-1';
+ $charset = 'UTF-8';
}
+
+ $body2 = '';
if ($extra_headers) {
- $body2 = $extra_headers."\n";
+ $body2 .= $extra_headers."\n";
}
$body2 .= "To: $to".
- "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset).
- "\nBCC: $BCC".
- "\nSubject: ".util_encode_mimeheader($subject, $charset).
- "\nContent-type: text/plain; charset=$charset".
+ "\nFrom: ".util_encode_mailaddr($from,$sendername,$charset);
+ if (!empty($sys_bcc_all_email_address)) {
+ $BCC.=",$sys_bcc_all_email_address";
+ }
+ if(!empty($BCC)) {
+ $body2 .= "\nBCC: $BCC";
+ }
+ $send_html_email?$type="html":$type="plain";
+ $body2 .= "\n".util_encode_mimeheader("Subject", $subject, $charset).
+ "\nContent-type: text/$type; charset=$charset".
"\n\n".
util_convert_body($body, $charset);
$sys_sendmail_path="/usr/sbin/sendmail";
}
- exec ("/bin/echo \"". util_prep_string_for_sendmail($body2) .
- "\" | ".$sys_sendmail_path." -f'$from' -t -i > /dev/null 2>&1 &");
+ $handle = popen($sys_sendmail_path." -f'$from' -t -i", 'w');
+ fwrite ($handle, $body2);
+ pclose($handle);
}
/**
/**
* util_encode_mimeheader() - Encode mimeheader
*
+ * @param string The name of the header (e.g. "Subject")
* @param string The email subject
* @param string The converting charset (like ISO-2022-JP)
* @return string The MIME encoded subject
*
*/
-function util_encode_mimeheader($str,$charset) {
+function util_encode_mimeheader($headername,$str,$charset) {
+ if (function_exists('mb_internal_encoding') &&
+ function_exists('mb_encode_mimeheader')) {
+ $x = mb_internal_encoding();
+ mb_internal_encoding("UTF-8");
+ $y = mb_encode_mimeheader($headername . ": " . $str,
+ $charset, "Q");
+ mb_internal_encoding($x);
+ return $y;
+ }
+
if (!function_exists('mb_convert_encoding')) {
- return $str;
+ return $headername . ": " . $str;
}
- return "=?".$charset."?B?".
+ return $headername . ": " . "=?".$charset."?B?".
base64_encode(mb_convert_encoding(
$str,$charset,"UTF-8")).
"?=";
*
*/
function util_convert_body($str,$charset) {
- if (!function_exists('mb_convert_encoding')) {
+ if (!function_exists('mb_convert_encoding') || $charset == 'UTF-8') {
return $str;
}
-
+
return mb_convert_encoding($str,$charset,"UTF-8");
}
*
*/
function util_prep_string_for_sendmail($body) {
- //$body=str_replace("\\","\\\\",$body);
- $body=str_replace("`","\\`",$body);
+ /*$body=str_replace("`","\\`",$body);
$body=str_replace("\"","\\\"",$body);
- $body=str_replace("\$","\\\$",$body);
+ $body=str_replace("\$","\\\$",$body);*/
+ $body = escapeshellarg($body);
return $body;
}
if (count($id_arr) < 1) {
} else {
- $res=db_query("SELECT user_id, jabber_address,email,jabber_only
- FROM users WHERE user_id IN (". implode($id_arr,',') .")");
- $rows=db_numrows($res);
+ $res = db_query_params ('SELECT user_id,jabber_address,email,jabber_only FROM users WHERE user_id = ANY ($1)',
+ array (db_int_array_to_any_clause ($id_arr))) ;
+ $rows = db_numrows($res) ;
for ($i=0; $i<$rows; $i++) {
if (db_result($res, $i, 'user_id') == 100) {
$address['email'][]=db_result($res,$i,'email');
}
}
- if (count($address['email']) > 0) {
- $extra_email1=implode($address['email'],',').',';
+ if (isset ($address['email']) && count($address['email']) > 0) {
+ $extra_emails=implode($address['email'],',').',' . $extra_emails;
}
- if (count($address['jabber_address']) > 0) {
- $extra_jabber1=implode($address['jabber_address'],',').',';
+ if (isset ($address['jabber_address']) && count($address['jabber_address']) > 0) {
+ $extra_jabbers=implode($address['jabber_address'],',').','.$extra_jabbers;
}
}
- if ($extra_email1 || $extra_emails) {
- util_send_message('',$subject,$body,$from,$extra_email1.$extra_emails);
+ if ($extra_emails) {
+ util_send_message('',$subject,$body,$from,$extra_emails);
}
- if ($extra_jabber1 || $extra_jabbers) {
- util_send_jabber($extra_jabber1.$extra_jabbers,$subject,$body);
+ if ($extra_jabbers) {
+ util_send_jabber($extra_jabbers,$subject,$body);
}
}
*
*/
function util_make_links ($data='') {
- if(empty($data)) { return $data; }
-
+ if(empty($data)) {
+ return $data;
+ }
$lines = split("\n",$data);
+ $newText = "";
while ( list ($key,$line) = each ($lines)) {
// When we come here, we usually have form input
// encoded in entities. Our aim is to NOT include
*
*/
function show_priority_colors_key() {
- global $Language;
- echo '<p /><strong> '.$Language->getText('common_utils','priority_colors').':</strong><br />
+ echo '<p /><strong> '._('Priority Colors').':</strong><br />
<table border="0"><tr>';
- for ($i=1; $i<10; $i++) {
+ for ($i=1; $i<6; $i++) {
echo '
- <td bgcolor="'.html_get_priority_color($i).'">'.$i.'</td>';
+ <td class="priority'.$i.'">'.$i.'</td>';
}
echo '</tr></table>';
}
<br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
for ($j=0; $j<$checked_count; $j++) {
if ($i == $checked_array[$j]) {
- echo ' CHECKED';
+ echo ' checked';
}
}
echo '> '.$options[$i];
* @return a string holding the HTML to mark a required field
*/
function utils_requiredField() {
- return '<span><font color="red">*</font></span>';
+ return '<span class="requiredfield">*</span>';
}
/**
}
/* Display the headers */
- echo $HTML->multiTableRow('', $headersCellData, TRUE);
+ if($displayHeaders) {
+ echo $HTML->multiTableRow('', $headersCellData, TRUE);
+ }
/* Create the rows */
for ($j = 0; $j < $rows; $j++) {
for ($i = 0; $i < $cols; $i++) {
if(in_array($i, $colsToKeep)) {
if ($linkify && $i == 0) {
- $link = '<a href="'.$PHP_SELF.'?';
+ $link = '<a href="'.getStringFromServer('PHP_SELF').'?';
$linkend = '</a>';
if ($linkify == "bug_cat") {
$link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
*
*/
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));
+ return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address) !== false);
+}
+
+/**
+ * validate_emails() - Validate a list of e-mail addresses
+ *
+ * @param string E-mail list
+ * @param char Separator
+ * @returns array Array of invalid e-mail addresses (if empty, all addresses are OK)
+*/
+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"
+ if (!validate_email($email)) $ret[] = $email;
+ }
+ }
+ return $ret;
}
+
+
/**
* util_is_valid_filename() - Verifies whether a file has a valid filename
*
*/
function util_is_valid_filename ($file) {
//bad char test
- $invalidchars = eregi_replace("[-A-Z0-9_\.]","",$file);
+ $invalidchars = eregi_replace("[-A-Z0-9+_\. ]","",$file);
if (!empty($invalidchars)) {
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;
-
- $log = (int)(log10($bytes)/log10($base));
-
- krsort($labels);
-
- foreach ($labels as $p=>$lab) {
- $pow = $p * $step;
- if ($log < $pow) continue;
- $text = round($bytes/pow($base,$pow),$round) . $lab;
- break;
- }
-
- return $text;
+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;
+ $log = (int)(log10($bytes)/log10($base));
+ krsort($labels);
+ foreach ($labels as $p=>$lab) {
+ $pow = $p * $step;
+ if ($log < $pow) {
+ continue;
+ }
+ if ($lab == " MB" or $lab == " GB") {
+ $round = 2;
+ }
+ $text = round($bytes/pow($base,$pow),$round).$lab;
+ break;
+ }
+ return $text;
+}
+
+/**
+ * ls - lists a specified directory and returns an array of files
+ * @param string the path of the directory to list
+ * @param boolean whether to filter out directories and illegal filenames
+ * @return array array of file names.
+ */
+function &ls($dir,$filter=false) {
+ 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];
+ }
+ }
+ return $filtered;
+ } else {
+ return $out;
+ }
+}
+
+/**
+ * readfile_chunked() - replacement for readfile
+ *
+ * @param string The file path
+ * @param bool Whether to return bytes served or just a bool
+ *
+ */
+function readfile_chunked($filename, $returnBytes=true) {
+ $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);
+ echo $buffer;
+ ob_flush() ;
+ flush () ;
+ if ($returnBytes) {
+ $byteCounter += strlen($buffer);
+ }
+ }
+ ob_end_flush () ;
+ $status = fclose($handle);
+ if ($returnBytes && $status) {
+ return $byteCounter; // return num. bytes delivered like readfile() does.
+ }
+ return $status;
+}
+
+/**
+ * util_is_root_dir() - Checks if a directory points to the root dir
+ * @param string Directory
+ * @return bool
+ */
+function util_is_root_dir($dir) {
+ return !preg_match('/[^\\/]/',$dir);
}
+/**
+ * util_strip_accents() - Remove accents from given text.
+ * @param string Text
+ * @return string
+ */
+function util_strip_accents($text) {
+ $find = utf8_decode($text);
+ $find = strtr($find,
+ utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
+ 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
+ return utf8_encode($find);
+}
+/**
+ * Constructs the forge's URL prefix out of $GLOBALS['sys_urlprefix']
+ *
+ * @return string
+ */
+function normalized_urlprefix () {
+ $prefix = $GLOBALS['sys_urlprefix'] ;
+ $prefix = ereg_replace ("^/", "", $prefix) ;
+ $prefix = ereg_replace ("/$", "", $prefix) ;
+ $prefix = "/$prefix/" ;
+ if ($prefix == '//')
+ $prefix = '/' ;
+ return $prefix ;
+}
+
+/**
+ * Construct full URL from a relative path
+ *
+ * @param string $path
+ * @return string URL
+ */
+function util_make_url ($path) {
+ if ($GLOBALS['sys_use_ssl'])
+ $url = "https://" ;
+ else
+ $url = "http://" ;
+
+ $url .= $GLOBALS['sys_default_domain'] ;
+ $url .= util_make_uri ($path) ;
+ return $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_link ($path, $text, $extra_params=false, $absolute=false) {
+ $ep = '' ;
+ if (is_array($extra_params)) {
+ foreach ($extra_params as $key => $value) {
+ $ep .= "$key=\"$value\" ";
+ }
+ }
+ if ($absolute) {
+ return '<a ' . $ep . 'href="' . $path . '">' . $text . '</a>' ;
+ } else {
+ return '<a ' . $ep . 'href="' . util_make_url ($path) . '">' . $text . '</a>' ;
+ }
+}
+
+/**
+ * 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>' ;
+}
+
+/**
+ * Create URL for user's profile page
+ *
+ * @param string $username
+ * @param int $user_id
+ * @return string URL
+ */
+function util_make_url_u ($username, $user_id) {
+ if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
+ return util_make_url ("/developer/?user_id=$user_id");
+ } else {
+ return util_make_url ("/users/$username/");
+ }
+}
+
+/**
+ * Create a HTML link to a project's page
+ * @param string $groupame
+ * @param int $group_id
+ * @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>' ;
+}
+
+/**
+ * Create URL for a project's page
+ *
+ * @param string $groupame
+ * @param int $group_id
+ * @return string
+ */
+function util_make_url_g ($groupame, $group_id) {
+ if (isset ($GLOBALS['sys_noforcetype']) && $GLOBALS['sys_noforcetype']) {
+ return util_make_url ("/project/?group_id=$group_id");
+ } else {
+ return util_make_url ("/projects/$groupame/");
+ }
+}
+
+function util_ensure_value_in_set ($value, $set) {
+ if (in_array ($value, $set)) {
+ return $value ;
+ } else {
+ return $set[0] ;
+ }
+}
+
+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.');
+ 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;
+ }
+ }
+ }
+
+ // Email is available
+ return true;
+}
+// Local Variables:
+// mode: php
+// c-file-style: "bsd"
+// End:
?>