cleanup
[bMailZu.git] / lib / CmnFns.class.php
blob82cbeb85d3e1c3976a5adde0e59ec9e3d9df6500
1 <?php
2 /**
3 * These functions common to most pages
5 * @author Samuel Tran <stran2005@users.sourceforge.net>
6 * @author Brian Wong <bwsource@users.sourceforge.net>
7 * @author Jeremy Fowler <jfowler06@users.sourceforge.net>
8 * @package MailZu
10 * Following functions taken from PhpScheduleIt,
11 * @author Nick Korbel <lqqkout13@users.sourceforge.net>
12 * @version 04-03-07:
13 * formatTime(), formatDate(), formatDateTime(), minutes_to_hours(), getScriptURL(),
14 * do_error_box(), do_message_box(), getNewLink(), getNewPager(), cleanPostVals(),
15 * get_vert_order(), get_value_order(), write_log(), get_day_name(), redirect(),
16 * print_language_pulldown(), html_activate_links()
18 * Copyright (C) 2005 - 2007 MailZu
19 * License: GPL, see LICENSE
21 /**
22 * Base directory of application
24 @define('BASE_DIR', dirname(__FILE__) . '/..');
25 /**
26 * Include configuration file
27 **/
28 include_once(BASE_DIR . '/config/config.php');
29 /**
30 * Include Link class
32 include_once('Link.class.php');
33 /**
34 * Include Pager class
36 include_once('Pager.class.php');
38 // Define constants for method getGlobalVar()
39 @define('INORDER',0);
40 @define('GET',1);
41 @define('POST',2);
42 @define('SESSION',3);
43 @define('SERVER',4);
44 @define('FORM',5);
46 /**
47 * Provides functions common to most pages
49 class CmnFns {
51 /**
52 * Convert minutes to hours
53 * @param double $time time to convert in minutes
54 * @return string time in 12 hour time
56 function formatTime($time) {
57 global $conf;
59 // Set up time array with $timeArray[0]=hour, $timeArray[1]=minute
60 // If time does not contain decimal point
61 // then set time array manually
62 // else explode on the decimal point
63 $hour = intval($time / 60);
64 $min = $time % 60;
65 if ($conf['app']['timeFormat'] == 24) {
66 $a = ''; // AM/PM does not exist
67 if ($hour < 10) $hour = '0' . $hour;
69 else {
70 $a = ($hour < 12 || $hour == 24) ? translate('am') : translate('pm'); // Set am/pm
71 if ($hour > 12) $hour = $hour - 12; // Take out of 24hr clock
72 if ($hour == 0) $hour = 12; // Don't show 0hr, show 12 am
74 // Set proper minutes (the same for 12/24 format)
75 if ($min < 10) $min = 0 . $min;
76 // Put into a string and return
77 return $hour . ':' . $min . $a;
80 /**
81 * Convert ISO8601 date to date format
82 * @param string $date string (yyyy-mm-dd)
83 * @return int timestamp
85 function formatDateISO($date) {
87 $time = strtotime($date);
88 return $time;
91 /**
92 * Convert timestamp to date format
93 * @param string $date timestamp
94 * @param string $format format to put datestamp into
95 * @return string date as $format or as default format
97 function formatDate($date, $format = '') {
98 global $dates;
100 if (empty($format)) $format = $dates['general_date'];
101 return strftime($format, $date);
106 * Convert UNIX timestamp to datetime format
107 * @param string $ts MySQL timestamp
108 * @param string $format format to put datestamp into
109 * @return string date/time as $format or as default format
111 function formatDateTime($ts, $format = '') {
112 global $conf;
113 global $dates;
115 if (empty($format))
116 $format = $dates['general_datetime'] . ' ' . (($conf['app']['timeFormat'] ==24) ? '%H' : '%I') . ':%M:%S' . (($conf['app']['timeFormat'] == 24) ? '' : ' %p');
117 return strftime($format, $ts);
122 * Convert minutes to hours/minutes
123 * @param int $minutes minutes to convert
124 * @return string version of hours and minutes
126 function minutes_to_hours($minutes) {
127 if ($minutes == 0)
128 return '0 ' . translate('hours');
130 $hours = (intval($minutes / 60) != 0) ? intval($minutes / 60) . ' ' . translate('hours') : '';
131 $min = (intval($minutes % 60) != 0) ? intval($minutes % 60) . ' ' . translate('minutes') : '';
132 return ($hours . ' ' . $min);
136 * Return the current script URL directory
137 * @param none
138 * @return url url of curent script directory
140 function getScriptURL() {
141 global $conf;
142 $uri = $conf['app']['weburi'];
143 return (strrpos($uri, '/') === false) ? $uri : substr($uri, 0, strlen($uri));
148 * Prints an error message box and kills the app
149 * @param string $msg error message to print
150 * @param string $style inline CSS style definition to apply to box
151 * @param boolean $die whether to kill the app or not
153 function do_error_box($msg, $style='', $die = true) {
154 global $conf;
156 echo '<table border="0" cellspacing="0" cellpadding="0" align="center" class="alert" style="' . $style . '"><tr><td>' . $msg . '</td></tr></table>';
158 if ($die) {
159 echo '</td></tr></table>'; // endMain() in Template
160 echo '<p align="center"><a href="http://www.mailzu.net">' . $conf['app']['title'] .' v' . $conf['app']['version'] . '</a></p></body></html>'; // printHTMLFooter() in Template
162 //$t = new Template();
163 //$t->endMain();
164 //$t->printHTMLFooter();
165 die();
170 * Prints out a box with notification message
171 * @param string $msg message to print out
172 * @param string $style inline CSS style definition to apply to box
174 function do_message_box($msg, $style='') {
175 echo '<table border="0" cellspacing="0" cellpadding="0" align="center" class="message" style="' . $style . '"><tr><td>' . $msg . '</td></tr></table>';
179 * Returns a reference to a new Link object
180 * Used to make HTML links
181 * @param none
182 * @return Link object
184 function getNewLink() {
185 return new Link();
189 * Returns a reference to a new Pager object
190 * Used to iterate over limited recordesets
191 * @param none
192 * @return Pager object
194 function getNewPager() {
195 return new Pager();
199 * Strip out slahses from POST values
200 * @param none
201 * @return array of cleaned up POST values
203 function cleanPostVals() {
204 $return = array();
206 foreach ($_POST as $key => $val)
207 $return[$key] = stripslashes(trim($val));
209 return $return;
213 * Strip out slahses from an array of data
214 * @param none
215 * @return array of cleaned up data
217 function cleanVals($data) {
218 $return = array();
220 foreach ($data as $key => $val)
221 $return[$key] = stripslashes($val);
223 return $return;
227 * Verifies vertical order and returns value
228 * @param string $vert value of vertical order
229 * @return string vertical order
231 function get_vert_order($get_name = 'vert') {
232 // If no vertical value is specified, use DESC
233 $vert = isset($_GET[$get_name]) ? $_GET[$get_name] : 'DESC';
235 // Validate vert value, default to DESC if invalid
236 switch($vert) {
237 case 'DESC';
238 case 'ASC';
239 break;
240 default :
241 $vert = 'DESC';
242 break;
245 return $vert;
249 * Verifies and returns the order to list recordset results by
250 * If none of the values are valid, it will return the 1st element in the array
251 * @param array $orders all valid order names
252 * @return string order of recorset
254 function get_value_order($orders = array(), $get_name = 'order') {
255 if (empty($orders)) // Return null if the order array is empty
256 return NULL;
258 // Set default order value
259 // If a value is specifed in GET, use that. Else use the first element in the array
260 $order = isset($_GET[$get_name]) ? $_GET[$get_name] : $orders[0];
262 if (in_array($order, $orders))
263 $order = $order;
264 else
265 $order = $orders[0];
267 return $order;
272 * Opposite of php's nl2br function.
273 * Subs in a newline for all brs
274 * @param string $subject line to make subs on
275 * @return reformatted line
277 function br2nl($subject) {
278 return str_replace('<br />', "\n", $subject);
282 * Writes a log string to the log file specified in config.php
283 * @param string $string log entry to write to file
284 * @param string $userid memeber id of user performing the action
285 * @param string $ip ip address of user performing the action
287 function write_log($string, $userid = NULL, $ip = NULL) {
288 global $conf;
289 $delim = "\t";
290 $file = $conf['app']['logfile'];
291 $values = '';
293 if (!$conf['app']['use_log']) // Return if we aren't going to log
294 return;
296 if (empty($ip))
297 $ip = $_SERVER['REMOTE_ADDR'];
299 clearstatcache(); // Clear cached results
301 if (!is_dir(dirname($file)))
302 mkdir(dirname($file), 0777); // Create the directory
304 if (!touch($file))
305 return; // Return if we cant touch the file
307 if (!$fp = fopen($file, 'a'))
308 return; // Return if the fopen fails
310 flock($fp, LOCK_EX); // Lock file for writing
311 if (!fwrite($fp, '[' . date('D, d M Y H:i:s') . ']' . $delim . $ip . $delim . $userid . $delim . $string . "\r\n")) // Write log entry
312 return; // Return if we cant write to the file
313 flock($fp, LOCK_UN); // Unlock file
314 fclose($fp);
318 * Returns the day name
319 * @param int $day_of_week day of the week
320 * @param int $type how to return the day name (0 = full, 1 = one letter, 2 = two letter, 3 = three letter)
322 function get_day_name($day_of_week, $type = 0) {
323 global $days_full;
324 global $days_abbr;
325 global $days_letter;
326 global $days_two;
328 $names = array (
329 $days_full, $days_letter, $days_two, $days_letter
331 array ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
332 array ('S', 'M', 'T', 'W', 'T', 'F', 'S'),
333 array ('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'),
334 array ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')
338 return $names[$type][$day_of_week];
342 * Redirects a user to a new location
343 * @param string $location new http location
344 * @param int $time time in seconds to wait before redirect
346 function redirect($location, $time = 0, $die = true) {
347 header("Refresh: $time; URL=$location");
348 if ($die) exit;
352 * Prints out the HTML to choose a language
353 * @param none
355 function print_language_pulldown() {
356 global $conf;
358 <select name="language" class="textbox" onchange="changeLanguage(this);">
360 $languages = get_language_list();
361 foreach ($languages as $lang => $settings) {
362 echo '<option value="' . $lang . '"'
363 . ((determine_language() == $lang) ? ' selected="selected"' : '' )
364 . '>' . $settings[3] . ($lang == $conf['app']['defaultLanguage'] ? ' ' . translate('(Default)') : '') . "</option>\n";
367 </select>
372 * Searches the input string and creates links out of any properly formatted 'URL-like' text
373 * Written by Fredrik Kristiansen (russlndr at online.no)
374 * and Albrecht Guenther (ag at phprojekt.de).
375 * @param string $str string to search for links to create
376 * @return string with 'URL-like' text changed into clickable links
378 function html_activate_links($str) {
379 $str = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', '<a href="\1" target="_blank">\1</a>', $str);
380 $str = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', '\1<a href="http://\2" target="_blank">\2</a>', $str);
381 $str = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})','<a href="mailto:\1">\1</a>', $str);
382 return $str;
387 * Verifies current page number and returns value
388 * @param integer $page value of current page number
389 * @return integer current page number
391 function get_current_page_number($get_name = 'page') {
392 // If no page number is specified, use 0
393 $page = ( isset($_GET[$get_name]) && is_numeric($_GET[$get_name]) ) ? $_GET[$get_name] : 0;
394 return $page;
398 * Gets the requested mail_id
399 * @param none
400 * @return string mail_id
402 function get_mail_id($get_name = 'mail_id') {
403 // If there isnt one set, return NULL
404 $mail_id = (isset($_GET[$get_name])) ? $_GET[$get_name] : NULL;
405 return $mail_id;
409 * Verifies and returns the order to list recordset results by
411 * Convert an array to a query string
412 * @param array $array
413 * @param array $exclude_vars to be excluded from the resulting string
414 * @param boolean $url_encode_ampersands
416 function array_to_query_string( $array, $exclude_vars=array(), $url_encode_ampersands=true )
418 if( ! is_array( $array ) )
419 return '';
420 if( ! $array )
421 return '';
422 $str = '';
423 $i=0;
424 foreach( $array as $name => $val ) {
425 if( ! in_array( $name, $exclude_vars ) ) {
426 if( $i>0 )
427 if( $url_encode_ampersands )
428 $str .= '&amp;';
429 else
430 $str .= '&';
431 $str .= urlencode( $name ) . '=' . urlencode( $val );
432 $i++;
435 return $str;
439 * Generate HTML for multipage links
440 * @param integer $page current page
441 * @param integer $sizeLimit maximum number of messages per page
442 * @param integer $count total number of messages
444 function genMultiPagesLinks( $page, $sizeLimit, $count) {
445 global $link;
447 $total_pages = $count / $sizeLimit;
449 $php_self = $_SERVER['PHP_SELF'];
451 if( $page != 0 ) {
452 $query_string = CmnFns::array_to_query_string( $_GET, array( 'page' ) );
453 $query_string_first = $query_string . '&page=0';
454 $query_string_previous = $query_string . '&page=' . ($page-1);
455 $pager_html .= $link->getLink($php_self . '?' . $query_string_first, translate('first'), '', '', translate('Go to first page')) . " | ";
456 $pager_html .= $link->getLink($php_self . '?' . $query_string_previous, translate('previous'), '', '', translate('Go to previous page')) . " | ";
457 } else {
458 $pager_html .= translate('first') . " | " . translate('previous') ." | ";
461 $pager_html .= '&nbsp;&nbsp;';
463 // for large search results where we page beyone the first 20 pages,
464 // print elipsis instead of making the pager be super wide.
465 $elipsis_printed = false;
467 for( $i=0; $i<$count; $i+=$sizeLimit ) {
468 $page_num = $i/$sizeLimit;
469 if( $count > $size_limit * 20 && abs( $page_num - $page ) > 10 ) {
470 if( ! $elipsis_printed ) {
471 $pager_html .= '...&nbsp;&nbsp;';
472 $elipsis_printed = true;
474 } else if( $page == $page_num ) {
475 $pager_html .= '<b>' . ($page_num + 1) . '</b>';
476 $pager_html .= '&nbsp;&nbsp;';
477 $elipsis_printed = false;
478 } else {
479 $query_string = CmnFns::array_to_query_string( $_GET, array( 'page' ) );
480 $query_string .= '&page=' . $page_num;
481 $pager_html .= $link->getLink($php_self . '?' . $query_string, ($page_num+1), '', '', translate('Go to page') . ' ' . ($page_num+1));
482 $pager_html .= '&nbsp;&nbsp;';
483 $elipsis_printed = false;
487 if( $page+1 < $total_pages ) {
488 $query_string = CmnFns::array_to_query_string( $_GET, array( 'page' ) );
489 $query_string_next .= $query_string . '&page=' . ($page+1);
490 $query_string_last .= $query_string . '&page=' . (ceil($total_pages)-1);
491 $pager_html .= ' | ' . $link->getLink($php_self . '?' . $query_string_next, strtolower(translate('Next')), '', '', translate('Go to next page'));
492 $pager_html .= ' | ' . $link->getLink($php_self . '?' . $query_string_last, translate('last'), '', '', translate('Go to last page'));
493 } else {
494 $pager_html .= " | " . strtolower(translate('Next')) . " | " . translate('last');
497 return $pager_html;
501 * Generate HTML for search engine
502 * @param $content_type: 'B' (attachment) or 'S' (spam)
504 function searchEngine($content_type, $submit_page, $full_search = false) {
505 global $conf;
507 $fields_array = array("f" => translate('From'),
508 "s" => translate('Subject')
510 if (Auth::isMailAdmin() || $conf['app']['allowMailid']) {
511 $fields_array = array_merge(array("m" => "Mail ID"), $fields_array);
513 if ($full_search) $fields_array = array_merge(array("t" => translate('To')), $fields_array);
516 <table border=0 width="100%">
517 <form action="<? echo $submit_page ?>" method="get" name="quarantine">
519 <tr><td colspan=2 align="center"><? echo translate('Search for messages whose:'); ?>&nbsp;</td></tr>
520 <tr><td align="right">&nbsp;
522 $i = 1;
523 $array_size = count($fields_array);
524 foreach ($fields_array as $k => $name) {
525 echo "\t\t\t$name: \n";
526 echo "\t\t\t<select name='" . $k . "_criterion' class='button'>\n";
527 echo "\t\t\t<option value='contains'";
528 echo "contains" == CmnFns::getGlobalVar($k . '_criterion', GET) ? " selected='true'>" : ">";
529 echo translate('contains') . "</option>\n";
530 echo "\t\t\t<option value='not_contain'";
531 echo "not_contain" == CmnFns::getGlobalVar($k . '_criterion', GET) ? " selected='true'>" : ">";
532 echo translate('doesn\'t contain') . "</option>\n";
533 echo "\t\t\t<option value='equals'";
534 echo "equals" == CmnFns::getGlobalVar($k . '_criterion', GET) ? " selected='true'>" : ">";
535 echo translate('equals') . "</option>\n";
536 echo "\t\t\t<option value='not_equal'";
537 echo "not_equal" == CmnFns::getGlobalVar($k . '_criterion', GET) ? " selected='true'>" : ">";
538 echo translate('doesn\'t equal') . "</option>\n";
539 echo "\t\t\t</select>\n";
540 echo "\t\t\t<input type='text' name='" . $k . "_string' size='20' value='"
541 . CmnFns::getGlobalVar($k . '_string', GET) . "' />\n";
542 echo ($i % 2) ? "\t\t\t&nbsp;</td>\n\t\t\t<td align='left'>&nbsp\n" : "\t\t\t&nbsp;</td></tr>\n\t\t\t<tr><td align='right'>&nbsp\n";
543 $i ++;
546 <? echo translate('Content Type'); ?>:
547 <select name="ctype" class="button">
548 <option value="A" <? echo ($content_type == 'A' ? ' selected="true"':''); ?>>
549 <? echo translate('All'); ?></option>
550 <option value="S" <? echo ($content_type == 'S' ? ' selected="true"':''); ?>>
551 <? echo translate('Spam'); ?></option>
552 <option value="B" <? echo ($content_type == 'B' ? ' selected="true"':''); ?>>
553 <? echo translate('Banned'); ?></option>
554 <? if (Auth::isMailAdmin() || $conf['app']['allowViruses']) { ?>
555 <option value="V" <? echo ($content_type == 'V' ? ' selected="true"':''); ?>>
556 <? echo translate('Virus'); ?></option>
557 <? }
558 if (Auth::isMailAdmin() || $conf['app']['allowBadHeaders']) { ?>
559 <option value="H" <? echo ($content_type == 'H' ? ' selected="true"':''); ?>>
560 <? echo translate('Bad Header'); ?></option>
561 <? }
562 echo "</select>";
563 $i ++;
564 echo ($i % 2) ? "&nbsp;</td></tr>\n\t\t\t<tr><td colspan='2' align='center'>&nbsp\n" : "&nbsp;</td><td align='left'>&nbsp";
566 <input type="submit" class="button" name="search_action" value="<? echo translate('Search'); ?>" />
567 <? if (CmnFns::didSearch())
568 echo "<input type=\"submit\" class=\"button\" name=\"search_action\" value=\"" . translate('Clear search results') . "\" />";
570 &nbsp;</td></tr>
571 </form>
572 </table>
578 * Did we do a search?
579 * @param none
580 * @return value boolean
582 function didSearch() {
583 $return = false;
584 $strings = array('f_string','s_string','t_string','m_string');
585 foreach ($strings as $string) {
586 if ( CmnFns::getGlobalVar($string, GET) != '') $return = true;
588 return $return;
592 * Function that convert $_GET into query string and exclude array
593 * @param array of variables to exclude
594 * @return query string
596 function querystring_exclude_vars( $excl_array = array() ) {
597 return CmnFns::array_to_query_string( $_GET, $excl_array );
601 * Gets the 'ctype' value
602 * @param none
603 * @return value
605 function get_ctype($get_name = 'ctype') {
606 // If there isnt one set, return NULL
607 $result = NULL;
608 if ( isset($_GET[$get_name]) )
609 $result = $_GET[$get_name];
610 elseif ( isset($_POST[$get_name]) )
611 $result = $_POST[$get_name];
612 return $result;
616 * Gets the 'action' value
617 * @param none
618 * @return value
620 function get_action($get_name = 'action') {
621 // If there isnt one set, return NULL
622 $result = (isset($_POST[$get_name])) ? $_POST[$get_name] : NULL;
623 return $result;
627 * Gets the 'query_string' value
628 * @param none
629 * @return value
631 function get_query_string($get_name = 'query_string') {
632 // If there isnt one set, return NULL
633 $result = (isset($_POST[$get_name])) ? $_POST[$get_name] : NULL;
634 return $result;
639 * Search for the var $name in $_SESSION, $_POST, $_GET,
640 * $_SERVER and set it in provided var.
642 * If $search is not provided, or == INORDER, it will search
643 * $_SESSION, then $_POST, then $_GET. Otherwise,
644 * use one of the defined constants to look for
645 * a var in one place specifically.
647 * Note: $search is an int value equal to one of the
648 * constants defined above.
650 * example:
651 * getGlobalVar('page', GET);
652 * -- no quotes around last param!
654 * @param string $name the name of the var to search
655 * @param int search constant defining where to look:
656 * INORDER, SESSION, FORM, POST, GET, SERVER
657 * @return value of var
659 function getGlobalVar($name, $search = INORDER) {
661 switch ($search) {
663 /* we want the default case to be first here,
664 so that if a valid value isn't specified,
665 all four arrays will be searched. */
666 default:
668 case INORDER: // check session, post, get
670 case SESSION:
671 if( isset($_SESSION[$name]) )
672 return $_SESSION[$name];
673 elseif ( $search == SESSION )
674 break;
676 case FORM: // check post, get
678 case POST:
679 if( isset($_POST[$name]) )
680 return $_POST[$name];
681 elseif ( $search == POST )
682 break;
684 case GET:
685 if( isset($_GET[$name]) )
686 return $_GET[$name];
687 /* For INORDER case, exit after GET */
688 break;
690 case SERVER:
691 if( isset($_SERVER[$name]) )
692 return $_SERVER[$name];
693 break;
695 return NULL;
699 * Redirect using javascript
700 * @param $location string
702 function redirect_js($location) {
703 echo "<SCRIPT LANGUAGE=\"JavaScript\">";
704 echo "parent.location.href = '" . $location . "';";
705 echo "</SCRIPT>";