Fixed broken GO button in compact paginator (when javascript is off) -- problem was...
[squirrelmail.git] / functions / global.php
1 <?php
2
3 /**
4 * global.php
5 *
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
8 * php versions.
9 *
10 * @copyright &copy; 1999-2006 The SquirrelMail Project Team
11 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
12 * @version $Id$
13 * @package squirrelmail
14 */
15
16 /**
17 */
18 define('SQ_INORDER',0);
19 define('SQ_GET',1);
20 define('SQ_POST',2);
21 define('SQ_SESSION',3);
22 define('SQ_COOKIE',4);
23 define('SQ_SERVER',5);
24 define('SQ_FORM',6);
25
26
27 /**
28 * returns true if current php version is at mimimum a.b.c
29 *
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
34 * @return bool
35 */
36 function check_php_version ($a = '0', $b = '0', $c = '0')
37 {
38 return version_compare ( PHP_VERSION, "$a.$b.$c", 'ge' );
39 }
40
41 /**
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.
45 *
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
50 * @return bool
51 */
52 function check_sm_version($a = 0, $b = 0, $c = 0)
53 {
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 ) ) {
62 return FALSE;
63 }
64 return TRUE;
65 }
66
67
68 /**
69 * Recursively strip slashes from the values of an array.
70 * @param array array the array to strip, passed by reference
71 * @return void
72 */
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]);
78 }
79 else {
80 $array[$index] = stripslashes($value);
81 }
82 }
83 }
84 }
85
86 /**
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
90 * @return void
91 */
92 function sqsession_register ($var, $name) {
93
94 sqsession_is_active();
95
96 $_SESSION["$name"] = $var;
97
98 session_register("$name");
99 }
100
101 /**
102 * Delete a variable from the session.
103 * @param string $name the name of the var to delete
104 * @return void
105 */
106 function sqsession_unregister ($name) {
107
108 sqsession_is_active();
109
110 unset($_SESSION[$name]);
111
112 session_unregister("$name");
113 }
114
115 /**
116 * Checks to see if a variable has already been registered
117 * in the session.
118 * @param string $name the name of the var to check
119 * @return bool whether the var has been registered
120 */
121 function sqsession_is_registered ($name) {
122 $test_name = &$name;
123 $result = false;
124
125 if (isset($_SESSION[$test_name])) {
126 $result = true;
127 }
128
129 return $result;
130 }
131
132
133 /**
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".
148 *
149 * NOTE that form widgets must be named with the suffix "_1", "_2", "_3"
150 * and so on, or this function will not work.
151 *
152 * If more than one of the indicator fields is found, the first one
153 * (numerically) will win.
154 *
155 * If an indicator field is found without a matching input field,
156 * a field without any suffix is searched for (but only if
157 * $fallback_no_suffix is TRUE), and if not found, FALSE is
158 * ultimately returned.
159 *
160 * It should also be possible to use the same string for both
161 * $name and $indicator_field to look for the first possible
162 * widget with a suffix that can be found (and possibly fallback
163 * to a widget without a suffix).
164 *
165 * @param string name the name of the var to search
166 * @param mixed value the variable to return
167 * @param string indicator_field the name of the field upon which to base
168 * our decision upon (see above)
169 * @param int search constant defining where to look
170 * @param bool fallback_no_suffix whether or not to look for $name with
171 * no suffix when nothing else is found
172 * @param mixed default the value to assign to $value when nothing is found
173 * @param int typecast force variable to be cast to given type (please
174 * use SQ_TYPE_XXX constants or set to FALSE (default)
175 * to leave variable type unmolested)
176 *
177 * @return bool whether variable is found.
178 */
179 function sqGetGlobalVarMultiple($name, &$value, $indicator_field,
180 $search = SQ_INORDER,
181 $fallback_no_suffix=TRUE, $default=NULL,
182 $typecast=FALSE) {
183
184 $max_form_search = 15;
185
186 for ($i = 1; $i <= $max_form_search; $i++) {
187 if (sqGetGlobalVar($indicator_field . '_' . $i, $temp, $search)) {
188 return sqGetGlobalVar($name . '_' . $i, $value, $search, $default, $typecast);
189 }
190 }
191
192
193 // no indicator field found; just try without suffix if allowed
194 //
195 if ($fallback_no_suffix) {
196 return sqGetGlobalVar($name, $value, $search, $default, $typecast);
197 }
198
199
200 // no dice, set default and return FALSE
201 //
202 if (!is_null($default)) {
203 $value = $default;
204 }
205 return FALSE;
206
207 }
208
209
210 /**
211 * Search for the var $name in $_SESSION, $_POST, $_GET, $_COOKIE, or $_SERVER
212 * and set it in provided var.
213 *
214 * If $search is not provided, or if it is SQ_INORDER, it will search $_SESSION,
215 * then $_POST, then $_GET. If $search is SQ_FORM it will search $_POST and
216 * $_GET. Otherwise, use one of the defined constants to look for a var in one
217 * place specifically.
218 *
219 * Note: $search is an int value equal to one of the constants defined above.
220 *
221 * Example:
222 * sqgetGlobalVar('username',$username,SQ_SESSION);
223 * // No quotes around last param, it's a constant - not a string!
224 *
225 * @param string name the name of the var to search
226 * @param mixed value the variable to return
227 * @param int search constant defining where to look
228 * @param mixed default the value to assign to $value when nothing is found
229 * @param int typecast force variable to be cast to given type (please
230 * use SQ_TYPE_XXX constants or set to FALSE (default)
231 * to leave variable type unmolested)
232 *
233 * @return bool whether variable is found.
234 */
235 function sqgetGlobalVar($name, &$value, $search = SQ_INORDER, $default = NULL, $typecast = false) {
236
237 $result = false;
238
239 switch ($search) {
240 /* we want the default case to be first here,
241 so that if a valid value isn't specified,
242 all three arrays will be searched. */
243 default:
244 case SQ_INORDER: // check session, post, get
245 case SQ_SESSION:
246 if( isset($_SESSION[$name]) ) {
247 $value = $_SESSION[$name];
248 $result = TRUE;
249 break;
250 } elseif ( $search == SQ_SESSION ) {
251 break;
252 }
253 case SQ_FORM: // check post, get
254 case SQ_POST:
255 if( isset($_POST[$name]) ) {
256 $value = $_POST[$name];
257 $result = TRUE;
258 break;
259 } elseif ( $search == SQ_POST ) {
260 break;
261 }
262 case SQ_GET:
263 if ( isset($_GET[$name]) ) {
264 $value = $_GET[$name];
265 $result = TRUE;
266 break;
267 }
268 /* NO IF HERE. FOR SQ_INORDER CASE, EXIT after GET */
269 break;
270 case SQ_COOKIE:
271 if ( isset($_COOKIE[$name]) ) {
272 $value = $_COOKIE[$name];
273 $result = TRUE;
274 break;
275 }
276 break;
277 case SQ_SERVER:
278 if ( isset($_SERVER[$name]) ) {
279 $value = $_SERVER[$name];
280 $result = TRUE;
281 break;
282 }
283 break;
284 }
285 if ($result && $typecast) {
286 switch ($typecast) {
287 case SQ_TYPE_INT: $value = (int) $value; break;
288 case SQ_TYPE_STRING: $value = (string) $value; break;
289 case SQ_TYPE_BOOL: $value = (bool) $value; break;
290 default: break;
291 }
292 } else if (!$result && !is_null($default)) {
293 $value = $default;
294 }
295 return $result;
296 }
297
298 /**
299 * Deletes an existing session, more advanced than the standard PHP
300 * session_destroy(), it explicitly deletes the cookies and global vars.
301 *
302 * WARNING: Older PHP versions have some issues with session management.
303 * See http://bugs.php.net/11643 (warning, spammed bug tracker) and
304 * http://bugs.php.net/13834. SID constant is not destroyed in PHP 4.1.2,
305 * 4.2.3 and maybe other versions. If you restart session after session
306 * is destroyed, affected PHP versions produce PHP notice. Bug should
307 * be fixed only in 4.3.0
308 */
309 function sqsession_destroy() {
310
311 /*
312 * php.net says we can kill the cookie by setting just the name:
313 * http://www.php.net/manual/en/function.setcookie.php
314 * maybe this will help fix the session merging again.
315 *
316 * Changed the theory on this to kill the cookies first starting
317 * a new session will provide a new session for all instances of
318 * the browser, we don't want that, as that is what is causing the
319 * merging of sessions.
320 */
321
322 global $base_uri;
323
324 if (isset($_COOKIE[session_name()])) sqsetcookie(session_name(), '', 0, $base_uri);
325 if (isset($_COOKIE['username'])) sqsetcookie('username','',0,$base_uri);
326 if (isset($_COOKIE['key'])) sqsetcookie('key','',0,$base_uri);
327
328 $sessid = session_id();
329 if (!empty( $sessid )) {
330 $_SESSION = array();
331 @session_destroy();
332 }
333 }
334
335 /**
336 * Function to verify a session has been started. If it hasn't
337 * start a session up. php.net doesn't tell you that $_SESSION
338 * (even though autoglobal), is not created unless a session is
339 * started, unlike $_POST, $_GET and such
340 */
341 function sqsession_is_active() {
342 $sessid = session_id();
343 if ( empty( $sessid ) ) {
344 sqsession_start();
345 }
346 }
347
348 /**
349 * Function to start the session and store the cookie with the session_id as
350 * HttpOnly cookie which means that the cookie isn't accessible by javascript
351 * (IE6 only)
352 */
353 function sqsession_start() {
354 global $base_uri;
355
356 session_start();
357 $session_id = session_id();
358
359 // session_starts sets the sessionid cookie buth without the httponly var
360 // setting the cookie again sets the httponly cookie attribute
361
362 // disable, @see sqsetcookie and php 5.1.2
363 // sqsetcookie(session_name(),session_id(),false,$base_uri);
364 }
365
366
367 /**
368 * Set a cookie
369 * @param string $sName The name of the cookie.
370 * @param string $sValue The value of the cookie.
371 * @param int $iExpire The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch.
372 * @param string $sPath The path on the server in which the cookie will be available on.
373 * @param string $sDomain The domain that the cookie is available.
374 * @param boolean $bSecure Indicates that the cookie should only be transmitted over a secure HTTPS connection.
375 * @param boolean $bHttpOnly Disallow JS to access the cookie (IE6 only)
376 * @return void
377 */
378 function sqsetcookie($sName,$sValue,$iExpire=false,$sPath="",$sDomain="",$bSecure=false,$bHttpOnly=true,$bFlush=false) {
379 static $sCookieCache;
380 if (!isset($sCache)) {
381 $sCache = '';
382 }
383 /**
384 * We have to send all cookies with one header call otherwise we loose cookies.
385 * In order to achieve that the sqsetcookieflush function calls this function with $bFlush = true.
386 * If that happens we send the cookie header.
387 */
388 if ($bFlush) {
389 // header($sCookieCache);
390 return;
391 }
392 if (!$sName) return;
393
394 // php 5.1.2 and 4.4.2 do not allow to send multiple headers at once.
395 // Because that's the only way to get this thing working we fallback to
396 // setcookie until we solved this
397 if ($iExpire===false) $iExpire = 0;
398 setcookie($sName, $sValue, $iExpire, $sPath);
399 return;
400
401 $sHeader = "Set-Cookie: $sName=$sValue";
402 if ($sPath) {
403 $sHeader .= "; path=$sPath";
404 }
405 if ($iExpire !== false) {
406 $sHeader .= "; Max-Age=$iExpire";
407 // php uses Expire header, also add the expire header
408 $sHeader .= "; expires=". gmdate('D, d-M-Y H:i:s T',$iExpire);
409 }
410 if ($sDomain) {
411 $sHeader .= "; Domain=$sDomain";
412 }
413 // TODO: IE for Mac (5.2) thinks that semicolon is part of cookie domain
414 if ($bSecure) {
415 $sHeader .= "; Secure";
416 }
417 if ($bHttpOnly) {
418 $sHeader .= "; HttpOnly";
419 }
420 // $sHeader .= "; Version=1";
421 $sCookieCache .= $sHeader ."\r\n";
422 //header($sHeader."\r\n");
423 }
424
425 /**
426 * Send the cookie header
427 *
428 * Cookies set with sqsetcookie will bet set after a sqsetcookieflush call.
429 * @return void
430 */
431 function sqsetcookieflush() {
432 sqsetcookie('','','','','','','',true);
433 }
434
435 /**
436 * session_regenerate_id replacement for PHP < 4.3.2
437 *
438 * This code is borrowed from Gallery, session.php version 1.53.2.1
439 */
440 if (!function_exists('session_regenerate_id')) {
441 function make_seed() {
442 list($usec, $sec) = explode(' ', microtime());
443 return (float)$sec + ((float)$usec * 100000);
444 }
445
446 function php_combined_lcg() {
447 mt_srand(make_seed());
448 $tv = gettimeofday();
449 $lcg['s1'] = $tv['sec'] ^ (~$tv['usec']);
450 $lcg['s2'] = mt_rand();
451 $q = (int) ($lcg['s1'] / 53668);
452 $lcg['s1'] = (int) (40014 * ($lcg['s1'] - 53668 * $q) - 12211 * $q);
453 if ($lcg['s1'] < 0) {
454 $lcg['s1'] += 2147483563;
455 }
456 $q = (int) ($lcg['s2'] / 52774);
457 $lcg['s2'] = (int) (40692 * ($lcg['s2'] - 52774 * $q) - 3791 * $q);
458 if ($lcg['s2'] < 0) {
459 $lcg['s2'] += 2147483399;
460 }
461 $z = (int) ($lcg['s1'] - $lcg['s2']);
462 if ($z < 1) {
463 $z += 2147483562;
464 }
465 return $z * 4.656613e-10;
466 }
467
468 function session_regenerate_id() {
469 global $base_uri;
470 $tv = gettimeofday();
471 sqgetGlobalVar('REMOTE_ADDR',$remote_addr,SQ_SERVER);
472 $buf = sprintf("%.15s%ld%ld%0.8f", $remote_addr, $tv['sec'], $tv['usec'], php_combined_lcg() * 10);
473 session_id(md5($buf));
474 if (ini_get('session.use_cookies')) {
475 // at a later stage we use sqsetcookie. At this point just do
476 // what session_regenerate_id would do
477 setcookie(session_name(), session_id(), NULL, $base_uri);
478 }
479 return TRUE;
480 }
481 }
482
483
484 /**
485 * php_self
486 *
487 * Creates an URL for the page calling this function, using either the PHP global
488 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added. Before 1.5.1
489 * function was stored in function/strings.php.
490 *
491 * @return string the complete url for this page
492 * @since 1.2.3
493 */
494 function php_self () {
495 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
496 return $req_uri;
497 }
498
499 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
500
501 // need to add query string to end of PHP_SELF to match REQUEST_URI
502 //
503 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
504 $php_self .= '?' . $query_string;
505 }
506
507 return $php_self;
508 }
509
510 return '';
511 }
512
513
514 /**
515 * Find files and/or directories in a given directory optionally
516 * limited to only those with the given file extension. If the
517 * directory is not found or cannot be opened, no error is generated;
518 * only an empty file list is returned.
519 FIXME: do we WANT to throw an error or a notice or... or return FALSE?
520 *
521 * @param string $directory_path The path (relative or absolute)
522 * to the desired directory.
523 * @param string $extension The file extension filter (optional;
524 * default is to return all files (dirs).
525 * @param boolean $return_filenames_only When TRUE, only file/dir names
526 * are returned, otherwise the
527 * $directory_path string is
528 * prepended to each file/dir in
529 * the returned list (optional;
530 * default is filename/dirname only)
531 * @param boolean $include_directories When TRUE, directories are
532 * included (optional; default
533 * DO include directories).
534 * @param boolean $directories_only When TRUE, ONLY directories
535 * are included (optional; default
536 * is to include files too).
537 * @param boolean $separate_files_and_directories When TRUE, files and
538 * directories are returned
539 * in separate lists, so
540 * the return value is
541 * formatted as a two-element
542 * array with the two keys
543 * "FILES" and "DIRECTORIES",
544 * where corresponding values
545 * are lists of either all
546 * files or all directories
547 * (optional; default do not
548 * split up return array).
549 *
550 *
551 * @return array The requested file/directory list(s).
552 *
553 * @since 1.5.2
554 *
555 */
556 function list_files($directory_path, $extension='', $return_filenames_only=TRUE,
557 $include_directories=TRUE, $directories_only=FALSE,
558 $separate_files_and_directories=FALSE) {
559
560 $files = array();
561 $directories = array();
562
563 //FIXME: do we want to place security restrictions here like only allowing
564 // directories under SM_PATH?
565 // validate given directory
566 //
567 if (empty($directory_path)
568 || !is_dir($directory_path)
569 || !($DIR = opendir($directory_path))) {
570 return $files;
571 }
572
573
574 if (!empty($extension)) $extension = '.' . trim($extension, '.');
575 $directory_path = rtrim($directory_path, '/');
576
577
578 // parse through the files
579 //
580 while (($file = readdir($DIR)) !== false) {
581
582 if ($file == '.' || $file == '..') continue;
583
584 if (!empty($extension)
585 && strrpos($file, $extension) !== (strlen($file) - strlen($extension)))
586 continue;
587
588 // only use is_dir() if we really need to (be as efficient as possible)
589 //
590 $is_dir = FALSE;
591 if (!$include_directories || $directories_only
592 || $separate_files_and_directories) {
593 if (is_dir($directory_path . '/' . $file)) {
594 if (!$include_directories) continue;
595 $is_dir = TRUE;
596 $directories[] = ($return_filenames_only
597 ? $file
598 : $directory_path . '/' . $file);
599 }
600 if ($directories_only) continue;
601 }
602
603 if (!$separate_files_and_directories
604 || ($separate_files_and_directories && !$is_dir)) {
605 $files[] = ($return_filenames_only
606 ? $file
607 : $directory_path . '/' . $file);
608 }
609
610 }
611 closedir($DIR);
612
613
614 if ($directories_only) return $directories;
615 if ($separate_files_and_directories) return array('FILES' => $files,
616 'DIRECTORIES' => $directories);
617 return $files;
618
619 }
620
621
622 /**
623 * Print variable
624 *
625 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
626 *
627 * Debugging function - does the same as print_r, but makes sure special
628 * characters are converted to htmlentities first. This will allow
629 * values like <some@email.address> to be displayed.
630 * The output is wrapped in <<pre>> and <</pre>> tags.
631 * Since 1.4.2 accepts unlimited number of arguments.
632 * @since 1.4.1
633 * @return void
634 */
635 function sm_print_r() {
636 ob_start(); // Buffer output
637 foreach(func_get_args() as $var) {
638 print_r($var);
639 echo "\n";
640 // php has get_class_methods function that can print class methods
641 if (is_object($var)) {
642 // get class methods if $var is object
643 $aMethods=get_class_methods(get_class($var));
644 // make sure that $aMethods is array and array is not empty
645 if (is_array($aMethods) && $aMethods!=array()) {
646 echo "Object methods:\n";
647 foreach($aMethods as $method) {
648 echo '* ' . $method . "\n";
649 }
650 }
651 echo "\n";
652 }
653 }
654 $buffer = ob_get_contents(); // Grab the print_r output
655 ob_end_clean(); // Silently discard the output & stop buffering
656 print '<div align="left"><pre>';
657 print htmlentities($buffer);
658 print '</pre></div>';
659 }
660
661