6 * This includes code to update < 4.1.0 globals to the newer format
7 * It also has some session register functions that work across various
10 * @copyright © 1999-2006 The SquirrelMail Project Team
11 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
13 * @package squirrelmail
18 define('SQ_INORDER',0);
21 define('SQ_SESSION',3);
22 define('SQ_COOKIE',4);
23 define('SQ_SERVER',5);
28 * returns true if current php version is at mimimum a.b.c
30 * Called: check_php_version(4,1)
31 * @param int a major version number
32 * @param int b minor version number
33 * @param int c release number
36 function check_php_version ($a = '0', $b = '0', $c = '0')
38 return version_compare ( PHP_VERSION
, "$a.$b.$c", 'ge' );
42 * returns true if the current internal SM version is at minimum a.b.c
43 * These are plain integer comparisons, as our internal version is
44 * constructed by us, as an array of 3 ints.
46 * Called: check_sm_version(1,3,3)
47 * @param int a major version number
48 * @param int b minor version number
49 * @param int c release number
52 function check_sm_version($a = 0, $b = 0, $c = 0)
54 global $SQM_INTERNAL_VERSION;
55 if ( !isset($SQM_INTERNAL_VERSION) ||
56 $SQM_INTERNAL_VERSION[0] < $a ||
57 ( $SQM_INTERNAL_VERSION[0] == $a &&
58 $SQM_INTERNAL_VERSION[1] < $b) ||
59 ( $SQM_INTERNAL_VERSION[0] == $a &&
60 $SQM_INTERNAL_VERSION[1] == $b &&
61 $SQM_INTERNAL_VERSION[2] < $c ) ) {
69 * Recursively strip slashes from the values of an array.
70 * @param array array the array to strip, passed by reference
73 function sqstripslashes(&$array) {
74 if(count($array) > 0) {
75 foreach ($array as $index=>$value) {
76 if (is_array($array[$index])) {
77 sqstripslashes($array[$index]);
80 $array[$index] = stripslashes($value);
87 * Add a variable to the session.
88 * @param mixed $var the variable to register
89 * @param string $name the name to refer to this variable
92 function sqsession_register ($var, $name) {
94 sqsession_is_active();
96 $_SESSION["$name"] = $var;
98 session_register("$name");
102 * Delete a variable from the session.
103 * @param string $name the name of the var to delete
106 function sqsession_unregister ($name) {
108 sqsession_is_active();
110 unset($_SESSION[$name]);
112 session_unregister("$name");
116 * Checks to see if a variable has already been registered
118 * @param string $name the name of the var to check
119 * @return bool whether the var has been registered
121 function sqsession_is_registered ($name) {
125 if (isset($_SESSION[$test_name])) {
134 * Retrieves a form variable, from a set of possible similarly named
135 * form variables, based on finding a different, single field. This
136 * is intended to allow more than one same-named inputs in a single
137 * <form>, where the submit button that is clicked tells us which
138 * input we should retrieve. An example is if we have:
139 * <select name="startMessage_1">
140 * <select name="startMessage_2">
141 * <input type="submit" name="form_submit_1">
142 * <input type="submit" name="form_submit_2">
143 * and we want to know which one of the select inputs should be
144 * returned as $startMessage (without the suffix!), this function
145 * decides by looking for either "form_submit_1" or "form_submit_2"
146 * (both should not appear). In this example, $name should be
147 * "startMessage" and $indicator_field should be "form_submit".
149 * NOTE that form widgets must be named with the suffix "_1", "_2", "_3"
150 * and so on, or this function will not work.
152 * If more than one of the indicator fields is found, the first one
153 * (numerically) will win.
155 * If an indicator field is found without a matching input ($name)
156 * field, FALSE is returned.
158 * If no indicator fields are found, a field of $name *without* any
159 * suffix is searched for (but only if $fallback_no_suffix is TRUE),
160 * and if not found, FALSE is ultimately returned.
162 * It should also be possible to use the same string for both
163 * $name and $indicator_field to look for the first possible
164 * widget with a suffix that can be found (and possibly fallback
165 * to a widget without a suffix).
167 * @param string name the name of the var to search
168 * @param mixed value the variable to return
169 * @param string indicator_field the name of the field upon which to base
170 * our decision upon (see above)
171 * @param int search constant defining where to look
172 * @param bool fallback_no_suffix whether or not to look for $name with
173 * no suffix when nothing else is found
174 * @param mixed default the value to assign to $value when nothing is found
175 * @param int typecast force variable to be cast to given type (please
176 * use SQ_TYPE_XXX constants or set to FALSE (default)
177 * to leave variable type unmolested)
179 * @return bool whether variable is found.
181 function sqGetGlobalVarMultiple($name, &$value, $indicator_field,
182 $search = SQ_INORDER
,
183 $fallback_no_suffix=TRUE, $default=NULL,
186 // Set arbitrary max limit -- should be much lower except on the
187 // search results page, if there are many (50 or more?) mailboxes
188 // shown, this may not be high enough. Is there some way we should
189 // automate this value?
191 $max_form_search = 100;
193 for ($i = 1; $i <= $max_form_search; $i++
) {
194 if (sqGetGlobalVar($indicator_field . '_' . $i, $temp, $search)) {
195 return sqGetGlobalVar($name . '_' . $i, $value, $search, $default, $typecast);
200 // no indicator field found; just try without suffix if allowed
202 if ($fallback_no_suffix) {
203 return sqGetGlobalVar($name, $value, $search, $default, $typecast);
207 // no dice, set default and return FALSE
209 if (!is_null($default)) {
218 * Search for the var $name in $_SESSION, $_POST, $_GET, $_COOKIE, or $_SERVER
219 * and set it in provided var.
221 * If $search is not provided, or if it is SQ_INORDER, it will search $_SESSION,
222 * then $_POST, then $_GET. If $search is SQ_FORM it will search $_POST and
223 * $_GET. Otherwise, use one of the defined constants to look for a var in one
224 * place specifically.
226 * Note: $search is an int value equal to one of the constants defined above.
229 * sqgetGlobalVar('username',$username,SQ_SESSION);
230 * // No quotes around last param, it's a constant - not a string!
232 * @param string name the name of the var to search
233 * @param mixed value the variable to return
234 * @param int search constant defining where to look
235 * @param mixed default the value to assign to $value when nothing is found
236 * @param int typecast force variable to be cast to given type (please
237 * use SQ_TYPE_XXX constants or set to FALSE (default)
238 * to leave variable type unmolested)
240 * @return bool whether variable is found.
242 function sqgetGlobalVar($name, &$value, $search = SQ_INORDER
, $default = NULL, $typecast = false) {
247 /* we want the default case to be first here,
248 so that if a valid value isn't specified,
249 all three arrays will be searched. */
251 case SQ_INORDER
: // check session, post, get
253 if( isset($_SESSION[$name]) ) {
254 $value = $_SESSION[$name];
257 } elseif ( $search == SQ_SESSION
) {
260 case SQ_FORM
: // check post, get
262 if( isset($_POST[$name]) ) {
263 $value = $_POST[$name];
266 } elseif ( $search == SQ_POST
) {
270 if ( isset($_GET[$name]) ) {
271 $value = $_GET[$name];
275 /* NO IF HERE. FOR SQ_INORDER CASE, EXIT after GET */
278 if ( isset($_COOKIE[$name]) ) {
279 $value = $_COOKIE[$name];
285 if ( isset($_SERVER[$name]) ) {
286 $value = $_SERVER[$name];
292 if ($result && $typecast) {
294 case SQ_TYPE_INT
: $value = (int) $value; break;
295 case SQ_TYPE_STRING
: $value = (string) $value; break;
296 case SQ_TYPE_BOOL
: $value = (bool) $value; break;
299 } else if (!$result && !is_null($default)) {
306 * Deletes an existing session, more advanced than the standard PHP
307 * session_destroy(), it explicitly deletes the cookies and global vars.
309 * WARNING: Older PHP versions have some issues with session management.
310 * See http://bugs.php.net/11643 (warning, spammed bug tracker) and
311 * http://bugs.php.net/13834. SID constant is not destroyed in PHP 4.1.2,
312 * 4.2.3 and maybe other versions. If you restart session after session
313 * is destroyed, affected PHP versions produce PHP notice. Bug should
314 * be fixed only in 4.3.0
316 function sqsession_destroy() {
319 * php.net says we can kill the cookie by setting just the name:
320 * http://www.php.net/manual/en/function.setcookie.php
321 * maybe this will help fix the session merging again.
323 * Changed the theory on this to kill the cookies first starting
324 * a new session will provide a new session for all instances of
325 * the browser, we don't want that, as that is what is causing the
326 * merging of sessions.
331 if (isset($_COOKIE[session_name()])) sqsetcookie(session_name(), '', 0, $base_uri);
332 if (isset($_COOKIE['username'])) sqsetcookie('username','',0,$base_uri);
333 if (isset($_COOKIE['key'])) sqsetcookie('key','',0,$base_uri);
335 $sessid = session_id();
336 if (!empty( $sessid )) {
343 * Function to verify a session has been started. If it hasn't
344 * start a session up. php.net doesn't tell you that $_SESSION
345 * (even though autoglobal), is not created unless a session is
346 * started, unlike $_POST, $_GET and such
348 function sqsession_is_active() {
349 $sessid = session_id();
350 if ( empty( $sessid ) ) {
356 * Function to start the session and store the cookie with the session_id as
357 * HttpOnly cookie which means that the cookie isn't accessible by javascript
360 function sqsession_start() {
364 $session_id = session_id();
366 // session_starts sets the sessionid cookie buth without the httponly var
367 // setting the cookie again sets the httponly cookie attribute
369 // disable, @see sqsetcookie and php 5.1.2
370 // sqsetcookie(session_name(),session_id(),false,$base_uri);
376 * @param string $sName The name of the cookie.
377 * @param string $sValue The value of the cookie.
378 * @param int $iExpire The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch.
379 * @param string $sPath The path on the server in which the cookie will be available on.
380 * @param string $sDomain The domain that the cookie is available.
381 * @param boolean $bSecure Indicates that the cookie should only be transmitted over a secure HTTPS connection.
382 * @param boolean $bHttpOnly Disallow JS to access the cookie (IE6 only)
385 function sqsetcookie($sName,$sValue,$iExpire=false,$sPath="",$sDomain="",$bSecure=false,$bHttpOnly=true,$bFlush=false) {
386 static $sCookieCache;
387 if (!isset($sCache)) {
391 * We have to send all cookies with one header call otherwise we loose cookies.
392 * In order to achieve that the sqsetcookieflush function calls this function with $bFlush = true.
393 * If that happens we send the cookie header.
396 // header($sCookieCache);
401 // php 5.1.2 and 4.4.2 do not allow to send multiple headers at once.
402 // Because that's the only way to get this thing working we fallback to
403 // setcookie until we solved this
404 if ($iExpire===false) $iExpire = 0;
405 setcookie($sName, $sValue, $iExpire, $sPath);
408 $sHeader = "Set-Cookie: $sName=$sValue";
410 $sHeader .= "; path=$sPath";
412 if ($iExpire !== false) {
413 $sHeader .= "; Max-Age=$iExpire";
414 // php uses Expire header, also add the expire header
415 $sHeader .= "; expires=". gmdate('D, d-M-Y H:i:s T',$iExpire);
418 $sHeader .= "; Domain=$sDomain";
420 // TODO: IE for Mac (5.2) thinks that semicolon is part of cookie domain
422 $sHeader .= "; Secure";
425 $sHeader .= "; HttpOnly";
427 // $sHeader .= "; Version=1";
428 $sCookieCache .= $sHeader ."\r\n";
429 //header($sHeader."\r\n");
433 * Send the cookie header
435 * Cookies set with sqsetcookie will bet set after a sqsetcookieflush call.
438 function sqsetcookieflush() {
439 sqsetcookie('','','','','','','',true);
443 * session_regenerate_id replacement for PHP < 4.3.2
445 * This code is borrowed from Gallery, session.php version 1.53.2.1
447 if (!function_exists('session_regenerate_id')) {
448 function make_seed() {
449 list($usec, $sec) = explode(' ', microtime());
450 return (float)$sec +
((float)$usec * 100000);
453 function php_combined_lcg() {
454 mt_srand(make_seed());
455 $tv = gettimeofday();
456 $lcg['s1'] = $tv['sec'] ^
(~
$tv['usec']);
457 $lcg['s2'] = mt_rand();
458 $q = (int) ($lcg['s1'] / 53668);
459 $lcg['s1'] = (int) (40014 * ($lcg['s1'] - 53668 * $q) - 12211 * $q);
460 if ($lcg['s1'] < 0) {
461 $lcg['s1'] +
= 2147483563;
463 $q = (int) ($lcg['s2'] / 52774);
464 $lcg['s2'] = (int) (40692 * ($lcg['s2'] - 52774 * $q) - 3791 * $q);
465 if ($lcg['s2'] < 0) {
466 $lcg['s2'] +
= 2147483399;
468 $z = (int) ($lcg['s1'] - $lcg['s2']);
472 return $z * 4.656613e-10;
475 function session_regenerate_id() {
477 $tv = gettimeofday();
478 sqgetGlobalVar('REMOTE_ADDR',$remote_addr,SQ_SERVER
);
479 $buf = sprintf("%.15s%ld%ld%0.8f", $remote_addr, $tv['sec'], $tv['usec'], php_combined_lcg() * 10);
480 session_id(md5($buf));
481 if (ini_get('session.use_cookies')) {
482 // at a later stage we use sqsetcookie. At this point just do
483 // what session_regenerate_id would do
484 setcookie(session_name(), session_id(), NULL, $base_uri);
494 * Creates an URL for the page calling this function, using either the PHP global
495 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added. Before 1.5.1
496 * function was stored in function/strings.php.
498 * @return string the complete url for this page
501 function php_self () {
502 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER
) && !empty($req_uri) ) {
506 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER
) && !empty($php_self) ) {
508 // need to add query string to end of PHP_SELF to match REQUEST_URI
510 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER
) && !empty($query_string) ) {
511 $php_self .= '?' . $query_string;
522 * Find files and/or directories in a given directory optionally
523 * limited to only those with the given file extension. If the
524 * directory is not found or cannot be opened, no error is generated;
525 * only an empty file list is returned.
526 FIXME: do we WANT to throw an error or a notice or... or return FALSE?
528 * @param string $directory_path The path (relative or absolute)
529 * to the desired directory.
530 * @param string $extension The file extension filter (optional;
531 * default is to return all files (dirs).
532 * @param boolean $return_filenames_only When TRUE, only file/dir names
533 * are returned, otherwise the
534 * $directory_path string is
535 * prepended to each file/dir in
536 * the returned list (optional;
537 * default is filename/dirname only)
538 * @param boolean $include_directories When TRUE, directories are
539 * included (optional; default
540 * DO include directories).
541 * @param boolean $directories_only When TRUE, ONLY directories
542 * are included (optional; default
543 * is to include files too).
544 * @param boolean $separate_files_and_directories When TRUE, files and
545 * directories are returned
546 * in separate lists, so
547 * the return value is
548 * formatted as a two-element
549 * array with the two keys
550 * "FILES" and "DIRECTORIES",
551 * where corresponding values
552 * are lists of either all
553 * files or all directories
554 * (optional; default do not
555 * split up return array).
558 * @return array The requested file/directory list(s).
563 function list_files($directory_path, $extension='', $return_filenames_only=TRUE,
564 $include_directories=TRUE, $directories_only=FALSE,
565 $separate_files_and_directories=FALSE) {
568 $directories = array();
570 //FIXME: do we want to place security restrictions here like only allowing
571 // directories under SM_PATH?
572 // validate given directory
574 if (empty($directory_path)
575 ||
!is_dir($directory_path)
576 ||
!($DIR = opendir($directory_path))) {
581 if (!empty($extension)) $extension = '.' . trim($extension, '.');
582 $directory_path = rtrim($directory_path, '/');
585 // parse through the files
587 while (($file = readdir($DIR)) !== false) {
589 if ($file == '.' ||
$file == '..') continue;
591 if (!empty($extension)
592 && strrpos($file, $extension) !== (strlen($file) - strlen($extension)))
595 // only use is_dir() if we really need to (be as efficient as possible)
598 if (!$include_directories ||
$directories_only
599 ||
$separate_files_and_directories) {
600 if (is_dir($directory_path . '/' . $file)) {
601 if (!$include_directories) continue;
603 $directories[] = ($return_filenames_only
605 : $directory_path . '/' . $file);
607 if ($directories_only) continue;
610 if (!$separate_files_and_directories
611 ||
($separate_files_and_directories && !$is_dir)) {
612 $files[] = ($return_filenames_only
614 : $directory_path . '/' . $file);
621 if ($directories_only) return $directories;
622 if ($separate_files_and_directories) return array('FILES' => $files,
623 'DIRECTORIES' => $directories);
632 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
634 * Debugging function - does the same as print_r, but makes sure special
635 * characters are converted to htmlentities first. This will allow
636 * values like <some@email.address> to be displayed.
637 * The output is wrapped in <<pre>> and <</pre>> tags.
638 * Since 1.4.2 accepts unlimited number of arguments.
642 function sm_print_r() {
643 ob_start(); // Buffer output
644 foreach(func_get_args() as $var) {
647 // php has get_class_methods function that can print class methods
648 if (is_object($var)) {
649 // get class methods if $var is object
650 $aMethods=get_class_methods(get_class($var));
651 // make sure that $aMethods is array and array is not empty
652 if (is_array($aMethods) && $aMethods!=array()) {
653 echo "Object methods:\n";
654 foreach($aMethods as $method) {
655 echo '* ' . $method . "\n";
661 $buffer = ob_get_contents(); // Grab the print_r output
662 ob_end_clean(); // Silently discard the output & stop buffering
663 print '<div align="left"><pre>';
664 print htmlentities($buffer);
665 print '</pre></div>';