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