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') &&
57 (dirname($filename) != "/var/tmp")) {
64 * util_send_message() - Send email
65 * This function should be used in place of the PHP mail() function
67 * @param string The email recipients address
68 * @param string The email subject
69 * @param string The body of the email message
70 * @param string The optional email sender address. Defaults to 'noreply@'
71 * @param string The addresses to blind-carbon-copy this message
74 function util_send_message($to,$subject,$body,$from='',$BCC='') {
77 $to='noreply@'.$GLOBALS['sys_default_domain'];
80 $from='noreply@'.$GLOBALS['sys_default_domain'];
85 "\nSubject: $subject".
86 "\nContent-type: text/plain; charset=".$Language->getText('conf','content_encoding').
89 exec ("/bin/echo \"". util_prep_string_for_sendmail($body) .
90 "\" | /usr/sbin/sendmail -f'$from' -t -i > /dev/null 2>&1 &");
93 function util_send_jabber($to,$subject,$body) {
94 if (!$GLOBALS['sys_use_jabber']) {
97 $JABBER = new Jabber();
98 if (!$JABBER->Connect()) {
99 echo '<br />Unable to connect';
102 //$JABBER->SendAuth();
103 //$JABBER->AccountRegistration();
104 if (!$JABBER->SendAuth()) {
105 echo '<br />Auth Failure';
106 $JABBER->Disconnect();
108 //or die("Couldn't authenticate!");
110 $JABBER->SendPresence(NULL, NULL, "online");
112 $body=htmlspecialchars($body);
113 $to_arr=explode(',',$to);
114 for ($i=0; $i<count($to_arr); $i++) {
116 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
117 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
118 echo '<br />Error Sending to '.$to_arr[$i];
123 $JABBER->CruiseControl(2);
124 $JABBER->Disconnect();
128 * util_prep_string_for_sendmail() - Prepares a string to be sent by email
130 * @param string The text to be prepared
131 * @returns The prepared text
134 function util_prep_string_for_sendmail($body) {
135 //$body=str_replace("\\","\\\\",$body);
136 $body=str_replace("`","\\`",$body);
137 $body=str_replace("\"","\\\"",$body);
138 $body=str_replace("\$","\\\$",$body);
143 * util_handle_message() - a convenience wrapper which sends messages
144 * to either a jabber account or email account or both, depending on
147 * @param array array of user_id's from the user table
148 * @param string subject of the message
149 * @param string the message body
150 * @param string a comma-separated list of email address
151 * @param string a comma-separated list of jabber address
153 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='') {
156 if (count($id_arr) < 1) {
159 $res=db_query("SELECT user_id, jabber_address,email,jabber_only
160 FROM users WHERE user_id IN (". implode($id_arr,',') .")");
161 $rows=db_numrows($res);
163 for ($i=0; $i<$rows; $i++) {
164 if (db_result($res, $i, 'user_id') == 100) {
165 // Do not send messages to "Nobody"
169 // Build arrays of the jabber address
171 if (db_result($res,$i,'jabber_address')) {
172 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
173 if (db_result($res,$i,'jabber_only') != 1) {
174 $address['email'][]=db_result($res,$i,'email');
177 $address['email'][]=db_result($res,$i,'email');
180 if (count($address['email']) > 0) {
181 $extra_email1=implode($address['email'],',').',';
183 if (count($address['jabber_address']) > 0) {
184 $extra_jabber1=implode($address['jabber_address'],',').',';
187 if ($extra_email1 || $extra_emails) {
188 util_send_message('',$subject,$body,'',$extra_email1.$extra_emails);
190 if ($extra_jabber1 || $extra_jabbers) {
191 util_send_jabber($extra_jabber1.$extra_jabbers,$subject,$body);
196 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
197 * This function requires PHP 4.0.3 or greater
199 * @param string The string to unconvert
200 * @returns The unconverted string
203 function util_unconvert_htmlspecialchars($string) {
204 if (strlen($string) < 1) {
207 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
208 $trans = get_html_translation_table(HTML_ENTITIES);
209 $trans = array_flip ($trans);
210 $str = strtr ($string, $trans);
216 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
218 * @param string The result set ID
219 * @param int The column key
220 * @param int The optional column value
221 * @returns An associative array
224 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
225 $rows=db_numrows($result);
229 for ($i=0; $i<$rows; $i++) {
230 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
239 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
241 * @param int The result set ID
242 * @param int The column
246 function &util_result_column_to_array($result, $col=0) {
248 Takes a result set and turns the optional column into
251 $rows=db_numrows($result);
255 for ($i=0; $i<$rows; $i++) {
256 $arr[$i]=db_result($result,$i,$col);
265 * util_wrap_find_space() - Find the first space in a string
267 * @param string The string in which to find the space
268 * @param int The number of characters to wrap - Default is 80
269 * @returns The position of the first space
272 function util_wrap_find_space($string,$wrap) {
279 //find the first space starting at $start
280 $pos=@strpos($string,' ',$start);
282 //if that space is too far over, go back and start more to the left
283 if (($pos > ($wrap+5)) || !$pos) {
285 $start=($wrap-($try*5));
286 //if we've gotten so far left , just truncate the line
300 * util_line_wrap() - Automatically linewrap text
302 * @param string The text to wrap
303 * @param int The number of characters to wrap - Default is 80
304 * @param string The line break to use - Default is '\n'
305 * @returns The wrapped text
308 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
309 $paras = explode("\n", $text);
313 while ($i < count($paras)) {
314 if (strlen($paras[$i]) <= $wrap) {
315 $result[] = $paras[$i];
318 $pos=util_wrap_find_space($paras[$i],$wrap);
320 $result[] = substr($paras[$i], 0, $pos);
322 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
325 $pos=util_wrap_find_space($paras[$i],$wrap);
331 return implode($break, $result);
335 * util_make_links() - Turn URL's into HREF's.
337 * @param string The URL
338 * @returns The HREF'ed URL
341 function util_make_links ($data='') {
342 if(empty($data)) { return $data; }
344 $lines = split("\n",$data);
345 while ( list ($key,$line) = each ($lines)) {
346 // When we come here, we usually have form input
347 // encoded in entities. Our aim is to NOT include
348 // angle brackets in the URL
349 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
350 $line = str_replace('>', "\1", $line);
351 $line = eregi_replace("([ \t]|^)www\."," http://www.",$line);
352 $text = eregi_replace("([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
353 $text = eregi_replace("([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $text);
354 $text = str_replace("\1", '>', $text);
361 * show_priority_colors_key() - Show the priority colors legend
364 function show_priority_colors_key() {
366 echo '<p /><strong> '.$Language->getText('common_utils','priority_colors').':</strong><br />
368 <table border="0"><tr>';
370 for ($i=1; $i<10; $i++) {
372 <td bgcolor="'.html_get_priority_color($i).'">'.$i.'</td>';
374 echo '</tr></table>';
378 * utils_buildcheckboxarray() - Build a checkbox array
380 * @param int Number of options to be in the array
381 * @param string The name of the checkboxes
382 * @param array An array of boxes to be pre-checked
385 function utils_buildcheckboxarray($options,$name,$checked_array) {
386 $option_count=count($options);
387 $checked_count=count($checked_array);
389 for ($i=1; $i<=$option_count; $i++) {
391 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
392 for ($j=0; $j<$checked_count; $j++) {
393 if ($i == $checked_array[$j]) {
397 echo '> '.$options[$i];
402 * utils_requiredField() - Adds the required field marker
404 * @return a string holding the HTML to mark a required field
406 function utils_requiredField() {
407 return '<span><font color="red">*</font></span>';
411 * GraphResult() - Takes a database result set and builds a graph.
412 * The first column should be the name, and the second column should be the values
413 * Be sure to include HTL_Graphs.php before using this function
415 * @author Tim Perdue tperdue@valinux.com
416 * @param int The databse result set ID
417 * @param string The title of the graph
420 Function GraphResult($result,$title) {
421 $rows=db_numrows($result);
423 if ((!$result) || ($rows < 1)) {
429 for ($j=0; $j<db_numrows($result); $j++) {
430 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
431 $names[$j]= db_result($result, $j, 0);
432 $values[$j]= db_result($result, $j, 1);
437 This is another function detailed below
439 GraphIt($names,$values,$title);
444 * GraphIt() - Build a graph
446 * @author Tim Perdue tperdue@valinux.com
447 * @param array An array of names
448 * @param array An array of values
449 * @param string The title of the graph
452 Function GraphIt($name_string,$value_string,$title) {
455 $counter=count($name_string);
458 Can choose any color you wish
462 for ($i = 0; $i < $counter; $i++) {
463 $bars[$i]=$HTML->COLOR_LTBACK1;
466 $counter=count($value_string);
469 Figure the max_value passed in, so scale can be determined
474 for ($i = 0; $i < $counter; $i++) {
475 if ($value_string[$i] > $max_value) {
476 $max_value=$value_string[$i];
480 if ($max_value < 1) {
485 I want my graphs all to be 800 pixels wide, so that is my divisor
488 $scale=(400/$max_value);
491 I create a wrapper table around the graph that holds the title
497 echo $GLOBALS['HTML']->listTableTop ($title_arr);
500 Create an associate array to pass in. I leave most of it blank
529 This is the actual call to the HTML_Graphs class
532 html_graph($name_string,$value_string,$bars,$vals);
536 <!-- end outer graph table -->';
537 echo $GLOBALS['HTML']->listTableBottom();
541 * ShowResultSet() - Show a generic result set
542 * Very simple, plain way to show a generic result set
544 * @param int The result set ID
545 * @param string The title of the result set
546 * @param bool The option to turn URL's into links
549 function ShowResultSet($result,$title="Untitled",$linkify=false) {
550 global $group_id,$HTML;
553 $rows = db_numrows($result);
554 $cols = db_numfields($result);
557 <table border="0" width="100%">';
559 /* Create the title */
562 $cell_data[] = array($title, 'colspan="'.$cols.'"');
563 echo $HTML->multiTableRow('',$cell_data, TRUE);
565 /* Create the headers */
567 for ($i=0; $i < $cols; $i++) {
568 $cell_data[] = array(db_fieldname($result,$i));
570 echo $HTML->multiTableRow('',$cell_data, TRUE);
572 /* Create the rows */
573 for ($j = 0; $j < $rows; $j++) {
574 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
575 for ($i = 0; $i < $cols; $i++) {
576 if ($linkify && $i == 0) {
577 $link = '<a href="'.$PHP_SELF.'?';
579 if ($linkify == "bug_cat") {
580 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
581 } else if($linkify == "bug_group") {
582 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
583 } else if($linkify == "patch_cat") {
584 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
585 } else if($linkify == "support_cat") {
586 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
587 } else if($linkify == "pm_project") {
588 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
590 $link = $linkend = '';
593 $link = $linkend = '';
595 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
606 * validate_email() - Validate an email address
608 * @param string The address string to validate
609 * @returns true on success/false on error
612 function validate_email ($address) {
613 return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address));
617 * util_is_valid_filename() - Verifies whether a file has a valid filename
619 * @param string The file to verify
620 * @returns true on success/false on error
623 function util_is_valid_filename ($file) {
625 $invalidchars = eregi_replace("[-A-Z0-9_\.]","",$file);
627 if (!empty($invalidchars)) {
630 if (strstr($file,'..')) {
639 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
641 * @param string The optional hostname string
642 * @returns true on success/false on failur
645 function valid_hostname ($hostname = "xyz") {
648 $invalidchars = eregi_replace("[-A-Z0-9\.]","",$hostname);
650 if (!empty($invalidchars)) {
654 //double dot, starts with a . or -
655 if (ereg("\.\.",$hostname) || ereg("^\.",$hostname) || ereg("^\-",$hostname)) {
659 $multipoint = explode(".",$hostname);
661 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {