c4a186cd9376b3624aa2af6f301ae6ea7e6df446
[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 * Search for the var $name in $_SESSION, $_POST, $_GET, $_COOKIE, or $_SERVER
134 * and set it in provided var.
135 *
136 * If $search is not provided, or if it is SQ_INORDER, it will search $_SESSION,
137 * then $_POST, then $_GET. If $search is SQ_FORM it will search $_POST and
138 * $_GET. Otherwise, use one of the defined constants to look for a var in one
139 * place specifically.
140 *
141 * Note: $search is an int value equal to one of the constants defined above.
142 *
143 * Example:
144 * sqgetGlobalVar('username',$username,SQ_SESSION);
145 * // No quotes around last param, it's a constant - not a string!
146 *
147 * @param string name the name of the var to search
148 * @param mixed value the variable to return
149 * @param int search constant defining where to look
150 * @param int typecast force variable to be cast to given type (please
151 * use SQ_TYPE_XXX constants or set to FALSE (default)
152 * to leave variable type unmolested)
153 * @return bool whether variable is found.
154 */
155 function sqgetGlobalVar($name, &$value, $search = SQ_INORDER, $default = NULL, $typecast = false) {
156
157 $result = false;
158
159 switch ($search) {
160 /* we want the default case to be first here,
161 so that if a valid value isn't specified,
162 all three arrays will be searched. */
163 default:
164 case SQ_INORDER: // check session, post, get
165 case SQ_SESSION:
166 if( isset($_SESSION[$name]) ) {
167 $value = $_SESSION[$name];
168 $result = TRUE;
169 break;
170 } elseif ( $search == SQ_SESSION ) {
171 break;
172 }
173 case SQ_FORM: // check post, get
174 case SQ_POST:
175 if( isset($_POST[$name]) ) {
176 $value = $_POST[$name];
177 $result = TRUE;
178 break;
179 } elseif ( $search == SQ_POST ) {
180 break;
181 }
182 case SQ_GET:
183 if ( isset($_GET[$name]) ) {
184 $value = $_GET[$name];
185 $result = TRUE;
186 break;
187 }
188 /* NO IF HERE. FOR SQ_INORDER CASE, EXIT after GET */
189 break;
190 case SQ_COOKIE:
191 if ( isset($_COOKIE[$name]) ) {
192 $value = $_COOKIE[$name];
193 $result = TRUE;
194 break;
195 }
196 break;
197 case SQ_SERVER:
198 if ( isset($_SERVER[$name]) ) {
199 $value = $_SERVER[$name];
200 $result = TRUE;
201 break;
202 }
203 break;
204 }
205 if ($result && $typecast) {
206 switch ($typecast) {
207 case SQ_TYPE_INT: $value = (int) $value; break;
208 case SQ_TYPE_STRING: $value = (string) $value; break;
209 case SQ_TYPE_BOOL: $value = (bool) $value; break;
210 default: break;
211 }
212 } else if (!$result && !is_null($default)) {
213 $value = $default;
214 }
215 return $result;
216 }
217
218 /**
219 * Deletes an existing session, more advanced than the standard PHP
220 * session_destroy(), it explicitly deletes the cookies and global vars.
221 *
222 * WARNING: Older PHP versions have some issues with session management.
223 * See http://bugs.php.net/11643 (warning, spammed bug tracker) and
224 * http://bugs.php.net/13834. SID constant is not destroyed in PHP 4.1.2,
225 * 4.2.3 and maybe other versions. If you restart session after session
226 * is destroyed, affected PHP versions produce PHP notice. Bug should
227 * be fixed only in 4.3.0
228 */
229 function sqsession_destroy() {
230
231 /*
232 * php.net says we can kill the cookie by setting just the name:
233 * http://www.php.net/manual/en/function.setcookie.php
234 * maybe this will help fix the session merging again.
235 *
236 * Changed the theory on this to kill the cookies first starting
237 * a new session will provide a new session for all instances of
238 * the browser, we don't want that, as that is what is causing the
239 * merging of sessions.
240 */
241
242 global $base_uri;
243
244 if (isset($_COOKIE[session_name()])) sqsetcookie(session_name(), '', 0, $base_uri);
245 if (isset($_COOKIE['username'])) sqsetcookie('username','',0,$base_uri);
246 if (isset($_COOKIE['key'])) sqsetcookie('key','',0,$base_uri);
247
248 $sessid = session_id();
249 if (!empty( $sessid )) {
250 $_SESSION = array();
251 @session_destroy();
252 }
253 }
254
255 /**
256 * Function to verify a session has been started. If it hasn't
257 * start a session up. php.net doesn't tell you that $_SESSION
258 * (even though autoglobal), is not created unless a session is
259 * started, unlike $_POST, $_GET and such
260 */
261 function sqsession_is_active() {
262 $sessid = session_id();
263 if ( empty( $sessid ) ) {
264 sqsession_start();
265 }
266 }
267
268 /**
269 * Function to start the session and store the cookie with the session_id as
270 * HttpOnly cookie which means that the cookie isn't accessible by javascript
271 * (IE6 only)
272 */
273 function sqsession_start() {
274 global $base_uri;
275
276 session_start();
277 $session_id = session_id();
278
279 // session_starts sets the sessionid cookie buth without the httponly var
280 // setting the cookie again sets the httponly cookie attribute
281
282 // disable, @see sqsetcookie and php 5.1.2
283 // sqsetcookie(session_name(),session_id(),false,$base_uri);
284 }
285
286
287 /**
288 * Set a cookie
289 * @param string $sName The name of the cookie.
290 * @param string $sValue The value of the cookie.
291 * @param int $iExpire The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch.
292 * @param string $sPath The path on the server in which the cookie will be available on.
293 * @param string $sDomain The domain that the cookie is available.
294 * @param boolean $bSecure Indicates that the cookie should only be transmitted over a secure HTTPS connection.
295 * @param boolean $bHttpOnly Disallow JS to access the cookie (IE6 only)
296 * @return void
297 */
298 function sqsetcookie($sName,$sValue,$iExpire=false,$sPath="",$sDomain="",$bSecure=false,$bHttpOnly=true,$bFlush=false) {
299 static $sCookieCache;
300 if (!isset($sCache)) {
301 $sCache = '';
302 }
303 /**
304 * We have to send all cookies with one header call otherwise we loose cookies.
305 * In order to achieve that the sqsetcookieflush function calls this function with $bFlush = true.
306 * If that happens we send the cookie header.
307 */
308 if ($bFlush) {
309 // header($sCookieCache);
310 return;
311 }
312 if (!$sName) return;
313
314 // php 5.1.2 and 4.4.2 do not allow to send multiple headers at once.
315 // Because that's the only way to get this thing working we fallback to
316 // setcookie until we solved this
317 if ($iExpire===false) $iExpire = 0;
318 setcookie($sName, $sValue, $iExpire, $sPath);
319 return;
320
321 $sHeader = "Set-Cookie: $sName=$sValue";
322 if ($sPath) {
323 $sHeader .= "; path=$sPath";
324 }
325 if ($iExpire !== false) {
326 $sHeader .= "; Max-Age=$iExpire";
327 // php uses Expire header, also add the expire header
328 $sHeader .= "; expires=". gmdate('D, d-M-Y H:i:s T',$iExpire);
329 }
330 if ($sDomain) {
331 $sHeader .= "; Domain=$sDomain";
332 }
333 // TODO: IE for Mac (5.2) thinks that semicolon is part of cookie domain
334 if ($bSecure) {
335 $sHeader .= "; Secure";
336 }
337 if ($bHttpOnly) {
338 $sHeader .= "; HttpOnly";
339 }
340 // $sHeader .= "; Version=1";
341 $sCookieCache .= $sHeader ."\r\n";
342 //header($sHeader."\r\n");
343 }
344
345 /**
346 * Send the cookie header
347 *
348 * Cookies set with sqsetcookie will bet set after a sqsetcookieflush call.
349 * @return void
350 */
351 function sqsetcookieflush() {
352 sqsetcookie('','','','','','','',true);
353 }
354
355 /**
356 * session_regenerate_id replacement for PHP < 4.3.2
357 *
358 * This code is borrowed from Gallery, session.php version 1.53.2.1
359 */
360 if (!function_exists('session_regenerate_id')) {
361 function make_seed() {
362 list($usec, $sec) = explode(' ', microtime());
363 return (float)$sec + ((float)$usec * 100000);
364 }
365
366 function php_combined_lcg() {
367 mt_srand(make_seed());
368 $tv = gettimeofday();
369 $lcg['s1'] = $tv['sec'] ^ (~$tv['usec']);
370 $lcg['s2'] = mt_rand();
371 $q = (int) ($lcg['s1'] / 53668);
372 $lcg['s1'] = (int) (40014 * ($lcg['s1'] - 53668 * $q) - 12211 * $q);
373 if ($lcg['s1'] < 0) {
374 $lcg['s1'] += 2147483563;
375 }
376 $q = (int) ($lcg['s2'] / 52774);
377 $lcg['s2'] = (int) (40692 * ($lcg['s2'] - 52774 * $q) - 3791 * $q);
378 if ($lcg['s2'] < 0) {
379 $lcg['s2'] += 2147483399;
380 }
381 $z = (int) ($lcg['s1'] - $lcg['s2']);
382 if ($z < 1) {
383 $z += 2147483562;
384 }
385 return $z * 4.656613e-10;
386 }
387
388 function session_regenerate_id() {
389 global $base_uri;
390 $tv = gettimeofday();
391 sqgetGlobalVar('REMOTE_ADDR',$remote_addr,SQ_SERVER);
392 $buf = sprintf("%.15s%ld%ld%0.8f", $remote_addr, $tv['sec'], $tv['usec'], php_combined_lcg() * 10);
393 session_id(md5($buf));
394 if (ini_get('session.use_cookies')) {
395 // at a later stage we use sqsetcookie. At this point just do
396 // what session_regenerate_id would do
397 setcookie(session_name(), session_id(), NULL, $base_uri);
398 }
399 return TRUE;
400 }
401 }
402
403
404 /**
405 * php_self
406 *
407 * Creates an URL for the page calling this function, using either the PHP global
408 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added. Before 1.5.1
409 * function was stored in function/strings.php.
410 *
411 * @return string the complete url for this page
412 * @since 1.2.3
413 */
414 function php_self () {
415 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
416 return $req_uri;
417 }
418
419 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
420
421 // need to add query string to end of PHP_SELF to match REQUEST_URI
422 //
423 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
424 $php_self .= '?' . $query_string;
425 }
426
427 return $php_self;
428 }
429
430 return '';
431 }
432
433
434 /**
435 * Find files and/or directories in a given directory optionally
436 * limited to only those with the given file extension. If the
437 * directory is not found or cannot be opened, no error is generated;
438 * only an empty file list is returned.
439 FIXME: do we WANT to throw an error or a notice or... or return FALSE?
440 *
441 * @param string $directory_path The path (relative or absolute)
442 * to the desired directory.
443 * @param string $extension The file extension filter (optional;
444 * default is to return all files (dirs).
445 * @param boolean $return_filenames_only When TRUE, only file/dir names
446 * are returned, otherwise the
447 * $directory_path string is
448 * prepended to each file/dir in
449 * the returned list (optional;
450 * default is filename/dirname only)
451 * @param boolean $include_directories When TRUE, directories are
452 * included (optional; default
453 * DO include directories).
454 * @param boolean $directories_only When TRUE, ONLY directories
455 * are included (optional; default
456 * is to include files too).
457 * @param boolean $separate_files_and_directories When TRUE, files and
458 * directories are returned
459 * in separate lists, so
460 * the return value is
461 * formatted as a two-element
462 * array with the two keys
463 * "FILES" and "DIRECTORIES",
464 * where corresponding values
465 * are lists of either all
466 * files or all directories
467 * (optional; default do not
468 * split up return array).
469 *
470 *
471 * @return array The requested file/directory list(s).
472 *
473 * @since 1.5.2
474 *
475 */
476 function list_files($directory_path, $extension='', $return_filenames_only=TRUE,
477 $include_directories=TRUE, $directories_only=FALSE,
478 $separate_files_and_directories=FALSE) {
479
480 $files = array();
481 $directories = array();
482
483 //FIXME: do we want to place security restrictions here like only allowing
484 // directories under SM_PATH?
485 // validate given directory
486 //
487 if (empty($directory_path)
488 || !is_dir($directory_path)
489 || !($DIR = opendir($directory_path))) {
490 return $files;
491 }
492
493
494 if (!empty($extension)) $extension = '.' . trim($extension, '.');
495 $directory_path = rtrim($directory_path, '/');
496
497
498 // parse through the files
499 //
500 while (($file = readdir($DIR)) !== false) {
501
502 if ($file == '.' || $file == '..') continue;
503
504 if (!empty($extension)
505 && strrpos($file, $extension) !== (strlen($file) - strlen($extension)))
506 continue;
507
508 // only use is_dir() if we really need to (be as efficient as possible)
509 //
510 $is_dir = FALSE;
511 if (!$include_directories || $directories_only
512 || $separate_files_and_directories) {
513 if (is_dir($directory_path . '/' . $file)) {
514 if (!$include_directories) continue;
515 $is_dir = TRUE;
516 $directories[] = ($return_filenames_only
517 ? $file
518 : $directory_path . '/' . $file);
519 }
520 if ($directories_only) continue;
521 }
522
523 if (!$separate_files_and_directories
524 || ($separate_files_and_directories && !$is_dir)) {
525 $files[] = ($return_filenames_only
526 ? $file
527 : $directory_path . '/' . $file);
528 }
529
530 }
531 closedir($DIR);
532
533
534 if ($directories_only) return $directories;
535 if ($separate_files_and_directories) return array('FILES' => $files,
536 'DIRECTORIES' => $directories);
537 return $files;
538
539 }
540
541
542 /**
543 * Print variable
544 *
545 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
546 *
547 * Debugging function - does the same as print_r, but makes sure special
548 * characters are converted to htmlentities first. This will allow
549 * values like <some@email.address> to be displayed.
550 * The output is wrapped in <<pre>> and <</pre>> tags.
551 * Since 1.4.2 accepts unlimited number of arguments.
552 * @since 1.4.1
553 * @return void
554 */
555 function sm_print_r() {
556 ob_start(); // Buffer output
557 foreach(func_get_args() as $var) {
558 print_r($var);
559 echo "\n";
560 // php has get_class_methods function that can print class methods
561 if (is_object($var)) {
562 // get class methods if $var is object
563 $aMethods=get_class_methods(get_class($var));
564 // make sure that $aMethods is array and array is not empty
565 if (is_array($aMethods) && $aMethods!=array()) {
566 echo "Object methods:\n";
567 foreach($aMethods as $method) {
568 echo '* ' . $method . "\n";
569 }
570 }
571 echo "\n";
572 }
573 }
574 $buffer = ob_get_contents(); // Grab the print_r output
575 ob_end_clean(); // Silently discard the output & stop buffering
576 print '<div align="left"><pre>';
577 print htmlentities($buffer);
578 print '</pre></div>';
579 }
580
581