PageRenderTime 69ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 1ms

/phpBB/includes/functions.php

https://github.com/erikfrerejean/phpbb3
PHP | 4947 lines | 3608 code | 584 blank | 755 comment | 609 complexity | 31150ddcf41c23c40c67b7f25ddb209c MD5 | raw file
Possible License(s): AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. *
  4. * @package phpBB3
  5. * @version $Id$
  6. * @copyright (c) 2005 phpBB Group
  7. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  8. *
  9. */
  10. /**
  11. * @ignore
  12. */
  13. if (!defined('IN_PHPBB'))
  14. {
  15. exit;
  16. }
  17. // Common global functions
  18. /**
  19. * set_var
  20. *
  21. * Set variable, used by {@link request_var the request_var function}
  22. *
  23. * @access private
  24. */
  25. function set_var(&$result, $var, $type, $multibyte = false)
  26. {
  27. settype($var, $type);
  28. $result = $var;
  29. if ($type == 'string')
  30. {
  31. $result = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $result), ENT_COMPAT, 'UTF-8'));
  32. if (!empty($result))
  33. {
  34. // Make sure multibyte characters are wellformed
  35. if ($multibyte)
  36. {
  37. if (!preg_match('/^./u', $result))
  38. {
  39. $result = '';
  40. }
  41. }
  42. else
  43. {
  44. // no multibyte, allow only ASCII (0-127)
  45. $result = preg_replace('/[\x80-\xFF]/', '?', $result);
  46. }
  47. }
  48. $result = (STRIP) ? stripslashes($result) : $result;
  49. }
  50. }
  51. /**
  52. * request_var
  53. *
  54. * Used to get passed variable
  55. */
  56. function request_var($var_name, $default, $multibyte = false, $cookie = false)
  57. {
  58. if (!$cookie && isset($_COOKIE[$var_name]))
  59. {
  60. if (!isset($_GET[$var_name]) && !isset($_POST[$var_name]))
  61. {
  62. return (is_array($default)) ? array() : $default;
  63. }
  64. $_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name];
  65. }
  66. $super_global = ($cookie) ? '_COOKIE' : '_REQUEST';
  67. if (!isset($GLOBALS[$super_global][$var_name]) || is_array($GLOBALS[$super_global][$var_name]) != is_array($default))
  68. {
  69. return (is_array($default)) ? array() : $default;
  70. }
  71. $var = $GLOBALS[$super_global][$var_name];
  72. if (!is_array($default))
  73. {
  74. $type = gettype($default);
  75. }
  76. else
  77. {
  78. list($key_type, $type) = each($default);
  79. $type = gettype($type);
  80. $key_type = gettype($key_type);
  81. if ($type == 'array')
  82. {
  83. reset($default);
  84. $default = current($default);
  85. list($sub_key_type, $sub_type) = each($default);
  86. $sub_type = gettype($sub_type);
  87. $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type;
  88. $sub_key_type = gettype($sub_key_type);
  89. }
  90. }
  91. if (is_array($var))
  92. {
  93. $_var = $var;
  94. $var = array();
  95. foreach ($_var as $k => $v)
  96. {
  97. set_var($k, $k, $key_type);
  98. if ($type == 'array' && is_array($v))
  99. {
  100. foreach ($v as $_k => $_v)
  101. {
  102. if (is_array($_v))
  103. {
  104. $_v = null;
  105. }
  106. set_var($_k, $_k, $sub_key_type, $multibyte);
  107. set_var($var[$k][$_k], $_v, $sub_type, $multibyte);
  108. }
  109. }
  110. else
  111. {
  112. if ($type == 'array' || is_array($v))
  113. {
  114. $v = null;
  115. }
  116. set_var($var[$k], $v, $type, $multibyte);
  117. }
  118. }
  119. }
  120. else
  121. {
  122. set_var($var, $var, $type, $multibyte);
  123. }
  124. return $var;
  125. }
  126. /**
  127. * Sets a configuration option's value.
  128. *
  129. * Please note that this function does not update the is_dynamic value for
  130. * an already existing config option.
  131. *
  132. * @param string $config_name The configuration option's name
  133. * @param string $config_value New configuration value
  134. * @param bool $is_dynamic Whether this variable should be cached (false) or
  135. * if it changes too frequently (true) to be
  136. * efficiently cached.
  137. *
  138. * @return null
  139. */
  140. function set_config($config_name, $config_value, $is_dynamic = false)
  141. {
  142. global $db, $cache, $config;
  143. $sql = 'UPDATE ' . CONFIG_TABLE . "
  144. SET config_value = '" . $db->sql_escape($config_value) . "'
  145. WHERE config_name = '" . $db->sql_escape($config_name) . "'";
  146. $db->sql_query($sql);
  147. if (!$db->sql_affectedrows() && !isset($config[$config_name]))
  148. {
  149. $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array(
  150. 'config_name' => $config_name,
  151. 'config_value' => $config_value,
  152. 'is_dynamic' => ($is_dynamic) ? 1 : 0));
  153. $db->sql_query($sql);
  154. }
  155. $config[$config_name] = $config_value;
  156. if (!$is_dynamic)
  157. {
  158. $cache->destroy('config');
  159. }
  160. }
  161. /**
  162. * Increments an integer config value directly in the database.
  163. *
  164. * @param string $config_name The configuration option's name
  165. * @param int $increment Amount to increment by
  166. * @param bool $is_dynamic Whether this variable should be cached (false) or
  167. * if it changes too frequently (true) to be
  168. * efficiently cached.
  169. *
  170. * @return null
  171. */
  172. function set_config_count($config_name, $increment, $is_dynamic = false)
  173. {
  174. global $db, $cache;
  175. switch ($db->sql_layer)
  176. {
  177. case 'firebird':
  178. // Precision must be from 1 to 18
  179. $sql_update = 'CAST(CAST(config_value as DECIMAL(18, 0)) + ' . (int) $increment . ' as VARCHAR(255))';
  180. break;
  181. case 'postgres':
  182. // Need to cast to text first for PostgreSQL 7.x
  183. $sql_update = 'CAST(CAST(config_value::text as DECIMAL(255, 0)) + ' . (int) $increment . ' as VARCHAR(255))';
  184. break;
  185. // MySQL, SQlite, mssql, mssql_odbc, oracle
  186. default:
  187. $sql_update = 'config_value + ' . (int) $increment;
  188. break;
  189. }
  190. $db->sql_query('UPDATE ' . CONFIG_TABLE . ' SET config_value = ' . $sql_update . " WHERE config_name = '" . $db->sql_escape($config_name) . "'");
  191. if (!$is_dynamic)
  192. {
  193. $cache->destroy('config');
  194. }
  195. }
  196. /**
  197. * Generates an alphanumeric random string of given length
  198. *
  199. * @return string
  200. */
  201. function gen_rand_string($num_chars = 8)
  202. {
  203. // [a, z] + [0, 9] = 36
  204. return substr(strtoupper(base_convert(unique_id(), 16, 36)), 0, $num_chars);
  205. }
  206. /**
  207. * Generates a user-friendly alphanumeric random string of given length
  208. * We remove 0 and O so users cannot confuse those in passwords etc.
  209. *
  210. * @return string
  211. */
  212. function gen_rand_string_friendly($num_chars = 8)
  213. {
  214. $rand_str = unique_id();
  215. // Remove Z and Y from the base_convert(), replace 0 with Z and O with Y
  216. // [a, z] + [0, 9] - {z, y} = [a, z] + [0, 9] - {0, o} = 34
  217. $rand_str = str_replace(array('0', 'O'), array('Z', 'Y'), strtoupper(base_convert($rand_str, 16, 34)));
  218. return substr($rand_str, 0, $num_chars);
  219. }
  220. /**
  221. * Return unique id
  222. * @param string $extra additional entropy
  223. */
  224. function unique_id($extra = 'c')
  225. {
  226. static $dss_seeded = false;
  227. global $config;
  228. $val = $config['rand_seed'] . microtime();
  229. $val = md5($val);
  230. $config['rand_seed'] = md5($config['rand_seed'] . $val . $extra);
  231. if ($dss_seeded !== true && ($config['rand_seed_last_update'] < time() - rand(1,10)))
  232. {
  233. set_config('rand_seed_last_update', time(), true);
  234. set_config('rand_seed', $config['rand_seed'], true);
  235. $dss_seeded = true;
  236. }
  237. return substr($val, 4, 16);
  238. }
  239. /**
  240. * Wrapper for mt_rand() which allows swapping $min and $max parameters.
  241. *
  242. * PHP does not allow us to swap the order of the arguments for mt_rand() anymore.
  243. * (since PHP 5.3.4, see http://bugs.php.net/46587)
  244. *
  245. * @param int $min Lowest value to be returned
  246. * @param int $max Highest value to be returned
  247. *
  248. * @return int Random integer between $min and $max (or $max and $min)
  249. */
  250. function phpbb_mt_rand($min, $max)
  251. {
  252. return ($min > $max) ? mt_rand($max, $min) : mt_rand($min, $max);
  253. }
  254. /**
  255. * Wrapper for getdate() which returns the equivalent array for UTC timestamps.
  256. *
  257. * @param int $time Unix timestamp (optional)
  258. *
  259. * @return array Returns an associative array of information related to the timestamp.
  260. * See http://www.php.net/manual/en/function.getdate.php
  261. */
  262. function phpbb_gmgetdate($time = false)
  263. {
  264. if ($time === false)
  265. {
  266. $time = time();
  267. }
  268. // getdate() interprets timestamps in local time.
  269. // What follows uses the fact that getdate() and
  270. // date('Z') balance each other out.
  271. return getdate($time - date('Z'));
  272. }
  273. /**
  274. * Return formatted string for filesizes
  275. *
  276. * @param mixed $value filesize in bytes
  277. * (non-negative number; int, float or string)
  278. * @param bool $string_only true if language string should be returned
  279. * @param array $allowed_units only allow these units (data array indexes)
  280. *
  281. * @return mixed data array if $string_only is false
  282. * @author bantu
  283. */
  284. function get_formatted_filesize($value, $string_only = true, $allowed_units = false)
  285. {
  286. global $user;
  287. $available_units = array(
  288. 'tb' => array(
  289. 'min' => 1099511627776, // pow(2, 40)
  290. 'index' => 4,
  291. 'si_unit' => 'TB',
  292. 'iec_unit' => 'TIB',
  293. ),
  294. 'gb' => array(
  295. 'min' => 1073741824, // pow(2, 30)
  296. 'index' => 3,
  297. 'si_unit' => 'GB',
  298. 'iec_unit' => 'GIB',
  299. ),
  300. 'mb' => array(
  301. 'min' => 1048576, // pow(2, 20)
  302. 'index' => 2,
  303. 'si_unit' => 'MB',
  304. 'iec_unit' => 'MIB',
  305. ),
  306. 'kb' => array(
  307. 'min' => 1024, // pow(2, 10)
  308. 'index' => 1,
  309. 'si_unit' => 'KB',
  310. 'iec_unit' => 'KIB',
  311. ),
  312. 'b' => array(
  313. 'min' => 0,
  314. 'index' => 0,
  315. 'si_unit' => 'BYTES', // Language index
  316. 'iec_unit' => 'BYTES', // Language index
  317. ),
  318. );
  319. foreach ($available_units as $si_identifier => $unit_info)
  320. {
  321. if (!empty($allowed_units) && $si_identifier != 'b' && !in_array($si_identifier, $allowed_units))
  322. {
  323. continue;
  324. }
  325. if ($value >= $unit_info['min'])
  326. {
  327. $unit_info['si_identifier'] = $si_identifier;
  328. break;
  329. }
  330. }
  331. unset($available_units);
  332. for ($i = 0; $i < $unit_info['index']; $i++)
  333. {
  334. $value /= 1024;
  335. }
  336. $value = round($value, 2);
  337. // Lookup units in language dictionary
  338. $unit_info['si_unit'] = (isset($user->lang[$unit_info['si_unit']])) ? $user->lang[$unit_info['si_unit']] : $unit_info['si_unit'];
  339. $unit_info['iec_unit'] = (isset($user->lang[$unit_info['iec_unit']])) ? $user->lang[$unit_info['iec_unit']] : $unit_info['iec_unit'];
  340. // Default to IEC
  341. $unit_info['unit'] = $unit_info['iec_unit'];
  342. if (!$string_only)
  343. {
  344. $unit_info['value'] = $value;
  345. return $unit_info;
  346. }
  347. return $value . ' ' . $unit_info['unit'];
  348. }
  349. /**
  350. * Determine whether we are approaching the maximum execution time. Should be called once
  351. * at the beginning of the script in which it's used.
  352. * @return bool Either true if the maximum execution time is nearly reached, or false
  353. * if some time is still left.
  354. */
  355. function still_on_time($extra_time = 15)
  356. {
  357. static $max_execution_time, $start_time;
  358. $time = explode(' ', microtime());
  359. $current_time = $time[0] + $time[1];
  360. if (empty($max_execution_time))
  361. {
  362. $max_execution_time = (function_exists('ini_get')) ? (int) @ini_get('max_execution_time') : (int) @get_cfg_var('max_execution_time');
  363. // If zero, then set to something higher to not let the user catch the ten seconds barrier.
  364. if ($max_execution_time === 0)
  365. {
  366. $max_execution_time = 50 + $extra_time;
  367. }
  368. $max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50);
  369. // For debugging purposes
  370. // $max_execution_time = 10;
  371. global $starttime;
  372. $start_time = (empty($starttime)) ? $current_time : $starttime;
  373. }
  374. return (ceil($current_time - $start_time) < $max_execution_time) ? true : false;
  375. }
  376. /**
  377. *
  378. * @version Version 0.1 / slightly modified for phpBB 3.0.x (using $H$ as hash type identifier)
  379. *
  380. * Portable PHP password hashing framework.
  381. *
  382. * Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
  383. * the public domain.
  384. *
  385. * There's absolutely no warranty.
  386. *
  387. * The homepage URL for this framework is:
  388. *
  389. * http://www.openwall.com/phpass/
  390. *
  391. * Please be sure to update the Version line if you edit this file in any way.
  392. * It is suggested that you leave the main version number intact, but indicate
  393. * your project name (after the slash) and add your own revision information.
  394. *
  395. * Please do not change the "private" password hashing method implemented in
  396. * here, thereby making your hashes incompatible. However, if you must, please
  397. * change the hash type identifier (the "$P$") to something different.
  398. *
  399. * Obviously, since this code is in the public domain, the above are not
  400. * requirements (there can be none), but merely suggestions.
  401. *
  402. *
  403. * Hash the password
  404. */
  405. function phpbb_hash($password)
  406. {
  407. $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  408. $random_state = unique_id();
  409. $random = '';
  410. $count = 6;
  411. if (($fh = @fopen('/dev/urandom', 'rb')))
  412. {
  413. $random = fread($fh, $count);
  414. fclose($fh);
  415. }
  416. if (strlen($random) < $count)
  417. {
  418. $random = '';
  419. for ($i = 0; $i < $count; $i += 16)
  420. {
  421. $random_state = md5(unique_id() . $random_state);
  422. $random .= pack('H*', md5($random_state));
  423. }
  424. $random = substr($random, 0, $count);
  425. }
  426. $hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64);
  427. if (strlen($hash) == 34)
  428. {
  429. return $hash;
  430. }
  431. return md5($password);
  432. }
  433. /**
  434. * Check for correct password
  435. *
  436. * @param string $password The password in plain text
  437. * @param string $hash The stored password hash
  438. *
  439. * @return bool Returns true if the password is correct, false if not.
  440. */
  441. function phpbb_check_hash($password, $hash)
  442. {
  443. if (strlen($password) > 4096)
  444. {
  445. // If the password is too huge, we will simply reject it
  446. // and not let the server try to hash it.
  447. return false;
  448. }
  449. $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  450. if (strlen($hash) == 34)
  451. {
  452. return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
  453. }
  454. return (md5($password) === $hash) ? true : false;
  455. }
  456. /**
  457. * Generate salt for hash generation
  458. */
  459. function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6)
  460. {
  461. if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
  462. {
  463. $iteration_count_log2 = 8;
  464. }
  465. $output = '$H$';
  466. $output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)];
  467. $output .= _hash_encode64($input, 6, $itoa64);
  468. return $output;
  469. }
  470. /**
  471. * Encode hash
  472. */
  473. function _hash_encode64($input, $count, &$itoa64)
  474. {
  475. $output = '';
  476. $i = 0;
  477. do
  478. {
  479. $value = ord($input[$i++]);
  480. $output .= $itoa64[$value & 0x3f];
  481. if ($i < $count)
  482. {
  483. $value |= ord($input[$i]) << 8;
  484. }
  485. $output .= $itoa64[($value >> 6) & 0x3f];
  486. if ($i++ >= $count)
  487. {
  488. break;
  489. }
  490. if ($i < $count)
  491. {
  492. $value |= ord($input[$i]) << 16;
  493. }
  494. $output .= $itoa64[($value >> 12) & 0x3f];
  495. if ($i++ >= $count)
  496. {
  497. break;
  498. }
  499. $output .= $itoa64[($value >> 18) & 0x3f];
  500. }
  501. while ($i < $count);
  502. return $output;
  503. }
  504. /**
  505. * The crypt function/replacement
  506. */
  507. function _hash_crypt_private($password, $setting, &$itoa64)
  508. {
  509. $output = '*';
  510. // Check for correct hash
  511. if (substr($setting, 0, 3) != '$H$' && substr($setting, 0, 3) != '$P$')
  512. {
  513. return $output;
  514. }
  515. $count_log2 = strpos($itoa64, $setting[3]);
  516. if ($count_log2 < 7 || $count_log2 > 30)
  517. {
  518. return $output;
  519. }
  520. $count = 1 << $count_log2;
  521. $salt = substr($setting, 4, 8);
  522. if (strlen($salt) != 8)
  523. {
  524. return $output;
  525. }
  526. /**
  527. * We're kind of forced to use MD5 here since it's the only
  528. * cryptographic primitive available in all versions of PHP
  529. * currently in use. To implement our own low-level crypto
  530. * in PHP would result in much worse performance and
  531. * consequently in lower iteration counts and hashes that are
  532. * quicker to crack (by non-PHP code).
  533. */
  534. if (PHP_VERSION >= 5)
  535. {
  536. $hash = md5($salt . $password, true);
  537. do
  538. {
  539. $hash = md5($hash . $password, true);
  540. }
  541. while (--$count);
  542. }
  543. else
  544. {
  545. $hash = pack('H*', md5($salt . $password));
  546. do
  547. {
  548. $hash = pack('H*', md5($hash . $password));
  549. }
  550. while (--$count);
  551. }
  552. $output = substr($setting, 0, 12);
  553. $output .= _hash_encode64($hash, 16, $itoa64);
  554. return $output;
  555. }
  556. /**
  557. * Hashes an email address to a big integer
  558. *
  559. * @param string $email Email address
  560. *
  561. * @return string Unsigned Big Integer
  562. */
  563. function phpbb_email_hash($email)
  564. {
  565. return sprintf('%u', crc32(strtolower($email))) . strlen($email);
  566. }
  567. /**
  568. * Wrapper for version_compare() that allows using uppercase A and B
  569. * for alpha and beta releases.
  570. *
  571. * See http://www.php.net/manual/en/function.version-compare.php
  572. *
  573. * @param string $version1 First version number
  574. * @param string $version2 Second version number
  575. * @param string $operator Comparison operator (optional)
  576. *
  577. * @return mixed Boolean (true, false) if comparison operator is specified.
  578. * Integer (-1, 0, 1) otherwise.
  579. */
  580. function phpbb_version_compare($version1, $version2, $operator = null)
  581. {
  582. $version1 = strtolower($version1);
  583. $version2 = strtolower($version2);
  584. if (is_null($operator))
  585. {
  586. return version_compare($version1, $version2);
  587. }
  588. else
  589. {
  590. return version_compare($version1, $version2, $operator);
  591. }
  592. }
  593. /**
  594. * Global function for chmodding directories and files for internal use
  595. *
  596. * This function determines owner and group whom the file belongs to and user and group of PHP and then set safest possible file permissions.
  597. * The function determines owner and group from common.php file and sets the same to the provided file.
  598. * The function uses bit fields to build the permissions.
  599. * The function sets the appropiate execute bit on directories.
  600. *
  601. * Supported constants representing bit fields are:
  602. *
  603. * CHMOD_ALL - all permissions (7)
  604. * CHMOD_READ - read permission (4)
  605. * CHMOD_WRITE - write permission (2)
  606. * CHMOD_EXECUTE - execute permission (1)
  607. *
  608. * NOTE: The function uses POSIX extension and fileowner()/filegroup() functions. If any of them is disabled, this function tries to build proper permissions, by calling is_readable() and is_writable() functions.
  609. *
  610. * @param string $filename The file/directory to be chmodded
  611. * @param int $perms Permissions to set
  612. *
  613. * @return bool true on success, otherwise false
  614. * @author faw, phpBB Group
  615. */
  616. function phpbb_chmod($filename, $perms = CHMOD_READ)
  617. {
  618. static $_chmod_info;
  619. // Return if the file no longer exists.
  620. if (!file_exists($filename))
  621. {
  622. return false;
  623. }
  624. // Determine some common vars
  625. if (empty($_chmod_info))
  626. {
  627. if (!function_exists('fileowner') || !function_exists('filegroup'))
  628. {
  629. // No need to further determine owner/group - it is unknown
  630. $_chmod_info['process'] = false;
  631. }
  632. else
  633. {
  634. global $phpbb_root_path, $phpEx;
  635. // Determine owner/group of common.php file and the filename we want to change here
  636. $common_php_owner = @fileowner($phpbb_root_path . 'common.' . $phpEx);
  637. $common_php_group = @filegroup($phpbb_root_path . 'common.' . $phpEx);
  638. // And the owner and the groups PHP is running under.
  639. $php_uid = (function_exists('posix_getuid')) ? @posix_getuid() : false;
  640. $php_gids = (function_exists('posix_getgroups')) ? @posix_getgroups() : false;
  641. // If we are unable to get owner/group, then do not try to set them by guessing
  642. if (!$php_uid || empty($php_gids) || !$common_php_owner || !$common_php_group)
  643. {
  644. $_chmod_info['process'] = false;
  645. }
  646. else
  647. {
  648. $_chmod_info = array(
  649. 'process' => true,
  650. 'common_owner' => $common_php_owner,
  651. 'common_group' => $common_php_group,
  652. 'php_uid' => $php_uid,
  653. 'php_gids' => $php_gids,
  654. );
  655. }
  656. }
  657. }
  658. if ($_chmod_info['process'])
  659. {
  660. $file_uid = @fileowner($filename);
  661. $file_gid = @filegroup($filename);
  662. // Change owner
  663. if (@chown($filename, $_chmod_info['common_owner']))
  664. {
  665. clearstatcache();
  666. $file_uid = @fileowner($filename);
  667. }
  668. // Change group
  669. if (@chgrp($filename, $_chmod_info['common_group']))
  670. {
  671. clearstatcache();
  672. $file_gid = @filegroup($filename);
  673. }
  674. // If the file_uid/gid now match the one from common.php we can process further, else we are not able to change something
  675. if ($file_uid != $_chmod_info['common_owner'] || $file_gid != $_chmod_info['common_group'])
  676. {
  677. $_chmod_info['process'] = false;
  678. }
  679. }
  680. // Still able to process?
  681. if ($_chmod_info['process'])
  682. {
  683. if ($file_uid == $_chmod_info['php_uid'])
  684. {
  685. $php = 'owner';
  686. }
  687. else if (in_array($file_gid, $_chmod_info['php_gids']))
  688. {
  689. $php = 'group';
  690. }
  691. else
  692. {
  693. // Since we are setting the everyone bit anyway, no need to do expensive operations
  694. $_chmod_info['process'] = false;
  695. }
  696. }
  697. // We are not able to determine or change something
  698. if (!$_chmod_info['process'])
  699. {
  700. $php = 'other';
  701. }
  702. // Owner always has read/write permission
  703. $owner = CHMOD_READ | CHMOD_WRITE;
  704. if (is_dir($filename))
  705. {
  706. $owner |= CHMOD_EXECUTE;
  707. // Only add execute bit to the permission if the dir needs to be readable
  708. if ($perms & CHMOD_READ)
  709. {
  710. $perms |= CHMOD_EXECUTE;
  711. }
  712. }
  713. switch ($php)
  714. {
  715. case 'owner':
  716. $result = @chmod($filename, ($owner << 6) + (0 << 3) + (0 << 0));
  717. clearstatcache();
  718. if (is_readable($filename) && phpbb_is_writable($filename))
  719. {
  720. break;
  721. }
  722. case 'group':
  723. $result = @chmod($filename, ($owner << 6) + ($perms << 3) + (0 << 0));
  724. clearstatcache();
  725. if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))
  726. {
  727. break;
  728. }
  729. case 'other':
  730. $result = @chmod($filename, ($owner << 6) + ($perms << 3) + ($perms << 0));
  731. clearstatcache();
  732. if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))
  733. {
  734. break;
  735. }
  736. default:
  737. return false;
  738. break;
  739. }
  740. return $result;
  741. }
  742. /**
  743. * Test if a file/directory is writable
  744. *
  745. * This function calls the native is_writable() when not running under
  746. * Windows and it is not disabled.
  747. *
  748. * @param string $file Path to perform write test on
  749. * @return bool True when the path is writable, otherwise false.
  750. */
  751. function phpbb_is_writable($file)
  752. {
  753. if (strtolower(substr(PHP_OS, 0, 3)) === 'win' || !function_exists('is_writable'))
  754. {
  755. if (file_exists($file))
  756. {
  757. // Canonicalise path to absolute path
  758. $file = phpbb_realpath($file);
  759. if (is_dir($file))
  760. {
  761. // Test directory by creating a file inside the directory
  762. $result = @tempnam($file, 'i_w');
  763. if (is_string($result) && file_exists($result))
  764. {
  765. unlink($result);
  766. // Ensure the file is actually in the directory (returned realpathed)
  767. return (strpos($result, $file) === 0) ? true : false;
  768. }
  769. }
  770. else
  771. {
  772. $handle = @fopen($file, 'r+');
  773. if (is_resource($handle))
  774. {
  775. fclose($handle);
  776. return true;
  777. }
  778. }
  779. }
  780. else
  781. {
  782. // file does not exist test if we can write to the directory
  783. $dir = dirname($file);
  784. if (file_exists($dir) && is_dir($dir) && phpbb_is_writable($dir))
  785. {
  786. return true;
  787. }
  788. }
  789. return false;
  790. }
  791. else
  792. {
  793. return is_writable($file);
  794. }
  795. }
  796. // Compatibility functions
  797. if (!function_exists('array_combine'))
  798. {
  799. /**
  800. * A wrapper for the PHP5 function array_combine()
  801. * @param array $keys contains keys for the resulting array
  802. * @param array $values contains values for the resulting array
  803. *
  804. * @return Returns an array by using the values from the keys array as keys and the
  805. * values from the values array as the corresponding values. Returns false if the
  806. * number of elements for each array isn't equal or if the arrays are empty.
  807. */
  808. function array_combine($keys, $values)
  809. {
  810. $keys = array_values($keys);
  811. $values = array_values($values);
  812. $n = sizeof($keys);
  813. $m = sizeof($values);
  814. if (!$n || !$m || ($n != $m))
  815. {
  816. return false;
  817. }
  818. $combined = array();
  819. for ($i = 0; $i < $n; $i++)
  820. {
  821. $combined[$keys[$i]] = $values[$i];
  822. }
  823. return $combined;
  824. }
  825. }
  826. if (!function_exists('str_split'))
  827. {
  828. /**
  829. * A wrapper for the PHP5 function str_split()
  830. * @param array $string contains the string to be converted
  831. * @param array $split_length contains the length of each chunk
  832. *
  833. * @return Converts a string to an array. If the optional split_length parameter is specified,
  834. * the returned array will be broken down into chunks with each being split_length in length,
  835. * otherwise each chunk will be one character in length. FALSE is returned if split_length is
  836. * less than 1. If the split_length length exceeds the length of string, the entire string is
  837. * returned as the first (and only) array element.
  838. */
  839. function str_split($string, $split_length = 1)
  840. {
  841. if ($split_length < 1)
  842. {
  843. return false;
  844. }
  845. else if ($split_length >= strlen($string))
  846. {
  847. return array($string);
  848. }
  849. else
  850. {
  851. preg_match_all('#.{1,' . $split_length . '}#s', $string, $matches);
  852. return $matches[0];
  853. }
  854. }
  855. }
  856. if (!function_exists('stripos'))
  857. {
  858. /**
  859. * A wrapper for the PHP5 function stripos
  860. * Find position of first occurrence of a case-insensitive string
  861. *
  862. * @param string $haystack is the string to search in
  863. * @param string $needle is the string to search for
  864. *
  865. * @return mixed Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.
  866. * Note that the needle may be a string of one or more characters.
  867. * If needle is not found, stripos() will return boolean FALSE.
  868. */
  869. function stripos($haystack, $needle)
  870. {
  871. if (preg_match('#' . preg_quote($needle, '#') . '#i', $haystack, $m))
  872. {
  873. return strpos($haystack, $m[0]);
  874. }
  875. return false;
  876. }
  877. }
  878. /**
  879. * Checks if a path ($path) is absolute or relative
  880. *
  881. * @param string $path Path to check absoluteness of
  882. * @return boolean
  883. */
  884. function is_absolute($path)
  885. {
  886. return (isset($path[0]) && $path[0] == '/' || preg_match('#^[a-z]:[/\\\]#i', $path)) ? true : false;
  887. }
  888. /**
  889. * @author Chris Smith <chris@project-minerva.org>
  890. * @copyright 2006 Project Minerva Team
  891. * @param string $path The path which we should attempt to resolve.
  892. * @return mixed
  893. */
  894. function phpbb_own_realpath($path)
  895. {
  896. // Now to perform funky shizzle
  897. // Switch to use UNIX slashes
  898. $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
  899. $path_prefix = '';
  900. // Determine what sort of path we have
  901. if (is_absolute($path))
  902. {
  903. $absolute = true;
  904. if ($path[0] == '/')
  905. {
  906. // Absolute path, *NIX style
  907. $path_prefix = '';
  908. }
  909. else
  910. {
  911. // Absolute path, Windows style
  912. // Remove the drive letter and colon
  913. $path_prefix = $path[0] . ':';
  914. $path = substr($path, 2);
  915. }
  916. }
  917. else
  918. {
  919. // Relative Path
  920. // Prepend the current working directory
  921. if (function_exists('getcwd'))
  922. {
  923. // This is the best method, hopefully it is enabled!
  924. $path = str_replace(DIRECTORY_SEPARATOR, '/', getcwd()) . '/' . $path;
  925. $absolute = true;
  926. if (preg_match('#^[a-z]:#i', $path))
  927. {
  928. $path_prefix = $path[0] . ':';
  929. $path = substr($path, 2);
  930. }
  931. else
  932. {
  933. $path_prefix = '';
  934. }
  935. }
  936. else if (isset($_SERVER['SCRIPT_FILENAME']) && !empty($_SERVER['SCRIPT_FILENAME']))
  937. {
  938. // Warning: If chdir() has been used this will lie!
  939. // Warning: This has some problems sometime (CLI can create them easily)
  940. $path = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['SCRIPT_FILENAME'])) . '/' . $path;
  941. $absolute = true;
  942. $path_prefix = '';
  943. }
  944. else
  945. {
  946. // We have no way of getting the absolute path, just run on using relative ones.
  947. $absolute = false;
  948. $path_prefix = '.';
  949. }
  950. }
  951. // Remove any repeated slashes
  952. $path = preg_replace('#/{2,}#', '/', $path);
  953. // Remove the slashes from the start and end of the path
  954. $path = trim($path, '/');
  955. // Break the string into little bits for us to nibble on
  956. $bits = explode('/', $path);
  957. // Remove any . in the path, renumber array for the loop below
  958. $bits = array_values(array_diff($bits, array('.')));
  959. // Lets get looping, run over and resolve any .. (up directory)
  960. for ($i = 0, $max = sizeof($bits); $i < $max; $i++)
  961. {
  962. // @todo Optimise
  963. if ($bits[$i] == '..' )
  964. {
  965. if (isset($bits[$i - 1]))
  966. {
  967. if ($bits[$i - 1] != '..')
  968. {
  969. // We found a .. and we are able to traverse upwards, lets do it!
  970. unset($bits[$i]);
  971. unset($bits[$i - 1]);
  972. $i -= 2;
  973. $max -= 2;
  974. $bits = array_values($bits);
  975. }
  976. }
  977. else if ($absolute) // ie. !isset($bits[$i - 1]) && $absolute
  978. {
  979. // We have an absolute path trying to descend above the root of the filesystem
  980. // ... Error!
  981. return false;
  982. }
  983. }
  984. }
  985. // Prepend the path prefix
  986. array_unshift($bits, $path_prefix);
  987. $resolved = '';
  988. $max = sizeof($bits) - 1;
  989. // Check if we are able to resolve symlinks, Windows cannot.
  990. $symlink_resolve = (function_exists('readlink')) ? true : false;
  991. foreach ($bits as $i => $bit)
  992. {
  993. if (@is_dir("$resolved/$bit") || ($i == $max && @is_file("$resolved/$bit")))
  994. {
  995. // Path Exists
  996. if ($symlink_resolve && is_link("$resolved/$bit") && ($link = readlink("$resolved/$bit")))
  997. {
  998. // Resolved a symlink.
  999. $resolved = $link . (($i == $max) ? '' : '/');
  1000. continue;
  1001. }
  1002. }
  1003. else
  1004. {
  1005. // Something doesn't exist here!
  1006. // This is correct realpath() behaviour but sadly open_basedir and safe_mode make this problematic
  1007. // return false;
  1008. }
  1009. $resolved .= $bit . (($i == $max) ? '' : '/');
  1010. }
  1011. // @todo If the file exists fine and open_basedir only has one path we should be able to prepend it
  1012. // because we must be inside that basedir, the question is where...
  1013. // @internal The slash in is_dir() gets around an open_basedir restriction
  1014. if (!@file_exists($resolved) || (!@is_dir($resolved . '/') && !is_file($resolved)))
  1015. {
  1016. return false;
  1017. }
  1018. // Put the slashes back to the native operating systems slashes
  1019. $resolved = str_replace('/', DIRECTORY_SEPARATOR, $resolved);
  1020. // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
  1021. if (substr($resolved, -1) == DIRECTORY_SEPARATOR)
  1022. {
  1023. return substr($resolved, 0, -1);
  1024. }
  1025. return $resolved; // We got here, in the end!
  1026. }
  1027. if (!function_exists('realpath'))
  1028. {
  1029. /**
  1030. * A wrapper for realpath
  1031. * @ignore
  1032. */
  1033. function phpbb_realpath($path)
  1034. {
  1035. return phpbb_own_realpath($path);
  1036. }
  1037. }
  1038. else
  1039. {
  1040. /**
  1041. * A wrapper for realpath
  1042. */
  1043. function phpbb_realpath($path)
  1044. {
  1045. $realpath = realpath($path);
  1046. // Strangely there are provider not disabling realpath but returning strange values. :o
  1047. // We at least try to cope with them.
  1048. if ($realpath === $path || $realpath === false)
  1049. {
  1050. return phpbb_own_realpath($path);
  1051. }
  1052. // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
  1053. if (substr($realpath, -1) == DIRECTORY_SEPARATOR)
  1054. {
  1055. $realpath = substr($realpath, 0, -1);
  1056. }
  1057. return $realpath;
  1058. }
  1059. }
  1060. /**
  1061. * Eliminates useless . and .. components from specified path.
  1062. *
  1063. * @param string $path Path to clean
  1064. * @return string Cleaned path
  1065. */
  1066. function phpbb_clean_path($path)
  1067. {
  1068. $exploded = explode('/', $path);
  1069. $filtered = array();
  1070. foreach ($exploded as $part)
  1071. {
  1072. if ($part === '.' && !empty($filtered))
  1073. {
  1074. continue;
  1075. }
  1076. if ($part === '..' && !empty($filtered) && $filtered[sizeof($filtered) - 1] !== '..')
  1077. {
  1078. array_pop($filtered);
  1079. }
  1080. else
  1081. {
  1082. $filtered[] = $part;
  1083. }
  1084. }
  1085. $path = implode('/', $filtered);
  1086. return $path;
  1087. }
  1088. if (!function_exists('htmlspecialchars_decode'))
  1089. {
  1090. /**
  1091. * A wrapper for htmlspecialchars_decode
  1092. * @ignore
  1093. */
  1094. function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
  1095. {
  1096. return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
  1097. }
  1098. }
  1099. // functions used for building option fields
  1100. /**
  1101. * Pick a language, any language ...
  1102. */
  1103. function language_select($default = '')
  1104. {
  1105. global $db;
  1106. $sql = 'SELECT lang_iso, lang_local_name
  1107. FROM ' . LANG_TABLE . '
  1108. ORDER BY lang_english_name';
  1109. $result = $db->sql_query($sql);
  1110. $lang_options = '';
  1111. while ($row = $db->sql_fetchrow($result))
  1112. {
  1113. $selected = ($row['lang_iso'] == $default) ? ' selected="selected"' : '';
  1114. $lang_options .= '<option value="' . $row['lang_iso'] . '"' . $selected . '>' . $row['lang_local_name'] . '</option>';
  1115. }
  1116. $db->sql_freeresult($result);
  1117. return $lang_options;
  1118. }
  1119. /**
  1120. * Pick a template/theme combo,
  1121. */
  1122. function style_select($default = '', $all = false)
  1123. {
  1124. global $db;
  1125. $sql_where = (!$all) ? 'WHERE style_active = 1 ' : '';
  1126. $sql = 'SELECT style_id, style_name
  1127. FROM ' . STYLES_TABLE . "
  1128. $sql_where
  1129. ORDER BY style_name";
  1130. $result = $db->sql_query($sql);
  1131. $style_options = '';
  1132. while ($row = $db->sql_fetchrow($result))
  1133. {
  1134. $selected = ($row['style_id'] == $default) ? ' selected="selected"' : '';
  1135. $style_options .= '<option value="' . $row['style_id'] . '"' . $selected . '>' . $row['style_name'] . '</option>';
  1136. }
  1137. $db->sql_freeresult($result);
  1138. return $style_options;
  1139. }
  1140. /**
  1141. * Pick a timezone
  1142. */
  1143. function tz_select($default = '', $truncate = false)
  1144. {
  1145. global $user;
  1146. $tz_select = '';
  1147. foreach ($user->lang['tz_zones'] as $offset => $zone)
  1148. {
  1149. if ($truncate)
  1150. {
  1151. $zone_trunc = truncate_string($zone, 50, 255, false, '...');
  1152. }
  1153. else
  1154. {
  1155. $zone_trunc = $zone;
  1156. }
  1157. if (is_numeric($offset))
  1158. {
  1159. $selected = ($offset == $default) ? ' selected="selected"' : '';
  1160. $tz_select .= '<option title="' . $zone . '" value="' . $offset . '"' . $selected . '>' . $zone_trunc . '</option>';
  1161. }
  1162. }
  1163. return $tz_select;
  1164. }
  1165. // Functions handling topic/post tracking/marking
  1166. /**
  1167. * Marks a topic/forum as read
  1168. * Marks a topic as posted to
  1169. *
  1170. * @param int $user_id can only be used with $mode == 'post'
  1171. */
  1172. function markread($mode, $forum_id = false, $topic_id = false, $post_time = 0, $user_id = 0)
  1173. {
  1174. global $db, $user, $config;
  1175. if ($mode == 'all')
  1176. {
  1177. if ($forum_id === false || !sizeof($forum_id))
  1178. {
  1179. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1180. {
  1181. // Mark all forums read (index page)
  1182. $db->sql_query('DELETE FROM ' . TOPICS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
  1183. $db->sql_query('DELETE FROM ' . FORUMS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
  1184. $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
  1185. }
  1186. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1187. {
  1188. $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1189. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1190. unset($tracking_topics['tf']);
  1191. unset($tracking_topics['t']);
  1192. unset($tracking_topics['f']);
  1193. $tracking_topics['l'] = base_convert(time() - $config['board_startdate'], 10, 36);
  1194. $user->set_cookie('track', tracking_serialize($tracking_topics), time() + 31536000);
  1195. $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking_topics)) : tracking_serialize($tracking_topics);
  1196. unset($tracking_topics);
  1197. if ($user->data['is_registered'])
  1198. {
  1199. $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
  1200. }
  1201. }
  1202. }
  1203. return;
  1204. }
  1205. else if ($mode == 'topics')
  1206. {
  1207. // Mark all topics in forums read
  1208. if (!is_array($forum_id))
  1209. {
  1210. $forum_id = array($forum_id);
  1211. }
  1212. // Add 0 to forums array to mark global announcements correctly
  1213. // $forum_id[] = 0;
  1214. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1215. {
  1216. $sql = 'DELETE FROM ' . TOPICS_TRACK_TABLE . "
  1217. WHERE user_id = {$user->data['user_id']}
  1218. AND " . $db->sql_in_set('forum_id', $forum_id);
  1219. $db->sql_query($sql);
  1220. $sql = 'SELECT forum_id
  1221. FROM ' . FORUMS_TRACK_TABLE . "
  1222. WHERE user_id = {$user->data['user_id']}
  1223. AND " . $db->sql_in_set('forum_id', $forum_id);
  1224. $result = $db->sql_query($sql);
  1225. $sql_update = array();
  1226. while ($row = $db->sql_fetchrow($result))
  1227. {
  1228. $sql_update[] = (int) $row['forum_id'];
  1229. }
  1230. $db->sql_freeresult($result);
  1231. if (sizeof($sql_update))
  1232. {
  1233. $sql = 'UPDATE ' . FORUMS_TRACK_TABLE . '
  1234. SET mark_time = ' . time() . "
  1235. WHERE user_id = {$user->data['user_id']}
  1236. AND " . $db->sql_in_set('forum_id', $sql_update);
  1237. $db->sql_query($sql);
  1238. }
  1239. if ($sql_insert = array_diff($forum_id, $sql_update))
  1240. {
  1241. $sql_ary = array();
  1242. foreach ($sql_insert as $f_id)
  1243. {
  1244. $sql_ary[] = array(
  1245. 'user_id' => (int) $user->data['user_id'],
  1246. 'forum_id' => (int) $f_id,
  1247. 'mark_time' => time()
  1248. );
  1249. }
  1250. $db->sql_multi_insert(FORUMS_TRACK_TABLE, $sql_ary);
  1251. }
  1252. }
  1253. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1254. {
  1255. $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1256. $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
  1257. foreach ($forum_id as $f_id)
  1258. {
  1259. $topic_ids36 = (isset($tracking['tf'][$f_id])) ? $tracking['tf'][$f_id] : array();
  1260. if (isset($tracking['tf'][$f_id]))
  1261. {
  1262. unset($tracking['tf'][$f_id]);
  1263. }
  1264. foreach ($topic_ids36 as $topic_id36)
  1265. {
  1266. unset($tracking['t'][$topic_id36]);
  1267. }
  1268. if (isset($tracking['f'][$f_id]))
  1269. {
  1270. unset($tracking['f'][$f_id]);
  1271. }
  1272. $tracking['f'][$f_id] = base_convert(time() - $config['board_startdate'], 10, 36);
  1273. }
  1274. if (isset($tracking['tf']) && empty($tracking['tf']))
  1275. {
  1276. unset($tracking['tf']);
  1277. }
  1278. $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
  1279. $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
  1280. unset($tracking);
  1281. }
  1282. return;
  1283. }
  1284. else if ($mode == 'topic')
  1285. {
  1286. if ($topic_id === false || $forum_id === false)
  1287. {
  1288. return;
  1289. }
  1290. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1291. {
  1292. $sql = 'UPDATE ' . TOPICS_TRACK_TABLE . '
  1293. SET mark_time = ' . (($post_time) ? $post_time : time()) . "
  1294. WHERE user_id = {$user->data['user_id']}
  1295. AND topic_id = $topic_id";
  1296. $db->sql_query($sql);
  1297. // insert row
  1298. if (!$db->sql_affectedrows())
  1299. {
  1300. $db->sql_return_on_error(true);
  1301. $sql_ary = array(
  1302. 'user_id' => (int) $user->data['user_id'],
  1303. 'topic_id' => (int) $topic_id,
  1304. 'forum_id' => (int) $forum_id,
  1305. 'mark_time' => ($post_time) ? (int) $post_time : time(),
  1306. );
  1307. $db->sql_query('INSERT INTO ' . TOPICS_TRACK_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  1308. $db->sql_return_on_error(false);
  1309. }
  1310. }
  1311. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1312. {
  1313. $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1314. $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
  1315. $topic_id36 = base_convert($topic_id, 10, 36);
  1316. if (!isset($tracking['t'][$topic_id36]))
  1317. {
  1318. $tracking['tf'][$forum_id][$topic_id36] = true;
  1319. }
  1320. $post_time = ($post_time) ? $post_time : time();
  1321. $tracking['t'][$topic_id36] = base_convert($post_time - $config['board_startdate'], 10, 36);
  1322. // If the cookie grows larger than 10000 characters we will remove the smallest value
  1323. // This can result in old topics being unread - but most of the time it should be accurate...
  1324. if (isset($_COOKIE[$config['cookie_name'] . '_track']) && strlen($_COOKIE[$config['cookie_name'] . '_track']) > 10000)
  1325. {
  1326. //echo 'Cookie grown too large' . print_r($tracking, true);
  1327. // We get the ten most minimum stored time offsets and its associated topic ids
  1328. $time_keys = array();
  1329. for ($i = 0; $i < 10 && sizeof($tracking['t']); $i++)
  1330. {
  1331. $min_value = min($tracking['t']);
  1332. $m_tkey = array_search($min_value, $tracking['t']);
  1333. unset($tracking['t'][$m_tkey]);
  1334. $time_keys[$m_tkey] = $min_value;
  1335. }
  1336. // Now remove the topic ids from the array...
  1337. foreach ($tracking['tf'] as $f_id => $topic_id_ary)
  1338. {
  1339. foreach ($time_keys as $m_tkey => $min_value)
  1340. {
  1341. if (isset($topic_id_ary[$m_tkey]))
  1342. {
  1343. $tracking['f'][$f_id] = $min_value;
  1344. unset($tracking['tf'][$f_id][$m_tkey]);
  1345. }
  1346. }
  1347. }
  1348. if ($user->data['is_registered'])
  1349. {
  1350. $user->data['user_lastmark'] = intval(base_convert(max($time_keys) + $config['board_startdate'], 36, 10));
  1351. $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . $user->data['user_lastmark'] . " WHERE user_id = {$user->data['user_id']}");
  1352. }
  1353. else
  1354. {
  1355. $tracking['l'] = max($time_keys);
  1356. }
  1357. }
  1358. $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
  1359. $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
  1360. }
  1361. return;
  1362. }
  1363. else if ($mode == 'post')
  1364. {
  1365. if ($topic_id === false)
  1366. {
  1367. return;
  1368. }
  1369. $use_user_id = (!$user_id) ? $user->data['user_id'] : $user_id;
  1370. if ($config['load_db_track'] && $use_user_id != ANONYMOUS)
  1371. {
  1372. $db->sql_return_on_error(true);
  1373. $sql_ary = array(
  1374. 'user_id' => (int) $use_user_id,
  1375. 'topic_id' => (int) $topic_id,
  1376. 'topic_posted' => 1
  1377. );
  1378. $db->sql_query('INSERT INTO ' . TOPICS_POSTED_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  1379. $db->sql_return_on_error(false);
  1380. }
  1381. return;
  1382. }
  1383. }
  1384. /**
  1385. * Get topic tracking info by using already fetched info
  1386. */
  1387. function get_topic_tracking($forum_id, $topic_ids, &$rowset, $forum_mark_time, $global_announce_list = false)
  1388. {
  1389. global $config, $user;
  1390. $last_read = array();
  1391. if (!is_array($topic_ids))
  1392. {
  1393. $topic_ids = array($topic_ids);
  1394. }
  1395. foreach ($topic_ids as $topic_id)
  1396. {
  1397. if (!empty($rowset[$topic_id]['mark_time']))
  1398. {
  1399. $last_read[$topic_id] = $rowset[$topic_id]['mark_time'];
  1400. }
  1401. }
  1402. $topic_ids = array_diff($topic_ids, array_keys($last_read));
  1403. if (sizeof($topic_ids))
  1404. {
  1405. $mark_time = array();
  1406. // Get global announcement info
  1407. if ($global_announce_list && sizeof($global_announce_list))
  1408. {
  1409. if (!isset($forum_mark_time[0]))
  1410. {
  1411. global $db;
  1412. $sql = 'SELECT mark_time
  1413. FROM ' . FORUMS_TRACK_TABLE . "
  1414. WHERE user_id = {$user->data['user_id']}
  1415. AND forum_id = 0";
  1416. $result = $db->sql_query($sql);
  1417. $row = $db->sql_fetchrow($result);
  1418. $db->sql_freeresult($result);
  1419. if ($row)
  1420. {
  1421. $mark_time[0] = $row['mark_time'];
  1422. }
  1423. }
  1424. else
  1425. {
  1426. if ($forum_mark_time[0] !== false)
  1427. {
  1428. $mark_time[0] = $forum_mark_time[0];
  1429. }
  1430. }
  1431. }
  1432. if (!empty($forum_mark_time[$forum_id]) && $forum_mark_time[$forum_id] !== false)
  1433. {
  1434. $mark_time[$forum_id] = $forum_mark_time[$forum_id];
  1435. }
  1436. $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
  1437. foreach ($topic_ids as $topic_id)
  1438. {
  1439. if ($global_announce_list && isset($global_announce_list[$topic_id]))
  1440. {
  1441. $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
  1442. }
  1443. else
  1444. {
  1445. $last_read[$topic_id] = $user_lastmark;
  1446. }
  1447. }
  1448. }
  1449. return $last_read;
  1450. }
  1451. /**
  1452. * Get topic tracking info from db (for cookie based tracking only this function is used)
  1453. */
  1454. function get_complete_topic_tracking($forum_id, $topic_ids, $global_announce_list = false)
  1455. {
  1456. global $config, $user;
  1457. $last_read = array();
  1458. if (!is_array($topic_ids))
  1459. {
  1460. $topic_ids = array($topic_ids);
  1461. }
  1462. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1463. {
  1464. global $db;
  1465. $sql = 'SELECT topic_id, mark_time
  1466. FROM ' . TOPICS_TRACK_TABLE . "
  1467. WHERE user_id = {$user->data['user_id']}
  1468. AND " . $db->sql_in_set('topic_id', $topic_ids);
  1469. $result = $db->sql_query($sql);
  1470. while ($row = $db->sql_fetchrow($result))
  1471. {
  1472. $last_read[$row['topic_id']] = $row['mark_time'];
  1473. }
  1474. $db->sql_freeresult($result);
  1475. $topic_ids = array_diff($topic_ids, array_keys($last_read));
  1476. if (sizeof($topic_ids))
  1477. {
  1478. $sql = 'SELECT forum_id, mark_time
  1479. FROM ' . FORUMS_TRACK_TABLE . "
  1480. WHERE user_id = {$user->data['user_id']}
  1481. AND forum_id " .
  1482. (($global_announce_list && sizeof($global_announce_list)) ? "IN (0, $forum_id)" : "= $forum_id");
  1483. $result = $db->sql_query($sql);
  1484. $mark_time = array();
  1485. while ($row = $db->sql_fetchrow($result))
  1486. {
  1487. $mark_time[$row['forum_id']] = $row['mark_time'];
  1488. }
  1489. $db->sql_freeresult($result);
  1490. $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
  1491. foreach ($topic_ids as $topic_id)
  1492. {
  1493. if ($global_announce_list && isset($global_announce_list[$topic_id]))
  1494. {
  1495. $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
  1496. }
  1497. else
  1498. {
  1499. $last_read[$topic_id] = $user_lastmark;
  1500. }
  1501. }
  1502. }
  1503. }
  1504. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1505. {
  1506. global $tracking_topics;
  1507. if (!isset($tracking_topics) || !sizeof($tracking_topics))
  1508. {
  1509. $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1510. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1511. }
  1512. if (!$user->data['is_registered'])
  1513. {
  1514. $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
  1515. }
  1516. else
  1517. {
  1518. $user_lastmark = $user->data['user_lastmark'];
  1519. }
  1520. foreach ($topic_ids as $topic_id)
  1521. {
  1522. $topic_id36 = base_convert($topic_id, 10, 36);
  1523. if (isset($tracking_topics['t'][$topic_id36]))
  1524. {
  1525. $last_read[$topic_id] = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
  1526. }
  1527. }
  1528. $topic_ids = array_diff($topic_ids, array_keys($last_read));
  1529. if (sizeof($topic_ids))
  1530. {
  1531. $mark_time = array();
  1532. if ($global_announce_list && sizeof($global_announce_list))
  1533. {
  1534. if (isset($tracking_topics['f'][0]))
  1535. {
  1536. $mark_time[0] = base_convert($tracking_topics['f'][0], 36, 10) + $config['board_startdate'];
  1537. }
  1538. }
  1539. if (isset($tracking_topics['f'][$forum_id]))
  1540. {
  1541. $mark_time[$forum_id] = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
  1542. }
  1543. $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user_lastmark;
  1544. foreach ($topic_ids as $topic_id)
  1545. {
  1546. if ($global_announce_list && isset($global_announce_list[$topic_id]))
  1547. {
  1548. $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
  1549. }
  1550. else
  1551. {
  1552. $last_read[$topic_id] = $user_lastmark;
  1553. }
  1554. }
  1555. }
  1556. }
  1557. return $last_read;
  1558. }
  1559. /**
  1560. * Get list of unread topics
  1561. *
  1562. * @param int $user_id User ID (or false for current user)
  1563. * @param string $sql_extra Extra WHERE SQL statement
  1564. * @param string $sql_sort ORDER BY SQL sorting statement
  1565. * @param string $sql_limit Limits the size of unread topics list, 0 for unlimited query
  1566. * @param string $sql_limit_offset Sets the offset of the first row to search, 0 to search from the start
  1567. *
  1568. * @return array[int][int] Topic ids as keys, mark_time of topic as value
  1569. */
  1570. function get_unread_topics($user_id = false, $sql_extra = '', $sql_sort = '', $sql_limit = 1001, $sql_limit_offset = 0)
  1571. {
  1572. global $config, $db, $user;
  1573. $user_id = ($user_id === false) ? (int) $user->data['user_id'] : (int) $user_id;
  1574. // Data array we're going to return
  1575. $unread_topics = array();
  1576. if (empty($sql_sort))
  1577. {
  1578. $sql_sort = 'ORDER BY t.topic_last_post_time DESC';
  1579. }
  1580. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1581. {
  1582. // Get list of the unread topics
  1583. $last_mark = (int) $user->data['user_lastmark'];
  1584. $sql_array = array(
  1585. 'SELECT' => 't.topic_id, t.topic_last_post_time, tt.mark_time as topic_mark_time, ft.mark_time as forum_mark_time',
  1586. 'FROM' => array(TOPICS_TABLE => 't'),
  1587. 'LEFT_JOIN' => array(
  1588. array(
  1589. 'FROM' => array(TOPICS_TRACK_TABLE => 'tt'),
  1590. 'ON' => "tt.user_id = $user_id AND t.topic_id = tt.topic_id",
  1591. ),
  1592. array(
  1593. 'FROM' => array(FORUMS_TRACK_TABLE => 'ft'),
  1594. 'ON' => "ft.user_id = $user_id AND t.forum_id = ft.forum_id",
  1595. ),
  1596. ),
  1597. 'WHERE' => "
  1598. t.topic_last_post_time > $last_mark AND
  1599. (
  1600. (tt.mark_time IS NOT NULL AND t.topic_last_post_time > tt.mark_time) OR
  1601. (tt.mark_time IS NULL AND ft.mark_time IS NOT NULL AND t.topic_last_post_time > ft.mark_time) OR
  1602. (tt.mark_time IS NULL AND ft.mark_time IS NULL)
  1603. )
  1604. $sql_extra
  1605. $sql_sort",
  1606. );
  1607. $sql = $db->sql_build_query('SELECT', $sql_array);
  1608. $result = $db->sql_query_limit($sql, $sql_limit, $sql_limit_offset);
  1609. while ($row = $db->sql_fetchrow($result))
  1610. {
  1611. $topic_id = (int) $row['topic_id'];
  1612. $unread_topics[$topic_id] = ($row['topic_mark_time']) ? (int) $row['topic_mark_time'] : (($row['forum_mark_time']) ? (int) $row['forum_mark_time'] : $last_mark);
  1613. }
  1614. $db->sql_freeresult($result);
  1615. }
  1616. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1617. {
  1618. global $tracking_topics;
  1619. if (empty($tracking_topics))
  1620. {
  1621. $tracking_topics = request_var($config['cookie_name'] . '_track', '', false, true);
  1622. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1623. }
  1624. if (!$user->data['is_registered'])
  1625. {
  1626. $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
  1627. }
  1628. else
  1629. {
  1630. $user_lastmark = (int) $user->data['user_lastmark'];
  1631. }
  1632. $sql = 'SELECT t.topic_id, t.forum_id, t.topic_last_post_time
  1633. FROM ' . TOPICS_TABLE . ' t
  1634. WHERE t.topic_last_post_time > ' . $user_lastmark . "
  1635. $sql_extra
  1636. $sql_sort";
  1637. $result = $db->sql_query_limit($sql, $sql_limit, $sql_limit_offset);
  1638. while ($row = $db->sql_fetchrow($result))
  1639. {
  1640. $forum_id = (int) $row['forum_id'];
  1641. $topic_id = (int) $row['topic_id'];
  1642. $topic_id36 = base_convert($topic_id, 10, 36);
  1643. if (isset($tracking_topics['t'][$topic_id36]))
  1644. {
  1645. $last_read = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
  1646. if ($row['topic_last_post_time'] > $last_read)
  1647. {
  1648. $unread_topics[$topic_id] = $last_read;
  1649. }
  1650. }
  1651. else if (isset($tracking_topics['f'][$forum_id]))
  1652. {
  1653. $mark_time = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
  1654. if ($row['topic_last_post_time'] > $mark_time)
  1655. {
  1656. $unread_topics[$topic_id] = $mark_time;
  1657. }
  1658. }
  1659. else
  1660. {
  1661. $unread_topics[$topic_id] = $user_lastmark;
  1662. }
  1663. }
  1664. $db->sql_freeresult($result);
  1665. }
  1666. return $unread_topics;
  1667. }
  1668. /**
  1669. * Check for read forums and update topic tracking info accordingly
  1670. *
  1671. * @param int $forum_id the forum id to check
  1672. * @param int $forum_last_post_time the forums last post time
  1673. * @param int $f_mark_time the forums last mark time if user is registered and load_db_lastread enabled
  1674. * @param int $mark_time_forum false if the mark time needs to be obtained, else the last users forum mark time
  1675. *
  1676. * @return true if complete forum got marked read, else false.
  1677. */
  1678. function upd

Large files files are truncated, but you can click here to view the full file