4 * utils.php - Misc utils common to all aspects of the site
6 * SourceForge: Breaking Down the Barriers to Open Source Development
7 * Copyright 1999-2001 (c) VA Linux Systems
8 * http://sourceforge.net
16 * util_check_fileupload() - determines if a filename is appropriate for upload
18 * @param string The name of the file being uploaded
20 function util_check_fileupload($filename) {
22 /* Empty file is a valid file.
23 This is because this function should be called
24 unconditionally at the top of submit action processing
25 and many forms have optional file upload. */
26 if ($filename == 'none' || $filename == '') {
30 /* This should be enough... */
31 if (!is_uploaded_file($filename)) {
34 /* ... but we'd rather be paranoic */
35 if (strstr($filename, '..')) {
38 if (!is_file($filename)) {
41 if (!file_exists($filename)) {
44 if (dirname($filename) != '/tmp') {
51 * util_send_message() - Send email
52 * This function should be used in place of the PHP mail() function
54 * @param string The email recipients address
55 * @param string The email subject
56 * @param string The body of the email message
57 * @param string The optional email sender address. Defaults to 'noreply@'
58 * @param string The addresses to blind-carbon-copy this message
61 function util_send_message($to,$subject,$body,$from='',$BCC='') {
63 $to='noreply@'.$GLOBALS['sys_default_domain'];
66 $from='noreply@'.$GLOBALS['sys_default_domain'];
69 $to='noreply@'.$GLOBALS['sys_default_domain'];
74 "\nSubject: $subject".
77 exec ("/bin/echo \"". util_prep_string_for_sendmail($body) .
78 "\" | /usr/sbin/sendmail -f'$from' -t -i >& /dev/null &");
81 function util_send_jabber($to,$subject,$body) {
82 if (!$GLOBALS['sys_use_jabber']) {
85 $JABBER = new Jabber();
86 if (!$JABBER->Connect()) {
87 echo '<br />Unable to connect';
90 //$JABBER->SendAuth();
91 //$JABBER->AccountRegistration();
92 if (!$JABBER->SendAuth()) {
93 echo '<br />Auth Failure';
94 $JABBER->Disconnect();
96 //or die("Couldn't authenticate!");
98 $JABBER->SendPresence(NULL, NULL, "online");
100 $body=htmlspecialchars($body);
101 $to_arr=explode(',',$to);
102 for ($i=0; $i<count($to_arr); $i++) {
104 //echo '<br />Sending Jabbers To: '.$to_arr[$i];
105 if (!$JABBER->SendMessage($to_arr[$i], "normal", NULL, array("body" => $body,"subject"=>$subject))) {
106 echo '<br />Error Sending to '.$to_arr[$i];
111 $JABBER->CruiseControl(2);
112 $JABBER->Disconnect();
116 * util_prep_string_for_sendmail() - Prepares a string to be sent by email
118 * @param string The text to be prepared
119 * @returns The prepared text
122 function util_prep_string_for_sendmail($body) {
123 //$body=str_replace("\\","\\\\",$body);
124 $body=str_replace("`","\\`",$body);
125 $body=str_replace("\"","\\\"",$body);
126 $body=str_replace("\$","\\\$",$body);
131 * util_handle_message() - a convenience wrapper which sends messages
132 * to either a jabber account or email account or both, depending on
135 * @param array array of user_id's from the user table
136 * @param string subject of the message
137 * @param string the message body
138 * @param string a comma-separated list of email address
139 * @param string a comma-separated list of jabber address
141 function util_handle_message($id_arr,$subject,$body,$extra_emails='',$extra_jabbers='') {
144 if (count($id_arr) < 1) {
147 $res=db_query("SELECT jabber_address,email,jabber_only
148 FROM users WHERE user_id IN (". implode($id_arr,',') .")");
149 $rows=db_numrows($res);
151 for ($i=0; $i<$rows; $i++) {
153 // Build arrays of the jabber address
155 if (db_result($res,$i,'jabber_address')) {
156 $address['jabber_address'][]=db_result($res,$i,'jabber_address');
157 if (db_result($res,$i,'jabber_only') != 1) {
158 $address['email'][]=db_result($res,$i,'email');
161 $address['email'][]=db_result($res,$i,'email');
164 if (count($address['email']) > 0) {
165 $extra_email1=implode($address['email'],',').',';
167 if (count($address['jabber_address']) > 0) {
168 $extra_jabber1=implode($address['jabber_address'],',').',';
171 if ($extra_email1 || $extra_emails) {
172 util_send_message('',$subject,$body,'',$extra_email1.$extra_emails);
174 if ($extra_jabber1 || $extra_jabbers) {
175 util_send_jabber($extra_jabber1.$extra_jabbers,$subject,$body);
180 * util_unconvert_htmlspecialchars() - Unconverts a string converted with htmlspecialchars()
181 * This function requires PHP 4.0.3 or greater
183 * @param string The string to unconvert
184 * @returns The unconverted string
187 function util_unconvert_htmlspecialchars($string) {
188 if (strlen($string) < 1) {
191 //$trans = get_html_translation_table(HTMLENTITIES, ENT_QUOTES);
192 $trans = get_html_translation_table(HTML_ENTITIES);
193 $trans = array_flip ($trans);
194 $str = strtr ($string, $trans);
200 * util_result_columns_to_assoc() - Takes a result set and turns the column pair into an associative array
202 * @param string The result set ID
203 * @param int The column key
204 * @param int The optional column value
205 * @returns An associative array
208 function util_result_columns_to_assoc($result, $col_key=0, $col_val=1) {
209 $rows=db_numrows($result);
213 for ($i=0; $i<$rows; $i++) {
214 $arr[db_result($result,$i,$col_key)]=db_result($result,$i,$col_val);
223 * util_result_column_to_array() - Takes a result set and turns the optional column into an array
225 * @param int The result set ID
226 * @param int The column
230 function &util_result_column_to_array($result, $col=0) {
232 Takes a result set and turns the optional column into
235 $rows=db_numrows($result);
239 for ($i=0; $i<$rows; $i++) {
240 $arr[$i]=db_result($result,$i,$col);
249 * util_wrap_find_space() - Find the first space in a string
251 * @param string The string in which to find the space
252 * @param int The number of characters to wrap - Default is 80
253 * @returns The position of the first space
256 function util_wrap_find_space($string,$wrap) {
263 //find the first space starting at $start
264 $pos=@strpos($string,' ',$start);
266 //if that space is too far over, go back and start more to the left
267 if (($pos > ($wrap+5)) || !$pos) {
269 $start=($wrap-($try*5));
270 //if we've gotten so far left , just truncate the line
284 * util_line_wrap() - Automatically linewrap text
286 * @param string The text to wrap
287 * @param int The number of characters to wrap - Default is 80
288 * @param string The line break to use - Default is '\n'
289 * @returns The wrapped text
292 function util_line_wrap ($text, $wrap = 80, $break = "\n") {
293 $paras = explode("\n", $text);
297 while ($i < count($paras)) {
298 if (strlen($paras[$i]) <= $wrap) {
299 $result[] = $paras[$i];
302 $pos=util_wrap_find_space($paras[$i],$wrap);
304 $result[] = substr($paras[$i], 0, $pos);
306 $new = trim(substr($paras[$i], $pos, strlen($paras[$i]) - $pos));
309 $pos=util_wrap_find_space($paras[$i],$wrap);
315 return implode($break, $result);
319 * util_make_links() - Turn URL's into HREF's.
321 * @param string The URL
322 * @returns The HREF'ed URL
325 function util_make_links ($data='') {
326 if(empty($data)) { return $data; }
328 $lines = split("\n",$data);
329 while ( list ($key,$line) = each ($lines)) {
330 // When we come here, we usually have form input
331 // encoded in entities. Our aim is to NOT include
332 // angle brackets in the URL
333 // (RFC2396; http://www.w3.org/Addressing/URL/5.1_Wrappers.html)
334 $line = str_replace('>', "\1", $line);
335 $line = eregi_replace("([ \t]|^)www\."," http://www.",$line);
336 $text = eregi_replace("([[:alnum:]]+)://([^[:space:]<\1]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_new\">\\1://\\2\\3</a>", $line);
337 $text = eregi_replace("([[:space:]]|^)(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "\\1<a href=\"mailto:\\2\" target=\"_new\">\\2</a>", $text);
338 $text = str_replace("\1", '>', $text);
345 * show_priority_colors_key() - Show the priority colors legend
348 function show_priority_colors_key() {
350 echo '<p><strong>Priority Colors:</strong><br />
352 <table border=0><tr>';
354 for ($i=1; $i<10; $i++) {
356 <td bgcolor="'.html_get_priority_color($i).'">'.$i.'</td>';
358 echo '</tr></table>';
362 * utils_buildcheckboxarray() - Build a checkbox array
364 * @param int Number of options to be in the array
365 * @param string The name of the checkboxes
366 * @param array An array of boxes to be pre-checked
369 function utils_buildcheckboxarray($options,$name,$checked_array) {
370 $option_count=count($options);
371 $checked_count=count($checked_array);
373 for ($i=1; $i<=$option_count; $i++) {
375 <br /><input type="checkbox" name="'.$name.'" value="'.$i.'"';
376 for ($j=0; $j<$checked_count; $j++) {
377 if ($i == $checked_array[$j]) {
381 echo '> '.$options[$i];
386 * utils_requiredField() - Adds the required field marker
388 * @return a string holding the HTML to mark a required field
390 function utils_requiredField() {
391 return '<span><font color="red">*</font></span>';
395 * GraphResult() - Takes a database result set and builds a graph.
396 * The first column should be the name, and the second column should be the values
397 * Be sure to include HTL_Graphs.php before using this function
399 * @author Tim Perdue tperdue@valinux.com
400 * @param int The databse result set ID
401 * @param string The title of the graph
404 Function GraphResult($result,$title) {
405 $rows=db_numrows($result);
407 if ((!$result) || ($rows < 1)) {
413 for ($j=0; $j<db_numrows($result); $j++) {
414 if (db_result($result, $j, 0) != '' && db_result($result, $j, 1) != '' ) {
415 $names[$j]= db_result($result, $j, 0);
416 $values[$j]= db_result($result, $j, 1);
421 This is another function detailed below
423 GraphIt($names,$values,$title);
428 * GraphIt() - Build a graph
430 * @author Tim Perdue tperdue@valinux.com
431 * @param array An array of names
432 * @param array An array of values
433 * @param string The title of the graph
436 Function GraphIt($name_string,$value_string,$title) {
439 $counter=count($name_string);
442 Can choose any color you wish
446 for ($i = 0; $i < $counter; $i++) {
447 $bars[$i]=$HTML->COLOR_LTBACK1;
450 $counter=count($value_string);
453 Figure the max_value passed in, so scale can be determined
458 for ($i = 0; $i < $counter; $i++) {
459 if ($value_string[$i] > $max_value) {
460 $max_value=$value_string[$i];
464 if ($max_value < 1) {
469 I want my graphs all to be 800 pixels wide, so that is my divisor
472 $scale=(400/$max_value);
475 I create a wrapper table around the graph that holds the title
481 echo $GLOBALS['HTML']->listTableTop ($title_arr);
484 Create an associate array to pass in. I leave most of it blank
513 This is the actual call to the HTML_Graphs class
516 html_graph($name_string,$value_string,$bars,$vals);
520 <!-- end outer graph table -->';
521 echo $GLOBALS['HTML']->listTableBottom();
525 * ShowResultSet() - Show a generic result set
526 * Very simple, plain way to show a generic result set
528 * @param int The result set ID
529 * @param string The title of the result set
530 * @param bool The option to turn URL's into links
533 Function ShowResultSet($result,$title="Untitled",$linkify=false) {
534 global $group_id,$HTML;
537 $rows = db_numrows($result);
538 $cols = db_numfields($result);
541 <table border="0" width="100%">';
543 /* Create the title */
546 $cell_data[] = array($title, 'colspan='.$cols);
547 echo $HTML->multiTableRow('',$cell_data, TRUE);
549 /* Create the headers */
551 for ($i=0; $i < $cols; $i++) {
552 $cell_data[] = array(db_fieldname($result,$i));
554 echo $HTML->multiTableRow('',$cell_data, TRUE);
556 /* Create the rows */
557 for ($j = 0; $j < $rows; $j++) {
558 echo '<tr '. $HTML->boxGetAltRowStyle($j) . '>';
559 for ($i = 0; $i < $cols; $i++) {
560 if ($linkify && $i == 0) {
561 $link = '<a href="'.$PHP_SELF.'?';
563 if ($linkify == "bug_cat") {
564 $link .= 'group_id='.$group_id.'&bug_cat_mod=y&bug_cat_id='.db_result($result, $j, 'bug_category_id').'">';
565 } else if($linkify == "bug_group") {
566 $link .= 'group_id='.$group_id.'&bug_group_mod=y&bug_group_id='.db_result($result, $j, 'bug_group_id').'">';
567 } else if($linkify == "patch_cat") {
568 $link .= 'group_id='.$group_id.'&patch_cat_mod=y&patch_cat_id='.db_result($result, $j, 'patch_category_id').'">';
569 } else if($linkify == "support_cat") {
570 $link .= 'group_id='.$group_id.'&support_cat_mod=y&support_cat_id='.db_result($result, $j, 'support_category_id').'">';
571 } else if($linkify == "pm_project") {
572 $link .= 'group_id='.$group_id.'&project_cat_mod=y&project_cat_id='.db_result($result, $j, 'group_project_id').'">';
574 $link = $linkend = '';
577 $link = $linkend = '';
579 echo '<td>'.$link . db_result($result, $j, $i) . $linkend.'</td>';
590 * validate_email() - Validate an email address
592 * @param string The address string to validate
593 * @returns true on success/false on error
596 function validate_email ($address) {
597 return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address));
601 * util_is_valid_filename() - Verifies whether a file has a valid filename
603 * @param string The file to verify
604 * @returns true on success/false on error
607 function util_is_valid_filename ($file) {
609 $invalidchars = eregi_replace("[-A-Z0-9_\.]","",$file);
611 if (!empty($invalidchars)) {
614 if (strstr($file,'..')) {
623 * valid_hostname() - Validates a hostname string to make sure it doesn't contain invalid characters
625 * @param string The optional hostname string
626 * @returns true on success/false on failur
629 function valid_hostname ($hostname = "xyz") {
632 $invalidchars = eregi_replace("[-A-Z0-9\.]","",$hostname);
634 if (!empty($invalidchars)) {
638 //double dot, starts with a . or -
639 if (ereg("\.\.",$hostname) || ereg("^\.",$hostname) || ereg("^\-",$hostname)) {
643 $multipoint = explode(".",$hostname);
645 if (!(is_array($multipoint)) || ((count($multipoint) - 1) < 1)) {