global.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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. * Squelch error output to screen (only) for the given function.
  80. * If the SquirrelMail debug mode SM_DEBUG_MODE_ADVANCED is not
  81. * enabled, error output will not go to the log, either.
  82. *
  83. * This provides an alternative to the @ error-suppression
  84. * operator where errors will not be shown in the interface
  85. * but will show up in the server log file (assuming the
  86. * administrator has configured PHP logging).
  87. *
  88. * @since 1.4.12 and 1.5.2
  89. *
  90. * @param string $function The function to be executed
  91. * @param array $args The arguments to be passed to the function
  92. * (OPTIONAL; default no arguments)
  93. * NOTE: The caller must take extra action if
  94. * the function being called is supposed
  95. * to use any of the parameters by
  96. * reference. In the following example,
  97. * $x is passed by reference and $y is
  98. * passed by value to the "my_func"
  99. * function.
  100. * sq_call_function_suppress_errors('my_func', array(&$x, $y));
  101. *
  102. * @return mixed The return value, if any, of the function being
  103. * executed will be returned.
  104. *
  105. */
  106. function sq_call_function_suppress_errors($function, $args=NULL) {
  107. global $sm_debug_mode;
  108. $display_errors = ini_get('display_errors');
  109. ini_set('display_errors', '0');
  110. // if advanced debug mode isn't enabled, don't log the error, either
  111. //
  112. if (!($sm_debug_mode & SM_DEBUG_MODE_ADVANCED))
  113. $error_reporting = error_reporting(0);
  114. $ret = call_user_func_array($function, $args);
  115. if (!($sm_debug_mode & SM_DEBUG_MODE_ADVANCED))
  116. error_reporting($error_reporting);
  117. ini_set('display_errors', $display_errors);
  118. return $ret;
  119. }
  120. /**
  121. * Add a variable to the session.
  122. * @param mixed $var the variable to register
  123. * @param string $name the name to refer to this variable
  124. * @return void
  125. */
  126. function sqsession_register ($var, $name) {
  127. sqsession_is_active();
  128. $_SESSION[$name] = $var;
  129. }
  130. /**
  131. * Delete a variable from the session.
  132. * @param string $name the name of the var to delete
  133. * @return void
  134. */
  135. function sqsession_unregister ($name) {
  136. sqsession_is_active();
  137. unset($_SESSION[$name]);
  138. session_unregister("$name");
  139. }
  140. /**
  141. * Checks to see if a variable has already been registered
  142. * in the session.
  143. * @param string $name the name of the var to check
  144. * @return bool whether the var has been registered
  145. */
  146. function sqsession_is_registered ($name) {
  147. $test_name = &$name;
  148. $result = false;
  149. if (isset($_SESSION[$test_name])) {
  150. $result = true;
  151. }
  152. return $result;
  153. }
  154. /**
  155. * Retrieves a form variable, from a set of possible similarly named
  156. * form variables, based on finding a different, single field. This
  157. * is intended to allow more than one same-named inputs in a single
  158. * <form>, where the submit button that is clicked tells us which
  159. * input we should retrieve. An example is if we have:
  160. * <select name="startMessage_1">
  161. * <select name="startMessage_2">
  162. * <input type="submit" name="form_submit_1" />
  163. * <input type="submit" name="form_submit_2" />
  164. * and we want to know which one of the select inputs should be
  165. * returned as $startMessage (without the suffix!), this function
  166. * decides by looking for either "form_submit_1" or "form_submit_2"
  167. * (both should not appear). In this example, $name should be
  168. * "startMessage" and $indicator_field should be "form_submit".
  169. *
  170. * NOTE that form widgets must be named with the suffix "_1", "_2", "_3"
  171. * and so on, or this function will not work.
  172. *
  173. * If more than one of the indicator fields is found, the first one
  174. * (numerically) will win.
  175. *
  176. * If an indicator field is found without a matching input ($name)
  177. * field, FALSE is returned.
  178. *
  179. * If no indicator fields are found, a field of $name *without* any
  180. * suffix is searched for (but only if $fallback_no_suffix is TRUE),
  181. * and if not found, FALSE is ultimately returned.
  182. *
  183. * It should also be possible to use the same string for both
  184. * $name and $indicator_field to look for the first possible
  185. * widget with a suffix that can be found (and possibly fallback
  186. * to a widget without a suffix).
  187. *
  188. * @param string name the name of the var to search
  189. * @param mixed value the variable to return
  190. * @param string indicator_field the name of the field upon which to base
  191. * our decision upon (see above)
  192. * @param int search constant defining where to look
  193. * @param bool fallback_no_suffix whether or not to look for $name with
  194. * no suffix when nothing else is found
  195. * @param mixed default the value to assign to $value when nothing is found
  196. * @param int typecast force variable to be cast to given type (please
  197. * use SQ_TYPE_XXX constants or set to FALSE (default)
  198. * to leave variable type unmolested)
  199. *
  200. * @return bool whether variable is found.
  201. */
  202. function sqGetGlobalVarMultiple($name, &$value, $indicator_field,
  203. $search = SQ_INORDER,
  204. $fallback_no_suffix=TRUE, $default=NULL,
  205. $typecast=FALSE) {
  206. // Set arbitrary max limit -- should be much lower except on the
  207. // search results page, if there are many (50 or more?) mailboxes
  208. // shown, this may not be high enough. Is there some way we should
  209. // automate this value?
  210. //
  211. $max_form_search = 100;
  212. for ($i = 1; $i <= $max_form_search; $i++) {
  213. if (sqGetGlobalVar($indicator_field . '_' . $i, $temp, $search)) {
  214. return sqGetGlobalVar($name . '_' . $i, $value, $search, $default, $typecast);
  215. }
  216. }
  217. // no indicator field found; just try without suffix if allowed
  218. //
  219. if ($fallback_no_suffix) {
  220. return sqGetGlobalVar($name, $value, $search, $default, $typecast);
  221. }
  222. // no dice, set default and return FALSE
  223. //
  224. if (!is_null($default)) {
  225. $value = $default;
  226. }
  227. return FALSE;
  228. }
  229. /**
  230. * Search for the var $name in $_SESSION, $_POST, $_GET, $_COOKIE, or $_SERVER
  231. * and set it in provided var.
  232. *
  233. * If $search is not provided, or if it is SQ_INORDER, it will search $_SESSION,
  234. * then $_POST, then $_GET. If $search is SQ_FORM it will search $_POST and
  235. * $_GET. Otherwise, use one of the defined constants to look for a var in one
  236. * place specifically.
  237. *
  238. * Note: $search is an int value equal to one of the constants defined above.
  239. *
  240. * Example:
  241. * sqgetGlobalVar('username',$username,SQ_SESSION);
  242. * // No quotes around last param, it's a constant - not a string!
  243. *
  244. * @param string name the name of the var to search
  245. * @param mixed value the variable to return
  246. * @param int search constant defining where to look
  247. * @param mixed default the value to assign to $value when nothing is found
  248. * @param int typecast force variable to be cast to given type (please
  249. * use SQ_TYPE_XXX constants or set to FALSE (default)
  250. * to leave variable type unmolested)
  251. *
  252. * @return bool whether variable is found.
  253. */
  254. function sqgetGlobalVar($name, &$value, $search = SQ_INORDER, $default = NULL, $typecast = false) {
  255. $result = false;
  256. switch ($search) {
  257. /* we want the default case to be first here,
  258. so that if a valid value isn't specified,
  259. all three arrays will be searched. */
  260. default:
  261. case SQ_INORDER: // check session, post, get
  262. case SQ_SESSION:
  263. if( isset($_SESSION[$name]) ) {
  264. $value = $_SESSION[$name];
  265. $result = TRUE;
  266. break;
  267. } elseif ( $search == SQ_SESSION ) {
  268. break;
  269. }
  270. case SQ_FORM: // check post, get
  271. case SQ_POST:
  272. if( isset($_POST[$name]) ) {
  273. $value = $_POST[$name];
  274. $result = TRUE;
  275. break;
  276. } elseif ( $search == SQ_POST ) {
  277. break;
  278. }
  279. case SQ_GET:
  280. if ( isset($_GET[$name]) ) {
  281. $value = $_GET[$name];
  282. $result = TRUE;
  283. break;
  284. }
  285. /* NO IF HERE. FOR SQ_INORDER CASE, EXIT after GET */
  286. break;
  287. case SQ_COOKIE:
  288. if ( isset($_COOKIE[$name]) ) {
  289. $value = $_COOKIE[$name];
  290. $result = TRUE;
  291. break;
  292. }
  293. break;
  294. case SQ_SERVER:
  295. if ( isset($_SERVER[$name]) ) {
  296. $value = $_SERVER[$name];
  297. $result = TRUE;
  298. break;
  299. }
  300. break;
  301. }
  302. if ($result && $typecast) {
  303. switch ($typecast) {
  304. case SQ_TYPE_INT: $value = (int) $value; break;
  305. case SQ_TYPE_STRING: $value = (string) $value; break;
  306. case SQ_TYPE_BOOL: $value = (bool) $value; break;
  307. default: break;
  308. }
  309. } else if (!$result && !is_null($default)) {
  310. $value = $default;
  311. }
  312. return $result;
  313. }
  314. /**
  315. * Get an immutable copy of a configuration variable if SquirrelMail
  316. * is in "secured configuration" mode. This guarantees the caller
  317. * gets a copy of the requested value as it is set in the main
  318. * application configuration (including config_local overrides), and
  319. * not what it might be after possibly having been modified by some
  320. * other code (usually a plugin overriding configuration values for
  321. * one reason or another).
  322. *
  323. * WARNING: Please use this function as little as possible, because
  324. * every time it is called, it forcibly reloads the main configuration
  325. * file(s).
  326. *
  327. * Caller beware that this function will do nothing if SquirrelMail
  328. * is not in "secured configuration" mode per the $secured_config
  329. * setting.
  330. *
  331. * @param string $var_name The name of the desired variable
  332. *
  333. * @return mixed The desired value
  334. *
  335. * @since 1.5.2
  336. *
  337. */
  338. function get_secured_config_value($var_name) {
  339. static $return_values = array();
  340. // if we can avoid it, return values that have
  341. // already been retrieved (so we don't have to
  342. // include the config file yet again)
  343. //
  344. if (isset($return_values[$var_name])) {
  345. return $return_values[$var_name];
  346. }
  347. // load site configuration
  348. //
  349. require(SM_PATH . 'config/config.php');
  350. // load local configuration overrides
  351. //
  352. if (file_exists(SM_PATH . 'config/config_local.php')) {
  353. require(SM_PATH . 'config/config_local.php');
  354. }
  355. // if SM isn't in "secured configuration" mode,
  356. // just return the desired value from the global scope
  357. //
  358. if (!$secured_config) {
  359. global $$var_name;
  360. $return_values[$var_name] = $$var_name;
  361. return $$var_name;
  362. }
  363. // else we return what we got from the config file
  364. //
  365. $return_values[$var_name] = $$var_name;
  366. return $$var_name;
  367. }
  368. /**
  369. * Deletes an existing session, more advanced than the standard PHP
  370. * session_destroy(), it explicitly deletes the cookies and global vars.
  371. *
  372. * WARNING: Older PHP versions have some issues with session management.
  373. * See http://bugs.php.net/11643 (warning, spammed bug tracker) and
  374. * http://bugs.php.net/13834. SID constant is not destroyed in PHP 4.1.2,
  375. * 4.2.3 and maybe other versions. If you restart session after session
  376. * is destroyed, affected PHP versions produce PHP notice. Bug should
  377. * be fixed only in 4.3.0
  378. */
  379. function sqsession_destroy() {
  380. /*
  381. * php.net says we can kill the cookie by setting just the name:
  382. * http://www.php.net/manual/en/function.setcookie.php
  383. * maybe this will help fix the session merging again.
  384. *
  385. * Changed the theory on this to kill the cookies first starting
  386. * a new session will provide a new session for all instances of
  387. * the browser, we don't want that, as that is what is causing the
  388. * merging of sessions.
  389. */
  390. global $base_uri, $_COOKIE, $_SESSION;
  391. if (isset($_COOKIE[session_name()]) && session_name()) sqsetcookie(session_name(), $_COOKIE[session_name()], 1, $base_uri);
  392. if (isset($_COOKIE['key']) && $_COOKIE['key']) sqsetcookie('key','SQMTRASH',1,$base_uri);
  393. $sessid = session_id();
  394. if (!empty( $sessid )) {
  395. $_SESSION = array();
  396. @session_destroy();
  397. }
  398. }
  399. /**
  400. * Function to verify a session has been started. If it hasn't
  401. * start a session up. php.net doesn't tell you that $_SESSION
  402. * (even though autoglobal), is not created unless a session is
  403. * started, unlike $_POST, $_GET and such
  404. * Update: (see #1685031) the session ID is left over after the
  405. * session is closed in some PHP setups; this function just becomes
  406. * a passthru to sqsession_start(), but leaving old code in for
  407. * edification.
  408. */
  409. function sqsession_is_active() {
  410. //$sessid = session_id();
  411. //if ( empty( $sessid ) ) {
  412. sqsession_start();
  413. //}
  414. }
  415. /**
  416. * Function to start the session and store the cookie with the session_id as
  417. * HttpOnly cookie which means that the cookie isn't accessible by javascript
  418. * (IE6 only)
  419. * Note that as sqsession_is_active() no longer discriminates as to when
  420. * it calls this function, session_start() has to have E_NOTICE suppression
  421. * (thus the @ sign).
  422. */
  423. function sqsession_start() {
  424. global $base_uri;
  425. sq_call_function_suppress_errors('session_start');
  426. // was: @session_start();
  427. $session_id = session_id();
  428. // session_starts sets the sessionid cookie but without the httponly var
  429. // setting the cookie again sets the httponly cookie attribute
  430. //
  431. // need to check if headers have been sent, since sqsession_is_active()
  432. // has become just a passthru to this function, so the sqsetcookie()
  433. // below is called every time, even after headers have already been sent
  434. //
  435. if (!headers_sent())
  436. sqsetcookie(session_name(),$session_id,false,$base_uri);
  437. }
  438. /**
  439. * Set a cookie
  440. * @param string $sName The name of the cookie.
  441. * @param string $sValue The value of the cookie.
  442. * @param int $iExpire The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch.
  443. * @param string $sPath The path on the server in which the cookie will be available on.
  444. * @param string $sDomain The domain that the cookie is available.
  445. * @param boolean $bSecure Indicates that the cookie should only be transmitted over a secure HTTPS connection.
  446. * @param boolean $bHttpOnly Disallow JS to access the cookie (IE6 only)
  447. * @return void
  448. */
  449. function sqsetcookie($sName,$sValue='deleted',$iExpire=0,$sPath="",$sDomain="",$bSecure=false,$bHttpOnly=true) {
  450. // if we have a secure connection then limit the cookies to https only.
  451. if ($sName && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) {
  452. $bSecure = true;
  453. }
  454. // admin config can override the restriction of secure-only cookies
  455. global $only_secure_cookies;
  456. if (!$only_secure_cookies)
  457. $bSecure = false;
  458. if (false && check_php_version(5,2)) {
  459. // php 5 supports the httponly attribute in setcookie, but because setcookie seems a bit
  460. // broken we use the header function for php 5.2 as well. We might change that later.
  461. //setcookie($sName,$sValue,(int) $iExpire,$sPath,$sDomain,$bSecure,$bHttpOnly);
  462. } else {
  463. if (!empty($sDomain)) {
  464. // Fix the domain to accept domains with and without 'www.'.
  465. if (strtolower(substr($sDomain, 0, 4)) == 'www.') $sDomain = substr($sDomain, 4);
  466. $sDomain = '.' . $sDomain;
  467. // Remove port information.
  468. $Port = strpos($sDomain, ':');
  469. if ($Port !== false) $sDomain = substr($sDomain, 0, $Port);
  470. }
  471. if (!$sValue) $sValue = 'deleted';
  472. header('Set-Cookie: ' . rawurlencode($sName) . '=' . rawurlencode($sValue)
  473. . (empty($iExpire) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', $iExpire) . ' GMT')
  474. . (empty($sPath) ? '' : '; path=' . $sPath)
  475. . (empty($sDomain) ? '' : '; domain=' . $sDomain)
  476. . (!$bSecure ? '' : '; secure')
  477. . (!$bHttpOnly ? '' : '; HttpOnly'), false);
  478. }
  479. }
  480. /**
  481. * session_regenerate_id replacement for PHP < 4.3.2
  482. *
  483. * This code is borrowed from Gallery, session.php version 1.53.2.1
  484. */
  485. if (!function_exists('session_regenerate_id')) {
  486. function make_seed() {
  487. list($usec, $sec) = explode(' ', microtime());
  488. return (float)$sec + ((float)$usec * 100000);
  489. }
  490. function php_combined_lcg() {
  491. mt_srand(make_seed());
  492. $tv = gettimeofday();
  493. $lcg['s1'] = $tv['sec'] ^ (~$tv['usec']);
  494. $lcg['s2'] = mt_rand();
  495. $q = (int) ($lcg['s1'] / 53668);
  496. $lcg['s1'] = (int) (40014 * ($lcg['s1'] - 53668 * $q) - 12211 * $q);
  497. if ($lcg['s1'] < 0) {
  498. $lcg['s1'] += 2147483563;
  499. }
  500. $q = (int) ($lcg['s2'] / 52774);
  501. $lcg['s2'] = (int) (40692 * ($lcg['s2'] - 52774 * $q) - 3791 * $q);
  502. if ($lcg['s2'] < 0) {
  503. $lcg['s2'] += 2147483399;
  504. }
  505. $z = (int) ($lcg['s1'] - $lcg['s2']);
  506. if ($z < 1) {
  507. $z += 2147483562;
  508. }
  509. return $z * 4.656613e-10;
  510. }
  511. function session_regenerate_id() {
  512. global $base_uri;
  513. $tv = gettimeofday();
  514. sqgetGlobalVar('REMOTE_ADDR',$remote_addr,SQ_SERVER);
  515. $buf = sprintf("%.15s%ld%ld%0.8f", $remote_addr, $tv['sec'], $tv['usec'], php_combined_lcg() * 10);
  516. session_id(md5($buf));
  517. if (ini_get('session.use_cookies')) {
  518. // at a later stage we use sqsetcookie. At this point just do
  519. // what session_regenerate_id would do
  520. setcookie(session_name(), session_id(), NULL, $base_uri);
  521. }
  522. return TRUE;
  523. }
  524. }
  525. /**
  526. * php_self
  527. *
  528. * Creates an URL for the page calling this function, using either the PHP global
  529. * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added. Before 1.5.1
  530. * function was stored in function/strings.php.
  531. *
  532. * @return string the complete url for this page
  533. * @since 1.2.3
  534. */
  535. function php_self () {
  536. if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
  537. return $req_uri;
  538. }
  539. if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
  540. // need to add query string to end of PHP_SELF to match REQUEST_URI
  541. //
  542. if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
  543. $php_self .= '?' . $query_string;
  544. }
  545. return $php_self;
  546. }
  547. return '';
  548. }
  549. /**
  550. * Find files and/or directories in a given directory optionally
  551. * limited to only those with the given file extension. If the
  552. * directory is not found or cannot be opened, no error is generated;
  553. * only an empty file list is returned.
  554. FIXME: do we WANT to throw an error or a notice or... or return FALSE?
  555. *
  556. * @param string $directory_path The path (relative or absolute)
  557. * to the desired directory.
  558. * @param mixed $extension The file extension filter - either
  559. * an array of desired extension(s),
  560. * or a comma-separated list of same
  561. * (optional; default is to return
  562. * all files (dirs).
  563. * @param boolean $return_filenames_only When TRUE, only file/dir names
  564. * are returned, otherwise the
  565. * $directory_path string is
  566. * prepended to each file/dir in
  567. * the returned list (optional;
  568. * default is filename/dirname only)
  569. * @param boolean $include_directories When TRUE, directories are
  570. * included (optional; default
  571. * DO include directories).
  572. * @param boolean $directories_only When TRUE, ONLY directories
  573. * are included (optional; default
  574. * is to include files too).
  575. * @param boolean $separate_files_and_directories When TRUE, files and
  576. * directories are returned
  577. * in separate lists, so
  578. * the return value is
  579. * formatted as a two-element
  580. * array with the two keys
  581. * "FILES" and "DIRECTORIES",
  582. * where corresponding values
  583. * are lists of either all
  584. * files or all directories
  585. * (optional; default do not
  586. * split up return array).
  587. * @param boolean $only_sm When TRUE, a security check will
  588. * limit directory access to only
  589. * paths within the SquirrelMail
  590. * installation currently being used
  591. * (optional; default TRUE)
  592. *
  593. * @return array The requested file/directory list(s).
  594. *
  595. * @since 1.5.2
  596. *
  597. */
  598. function list_files($directory_path, $extensions='', $return_filenames_only=TRUE,
  599. $include_directories=TRUE, $directories_only=FALSE,
  600. $separate_files_and_directories=FALSE, $only_sm=TRUE) {
  601. $files = array();
  602. $directories = array();
  603. // make sure requested path is under SM_PATH if needed
  604. //
  605. if ($only_sm) {
  606. if (strpos(realpath($directory_path), realpath(SM_PATH)) !== 0) {
  607. //plain_error_message(_("Illegal filesystem access was requested"));
  608. echo _("Illegal filesystem access was requested");
  609. exit;
  610. }
  611. }
  612. // validate given directory
  613. //
  614. if (empty($directory_path)
  615. || !is_dir($directory_path)
  616. || !($DIR = opendir($directory_path))) {
  617. return $files;
  618. }
  619. // ensure extensions is an array and is properly formatted
  620. //
  621. if (!empty($extensions)) {
  622. if (!is_array($extensions))
  623. $extensions = explode(',', $extensions);
  624. $temp_extensions = array();
  625. foreach ($extensions as $ext)
  626. $temp_extensions[] = '.' . trim(trim($ext), '.');
  627. $extensions = $temp_extensions;
  628. } else $extensions = array();
  629. $directory_path = rtrim($directory_path, '/');
  630. // parse through the files
  631. //
  632. while (($file = readdir($DIR)) !== false) {
  633. if ($file == '.' || $file == '..') continue;
  634. if (!empty($extensions))
  635. foreach ($extensions as $ext)
  636. if (strrpos($file, $ext) !== (strlen($file) - strlen($ext)))
  637. continue 2;
  638. // only use is_dir() if we really need to (be as efficient as possible)
  639. //
  640. $is_dir = FALSE;
  641. if (!$include_directories || $directories_only
  642. || $separate_files_and_directories) {
  643. if (is_dir($directory_path . '/' . $file)) {
  644. if (!$include_directories) continue;
  645. $is_dir = TRUE;
  646. $directories[] = ($return_filenames_only
  647. ? $file
  648. : $directory_path . '/' . $file);
  649. }
  650. if ($directories_only) continue;
  651. }
  652. if (!$separate_files_and_directories
  653. || ($separate_files_and_directories && !$is_dir)) {
  654. $files[] = ($return_filenames_only
  655. ? $file
  656. : $directory_path . '/' . $file);
  657. }
  658. }
  659. closedir($DIR);
  660. if ($directories_only) return $directories;
  661. if ($separate_files_and_directories) return array('FILES' => $files,
  662. 'DIRECTORIES' => $directories);
  663. return $files;
  664. }
  665. /**
  666. * Print variable
  667. *
  668. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  669. *
  670. * Debugging function - does the same as print_r, but makes sure special
  671. * characters are converted to htmlentities first. This will allow
  672. * values like <some@email.address> to be displayed.
  673. * The output is wrapped in <<pre>> and <</pre>> tags.
  674. * Since 1.4.2 accepts unlimited number of arguments.
  675. * @since 1.4.1
  676. * @return void
  677. */
  678. function sm_print_r() {
  679. ob_start(); // Buffer output
  680. foreach(func_get_args() as $var) {
  681. print_r($var);
  682. echo "\n";
  683. // php has get_class_methods function that can print class methods
  684. if (is_object($var)) {
  685. // get class methods if $var is object
  686. $aMethods=get_class_methods(get_class($var));
  687. // make sure that $aMethods is array and array is not empty
  688. if (is_array($aMethods) && $aMethods!=array()) {
  689. echo "Object methods:\n";
  690. foreach($aMethods as $method) {
  691. echo '* ' . $method . "\n";
  692. }
  693. }
  694. echo "\n";
  695. }
  696. }
  697. $buffer = ob_get_contents(); // Grab the print_r output
  698. ob_end_clean(); // Silently discard the output & stop buffering
  699. print '<div align="left"><pre>';
  700. print htmlentities($buffer);
  701. print '</pre></div>';
  702. }
  703. /**
  704. * Sanitize a value using htmlspecialchars() or similar, but also
  705. * recursively run htmlspecialchars() (or similar) on array keys
  706. * and values.
  707. *
  708. * If $value is not a string or an array with strings in it,
  709. * the value is returned as is.
  710. *
  711. * @param mixed $value The value to be sanitized.
  712. * @param mixed $quote_style Either boolean or an integer. If it
  713. * is an integer, it must be the PHP
  714. * constant indicating if/how to escape
  715. * quotes: ENT_QUOTES, ENT_COMPAT, or
  716. * ENT_NOQUOTES. If it is a boolean value,
  717. * it must be TRUE and thus indicates
  718. * that the only sanitizing to be done
  719. * herein is to replace single and double
  720. * quotes with &#039; and &quot;, no other
  721. * changes are made to $value. If it is
  722. * boolean and FALSE, behavior reverts
  723. * to same as if the value was ENT_QUOTES
  724. * (OPTIONAL; default is ENT_QUOTES).
  725. *
  726. * @return mixed The sanitized value.
  727. *
  728. * @since 1.5.2
  729. *
  730. **/
  731. function sq_htmlspecialchars($value, $quote_style=ENT_QUOTES) {
  732. if ($quote_style === FALSE) $quote_style = ENT_QUOTES;
  733. // array? go recursive...
  734. //
  735. if (is_array($value)) {
  736. $return_array = array();
  737. foreach ($value as $key => $val) {
  738. $return_array[sq_htmlspecialchars($key, $quote_style)]
  739. = sq_htmlspecialchars($val, $quote_style);
  740. }
  741. return $return_array;
  742. // sanitize strings only
  743. //
  744. } else if (is_string($value)) {
  745. if ($quote_style === TRUE)
  746. return str_replace(array('\'', '"'), array('&#039;', '&quot;'), $value);
  747. else
  748. return htmlspecialchars($value, $quote_style);
  749. }
  750. // anything else gets returned with no changes
  751. //
  752. return $value;
  753. }