PageRenderTime 76ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/forum/includes/functions.php

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