global.php 22 KB

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