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