PageRenderTime 43ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/forum/includes/functions.php

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