PageRenderTime 59ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/station/forum/includes/functions.php

https://github.com/bryanveloso/sayonarane
PHP | 3893 lines | 2772 code | 564 blank | 557 comment | 587 complexity | ff8bce027d29e55356a3aecdf1285153 MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /**
  3. *
  4. * @package phpBB3
  5. * @version $Id: functions.php 9057 2008-11-10 16:24:18Z Kellanved $
  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. if (!isset($_REQUEST[$var_name]) || (is_array($_REQUEST[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($_REQUEST[$var_name])))
  67. {
  68. return (is_array($default)) ? array() : $default;
  69. }
  70. $var = $_REQUEST[$var_name];
  71. if (!is_array($default))
  72. {
  73. $type = gettype($default);
  74. }
  75. else
  76. {
  77. list($key_type, $type) = each($default);
  78. $type = gettype($type);
  79. $key_type = gettype($key_type);
  80. if ($type == 'array')
  81. {
  82. reset($default);
  83. $default = current($default);
  84. list($sub_key_type, $sub_type) = each($default);
  85. $sub_type = gettype($sub_type);
  86. $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type;
  87. $sub_key_type = gettype($sub_key_type);
  88. }
  89. }
  90. if (is_array($var))
  91. {
  92. $_var = $var;
  93. $var = array();
  94. foreach ($_var as $k => $v)
  95. {
  96. set_var($k, $k, $key_type);
  97. if ($type == 'array' && is_array($v))
  98. {
  99. foreach ($v as $_k => $_v)
  100. {
  101. if (is_array($_v))
  102. {
  103. $_v = null;
  104. }
  105. set_var($_k, $_k, $sub_key_type);
  106. set_var($var[$k][$_k], $_v, $sub_type, $multibyte);
  107. }
  108. }
  109. else
  110. {
  111. if ($type == 'array' || is_array($v))
  112. {
  113. $v = null;
  114. }
  115. set_var($var[$k], $v, $type, $multibyte);
  116. }
  117. }
  118. }
  119. else
  120. {
  121. set_var($var, $var, $type, $multibyte);
  122. }
  123. return $var;
  124. }
  125. /**
  126. * Set config value. Creates missing config entry.
  127. */
  128. function set_config($config_name, $config_value, $is_dynamic = false)
  129. {
  130. global $db, $cache, $config;
  131. $sql = 'UPDATE ' . CONFIG_TABLE . "
  132. SET config_value = '" . $db->sql_escape($config_value) . "'
  133. WHERE config_name = '" . $db->sql_escape($config_name) . "'";
  134. $db->sql_query($sql);
  135. if (!$db->sql_affectedrows() && !isset($config[$config_name]))
  136. {
  137. $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array(
  138. 'config_name' => $config_name,
  139. 'config_value' => $config_value,
  140. 'is_dynamic' => ($is_dynamic) ? 1 : 0));
  141. $db->sql_query($sql);
  142. }
  143. $config[$config_name] = $config_value;
  144. if (!$is_dynamic)
  145. {
  146. $cache->destroy('config');
  147. }
  148. }
  149. /**
  150. * Generates an alphanumeric random string of given length
  151. */
  152. function gen_rand_string($num_chars = 8)
  153. {
  154. $rand_str = unique_id();
  155. $rand_str = str_replace('0', 'Z', strtoupper(base_convert($rand_str, 16, 35)));
  156. return substr($rand_str, 0, $num_chars);
  157. }
  158. /**
  159. * Return unique id
  160. * @param string $extra additional entropy
  161. */
  162. function unique_id($extra = 'c')
  163. {
  164. static $dss_seeded = false;
  165. global $config;
  166. $val = $config['rand_seed'] . microtime();
  167. $val = md5($val);
  168. $config['rand_seed'] = md5($config['rand_seed'] . $val . $extra);
  169. if ($dss_seeded !== true && ($config['rand_seed_last_update'] < time() - rand(1,10)))
  170. {
  171. set_config('rand_seed', $config['rand_seed'], true);
  172. set_config('rand_seed_last_update', time(), true);
  173. $dss_seeded = true;
  174. }
  175. return substr($val, 4, 16);
  176. }
  177. /**
  178. * Return formatted string for filesizes
  179. */
  180. function get_formatted_filesize($bytes, $add_size_lang = true)
  181. {
  182. global $user;
  183. if ($bytes >= pow(2, 20))
  184. {
  185. return ($add_size_lang) ? round($bytes / 1024 / 1024, 2) . ' ' . $user->lang['MIB'] : round($bytes / 1024 / 1024, 2);
  186. }
  187. if ($bytes >= pow(2, 10))
  188. {
  189. return ($add_size_lang) ? round($bytes / 1024, 2) . ' ' . $user->lang['KIB'] : round($bytes / 1024, 2);
  190. }
  191. return ($add_size_lang) ? ($bytes) . ' ' . $user->lang['BYTES'] : ($bytes);
  192. }
  193. /**
  194. * Determine whether we are approaching the maximum execution time. Should be called once
  195. * at the beginning of the script in which it's used.
  196. * @return bool Either true if the maximum execution time is nearly reached, or false
  197. * if some time is still left.
  198. */
  199. function still_on_time($extra_time = 15)
  200. {
  201. static $max_execution_time, $start_time;
  202. $time = explode(' ', microtime());
  203. $current_time = $time[0] + $time[1];
  204. if (empty($max_execution_time))
  205. {
  206. $max_execution_time = (function_exists('ini_get')) ? (int) @ini_get('max_execution_time') : (int) @get_cfg_var('max_execution_time');
  207. // If zero, then set to something higher to not let the user catch the ten seconds barrier.
  208. if ($max_execution_time === 0)
  209. {
  210. $max_execution_time = 50 + $extra_time;
  211. }
  212. $max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50);
  213. // For debugging purposes
  214. // $max_execution_time = 10;
  215. global $starttime;
  216. $start_time = (empty($starttime)) ? $current_time : $starttime;
  217. }
  218. return (ceil($current_time - $start_time) < $max_execution_time) ? true : false;
  219. }
  220. /**
  221. *
  222. * @version Version 0.1 / slightly modified for phpBB 3.0.x (using $H$ as hash type identifier)
  223. *
  224. * Portable PHP password hashing framework.
  225. *
  226. * Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
  227. * the public domain.
  228. *
  229. * There's absolutely no warranty.
  230. *
  231. * The homepage URL for this framework is:
  232. *
  233. * http://www.openwall.com/phpass/
  234. *
  235. * Please be sure to update the Version line if you edit this file in any way.
  236. * It is suggested that you leave the main version number intact, but indicate
  237. * your project name (after the slash) and add your own revision information.
  238. *
  239. * Please do not change the "private" password hashing method implemented in
  240. * here, thereby making your hashes incompatible. However, if you must, please
  241. * change the hash type identifier (the "$P$") to something different.
  242. *
  243. * Obviously, since this code is in the public domain, the above are not
  244. * requirements (there can be none), but merely suggestions.
  245. *
  246. *
  247. * Hash the password
  248. */
  249. function phpbb_hash($password)
  250. {
  251. $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  252. $random_state = unique_id();
  253. $random = '';
  254. $count = 6;
  255. if (($fh = @fopen('/dev/urandom', 'rb')))
  256. {
  257. $random = fread($fh, $count);
  258. fclose($fh);
  259. }
  260. if (strlen($random) < $count)
  261. {
  262. $random = '';
  263. for ($i = 0; $i < $count; $i += 16)
  264. {
  265. $random_state = md5(unique_id() . $random_state);
  266. $random .= pack('H*', md5($random_state));
  267. }
  268. $random = substr($random, 0, $count);
  269. }
  270. $hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64);
  271. if (strlen($hash) == 34)
  272. {
  273. return $hash;
  274. }
  275. return md5($password);
  276. }
  277. /**
  278. * Check for correct password
  279. *
  280. * @param string $password The password in plain text
  281. * @param string $hash The stored password hash
  282. *
  283. * @return bool Returns true if the password is correct, false if not.
  284. */
  285. function phpbb_check_hash($password, $hash)
  286. {
  287. $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  288. if (strlen($hash) == 34)
  289. {
  290. return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
  291. }
  292. return (md5($password) === $hash) ? true : false;
  293. }
  294. /**
  295. * Generate salt for hash generation
  296. */
  297. function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6)
  298. {
  299. if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
  300. {
  301. $iteration_count_log2 = 8;
  302. }
  303. $output = '$H$';
  304. $output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)];
  305. $output .= _hash_encode64($input, 6, $itoa64);
  306. return $output;
  307. }
  308. /**
  309. * Encode hash
  310. */
  311. function _hash_encode64($input, $count, &$itoa64)
  312. {
  313. $output = '';
  314. $i = 0;
  315. do
  316. {
  317. $value = ord($input[$i++]);
  318. $output .= $itoa64[$value & 0x3f];
  319. if ($i < $count)
  320. {
  321. $value |= ord($input[$i]) << 8;
  322. }
  323. $output .= $itoa64[($value >> 6) & 0x3f];
  324. if ($i++ >= $count)
  325. {
  326. break;
  327. }
  328. if ($i < $count)
  329. {
  330. $value |= ord($input[$i]) << 16;
  331. }
  332. $output .= $itoa64[($value >> 12) & 0x3f];
  333. if ($i++ >= $count)
  334. {
  335. break;
  336. }
  337. $output .= $itoa64[($value >> 18) & 0x3f];
  338. }
  339. while ($i < $count);
  340. return $output;
  341. }
  342. /**
  343. * The crypt function/replacement
  344. */
  345. function _hash_crypt_private($password, $setting, &$itoa64)
  346. {
  347. $output = '*';
  348. // Check for correct hash
  349. if (substr($setting, 0, 3) != '$H$')
  350. {
  351. return $output;
  352. }
  353. $count_log2 = strpos($itoa64, $setting[3]);
  354. if ($count_log2 < 7 || $count_log2 > 30)
  355. {
  356. return $output;
  357. }
  358. $count = 1 << $count_log2;
  359. $salt = substr($setting, 4, 8);
  360. if (strlen($salt) != 8)
  361. {
  362. return $output;
  363. }
  364. /**
  365. * We're kind of forced to use MD5 here since it's the only
  366. * cryptographic primitive available in all versions of PHP
  367. * currently in use. To implement our own low-level crypto
  368. * in PHP would result in much worse performance and
  369. * consequently in lower iteration counts and hashes that are
  370. * quicker to crack (by non-PHP code).
  371. */
  372. if (PHP_VERSION >= 5)
  373. {
  374. $hash = md5($salt . $password, true);
  375. do
  376. {
  377. $hash = md5($hash . $password, true);
  378. }
  379. while (--$count);
  380. }
  381. else
  382. {
  383. $hash = pack('H*', md5($salt . $password));
  384. do
  385. {
  386. $hash = pack('H*', md5($hash . $password));
  387. }
  388. while (--$count);
  389. }
  390. $output = substr($setting, 0, 12);
  391. $output .= _hash_encode64($hash, 16, $itoa64);
  392. return $output;
  393. }
  394. /**
  395. * Global function for chmodding directories and files for internal use
  396. * This function determines owner and group whom the file belongs to and user and group of PHP and then set safest possible file permissions.
  397. * The function determines owner and group from common.php file and sets the same to the provided file.
  398. * The function uses bit fields to build the permissions.
  399. * The function sets the appropiate execute bit on directories.
  400. *
  401. * Supported constants representing bit fields are:
  402. *
  403. * CHMOD_ALL - all permissions (7)
  404. * CHMOD_READ - read permission (4)
  405. * CHMOD_WRITE - write permission (2)
  406. * CHMOD_EXECUTE - execute permission (1)
  407. *
  408. * 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.
  409. *
  410. * @param $filename The file/directory to be chmodded
  411. * @param $perms Permissions to set
  412. * @return true on success, otherwise false
  413. *
  414. * @author faw, phpBB Group
  415. */
  416. function phpbb_chmod($filename, $perms = CHMOD_READ)
  417. {
  418. // Return if the file no longer exists.
  419. if (!file_exists($filename))
  420. {
  421. return false;
  422. }
  423. if (!function_exists('fileowner') || !function_exists('filegroup'))
  424. {
  425. $file_uid = $file_gid = false;
  426. $common_php_owner = $common_php_group = false;
  427. }
  428. else
  429. {
  430. global $phpbb_root_path, $phpEx;
  431. // Determine owner/group of common.php file and the filename we want to change here
  432. $common_php_owner = fileowner($phpbb_root_path . 'common.' . $phpEx);
  433. $common_php_group = filegroup($phpbb_root_path . 'common.' . $phpEx);
  434. $file_uid = fileowner($filename);
  435. $file_gid = filegroup($filename);
  436. // Try to set the owner to the same common.php has
  437. if ($common_php_owner !== $file_uid && $common_php_owner !== false && $file_uid !== false)
  438. {
  439. // Will most likely not work
  440. if (@chown($filename, $common_php_owner));
  441. {
  442. $file_uid = fileowner($filename);
  443. }
  444. }
  445. // Try to set the group to the same common.php has
  446. if ($common_php_group !== $file_gid && $common_php_group !== false && $file_gid !== false)
  447. {
  448. if (@chgrp($filename, $common_php_group));
  449. {
  450. $file_gid = filegroup($filename);
  451. }
  452. }
  453. }
  454. // And the owner and the groups PHP is running under.
  455. $php_uid = (function_exists('posix_getuid')) ? @posix_getuid() : false;
  456. $php_gids = (function_exists('posix_getgroups')) ? @posix_getgroups() : false;
  457. // Who is PHP?
  458. if ($file_uid === false || $file_gid === false || $php_uid === false || $php_gids === false)
  459. {
  460. $php = null;
  461. }
  462. else if ($file_uid == $php_uid /* && $common_php_owner !== false && $common_php_owner === $file_uid*/)
  463. {
  464. $php = 'owner';
  465. }
  466. else if (in_array($file_gid, $php_gids))
  467. {
  468. $php = 'group';
  469. }
  470. else
  471. {
  472. $php = 'other';
  473. }
  474. // Owner always has read/write permission
  475. $owner = CHMOD_READ | CHMOD_WRITE;
  476. if (is_dir($filename))
  477. {
  478. $owner |= CHMOD_EXECUTE;
  479. // Only add execute bit to the permission if the dir needs to be readable
  480. if ($perms & CHMOD_READ)
  481. {
  482. $perms |= CHMOD_EXECUTE;
  483. }
  484. }
  485. switch ($php)
  486. {
  487. case null:
  488. case 'owner':
  489. $result = @chmod($filename, ($owner << 6) + (0 << 3) + (0 << 0));
  490. if (!is_null($php) || (is_readable($filename) && is_writable($filename)))
  491. {
  492. break;
  493. }
  494. case 'group':
  495. $result = @chmod($filename, ($owner << 6) + ($perms << 3) + (0 << 0));
  496. if (!is_null($php) || ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || is_writable($filename))))
  497. {
  498. break;
  499. }
  500. case 'other':
  501. $result = @chmod($filename, ($owner << 6) + ($perms << 3) + ($perms << 0));
  502. if (!is_null($php) || ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || is_writable($filename))))
  503. {
  504. break;
  505. }
  506. default:
  507. return false;
  508. break;
  509. }
  510. return $result;
  511. }
  512. // Compatibility functions
  513. if (!function_exists('array_combine'))
  514. {
  515. /**
  516. * A wrapper for the PHP5 function array_combine()
  517. * @param array $keys contains keys for the resulting array
  518. * @param array $values contains values for the resulting array
  519. *
  520. * @return Returns an array by using the values from the keys array as keys and the
  521. * values from the values array as the corresponding values. Returns false if the
  522. * number of elements for each array isn't equal or if the arrays are empty.
  523. */
  524. function array_combine($keys, $values)
  525. {
  526. $keys = array_values($keys);
  527. $values = array_values($values);
  528. $n = sizeof($keys);
  529. $m = sizeof($values);
  530. if (!$n || !$m || ($n != $m))
  531. {
  532. return false;
  533. }
  534. $combined = array();
  535. for ($i = 0; $i < $n; $i++)
  536. {
  537. $combined[$keys[$i]] = $values[$i];
  538. }
  539. return $combined;
  540. }
  541. }
  542. if (!function_exists('str_split'))
  543. {
  544. /**
  545. * A wrapper for the PHP5 function str_split()
  546. * @param array $string contains the string to be converted
  547. * @param array $split_length contains the length of each chunk
  548. *
  549. * @return Converts a string to an array. If the optional split_length parameter is specified,
  550. * the returned array will be broken down into chunks with each being split_length in length,
  551. * otherwise each chunk will be one character in length. FALSE is returned if split_length is
  552. * less than 1. If the split_length length exceeds the length of string, the entire string is
  553. * returned as the first (and only) array element.
  554. */
  555. function str_split($string, $split_length = 1)
  556. {
  557. if ($split_length < 1)
  558. {
  559. return false;
  560. }
  561. else if ($split_length >= strlen($string))
  562. {
  563. return array($string);
  564. }
  565. else
  566. {
  567. preg_match_all('#.{1,' . $split_length . '}#s', $string, $matches);
  568. return $matches[0];
  569. }
  570. }
  571. }
  572. if (!function_exists('stripos'))
  573. {
  574. /**
  575. * A wrapper for the PHP5 function stripos
  576. * Find position of first occurrence of a case-insensitive string
  577. *
  578. * @param string $haystack is the string to search in
  579. * @param string $needle is the string to search for
  580. *
  581. * @return mixed Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.
  582. * Note that the needle may be a string of one or more characters.
  583. * If needle is not found, stripos() will return boolean FALSE.
  584. */
  585. function stripos($haystack, $needle)
  586. {
  587. if (preg_match('#' . preg_quote($needle, '#') . '#i', $haystack, $m))
  588. {
  589. return strpos($haystack, $m[0]);
  590. }
  591. return false;
  592. }
  593. }
  594. /**
  595. * Checks if a path ($path) is absolute or relative
  596. *
  597. * @param string $path Path to check absoluteness of
  598. * @return boolean
  599. */
  600. function is_absolute($path)
  601. {
  602. return ($path[0] == '/' || (DIRECTORY_SEPARATOR == '\\' && preg_match('#^[a-z]:/#i', $path))) ? true : false;
  603. }
  604. /**
  605. * @author Chris Smith <chris@project-minerva.org>
  606. * @copyright 2006 Project Minerva Team
  607. * @param string $path The path which we should attempt to resolve.
  608. * @return mixed
  609. */
  610. function phpbb_own_realpath($path)
  611. {
  612. // Now to perform funky shizzle
  613. // Switch to use UNIX slashes
  614. $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
  615. $path_prefix = '';
  616. // Determine what sort of path we have
  617. if (is_absolute($path))
  618. {
  619. $absolute = true;
  620. if ($path[0] == '/')
  621. {
  622. // Absolute path, *NIX style
  623. $path_prefix = '';
  624. }
  625. else
  626. {
  627. // Absolute path, Windows style
  628. // Remove the drive letter and colon
  629. $path_prefix = $path[0] . ':';
  630. $path = substr($path, 2);
  631. }
  632. }
  633. else
  634. {
  635. // Relative Path
  636. // Prepend the current working directory
  637. if (function_exists('getcwd'))
  638. {
  639. // This is the best method, hopefully it is enabled!
  640. $path = str_replace(DIRECTORY_SEPARATOR, '/', getcwd()) . '/' . $path;
  641. $absolute = true;
  642. if (preg_match('#^[a-z]:#i', $path))
  643. {
  644. $path_prefix = $path[0] . ':';
  645. $path = substr($path, 2);
  646. }
  647. else
  648. {
  649. $path_prefix = '';
  650. }
  651. }
  652. else if (isset($_SERVER['SCRIPT_FILENAME']) && !empty($_SERVER['SCRIPT_FILENAME']))
  653. {
  654. // Warning: If chdir() has been used this will lie!
  655. // Warning: This has some problems sometime (CLI can create them easily)
  656. $path = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['SCRIPT_FILENAME'])) . '/' . $path;
  657. $absolute = true;
  658. $path_prefix = '';
  659. }
  660. else
  661. {
  662. // We have no way of getting the absolute path, just run on using relative ones.
  663. $absolute = false;
  664. $path_prefix = '.';
  665. }
  666. }
  667. // Remove any repeated slashes
  668. $path = preg_replace('#/{2,}#', '/', $path);
  669. // Remove the slashes from the start and end of the path
  670. $path = trim($path, '/');
  671. // Break the string into little bits for us to nibble on
  672. $bits = explode('/', $path);
  673. // Remove any . in the path, renumber array for the loop below
  674. $bits = array_values(array_diff($bits, array('.')));
  675. // Lets get looping, run over and resolve any .. (up directory)
  676. for ($i = 0, $max = sizeof($bits); $i < $max; $i++)
  677. {
  678. // @todo Optimise
  679. if ($bits[$i] == '..' )
  680. {
  681. if (isset($bits[$i - 1]))
  682. {
  683. if ($bits[$i - 1] != '..')
  684. {
  685. // We found a .. and we are able to traverse upwards, lets do it!
  686. unset($bits[$i]);
  687. unset($bits[$i - 1]);
  688. $i -= 2;
  689. $max -= 2;
  690. $bits = array_values($bits);
  691. }
  692. }
  693. else if ($absolute) // ie. !isset($bits[$i - 1]) && $absolute
  694. {
  695. // We have an absolute path trying to descend above the root of the filesystem
  696. // ... Error!
  697. return false;
  698. }
  699. }
  700. }
  701. // Prepend the path prefix
  702. array_unshift($bits, $path_prefix);
  703. $resolved = '';
  704. $max = sizeof($bits) - 1;
  705. // Check if we are able to resolve symlinks, Windows cannot.
  706. $symlink_resolve = (function_exists('readlink')) ? true : false;
  707. foreach ($bits as $i => $bit)
  708. {
  709. if (@is_dir("$resolved/$bit") || ($i == $max && @is_file("$resolved/$bit")))
  710. {
  711. // Path Exists
  712. if ($symlink_resolve && is_link("$resolved/$bit") && ($link = readlink("$resolved/$bit")))
  713. {
  714. // Resolved a symlink.
  715. $resolved = $link . (($i == $max) ? '' : '/');
  716. continue;
  717. }
  718. }
  719. else
  720. {
  721. // Something doesn't exist here!
  722. // This is correct realpath() behaviour but sadly open_basedir and safe_mode make this problematic
  723. // return false;
  724. }
  725. $resolved .= $bit . (($i == $max) ? '' : '/');
  726. }
  727. // @todo If the file exists fine and open_basedir only has one path we should be able to prepend it
  728. // because we must be inside that basedir, the question is where...
  729. // @internal The slash in is_dir() gets around an open_basedir restriction
  730. if (!@file_exists($resolved) || (!is_dir($resolved . '/') && !is_file($resolved)))
  731. {
  732. return false;
  733. }
  734. // Put the slashes back to the native operating systems slashes
  735. $resolved = str_replace('/', DIRECTORY_SEPARATOR, $resolved);
  736. // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
  737. if (substr($resolved, -1) == DIRECTORY_SEPARATOR)
  738. {
  739. return substr($resolved, 0, -1);
  740. }
  741. return $resolved; // We got here, in the end!
  742. }
  743. if (!function_exists('realpath'))
  744. {
  745. /**
  746. * A wrapper for realpath
  747. * @ignore
  748. */
  749. function phpbb_realpath($path)
  750. {
  751. return phpbb_own_realpath($path);
  752. }
  753. }
  754. else
  755. {
  756. /**
  757. * A wrapper for realpath
  758. */
  759. function phpbb_realpath($path)
  760. {
  761. $realpath = realpath($path);
  762. // Strangely there are provider not disabling realpath but returning strange values. :o
  763. // We at least try to cope with them.
  764. if ($realpath === $path || $realpath === false)
  765. {
  766. return phpbb_own_realpath($path);
  767. }
  768. // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
  769. if (substr($realpath, -1) == DIRECTORY_SEPARATOR)
  770. {
  771. $realpath = substr($realpath, 0, -1);
  772. }
  773. return $realpath;
  774. }
  775. }
  776. if (!function_exists('htmlspecialchars_decode'))
  777. {
  778. /**
  779. * A wrapper for htmlspecialchars_decode
  780. * @ignore
  781. */
  782. function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
  783. {
  784. return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
  785. }
  786. }
  787. // functions used for building option fields
  788. /**
  789. * Pick a language, any language ...
  790. */
  791. function language_select($default = '')
  792. {
  793. global $db;
  794. $sql = 'SELECT lang_iso, lang_local_name
  795. FROM ' . LANG_TABLE . '
  796. ORDER BY lang_english_name';
  797. $result = $db->sql_query($sql);
  798. $lang_options = '';
  799. while ($row = $db->sql_fetchrow($result))
  800. {
  801. $selected = ($row['lang_iso'] == $default) ? ' selected="selected"' : '';
  802. $lang_options .= '<option value="' . $row['lang_iso'] . '"' . $selected . '>' . $row['lang_local_name'] . '</option>';
  803. }
  804. $db->sql_freeresult($result);
  805. return $lang_options;
  806. }
  807. /**
  808. * Pick a template/theme combo,
  809. */
  810. function style_select($default = '', $all = false)
  811. {
  812. global $db;
  813. $sql_where = (!$all) ? 'WHERE style_active = 1 ' : '';
  814. $sql = 'SELECT style_id, style_name
  815. FROM ' . STYLES_TABLE . "
  816. $sql_where
  817. ORDER BY style_name";
  818. $result = $db->sql_query($sql);
  819. $style_options = '';
  820. while ($row = $db->sql_fetchrow($result))
  821. {
  822. $selected = ($row['style_id'] == $default) ? ' selected="selected"' : '';
  823. $style_options .= '<option value="' . $row['style_id'] . '"' . $selected . '>' . $row['style_name'] . '</option>';
  824. }
  825. $db->sql_freeresult($result);
  826. return $style_options;
  827. }
  828. /**
  829. * Pick a timezone
  830. */
  831. function tz_select($default = '', $truncate = false)
  832. {
  833. global $user;
  834. $tz_select = '';
  835. foreach ($user->lang['tz_zones'] as $offset => $zone)
  836. {
  837. if ($truncate)
  838. {
  839. $zone_trunc = truncate_string($zone, 50, 255, false, '...');
  840. }
  841. else
  842. {
  843. $zone_trunc = $zone;
  844. }
  845. if (is_numeric($offset))
  846. {
  847. $selected = ($offset == $default) ? ' selected="selected"' : '';
  848. $tz_select .= '<option title="'.$zone.'" value="' . $offset . '"' . $selected . '>' . $zone_trunc . '</option>';
  849. }
  850. }
  851. return $tz_select;
  852. }
  853. // Functions handling topic/post tracking/marking
  854. /**
  855. * Marks a topic/forum as read
  856. * Marks a topic as posted to
  857. *
  858. * @param int $user_id can only be used with $mode == 'post'
  859. */
  860. function markread($mode, $forum_id = false, $topic_id = false, $post_time = 0, $user_id = 0)
  861. {
  862. global $db, $user, $config;
  863. if ($mode == 'all')
  864. {
  865. if ($forum_id === false || !sizeof($forum_id))
  866. {
  867. if ($config['load_db_lastread'] && $user->data['is_registered'])
  868. {
  869. // Mark all forums read (index page)
  870. $db->sql_query('DELETE FROM ' . TOPICS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
  871. $db->sql_query('DELETE FROM ' . FORUMS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
  872. $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
  873. }
  874. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  875. {
  876. $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  877. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  878. unset($tracking_topics['tf']);
  879. unset($tracking_topics['t']);
  880. unset($tracking_topics['f']);
  881. $tracking_topics['l'] = base_convert(time() - $config['board_startdate'], 10, 36);
  882. $user->set_cookie('track', tracking_serialize($tracking_topics), time() + 31536000);
  883. $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking_topics)) : tracking_serialize($tracking_topics);
  884. unset($tracking_topics);
  885. if ($user->data['is_registered'])
  886. {
  887. $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
  888. }
  889. }
  890. }
  891. return;
  892. }
  893. else if ($mode == 'topics')
  894. {
  895. // Mark all topics in forums read
  896. if (!is_array($forum_id))
  897. {
  898. $forum_id = array($forum_id);
  899. }
  900. // Add 0 to forums array to mark global announcements correctly
  901. $forum_id[] = 0;
  902. if ($config['load_db_lastread'] && $user->data['is_registered'])
  903. {
  904. $sql = 'DELETE FROM ' . TOPICS_TRACK_TABLE . "
  905. WHERE user_id = {$user->data['user_id']}
  906. AND " . $db->sql_in_set('forum_id', $forum_id);
  907. $db->sql_query($sql);
  908. $sql = 'SELECT forum_id
  909. FROM ' . FORUMS_TRACK_TABLE . "
  910. WHERE user_id = {$user->data['user_id']}
  911. AND " . $db->sql_in_set('forum_id', $forum_id);
  912. $result = $db->sql_query($sql);
  913. $sql_update = array();
  914. while ($row = $db->sql_fetchrow($result))
  915. {
  916. $sql_update[] = $row['forum_id'];
  917. }
  918. $db->sql_freeresult($result);
  919. if (sizeof($sql_update))
  920. {
  921. $sql = 'UPDATE ' . FORUMS_TRACK_TABLE . '
  922. SET mark_time = ' . time() . "
  923. WHERE user_id = {$user->data['user_id']}
  924. AND " . $db->sql_in_set('forum_id', $sql_update);
  925. $db->sql_query($sql);
  926. }
  927. if ($sql_insert = array_diff($forum_id, $sql_update))
  928. {
  929. $sql_ary = array();
  930. foreach ($sql_insert as $f_id)
  931. {
  932. $sql_ary[] = array(
  933. 'user_id' => (int) $user->data['user_id'],
  934. 'forum_id' => (int) $f_id,
  935. 'mark_time' => time()
  936. );
  937. }
  938. $db->sql_multi_insert(FORUMS_TRACK_TABLE, $sql_ary);
  939. }
  940. }
  941. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  942. {
  943. $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  944. $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
  945. foreach ($forum_id as $f_id)
  946. {
  947. $topic_ids36 = (isset($tracking['tf'][$f_id])) ? $tracking['tf'][$f_id] : array();
  948. if (isset($tracking['tf'][$f_id]))
  949. {
  950. unset($tracking['tf'][$f_id]);
  951. }
  952. foreach ($topic_ids36 as $topic_id36)
  953. {
  954. unset($tracking['t'][$topic_id36]);
  955. }
  956. if (isset($tracking['f'][$f_id]))
  957. {
  958. unset($tracking['f'][$f_id]);
  959. }
  960. $tracking['f'][$f_id] = base_convert(time() - $config['board_startdate'], 10, 36);
  961. }
  962. if (isset($tracking['tf']) && empty($tracking['tf']))
  963. {
  964. unset($tracking['tf']);
  965. }
  966. $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
  967. $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
  968. unset($tracking);
  969. }
  970. return;
  971. }
  972. else if ($mode == 'topic')
  973. {
  974. if ($topic_id === false || $forum_id === false)
  975. {
  976. return;
  977. }
  978. if ($config['load_db_lastread'] && $user->data['is_registered'])
  979. {
  980. $sql = 'UPDATE ' . TOPICS_TRACK_TABLE . '
  981. SET mark_time = ' . (($post_time) ? $post_time : time()) . "
  982. WHERE user_id = {$user->data['user_id']}
  983. AND topic_id = $topic_id";
  984. $db->sql_query($sql);
  985. // insert row
  986. if (!$db->sql_affectedrows())
  987. {
  988. $db->sql_return_on_error(true);
  989. $sql_ary = array(
  990. 'user_id' => (int) $user->data['user_id'],
  991. 'topic_id' => (int) $topic_id,
  992. 'forum_id' => (int) $forum_id,
  993. 'mark_time' => ($post_time) ? (int) $post_time : time(),
  994. );
  995. $db->sql_query('INSERT INTO ' . TOPICS_TRACK_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  996. $db->sql_return_on_error(false);
  997. }
  998. }
  999. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1000. {
  1001. $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1002. $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
  1003. $topic_id36 = base_convert($topic_id, 10, 36);
  1004. if (!isset($tracking['t'][$topic_id36]))
  1005. {
  1006. $tracking['tf'][$forum_id][$topic_id36] = true;
  1007. }
  1008. $post_time = ($post_time) ? $post_time : time();
  1009. $tracking['t'][$topic_id36] = base_convert($post_time - $config['board_startdate'], 10, 36);
  1010. // If the cookie grows larger than 10000 characters we will remove the smallest value
  1011. // This can result in old topics being unread - but most of the time it should be accurate...
  1012. if (isset($_COOKIE[$config['cookie_name'] . '_track']) && strlen($_COOKIE[$config['cookie_name'] . '_track']) > 10000)
  1013. {
  1014. //echo 'Cookie grown too large' . print_r($tracking, true);
  1015. // We get the ten most minimum stored time offsets and its associated topic ids
  1016. $time_keys = array();
  1017. for ($i = 0; $i < 10 && sizeof($tracking['t']); $i++)
  1018. {
  1019. $min_value = min($tracking['t']);
  1020. $m_tkey = array_search($min_value, $tracking['t']);
  1021. unset($tracking['t'][$m_tkey]);
  1022. $time_keys[$m_tkey] = $min_value;
  1023. }
  1024. // Now remove the topic ids from the array...
  1025. foreach ($tracking['tf'] as $f_id => $topic_id_ary)
  1026. {
  1027. foreach ($time_keys as $m_tkey => $min_value)
  1028. {
  1029. if (isset($topic_id_ary[$m_tkey]))
  1030. {
  1031. $tracking['f'][$f_id] = $min_value;
  1032. unset($tracking['tf'][$f_id][$m_tkey]);
  1033. }
  1034. }
  1035. }
  1036. if ($user->data['is_registered'])
  1037. {
  1038. $user->data['user_lastmark'] = intval(base_convert(max($time_keys) + $config['board_startdate'], 36, 10));
  1039. $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . $user->data['user_lastmark'] . " WHERE user_id = {$user->data['user_id']}");
  1040. }
  1041. else
  1042. {
  1043. $tracking['l'] = max($time_keys);
  1044. }
  1045. }
  1046. $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
  1047. $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
  1048. }
  1049. return;
  1050. }
  1051. else if ($mode == 'post')
  1052. {
  1053. if ($topic_id === false)
  1054. {
  1055. return;
  1056. }
  1057. $use_user_id = (!$user_id) ? $user->data['user_id'] : $user_id;
  1058. if ($config['load_db_track'] && $use_user_id != ANONYMOUS)
  1059. {
  1060. $db->sql_return_on_error(true);
  1061. $sql_ary = array(
  1062. 'user_id' => (int) $use_user_id,
  1063. 'topic_id' => (int) $topic_id,
  1064. 'topic_posted' => 1
  1065. );
  1066. $db->sql_query('INSERT INTO ' . TOPICS_POSTED_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  1067. $db->sql_return_on_error(false);
  1068. }
  1069. return;
  1070. }
  1071. }
  1072. /**
  1073. * Get topic tracking info by using already fetched info
  1074. */
  1075. function get_topic_tracking($forum_id, $topic_ids, &$rowset, $forum_mark_time, $global_announce_list = false)
  1076. {
  1077. global $config, $user;
  1078. $last_read = array();
  1079. if (!is_array($topic_ids))
  1080. {
  1081. $topic_ids = array($topic_ids);
  1082. }
  1083. foreach ($topic_ids as $topic_id)
  1084. {
  1085. if (!empty($rowset[$topic_id]['mark_time']))
  1086. {
  1087. $last_read[$topic_id] = $rowset[$topic_id]['mark_time'];
  1088. }
  1089. }
  1090. $topic_ids = array_diff($topic_ids, array_keys($last_read));
  1091. if (sizeof($topic_ids))
  1092. {
  1093. $mark_time = array();
  1094. // Get global announcement info
  1095. if ($global_announce_list && sizeof($global_announce_list))
  1096. {
  1097. if (!isset($forum_mark_time[0]))
  1098. {
  1099. global $db;
  1100. $sql = 'SELECT mark_time
  1101. FROM ' . FORUMS_TRACK_TABLE . "
  1102. WHERE user_id = {$user->data['user_id']}
  1103. AND forum_id = 0";
  1104. $result = $db->sql_query($sql);
  1105. $row = $db->sql_fetchrow($result);
  1106. $db->sql_freeresult($result);
  1107. if ($row)
  1108. {
  1109. $mark_time[0] = $row['mark_time'];
  1110. }
  1111. }
  1112. else
  1113. {
  1114. if ($forum_mark_time[0] !== false)
  1115. {
  1116. $mark_time[0] = $forum_mark_time[0];
  1117. }
  1118. }
  1119. }
  1120. if (!empty($forum_mark_time[$forum_id]) && $forum_mark_time[$forum_id] !== false)
  1121. {
  1122. $mark_time[$forum_id] = $forum_mark_time[$forum_id];
  1123. }
  1124. $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
  1125. foreach ($topic_ids as $topic_id)
  1126. {
  1127. if ($global_announce_list && isset($global_announce_list[$topic_id]))
  1128. {
  1129. $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
  1130. }
  1131. else
  1132. {
  1133. $last_read[$topic_id] = $user_lastmark;
  1134. }
  1135. }
  1136. }
  1137. return $last_read;
  1138. }
  1139. /**
  1140. * Get topic tracking info from db (for cookie based tracking only this function is used)
  1141. */
  1142. function get_complete_topic_tracking($forum_id, $topic_ids, $global_announce_list = false)
  1143. {
  1144. global $config, $user;
  1145. $last_read = array();
  1146. if (!is_array($topic_ids))
  1147. {
  1148. $topic_ids = array($topic_ids);
  1149. }
  1150. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1151. {
  1152. global $db;
  1153. $sql = 'SELECT topic_id, mark_time
  1154. FROM ' . TOPICS_TRACK_TABLE . "
  1155. WHERE user_id = {$user->data['user_id']}
  1156. AND " . $db->sql_in_set('topic_id', $topic_ids);
  1157. $result = $db->sql_query($sql);
  1158. while ($row = $db->sql_fetchrow($result))
  1159. {
  1160. $last_read[$row['topic_id']] = $row['mark_time'];
  1161. }
  1162. $db->sql_freeresult($result);
  1163. $topic_ids = array_diff($topic_ids, array_keys($last_read));
  1164. if (sizeof($topic_ids))
  1165. {
  1166. $sql = 'SELECT forum_id, mark_time
  1167. FROM ' . FORUMS_TRACK_TABLE . "
  1168. WHERE user_id = {$user->data['user_id']}
  1169. AND forum_id " .
  1170. (($global_announce_list && sizeof($global_announce_list)) ? "IN (0, $forum_id)" : "= $forum_id");
  1171. $result = $db->sql_query($sql);
  1172. $mark_time = array();
  1173. while ($row = $db->sql_fetchrow($result))
  1174. {
  1175. $mark_time[$row['forum_id']] = $row['mark_time'];
  1176. }
  1177. $db->sql_freeresult($result);
  1178. $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
  1179. foreach ($topic_ids as $topic_id)
  1180. {
  1181. if ($global_announce_list && isset($global_announce_list[$topic_id]))
  1182. {
  1183. $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
  1184. }
  1185. else
  1186. {
  1187. $last_read[$topic_id] = $user_lastmark;
  1188. }
  1189. }
  1190. }
  1191. }
  1192. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1193. {
  1194. global $tracking_topics;
  1195. if (!isset($tracking_topics) || !sizeof($tracking_topics))
  1196. {
  1197. $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1198. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1199. }
  1200. if (!$user->data['is_registered'])
  1201. {
  1202. $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
  1203. }
  1204. else
  1205. {
  1206. $user_lastmark = $user->data['user_lastmark'];
  1207. }
  1208. foreach ($topic_ids as $topic_id)
  1209. {
  1210. $topic_id36 = base_convert($topic_id, 10, 36);
  1211. if (isset($tracking_topics['t'][$topic_id36]))
  1212. {
  1213. $last_read[$topic_id] = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
  1214. }
  1215. }
  1216. $topic_ids = array_diff($topic_ids, array_keys($last_read));
  1217. if (sizeof($topic_ids))
  1218. {
  1219. $mark_time = array();
  1220. if ($global_announce_list && sizeof($global_announce_list))
  1221. {
  1222. if (isset($tracking_topics['f'][0]))
  1223. {
  1224. $mark_time[0] = base_convert($tracking_topics['f'][0], 36, 10) + $config['board_startdate'];
  1225. }
  1226. }
  1227. if (isset($tracking_topics['f'][$forum_id]))
  1228. {
  1229. $mark_time[$forum_id] = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
  1230. }
  1231. $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user_lastmark;
  1232. foreach ($topic_ids as $topic_id)
  1233. {
  1234. if ($global_announce_list && isset($global_announce_list[$topic_id]))
  1235. {
  1236. $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
  1237. }
  1238. else
  1239. {
  1240. $last_read[$topic_id] = $user_lastmark;
  1241. }
  1242. }
  1243. }
  1244. }
  1245. return $last_read;
  1246. }
  1247. /**
  1248. * Check for read forums and update topic tracking info accordingly
  1249. *
  1250. * @param int $forum_id the forum id to check
  1251. * @param int $forum_last_post_time the forums last post time
  1252. * @param int $f_mark_time the forums last mark time if user is registered and load_db_lastread enabled
  1253. * @param int $mark_time_forum false if the mark time needs to be obtained, else the last users forum mark time
  1254. *
  1255. * @return true if complete forum got marked read, else false.
  1256. */
  1257. function update_forum_tracking_info($forum_id, $forum_last_post_time, $f_mark_time = false, $mark_time_forum = false)
  1258. {
  1259. global $db, $tracking_topics, $user, $config;
  1260. // Determine the users last forum mark time if not given.
  1261. if ($mark_time_forum === false)
  1262. {
  1263. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1264. {
  1265. $mark_time_forum = (!empty($f_mark_time)) ? $f_mark_time : $user->data['user_lastmark'];
  1266. }
  1267. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1268. {
  1269. $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
  1270. $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
  1271. if (!$user->data['is_registered'])
  1272. {
  1273. $user->data['user_lastmark'] = (isset($tracking_topics['l'])) ? (int) (base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate']) : 0;
  1274. }
  1275. $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'];
  1276. }
  1277. }
  1278. // Check the forum for any left unread topics.
  1279. // If there are none, we mark the forum as read.
  1280. if ($config['load_db_lastread'] && $user->data['is_registered'])
  1281. {
  1282. if ($mark_time_forum >= $forum_last_post_time)
  1283. {
  1284. // We do not need to mark read, this happened before. Therefore setting this to true
  1285. $row = true;
  1286. }
  1287. else
  1288. {
  1289. $sql = 'SELECT t.forum_id FROM ' . TOPICS_TABLE . ' t
  1290. LEFT JOIN ' . TOPICS_TRACK_TABLE . ' tt ON (tt.topic_id = t.topic_id AND tt.user_id = ' . $user->data['user_id'] . ')
  1291. WHERE t.forum_id = ' . $forum_id . '
  1292. AND t.topic_last_post_time > ' . $mark_time_forum . '
  1293. AND t.topic_moved_id = 0
  1294. AND (tt.topic_id IS NULL OR tt.mark_time < t.topic_last_post_time)
  1295. GROUP BY t.forum_id';
  1296. $result = $db->sql_query_limit($sql, 1);
  1297. $row = $db->sql_fetchrow($result);
  1298. $db->sql_freeresult($result);
  1299. }
  1300. }
  1301. else if ($config['load_anon_lastread'] || $user->data['is_registered'])
  1302. {
  1303. // Get information from cookie
  1304. $row = false;
  1305. if (!isset($tracking_topics['tf'][$forum_id]))
  1306. {
  1307. // We do not need to mark read, this happened before. Therefore setting this to true
  1308. $row = true;
  1309. }
  1310. else
  1311. {
  1312. $sql = 'SELECT topic_id
  1313. FROM ' . TOPICS_TABLE . '
  1314. WHERE forum_id = ' . $forum_id . '
  1315. AND topic_last_post_time > ' . $mark_time_forum . '
  1316. AND topic_moved_id = 0';
  1317. $result = $db->sql_query($sql);
  1318. $check_forum = $tracking_topics['tf'][$forum_id];
  1319. $unread = false;
  1320. while ($row = $db->sql_fetchrow($result))
  1321. {
  1322. if (!isset($check_forum[base_convert($row['topic_id'], 10, 36)]))
  1323. {
  1324. $unread = true;
  1325. break;
  1326. }
  1327. }
  1328. $db->sql_freeresult($result);
  1329. $row = $unread;
  1330. }
  1331. }
  1332. else
  1333. {
  1334. $row = true;
  1335. }
  1336. if (!$row)
  1337. {
  1338. markread('topics', $forum_id);
  1339. return true;
  1340. }
  1341. return false;
  1342. }
  1343. /**
  1344. * Transform an array into a serialized format
  1345. */
  1346. function tracking_serialize($input)
  1347. {
  1348. $out = '';
  1349. foreach ($input as $key => $value)
  1350. {
  1351. if (is_array($value))
  1352. {
  1353. $out .= $key . ':(' . tracking_serialize($value) . ');';
  1354. }
  1355. else
  1356. {
  1357. $out .= $key . ':' . $value . ';';
  1358. }
  1359. }
  1360. return $out;
  1361. }
  1362. /**
  1363. * Transform a serialized array into an actual array
  1364. */
  1365. function tracking_unserialize($string, $max_depth = 3)
  1366. {
  1367. $n = strlen($string);
  1368. if ($n > 10010)
  1369. {
  1370. die('Invalid data supplied');
  1371. }
  1372. $data = $stack = array();
  1373. $key = '';
  1374. $mode = 0;
  1375. $level = &$data;
  1376. for ($i = 0; $i < $n; ++$i)
  1377. {
  1378. switch ($mode)
  1379. {
  1380. case 0:
  1381. switch ($string[$i])
  1382. {
  1383. case ':':
  1384. $level[$key] = 0;
  1385. $mode = 1;
  1386. break;
  1387. case ')':
  1388. unset($level);
  1389. $level = array_pop($stack);
  1390. $mode = 3;
  1391. break;
  1392. default:
  1393. $key .= $string[$i];
  1394. }
  1395. break;
  1396. case 1:
  1397. switch ($string[$i])
  1398. {
  1399. case '(':
  1400. if (sizeof($stack) >= $max_depth)
  1401. {
  1402. die('Invalid data supplied');
  1403. }
  1404. $stack[] = &$level;
  1405. $level[$key] = array();
  1406. $level = &$level[$key];
  1407. $key = '';
  1408. $mode = 0;
  1409. break;
  1410. default:
  1411. $level[$key] = $string[$i];
  1412. $mode = 2;
  1413. break;
  1414. }
  1415. break;
  1416. case 2:
  1417. switch ($string[$i])
  1418. {
  1419. case ')':
  1420. unset($level);
  1421. $level = array_pop($stack);
  1422. $mode = 3;
  1423. break;
  1424. case ';':
  1425. $key = '';
  1426. $mode = 0;
  1427. break;
  1428. default:
  1429. $level[$key] .= $string[$i];
  1430. break;
  1431. }
  1432. break;
  1433. case 3:
  1434. switch ($string[$i])
  1435. {
  1436. case ')':
  1437. unset($level);
  1438. $level = array_pop($stack);
  1439. break;
  1440. case ';':
  1441. $key = '';
  1442. $mode = 0;
  1443. break;
  1444. default:
  1445. die('Invalid data supplied');
  1446. break;
  1447. }
  1448. break;
  1449. }
  1450. }
  1451. if (sizeof($stack) != 0 || ($mode != 0 && $mode != 3))
  1452. {
  1453. die('Invalid data supplied');
  1454. }
  1455. return $level;
  1456. }
  1457. // Pagination functions
  1458. /**
  1459. * Pagination routine, generates page number sequence
  1460. * tpl_prefix is for using different pagination blocks at one page
  1461. */
  1462. function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = false, $tpl_prefix = '')
  1463. {
  1464. global $template, $user;
  1465. // Make sure $per_page is a valid value
  1466. $per_page = ($per_page <= 0) ? 1 : $per_page;
  1467. $seperator = '<span class="page-sep">' . $user->lang['COMMA_SEPARATOR'] . '</span>';
  1468. $total_pages = ceil($num_items / $per_page);
  1469. if ($total_pages == 1 || !$num_items)
  1470. {
  1471. return false;
  1472. }
  1473. $on_page = floor($start_item / $per_page) + 1;
  1474. $url_delim = (strpos($base_url, '?') === false) ? '?' : '&amp;';
  1475. $page_string = ($on_page == 1) ? '<strong>1</strong>' : '<a href="' . $base_url . '">1</a>';
  1476. if ($total_pages > 5)
  1477. {
  1478. $start_cnt = min(max(1, $on_page - 4), $total_pages - 5);
  1479. $end_cnt = max(min($total_pages, $on_page + 4), 6);
  1480. $page_string .= ($start_cnt > 1) ? ' ... ' : $seperator;
  1481. for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
  1482. {
  1483. $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
  1484. if ($i < $end_cnt - 1)
  1485. {
  1486. $page_string .= $seperator;
  1487. }
  1488. }
  1489. $page_string .= ($end_cnt < $total_pages) ? ' ... ' : $seperator;
  1490. }
  1491. else
  1492. {
  1493. $page_string .= $seperator;
  1494. for ($i = 2; $i < $total_pages; $i++)
  1495. {
  1496. $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
  1497. if ($i < $total_pages)
  1498. {
  1499. $page_string .= $seperator;
  1500. }
  1501. }
  1502. }
  1503. $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>';
  1504. if ($add_prevnext_text)
  1505. {
  1506. if ($on_page != 1)
  1507. {
  1508. $page_string = '<a href="' . $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page) . '">' . $user->lang['PREVIOUS'] . '</a>&nbsp;&nbsp;' . $page_string;
  1509. }
  1510. if ($on_page != $total_pages)
  1511. {
  1512. $page_string .= '&nbsp;&nbsp;<a href="' . $base_url . "{$url_delim}start=" . ($on_page * $per_page) . '">' . $user->lang['NEXT'] . '</a>';
  1513. }
  1514. }
  1515. $template->assign_vars(array(
  1516. $tpl_prefix . 'BASE_URL' => $base_url,
  1517. 'A_' . $tpl_prefix . 'BASE_URL' => addslashes($base_url),
  1518. $tpl_prefix . 'PER_PAGE' => $per_page,
  1519. $tpl_prefix . 'PREVIOUS_PAGE' => ($on_page == 1) ? '' : $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page),
  1520. $tpl_prefix . 'NEXT_PAGE' => ($on_page == $total_pages) ? '' : $base_url . "{$url_delim}start=" . ($on_page * $per_page),
  1521. $tpl_prefix . 'TOTAL_PAGES' => $total_pages,
  1522. ));
  1523. return $page_string;
  1524. }
  1525. /**
  1526. * Return current page (pagination)
  1527. */
  1528. function on_page($num_items, $per_page, $start)
  1529. {
  1530. global $template, $user;
  1531. // Make sure $per_page is a valid value
  1532. $per_page = ($per_page <= 0) ? 1 : $per_page;
  1533. $on_page = floor($start / $per_page) + 1;
  1534. $template->assign_vars(array(
  1535. 'ON_PAGE' => $on_page)
  1536. );
  1537. return sprintf($user->lang['PAGE_OF'], $on_page, max(ceil($num_items / $per_page), 1));
  1538. }
  1539. // Server functions (building urls, redirecting...)
  1540. /**
  1541. * Append session id to url.
  1542. * This function supports hooks.
  1543. *
  1544. * @param string $url The url the session id needs to be appended to (can have params)
  1545. * @param mixed $params String or array of additional url parameters
  1546. * @param bool $is_amp Is url using &amp; (true) or & (false)
  1547. * @param string $session_id Possibility to use a custom session id instead of the global one
  1548. *
  1549. * Examples:
  1550. * <code>
  1551. * append_sid("{$phpbb_root_path}viewtopic.$phpEx?t=1&amp;f=2");
  1552. * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&amp;f=2');
  1553. * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2', false);
  1554. * append_sid("{$phpbb_root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
  1555. * </code>
  1556. *
  1557. */
  1558. function append_sid($url, $params = false, $is_amp = true, $session_id = false)
  1559. {
  1560. global $_SID, $_EXTRA_URL, $phpbb_hook;
  1561. // Developers using the hook function need to globalise the $_SID and $_EXTRA_URL on their own and also handle it appropiatly.
  1562. // They could mimick most of what is within this function
  1563. if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__, $url, $params, $is_amp, $session_id))
  1564. {
  1565. if ($phpbb_hook->hook_return(__FUNCTION__))
  1566. {
  1567. return $phpbb_hook->hook_return_result(__FUNCTION__);
  1568. }
  1569. }
  1570. // Assign sid if session id is not specified
  1571. if ($session_id === false)
  1572. {
  1573. $session_id = $_SID;
  1574. }
  1575. $amp_delim = ($is_amp) ? '&amp;' : '&';
  1576. $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
  1577. // Appending custom url parameter?
  1578. $append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';
  1579. $anchor = '';
  1580. if (strpos($url, '#') !== false)
  1581. {
  1582. list($url, $anchor) = explode('#', $url, 2);
  1583. $anchor = '#' . $anchor;
  1584. }
  1585. else if (!is_array($params) && strpos($params, '#') !== false)
  1586. {
  1587. list($params, $anchor) = explode('#', $params, 2);
  1588. $anchor = '#' . $anchor;
  1589. }
  1590. // Use the short variant if possible ;)
  1591. if ($params === false)
  1592. {
  1593. // Append session id
  1594. if (!$session_id)
  1595. {
  1596. return $url . (($append_url) ? $url_delim . $append_url : '') . $anchor;
  1597. }
  1598. else
  1599. {
  1600. return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id . $anchor;
  1601. }
  1602. }
  1603. // Build string if parameters are specified as array
  1604. if (is_array($params))
  1605. {
  1606. $output = array();
  1607. foreach ($params as $key => $item)
  1608. {
  1609. if ($item === NULL)
  1610. {
  1611. continue;
  1612. }
  1613. if ($key == '#')
  1614. {
  1615. $anchor = '#' . $item;
  1616. continue;
  1617. }
  1618. $output[] = $key . '=' . $item;
  1619. }
  1620. $params = implode($amp_delim, $output);
  1621. }
  1622. // Append session id and parameters (even if they are empty)
  1623. // If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
  1624. return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
  1625. }
  1626. /**
  1627. * Generate board url (example: http://www.example.com/phpBB)
  1628. * @param bool $without_script_path if set to true the script path gets not appended (example: http://www.example.com)
  1629. */
  1630. function generate_board_url($without_script_path = false)
  1631. {
  1632. global $config, $user;
  1633. $server_name = $user->host;
  1634. $server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
  1635. // Forcing server vars is the only way to specify/override the protocol
  1636. if ($config['force_server_vars'] || !$server_name)
  1637. {
  1638. $server_protocol = ($config['server_protocol']) ? $config['server_protocol'] : (($config['cookie_secure']) ? 'https://' : 'http://');
  1639. $server_name = $config['server_name'];
  1640. $server_port = (int) $config['server_port'];
  1641. $script_path = $config['script_path'];
  1642. $url = $server_protocol . $server_name;
  1643. $cookie_secure = $config['cookie_secure'];
  1644. }
  1645. else
  1646. {
  1647. // Do not rely on cookie_secure, users seem to think that it means a secured cookie instead of an encrypted connection
  1648. $cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
  1649. $url = (($cookie_secure) ? 'https://' : 'http://') . $server_name;
  1650. $script_path = $user->page['root_script_path'];
  1651. }
  1652. if ($server_port && (($cookie_secure && $server_port <> 443) || (!$cookie_secure && $server_port <> 80)))
  1653. {
  1654. // HTTP HOST can carry a port number (we fetch $user->host, but for old versions this may be true)
  1655. if (strpos($server_name, ':') === false)
  1656. {
  1657. $url .= ':' . $server_port;
  1658. }
  1659. }
  1660. if (!$without_script_path)
  1661. {
  1662. $url .= $script_path;
  1663. }
  1664. // Strip / from the end
  1665. if (substr($url, -1, 1) == '/')
  1666. {
  1667. $url = substr($url, 0, -1);
  1668. }
  1669. return $url;
  1670. }
  1671. /**
  1672. * Redirects the user to another page then exits the script nicely
  1673. * This function is intended for urls within the board. It's not meant to redirect to cross-domains.
  1674. *
  1675. * @param string $url The url to redirect to
  1676. * @param bool $return If true, do not redirect but return the sanitized URL. Default is no return.
  1677. * @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.
  1678. */
  1679. function redirect($url, $return = false, $disable_cd_check = false)
  1680. {
  1681. global $db, $cache, $config, $user, $phpbb_root_path;
  1682. if (empty($user->lang))
  1683. {
  1684. $user->add_lang('common');
  1685. }
  1686. if (!$return)
  1687. {
  1688. garbage_collection();
  1689. }
  1690. // Make sure no &amp;'s are in, this will break the redirect
  1691. $url = str_replace('&amp;', '&', $url);
  1692. // Determine which type of redirect we need to handle...
  1693. $url_parts = parse_url($url);
  1694. if ($url_parts === false)
  1695. {
  1696. // Malformed url, redirect to current page...
  1697. $url = generate_board_url() . '/' . $user->page['page'];
  1698. }
  1699. else if (!empty($url_parts['scheme']) && !empty($url_parts['host']))
  1700. {
  1701. // Attention: only able to redirect within the same domain if $disable_cd_check is false (yourdomain.com -> www.yourdomain.com will not work)
  1702. if (!$disable_cd_check && $url_parts['host'] !== $user->host)
  1703. {
  1704. $url = generate_board_url();
  1705. }
  1706. }
  1707. else if ($url[0] == '/')
  1708. {
  1709. // Absolute uri, prepend direct url...
  1710. $url = generate_board_url(true) . $url;
  1711. }
  1712. else
  1713. {
  1714. // Relative uri
  1715. $pathinfo = pathinfo($url);
  1716. // Is the uri pointing to the current directory?
  1717. if ($pathinfo['dirname'] == '.')
  1718. {
  1719. $url = str_replace('./', '', $url);
  1720. // Strip / from the beginning
  1721. if ($url && substr($url, 0, 1) == '/')
  1722. {
  1723. $url = substr($url, 1);
  1724. }
  1725. if ($user->page['page_dir'])
  1726. {
  1727. $url = generate_board_url() . '/' . $user->page['page_dir'] . '/' . $url;
  1728. }
  1729. else
  1730. {
  1731. $url = generate_board_url() . '/' . $url;
  1732. }
  1733. }
  1734. else
  1735. {
  1736. // Used ./ before, but $phpbb_root_path is working better with urls within another root path
  1737. $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($phpbb_root_path)));
  1738. $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($pathinfo['dirname'])));
  1739. $intersection = array_intersect_assoc($root_dirs, $page_dirs);
  1740. $root_dirs = array_diff_assoc($root_dirs, $intersection);
  1741. $page_dirs = array_diff_assoc($page_dirs, $intersection);
  1742. $dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
  1743. // Strip / from the end
  1744. if ($dir && substr($dir, -1, 1) == '/')
  1745. {
  1746. $dir = substr($dir, 0, -1);
  1747. }
  1748. // Strip / from the beginning
  1749. if ($dir && substr($dir, 0, 1) == '/')
  1750. {
  1751. $dir = substr($dir, 1);
  1752. }
  1753. $url = str_replace($pathinfo['dirname'] . '/', '', $url);
  1754. // Strip / from the beginning
  1755. if (substr($url, 0, 1) == '/')
  1756. {
  1757. $url = substr($url, 1);
  1758. }
  1759. $url = (!empty($dir) ? $dir . '/' : '') . $url;
  1760. $url = generate_board_url() . '/' . $url;
  1761. }
  1762. }
  1763. // Make sure no linebreaks are there... to prevent http response splitting for PHP < 4.4.2
  1764. if (strpos(urldecode($url), "\n") !== false || strpos(urldecode($url), "\r") !== false || strpos($url, ';') !== false)
  1765. {
  1766. trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
  1767. }
  1768. // Now, also check the protocol and for a valid url the last time...
  1769. $allowed_protocols = array('http', 'https', 'ftp', 'ftps');
  1770. $url_parts = parse_url($url);
  1771. if ($url_parts === false || empty($url_parts['scheme']) || !in_array($url_parts['scheme'], $allowed_protocols))
  1772. {
  1773. trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
  1774. }
  1775. if ($return)
  1776. {
  1777. return $url;
  1778. }
  1779. // Redirect via an HTML form for PITA webservers
  1780. if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
  1781. {
  1782. header('Refresh: 0; URL=' . $url);
  1783. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  1784. echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="' . $user->lang['DIRECTION'] . '" lang="' . $user->lang['USER_LANG'] . '" xml:lang="' . $user->lang['USER_LANG'] . '">';
  1785. echo '<head>';
  1786. echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
  1787. echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&amp;', $url) . '" />';
  1788. echo '<title>' . $user->lang['REDIRECT'] . '</title>';
  1789. echo '</head>';
  1790. echo '<body>';
  1791. echo '<div style="text-align: center;">' . sprintf($user->lang['URL_REDIRECT'], '<a href="' . str_replace('&', '&amp;', $url) . '">', '</a>') . '</div>';
  1792. echo '</body>';
  1793. echo '</html>';
  1794. exit;
  1795. }
  1796. // Behave as per HTTP/1.1 spec for others
  1797. header('Location: ' . $url);
  1798. exit;
  1799. }
  1800. /**
  1801. * Re-Apply session id after page reloads
  1802. */
  1803. function reapply_sid($url)
  1804. {
  1805. global $phpEx, $phpbb_root_path;
  1806. if ($url === "index.$phpEx")
  1807. {
  1808. return append_sid("index.$phpEx");
  1809. }
  1810. else if ($url === "{$phpbb_root_path}index.$phpEx")
  1811. {
  1812. return append_sid("{$phpbb_root_path}index.$phpEx");
  1813. }
  1814. // Remove previously added sid
  1815. if (strpos($url, '?sid=') !== false)
  1816. {
  1817. $url = preg_replace('/(\?)sid=[a-z0-9]+(&amp;|&)?/', '\1', $url);
  1818. }
  1819. else if (strpos($url, '&sid=') !== false)
  1820. {
  1821. $url = preg_replace('/&sid=[a-z0-9]+(&)?/', '\1', $url);
  1822. }
  1823. else if (strpos($url, '&amp;sid=') !== false)
  1824. {
  1825. $url = preg_replace('/&amp;sid=[a-z0-9]+(&amp;)?/', '\1', $url);
  1826. }
  1827. return append_sid($url);
  1828. }
  1829. /**
  1830. * Returns url from the session/current page with an re-appended SID with optionally stripping vars from the url
  1831. */
  1832. function build_url($strip_vars = false)
  1833. {
  1834. global $user, $phpbb_root_path;
  1835. // Append SID
  1836. $redirect = append_sid($user->page['page'], false, false);
  1837. // Add delimiter if not there...
  1838. if (strpos($redirect, '?') === false)
  1839. {
  1840. $redirect .= '?';
  1841. }
  1842. // Strip vars...
  1843. if ($strip_vars !== false && strpos($redirect, '?') !== false)
  1844. {
  1845. if (!is_array($strip_vars))
  1846. {
  1847. $strip_vars = array($strip_vars);
  1848. }
  1849. $query = $_query = array();
  1850. $args = substr($redirect, strpos($redirect, '?') + 1);
  1851. $args = ($args) ? explode('&', $args) : array();
  1852. $redirect = substr($redirect, 0, strpos($redirect, '?'));
  1853. foreach ($args as $argument)
  1854. {
  1855. $arguments = explode('=', $argument);
  1856. $key = $arguments[0];
  1857. unset($arguments[0]);
  1858. $query[$key] = implode('=', $arguments);
  1859. }
  1860. // Strip the vars off
  1861. foreach ($strip_vars as $strip)
  1862. {
  1863. if (isset($query[$strip]))
  1864. {
  1865. unset($query[$strip]);
  1866. }
  1867. }
  1868. // Glue the remaining parts together... already urlencoded
  1869. foreach ($query as $key => $value)
  1870. {
  1871. $_query[] = $key . '=' . $value;
  1872. }
  1873. $query = implode('&', $_query);
  1874. $redirect .= ($query) ? '?' . $query : '';
  1875. }
  1876. return $phpbb_root_path . str_replace('&', '&amp;', $redirect);
  1877. }
  1878. /**
  1879. * Meta refresh assignment
  1880. */
  1881. function meta_refresh($time, $url)
  1882. {
  1883. global $template;
  1884. $url = redirect($url, true);
  1885. $url = str_replace('&', '&amp;', $url);
  1886. // For XHTML compatibility we change back & to &amp;
  1887. $template->assign_vars(array(
  1888. 'META' => '<meta http-equiv="refresh" content="' . $time . ';url=' . $url . '" />')
  1889. );
  1890. return $url;
  1891. }
  1892. //Form validation
  1893. /**
  1894. * Add a secret hash for use in links/GET requests
  1895. * @param string $link_name The name of the link; has to match the name used in check_link_hash, otherwise no restrictions apply
  1896. * @return string the hash
  1897. */
  1898. function generate_link_hash($link_name)
  1899. {
  1900. global $user;
  1901. if (!isset($user->data["hash_$link_name"]))
  1902. {
  1903. $user->data["hash_$link_name"] = substr(sha1($user->data['user_form_salt'] . $link_name), 0, 8);
  1904. }
  1905. return $user->data["hash_$link_name"];
  1906. }
  1907. /**
  1908. * checks a link hash - for GET requests
  1909. * @param string $token the submitted token
  1910. * @param string $link_name The name of the link
  1911. * @return boolean true if all is fine
  1912. */
  1913. function check_link_hash($token, $link_name)
  1914. {
  1915. return $token === generate_link_hash($link_name);
  1916. }
  1917. /**
  1918. * Add a secret token to the form (requires the S_FORM_TOKEN template variable)
  1919. * @param string $form_name The name of the form; has to match the name used in check_form_key, otherwise no restrictions apply
  1920. */
  1921. function add_form_key($form_name)
  1922. {
  1923. global $config, $template, $user;
  1924. $now = time();
  1925. $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
  1926. $token = sha1($now . $user->data['user_form_salt'] . $form_name . $token_sid);
  1927. $s_fields = build_hidden_fields(array(
  1928. 'creation_time' => $now,
  1929. 'form_token' => $token,
  1930. ));
  1931. $template->assign_vars(array(
  1932. 'S_FORM_TOKEN' => $s_fields,
  1933. ));
  1934. }
  1935. /**
  1936. * Check the form key. Required for all altering actions not secured by confirm_box
  1937. * @param string $form_name The name of the form; has to match the name used in add_form_key, otherwise no restrictions apply
  1938. * @param int $timespan The maximum acceptable age for a submitted form in seconds. Defaults to the config setting.
  1939. * @param string $return_page The address for the return link
  1940. * @param bool $trigger If true, the function will triger an error when encountering an invalid form
  1941. */
  1942. function check_form_key($form_name, $timespan = false, $return_page = '', $trigger = false)
  1943. {
  1944. global $config, $user;
  1945. if ($timespan === false)
  1946. {
  1947. // we enforce a minimum value of half a minute here.
  1948. $timespan = ($config['form_token_lifetime'] == -1) ? -1 : max(30, $config['form_token_lifetime']);
  1949. }
  1950. if (isset($_POST['creation_time']) && isset($_POST['form_token']))
  1951. {
  1952. $creation_time = abs(request_var('creation_time', 0));
  1953. $token = request_var('form_token', '');
  1954. $diff = time() - $creation_time;
  1955. // If creation_time and the time() now is zero we can assume it was not a human doing this (the check for if ($diff)...
  1956. if ($diff && ($diff <= $timespan || $timespan === -1))
  1957. {
  1958. $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
  1959. $key = sha1($creation_time . $user->data['user_form_salt'] . $form_name . $token_sid);
  1960. if ($key === $token)
  1961. {
  1962. return true;
  1963. }
  1964. }
  1965. }
  1966. if ($trigger)
  1967. {
  1968. trigger_error($user->lang['FORM_INVALID'] . $return_page);
  1969. }
  1970. return false;
  1971. }
  1972. // Message/Login boxes
  1973. /**
  1974. * Build Confirm box
  1975. * @param boolean $check True for checking if confirmed (without any additional parameters) and false for displaying the confirm box
  1976. * @param string $title Title/Message used for confirm box.
  1977. * message text is _CONFIRM appended to title.
  1978. * If title cannot be found in user->lang a default one is displayed
  1979. * If title_CONFIRM cannot be found in user->lang the text given is used.
  1980. * @param string $hidden Hidden variables
  1981. * @param string $html_body Template used for confirm box
  1982. * @param string $u_action Custom form action
  1983. */
  1984. function confirm_box($check, $title = '', $hidden = '', $html_body = 'confirm_body.html', $u_action = '')
  1985. {
  1986. global $user, $template, $db;
  1987. global $phpEx, $phpbb_root_path;
  1988. if (isset($_POST['cancel']))
  1989. {
  1990. return false;
  1991. }
  1992. $confirm = false;
  1993. if (isset($_POST['confirm']))
  1994. {
  1995. // language frontier
  1996. if ($_POST['confirm'] === $user->lang['YES'])
  1997. {
  1998. $confirm = true;
  1999. }
  2000. }
  2001. if ($check && $confirm)
  2002. {
  2003. $user_id = request_var('user_id', 0);
  2004. $session_id = request_var('sess', '');
  2005. $confirm_key = request_var('confirm_key', '');
  2006. 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'])
  2007. {
  2008. return false;
  2009. }
  2010. // Reset user_last_confirm_key
  2011. $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = ''
  2012. WHERE user_id = " . $user->data['user_id'];
  2013. $db->sql_query($sql);
  2014. return true;
  2015. }
  2016. else if ($check)
  2017. {
  2018. return false;
  2019. }
  2020. $s_hidden_fields = build_hidden_fields(array(
  2021. 'user_id' => $user->data['user_id'],
  2022. 'sess' => $user->session_id,
  2023. 'sid' => $user->session_id)
  2024. );
  2025. // generate activation key
  2026. $confirm_key = gen_rand_string(10);
  2027. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  2028. {
  2029. adm_page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
  2030. }
  2031. else
  2032. {
  2033. page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
  2034. }
  2035. $template->set_filenames(array(
  2036. 'body' => $html_body)
  2037. );
  2038. // If activation key already exist, we better do not re-use the key (something very strange is going on...)
  2039. if (request_var('confirm_key', ''))
  2040. {
  2041. // This should not occur, therefore we cancel the operation to safe the user
  2042. return false;
  2043. }
  2044. // re-add sid / transform & to &amp; for user->page (user->page is always using &)
  2045. $use_page = ($u_action) ? $phpbb_root_path . $u_action : $phpbb_root_path . str_replace('&', '&amp;', $user->page['page']);
  2046. $u_action = reapply_sid($use_page);
  2047. $u_action .= ((strpos($u_action, '?') === false) ? '?' : '&amp;') . 'confirm_key=' . $confirm_key;
  2048. $template->assign_vars(array(
  2049. 'MESSAGE_TITLE' => (!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title],
  2050. 'MESSAGE_TEXT' => (!isset($user->lang[$title . '_CONFIRM'])) ? $title : $user->lang[$title . '_CONFIRM'],
  2051. 'YES_VALUE' => $user->lang['YES'],
  2052. 'S_CONFIRM_ACTION' => $u_action,
  2053. 'S_HIDDEN_FIELDS' => $hidden . $s_hidden_fields)
  2054. );
  2055. $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = '" . $db->sql_escape($confirm_key) . "'
  2056. WHERE user_id = " . $user->data['user_id'];
  2057. $db->sql_query($sql);
  2058. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  2059. {
  2060. adm_page_footer();
  2061. }
  2062. else
  2063. {
  2064. page_footer();
  2065. }
  2066. }
  2067. /**
  2068. * Generate login box or verify password
  2069. */
  2070. function login_box($redirect = '', $l_explain = '', $l_success = '', $admin = false, $s_display = true)
  2071. {
  2072. global $db, $user, $template, $auth, $phpEx, $phpbb_root_path, $config;
  2073. $err = '';
  2074. // Make sure user->setup() has been called
  2075. if (empty($user->lang))
  2076. {
  2077. $user->setup();
  2078. }
  2079. // Print out error if user tries to authenticate as an administrator without having the privileges...
  2080. if ($admin && !$auth->acl_get('a_'))
  2081. {
  2082. // Not authd
  2083. // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
  2084. if ($user->data['is_registered'])
  2085. {
  2086. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2087. }
  2088. trigger_error('NO_AUTH_ADMIN');
  2089. }
  2090. if (isset($_POST['login']))
  2091. {
  2092. // Get credential
  2093. if ($admin)
  2094. {
  2095. $credential = request_var('credential', '');
  2096. if (strspn($credential, 'abcdef0123456789') !== strlen($credential) || strlen($credential) != 32)
  2097. {
  2098. if ($user->data['is_registered'])
  2099. {
  2100. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2101. }
  2102. trigger_error('NO_AUTH_ADMIN');
  2103. }
  2104. $password = request_var('password_' . $credential, '', true);
  2105. }
  2106. else
  2107. {
  2108. $password = request_var('password', '', true);
  2109. }
  2110. $username = request_var('username', '', true);
  2111. $autologin = (!empty($_POST['autologin'])) ? true : false;
  2112. $viewonline = (!empty($_POST['viewonline'])) ? 0 : 1;
  2113. $admin = ($admin) ? 1 : 0;
  2114. $viewonline = ($admin) ? $user->data['session_viewonline'] : $viewonline;
  2115. // Check if the supplied username is equal to the one stored within the database if re-authenticating
  2116. if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
  2117. {
  2118. // We log the attempt to use a different username...
  2119. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2120. trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
  2121. }
  2122. // If authentication is successful we redirect user to previous page
  2123. $result = $auth->login($username, $password, $autologin, $viewonline, $admin);
  2124. // If admin authentication and login, we will log if it was a success or not...
  2125. // We also break the operation on the first non-success login - it could be argued that the user already knows
  2126. if ($admin)
  2127. {
  2128. if ($result['status'] == LOGIN_SUCCESS)
  2129. {
  2130. add_log('admin', 'LOG_ADMIN_AUTH_SUCCESS');
  2131. }
  2132. else
  2133. {
  2134. // Only log the failed attempt if a real user tried to.
  2135. // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
  2136. if ($user->data['is_registered'])
  2137. {
  2138. add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
  2139. }
  2140. }
  2141. }
  2142. // The result parameter is always an array, holding the relevant information...
  2143. if ($result['status'] == LOGIN_SUCCESS)
  2144. {
  2145. $redirect = request_var('redirect', "{$phpbb_root_path}index.$phpEx");
  2146. $message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
  2147. $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']);
  2148. // append/replace SID (may change during the session for AOL users)
  2149. $redirect = reapply_sid($redirect);
  2150. // Special case... the user is effectively banned, but we allow founders to login
  2151. if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != USER_FOUNDER)
  2152. {
  2153. return;
  2154. }
  2155. $redirect = meta_refresh(3, $redirect);
  2156. trigger_error($message . '<br /><br />' . sprintf($l_redirect, '<a href="' . $redirect . '">', '</a>'));
  2157. }
  2158. // Something failed, determine what...
  2159. if ($result['status'] == LOGIN_BREAK)
  2160. {
  2161. trigger_error($result['error_msg']);
  2162. }
  2163. // Special cases... determine
  2164. switch ($result['status'])
  2165. {
  2166. case LOGIN_ERROR_ATTEMPTS:
  2167. // Show confirm image
  2168. $sql = 'DELETE FROM ' . CONFIRM_TABLE . "
  2169. WHERE session_id = '" . $db->sql_escape($user->session_id) . "'
  2170. AND confirm_type = " . CONFIRM_LOGIN;
  2171. $db->sql_query($sql);
  2172. // Generate code
  2173. $code = gen_rand_string(mt_rand(5, 8));
  2174. $confirm_id = md5(unique_id($user->ip));
  2175. $seed = hexdec(substr(unique_id(), 4, 10));
  2176. // compute $seed % 0x7fffffff
  2177. $seed -= 0x7fffffff * floor($seed / 0x7fffffff);
  2178. $sql = 'INSERT INTO ' . CONFIRM_TABLE . ' ' . $db->sql_build_array('INSERT', array(
  2179. 'confirm_id' => (string) $confirm_id,
  2180. 'session_id' => (string) $user->session_id,
  2181. 'confirm_type' => (int) CONFIRM_LOGIN,
  2182. 'code' => (string) $code,
  2183. 'seed' => (int) $seed)
  2184. );
  2185. $db->sql_query($sql);
  2186. $template->assign_vars(array(
  2187. 'S_CONFIRM_CODE' => true,
  2188. 'CONFIRM_ID' => $confirm_id,
  2189. 'CONFIRM_IMAGE' => '<img src="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=confirm&amp;id=' . $confirm_id . '&amp;type=' . CONFIRM_LOGIN) . '" alt="" title="" />',
  2190. 'L_LOGIN_CONFIRM_EXPLAIN' => sprintf($user->lang['LOGIN_CONFIRM_EXPLAIN'], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>'),
  2191. ));
  2192. $err = $user->lang[$result['error_msg']];
  2193. break;
  2194. case LOGIN_ERROR_PASSWORD_CONVERT:
  2195. $err = sprintf(
  2196. $user->lang[$result['error_msg']],
  2197. ($config['email_enable']) ? '<a href="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') . '">' : '',
  2198. ($config['email_enable']) ? '</a>' : '',
  2199. ($config['board_contact']) ? '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">' : '',
  2200. ($config['board_contact']) ? '</a>' : ''
  2201. );
  2202. break;
  2203. // Username, password, etc...
  2204. default:
  2205. $err = $user->lang[$result['error_msg']];
  2206. // Assign admin contact to some error messages
  2207. if ($result['error_msg'] == 'LOGIN_ERROR_USERNAME' || $result['error_msg'] == 'LOGIN_ERROR_PASSWORD')
  2208. {
  2209. $err = (!$config['board_contact']) ? sprintf($user->lang[$result['error_msg']], '', '') : sprintf($user->lang[$result['error_msg']], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');
  2210. }
  2211. break;
  2212. }
  2213. }
  2214. if (!$redirect)
  2215. {
  2216. // We just use what the session code determined...
  2217. // If we are not within the admin directory we use the page dir...
  2218. $redirect = '';
  2219. if (!$admin)
  2220. {
  2221. $redirect .= ($user->page['page_dir']) ? $user->page['page_dir'] . '/' : '';
  2222. }
  2223. $redirect .= $user->page['page_name'] . (($user->page['query_string']) ? '?' . htmlspecialchars($user->page['query_string']) : '');
  2224. }
  2225. // Assign credential for username/password pair
  2226. $credential = ($admin) ? md5(unique_id()) : false;
  2227. $s_hidden_fields = array(
  2228. 'redirect' => $redirect,
  2229. 'sid' => $user->session_id,
  2230. );
  2231. if ($admin)
  2232. {
  2233. $s_hidden_fields['credential'] = $credential;
  2234. }
  2235. $s_hidden_fields = build_hidden_fields($s_hidden_fields);
  2236. $template->assign_vars(array(
  2237. 'LOGIN_ERROR' => $err,
  2238. 'LOGIN_EXPLAIN' => $l_explain,
  2239. 'U_SEND_PASSWORD' => ($config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') : '',
  2240. 'U_RESEND_ACTIVATION' => ($config['require_activation'] != USER_ACTIVATION_NONE && $config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=resend_act') : '',
  2241. 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
  2242. 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
  2243. 'S_DISPLAY_FULL_LOGIN' => ($s_display) ? true : false,
  2244. 'S_LOGIN_ACTION' => (!$admin) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login') : append_sid("index.$phpEx", false, true, $user->session_id), // Needs to stay index.$phpEx because we are within the admin directory
  2245. 'S_HIDDEN_FIELDS' => $s_hidden_fields,
  2246. 'S_ADMIN_AUTH' => $admin,
  2247. 'USERNAME' => ($admin) ? $user->data['username'] : '',
  2248. 'USERNAME_CREDENTIAL' => 'username',
  2249. 'PASSWORD_CREDENTIAL' => ($admin) ? 'password_' . $credential : 'password',
  2250. ));
  2251. page_header($user->lang['LOGIN'], false);
  2252. $template->set_filenames(array(
  2253. 'body' => 'login_body.html')
  2254. );
  2255. make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"));
  2256. page_footer();
  2257. }
  2258. /**
  2259. * Generate forum login box
  2260. */
  2261. function login_forum_box($forum_data)
  2262. {
  2263. global $db, $config, $user, $template, $phpEx;
  2264. $password = request_var('password', '', true);
  2265. $sql = 'SELECT forum_id
  2266. FROM ' . FORUMS_ACCESS_TABLE . '
  2267. WHERE forum_id = ' . $forum_data['forum_id'] . '
  2268. AND user_id = ' . $user->data['user_id'] . "
  2269. AND session_id = '" . $db->sql_escape($user->session_id) . "'";
  2270. $result = $db->sql_query($sql);
  2271. $row = $db->sql_fetchrow($result);
  2272. $db->sql_freeresult($result);
  2273. if ($row)
  2274. {
  2275. return true;
  2276. }
  2277. if ($password)
  2278. {
  2279. // Remove expired authorised sessions
  2280. $sql = 'SELECT f.session_id
  2281. FROM ' . FORUMS_ACCESS_TABLE . ' f
  2282. LEFT JOIN ' . SESSIONS_TABLE . ' s ON (f.session_id = s.session_id)
  2283. WHERE s.session_id IS NULL';
  2284. $result = $db->sql_query($sql);
  2285. if ($row = $db->sql_fetchrow($result))
  2286. {
  2287. $sql_in = array();
  2288. do
  2289. {
  2290. $sql_in[] = (string) $row['session_id'];
  2291. }
  2292. while ($row = $db->sql_fetchrow($result));
  2293. // Remove expired sessions
  2294. $sql = 'DELETE FROM ' . FORUMS_ACCESS_TABLE . '
  2295. WHERE ' . $db->sql_in_set('session_id', $sql_in);
  2296. $db->sql_query($sql);
  2297. }
  2298. $db->sql_freeresult($result);
  2299. if (phpbb_check_hash($password, $forum_data['forum_password']))
  2300. {
  2301. $sql_ary = array(
  2302. 'forum_id' => (int) $forum_data['forum_id'],
  2303. 'user_id' => (int) $user->data['user_id'],
  2304. 'session_id' => (string) $user->session_id,
  2305. );
  2306. $db->sql_query('INSERT INTO ' . FORUMS_ACCESS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  2307. return true;
  2308. }
  2309. $template->assign_var('LOGIN_ERROR', $user->lang['WRONG_PASSWORD']);
  2310. }
  2311. page_header($user->lang['LOGIN']);
  2312. $template->assign_vars(array(
  2313. 'S_HIDDEN_FIELDS' => build_hidden_fields(array('f' => $forum_data['forum_id'])))
  2314. );
  2315. $template->set_filenames(array(
  2316. 'body' => 'login_forum.html')
  2317. );
  2318. page_footer();
  2319. }
  2320. // Little helpers
  2321. /**
  2322. * Little helper for the build_hidden_fields function
  2323. */
  2324. function _build_hidden_fields($key, $value, $specialchar, $stripslashes)
  2325. {
  2326. $hidden_fields = '';
  2327. if (!is_array($value))
  2328. {
  2329. $value = ($stripslashes) ? stripslashes($value) : $value;
  2330. $value = ($specialchar) ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value;
  2331. $hidden_fields .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />' . "\n";
  2332. }
  2333. else
  2334. {
  2335. foreach ($value as $_key => $_value)
  2336. {
  2337. $_key = ($stripslashes) ? stripslashes($_key) : $_key;
  2338. $_key = ($specialchar) ? htmlspecialchars($_key, ENT_COMPAT, 'UTF-8') : $_key;
  2339. $hidden_fields .= _build_hidden_fields($key . '[' . $_key . ']', $_value, $specialchar, $stripslashes);
  2340. }
  2341. }
  2342. return $hidden_fields;
  2343. }
  2344. /**
  2345. * Build simple hidden fields from array
  2346. *
  2347. * @param array $field_ary an array of values to build the hidden field from
  2348. * @param bool $specialchar if true, keys and values get specialchared
  2349. * @param bool $stripslashes if true, keys and values get stripslashed
  2350. *
  2351. * @return string the hidden fields
  2352. */
  2353. function build_hidden_fields($field_ary, $specialchar = false, $stripslashes = false)
  2354. {
  2355. $s_hidden_fields = '';
  2356. foreach ($field_ary as $name => $vars)
  2357. {
  2358. $name = ($stripslashes) ? stripslashes($name) : $name;
  2359. $name = ($specialchar) ? htmlspecialchars($name, ENT_COMPAT, 'UTF-8') : $name;
  2360. $s_hidden_fields .= _build_hidden_fields($name, $vars, $specialchar, $stripslashes);
  2361. }
  2362. return $s_hidden_fields;
  2363. }
  2364. /**
  2365. * Parse cfg file
  2366. */
  2367. function parse_cfg_file($filename, $lines = false)
  2368. {
  2369. $parsed_items = array();
  2370. if ($lines === false)
  2371. {
  2372. $lines = file($filename);
  2373. }
  2374. foreach ($lines as $line)
  2375. {
  2376. $line = trim($line);
  2377. if (!$line || $line[0] == '#' || ($delim_pos = strpos($line, '=')) === false)
  2378. {
  2379. continue;
  2380. }
  2381. // Determine first occurrence, since in values the equal sign is allowed
  2382. $key = strtolower(trim(substr($line, 0, $delim_pos)));
  2383. $value = trim(substr($line, $delim_pos + 1));
  2384. if (in_array($value, array('off', 'false', '0')))
  2385. {
  2386. $value = false;
  2387. }
  2388. else if (in_array($value, array('on', 'true', '1')))
  2389. {
  2390. $value = true;
  2391. }
  2392. else if (!trim($value))
  2393. {
  2394. $value = '';
  2395. }
  2396. else if (($value[0] == "'" && $value[sizeof($value) - 1] == "'") || ($value[0] == '"' && $value[sizeof($value) - 1] == '"'))
  2397. {
  2398. $value = substr($value, 1, sizeof($value)-2);
  2399. }
  2400. $parsed_items[$key] = $value;
  2401. }
  2402. return $parsed_items;
  2403. }
  2404. /**
  2405. * Add log event
  2406. */
  2407. function add_log()
  2408. {
  2409. global $db, $user;
  2410. $args = func_get_args();
  2411. $mode = array_shift($args);
  2412. $reportee_id = ($mode == 'user') ? intval(array_shift($args)) : '';
  2413. $forum_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
  2414. $topic_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
  2415. $action = array_shift($args);
  2416. $data = (!sizeof($args)) ? '' : serialize($args);
  2417. $sql_ary = array(
  2418. 'user_id' => (empty($user->data)) ? ANONYMOUS : $user->data['user_id'],
  2419. 'log_ip' => $user->ip,
  2420. 'log_time' => time(),
  2421. 'log_operation' => $action,
  2422. 'log_data' => $data,
  2423. );
  2424. switch ($mode)
  2425. {
  2426. case 'admin':
  2427. $sql_ary['log_type'] = LOG_ADMIN;
  2428. break;
  2429. case 'mod':
  2430. $sql_ary += array(
  2431. 'log_type' => LOG_MOD,
  2432. 'forum_id' => $forum_id,
  2433. 'topic_id' => $topic_id
  2434. );
  2435. break;
  2436. case 'user':
  2437. $sql_ary += array(
  2438. 'log_type' => LOG_USERS,
  2439. 'reportee_id' => $reportee_id
  2440. );
  2441. break;
  2442. case 'critical':
  2443. $sql_ary['log_type'] = LOG_CRITICAL;
  2444. break;
  2445. default:
  2446. return false;
  2447. }
  2448. $db->sql_query('INSERT INTO ' . LOG_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  2449. return $db->sql_nextid();
  2450. }
  2451. /**
  2452. * Return a nicely formatted backtrace (parts from the php manual by diz at ysagoon dot com)
  2453. */
  2454. function get_backtrace()
  2455. {
  2456. global $phpbb_root_path;
  2457. $output = '<div style="font-family: monospace;">';
  2458. $backtrace = debug_backtrace();
  2459. $path = phpbb_realpath($phpbb_root_path);
  2460. foreach ($backtrace as $number => $trace)
  2461. {
  2462. // We skip the first one, because it only shows this file/function
  2463. if ($number == 0)
  2464. {
  2465. continue;
  2466. }
  2467. // Strip the current directory from path
  2468. if (empty($trace['file']))
  2469. {
  2470. $trace['file'] = '';
  2471. }
  2472. else
  2473. {
  2474. $trace['file'] = str_replace(array($path, '\\'), array('', '/'), $trace['file']);
  2475. $trace['file'] = substr($trace['file'], 1);
  2476. }
  2477. $args = array();
  2478. // If include/require/include_once is not called, do not show arguments - they may contain sensible information
  2479. if (!in_array($trace['function'], array('include', 'require', 'include_once')))
  2480. {
  2481. unset($trace['args']);
  2482. }
  2483. else
  2484. {
  2485. // Path...
  2486. if (!empty($trace['args'][0]))
  2487. {
  2488. $argument = htmlspecialchars($trace['args'][0]);
  2489. $argument = str_replace(array($path, '\\'), array('', '/'), $argument);
  2490. $argument = substr($argument, 1);
  2491. $args[] = "'{$argument}'";
  2492. }
  2493. }
  2494. $trace['class'] = (!isset($trace['class'])) ? '' : $trace['class'];
  2495. $trace['type'] = (!isset($trace['type'])) ? '' : $trace['type'];
  2496. $output .= '<br />';
  2497. $output .= '<b>FILE:</b> ' . htmlspecialchars($trace['file']) . '<br />';
  2498. $output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
  2499. $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']) . '(' . ((sizeof($args)) ? implode(', ', $args) : '') . ')<br />';
  2500. }
  2501. $output .= '</div>';
  2502. return $output;
  2503. }
  2504. /**
  2505. * This function returns a regular expression pattern for commonly used expressions
  2506. * Use with / as delimiter for email mode and # for url modes
  2507. * mode can be: email|bbcode_htm|url|url_inline|www_url|www_url_inline|relative_url|relative_url_inline|ipv4|ipv6
  2508. */
  2509. function get_preg_expression($mode)
  2510. {
  2511. switch ($mode)
  2512. {
  2513. case 'email':
  2514. return '(?:[a-z0-9\'\.\-_\+\|]++|&amp;)+@[a-z0-9\-]+\.(?:[a-z0-9\-]+\.)*[a-z]+';
  2515. break;
  2516. case 'bbcode_htm':
  2517. return array(
  2518. '#<!\-\- e \-\-><a href="mailto:(.*?)">.*?</a><!\-\- e \-\->#',
  2519. '#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&amp;|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
  2520. '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
  2521. '#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
  2522. '#<!\-\- .*? \-\->#s',
  2523. '#<.*?>#s',
  2524. );
  2525. break;
  2526. // Whoa these look impressive!
  2527. // The code to generate the following two regular expressions which match valid IPv4/IPv6 addresses
  2528. // can be found in the develop directory
  2529. case 'ipv4':
  2530. 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])$#';
  2531. break;
  2532. case 'ipv6':
  2533. 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}:){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';
  2534. break;
  2535. case 'url':
  2536. case 'url_inline':
  2537. $inline = ($mode == 'url') ? ')' : '';
  2538. $scheme = ($mode == 'url') ? '[a-z\d+\-.]' : '[a-z\d+]'; // avoid automatic parsing of "word" in "last word.http://..."
  2539. // generated with regex generation file in the develop folder
  2540. 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})*)?";
  2541. break;
  2542. case 'www_url':
  2543. case 'www_url_inline':
  2544. $inline = ($mode == 'www_url') ? ')' : '';
  2545. 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})*)?";
  2546. break;
  2547. case 'relative_url':
  2548. case 'relative_url_inline':
  2549. $inline = ($mode == 'relative_url') ? ')' : '';
  2550. 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})*)?";
  2551. break;
  2552. }
  2553. return '';
  2554. }
  2555. /**
  2556. * Returns the first block of the specified IPv6 address and as many additional
  2557. * ones as specified in the length paramater.
  2558. * If length is zero, then an empty string is returned.
  2559. * If length is greater than 3 the complete IP will be returned
  2560. */
  2561. function short_ipv6($ip, $length)
  2562. {
  2563. if ($length < 1)
  2564. {
  2565. return '';
  2566. }
  2567. // extend IPv6 addresses
  2568. $blocks = substr_count($ip, ':') + 1;
  2569. if ($blocks < 9)
  2570. {
  2571. $ip = str_replace('::', ':' . str_repeat('0000:', 9 - $blocks), $ip);
  2572. }
  2573. if ($ip[0] == ':')
  2574. {
  2575. $ip = '0000' . $ip;
  2576. }
  2577. if ($length < 4)
  2578. {
  2579. $ip = implode(':', array_slice(explode(':', $ip), 0, 1 + $length));
  2580. }
  2581. return $ip;
  2582. }
  2583. /**
  2584. * Wrapper for php's checkdnsrr function.
  2585. *
  2586. * The windows failover is from the php manual
  2587. * Please make sure to check the return value for === true and === false, since NULL could
  2588. * be returned too.
  2589. *
  2590. * @return true if entry found, false if not, NULL if this function is not supported by this environment
  2591. */
  2592. function phpbb_checkdnsrr($host, $type = '')
  2593. {
  2594. $type = (!$type) ? 'MX' : $type;
  2595. if (DIRECTORY_SEPARATOR == '\\')
  2596. {
  2597. if (!function_exists('exec'))
  2598. {
  2599. return NULL;
  2600. }
  2601. // @exec('nslookup -retry=1 -timout=1 -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host), $output);
  2602. @exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host) . '.', $output);
  2603. // If output is empty, the nslookup failed
  2604. if (empty($output))
  2605. {
  2606. return NULL;
  2607. }
  2608. foreach ($output as $line)
  2609. {
  2610. if (!trim($line))
  2611. {
  2612. continue;
  2613. }
  2614. // Valid records begin with host name:
  2615. if (strpos($line, $host) === 0)
  2616. {
  2617. return true;
  2618. }
  2619. }
  2620. return false;
  2621. }
  2622. else if (function_exists('checkdnsrr'))
  2623. {
  2624. // The dot indicates to search the DNS root (helps those having DNS prefixes on the same domain)
  2625. return (checkdnsrr($host . '.', $type)) ? true : false;
  2626. }
  2627. return NULL;
  2628. }
  2629. // Handler, header and footer
  2630. /**
  2631. * Error and message handler, call with trigger_error if reqd
  2632. */
  2633. function msg_handler($errno, $msg_text, $errfile, $errline)
  2634. {
  2635. global $cache, $db, $auth, $template, $config, $user;
  2636. global $phpEx, $phpbb_root_path, $msg_title, $msg_long_text;
  2637. // Do not display notices if we suppress them via @
  2638. if (error_reporting() == 0)
  2639. {
  2640. return;
  2641. }
  2642. // Message handler is stripping text. In case we need it, we are possible to define long text...
  2643. if (isset($msg_long_text) && $msg_long_text && !$msg_text)
  2644. {
  2645. $msg_text = $msg_long_text;
  2646. }
  2647. switch ($errno)
  2648. {
  2649. case E_NOTICE:
  2650. case E_WARNING:
  2651. // Check the error reporting level and return if the error level does not match
  2652. // If DEBUG is defined the default level is E_ALL
  2653. if (($errno & ((defined('DEBUG')) ? E_ALL : error_reporting())) == 0)
  2654. {
  2655. return;
  2656. }
  2657. if (strpos($errfile, 'cache') === false && strpos($errfile, 'template.') === false)
  2658. {
  2659. // flush the content, else we get a white page if output buffering is on
  2660. if ((int) @ini_get('output_buffering') === 1 || strtolower(@ini_get('output_buffering')) === 'on')
  2661. {
  2662. @ob_flush();
  2663. }
  2664. // Another quick fix for those having gzip compression enabled, but do not flush if the coder wants to catch "something". ;)
  2665. if (!empty($config['gzip_compress']))
  2666. {
  2667. if (@extension_loaded('zlib') && !headers_sent() && !ob_get_level())
  2668. {
  2669. @ob_flush();
  2670. }
  2671. }
  2672. // remove complete path to installation, with the risk of changing backslashes meant to be there
  2673. $errfile = str_replace(array(phpbb_realpath($phpbb_root_path), '\\'), array('', '/'), $errfile);
  2674. $msg_text = str_replace(array(phpbb_realpath($phpbb_root_path), '\\'), array('', '/'), $msg_text);
  2675. echo '<b>[phpBB Debug] PHP Notice</b>: in file <b>' . $errfile . '</b> on line <b>' . $errline . '</b>: <b>' . $msg_text . '</b><br />' . "\n";
  2676. }
  2677. return;
  2678. break;
  2679. case E_USER_ERROR:
  2680. if (!empty($user) && !empty($user->lang))
  2681. {
  2682. $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
  2683. $msg_title = (!isset($msg_title)) ? $user->lang['GENERAL_ERROR'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
  2684. $l_return_index = sprintf($user->lang['RETURN_INDEX'], '<a href="' . $phpbb_root_path . '">', '</a>');
  2685. $l_notify = '';
  2686. if (!empty($config['board_contact']))
  2687. {
  2688. $l_notify = '<p>' . sprintf($user->lang['NOTIFY_ADMIN_EMAIL'], $config['board_contact']) . '</p>';
  2689. }
  2690. }
  2691. else
  2692. {
  2693. $msg_title = 'General Error';
  2694. $l_return_index = '<a href="' . $phpbb_root_path . '">Return to index page</a>';
  2695. $l_notify = '';
  2696. if (!empty($config['board_contact']))
  2697. {
  2698. $l_notify = '<p>Please notify the board administrator or webmaster: <a href="mailto:' . $config['board_contact'] . '">' . $config['board_contact'] . '</a></p>';
  2699. }
  2700. }
  2701. garbage_collection();
  2702. // Try to not call the adm page data...
  2703. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
  2704. echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
  2705. echo '<head>';
  2706. echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
  2707. echo '<title>' . $msg_title . '</title>';
  2708. echo '<style type="text/css">' . "\n" . '/* <![CDATA[ */' . "\n";
  2709. 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; } ';
  2710. echo 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
  2711. 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; } ';
  2712. echo '.panel { margin: 4px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
  2713. 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; } ';
  2714. 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; } ';
  2715. echo "\n" . '/* ]]> */' . "\n";
  2716. echo '</style>';
  2717. echo '</head>';
  2718. echo '<body id="errorpage">';
  2719. echo '<div id="wrap">';
  2720. echo ' <div id="page-header">';
  2721. echo ' ' . $l_return_index;
  2722. echo ' </div>';
  2723. echo ' <div id="acp">';
  2724. echo ' <div class="panel">';
  2725. echo ' <div id="content">';
  2726. echo ' <h1>' . $msg_title . '</h1>';
  2727. echo ' <div>' . $msg_text . '</div>';
  2728. echo $l_notify;
  2729. echo ' </div>';
  2730. echo ' </div>';
  2731. echo ' </div>';
  2732. echo ' <div id="page-footer">';
  2733. echo ' Powered by phpBB &copy; 2000, 2002, 2005, 2007 <a href="http://www.phpbb.com/">phpBB Group</a>';
  2734. echo ' </div>';
  2735. echo '</div>';
  2736. echo '</body>';
  2737. echo '</html>';
  2738. exit_handler();
  2739. // On a fatal error (and E_USER_ERROR *is* fatal) we never want other scripts to continue and force an exit here.
  2740. exit;
  2741. break;
  2742. case E_USER_WARNING:
  2743. case E_USER_NOTICE:
  2744. define('IN_ERROR_HANDLER', true);
  2745. if (empty($user->data))
  2746. {
  2747. $user->session_begin();
  2748. }
  2749. // We re-init the auth array to get correct results on login/logout
  2750. $auth->acl($user->data);
  2751. if (empty($user->lang))
  2752. {
  2753. $user->setup();
  2754. }
  2755. $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
  2756. $msg_title = (!isset($msg_title)) ? $user->lang['INFORMATION'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
  2757. if (!defined('HEADER_INC'))
  2758. {
  2759. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  2760. {
  2761. adm_page_header($msg_title);
  2762. }
  2763. else
  2764. {
  2765. page_header($msg_title);
  2766. }
  2767. }
  2768. $template->set_filenames(array(
  2769. 'body' => 'message_body.html')
  2770. );
  2771. $template->assign_vars(array(
  2772. 'MESSAGE_TITLE' => $msg_title,
  2773. 'MESSAGE_TEXT' => $msg_text,
  2774. 'S_USER_WARNING' => ($errno == E_USER_WARNING) ? true : false,
  2775. 'S_USER_NOTICE' => ($errno == E_USER_NOTICE) ? true : false)
  2776. );
  2777. // We do not want the cron script to be called on error messages
  2778. define('IN_CRON', true);
  2779. if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
  2780. {
  2781. adm_page_footer();
  2782. }
  2783. else
  2784. {
  2785. page_footer();
  2786. }
  2787. exit_handler();
  2788. break;
  2789. }
  2790. // If we notice an error not handled here we pass this back to PHP by returning false
  2791. // This may not work for all php versions
  2792. return false;
  2793. }
  2794. /**
  2795. * Queries the session table to get information about online guests
  2796. * @param int $forum_id Limits the search to the forum with this id
  2797. * @return int The number of active distinct guest sessions
  2798. */
  2799. function obtain_guest_count($forum_id = 0)
  2800. {
  2801. global $db, $config;
  2802. if ($forum_id)
  2803. {
  2804. $reading_sql = ' AND s.session_forum_id = ' . (int) $forum_id;
  2805. }
  2806. else
  2807. {
  2808. $reading_sql = '';
  2809. }
  2810. $time = (time() - (intval($config['load_online_time']) * 60));
  2811. // Get number of online guests
  2812. if ($db->sql_layer === 'sqlite')
  2813. {
  2814. $sql = 'SELECT COUNT(session_ip) as num_guests
  2815. FROM (
  2816. SELECT DISTINCT s.session_ip
  2817. FROM ' . SESSIONS_TABLE . ' s
  2818. WHERE s.session_user_id = ' . ANONYMOUS . '
  2819. AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
  2820. $reading_sql .
  2821. ')';
  2822. }
  2823. else
  2824. {
  2825. $sql = 'SELECT COUNT(DISTINCT s.session_ip) as num_guests
  2826. FROM ' . SESSIONS_TABLE . ' s
  2827. WHERE s.session_user_id = ' . ANONYMOUS . '
  2828. AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
  2829. $reading_sql;
  2830. }
  2831. $result = $db->sql_query($sql, 60);
  2832. $guests_online = (int) $db->sql_fetchfield('num_guests');
  2833. $db->sql_freeresult($result);
  2834. return $guests_online;
  2835. }
  2836. /**
  2837. * Queries the session table to get information about online users
  2838. * @param int $forum_id Limits the search to the forum with this id
  2839. * @return array An array containing the ids of online, hidden and visible users, as well as statistical info
  2840. */
  2841. function obtain_users_online($forum_id = 0)
  2842. {
  2843. global $db, $config, $user;
  2844. $reading_sql = '';
  2845. if ($forum_id !== 0)
  2846. {
  2847. $reading_sql = ' AND s.session_forum_id = ' . (int) $forum_id;
  2848. }
  2849. $online_users = array(
  2850. 'online_users' => array(),
  2851. 'hidden_users' => array(),
  2852. 'total_online' => 0,
  2853. 'visible_online' => 0,
  2854. 'hidden_online' => 0,
  2855. 'guests_online' => 0,
  2856. );
  2857. if ($config['load_online_guests'])
  2858. {
  2859. $online_users['guests_online'] = obtain_guest_count($forum_id);
  2860. }
  2861. // a little discrete magic to cache this for 30 seconds
  2862. $time = (time() - (intval($config['load_online_time']) * 60));
  2863. $sql = 'SELECT s.session_user_id, s.session_ip, s.session_viewonline
  2864. FROM ' . SESSIONS_TABLE . ' s
  2865. WHERE s.session_time >= ' . ($time - ((int) ($time % 30))) .
  2866. $reading_sql .
  2867. ' AND s.session_user_id <> ' . ANONYMOUS;
  2868. $result = $db->sql_query($sql);
  2869. while ($row = $db->sql_fetchrow($result))
  2870. {
  2871. // Skip multiple sessions for one user
  2872. if (!isset($online_users['online_users'][$row['session_user_id']]))
  2873. {
  2874. $online_users['online_users'][$row['session_user_id']] = (int) $row['session_user_id'];
  2875. if ($row['session_viewonline'])
  2876. {
  2877. $online_users['visible_online']++;
  2878. }
  2879. else
  2880. {
  2881. $online_users['hidden_users'][$row['session_user_id']] = (int) $row['session_user_id'];
  2882. $online_users['hidden_online']++;
  2883. }
  2884. }
  2885. }
  2886. $online_users['total_online'] = $online_users['guests_online'] + $online_users['visible_online'] + $online_users['hidden_online'];
  2887. $db->sql_freeresult($result);
  2888. return $online_users;
  2889. }
  2890. /**
  2891. * Uses the result of obtain_users_online to generate a localized, readable representation.
  2892. * @param mixed $online_users result of obtain_users_online - array with user_id lists for total, hidden and visible users, and statistics
  2893. * @param int $forum_id Indicate that the data is limited to one forum and not global.
  2894. * @return array An array containing the string for output to the template
  2895. */
  2896. function obtain_users_online_string($online_users, $forum_id = 0)
  2897. {
  2898. global $config, $db, $user, $auth;
  2899. $user_online_link = $online_userlist = '';
  2900. if (sizeof($online_users['online_users']))
  2901. {
  2902. $sql = 'SELECT username, username_clean, user_id, user_type, user_allow_viewonline, user_colour
  2903. FROM ' . USERS_TABLE . '
  2904. WHERE ' . $db->sql_in_set('user_id', $online_users['online_users']) . '
  2905. ORDER BY username_clean ASC';
  2906. $result = $db->sql_query($sql);
  2907. while ($row = $db->sql_fetchrow($result))
  2908. {
  2909. // User is logged in and therefore not a guest
  2910. if ($row['user_id'] != ANONYMOUS)
  2911. {
  2912. if (isset($online_users['hidden_users'][$row['user_id']]))
  2913. {
  2914. $row['username'] = '<em>' . $row['username'] . '</em>';
  2915. }
  2916. if (!isset($online_users['hidden_users'][$row['user_id']]) || $auth->acl_get('u_viewonline'))
  2917. {
  2918. $user_online_link = get_username_string(($row['user_type'] <> USER_IGNORE) ? 'full' : 'no_profile', $row['user_id'], $row['username'], $row['user_colour']);
  2919. $online_userlist .= ($online_userlist != '') ? ', ' . $user_online_link : $user_online_link;
  2920. }
  2921. }
  2922. }
  2923. $db->sql_freeresult($result);
  2924. }
  2925. if (!$online_userlist)
  2926. {
  2927. $online_userlist = $user->lang['NO_ONLINE_USERS'];
  2928. }
  2929. if ($forum_id === 0)
  2930. {
  2931. $online_userlist = $user->lang['REGISTERED_USERS'] . ' ' . $online_userlist;
  2932. }
  2933. else if ($config['load_online_guests'])
  2934. {
  2935. $l_online = ($online_users['guests_online'] === 1) ? $user->lang['BROWSING_FORUM_GUEST'] : $user->lang['BROWSING_FORUM_GUESTS'];
  2936. $online_userlist = sprintf($l_online, $online_userlist, $online_users['guests_online']);
  2937. }
  2938. else
  2939. {
  2940. $online_userlist = sprintf($user->lang['BROWSING_FORUM'], $online_userlist);
  2941. }
  2942. // Build online listing
  2943. $vars_online = array(
  2944. 'ONLINE' => array('total_online', 'l_t_user_s', 0),
  2945. 'REG' => array('visible_online', 'l_r_user_s', !$config['load_online_guests']),
  2946. 'HIDDEN' => array('hidden_online', 'l_h_user_s', $config['load_online_guests']),
  2947. 'GUEST' => array('guests_online', 'l_g_user_s', 0)
  2948. );
  2949. foreach ($vars_online as $l_prefix => $var_ary)
  2950. {
  2951. if ($var_ary[2])
  2952. {
  2953. $l_suffix = '_AND';
  2954. }
  2955. else
  2956. {
  2957. $l_suffix = '';
  2958. }
  2959. switch ($online_users[$var_ary[0]])
  2960. {
  2961. case 0:
  2962. ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_ZERO_TOTAL' . $l_suffix];
  2963. break;
  2964. case 1:
  2965. ${$var_ary[1]} = $user->lang[$l_prefix . '_USER_TOTAL' . $l_suffix];
  2966. break;
  2967. default:
  2968. ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_TOTAL' . $l_suffix];
  2969. break;
  2970. }
  2971. }
  2972. unset($vars_online);
  2973. $l_online_users = sprintf($l_t_user_s, $online_users['total_online']);
  2974. $l_online_users .= sprintf($l_r_user_s, $online_users['visible_online']);
  2975. $l_online_users .= sprintf($l_h_user_s, $online_users['hidden_online']);
  2976. if ($config['load_online_guests'])
  2977. {
  2978. $l_online_users .= sprintf($l_g_user_s, $online_users['guests_online']);
  2979. }
  2980. return array(
  2981. 'online_userlist' => $online_userlist,
  2982. 'l_online_users' => $l_online_users,
  2983. );
  2984. }
  2985. /**
  2986. * Generate page header
  2987. */
  2988. function page_header($page_title = '', $display_online_list = true)
  2989. {
  2990. global $db, $config, $template, $SID, $_SID, $user, $auth, $phpEx, $phpbb_root_path;
  2991. if (defined('HEADER_INC'))
  2992. {
  2993. return;
  2994. }
  2995. define('HEADER_INC', true);
  2996. // gzip_compression
  2997. if ($config['gzip_compress'])
  2998. {
  2999. if (@extension_loaded('zlib') && !headers_sent())
  3000. {
  3001. ob_start('ob_gzhandler');
  3002. }
  3003. }
  3004. // Generate logged in/logged out status
  3005. if ($user->data['user_id'] != ANONYMOUS)
  3006. {
  3007. $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=logout', true, $user->session_id);
  3008. $l_login_logout = sprintf($user->lang['LOGOUT_USER'], $user->data['username']);
  3009. }
  3010. else
  3011. {
  3012. $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login');
  3013. $l_login_logout = $user->lang['LOGIN'];
  3014. }
  3015. // Last visit date/time
  3016. $s_last_visit = ($user->data['user_id'] != ANONYMOUS) ? $user->format_date($user->data['session_last_visit']) : '';
  3017. // Get users online list ... if required
  3018. $l_online_users = $online_userlist = $l_online_record = '';
  3019. if ($config['load_online'] && $config['load_online_time'] && $display_online_list)
  3020. {
  3021. $f = request_var('f', 0);
  3022. $f = max($f, 0);
  3023. $online_users = obtain_users_online($f);
  3024. $user_online_strings = obtain_users_online_string($online_users, $f);
  3025. $l_online_users = $user_online_strings['l_online_users'];
  3026. $online_userlist = $user_online_strings['online_userlist'];
  3027. $total_online_users = $online_users['total_online'];
  3028. if ($total_online_users > $config['record_online_users'])
  3029. {
  3030. set_config('record_online_users', $total_online_users, true);
  3031. set_config('record_online_date', time(), true);
  3032. }
  3033. $l_online_record = sprintf($user->lang['RECORD_ONLINE_USERS'], $config['record_online_users'], $user->format_date($config['record_online_date']));
  3034. $l_online_time = ($config['load_online_time'] == 1) ? 'VIEW_ONLINE_TIME' : 'VIEW_ONLINE_TIMES';
  3035. $l_online_time = sprintf($user->lang[$l_online_time], $config['load_online_time']);
  3036. }
  3037. else
  3038. {
  3039. $l_online_time = '';
  3040. }
  3041. $l_privmsgs_text = $l_privmsgs_text_unread = '';
  3042. $s_privmsg_new = false;
  3043. // Obtain number of new private messages if user is logged in
  3044. if (!empty($user->data['is_registered']))
  3045. {
  3046. if ($user->data['user_new_privmsg'])
  3047. {
  3048. $l_message_new = ($user->data['user_new_privmsg'] == 1) ? $user->lang['NEW_PM'] : $user->lang['NEW_PMS'];
  3049. $l_privmsgs_text = sprintf($l_message_new, $user->data['user_new_privmsg']);
  3050. if (!$user->data['user_last_privmsg'] || $user->data['user_last_privmsg'] > $user->data['session_last_visit'])
  3051. {
  3052. $sql = 'UPDATE ' . USERS_TABLE . '
  3053. SET user_last_privmsg = ' . $user->data['session_last_visit'] . '
  3054. WHERE user_id = ' . $user->data['user_id'];
  3055. $db->sql_query($sql);
  3056. $s_privmsg_new = true;
  3057. }
  3058. else
  3059. {
  3060. $s_privmsg_new = false;
  3061. }
  3062. }
  3063. else
  3064. {
  3065. $l_privmsgs_text = $user->lang['NO_NEW_PM'];
  3066. $s_privmsg_new = false;
  3067. }
  3068. $l_privmsgs_text_unread = '';
  3069. if ($user->data['user_unread_privmsg'] && $user->data['user_unread_privmsg'] != $user->data['user_new_privmsg'])
  3070. {
  3071. $l_message_unread = ($user->data['user_unread_privmsg'] == 1) ? $user->lang['UNREAD_PM'] : $user->lang['UNREAD_PMS'];
  3072. $l_privmsgs_text_unread = sprintf($l_message_unread, $user->data['user_unread_privmsg']);
  3073. }
  3074. }
  3075. // Which timezone?
  3076. $tz = ($user->data['user_id'] != ANONYMOUS) ? strval(doubleval($user->data['user_timezone'])) : strval(doubleval($config['board_timezone']));
  3077. // Send a proper content-language to the output
  3078. $user_lang = $user->lang['USER_LANG'];
  3079. if (strpos($user_lang, '-x-') !== false)
  3080. {
  3081. $user_lang = substr($user_lang, 0, strpos($user_lang, '-x-'));
  3082. }
  3083. // The following assigns all _common_ variables that may be used at any point in a template.
  3084. $template->assign_vars(array(
  3085. 'SITENAME' => $config['sitename'],
  3086. 'SITE_DESCRIPTION' => $config['site_desc'],
  3087. 'PAGE_TITLE' => $page_title,
  3088. 'SCRIPT_NAME' => str_replace('.' . $phpEx, '', $user->page['page_name']),
  3089. 'LAST_VISIT_DATE' => sprintf($user->lang['YOU_LAST_VISIT'], $s_last_visit),
  3090. 'LAST_VISIT_YOU' => $s_last_visit,
  3091. 'CURRENT_TIME' => sprintf($user->lang['CURRENT_TIME'], $user->format_date(time(), false, true)),
  3092. 'TOTAL_USERS_ONLINE' => $l_online_users,
  3093. 'LOGGED_IN_USER_LIST' => $online_userlist,
  3094. 'RECORD_USERS' => $l_online_record,
  3095. 'PRIVATE_MESSAGE_INFO' => $l_privmsgs_text,
  3096. 'PRIVATE_MESSAGE_INFO_UNREAD' => $l_privmsgs_text_unread,
  3097. 'S_USER_NEW_PRIVMSG' => $user->data['user_new_privmsg'],
  3098. 'S_USER_UNREAD_PRIVMSG' => $user->data['user_unread_privmsg'],
  3099. 'SID' => $SID,
  3100. '_SID' => $_SID,
  3101. 'SESSION_ID' => $user->session_id,
  3102. 'ROOT_PATH' => $phpbb_root_path,
  3103. 'L_LOGIN_LOGOUT' => $l_login_logout,
  3104. 'L_INDEX' => $user->lang['FORUM_INDEX'],
  3105. 'L_ONLINE_EXPLAIN' => $l_online_time,
  3106. 'U_PRIVATEMSGS' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;folder=inbox'),
  3107. 'U_RETURN_INBOX' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;folder=inbox'),
  3108. 'U_POPUP_PM' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;mode=popup'),
  3109. 'UA_POPUP_PM' => addslashes(append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;mode=popup')),
  3110. 'U_MEMBERLIST' => append_sid("{$phpbb_root_path}memberlist.$phpEx"),
  3111. 'U_VIEWONLINE' => ($auth->acl_gets('u_viewprofile', 'a_user', 'a_useradd', 'a_userdel')) ? append_sid("{$phpbb_root_path}viewonline.$phpEx") : '',
  3112. 'U_LOGIN_LOGOUT' => $u_login_logout,
  3113. 'U_INDEX' => append_sid("{$phpbb_root_path}index.$phpEx"),
  3114. 'U_SEARCH' => append_sid("{$phpbb_root_path}search.$phpEx"),
  3115. 'U_REGISTER' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register'),
  3116. 'U_PROFILE' => append_sid("{$phpbb_root_path}ucp.$phpEx"),
  3117. 'U_MODCP' => append_sid("{$phpbb_root_path}mcp.$phpEx", false, true, $user->session_id),
  3118. 'U_FAQ' => append_sid("{$phpbb_root_path}faq.$phpEx"),
  3119. 'U_SEARCH_SELF' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=egosearch'),
  3120. 'U_SEARCH_NEW' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=newposts'),
  3121. 'U_SEARCH_UNANSWERED' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unanswered'),
  3122. 'U_SEARCH_ACTIVE_TOPICS'=> append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=active_topics'),
  3123. 'U_DELETE_COOKIES' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=delete_cookies'),
  3124. 'U_TEAM' => ($user->data['user_id'] != ANONYMOUS && !$auth->acl_get('u_viewprofile')) ? '' : append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=leaders'),
  3125. 'U_RESTORE_PERMISSIONS' => ($user->data['user_perm_from'] && $auth->acl_get('a_switchperm')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=restore_perm') : '',
  3126. 'S_USER_LOGGED_IN' => ($user->data['user_id'] != ANONYMOUS) ? true : false,
  3127. 'S_AUTOLOGIN_ENABLED' => ($config['allow_autologin']) ? true : false,
  3128. 'S_BOARD_DISABLED' => ($config['board_disable']) ? true : false,
  3129. 'S_REGISTERED_USER' => (!empty($user->data['is_registered'])) ? true : false,
  3130. 'S_IS_BOT' => (!empty($user->data['is_bot'])) ? true : false,
  3131. 'S_USER_PM_POPUP' => $user->optionget('popuppm'),
  3132. 'S_USER_LANG' => $user_lang,
  3133. 'S_USER_BROWSER' => (isset($user->data['session_browser'])) ? $user->data['session_browser'] : $user->lang['UNKNOWN_BROWSER'],
  3134. 'S_USERNAME' => $user->data['username'],
  3135. 'S_CONTENT_DIRECTION' => $user->lang['DIRECTION'],
  3136. 'S_CONTENT_FLOW_BEGIN' => ($user->lang['DIRECTION'] == 'ltr') ? 'left' : 'right',
  3137. 'S_CONTENT_FLOW_END' => ($user->lang['DIRECTION'] == 'ltr') ? 'right' : 'left',
  3138. 'S_CONTENT_ENCODING' => 'UTF-8',
  3139. 'S_TIMEZONE' => ($user->data['user_dst'] || ($user->data['user_id'] == ANONYMOUS && $config['board_dst'])) ? sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], $user->lang['tz']['dst']) : sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], ''),
  3140. 'S_DISPLAY_ONLINE_LIST' => ($l_online_time) ? 1 : 0,
  3141. 'S_DISPLAY_SEARCH' => (!$config['load_search']) ? 0 : (isset($auth) ? ($auth->acl_get('u_search') && $auth->acl_getf_global('f_search')) : 1),
  3142. 'S_DISPLAY_PM' => ($config['allow_privmsg'] && !empty($user->data['is_registered']) && ($auth->acl_get('u_readpm') || $auth->acl_get('u_sendpm'))) ? true : false,
  3143. 'S_DISPLAY_MEMBERLIST' => (isset($auth)) ? $auth->acl_get('u_viewprofile') : 0,
  3144. 'S_NEW_PM' => ($s_privmsg_new) ? 1 : 0,
  3145. 'S_REGISTER_ENABLED' => ($config['require_activation'] != USER_ACTIVATION_DISABLE) ? true : false,
  3146. 'T_THEME_PATH' => "{$phpbb_root_path}styles/" . $user->theme['theme_path'] . '/theme',
  3147. 'T_TEMPLATE_PATH' => "{$phpbb_root_path}styles/" . $user->theme['template_path'] . '/template',
  3148. 'T_SUPER_TEMPLATE_PATH' => (isset($user->theme['template_inherit_path']) && $user->theme['template_inherit_path']) ? "{$phpbb_root_path}styles/" . $user->theme['template_inherit_path'] . '/template' : "{$phpbb_root_path}styles/" . $user->theme['template_path'] . '/template',
  3149. 'T_IMAGESET_PATH' => "{$phpbb_root_path}styles/" . $user->theme['imageset_path'] . '/imageset',
  3150. 'T_IMAGESET_LANG_PATH' => "{$phpbb_root_path}styles/" . $user->theme['imageset_path'] . '/imageset/' . $user->data['user_lang'],
  3151. 'T_IMAGES_PATH' => "{$phpbb_root_path}images/",
  3152. 'T_SMILIES_PATH' => "{$phpbb_root_path}{$config['smilies_path']}/",
  3153. 'T_AVATAR_PATH' => "{$phpbb_root_path}{$config['avatar_path']}/",
  3154. 'T_AVATAR_GALLERY_PATH' => "{$phpbb_root_path}{$config['avatar_gallery_path']}/",
  3155. 'T_ICONS_PATH' => "{$phpbb_root_path}{$config['icons_path']}/",
  3156. 'T_RANKS_PATH' => "{$phpbb_root_path}{$config['ranks_path']}/",
  3157. 'T_UPLOAD_PATH' => "{$phpbb_root_path}{$config['upload_path']}/",
  3158. 'T_STYLESHEET_LINK' => (!$user->theme['theme_storedb']) ? "{$phpbb_root_path}styles/" . $user->theme['theme_path'] . '/theme/stylesheet.css' : "{$phpbb_root_path}style.$phpEx?sid=$user->session_id&amp;id=" . $user->theme['style_id'] . '&amp;lang=' . $user->data['user_lang'],
  3159. 'T_STYLESHEET_NAME' => $user->theme['theme_name'],
  3160. 'SITE_LOGO_IMG' => $user->img('site_logo'),
  3161. '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')),
  3162. ));
  3163. // application/xhtml+xml not used because of IE
  3164. header('Content-type: text/html; charset=UTF-8');
  3165. header('Cache-Control: private, no-cache="set-cookie"');
  3166. header('Expires: 0');
  3167. header('Pragma: no-cache');
  3168. return;
  3169. }
  3170. /**
  3171. * Generate page footer
  3172. */
  3173. function page_footer($run_cron = true)
  3174. {
  3175. global $db, $config, $template, $user, $auth, $cache, $starttime, $phpbb_root_path, $phpEx;
  3176. // Output page creation time
  3177. if (defined('DEBUG'))
  3178. {
  3179. $mtime = explode(' ', microtime());
  3180. $totaltime = $mtime[0] + $mtime[1] - $starttime;
  3181. if (!empty($_REQUEST['explain']) && $auth->acl_get('a_') && defined('DEBUG_EXTRA') && method_exists($db, 'sql_report'))
  3182. {
  3183. $db->sql_report('display');
  3184. }
  3185. $debug_output = sprintf('Time : %.3fs | ' . $db->sql_num_queries() . ' Queries | GZIP : ' . (($config['gzip_compress']) ? 'On' : 'Off') . (($user->load) ? ' | Load : ' . $user->load : ''), $totaltime);
  3186. if ($auth->acl_get('a_') && defined('DEBUG_EXTRA'))
  3187. {
  3188. if (function_exists('memory_get_usage'))
  3189. {
  3190. if ($memory_usage = memory_get_usage())
  3191. {
  3192. global $base_memory_usage;
  3193. $memory_usage -= $base_memory_usage;
  3194. $memory_usage = get_formatted_filesize($memory_usage);
  3195. $debug_output .= ' | Memory Usage: ' . $memory_usage;
  3196. }
  3197. }
  3198. $debug_output .= ' | <a href="' . build_url() . '&amp;explain=1">Explain</a>';
  3199. }
  3200. }
  3201. $template->assign_vars(array(
  3202. 'DEBUG_OUTPUT' => (defined('DEBUG')) ? $debug_output : '',
  3203. 'TRANSLATION_INFO' => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
  3204. 'U_ACP' => ($auth->acl_get('a_') && !empty($user->data['is_registered'])) ? append_sid("{$phpbb_root_path}adm/index.$phpEx", false, true, $user->session_id) : '')
  3205. );
  3206. // Call cron-type script
  3207. if (!defined('IN_CRON') && $run_cron && !$config['board_disable'])
  3208. {
  3209. $cron_type = '';
  3210. if (time() - $config['queue_interval'] > $config['last_queue_run'] && !defined('IN_ADMIN') && file_exists($phpbb_root_path . 'cache/queue.' . $phpEx))
  3211. {
  3212. // Process email queue
  3213. $cron_type = 'queue';
  3214. }
  3215. else if (method_exists($cache, 'tidy') && time() - $config['cache_gc'] > $config['cache_last_gc'])
  3216. {
  3217. // Tidy the cache
  3218. $cron_type = 'tidy_cache';
  3219. }
  3220. else if (time() - $config['warnings_gc'] > $config['warnings_last_gc'])
  3221. {
  3222. $cron_type = 'tidy_warnings';
  3223. }
  3224. else if (time() - $config['database_gc'] > $config['database_last_gc'])
  3225. {
  3226. // Tidy the database
  3227. $cron_type = 'tidy_database';
  3228. }
  3229. else if (time() - $config['search_gc'] > $config['search_last_gc'])
  3230. {
  3231. // Tidy the search
  3232. $cron_type = 'tidy_search';
  3233. }
  3234. else if (time() - $config['session_gc'] > $config['session_last_gc'])
  3235. {
  3236. $cron_type = 'tidy_sessions';
  3237. }
  3238. if ($cron_type)
  3239. {
  3240. $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" />');
  3241. }
  3242. }
  3243. $template->display('body');
  3244. garbage_collection();
  3245. exit_handler();
  3246. }
  3247. /**
  3248. * Closing the cache object and the database
  3249. * Cool function name, eh? We might want to add operations to it later
  3250. */
  3251. function garbage_collection()
  3252. {
  3253. global $cache, $db;
  3254. // Unload cache, must be done before the DB connection if closed
  3255. if (!empty($cache))
  3256. {
  3257. $cache->unload();
  3258. }
  3259. // Close our DB connection.
  3260. if (!empty($db))
  3261. {
  3262. $db->sql_close();
  3263. }
  3264. }
  3265. /**
  3266. * Handler for exit calls in phpBB.
  3267. * This function supports hooks.
  3268. *
  3269. * Note: This function is called after the template has been outputted.
  3270. */
  3271. function exit_handler()
  3272. {
  3273. global $phpbb_hook, $config;
  3274. if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
  3275. {
  3276. if ($phpbb_hook->hook_return(__FUNCTION__))
  3277. {
  3278. return $phpbb_hook->hook_return_result(__FUNCTION__);
  3279. }
  3280. }
  3281. // As a pre-caution... some setups display a blank page if the flush() is not there.
  3282. (empty($config['gzip_compress'])) ? @flush() : @ob_flush();
  3283. exit;
  3284. }
  3285. /**
  3286. * Handler for init calls in phpBB. This function is called in user::setup();
  3287. * This function supports hooks.
  3288. */
  3289. function phpbb_user_session_handler()
  3290. {
  3291. global $phpbb_hook;
  3292. if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
  3293. {
  3294. if ($phpbb_hook->hook_return(__FUNCTION__))
  3295. {
  3296. return $phpbb_hook->hook_return_result(__FUNCTION__);
  3297. }
  3298. }
  3299. return;
  3300. }
  3301. ?>