3 * utils.php - Misc utils common to all aspects of the site
5 * Copyright 1999-2001 (c) VA Linux Systems
9 * This file is part of GForge.
11 * GForge is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * GForge is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with GForge; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 US
28 * util_check_fileupload() - determines if a filename is appropriate for upload
30 * @param string The name of the file being uploaded
32 function util_check_fileupload($filename) {
34 /* Empty file is a valid file.
35 This is because this function should be called
36 unconditionally at the top of submit action processing
37 and many forms have optional file upload. */
38 if ($filename == 'none' || $filename == '') {
42 /* This should be enough... */
43 if (!is_uploaded_file($filename)) {
46 /* ... but we'd rather be paranoic */
47 if (strstr($filename, '..')) {
50 if (!is_file($filename)) {
53 if (!file_exists($filename)) {
56 if (dirname($filename) != '/tmp') {
63 * util_send_message() - Send email
64 * This function should be used in place of the PHP mail() function
66 * @param string The email recipients address
67 * @param string The email subject
68 * @param string The body of the email message
69 * @param string The optional email sender address. Defaults to 'noreply@'
70 * @param string The addresses to blind-carbon-copy this message
73 function util_send_message($to,$subject,$body,$from='',$BCC='') {
75 $to='noreply@'.$GLOBALS['sys_default_domain'];
78 $from='noreply@'.$GLOBALS['sys_default_domain'];
83 "\nSubject: $subject".
86 exec ("/bin/echo \"". util_prep_string_for_sendmail($body) .
87 "\" | /usr/sbin/sendmail -f'$from' -t -i >& /dev/null &");
90 function util_send_jabber($to,$subject,$body) {
91 if (!$GLOBALS['sys_use_jabber']) {
94 $JABBER = new Jabber();
95 if (!$JABBER->Connect()) {
96 echo '<br />Unable to connect';
99 //$JABBER->SendAuth();
100 //$JABBER->AccountRegistration();
101 if (!$JABBER->SendAuth()) {
102 echo '<br />Auth Failure';
103 $JABBER->Disconnect();
105 //or die("Couldn't authenticate!");
107 $JABBER->SendPresence(NULL, NULL, "online");
109 $body=htmlspecialchars($body);
110 $to_arr=explode(',',$to);
111 for ($i=0; $i<count($to_arr); $i++) {
113 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
114 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
115 echo '<br />Error Sending to '.$to_arr[$i];
120 $JABBER->CruiseControl(2);
121 $JABBER->Disconnect();
125 * util_prep_string_for_sendmail() - Prepares a string to be sent by email
127 * @param string The text to be prepared
128 * @returns The prepared text
131 function util_prep_string_for_sendmail($body) {
132 //$body=str_replace("\\","\\\\",$body);
133 $body=str_replace("`","\\`",$body);
134 $body=str_replace("\"","\\\"",$body);
135 $body=str_replace("\$","\\\$",$body);
140 * util_handle_message() - a convenience wrapper which sends messages
141 * to either a jabber account or email account or both, depending on
144 * @param array array of user_id's from the user table
145 * @param string subject of the message
146 * @param string the message body
147 * @param string a comma-separated list of email address
148 * @param string a comma-separated list of jabber address
150 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='') {
153 if (count($id_arr) < 1) {
156 $res=db_query("SELECT user_id, jabber_address,email,jabber_only
157 FROM users WHERE user_id IN (". implode($id_arr,',') .")");
158 $rows=db_numrows($res);
160 for ($i=0; $i<$rows; $i++) {
161 if (db_result($res, $i, 'user_id') == 100) {
162 // Do not send messages to "Nobody"
166 // Build arrays of the jabber address
168 if (db_result($res,$i,'jabber_address')) {
169 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
170 if (db_result($res,$i,'jabber_only') != 1) {
171 $address['email'][]=db_result($res,$i,'email');
174 $address['email'][]=db_result($res,$i,'email');
177 if (count($address['email']) > 0) {
178 $extra_email1=implode($address['email'],',').',';
180 if (count($address['jabber_address']) > 0) {
181 $extra_jabber1=implode($address['jabber_address'],',').',';
184 if ($extra_email1 || $extra_emails) {
185 util_send_message('',$subject,$body,'',$extra_email1.$extra_emails);
187 if ($extra_jabber1 || $extra_jabbers) {
188 util_send_jabber($extra_jabber1.$extra_jabbers,$subject,$body);
193 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
194 * This function requires PHP 4.0.3 or greater
196 * @param string The string to unconvert
197 * @returns The unconverted string
200 function util_unconvert_htmlspecialchars($string) {
201 if (strlen($string) < 1) {
204 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
205 $trans = get_html_translation_table(HTML_ENTITIES);
206 $trans = array_flip ($trans);
207 $str = strtr ($string, $trans);
213 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
215 * @param string The result set ID
216 * @param int The column key
217 * @param int The optional column value
218 * @returns An associative array
221 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
222 $rows=db_numrows($result);
226 for ($i=0; $i<$rows; $i++) {
227 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
236 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
238 * @param int The result set ID
239 * @param int The column
243 function &util_result_column_to_array($result, $col=0) {
245 Takes a result set and turns the optional column into
248 $rows=db_numrows($result);
252 for ($i=0; $i<$rows; $i++) {
253 $arr[$i]=db_result($result,$i,$col);
262 * util_wrap_find_space() - Find the first space in a string
264 * @param string The string in which to find the space
265 * @param int The number of characters to wrap - Default is 80
266 * @returns The position of the first space
269 function util_wrap_find_space($string,$wrap) {
276 //find the first space starting at $start
277 $pos=@strpos($string,' ',$start);
279 //if that space is too far over, go back and start more to the left
280 if (($pos > ($wrap+5)) || !$pos) {
282 $start=($wrap-($try*5));
283 //if we've gotten so far left , just truncate the line
297 * util_line_wrap() - Automatically linewrap text
299 * @param string The text to wrap
300 * @param int The number of characters to wrap - Default is 80
301 * @param string The line break to use - Default is '\n'
302 * @returns The wrapped text
305 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
306 $paras = explode("\n", $text);
310 while ($i < count($paras)) {
311 if (strlen($paras[$i]) <= $wrap) {
312 $result[] = $paras[$i];
315 $pos=util_wrap_find_space($paras[$i],$wrap);
317 $result[] = substr($paras[$i], 0, $pos);
319 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
322 $pos=util_wrap_find_space($paras[$i],$wrap);
328 return implode($break, $result);
332 * util_make_links() - Turn URL's into HREF's.
334 * @param string The URL
335 * @returns The HREF'ed URL
338 function util_make_links ($data='') {
339 if(empty($data)) { return $data; }
341 $lines = split("\n",$data);
342 while ( list ($key,$line) = each ($lines)) {
343 // When we come here, we usually have form input
344 // encoded in entities. Our aim is to NOT include
345 // angle brackets in the URL
346 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
347 $line = str_replace('>', "\1", $line);
348 $line = eregi_replace("([ \t]|^)www\."," http://www.",$line);
349 $text = eregi_replace("([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
350 $text = eregi_replace("([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $text);
351 $text = str_replace("\1", '>', $text);
358 * show_priority_colors_key() - Show the priority colors legend
361 function show_priority_colors_key() {
363 echo '<p><strong> '.$Language->getText('common_utils','priority_colors').':</strong><br />
365 <table border=0><tr>';
367 for ($i=1; $i<10; $i++) {
369 <td bgcolor="'.html_get_priority_color($i).'">'.$i.'</td>';
371 echo '</tr></table>';
375 * utils_buildcheckboxarray() - Build a checkbox array
377 * @param int Number of options to be in the array
378 * @param string The name of the checkboxes
379 * @param array An array of boxes to be pre-checked
382 function utils_buildcheckboxarray($options,$name,$checked_array) {
383 $option_count=count($options);
384 $checked_count=count($checked_array);
386 for ($i=1; $i<=$option_count; $i++) {
388 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
389 for ($j=0; $j<$checked_count; $j++) {
390 if ($i == $checked_array[$j]) {
394 echo '> '.$options[$i];
399 * utils_requiredField() - Adds the required field marker
401 * @return a string holding the HTML to mark a required field
403 function utils_requiredField() {
404 return '<span><font color="red">*</font></span>';
408 * GraphResult() - Takes a database result set and builds a graph.
409 * The first column should be the name, and the second column should be the values
410 * Be sure to include HTL_Graphs.php before using this function
412 * @author Tim Perdue tperdue@valinux.com
413 * @param int The databse result set ID
414 * @param string The title of the graph
417 Function GraphResult($result,$title) {
418 $rows=db_numrows($result);
420 if ((!$result) || ($rows < 1)) {
426 for ($j=0; $j<db_numrows($result); $j++) {
427 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
428 $names[$j]= db_result($result, $j, 0);
429 $values[$j]= db_result($result, $j, 1);
434 This is another function detailed below
436 GraphIt($names,$values,$title);
441 * GraphIt() - Build a graph
443 * @author Tim Perdue tperdue@valinux.com
444 * @param array An array of names
445 * @param array An array of values
446 * @param string The title of the graph
449 Function GraphIt($name_string,$value_string,$title) {
452 $counter=count($name_string);
455 Can choose any color you wish
459 for ($i = 0; $i < $counter; $i++) {
460 $bars[$i]=$HTML->COLOR_LTBACK1;
463 $counter=count($value_string);
466 Figure the max_value passed in, so scale can be determined
471 for ($i = 0; $i < $counter; $i++) {
472 if ($value_string[$i] > $max_value) {
473 $max_value=$value_string[$i];
477 if ($max_value < 1) {
482 I want my graphs all to be 800 pixels wide, so that is my divisor
485 $scale=(400/$max_value);
488 I create a wrapper table around the graph that holds the title
494 echo $GLOBALS['HTML']->listTableTop ($title_arr);
497 Create an associate array to pass in. I leave most of it blank
526 This is the actual call to the HTML_Graphs class
529 html_graph($name_string,$value_string,$bars,$vals);
533 <!-- end outer graph table -->';
534 echo $GLOBALS['HTML']->listTableBottom();
538 * ShowResultSet() - Show a generic result set
539 * Very simple, plain way to show a generic result set
541 * @param int The result set ID
542 * @param string The title of the result set
543 * @param bool The option to turn URL's into links
546 Function ShowResultSet($result,$title="Untitled",$linkify=false) {
547 global $group_id,$HTML;
550 $rows = db_numrows($result);
551 $cols = db_numfields($result);
554 <table border="0" width="100%">';
556 /* Create the title */
559 $cell_data[] = array($title, 'colspan='.$cols);
560 echo $HTML->multiTableRow('',$cell_data, TRUE);
562 /* Create the headers */
564 for ($i=0; $i < $cols; $i++) {
565 $cell_data[] = array(db_fieldname($result,$i));
567 echo $HTML->multiTableRow('',$cell_data, TRUE);
569 /* Create the rows */
570 for ($j = 0; $j < $rows; $j++) {
571 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
572 for ($i = 0; $i < $cols; $i++) {
573 if ($linkify && $i == 0) {
574 $link = '<a href="'.$PHP_SELF.'?';
576 if ($linkify == "bug_cat") {
577 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
578 } else if($linkify == "bug_group") {
579 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
580 } else if($linkify == "patch_cat") {
581 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
582 } else if($linkify == "support_cat") {
583 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
584 } else if($linkify == "pm_project") {
585 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
587 $link = $linkend = '';
590 $link = $linkend = '';
592 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
603 * validate_email() - Validate an email address
605 * @param string The address string to validate
606 * @returns true on success/false on error
609 function validate_email ($address) {
610 return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address));
614 * util_is_valid_filename() - Verifies whether a file has a valid filename
616 * @param string The file to verify
617 * @returns true on success/false on error
620 function util_is_valid_filename ($file) {
622 $invalidchars = eregi_replace("[-A-Z0-9_\.]","",$file);
624 if (!empty($invalidchars)) {
627 if (strstr($file,'..')) {
636 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
638 * @param string The optional hostname string
639 * @returns true on success/false on failur
642 function valid_hostname ($hostname = "xyz") {
645 $invalidchars = eregi_replace("[-A-Z0-9\.]","",$hostname);
647 if (!empty($invalidchars)) {
651 //double dot, starts with a . or -
652 if (ereg("\.\.",$hostname) || ereg("^\.",$hostname) || ereg("^\-",$hostname)) {
656 $multipoint = explode(".",$hostname);
658 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {