PageRenderTime 82ms CodeModel.GetById 20ms RepoModel.GetById 0ms 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
  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 update_forum_tracking_info($forum_id, $forum_last_post_time, $f_mark_time = false, $mark_time_forum = false)
  1679. {
  1680. global $db, $tracking_topics, $user, $config, $auth;
  1681. // Determine the users last forum mark time if not given.
  1682. if ($mark_time_forum === false)
  1683. {
  1684. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1685. {
  1686. $mark_time_forum = (!empty($f_mark_time)) ? $f_mark_time : $user->data['user_lastmark'];
  1687. }
  1688. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1689. {
  1690. $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1691. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1692. if (!$user->data['is_registered'])
  1693. {
  1694. $user->data['user_lastmark'] = (isset($tracking_topics['l'])) ? (int) (base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate']) : 0;
  1695. }
  1696. $mark_time_forum = (isset($tracking_topics['f'][$forum_id])) ? (int) (base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate']) : $user->data['user_lastmark'];
  1697. }
  1698. }
  1699. // Handle update of unapproved topics info.
  1700. // Only update for moderators having m_approve permission for the forum.
  1701. $sql_update_unapproved = ($auth->acl_get('m_approve', $forum_id)) ? '': 'AND t.topic_approved = 1';
  1702. // Check the forum for any left unread topics.
  1703. // If there are none, we mark the forum as read.
  1704. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1705. {
  1706. if ($mark_time_forum >= $forum_last_post_time)
  1707. {
  1708. // We do not need to mark read, this happened before. Therefore setting this to true
  1709. $row = true;
  1710. }
  1711. else
  1712. {
  1713. $sql = 'SELECT t.forum_id
  1714. FROM ' . TOPICS_TABLE . ' t
  1715. LEFT JOIN ' . TOPICS_TRACK_TABLE . ' tt
  1716. ON (tt.topic_id = t.topic_id
  1717. AND tt.user_id = ' . $user->data['user_id'] . ')
  1718. WHERE t.forum_id = ' . $forum_id . '
  1719. AND t.topic_last_post_time > ' . $mark_time_forum . '
  1720. AND t.topic_moved_id = 0 ' .
  1721. $sql_update_unapproved . '
  1722. AND (tt.topic_id IS NULL
  1723. OR tt.mark_time < t.topic_last_post_time)';
  1724. $result = $db->sql_query_limit($sql, 1);
  1725. $row = $db->sql_fetchrow($result);
  1726. $db->sql_freeresult($result);
  1727. }
  1728. }
  1729. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1730. {
  1731. // Get information from cookie
  1732. $row = false;
  1733. if (!isset($tracking_topics['tf'][$forum_id]))
  1734. {
  1735. // We do not need to mark read, this happened before. Therefore setting this to true
  1736. $row = true;
  1737. }
  1738. else
  1739. {
  1740. $sql = 'SELECT t.topic_id
  1741. FROM ' . TOPICS_TABLE . ' t
  1742. WHERE t.forum_id = ' . $forum_id . '
  1743. AND t.topic_last_post_time > ' . $mark_time_forum . '
  1744. AND t.topic_moved_id = 0 ' .
  1745. $sql_update_unapproved;
  1746. $result = $db->sql_query($sql);
  1747. $check_forum = $tracking_topics['tf'][$forum_id];
  1748. $unread = false;
  1749. while ($row = $db->sql_fetchrow($result))
  1750. {
  1751. if (!isset($check_forum[base_convert($row['topic_id'], 10, 36)]))
  1752. {
  1753. $unread = true;
  1754. break;
  1755. }
  1756. }
  1757. $db->sql_freeresult($result);
  1758. $row = $unread;
  1759. }
  1760. }
  1761. else
  1762. {
  1763. $row = true;
  1764. }
  1765. if (!$row)
  1766. {
  1767. markread('topics', $forum_id);
  1768. return true;
  1769. }
  1770. return false;
  1771. }
  1772. /**
  1773. * Transform an array into a serialized format
  1774. */
  1775. function tracking_serialize($input)
  1776. {
  1777. $out = '';
  1778. foreach ($input as $key => $value)
  1779. {
  1780. if (is_array($value))
  1781. {
  1782. $out .= $key . ':(' . tracking_serialize($value) . ');';
  1783. }
  1784. else
  1785. {
  1786. $out .= $key . ':' . $value . ';';
  1787. }
  1788. }
  1789. return $out;
  1790. }
  1791. /**
  1792. * Transform a serialized array into an actual array
  1793. */
  1794. function tracking_unserialize($string, $max_depth = 3)
  1795. {
  1796. $n = strlen($string);
  1797. if ($n > 10010)
  1798. {
  1799. die('Invalid data supplied');
  1800. }
  1801. $data = $stack = array();
  1802. $key = '';
  1803. $mode = 0;
  1804. $level = &$data;
  1805. for ($i = 0; $i < $n; ++$i)
  1806. {
  1807. switch ($mode)
  1808. {
  1809. case 0:
  1810. switch ($string[$i])
  1811. {
  1812. case ':':
  1813. $level[$key] = 0;
  1814. $mode = 1;
  1815. break;
  1816. case ')':
  1817. unset($level);
  1818. $level = array_pop($stack);
  1819. $mode = 3;
  1820. break;
  1821. default:
  1822. $key .= $string[$i];
  1823. }
  1824. break;
  1825. case 1:
  1826. switch ($string[$i])
  1827. {
  1828. case '(':
  1829. if (sizeof($stack) >= $max_depth)
  1830. {
  1831. die('Invalid data supplied');
  1832. }
  1833. $stack[] = &$level;
  1834. $level[$key] = array();
  1835. $level = &$level[$key];
  1836. $key = '';
  1837. $mode = 0;
  1838. break;
  1839. default:
  1840. $level[$key] = $string[$i];
  1841. $mode = 2;
  1842. break;
  1843. }
  1844. break;
  1845. case 2:
  1846. switch ($string[$i])
  1847. {
  1848. case ')':
  1849. unset($level);
  1850. $level = array_pop($stack);
  1851. $mode = 3;
  1852. break;
  1853. case ';':
  1854. $key = '';
  1855. $mode = 0;
  1856. break;
  1857. default:
  1858. $level[$key] .= $string[$i];
  1859. break;
  1860. }
  1861. break;
  1862. case 3:
  1863. switch ($string[$i])
  1864. {
  1865. case ')':
  1866. unset($level);
  1867. $level = array_pop($stack);
  1868. break;
  1869. case ';':
  1870. $key = '';
  1871. $mode = 0;
  1872. break;
  1873. default:
  1874. die('Invalid data supplied');
  1875. break;
  1876. }
  1877. break;
  1878. }
  1879. }
  1880. if (sizeof($stack) != 0 || ($mode != 0 && $mode != 3))
  1881. {
  1882. die('Invalid data supplied');
  1883. }
  1884. return $level;
  1885. }
  1886. // Pagination functions
  1887. /**
  1888. * Pagination routine, generates page number sequence
  1889. * tpl_prefix is for using different pagination blocks at one page
  1890. */
  1891. function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = false, $tpl_prefix = '')
  1892. {
  1893. global $template, $user;
  1894. // Make sure $per_page is a valid value
  1895. $per_page = ($per_page <= 0) ? 1 : $per_page;
  1896. $seperator = '<span class="page-sep">' . $user->lang['COMMA_SEPARATOR'] . '</span>';
  1897. $total_pages = ceil($num_items / $per_page);
  1898. if ($total_pages == 1 || !$num_items)
  1899. {
  1900. return false;
  1901. }
  1902. $on_page = floor($start_item / $per_page) + 1;
  1903. $url_delim = (strpos($base_url, '?') === false) ? '?' : ((strpos($base_url, '?') === strlen($base_url) - 1) ? '' : '&amp;');
  1904. $page_string = ($on_page == 1) ? '<strong>1</strong>' : '<a href="' . $base_url . '">1</a>';
  1905. if ($total_pages > 5)
  1906. {
  1907. $start_cnt = min(max(1, $on_page - 4), $total_pages - 5);
  1908. $end_cnt = max(min($total_pages, $on_page + 4), 6);
  1909. $page_string .= ($start_cnt > 1) ? '<span class="page-dots"> ... </span>' : $seperator;
  1910. for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
  1911. {
  1912. $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
  1913. if ($i < $end_cnt - 1)
  1914. {
  1915. $page_string .= $seperator;
  1916. }
  1917. }
  1918. $page_string .= ($end_cnt < $total_pages) ? '<span class="page-dots"> ... </span>' : $seperator;
  1919. }
  1920. else
  1921. {
  1922. $page_string .= $seperator;
  1923. for ($i = 2; $i < $total_pages; $i++)
  1924. {
  1925. $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
  1926. if ($i < $total_pages)
  1927. {
  1928. $page_string .= $seperator;
  1929. }
  1930. }
  1931. }
  1932. $page_string .= ($on_page == $total_pages) ? '<strong>' . $total_pages . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($total_pages - 1) * $per_page) . '">' . $total_pages . '</a>';
  1933. if ($add_prevnext_text)
  1934. {
  1935. if ($on_page != 1)
  1936. {
  1937. $page_string = '<a href="' . $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page) . '">' . $user->lang['PREVIOUS'] . '</a>&nbsp;&nbsp;' . $page_string;
  1938. }
  1939. if ($on_page != $total_pages)
  1940. {
  1941. $page_string .= '&nbsp;&nbsp;<a href="' . $base_url . "{$url_delim}start=" . ($on_page * $per_page) . '">' . $user->lang['NEXT'] . '</a>';
  1942. }
  1943. }
  1944. $template->assign_vars(array(
  1945. $tpl_prefix . 'BASE_URL' => $base_url,
  1946. 'A_' . $tpl_prefix . 'BASE_URL' => addslashes($base_url),
  1947. $tpl_prefix . 'PER_PAGE' => $per_page,
  1948. $tpl_prefix . 'PREVIOUS_PAGE' => ($on_page == 1) ? '' : $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page),
  1949. $tpl_prefix . 'NEXT_PAGE' => ($on_page == $total_pages) ? '' : $base_url . "{$url_delim}start=" . ($on_page * $per_page),
  1950. $tpl_prefix . 'TOTAL_PAGES' => $total_pages,
  1951. ));
  1952. return $page_string;
  1953. }
  1954. /**
  1955. * Return current page (pagination)
  1956. */
  1957. function on_page($num_items, $per_page, $start)
  1958. {
  1959. global $template, $user;
  1960. // Make sure $per_page is a valid value
  1961. $per_page = ($per_page <= 0) ? 1 : $per_page;
  1962. $on_page = floor($start / $per_page) + 1;
  1963. $template->assign_vars(array(
  1964. 'ON_PAGE' => $on_page)
  1965. );
  1966. return sprintf($user->lang['PAGE_OF'], $on_page, max(ceil($num_items / $per_page), 1));
  1967. }
  1968. // Server functions (building urls, redirecting...)
  1969. /**
  1970. * Append session id to url.
  1971. * This function supports hooks.
  1972. *
  1973. * @param string $url The url the session id needs to be appended to (can have params)
  1974. * @param mixed $params String or array of additional url parameters
  1975. * @param bool $is_amp Is url using &amp; (true) or & (false)
  1976. * @param string $session_id Possibility to use a custom session id instead of the global one
  1977. *
  1978. * Examples:
  1979. * <code>
  1980. * append_sid("{$phpbb_root_path}viewtopic.$phpEx?t=1&amp;f=2");
  1981. * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&amp;f=2');
  1982. * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2', false);
  1983. * append_sid("{$phpbb_root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
  1984. * </code>
  1985. *
  1986. */
  1987. function append_sid($url, $params = false, $is_amp = true, $session_id = false)
  1988. {
  1989. global $_SID, $_EXTRA_URL, $phpbb_hook;
  1990. if ($params === '' || (is_array($params) && empty($params)))
  1991. {
  1992. // Do not append the ? if the param-list is empty anyway.
  1993. $params = false;
  1994. }
  1995. // Developers using the hook function need to globalise the $_SID and $_EXTRA_URL on their own and also handle it appropriately.
  1996. // They could mimic most of what is within this function
  1997. if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__, $url, $params, $is_amp, $session_id))
  1998. {
  1999. if ($phpbb_hook->hook_return(__FUNCTION__))
  2000. {
  2001. return $phpbb_hook->hook_return_result(__FUNCTION__);
  2002. }
  2003. }
  2004. $params_is_array = is_array($params);
  2005. // Get anchor
  2006. $anchor = '';
  2007. if (strpos($url, '#') !== false)
  2008. {
  2009. list($url, $anchor) = explode('#', $url, 2);
  2010. $anchor = '#' . $anchor;
  2011. }
  2012. else if (!$params_is_array && strpos($params, '#') !== false)
  2013. {
  2014. list($params, $anchor) = explode('#', $params, 2);
  2015. $anchor = '#' . $anchor;
  2016. }
  2017. // Handle really simple cases quickly
  2018. if ($_SID == '' && $session_id === false && empty($_EXTRA_URL) && !$params_is_array && !$anchor)
  2019. {
  2020. if ($params === false)
  2021. {
  2022. return $url;
  2023. }
  2024. $url_delim = (strpos($url, '?') === false) ? '?' : (($is_amp) ? '&amp;' : '&');
  2025. return $url . ($params !== false ? $url_delim. $params : '');
  2026. }
  2027. // Assign sid if session id is not specified
  2028. if ($session_id === false)
  2029. {
  2030. $session_id = $_SID;
  2031. }
  2032. $amp_delim = ($is_amp) ? '&amp;' : '&';
  2033. $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
  2034. // Appending custom url parameter?
  2035. $append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';
  2036. // Use the short variant if possible ;)
  2037. if ($params === false)
  2038. {
  2039. // Append session id
  2040. if (!$session_id)
  2041. {
  2042. return $url . (($append_url) ? $url_delim . $append_url : '') . $anchor;
  2043. }
  2044. else
  2045. {
  2046. return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id . $anchor;
  2047. }
  2048. }
  2049. // Build string if parameters are specified as array
  2050. if (is_array($params))
  2051. {
  2052. $output = array();
  2053. foreach ($params as $key => $item)
  2054. {
  2055. if ($item === NULL)
  2056. {
  2057. continue;
  2058. }
  2059. if ($key == '#')
  2060. {
  2061. $anchor = '#' . $item;
  2062. continue;
  2063. }
  2064. $output[] = $key . '=' . $item;
  2065. }
  2066. $params = implode($amp_delim, $output);
  2067. }
  2068. // Append session id and parameters (even if they are empty)
  2069. // If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
  2070. return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
  2071. }
  2072. /**
  2073. * Generate board url (example: http://www.example.com/phpBB)
  2074. *
  2075. * @param bool $without_script_path if set to true the script path gets not appended (example: http://www.example.com)
  2076. *
  2077. * @return string the generated board url
  2078. */
  2079. function generate_board_url($without_script_path = false)
  2080. {
  2081. global $config, $user;
  2082. $server_name = $user->host;
  2083. $server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
  2084. // Forcing server vars is the only way to specify/override the protocol
  2085. if ($config['force_server_vars'] || !$server_name)
  2086. {
  2087. $server_protocol = ($config['server_protocol']) ? $config['server_protocol'] : (($config['cookie_secure']) ? 'https://' : 'http://');
  2088. $server_name = $config['server_name'];
  2089. $server_port = (int) $config['server_port'];
  2090. $script_path = $config['script_path'];
  2091. $url = $server_protocol . $server_name;
  2092. $cookie_secure = $config['cookie_secure'];
  2093. }
  2094. else
  2095. {
  2096. // Do not rely on cookie_secure, users seem to think that it means a secured cookie instead of an encrypted connection
  2097. $cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
  2098. $url = (($cookie_secure) ? 'https://' : 'http://') . $server_name;
  2099. $script_path = $user->page['root_script_path'];
  2100. }
  2101. if ($server_port && (($cookie_secure && $server_port <> 443) || (!$cookie_secure && $server_port <> 80)))
  2102. {
  2103. // HTTP HOST can carry a port number (we fetch $user->host, but for old versions this may be true)
  2104. if (strpos($server_name, ':') === false)
  2105. {
  2106. $url .= ':' . $server_port;
  2107. }
  2108. }
  2109. if (!$without_script_path)
  2110. {
  2111. $url .= $script_path;
  2112. }
  2113. // Strip / from the end
  2114. if (substr($url, -1, 1) == '/')
  2115. {
  2116. $url = substr($url, 0, -1);
  2117. }
  2118. return $url;
  2119. }
  2120. /**
  2121. * Redirects the user to another page then exits the script nicely
  2122. * This function is intended for urls within the board. It's not meant to redirect to cross-domains.
  2123. *
  2124. * @param string $url The url to redirect to
  2125. * @param bool $return If true, do not redirect but return the sanitized URL. Default is no return.
  2126. * @param bool $disable_cd_check If true, redirect() will redirect to an external domain. If false, the redirect point to the boards url if it does not match the current domain. Default is false.
  2127. */
  2128. function redirect($url, $return = false, $disable_cd_check = false)
  2129. {
  2130. global $db, $cache, $config, $user, $phpbb_root_path;
  2131. $failover_flag = false;
  2132. if (empty($user->lang))
  2133. {
  2134. $user->add_lang('common');
  2135. }
  2136. if (!$return)
  2137. {
  2138. garbage_collection();
  2139. }
  2140. // Make sure no &amp;'s are in, this will break the redirect
  2141. $url = str_replace('&amp;', '&', $url);
  2142. // Determine which type of redirect we need to handle...
  2143. $url_parts = @parse_url($url);
  2144. if ($url_parts === false)
  2145. {
  2146. // Malformed url, redirect to current page...
  2147. $url = generate_board_url() . '/' . $user->page['page'];
  2148. }
  2149. else if (!empty($url_parts['scheme']) && !empty($url_parts['host']))
  2150. {
  2151. // Attention: only able to redirect within the same domain if $disable_cd_check is false (yourdomain.com -> www.yourdomain.com will not work)
  2152. if (!$disable_cd_check && $url_parts['host'] !== $user->host)
  2153. {
  2154. $url = generate_board_url();
  2155. }
  2156. }
  2157. else if ($url[0] == '/')
  2158. {
  2159. // Absolute uri, prepend direct url...
  2160. $url = generate_board_url(true) . $url;
  2161. }
  2162. else
  2163. {
  2164. // Relative uri
  2165. $pathinfo = pathinfo($url);
  2166. if (!$disable_cd_check && !file_exists($pathinfo['dirname'] . '/'))
  2167. {
  2168. $url = str_replace('../', '', $url);
  2169. $pathinfo = pathinfo($url);
  2170. if (!file_exists($pathinfo['dirname'] . '/'))
  2171. {
  2172. // fallback to "last known user page"
  2173. // at least this way we know the user does not leave the phpBB root
  2174. $url = generate_board_url() . '/' . $user->page['page'];
  2175. $failover_flag = true;
  2176. }
  2177. }
  2178. if (!$failover_flag)
  2179. {
  2180. // Is the uri pointing to the current directory?
  2181. if ($pathinfo['dirname'] == '.')
  2182. {
  2183. $url = str_replace('./', '', $url);
  2184. // Strip / from the beginning
  2185. if ($url && substr($url, 0, 1) == '/')
  2186. {
  2187. $url = substr($url, 1);
  2188. }
  2189. if ($user->page['page_dir'])
  2190. {
  2191. $url = generate_board_url() . '/' . $user->page['page_dir'] . '/' . $url;
  2192. }
  2193. else
  2194. {
  2195. $url = generate_board_url() . '/' . $url;
  2196. }
  2197. }
  2198. else
  2199. {
  2200. // Used ./ before, but $phpbb_root_path is working better with urls within another root path
  2201. $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($phpbb_root_path)));
  2202. $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($pathinfo['dirname'])));
  2203. $intersection = array_intersect_assoc($root_dirs, $page_dirs);
  2204. $root_dirs = array_diff_assoc($root_dirs, $intersection);
  2205. $page_dirs = array_diff_assoc($page_dirs, $intersection);
  2206. $dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
  2207. // Strip / from the end
  2208. if ($dir && substr($dir, -1, 1) == '/')
  2209. {
  2210. $dir = substr($dir, 0, -1);
  2211. }
  2212. // Strip / from the beginning
  2213. if ($dir && substr($dir, 0, 1) == '/')
  2214. {
  2215. $dir = substr($dir, 1);
  2216. }
  2217. $url = str_replace($pathinfo['dirname'] . '/', '', $url);
  2218. // Strip / from the beginning
  2219. if (substr($url, 0, 1) == '/')
  2220. {
  2221. $url = substr($url, 1);
  2222. }
  2223. $url = (!empty($dir) ? $dir . '/' : '') . $url;
  2224. $url = generate_board_url() . '/' . $url;
  2225. }
  2226. }
  2227. }
  2228. // Make sure no linebreaks are there... to prevent http response splitting for PHP < 4.4.2
  2229. if (strpos(urldecode($url), "\n") !== false || strpos(urldecode($url), "\r") !== false || strpos($url, ';') !== false)
  2230. {
  2231. trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
  2232. }
  2233. // Now, also check the protocol and for a valid url the last time...
  2234. $allowed_protocols = array('http', 'https', 'ftp', 'ftps');
  2235. $url_parts = parse_url($url);
  2236. if ($url_parts === false || empty($url_parts['scheme']) || !in_array($url_parts['scheme'], $allowed_protocols))
  2237. {
  2238. trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
  2239. }
  2240. if ($return)
  2241. {
  2242. return $url;
  2243. }
  2244. // Redirect via an HTML form for PITA webservers
  2245. if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
  2246. {
  2247. header('Refresh: 0; URL=' . $url);
  2248. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  2249. echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="' . $user->lang['DIRECTION'] . '" lang="' . $user->lang['USER_LANG'] . '" xml:lang="' . $user->lang['USER_LANG'] . '">';
  2250. echo '<head>';
  2251. echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
  2252. echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&amp;', $url) . '" />';
  2253. echo '<title>' . $user->lang['REDIRECT'] . '</title>';
  2254. echo '</head>';
  2255. echo '<body>';
  2256. echo '<div style="text-align: center;">' . sprintf($user->lang['URL_REDIRECT'], '<a href="' . str_replace('&', '&amp;', $url) . '">', '</a>') . '</div>';
  2257. echo '</body>';
  2258. echo '</html>';
  2259. exit;
  2260. }
  2261. // Behave as per HTTP/1.1 spec for others
  2262. header('Location: ' . $url);
  2263. exit;
  2264. }
  2265. /**
  2266. * Re-Apply session id after page reloads
  2267. */
  2268. function reapply_sid($url)
  2269. {
  2270. global $phpEx, $phpbb_root_path;
  2271. if ($url === "index.$phpEx")
  2272. {
  2273. return append_sid("index.$phpEx");
  2274. }
  2275. else if ($url === "{$phpbb_root_path}index.$phpEx")
  2276. {
  2277. return append_sid("{$phpbb_root_path}index.$phpEx");
  2278. }
  2279. // Remove previously added sid
  2280. if (strpos($url, 'sid=') !== false)
  2281. {
  2282. // All kind of links
  2283. $url = preg_replace('/(\?)?(&amp;|&)?sid=[a-z0-9]+/', '', $url);
  2284. // if the sid was the first param, make the old second as first ones
  2285. $url = preg_replace("/$phpEx(&amp;|&)+?/", "$phpEx?", $url);
  2286. }
  2287. return append_sid($url);
  2288. }
  2289. /**
  2290. * Returns url from the session/current page with an re-appended SID with optionally stripping vars from the url
  2291. */
  2292. function build_url($strip_vars = false)
  2293. {
  2294. global $user, $phpbb_root_path;
  2295. // Append SID
  2296. $redirect = append_sid($user->page['page'], false, false);
  2297. // Add delimiter if not there...
  2298. if (strpos($redirect, '?') === false)
  2299. {
  2300. $redirect .= '?';
  2301. }
  2302. // Strip vars...
  2303. if ($strip_vars !== false && strpos($redirect, '?') !== false)
  2304. {
  2305. if (!is_array($strip_vars))
  2306. {
  2307. $strip_vars = array($strip_vars);
  2308. }
  2309. $query = $_query = array();
  2310. $args = substr($redirect, strpos($redirect, '?') + 1);
  2311. $args = ($args) ? explode('&', $args) : array();
  2312. $redirect = substr($redirect, 0, strpos($redirect, '?'));
  2313. foreach ($args as $argument)
  2314. {
  2315. $arguments = explode('=', $argument);
  2316. $key = $arguments[0];
  2317. unset($arguments[0]);
  2318. if ($key === '')
  2319. {
  2320. continue;
  2321. }
  2322. $query[$key] = implode('=', $arguments);
  2323. }
  2324. // Strip the vars off
  2325. foreach ($strip_vars as $strip)
  2326. {
  2327. if (isset($query[$strip]))
  2328. {
  2329. unset($query[$strip]);
  2330. }
  2331. }
  2332. // Glue the remaining parts together... already urlencoded
  2333. foreach ($query as $key => $value)
  2334. {
  2335. $_query[] = $key . '=' . $value;
  2336. }
  2337. $query = implode('&', $_query);
  2338. $redirect .= ($query) ? '?' . $query : '';
  2339. }
  2340. // We need to be cautious here.
  2341. // On some situations, the redirect path is an absolute URL, sometimes a relative path
  2342. // For a relative path, let's prefix it with $phpbb_root_path to point to the correct location,
  2343. // else we use the URL directly.
  2344. $url_parts = @parse_url($redirect);
  2345. // URL
  2346. if ($url_parts !== false && !empty($url_parts['scheme']) && !empty($url_parts['host']))
  2347. {
  2348. return str_replace('&', '&amp;', $redirect);
  2349. }
  2350. return $phpbb_root_path . str_replace('&', '&amp;', $redirect);
  2351. }
  2352. /**
  2353. * Meta refresh assignment
  2354. * Adds META template variable with meta http tag.
  2355. *
  2356. * @param int $time Time in seconds for meta refresh tag
  2357. * @param string $url URL to redirect to. The url will go through redirect() first before the template variable is assigned
  2358. * @param bool $disable_cd_check If true, meta_refresh() will redirect to an external domain. If false, the redirect point to the boards url if it does not match the current domain. Default is false.
  2359. */
  2360. function meta_refresh($time, $url, $disable_cd_check = false)
  2361. {
  2362. global $template;
  2363. $url = redirect($url, true, $disable_cd_check);
  2364. $url = str_replace('&', '&amp;', $url);
  2365. // For XHTML compatibility we change back & to &amp;
  2366. $template->assign_vars(array(
  2367. 'META' => '<meta http-equiv="refresh" content="' . $time . '; url=' . $url . '" />')
  2368. );
  2369. return $url;
  2370. }
  2371. /**
  2372. * Outputs correct status line header.
  2373. *
  2374. * Depending on php sapi one of the two following forms is used:
  2375. *
  2376. * Status: 404 Not Found
  2377. *
  2378. * HTTP/1.x 404 Not Found
  2379. *
  2380. * HTTP version is taken from HTTP_VERSION environment variable,
  2381. * and defaults to 1.0.
  2382. *
  2383. * Sample usage:
  2384. *
  2385. * send_status_line(404, 'Not Found');
  2386. *
  2387. * @param int $code HTTP status code
  2388. * @param string $message Message for the status code
  2389. * @return null
  2390. */
  2391. function send_status_line($code, $message)
  2392. {
  2393. if (substr(strtolower(@php_sapi_name()), 0, 3) === 'cgi')
  2394. {
  2395. // in theory, we shouldn't need that due to php doing it. Reality offers a differing opinion, though
  2396. header("Status: $code $message", true, $code);
  2397. }
  2398. else
  2399. {
  2400. if (!empty($_SERVER['SERVER_PROTOCOL']))
  2401. {
  2402. $version = $_SERVER['SERVER_PROTOCOL'];
  2403. }
  2404. else
  2405. {
  2406. $version = 'HTTP/1.0';
  2407. }
  2408. header("$version $code $message", true, $code);
  2409. }
  2410. }
  2411. //Form validation
  2412. /**
  2413. * Add a secret hash for use in links/GET requests
  2414. * @param string $link_name The name of the link; has to match the name used in check_link_hash, otherwise no restrictions apply
  2415. * @return string the hash
  2416. */
  2417. function generate_link_hash($link_name)
  2418. {
  2419. global $user;
  2420. if (!isset($user->data["hash_$link_name"]))
  2421. {
  2422. $user->data["hash_$link_name"] = substr(sha1($user->data['user_form_salt'] . $link_name), 0, 8);
  2423. }
  2424. return $user->data["hash_$link_name"];
  2425. }
  2426. /**
  2427. * checks a link hash - for GET requests
  2428. * @param string $token the submitted token
  2429. * @param string $link_name The name of the link
  2430. * @return boolean true if all is fine
  2431. */
  2432. function check_link_hash($token, $link_name)
  2433. {
  2434. return $token === generate_link_hash($link_name);
  2435. }
  2436. /**
  2437. * Add a secret token to the form (requires the S_FORM_TOKEN template variable)
  2438. * @param string $form_name The name of the form; has to match the name used in check_form_key, otherwise no restrictions apply
  2439. */
  2440. function add_form_key($form_name)
  2441. {
  2442. global $config, $template, $user;
  2443. $now = time();
  2444. $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
  2445. $token = sha1($now . $user->data['user_form_salt'] . $form_name . $token_sid);
  2446. $s_fields = build_hidden_fields(array(
  2447. 'creation_time' => $now,
  2448. 'form_token' => $token,
  2449. ));
  2450. $template->assign_vars(array(
  2451. 'S_FORM_TOKEN' => $s_fields,
  2452. ));
  2453. }
  2454. /**
  2455. * Check the form key. Required for all altering actions not secured by confirm_box
  2456. * @param string $form_name The name of the form; has to match the name used in add_form_key, otherwise no restrictions apply
  2457. * @param int $timespan The maximum acceptable age for a submitted form in seconds. Defaults to the config setting.
  2458. * @param string $return_page The address for the return link
  2459. * @param bool $trigger If true, the function will triger an error when encountering an invalid form
  2460. */
  2461. function check_form_key($form_name, $timespan = false, $return_page = '', $trigger = false)
  2462. {
  2463. global $config, $user;
  2464. if ($timespan === false)
  2465. {
  2466. // we enforce a minimum value of half a minute here.
  2467. $timespan = ($config['form_token_lifetime'] == -1) ? -1 : max(30, $config['form_token_lifetime']);
  2468. }
  2469. if (isset($_POST['creation_time']) && isset($_POST['form_token']))
  2470. {
  2471. $creation_time = abs(request_var('creation_time', 0));
  2472. $token = request_var('form_token', '');
  2473. $diff = time() - $creation_time;
  2474. // If creation_time and the time() now is zero we can assume it was not a human doing this (the check for if ($diff)...
  2475. if (defined('DEBUG_TEST') || $diff && ($diff <= $timespan || $timespan === -1))
  2476. {
  2477. $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
  2478. $key = sha1($creation_time . $user->data['user_form_salt'] . $form_name . $token_sid);
  2479. if ($key === $token)
  2480. {
  2481. return true;
  2482. }
  2483. }
  2484. }
  2485. if ($trigger)
  2486. {
  2487. trigger_error($user->lang['FORM_INVALID'] . $return_page);
  2488. }
  2489. return false;
  2490. }
  2491. // Message/Login boxes
  2492. /**
  2493. * Build Confirm box
  2494. * @param boolean $check True for checking if confirmed (without any additional parameters) and false for displaying the confirm box
  2495. * @param string $title Title/Message used for confirm box.
  2496. * message text is _CONFIRM appended to title.
  2497. * If title cannot be found in user->lang a default one is displayed
  2498. * If title_CONFIRM cannot be found in user->lang the text given is used.
  2499. * @param string $hidden Hidden variables
  2500. * @param string $html_body Template used for confirm box
  2501. * @param string $u_action Custom form action
  2502. */
  2503. function confirm_box($check, $title = '', $hidden = '', $html_body = 'confirm_body.html', $u_action = '')
  2504. {
  2505. global $user, $template, $db;
  2506. global $phpEx, $phpbb_root_path;
  2507. if (isset($_POST['cancel']))
  2508. {
  2509. return false;
  2510. }
  2511. $confirm = false;
  2512. if (isset($_POST['confirm']))
  2513. {
  2514. // language frontier
  2515. if ($_POST['confirm'] === $user->lang['YES'])
  2516. {
  2517. $confirm = true;
  2518. }
  2519. }
  2520. if ($check && $confirm)
  2521. {
  2522. $user_id = request_var('confirm_uid', 0);
  2523. $session_id = request_var('sess', '');
  2524. $confirm_key = request_var('confirm_key', '');
  2525. if ($user_id != $user->data['user_id'] || $session_id != $user->session_id || !$confirm_key || !$user->data['user_last_confirm_key'] || $confirm_key != $user->data['user_last_confirm_key'])
  2526. {
  2527. return false;
  2528. }
  2529. // Reset user_last_confirm_key
  2530. $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = ''
  2531. WHERE user_id = " . $user->data['user_id'];
  2532. $db->sql_query($sql);
  2533. return true;
  2534. }
  2535. else if ($check)
  2536. {
  2537. return false;
  2538. }
  2539. $s_hidden_fields = build_hidden_fields(array(
  2540. 'confirm_uid' => $user->data['user_id'],
  2541. 'sess' => $user->session_id,
  2542. 'sid' => $user->session_id,
  2543. ));
  2544. // generate activation key
  2545. $confirm_key = gen_rand_string(10);
  2546. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  2547. {
  2548. adm_page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
  2549. }
  2550. else
  2551. {
  2552. page_header(((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]), false);
  2553. }
  2554. $template->set_filenames(array(
  2555. 'body' => $html_body)
  2556. );
  2557. // If activation key already exist, we better do not re-use the key (something very strange is going on...)
  2558. if (request_var('confirm_key', ''))
  2559. {
  2560. // This should not occur, therefore we cancel the operation to safe the user
  2561. return false;
  2562. }
  2563. // re-add sid / transform & to &amp; for user->page (user->page is always using &)
  2564. $use_page = ($u_action) ? $phpbb_root_path . $u_action : $phpbb_root_path . str_replace('&', '&amp;', $user->page['page']);
  2565. $u_action = reapply_sid($use_page);
  2566. $u_action .= ((strpos($u_action, '?') === false) ? '?' : '&amp;') . 'confirm_key=' . $confirm_key;
  2567. $template->assign_vars(array(
  2568. 'MESSAGE_TITLE' => (!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title],
  2569. 'MESSAGE_TEXT' => (!isset($user->lang[$title . '_CONFIRM'])) ? $title : $user->lang[$title . '_CONFIRM'],
  2570. 'YES_VALUE' => $user->lang['YES'],
  2571. 'S_CONFIRM_ACTION' => $u_action,
  2572. 'S_HIDDEN_FIELDS' => $hidden . $s_hidden_fields)
  2573. );
  2574. $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = '" . $db->sql_escape($confirm_key) . "'
  2575. WHERE user_id = " . $user->data['user_id'];
  2576. $db->sql_query($sql);
  2577. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  2578. {
  2579. adm_page_footer();
  2580. }
  2581. else
  2582. {
  2583. page_footer();
  2584. }
  2585. }
  2586. /**
  2587. * Generate login box or verify password
  2588. */
  2589. function login_box($redirect = '', $l_explain = '', $l_success = '', $admin = false, $s_display = true)
  2590. {
  2591. global $db, $user, $template, $auth, $phpEx, $phpbb_root_path, $config;
  2592. if (!class_exists('phpbb_captcha_factory'))
  2593. {
  2594. include($phpbb_root_path . 'includes/captcha/captcha_factory.' . $phpEx);
  2595. }
  2596. $err = '';
  2597. // Make sure user->setup() has been called
  2598. if (empty($user->lang))
  2599. {
  2600. $user->setup();
  2601. }
  2602. // Print out error if user tries to authenticate as an administrator without having the privileges...
  2603. if ($admin && !$auth->acl_get('a_'))
  2604. {
  2605. // Not authd
  2606. // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
  2607. if ($user->data['is_registered'])
  2608. {
  2609. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2610. }
  2611. trigger_error('NO_AUTH_ADMIN');
  2612. }
  2613. if (isset($_POST['login']))
  2614. {
  2615. // Get credential
  2616. if ($admin)
  2617. {
  2618. $credential = request_var('credential', '');
  2619. if (strspn($credential, 'abcdef0123456789') !== strlen($credential) || strlen($credential) != 32)
  2620. {
  2621. if ($user->data['is_registered'])
  2622. {
  2623. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2624. }
  2625. trigger_error('NO_AUTH_ADMIN');
  2626. }
  2627. $password = request_var('password_' . $credential, '', true);
  2628. }
  2629. else
  2630. {
  2631. $password = request_var('password', '', true);
  2632. }
  2633. $username = request_var('username', '', true);
  2634. $autologin = (!empty($_POST['autologin'])) ? true : false;
  2635. $viewonline = (!empty($_POST['viewonline'])) ? 0 : 1;
  2636. $admin = ($admin) ? 1 : 0;
  2637. $viewonline = ($admin) ? $user->data['session_viewonline'] : $viewonline;
  2638. // Check if the supplied username is equal to the one stored within the database if re-authenticating
  2639. if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
  2640. {
  2641. // We log the attempt to use a different username...
  2642. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2643. trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
  2644. }
  2645. // If authentication is successful we redirect user to previous page
  2646. $result = $auth->login($username, $password, $autologin, $viewonline, $admin);
  2647. // If admin authentication and login, we will log if it was a success or not...
  2648. // We also break the operation on the first non-success login - it could be argued that the user already knows
  2649. if ($admin)
  2650. {
  2651. if ($result['status'] == LOGIN_SUCCESS)
  2652. {
  2653. add_log('admin', 'LOG_ADMIN_AUTH_SUCCESS');
  2654. }
  2655. else
  2656. {
  2657. // Only log the failed attempt if a real user tried to.
  2658. // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
  2659. if ($user->data['is_registered'])
  2660. {
  2661. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2662. }
  2663. }
  2664. }
  2665. // The result parameter is always an array, holding the relevant information...
  2666. if ($result['status'] == LOGIN_SUCCESS)
  2667. {
  2668. $redirect = request_var('redirect', "{$phpbb_root_path}index.$phpEx");
  2669. $message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
  2670. $l_redirect = ($admin) ? $user->lang['PROCEED_TO_ACP'] : (($redirect === "{$phpbb_root_path}index.$phpEx" || $redirect === "index.$phpEx") ? $user->lang['RETURN_INDEX'] : $user->lang['RETURN_PAGE']);
  2671. // append/replace SID (may change during the session for AOL users)
  2672. $redirect = reapply_sid($redirect);
  2673. // Special case... the user is effectively banned, but we allow founders to login
  2674. if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != USER_FOUNDER)
  2675. {
  2676. return;
  2677. }
  2678. $redirect = meta_refresh(3, $redirect);
  2679. trigger_error($message . '<br /><br />' . sprintf($l_redirect, '<a href="' . $redirect . '">', '</a>'));
  2680. }
  2681. // Something failed, determine what...
  2682. if ($result['status'] == LOGIN_BREAK)
  2683. {
  2684. trigger_error($result['error_msg']);
  2685. }
  2686. // Special cases... determine
  2687. switch ($result['status'])
  2688. {
  2689. case LOGIN_ERROR_ATTEMPTS:
  2690. $captcha = phpbb_captcha_factory::get_instance($config['captcha_plugin']);
  2691. $captcha->init(CONFIRM_LOGIN);
  2692. // $captcha->reset();
  2693. $template->assign_vars(array(
  2694. 'CAPTCHA_TEMPLATE' => $captcha->get_template(),
  2695. ));
  2696. $err = $user->lang[$result['error_msg']];
  2697. break;
  2698. case LOGIN_ERROR_PASSWORD_CONVERT:
  2699. $err = sprintf(
  2700. $user->lang[$result['error_msg']],
  2701. ($config['email_enable']) ? '<a href="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') . '">' : '',
  2702. ($config['email_enable']) ? '</a>' : '',
  2703. ($config['board_contact']) ? '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">' : '',
  2704. ($config['board_contact']) ? '</a>' : ''
  2705. );
  2706. break;
  2707. // Username, password, etc...
  2708. default:
  2709. $err = $user->lang[$result['error_msg']];
  2710. // Assign admin contact to some error messages
  2711. if ($result['error_msg'] == 'LOGIN_ERROR_USERNAME' || $result['error_msg'] == 'LOGIN_ERROR_PASSWORD')
  2712. {
  2713. $err = (!$config['board_contact']) ? sprintf($user->lang[$result['error_msg']], '', '') : sprintf($user->lang[$result['error_msg']], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');
  2714. }
  2715. break;
  2716. }
  2717. }
  2718. // Assign credential for username/password pair
  2719. $credential = ($admin) ? md5(unique_id()) : false;
  2720. $s_hidden_fields = array(
  2721. 'sid' => $user->session_id,
  2722. );
  2723. if ($redirect)
  2724. {
  2725. $s_hidden_fields['redirect'] = $redirect;
  2726. }
  2727. if ($admin)
  2728. {
  2729. $s_hidden_fields['credential'] = $credential;
  2730. }
  2731. $s_hidden_fields = build_hidden_fields($s_hidden_fields);
  2732. $template->assign_vars(array(
  2733. 'LOGIN_ERROR' => $err,
  2734. 'LOGIN_EXPLAIN' => $l_explain,
  2735. 'U_SEND_PASSWORD' => ($config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') : '',
  2736. 'U_RESEND_ACTIVATION' => ($config['require_activation'] == USER_ACTIVATION_SELF && $config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=resend_act') : '',
  2737. 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
  2738. 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
  2739. 'S_DISPLAY_FULL_LOGIN' => ($s_display) ? true : false,
  2740. 'S_HIDDEN_FIELDS' => $s_hidden_fields,
  2741. 'S_ADMIN_AUTH' => $admin,
  2742. 'USERNAME' => ($admin) ? $user->data['username'] : '',
  2743. 'USERNAME_CREDENTIAL' => 'username',
  2744. 'PASSWORD_CREDENTIAL' => ($admin) ? 'password_' . $credential : 'password',
  2745. ));
  2746. page_header($user->lang['LOGIN'], false);
  2747. $template->set_filenames(array(
  2748. 'body' => 'login_body.html')
  2749. );
  2750. make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"));
  2751. page_footer();
  2752. }
  2753. /**
  2754. * Generate forum login box
  2755. */
  2756. function login_forum_box($forum_data)
  2757. {
  2758. global $db, $config, $user, $template, $phpEx;
  2759. $password = request_var('password', '', true);
  2760. $sql = 'SELECT forum_id
  2761. FROM ' . FORUMS_ACCESS_TABLE . '
  2762. WHERE forum_id = ' . $forum_data['forum_id'] . '
  2763. AND user_id = ' . $user->data['user_id'] . "
  2764. AND session_id = '" . $db->sql_escape($user->session_id) . "'";
  2765. $result = $db->sql_query($sql);
  2766. $row = $db->sql_fetchrow($result);
  2767. $db->sql_freeresult($result);
  2768. if ($row)
  2769. {
  2770. return true;
  2771. }
  2772. if ($password)
  2773. {
  2774. // Remove expired authorised sessions
  2775. $sql = 'SELECT f.session_id
  2776. FROM ' . FORUMS_ACCESS_TABLE . ' f
  2777. LEFT JOIN ' . SESSIONS_TABLE . ' s ON (f.session_id = s.session_id)
  2778. WHERE s.session_id IS NULL';
  2779. $result = $db->sql_query($sql);
  2780. if ($row = $db->sql_fetchrow($result))
  2781. {
  2782. $sql_in = array();
  2783. do
  2784. {
  2785. $sql_in[] = (string) $row['session_id'];
  2786. }
  2787. while ($row = $db->sql_fetchrow($result));
  2788. // Remove expired sessions
  2789. $sql = 'DELETE FROM ' . FORUMS_ACCESS_TABLE . '
  2790. WHERE ' . $db->sql_in_set('session_id', $sql_in);
  2791. $db->sql_query($sql);
  2792. }
  2793. $db->sql_freeresult($result);
  2794. if (phpbb_check_hash($password, $forum_data['forum_password']))
  2795. {
  2796. $sql_ary = array(
  2797. 'forum_id' => (int) $forum_data['forum_id'],
  2798. 'user_id' => (int) $user->data['user_id'],
  2799. 'session_id' => (string) $user->session_id,
  2800. );
  2801. $db->sql_query('INSERT INTO ' . FORUMS_ACCESS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  2802. return true;
  2803. }
  2804. $template->assign_var('LOGIN_ERROR', $user->lang['WRONG_PASSWORD']);
  2805. }
  2806. page_header($user->lang['LOGIN'], false);
  2807. $template->assign_vars(array(
  2808. 'FORUM_NAME' => isset($forum_data['forum_name']) ? $forum_data['forum_name'] : '',
  2809. 'S_LOGIN_ACTION' => build_url(array('f')),
  2810. 'S_HIDDEN_FIELDS' => build_hidden_fields(array('f' => $forum_data['forum_id'])))
  2811. );
  2812. $template->set_filenames(array(
  2813. 'body' => 'login_forum.html')
  2814. );
  2815. page_footer();
  2816. }
  2817. // Little helpers
  2818. /**
  2819. * Little helper for the build_hidden_fields function
  2820. */
  2821. function _build_hidden_fields($key, $value, $specialchar, $stripslashes)
  2822. {
  2823. $hidden_fields = '';
  2824. if (!is_array($value))
  2825. {
  2826. $value = ($stripslashes) ? stripslashes($value) : $value;
  2827. $value = ($specialchar) ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value;
  2828. $hidden_fields .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />' . "\n";
  2829. }
  2830. else
  2831. {
  2832. foreach ($value as $_key => $_value)
  2833. {
  2834. $_key = ($stripslashes) ? stripslashes($_key) : $_key;
  2835. $_key = ($specialchar) ? htmlspecialchars($_key, ENT_COMPAT, 'UTF-8') : $_key;
  2836. $hidden_fields .= _build_hidden_fields($key . '[' . $_key . ']', $_value, $specialchar, $stripslashes);
  2837. }
  2838. }
  2839. return $hidden_fields;
  2840. }
  2841. /**
  2842. * Build simple hidden fields from array
  2843. *
  2844. * @param array $field_ary an array of values to build the hidden field from
  2845. * @param bool $specialchar if true, keys and values get specialchared
  2846. * @param bool $stripslashes if true, keys and values get stripslashed
  2847. *
  2848. * @return string the hidden fields
  2849. */
  2850. function build_hidden_fields($field_ary, $specialchar = false, $stripslashes = false)
  2851. {
  2852. $s_hidden_fields = '';
  2853. foreach ($field_ary as $name => $vars)
  2854. {
  2855. $name = ($stripslashes) ? stripslashes($name) : $name;
  2856. $name = ($specialchar) ? htmlspecialchars($name, ENT_COMPAT, 'UTF-8') : $name;
  2857. $s_hidden_fields .= _build_hidden_fields($name, $vars, $specialchar, $stripslashes);
  2858. }
  2859. return $s_hidden_fields;
  2860. }
  2861. /**
  2862. * Parse cfg file
  2863. */
  2864. function parse_cfg_file($filename, $lines = false)
  2865. {
  2866. $parsed_items = array();
  2867. if ($lines === false)
  2868. {
  2869. $lines = file($filename);
  2870. }
  2871. foreach ($lines as $line)
  2872. {
  2873. $line = trim($line);
  2874. if (!$line || $line[0] == '#' || ($delim_pos = strpos($line, '=')) === false)
  2875. {
  2876. continue;
  2877. }
  2878. // Determine first occurrence, since in values the equal sign is allowed
  2879. $key = htmlspecialchars(strtolower(trim(substr($line, 0, $delim_pos))));
  2880. $value = trim(substr($line, $delim_pos + 1));
  2881. if (in_array($value, array('off', 'false', '0')))
  2882. {
  2883. $value = false;
  2884. }
  2885. else if (in_array($value, array('on', 'true', '1')))
  2886. {
  2887. $value = true;
  2888. }
  2889. else if (!trim($value))
  2890. {
  2891. $value = '';
  2892. }
  2893. else if (($value[0] == "'" && $value[sizeof($value) - 1] == "'") || ($value[0] == '"' && $value[sizeof($value) - 1] == '"'))
  2894. {
  2895. $value = htmlspecialchars(substr($value, 1, sizeof($value)-2));
  2896. }
  2897. else
  2898. {
  2899. $value = htmlspecialchars($value);
  2900. }
  2901. $parsed_items[$key] = $value;
  2902. }
  2903. if (isset($parsed_items['inherit_from']) && isset($parsed_items['name']) && $parsed_items['inherit_from'] == $parsed_items['name'])
  2904. {
  2905. unset($parsed_items['inherit_from']);
  2906. }
  2907. return $parsed_items;
  2908. }
  2909. /**
  2910. * Add log event
  2911. */
  2912. function add_log()
  2913. {
  2914. global $db, $user;
  2915. // In phpBB 3.1.x i want to have logging in a class to be able to control it
  2916. // For now, we need a quite hakish approach to circumvent logging for some actions
  2917. // @todo implement cleanly
  2918. if (!empty($GLOBALS['skip_add_log']))
  2919. {
  2920. return false;
  2921. }
  2922. $args = func_get_args();
  2923. $mode = array_shift($args);
  2924. $reportee_id = ($mode == 'user') ? intval(array_shift($args)) : '';
  2925. $forum_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
  2926. $topic_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
  2927. $action = array_shift($args);
  2928. $data = (!sizeof($args)) ? '' : serialize($args);
  2929. $sql_ary = array(
  2930. 'user_id' => (empty($user->data)) ? ANONYMOUS : $user->data['user_id'],
  2931. 'log_ip' => $user->ip,
  2932. 'log_time' => time(),
  2933. 'log_operation' => $action,
  2934. 'log_data' => $data,
  2935. );
  2936. switch ($mode)
  2937. {
  2938. case 'admin':
  2939. $sql_ary['log_type'] = LOG_ADMIN;
  2940. break;
  2941. case 'mod':
  2942. $sql_ary += array(
  2943. 'log_type' => LOG_MOD,
  2944. 'forum_id' => $forum_id,
  2945. 'topic_id' => $topic_id
  2946. );
  2947. break;
  2948. case 'user':
  2949. $sql_ary += array(
  2950. 'log_type' => LOG_USERS,
  2951. 'reportee_id' => $reportee_id
  2952. );
  2953. break;
  2954. case 'critical':
  2955. $sql_ary['log_type'] = LOG_CRITICAL;
  2956. break;
  2957. default:
  2958. return false;
  2959. }
  2960. $db->sql_query('INSERT INTO ' . LOG_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  2961. return $db->sql_nextid();
  2962. }
  2963. /**
  2964. * Return a nicely formatted backtrace.
  2965. *
  2966. * Turns the array returned by debug_backtrace() into HTML markup.
  2967. * Also filters out absolute paths to phpBB root.
  2968. *
  2969. * @return string HTML markup
  2970. */
  2971. function get_backtrace()
  2972. {
  2973. $output = '<div style="font-family: monospace;">';
  2974. $backtrace = debug_backtrace();
  2975. // We skip the first one, because it only shows this file/function
  2976. unset($backtrace[0]);
  2977. foreach ($backtrace as $trace)
  2978. {
  2979. // Strip the current directory from path
  2980. $trace['file'] = (empty($trace['file'])) ? '(not given by php)' : htmlspecialchars(phpbb_filter_root_path($trace['file']));
  2981. $trace['line'] = (empty($trace['line'])) ? '(not given by php)' : $trace['line'];
  2982. // Only show function arguments for include etc.
  2983. // Other parameters may contain sensible information
  2984. $argument = '';
  2985. if (!empty($trace['args'][0]) && in_array($trace['function'], array('include', 'require', 'include_once', 'require_once')))
  2986. {
  2987. $argument = htmlspecialchars(phpbb_filter_root_path($trace['args'][0]));
  2988. }
  2989. $trace['class'] = (!isset($trace['class'])) ? '' : $trace['class'];
  2990. $trace['type'] = (!isset($trace['type'])) ? '' : $trace['type'];
  2991. $output .= '<br />';
  2992. $output .= '<b>FILE:</b> ' . $trace['file'] . '<br />';
  2993. $output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
  2994. $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']);
  2995. $output .= '(' . (($argument !== '') ? "'$argument'" : '') . ')<br />';
  2996. }
  2997. $output .= '</div>';
  2998. return $output;
  2999. }
  3000. /**
  3001. * This function returns a regular expression pattern for commonly used expressions
  3002. * Use with / as delimiter for email mode and # for url modes
  3003. * mode can be: email|bbcode_htm|url|url_inline|www_url|www_url_inline|relative_url|relative_url_inline|ipv4|ipv6
  3004. */
  3005. function get_preg_expression($mode)
  3006. {
  3007. switch ($mode)
  3008. {
  3009. case 'email':
  3010. // Regex written by James Watts and Francisco Jose Martin Moreno
  3011. // http://fightingforalostcause.net/misc/2006/compare-email-regex.php
  3012. return '([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*(?:[\w\!\#$\%\'\*\+\-\/\=\?\^\`{\|\}\~]|&amp;)+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,63})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)';
  3013. break;
  3014. case 'bbcode_htm':
  3015. return array(
  3016. '#<!\-\- e \-\-><a href="mailto:(.*?)">.*?</a><!\-\- e \-\->#',
  3017. '#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&amp;|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
  3018. '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
  3019. '#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
  3020. '#<!\-\- .*? \-\->#s',
  3021. '#<.*?>#s',
  3022. );
  3023. break;
  3024. // Whoa these look impressive!
  3025. // The code to generate the following two regular expressions which match valid IPv4/IPv6 addresses
  3026. // can be found in the develop directory
  3027. case 'ipv4':
  3028. return '#^(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$#';
  3029. break;
  3030. case 'ipv6':
  3031. return '#^(?:(?:(?:[\dA-F]{1,4}:){6}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:::(?:[\dA-F]{1,4}:){0,5}(?:[\dA-F]{1,4}(?::[\dA-F]{1,4})?|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:):(?:[\dA-F]{1,4}:){4}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,2}:(?:[\dA-F]{1,4}:){3}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,3}:(?:[\dA-F]{1,4}:){2}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,4}:(?:[\dA-F]{1,4}:)(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,5}:(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,6}:[\dA-F]{1,4})|(?:(?:[\dA-F]{1,4}:){1,7}:)|(?:::))$#i';
  3032. break;
  3033. case 'url':
  3034. case 'url_inline':
  3035. $inline = ($mode == 'url') ? ')' : '';
  3036. $scheme = ($mode == 'url') ? '[a-z\d+\-.]' : '[a-z\d+]'; // avoid automatic parsing of "word" in "last word.http://..."
  3037. // generated with regex generation file in the develop folder
  3038. return "[a-z]$scheme*:/{2}(?:(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})+|[0-9.]+|\[[a-z0-9.]+:[a-z0-9.]+:[a-z0-9.:]+\])(?::\d*)?(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
  3039. break;
  3040. case 'www_url':
  3041. case 'www_url_inline':
  3042. $inline = ($mode == 'www_url') ? ')' : '';
  3043. return "www\.(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})+(?::\d*)?(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
  3044. break;
  3045. case 'relative_url':
  3046. case 'relative_url_inline':
  3047. $inline = ($mode == 'relative_url') ? ')' : '';
  3048. return "(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
  3049. break;
  3050. case 'table_prefix':
  3051. return '#^[a-zA-Z][a-zA-Z0-9_]*$#';
  3052. break;
  3053. }
  3054. return '';
  3055. }
  3056. /**
  3057. * Generate regexp for naughty words censoring
  3058. * Depends on whether installed PHP version supports unicode properties
  3059. *
  3060. * @param string $word word template to be replaced
  3061. * @param bool $use_unicode whether or not to take advantage of PCRE supporting unicode
  3062. *
  3063. * @return string $preg_expr regex to use with word censor
  3064. */
  3065. function get_censor_preg_expression($word, $use_unicode = true)
  3066. {
  3067. static $unicode_support = null;
  3068. // Check whether PHP version supports unicode properties
  3069. if (is_null($unicode_support))
  3070. {
  3071. $unicode_support = ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false) ? true : false;
  3072. }
  3073. // Unescape the asterisk to simplify further conversions
  3074. $word = str_replace('\*', '*', preg_quote($word, '#'));
  3075. if ($use_unicode && $unicode_support)
  3076. {
  3077. // Replace asterisk(s) inside the pattern, at the start and at the end of it with regexes
  3078. $word = preg_replace(array('#(?<=[\p{Nd}\p{L}_])\*+(?=[\p{Nd}\p{L}_])#iu', '#^\*+#', '#\*+$#'), array('([\x20]*?|[\p{Nd}\p{L}_-]*?)', '[\p{Nd}\p{L}_-]*?', '[\p{Nd}\p{L}_-]*?'), $word);
  3079. // Generate the final substitution
  3080. $preg_expr = '#(?<![\p{Nd}\p{L}_-])(' . $word . ')(?![\p{Nd}\p{L}_-])#iu';
  3081. }
  3082. else
  3083. {
  3084. // Replace the asterisk inside the pattern, at the start and at the end of it with regexes
  3085. $word = preg_replace(array('#(?<=\S)\*+(?=\S)#iu', '#^\*+#', '#\*+$#'), array('(\x20*?\S*?)', '\S*?', '\S*?'), $word);
  3086. // Generate the final substitution
  3087. $preg_expr = '#(?<!\S)(' . $word . ')(?!\S)#iu';
  3088. }
  3089. return $preg_expr;
  3090. }
  3091. /**
  3092. * Returns the first block of the specified IPv6 address and as many additional
  3093. * ones as specified in the length paramater.
  3094. * If length is zero, then an empty string is returned.
  3095. * If length is greater than 3 the complete IP will be returned
  3096. */
  3097. function short_ipv6($ip, $length)
  3098. {
  3099. if ($length < 1)
  3100. {
  3101. return '';
  3102. }
  3103. // extend IPv6 addresses
  3104. $blocks = substr_count($ip, ':') + 1;
  3105. if ($blocks < 9)
  3106. {
  3107. $ip = str_replace('::', ':' . str_repeat('0000:', 9 - $blocks), $ip);
  3108. }
  3109. if ($ip[0] == ':')
  3110. {
  3111. $ip = '0000' . $ip;
  3112. }
  3113. if ($length < 4)
  3114. {
  3115. $ip = implode(':', array_slice(explode(':', $ip), 0, 1 + $length));
  3116. }
  3117. return $ip;
  3118. }
  3119. /**
  3120. * Wrapper for php's checkdnsrr function.
  3121. *
  3122. * @param string $host Fully-Qualified Domain Name
  3123. * @param string $type Resource record type to lookup
  3124. * Supported types are: MX (default), A, AAAA, NS, TXT, CNAME
  3125. * Other types may work or may not work
  3126. *
  3127. * @return mixed true if entry found,
  3128. * false if entry not found,
  3129. * null if this function is not supported by this environment
  3130. *
  3131. * Since null can also be returned, you probably want to compare the result
  3132. * with === true or === false,
  3133. *
  3134. * @author bantu
  3135. */
  3136. function phpbb_checkdnsrr($host, $type = 'MX')
  3137. {
  3138. // The dot indicates to search the DNS root (helps those having DNS prefixes on the same domain)
  3139. if (substr($host, -1) == '.')
  3140. {
  3141. $host_fqdn = $host;
  3142. $host = substr($host, 0, -1);
  3143. }
  3144. else
  3145. {
  3146. $host_fqdn = $host . '.';
  3147. }
  3148. // $host has format some.host.example.com
  3149. // $host_fqdn has format some.host.example.com.
  3150. // If we're looking for an A record we can use gethostbyname()
  3151. if ($type == 'A' && function_exists('gethostbyname'))
  3152. {
  3153. return (@gethostbyname($host_fqdn) == $host_fqdn) ? false : true;
  3154. }
  3155. // checkdnsrr() is available on Windows since PHP 5.3,
  3156. // but until 5.3.3 it only works for MX records
  3157. // See: http://bugs.php.net/bug.php?id=51844
  3158. // Call checkdnsrr() if
  3159. // we're looking for an MX record or
  3160. // we're not on Windows or
  3161. // we're running a PHP version where #51844 has been fixed
  3162. // checkdnsrr() supports AAAA since 5.0.0
  3163. // checkdnsrr() supports TXT since 5.2.4
  3164. if (
  3165. ($type == 'MX' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.3', '>=')) &&
  3166. ($type != 'AAAA' || version_compare(PHP_VERSION, '5.0.0', '>=')) &&
  3167. ($type != 'TXT' || version_compare(PHP_VERSION, '5.2.4', '>=')) &&
  3168. function_exists('checkdnsrr')
  3169. )
  3170. {
  3171. return checkdnsrr($host_fqdn, $type);
  3172. }
  3173. // dns_get_record() is available since PHP 5; since PHP 5.3 also on Windows,
  3174. // but on Windows it does not work reliable for AAAA records before PHP 5.3.1
  3175. // Call dns_get_record() if
  3176. // we're not looking for an AAAA record or
  3177. // we're not on Windows or
  3178. // we're running a PHP version where AAAA lookups work reliable
  3179. if (
  3180. ($type != 'AAAA' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.1', '>=')) &&
  3181. function_exists('dns_get_record')
  3182. )
  3183. {
  3184. // dns_get_record() expects an integer as second parameter
  3185. // We have to convert the string $type to the corresponding integer constant.
  3186. $type_constant = 'DNS_' . $type;
  3187. $type_param = (defined($type_constant)) ? constant($type_constant) : DNS_ANY;
  3188. // dns_get_record() might throw E_WARNING and return false for records that do not exist
  3189. $resultset = @dns_get_record($host_fqdn, $type_param);
  3190. if (empty($resultset) || !is_array($resultset))
  3191. {
  3192. return false;
  3193. }
  3194. else if ($type_param == DNS_ANY)
  3195. {
  3196. // $resultset is a non-empty array
  3197. return true;
  3198. }
  3199. foreach ($resultset as $result)
  3200. {
  3201. if (
  3202. isset($result['host']) && $result['host'] == $host &&
  3203. isset($result['type']) && $result['type'] == $type
  3204. )
  3205. {
  3206. return true;
  3207. }
  3208. }
  3209. return false;
  3210. }
  3211. // If we're on Windows we can still try to call nslookup via exec() as a last resort
  3212. if (DIRECTORY_SEPARATOR == '\\' && function_exists('exec'))
  3213. {
  3214. @exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host_fqdn), $output);
  3215. // If output is empty, the nslookup failed
  3216. if (empty($output))
  3217. {
  3218. return NULL;
  3219. }
  3220. foreach ($output as $line)
  3221. {
  3222. $line = trim($line);
  3223. if (empty($line))
  3224. {
  3225. continue;
  3226. }
  3227. // Squash tabs and multiple whitespaces to a single whitespace.
  3228. $line = preg_replace('/\s+/', ' ', $line);
  3229. switch ($type)
  3230. {
  3231. case 'MX':
  3232. if (stripos($line, "$host MX") === 0)
  3233. {
  3234. return true;
  3235. }
  3236. break;
  3237. case 'NS':
  3238. if (stripos($line, "$host nameserver") === 0)
  3239. {
  3240. return true;
  3241. }
  3242. break;
  3243. case 'TXT':
  3244. if (stripos($line, "$host text") === 0)
  3245. {
  3246. return true;
  3247. }
  3248. break;
  3249. case 'CNAME':
  3250. if (stripos($line, "$host canonical name") === 0)
  3251. {
  3252. return true;
  3253. }
  3254. break;
  3255. default:
  3256. case 'AAAA':
  3257. // AAAA records returned by nslookup on Windows XP/2003 have this format.
  3258. // Later Windows versions use the A record format below for AAAA records.
  3259. if (stripos($line, "$host AAAA IPv6 address") === 0)
  3260. {
  3261. return true;
  3262. }
  3263. // No break
  3264. case 'A':
  3265. if (!empty($host_matches))
  3266. {
  3267. // Second line
  3268. if (stripos($line, "Address: ") === 0)
  3269. {
  3270. return true;
  3271. }
  3272. else
  3273. {
  3274. $host_matches = false;
  3275. }
  3276. }
  3277. else if (stripos($line, "Name: $host") === 0)
  3278. {
  3279. // First line
  3280. $host_matches = true;
  3281. }
  3282. break;
  3283. }
  3284. }
  3285. return false;
  3286. }
  3287. return NULL;
  3288. }
  3289. // Handler, header and footer
  3290. /**
  3291. * Error and message handler, call with trigger_error if reqd
  3292. */
  3293. function msg_handler($errno, $msg_text, $errfile, $errline)
  3294. {
  3295. global $cache, $db, $auth, $template, $config, $user;
  3296. global $phpEx, $phpbb_root_path, $msg_title, $msg_long_text;
  3297. // Do not display notices if we suppress them via @
  3298. if (error_reporting() == 0 && $errno != E_USER_ERROR && $errno != E_USER_WARNING && $errno != E_USER_NOTICE)
  3299. {
  3300. return;
  3301. }
  3302. // Message handler is stripping text. In case we need it, we are possible to define long text...
  3303. if (isset($msg_long_text) && $msg_long_text && !$msg_text)
  3304. {
  3305. $msg_text = $msg_long_text;
  3306. }
  3307. if (!defined('E_DEPRECATED'))
  3308. {
  3309. define('E_DEPRECATED', 8192);
  3310. }
  3311. switch ($errno)
  3312. {
  3313. case E_NOTICE:
  3314. case E_WARNING:
  3315. // Check the error reporting level and return if the error level does not match
  3316. // If DEBUG is defined the default level is E_ALL
  3317. if (($errno & ((defined('DEBUG')) ? E_ALL : error_reporting())) == 0)
  3318. {
  3319. return;
  3320. }
  3321. if (strpos($errfile, 'cache') === false && strpos($errfile, 'template.') === false)
  3322. {
  3323. $errfile = phpbb_filter_root_path($errfile);
  3324. $msg_text = phpbb_filter_root_path($msg_text);
  3325. $error_name = ($errno === E_WARNING) ? 'PHP Warning' : 'PHP Notice';
  3326. echo '<b>[phpBB Debug] ' . $error_name . '</b>: in file <b>' . $errfile . '</b> on line <b>' . $errline . '</b>: <b>' . $msg_text . '</b><br />' . "\n";
  3327. // we are writing an image - the user won't see the debug, so let's place it in the log
  3328. if (defined('IMAGE_OUTPUT') || defined('IN_CRON'))
  3329. {
  3330. add_log('critical', 'LOG_IMAGE_GENERATION_ERROR', $errfile, $errline, $msg_text);
  3331. }
  3332. // echo '<br /><br />BACKTRACE<br />' . get_backtrace() . '<br />' . "\n";
  3333. }
  3334. return;
  3335. break;
  3336. case E_USER_ERROR:
  3337. if (!empty($user) && !empty($user->lang))
  3338. {
  3339. $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
  3340. $msg_title = (!isset($msg_title)) ? $user->lang['GENERAL_ERROR'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
  3341. $l_return_index = sprintf($user->lang['RETURN_INDEX'], '<a href="' . $phpbb_root_path . '">', '</a>');
  3342. $l_notify = '';
  3343. if (!empty($config['board_contact']))
  3344. {
  3345. $l_notify = '<p>' . sprintf($user->lang['NOTIFY_ADMIN_EMAIL'], $config['board_contact']) . '</p>';
  3346. }
  3347. }
  3348. else
  3349. {
  3350. $msg_title = 'General Error';
  3351. $l_return_index = '<a href="' . $phpbb_root_path . '">Return to index page</a>';
  3352. $l_notify = '';
  3353. if (!empty($config['board_contact']))
  3354. {
  3355. $l_notify = '<p>Please notify the board administrator or webmaster: <a href="mailto:' . $config['board_contact'] . '">' . $config['board_contact'] . '</a></p>';
  3356. }
  3357. }
  3358. $log_text = $msg_text;
  3359. $backtrace = get_backtrace();
  3360. if ($backtrace)
  3361. {
  3362. $log_text .= '<br /><br />BACKTRACE<br />' . $backtrace;
  3363. }
  3364. if (defined('IN_INSTALL') || defined('DEBUG_EXTRA') || isset($auth) && $auth->acl_get('a_'))
  3365. {
  3366. $msg_text = $log_text;
  3367. }
  3368. if ((defined('DEBUG') || defined('IN_CRON') || defined('IMAGE_OUTPUT')) && isset($db))
  3369. {
  3370. // let's avoid loops
  3371. $db->sql_return_on_error(true);
  3372. add_log('critical', 'LOG_GENERAL_ERROR', $msg_title, $log_text);
  3373. $db->sql_return_on_error(false);
  3374. }
  3375. // Do not send 200 OK, but service unavailable on errors
  3376. send_status_line(503, 'Service Unavailable');
  3377. garbage_collection();
  3378. // Try to not call the adm page data...
  3379. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  3380. echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
  3381. echo '<head>';
  3382. echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
  3383. echo '<title>' . $msg_title . '</title>';
  3384. echo '<style type="text/css">' . "\n" . '/* <![CDATA[ */' . "\n";
  3385. echo '* { margin: 0; padding: 0; } html { font-size: 100%; height: 100%; margin-bottom: 1px; background-color: #E4EDF0; } body { font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif; color: #536482; background: #E4EDF0; font-size: 62.5%; margin: 0; } ';
  3386. echo 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
  3387. echo '#wrap { padding: 0 20px 15px 20px; min-width: 615px; } #page-header { text-align: right; height: 40px; } #page-footer { clear: both; font-size: 1em; text-align: center; } ';
  3388. echo '.panel { margin: 4px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
  3389. echo '#errorpage #page-header a { font-weight: bold; line-height: 6em; } #errorpage #content { padding: 10px; } #errorpage #content h1 { line-height: 1.2em; margin-bottom: 0; color: #DF075C; } ';
  3390. echo '#errorpage #content div { margin-top: 20px; margin-bottom: 5px; border-bottom: 1px solid #CCCCCC; padding-bottom: 5px; color: #333333; font: bold 1.2em "Lucida Grande", Arial, Helvetica, sans-serif; text-decoration: none; line-height: 120%; text-align: left; } ';
  3391. echo "\n" . '/* ]]> */' . "\n";
  3392. echo '</style>';
  3393. echo '</head>';
  3394. echo '<body id="errorpage">';
  3395. echo '<div id="wrap">';
  3396. echo ' <div id="page-header">';
  3397. echo ' ' . $l_return_index;
  3398. echo ' </div>';
  3399. echo ' <div id="acp">';
  3400. echo ' <div class="panel">';
  3401. echo ' <div id="content">';
  3402. echo ' <h1>' . $msg_title . '</h1>';
  3403. echo ' <div>' . $msg_text . '</div>';
  3404. echo $l_notify;
  3405. echo ' </div>';
  3406. echo ' </div>';
  3407. echo ' </div>';
  3408. echo ' <div id="page-footer">';
  3409. echo ' Powered by <a href="https://www.phpbb.com/">phpBB</a>&reg; Forum Software &copy; phpBB Group';
  3410. echo ' </div>';
  3411. echo '</div>';
  3412. echo '</body>';
  3413. echo '</html>';
  3414. exit_handler();
  3415. // On a fatal error (and E_USER_ERROR *is* fatal) we never want other scripts to continue and force an exit here.
  3416. exit;
  3417. break;
  3418. case E_USER_WARNING:
  3419. case E_USER_NOTICE:
  3420. define('IN_ERROR_HANDLER', true);
  3421. if (empty($user->data))
  3422. {
  3423. $user->session_begin();
  3424. }
  3425. // We re-init the auth array to get correct results on login/logout
  3426. $auth->acl($user->data);
  3427. if (empty($user->lang))
  3428. {
  3429. $user->setup();
  3430. }
  3431. if ($msg_text == 'ERROR_NO_ATTACHMENT' || $msg_text == 'NO_FORUM' || $msg_text == 'NO_TOPIC' || $msg_text == 'NO_USER')
  3432. {
  3433. send_status_line(404, 'Not Found');
  3434. }
  3435. $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
  3436. $msg_title = (!isset($msg_title)) ? $user->lang['INFORMATION'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
  3437. if (!defined('HEADER_INC'))
  3438. {
  3439. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  3440. {
  3441. adm_page_header($msg_title);
  3442. }
  3443. else
  3444. {
  3445. page_header($msg_title, false);
  3446. }
  3447. }
  3448. $template->set_filenames(array(
  3449. 'body' => 'message_body.html')
  3450. );
  3451. $template->assign_vars(array(
  3452. 'MESSAGE_TITLE' => $msg_title,
  3453. 'MESSAGE_TEXT' => $msg_text,
  3454. 'S_USER_WARNING' => ($errno == E_USER_WARNING) ? true : false,
  3455. 'S_USER_NOTICE' => ($errno == E_USER_NOTICE) ? true : false)
  3456. );
  3457. // We do not want the cron script to be called on error messages
  3458. define('IN_CRON', true);
  3459. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  3460. {
  3461. adm_page_footer();
  3462. }
  3463. else
  3464. {
  3465. page_footer();
  3466. }
  3467. exit_handler();
  3468. break;
  3469. // PHP4 compatibility
  3470. case E_DEPRECATED:
  3471. return true;
  3472. break;
  3473. }
  3474. // If we notice an error not handled here we pass this back to PHP by returning false
  3475. // This may not work for all php versions
  3476. return false;
  3477. }
  3478. /**
  3479. * Removes absolute path to phpBB root directory from error messages
  3480. * and converts backslashes to forward slashes.
  3481. *
  3482. * @param string $errfile Absolute file path
  3483. * (e.g. /var/www/phpbb3/phpBB/includes/functions.php)
  3484. * Please note that if $errfile is outside of the phpBB root,
  3485. * the root path will not be found and can not be filtered.
  3486. * @return string Relative file path
  3487. * (e.g. /includes/functions.php)
  3488. */
  3489. function phpbb_filter_root_path($errfile)
  3490. {
  3491. static $root_path;
  3492. if (empty($root_path))
  3493. {
  3494. $root_path = phpbb_realpath(dirname(__FILE__) . '/../');
  3495. }
  3496. return str_replace(array($root_path, '\\'), array('[ROOT]', '/'), $errfile);
  3497. }
  3498. /**
  3499. * Queries the session table to get information about online guests
  3500. * @param int $item_id Limits the search to the item with this id
  3501. * @param string $item The name of the item which is stored in the session table as session_{$item}_id
  3502. * @return int The number of active distinct guest sessions
  3503. */
  3504. function obtain_guest_count($item_id = 0, $item = 'forum')
  3505. {
  3506. global $db, $config;
  3507. if ($item_id)
  3508. {
  3509. $reading_sql = ' AND s.session_' . $item . '_id = ' . (int) $item_id;
  3510. }
  3511. else
  3512. {
  3513. $reading_sql = '';
  3514. }
  3515. $time = (time() - (intval($config['load_online_time']) * 60));
  3516. // Get number of online guests
  3517. if ($db->sql_layer === 'sqlite')
  3518. {
  3519. $sql = 'SELECT COUNT(session_ip) as num_guests
  3520. FROM (
  3521. SELECT DISTINCT s.session_ip
  3522. FROM ' . SESSIONS_TABLE . ' s
  3523. WHERE s.session_user_id = ' . ANONYMOUS . '
  3524. AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
  3525. $reading_sql .
  3526. ')';
  3527. }
  3528. else
  3529. {
  3530. $sql = 'SELECT COUNT(DISTINCT s.session_ip) as num_guests
  3531. FROM ' . SESSIONS_TABLE . ' s
  3532. WHERE s.session_user_id = ' . ANONYMOUS . '
  3533. AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
  3534. $reading_sql;
  3535. }
  3536. $result = $db->sql_query($sql);
  3537. $guests_online = (int) $db->sql_fetchfield('num_guests');
  3538. $db->sql_freeresult($result);
  3539. return $guests_online;
  3540. }
  3541. /**
  3542. * Queries the session table to get information about online users
  3543. * @param int $item_id Limits the search to the item with this id
  3544. * @param string $item The name of the item which is stored in the session table as session_{$item}_id
  3545. * @return array An array containing the ids of online, hidden and visible users, as well as statistical info
  3546. */
  3547. function obtain_users_online($item_id = 0, $item = 'forum')
  3548. {
  3549. global $db, $config, $user;
  3550. $reading_sql = '';
  3551. if ($item_id !== 0)
  3552. {
  3553. $reading_sql = ' AND s.session_' . $item . '_id = ' . (int) $item_id;
  3554. }
  3555. $online_users = array(
  3556. 'online_users' => array(),
  3557. 'hidden_users' => array(),
  3558. 'total_online' => 0,
  3559. 'visible_online' => 0,
  3560. 'hidden_online' => 0,
  3561. 'guests_online' => 0,
  3562. );
  3563. if ($config['load_online_guests'])
  3564. {
  3565. $online_users['guests_online'] = obtain_guest_count($item_id, $item);
  3566. }
  3567. // a little discrete magic to cache this for 30 seconds
  3568. $time = (time() - (intval($config['load_online_time']) * 60));
  3569. $sql = 'SELECT s.session_user_id, s.session_ip, s.session_viewonline
  3570. FROM ' . SESSIONS_TABLE . ' s
  3571. WHERE s.session_time >= ' . ($time - ((int) ($time % 30))) .
  3572. $reading_sql .
  3573. ' AND s.session_user_id <> ' . ANONYMOUS;
  3574. $result = $db->sql_query($sql);
  3575. while ($row = $db->sql_fetchrow($result))
  3576. {
  3577. // Skip multiple sessions for one user
  3578. if (!isset($online_users['online_users'][$row['session_user_id']]))
  3579. {
  3580. $online_users['online_users'][$row['session_user_id']] = (int) $row['session_user_id'];
  3581. if ($row['session_viewonline'])
  3582. {
  3583. $online_users['visible_online']++;
  3584. }
  3585. else
  3586. {
  3587. $online_users['hidden_users'][$row['session_user_id']] = (int) $row['session_user_id'];
  3588. $online_users['hidden_online']++;
  3589. }
  3590. }
  3591. }
  3592. $online_users['total_online'] = $online_users['guests_online'] + $online_users['visible_online'] + $online_users['hidden_online'];
  3593. $db->sql_freeresult($result);
  3594. return $online_users;
  3595. }
  3596. /**
  3597. * Uses the result of obtain_users_online to generate a localized, readable representation.
  3598. * @param mixed $online_users result of obtain_users_online - array with user_id lists for total, hidden and visible users, and statistics
  3599. * @param int $item_id Indicate that the data is limited to one item and not global
  3600. * @param string $item The name of the item which is stored in the session table as session_{$item}_id
  3601. * @return array An array containing the string for output to the template
  3602. */
  3603. function obtain_users_online_string($online_users, $item_id = 0, $item = 'forum')
  3604. {
  3605. global $config, $db, $user, $auth;
  3606. $user_online_link = $online_userlist = '';
  3607. // Need caps version of $item for language-strings
  3608. $item_caps = strtoupper($item);
  3609. if (sizeof($online_users['online_users']))
  3610. {
  3611. $sql = 'SELECT username, username_clean, user_id, user_type, user_allow_viewonline, user_colour
  3612. FROM ' . USERS_TABLE . '
  3613. WHERE ' . $db->sql_in_set('user_id', $online_users['online_users']) . '
  3614. ORDER BY username_clean ASC';
  3615. $result = $db->sql_query($sql);
  3616. while ($row = $db->sql_fetchrow($result))
  3617. {
  3618. // User is logged in and therefore not a guest
  3619. if ($row['user_id'] != ANONYMOUS)
  3620. {
  3621. if (isset($online_users['hidden_users'][$row['user_id']]))
  3622. {
  3623. $row['username'] = '<em>' . $row['username'] . '</em>';
  3624. }
  3625. if (!isset($online_users['hidden_users'][$row['user_id']]) || $auth->acl_get('u_viewonline'))
  3626. {
  3627. $user_online_link = get_username_string(($row['user_type'] <> USER_IGNORE) ? 'full' : 'no_profile', $row['user_id'], $row['username'], $row['user_colour']);
  3628. $online_userlist .= ($online_userlist != '') ? ', ' . $user_online_link : $user_online_link;
  3629. }
  3630. }
  3631. }
  3632. $db->sql_freeresult($result);
  3633. }
  3634. if (!$online_userlist)
  3635. {
  3636. $online_userlist = $user->lang['NO_ONLINE_USERS'];
  3637. }
  3638. if ($item_id === 0)
  3639. {
  3640. $online_userlist = $user->lang['REGISTERED_USERS'] . ' ' . $online_userlist;
  3641. }
  3642. else if ($config['load_online_guests'])
  3643. {
  3644. $l_online = ($online_users['guests_online'] === 1) ? $user->lang['BROWSING_' . $item_caps . '_GUEST'] : $user->lang['BROWSING_' . $item_caps . '_GUESTS'];
  3645. $online_userlist = sprintf($l_online, $online_userlist, $online_users['guests_online']);
  3646. }
  3647. else
  3648. {
  3649. $online_userlist = sprintf($user->lang['BROWSING_' . $item_caps], $online_userlist);
  3650. }
  3651. // Build online listing
  3652. $vars_online = array(
  3653. 'ONLINE' => array('total_online', 'l_t_user_s', 0),
  3654. 'REG' => array('visible_online', 'l_r_user_s', !$config['load_online_guests']),
  3655. 'HIDDEN' => array('hidden_online', 'l_h_user_s', $config['load_online_guests']),
  3656. 'GUEST' => array('guests_online', 'l_g_user_s', 0)
  3657. );
  3658. foreach ($vars_online as $l_prefix => $var_ary)
  3659. {
  3660. if ($var_ary[2])
  3661. {
  3662. $l_suffix = '_AND';
  3663. }
  3664. else
  3665. {
  3666. $l_suffix = '';
  3667. }
  3668. switch ($online_users[$var_ary[0]])
  3669. {
  3670. case 0:
  3671. ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_ZERO_TOTAL' . $l_suffix];
  3672. break;
  3673. case 1:
  3674. ${$var_ary[1]} = $user->lang[$l_prefix . '_USER_TOTAL' . $l_suffix];
  3675. break;
  3676. default:
  3677. ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_TOTAL' . $l_suffix];
  3678. break;
  3679. }
  3680. }
  3681. unset($vars_online);
  3682. $l_online_users = sprintf($l_t_user_s, $online_users['total_online']);
  3683. $l_online_users .= sprintf($l_r_user_s, $online_users['visible_online']);
  3684. $l_online_users .= sprintf($l_h_user_s, $online_users['hidden_online']);
  3685. if ($config['load_online_guests'])
  3686. {
  3687. $l_online_users .= sprintf($l_g_user_s, $online_users['guests_online']);
  3688. }
  3689. return array(
  3690. 'online_userlist' => $online_userlist,
  3691. 'l_online_users' => $l_online_users,
  3692. );
  3693. }
  3694. /**
  3695. * Get option bitfield from custom data
  3696. *
  3697. * @param int $bit The bit/value to get
  3698. * @param int $data Current bitfield to check
  3699. * @return bool Returns true if value of constant is set in bitfield, else false
  3700. */
  3701. function phpbb_optionget($bit, $data)
  3702. {
  3703. return ($data & 1 << (int) $bit) ? true : false;
  3704. }
  3705. /**
  3706. * Set option bitfield
  3707. *
  3708. * @param int $bit The bit/value to set/unset
  3709. * @param bool $set True if option should be set, false if option should be unset.
  3710. * @param int $data Current bitfield to change
  3711. *
  3712. * @return int The new bitfield
  3713. */
  3714. function phpbb_optionset($bit, $set, $data)
  3715. {
  3716. if ($set && !($data & 1 << $bit))
  3717. {
  3718. $data += 1 << $bit;
  3719. }
  3720. else if (!$set && ($data & 1 << $bit))
  3721. {
  3722. $data -= 1 << $bit;
  3723. }
  3724. return $data;
  3725. }
  3726. /**
  3727. * Login using http authenticate.
  3728. *
  3729. * @param array $param Parameter array, see $param_defaults array.
  3730. *
  3731. * @return null
  3732. */
  3733. function phpbb_http_login($param)
  3734. {
  3735. global $auth, $user;
  3736. global $config;
  3737. $param_defaults = array(
  3738. 'auth_message' => '',
  3739. 'autologin' => false,
  3740. 'viewonline' => true,
  3741. 'admin' => false,
  3742. );
  3743. // Overwrite default values with passed values
  3744. $param = array_merge($param_defaults, $param);
  3745. // User is already logged in
  3746. // We will not overwrite his session
  3747. if (!empty($user->data['is_registered']))
  3748. {
  3749. return;
  3750. }
  3751. // $_SERVER keys to check
  3752. $username_keys = array(
  3753. 'PHP_AUTH_USER',
  3754. 'Authorization',
  3755. 'REMOTE_USER', 'REDIRECT_REMOTE_USER',
  3756. 'HTTP_AUTHORIZATION', 'REDIRECT_HTTP_AUTHORIZATION',
  3757. 'REMOTE_AUTHORIZATION', 'REDIRECT_REMOTE_AUTHORIZATION',
  3758. 'AUTH_USER',
  3759. );
  3760. $password_keys = array(
  3761. 'PHP_AUTH_PW',
  3762. 'REMOTE_PASSWORD',
  3763. 'AUTH_PASSWORD',
  3764. );
  3765. $username = null;
  3766. foreach ($username_keys as $k)
  3767. {
  3768. if (isset($_SERVER[$k]))
  3769. {
  3770. $username = $_SERVER[$k];
  3771. break;
  3772. }
  3773. }
  3774. $password = null;
  3775. foreach ($password_keys as $k)
  3776. {
  3777. if (isset($_SERVER[$k]))
  3778. {
  3779. $password = $_SERVER[$k];
  3780. break;
  3781. }
  3782. }
  3783. // Decode encoded information (IIS, CGI, FastCGI etc.)
  3784. if (!is_null($username) && is_null($password) && strpos($username, 'Basic ') === 0)
  3785. {
  3786. list($username, $password) = explode(':', base64_decode(substr($username, 6)), 2);
  3787. }
  3788. if (!is_null($username) && !is_null($password))
  3789. {
  3790. set_var($username, $username, 'string', true);
  3791. set_var($password, $password, 'string', true);
  3792. $auth_result = $auth->login($username, $password, $param['autologin'], $param['viewonline'], $param['admin']);
  3793. if ($auth_result['status'] == LOGIN_SUCCESS)
  3794. {
  3795. return;
  3796. }
  3797. else if ($auth_result['status'] == LOGIN_ERROR_ATTEMPTS)
  3798. {
  3799. send_status_line(401, 'Unauthorized');
  3800. trigger_error('NOT_AUTHORISED');
  3801. }
  3802. }
  3803. // Prepend sitename to auth_message
  3804. $param['auth_message'] = ($param['auth_message'] === '') ? $config['sitename'] : $config['sitename'] . ' - ' . $param['auth_message'];
  3805. // We should probably filter out non-ASCII characters - RFC2616
  3806. $param['auth_message'] = preg_replace('/[\x80-\xFF]/', '?', $param['auth_message']);
  3807. header('WWW-Authenticate: Basic realm="' . $param['auth_message'] . '"');
  3808. send_status_line(401, 'Unauthorized');
  3809. trigger_error('NOT_AUTHORISED');
  3810. }
  3811. /**
  3812. * Generate page header
  3813. */
  3814. function page_header($page_title = '', $display_online_list = true, $item_id = 0, $item = 'forum')
  3815. {
  3816. global $db, $config, $template, $SID, $_SID, $_EXTRA_URL, $user, $auth, $phpEx, $phpbb_root_path;
  3817. if (defined('HEADER_INC'))
  3818. {
  3819. return;
  3820. }
  3821. define('HEADER_INC', true);
  3822. // gzip_compression
  3823. if ($config['gzip_compress'])
  3824. {
  3825. // to avoid partially compressed output resulting in blank pages in
  3826. // the browser or error messages, compression is disabled in a few cases:
  3827. //
  3828. // 1) if headers have already been sent, this indicates plaintext output
  3829. // has been started so further content must not be compressed
  3830. // 2) the length of the current output buffer is non-zero. This means
  3831. // there is already some uncompressed content in this output buffer
  3832. // so further output must not be compressed
  3833. // 3) if more than one level of output buffering is used because we
  3834. // cannot test all output buffer level content lengths. One level
  3835. // could be caused by php.ini output_buffering. Anything
  3836. // beyond that is manual, so the code wrapping phpBB in output buffering
  3837. // can easily compress the output itself.
  3838. //
  3839. if (@extension_loaded('zlib') && !headers_sent() && ob_get_level() <= 1 && ob_get_length() == 0)
  3840. {
  3841. ob_start('ob_gzhandler');
  3842. }
  3843. }
  3844. // Generate logged in/logged out status
  3845. if ($user->data['user_id'] != ANONYMOUS)
  3846. {
  3847. $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=logout', true, $user->session_id);
  3848. $l_login_logout = sprintf($user->lang['LOGOUT_USER'], $user->data['username']);
  3849. }
  3850. else
  3851. {
  3852. $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login');
  3853. $l_login_logout = $user->lang['LOGIN'];
  3854. }
  3855. // Last visit date/time
  3856. $s_last_visit = ($user->data['user_id'] != ANONYMOUS) ? $user->format_date($user->data['session_last_visit']) : '';
  3857. // Get users online list ... if required
  3858. $l_online_users = $online_userlist = $l_online_record = $l_online_time = '';
  3859. if ($config['load_online'] && $config['load_online_time'] && $display_online_list)
  3860. {
  3861. /**
  3862. * Load online data:
  3863. * For obtaining another session column use $item and $item_id in the function-parameter, whereby the column is session_{$item}_id.
  3864. */
  3865. $item_id = max($item_id, 0);
  3866. $online_users = obtain_users_online($item_id, $item);
  3867. $user_online_strings = obtain_users_online_string($online_users, $item_id, $item);
  3868. $l_online_users = $user_online_strings['l_online_users'];
  3869. $online_userlist = $user_online_strings['online_userlist'];
  3870. $total_online_users = $online_users['total_online'];
  3871. if ($total_online_users > $config['record_online_users'])
  3872. {
  3873. set_config('record_online_users', $total_online_users, true);
  3874. set_config('record_online_date', time(), true);
  3875. }
  3876. $l_online_record = sprintf($user->lang['RECORD_ONLINE_USERS'], $config['record_online_users'], $user->format_date($config['record_online_date'], false, true));
  3877. $l_online_time = ($config['load_online_time'] == 1) ? 'VIEW_ONLINE_TIME' : 'VIEW_ONLINE_TIMES';
  3878. $l_online_time = sprintf($user->lang[$l_online_time], $config['load_online_time']);
  3879. }
  3880. $l_privmsgs_text = $l_privmsgs_text_unread = '';
  3881. $s_privmsg_new = false;
  3882. // Obtain number of new private messages if user is logged in
  3883. if (!empty($user->data['is_registered']))
  3884. {
  3885. if ($user->data['user_new_privmsg'])
  3886. {
  3887. $l_message_new = ($user->data['user_new_privmsg'] == 1) ? $user->lang['NEW_PM'] : $user->lang['NEW_PMS'];
  3888. $l_privmsgs_text = sprintf($l_message_new, $user->data['user_new_privmsg']);
  3889. if (!$user->data['user_last_privmsg'] || $user->data['user_last_privmsg'] > $user->data['session_last_visit'])
  3890. {
  3891. $sql = 'UPDATE ' . USERS_TABLE . '
  3892. SET user_last_privmsg = ' . $user->data['session_last_visit'] . '
  3893. WHERE user_id = ' . $user->data['user_id'];
  3894. $db->sql_query($sql);
  3895. $s_privmsg_new = true;
  3896. }
  3897. else
  3898. {
  3899. $s_privmsg_new = false;
  3900. }
  3901. }
  3902. else
  3903. {
  3904. $l_privmsgs_text = $user->lang['NO_NEW_PM'];
  3905. $s_privmsg_new = false;
  3906. }
  3907. $l_privmsgs_text_unread = '';
  3908. if ($user->data['user_unread_privmsg'] && $user->data['user_unread_privmsg'] != $user->data['user_new_privmsg'])
  3909. {
  3910. $l_message_unread = ($user->data['user_unread_privmsg'] == 1) ? $user->lang['UNREAD_PM'] : $user->lang['UNREAD_PMS'];
  3911. $l_privmsgs_text_unread = sprintf($l_message_unread, $user->data['user_unread_privmsg']);
  3912. }
  3913. }
  3914. $forum_id = request_var('f', 0);
  3915. $topic_id = request_var('t', 0);
  3916. $s_feed_news = false;
  3917. // Get option for news
  3918. if ($config['feed_enable'])
  3919. {
  3920. $sql = 'SELECT forum_id
  3921. FROM ' . FORUMS_TABLE . '
  3922. WHERE ' . $db->sql_bit_and('forum_options', FORUM_OPTION_FEED_NEWS, '<> 0');
  3923. $result = $db->sql_query_limit($sql, 1, 0, 600);
  3924. $s_feed_news = (int) $db->sql_fetchfield('forum_id');
  3925. $db->sql_freeresult($result);
  3926. }
  3927. // Determine board url - we may need it later
  3928. $board_url = generate_board_url() . '/';
  3929. $web_path = (defined('PHPBB_USE_BOARD_URL_PATH') && PHPBB_USE_BOARD_URL_PATH) ? $board_url : $phpbb_root_path;
  3930. // Which timezone?
  3931. $tz = ($user->data['user_id'] != ANONYMOUS) ? strval(doubleval($user->data['user_timezone'])) : strval(doubleval($config['board_timezone']));
  3932. // Send a proper content-language to the output
  3933. $user_lang = $user->lang['USER_LANG'];
  3934. if (strpos($user_lang, '-x-') !== false)
  3935. {
  3936. $user_lang = substr($user_lang, 0, strpos($user_lang, '-x-'));
  3937. }
  3938. $s_search_hidden_fields = array();
  3939. if ($_SID)
  3940. {
  3941. $s_search_hidden_fields['sid'] = $_SID;
  3942. }
  3943. if (!empty($_EXTRA_URL))
  3944. {
  3945. foreach ($_EXTRA_URL as $url_param)
  3946. {
  3947. $url_param = explode('=', $url_param, 2);
  3948. $s_search_hidden_fields[$url_param[0]] = $url_param[1];
  3949. }
  3950. }
  3951. // The following assigns all _common_ variables that may be used at any point in a template.
  3952. $template->assign_vars(array(
  3953. 'SITENAME' => $config['sitename'],
  3954. 'SITE_DESCRIPTION' => $config['site_desc'],
  3955. 'PAGE_TITLE' => $page_title,
  3956. 'SCRIPT_NAME' => str_replace('.' . $phpEx, '', $user->page['page_name']),
  3957. 'LAST_VISIT_DATE' => sprintf($user->lang['YOU_LAST_VISIT'], $s_last_visit),
  3958. 'LAST_VISIT_YOU' => $s_last_visit,
  3959. 'CURRENT_TIME' => sprintf($user->lang['CURRENT_TIME'], $user->format_date(time(), false, true)),
  3960. 'TOTAL_USERS_ONLINE' => $l_online_users,
  3961. 'LOGGED_IN_USER_LIST' => $online_userlist,
  3962. 'RECORD_USERS' => $l_online_record,
  3963. 'PRIVATE_MESSAGE_INFO' => $l_privmsgs_text,
  3964. 'PRIVATE_MESSAGE_INFO_UNREAD' => $l_privmsgs_text_unread,
  3965. 'S_USER_NEW_PRIVMSG' => $user->data['user_new_privmsg'],
  3966. 'S_USER_UNREAD_PRIVMSG' => $user->data['user_unread_privmsg'],
  3967. 'S_USER_NEW' => $user->data['user_new'],
  3968. 'SID' => $SID,
  3969. '_SID' => $_SID,
  3970. 'SESSION_ID' => $user->session_id,
  3971. 'ROOT_PATH' => $phpbb_root_path,
  3972. 'BOARD_URL' => $board_url,
  3973. 'L_LOGIN_LOGOUT' => $l_login_logout,
  3974. 'L_INDEX' => $user->lang['FORUM_INDEX'],
  3975. 'L_ONLINE_EXPLAIN' => $l_online_time,
  3976. 'U_PRIVATEMSGS' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;folder=inbox'),
  3977. 'U_RETURN_INBOX' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;folder=inbox'),
  3978. 'U_POPUP_PM' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;mode=popup'),
  3979. 'UA_POPUP_PM' => addslashes(append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;mode=popup')),
  3980. 'U_MEMBERLIST' => append_sid("{$phpbb_root_path}memberlist.$phpEx"),
  3981. 'U_VIEWONLINE' => ($auth->acl_gets('u_viewprofile', 'a_user', 'a_useradd', 'a_userdel')) ? append_sid("{$phpbb_root_path}viewonline.$phpEx") : '',
  3982. 'U_LOGIN_LOGOUT' => $u_login_logout,
  3983. 'U_INDEX' => append_sid("{$phpbb_root_path}index.$phpEx"),
  3984. 'U_SEARCH' => append_sid("{$phpbb_root_path}search.$phpEx"),
  3985. 'U_REGISTER' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register'),
  3986. 'U_PROFILE' => append_sid("{$phpbb_root_path}ucp.$phpEx"),
  3987. 'U_MODCP' => append_sid("{$phpbb_root_path}mcp.$phpEx", false, true, $user->session_id),
  3988. 'U_FAQ' => append_sid("{$phpbb_root_path}faq.$phpEx"),
  3989. 'U_SEARCH_SELF' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=egosearch'),
  3990. 'U_SEARCH_NEW' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=newposts'),
  3991. 'U_SEARCH_UNANSWERED' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unanswered'),
  3992. 'U_SEARCH_UNREAD' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unreadposts'),
  3993. 'U_SEARCH_ACTIVE_TOPICS'=> append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=active_topics'),
  3994. 'U_DELETE_COOKIES' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=delete_cookies'),
  3995. 'U_TEAM' => ($user->data['user_id'] != ANONYMOUS && !$auth->acl_get('u_viewprofile')) ? '' : append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=leaders'),
  3996. 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
  3997. 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
  3998. 'U_RESTORE_PERMISSIONS' => ($user->data['user_perm_from'] && $auth->acl_get('a_switchperm')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=restore_perm') : '',
  3999. 'U_FEED' => generate_board_url() . "/feed.$phpEx",
  4000. 'S_USER_LOGGED_IN' => ($user->data['user_id'] != ANONYMOUS) ? true : false,
  4001. 'S_AUTOLOGIN_ENABLED' => ($config['allow_autologin']) ? true : false,
  4002. 'S_BOARD_DISABLED' => ($config['board_disable']) ? true : false,
  4003. 'S_REGISTERED_USER' => (!empty($user->data['is_registered'])) ? true : false,
  4004. 'S_IS_BOT' => (!empty($user->data['is_bot'])) ? true : false,
  4005. 'S_USER_PM_POPUP' => $user->optionget('popuppm'),
  4006. 'S_USER_LANG' => $user_lang,
  4007. 'S_USER_BROWSER' => (isset($user->data['session_browser'])) ? $user->data['session_browser'] : $user->lang['UNKNOWN_BROWSER'],
  4008. 'S_USERNAME' => $user->data['username'],
  4009. 'S_CONTENT_DIRECTION' => $user->lang['DIRECTION'],
  4010. 'S_CONTENT_FLOW_BEGIN' => ($user->lang['DIRECTION'] == 'ltr') ? 'left' : 'right',
  4011. 'S_CONTENT_FLOW_END' => ($user->lang['DIRECTION'] == 'ltr') ? 'right' : 'left',
  4012. 'S_CONTENT_ENCODING' => 'UTF-8',
  4013. 'S_TIMEZONE' => ($user->data['user_dst'] || ($user->data['user_id'] == ANONYMOUS && $config['board_dst'])) ? sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], $user->lang['tz']['dst']) : sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], ''),
  4014. 'S_DISPLAY_ONLINE_LIST' => ($l_online_time) ? 1 : 0,
  4015. 'S_DISPLAY_SEARCH' => (!$config['load_search']) ? 0 : (isset($auth) ? ($auth->acl_get('u_search') && $auth->acl_getf_global('f_search')) : 1),
  4016. 'S_DISPLAY_PM' => ($config['allow_privmsg'] && !empty($user->data['is_registered']) && ($auth->acl_get('u_readpm') || $auth->acl_get('u_sendpm'))) ? true : false,
  4017. 'S_DISPLAY_MEMBERLIST' => (isset($auth)) ? $auth->acl_get('u_viewprofile') : 0,
  4018. 'S_NEW_PM' => ($s_privmsg_new) ? 1 : 0,
  4019. 'S_REGISTER_ENABLED' => ($config['require_activation'] != USER_ACTIVATION_DISABLE) ? true : false,
  4020. 'S_FORUM_ID' => $forum_id,
  4021. 'S_TOPIC_ID' => $topic_id,
  4022. 'S_LOGIN_ACTION' => ((!defined('ADMIN_START')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login') : append_sid("index.$phpEx", false, true, $user->session_id)),
  4023. 'S_LOGIN_REDIRECT' => build_hidden_fields(array('redirect' => build_url())),
  4024. 'S_ENABLE_FEEDS' => ($config['feed_enable']) ? true : false,
  4025. 'S_ENABLE_FEEDS_OVERALL' => ($config['feed_overall']) ? true : false,
  4026. 'S_ENABLE_FEEDS_FORUMS' => ($config['feed_overall_forums']) ? true : false,
  4027. 'S_ENABLE_FEEDS_TOPICS' => ($config['feed_topics_new']) ? true : false,
  4028. 'S_ENABLE_FEEDS_TOPICS_ACTIVE' => ($config['feed_topics_active']) ? true : false,
  4029. 'S_ENABLE_FEEDS_NEWS' => ($s_feed_news) ? true : false,
  4030. 'S_LOAD_UNREADS' => ($config['load_unreads_search'] && ($config['load_anon_lastread'] || $user->data['is_registered'])) ? true : false,
  4031. 'S_SEARCH_HIDDEN_FIELDS' => build_hidden_fields($s_search_hidden_fields),
  4032. 'T_THEME_PATH' => "{$web_path}styles/" . rawurlencode($user->theme['theme_path']) . '/theme',
  4033. 'T_TEMPLATE_PATH' => "{$web_path}styles/" . rawurlencode($user->theme['template_path']) . '/template',
  4034. 'T_SUPER_TEMPLATE_PATH' => (isset($user->theme['template_inherit_path']) && $user->theme['template_inherit_path']) ? "{$web_path}styles/" . rawurlencode($user->theme['template_inherit_path']) . '/template' : "{$web_path}styles/" . rawurlencode($user->theme['template_path']) . '/template',
  4035. 'T_IMAGESET_PATH' => "{$web_path}styles/" . rawurlencode($user->theme['imageset_path']) . '/imageset',
  4036. 'T_IMAGESET_LANG_PATH' => "{$web_path}styles/" . rawurlencode($user->theme['imageset_path']) . '/imageset/' . $user->lang_name,
  4037. 'T_IMAGES_PATH' => "{$web_path}images/",
  4038. 'T_SMILIES_PATH' => "{$web_path}{$config['smilies_path']}/",
  4039. 'T_AVATAR_PATH' => "{$web_path}{$config['avatar_path']}/",
  4040. 'T_AVATAR_GALLERY_PATH' => "{$web_path}{$config['avatar_gallery_path']}/",
  4041. 'T_ICONS_PATH' => "{$web_path}{$config['icons_path']}/",
  4042. 'T_RANKS_PATH' => "{$web_path}{$config['ranks_path']}/",
  4043. 'T_UPLOAD_PATH' => "{$web_path}{$config['upload_path']}/",
  4044. 'T_STYLESHEET_LINK' => (!$user->theme['theme_storedb']) ? "{$web_path}styles/" . rawurlencode($user->theme['theme_path']) . '/theme/stylesheet.css' : append_sid("{$phpbb_root_path}style.$phpEx", 'id=' . $user->theme['style_id'] . '&amp;lang=' . $user->lang_name),
  4045. 'T_STYLESHEET_NAME' => $user->theme['theme_name'],
  4046. 'T_THEME_NAME' => rawurlencode($user->theme['theme_path']),
  4047. 'T_TEMPLATE_NAME' => rawurlencode($user->theme['template_path']),
  4048. 'T_SUPER_TEMPLATE_NAME' => rawurlencode((isset($user->theme['template_inherit_path']) && $user->theme['template_inherit_path']) ? $user->theme['template_inherit_path'] : $user->theme['template_path']),
  4049. 'T_IMAGESET_NAME' => rawurlencode($user->theme['imageset_path']),
  4050. 'T_IMAGESET_LANG_NAME' => $user->data['user_lang'],
  4051. 'T_IMAGES' => 'images',
  4052. 'T_SMILIES' => $config['smilies_path'],
  4053. 'T_AVATAR' => $config['avatar_path'],
  4054. 'T_AVATAR_GALLERY' => $config['avatar_gallery_path'],
  4055. 'T_ICONS' => $config['icons_path'],
  4056. 'T_RANKS' => $config['ranks_path'],
  4057. 'T_UPLOAD' => $config['upload_path'],
  4058. 'SITE_LOGO_IMG' => $user->img('site_logo'),
  4059. 'A_COOKIE_SETTINGS' => addslashes('; path=' . $config['cookie_path'] . ((!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . $config['cookie_domain']) . ((!$config['cookie_secure']) ? '' : '; secure')),
  4060. ));
  4061. // application/xhtml+xml not used because of IE
  4062. header('Content-type: text/html; charset=UTF-8');
  4063. header('Cache-Control: private, no-cache="set-cookie"');
  4064. header('Expires: 0');
  4065. header('Pragma: no-cache');
  4066. if (!empty($user->data['is_bot']))
  4067. {
  4068. // Let reverse proxies know we detected a bot.
  4069. header('X-PHPBB-IS-BOT: yes');
  4070. }
  4071. return;
  4072. }
  4073. /**
  4074. * Generate page footer
  4075. */
  4076. function page_footer($run_cron = true)
  4077. {
  4078. global $db, $config, $template, $user, $auth, $cache, $starttime, $phpbb_root_path, $phpEx;
  4079. // Output page creation time
  4080. if (defined('DEBUG'))
  4081. {
  4082. $mtime = explode(' ', microtime());
  4083. $totaltime = $mtime[0] + $mtime[1] - $starttime;
  4084. if (!empty($_REQUEST['explain']) && $auth->acl_get('a_') && defined('DEBUG_EXTRA') && method_exists($db, 'sql_report'))
  4085. {
  4086. $db->sql_report('display');
  4087. }
  4088. $debug_output = sprintf('Time : %.3fs | ' . $db->sql_num_queries() . ' Queries | GZIP : ' . (($config['gzip_compress'] && @extension_loaded('zlib')) ? 'On' : 'Off') . (($user->load) ? ' | Load : ' . $user->load : ''), $totaltime);
  4089. if ($auth->acl_get('a_') && defined('DEBUG_EXTRA'))
  4090. {
  4091. if (function_exists('memory_get_usage'))
  4092. {
  4093. if ($memory_usage = memory_get_usage())
  4094. {
  4095. global $base_memory_usage;
  4096. $memory_usage -= $base_memory_usage;
  4097. $memory_usage = get_formatted_filesize($memory_usage);
  4098. $debug_output .= ' | Memory Usage: ' . $memory_usage;
  4099. }
  4100. }
  4101. $debug_output .= ' | <a href="' . build_url() . '&amp;explain=1">Explain</a>';
  4102. }
  4103. }
  4104. $template->assign_vars(array(
  4105. 'DEBUG_OUTPUT' => (defined('DEBUG')) ? $debug_output : '',
  4106. 'TRANSLATION_INFO' => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
  4107. 'CREDIT_LINE' => $user->lang('POWERED_BY', '<a href="https://www.phpbb.com/">phpBB</a>&reg; Forum Software &copy; phpBB Group'),
  4108. 'U_ACP' => ($auth->acl_get('a_') && !empty($user->data['is_registered'])) ? append_sid("{$phpbb_root_path}adm/index.$phpEx", false, true, $user->session_id) : '')
  4109. );
  4110. // Call cron-type script
  4111. $call_cron = false;
  4112. if (!defined('IN_CRON') && $run_cron && !$config['board_disable'] && !$user->data['is_bot'])
  4113. {
  4114. $call_cron = true;
  4115. $time_now = (!empty($user->time_now) && is_int($user->time_now)) ? $user->time_now : time();
  4116. // Any old lock present?
  4117. if (!empty($config['cron_lock']))
  4118. {
  4119. $cron_time = explode(' ', $config['cron_lock']);
  4120. // If 1 hour lock is present we do not call cron.php
  4121. if ($cron_time[0] + 3600 >= $time_now)
  4122. {
  4123. $call_cron = false;
  4124. }
  4125. }
  4126. }
  4127. // Call cron job?
  4128. if ($call_cron)
  4129. {
  4130. $cron_type = '';
  4131. if ($time_now - $config['queue_interval'] > $config['last_queue_run'] && !defined('IN_ADMIN') && file_exists($phpbb_root_path . 'cache/queue.' . $phpEx))
  4132. {
  4133. // Process email queue
  4134. $cron_type = 'queue';
  4135. }
  4136. else if (method_exists($cache, 'tidy') && $time_now - $config['cache_gc'] > $config['cache_last_gc'])
  4137. {
  4138. // Tidy the cache
  4139. $cron_type = 'tidy_cache';
  4140. }
  4141. else if ($config['warnings_expire_days'] && ($time_now - $config['warnings_gc'] > $config['warnings_last_gc']))
  4142. {
  4143. $cron_type = 'tidy_warnings';
  4144. }
  4145. else if ($time_now - $config['database_gc'] > $config['database_last_gc'])
  4146. {
  4147. // Tidy the database
  4148. $cron_type = 'tidy_database';
  4149. }
  4150. else if ($time_now - $config['search_gc'] > $config['search_last_gc'])
  4151. {
  4152. // Tidy the search
  4153. $cron_type = 'tidy_search';
  4154. }
  4155. else if ($time_now - $config['session_gc'] > $config['session_last_gc'])
  4156. {
  4157. $cron_type = 'tidy_sessions';
  4158. }
  4159. if ($cron_type)
  4160. {
  4161. $template->assign_var('RUN_CRON_TASK', '<img src="' . append_sid($phpbb_root_path . 'cron.' . $phpEx, 'cron_type=' . $cron_type) . '" width="1" height="1" alt="cron" />');
  4162. }
  4163. }
  4164. $template->display('body');
  4165. garbage_collection();
  4166. exit_handler();
  4167. }
  4168. /**
  4169. * Closing the cache object and the database
  4170. * Cool function name, eh? We might want to add operations to it later
  4171. */
  4172. function garbage_collection()
  4173. {
  4174. global $cache, $db;
  4175. // Unload cache, must be done before the DB connection if closed
  4176. if (!empty($cache))
  4177. {
  4178. $cache->unload();
  4179. }
  4180. // Close our DB connection.
  4181. if (!empty($db))
  4182. {
  4183. $db->sql_close();
  4184. }
  4185. }
  4186. /**
  4187. * Handler for exit calls in phpBB.
  4188. * This function supports hooks.
  4189. *
  4190. * Note: This function is called after the template has been outputted.
  4191. */
  4192. function exit_handler()
  4193. {
  4194. global $phpbb_hook, $config;
  4195. if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
  4196. {
  4197. if ($phpbb_hook->hook_return(__FUNCTION__))
  4198. {
  4199. return $phpbb_hook->hook_return_result(__FUNCTION__);
  4200. }
  4201. }
  4202. // As a pre-caution... some setups display a blank page if the flush() is not there.
  4203. (ob_get_level() > 0) ? @ob_flush() : @flush();
  4204. exit;
  4205. }
  4206. /**
  4207. * Handler for init calls in phpBB. This function is called in user::setup();
  4208. * This function supports hooks.
  4209. */
  4210. function phpbb_user_session_handler()
  4211. {
  4212. global $phpbb_hook;
  4213. if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
  4214. {
  4215. if ($phpbb_hook->hook_return(__FUNCTION__))
  4216. {
  4217. return $phpbb_hook->hook_return_result(__FUNCTION__);
  4218. }
  4219. }
  4220. return;
  4221. }
  4222. ?>