global.php 22 KB

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