5
* @version $Id: functions.php,v 1.647 2007/12/10 18:35:28 kellanved Exp $
6
* @copyright (c) 2005 phpBB Group
7
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
14
if (!defined('IN_PHPBB'))
19
// Common global functions
24
* Set variable, used by {@link request_var the request_var function}
28
function set_var(&$result, $var, $type, $multibyte = false)
33
if ($type == 'string')
35
$result = trim(htmlspecialchars(str_replace(array("\r\n", "\r"), array("\n", "\n"), $result), ENT_COMPAT, 'UTF-8'));
39
// Make sure multibyte characters are wellformed
42
if (!preg_match('/^./u', $result))
49
// no multibyte, allow only ASCII (0-127)
50
$result = preg_replace('/[\x80-\xFF]/', '?', $result);
54
$result = (STRIP) ? stripslashes($result) : $result;
61
* Used to get passed variable
63
function request_var($var_name, $default, $multibyte = false, $cookie = false)
65
if (!$cookie && isset($_COOKIE[$var_name]))
67
if (!isset($_GET[$var_name]) && !isset($_POST[$var_name]))
69
return (is_array($default)) ? array() : $default;
71
$_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name];
74
if (!isset($_REQUEST[$var_name]) || (is_array($_REQUEST[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($_REQUEST[$var_name])))
76
return (is_array($default)) ? array() : $default;
79
$var = $_REQUEST[$var_name];
80
if (!is_array($default))
82
$type = gettype($default);
86
list($key_type, $type) = each($default);
87
$type = gettype($type);
88
$key_type = gettype($key_type);
92
$default = current($default);
93
list($sub_key_type, $sub_type) = each($default);
94
$sub_type = gettype($sub_type);
95
$sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type;
96
$sub_key_type = gettype($sub_key_type);
105
foreach ($_var as $k => $v)
107
set_var($k, $k, $key_type);
108
if ($type == 'array' && is_array($v))
110
foreach ($v as $_k => $_v)
116
set_var($_k, $_k, $sub_key_type);
117
set_var($var[$k][$_k], $_v, $sub_type, $multibyte);
122
if ($type == 'array' || is_array($v))
126
set_var($var[$k], $v, $type, $multibyte);
132
set_var($var, $var, $type, $multibyte);
139
* Set config value. Creates missing config entry.
141
function set_config($config_name, $config_value, $is_dynamic = false)
143
global $db, $cache, $config;
145
$sql = 'UPDATE ' . CONFIG_TABLE . "
146
SET config_value = '" . $db->sql_escape($config_value) . "'
147
WHERE config_name = '" . $db->sql_escape($config_name) . "'";
148
$db->sql_query($sql);
150
if (!$db->sql_affectedrows() && !isset($config[$config_name]))
152
$sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array(
153
'config_name' => $config_name,
154
'config_value' => $config_value,
155
'is_dynamic' => ($is_dynamic) ? 1 : 0));
156
$db->sql_query($sql);
159
$config[$config_name] = $config_value;
163
$cache->destroy('config');
168
* Generates an alphanumeric random string of given length
170
function gen_rand_string($num_chars = 8)
172
$rand_str = unique_id();
173
$rand_str = str_replace('0', 'Z', strtoupper(base_convert($rand_str, 16, 35)));
175
return substr($rand_str, 0, $num_chars);
180
* @param string $extra additional entropy
182
function unique_id($extra = 'c')
184
static $dss_seeded = false;
187
$val = $config['rand_seed'] . microtime();
189
$config['rand_seed'] = md5($config['rand_seed'] . $val . $extra);
191
if ($dss_seeded !== true && ($config['rand_seed_last_update'] < time() - rand(1,10)))
193
set_config('rand_seed', $config['rand_seed'], true);
194
set_config('rand_seed_last_update', time(), true);
198
return substr($val, 4, 16);
202
* Determine whether we are approaching the maximum execution time. Should be called once
203
* at the beginning of the script in which it's used.
204
* @return bool Either true if the maximum execution time is nearly reached, or false
205
* if some time is still left.
207
function still_on_time($extra_time = 15)
209
static $max_execution_time, $start_time;
211
$time = explode(' ', microtime());
212
$current_time = $time[0] + $time[1];
214
if (empty($max_execution_time))
216
$max_execution_time = (function_exists('ini_get')) ? (int) @ini_get('max_execution_time') : (int) @get_cfg_var('max_execution_time');
218
// If zero, then set to something higher to not let the user catch the ten seconds barrier.
219
if ($max_execution_time === 0)
221
$max_execution_time = 50 + $extra_time;
224
$max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50);
226
// For debugging purposes
227
// $max_execution_time = 10;
230
$start_time = (empty($starttime)) ? $current_time : $starttime;
233
return (ceil($current_time - $start_time) < $max_execution_time) ? true : false;
238
* @version Version 0.1 / $Id: functions.php,v 1.647 2007/12/10 18:35:28 kellanved Exp $
240
* Portable PHP password hashing framework.
242
* Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
245
* There's absolutely no warranty.
247
* The homepage URL for this framework is:
249
* http://www.openwall.com/phpass/
251
* Please be sure to update the Version line if you edit this file in any way.
252
* It is suggested that you leave the main version number intact, but indicate
253
* your project name (after the slash) and add your own revision information.
255
* Please do not change the "private" password hashing method implemented in
256
* here, thereby making your hashes incompatible. However, if you must, please
257
* change the hash type identifier (the "$P$") to something different.
259
* Obviously, since this code is in the public domain, the above are not
260
* requirements (there can be none), but merely suggestions.
265
function phpbb_hash($password)
267
$itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
269
$random_state = unique_id();
273
if (($fh = @fopen('/dev/urandom', 'rb')))
275
$random = fread($fh, $count);
279
if (strlen($random) < $count)
283
for ($i = 0; $i < $count; $i += 16)
285
$random_state = md5(unique_id() . $random_state);
286
$random .= pack('H*', md5($random_state));
288
$random = substr($random, 0, $count);
291
$hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64);
293
if (strlen($hash) == 34)
298
return md5($password);
302
* Check for correct password
304
function phpbb_check_hash($password, $hash)
306
$itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
307
if (strlen($hash) == 34)
309
return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
312
return (md5($password) === $hash) ? true : false;
316
* Generate salt for hash generation
318
function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6)
320
if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
322
$iteration_count_log2 = 8;
326
$output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)];
327
$output .= _hash_encode64($input, 6, $itoa64);
335
function _hash_encode64($input, $count, &$itoa64)
342
$value = ord($input[$i++]);
343
$output .= $itoa64[$value & 0x3f];
347
$value |= ord($input[$i]) << 8;
350
$output .= $itoa64[($value >> 6) & 0x3f];
359
$value |= ord($input[$i]) << 16;
362
$output .= $itoa64[($value >> 12) & 0x3f];
369
$output .= $itoa64[($value >> 18) & 0x3f];
377
* The crypt function/replacement
379
function _hash_crypt_private($password, $setting, &$itoa64)
383
// Check for correct hash
384
if (substr($setting, 0, 3) != '$H$')
389
$count_log2 = strpos($itoa64, $setting[3]);
391
if ($count_log2 < 7 || $count_log2 > 30)
396
$count = 1 << $count_log2;
397
$salt = substr($setting, 4, 8);
399
if (strlen($salt) != 8)
405
* We're kind of forced to use MD5 here since it's the only
406
* cryptographic primitive available in all versions of PHP
407
* currently in use. To implement our own low-level crypto
408
* in PHP would result in much worse performance and
409
* consequently in lower iteration counts and hashes that are
410
* quicker to crack (by non-PHP code).
412
if (PHP_VERSION >= 5)
414
$hash = md5($salt . $password, true);
417
$hash = md5($hash . $password, true);
423
$hash = pack('H*', md5($salt . $password));
426
$hash = pack('H*', md5($hash . $password));
431
$output = substr($setting, 0, 12);
432
$output .= _hash_encode64($hash, 16, $itoa64);
437
// Compatibility functions
439
if (!function_exists('array_combine'))
442
* A wrapper for the PHP5 function array_combine()
443
* @param array $keys contains keys for the resulting array
444
* @param array $values contains values for the resulting array
446
* @return Returns an array by using the values from the keys array as keys and the
447
* values from the values array as the corresponding values. Returns false if the
448
* number of elements for each array isn't equal or if the arrays are empty.
450
function array_combine($keys, $values)
452
$keys = array_values($keys);
453
$values = array_values($values);
456
$m = sizeof($values);
457
if (!$n || !$m || ($n != $m))
463
for ($i = 0; $i < $n; $i++)
465
$combined[$keys[$i]] = $values[$i];
471
if (!function_exists('str_split'))
474
* A wrapper for the PHP5 function str_split()
475
* @param array $string contains the string to be converted
476
* @param array $split_length contains the length of each chunk
478
* @return Converts a string to an array. If the optional split_length parameter is specified,
479
* the returned array will be broken down into chunks with each being split_length in length,
480
* otherwise each chunk will be one character in length. FALSE is returned if split_length is
481
* less than 1. If the split_length length exceeds the length of string, the entire string is
482
* returned as the first (and only) array element.
484
function str_split($string, $split_length = 1)
486
if ($split_length < 1)
490
else if ($split_length >= strlen($string))
492
return array($string);
496
preg_match_all('#.{1,' . $split_length . '}#s', $string, $matches);
502
if (!function_exists('stripos'))
505
* A wrapper for the PHP5 function stripos
506
* Find position of first occurrence of a case-insensitive string
508
* @param string $haystack is the string to search in
509
* @param string $needle is the string to search for
511
* @return mixed Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.
512
* Note that the needle may be a string of one or more characters.
513
* If needle is not found, stripos() will return boolean FALSE.
515
function stripos($haystack, $needle)
517
if (preg_match('#' . preg_quote($needle, '#') . '#i', $haystack, $m))
519
return strpos($haystack, $m[0]);
526
if (!function_exists('realpath'))
529
* Checks if a path ($path) is absolute or relative
531
* @param string $path Path to check absoluteness of
534
function is_absolute($path)
536
return ($path[0] == '/' || (DIRECTORY_SEPARATOR == '\\' && preg_match('#^[a-z]:/#i', $path))) ? true : false;
540
* @author Chris Smith <chris@project-minerva.org>
541
* @copyright 2006 Project Minerva Team
542
* @param string $path The path which we should attempt to resolve.
545
function phpbb_realpath($path)
547
// Now to perform funky shizzle
549
// Switch to use UNIX slashes
550
$path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
553
// Determine what sort of path we have
554
if (is_absolute($path))
560
// Absolute path, *NIX style
565
// Absolute path, Windows style
566
// Remove the drive letter and colon
567
$path_prefix = $path[0] . ':';
568
$path = substr($path, 2);
574
// Prepend the current working directory
575
if (function_exists('getcwd'))
577
// This is the best method, hopefully it is enabled!
578
$path = str_replace(DIRECTORY_SEPARATOR, '/', getcwd()) . '/' . $path;
580
if (preg_match('#^[a-z]:#i', $path))
582
$path_prefix = $path[0] . ':';
583
$path = substr($path, 2);
590
else if (isset($_SERVER['SCRIPT_FILENAME']) && !empty($_SERVER['SCRIPT_FILENAME']))
592
// Warning: If chdir() has been used this will lie!
593
// Warning: This has some problems sometime (CLI can create them easily)
594
$path = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['SCRIPT_FILENAME'])) . '/' . $path;
600
// We have no way of getting the absolute path, just run on using relative ones.
606
// Remove any repeated slashes
607
$path = preg_replace('#/{2,}#', '/', $path);
609
// Remove the slashes from the start and end of the path
610
$path = trim($path, '/');
612
// Break the string into little bits for us to nibble on
613
$bits = explode('/', $path);
615
// Remove any . in the path, renumber array for the loop below
616
$bits = array_values(array_diff($bits, array('.')));
618
// Lets get looping, run over and resolve any .. (up directory)
619
for ($i = 0, $max = sizeof($bits); $i < $max; $i++)
622
if ($bits[$i] == '..' )
624
if (isset($bits[$i - 1]))
626
if ($bits[$i - 1] != '..')
628
// We found a .. and we are able to traverse upwards, lets do it!
630
unset($bits[$i - 1]);
633
$bits = array_values($bits);
636
else if ($absolute) // ie. !isset($bits[$i - 1]) && $absolute
638
// We have an absolute path trying to descend above the root of the filesystem
645
// Prepend the path prefix
646
array_unshift($bits, $path_prefix);
650
$max = sizeof($bits) - 1;
652
// Check if we are able to resolve symlinks, Windows cannot.
653
$symlink_resolve = (function_exists('readlink')) ? true : false;
655
foreach ($bits as $i => $bit)
657
if (@is_dir("$resolved/$bit") || ($i == $max && @is_file("$resolved/$bit")))
660
if ($symlink_resolve && is_link("$resolved/$bit") && ($link = readlink("$resolved/$bit")))
662
// Resolved a symlink.
663
$resolved = $link . (($i == $max) ? '' : '/');
669
// Something doesn't exist here!
670
// This is correct realpath() behaviour but sadly open_basedir and safe_mode make this problematic
673
$resolved .= $bit . (($i == $max) ? '' : '/');
676
// @todo If the file exists fine and open_basedir only has one path we should be able to prepend it
677
// because we must be inside that basedir, the question is where...
678
// @internal The slash in is_dir() gets around an open_basedir restriction
679
if (!@file_exists($resolved) || (!is_dir($resolved . '/') && !is_file($resolved)))
684
// Put the slashes back to the native operating systems slashes
685
$resolved = str_replace('/', DIRECTORY_SEPARATOR, $resolved);
687
// Check for DIRECTORY_SEPARATOR at the end (and remove it!)
688
if (substr($resolved, -1) == DIRECTORY_SEPARATOR)
690
return substr($resolved, 0, -1);
693
return $resolved; // We got here, in the end!
699
* A wrapper for realpath
702
function phpbb_realpath($path)
704
$path = realpath($path);
706
// Check for DIRECTORY_SEPARATOR at the end (and remove it!)
707
if (substr($path, -1) == DIRECTORY_SEPARATOR)
709
return substr($path, 0, -1);
716
if (!function_exists('htmlspecialchars_decode'))
719
* A wrapper for htmlspecialchars_decode
722
function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
724
return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
728
// functions used for building option fields
731
* Pick a language, any language ...
733
function language_select($default = '')
737
$sql = 'SELECT lang_iso, lang_local_name
738
FROM ' . LANG_TABLE . '
739
ORDER BY lang_english_name';
740
$result = $db->sql_query($sql);
743
while ($row = $db->sql_fetchrow($result))
745
$selected = ($row['lang_iso'] == $default) ? ' selected="selected"' : '';
746
$lang_options .= '<option value="' . $row['lang_iso'] . '"' . $selected . '>' . $row['lang_local_name'] . '</option>';
748
$db->sql_freeresult($result);
750
return $lang_options;
754
* Pick a template/theme combo,
756
function style_select($default = '', $all = false)
760
$sql_where = (!$all) ? 'WHERE style_active = 1 ' : '';
761
$sql = 'SELECT style_id, style_name
762
FROM ' . STYLES_TABLE . "
764
ORDER BY style_name";
765
$result = $db->sql_query($sql);
768
while ($row = $db->sql_fetchrow($result))
770
$selected = ($row['style_id'] == $default) ? ' selected="selected"' : '';
771
$style_options .= '<option value="' . $row['style_id'] . '"' . $selected . '>' . $row['style_name'] . '</option>';
773
$db->sql_freeresult($result);
775
return $style_options;
781
function tz_select($default = '', $truncate = false)
786
foreach ($user->lang['tz_zones'] as $offset => $zone)
790
$zone_trunc = truncate_string($zone, 50, false, '...');
797
if (is_numeric($offset))
799
$selected = ($offset == $default) ? ' selected="selected"' : '';
800
$tz_select .= '<option title="'.$zone.'" value="' . $offset . '"' . $selected . '>' . $zone_trunc . '</option>';
807
// Functions handling topic/post tracking/marking
810
* Marks a topic/forum as read
811
* Marks a topic as posted to
813
* @param int $user_id can only be used with $mode == 'post'
815
function markread($mode, $forum_id = false, $topic_id = false, $post_time = 0, $user_id = 0)
817
global $db, $user, $config;
821
if ($forum_id === false || !sizeof($forum_id))
823
if ($config['load_db_lastread'] && $user->data['is_registered'])
825
// Mark all forums read (index page)
826
$db->sql_query('DELETE FROM ' . TOPICS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
827
$db->sql_query('DELETE FROM ' . FORUMS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
828
$db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
830
else if ($config['load_anon_lastread'] || $user->data['is_registered'])
832
$tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
833
$tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
835
unset($tracking_topics['tf']);
836
unset($tracking_topics['t']);
837
unset($tracking_topics['f']);
838
$tracking_topics['l'] = base_convert(time() - $config['board_startdate'], 10, 36);
840
$user->set_cookie('track', tracking_serialize($tracking_topics), time() + 31536000);
841
$_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking_topics)) : tracking_serialize($tracking_topics);
843
unset($tracking_topics);
845
if ($user->data['is_registered'])
847
$db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
854
else if ($mode == 'topics')
856
// Mark all topics in forums read
857
if (!is_array($forum_id))
859
$forum_id = array($forum_id);
862
// Add 0 to forums array to mark global announcements correctly
865
if ($config['load_db_lastread'] && $user->data['is_registered'])
867
$sql = 'DELETE FROM ' . TOPICS_TRACK_TABLE . "
868
WHERE user_id = {$user->data['user_id']}
869
AND " . $db->sql_in_set('forum_id', $forum_id);
870
$db->sql_query($sql);
872
$sql = 'SELECT forum_id
873
FROM ' . FORUMS_TRACK_TABLE . "
874
WHERE user_id = {$user->data['user_id']}
875
AND " . $db->sql_in_set('forum_id', $forum_id);
876
$result = $db->sql_query($sql);
878
$sql_update = array();
879
while ($row = $db->sql_fetchrow($result))
881
$sql_update[] = $row['forum_id'];
883
$db->sql_freeresult($result);
885
if (sizeof($sql_update))
887
$sql = 'UPDATE ' . FORUMS_TRACK_TABLE . '
888
SET mark_time = ' . time() . "
889
WHERE user_id = {$user->data['user_id']}
890
AND " . $db->sql_in_set('forum_id', $sql_update);
891
$db->sql_query($sql);
894
if ($sql_insert = array_diff($forum_id, $sql_update))
897
foreach ($sql_insert as $f_id)
900
'user_id' => (int) $user->data['user_id'],
901
'forum_id' => (int) $f_id,
902
'mark_time' => time()
906
$db->sql_multi_insert(FORUMS_TRACK_TABLE, $sql_ary);
909
else if ($config['load_anon_lastread'] || $user->data['is_registered'])
911
$tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
912
$tracking = ($tracking) ? tracking_unserialize($tracking) : array();
914
foreach ($forum_id as $f_id)
916
$topic_ids36 = (isset($tracking['tf'][$f_id])) ? $tracking['tf'][$f_id] : array();
918
if (isset($tracking['tf'][$f_id]))
920
unset($tracking['tf'][$f_id]);
923
foreach ($topic_ids36 as $topic_id36)
925
unset($tracking['t'][$topic_id36]);
928
if (isset($tracking['f'][$f_id]))
930
unset($tracking['f'][$f_id]);
933
$tracking['f'][$f_id] = base_convert(time() - $config['board_startdate'], 10, 36);
936
if (isset($tracking['tf']) && empty($tracking['tf']))
938
unset($tracking['tf']);
941
$user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
942
$_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
949
else if ($mode == 'topic')
951
if ($topic_id === false || $forum_id === false)
956
if ($config['load_db_lastread'] && $user->data['is_registered'])
958
$sql = 'UPDATE ' . TOPICS_TRACK_TABLE . '
959
SET mark_time = ' . (($post_time) ? $post_time : time()) . "
960
WHERE user_id = {$user->data['user_id']}
961
AND topic_id = $topic_id";
962
$db->sql_query($sql);
965
if (!$db->sql_affectedrows())
967
$db->sql_return_on_error(true);
970
'user_id' => (int) $user->data['user_id'],
971
'topic_id' => (int) $topic_id,
972
'forum_id' => (int) $forum_id,
973
'mark_time' => ($post_time) ? (int) $post_time : time(),
976
$db->sql_query('INSERT INTO ' . TOPICS_TRACK_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
978
$db->sql_return_on_error(false);
981
else if ($config['load_anon_lastread'] || $user->data['is_registered'])
983
$tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
984
$tracking = ($tracking) ? tracking_unserialize($tracking) : array();
986
$topic_id36 = base_convert($topic_id, 10, 36);
988
if (!isset($tracking['t'][$topic_id36]))
990
$tracking['tf'][$forum_id][$topic_id36] = true;
993
$post_time = ($post_time) ? $post_time : time();
994
$tracking['t'][$topic_id36] = base_convert($post_time - $config['board_startdate'], 10, 36);
996
// If the cookie grows larger than 10000 characters we will remove the smallest value
997
// This can result in old topics being unread - but most of the time it should be accurate...
998
if (isset($_COOKIE[$config['cookie_name'] . '_track']) && strlen($_COOKIE[$config['cookie_name'] . '_track']) > 10000)
1000
//echo 'Cookie grown too large' . print_r($tracking, true);
1002
// We get the ten most minimum stored time offsets and its associated topic ids
1003
$time_keys = array();
1004
for ($i = 0; $i < 10 && sizeof($tracking['t']); $i++)
1006
$min_value = min($tracking['t']);
1007
$m_tkey = array_search($min_value, $tracking['t']);
1008
unset($tracking['t'][$m_tkey]);
1010
$time_keys[$m_tkey] = $min_value;
1013
// Now remove the topic ids from the array...
1014
foreach ($tracking['tf'] as $f_id => $topic_id_ary)
1016
foreach ($time_keys as $m_tkey => $min_value)
1018
if (isset($topic_id_ary[$m_tkey]))
1020
$tracking['f'][$f_id] = $min_value;
1021
unset($tracking['tf'][$f_id][$m_tkey]);
1026
if ($user->data['is_registered'])
1028
$user->data['user_lastmark'] = intval(base_convert(max($time_keys) + $config['board_startdate'], 36, 10));
1029
$db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . $user->data['user_lastmark'] . " WHERE user_id = {$user->data['user_id']}");
1033
$tracking['l'] = max($time_keys);
1037
$user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
1038
$_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
1043
else if ($mode == 'post')
1045
if ($topic_id === false)
1050
$use_user_id = (!$user_id) ? $user->data['user_id'] : $user_id;
1052
if ($config['load_db_track'] && $use_user_id != ANONYMOUS)
1054
$db->sql_return_on_error(true);
1057
'user_id' => (int) $use_user_id,
1058
'topic_id' => (int) $topic_id,
1062
$db->sql_query('INSERT INTO ' . TOPICS_POSTED_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
1064
$db->sql_return_on_error(false);
1072
* Get topic tracking info by using already fetched info
1074
function get_topic_tracking($forum_id, $topic_ids, &$rowset, $forum_mark_time, $global_announce_list = false)
1076
global $config, $user;
1078
$last_read = array();
1080
if (!is_array($topic_ids))
1082
$topic_ids = array($topic_ids);
1085
foreach ($topic_ids as $topic_id)
1087
if (!empty($rowset[$topic_id]['mark_time']))
1089
$last_read[$topic_id] = $rowset[$topic_id]['mark_time'];
1093
$topic_ids = array_diff($topic_ids, array_keys($last_read));
1095
if (sizeof($topic_ids))
1097
$mark_time = array();
1099
// Get global announcement info
1100
if ($global_announce_list && sizeof($global_announce_list))
1102
if (!isset($forum_mark_time[0]))
1106
$sql = 'SELECT mark_time
1107
FROM ' . FORUMS_TRACK_TABLE . "
1108
WHERE user_id = {$user->data['user_id']}
1110
$result = $db->sql_query($sql);
1111
$row = $db->sql_fetchrow($result);
1112
$db->sql_freeresult($result);
1116
$mark_time[0] = $row['mark_time'];
1121
if ($forum_mark_time[0] !== false)
1123
$mark_time[0] = $forum_mark_time[0];
1128
if (!empty($forum_mark_time[$forum_id]) && $forum_mark_time[$forum_id] !== false)
1130
$mark_time[$forum_id] = $forum_mark_time[$forum_id];
1133
$user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
1135
foreach ($topic_ids as $topic_id)
1137
if ($global_announce_list && isset($global_announce_list[$topic_id]))
1139
$last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1143
$last_read[$topic_id] = $user_lastmark;
1152
* Get topic tracking info from db (for cookie based tracking only this function is used)
1154
function get_complete_topic_tracking($forum_id, $topic_ids, $global_announce_list = false)
1156
global $config, $user;
1158
$last_read = array();
1160
if (!is_array($topic_ids))
1162
$topic_ids = array($topic_ids);
1165
if ($config['load_db_lastread'] && $user->data['is_registered'])
1169
$sql = 'SELECT topic_id, mark_time
1170
FROM ' . TOPICS_TRACK_TABLE . "
1171
WHERE user_id = {$user->data['user_id']}
1172
AND " . $db->sql_in_set('topic_id', $topic_ids);
1173
$result = $db->sql_query($sql);
1175
while ($row = $db->sql_fetchrow($result))
1177
$last_read[$row['topic_id']] = $row['mark_time'];
1179
$db->sql_freeresult($result);
1181
$topic_ids = array_diff($topic_ids, array_keys($last_read));
1183
if (sizeof($topic_ids))
1185
$sql = 'SELECT forum_id, mark_time
1186
FROM ' . FORUMS_TRACK_TABLE . "
1187
WHERE user_id = {$user->data['user_id']}
1189
(($global_announce_list && sizeof($global_announce_list)) ? "IN (0, $forum_id)" : "= $forum_id");
1190
$result = $db->sql_query($sql);
1192
$mark_time = array();
1193
while ($row = $db->sql_fetchrow($result))
1195
$mark_time[$row['forum_id']] = $row['mark_time'];
1197
$db->sql_freeresult($result);
1199
$user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
1201
foreach ($topic_ids as $topic_id)
1203
if ($global_announce_list && isset($global_announce_list[$topic_id]))
1205
$last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1209
$last_read[$topic_id] = $user_lastmark;
1214
else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1216
global $tracking_topics;
1218
if (!isset($tracking_topics) || !sizeof($tracking_topics))
1220
$tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1221
$tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1224
if (!$user->data['is_registered'])
1226
$user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
1230
$user_lastmark = $user->data['user_lastmark'];
1233
foreach ($topic_ids as $topic_id)
1235
$topic_id36 = base_convert($topic_id, 10, 36);
1237
if (isset($tracking_topics['t'][$topic_id36]))
1239
$last_read[$topic_id] = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
1243
$topic_ids = array_diff($topic_ids, array_keys($last_read));
1245
if (sizeof($topic_ids))
1247
$mark_time = array();
1248
if ($global_announce_list && sizeof($global_announce_list))
1250
if (isset($tracking_topics['f'][0]))
1252
$mark_time[0] = base_convert($tracking_topics['f'][0], 36, 10) + $config['board_startdate'];
1256
if (isset($tracking_topics['f'][$forum_id]))
1258
$mark_time[$forum_id] = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
1261
$user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user_lastmark;
1263
foreach ($topic_ids as $topic_id)
1265
if ($global_announce_list && isset($global_announce_list[$topic_id]))
1267
$last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1271
$last_read[$topic_id] = $user_lastmark;
1281
* Check for read forums and update topic tracking info accordingly
1283
* @param int $forum_id the forum id to check
1284
* @param int $forum_last_post_time the forums last post time
1285
* @param int $f_mark_time the forums last mark time if user is registered and load_db_lastread enabled
1286
* @param int $mark_time_forum false if the mark time needs to be obtained, else the last users forum mark time
1288
* @return true if complete forum got marked read, else false.
1290
function update_forum_tracking_info($forum_id, $forum_last_post_time, $f_mark_time = false, $mark_time_forum = false)
1292
global $db, $tracking_topics, $user, $config;
1294
// Determine the users last forum mark time if not given.
1295
if ($mark_time_forum === false)
1297
if ($config['load_db_lastread'] && $user->data['is_registered'])
1299
$mark_time_forum = (!empty($f_mark_time)) ? $f_mark_time : $user->data['user_lastmark'];
1301
else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1303
$tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1304
$tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1306
if (!$user->data['is_registered'])
1308
$user->data['user_lastmark'] = (isset($tracking_topics['l'])) ? (int) (base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate']) : 0;
1311
$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'];
1315
// Check the forum for any left unread topics.
1316
// If there are none, we mark the forum as read.
1317
if ($config['load_db_lastread'] && $user->data['is_registered'])
1319
if ($mark_time_forum >= $forum_last_post_time)
1321
// We do not need to mark read, this happened before. Therefore setting this to true
1326
$sql = 'SELECT t.forum_id FROM ' . TOPICS_TABLE . ' t
1327
LEFT JOIN ' . TOPICS_TRACK_TABLE . ' tt ON (tt.topic_id = t.topic_id AND tt.user_id = ' . $user->data['user_id'] . ')
1328
WHERE t.forum_id = ' . $forum_id . '
1329
AND t.topic_last_post_time > ' . $mark_time_forum . '
1330
AND t.topic_moved_id = 0
1331
AND (tt.topic_id IS NULL OR tt.mark_time < t.topic_last_post_time)
1332
GROUP BY t.forum_id';
1333
$result = $db->sql_query_limit($sql, 1);
1334
$row = $db->sql_fetchrow($result);
1335
$db->sql_freeresult($result);
1338
else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1340
// Get information from cookie
1343
if (!isset($tracking_topics['tf'][$forum_id]))
1345
// We do not need to mark read, this happened before. Therefore setting this to true
1350
$sql = 'SELECT topic_id
1351
FROM ' . TOPICS_TABLE . '
1352
WHERE forum_id = ' . $forum_id . '
1353
AND topic_last_post_time > ' . $mark_time_forum . '
1354
AND topic_moved_id = 0';
1355
$result = $db->sql_query($sql);
1357
$check_forum = $tracking_topics['tf'][$forum_id];
1360
while ($row = $db->sql_fetchrow($result))
1362
if (!in_array(base_convert($row['topic_id'], 10, 36), array_keys($check_forum)))
1368
$db->sql_freeresult($result);
1380
markread('topics', $forum_id);
1388
* Transform an array into a serialized format
1390
function tracking_serialize($input)
1393
foreach ($input as $key => $value)
1395
if (is_array($value))
1397
$out .= $key . ':(' . tracking_serialize($value) . ');';
1401
$out .= $key . ':' . $value . ';';
1408
* Transform a serialized array into an actual array
1410
function tracking_unserialize($string, $max_depth = 3)
1412
$n = strlen($string);
1415
die('Invalid data supplied');
1417
$data = $stack = array();
1421
for ($i = 0; $i < $n; ++$i)
1426
switch ($string[$i])
1434
$level = array_pop($stack);
1438
$key .= $string[$i];
1443
switch ($string[$i])
1446
if (sizeof($stack) >= $max_depth)
1448
die('Invalid data supplied');
1451
$level[$key] = array();
1452
$level = &$level[$key];
1457
$level[$key] = $string[$i];
1464
switch ($string[$i])
1468
$level = array_pop($stack);
1476
$level[$key] .= $string[$i];
1482
switch ($string[$i])
1486
$level = array_pop($stack);
1493
die('Invalid data supplied');
1500
if (sizeof($stack) != 0 || ($mode != 0 && $mode != 3))
1502
die('Invalid data supplied');
1508
// Pagination functions
1511
* Pagination routine, generates page number sequence
1512
* tpl_prefix is for using different pagination blocks at one page
1514
function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = false, $tpl_prefix = '')
1516
global $template, $user;
1518
// Make sure $per_page is a valid value
1519
$per_page = ($per_page <= 0) ? 1 : $per_page;
1521
$seperator = '<span class="page-sep">' . $user->lang['COMMA_SEPARATOR'] . '</span>';
1522
$total_pages = ceil($num_items / $per_page);
1524
if ($total_pages == 1 || !$num_items)
1529
$on_page = floor($start_item / $per_page) + 1;
1530
$url_delim = (strpos($base_url, '?') === false) ? '?' : '&';
1532
$page_string = ($on_page == 1) ? '<strong>1</strong>' : '<a href="' . $base_url . '">1</a>';
1534
if ($total_pages > 5)
1536
$start_cnt = min(max(1, $on_page - 4), $total_pages - 5);
1537
$end_cnt = max(min($total_pages, $on_page + 4), 6);
1539
$page_string .= ($start_cnt > 1) ? ' ... ' : $seperator;
1541
for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
1543
$page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
1544
if ($i < $end_cnt - 1)
1546
$page_string .= $seperator;
1550
$page_string .= ($end_cnt < $total_pages) ? ' ... ' : $seperator;
1554
$page_string .= $seperator;
1556
for ($i = 2; $i < $total_pages; $i++)
1558
$page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
1559
if ($i < $total_pages)
1561
$page_string .= $seperator;
1566
$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>';
1568
if ($add_prevnext_text)
1572
$page_string = '<a href="' . $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page) . '">' . $user->lang['PREVIOUS'] . '</a> ' . $page_string;
1575
if ($on_page != $total_pages)
1577
$page_string .= ' <a href="' . $base_url . "{$url_delim}start=" . ($on_page * $per_page) . '">' . $user->lang['NEXT'] . '</a>';
1581
$template->assign_vars(array(
1582
$tpl_prefix . 'BASE_URL' => $base_url,
1583
'A_' . $tpl_prefix . 'BASE_URL' => addslashes($base_url),
1584
$tpl_prefix . 'PER_PAGE' => $per_page,
1586
$tpl_prefix . 'PREVIOUS_PAGE' => ($on_page == 1) ? '' : $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page),
1587
$tpl_prefix . 'NEXT_PAGE' => ($on_page == $total_pages) ? '' : $base_url . "{$url_delim}start=" . ($on_page * $per_page),
1588
$tpl_prefix . 'TOTAL_PAGES' => $total_pages,
1591
return $page_string;
1595
* Return current page (pagination)
1597
function on_page($num_items, $per_page, $start)
1599
global $template, $user;
1601
// Make sure $per_page is a valid value
1602
$per_page = ($per_page <= 0) ? 1 : $per_page;
1604
$on_page = floor($start / $per_page) + 1;
1606
$template->assign_vars(array(
1607
'ON_PAGE' => $on_page)
1610
return sprintf($user->lang['PAGE_OF'], $on_page, max(ceil($num_items / $per_page), 1));
1613
// Server functions (building urls, redirecting...)
1616
* Append session id to url.
1617
* This function supports hooks.
1619
* @param string $url The url the session id needs to be appended to (can have params)
1620
* @param mixed $params String or array of additional url parameters
1621
* @param bool $is_amp Is url using & (true) or & (false)
1622
* @param string $session_id Possibility to use a custom session id instead of the global one
1626
* append_sid("{$phpbb_root_path}viewtopic.$phpEx?t=1&f=2");
1627
* append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2');
1628
* append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2', false);
1629
* append_sid("{$phpbb_root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
1633
function append_sid($url, $params = false, $is_amp = true, $session_id = false)
1635
global $_SID, $_EXTRA_URL, $phpbb_hook;
1637
// Developers using the hook function need to globalise the $_SID and $_EXTRA_URL on their own and also handle it appropiatly.
1638
// They could mimick most of what is within this function
1639
if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__, $url, $params, $is_amp, $session_id))
1641
if ($phpbb_hook->hook_return(__FUNCTION__))
1643
return $phpbb_hook->hook_return_result(__FUNCTION__);
1647
// Assign sid if session id is not specified
1648
if ($session_id === false)
1650
$session_id = $_SID;
1653
$amp_delim = ($is_amp) ? '&' : '&';
1654
$url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
1656
// Appending custom url parameter?
1657
$append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';
1660
if (strpos($url, '#') !== false)
1662
list($url, $anchor) = explode('#', $url, 2);
1663
$anchor = '#' . $anchor;
1665
else if (!is_array($params) && strpos($params, '#') !== false)
1667
list($params, $anchor) = explode('#', $params, 2);
1668
$anchor = '#' . $anchor;
1671
// Use the short variant if possible ;)
1672
if ($params === false)
1674
// Append session id
1677
return $url . (($append_url) ? $url_delim . $append_url : '') . $anchor;
1681
return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id . $anchor;
1685
// Build string if parameters are specified as array
1686
if (is_array($params))
1690
foreach ($params as $key => $item)
1699
$anchor = '#' . $item;
1703
$output[] = $key . '=' . $item;
1706
$params = implode($amp_delim, $output);
1709
// Append session id and parameters (even if they are empty)
1710
// If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
1711
return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
1715
* Generate board url (example: http://www.example.com/phpBB)
1716
* @param bool $without_script_path if set to true the script path gets not appended (example: http://www.example.com)
1718
function generate_board_url($without_script_path = false)
1720
global $config, $user;
1722
$server_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME');
1723
$server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
1725
// Forcing server vars is the only way to specify/override the protocol
1726
if ($config['force_server_vars'] || !$server_name)
1728
$server_protocol = ($config['server_protocol']) ? $config['server_protocol'] : (($config['cookie_secure']) ? 'https://' : 'http://');
1729
$server_name = $config['server_name'];
1730
$server_port = (int) $config['server_port'];
1731
$script_path = $config['script_path'];
1733
$url = $server_protocol . $server_name;
1737
// Do not rely on cookie_secure, users seem to think that it means a secured cookie instead of an encrypted connection
1738
$cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
1739
$url = (($cookie_secure) ? 'https://' : 'http://') . $server_name;
1741
$script_path = $user->page['root_script_path'];
1744
if ($server_port && (($config['cookie_secure'] && $server_port <> 443) || (!$config['cookie_secure'] && $server_port <> 80)))
1746
$url .= ':' . $server_port;
1749
if (!$without_script_path)
1751
$url .= $script_path;
1754
// Strip / from the end
1755
if (substr($url, -1, 1) == '/')
1757
$url = substr($url, 0, -1);
1764
* Redirects the user to another page then exits the script nicely
1766
function redirect($url, $return = false)
1768
global $db, $cache, $config, $user, $phpbb_root_path;
1770
if (empty($user->lang))
1772
$user->add_lang('common');
1777
garbage_collection();
1780
// Make sure no &'s are in, this will break the redirect
1781
$url = str_replace('&', '&', $url);
1783
// Determine which type of redirect we need to handle...
1784
$url_parts = parse_url($url);
1786
if ($url_parts === false)
1788
// Malformed url, redirect to current page...
1789
$url = generate_board_url() . '/' . $user->page['page'];
1791
else if (!empty($url_parts['scheme']) && !empty($url_parts['host']))
1795
else if ($url[0] == '/')
1797
// Absolute uri, prepend direct url...
1798
$url = generate_board_url(true) . $url;
1803
$pathinfo = pathinfo($url);
1805
// Is the uri pointing to the current directory?
1806
if ($pathinfo['dirname'] == '.')
1808
$url = str_replace('./', '', $url);
1810
// Strip / from the beginning
1811
if ($url && substr($url, 0, 1) == '/')
1813
$url = substr($url, 1);
1816
if ($user->page['page_dir'])
1818
$url = generate_board_url() . '/' . $user->page['page_dir'] . '/' . $url;
1822
$url = generate_board_url() . '/' . $url;
1827
// Used ./ before, but $phpbb_root_path is working better with urls within another root path
1828
$root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($phpbb_root_path)));
1829
$page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($pathinfo['dirname'])));
1830
$intersection = array_intersect_assoc($root_dirs, $page_dirs);
1832
$root_dirs = array_diff_assoc($root_dirs, $intersection);
1833
$page_dirs = array_diff_assoc($page_dirs, $intersection);
1835
$dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
1837
// Strip / from the end
1838
if ($dir && substr($dir, -1, 1) == '/')
1840
$dir = substr($dir, 0, -1);
1843
// Strip / from the beginning
1844
if ($dir && substr($dir, 0, 1) == '/')
1846
$dir = substr($dir, 1);
1849
$url = str_replace($pathinfo['dirname'] . '/', '', $url);
1851
// Strip / from the beginning
1852
if (substr($url, 0, 1) == '/')
1854
$url = substr($url, 1);
1857
$url = $dir . '/' . $url;
1858
$url = generate_board_url() . '/' . $url;
1862
// Make sure no linebreaks are there... to prevent http response splitting for PHP < 4.4.2
1863
if (strpos(urldecode($url), "\n") !== false || strpos(urldecode($url), "\r") !== false || strpos($url, ';') !== false)
1865
trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
1868
// Now, also check the protocol and for a valid url the last time...
1869
$allowed_protocols = array('http', 'https', 'ftp', 'ftps');
1870
$url_parts = parse_url($url);
1872
if ($url_parts === false || empty($url_parts['scheme']) || !in_array($url_parts['scheme'], $allowed_protocols))
1874
trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
1882
// Redirect via an HTML form for PITA webservers
1883
if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
1885
header('Refresh: 0; URL=' . $url);
1887
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
1888
echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="' . $user->lang['DIRECTION'] . '" lang="' . $user->lang['USER_LANG'] . '" xml:lang="' . $user->lang['USER_LANG'] . '">';
1890
echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
1891
echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&', $url) . '" />';
1892
echo '<title>' . $user->lang['REDIRECT'] . '</title>';
1895
echo '<div style="text-align: center;">' . sprintf($user->lang['URL_REDIRECT'], '<a href="' . str_replace('&', '&', $url) . '">', '</a>') . '</div>';
1902
// Behave as per HTTP/1.1 spec for others
1903
header('Location: ' . $url);
1908
* Re-Apply session id after page reloads
1910
function reapply_sid($url)
1912
global $phpEx, $phpbb_root_path;
1914
if ($url === "index.$phpEx")
1916
return append_sid("index.$phpEx");
1918
else if ($url === "{$phpbb_root_path}index.$phpEx")
1920
return append_sid("{$phpbb_root_path}index.$phpEx");
1923
// Remove previously added sid
1924
if (strpos($url, '?sid=') !== false)
1926
$url = preg_replace('/(\?)sid=[a-z0-9]+(&|&)?/', '\1', $url);
1928
else if (strpos($url, '&sid=') !== false)
1930
$url = preg_replace('/&sid=[a-z0-9]+(&)?/', '\1', $url);
1932
else if (strpos($url, '&sid=') !== false)
1934
$url = preg_replace('/&sid=[a-z0-9]+(&)?/', '\1', $url);
1937
return append_sid($url);
1941
* Returns url from the session/current page with an re-appended SID with optionally stripping vars from the url
1943
function build_url($strip_vars = false)
1945
global $user, $phpbb_root_path;
1948
$redirect = append_sid($user->page['page'], false, false);
1950
// Add delimiter if not there...
1951
if (strpos($redirect, '?') === false)
1957
if ($strip_vars !== false && strpos($redirect, '?') !== false)
1959
if (!is_array($strip_vars))
1961
$strip_vars = array($strip_vars);
1964
$query = $_query = array();
1966
$args = substr($redirect, strpos($redirect, '?') + 1);
1967
$args = ($args) ? explode('&', $args) : array();
1968
$redirect = substr($redirect, 0, strpos($redirect, '?'));
1970
foreach ($args as $argument)
1972
$arguments = explode('=', $argument);
1973
$key = $arguments[0];
1974
unset($arguments[0]);
1976
$query[$key] = implode('=', $arguments);
1979
// Strip the vars off
1980
foreach ($strip_vars as $strip)
1982
if (isset($query[$strip]))
1984
unset($query[$strip]);
1988
// Glue the remaining parts together... already urlencoded
1989
foreach ($query as $key => $value)
1991
$_query[] = $key . '=' . $value;
1993
$query = implode('&', $_query);
1995
$redirect .= ($query) ? '?' . $query : '';
1998
return $phpbb_root_path . str_replace('&', '&', $redirect);
2002
* Meta refresh assignment
2004
function meta_refresh($time, $url)
2008
$url = redirect($url, true);
2010
// For XHTML compatibility we change back & to &
2011
$template->assign_vars(array(
2012
'META' => '<meta http-equiv="refresh" content="' . $time . ';url=' . str_replace('&', '&', $url) . '" />')
2019
* Add a secret token to the form (requires the S_FORM_TOKEN template variable)
2020
* @param string $form_name The name of the form; has to match the name used in check_form_key, otherwise no restrictions apply
2022
function add_form_key($form_name)
2024
global $config, $template, $user;
2026
$token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
2027
$token = sha1($now . $user->data['user_form_salt'] . $form_name . $token_sid);
2029
$s_fields = build_hidden_fields(array(
2030
'creation_time' => $now,
2031
'form_token' => $token,
2033
$template->assign_vars(array(
2034
'S_FORM_TOKEN' => $s_fields,
2039
* Check the form key. Required for all altering actions not secured by confirm_box
2040
* @param string $form_name The name of the form; has to match the name used in add_form_key, otherwise no restrictions apply
2041
* @param int $timespan The maximum acceptable age for a submitted form in seconds. Defaults to the config setting.
2042
* @param string $return_page The address for the return link
2043
* @param bool $trigger If true, the function will triger an error when encountering an invalid form
2044
* @param int $minimum_time The minimum acceptable age for a submitted form in seconds
2046
function check_form_key($form_name, $timespan = false, $return_page = '', $trigger = false, $minimum_time = false)
2048
global $config, $user;
2050
if ($timespan === false)
2052
// we enforce a minimum value of half a minute here.
2053
$timespan = ($config['form_token_lifetime'] == -1) ? -1 : max(30, $config['form_token_lifetime']);
2055
if ($minimum_time === false)
2057
$minimum_time = (int) $config['form_token_mintime'];
2060
if (isset($_POST['creation_time']) && isset($_POST['form_token']))
2062
$creation_time = abs(request_var('creation_time', 0));
2063
$token = request_var('form_token', '');
2065
$diff = (time() - $creation_time);
2067
if (($diff >= $minimum_time) && (($diff <= $timespan) || $timespan == -1))
2069
$token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
2071
$key = sha1($creation_time . $user->data['user_form_salt'] . $form_name . $token_sid);
2072
if ($key === $token)
2080
trigger_error($user->lang['FORM_INVALID'] . $return_page);
2085
// Message/Login boxes
2089
* @param boolean $check True for checking if confirmed (without any additional parameters) and false for displaying the confirm box
2090
* @param string $title Title/Message used for confirm box.
2091
* message text is _CONFIRM appended to title.
2092
* If title cannot be found in user->lang a default one is displayed
2093
* If title_CONFIRM cannot be found in user->lang the text given is used.
2094
* @param string $hidden Hidden variables
2095
* @param string $html_body Template used for confirm box
2096
* @param string $u_action Custom form action
2098
function confirm_box($check, $title = '', $hidden = '', $html_body = 'confirm_body.html', $u_action = '')
2100
global $user, $template, $db;
2101
global $phpEx, $phpbb_root_path;
2103
if (isset($_POST['cancel']))
2109
if (isset($_POST['confirm']))
2111
// language frontier
2112
if ($_POST['confirm'] === $user->lang['YES'])
2118
if ($check && $confirm)
2120
$user_id = request_var('user_id', 0);
2121
$session_id = request_var('sess', '');
2122
$confirm_key = request_var('confirm_key', '');
2124
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'])
2129
// Reset user_last_confirm_key
2130
$sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = ''
2131
WHERE user_id = " . $user->data['user_id'];
2132
$db->sql_query($sql);
2141
$s_hidden_fields = build_hidden_fields(array(
2142
'user_id' => $user->data['user_id'],
2143
'sess' => $user->session_id,
2144
'sid' => $user->session_id)
2147
// generate activation key
2148
$confirm_key = gen_rand_string(10);
2150
if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
2152
adm_page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
2156
page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
2159
$template->set_filenames(array(
2160
'body' => $html_body)
2163
// If activation key already exist, we better do not re-use the key (something very strange is going on...)
2164
if (request_var('confirm_key', ''))
2166
// This should not occur, therefore we cancel the operation to safe the user
2170
// re-add sid / transform & to & for user->page (user->page is always using &)
2171
$use_page = ($u_action) ? $phpbb_root_path . $u_action : $phpbb_root_path . str_replace('&', '&', $user->page['page']);
2172
$u_action = reapply_sid($use_page);
2173
$u_action .= ((strpos($u_action, '?') === false) ? '?' : '&') . 'confirm_key=' . $confirm_key;
2175
$template->assign_vars(array(
2176
'MESSAGE_TITLE' => (!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title],
2177
'MESSAGE_TEXT' => (!isset($user->lang[$title . '_CONFIRM'])) ? $title : $user->lang[$title . '_CONFIRM'],
2179
'YES_VALUE' => $user->lang['YES'],
2180
'S_CONFIRM_ACTION' => $u_action,
2181
'S_HIDDEN_FIELDS' => $hidden . $s_hidden_fields)
2184
$sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = '" . $db->sql_escape($confirm_key) . "'
2185
WHERE user_id = " . $user->data['user_id'];
2186
$db->sql_query($sql);
2188
if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
2199
* Generate login box or verify password
2201
function login_box($redirect = '', $l_explain = '', $l_success = '', $admin = false, $s_display = true)
2203
global $db, $user, $template, $auth, $phpEx, $phpbb_root_path, $config;
2207
// Make sure user->setup() has been called
2208
if (empty($user->lang))
2213
// Print out error if user tries to authenticate as an administrator without having the privileges...
2214
if ($admin && !$auth->acl_get('a_'))
2217
// anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
2218
if ($user->data['is_registered'])
2220
add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2222
trigger_error('NO_AUTH_ADMIN');
2225
if (isset($_POST['login']))
2230
$credential = request_var('credential', '');
2232
if (strspn($credential, 'abcdef0123456789') !== strlen($credential) || strlen($credential) != 32)
2234
if ($user->data['is_registered'])
2236
add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2238
trigger_error('NO_AUTH_ADMIN');
2241
$password = request_var('password_' . $credential, '', true);
2245
$password = request_var('password', '', true);
2248
$username = request_var('username', '', true);
2249
$autologin = (!empty($_POST['autologin'])) ? true : false;
2250
$viewonline = (!empty($_POST['viewonline'])) ? 0 : 1;
2251
$admin = ($admin) ? 1 : 0;
2252
$viewonline = ($admin) ? $user->data['session_viewonline'] : $viewonline;
2254
// Check if the supplied username is equal to the one stored within the database if re-authenticating
2255
if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
2257
// We log the attempt to use a different username...
2258
add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2259
trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
2262
// If authentication is successful we redirect user to previous page
2263
$result = $auth->login($username, $password, $autologin, $viewonline, $admin);
2265
// If admin authentication and login, we will log if it was a success or not...
2266
// We also break the operation on the first non-success login - it could be argued that the user already knows
2269
if ($result['status'] == LOGIN_SUCCESS)
2271
add_log('admin', 'LOG_ADMIN_AUTH_SUCCESS');
2275
// Only log the failed attempt if a real user tried to.
2276
// anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
2277
if ($user->data['is_registered'])
2279
add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2284
// The result parameter is always an array, holding the relevant information...
2285
if ($result['status'] == LOGIN_SUCCESS)
2287
$redirect = request_var('redirect', "{$phpbb_root_path}index.$phpEx");
2288
$message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
2289
$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']);
2291
// append/replace SID (may change during the session for AOL users)
2292
$redirect = reapply_sid($redirect);
2294
// Special case... the user is effectively banned, but we allow founders to login
2295
if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != USER_FOUNDER)
2300
meta_refresh(3, $redirect);
2301
trigger_error($message . '<br /><br />' . sprintf($l_redirect, '<a href="' . $redirect . '">', '</a>'));
2304
// Something failed, determine what...
2305
if ($result['status'] == LOGIN_BREAK)
2307
trigger_error($result['error_msg'], E_USER_ERROR);
2310
// Special cases... determine
2311
switch ($result['status'])
2313
case LOGIN_ERROR_ATTEMPTS:
2315
// Show confirm image
2316
$sql = 'DELETE FROM ' . CONFIRM_TABLE . "
2317
WHERE session_id = '" . $db->sql_escape($user->session_id) . "'
2318
AND confirm_type = " . CONFIRM_LOGIN;
2319
$db->sql_query($sql);
2322
$code = gen_rand_string(mt_rand(5, 8));
2323
$confirm_id = md5(unique_id($user->ip));
2324
$seed = hexdec(substr(unique_id(), 4, 10));
2326
// compute $seed % 0x7fffffff
2327
$seed -= 0x7fffffff * floor($seed / 0x7fffffff);
2329
$sql = 'INSERT INTO ' . CONFIRM_TABLE . ' ' . $db->sql_build_array('INSERT', array(
2330
'confirm_id' => (string) $confirm_id,
2331
'session_id' => (string) $user->session_id,
2332
'confirm_type' => (int) CONFIRM_LOGIN,
2333
'code' => (string) $code,
2334
'seed' => (int) $seed)
2336
$db->sql_query($sql);
2338
$template->assign_vars(array(
2339
'S_CONFIRM_CODE' => true,
2340
'CONFIRM_ID' => $confirm_id,
2341
'CONFIRM_IMAGE' => '<img src="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=confirm&id=' . $confirm_id . '&type=' . CONFIRM_LOGIN) . '" alt="" title="" />',
2342
'L_LOGIN_CONFIRM_EXPLAIN' => sprintf($user->lang['LOGIN_CONFIRM_EXPLAIN'], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>'),
2345
$err = $user->lang[$result['error_msg']];
2349
case LOGIN_ERROR_PASSWORD_CONVERT:
2351
$user->lang[$result['error_msg']],
2352
($config['email_enable']) ? '<a href="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') . '">' : '',
2353
($config['email_enable']) ? '</a>' : '',
2354
($config['board_contact']) ? '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">' : '',
2355
($config['board_contact']) ? '</a>' : ''
2359
// Username, password, etc...
2361
$err = $user->lang[$result['error_msg']];
2363
// Assign admin contact to some error messages
2364
if ($result['error_msg'] == 'LOGIN_ERROR_USERNAME' || $result['error_msg'] == 'LOGIN_ERROR_PASSWORD')
2366
$err = (!$config['board_contact']) ? sprintf($user->lang[$result['error_msg']], '', '') : sprintf($user->lang[$result['error_msg']], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');
2375
// We just use what the session code determined...
2376
// If we are not within the admin directory we use the page dir...
2381
$redirect .= ($user->page['page_dir']) ? $user->page['page_dir'] . '/' : '';
2384
$redirect .= $user->page['page_name'] . (($user->page['query_string']) ? '?' . htmlspecialchars($user->page['query_string']) : '');
2387
// Assign credential for username/password pair
2388
$credential = ($admin) ? md5(unique_id()) : false;
2390
$s_hidden_fields = array(
2391
'redirect' => $redirect,
2392
'sid' => $user->session_id,
2397
$s_hidden_fields['credential'] = $credential;
2400
$s_hidden_fields = build_hidden_fields($s_hidden_fields);
2402
$template->assign_vars(array(
2403
'LOGIN_ERROR' => $err,
2404
'LOGIN_EXPLAIN' => $l_explain,
2406
'U_SEND_PASSWORD' => ($config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') : '',
2407
'U_RESEND_ACTIVATION' => ($config['require_activation'] != USER_ACTIVATION_NONE && $config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=resend_act') : '',
2408
'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
2409
'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
2411
'S_DISPLAY_FULL_LOGIN' => ($s_display) ? true : false,
2412
'S_LOGIN_ACTION' => (!$admin) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login') : append_sid("index.$phpEx", false, true, $user->session_id), // Needs to stay index.$phpEx because we are within the admin directory
2413
'S_HIDDEN_FIELDS' => $s_hidden_fields,
2415
'S_ADMIN_AUTH' => $admin,
2416
'USERNAME' => ($admin) ? $user->data['username'] : '',
2418
'USERNAME_CREDENTIAL' => 'username',
2419
'PASSWORD_CREDENTIAL' => ($admin) ? 'password_' . $credential : 'password',
2422
page_header($user->lang['LOGIN']);
2424
$template->set_filenames(array(
2425
'body' => 'login_body.html')
2427
make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"));
2433
* Generate forum login box
2435
function login_forum_box($forum_data)
2437
global $db, $config, $user, $template, $phpEx;
2439
$password = request_var('password', '', true);
2441
$sql = 'SELECT forum_id
2442
FROM ' . FORUMS_ACCESS_TABLE . '
2443
WHERE forum_id = ' . $forum_data['forum_id'] . '
2444
AND user_id = ' . $user->data['user_id'] . "
2445
AND session_id = '" . $db->sql_escape($user->session_id) . "'";
2446
$result = $db->sql_query($sql);
2447
$row = $db->sql_fetchrow($result);
2448
$db->sql_freeresult($result);
2457
// Remove expired authorised sessions
2458
$sql = 'SELECT f.session_id
2459
FROM ' . FORUMS_ACCESS_TABLE . ' f
2460
LEFT JOIN ' . SESSIONS_TABLE . ' s ON (f.session_id = s.session_id)
2461
WHERE s.session_id IS NULL';
2462
$result = $db->sql_query($sql);
2464
if ($row = $db->sql_fetchrow($result))
2469
$sql_in[] = (string) $row['session_id'];
2471
while ($row = $db->sql_fetchrow($result));
2473
// Remove expired sessions
2474
$sql = 'DELETE FROM ' . FORUMS_ACCESS_TABLE . '
2475
WHERE ' . $db->sql_in_set('session_id', $sql_in);
2476
$db->sql_query($sql);
2478
$db->sql_freeresult($result);
2480
if (phpbb_check_hash($password, $forum_data['forum_password']))
2483
'forum_id' => (int) $forum_data['forum_id'],
2484
'user_id' => (int) $user->data['user_id'],
2485
'session_id' => (string) $user->session_id,
2488
$db->sql_query('INSERT INTO ' . FORUMS_ACCESS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
2493
$template->assign_var('LOGIN_ERROR', $user->lang['WRONG_PASSWORD']);
2496
page_header($user->lang['LOGIN']);
2498
$template->assign_vars(array(
2499
'S_HIDDEN_FIELDS' => build_hidden_fields(array('f' => $forum_data['forum_id'])))
2502
$template->set_filenames(array(
2503
'body' => 'login_forum.html')
2512
* Little helper for the build_hidden_fields function
2514
function _build_hidden_fields($key, $value, $specialchar, $stripslashes)
2516
$hidden_fields = '';
2518
if (!is_array($value))
2520
$value = ($stripslashes) ? stripslashes($value) : $value;
2521
$value = ($specialchar) ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value;
2523
$hidden_fields .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />' . "\n";
2527
foreach ($value as $_key => $_value)
2529
$_key = ($stripslashes) ? stripslashes($_key) : $_key;
2530
$_key = ($specialchar) ? htmlspecialchars($_key, ENT_COMPAT, 'UTF-8') : $_key;
2532
$hidden_fields .= _build_hidden_fields($key . '[' . $_key . ']', $_value, $specialchar, $stripslashes);
2536
return $hidden_fields;
2540
* Build simple hidden fields from array
2542
* @param array $field_ary an array of values to build the hidden field from
2543
* @param bool $specialchar if true, keys and values get specialchared
2544
* @param bool $stripslashes if true, keys and values get stripslashed
2546
* @return string the hidden fields
2548
function build_hidden_fields($field_ary, $specialchar = false, $stripslashes = false)
2550
$s_hidden_fields = '';
2552
foreach ($field_ary as $name => $vars)
2554
$name = ($stripslashes) ? stripslashes($name) : $name;
2555
$name = ($specialchar) ? htmlspecialchars($name, ENT_COMPAT, 'UTF-8') : $name;
2557
$s_hidden_fields .= _build_hidden_fields($name, $vars, $specialchar, $stripslashes);
2560
return $s_hidden_fields;
2566
function parse_cfg_file($filename, $lines = false)
2568
$parsed_items = array();
2570
if ($lines === false)
2572
$lines = file($filename);
2575
foreach ($lines as $line)
2577
$line = trim($line);
2579
if (!$line || $line[0] == '#' || ($delim_pos = strpos($line, '=')) === false)
2584
// Determine first occurrence, since in values the equal sign is allowed
2585
$key = strtolower(trim(substr($line, 0, $delim_pos)));
2586
$value = trim(substr($line, $delim_pos + 1));
2588
if (in_array($value, array('off', 'false', '0')))
2592
else if (in_array($value, array('on', 'true', '1')))
2596
else if (!trim($value))
2600
else if (($value[0] == "'" && $value[sizeof($value) - 1] == "'") || ($value[0] == '"' && $value[sizeof($value) - 1] == '"'))
2602
$value = substr($value, 1, sizeof($value)-2);
2605
$parsed_items[$key] = $value;
2608
return $parsed_items;
2618
$args = func_get_args();
2620
$mode = array_shift($args);
2621
$reportee_id = ($mode == 'user') ? intval(array_shift($args)) : '';
2622
$forum_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
2623
$topic_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
2624
$action = array_shift($args);
2625
$data = (!sizeof($args)) ? '' : serialize($args);
2628
'user_id' => (empty($user->data)) ? ANONYMOUS : $user->data['user_id'],
2629
'log_ip' => $user->ip,
2630
'log_time' => time(),
2631
'log_operation' => $action,
2632
'log_data' => $data,
2638
$sql_ary['log_type'] = LOG_ADMIN;
2643
'log_type' => LOG_MOD,
2644
'forum_id' => $forum_id,
2645
'topic_id' => $topic_id
2651
'log_type' => LOG_USERS,
2652
'reportee_id' => $reportee_id
2657
$sql_ary['log_type'] = LOG_CRITICAL;
2664
$db->sql_query('INSERT INTO ' . LOG_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
2666
return $db->sql_nextid();
2670
* Return a nicely formatted backtrace (parts from the php manual by diz at ysagoon dot com)
2672
function get_backtrace()
2674
global $phpbb_root_path;
2676
$output = '<div style="font-family: monospace;">';
2677
$backtrace = debug_backtrace();
2678
$path = phpbb_realpath($phpbb_root_path);
2680
foreach ($backtrace as $number => $trace)
2682
// We skip the first one, because it only shows this file/function
2688
// Strip the current directory from path
2689
if (empty($trace['file']))
2691
$trace['file'] = '';
2695
$trace['file'] = str_replace(array($path, '\\'), array('', '/'), $trace['file']);
2696
$trace['file'] = substr($trace['file'], 1);
2700
// If include/require/include_once is not called, do not show arguments - they may contain sensible information
2701
if (!in_array($trace['function'], array('include', 'require', 'include_once')))
2703
unset($trace['args']);
2708
if (!empty($trace['args'][0]))
2710
$argument = htmlspecialchars($trace['args'][0]);
2711
$argument = str_replace(array($path, '\\'), array('', '/'), $argument);
2712
$argument = substr($argument, 1);
2713
$args[] = "'{$argument}'";
2717
$trace['class'] = (!isset($trace['class'])) ? '' : $trace['class'];
2718
$trace['type'] = (!isset($trace['type'])) ? '' : $trace['type'];
2720
$output .= '<br />';
2721
$output .= '<b>FILE:</b> ' . htmlspecialchars($trace['file']) . '<br />';
2722
$output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
2724
$output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']) . '(' . ((sizeof($args)) ? implode(', ', $args) : '') . ')<br />';
2726
$output .= '</div>';
2731
* This function returns a regular expression pattern for commonly used expressions
2732
* Use with / as delimiter for email mode and # for url modes
2733
* mode can be: email|bbcode_htm|url|url_inline|www_url|www_url_inline|relative_url|relative_url_inline|ipv4|ipv6
2735
function get_preg_expression($mode)
2740
return '[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*[a-z]+';
2745
'#<!\-\- e \-\-><a href="mailto:(.*?)">.*?</a><!\-\- e \-\->#',
2746
'#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
2747
'#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
2748
'#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
2749
'#<!\-\- .*? \-\->#s',
2754
// Whoa these look impressive!
2755
// The code to generate the following two regular expressions which match valid IPv4/IPv6 addresses
2756
// can be found in the develop directory
2758
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])$#';
2762
return '#^(?:(?:(?:[\dA-F]{1,4}:){6}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:::(?:[\dA-F]{1,4}:){5}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:):(?:[\dA-F]{1,4}:){4}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,2}:(?:[\dA-F]{1,4}:){3}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,3}:(?:[\dA-F]{1,4}:){2}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,4}:(?:[\dA-F]{1,4}:)(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,5}:(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,6}:[\dA-F]{1,4})|(?:(?:[\dA-F]{1,4}:){1,7}:))$#i';
2767
$inline = ($mode == 'url') ? ')' : '';
2768
$scheme = ($mode == 'url') ? '[a-z\d+\-.]' : '[a-z\d+]'; // avoid automatic parsing of "word" in "last word.http://..."
2769
// generated with regex generation file in the develop folder
2770
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})*)?";
2774
case 'www_url_inline':
2775
$inline = ($mode == 'www_url') ? ')' : '';
2776
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})*)?";
2779
case 'relative_url':
2780
case 'relative_url_inline':
2781
$inline = ($mode == 'relative_url') ? ')' : '';
2782
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})*)?";
2790
* Returns the first block of the specified IPv6 address and as many additional
2791
* ones as specified in the length paramater.
2792
* If length is zero, then an empty string is returned.
2793
* If length is greater than 3 the complete IP will be returned
2795
function short_ipv6($ip, $length)
2802
// extend IPv6 addresses
2803
$blocks = substr_count($ip, ':') + 1;
2806
$ip = str_replace('::', ':' . str_repeat('0000:', 9 - $blocks), $ip);
2814
$ip = implode(':', array_slice(explode(':', $ip), 0, 1 + $length));
2821
* Wrapper for php's checkdnsrr function.
2823
* The windows failover is from the php manual
2824
* Please make sure to check the return value for === true and === false, since NULL could
2827
* @return true if entry found, false if not, NULL if this function is not supported by this environment
2829
function phpbb_checkdnsrr($host, $type = '')
2831
$type = (!$type) ? 'MX' : $type;
2833
if (DIRECTORY_SEPARATOR == '\\')
2835
if (!function_exists('exec'))
2840
// @exec('nslookup -retry=1 -timout=1 -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host), $output);
2841
@exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host), $output);
2843
// If output is empty, the nslookup failed
2849
foreach ($output as $line)
2856
// Valid records begin with host name:
2857
if (strpos($line, $host) === 0)
2865
else if (function_exists('checkdnsrr'))
2867
return (checkdnsrr($host, $type)) ? true : false;
2873
// Handler, header and footer
2876
* Error and message handler, call with trigger_error if reqd
2878
function msg_handler($errno, $msg_text, $errfile, $errline)
2880
global $cache, $db, $auth, $template, $config, $user;
2881
global $phpEx, $phpbb_root_path, $msg_title, $msg_long_text;
2883
// Do not display notices if we suppress them via @
2884
if (error_reporting() == 0)
2889
// Message handler is stripping text. In case we need it, we are possible to define long text...
2890
if (isset($msg_long_text) && $msg_long_text && !$msg_text)
2892
$msg_text = $msg_long_text;
2900
// Check the error reporting level and return if the error level does not match
2901
// If DEBUG is defined the default level is E_ALL
2902
if (($errno & ((defined('DEBUG')) ? E_ALL : error_reporting())) == 0)
2907
if (strpos($errfile, 'cache') === false && strpos($errfile, 'template.') === false)
2909
// flush the content, else we get a white page if output buffering is on
2910
if ($config['gzip_compress'])
2912
if (@extension_loaded('zlib') && !headers_sent())
2918
// remove complete path to installation, with the risk of changing backslashes meant to be there
2919
$errfile = str_replace(array(phpbb_realpath($phpbb_root_path), '\\'), array('', '/'), $errfile);
2920
$msg_text = str_replace(array(phpbb_realpath($phpbb_root_path), '\\'), array('', '/'), $msg_text);
2922
echo '<b>[phpBB Debug] PHP Notice</b>: in file <b>' . $errfile . '</b> on line <b>' . $errline . '</b>: <b>' . $msg_text . '</b><br />' . "\n";
2931
if (!empty($user) && !empty($user->lang))
2933
$msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
2934
$msg_title = (!isset($msg_title)) ? $user->lang['GENERAL_ERROR'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
2936
$l_return_index = sprintf($user->lang['RETURN_INDEX'], '<a href="' . $phpbb_root_path . '">', '</a>');
2939
if (!empty($config['board_contact']))
2941
$l_notify = '<p>' . sprintf($user->lang['NOTIFY_ADMIN_EMAIL'], $config['board_contact']) . '</p>';
2946
$msg_title = 'General Error';
2947
$l_return_index = '<a href="' . $phpbb_root_path . '">Return to index page</a>';
2950
if (!empty($config['board_contact']))
2952
$l_notify = '<p>Please notify the board administrator or webmaster: <a href="mailto:' . $config['board_contact'] . '">' . $config['board_contact'] . '</a></p>';
2956
garbage_collection();
2958
// Try to not call the adm page data...
2960
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2961
echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
2963
echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
2964
echo '<title>' . $msg_title . '</title>';
2965
echo '<style type="text/css">' . "\n" . '<!--' . "\n";
2966
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; } ';
2967
echo 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
2968
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; } ';
2969
echo '.panel { margin: 4px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
2970
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; } ';
2971
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; } ';
2972
echo "\n" . '//-->' . "\n";
2975
echo '<body id="errorpage">';
2976
echo '<div id="wrap">';
2977
echo ' <div id="page-header">';
2978
echo ' ' . $l_return_index;
2980
echo ' <div id="acp">';
2981
echo ' <div class="panel">';
2982
echo ' <div id="content">';
2983
echo ' <h1>' . $msg_title . '</h1>';
2985
echo ' <div>' . $msg_text . '</div>';
2992
echo ' <div id="page-footer">';
2993
echo ' Powered by phpBB © 2000, 2002, 2005, 2007 <a href="http://www.phpbb.com/">phpBB Group</a>';
3002
case E_USER_WARNING:
3005
define('IN_ERROR_HANDLER', true);
3007
if (empty($user->data))
3009
$user->session_begin();
3012
// We re-init the auth array to get correct results on login/logout
3013
$auth->acl($user->data);
3015
if (empty($user->lang))
3020
$msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
3021
$msg_title = (!isset($msg_title)) ? $user->lang['INFORMATION'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
3023
if (!defined('HEADER_INC'))
3025
if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
3027
adm_page_header($msg_title);
3031
page_header($msg_title);
3035
$template->set_filenames(array(
3036
'body' => 'message_body.html')
3039
$template->assign_vars(array(
3040
'MESSAGE_TITLE' => $msg_title,
3041
'MESSAGE_TEXT' => $msg_text,
3042
'S_USER_WARNING' => ($errno == E_USER_WARNING) ? true : false,
3043
'S_USER_NOTICE' => ($errno == E_USER_NOTICE) ? true : false)
3046
// We do not want the cron script to be called on error messages
3047
define('IN_CRON', true);
3049
if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
3062
// If we notice an error not handled here we pass this back to PHP by returning false
3063
// This may not work for all php versions
3068
* Generate page header
3070
function page_header($page_title = '', $display_online_list = true)
3072
global $db, $config, $template, $SID, $_SID, $user, $auth, $phpEx, $phpbb_root_path;
3074
if (defined('HEADER_INC'))
3079
define('HEADER_INC', true);
3082
if ($config['gzip_compress'])
3084
if (@extension_loaded('zlib') && !headers_sent())
3086
ob_start('ob_gzhandler');
3090
// Generate logged in/logged out status
3091
if ($user->data['user_id'] != ANONYMOUS)
3093
$u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=logout', true, $user->session_id);
3094
$l_login_logout = sprintf($user->lang['LOGOUT_USER'], $user->data['username']);
3098
$u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login');
3099
$l_login_logout = $user->lang['LOGIN'];
3102
// Last visit date/time
3103
$s_last_visit = ($user->data['user_id'] != ANONYMOUS) ? $user->format_date($user->data['session_last_visit']) : '';
3105
// Get users online list ... if required
3106
$l_online_users = $online_userlist = $l_online_record = '';
3108
if ($config['load_online'] && $config['load_online_time'] && $display_online_list)
3110
$logged_visible_online = $logged_hidden_online = $guests_online = $prev_user_id = 0;
3111
$prev_session_ip = $reading_sql = '';
3113
if (!empty($_REQUEST['f']))
3115
$f = request_var('f', 0);
3117
$reading_sql = ' AND s.session_page ' . $db->sql_like_expression("{$db->any_char}_f_={$f}x{$db->any_char}");
3120
// Get number of online guests
3121
if (!$config['load_online_guests'])
3123
if ($db->sql_layer === 'sqlite')
3125
$sql = 'SELECT COUNT(session_ip) as num_guests
3127
SELECT DISTINCT s.session_ip
3128
FROM ' . SESSIONS_TABLE . ' s
3129
WHERE s.session_user_id = ' . ANONYMOUS . '
3130
AND s.session_time >= ' . (time() - ($config['load_online_time'] * 60)) .
3136
$sql = 'SELECT COUNT(DISTINCT s.session_ip) as num_guests
3137
FROM ' . SESSIONS_TABLE . ' s
3138
WHERE s.session_user_id = ' . ANONYMOUS . '
3139
AND s.session_time >= ' . (time() - ($config['load_online_time'] * 60)) .
3142
$result = $db->sql_query($sql);
3143
$guests_online = (int) $db->sql_fetchfield('num_guests');
3144
$db->sql_freeresult($result);
3147
$sql = 'SELECT u.username, u.username_clean, u.user_id, u.user_type, u.user_allow_viewonline, u.user_colour, s.session_ip, s.session_viewonline
3148
FROM ' . USERS_TABLE . ' u, ' . SESSIONS_TABLE . ' s
3149
WHERE s.session_time >= ' . (time() - (intval($config['load_online_time']) * 60)) .
3151
((!$config['load_online_guests']) ? ' AND s.session_user_id <> ' . ANONYMOUS : '') . '
3152
AND u.user_id = s.session_user_id
3153
ORDER BY u.username_clean ASC, s.session_ip ASC';
3154
$result = $db->sql_query($sql);
3156
while ($row = $db->sql_fetchrow($result))
3158
// User is logged in and therefore not a guest
3159
if ($row['user_id'] != ANONYMOUS)
3161
// Skip multiple sessions for one user
3162
if ($row['user_id'] != $prev_user_id)
3164
if ($row['session_viewonline'])
3166
$logged_visible_online++;
3170
$row['username'] = '<em>' . $row['username'] . '</em>';
3171
$logged_hidden_online++;
3174
if (($row['session_viewonline']) || $auth->acl_get('u_viewonline'))
3176
$user_online_link = get_username_string(($row['user_type'] <> USER_IGNORE) ? 'full' : 'no_profile', $row['user_id'], $row['username'], $row['user_colour']);
3177
$online_userlist .= ($online_userlist != '') ? ', ' . $user_online_link : $user_online_link;
3181
$prev_user_id = $row['user_id'];
3185
// Skip multiple sessions for one user
3186
if ($row['session_ip'] != $prev_session_ip)
3192
$prev_session_ip = $row['session_ip'];
3194
$db->sql_freeresult($result);
3196
if (!$online_userlist)
3198
$online_userlist = $user->lang['NO_ONLINE_USERS'];
3201
if (empty($_REQUEST['f']))
3203
$online_userlist = $user->lang['REGISTERED_USERS'] . ' ' . $online_userlist;
3207
$l_online = ($guests_online == 1) ? $user->lang['BROWSING_FORUM_GUEST'] : $user->lang['BROWSING_FORUM_GUESTS'];
3208
$online_userlist = sprintf($l_online, $online_userlist, $guests_online);
3211
$total_online_users = $logged_visible_online + $logged_hidden_online + $guests_online;
3213
if ($total_online_users > $config['record_online_users'])
3215
set_config('record_online_users', $total_online_users, true);
3216
set_config('record_online_date', time(), true);
3219
// Build online listing
3220
$vars_online = array(
3221
'ONLINE' => array('total_online_users', 'l_t_user_s'),
3222
'REG' => array('logged_visible_online', 'l_r_user_s'),
3223
'HIDDEN' => array('logged_hidden_online', 'l_h_user_s'),
3224
'GUEST' => array('guests_online', 'l_g_user_s')
3227
foreach ($vars_online as $l_prefix => $var_ary)
3229
switch (${$var_ary[0]})
3232
${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_ZERO_TOTAL'];
3236
${$var_ary[1]} = $user->lang[$l_prefix . '_USER_TOTAL'];
3240
${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_TOTAL'];
3244
unset($vars_online);
3246
$l_online_users = sprintf($l_t_user_s, $total_online_users);
3247
$l_online_users .= sprintf($l_r_user_s, $logged_visible_online);
3248
$l_online_users .= sprintf($l_h_user_s, $logged_hidden_online);
3249
$l_online_users .= sprintf($l_g_user_s, $guests_online);
3251
$l_online_record = sprintf($user->lang['RECORD_ONLINE_USERS'], $config['record_online_users'], $user->format_date($config['record_online_date']));
3253
$l_online_time = ($config['load_online_time'] == 1) ? 'VIEW_ONLINE_TIME' : 'VIEW_ONLINE_TIMES';
3254
$l_online_time = sprintf($user->lang[$l_online_time], $config['load_online_time']);
3258
$l_online_time = '';
3261
$l_privmsgs_text = $l_privmsgs_text_unread = '';
3262
$s_privmsg_new = false;
3264
// Obtain number of new private messages if user is logged in
3265
if (isset($user->data['is_registered']) && $user->data['is_registered'])
3267
if ($user->data['user_new_privmsg'])
3269
$l_message_new = ($user->data['user_new_privmsg'] == 1) ? $user->lang['NEW_PM'] : $user->lang['NEW_PMS'];
3270
$l_privmsgs_text = sprintf($l_message_new, $user->data['user_new_privmsg']);
3272
if (!$user->data['user_last_privmsg'] || $user->data['user_last_privmsg'] > $user->data['session_last_visit'])
3274
$sql = 'UPDATE ' . USERS_TABLE . '
3275
SET user_last_privmsg = ' . $user->data['session_last_visit'] . '
3276
WHERE user_id = ' . $user->data['user_id'];
3277
$db->sql_query($sql);
3279
$s_privmsg_new = true;
3283
$s_privmsg_new = false;
3288
$l_privmsgs_text = $user->lang['NO_NEW_PM'];
3289
$s_privmsg_new = false;
3292
$l_privmsgs_text_unread = '';
3294
if ($user->data['user_unread_privmsg'] && $user->data['user_unread_privmsg'] != $user->data['user_new_privmsg'])
3296
$l_message_unread = ($user->data['user_unread_privmsg'] == 1) ? $user->lang['UNREAD_PM'] : $user->lang['UNREAD_PMS'];
3297
$l_privmsgs_text_unread = sprintf($l_message_unread, $user->data['user_unread_privmsg']);
3302
$tz = ($user->data['user_id'] != ANONYMOUS) ? strval(doubleval($user->data['user_timezone'])) : strval(doubleval($config['board_timezone']));
3304
// The following assigns all _common_ variables that may be used at any point in a template.
3305
$template->assign_vars(array(
3306
'SITENAME' => $config['sitename'],
3307
'SITE_DESCRIPTION' => $config['site_desc'],
3308
'PAGE_TITLE' => $page_title,
3309
'SCRIPT_NAME' => str_replace('.' . $phpEx, '', $user->page['page_name']),
3310
'LAST_VISIT_DATE' => sprintf($user->lang['YOU_LAST_VISIT'], $s_last_visit),
3311
'LAST_VISIT_YOU' => $s_last_visit,
3312
'CURRENT_TIME' => sprintf($user->lang['CURRENT_TIME'], $user->format_date(time(), false, true)),
3313
'TOTAL_USERS_ONLINE' => $l_online_users,
3314
'LOGGED_IN_USER_LIST' => $online_userlist,
3315
'RECORD_USERS' => $l_online_record,
3316
'PRIVATE_MESSAGE_INFO' => $l_privmsgs_text,
3317
'PRIVATE_MESSAGE_INFO_UNREAD' => $l_privmsgs_text_unread,
3319
'S_USER_NEW_PRIVMSG' => $user->data['user_new_privmsg'],
3320
'S_USER_UNREAD_PRIVMSG' => $user->data['user_unread_privmsg'],
3324
'SESSION_ID' => $user->session_id,
3325
'ROOT_PATH' => $phpbb_root_path,
3327
'L_LOGIN_LOGOUT' => $l_login_logout,
3328
'L_INDEX' => $user->lang['FORUM_INDEX'],
3329
'L_ONLINE_EXPLAIN' => $l_online_time,
3331
'U_PRIVATEMSGS' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&folder=inbox'),
3332
'U_RETURN_INBOX' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&folder=inbox'),
3333
'U_POPUP_PM' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&mode=popup'),
3334
'UA_POPUP_PM' => addslashes(append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&mode=popup')),
3335
'U_MEMBERLIST' => append_sid("{$phpbb_root_path}memberlist.$phpEx"),
3336
'U_MEMBERSLIST' => append_sid("{$phpbb_root_path}memberlist.$phpEx"),
3337
'U_VIEWONLINE' => ($auth->acl_gets('u_viewprofile', 'a_user', 'a_useradd', 'a_userdel')) ? append_sid("{$phpbb_root_path}viewonline.$phpEx") : '',
3338
'U_LOGIN_LOGOUT' => $u_login_logout,
3339
'U_INDEX' => append_sid("{$phpbb_root_path}index.$phpEx"),
3340
'U_SEARCH' => append_sid("{$phpbb_root_path}search.$phpEx"),
3341
'U_REGISTER' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register'),
3342
'U_PROFILE' => append_sid("{$phpbb_root_path}ucp.$phpEx"),
3343
'U_MODCP' => append_sid("{$phpbb_root_path}mcp.$phpEx", false, true, $user->session_id),
3344
'U_FAQ' => append_sid("{$phpbb_root_path}faq.$phpEx"),
3345
'U_SEARCH_SELF' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=egosearch'),
3346
'U_SEARCH_NEW' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=newposts'),
3347
'U_SEARCH_UNANSWERED' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unanswered'),
3348
'U_SEARCH_ACTIVE_TOPICS'=> append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=active_topics'),
3349
'U_DELETE_COOKIES' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=delete_cookies'),
3350
'U_TEAM' => append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=leaders'),
3351
'U_RESTORE_PERMISSIONS' => ($user->data['user_perm_from'] && $auth->acl_get('a_switchperm')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=restore_perm') : '',
3353
'S_USER_LOGGED_IN' => ($user->data['user_id'] != ANONYMOUS) ? true : false,
3354
'S_AUTOLOGIN_ENABLED' => ($config['allow_autologin']) ? true : false,
3355
'S_BOARD_DISABLED' => ($config['board_disable']) ? true : false,
3356
'S_REGISTERED_USER' => $user->data['is_registered'],
3357
'S_IS_BOT' => $user->data['is_bot'],
3358
'S_USER_PM_POPUP' => $user->optionget('popuppm'),
3359
'S_USER_LANG' => $user->lang['USER_LANG'],
3360
'S_USER_BROWSER' => (isset($user->data['session_browser'])) ? $user->data['session_browser'] : $user->lang['UNKNOWN_BROWSER'],
3361
'S_USERNAME' => $user->data['username'],
3362
'S_CONTENT_DIRECTION' => $user->lang['DIRECTION'],
3363
'S_CONTENT_FLOW_BEGIN' => ($user->lang['DIRECTION'] == 'ltr') ? 'left' : 'right',
3364
'S_CONTENT_FLOW_END' => ($user->lang['DIRECTION'] == 'ltr') ? 'right' : 'left',
3365
'S_CONTENT_ENCODING' => 'UTF-8',
3366
'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], ''),
3367
'S_DISPLAY_ONLINE_LIST' => ($l_online_time) ? 1 : 0,
3368
'S_DISPLAY_SEARCH' => (!$config['load_search']) ? 0 : (isset($auth) ? ($auth->acl_get('u_search') && $auth->acl_getf_global('f_search')) : 1),
3369
'S_DISPLAY_PM' => ($config['allow_privmsg'] && $user->data['is_registered'] && ($auth->acl_get('u_readpm') || $auth->acl_get('u_sendpm'))) ? true : false,
3370
'S_DISPLAY_MEMBERLIST' => (isset($auth)) ? $auth->acl_get('u_viewprofile') : 0,
3371
'S_NEW_PM' => ($s_privmsg_new) ? 1 : 0,
3373
'T_THEME_PATH' => "{$phpbb_root_path}styles/" . $user->theme['theme_path'] . '/theme',
3374
'T_TEMPLATE_PATH' => "{$phpbb_root_path}styles/" . $user->theme['template_path'] . '/template',
3375
'T_IMAGESET_PATH' => "{$phpbb_root_path}styles/" . $user->theme['imageset_path'] . '/imageset',
3376
'T_IMAGESET_LANG_PATH' => "{$phpbb_root_path}styles/" . $user->theme['imageset_path'] . '/imageset/' . $user->data['user_lang'],
3377
'T_IMAGES_PATH' => "{$phpbb_root_path}images/",
3378
'T_SMILIES_PATH' => "{$phpbb_root_path}{$config['smilies_path']}/",
3379
'T_AVATAR_PATH' => "{$phpbb_root_path}{$config['avatar_path']}/",
3380
'T_AVATAR_GALLERY_PATH' => "{$phpbb_root_path}{$config['avatar_gallery_path']}/",
3381
'T_ICONS_PATH' => "{$phpbb_root_path}{$config['icons_path']}/",
3382
'T_RANKS_PATH' => "{$phpbb_root_path}{$config['ranks_path']}/",
3383
'T_UPLOAD_PATH' => "{$phpbb_root_path}{$config['upload_path']}/",
3384
'T_STYLESHEET_LINK' => (!$user->theme['theme_storedb']) ? "{$phpbb_root_path}styles/" . $user->theme['theme_path'] . '/theme/stylesheet.css' : "{$phpbb_root_path}style.$phpEx?sid=$user->session_id&id=" . $user->theme['style_id'] . '&lang=' . $user->data['user_lang'],
3385
'T_STYLESHEET_NAME' => $user->theme['theme_name'],
3387
'SITE_LOGO_IMG' => $user->img('site_logo'))
3390
// application/xhtml+xml not used because of IE
3391
header('Content-type: text/html; charset=UTF-8');
3393
header('Cache-Control: private, no-cache="set-cookie"');
3394
header('Expires: 0');
3395
header('Pragma: no-cache');
3401
* Generate page footer
3403
function page_footer($run_cron = true)
3405
global $db, $config, $template, $user, $auth, $cache, $starttime, $phpbb_root_path, $phpEx;
3407
// Output page creation time
3408
if (defined('DEBUG'))
3410
$mtime = explode(' ', microtime());
3411
$totaltime = $mtime[0] + $mtime[1] - $starttime;
3413
if (!empty($_REQUEST['explain']) && $auth->acl_get('a_') && defined('DEBUG_EXTRA') && method_exists($db, 'sql_report'))
3415
$db->sql_report('display');
3418
$debug_output = sprintf('Time : %.3fs | ' . $db->sql_num_queries() . ' Queries | GZIP : ' . (($config['gzip_compress']) ? 'On' : 'Off') . (($user->load) ? ' | Load : ' . $user->load : ''), $totaltime);
3420
if ($auth->acl_get('a_') && defined('DEBUG_EXTRA'))
3422
if (function_exists('memory_get_usage'))
3424
if ($memory_usage = memory_get_usage())
3426
global $base_memory_usage;
3427
$memory_usage -= $base_memory_usage;
3428
$memory_usage = ($memory_usage >= 1048576) ? round((round($memory_usage / 1048576 * 100) / 100), 2) . ' ' . $user->lang['MB'] : (($memory_usage >= 1024) ? round((round($memory_usage / 1024 * 100) / 100), 2) . ' ' . $user->lang['KB'] : $memory_usage . ' ' . $user->lang['BYTES']);
3430
$debug_output .= ' | Memory Usage: ' . $memory_usage;
3434
$debug_output .= ' | <a href="' . build_url() . '&explain=1">Explain</a>';
3438
$template->assign_vars(array(
3439
'DEBUG_OUTPUT' => (defined('DEBUG')) ? $debug_output : '',
3440
'TRANSLATION_INFO' => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
3442
'U_ACP' => ($auth->acl_get('a_') && $user->data['is_registered']) ? append_sid("{$phpbb_root_path}adm/index.$phpEx", false, true, $user->session_id) : '')
3445
// Call cron-type script
3446
if (!defined('IN_CRON') && $run_cron && !$config['board_disable'])
3450
if (time() - $config['queue_interval'] > $config['last_queue_run'] && !defined('IN_ADMIN') && file_exists($phpbb_root_path . 'cache/queue.' . $phpEx))
3452
// Process email queue
3453
$cron_type = 'queue';
3455
else if (method_exists($cache, 'tidy') && time() - $config['cache_gc'] > $config['cache_last_gc'])
3458
$cron_type = 'tidy_cache';
3460
else if (time() - $config['warnings_gc'] > $config['warnings_last_gc'])
3462
$cron_type = 'tidy_warnings';
3464
else if (time() - $config['database_gc'] > $config['database_last_gc'])
3466
// Tidy the database
3467
$cron_type = 'tidy_database';
3469
else if (time() - $config['search_gc'] > $config['search_last_gc'])
3472
$cron_type = 'tidy_search';
3474
else if (time() - $config['session_gc'] > $config['session_last_gc'])
3476
$cron_type = 'tidy_sessions';
3481
$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" />');
3485
$template->display('body');
3487
garbage_collection();
3492
* Closing the cache object and the database
3493
* Cool function name, eh? We might want to add operations to it later
3495
function garbage_collection()
3499
// Unload cache, must be done before the DB connection if closed
3505
// Close our DB connection.
3513
* Handler for exit calls in phpBB.
3514
* This function supports hooks.
3516
* Note: This function is called after the template has been outputted.
3518
function exit_handler()
3522
if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
3524
if ($phpbb_hook->hook_return(__FUNCTION__))
3526
return $phpbb_hook->hook_return_result(__FUNCTION__);
3534
* Handler for init calls in phpBB. This function is called in user::setup();
3535
* This function supports hooks.
3537
function phpbb_user_session_handler()
3541
if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
3543
if ($phpbb_hook->hook_return(__FUNCTION__))
3545
return $phpbb_hook->hook_return_result(__FUNCTION__);
b'\\ No newline at end of file'