PageRenderTime 83ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

/includes/functions.php

https://bitbucket.org/VolCh/phpbb3-russian-stable
PHP | 4858 lines | 3596 code | 560 blank | 702 comment | 565 complexity | 9a191ab0207c174fb6c1a096f895aea3 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. * Set config value. Creates missing config entry.
  128. */
  129. function set_config($config_name, $config_value, $is_dynamic = false)
  130. {
  131. global $db, $cache, $config;
  132. $sql = 'UPDATE ' . CONFIG_TABLE . "
  133. SET config_value = '" . $db->sql_escape($config_value) . "'
  134. WHERE config_name = '" . $db->sql_escape($config_name) . "'";
  135. $db->sql_query($sql);
  136. if (!$db->sql_affectedrows() && !isset($config[$config_name]))
  137. {
  138. $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array(
  139. 'config_name' => $config_name,
  140. 'config_value' => $config_value,
  141. 'is_dynamic' => ($is_dynamic) ? 1 : 0));
  142. $db->sql_query($sql);
  143. }
  144. $config[$config_name] = $config_value;
  145. if (!$is_dynamic)
  146. {
  147. $cache->destroy('config');
  148. }
  149. }
  150. /**
  151. * Set dynamic config value with arithmetic operation.
  152. */
  153. function set_config_count($config_name, $increment, $is_dynamic = false)
  154. {
  155. global $db, $cache;
  156. switch ($db->sql_layer)
  157. {
  158. case 'firebird':
  159. // Precision must be from 1 to 18
  160. $sql_update = 'CAST(CAST(config_value as DECIMAL(18, 0)) + ' . (int) $increment . ' as VARCHAR(255))';
  161. break;
  162. case 'postgres':
  163. // Need to cast to text first for PostgreSQL 7.x
  164. $sql_update = 'CAST(CAST(config_value::text as DECIMAL(255, 0)) + ' . (int) $increment . ' as VARCHAR(255))';
  165. break;
  166. // MySQL, SQlite, mssql, mssql_odbc, oracle
  167. default:
  168. $sql_update = 'config_value + ' . (int) $increment;
  169. break;
  170. }
  171. $db->sql_query('UPDATE ' . CONFIG_TABLE . ' SET config_value = ' . $sql_update . " WHERE config_name = '" . $db->sql_escape($config_name) . "'");
  172. if (!$is_dynamic)
  173. {
  174. $cache->destroy('config');
  175. }
  176. }
  177. /**
  178. * Generates an alphanumeric random string of given length
  179. *
  180. * @return string
  181. */
  182. function gen_rand_string($num_chars = 8)
  183. {
  184. // [a, z] + [0, 9] = 36
  185. return substr(strtoupper(base_convert(unique_id(), 16, 36)), 0, $num_chars);
  186. }
  187. /**
  188. * Generates a user-friendly alphanumeric random string of given length
  189. * We remove 0 and O so users cannot confuse those in passwords etc.
  190. *
  191. * @return string
  192. */
  193. function gen_rand_string_friendly($num_chars = 8)
  194. {
  195. $rand_str = unique_id();
  196. // Remove Z and Y from the base_convert(), replace 0 with Z and O with Y
  197. // [a, z] + [0, 9] - {z, y} = [a, z] + [0, 9] - {0, o} = 34
  198. $rand_str = str_replace(array('0', 'O'), array('Z', 'Y'), strtoupper(base_convert($rand_str, 16, 34)));
  199. return substr($rand_str, 0, $num_chars);
  200. }
  201. /**
  202. * Return unique id
  203. * @param string $extra additional entropy
  204. */
  205. function unique_id($extra = 'c')
  206. {
  207. static $dss_seeded = false;
  208. global $config;
  209. $val = $config['rand_seed'] . microtime();
  210. $val = md5($val);
  211. $config['rand_seed'] = md5($config['rand_seed'] . $val . $extra);
  212. if ($dss_seeded !== true && ($config['rand_seed_last_update'] < time() - rand(1,10)))
  213. {
  214. set_config('rand_seed_last_update', time(), true);
  215. set_config('rand_seed', $config['rand_seed'], true);
  216. $dss_seeded = true;
  217. }
  218. return substr($val, 4, 16);
  219. }
  220. /**
  221. * Wrapper for mt_rand() which allows swapping $min and $max parameters.
  222. *
  223. * PHP does not allow us to swap the order of the arguments for mt_rand() anymore.
  224. * (since PHP 5.3.4, see http://bugs.php.net/46587)
  225. *
  226. * @param int $min Lowest value to be returned
  227. * @param int $max Highest value to be returned
  228. *
  229. * @return int Random integer between $min and $max (or $max and $min)
  230. */
  231. function phpbb_mt_rand($min, $max)
  232. {
  233. return ($min > $max) ? mt_rand($max, $min) : mt_rand($min, $max);
  234. }
  235. /**
  236. * Wrapper for getdate() which returns the equivalent array for UTC timestamps.
  237. *
  238. * @param int $time Unix timestamp (optional)
  239. *
  240. * @return array Returns an associative array of information related to the timestamp.
  241. * See http://www.php.net/manual/en/function.getdate.php
  242. */
  243. function phpbb_gmgetdate($time = false)
  244. {
  245. if ($time === false)
  246. {
  247. $time = time();
  248. }
  249. // getdate() interprets timestamps in local time.
  250. // What follows uses the fact that getdate() and
  251. // date('Z') balance each other out.
  252. return getdate($time - date('Z'));
  253. }
  254. /**
  255. * Return formatted string for filesizes
  256. *
  257. * @param int $value filesize in bytes
  258. * @param bool $string_only true if language string should be returned
  259. * @param array $allowed_units only allow these units (data array indexes)
  260. *
  261. * @return mixed data array if $string_only is false
  262. * @author bantu
  263. */
  264. function get_formatted_filesize($value, $string_only = true, $allowed_units = false)
  265. {
  266. global $user;
  267. $available_units = array(
  268. 'gb' => array(
  269. 'min' => 1073741824, // pow(2, 30)
  270. 'index' => 3,
  271. 'si_unit' => 'GB',
  272. 'iec_unit' => 'GIB',
  273. ),
  274. 'mb' => array(
  275. 'min' => 1048576, // pow(2, 20)
  276. 'index' => 2,
  277. 'si_unit' => 'MB',
  278. 'iec_unit' => 'MIB',
  279. ),
  280. 'kb' => array(
  281. 'min' => 1024, // pow(2, 10)
  282. 'index' => 1,
  283. 'si_unit' => 'KB',
  284. 'iec_unit' => 'KIB',
  285. ),
  286. 'b' => array(
  287. 'min' => 0,
  288. 'index' => 0,
  289. 'si_unit' => 'BYTES', // Language index
  290. 'iec_unit' => 'BYTES', // Language index
  291. ),
  292. );
  293. foreach ($available_units as $si_identifier => $unit_info)
  294. {
  295. if (!empty($allowed_units) && $si_identifier != 'b' && !in_array($si_identifier, $allowed_units))
  296. {
  297. continue;
  298. }
  299. if ($value >= $unit_info['min'])
  300. {
  301. $unit_info['si_identifier'] = $si_identifier;
  302. break;
  303. }
  304. }
  305. unset($available_units);
  306. for ($i = 0; $i < $unit_info['index']; $i++)
  307. {
  308. $value /= 1024;
  309. }
  310. $value = round($value, 2);
  311. // Lookup units in language dictionary
  312. $unit_info['si_unit'] = (isset($user->lang[$unit_info['si_unit']])) ? $user->lang[$unit_info['si_unit']] : $unit_info['si_unit'];
  313. $unit_info['iec_unit'] = (isset($user->lang[$unit_info['iec_unit']])) ? $user->lang[$unit_info['iec_unit']] : $unit_info['iec_unit'];
  314. // Default to IEC
  315. $unit_info['unit'] = $unit_info['iec_unit'];
  316. if (!$string_only)
  317. {
  318. $unit_info['value'] = $value;
  319. return $unit_info;
  320. }
  321. return $value . ' ' . $unit_info['unit'];
  322. }
  323. /**
  324. * Determine whether we are approaching the maximum execution time. Should be called once
  325. * at the beginning of the script in which it's used.
  326. * @return bool Either true if the maximum execution time is nearly reached, or false
  327. * if some time is still left.
  328. */
  329. function still_on_time($extra_time = 15)
  330. {
  331. static $max_execution_time, $start_time;
  332. $time = explode(' ', microtime());
  333. $current_time = $time[0] + $time[1];
  334. if (empty($max_execution_time))
  335. {
  336. $max_execution_time = (function_exists('ini_get')) ? (int) @ini_get('max_execution_time') : (int) @get_cfg_var('max_execution_time');
  337. // If zero, then set to something higher to not let the user catch the ten seconds barrier.
  338. if ($max_execution_time === 0)
  339. {
  340. $max_execution_time = 50 + $extra_time;
  341. }
  342. $max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50);
  343. // For debugging purposes
  344. // $max_execution_time = 10;
  345. global $starttime;
  346. $start_time = (empty($starttime)) ? $current_time : $starttime;
  347. }
  348. return (ceil($current_time - $start_time) < $max_execution_time) ? true : false;
  349. }
  350. /**
  351. *
  352. * @version Version 0.1 / slightly modified for phpBB 3.0.x (using $H$ as hash type identifier)
  353. *
  354. * Portable PHP password hashing framework.
  355. *
  356. * Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
  357. * the public domain.
  358. *
  359. * There's absolutely no warranty.
  360. *
  361. * The homepage URL for this framework is:
  362. *
  363. * http://www.openwall.com/phpass/
  364. *
  365. * Please be sure to update the Version line if you edit this file in any way.
  366. * It is suggested that you leave the main version number intact, but indicate
  367. * your project name (after the slash) and add your own revision information.
  368. *
  369. * Please do not change the "private" password hashing method implemented in
  370. * here, thereby making your hashes incompatible. However, if you must, please
  371. * change the hash type identifier (the "$P$") to something different.
  372. *
  373. * Obviously, since this code is in the public domain, the above are not
  374. * requirements (there can be none), but merely suggestions.
  375. *
  376. *
  377. * Hash the password
  378. */
  379. function phpbb_hash($password)
  380. {
  381. $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  382. $random_state = unique_id();
  383. $random = '';
  384. $count = 6;
  385. if (($fh = @fopen('/dev/urandom', 'rb')))
  386. {
  387. $random = fread($fh, $count);
  388. fclose($fh);
  389. }
  390. if (strlen($random) < $count)
  391. {
  392. $random = '';
  393. for ($i = 0; $i < $count; $i += 16)
  394. {
  395. $random_state = md5(unique_id() . $random_state);
  396. $random .= pack('H*', md5($random_state));
  397. }
  398. $random = substr($random, 0, $count);
  399. }
  400. $hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64);
  401. if (strlen($hash) == 34)
  402. {
  403. return $hash;
  404. }
  405. return md5($password);
  406. }
  407. /**
  408. * Check for correct password
  409. *
  410. * @param string $password The password in plain text
  411. * @param string $hash The stored password hash
  412. *
  413. * @return bool Returns true if the password is correct, false if not.
  414. */
  415. function phpbb_check_hash($password, $hash)
  416. {
  417. $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  418. if (strlen($hash) == 34)
  419. {
  420. return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
  421. }
  422. return (md5($password) === $hash) ? true : false;
  423. }
  424. /**
  425. * Generate salt for hash generation
  426. */
  427. function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6)
  428. {
  429. if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
  430. {
  431. $iteration_count_log2 = 8;
  432. }
  433. $output = '$H$';
  434. $output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)];
  435. $output .= _hash_encode64($input, 6, $itoa64);
  436. return $output;
  437. }
  438. /**
  439. * Encode hash
  440. */
  441. function _hash_encode64($input, $count, &$itoa64)
  442. {
  443. $output = '';
  444. $i = 0;
  445. do
  446. {
  447. $value = ord($input[$i++]);
  448. $output .= $itoa64[$value & 0x3f];
  449. if ($i < $count)
  450. {
  451. $value |= ord($input[$i]) << 8;
  452. }
  453. $output .= $itoa64[($value >> 6) & 0x3f];
  454. if ($i++ >= $count)
  455. {
  456. break;
  457. }
  458. if ($i < $count)
  459. {
  460. $value |= ord($input[$i]) << 16;
  461. }
  462. $output .= $itoa64[($value >> 12) & 0x3f];
  463. if ($i++ >= $count)
  464. {
  465. break;
  466. }
  467. $output .= $itoa64[($value >> 18) & 0x3f];
  468. }
  469. while ($i < $count);
  470. return $output;
  471. }
  472. /**
  473. * The crypt function/replacement
  474. */
  475. function _hash_crypt_private($password, $setting, &$itoa64)
  476. {
  477. $output = '*';
  478. // Check for correct hash
  479. if (substr($setting, 0, 3) != '$H$' && substr($setting, 0, 3) != '$P$')
  480. {
  481. return $output;
  482. }
  483. $count_log2 = strpos($itoa64, $setting[3]);
  484. if ($count_log2 < 7 || $count_log2 > 30)
  485. {
  486. return $output;
  487. }
  488. $count = 1 << $count_log2;
  489. $salt = substr($setting, 4, 8);
  490. if (strlen($salt) != 8)
  491. {
  492. return $output;
  493. }
  494. /**
  495. * We're kind of forced to use MD5 here since it's the only
  496. * cryptographic primitive available in all versions of PHP
  497. * currently in use. To implement our own low-level crypto
  498. * in PHP would result in much worse performance and
  499. * consequently in lower iteration counts and hashes that are
  500. * quicker to crack (by non-PHP code).
  501. */
  502. if (PHP_VERSION >= 5)
  503. {
  504. $hash = md5($salt . $password, true);
  505. do
  506. {
  507. $hash = md5($hash . $password, true);
  508. }
  509. while (--$count);
  510. }
  511. else
  512. {
  513. $hash = pack('H*', md5($salt . $password));
  514. do
  515. {
  516. $hash = pack('H*', md5($hash . $password));
  517. }
  518. while (--$count);
  519. }
  520. $output = substr($setting, 0, 12);
  521. $output .= _hash_encode64($hash, 16, $itoa64);
  522. return $output;
  523. }
  524. /**
  525. * Hashes an email address to a big integer
  526. *
  527. * @param string $email Email address
  528. *
  529. * @return string Unsigned Big Integer
  530. */
  531. function phpbb_email_hash($email)
  532. {
  533. return sprintf('%u', crc32(strtolower($email))) . strlen($email);
  534. }
  535. /**
  536. * Wrapper for version_compare() that allows using uppercase A and B
  537. * for alpha and beta releases.
  538. *
  539. * See http://www.php.net/manual/en/function.version-compare.php
  540. *
  541. * @param string $version1 First version number
  542. * @param string $version2 Second version number
  543. * @param string $operator Comparison operator (optional)
  544. *
  545. * @return mixed Boolean (true, false) if comparison operator is specified.
  546. * Integer (-1, 0, 1) otherwise.
  547. */
  548. function phpbb_version_compare($version1, $version2, $operator = null)
  549. {
  550. $version1 = strtolower($version1);
  551. $version2 = strtolower($version2);
  552. if (is_null($operator))
  553. {
  554. return version_compare($version1, $version2);
  555. }
  556. else
  557. {
  558. return version_compare($version1, $version2, $operator);
  559. }
  560. }
  561. /**
  562. * Global function for chmodding directories and files for internal use
  563. *
  564. * This function determines owner and group whom the file belongs to and user and group of PHP and then set safest possible file permissions.
  565. * The function determines owner and group from common.php file and sets the same to the provided file.
  566. * The function uses bit fields to build the permissions.
  567. * The function sets the appropiate execute bit on directories.
  568. *
  569. * Supported constants representing bit fields are:
  570. *
  571. * CHMOD_ALL - all permissions (7)
  572. * CHMOD_READ - read permission (4)
  573. * CHMOD_WRITE - write permission (2)
  574. * CHMOD_EXECUTE - execute permission (1)
  575. *
  576. * 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.
  577. *
  578. * @param string $filename The file/directory to be chmodded
  579. * @param int $perms Permissions to set
  580. *
  581. * @return bool true on success, otherwise false
  582. * @author faw, phpBB Group
  583. */
  584. function phpbb_chmod($filename, $perms = CHMOD_READ)
  585. {
  586. static $_chmod_info;
  587. // Return if the file no longer exists.
  588. if (!file_exists($filename))
  589. {
  590. return false;
  591. }
  592. // Determine some common vars
  593. if (empty($_chmod_info))
  594. {
  595. if (!function_exists('fileowner') || !function_exists('filegroup'))
  596. {
  597. // No need to further determine owner/group - it is unknown
  598. $_chmod_info['process'] = false;
  599. }
  600. else
  601. {
  602. global $phpbb_root_path, $phpEx;
  603. // Determine owner/group of common.php file and the filename we want to change here
  604. $common_php_owner = @fileowner($phpbb_root_path . 'common.' . $phpEx);
  605. $common_php_group = @filegroup($phpbb_root_path . 'common.' . $phpEx);
  606. // And the owner and the groups PHP is running under.
  607. $php_uid = (function_exists('posix_getuid')) ? @posix_getuid() : false;
  608. $php_gids = (function_exists('posix_getgroups')) ? @posix_getgroups() : false;
  609. // If we are unable to get owner/group, then do not try to set them by guessing
  610. if (!$php_uid || empty($php_gids) || !$common_php_owner || !$common_php_group)
  611. {
  612. $_chmod_info['process'] = false;
  613. }
  614. else
  615. {
  616. $_chmod_info = array(
  617. 'process' => true,
  618. 'common_owner' => $common_php_owner,
  619. 'common_group' => $common_php_group,
  620. 'php_uid' => $php_uid,
  621. 'php_gids' => $php_gids,
  622. );
  623. }
  624. }
  625. }
  626. if ($_chmod_info['process'])
  627. {
  628. $file_uid = @fileowner($filename);
  629. $file_gid = @filegroup($filename);
  630. // Change owner
  631. if (@chown($filename, $_chmod_info['common_owner']))
  632. {
  633. clearstatcache();
  634. $file_uid = @fileowner($filename);
  635. }
  636. // Change group
  637. if (@chgrp($filename, $_chmod_info['common_group']))
  638. {
  639. clearstatcache();
  640. $file_gid = @filegroup($filename);
  641. }
  642. // If the file_uid/gid now match the one from common.php we can process further, else we are not able to change something
  643. if ($file_uid != $_chmod_info['common_owner'] || $file_gid != $_chmod_info['common_group'])
  644. {
  645. $_chmod_info['process'] = false;
  646. }
  647. }
  648. // Still able to process?
  649. if ($_chmod_info['process'])
  650. {
  651. if ($file_uid == $_chmod_info['php_uid'])
  652. {
  653. $php = 'owner';
  654. }
  655. else if (in_array($file_gid, $_chmod_info['php_gids']))
  656. {
  657. $php = 'group';
  658. }
  659. else
  660. {
  661. // Since we are setting the everyone bit anyway, no need to do expensive operations
  662. $_chmod_info['process'] = false;
  663. }
  664. }
  665. // We are not able to determine or change something
  666. if (!$_chmod_info['process'])
  667. {
  668. $php = 'other';
  669. }
  670. // Owner always has read/write permission
  671. $owner = CHMOD_READ | CHMOD_WRITE;
  672. if (is_dir($filename))
  673. {
  674. $owner |= CHMOD_EXECUTE;
  675. // Only add execute bit to the permission if the dir needs to be readable
  676. if ($perms & CHMOD_READ)
  677. {
  678. $perms |= CHMOD_EXECUTE;
  679. }
  680. }
  681. switch ($php)
  682. {
  683. case 'owner':
  684. $result = @chmod($filename, ($owner << 6) + (0 << 3) + (0 << 0));
  685. clearstatcache();
  686. if (is_readable($filename) && phpbb_is_writable($filename))
  687. {
  688. break;
  689. }
  690. case 'group':
  691. $result = @chmod($filename, ($owner << 6) + ($perms << 3) + (0 << 0));
  692. clearstatcache();
  693. if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))
  694. {
  695. break;
  696. }
  697. case 'other':
  698. $result = @chmod($filename, ($owner << 6) + ($perms << 3) + ($perms << 0));
  699. clearstatcache();
  700. if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))
  701. {
  702. break;
  703. }
  704. default:
  705. return false;
  706. break;
  707. }
  708. return $result;
  709. }
  710. /**
  711. * Test if a file/directory is writable
  712. *
  713. * This function calls the native is_writable() when not running under
  714. * Windows and it is not disabled.
  715. *
  716. * @param string $file Path to perform write test on
  717. * @return bool True when the path is writable, otherwise false.
  718. */
  719. function phpbb_is_writable($file)
  720. {
  721. if (strtolower(substr(PHP_OS, 0, 3)) === 'win' || !function_exists('is_writable'))
  722. {
  723. if (file_exists($file))
  724. {
  725. // Canonicalise path to absolute path
  726. $file = phpbb_realpath($file);
  727. if (is_dir($file))
  728. {
  729. // Test directory by creating a file inside the directory
  730. $result = @tempnam($file, 'i_w');
  731. if (is_string($result) && file_exists($result))
  732. {
  733. unlink($result);
  734. // Ensure the file is actually in the directory (returned realpathed)
  735. return (strpos($result, $file) === 0) ? true : false;
  736. }
  737. }
  738. else
  739. {
  740. $handle = @fopen($file, 'r+');
  741. if (is_resource($handle))
  742. {
  743. fclose($handle);
  744. return true;
  745. }
  746. }
  747. }
  748. else
  749. {
  750. // file does not exist test if we can write to the directory
  751. $dir = dirname($file);
  752. if (file_exists($dir) && is_dir($dir) && phpbb_is_writable($dir))
  753. {
  754. return true;
  755. }
  756. }
  757. return false;
  758. }
  759. else
  760. {
  761. return is_writable($file);
  762. }
  763. }
  764. // Compatibility functions
  765. if (!function_exists('array_combine'))
  766. {
  767. /**
  768. * A wrapper for the PHP5 function array_combine()
  769. * @param array $keys contains keys for the resulting array
  770. * @param array $values contains values for the resulting array
  771. *
  772. * @return Returns an array by using the values from the keys array as keys and the
  773. * values from the values array as the corresponding values. Returns false if the
  774. * number of elements for each array isn't equal or if the arrays are empty.
  775. */
  776. function array_combine($keys, $values)
  777. {
  778. $keys = array_values($keys);
  779. $values = array_values($values);
  780. $n = sizeof($keys);
  781. $m = sizeof($values);
  782. if (!$n || !$m || ($n != $m))
  783. {
  784. return false;
  785. }
  786. $combined = array();
  787. for ($i = 0; $i < $n; $i++)
  788. {
  789. $combined[$keys[$i]] = $values[$i];
  790. }
  791. return $combined;
  792. }
  793. }
  794. if (!function_exists('str_split'))
  795. {
  796. /**
  797. * A wrapper for the PHP5 function str_split()
  798. * @param array $string contains the string to be converted
  799. * @param array $split_length contains the length of each chunk
  800. *
  801. * @return Converts a string to an array. If the optional split_length parameter is specified,
  802. * the returned array will be broken down into chunks with each being split_length in length,
  803. * otherwise each chunk will be one character in length. FALSE is returned if split_length is
  804. * less than 1. If the split_length length exceeds the length of string, the entire string is
  805. * returned as the first (and only) array element.
  806. */
  807. function str_split($string, $split_length = 1)
  808. {
  809. if ($split_length < 1)
  810. {
  811. return false;
  812. }
  813. else if ($split_length >= strlen($string))
  814. {
  815. return array($string);
  816. }
  817. else
  818. {
  819. preg_match_all('#.{1,' . $split_length . '}#s', $string, $matches);
  820. return $matches[0];
  821. }
  822. }
  823. }
  824. if (!function_exists('stripos'))
  825. {
  826. /**
  827. * A wrapper for the PHP5 function stripos
  828. * Find position of first occurrence of a case-insensitive string
  829. *
  830. * @param string $haystack is the string to search in
  831. * @param string $needle is the string to search for
  832. *
  833. * @return mixed Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.
  834. * Note that the needle may be a string of one or more characters.
  835. * If needle is not found, stripos() will return boolean FALSE.
  836. */
  837. function stripos($haystack, $needle)
  838. {
  839. if (preg_match('#' . preg_quote($needle, '#') . '#i', $haystack, $m))
  840. {
  841. return strpos($haystack, $m[0]);
  842. }
  843. return false;
  844. }
  845. }
  846. /**
  847. * Checks if a path ($path) is absolute or relative
  848. *
  849. * @param string $path Path to check absoluteness of
  850. * @return boolean
  851. */
  852. function is_absolute($path)
  853. {
  854. return ($path[0] == '/' || (DIRECTORY_SEPARATOR == '\\' && preg_match('#^[a-z]:[/\\\]#i', $path))) ? true : false;
  855. }
  856. /**
  857. * @author Chris Smith <chris@project-minerva.org>
  858. * @copyright 2006 Project Minerva Team
  859. * @param string $path The path which we should attempt to resolve.
  860. * @return mixed
  861. */
  862. function phpbb_own_realpath($path)
  863. {
  864. // Now to perform funky shizzle
  865. // Switch to use UNIX slashes
  866. $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
  867. $path_prefix = '';
  868. // Determine what sort of path we have
  869. if (is_absolute($path))
  870. {
  871. $absolute = true;
  872. if ($path[0] == '/')
  873. {
  874. // Absolute path, *NIX style
  875. $path_prefix = '';
  876. }
  877. else
  878. {
  879. // Absolute path, Windows style
  880. // Remove the drive letter and colon
  881. $path_prefix = $path[0] . ':';
  882. $path = substr($path, 2);
  883. }
  884. }
  885. else
  886. {
  887. // Relative Path
  888. // Prepend the current working directory
  889. if (function_exists('getcwd'))
  890. {
  891. // This is the best method, hopefully it is enabled!
  892. $path = str_replace(DIRECTORY_SEPARATOR, '/', getcwd()) . '/' . $path;
  893. $absolute = true;
  894. if (preg_match('#^[a-z]:#i', $path))
  895. {
  896. $path_prefix = $path[0] . ':';
  897. $path = substr($path, 2);
  898. }
  899. else
  900. {
  901. $path_prefix = '';
  902. }
  903. }
  904. else if (isset($_SERVER['SCRIPT_FILENAME']) && !empty($_SERVER['SCRIPT_FILENAME']))
  905. {
  906. // Warning: If chdir() has been used this will lie!
  907. // Warning: This has some problems sometime (CLI can create them easily)
  908. $path = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['SCRIPT_FILENAME'])) . '/' . $path;
  909. $absolute = true;
  910. $path_prefix = '';
  911. }
  912. else
  913. {
  914. // We have no way of getting the absolute path, just run on using relative ones.
  915. $absolute = false;
  916. $path_prefix = '.';
  917. }
  918. }
  919. // Remove any repeated slashes
  920. $path = preg_replace('#/{2,}#', '/', $path);
  921. // Remove the slashes from the start and end of the path
  922. $path = trim($path, '/');
  923. // Break the string into little bits for us to nibble on
  924. $bits = explode('/', $path);
  925. // Remove any . in the path, renumber array for the loop below
  926. $bits = array_values(array_diff($bits, array('.')));
  927. // Lets get looping, run over and resolve any .. (up directory)
  928. for ($i = 0, $max = sizeof($bits); $i < $max; $i++)
  929. {
  930. // @todo Optimise
  931. if ($bits[$i] == '..' )
  932. {
  933. if (isset($bits[$i - 1]))
  934. {
  935. if ($bits[$i - 1] != '..')
  936. {
  937. // We found a .. and we are able to traverse upwards, lets do it!
  938. unset($bits[$i]);
  939. unset($bits[$i - 1]);
  940. $i -= 2;
  941. $max -= 2;
  942. $bits = array_values($bits);
  943. }
  944. }
  945. else if ($absolute) // ie. !isset($bits[$i - 1]) && $absolute
  946. {
  947. // We have an absolute path trying to descend above the root of the filesystem
  948. // ... Error!
  949. return false;
  950. }
  951. }
  952. }
  953. // Prepend the path prefix
  954. array_unshift($bits, $path_prefix);
  955. $resolved = '';
  956. $max = sizeof($bits) - 1;
  957. // Check if we are able to resolve symlinks, Windows cannot.
  958. $symlink_resolve = (function_exists('readlink')) ? true : false;
  959. foreach ($bits as $i => $bit)
  960. {
  961. if (@is_dir("$resolved/$bit") || ($i == $max && @is_file("$resolved/$bit")))
  962. {
  963. // Path Exists
  964. if ($symlink_resolve && is_link("$resolved/$bit") && ($link = readlink("$resolved/$bit")))
  965. {
  966. // Resolved a symlink.
  967. $resolved = $link . (($i == $max) ? '' : '/');
  968. continue;
  969. }
  970. }
  971. else
  972. {
  973. // Something doesn't exist here!
  974. // This is correct realpath() behaviour but sadly open_basedir and safe_mode make this problematic
  975. // return false;
  976. }
  977. $resolved .= $bit . (($i == $max) ? '' : '/');
  978. }
  979. // @todo If the file exists fine and open_basedir only has one path we should be able to prepend it
  980. // because we must be inside that basedir, the question is where...
  981. // @internal The slash in is_dir() gets around an open_basedir restriction
  982. if (!@file_exists($resolved) || (!@is_dir($resolved . '/') && !is_file($resolved)))
  983. {
  984. return false;
  985. }
  986. // Put the slashes back to the native operating systems slashes
  987. $resolved = str_replace('/', DIRECTORY_SEPARATOR, $resolved);
  988. // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
  989. if (substr($resolved, -1) == DIRECTORY_SEPARATOR)
  990. {
  991. return substr($resolved, 0, -1);
  992. }
  993. return $resolved; // We got here, in the end!
  994. }
  995. if (!function_exists('realpath'))
  996. {
  997. /**
  998. * A wrapper for realpath
  999. * @ignore
  1000. */
  1001. function phpbb_realpath($path)
  1002. {
  1003. return phpbb_own_realpath($path);
  1004. }
  1005. }
  1006. else
  1007. {
  1008. /**
  1009. * A wrapper for realpath
  1010. */
  1011. function phpbb_realpath($path)
  1012. {
  1013. $realpath = realpath($path);
  1014. // Strangely there are provider not disabling realpath but returning strange values. :o
  1015. // We at least try to cope with them.
  1016. if ($realpath === $path || $realpath === false)
  1017. {
  1018. return phpbb_own_realpath($path);
  1019. }
  1020. // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
  1021. if (substr($realpath, -1) == DIRECTORY_SEPARATOR)
  1022. {
  1023. $realpath = substr($realpath, 0, -1);
  1024. }
  1025. return $realpath;
  1026. }
  1027. }
  1028. if (!function_exists('htmlspecialchars_decode'))
  1029. {
  1030. /**
  1031. * A wrapper for htmlspecialchars_decode
  1032. * @ignore
  1033. */
  1034. function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
  1035. {
  1036. return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
  1037. }
  1038. }
  1039. // functions used for building option fields
  1040. /**
  1041. * Pick a language, any language ...
  1042. */
  1043. function language_select($default = '')
  1044. {
  1045. global $db;
  1046. $sql = 'SELECT lang_iso, lang_local_name
  1047. FROM ' . LANG_TABLE . '
  1048. ORDER BY lang_english_name';
  1049. $result = $db->sql_query($sql);
  1050. $lang_options = '';
  1051. while ($row = $db->sql_fetchrow($result))
  1052. {
  1053. $selected = ($row['lang_iso'] == $default) ? ' selected="selected"' : '';
  1054. $lang_options .= '<option value="' . $row['lang_iso'] . '"' . $selected . '>' . $row['lang_local_name'] . '</option>';
  1055. }
  1056. $db->sql_freeresult($result);
  1057. return $lang_options;
  1058. }
  1059. /**
  1060. * Pick a template/theme combo,
  1061. */
  1062. function style_select($default = '', $all = false)
  1063. {
  1064. global $db;
  1065. $sql_where = (!$all) ? 'WHERE style_active = 1 ' : '';
  1066. $sql = 'SELECT style_id, style_name
  1067. FROM ' . STYLES_TABLE . "
  1068. $sql_where
  1069. ORDER BY style_name";
  1070. $result = $db->sql_query($sql);
  1071. $style_options = '';
  1072. while ($row = $db->sql_fetchrow($result))
  1073. {
  1074. $selected = ($row['style_id'] == $default) ? ' selected="selected"' : '';
  1075. $style_options .= '<option value="' . $row['style_id'] . '"' . $selected . '>' . $row['style_name'] . '</option>';
  1076. }
  1077. $db->sql_freeresult($result);
  1078. return $style_options;
  1079. }
  1080. /**
  1081. * Pick a timezone
  1082. */
  1083. function tz_select($default = '', $truncate = false)
  1084. {
  1085. global $user;
  1086. $tz_select = '';
  1087. foreach ($user->lang['tz_zones'] as $offset => $zone)
  1088. {
  1089. if ($truncate)
  1090. {
  1091. $zone_trunc = truncate_string($zone, 50, 255, false, '...');
  1092. }
  1093. else
  1094. {
  1095. $zone_trunc = $zone;
  1096. }
  1097. if (is_numeric($offset))
  1098. {
  1099. $selected = ($offset == $default) ? ' selected="selected"' : '';
  1100. $tz_select .= '<option title="' . $zone . '" value="' . $offset . '"' . $selected . '>' . $zone_trunc . '</option>';
  1101. }
  1102. }
  1103. return $tz_select;
  1104. }
  1105. // Functions handling topic/post tracking/marking
  1106. /**
  1107. * Marks a topic/forum as read
  1108. * Marks a topic as posted to
  1109. *
  1110. * @param int $user_id can only be used with $mode == 'post'
  1111. */
  1112. function markread($mode, $forum_id = false, $topic_id = false, $post_time = 0, $user_id = 0)
  1113. {
  1114. global $db, $user, $config;
  1115. if ($mode == 'all')
  1116. {
  1117. if ($forum_id === false || !sizeof($forum_id))
  1118. {
  1119. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1120. {
  1121. // Mark all forums read (index page)
  1122. $db->sql_query('DELETE FROM ' . TOPICS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
  1123. $db->sql_query('DELETE FROM ' . FORUMS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
  1124. $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
  1125. }
  1126. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1127. {
  1128. $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1129. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1130. unset($tracking_topics['tf']);
  1131. unset($tracking_topics['t']);
  1132. unset($tracking_topics['f']);
  1133. $tracking_topics['l'] = base_convert(time() - $config['board_startdate'], 10, 36);
  1134. $user->set_cookie('track', tracking_serialize($tracking_topics), time() + 31536000);
  1135. $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking_topics)) : tracking_serialize($tracking_topics);
  1136. unset($tracking_topics);
  1137. if ($user->data['is_registered'])
  1138. {
  1139. $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
  1140. }
  1141. }
  1142. }
  1143. return;
  1144. }
  1145. else if ($mode == 'topics')
  1146. {
  1147. // Mark all topics in forums read
  1148. if (!is_array($forum_id))
  1149. {
  1150. $forum_id = array($forum_id);
  1151. }
  1152. // Add 0 to forums array to mark global announcements correctly
  1153. // $forum_id[] = 0;
  1154. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1155. {
  1156. $sql = 'DELETE FROM ' . TOPICS_TRACK_TABLE . "
  1157. WHERE user_id = {$user->data['user_id']}
  1158. AND " . $db->sql_in_set('forum_id', $forum_id);
  1159. $db->sql_query($sql);
  1160. $sql = 'SELECT forum_id
  1161. FROM ' . FORUMS_TRACK_TABLE . "
  1162. WHERE user_id = {$user->data['user_id']}
  1163. AND " . $db->sql_in_set('forum_id', $forum_id);
  1164. $result = $db->sql_query($sql);
  1165. $sql_update = array();
  1166. while ($row = $db->sql_fetchrow($result))
  1167. {
  1168. $sql_update[] = (int) $row['forum_id'];
  1169. }
  1170. $db->sql_freeresult($result);
  1171. if (sizeof($sql_update))
  1172. {
  1173. $sql = 'UPDATE ' . FORUMS_TRACK_TABLE . '
  1174. SET mark_time = ' . time() . "
  1175. WHERE user_id = {$user->data['user_id']}
  1176. AND " . $db->sql_in_set('forum_id', $sql_update);
  1177. $db->sql_query($sql);
  1178. }
  1179. if ($sql_insert = array_diff($forum_id, $sql_update))
  1180. {
  1181. $sql_ary = array();
  1182. foreach ($sql_insert as $f_id)
  1183. {
  1184. $sql_ary[] = array(
  1185. 'user_id' => (int) $user->data['user_id'],
  1186. 'forum_id' => (int) $f_id,
  1187. 'mark_time' => time()
  1188. );
  1189. }
  1190. $db->sql_multi_insert(FORUMS_TRACK_TABLE, $sql_ary);
  1191. }
  1192. }
  1193. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1194. {
  1195. $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1196. $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
  1197. foreach ($forum_id as $f_id)
  1198. {
  1199. $topic_ids36 = (isset($tracking['tf'][$f_id])) ? $tracking['tf'][$f_id] : array();
  1200. if (isset($tracking['tf'][$f_id]))
  1201. {
  1202. unset($tracking['tf'][$f_id]);
  1203. }
  1204. foreach ($topic_ids36 as $topic_id36)
  1205. {
  1206. unset($tracking['t'][$topic_id36]);
  1207. }
  1208. if (isset($tracking['f'][$f_id]))
  1209. {
  1210. unset($tracking['f'][$f_id]);
  1211. }
  1212. $tracking['f'][$f_id] = base_convert(time() - $config['board_startdate'], 10, 36);
  1213. }
  1214. if (isset($tracking['tf']) && empty($tracking['tf']))
  1215. {
  1216. unset($tracking['tf']);
  1217. }
  1218. $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
  1219. $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
  1220. unset($tracking);
  1221. }
  1222. return;
  1223. }
  1224. else if ($mode == 'topic')
  1225. {
  1226. if ($topic_id === false || $forum_id === false)
  1227. {
  1228. return;
  1229. }
  1230. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1231. {
  1232. $sql = 'UPDATE ' . TOPICS_TRACK_TABLE . '
  1233. SET mark_time = ' . (($post_time) ? $post_time : time()) . "
  1234. WHERE user_id = {$user->data['user_id']}
  1235. AND topic_id = $topic_id";
  1236. $db->sql_query($sql);
  1237. // insert row
  1238. if (!$db->sql_affectedrows())
  1239. {
  1240. $db->sql_return_on_error(true);
  1241. $sql_ary = array(
  1242. 'user_id' => (int) $user->data['user_id'],
  1243. 'topic_id' => (int) $topic_id,
  1244. 'forum_id' => (int) $forum_id,
  1245. 'mark_time' => ($post_time) ? (int) $post_time : time(),
  1246. );
  1247. $db->sql_query('INSERT INTO ' . TOPICS_TRACK_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  1248. $db->sql_return_on_error(false);
  1249. }
  1250. }
  1251. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1252. {
  1253. $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1254. $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
  1255. $topic_id36 = base_convert($topic_id, 10, 36);
  1256. if (!isset($tracking['t'][$topic_id36]))
  1257. {
  1258. $tracking['tf'][$forum_id][$topic_id36] = true;
  1259. }
  1260. $post_time = ($post_time) ? $post_time : time();
  1261. $tracking['t'][$topic_id36] = base_convert($post_time - $config['board_startdate'], 10, 36);
  1262. // If the cookie grows larger than 10000 characters we will remove the smallest value
  1263. // This can result in old topics being unread - but most of the time it should be accurate...
  1264. if (isset($_COOKIE[$config['cookie_name'] . '_track']) && strlen($_COOKIE[$config['cookie_name'] . '_track']) > 10000)
  1265. {
  1266. //echo 'Cookie grown too large' . print_r($tracking, true);
  1267. // We get the ten most minimum stored time offsets and its associated topic ids
  1268. $time_keys = array();
  1269. for ($i = 0; $i < 10 && sizeof($tracking['t']); $i++)
  1270. {
  1271. $min_value = min($tracking['t']);
  1272. $m_tkey = array_search($min_value, $tracking['t']);
  1273. unset($tracking['t'][$m_tkey]);
  1274. $time_keys[$m_tkey] = $min_value;
  1275. }
  1276. // Now remove the topic ids from the array...
  1277. foreach ($tracking['tf'] as $f_id => $topic_id_ary)
  1278. {
  1279. foreach ($time_keys as $m_tkey => $min_value)
  1280. {
  1281. if (isset($topic_id_ary[$m_tkey]))
  1282. {
  1283. $tracking['f'][$f_id] = $min_value;
  1284. unset($tracking['tf'][$f_id][$m_tkey]);
  1285. }
  1286. }
  1287. }
  1288. if ($user->data['is_registered'])
  1289. {
  1290. $user->data['user_lastmark'] = intval(base_convert(max($time_keys) + $config['board_startdate'], 36, 10));
  1291. $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . $user->data['user_lastmark'] . " WHERE user_id = {$user->data['user_id']}");
  1292. }
  1293. else
  1294. {
  1295. $tracking['l'] = max($time_keys);
  1296. }
  1297. }
  1298. $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
  1299. $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
  1300. }
  1301. return;
  1302. }
  1303. else if ($mode == 'post')
  1304. {
  1305. if ($topic_id === false)
  1306. {
  1307. return;
  1308. }
  1309. $use_user_id = (!$user_id) ? $user->data['user_id'] : $user_id;
  1310. if ($config['load_db_track'] && $use_user_id != ANONYMOUS)
  1311. {
  1312. $db->sql_return_on_error(true);
  1313. $sql_ary = array(
  1314. 'user_id' => (int) $use_user_id,
  1315. 'topic_id' => (int) $topic_id,
  1316. 'topic_posted' => 1
  1317. );
  1318. $db->sql_query('INSERT INTO ' . TOPICS_POSTED_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  1319. $db->sql_return_on_error(false);
  1320. }
  1321. return;
  1322. }
  1323. }
  1324. /**
  1325. * Get topic tracking info by using already fetched info
  1326. */
  1327. function get_topic_tracking($forum_id, $topic_ids, &$rowset, $forum_mark_time, $global_announce_list = false)
  1328. {
  1329. global $config, $user;
  1330. $last_read = array();
  1331. if (!is_array($topic_ids))
  1332. {
  1333. $topic_ids = array($topic_ids);
  1334. }
  1335. foreach ($topic_ids as $topic_id)
  1336. {
  1337. if (!empty($rowset[$topic_id]['mark_time']))
  1338. {
  1339. $last_read[$topic_id] = $rowset[$topic_id]['mark_time'];
  1340. }
  1341. }
  1342. $topic_ids = array_diff($topic_ids, array_keys($last_read));
  1343. if (sizeof($topic_ids))
  1344. {
  1345. $mark_time = array();
  1346. // Get global announcement info
  1347. if ($global_announce_list && sizeof($global_announce_list))
  1348. {
  1349. if (!isset($forum_mark_time[0]))
  1350. {
  1351. global $db;
  1352. $sql = 'SELECT mark_time
  1353. FROM ' . FORUMS_TRACK_TABLE . "
  1354. WHERE user_id = {$user->data['user_id']}
  1355. AND forum_id = 0";
  1356. $result = $db->sql_query($sql);
  1357. $row = $db->sql_fetchrow($result);
  1358. $db->sql_freeresult($result);
  1359. if ($row)
  1360. {
  1361. $mark_time[0] = $row['mark_time'];
  1362. }
  1363. }
  1364. else
  1365. {
  1366. if ($forum_mark_time[0] !== false)
  1367. {
  1368. $mark_time[0] = $forum_mark_time[0];
  1369. }
  1370. }
  1371. }
  1372. if (!empty($forum_mark_time[$forum_id]) && $forum_mark_time[$forum_id] !== false)
  1373. {
  1374. $mark_time[$forum_id] = $forum_mark_time[$forum_id];
  1375. }
  1376. $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
  1377. foreach ($topic_ids as $topic_id)
  1378. {
  1379. if ($global_announce_list && isset($global_announce_list[$topic_id]))
  1380. {
  1381. $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
  1382. }
  1383. else
  1384. {
  1385. $last_read[$topic_id] = $user_lastmark;
  1386. }
  1387. }
  1388. }
  1389. return $last_read;
  1390. }
  1391. /**
  1392. * Get topic tracking info from db (for cookie based tracking only this function is used)
  1393. */
  1394. function get_complete_topic_tracking($forum_id, $topic_ids, $global_announce_list = false)
  1395. {
  1396. global $config, $user;
  1397. $last_read = array();
  1398. if (!is_array($topic_ids))
  1399. {
  1400. $topic_ids = array($topic_ids);
  1401. }
  1402. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1403. {
  1404. global $db;
  1405. $sql = 'SELECT topic_id, mark_time
  1406. FROM ' . TOPICS_TRACK_TABLE . "
  1407. WHERE user_id = {$user->data['user_id']}
  1408. AND " . $db->sql_in_set('topic_id', $topic_ids);
  1409. $result = $db->sql_query($sql);
  1410. while ($row = $db->sql_fetchrow($result))
  1411. {
  1412. $last_read[$row['topic_id']] = $row['mark_time'];
  1413. }
  1414. $db->sql_freeresult($result);
  1415. $topic_ids = array_diff($topic_ids, array_keys($last_read));
  1416. if (sizeof($topic_ids))
  1417. {
  1418. $sql = 'SELECT forum_id, mark_time
  1419. FROM ' . FORUMS_TRACK_TABLE . "
  1420. WHERE user_id = {$user->data['user_id']}
  1421. AND forum_id " .
  1422. (($global_announce_list && sizeof($global_announce_list)) ? "IN (0, $forum_id)" : "= $forum_id");
  1423. $result = $db->sql_query($sql);
  1424. $mark_time = array();
  1425. while ($row = $db->sql_fetchrow($result))
  1426. {
  1427. $mark_time[$row['forum_id']] = $row['mark_time'];
  1428. }
  1429. $db->sql_freeresult($result);
  1430. $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
  1431. foreach ($topic_ids as $topic_id)
  1432. {
  1433. if ($global_announce_list && isset($global_announce_list[$topic_id]))
  1434. {
  1435. $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
  1436. }
  1437. else
  1438. {
  1439. $last_read[$topic_id] = $user_lastmark;
  1440. }
  1441. }
  1442. }
  1443. }
  1444. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1445. {
  1446. global $tracking_topics;
  1447. if (!isset($tracking_topics) || !sizeof($tracking_topics))
  1448. {
  1449. $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1450. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1451. }
  1452. if (!$user->data['is_registered'])
  1453. {
  1454. $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
  1455. }
  1456. else
  1457. {
  1458. $user_lastmark = $user->data['user_lastmark'];
  1459. }
  1460. foreach ($topic_ids as $topic_id)
  1461. {
  1462. $topic_id36 = base_convert($topic_id, 10, 36);
  1463. if (isset($tracking_topics['t'][$topic_id36]))
  1464. {
  1465. $last_read[$topic_id] = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
  1466. }
  1467. }
  1468. $topic_ids = array_diff($topic_ids, array_keys($last_read));
  1469. if (sizeof($topic_ids))
  1470. {
  1471. $mark_time = array();
  1472. if ($global_announce_list && sizeof($global_announce_list))
  1473. {
  1474. if (isset($tracking_topics['f'][0]))
  1475. {
  1476. $mark_time[0] = base_convert($tracking_topics['f'][0], 36, 10) + $config['board_startdate'];
  1477. }
  1478. }
  1479. if (isset($tracking_topics['f'][$forum_id]))
  1480. {
  1481. $mark_time[$forum_id] = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
  1482. }
  1483. $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user_lastmark;
  1484. foreach ($topic_ids as $topic_id)
  1485. {
  1486. if ($global_announce_list && isset($global_announce_list[$topic_id]))
  1487. {
  1488. $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
  1489. }
  1490. else
  1491. {
  1492. $last_read[$topic_id] = $user_lastmark;
  1493. }
  1494. }
  1495. }
  1496. }
  1497. return $last_read;
  1498. }
  1499. /**
  1500. * Get list of unread topics
  1501. *
  1502. * @param int $user_id User ID (or false for current user)
  1503. * @param string $sql_extra Extra WHERE SQL statement
  1504. * @param string $sql_sort ORDER BY SQL sorting statement
  1505. * @param string $sql_limit Limits the size of unread topics list, 0 for unlimited query
  1506. * @param string $sql_limit_offset Sets the offset of the first row to search, 0 to search from the start
  1507. *
  1508. * @return array[int][int] Topic ids as keys, mark_time of topic as value
  1509. */
  1510. function get_unread_topics($user_id = false, $sql_extra = '', $sql_sort = '', $sql_limit = 1001, $sql_limit_offset = 0)
  1511. {
  1512. global $config, $db, $user;
  1513. $user_id = ($user_id === false) ? (int) $user->data['user_id'] : (int) $user_id;
  1514. // Data array we're going to return
  1515. $unread_topics = array();
  1516. if (empty($sql_sort))
  1517. {
  1518. $sql_sort = 'ORDER BY t.topic_last_post_time DESC';
  1519. }
  1520. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1521. {
  1522. // Get list of the unread topics
  1523. $last_mark = (int) $user->data['user_lastmark'];
  1524. $sql_array = array(
  1525. 'SELECT' => 't.topic_id, t.topic_last_post_time, tt.mark_time as topic_mark_time, ft.mark_time as forum_mark_time',
  1526. 'FROM' => array(TOPICS_TABLE => 't'),
  1527. 'LEFT_JOIN' => array(
  1528. array(
  1529. 'FROM' => array(TOPICS_TRACK_TABLE => 'tt'),
  1530. 'ON' => "tt.user_id = $user_id AND t.topic_id = tt.topic_id",
  1531. ),
  1532. array(
  1533. 'FROM' => array(FORUMS_TRACK_TABLE => 'ft'),
  1534. 'ON' => "ft.user_id = $user_id AND t.forum_id = ft.forum_id",
  1535. ),
  1536. ),
  1537. 'WHERE' => "
  1538. t.topic_last_post_time > $last_mark AND
  1539. (
  1540. (tt.mark_time IS NOT NULL AND t.topic_last_post_time > tt.mark_time) OR
  1541. (tt.mark_time IS NULL AND ft.mark_time IS NOT NULL AND t.topic_last_post_time > ft.mark_time) OR
  1542. (tt.mark_time IS NULL AND ft.mark_time IS NULL)
  1543. )
  1544. $sql_extra
  1545. $sql_sort",
  1546. );
  1547. $sql = $db->sql_build_query('SELECT', $sql_array);
  1548. $result = $db->sql_query_limit($sql, $sql_limit, $sql_limit_offset);
  1549. while ($row = $db->sql_fetchrow($result))
  1550. {
  1551. $topic_id = (int) $row['topic_id'];
  1552. $unread_topics[$topic_id] = ($row['topic_mark_time']) ? (int) $row['topic_mark_time'] : (($row['forum_mark_time']) ? (int) $row['forum_mark_time'] : $last_mark);
  1553. }
  1554. $db->sql_freeresult($result);
  1555. }
  1556. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1557. {
  1558. global $tracking_topics;
  1559. if (empty($tracking_topics))
  1560. {
  1561. $tracking_topics = request_var($config['cookie_name'] . '_track', '', false, true);
  1562. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1563. }
  1564. if (!$user->data['is_registered'])
  1565. {
  1566. $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
  1567. }
  1568. else
  1569. {
  1570. $user_lastmark = (int) $user->data['user_lastmark'];
  1571. }
  1572. $sql = 'SELECT t.topic_id, t.forum_id, t.topic_last_post_time
  1573. FROM ' . TOPICS_TABLE . ' t
  1574. WHERE t.topic_last_post_time > ' . $user_lastmark . "
  1575. $sql_extra
  1576. $sql_sort";
  1577. $result = $db->sql_query_limit($sql, $sql_limit, $sql_limit_offset);
  1578. while ($row = $db->sql_fetchrow($result))
  1579. {
  1580. $forum_id = (int) $row['forum_id'];
  1581. $topic_id = (int) $row['topic_id'];
  1582. $topic_id36 = base_convert($topic_id, 10, 36);
  1583. if (isset($tracking_topics['t'][$topic_id36]))
  1584. {
  1585. $last_read = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
  1586. if ($row['topic_last_post_time'] > $last_read)
  1587. {
  1588. $unread_topics[$topic_id] = $last_read;
  1589. }
  1590. }
  1591. else if (isset($tracking_topics['f'][$forum_id]))
  1592. {
  1593. $mark_time = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
  1594. if ($row['topic_last_post_time'] > $mark_time)
  1595. {
  1596. $unread_topics[$topic_id] = $mark_time;
  1597. }
  1598. }
  1599. else
  1600. {
  1601. $unread_topics[$topic_id] = $user_lastmark;
  1602. }
  1603. }
  1604. $db->sql_freeresult($result);
  1605. }
  1606. return $unread_topics;
  1607. }
  1608. /**
  1609. * Check for read forums and update topic tracking info accordingly
  1610. *
  1611. * @param int $forum_id the forum id to check
  1612. * @param int $forum_last_post_time the forums last post time
  1613. * @param int $f_mark_time the forums last mark time if user is registered and load_db_lastread enabled
  1614. * @param int $mark_time_forum false if the mark time needs to be obtained, else the last users forum mark time
  1615. *
  1616. * @return true if complete forum got marked read, else false.
  1617. */
  1618. function update_forum_tracking_info($forum_id, $forum_last_post_time, $f_mark_time = false, $mark_time_forum = false)
  1619. {
  1620. global $db, $tracking_topics, $user, $config, $auth;
  1621. // Determine the users last forum mark time if not given.
  1622. if ($mark_time_forum === false)
  1623. {
  1624. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1625. {
  1626. $mark_time_forum = (!empty($f_mark_time)) ? $f_mark_time : $user->data['user_lastmark'];
  1627. }
  1628. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1629. {
  1630. $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1631. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1632. if (!$user->data['is_registered'])
  1633. {
  1634. $user->data['user_lastmark'] = (isset($tracking_topics['l'])) ? (int) (base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate']) : 0;
  1635. }
  1636. $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'];
  1637. }
  1638. }
  1639. // Handle update of unapproved topics info.
  1640. // Only update for moderators having m_approve permission for the forum.
  1641. $sql_update_unapproved = ($auth->acl_get('m_approve', $forum_id)) ? '': 'AND t.topic_approved = 1';
  1642. // Check the forum for any left unread topics.
  1643. // If there are none, we mark the forum as read.
  1644. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1645. {
  1646. if ($mark_time_forum >= $forum_last_post_time)
  1647. {
  1648. // We do not need to mark read, this happened before. Therefore setting this to true
  1649. $row = true;
  1650. }
  1651. else
  1652. {
  1653. $sql = 'SELECT t.forum_id FROM ' . TOPICS_TABLE . ' t
  1654. LEFT JOIN ' . TOPICS_TRACK_TABLE . ' tt ON (tt.topic_id = t.topic_id AND tt.user_id = ' . $user->data['user_id'] . ')
  1655. WHERE t.forum_id = ' . $forum_id . '
  1656. AND t.topic_last_post_time > ' . $mark_time_forum . '
  1657. AND t.topic_moved_id = 0 ' .
  1658. $sql_update_unapproved . '
  1659. AND (tt.topic_id IS NULL OR tt.mark_time < t.topic_last_post_time)
  1660. GROUP BY t.forum_id';
  1661. $result = $db->sql_query_limit($sql, 1);
  1662. $row = $db->sql_fetchrow($result);
  1663. $db->sql_freeresult($result);
  1664. }
  1665. }
  1666. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1667. {
  1668. // Get information from cookie
  1669. $row = false;
  1670. if (!isset($tracking_topics['tf'][$forum_id]))
  1671. {
  1672. // We do not need to mark read, this happened before. Therefore setting this to true
  1673. $row = true;
  1674. }
  1675. else
  1676. {
  1677. $sql = 'SELECT t.topic_id
  1678. FROM ' . TOPICS_TABLE . ' t
  1679. WHERE t.forum_id = ' . $forum_id . '
  1680. AND t.topic_last_post_time > ' . $mark_time_forum . '
  1681. AND t.topic_moved_id = 0 ' .
  1682. $sql_update_unapproved;
  1683. $result = $db->sql_query($sql);
  1684. $check_forum = $tracking_topics['tf'][$forum_id];
  1685. $unread = false;
  1686. while ($row = $db->sql_fetchrow($result))
  1687. {
  1688. if (!isset($check_forum[base_convert($row['topic_id'], 10, 36)]))
  1689. {
  1690. $unread = true;
  1691. break;
  1692. }
  1693. }
  1694. $db->sql_freeresult($result);
  1695. $row = $unread;
  1696. }
  1697. }
  1698. else
  1699. {
  1700. $row = true;
  1701. }
  1702. if (!$row)
  1703. {
  1704. markread('topics', $forum_id);
  1705. return true;
  1706. }
  1707. return false;
  1708. }
  1709. /**
  1710. * Transform an array into a serialized format
  1711. */
  1712. function tracking_serialize($input)
  1713. {
  1714. $out = '';
  1715. foreach ($input as $key => $value)
  1716. {
  1717. if (is_array($value))
  1718. {
  1719. $out .= $key . ':(' . tracking_serialize($value) . ');';
  1720. }
  1721. else
  1722. {
  1723. $out .= $key . ':' . $value . ';';
  1724. }
  1725. }
  1726. return $out;
  1727. }
  1728. /**
  1729. * Transform a serialized array into an actual array
  1730. */
  1731. function tracking_unserialize($string, $max_depth = 3)
  1732. {
  1733. $n = strlen($string);
  1734. if ($n > 10010)
  1735. {
  1736. die('Invalid data supplied');
  1737. }
  1738. $data = $stack = array();
  1739. $key = '';
  1740. $mode = 0;
  1741. $level = &$data;
  1742. for ($i = 0; $i < $n; ++$i)
  1743. {
  1744. switch ($mode)
  1745. {
  1746. case 0:
  1747. switch ($string[$i])
  1748. {
  1749. case ':':
  1750. $level[$key] = 0;
  1751. $mode = 1;
  1752. break;
  1753. case ')':
  1754. unset($level);
  1755. $level = array_pop($stack);
  1756. $mode = 3;
  1757. break;
  1758. default:
  1759. $key .= $string[$i];
  1760. }
  1761. break;
  1762. case 1:
  1763. switch ($string[$i])
  1764. {
  1765. case '(':
  1766. if (sizeof($stack) >= $max_depth)
  1767. {
  1768. die('Invalid data supplied');
  1769. }
  1770. $stack[] = &$level;
  1771. $level[$key] = array();
  1772. $level = &$level[$key];
  1773. $key = '';
  1774. $mode = 0;
  1775. break;
  1776. default:
  1777. $level[$key] = $string[$i];
  1778. $mode = 2;
  1779. break;
  1780. }
  1781. break;
  1782. case 2:
  1783. switch ($string[$i])
  1784. {
  1785. case ')':
  1786. unset($level);
  1787. $level = array_pop($stack);
  1788. $mode = 3;
  1789. break;
  1790. case ';':
  1791. $key = '';
  1792. $mode = 0;
  1793. break;
  1794. default:
  1795. $level[$key] .= $string[$i];
  1796. break;
  1797. }
  1798. break;
  1799. case 3:
  1800. switch ($string[$i])
  1801. {
  1802. case ')':
  1803. unset($level);
  1804. $level = array_pop($stack);
  1805. break;
  1806. case ';':
  1807. $key = '';
  1808. $mode = 0;
  1809. break;
  1810. default:
  1811. die('Invalid data supplied');
  1812. break;
  1813. }
  1814. break;
  1815. }
  1816. }
  1817. if (sizeof($stack) != 0 || ($mode != 0 && $mode != 3))
  1818. {
  1819. die('Invalid data supplied');
  1820. }
  1821. return $level;
  1822. }
  1823. // Pagination functions
  1824. /**
  1825. * Pagination routine, generates page number sequence
  1826. * tpl_prefix is for using different pagination blocks at one page
  1827. */
  1828. function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = false, $tpl_prefix = '')
  1829. {
  1830. global $template, $user;
  1831. // Make sure $per_page is a valid value
  1832. $per_page = ($per_page <= 0) ? 1 : $per_page;
  1833. $seperator = '<span class="page-sep">' . $user->lang['COMMA_SEPARATOR'] . '</span>';
  1834. $total_pages = ceil($num_items / $per_page);
  1835. if ($total_pages == 1 || !$num_items)
  1836. {
  1837. return false;
  1838. }
  1839. $on_page = floor($start_item / $per_page) + 1;
  1840. $url_delim = (strpos($base_url, '?') === false) ? '?' : ((strpos($base_url, '?') === strlen($base_url) - 1) ? '' : '&amp;');
  1841. $page_string = ($on_page == 1) ? '<strong>1</strong>' : '<a href="' . $base_url . '">1</a>';
  1842. if ($total_pages > 5)
  1843. {
  1844. $start_cnt = min(max(1, $on_page - 4), $total_pages - 5);
  1845. $end_cnt = max(min($total_pages, $on_page + 4), 6);
  1846. $page_string .= ($start_cnt > 1) ? '<span class="page-dots"> ... </span>' : $seperator;
  1847. for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
  1848. {
  1849. $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
  1850. if ($i < $end_cnt - 1)
  1851. {
  1852. $page_string .= $seperator;
  1853. }
  1854. }
  1855. $page_string .= ($end_cnt < $total_pages) ? '<span class="page-dots"> ... </span>' : $seperator;
  1856. }
  1857. else
  1858. {
  1859. $page_string .= $seperator;
  1860. for ($i = 2; $i < $total_pages; $i++)
  1861. {
  1862. $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
  1863. if ($i < $total_pages)
  1864. {
  1865. $page_string .= $seperator;
  1866. }
  1867. }
  1868. }
  1869. $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>';
  1870. if ($add_prevnext_text)
  1871. {
  1872. if ($on_page != 1)
  1873. {
  1874. $page_string = '<a href="' . $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page) . '">' . $user->lang['PREVIOUS'] . '</a>&nbsp;&nbsp;' . $page_string;
  1875. }
  1876. if ($on_page != $total_pages)
  1877. {
  1878. $page_string .= '&nbsp;&nbsp;<a href="' . $base_url . "{$url_delim}start=" . ($on_page * $per_page) . '">' . $user->lang['NEXT'] . '</a>';
  1879. }
  1880. }
  1881. $template->assign_vars(array(
  1882. $tpl_prefix . 'BASE_URL' => $base_url,
  1883. 'A_' . $tpl_prefix . 'BASE_URL' => addslashes($base_url),
  1884. $tpl_prefix . 'PER_PAGE' => $per_page,
  1885. $tpl_prefix . 'PREVIOUS_PAGE' => ($on_page == 1) ? '' : $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page),
  1886. $tpl_prefix . 'NEXT_PAGE' => ($on_page == $total_pages) ? '' : $base_url . "{$url_delim}start=" . ($on_page * $per_page),
  1887. $tpl_prefix . 'TOTAL_PAGES' => $total_pages,
  1888. ));
  1889. return $page_string;
  1890. }
  1891. /**
  1892. * Return current page (pagination)
  1893. */
  1894. function on_page($num_items, $per_page, $start)
  1895. {
  1896. global $template, $user;
  1897. // Make sure $per_page is a valid value
  1898. $per_page = ($per_page <= 0) ? 1 : $per_page;
  1899. $on_page = floor($start / $per_page) + 1;
  1900. $template->assign_vars(array(
  1901. 'ON_PAGE' => $on_page)
  1902. );
  1903. return sprintf($user->lang['PAGE_OF'], $on_page, max(ceil($num_items / $per_page), 1));
  1904. }
  1905. // Server functions (building urls, redirecting...)
  1906. /**
  1907. * Append session id to url.
  1908. * This function supports hooks.
  1909. *
  1910. * @param string $url The url the session id needs to be appended to (can have params)
  1911. * @param mixed $params String or array of additional url parameters
  1912. * @param bool $is_amp Is url using &amp; (true) or & (false)
  1913. * @param string $session_id Possibility to use a custom session id instead of the global one
  1914. *
  1915. * Examples:
  1916. * <code>
  1917. * append_sid("{$phpbb_root_path}viewtopic.$phpEx?t=1&amp;f=2");
  1918. * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&amp;f=2');
  1919. * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2', false);
  1920. * append_sid("{$phpbb_root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
  1921. * </code>
  1922. *
  1923. */
  1924. function append_sid($url, $params = false, $is_amp = true, $session_id = false)
  1925. {
  1926. global $_SID, $_EXTRA_URL, $phpbb_hook;
  1927. if ($params === '' || (is_array($params) && empty($params)))
  1928. {
  1929. // Do not append the ? if the param-list is empty anyway.
  1930. $params = false;
  1931. }
  1932. // Developers using the hook function need to globalise the $_SID and $_EXTRA_URL on their own and also handle it appropriately.
  1933. // They could mimic most of what is within this function
  1934. if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__, $url, $params, $is_amp, $session_id))
  1935. {
  1936. if ($phpbb_hook->hook_return(__FUNCTION__))
  1937. {
  1938. return $phpbb_hook->hook_return_result(__FUNCTION__);
  1939. }
  1940. }
  1941. $params_is_array = is_array($params);
  1942. // Get anchor
  1943. $anchor = '';
  1944. if (strpos($url, '#') !== false)
  1945. {
  1946. list($url, $anchor) = explode('#', $url, 2);
  1947. $anchor = '#' . $anchor;
  1948. }
  1949. else if (!$params_is_array && strpos($params, '#') !== false)
  1950. {
  1951. list($params, $anchor) = explode('#', $params, 2);
  1952. $anchor = '#' . $anchor;
  1953. }
  1954. // Handle really simple cases quickly
  1955. if ($_SID == '' && $session_id === false && empty($_EXTRA_URL) && !$params_is_array && !$anchor)
  1956. {
  1957. if ($params === false)
  1958. {
  1959. return $url;
  1960. }
  1961. $url_delim = (strpos($url, '?') === false) ? '?' : (($is_amp) ? '&amp;' : '&');
  1962. return $url . ($params !== false ? $url_delim. $params : '');
  1963. }
  1964. // Assign sid if session id is not specified
  1965. if ($session_id === false)
  1966. {
  1967. $session_id = $_SID;
  1968. }
  1969. $amp_delim = ($is_amp) ? '&amp;' : '&';
  1970. $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
  1971. // Appending custom url parameter?
  1972. $append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';
  1973. // Use the short variant if possible ;)
  1974. if ($params === false)
  1975. {
  1976. // Append session id
  1977. if (!$session_id)
  1978. {
  1979. return $url . (($append_url) ? $url_delim . $append_url : '') . $anchor;
  1980. }
  1981. else
  1982. {
  1983. return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id . $anchor;
  1984. }
  1985. }
  1986. // Build string if parameters are specified as array
  1987. if (is_array($params))
  1988. {
  1989. $output = array();
  1990. foreach ($params as $key => $item)
  1991. {
  1992. if ($item === NULL)
  1993. {
  1994. continue;
  1995. }
  1996. if ($key == '#')
  1997. {
  1998. $anchor = '#' . $item;
  1999. continue;
  2000. }
  2001. $output[] = $key . '=' . $item;
  2002. }
  2003. $params = implode($amp_delim, $output);
  2004. }
  2005. // Append session id and parameters (even if they are empty)
  2006. // If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
  2007. return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
  2008. }
  2009. /**
  2010. * Generate board url (example: http://www.example.com/phpBB)
  2011. *
  2012. * @param bool $without_script_path if set to true the script path gets not appended (example: http://www.example.com)
  2013. *
  2014. * @return string the generated board url
  2015. */
  2016. function generate_board_url($without_script_path = false)
  2017. {
  2018. global $config, $user;
  2019. $server_name = $user->host;
  2020. $server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
  2021. // Forcing server vars is the only way to specify/override the protocol
  2022. if ($config['force_server_vars'] || !$server_name)
  2023. {
  2024. $server_protocol = ($config['server_protocol']) ? $config['server_protocol'] : (($config['cookie_secure']) ? 'https://' : 'http://');
  2025. $server_name = $config['server_name'];
  2026. $server_port = (int) $config['server_port'];
  2027. $script_path = $config['script_path'];
  2028. $url = $server_protocol . $server_name;
  2029. $cookie_secure = $config['cookie_secure'];
  2030. }
  2031. else
  2032. {
  2033. // Do not rely on cookie_secure, users seem to think that it means a secured cookie instead of an encrypted connection
  2034. $cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
  2035. $url = (($cookie_secure) ? 'https://' : 'http://') . $server_name;
  2036. $script_path = $user->page['root_script_path'];
  2037. }
  2038. if ($server_port && (($cookie_secure && $server_port <> 443) || (!$cookie_secure && $server_port <> 80)))
  2039. {
  2040. // HTTP HOST can carry a port number (we fetch $user->host, but for old versions this may be true)
  2041. if (strpos($server_name, ':') === false)
  2042. {
  2043. $url .= ':' . $server_port;
  2044. }
  2045. }
  2046. if (!$without_script_path)
  2047. {
  2048. $url .= $script_path;
  2049. }
  2050. // Strip / from the end
  2051. if (substr($url, -1, 1) == '/')
  2052. {
  2053. $url = substr($url, 0, -1);
  2054. }
  2055. return $url;
  2056. }
  2057. /**
  2058. * Redirects the user to another page then exits the script nicely
  2059. * This function is intended for urls within the board. It's not meant to redirect to cross-domains.
  2060. *
  2061. * @param string $url The url to redirect to
  2062. * @param bool $return If true, do not redirect but return the sanitized URL. Default is no return.
  2063. * @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.
  2064. */
  2065. function redirect($url, $return = false, $disable_cd_check = false)
  2066. {
  2067. global $db, $cache, $config, $user, $phpbb_root_path;
  2068. $failover_flag = false;
  2069. if (empty($user->lang))
  2070. {
  2071. $user->add_lang('common');
  2072. }
  2073. if (!$return)
  2074. {
  2075. garbage_collection();
  2076. }
  2077. // Make sure no &amp;'s are in, this will break the redirect
  2078. $url = str_replace('&amp;', '&', $url);
  2079. // Determine which type of redirect we need to handle...
  2080. $url_parts = @parse_url($url);
  2081. if ($url_parts === false)
  2082. {
  2083. // Malformed url, redirect to current page...
  2084. $url = generate_board_url() . '/' . $user->page['page'];
  2085. }
  2086. else if (!empty($url_parts['scheme']) && !empty($url_parts['host']))
  2087. {
  2088. // Attention: only able to redirect within the same domain if $disable_cd_check is false (yourdomain.com -> www.yourdomain.com will not work)
  2089. if (!$disable_cd_check && $url_parts['host'] !== $user->host)
  2090. {
  2091. $url = generate_board_url();
  2092. }
  2093. }
  2094. else if ($url[0] == '/')
  2095. {
  2096. // Absolute uri, prepend direct url...
  2097. $url = generate_board_url(true) . $url;
  2098. }
  2099. else
  2100. {
  2101. // Relative uri
  2102. $pathinfo = pathinfo($url);
  2103. if (!$disable_cd_check && !file_exists($pathinfo['dirname'] . '/'))
  2104. {
  2105. $url = str_replace('../', '', $url);
  2106. $pathinfo = pathinfo($url);
  2107. if (!file_exists($pathinfo['dirname'] . '/'))
  2108. {
  2109. // fallback to "last known user page"
  2110. // at least this way we know the user does not leave the phpBB root
  2111. $url = generate_board_url() . '/' . $user->page['page'];
  2112. $failover_flag = true;
  2113. }
  2114. }
  2115. if (!$failover_flag)
  2116. {
  2117. // Is the uri pointing to the current directory?
  2118. if ($pathinfo['dirname'] == '.')
  2119. {
  2120. $url = str_replace('./', '', $url);
  2121. // Strip / from the beginning
  2122. if ($url && substr($url, 0, 1) == '/')
  2123. {
  2124. $url = substr($url, 1);
  2125. }
  2126. if ($user->page['page_dir'])
  2127. {
  2128. $url = generate_board_url() . '/' . $user->page['page_dir'] . '/' . $url;
  2129. }
  2130. else
  2131. {
  2132. $url = generate_board_url() . '/' . $url;
  2133. }
  2134. }
  2135. else
  2136. {
  2137. // Used ./ before, but $phpbb_root_path is working better with urls within another root path
  2138. $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($phpbb_root_path)));
  2139. $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($pathinfo['dirname'])));
  2140. $intersection = array_intersect_assoc($root_dirs, $page_dirs);
  2141. $root_dirs = array_diff_assoc($root_dirs, $intersection);
  2142. $page_dirs = array_diff_assoc($page_dirs, $intersection);
  2143. $dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
  2144. // Strip / from the end
  2145. if ($dir && substr($dir, -1, 1) == '/')
  2146. {
  2147. $dir = substr($dir, 0, -1);
  2148. }
  2149. // Strip / from the beginning
  2150. if ($dir && substr($dir, 0, 1) == '/')
  2151. {
  2152. $dir = substr($dir, 1);
  2153. }
  2154. $url = str_replace($pathinfo['dirname'] . '/', '', $url);
  2155. // Strip / from the beginning
  2156. if (substr($url, 0, 1) == '/')
  2157. {
  2158. $url = substr($url, 1);
  2159. }
  2160. $url = (!empty($dir) ? $dir . '/' : '') . $url;
  2161. $url = generate_board_url() . '/' . $url;
  2162. }
  2163. }
  2164. }
  2165. // Make sure no linebreaks are there... to prevent http response splitting for PHP < 4.4.2
  2166. if (strpos(urldecode($url), "\n") !== false || strpos(urldecode($url), "\r") !== false || strpos($url, ';') !== false)
  2167. {
  2168. trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
  2169. }
  2170. // Now, also check the protocol and for a valid url the last time...
  2171. $allowed_protocols = array('http', 'https', 'ftp', 'ftps');
  2172. $url_parts = parse_url($url);
  2173. if ($url_parts === false || empty($url_parts['scheme']) || !in_array($url_parts['scheme'], $allowed_protocols))
  2174. {
  2175. trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
  2176. }
  2177. if ($return)
  2178. {
  2179. return $url;
  2180. }
  2181. // Redirect via an HTML form for PITA webservers
  2182. if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
  2183. {
  2184. header('Refresh: 0; URL=' . $url);
  2185. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  2186. echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="' . $user->lang['DIRECTION'] . '" lang="' . $user->lang['USER_LANG'] . '" xml:lang="' . $user->lang['USER_LANG'] . '">';
  2187. echo '<head>';
  2188. echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
  2189. echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&amp;', $url) . '" />';
  2190. echo '<title>' . $user->lang['REDIRECT'] . '</title>';
  2191. echo '</head>';
  2192. echo '<body>';
  2193. echo '<div style="text-align: center;">' . sprintf($user->lang['URL_REDIRECT'], '<a href="' . str_replace('&', '&amp;', $url) . '">', '</a>') . '</div>';
  2194. echo '</body>';
  2195. echo '</html>';
  2196. exit;
  2197. }
  2198. // Behave as per HTTP/1.1 spec for others
  2199. header('Location: ' . $url);
  2200. exit;
  2201. }
  2202. /**
  2203. * Re-Apply session id after page reloads
  2204. */
  2205. function reapply_sid($url)
  2206. {
  2207. global $phpEx, $phpbb_root_path;
  2208. if ($url === "index.$phpEx")
  2209. {
  2210. return append_sid("index.$phpEx");
  2211. }
  2212. else if ($url === "{$phpbb_root_path}index.$phpEx")
  2213. {
  2214. return append_sid("{$phpbb_root_path}index.$phpEx");
  2215. }
  2216. // Remove previously added sid
  2217. if (strpos($url, 'sid=') !== false)
  2218. {
  2219. // All kind of links
  2220. $url = preg_replace('/(\?)?(&amp;|&)?sid=[a-z0-9]+/', '', $url);
  2221. // if the sid was the first param, make the old second as first ones
  2222. $url = preg_replace("/$phpEx(&amp;|&)+?/", "$phpEx?", $url);
  2223. }
  2224. return append_sid($url);
  2225. }
  2226. /**
  2227. * Returns url from the session/current page with an re-appended SID with optionally stripping vars from the url
  2228. */
  2229. function build_url($strip_vars = false)
  2230. {
  2231. global $user, $phpbb_root_path;
  2232. // Append SID
  2233. $redirect = append_sid($user->page['page'], false, false);
  2234. // Add delimiter if not there...
  2235. if (strpos($redirect, '?') === false)
  2236. {
  2237. $redirect .= '?';
  2238. }
  2239. // Strip vars...
  2240. if ($strip_vars !== false && strpos($redirect, '?') !== false)
  2241. {
  2242. if (!is_array($strip_vars))
  2243. {
  2244. $strip_vars = array($strip_vars);
  2245. }
  2246. $query = $_query = array();
  2247. $args = substr($redirect, strpos($redirect, '?') + 1);
  2248. $args = ($args) ? explode('&', $args) : array();
  2249. $redirect = substr($redirect, 0, strpos($redirect, '?'));
  2250. foreach ($args as $argument)
  2251. {
  2252. $arguments = explode('=', $argument);
  2253. $key = $arguments[0];
  2254. unset($arguments[0]);
  2255. if ($key === '')
  2256. {
  2257. continue;
  2258. }
  2259. $query[$key] = implode('=', $arguments);
  2260. }
  2261. // Strip the vars off
  2262. foreach ($strip_vars as $strip)
  2263. {
  2264. if (isset($query[$strip]))
  2265. {
  2266. unset($query[$strip]);
  2267. }
  2268. }
  2269. // Glue the remaining parts together... already urlencoded
  2270. foreach ($query as $key => $value)
  2271. {
  2272. $_query[] = $key . '=' . $value;
  2273. }
  2274. $query = implode('&', $_query);
  2275. $redirect .= ($query) ? '?' . $query : '';
  2276. }
  2277. // We need to be cautious here.
  2278. // On some situations, the redirect path is an absolute URL, sometimes a relative path
  2279. // For a relative path, let's prefix it with $phpbb_root_path to point to the correct location,
  2280. // else we use the URL directly.
  2281. $url_parts = @parse_url($redirect);
  2282. // URL
  2283. if ($url_parts !== false && !empty($url_parts['scheme']) && !empty($url_parts['host']))
  2284. {
  2285. return str_replace('&', '&amp;', $redirect);
  2286. }
  2287. return $phpbb_root_path . str_replace('&', '&amp;', $redirect);
  2288. }
  2289. /**
  2290. * Meta refresh assignment
  2291. * Adds META template variable with meta http tag.
  2292. *
  2293. * @param int $time Time in seconds for meta refresh tag
  2294. * @param string $url URL to redirect to. The url will go through redirect() first before the template variable is assigned
  2295. * @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.
  2296. */
  2297. function meta_refresh($time, $url, $disable_cd_check = false)
  2298. {
  2299. global $template;
  2300. $url = redirect($url, true, $disable_cd_check);
  2301. $url = str_replace('&', '&amp;', $url);
  2302. // For XHTML compatibility we change back & to &amp;
  2303. $template->assign_vars(array(
  2304. 'META' => '<meta http-equiv="refresh" content="' . $time . ';url=' . $url . '" />')
  2305. );
  2306. return $url;
  2307. }
  2308. /**
  2309. * Outputs correct status line header.
  2310. *
  2311. * Depending on php sapi one of the two following forms is used:
  2312. *
  2313. * Status: 404 Not Found
  2314. *
  2315. * HTTP/1.x 404 Not Found
  2316. *
  2317. * HTTP version is taken from HTTP_VERSION environment variable,
  2318. * and defaults to 1.0.
  2319. *
  2320. * Sample usage:
  2321. *
  2322. * send_status_line(404, 'Not Found');
  2323. *
  2324. * @param int $code HTTP status code
  2325. * @param string $message Message for the status code
  2326. * @return void
  2327. */
  2328. function send_status_line($code, $message)
  2329. {
  2330. if (substr(strtolower(@php_sapi_name()), 0, 3) === 'cgi')
  2331. {
  2332. // in theory, we shouldn't need that due to php doing it. Reality offers a differing opinion, though
  2333. header("Status: $code $message", true, $code);
  2334. }
  2335. else
  2336. {
  2337. if (!empty($_SERVER['SERVER_PROTOCOL']))
  2338. {
  2339. $version = $_SERVER['SERVER_PROTOCOL'];
  2340. }
  2341. else
  2342. {
  2343. $version = 'HTTP/1.0';
  2344. }
  2345. header("$version $code $message", true, $code);
  2346. }
  2347. }
  2348. //Form validation
  2349. /**
  2350. * Add a secret hash for use in links/GET requests
  2351. * @param string $link_name The name of the link; has to match the name used in check_link_hash, otherwise no restrictions apply
  2352. * @return string the hash
  2353. */
  2354. function generate_link_hash($link_name)
  2355. {
  2356. global $user;
  2357. if (!isset($user->data["hash_$link_name"]))
  2358. {
  2359. $user->data["hash_$link_name"] = substr(sha1($user->data['user_form_salt'] . $link_name), 0, 8);
  2360. }
  2361. return $user->data["hash_$link_name"];
  2362. }
  2363. /**
  2364. * checks a link hash - for GET requests
  2365. * @param string $token the submitted token
  2366. * @param string $link_name The name of the link
  2367. * @return boolean true if all is fine
  2368. */
  2369. function check_link_hash($token, $link_name)
  2370. {
  2371. return $token === generate_link_hash($link_name);
  2372. }
  2373. /**
  2374. * Add a secret token to the form (requires the S_FORM_TOKEN template variable)
  2375. * @param string $form_name The name of the form; has to match the name used in check_form_key, otherwise no restrictions apply
  2376. */
  2377. function add_form_key($form_name)
  2378. {
  2379. global $config, $template, $user;
  2380. $now = time();
  2381. $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
  2382. $token = sha1($now . $user->data['user_form_salt'] . $form_name . $token_sid);
  2383. $s_fields = build_hidden_fields(array(
  2384. 'creation_time' => $now,
  2385. 'form_token' => $token,
  2386. ));
  2387. $template->assign_vars(array(
  2388. 'S_FORM_TOKEN' => $s_fields,
  2389. ));
  2390. }
  2391. /**
  2392. * Check the form key. Required for all altering actions not secured by confirm_box
  2393. * @param string $form_name The name of the form; has to match the name used in add_form_key, otherwise no restrictions apply
  2394. * @param int $timespan The maximum acceptable age for a submitted form in seconds. Defaults to the config setting.
  2395. * @param string $return_page The address for the return link
  2396. * @param bool $trigger If true, the function will triger an error when encountering an invalid form
  2397. */
  2398. function check_form_key($form_name, $timespan = false, $return_page = '', $trigger = false)
  2399. {
  2400. global $config, $user;
  2401. if ($timespan === false)
  2402. {
  2403. // we enforce a minimum value of half a minute here.
  2404. $timespan = ($config['form_token_lifetime'] == -1) ? -1 : max(30, $config['form_token_lifetime']);
  2405. }
  2406. if (isset($_POST['creation_time']) && isset($_POST['form_token']))
  2407. {
  2408. $creation_time = abs(request_var('creation_time', 0));
  2409. $token = request_var('form_token', '');
  2410. $diff = time() - $creation_time;
  2411. // If creation_time and the time() now is zero we can assume it was not a human doing this (the check for if ($diff)...
  2412. if ($diff && ($diff <= $timespan || $timespan === -1))
  2413. {
  2414. $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
  2415. $key = sha1($creation_time . $user->data['user_form_salt'] . $form_name . $token_sid);
  2416. if ($key === $token)
  2417. {
  2418. return true;
  2419. }
  2420. }
  2421. }
  2422. if ($trigger)
  2423. {
  2424. trigger_error($user->lang['FORM_INVALID'] . $return_page);
  2425. }
  2426. return false;
  2427. }
  2428. // Message/Login boxes
  2429. /**
  2430. * Build Confirm box
  2431. * @param boolean $check True for checking if confirmed (without any additional parameters) and false for displaying the confirm box
  2432. * @param string $title Title/Message used for confirm box.
  2433. * message text is _CONFIRM appended to title.
  2434. * If title cannot be found in user->lang a default one is displayed
  2435. * If title_CONFIRM cannot be found in user->lang the text given is used.
  2436. * @param string $hidden Hidden variables
  2437. * @param string $html_body Template used for confirm box
  2438. * @param string $u_action Custom form action
  2439. */
  2440. function confirm_box($check, $title = '', $hidden = '', $html_body = 'confirm_body.html', $u_action = '')
  2441. {
  2442. global $user, $template, $db;
  2443. global $phpEx, $phpbb_root_path;
  2444. if (isset($_POST['cancel']))
  2445. {
  2446. return false;
  2447. }
  2448. $confirm = false;
  2449. if (isset($_POST['confirm']))
  2450. {
  2451. // language frontier
  2452. if ($_POST['confirm'] === $user->lang['YES'])
  2453. {
  2454. $confirm = true;
  2455. }
  2456. }
  2457. if ($check && $confirm)
  2458. {
  2459. $user_id = request_var('confirm_uid', 0);
  2460. $session_id = request_var('sess', '');
  2461. $confirm_key = request_var('confirm_key', '');
  2462. 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'])
  2463. {
  2464. return false;
  2465. }
  2466. // Reset user_last_confirm_key
  2467. $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = ''
  2468. WHERE user_id = " . $user->data['user_id'];
  2469. $db->sql_query($sql);
  2470. return true;
  2471. }
  2472. else if ($check)
  2473. {
  2474. return false;
  2475. }
  2476. $s_hidden_fields = build_hidden_fields(array(
  2477. 'confirm_uid' => $user->data['user_id'],
  2478. 'sess' => $user->session_id,
  2479. 'sid' => $user->session_id,
  2480. ));
  2481. // generate activation key
  2482. $confirm_key = gen_rand_string(10);
  2483. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  2484. {
  2485. adm_page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
  2486. }
  2487. else
  2488. {
  2489. page_header(((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]), false);
  2490. }
  2491. $template->set_filenames(array(
  2492. 'body' => $html_body)
  2493. );
  2494. // If activation key already exist, we better do not re-use the key (something very strange is going on...)
  2495. if (request_var('confirm_key', ''))
  2496. {
  2497. // This should not occur, therefore we cancel the operation to safe the user
  2498. return false;
  2499. }
  2500. // re-add sid / transform & to &amp; for user->page (user->page is always using &)
  2501. $use_page = ($u_action) ? $phpbb_root_path . $u_action : $phpbb_root_path . str_replace('&', '&amp;', $user->page['page']);
  2502. $u_action = reapply_sid($use_page);
  2503. $u_action .= ((strpos($u_action, '?') === false) ? '?' : '&amp;') . 'confirm_key=' . $confirm_key;
  2504. $template->assign_vars(array(
  2505. 'MESSAGE_TITLE' => (!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title],
  2506. 'MESSAGE_TEXT' => (!isset($user->lang[$title . '_CONFIRM'])) ? $title : $user->lang[$title . '_CONFIRM'],
  2507. 'YES_VALUE' => $user->lang['YES'],
  2508. 'S_CONFIRM_ACTION' => $u_action,
  2509. 'S_HIDDEN_FIELDS' => $hidden . $s_hidden_fields)
  2510. );
  2511. $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = '" . $db->sql_escape($confirm_key) . "'
  2512. WHERE user_id = " . $user->data['user_id'];
  2513. $db->sql_query($sql);
  2514. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  2515. {
  2516. adm_page_footer();
  2517. }
  2518. else
  2519. {
  2520. page_footer();
  2521. }
  2522. }
  2523. /**
  2524. * Generate login box or verify password
  2525. */
  2526. function login_box($redirect = '', $l_explain = '', $l_success = '', $admin = false, $s_display = true)
  2527. {
  2528. global $db, $user, $template, $auth, $phpEx, $phpbb_root_path, $config;
  2529. if (!class_exists('phpbb_captcha_factory'))
  2530. {
  2531. include($phpbb_root_path . 'includes/captcha/captcha_factory.' . $phpEx);
  2532. }
  2533. $err = '';
  2534. // Make sure user->setup() has been called
  2535. if (empty($user->lang))
  2536. {
  2537. $user->setup();
  2538. }
  2539. // Print out error if user tries to authenticate as an administrator without having the privileges...
  2540. if ($admin && !$auth->acl_get('a_'))
  2541. {
  2542. // Not authd
  2543. // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
  2544. if ($user->data['is_registered'])
  2545. {
  2546. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2547. }
  2548. trigger_error('NO_AUTH_ADMIN');
  2549. }
  2550. if (isset($_POST['login']))
  2551. {
  2552. // Get credential
  2553. if ($admin)
  2554. {
  2555. $credential = request_var('credential', '');
  2556. if (strspn($credential, 'abcdef0123456789') !== strlen($credential) || strlen($credential) != 32)
  2557. {
  2558. if ($user->data['is_registered'])
  2559. {
  2560. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2561. }
  2562. trigger_error('NO_AUTH_ADMIN');
  2563. }
  2564. $password = request_var('password_' . $credential, '', true);
  2565. }
  2566. else
  2567. {
  2568. $password = request_var('password', '', true);
  2569. }
  2570. $username = request_var('username', '', true);
  2571. $autologin = (!empty($_POST['autologin'])) ? true : false;
  2572. $viewonline = (!empty($_POST['viewonline'])) ? 0 : 1;
  2573. $admin = ($admin) ? 1 : 0;
  2574. $viewonline = ($admin) ? $user->data['session_viewonline'] : $viewonline;
  2575. // Check if the supplied username is equal to the one stored within the database if re-authenticating
  2576. if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
  2577. {
  2578. // We log the attempt to use a different username...
  2579. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2580. trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
  2581. }
  2582. // If authentication is successful we redirect user to previous page
  2583. $result = $auth->login($username, $password, $autologin, $viewonline, $admin);
  2584. // If admin authentication and login, we will log if it was a success or not...
  2585. // We also break the operation on the first non-success login - it could be argued that the user already knows
  2586. if ($admin)
  2587. {
  2588. if ($result['status'] == LOGIN_SUCCESS)
  2589. {
  2590. add_log('admin', 'LOG_ADMIN_AUTH_SUCCESS');
  2591. }
  2592. else
  2593. {
  2594. // Only log the failed attempt if a real user tried to.
  2595. // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
  2596. if ($user->data['is_registered'])
  2597. {
  2598. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2599. }
  2600. }
  2601. }
  2602. // The result parameter is always an array, holding the relevant information...
  2603. if ($result['status'] == LOGIN_SUCCESS)
  2604. {
  2605. $redirect = request_var('redirect', "{$phpbb_root_path}index.$phpEx");
  2606. $message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
  2607. $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']);
  2608. // append/replace SID (may change during the session for AOL users)
  2609. $redirect = reapply_sid($redirect);
  2610. // Special case... the user is effectively banned, but we allow founders to login
  2611. if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != USER_FOUNDER)
  2612. {
  2613. return;
  2614. }
  2615. $redirect = meta_refresh(3, $redirect);
  2616. trigger_error($message . '<br /><br />' . sprintf($l_redirect, '<a href="' . $redirect . '">', '</a>'));
  2617. }
  2618. // Something failed, determine what...
  2619. if ($result['status'] == LOGIN_BREAK)
  2620. {
  2621. trigger_error($result['error_msg']);
  2622. }
  2623. // Special cases... determine
  2624. switch ($result['status'])
  2625. {
  2626. case LOGIN_ERROR_ATTEMPTS:
  2627. $captcha = phpbb_captcha_factory::get_instance($config['captcha_plugin']);
  2628. $captcha->init(CONFIRM_LOGIN);
  2629. // $captcha->reset();
  2630. $template->assign_vars(array(
  2631. 'CAPTCHA_TEMPLATE' => $captcha->get_template(),
  2632. ));
  2633. $err = $user->lang[$result['error_msg']];
  2634. break;
  2635. case LOGIN_ERROR_PASSWORD_CONVERT:
  2636. $err = sprintf(
  2637. $user->lang[$result['error_msg']],
  2638. ($config['email_enable']) ? '<a href="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') . '">' : '',
  2639. ($config['email_enable']) ? '</a>' : '',
  2640. ($config['board_contact']) ? '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">' : '',
  2641. ($config['board_contact']) ? '</a>' : ''
  2642. );
  2643. break;
  2644. // Username, password, etc...
  2645. default:
  2646. $err = $user->lang[$result['error_msg']];
  2647. // Assign admin contact to some error messages
  2648. if ($result['error_msg'] == 'LOGIN_ERROR_USERNAME' || $result['error_msg'] == 'LOGIN_ERROR_PASSWORD')
  2649. {
  2650. $err = (!$config['board_contact']) ? sprintf($user->lang[$result['error_msg']], '', '') : sprintf($user->lang[$result['error_msg']], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');
  2651. }
  2652. break;
  2653. }
  2654. }
  2655. // Assign credential for username/password pair
  2656. $credential = ($admin) ? md5(unique_id()) : false;
  2657. $s_hidden_fields = array(
  2658. 'sid' => $user->session_id,
  2659. );
  2660. if ($redirect)
  2661. {
  2662. $s_hidden_fields['redirect'] = $redirect;
  2663. }
  2664. if ($admin)
  2665. {
  2666. $s_hidden_fields['credential'] = $credential;
  2667. }
  2668. $s_hidden_fields = build_hidden_fields($s_hidden_fields);
  2669. $template->assign_vars(array(
  2670. 'LOGIN_ERROR' => $err,
  2671. 'LOGIN_EXPLAIN' => $l_explain,
  2672. 'U_SEND_PASSWORD' => ($config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') : '',
  2673. 'U_RESEND_ACTIVATION' => ($config['require_activation'] == USER_ACTIVATION_SELF && $config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=resend_act') : '',
  2674. 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
  2675. 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
  2676. 'S_DISPLAY_FULL_LOGIN' => ($s_display) ? true : false,
  2677. 'S_HIDDEN_FIELDS' => $s_hidden_fields,
  2678. 'S_ADMIN_AUTH' => $admin,
  2679. 'USERNAME' => ($admin) ? $user->data['username'] : '',
  2680. 'USERNAME_CREDENTIAL' => 'username',
  2681. 'PASSWORD_CREDENTIAL' => ($admin) ? 'password_' . $credential : 'password',
  2682. ));
  2683. page_header($user->lang['LOGIN'], false);
  2684. $template->set_filenames(array(
  2685. 'body' => 'login_body.html')
  2686. );
  2687. make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"));
  2688. page_footer();
  2689. }
  2690. /**
  2691. * Generate forum login box
  2692. */
  2693. function login_forum_box($forum_data)
  2694. {
  2695. global $db, $config, $user, $template, $phpEx;
  2696. $password = request_var('password', '', true);
  2697. $sql = 'SELECT forum_id
  2698. FROM ' . FORUMS_ACCESS_TABLE . '
  2699. WHERE forum_id = ' . $forum_data['forum_id'] . '
  2700. AND user_id = ' . $user->data['user_id'] . "
  2701. AND session_id = '" . $db->sql_escape($user->session_id) . "'";
  2702. $result = $db->sql_query($sql);
  2703. $row = $db->sql_fetchrow($result);
  2704. $db->sql_freeresult($result);
  2705. if ($row)
  2706. {
  2707. return true;
  2708. }
  2709. if ($password)
  2710. {
  2711. // Remove expired authorised sessions
  2712. $sql = 'SELECT f.session_id
  2713. FROM ' . FORUMS_ACCESS_TABLE . ' f
  2714. LEFT JOIN ' . SESSIONS_TABLE . ' s ON (f.session_id = s.session_id)
  2715. WHERE s.session_id IS NULL';
  2716. $result = $db->sql_query($sql);
  2717. if ($row = $db->sql_fetchrow($result))
  2718. {
  2719. $sql_in = array();
  2720. do
  2721. {
  2722. $sql_in[] = (string) $row['session_id'];
  2723. }
  2724. while ($row = $db->sql_fetchrow($result));
  2725. // Remove expired sessions
  2726. $sql = 'DELETE FROM ' . FORUMS_ACCESS_TABLE . '
  2727. WHERE ' . $db->sql_in_set('session_id', $sql_in);
  2728. $db->sql_query($sql);
  2729. }
  2730. $db->sql_freeresult($result);
  2731. if (phpbb_check_hash($password, $forum_data['forum_password']))
  2732. {
  2733. $sql_ary = array(
  2734. 'forum_id' => (int) $forum_data['forum_id'],
  2735. 'user_id' => (int) $user->data['user_id'],
  2736. 'session_id' => (string) $user->session_id,
  2737. );
  2738. $db->sql_query('INSERT INTO ' . FORUMS_ACCESS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  2739. return true;
  2740. }
  2741. $template->assign_var('LOGIN_ERROR', $user->lang['WRONG_PASSWORD']);
  2742. }
  2743. page_header($user->lang['LOGIN'], false);
  2744. $template->assign_vars(array(
  2745. 'S_LOGIN_ACTION' => build_url(array('f')),
  2746. 'S_HIDDEN_FIELDS' => build_hidden_fields(array('f' => $forum_data['forum_id'])))
  2747. );
  2748. $template->set_filenames(array(
  2749. 'body' => 'login_forum.html')
  2750. );
  2751. page_footer();
  2752. }
  2753. // Little helpers
  2754. /**
  2755. * Little helper for the build_hidden_fields function
  2756. */
  2757. function _build_hidden_fields($key, $value, $specialchar, $stripslashes)
  2758. {
  2759. $hidden_fields = '';
  2760. if (!is_array($value))
  2761. {
  2762. $value = ($stripslashes) ? stripslashes($value) : $value;
  2763. $value = ($specialchar) ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value;
  2764. $hidden_fields .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />' . "\n";
  2765. }
  2766. else
  2767. {
  2768. foreach ($value as $_key => $_value)
  2769. {
  2770. $_key = ($stripslashes) ? stripslashes($_key) : $_key;
  2771. $_key = ($specialchar) ? htmlspecialchars($_key, ENT_COMPAT, 'UTF-8') : $_key;
  2772. $hidden_fields .= _build_hidden_fields($key . '[' . $_key . ']', $_value, $specialchar, $stripslashes);
  2773. }
  2774. }
  2775. return $hidden_fields;
  2776. }
  2777. /**
  2778. * Build simple hidden fields from array
  2779. *
  2780. * @param array $field_ary an array of values to build the hidden field from
  2781. * @param bool $specialchar if true, keys and values get specialchared
  2782. * @param bool $stripslashes if true, keys and values get stripslashed
  2783. *
  2784. * @return string the hidden fields
  2785. */
  2786. function build_hidden_fields($field_ary, $specialchar = false, $stripslashes = false)
  2787. {
  2788. $s_hidden_fields = '';
  2789. foreach ($field_ary as $name => $vars)
  2790. {
  2791. $name = ($stripslashes) ? stripslashes($name) : $name;
  2792. $name = ($specialchar) ? htmlspecialchars($name, ENT_COMPAT, 'UTF-8') : $name;
  2793. $s_hidden_fields .= _build_hidden_fields($name, $vars, $specialchar, $stripslashes);
  2794. }
  2795. return $s_hidden_fields;
  2796. }
  2797. /**
  2798. * Parse cfg file
  2799. */
  2800. function parse_cfg_file($filename, $lines = false)
  2801. {
  2802. $parsed_items = array();
  2803. if ($lines === false)
  2804. {
  2805. $lines = file($filename);
  2806. }
  2807. foreach ($lines as $line)
  2808. {
  2809. $line = trim($line);
  2810. if (!$line || $line[0] == '#' || ($delim_pos = strpos($line, '=')) === false)
  2811. {
  2812. continue;
  2813. }
  2814. // Determine first occurrence, since in values the equal sign is allowed
  2815. $key = strtolower(trim(substr($line, 0, $delim_pos)));
  2816. $value = trim(substr($line, $delim_pos + 1));
  2817. if (in_array($value, array('off', 'false', '0')))
  2818. {
  2819. $value = false;
  2820. }
  2821. else if (in_array($value, array('on', 'true', '1')))
  2822. {
  2823. $value = true;
  2824. }
  2825. else if (!trim($value))
  2826. {
  2827. $value = '';
  2828. }
  2829. else if (($value[0] == "'" && $value[sizeof($value) - 1] == "'") || ($value[0] == '"' && $value[sizeof($value) - 1] == '"'))
  2830. {
  2831. $value = substr($value, 1, sizeof($value)-2);
  2832. }
  2833. $parsed_items[$key] = $value;
  2834. }
  2835. return $parsed_items;
  2836. }
  2837. /**
  2838. * Add log event
  2839. */
  2840. function add_log()
  2841. {
  2842. global $db, $user;
  2843. // In phpBB 3.1.x i want to have logging in a class to be able to control it
  2844. // For now, we need a quite hakish approach to circumvent logging for some actions
  2845. // @todo implement cleanly
  2846. if (!empty($GLOBALS['skip_add_log']))
  2847. {
  2848. return false;
  2849. }
  2850. $args = func_get_args();
  2851. $mode = array_shift($args);
  2852. $reportee_id = ($mode == 'user') ? intval(array_shift($args)) : '';
  2853. $forum_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
  2854. $topic_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
  2855. $action = array_shift($args);
  2856. $data = (!sizeof($args)) ? '' : serialize($args);
  2857. $sql_ary = array(
  2858. 'user_id' => (empty($user->data)) ? ANONYMOUS : $user->data['user_id'],
  2859. 'log_ip' => $user->ip,
  2860. 'log_time' => time(),
  2861. 'log_operation' => $action,
  2862. 'log_data' => $data,
  2863. );
  2864. switch ($mode)
  2865. {
  2866. case 'admin':
  2867. $sql_ary['log_type'] = LOG_ADMIN;
  2868. break;
  2869. case 'mod':
  2870. $sql_ary += array(
  2871. 'log_type' => LOG_MOD,
  2872. 'forum_id' => $forum_id,
  2873. 'topic_id' => $topic_id
  2874. );
  2875. break;
  2876. case 'user':
  2877. $sql_ary += array(
  2878. 'log_type' => LOG_USERS,
  2879. 'reportee_id' => $reportee_id
  2880. );
  2881. break;
  2882. case 'critical':
  2883. $sql_ary['log_type'] = LOG_CRITICAL;
  2884. break;
  2885. default:
  2886. return false;
  2887. }
  2888. $db->sql_query('INSERT INTO ' . LOG_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  2889. return $db->sql_nextid();
  2890. }
  2891. /**
  2892. * Return a nicely formatted backtrace.
  2893. *
  2894. * Turns the array returned by debug_backtrace() into HTML markup.
  2895. * Also filters out absolute paths to phpBB root.
  2896. *
  2897. * @return string HTML markup
  2898. */
  2899. function get_backtrace()
  2900. {
  2901. $output = '<div style="font-family: monospace;">';
  2902. $backtrace = debug_backtrace();
  2903. // We skip the first one, because it only shows this file/function
  2904. unset($backtrace[0]);
  2905. foreach ($backtrace as $trace)
  2906. {
  2907. // Strip the current directory from path
  2908. $trace['file'] = (empty($trace['file'])) ? '(not given by php)' : htmlspecialchars(phpbb_filter_root_path($trace['file']));
  2909. $trace['line'] = (empty($trace['line'])) ? '(not given by php)' : $trace['line'];
  2910. // Only show function arguments for include etc.
  2911. // Other parameters may contain sensible information
  2912. $argument = '';
  2913. if (!empty($trace['args'][0]) && in_array($trace['function'], array('include', 'require', 'include_once', 'require_once')))
  2914. {
  2915. $argument = htmlspecialchars(phpbb_filter_root_path($trace['args'][0]));
  2916. }
  2917. $trace['class'] = (!isset($trace['class'])) ? '' : $trace['class'];
  2918. $trace['type'] = (!isset($trace['type'])) ? '' : $trace['type'];
  2919. $output .= '<br />';
  2920. $output .= '<b>FILE:</b> ' . $trace['file'] . '<br />';
  2921. $output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
  2922. $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']);
  2923. $output .= '(' . (($argument !== '') ? "'$argument'" : '') . ')<br />';
  2924. }
  2925. $output .= '</div>';
  2926. return $output;
  2927. }
  2928. /**
  2929. * This function returns a regular expression pattern for commonly used expressions
  2930. * Use with / as delimiter for email mode and # for url modes
  2931. * mode can be: email|bbcode_htm|url|url_inline|www_url|www_url_inline|relative_url|relative_url_inline|ipv4|ipv6
  2932. */
  2933. function get_preg_expression($mode)
  2934. {
  2935. switch ($mode)
  2936. {
  2937. case 'email':
  2938. // Regex written by James Watts and Francisco Jose Martin Moreno
  2939. // http://fightingforalostcause.net/misc/2006/compare-email-regex.php
  2940. return '([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*(?:[\w\!\#$\%\'\*\+\-\/\=\?\^\`{\|\}\~]|&amp;)+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)';
  2941. break;
  2942. case 'bbcode_htm':
  2943. return array(
  2944. '#<!\-\- e \-\-><a href="mailto:(.*?)">.*?</a><!\-\- e \-\->#',
  2945. '#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&amp;|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
  2946. '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
  2947. '#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
  2948. '#<!\-\- .*? \-\->#s',
  2949. '#<.*?>#s',
  2950. );
  2951. break;
  2952. // Whoa these look impressive!
  2953. // The code to generate the following two regular expressions which match valid IPv4/IPv6 addresses
  2954. // can be found in the develop directory
  2955. case 'ipv4':
  2956. 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])$#';
  2957. break;
  2958. case 'ipv6':
  2959. 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';
  2960. break;
  2961. case 'url':
  2962. case 'url_inline':
  2963. $inline = ($mode == 'url') ? ')' : '';
  2964. $scheme = ($mode == 'url') ? '[a-z\d+\-.]' : '[a-z\d+]'; // avoid automatic parsing of "word" in "last word.http://..."
  2965. // generated with regex generation file in the develop folder
  2966. 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})*)?";
  2967. break;
  2968. case 'www_url':
  2969. case 'www_url_inline':
  2970. $inline = ($mode == 'www_url') ? ')' : '';
  2971. 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})*)?";
  2972. break;
  2973. case 'relative_url':
  2974. case 'relative_url_inline':
  2975. $inline = ($mode == 'relative_url') ? ')' : '';
  2976. 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})*)?";
  2977. break;
  2978. case 'table_prefix':
  2979. return '#^[a-zA-Z][a-zA-Z0-9_]*$#';
  2980. break;
  2981. }
  2982. return '';
  2983. }
  2984. /**
  2985. * Generate regexp for naughty words censoring
  2986. * Depends on whether installed PHP version supports unicode properties
  2987. *
  2988. * @param string $word word template to be replaced
  2989. * @param bool $use_unicode whether or not to take advantage of PCRE supporting unicode
  2990. *
  2991. * @return string $preg_expr regex to use with word censor
  2992. */
  2993. function get_censor_preg_expression($word, $use_unicode = true)
  2994. {
  2995. static $unicode_support = null;
  2996. // Check whether PHP version supports unicode properties
  2997. if (is_null($unicode_support))
  2998. {
  2999. $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;
  3000. }
  3001. // Unescape the asterisk to simplify further conversions
  3002. $word = str_replace('\*', '*', preg_quote($word, '#'));
  3003. if ($use_unicode && $unicode_support)
  3004. {
  3005. // Replace asterisk(s) inside the pattern, at the start and at the end of it with regexes
  3006. $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);
  3007. // Generate the final substitution
  3008. $preg_expr = '#(?<![\p{Nd}\p{L}_-])(' . $word . ')(?![\p{Nd}\p{L}_-])#iu';
  3009. }
  3010. else
  3011. {
  3012. // Replace the asterisk inside the pattern, at the start and at the end of it with regexes
  3013. $word = preg_replace(array('#(?<=\S)\*+(?=\S)#iu', '#^\*+#', '#\*+$#'), array('(\x20*?\S*?)', '\S*?', '\S*?'), $word);
  3014. // Generate the final substitution
  3015. $preg_expr = '#(?<!\S)(' . $word . ')(?!\S)#iu';
  3016. }
  3017. return $preg_expr;
  3018. }
  3019. /**
  3020. * Returns the first block of the specified IPv6 address and as many additional
  3021. * ones as specified in the length paramater.
  3022. * If length is zero, then an empty string is returned.
  3023. * If length is greater than 3 the complete IP will be returned
  3024. */
  3025. function short_ipv6($ip, $length)
  3026. {
  3027. if ($length < 1)
  3028. {
  3029. return '';
  3030. }
  3031. // extend IPv6 addresses
  3032. $blocks = substr_count($ip, ':') + 1;
  3033. if ($blocks < 9)
  3034. {
  3035. $ip = str_replace('::', ':' . str_repeat('0000:', 9 - $blocks), $ip);
  3036. }
  3037. if ($ip[0] == ':')
  3038. {
  3039. $ip = '0000' . $ip;
  3040. }
  3041. if ($length < 4)
  3042. {
  3043. $ip = implode(':', array_slice(explode(':', $ip), 0, 1 + $length));
  3044. }
  3045. return $ip;
  3046. }
  3047. /**
  3048. * Wrapper for php's checkdnsrr function.
  3049. *
  3050. * @param string $host Fully-Qualified Domain Name
  3051. * @param string $type Resource record type to lookup
  3052. * Supported types are: MX (default), A, AAAA, NS, TXT, CNAME
  3053. * Other types may work or may not work
  3054. *
  3055. * @return mixed true if entry found,
  3056. * false if entry not found,
  3057. * null if this function is not supported by this environment
  3058. *
  3059. * Since null can also be returned, you probably want to compare the result
  3060. * with === true or === false,
  3061. *
  3062. * @author bantu
  3063. */
  3064. function phpbb_checkdnsrr($host, $type = 'MX')
  3065. {
  3066. // The dot indicates to search the DNS root (helps those having DNS prefixes on the same domain)
  3067. if (substr($host, -1) == '.')
  3068. {
  3069. $host_fqdn = $host;
  3070. $host = substr($host, 0, -1);
  3071. }
  3072. else
  3073. {
  3074. $host_fqdn = $host . '.';
  3075. }
  3076. // $host has format some.host.example.com
  3077. // $host_fqdn has format some.host.example.com.
  3078. // If we're looking for an A record we can use gethostbyname()
  3079. if ($type == 'A' && function_exists('gethostbyname'))
  3080. {
  3081. return (@gethostbyname($host_fqdn) == $host_fqdn) ? false : true;
  3082. }
  3083. // checkdnsrr() is available on Windows since PHP 5.3,
  3084. // but until 5.3.3 it only works for MX records
  3085. // See: http://bugs.php.net/bug.php?id=51844
  3086. // Call checkdnsrr() if
  3087. // we're looking for an MX record or
  3088. // we're not on Windows or
  3089. // we're running a PHP version where #51844 has been fixed
  3090. // checkdnsrr() supports AAAA since 5.0.0
  3091. // checkdnsrr() supports TXT since 5.2.4
  3092. if (
  3093. ($type == 'MX' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.3', '>=')) &&
  3094. ($type != 'AAAA' || version_compare(PHP_VERSION, '5.0.0', '>=')) &&
  3095. ($type != 'TXT' || version_compare(PHP_VERSION, '5.2.4', '>=')) &&
  3096. function_exists('checkdnsrr')
  3097. )
  3098. {
  3099. return checkdnsrr($host_fqdn, $type);
  3100. }
  3101. // dns_get_record() is available since PHP 5; since PHP 5.3 also on Windows,
  3102. // but on Windows it does not work reliable for AAAA records before PHP 5.3.1
  3103. // Call dns_get_record() if
  3104. // we're not looking for an AAAA record or
  3105. // we're not on Windows or
  3106. // we're running a PHP version where AAAA lookups work reliable
  3107. if (
  3108. ($type != 'AAAA' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.1', '>=')) &&
  3109. function_exists('dns_get_record')
  3110. )
  3111. {
  3112. // dns_get_record() expects an integer as second parameter
  3113. // We have to convert the string $type to the corresponding integer constant.
  3114. $type_constant = 'DNS_' . $type;
  3115. $type_param = (defined($type_constant)) ? constant($type_constant) : DNS_ANY;
  3116. // dns_get_record() might throw E_WARNING and return false for records that do not exist
  3117. $resultset = @dns_get_record($host_fqdn, $type_param);
  3118. if (empty($resultset) || !is_array($resultset))
  3119. {
  3120. return false;
  3121. }
  3122. else if ($type_param == DNS_ANY)
  3123. {
  3124. // $resultset is a non-empty array
  3125. return true;
  3126. }
  3127. foreach ($resultset as $result)
  3128. {
  3129. if (
  3130. isset($result['host']) && $result['host'] == $host &&
  3131. isset($result['type']) && $result['type'] == $type
  3132. )
  3133. {
  3134. return true;
  3135. }
  3136. }
  3137. return false;
  3138. }
  3139. // If we're on Windows we can still try to call nslookup via exec() as a last resort
  3140. if (DIRECTORY_SEPARATOR == '\\' && function_exists('exec'))
  3141. {
  3142. @exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host_fqdn), $output);
  3143. // If output is empty, the nslookup failed
  3144. if (empty($output))
  3145. {
  3146. return NULL;
  3147. }
  3148. foreach ($output as $line)
  3149. {
  3150. $line = trim($line);
  3151. if (empty($line))
  3152. {
  3153. continue;
  3154. }
  3155. // Squash tabs and multiple whitespaces to a single whitespace.
  3156. $line = preg_replace('/\s+/', ' ', $line);
  3157. switch ($type)
  3158. {
  3159. case 'MX':
  3160. if (stripos($line, "$host MX") === 0)
  3161. {
  3162. return true;
  3163. }
  3164. break;
  3165. case 'NS':
  3166. if (stripos($line, "$host nameserver") === 0)
  3167. {
  3168. return true;
  3169. }
  3170. break;
  3171. case 'TXT':
  3172. if (stripos($line, "$host text") === 0)
  3173. {
  3174. return true;
  3175. }
  3176. break;
  3177. case 'CNAME':
  3178. if (stripos($line, "$host canonical name") === 0)
  3179. {
  3180. return true;
  3181. }
  3182. break;
  3183. default:
  3184. case 'AAAA':
  3185. // AAAA records returned by nslookup on Windows XP/2003 have this format.
  3186. // Later Windows versions use the A record format below for AAAA records.
  3187. if (stripos($line, "$host AAAA IPv6 address") === 0)
  3188. {
  3189. return true;
  3190. }
  3191. // No break
  3192. case 'A':
  3193. if (!empty($host_matches))
  3194. {
  3195. // Second line
  3196. if (stripos($line, "Address: ") === 0)
  3197. {
  3198. return true;
  3199. }
  3200. else
  3201. {
  3202. $host_matches = false;
  3203. }
  3204. }
  3205. else if (stripos($line, "Name: $host") === 0)
  3206. {
  3207. // First line
  3208. $host_matches = true;
  3209. }
  3210. break;
  3211. }
  3212. }
  3213. return false;
  3214. }
  3215. return NULL;
  3216. }
  3217. // Handler, header and footer
  3218. /**
  3219. * Error and message handler, call with trigger_error if reqd
  3220. */
  3221. function msg_handler($errno, $msg_text, $errfile, $errline)
  3222. {
  3223. global $cache, $db, $auth, $template, $config, $user;
  3224. global $phpEx, $phpbb_root_path, $msg_title, $msg_long_text;
  3225. // Do not display notices if we suppress them via @
  3226. if (error_reporting() == 0 && $errno != E_USER_ERROR && $errno != E_USER_WARNING && $errno != E_USER_NOTICE)
  3227. {
  3228. return;
  3229. }
  3230. // Message handler is stripping text. In case we need it, we are possible to define long text...
  3231. if (isset($msg_long_text) && $msg_long_text && !$msg_text)
  3232. {
  3233. $msg_text = $msg_long_text;
  3234. }
  3235. if (!defined('E_DEPRECATED'))
  3236. {
  3237. define('E_DEPRECATED', 8192);
  3238. }
  3239. switch ($errno)
  3240. {
  3241. case E_NOTICE:
  3242. case E_WARNING:
  3243. // Check the error reporting level and return if the error level does not match
  3244. // If DEBUG is defined the default level is E_ALL
  3245. if (($errno & ((defined('DEBUG')) ? E_ALL : error_reporting())) == 0)
  3246. {
  3247. return;
  3248. }
  3249. if (strpos($errfile, 'cache') === false && strpos($errfile, 'template.') === false)
  3250. {
  3251. $errfile = phpbb_filter_root_path($errfile);
  3252. $msg_text = phpbb_filter_root_path($msg_text);
  3253. $error_name = ($errno === E_WARNING) ? 'PHP Warning' : 'PHP Notice';
  3254. echo '<b>[phpBB Debug] ' . $error_name . '</b>: in file <b>' . $errfile . '</b> on line <b>' . $errline . '</b>: <b>' . $msg_text . '</b><br />' . "\n";
  3255. // we are writing an image - the user won't see the debug, so let's place it in the log
  3256. if (defined('IMAGE_OUTPUT') || defined('IN_CRON'))
  3257. {
  3258. add_log('critical', 'LOG_IMAGE_GENERATION_ERROR', $errfile, $errline, $msg_text);
  3259. }
  3260. // echo '<br /><br />BACKTRACE<br />' . get_backtrace() . '<br />' . "\n";
  3261. }
  3262. return;
  3263. break;
  3264. case E_USER_ERROR:
  3265. if (!empty($user) && !empty($user->lang))
  3266. {
  3267. $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
  3268. $msg_title = (!isset($msg_title)) ? $user->lang['GENERAL_ERROR'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
  3269. $l_return_index = sprintf($user->lang['RETURN_INDEX'], '<a href="' . $phpbb_root_path . '">', '</a>');
  3270. $l_notify = '';
  3271. if (!empty($config['board_contact']))
  3272. {
  3273. $l_notify = '<p>' . sprintf($user->lang['NOTIFY_ADMIN_EMAIL'], $config['board_contact']) . '</p>';
  3274. }
  3275. }
  3276. else
  3277. {
  3278. $msg_title = 'General Error';
  3279. $l_return_index = '<a href="' . $phpbb_root_path . '">Return to index page</a>';
  3280. $l_notify = '';
  3281. if (!empty($config['board_contact']))
  3282. {
  3283. $l_notify = '<p>Please notify the board administrator or webmaster: <a href="mailto:' . $config['board_contact'] . '">' . $config['board_contact'] . '</a></p>';
  3284. }
  3285. }
  3286. if ((defined('DEBUG') || defined('IN_CRON') || defined('IMAGE_OUTPUT')) && isset($db))
  3287. {
  3288. // let's avoid loops
  3289. $db->sql_return_on_error(true);
  3290. add_log('critical', 'LOG_GENERAL_ERROR', $msg_title, $msg_text);
  3291. $db->sql_return_on_error(false);
  3292. }
  3293. // Do not send 200 OK, but service unavailable on errors
  3294. send_status_line(503, 'Service Unavailable');
  3295. garbage_collection();
  3296. // Try to not call the adm page data...
  3297. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  3298. echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
  3299. echo '<head>';
  3300. echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
  3301. echo '<title>' . $msg_title . '</title>';
  3302. echo '<style type="text/css">' . "\n" . '/* <![CDATA[ */' . "\n";
  3303. 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; } ';
  3304. echo 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
  3305. 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; } ';
  3306. echo '.panel { margin: 4px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
  3307. 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; } ';
  3308. 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; } ';
  3309. echo "\n" . '/* ]]> */' . "\n";
  3310. echo '</style>';
  3311. echo '</head>';
  3312. echo '<body id="errorpage">';
  3313. echo '<div id="wrap">';
  3314. echo ' <div id="page-header">';
  3315. echo ' ' . $l_return_index;
  3316. echo ' </div>';
  3317. echo ' <div id="acp">';
  3318. echo ' <div class="panel">';
  3319. echo ' <div id="content">';
  3320. echo ' <h1>' . $msg_title . '</h1>';
  3321. echo ' <div>' . $msg_text . '</div>';
  3322. echo $l_notify;
  3323. echo ' </div>';
  3324. echo ' </div>';
  3325. echo ' </div>';
  3326. echo ' <div id="page-footer">';
  3327. echo ' Powered by <a href="http://www.phpbb.com/">phpBB</a>&reg; Forum Software &copy; phpBB Group';
  3328. echo ' </div>';
  3329. echo '</div>';
  3330. echo '</body>';
  3331. echo '</html>';
  3332. exit_handler();
  3333. // On a fatal error (and E_USER_ERROR *is* fatal) we never want other scripts to continue and force an exit here.
  3334. exit;
  3335. break;
  3336. case E_USER_WARNING:
  3337. case E_USER_NOTICE:
  3338. define('IN_ERROR_HANDLER', true);
  3339. if (empty($user->data))
  3340. {
  3341. $user->session_begin();
  3342. }
  3343. // We re-init the auth array to get correct results on login/logout
  3344. $auth->acl($user->data);
  3345. if (empty($user->lang))
  3346. {
  3347. $user->setup();
  3348. }
  3349. if ($msg_text == 'ERROR_NO_ATTACHMENT' || $msg_text == 'NO_FORUM' || $msg_text == 'NO_TOPIC' || $msg_text == 'NO_USER')
  3350. {
  3351. send_status_line(404, 'Not Found');
  3352. }
  3353. $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
  3354. $msg_title = (!isset($msg_title)) ? $user->lang['INFORMATION'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
  3355. if (!defined('HEADER_INC'))
  3356. {
  3357. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  3358. {
  3359. adm_page_header($msg_title);
  3360. }
  3361. else
  3362. {
  3363. page_header($msg_title, false);
  3364. }
  3365. }
  3366. $template->set_filenames(array(
  3367. 'body' => 'message_body.html')
  3368. );
  3369. $template->assign_vars(array(
  3370. 'MESSAGE_TITLE' => $msg_title,
  3371. 'MESSAGE_TEXT' => $msg_text,
  3372. 'S_USER_WARNING' => ($errno == E_USER_WARNING) ? true : false,
  3373. 'S_USER_NOTICE' => ($errno == E_USER_NOTICE) ? true : false)
  3374. );
  3375. // We do not want the cron script to be called on error messages
  3376. define('IN_CRON', true);
  3377. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  3378. {
  3379. adm_page_footer();
  3380. }
  3381. else
  3382. {
  3383. page_footer();
  3384. }
  3385. exit_handler();
  3386. break;
  3387. // PHP4 compatibility
  3388. case E_DEPRECATED:
  3389. return true;
  3390. break;
  3391. }
  3392. // If we notice an error not handled here we pass this back to PHP by returning false
  3393. // This may not work for all php versions
  3394. return false;
  3395. }
  3396. /**
  3397. * Removes absolute path to phpBB root directory from error messages
  3398. * and converts backslashes to forward slashes.
  3399. *
  3400. * @param string $errfile Absolute file path
  3401. * (e.g. /var/www/phpbb3/phpBB/includes/functions.php)
  3402. * Please note that if $errfile is outside of the phpBB root,
  3403. * the root path will not be found and can not be filtered.
  3404. * @return string Relative file path
  3405. * (e.g. /includes/functions.php)
  3406. */
  3407. function phpbb_filter_root_path($errfile)
  3408. {
  3409. static $root_path;
  3410. if (empty($root_path))
  3411. {
  3412. $root_path = phpbb_realpath(dirname(__FILE__) . '/../');
  3413. }
  3414. return str_replace(array($root_path, '\\'), array('[ROOT]', '/'), $errfile);
  3415. }
  3416. /**
  3417. * Queries the session table to get information about online guests
  3418. * @param int $item_id Limits the search to the item with this id
  3419. * @param string $item The name of the item which is stored in the session table as session_{$item}_id
  3420. * @return int The number of active distinct guest sessions
  3421. */
  3422. function obtain_guest_count($item_id = 0, $item = 'forum')
  3423. {
  3424. global $db, $config;
  3425. if ($item_id)
  3426. {
  3427. $reading_sql = ' AND s.session_' . $item . '_id = ' . (int) $item_id;
  3428. }
  3429. else
  3430. {
  3431. $reading_sql = '';
  3432. }
  3433. $time = (time() - (intval($config['load_online_time']) * 60));
  3434. // Get number of online guests
  3435. if ($db->sql_layer === 'sqlite')
  3436. {
  3437. $sql = 'SELECT COUNT(session_ip) as num_guests
  3438. FROM (
  3439. SELECT DISTINCT s.session_ip
  3440. FROM ' . SESSIONS_TABLE . ' s
  3441. WHERE s.session_user_id = ' . ANONYMOUS . '
  3442. AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
  3443. $reading_sql .
  3444. ')';
  3445. }
  3446. else
  3447. {
  3448. $sql = 'SELECT COUNT(DISTINCT s.session_ip) as num_guests
  3449. FROM ' . SESSIONS_TABLE . ' s
  3450. WHERE s.session_user_id = ' . ANONYMOUS . '
  3451. AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
  3452. $reading_sql;
  3453. }
  3454. $result = $db->sql_query($sql);
  3455. $guests_online = (int) $db->sql_fetchfield('num_guests');
  3456. $db->sql_freeresult($result);
  3457. return $guests_online;
  3458. }
  3459. /**
  3460. * Queries the session table to get information about online users
  3461. * @param int $item_id Limits the search to the item with this id
  3462. * @param string $item The name of the item which is stored in the session table as session_{$item}_id
  3463. * @return array An array containing the ids of online, hidden and visible users, as well as statistical info
  3464. */
  3465. function obtain_users_online($item_id = 0, $item = 'forum')
  3466. {
  3467. global $db, $config, $user;
  3468. $reading_sql = '';
  3469. if ($item_id !== 0)
  3470. {
  3471. $reading_sql = ' AND s.session_' . $item . '_id = ' . (int) $item_id;
  3472. }
  3473. $online_users = array(
  3474. 'online_users' => array(),
  3475. 'hidden_users' => array(),
  3476. 'total_online' => 0,
  3477. 'visible_online' => 0,
  3478. 'hidden_online' => 0,
  3479. 'guests_online' => 0,
  3480. );
  3481. if ($config['load_online_guests'])
  3482. {
  3483. $online_users['guests_online'] = obtain_guest_count($item_id, $item);
  3484. }
  3485. // a little discrete magic to cache this for 30 seconds
  3486. $time = (time() - (intval($config['load_online_time']) * 60));
  3487. $sql = 'SELECT s.session_user_id, s.session_ip, s.session_viewonline
  3488. FROM ' . SESSIONS_TABLE . ' s
  3489. WHERE s.session_time >= ' . ($time - ((int) ($time % 30))) .
  3490. $reading_sql .
  3491. ' AND s.session_user_id <> ' . ANONYMOUS;
  3492. $result = $db->sql_query($sql);
  3493. while ($row = $db->sql_fetchrow($result))
  3494. {
  3495. // Skip multiple sessions for one user
  3496. if (!isset($online_users['online_users'][$row['session_user_id']]))
  3497. {
  3498. $online_users['online_users'][$row['session_user_id']] = (int) $row['session_user_id'];
  3499. if ($row['session_viewonline'])
  3500. {
  3501. $online_users['visible_online']++;
  3502. }
  3503. else
  3504. {
  3505. $online_users['hidden_users'][$row['session_user_id']] = (int) $row['session_user_id'];
  3506. $online_users['hidden_online']++;
  3507. }
  3508. }
  3509. }
  3510. $online_users['total_online'] = $online_users['guests_online'] + $online_users['visible_online'] + $online_users['hidden_online'];
  3511. $db->sql_freeresult($result);
  3512. return $online_users;
  3513. }
  3514. /**
  3515. * Uses the result of obtain_users_online to generate a localized, readable representation.
  3516. * @param mixed $online_users result of obtain_users_online - array with user_id lists for total, hidden and visible users, and statistics
  3517. * @param int $item_id Indicate that the data is limited to one item and not global
  3518. * @param string $item The name of the item which is stored in the session table as session_{$item}_id
  3519. * @return array An array containing the string for output to the template
  3520. */
  3521. function obtain_users_online_string($online_users, $item_id = 0, $item = 'forum')
  3522. {
  3523. global $config, $db, $user, $auth;
  3524. $user_online_link = $online_userlist = '';
  3525. // Need caps version of $item for language-strings
  3526. $item_caps = strtoupper($item);
  3527. if (sizeof($online_users['online_users']))
  3528. {
  3529. $sql = 'SELECT username, username_clean, user_id, user_type, user_allow_viewonline, user_colour
  3530. FROM ' . USERS_TABLE . '
  3531. WHERE ' . $db->sql_in_set('user_id', $online_users['online_users']) . '
  3532. ORDER BY username_clean ASC';
  3533. $result = $db->sql_query($sql);
  3534. while ($row = $db->sql_fetchrow($result))
  3535. {
  3536. // User is logged in and therefore not a guest
  3537. if ($row['user_id'] != ANONYMOUS)
  3538. {
  3539. if (isset($online_users['hidden_users'][$row['user_id']]))
  3540. {
  3541. $row['username'] = '<em>' . $row['username'] . '</em>';
  3542. }
  3543. if (!isset($online_users['hidden_users'][$row['user_id']]) || $auth->acl_get('u_viewonline'))
  3544. {
  3545. $user_online_link = get_username_string(($row['user_type'] <> USER_IGNORE) ? 'full' : 'no_profile', $row['user_id'], $row['username'], $row['user_colour']);
  3546. $online_userlist .= ($online_userlist != '') ? ', ' . $user_online_link : $user_online_link;
  3547. }
  3548. }
  3549. }
  3550. $db->sql_freeresult($result);
  3551. }
  3552. if (!$online_userlist)
  3553. {
  3554. $online_userlist = $user->lang['NO_ONLINE_USERS'];
  3555. }
  3556. if ($item_id === 0)
  3557. {
  3558. $online_userlist = $user->lang['REGISTERED_USERS'] . ' ' . $online_userlist;
  3559. }
  3560. else if ($config['load_online_guests'])
  3561. {
  3562. $l_online = ($online_users['guests_online'] === 1) ? $user->lang['BROWSING_' . $item_caps . '_GUEST'] : $user->lang['BROWSING_' . $item_caps . '_GUESTS'];
  3563. $online_userlist = sprintf($l_online, $online_userlist, $online_users['guests_online']);
  3564. }
  3565. else
  3566. {
  3567. $online_userlist = sprintf($user->lang['BROWSING_' . $item_caps], $online_userlist);
  3568. }
  3569. // Build online listing
  3570. $vars_online = array(
  3571. 'ONLINE' => array('total_online', 'l_t_user_s', 0),
  3572. 'REG' => array('visible_online', 'l_r_user_s', !$config['load_online_guests']),
  3573. 'HIDDEN' => array('hidden_online', 'l_h_user_s', $config['load_online_guests']),
  3574. 'GUEST' => array('guests_online', 'l_g_user_s', 0)
  3575. );
  3576. foreach ($vars_online as $l_prefix => $var_ary)
  3577. {
  3578. if ($var_ary[2])
  3579. {
  3580. $l_suffix = '_AND';
  3581. }
  3582. else
  3583. {
  3584. $l_suffix = '';
  3585. }
  3586. switch ($online_users[$var_ary[0]])
  3587. {
  3588. case 0:
  3589. ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_ZERO_TOTAL' . $l_suffix];
  3590. break;
  3591. case 1:
  3592. ${$var_ary[1]} = $user->lang[$l_prefix . '_USER_TOTAL' . $l_suffix];
  3593. break;
  3594. default:
  3595. ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_TOTAL' . $l_suffix];
  3596. break;
  3597. }
  3598. }
  3599. unset($vars_online);
  3600. $l_online_users = sprintf($l_t_user_s, $online_users['total_online']);
  3601. $l_online_users .= sprintf($l_r_user_s, $online_users['visible_online']);
  3602. $l_online_users .= sprintf($l_h_user_s, $online_users['hidden_online']);
  3603. if ($config['load_online_guests'])
  3604. {
  3605. $l_online_users .= sprintf($l_g_user_s, $online_users['guests_online']);
  3606. }
  3607. return array(
  3608. 'online_userlist' => $online_userlist,
  3609. 'l_online_users' => $l_online_users,
  3610. );
  3611. }
  3612. /**
  3613. * Get option bitfield from custom data
  3614. *
  3615. * @param int $bit The bit/value to get
  3616. * @param int $data Current bitfield to check
  3617. * @return bool Returns true if value of constant is set in bitfield, else false
  3618. */
  3619. function phpbb_optionget($bit, $data)
  3620. {
  3621. return ($data & 1 << (int) $bit) ? true : false;
  3622. }
  3623. /**
  3624. * Set option bitfield
  3625. *
  3626. * @param int $bit The bit/value to set/unset
  3627. * @param bool $set True if option should be set, false if option should be unset.
  3628. * @param int $data Current bitfield to change
  3629. *
  3630. * @return int The new bitfield
  3631. */
  3632. function phpbb_optionset($bit, $set, $data)
  3633. {
  3634. if ($set && !($data & 1 << $bit))
  3635. {
  3636. $data += 1 << $bit;
  3637. }
  3638. else if (!$set && ($data & 1 << $bit))
  3639. {
  3640. $data -= 1 << $bit;
  3641. }
  3642. return $data;
  3643. }
  3644. /**
  3645. * Login using http authenticate.
  3646. *
  3647. * @param array $param Parameter array, see $param_defaults array.
  3648. *
  3649. * @return void
  3650. */
  3651. function phpbb_http_login($param)
  3652. {
  3653. global $auth, $user;
  3654. global $config;
  3655. $param_defaults = array(
  3656. 'auth_message' => '',
  3657. 'autologin' => false,
  3658. 'viewonline' => true,
  3659. 'admin' => false,
  3660. );
  3661. // Overwrite default values with passed values
  3662. $param = array_merge($param_defaults, $param);
  3663. // User is already logged in
  3664. // We will not overwrite his session
  3665. if (!empty($user->data['is_registered']))
  3666. {
  3667. return;
  3668. }
  3669. // $_SERVER keys to check
  3670. $username_keys = array(
  3671. 'PHP_AUTH_USER',
  3672. 'Authorization',
  3673. 'REMOTE_USER', 'REDIRECT_REMOTE_USER',
  3674. 'HTTP_AUTHORIZATION', 'REDIRECT_HTTP_AUTHORIZATION',
  3675. 'REMOTE_AUTHORIZATION', 'REDIRECT_REMOTE_AUTHORIZATION',
  3676. 'AUTH_USER',
  3677. );
  3678. $password_keys = array(
  3679. 'PHP_AUTH_PW',
  3680. 'REMOTE_PASSWORD',
  3681. 'AUTH_PASSWORD',
  3682. );
  3683. $username = null;
  3684. foreach ($username_keys as $k)
  3685. {
  3686. if (isset($_SERVER[$k]))
  3687. {
  3688. $username = $_SERVER[$k];
  3689. break;
  3690. }
  3691. }
  3692. $password = null;
  3693. foreach ($password_keys as $k)
  3694. {
  3695. if (isset($_SERVER[$k]))
  3696. {
  3697. $password = $_SERVER[$k];
  3698. break;
  3699. }
  3700. }
  3701. // Decode encoded information (IIS, CGI, FastCGI etc.)
  3702. if (!is_null($username) && is_null($password) && strpos($username, 'Basic ') === 0)
  3703. {
  3704. list($username, $password) = explode(':', base64_decode(substr($username, 6)), 2);
  3705. }
  3706. if (!is_null($username) && !is_null($password))
  3707. {
  3708. set_var($username, $username, 'string', true);
  3709. set_var($password, $password, 'string', true);
  3710. $auth_result = $auth->login($username, $password, $param['autologin'], $param['viewonline'], $param['admin']);
  3711. if ($auth_result['status'] == LOGIN_SUCCESS)
  3712. {
  3713. return;
  3714. }
  3715. else if ($auth_result['status'] == LOGIN_ERROR_ATTEMPTS)
  3716. {
  3717. send_status_line(401, 'Unauthorized');
  3718. trigger_error('NOT_AUTHORISED');
  3719. }
  3720. }
  3721. // Prepend sitename to auth_message
  3722. $param['auth_message'] = ($param['auth_message'] === '') ? $config['sitename'] : $config['sitename'] . ' - ' . $param['auth_message'];
  3723. // We should probably filter out non-ASCII characters - RFC2616
  3724. $param['auth_message'] = preg_replace('/[\x80-\xFF]/', '?', $param['auth_message']);
  3725. header('WWW-Authenticate: Basic realm="' . $param['auth_message'] . '"');
  3726. send_status_line(401, 'Unauthorized');
  3727. trigger_error('NOT_AUTHORISED');
  3728. }
  3729. /**
  3730. * Generate page header
  3731. */
  3732. function page_header($page_title = '', $display_online_list = true, $item_id = 0, $item = 'forum')
  3733. {
  3734. global $db, $config, $template, $SID, $_SID, $_EXTRA_URL, $user, $auth, $phpEx, $phpbb_root_path;
  3735. if (defined('HEADER_INC'))
  3736. {
  3737. return;
  3738. }
  3739. define('HEADER_INC', true);
  3740. // gzip_compression
  3741. if ($config['gzip_compress'])
  3742. {
  3743. // to avoid partially compressed output resulting in blank pages in
  3744. // the browser or error messages, compression is disabled in a few cases:
  3745. //
  3746. // 1) if headers have already been sent, this indicates plaintext output
  3747. // has been started so further content must not be compressed
  3748. // 2) the length of the current output buffer is non-zero. This means
  3749. // there is already some uncompressed content in this output buffer
  3750. // so further output must not be compressed
  3751. // 3) if more than one level of output buffering is used because we
  3752. // cannot test all output buffer level content lengths. One level
  3753. // could be caused by php.ini output_buffering. Anything
  3754. // beyond that is manual, so the code wrapping phpBB in output buffering
  3755. // can easily compress the output itself.
  3756. //
  3757. if (@extension_loaded('zlib') && !headers_sent() && ob_get_level() <= 1 && ob_get_length() == 0)
  3758. {
  3759. ob_start('ob_gzhandler');
  3760. }
  3761. }
  3762. // Generate logged in/logged out status
  3763. if ($user->data['user_id'] != ANONYMOUS)
  3764. {
  3765. $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=logout', true, $user->session_id);
  3766. $l_login_logout = sprintf($user->lang['LOGOUT_USER'], $user->data['username']);
  3767. }
  3768. else
  3769. {
  3770. $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login');
  3771. $l_login_logout = $user->lang['LOGIN'];
  3772. }
  3773. // Last visit date/time
  3774. $s_last_visit = ($user->data['user_id'] != ANONYMOUS) ? $user->format_date($user->data['session_last_visit']) : '';
  3775. // Get users online list ... if required
  3776. $l_online_users = $online_userlist = $l_online_record = $l_online_time = '';
  3777. if ($config['load_online'] && $config['load_online_time'] && $display_online_list)
  3778. {
  3779. /**
  3780. * Load online data:
  3781. * For obtaining another session column use $item and $item_id in the function-parameter, whereby the column is session_{$item}_id.
  3782. */
  3783. $item_id = max($item_id, 0);
  3784. $online_users = obtain_users_online($item_id, $item);
  3785. $user_online_strings = obtain_users_online_string($online_users, $item_id, $item);
  3786. $l_online_users = $user_online_strings['l_online_users'];
  3787. $online_userlist = $user_online_strings['online_userlist'];
  3788. $total_online_users = $online_users['total_online'];
  3789. if ($total_online_users > $config['record_online_users'])
  3790. {
  3791. set_config('record_online_users', $total_online_users, true);
  3792. set_config('record_online_date', time(), true);
  3793. }
  3794. $l_online_record = sprintf($user->lang['RECORD_ONLINE_USERS'], $config['record_online_users'], $user->format_date($config['record_online_date'], false, true));
  3795. $l_online_time = ($config['load_online_time'] == 1) ? 'VIEW_ONLINE_TIME' : 'VIEW_ONLINE_TIMES';
  3796. $l_online_time = sprintf($user->lang[$l_online_time], $config['load_online_time']);
  3797. }
  3798. $l_privmsgs_text = $l_privmsgs_text_unread = '';
  3799. $s_privmsg_new = false;
  3800. // Obtain number of new private messages if user is logged in
  3801. if (!empty($user->data['is_registered']))
  3802. {
  3803. if ($user->data['user_new_privmsg'])
  3804. {
  3805. $l_message_new = ($user->data['user_new_privmsg'] == 1) ? $user->lang['NEW_PM'] : $user->lang['NEW_PMS'];
  3806. $l_privmsgs_text = sprintf($l_message_new, $user->data['user_new_privmsg']);
  3807. if (!$user->data['user_last_privmsg'] || $user->data['user_last_privmsg'] > $user->data['session_last_visit'])
  3808. {
  3809. $sql = 'UPDATE ' . USERS_TABLE . '
  3810. SET user_last_privmsg = ' . $user->data['session_last_visit'] . '
  3811. WHERE user_id = ' . $user->data['user_id'];
  3812. $db->sql_query($sql);
  3813. $s_privmsg_new = true;
  3814. }
  3815. else
  3816. {
  3817. $s_privmsg_new = false;
  3818. }
  3819. }
  3820. else
  3821. {
  3822. $l_privmsgs_text = $user->lang['NO_NEW_PM'];
  3823. $s_privmsg_new = false;
  3824. }
  3825. $l_privmsgs_text_unread = '';
  3826. if ($user->data['user_unread_privmsg'] && $user->data['user_unread_privmsg'] != $user->data['user_new_privmsg'])
  3827. {
  3828. $l_message_unread = ($user->data['user_unread_privmsg'] == 1) ? $user->lang['UNREAD_PM'] : $user->lang['UNREAD_PMS'];
  3829. $l_privmsgs_text_unread = sprintf($l_message_unread, $user->data['user_unread_privmsg']);
  3830. }
  3831. }
  3832. $forum_id = request_var('f', 0);
  3833. $topic_id = request_var('t', 0);
  3834. $s_feed_news = false;
  3835. // Get option for news
  3836. if ($config['feed_enable'])
  3837. {
  3838. $sql = 'SELECT forum_id
  3839. FROM ' . FORUMS_TABLE . '
  3840. WHERE ' . $db->sql_bit_and('forum_options', FORUM_OPTION_FEED_NEWS, '<> 0');
  3841. $result = $db->sql_query_limit($sql, 1, 0, 600);
  3842. $s_feed_news = (int) $db->sql_fetchfield('forum_id');
  3843. $db->sql_freeresult($result);
  3844. }
  3845. // Determine board url - we may need it later
  3846. $board_url = generate_board_url() . '/';
  3847. $web_path = (defined('PHPBB_USE_BOARD_URL_PATH') && PHPBB_USE_BOARD_URL_PATH) ? $board_url : $phpbb_root_path;
  3848. // Which timezone?
  3849. $tz = ($user->data['user_id'] != ANONYMOUS) ? strval(doubleval($user->data['user_timezone'])) : strval(doubleval($config['board_timezone']));
  3850. // Send a proper content-language to the output
  3851. $user_lang = $user->lang['USER_LANG'];
  3852. if (strpos($user_lang, '-x-') !== false)
  3853. {
  3854. $user_lang = substr($user_lang, 0, strpos($user_lang, '-x-'));
  3855. }
  3856. $s_search_hidden_fields = array();
  3857. if ($_SID)
  3858. {
  3859. $s_search_hidden_fields['sid'] = $_SID;
  3860. }
  3861. if (!empty($_EXTRA_URL))
  3862. {
  3863. foreach ($_EXTRA_URL as $url_param)
  3864. {
  3865. $url_param = explode('=', $url_param, 2);
  3866. $s_hidden_fields[$url_param[0]] = $url_param[1];
  3867. }
  3868. }
  3869. // The following assigns all _common_ variables that may be used at any point in a template.
  3870. $template->assign_vars(array(
  3871. 'SITENAME' => $config['sitename'],
  3872. 'SITE_DESCRIPTION' => $config['site_desc'],
  3873. 'PAGE_TITLE' => $page_title,
  3874. 'SCRIPT_NAME' => str_replace('.' . $phpEx, '', $user->page['page_name']),
  3875. 'LAST_VISIT_DATE' => sprintf($user->lang['YOU_LAST_VISIT'], $s_last_visit),
  3876. 'LAST_VISIT_YOU' => $s_last_visit,
  3877. 'CURRENT_TIME' => sprintf($user->lang['CURRENT_TIME'], $user->format_date(time(), false, true)),
  3878. 'TOTAL_USERS_ONLINE' => $l_online_users,
  3879. 'LOGGED_IN_USER_LIST' => $online_userlist,
  3880. 'RECORD_USERS' => $l_online_record,
  3881. 'PRIVATE_MESSAGE_INFO' => $l_privmsgs_text,
  3882. 'PRIVATE_MESSAGE_INFO_UNREAD' => $l_privmsgs_text_unread,
  3883. 'S_USER_NEW_PRIVMSG' => $user->data['user_new_privmsg'],
  3884. 'S_USER_UNREAD_PRIVMSG' => $user->data['user_unread_privmsg'],
  3885. 'S_USER_NEW' => $user->data['user_new'],
  3886. 'SID' => $SID,
  3887. '_SID' => $_SID,
  3888. 'SESSION_ID' => $user->session_id,
  3889. 'ROOT_PATH' => $phpbb_root_path,
  3890. 'BOARD_URL' => $board_url,
  3891. 'L_LOGIN_LOGOUT' => $l_login_logout,
  3892. 'L_INDEX' => $user->lang['FORUM_INDEX'],
  3893. 'L_ONLINE_EXPLAIN' => $l_online_time,
  3894. 'U_PRIVATEMSGS' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;folder=inbox'),
  3895. 'U_RETURN_INBOX' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;folder=inbox'),
  3896. 'U_POPUP_PM' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;mode=popup'),
  3897. 'UA_POPUP_PM' => addslashes(append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;mode=popup')),
  3898. 'U_MEMBERLIST' => append_sid("{$phpbb_root_path}memberlist.$phpEx"),
  3899. 'U_VIEWONLINE' => ($auth->acl_gets('u_viewprofile', 'a_user', 'a_useradd', 'a_userdel')) ? append_sid("{$phpbb_root_path}viewonline.$phpEx") : '',
  3900. 'U_LOGIN_LOGOUT' => $u_login_logout,
  3901. 'U_INDEX' => append_sid("{$phpbb_root_path}index.$phpEx"),
  3902. 'U_SEARCH' => append_sid("{$phpbb_root_path}search.$phpEx"),
  3903. 'U_REGISTER' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register'),
  3904. 'U_PROFILE' => append_sid("{$phpbb_root_path}ucp.$phpEx"),
  3905. 'U_MODCP' => append_sid("{$phpbb_root_path}mcp.$phpEx", false, true, $user->session_id),
  3906. 'U_FAQ' => append_sid("{$phpbb_root_path}faq.$phpEx"),
  3907. 'U_SEARCH_SELF' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=egosearch'),
  3908. 'U_SEARCH_NEW' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=newposts'),
  3909. 'U_SEARCH_UNANSWERED' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unanswered'),
  3910. 'U_SEARCH_UNREAD' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unreadposts'),
  3911. 'U_SEARCH_ACTIVE_TOPICS'=> append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=active_topics'),
  3912. 'U_DELETE_COOKIES' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=delete_cookies'),
  3913. 'U_TEAM' => ($user->data['user_id'] != ANONYMOUS && !$auth->acl_get('u_viewprofile')) ? '' : append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=leaders'),
  3914. 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
  3915. 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
  3916. 'U_RESTORE_PERMISSIONS' => ($user->data['user_perm_from'] && $auth->acl_get('a_switchperm')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=restore_perm') : '',
  3917. 'U_FEED' => generate_board_url() . "/feed.$phpEx",
  3918. 'S_USER_LOGGED_IN' => ($user->data['user_id'] != ANONYMOUS) ? true : false,
  3919. 'S_AUTOLOGIN_ENABLED' => ($config['allow_autologin']) ? true : false,
  3920. 'S_BOARD_DISABLED' => ($config['board_disable']) ? true : false,
  3921. 'S_REGISTERED_USER' => (!empty($user->data['is_registered'])) ? true : false,
  3922. 'S_IS_BOT' => (!empty($user->data['is_bot'])) ? true : false,
  3923. 'S_USER_PM_POPUP' => $user->optionget('popuppm'),
  3924. 'S_USER_LANG' => $user_lang,
  3925. 'S_USER_BROWSER' => (isset($user->data['session_browser'])) ? $user->data['session_browser'] : $user->lang['UNKNOWN_BROWSER'],
  3926. 'S_USERNAME' => $user->data['username'],
  3927. 'S_CONTENT_DIRECTION' => $user->lang['DIRECTION'],
  3928. 'S_CONTENT_FLOW_BEGIN' => ($user->lang['DIRECTION'] == 'ltr') ? 'left' : 'right',
  3929. 'S_CONTENT_FLOW_END' => ($user->lang['DIRECTION'] == 'ltr') ? 'right' : 'left',
  3930. 'S_CONTENT_ENCODING' => 'UTF-8',
  3931. '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], ''),
  3932. 'S_DISPLAY_ONLINE_LIST' => ($l_online_time) ? 1 : 0,
  3933. 'S_DISPLAY_SEARCH' => (!$config['load_search']) ? 0 : (isset($auth) ? ($auth->acl_get('u_search') && $auth->acl_getf_global('f_search')) : 1),
  3934. 'S_DISPLAY_PM' => ($config['allow_privmsg'] && !empty($user->data['is_registered']) && ($auth->acl_get('u_readpm') || $auth->acl_get('u_sendpm'))) ? true : false,
  3935. 'S_DISPLAY_MEMBERLIST' => (isset($auth)) ? $auth->acl_get('u_viewprofile') : 0,
  3936. 'S_NEW_PM' => ($s_privmsg_new) ? 1 : 0,
  3937. 'S_REGISTER_ENABLED' => ($config['require_activation'] != USER_ACTIVATION_DISABLE) ? true : false,
  3938. 'S_FORUM_ID' => $forum_id,
  3939. 'S_TOPIC_ID' => $topic_id,
  3940. 'S_LOGIN_ACTION' => ((!defined('ADMIN_START')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login') : append_sid("index.$phpEx", false, true, $user->session_id)),
  3941. 'S_LOGIN_REDIRECT' => build_hidden_fields(array('redirect' => build_url())),
  3942. 'S_ENABLE_FEEDS' => ($config['feed_enable']) ? true : false,
  3943. 'S_ENABLE_FEEDS_OVERALL' => ($config['feed_overall']) ? true : false,
  3944. 'S_ENABLE_FEEDS_FORUMS' => ($config['feed_overall_forums']) ? true : false,
  3945. 'S_ENABLE_FEEDS_TOPICS' => ($config['feed_topics_new']) ? true : false,
  3946. 'S_ENABLE_FEEDS_TOPICS_ACTIVE' => ($config['feed_topics_active']) ? true : false,
  3947. 'S_ENABLE_FEEDS_NEWS' => ($s_feed_news) ? true : false,
  3948. 'S_LOAD_UNREADS' => ($config['load_unreads_search'] && ($config['load_anon_lastread'] || $user->data['is_registered'])) ? true : false,
  3949. 'S_SEARCH_HIDDEN_FIELDS' => build_hidden_fields($s_search_hidden_fields),
  3950. 'T_THEME_PATH' => "{$web_path}styles/" . $user->theme['theme_path'] . '/theme',
  3951. 'T_TEMPLATE_PATH' => "{$web_path}styles/" . $user->theme['template_path'] . '/template',
  3952. 'T_SUPER_TEMPLATE_PATH' => (isset($user->theme['template_inherit_path']) && $user->theme['template_inherit_path']) ? "{$web_path}styles/" . $user->theme['template_inherit_path'] . '/template' : "{$web_path}styles/" . $user->theme['template_path'] . '/template',
  3953. 'T_IMAGESET_PATH' => "{$web_path}styles/" . $user->theme['imageset_path'] . '/imageset',
  3954. 'T_IMAGESET_LANG_PATH' => "{$web_path}styles/" . $user->theme['imageset_path'] . '/imageset/' . $user->lang_name,
  3955. 'T_IMAGES_PATH' => "{$web_path}images/",
  3956. 'T_SMILIES_PATH' => "{$web_path}{$config['smilies_path']}/",
  3957. 'T_AVATAR_PATH' => "{$web_path}{$config['avatar_path']}/",
  3958. 'T_AVATAR_GALLERY_PATH' => "{$web_path}{$config['avatar_gallery_path']}/",
  3959. 'T_ICONS_PATH' => "{$web_path}{$config['icons_path']}/",
  3960. 'T_RANKS_PATH' => "{$web_path}{$config['ranks_path']}/",
  3961. 'T_UPLOAD_PATH' => "{$web_path}{$config['upload_path']}/",
  3962. 'T_STYLESHEET_LINK' => (!$user->theme['theme_storedb']) ? "{$web_path}styles/" . $user->theme['theme_path'] . '/theme/stylesheet.css' : append_sid("{$phpbb_root_path}style.$phpEx", 'id=' . $user->theme['style_id'] . '&amp;lang=' . $user->lang_name),
  3963. 'T_STYLESHEET_NAME' => $user->theme['theme_name'],
  3964. 'T_THEME_NAME' => $user->theme['theme_path'],
  3965. 'T_TEMPLATE_NAME' => $user->theme['template_path'],
  3966. 'T_SUPER_TEMPLATE_NAME' => (isset($user->theme['template_inherit_path']) && $user->theme['template_inherit_path']) ? $user->theme['template_inherit_path'] : $user->theme['template_path'],
  3967. 'T_IMAGESET_NAME' => $user->theme['imageset_path'],
  3968. 'T_IMAGESET_LANG_NAME' => $user->data['user_lang'],
  3969. 'T_IMAGES' => 'images',
  3970. 'T_SMILIES' => $config['smilies_path'],
  3971. 'T_AVATAR' => $config['avatar_path'],
  3972. 'T_AVATAR_GALLERY' => $config['avatar_gallery_path'],
  3973. 'T_ICONS' => $config['icons_path'],
  3974. 'T_RANKS' => $config['ranks_path'],
  3975. 'T_UPLOAD' => $config['upload_path'],
  3976. 'SITE_LOGO_IMG' => $user->img('site_logo'),
  3977. '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')),
  3978. ));
  3979. // application/xhtml+xml not used because of IE
  3980. header('Content-type: text/html; charset=UTF-8');
  3981. header('Cache-Control: private, no-cache="set-cookie"');
  3982. header('Expires: 0');
  3983. header('Pragma: no-cache');
  3984. if (!empty($user->data['is_bot']))
  3985. {
  3986. // Let reverse proxies know we detected a bot.
  3987. header('X-PHPBB-IS-BOT: yes');
  3988. }
  3989. return;
  3990. }
  3991. /**
  3992. * Generate page footer
  3993. */
  3994. function page_footer($run_cron = true)
  3995. {
  3996. global $db, $config, $template, $user, $auth, $cache, $starttime, $phpbb_root_path, $phpEx;
  3997. // Output page creation time
  3998. if (defined('DEBUG'))
  3999. {
  4000. $mtime = explode(' ', microtime());
  4001. $totaltime = $mtime[0] + $mtime[1] - $starttime;
  4002. if (!empty($_REQUEST['explain']) && $auth->acl_get('a_') && defined('DEBUG_EXTRA') && method_exists($db, 'sql_report'))
  4003. {
  4004. $db->sql_report('display');
  4005. }
  4006. $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);
  4007. if ($auth->acl_get('a_') && defined('DEBUG_EXTRA'))
  4008. {
  4009. if (function_exists('memory_get_usage'))
  4010. {
  4011. if ($memory_usage = memory_get_usage())
  4012. {
  4013. global $base_memory_usage;
  4014. $memory_usage -= $base_memory_usage;
  4015. $memory_usage = get_formatted_filesize($memory_usage);
  4016. $debug_output .= ' | Memory Usage: ' . $memory_usage;
  4017. }
  4018. }
  4019. $debug_output .= ' | <a href="' . build_url() . '&amp;explain=1">Explain</a>';
  4020. }
  4021. }
  4022. $template->assign_vars(array(
  4023. 'DEBUG_OUTPUT' => (defined('DEBUG')) ? $debug_output : '',
  4024. 'TRANSLATION_INFO' => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
  4025. 'U_ACP' => ($auth->acl_get('a_') && !empty($user->data['is_registered'])) ? append_sid("{$phpbb_root_path}adm/index.$phpEx", false, true, $user->session_id) : '')
  4026. );
  4027. // Call cron-type script
  4028. $call_cron = false;
  4029. if (!defined('IN_CRON') && $run_cron && !$config['board_disable'] && !$user->data['is_bot'])
  4030. {
  4031. $call_cron = true;
  4032. $time_now = (!empty($user->time_now) && is_int($user->time_now)) ? $user->time_now : time();
  4033. // Any old lock present?
  4034. if (!empty($config['cron_lock']))
  4035. {
  4036. $cron_time = explode(' ', $config['cron_lock']);
  4037. // If 1 hour lock is present we do not call cron.php
  4038. if ($cron_time[0] + 3600 >= $time_now)
  4039. {
  4040. $call_cron = false;
  4041. }
  4042. }
  4043. }
  4044. // Call cron job?
  4045. if ($call_cron)
  4046. {
  4047. $cron_type = '';
  4048. if ($time_now - $config['queue_interval'] > $config['last_queue_run'] && !defined('IN_ADMIN') && file_exists($phpbb_root_path . 'cache/queue.' . $phpEx))
  4049. {
  4050. // Process email queue
  4051. $cron_type = 'queue';
  4052. }
  4053. else if (method_exists($cache, 'tidy') && $time_now - $config['cache_gc'] > $config['cache_last_gc'])
  4054. {
  4055. // Tidy the cache
  4056. $cron_type = 'tidy_cache';
  4057. }
  4058. else if ($config['warnings_expire_days'] && ($time_now - $config['warnings_gc'] > $config['warnings_last_gc']))
  4059. {
  4060. $cron_type = 'tidy_warnings';
  4061. }
  4062. else if ($time_now - $config['database_gc'] > $config['database_last_gc'])
  4063. {
  4064. // Tidy the database
  4065. $cron_type = 'tidy_database';
  4066. }
  4067. else if ($time_now - $config['search_gc'] > $config['search_last_gc'])
  4068. {
  4069. // Tidy the search
  4070. $cron_type = 'tidy_search';
  4071. }
  4072. else if ($time_now - $config['session_gc'] > $config['session_last_gc'])
  4073. {
  4074. $cron_type = 'tidy_sessions';
  4075. }
  4076. if ($cron_type)
  4077. {
  4078. $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" />');
  4079. }
  4080. }
  4081. $template->display('body');
  4082. garbage_collection();
  4083. exit_handler();
  4084. }
  4085. /**
  4086. * Closing the cache object and the database
  4087. * Cool function name, eh? We might want to add operations to it later
  4088. */
  4089. function garbage_collection()
  4090. {
  4091. global $cache, $db;
  4092. // Unload cache, must be done before the DB connection if closed
  4093. if (!empty($cache))
  4094. {
  4095. $cache->unload();
  4096. }
  4097. // Close our DB connection.
  4098. if (!empty($db))
  4099. {
  4100. $db->sql_close();
  4101. }
  4102. }
  4103. /**
  4104. * Handler for exit calls in phpBB.
  4105. * This function supports hooks.
  4106. *
  4107. * Note: This function is called after the template has been outputted.
  4108. */
  4109. function exit_handler()
  4110. {
  4111. global $phpbb_hook, $config;
  4112. if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
  4113. {
  4114. if ($phpbb_hook->hook_return(__FUNCTION__))
  4115. {
  4116. return $phpbb_hook->hook_return_result(__FUNCTION__);
  4117. }
  4118. }
  4119. // As a pre-caution... some setups display a blank page if the flush() is not there.
  4120. (ob_get_level() > 0) ? @ob_flush() : @flush();
  4121. exit;
  4122. }
  4123. /**
  4124. * Handler for init calls in phpBB. This function is called in user::setup();
  4125. * This function supports hooks.
  4126. */
  4127. function phpbb_user_session_handler()
  4128. {
  4129. global $phpbb_hook;
  4130. if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
  4131. {
  4132. if ($phpbb_hook->hook_return(__FUNCTION__))
  4133. {
  4134. return $phpbb_hook->hook_return_result(__FUNCTION__);
  4135. }
  4136. }
  4137. return;
  4138. }
  4139. ?>