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