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", "\0"), 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 $super_global = ($cookie) ? '_COOKIE' : '_REQUEST';
75 if (!isset($GLOBALS[$super_global][$var_name]) || is_array($GLOBALS[$super_global][$var_name]) != is_array($default))
77 return (is_array($default)) ? array() : $default;
80 $var = $GLOBALS[$super_global][$var_name];
81 if (!is_array($default))
83 $type = gettype($default);
87 list($key_type, $type) = each($default);
88 $type = gettype($type);
89 $key_type = gettype($key_type);
93 $default = current($default);
94 list($sub_key_type, $sub_type) = each($default);
95 $sub_type = gettype($sub_type);
96 $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type;
97 $sub_key_type = gettype($sub_key_type);
106 foreach ($_var as $k => $v)
108 set_var($k, $k, $key_type);
109 if ($type == 'array' && is_array($v))
111 foreach ($v as $_k => $_v)
117 set_var($_k, $_k, $sub_key_type, $multibyte);
118 set_var($var[$k][$_k], $_v, $sub_type, $multibyte);
123 if ($type == 'array' || is_array($v))
127 set_var($var[$k], $v, $type, $multibyte);
133 set_var($var, $var, $type, $multibyte);
140 * Set config value. Creates missing config entry.
142 function set_config($config_name, $config_value, $is_dynamic = false)
144 global $db, $cache, $config;
146 $sql = 'UPDATE ' . CONFIG_TABLE . "
147 SET config_value = '" . $db->sql_escape($config_value) . "'
148 WHERE config_name = '" . $db->sql_escape($config_name) . "'";
149 $db->sql_query($sql);
151 if (!$db->sql_affectedrows() && !isset($config[$config_name]))
153 $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array(
154 'config_name' => $config_name,
155 'config_value' => $config_value,
156 'is_dynamic' => ($is_dynamic) ? 1 : 0));
157 $db->sql_query($sql);
160 $config[$config_name] = $config_value;
164 $cache->destroy('config');
169 * Set dynamic config value with arithmetic operation.
171 function set_config_count($config_name, $increment, $is_dynamic = false)
175 switch ($db->sql_layer)
178 // Precision must be from 1 to 18
179 $sql_update = 'CAST(CAST(config_value as DECIMAL(18, 0)) + ' . (int) $increment . ' as VARCHAR(255))';
183 // Need to cast to text first for PostgreSQL 7.x
184 $sql_update = 'CAST(CAST(config_value::text as DECIMAL(255, 0)) + ' . (int) $increment . ' as VARCHAR(255))';
187 // MySQL, SQlite, mssql, mssql_odbc, oracle
189 $sql_update = 'config_value + ' . (int) $increment;
193 $db->sql_query('UPDATE ' . CONFIG_TABLE . ' SET config_value = ' . $sql_update . " WHERE config_name = '" . $db->sql_escape($config_name) . "'");
197 $cache->destroy('config');
202 * Generates an alphanumeric random string of given length
206 function gen_rand_string($num_chars = 8)
208 // [a, z] + [0, 9] = 36
209 return substr(strtoupper(base_convert(unique_id(), 16, 36)), 0, $num_chars);
213 * Generates a user-friendly alphanumeric random string of given length
214 * We remove 0 and O so users cannot confuse those in passwords etc.
218 function gen_rand_string_friendly($num_chars = 8)
220 $rand_str = unique_id();
222 // Remove Z and Y from the base_convert(), replace 0 with Z and O with Y
223 // [a, z] + [0, 9] - {z, y} = [a, z] + [0, 9] - {0, o} = 34
224 $rand_str = str_replace(array('0', 'O'), array('Z', 'Y'), strtoupper(base_convert($rand_str, 16, 34)));
226 return substr($rand_str, 0, $num_chars);
231 * @param string $extra additional entropy
233 function unique_id($extra = 'c')
235 static $dss_seeded = false;
238 $val = $config['rand_seed'] . microtime();
240 $config['rand_seed'] = md5($config['rand_seed'] . $val . $extra);
242 if ($dss_seeded !== true && ($config['rand_seed_last_update'] < time() - rand(1,10)))
244 set_config('rand_seed_last_update', time(), true);
245 set_config('rand_seed', $config['rand_seed'], true);
249 return substr($val, 4, 16);
253 * Wrapper for mt_rand() which allows swapping $min and $max parameters.
255 * PHP does not allow us to swap the order of the arguments for mt_rand() anymore.
256 * (since PHP 5.3.4, see http://bugs.php.net/46587)
258 * @param int $min Lowest value to be returned
259 * @param int $max Highest value to be returned
261 * @return int Random integer between $min and $max (or $max and $min)
263 function phpbb_mt_rand($min, $max)
265 return ($min > $max) ? mt_rand($max, $min) : mt_rand($min, $max);
269 * Wrapper for getdate() which returns the equivalent array for UTC timestamps.
271 * @param int $time Unix timestamp (optional)
273 * @return array Returns an associative array of information related to the timestamp.
274 * See http://www.php.net/manual/en/function.getdate.php
276 function phpbb_gmgetdate($time = false)
283 // getdate() interprets timestamps in local time.
284 // What follows uses the fact that getdate() and
285 // date('Z') balance each other out.
286 return getdate($time - date('Z'));
290 * Return formatted string for filesizes
292 * @param int $value filesize in bytes
293 * @param bool $string_only true if language string should be returned
294 * @param array $allowed_units only allow these units (data array indexes)
296 * @return mixed data array if $string_only is false
299 function get_formatted_filesize($value, $string_only = true, $allowed_units = false)
303 $available_units = array(
305 'min' => 1073741824, // pow(2, 30)
311 'min' => 1048576, // pow(2, 20)
317 'min' => 1024, // pow(2, 10)
325 'si_unit' => 'BYTES', // Language index
326 'iec_unit' => 'BYTES', // Language index
330 foreach ($available_units as $si_identifier => $unit_info)
332 if (!empty($allowed_units) && $si_identifier != 'b' && !in_array($si_identifier, $allowed_units))
337 if ($value >= $unit_info['min'])
339 $unit_info['si_identifier'] = $si_identifier;
344 unset($available_units);
346 for ($i = 0; $i < $unit_info['index']; $i++)
350 $value = round($value, 2);
352 // Lookup units in language dictionary
353 $unit_info['si_unit'] = (isset($user->lang[$unit_info['si_unit']])) ? $user->lang[$unit_info['si_unit']] : $unit_info['si_unit'];
354 $unit_info['iec_unit'] = (isset($user->lang[$unit_info['iec_unit']])) ? $user->lang[$unit_info['iec_unit']] : $unit_info['iec_unit'];
357 $unit_info['unit'] = $unit_info['iec_unit'];
361 $unit_info['value'] = $value;
366 return $value . ' ' . $unit_info['unit'];
370 * Determine whether we are approaching the maximum execution time. Should be called once
371 * at the beginning of the script in which it's used.
372 * @return bool Either true if the maximum execution time is nearly reached, or false
373 * if some time is still left.
375 function still_on_time($extra_time = 15)
377 static $max_execution_time, $start_time;
379 $time = explode(' ', microtime());
380 $current_time = $time[0] + $time[1];
382 if (empty($max_execution_time))
384 $max_execution_time = (function_exists('ini_get')) ? (int) @ini_get('max_execution_time') : (int) @get_cfg_var('max_execution_time');
386 // If zero, then set to something higher to not let the user catch the ten seconds barrier.
387 if ($max_execution_time === 0)
389 $max_execution_time = 50 + $extra_time;
392 $max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50);
394 // For debugging purposes
395 // $max_execution_time = 10;
398 $start_time = (empty($starttime)) ? $current_time : $starttime;
401 return (ceil($current_time - $start_time) < $max_execution_time) ? true : false;
406 * @version Version 0.1 / slightly modified for phpBB 3.0.x (using $H$ as hash type identifier)
408 * Portable PHP password hashing framework.
410 * Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
413 * There's absolutely no warranty.
415 * The homepage URL for this framework is:
417 * http://www.openwall.com/phpass/
419 * Please be sure to update the Version line if you edit this file in any way.
420 * It is suggested that you leave the main version number intact, but indicate
421 * your project name (after the slash) and add your own revision information.
423 * Please do not change the "private" password hashing method implemented in
424 * here, thereby making your hashes incompatible. However, if you must, please
425 * change the hash type identifier (the "$P$") to something different.
427 * Obviously, since this code is in the public domain, the above are not
428 * requirements (there can be none), but merely suggestions.
433 function phpbb_hash($password)
436 $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
438 $random_state = unique_id();
442 if (($fh = @fopen('/dev/urandom', 'rb')))
444 $random = fread($fh, $count);
448 if (strlen($random) < $count)
452 for ($i = 0; $i < $count; $i += 16)
454 $random_state = md5(unique_id() . $random_state);
455 $random .= pack('H*', md5($random_state));
457 $random = substr($random, 0, $count);
460 $hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64);
462 if (strlen($hash) == 34)
468 return md5($password);
472 * Check for correct password
474 * @param string $password The password in plain text
475 * @param string $hash The stored password hash
477 * @return bool Returns true if the password is correct, false if not.
479 function phpbb_check_hash($password, $hash)
482 $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
483 if (strlen($hash) == 34)
485 return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
489 return (md5($password) === $hash) ? true : false;
493 * Generate salt for hash generation
495 function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6)
497 if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
499 $iteration_count_log2 = 8;
503 $output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)];
504 $output .= _hash_encode64($input, 6, $itoa64);
512 function _hash_encode64($input, $count, &$itoa64)
519 $value = ord($input[$i++]);
520 $output .= $itoa64[$value & 0x3f];
524 $value |= ord($input[$i]) << 8;
527 $output .= $itoa64[($value >> 6) & 0x3f];
536 $value |= ord($input[$i]) << 16;
539 $output .= $itoa64[($value >> 12) & 0x3f];
546 $output .= $itoa64[($value >> 18) & 0x3f];
554 * The crypt function/replacement
556 function _hash_crypt_private($password, $setting, &$itoa64)
560 // Check for correct hash
561 if (substr($setting, 0, 3) != '$H$' && substr($setting, 0, 3) != '$P$')
566 $count_log2 = strpos($itoa64, $setting[3]);
568 if ($count_log2 < 7 || $count_log2 > 30)
573 $count = 1 << $count_log2;
574 $salt = substr($setting, 4, 8);
576 if (strlen($salt) != 8)
582 * We're kind of forced to use MD5 here since it's the only
583 * cryptographic primitive available in all versions of PHP
584 * currently in use. To implement our own low-level crypto
585 * in PHP would result in much worse performance and
586 * consequently in lower iteration counts and hashes that are
587 * quicker to crack (by non-PHP code).
589 if (PHP_VERSION >= 5)
591 $hash = md5($salt . $password, true);
594 $hash = md5($hash . $password, true);
600 $hash = pack('H*', md5($salt . $password));
603 $hash = pack('H*', md5($hash . $password));
608 $output = substr($setting, 0, 12);
609 $output .= _hash_encode64($hash, 16, $itoa64);
615 * Hashes an email address to a big integer
617 * @param string $email Email address
619 * @return string Unsigned Big Integer
621 function phpbb_email_hash($email)
623 return sprintf('%u', crc32(strtolower($email))) . strlen($email);
627 * Wrapper for version_compare() that allows using uppercase A and B
628 * for alpha and beta releases.
630 * See http://www.php.net/manual/en/function.version-compare.php
632 * @param string $version1 First version number
633 * @param string $version2 Second version number
634 * @param string $operator Comparison operator (optional)
636 * @return mixed Boolean (true, false) if comparison operator is specified.
637 * Integer (-1, 0, 1) otherwise.
639 function phpbb_version_compare($version1, $version2, $operator = null)
641 $version1 = strtolower($version1);
642 $version2 = strtolower($version2);
644 if (is_null($operator))
646 return version_compare($version1, $version2);
650 return version_compare($version1, $version2, $operator);
655 * Global function for chmodding directories and files for internal use
657 * This function determines owner and group whom the file belongs to and user and group of PHP and then set safest possible file permissions.
658 * The function determines owner and group from common.php file and sets the same to the provided file.
659 * The function uses bit fields to build the permissions.
660 * The function sets the appropiate execute bit on directories.
662 * Supported constants representing bit fields are:
664 * CHMOD_ALL - all permissions (7)
665 * CHMOD_READ - read permission (4)
666 * CHMOD_WRITE - write permission (2)
667 * CHMOD_EXECUTE - execute permission (1)
669 * NOTE: The function uses POSIX extension and fileowner()/filegroup() functions. If any of them is disabled, this function tries to build proper permissions, by calling is_readable() and is_writable() functions.
671 * @param string $filename The file/directory to be chmodded
672 * @param int $perms Permissions to set
674 * @return bool true on success, otherwise false
675 * @author faw, phpBB Group
677 function phpbb_chmod($filename, $perms = CHMOD_READ)
681 // Return if the file no longer exists.
682 if (!file_exists($filename))
687 // Determine some common vars
688 if (empty($_chmod_info))
690 if (!function_exists('fileowner') || !function_exists('filegroup'))
692 // No need to further determine owner/group - it is unknown
693 $_chmod_info['process'] = false;
697 global $phpbb_root_path, $phpEx;
699 // Determine owner/group of common.php file and the filename we want to change here
700 $common_php_owner = @fileowner($phpbb_root_path . 'common.' . $phpEx);
701 $common_php_group = @filegroup($phpbb_root_path . 'common.' . $phpEx);
703 // And the owner and the groups PHP is running under.
704 $php_uid = (function_exists('posix_getuid')) ? @posix_getuid() : false;
705 $php_gids = (function_exists('posix_getgroups')) ? @posix_getgroups() : false;
707 // If we are unable to get owner/group, then do not try to set them by guessing
708 if (!$php_uid || empty($php_gids) || !$common_php_owner || !$common_php_group)
710 $_chmod_info['process'] = false;
714 $_chmod_info = array(
716 'common_owner' => $common_php_owner,
717 'common_group' => $common_php_group,
718 'php_uid' => $php_uid,
719 'php_gids' => $php_gids,
725 if ($_chmod_info['process'])
727 $file_uid = @fileowner($filename);
728 $file_gid = @filegroup($filename);
731 if (@chown($filename, $_chmod_info['common_owner']))
734 $file_uid = @fileowner($filename);
738 if (@chgrp($filename, $_chmod_info['common_group']))
741 $file_gid = @filegroup($filename);
744 // If the file_uid/gid now match the one from common.php we can process further, else we are not able to change something
745 if ($file_uid != $_chmod_info['common_owner'] || $file_gid != $_chmod_info['common_group'])
747 $_chmod_info['process'] = false;
751 // Still able to process?
752 if ($_chmod_info['process'])
754 if ($file_uid == $_chmod_info['php_uid'])
758 else if (in_array($file_gid, $_chmod_info['php_gids']))
764 // Since we are setting the everyone bit anyway, no need to do expensive operations
765 $_chmod_info['process'] = false;
769 // We are not able to determine or change something
770 if (!$_chmod_info['process'])
775 // Owner always has read/write permission
776 $owner = CHMOD_READ | CHMOD_WRITE;
777 if (is_dir($filename))
779 $owner |= CHMOD_EXECUTE;
781 // Only add execute bit to the permission if the dir needs to be readable
782 if ($perms & CHMOD_READ)
784 $perms |= CHMOD_EXECUTE;
791 $result = @chmod($filename, ($owner << 6) + (0 << 3) + (0 << 0));
795 if (is_readable($filename) && phpbb_is_writable($filename))
801 $result = @chmod($filename, ($owner << 6) + ($perms << 3) + (0 << 0));
805 if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))
811 $result = @chmod($filename, ($owner << 6) + ($perms << 3) + ($perms << 0));
815 if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))
829 * Test if a file/directory is writable
831 * This function calls the native is_writable() when not running under
832 * Windows and it is not disabled.
834 * @param string $file Path to perform write test on
835 * @return bool True when the path is writable, otherwise false.
837 function phpbb_is_writable($file)
839 if (strtolower(substr(PHP_OS, 0, 3)) === 'win' || !function_exists('is_writable'))
841 if (file_exists($file))
843 // Canonicalise path to absolute path
844 $file = phpbb_realpath($file);
848 // Test directory by creating a file inside the directory
849 $result = @tempnam($file, 'i_w');
851 if (is_string($result) && file_exists($result))
855 // Ensure the file is actually in the directory (returned realpathed)
856 return (strpos($result, $file) === 0) ? true : false;
861 $handle = @fopen($file, 'r+');
863 if (is_resource($handle))
872 // file does not exist test if we can write to the directory
873 $dir = dirname($file);
875 if (file_exists($dir) && is_dir($dir) && phpbb_is_writable($dir))
885 return is_writable($file);
889 // Compatibility functions
891 if (!function_exists('array_combine'))
894 * A wrapper for the PHP5 function array_combine()
895 * @param array $keys contains keys for the resulting array
896 * @param array $values contains values for the resulting array
898 * @return Returns an array by using the values from the keys array as keys and the
899 * values from the values array as the corresponding values. Returns false if the
900 * number of elements for each array isn't equal or if the arrays are empty.
902 function array_combine($keys, $values)
904 $keys = array_values($keys);
905 $values = array_values($values);
908 $m = sizeof($values);
909 if (!$n || !$m || ($n != $m))
915 for ($i = 0; $i < $n; $i++)
917 $combined[$keys[$i]] = $values[$i];
923 if (!function_exists('str_split'))
926 * A wrapper for the PHP5 function str_split()
927 * @param array $string contains the string to be converted
928 * @param array $split_length contains the length of each chunk
930 * @return Converts a string to an array. If the optional split_length parameter is specified,
931 * the returned array will be broken down into chunks with each being split_length in length,
932 * otherwise each chunk will be one character in length. FALSE is returned if split_length is
933 * less than 1. If the split_length length exceeds the length of string, the entire string is
934 * returned as the first (and only) array element.
936 function str_split($string, $split_length = 1)
938 if ($split_length < 1)
942 else if ($split_length >= strlen($string))
944 return array($string);
948 preg_match_all('#.{1,' . $split_length . '}#s', $string, $matches);
954 if (!function_exists('stripos'))
957 * A wrapper for the PHP5 function stripos
958 * Find position of first occurrence of a case-insensitive string
960 * @param string $haystack is the string to search in
961 * @param string $needle is the string to search for
963 * @return mixed Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.
964 * Note that the needle may be a string of one or more characters.
965 * If needle is not found, stripos() will return boolean FALSE.
967 function stripos($haystack, $needle)
969 if (preg_match('#' . preg_quote($needle, '#') . '#i', $haystack, $m))
971 return strpos($haystack, $m[0]);
979 * Checks if a path ($path) is absolute or relative
981 * @param string $path Path to check absoluteness of
984 function is_absolute($path)
986 return ($path[0] == '/' || (DIRECTORY_SEPARATOR == '\\' && preg_match('#^[a-z]:[/\\\]#i', $path))) ? true : false;
990 * @author Chris Smith <chris@project-minerva.org>
991 * @copyright 2006 Project Minerva Team
992 * @param string $path The path which we should attempt to resolve.
995 function phpbb_own_realpath($path)
997 // Now to perform funky shizzle
999 // Switch to use UNIX slashes
1000 $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
1003 // Determine what sort of path we have
1004 if (is_absolute($path))
1008 if ($path[0] == '/')
1010 // Absolute path, *NIX style
1015 // Absolute path, Windows style
1016 // Remove the drive letter and colon
1017 $path_prefix = $path[0] . ':';
1018 $path = substr($path, 2);
1024 // Prepend the current working directory
1025 if (function_exists('getcwd'))
1027 // This is the best method, hopefully it is enabled!
1028 $path = str_replace(DIRECTORY_SEPARATOR, '/', getcwd()) . '/' . $path;
1030 if (preg_match('#^[a-z]:#i', $path))
1032 $path_prefix = $path[0] . ':';
1033 $path = substr($path, 2);
1040 else if (isset($_SERVER['SCRIPT_FILENAME']) && !empty($_SERVER['SCRIPT_FILENAME']))
1042 // Warning: If chdir() has been used this will lie!
1043 // Warning: This has some problems sometime (CLI can create them easily)
1044 $path = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['SCRIPT_FILENAME'])) . '/' . $path;
1050 // We have no way of getting the absolute path, just run on using relative ones.
1056 // Remove any repeated slashes
1057 $path = preg_replace('#/{2,}#', '/', $path);
1059 // Remove the slashes from the start and end of the path
1060 $path = trim($path, '/');
1062 // Break the string into little bits for us to nibble on
1063 $bits = explode('/', $path);
1065 // Remove any . in the path, renumber array for the loop below
1066 $bits = array_values(array_diff($bits, array('.')));
1068 // Lets get looping, run over and resolve any .. (up directory)
1069 for ($i = 0, $max = sizeof($bits); $i < $max; $i++)
1072 if ($bits[$i] == '..' )
1074 if (isset($bits[$i - 1]))
1076 if ($bits[$i - 1] != '..')
1078 // We found a .. and we are able to traverse upwards, lets do it!
1080 unset($bits[$i - 1]);
1083 $bits = array_values($bits);
1086 else if ($absolute) // ie. !isset($bits[$i - 1]) && $absolute
1088 // We have an absolute path trying to descend above the root of the filesystem
1095 // Prepend the path prefix
1096 array_unshift($bits, $path_prefix);
1100 $max = sizeof($bits) - 1;
1102 // Check if we are able to resolve symlinks, Windows cannot.
1103 $symlink_resolve = (function_exists('readlink')) ? true : false;
1105 foreach ($bits as $i => $bit)
1107 if (@is_dir("$resolved/$bit") || ($i == $max && @is_file("$resolved/$bit")))
1110 if ($symlink_resolve && is_link("$resolved/$bit") && ($link = readlink("$resolved/$bit")))
1112 // Resolved a symlink.
1113 $resolved = $link . (($i == $max) ? '' : '/');
1119 // Something doesn't exist here!
1120 // This is correct realpath() behaviour but sadly open_basedir and safe_mode make this problematic
1123 $resolved .= $bit . (($i == $max) ? '' : '/');
1126 // @todo If the file exists fine and open_basedir only has one path we should be able to prepend it
1127 // because we must be inside that basedir, the question is where...
1128 // @internal The slash in is_dir() gets around an open_basedir restriction
1129 if (!@file_exists($resolved) || (!@is_dir($resolved . '/') && !is_file($resolved)))
1134 // Put the slashes back to the native operating systems slashes
1135 $resolved = str_replace('/', DIRECTORY_SEPARATOR, $resolved);
1137 // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
1138 if (substr($resolved, -1) == DIRECTORY_SEPARATOR)
1140 return substr($resolved, 0, -1);
1143 return $resolved; // We got here, in the end!
1146 if (!function_exists('realpath'))
1149 * A wrapper for realpath
1152 function phpbb_realpath($path)
1154 return phpbb_own_realpath($path);
1160 * A wrapper for realpath
1162 function phpbb_realpath($path)
1164 $realpath = realpath($path);
1166 // Strangely there are provider not disabling realpath but returning strange values. :o
1167 // We at least try to cope with them.
1168 if ($realpath === $path || $realpath === false)
1170 return phpbb_own_realpath($path);
1173 // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
1174 if (substr($realpath, -1) == DIRECTORY_SEPARATOR)
1176 $realpath = substr($realpath, 0, -1);
1183 if (!function_exists('htmlspecialchars_decode'))
1186 * A wrapper for htmlspecialchars_decode
1189 function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
1191 return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
1195 // functions used for building option fields
1198 * Pick a language, any language ...
1200 function language_select($default = '')
1204 $sql = 'SELECT lang_iso, lang_local_name
1205 FROM ' . LANG_TABLE . '
1206 ORDER BY lang_english_name';
1207 $result = $db->sql_query($sql);
1210 while ($row = $db->sql_fetchrow($result))
1212 $selected = ($row['lang_iso'] == $default) ? ' selected="selected"' : '';
1213 $lang_options .= '<option value="' . $row['lang_iso'] . '"' . $selected . '>' . $row['lang_local_name'] . '</option>';
1215 $db->sql_freeresult($result);
1217 return $lang_options;
1221 * Pick a template/theme combo,
1223 function style_select($default = '', $all = false)
1227 $sql_where = (!$all) ? 'WHERE style_active = 1 ' : '';
1228 $sql = 'SELECT style_id, style_name
1229 FROM ' . STYLES_TABLE . "
1231 ORDER BY style_name";
1232 $result = $db->sql_query($sql);
1234 $style_options = '';
1235 while ($row = $db->sql_fetchrow($result))
1237 $selected = ($row['style_id'] == $default) ? ' selected="selected"' : '';
1238 $style_options .= '<option value="' . $row['style_id'] . '"' . $selected . '>' . $row['style_name'] . '</option>';
1240 $db->sql_freeresult($result);
1242 return $style_options;
1248 function tz_select($default = '', $truncate = false)
1253 foreach ($user->lang['tz_zones'] as $offset => $zone)
1257 $zone_trunc = truncate_string($zone, 50, 255, false, '...');
1261 $zone_trunc = $zone;
1264 if (is_numeric($offset))
1266 $selected = ($offset == $default) ? ' selected="selected"' : '';
1267 $tz_select .= '<option title="' . $zone . '" value="' . $offset . '"' . $selected . '>' . $zone_trunc . '</option>';
1274 // Functions handling topic/post tracking/marking
1277 * Marks a topic/forum as read
1278 * Marks a topic as posted to
1280 * @param int $user_id can only be used with $mode == 'post'
1282 function markread($mode, $forum_id = false, $topic_id = false, $post_time = 0, $user_id = 0)
1284 global $db, $user, $config;
1288 if ($forum_id === false || !sizeof($forum_id))
1290 if ($config['load_db_lastread'] && $user->data['is_registered'])
1292 // Mark all forums read (index page)
1293 $db->sql_query('DELETE FROM ' . TOPICS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
1294 $db->sql_query('DELETE FROM ' . FORUMS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
1295 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
1297 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1299 $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1300 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1302 unset($tracking_topics['tf']);
1303 unset($tracking_topics['t']);
1304 unset($tracking_topics['f']);
1305 $tracking_topics['l'] = base_convert(time() - $config['board_startdate'], 10, 36);
1307 $user->set_cookie('track', tracking_serialize($tracking_topics), time() + 31536000);
1308 $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking_topics)) : tracking_serialize($tracking_topics);
1310 unset($tracking_topics);
1312 if ($user->data['is_registered'])
1314 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
1321 else if ($mode == 'topics')
1323 // Mark all topics in forums read
1324 if (!is_array($forum_id))
1326 $forum_id = array($forum_id);
1329 // Add 0 to forums array to mark global announcements correctly
1332 if ($config['load_db_lastread'] && $user->data['is_registered'])
1334 $sql = 'DELETE FROM ' . TOPICS_TRACK_TABLE . "
1335 WHERE user_id = {$user->data['user_id']}
1336 AND " . $db->sql_in_set('forum_id', $forum_id);
1337 $db->sql_query($sql);
1339 $sql = 'SELECT forum_id
1340 FROM ' . FORUMS_TRACK_TABLE . "
1341 WHERE user_id = {$user->data['user_id']}
1342 AND " . $db->sql_in_set('forum_id', $forum_id);
1343 $result = $db->sql_query($sql);
1345 $sql_update = array();
1346 while ($row = $db->sql_fetchrow($result))
1348 $sql_update[] = (int) $row['forum_id'];
1350 $db->sql_freeresult($result);
1352 if (sizeof($sql_update))
1354 $sql = 'UPDATE ' . FORUMS_TRACK_TABLE . '
1355 SET mark_time = ' . time() . "
1356 WHERE user_id = {$user->data['user_id']}
1357 AND " . $db->sql_in_set('forum_id', $sql_update);
1358 $db->sql_query($sql);
1361 if ($sql_insert = array_diff($forum_id, $sql_update))
1364 foreach ($sql_insert as $f_id)
1367 'user_id' => (int) $user->data['user_id'],
1368 'forum_id' => (int) $f_id,
1369 'mark_time' => time()
1373 $db->sql_multi_insert(FORUMS_TRACK_TABLE, $sql_ary);
1376 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1378 $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1379 $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
1381 foreach ($forum_id as $f_id)
1383 $topic_ids36 = (isset($tracking['tf'][$f_id])) ? $tracking['tf'][$f_id] : array();
1385 if (isset($tracking['tf'][$f_id]))
1387 unset($tracking['tf'][$f_id]);
1390 foreach ($topic_ids36 as $topic_id36)
1392 unset($tracking['t'][$topic_id36]);
1395 if (isset($tracking['f'][$f_id]))
1397 unset($tracking['f'][$f_id]);
1400 $tracking['f'][$f_id] = base_convert(time() - $config['board_startdate'], 10, 36);
1403 if (isset($tracking['tf']) && empty($tracking['tf']))
1405 unset($tracking['tf']);
1408 $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
1409 $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
1416 else if ($mode == 'topic')
1418 if ($topic_id === false || $forum_id === false)
1423 if ($config['load_db_lastread'] && $user->data['is_registered'])
1425 $sql = 'UPDATE ' . TOPICS_TRACK_TABLE . '
1426 SET mark_time = ' . (($post_time) ? $post_time : time()) . "
1427 WHERE user_id = {$user->data['user_id']}
1428 AND topic_id = $topic_id";
1429 $db->sql_query($sql);
1432 if (!$db->sql_affectedrows())
1434 $db->sql_return_on_error(true);
1437 'user_id' => (int) $user->data['user_id'],
1438 'topic_id' => (int) $topic_id,
1439 'forum_id' => (int) $forum_id,
1440 'mark_time' => ($post_time) ? (int) $post_time : time(),
1443 $db->sql_query('INSERT INTO ' . TOPICS_TRACK_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
1445 $db->sql_return_on_error(false);
1448 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1450 $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1451 $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
1453 $topic_id36 = base_convert($topic_id, 10, 36);
1455 if (!isset($tracking['t'][$topic_id36]))
1457 $tracking['tf'][$forum_id][$topic_id36] = true;
1460 $post_time = ($post_time) ? $post_time : time();
1461 $tracking['t'][$topic_id36] = base_convert($post_time - $config['board_startdate'], 10, 36);
1463 // If the cookie grows larger than 10000 characters we will remove the smallest value
1464 // This can result in old topics being unread - but most of the time it should be accurate...
1465 if (isset($_COOKIE[$config['cookie_name'] . '_track']) && strlen($_COOKIE[$config['cookie_name'] . '_track']) > 10000)
1467 //echo 'Cookie grown too large' . print_r($tracking, true);
1469 // We get the ten most minimum stored time offsets and its associated topic ids
1470 $time_keys = array();
1471 for ($i = 0; $i < 10 && sizeof($tracking['t']); $i++)
1473 $min_value = min($tracking['t']);
1474 $m_tkey = array_search($min_value, $tracking['t']);
1475 unset($tracking['t'][$m_tkey]);
1477 $time_keys[$m_tkey] = $min_value;
1480 // Now remove the topic ids from the array...
1481 foreach ($tracking['tf'] as $f_id => $topic_id_ary)
1483 foreach ($time_keys as $m_tkey => $min_value)
1485 if (isset($topic_id_ary[$m_tkey]))
1487 $tracking['f'][$f_id] = $min_value;
1488 unset($tracking['tf'][$f_id][$m_tkey]);
1493 if ($user->data['is_registered'])
1495 $user->data['user_lastmark'] = intval(base_convert(max($time_keys) + $config['board_startdate'], 36, 10));
1496 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . $user->data['user_lastmark'] . " WHERE user_id = {$user->data['user_id']}");
1500 $tracking['l'] = max($time_keys);
1504 $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
1505 $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
1510 else if ($mode == 'post')
1512 if ($topic_id === false)
1517 $use_user_id = (!$user_id) ? $user->data['user_id'] : $user_id;
1519 if ($config['load_db_track'] && $use_user_id != ANONYMOUS)
1521 $db->sql_return_on_error(true);
1524 'user_id' => (int) $use_user_id,
1525 'topic_id' => (int) $topic_id,
1529 $db->sql_query('INSERT INTO ' . TOPICS_POSTED_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
1531 $db->sql_return_on_error(false);
1539 * Get topic tracking info by using already fetched info
1541 function get_topic_tracking($forum_id, $topic_ids, &$rowset, $forum_mark_time, $global_announce_list = false)
1543 global $config, $user;
1545 $last_read = array();
1547 if (!is_array($topic_ids))
1549 $topic_ids = array($topic_ids);
1552 foreach ($topic_ids as $topic_id)
1554 if (!empty($rowset[$topic_id]['mark_time']))
1556 $last_read[$topic_id] = $rowset[$topic_id]['mark_time'];
1560 $topic_ids = array_diff($topic_ids, array_keys($last_read));
1562 if (sizeof($topic_ids))
1564 $mark_time = array();
1566 // Get global announcement info
1567 if ($global_announce_list && sizeof($global_announce_list))
1569 if (!isset($forum_mark_time[0]))
1573 $sql = 'SELECT mark_time
1574 FROM ' . FORUMS_TRACK_TABLE . "
1575 WHERE user_id = {$user->data['user_id']}
1577 $result = $db->sql_query($sql);
1578 $row = $db->sql_fetchrow($result);
1579 $db->sql_freeresult($result);
1583 $mark_time[0] = $row['mark_time'];
1588 if ($forum_mark_time[0] !== false)
1590 $mark_time[0] = $forum_mark_time[0];
1595 if (!empty($forum_mark_time[$forum_id]) && $forum_mark_time[$forum_id] !== false)
1597 $mark_time[$forum_id] = $forum_mark_time[$forum_id];
1600 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
1602 foreach ($topic_ids as $topic_id)
1604 if ($global_announce_list && isset($global_announce_list[$topic_id]))
1606 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1610 $last_read[$topic_id] = $user_lastmark;
1619 * Get topic tracking info from db (for cookie based tracking only this function is used)
1621 function get_complete_topic_tracking($forum_id, $topic_ids, $global_announce_list = false)
1623 global $config, $user;
1625 $last_read = array();
1627 if (!is_array($topic_ids))
1629 $topic_ids = array($topic_ids);
1632 if ($config['load_db_lastread'] && $user->data['is_registered'])
1636 $sql = 'SELECT topic_id, mark_time
1637 FROM ' . TOPICS_TRACK_TABLE . "
1638 WHERE user_id = {$user->data['user_id']}
1639 AND " . $db->sql_in_set('topic_id', $topic_ids);
1640 $result = $db->sql_query($sql);
1642 while ($row = $db->sql_fetchrow($result))
1644 $last_read[$row['topic_id']] = $row['mark_time'];
1646 $db->sql_freeresult($result);
1648 $topic_ids = array_diff($topic_ids, array_keys($last_read));
1650 if (sizeof($topic_ids))
1652 $sql = 'SELECT forum_id, mark_time
1653 FROM ' . FORUMS_TRACK_TABLE . "
1654 WHERE user_id = {$user->data['user_id']}
1656 (($global_announce_list && sizeof($global_announce_list)) ? "IN (0, $forum_id)" : "= $forum_id");
1657 $result = $db->sql_query($sql);
1659 $mark_time = array();
1660 while ($row = $db->sql_fetchrow($result))
1662 $mark_time[$row['forum_id']] = $row['mark_time'];
1664 $db->sql_freeresult($result);
1666 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
1668 foreach ($topic_ids as $topic_id)
1670 if ($global_announce_list && isset($global_announce_list[$topic_id]))
1672 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1676 $last_read[$topic_id] = $user_lastmark;
1681 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1683 global $tracking_topics;
1685 if (!isset($tracking_topics) || !sizeof($tracking_topics))
1687 $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1688 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1691 if (!$user->data['is_registered'])
1693 $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
1697 $user_lastmark = $user->data['user_lastmark'];
1700 foreach ($topic_ids as $topic_id)
1702 $topic_id36 = base_convert($topic_id, 10, 36);
1704 if (isset($tracking_topics['t'][$topic_id36]))
1706 $last_read[$topic_id] = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
1710 $topic_ids = array_diff($topic_ids, array_keys($last_read));
1712 if (sizeof($topic_ids))
1714 $mark_time = array();
1715 if ($global_announce_list && sizeof($global_announce_list))
1717 if (isset($tracking_topics['f'][0]))
1719 $mark_time[0] = base_convert($tracking_topics['f'][0], 36, 10) + $config['board_startdate'];
1723 if (isset($tracking_topics['f'][$forum_id]))
1725 $mark_time[$forum_id] = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
1728 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user_lastmark;
1730 foreach ($topic_ids as $topic_id)
1732 if ($global_announce_list && isset($global_announce_list[$topic_id]))
1734 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1738 $last_read[$topic_id] = $user_lastmark;
1748 * Get list of unread topics
1750 * @param int $user_id User ID (or false for current user)
1751 * @param string $sql_extra Extra WHERE SQL statement
1752 * @param string $sql_sort ORDER BY SQL sorting statement
1753 * @param string $sql_limit Limits the size of unread topics list, 0 for unlimited query
1754 * @param string $sql_limit_offset Sets the offset of the first row to search, 0 to search from the start
1756 * @return array[int][int] Topic ids as keys, mark_time of topic as value
1758 function get_unread_topics($user_id = false, $sql_extra = '', $sql_sort = '', $sql_limit = 1001, $sql_limit_offset = 0)
1760 global $config, $db, $user;
1762 $user_id = ($user_id === false) ? (int) $user->data['user_id'] : (int) $user_id;
1764 // Data array we're going to return
1765 $unread_topics = array();
1767 if (empty($sql_sort))
1769 $sql_sort = 'ORDER BY t.topic_last_post_time DESC';
1772 if ($config['load_db_lastread'] && $user->data['is_registered'])
1774 // Get list of the unread topics
1775 $last_mark = (int) $user->data['user_lastmark'];
1778 'SELECT' => 't.topic_id, t.topic_last_post_time, tt.mark_time as topic_mark_time, ft.mark_time as forum_mark_time',
1780 'FROM' => array(TOPICS_TABLE => 't'),
1782 'LEFT_JOIN' => array(
1784 'FROM' => array(TOPICS_TRACK_TABLE => 'tt'),
1785 'ON' => "tt.user_id = $user_id AND t.topic_id = tt.topic_id",
1788 'FROM' => array(FORUMS_TRACK_TABLE => 'ft'),
1789 'ON' => "ft.user_id = $user_id AND t.forum_id = ft.forum_id",
1794 t.topic_last_post_time > $last_mark AND
1796 (tt.mark_time IS NOT NULL AND t.topic_last_post_time > tt.mark_time) OR
1797 (tt.mark_time IS NULL AND ft.mark_time IS NOT NULL AND t.topic_last_post_time > ft.mark_time) OR
1798 (tt.mark_time IS NULL AND ft.mark_time IS NULL)
1804 $sql = $db->sql_build_query('SELECT', $sql_array);
1805 $result = $db->sql_query_limit($sql, $sql_limit, $sql_limit_offset);
1807 while ($row = $db->sql_fetchrow($result))
1809 $topic_id = (int) $row['topic_id'];
1810 $unread_topics[$topic_id] = ($row['topic_mark_time']) ? (int) $row['topic_mark_time'] : (($row['forum_mark_time']) ? (int) $row['forum_mark_time'] : $last_mark);
1812 $db->sql_freeresult($result);
1814 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1816 global $tracking_topics;
1818 if (empty($tracking_topics))
1820 $tracking_topics = request_var($config['cookie_name'] . '_track', '', false, true);
1821 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1824 if (!$user->data['is_registered'])
1826 $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
1830 $user_lastmark = (int) $user->data['user_lastmark'];
1833 $sql = 'SELECT t.topic_id, t.forum_id, t.topic_last_post_time
1834 FROM ' . TOPICS_TABLE . ' t
1835 WHERE t.topic_last_post_time > ' . $user_lastmark . "
1838 $result = $db->sql_query_limit($sql, $sql_limit, $sql_limit_offset);
1840 while ($row = $db->sql_fetchrow($result))
1842 $forum_id = (int) $row['forum_id'];
1843 $topic_id = (int) $row['topic_id'];
1844 $topic_id36 = base_convert($topic_id, 10, 36);
1846 if (isset($tracking_topics['t'][$topic_id36]))
1848 $last_read = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
1850 if ($row['topic_last_post_time'] > $last_read)
1852 $unread_topics[$topic_id] = $last_read;
1855 else if (isset($tracking_topics['f'][$forum_id]))
1857 $mark_time = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
1859 if ($row['topic_last_post_time'] > $mark_time)
1861 $unread_topics[$topic_id] = $mark_time;
1866 $unread_topics[$topic_id] = $user_lastmark;
1869 $db->sql_freeresult($result);
1872 return $unread_topics;
1876 * Check for read forums and update topic tracking info accordingly
1878 * @param int $forum_id the forum id to check
1879 * @param int $forum_last_post_time the forums last post time
1880 * @param int $f_mark_time the forums last mark time if user is registered and load_db_lastread enabled
1881 * @param int $mark_time_forum false if the mark time needs to be obtained, else the last users forum mark time
1883 * @return true if complete forum got marked read, else false.
1885 function update_forum_tracking_info($forum_id, $forum_last_post_time, $f_mark_time = false, $mark_time_forum = false)
1887 global $db, $tracking_topics, $user, $config, $auth;
1889 // Determine the users last forum mark time if not given.
1890 if ($mark_time_forum === false)
1892 if ($config['load_db_lastread'] && $user->data['is_registered'])
1894 $mark_time_forum = (!empty($f_mark_time)) ? $f_mark_time : $user->data['user_lastmark'];
1896 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1898 $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1899 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1901 if (!$user->data['is_registered'])
1903 $user->data['user_lastmark'] = (isset($tracking_topics['l'])) ? (int) (base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate']) : 0;
1906 $mark_time_forum = (isset($tracking_topics['f'][$forum_id])) ? (int) (base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate']) : $user->data['user_lastmark'];
1910 // Handle update of unapproved topics info.
1911 // Only update for moderators having m_approve permission for the forum.
1912 $sql_update_unapproved = ($auth->acl_get('m_approve', $forum_id)) ? '': 'AND t.topic_approved = 1';
1914 // Check the forum for any left unread topics.
1915 // If there are none, we mark the forum as read.
1916 if ($config['load_db_lastread'] && $user->data['is_registered'])
1918 if ($mark_time_forum >= $forum_last_post_time)
1920 // We do not need to mark read, this happened before. Therefore setting this to true
1925 $sql = 'SELECT t.forum_id FROM ' . TOPICS_TABLE . ' t
1926 LEFT JOIN ' . TOPICS_TRACK_TABLE . ' tt ON (tt.topic_id = t.topic_id AND tt.user_id = ' . $user->data['user_id'] . ')
1927 WHERE t.forum_id = ' . $forum_id . '
1928 AND t.topic_last_post_time > ' . $mark_time_forum . '
1929 AND t.topic_moved_id = 0 ' .
1930 $sql_update_unapproved . '
1931 AND (tt.topic_id IS NULL OR tt.mark_time < t.topic_last_post_time)
1932 GROUP BY t.forum_id';
1933 $result = $db->sql_query_limit($sql, 1);
1934 $row = $db->sql_fetchrow($result);
1935 $db->sql_freeresult($result);
1938 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1940 // Get information from cookie
1943 if (!isset($tracking_topics['tf'][$forum_id]))
1945 // We do not need to mark read, this happened before. Therefore setting this to true
1950 $sql = 'SELECT t.topic_id
1951 FROM ' . TOPICS_TABLE . ' t
1952 WHERE t.forum_id = ' . $forum_id . '
1953 AND t.topic_last_post_time > ' . $mark_time_forum . '
1954 AND t.topic_moved_id = 0 ' .
1955 $sql_update_unapproved;
1956 $result = $db->sql_query($sql);
1958 $check_forum = $tracking_topics['tf'][$forum_id];
1961 while ($row = $db->sql_fetchrow($result))
1963 if (!isset($check_forum[base_convert($row['topic_id'], 10, 36)]))
1969 $db->sql_freeresult($result);
1981 markread('topics', $forum_id);
1989 * Transform an array into a serialized format
1991 function tracking_serialize($input)
1994 foreach ($input as $key => $value)
1996 if (is_array($value))
1998 $out .= $key . ':(' . tracking_serialize($value) . ');';
2002 $out .= $key . ':' . $value . ';';
2009 * Transform a serialized array into an actual array
2011 function tracking_unserialize($string, $max_depth = 3)
2013 $n = strlen($string);
2016 die('Invalid data supplied');
2018 $data = $stack = array();
2022 for ($i = 0; $i < $n; ++$i)
2027 switch ($string[$i])
2035 $level = array_pop($stack);
2039 $key .= $string[$i];
2044 switch ($string[$i])
2047 if (sizeof($stack) >= $max_depth)
2049 die('Invalid data supplied');
2052 $level[$key] = array();
2053 $level = &$level[$key];
2058 $level[$key] = $string[$i];
2065 switch ($string[$i])
2069 $level = array_pop($stack);
2077 $level[$key] .= $string[$i];
2083 switch ($string[$i])
2087 $level = array_pop($stack);
2094 die('Invalid data supplied');
2101 if (sizeof($stack) != 0 || ($mode != 0 && $mode != 3))
2103 die('Invalid data supplied');
2109 // Pagination functions
2112 * Pagination routine, generates page number sequence
2113 * tpl_prefix is for using different pagination blocks at one page
2115 function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = false, $tpl_prefix = '')
2117 global $template, $user;
2119 // Make sure $per_page is a valid value
2120 $per_page = ($per_page <= 0) ? 1 : $per_page;
2122 $seperator = '<span class="page-sep">' . $user->lang['COMMA_SEPARATOR'] . '</span>';
2123 $total_pages = ceil($num_items / $per_page);
2125 if ($total_pages == 1 || !$num_items)
2130 $on_page = floor($start_item / $per_page) + 1;
2131 $url_delim = (strpos($base_url, '?') === false) ? '?' : ((strpos($base_url, '?') === strlen($base_url) - 1) ? '' : '&');
2133 $page_string = ($on_page == 1) ? '<strong>1</strong>' : '<a href="' . $base_url . '">1</a>';
2135 if ($total_pages > 5)
2137 $start_cnt = min(max(1, $on_page - 4), $total_pages - 5);
2138 $end_cnt = max(min($total_pages, $on_page + 4), 6);
2140 $page_string .= ($start_cnt > 1) ? '<span class="page-dots"> ... </span>' : $seperator;
2142 for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
2144 $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
2145 if ($i < $end_cnt - 1)
2147 $page_string .= $seperator;
2151 $page_string .= ($end_cnt < $total_pages) ? '<span class="page-dots"> ... </span>' : $seperator;
2155 $page_string .= $seperator;
2157 for ($i = 2; $i < $total_pages; $i++)
2159 $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
2160 if ($i < $total_pages)
2162 $page_string .= $seperator;
2167 $page_string .= ($on_page == $total_pages) ? '<strong>' . $total_pages . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($total_pages - 1) * $per_page) . '">' . $total_pages . '</a>';
2169 if ($add_prevnext_text)
2173 $page_string = '<a href="' . $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page) . '">' . $user->lang['PREVIOUS'] . '</a> ' . $page_string;
2176 if ($on_page != $total_pages)
2178 $page_string .= ' <a href="' . $base_url . "{$url_delim}start=" . ($on_page * $per_page) . '">' . $user->lang['NEXT'] . '</a>';
2182 $template->assign_vars(array(
2183 $tpl_prefix . 'BASE_URL' => $base_url,
2184 'A_' . $tpl_prefix . 'BASE_URL' => addslashes($base_url),
2185 $tpl_prefix . 'PER_PAGE' => $per_page,
2187 $tpl_prefix . 'PREVIOUS_PAGE' => ($on_page == 1) ? '' : $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page),
2188 $tpl_prefix . 'NEXT_PAGE' => ($on_page == $total_pages) ? '' : $base_url . "{$url_delim}start=" . ($on_page * $per_page),
2189 $tpl_prefix . 'TOTAL_PAGES' => $total_pages,
2192 return $page_string;
2196 * Return current page (pagination)
2198 function on_page($num_items, $per_page, $start)
2200 global $template, $user;
2202 // Make sure $per_page is a valid value
2203 $per_page = ($per_page <= 0) ? 1 : $per_page;
2205 $on_page = floor($start / $per_page) + 1;
2207 $template->assign_vars(array(
2208 'ON_PAGE' => $on_page)
2211 return sprintf($user->lang['PAGE_OF'], $on_page, max(ceil($num_items / $per_page), 1));
2214 // Server functions (building urls, redirecting...)
2217 * Append session id to url.
2218 * This function supports hooks.
2220 * @param string $url The url the session id needs to be appended to (can have params)
2221 * @param mixed $params String or array of additional url parameters
2222 * @param bool $is_amp Is url using & (true) or & (false)
2223 * @param string $session_id Possibility to use a custom session id instead of the global one
2227 * append_sid("{$phpbb_root_path}viewtopic.$phpEx?t=1&f=2");
2228 * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2');
2229 * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2', false);
2230 * append_sid("{$phpbb_root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
2234 function append_sid($url, $params = false, $is_amp = true, $session_id = false)
2236 global $_SID, $_EXTRA_URL, $phpbb_hook;
2238 if ($params === '' || (is_array($params) && empty($params)))
2240 // Do not append the ? if the param-list is empty anyway.
2244 // Developers using the hook function need to globalise the $_SID and $_EXTRA_URL on their own and also handle it appropriately.
2245 // They could mimic most of what is within this function
2246 if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__, $url, $params, $is_amp, $session_id))
2248 if ($phpbb_hook->hook_return(__FUNCTION__))
2250 return $phpbb_hook->hook_return_result(__FUNCTION__);
2254 $params_is_array = is_array($params);
2258 if (strpos($url, '#') !== false)
2260 list($url, $anchor) = explode('#', $url, 2);
2261 $anchor = '#' . $anchor;
2263 else if (!$params_is_array && strpos($params, '#') !== false)
2265 list($params, $anchor) = explode('#', $params, 2);
2266 $anchor = '#' . $anchor;
2269 // Handle really simple cases quickly
2270 if ($_SID == '' && $session_id === false && empty($_EXTRA_URL) && !$params_is_array && !$anchor)
2272 if ($params === false)
2277 $url_delim = (strpos($url, '?') === false) ? '?' : (($is_amp) ? '&' : '&');
2278 return $url . ($params !== false ? $url_delim. $params : '');
2281 // Assign sid if session id is not specified
2282 if ($session_id === false)
2284 $session_id = $_SID;
2287 $amp_delim = ($is_amp) ? '&' : '&';
2288 $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
2290 // Appending custom url parameter?
2291 $append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';
2293 // Use the short variant if possible ;)
2294 if ($params === false)
2296 // Append session id
2299 return $url . (($append_url) ? $url_delim . $append_url : '') . $anchor;
2303 return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id . $anchor;
2307 // Build string if parameters are specified as array
2308 if (is_array($params))
2312 foreach ($params as $key => $item)
2321 $anchor = '#' . $item;
2325 $output[] = $key . '=' . $item;
2328 $params = implode($amp_delim, $output);
2331 // Append session id and parameters (even if they are empty)
2332 // If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
2333 return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
2337 * Generate board url (example: http://www.example.com/phpBB)
2339 * @param bool $without_script_path if set to true the script path gets not appended (example: http://www.example.com)
2341 * @return string the generated board url
2343 function generate_board_url($without_script_path = false)
2345 global $config, $user;
2347 $server_name = $user->host;
2348 $server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
2350 // Forcing server vars is the only way to specify/override the protocol
2351 if ($config['force_server_vars'] || !$server_name)
2353 $server_protocol = ($config['server_protocol']) ? $config['server_protocol'] : (($config['cookie_secure']) ? 'https://' : 'http://');
2354 $server_name = $config['server_name'];
2355 $server_port = (int) $config['server_port'];
2356 $script_path = $config['script_path'];
2358 $url = $server_protocol . $server_name;
2359 $cookie_secure = $config['cookie_secure'];
2363 // Do not rely on cookie_secure, users seem to think that it means a secured cookie instead of an encrypted connection
2364 $cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
2365 $url = (($cookie_secure) ? 'https://' : 'http://') . $server_name;
2367 $script_path = $user->page['root_script_path'];
2370 if ($server_port && (($cookie_secure && $server_port <> 443) || (!$cookie_secure && $server_port <> 80)))
2372 // HTTP HOST can carry a port number (we fetch $user->host, but for old versions this may be true)
2373 if (strpos($server_name, ':') === false)
2375 $url .= ':' . $server_port;
2379 if (!$without_script_path)
2381 $url .= $script_path;
2384 // Strip / from the end
2385 if (substr($url, -1, 1) == '/')
2387 $url = substr($url, 0, -1);
2394 * Redirects the user to another page then exits the script nicely
2395 * This function is intended for urls within the board. It's not meant to redirect to cross-domains.
2397 * @param string $url The url to redirect to
2398 * @param bool $return If true, do not redirect but return the sanitized URL. Default is no return.
2399 * @param bool $disable_cd_check If true, redirect() will redirect to an external domain. If false, the redirect point to the boards url if it does not match the current domain. Default is false.
2401 function redirect($url, $return = false, $disable_cd_check = false)
2403 global $db, $cache, $config, $user, $phpbb_root_path;
2405 $failover_flag = false;
2407 if (empty($user->lang))
2409 $user->add_lang('common');
2414 garbage_collection();
2417 // Make sure no &'s are in, this will break the redirect
2418 $url = str_replace('&', '&', $url);
2420 // Determine which type of redirect we need to handle...
2421 $url_parts = @parse_url($url);
2423 if ($url_parts === false)
2425 // Malformed url, redirect to current page...
2426 $url = generate_board_url() . '/' . $user->page['page'];
2428 else if (!empty($url_parts['scheme']) && !empty($url_parts['host']))
2430 // Attention: only able to redirect within the same domain if $disable_cd_check is false (yourdomain.com -> www.yourdomain.com will not work)
2431 if (!$disable_cd_check && $url_parts['host'] !== $user->host)
2433 $url = generate_board_url();
2436 else if ($url[0] == '/')
2438 // Absolute uri, prepend direct url...
2439 $url = generate_board_url(true) . $url;
2444 $pathinfo = pathinfo($url);
2446 if (!$disable_cd_check && !file_exists($pathinfo['dirname'] . '/'))
2448 $url = str_replace('../', '', $url);
2449 $pathinfo = pathinfo($url);
2451 if (!file_exists($pathinfo['dirname'] . '/'))
2453 // fallback to "last known user page"
2454 // at least this way we know the user does not leave the phpBB root
2455 $url = generate_board_url() . '/' . $user->page['page'];
2456 $failover_flag = true;
2460 if (!$failover_flag)
2462 // Is the uri pointing to the current directory?
2463 if ($pathinfo['dirname'] == '.')
2465 $url = str_replace('./', '', $url);
2467 // Strip / from the beginning
2468 if ($url && substr($url, 0, 1) == '/')
2470 $url = substr($url, 1);
2473 if ($user->page['page_dir'])
2475 $url = generate_board_url() . '/' . $user->page['page_dir'] . '/' . $url;
2479 $url = generate_board_url() . '/' . $url;
2484 // Used ./ before, but $phpbb_root_path is working better with urls within another root path
2485 $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($phpbb_root_path)));
2486 $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($pathinfo['dirname'])));
2487 $intersection = array_intersect_assoc($root_dirs, $page_dirs);
2489 $root_dirs = array_diff_assoc($root_dirs, $intersection);
2490 $page_dirs = array_diff_assoc($page_dirs, $intersection);
2492 $dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
2494 // Strip / from the end
2495 if ($dir && substr($dir, -1, 1) == '/')
2497 $dir = substr($dir, 0, -1);
2500 // Strip / from the beginning
2501 if ($dir && substr($dir, 0, 1) == '/')
2503 $dir = substr($dir, 1);
2506 $url = str_replace($pathinfo['dirname'] . '/', '', $url);
2508 // Strip / from the beginning
2509 if (substr($url, 0, 1) == '/')
2511 $url = substr($url, 1);
2514 $url = (!empty($dir) ? $dir . '/' : '') . $url;
2515 $url = generate_board_url() . '/' . $url;
2520 // Make sure no linebreaks are there... to prevent http response splitting for PHP < 4.4.2
2521 if (strpos(urldecode($url), "\n") !== false || strpos(urldecode($url), "\r") !== false || strpos($url, ';') !== false)
2523 trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
2526 // Now, also check the protocol and for a valid url the last time...
2527 $allowed_protocols = array('http', 'https', 'ftp', 'ftps');
2528 $url_parts = parse_url($url);
2530 if ($url_parts === false || empty($url_parts['scheme']) || !in_array($url_parts['scheme'], $allowed_protocols))
2532 trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
2540 // Redirect via an HTML form for PITA webservers
2541 if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
2543 header('Refresh: 0; URL=' . $url);
2545 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2546 echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="' . $user->lang['DIRECTION'] . '" lang="' . $user->lang['USER_LANG'] . '" xml:lang="' . $user->lang['USER_LANG'] . '">';
2548 echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
2549 echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&', $url) . '" />';
2550 echo '<title>' . $user->lang['REDIRECT'] . '</title>';
2553 echo '<div style="text-align: center;">' . sprintf($user->lang['URL_REDIRECT'], '<a href="' . str_replace('&', '&', $url) . '">', '</a>') . '</div>';
2560 // Behave as per HTTP/1.1 spec for others
2561 header('Location: ' . $url);
2566 * Re-Apply session id after page reloads
2568 function reapply_sid($url)
2570 global $phpEx, $phpbb_root_path;
2572 if ($url === "index.$phpEx")
2574 return append_sid("index.$phpEx");
2576 else if ($url === "{$phpbb_root_path}index.$phpEx")
2578 return append_sid("{$phpbb_root_path}index.$phpEx");
2581 // Remove previously added sid
2582 if (strpos($url, 'sid=') !== false)
2584 // All kind of links
2585 $url = preg_replace('/(\?)?(&|&)?sid=[a-z0-9]+/', '', $url);
2586 // if the sid was the first param, make the old second as first ones
2587 $url = preg_replace("/$phpEx(&|&)+?/", "$phpEx?", $url);
2590 return append_sid($url);
2594 * Returns url from the session/current page with an re-appended SID with optionally stripping vars from the url
2596 function build_url($strip_vars = false)
2598 global $user, $phpbb_root_path;
2601 $redirect = append_sid($user->page['page'], false, false);
2603 // Add delimiter if not there...
2604 if (strpos($redirect, '?') === false)
2610 if ($strip_vars !== false && strpos($redirect, '?') !== false)
2612 if (!is_array($strip_vars))
2614 $strip_vars = array($strip_vars);
2617 $query = $_query = array();
2619 $args = substr($redirect, strpos($redirect, '?') + 1);
2620 $args = ($args) ? explode('&', $args) : array();
2621 $redirect = substr($redirect, 0, strpos($redirect, '?'));
2623 foreach ($args as $argument)
2625 $arguments = explode('=', $argument);
2626 $key = $arguments[0];
2627 unset($arguments[0]);
2634 $query[$key] = implode('=', $arguments);
2637 // Strip the vars off
2638 foreach ($strip_vars as $strip)
2640 if (isset($query[$strip]))
2642 unset($query[$strip]);
2646 // Glue the remaining parts together... already urlencoded
2647 foreach ($query as $key => $value)
2649 $_query[] = $key . '=' . $value;
2651 $query = implode('&', $_query);
2653 $redirect .= ($query) ? '?' . $query : '';
2656 // We need to be cautious here.
2657 // On some situations, the redirect path is an absolute URL, sometimes a relative path
2658 // For a relative path, let's prefix it with $phpbb_root_path to point to the correct location,
2659 // else we use the URL directly.
2660 $url_parts = @parse_url($redirect);
2663 if ($url_parts !== false && !empty($url_parts['scheme']) && !empty($url_parts['host']))
2665 return str_replace('&', '&', $redirect);
2668 return $phpbb_root_path . str_replace('&', '&', $redirect);
2672 * Meta refresh assignment
2673 * Adds META template variable with meta http tag.
2675 * @param int $time Time in seconds for meta refresh tag
2676 * @param string $url URL to redirect to. The url will go through redirect() first before the template variable is assigned
2677 * @param bool $disable_cd_check If true, meta_refresh() will redirect to an external domain. If false, the redirect point to the boards url if it does not match the current domain. Default is false.
2679 function meta_refresh($time, $url, $disable_cd_check = false)
2683 $url = redirect($url, true, $disable_cd_check);
2684 $url = str_replace('&', '&', $url);
2686 // For XHTML compatibility we change back & to &
2687 $template->assign_vars(array(
2688 'META' => '<meta http-equiv="refresh" content="' . $time . ';url=' . $url . '" />')
2695 * Outputs correct status line header.
2697 * Depending on php sapi one of the two following forms is used:
2699 * Status: 404 Not Found
2701 * HTTP/1.x 404 Not Found
2703 * HTTP version is taken from HTTP_VERSION environment variable,
2704 * and defaults to 1.0.
2708 * send_status_line(404, 'Not Found');
2710 * @param int $code HTTP status code
2711 * @param string $message Message for the status code
2714 function send_status_line($code, $message)
2716 if (substr(strtolower(@php_sapi_name()), 0, 3) === 'cgi')
2718 // in theory, we shouldn't need that due to php doing it. Reality offers a differing opinion, though
2719 header("Status: $code $message", true, $code);
2723 if (!empty($_SERVER['SERVER_PROTOCOL']))
2725 $version = $_SERVER['SERVER_PROTOCOL'];
2729 $version = 'HTTP/1.0';
2731 header("$version $code $message", true, $code);
2739 * Add a secret hash for use in links/GET requests
2740 * @param string $link_name The name of the link; has to match the name used in check_link_hash, otherwise no restrictions apply
2741 * @return string the hash
2744 function generate_link_hash($link_name)
2748 if (!isset($user->data["hash_$link_name"]))
2750 $user->data["hash_$link_name"] = substr(sha1($user->data['user_form_salt'] . $link_name), 0, 8);
2753 return $user->data["hash_$link_name"];
2758 * checks a link hash - for GET requests
2759 * @param string $token the submitted token
2760 * @param string $link_name The name of the link
2761 * @return boolean true if all is fine
2763 function check_link_hash($token, $link_name)
2765 return $token === generate_link_hash($link_name);
2769 * Add a secret token to the form (requires the S_FORM_TOKEN template variable)
2770 * @param string $form_name The name of the form; has to match the name used in check_form_key, otherwise no restrictions apply
2772 function add_form_key($form_name)
2774 global $config, $template, $user;
2777 $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
2778 $token = sha1($now . $user->data['user_form_salt'] . $form_name . $token_sid);
2780 $s_fields = build_hidden_fields(array(
2781 'creation_time' => $now,
2782 'form_token' => $token,
2785 $template->assign_vars(array(
2786 'S_FORM_TOKEN' => $s_fields,
2791 * Check the form key. Required for all altering actions not secured by confirm_box
2792 * @param string $form_name The name of the form; has to match the name used in add_form_key, otherwise no restrictions apply
2793 * @param int $timespan The maximum acceptable age for a submitted form in seconds. Defaults to the config setting.
2794 * @param string $return_page The address for the return link
2795 * @param bool $trigger If true, the function will triger an error when encountering an invalid form
2797 function check_form_key($form_name, $timespan = false, $return_page = '', $trigger = false)
2799 global $config, $user;
2801 if ($timespan === false)
2803 // we enforce a minimum value of half a minute here.
2804 $timespan = ($config['form_token_lifetime'] == -1) ? -1 : max(30, $config['form_token_lifetime']);
2807 if (isset($_POST['creation_time']) && isset($_POST['form_token']))
2809 $creation_time = abs(request_var('creation_time', 0));
2810 $token = request_var('form_token', '');
2812 $diff = time() - $creation_time;
2814 // If creation_time and the time() now is zero we can assume it was not a human doing this (the check for if ($diff)...
2815 if ($diff && ($diff <= $timespan || $timespan === -1))
2817 $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
2818 $key = sha1($creation_time . $user->data['user_form_salt'] . $form_name . $token_sid);
2820 if ($key === $token)
2829 trigger_error($user->lang['FORM_INVALID'] . $return_page);
2835 // Message/Login boxes
2839 * @param boolean $check True for checking if confirmed (without any additional parameters) and false for displaying the confirm box
2840 * @param string $title Title/Message used for confirm box.
2841 * message text is _CONFIRM appended to title.
2842 * If title cannot be found in user->lang a default one is displayed
2843 * If title_CONFIRM cannot be found in user->lang the text given is used.
2844 * @param string $hidden Hidden variables
2845 * @param string $html_body Template used for confirm box
2846 * @param string $u_action Custom form action
2848 function confirm_box($check, $title = '', $hidden = '', $html_body = 'confirm_body.html', $u_action = '')
2850 global $user, $template, $db;
2851 global $phpEx, $phpbb_root_path;
2853 if (isset($_POST['cancel']))
2859 if (isset($_POST['confirm']))
2861 // language frontier
2862 if ($_POST['confirm'] === $user->lang['YES'])
2868 if ($check && $confirm)
2870 $user_id = request_var('confirm_uid', 0);
2871 $session_id = request_var('sess', '');
2872 $confirm_key = request_var('confirm_key', '');
2874 if ($user_id != $user->data['user_id'] || $session_id != $user->session_id || !$confirm_key || !$user->data['user_last_confirm_key'] || $confirm_key != $user->data['user_last_confirm_key'])
2879 // Reset user_last_confirm_key
2880 $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = ''
2881 WHERE user_id = " . $user->data['user_id'];
2882 $db->sql_query($sql);
2891 $s_hidden_fields = build_hidden_fields(array(
2892 'confirm_uid' => $user->data['user_id'],
2893 'sess' => $user->session_id,
2894 'sid' => $user->session_id,
2897 // generate activation key
2898 $confirm_key = gen_rand_string(10);
2900 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
2902 adm_page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
2906 page_header(((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]), false);
2909 $template->set_filenames(array(
2910 'body' => $html_body)
2913 // If activation key already exist, we better do not re-use the key (something very strange is going on...)
2914 if (request_var('confirm_key', ''))
2916 // This should not occur, therefore we cancel the operation to safe the user
2920 // re-add sid / transform & to & for user->page (user->page is always using &)
2921 $use_page = ($u_action) ? $phpbb_root_path . $u_action : $phpbb_root_path . str_replace('&', '&', $user->page['page']);
2922 $u_action = reapply_sid($use_page);
2923 $u_action .= ((strpos($u_action, '?') === false) ? '?' : '&') . 'confirm_key=' . $confirm_key;
2925 $template->assign_vars(array(
2926 'MESSAGE_TITLE' => (!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title],
2927 'MESSAGE_TEXT' => (!isset($user->lang[$title . '_CONFIRM'])) ? $title : $user->lang[$title . '_CONFIRM'],
2929 'YES_VALUE' => $user->lang['YES'],
2930 'S_CONFIRM_ACTION' => $u_action,
2931 'S_HIDDEN_FIELDS' => $hidden . $s_hidden_fields)
2934 $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = '" . $db->sql_escape($confirm_key) . "'
2935 WHERE user_id = " . $user->data['user_id'];
2936 $db->sql_query($sql);
2938 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
2949 * Generate login box or verify password
2951 function login_box($redirect = '', $l_explain = '', $l_success = '', $admin = false, $s_display = true)
2953 global $db, $user, $template, $auth, $phpEx, $phpbb_root_path, $config;
2955 if (!class_exists('phpbb_captcha_factory'))
2957 include($phpbb_root_path . 'includes/captcha/captcha_factory.' . $phpEx);
2962 // Make sure user->setup() has been called
2963 if (empty($user->lang))
2968 // Print out error if user tries to authenticate as an administrator without having the privileges...
2969 if ($admin && !$auth->acl_get('a_'))
2972 // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
2973 if ($user->data['is_registered'])
2975 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2977 trigger_error('NO_AUTH_ADMIN');
2980 if (isset($_POST['login']))
2985 $credential = request_var('credential', '');
2987 if (strspn($credential, 'abcdef0123456789') !== strlen($credential) || strlen($credential) != 32)
2989 if ($user->data['is_registered'])
2991 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2993 trigger_error('NO_AUTH_ADMIN');
2996 $password = request_var('password_' . $credential, '', true);
3000 $password = request_var('password', '', true);
3003 $username = request_var('username', '', true);
3004 $autologin = (!empty($_POST['autologin'])) ? true : false;
3005 $viewonline = (!empty($_POST['viewonline'])) ? 0 : 1;
3006 $admin = ($admin) ? 1 : 0;
3007 $viewonline = ($admin) ? $user->data['session_viewonline'] : $viewonline;
3009 // Check if the supplied username is equal to the one stored within the database if re-authenticating
3010 if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
3012 // We log the attempt to use a different username...
3013 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
3014 trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
3017 // If authentication is successful we redirect user to previous page
3018 $result = $auth->login($username, $password, $autologin, $viewonline, $admin);
3020 // If admin authentication and login, we will log if it was a success or not...
3021 // We also break the operation on the first non-success login - it could be argued that the user already knows
3024 if ($result['status'] == LOGIN_SUCCESS)
3026 add_log('admin', 'LOG_ADMIN_AUTH_SUCCESS');
3030 // Only log the failed attempt if a real user tried to.
3031 // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
3032 if ($user->data['is_registered'])
3034 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
3039 // The result parameter is always an array, holding the relevant information...
3040 if ($result['status'] == LOGIN_SUCCESS)
3042 $redirect = request_var('redirect', "{$phpbb_root_path}index.$phpEx");
3043 $message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
3044 $l_redirect = ($admin) ? $user->lang['PROCEED_TO_ACP'] : (($redirect === "{$phpbb_root_path}index.$phpEx" || $redirect === "index.$phpEx") ? $user->lang['RETURN_INDEX'] : $user->lang['RETURN_PAGE']);
3046 // append/replace SID (may change during the session for AOL users)
3047 $redirect = reapply_sid($redirect);
3049 // Special case... the user is effectively banned, but we allow founders to login
3050 if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != USER_FOUNDER)
3055 $redirect = meta_refresh(3, $redirect);
3056 trigger_error($message . '<br /><br />' . sprintf($l_redirect, '<a href="' . $redirect . '">', '</a>'));
3059 // Something failed, determine what...
3060 if ($result['status'] == LOGIN_BREAK)
3062 trigger_error($result['error_msg']);
3065 // Special cases... determine
3066 switch ($result['status'])
3068 case LOGIN_ERROR_ATTEMPTS:
3070 $captcha = phpbb_captcha_factory::get_instance($config['captcha_plugin']);
3071 $captcha->init(CONFIRM_LOGIN);
3072 // $captcha->reset();
3074 $template->assign_vars(array(
3075 'CAPTCHA_TEMPLATE' => $captcha->get_template(),
3078 $err = $user->lang[$result['error_msg']];
3081 case LOGIN_ERROR_PASSWORD_CONVERT:
3083 $user->lang[$result['error_msg']],
3084 ($config['email_enable']) ? '<a href="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') . '">' : '',
3085 ($config['email_enable']) ? '</a>' : '',
3086 ($config['board_contact']) ? '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">' : '',
3087 ($config['board_contact']) ? '</a>' : ''
3091 // Username, password, etc...
3093 $err = $user->lang[$result['error_msg']];
3095 // Assign admin contact to some error messages
3096 if ($result['error_msg'] == 'LOGIN_ERROR_USERNAME' || $result['error_msg'] == 'LOGIN_ERROR_PASSWORD')
3098 $err = (!$config['board_contact']) ? sprintf($user->lang[$result['error_msg']], '', '') : sprintf($user->lang[$result['error_msg']], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');
3105 // Assign credential for username/password pair
3106 $credential = ($admin) ? md5(unique_id()) : false;
3108 $s_hidden_fields = array(
3109 'sid' => $user->session_id,
3114 $s_hidden_fields['redirect'] = $redirect;
3119 $s_hidden_fields['credential'] = $credential;
3122 $s_hidden_fields = build_hidden_fields($s_hidden_fields);
3124 $template->assign_vars(array(
3125 'LOGIN_ERROR' => $err,
3126 'LOGIN_EXPLAIN' => $l_explain,
3128 'U_SEND_PASSWORD' => ($config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') : '',
3129 'U_RESEND_ACTIVATION' => ($config['require_activation'] == USER_ACTIVATION_SELF && $config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=resend_act') : '',
3130 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
3131 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
3133 'S_DISPLAY_FULL_LOGIN' => ($s_display) ? true : false,
3134 'S_HIDDEN_FIELDS' => $s_hidden_fields,
3136 'S_ADMIN_AUTH' => $admin,
3137 'USERNAME' => ($admin) ? $user->data['username'] : '',
3139 'USERNAME_CREDENTIAL' => 'username',
3140 'PASSWORD_CREDENTIAL' => ($admin) ? 'password_' . $credential : 'password',
3143 page_header($user->lang['LOGIN'], false);
3145 $template->set_filenames(array(
3146 'body' => 'login_body.html')
3148 make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"));
3154 * Generate forum login box
3156 function login_forum_box($forum_data)
3158 global $db, $config, $user, $template, $phpEx;
3160 $password = request_var('password', '', true);
3162 $sql = 'SELECT forum_id
3163 FROM ' . FORUMS_ACCESS_TABLE . '
3164 WHERE forum_id = ' . $forum_data['forum_id'] . '
3165 AND user_id = ' . $user->data['user_id'] . "
3166 AND session_id = '" . $db->sql_escape($user->session_id) . "'";
3167 $result = $db->sql_query($sql);
3168 $row = $db->sql_fetchrow($result);
3169 $db->sql_freeresult($result);
3178 // Remove expired authorised sessions
3179 $sql = 'SELECT f.session_id
3180 FROM ' . FORUMS_ACCESS_TABLE . ' f
3181 LEFT JOIN ' . SESSIONS_TABLE . ' s ON (f.session_id = s.session_id)
3182 WHERE s.session_id IS NULL';
3183 $result = $db->sql_query($sql);
3185 if ($row = $db->sql_fetchrow($result))
3190 $sql_in[] = (string) $row['session_id'];
3192 while ($row = $db->sql_fetchrow($result));
3194 // Remove expired sessions
3195 $sql = 'DELETE FROM ' . FORUMS_ACCESS_TABLE . '
3196 WHERE ' . $db->sql_in_set('session_id', $sql_in);
3197 $db->sql_query($sql);
3199 $db->sql_freeresult($result);
3201 if (phpbb_check_hash($password, $forum_data['forum_password']))
3204 'forum_id' => (int) $forum_data['forum_id'],
3205 'user_id' => (int) $user->data['user_id'],
3206 'session_id' => (string) $user->session_id,
3209 $db->sql_query('INSERT INTO ' . FORUMS_ACCESS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
3214 $template->assign_var('LOGIN_ERROR', $user->lang['WRONG_PASSWORD']);
3217 page_header($user->lang['LOGIN'], false);
3219 $template->assign_vars(array(
3220 'S_LOGIN_ACTION' => build_url(array('f')),
3221 'S_HIDDEN_FIELDS' => build_hidden_fields(array('f' => $forum_data['forum_id'])))
3224 $template->set_filenames(array(
3225 'body' => 'login_forum.html')
3234 * Little helper for the build_hidden_fields function
3236 function _build_hidden_fields($key, $value, $specialchar, $stripslashes)
3238 $hidden_fields = '';
3240 if (!is_array($value))
3242 $value = ($stripslashes) ? stripslashes($value) : $value;
3243 $value = ($specialchar) ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value;
3245 $hidden_fields .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />' . "\n";
3249 foreach ($value as $_key => $_value)
3251 $_key = ($stripslashes) ? stripslashes($_key) : $_key;
3252 $_key = ($specialchar) ? htmlspecialchars($_key, ENT_COMPAT, 'UTF-8') : $_key;
3254 $hidden_fields .= _build_hidden_fields($key . '[' . $_key . ']', $_value, $specialchar, $stripslashes);
3258 return $hidden_fields;
3262 * Build simple hidden fields from array
3264 * @param array $field_ary an array of values to build the hidden field from
3265 * @param bool $specialchar if true, keys and values get specialchared
3266 * @param bool $stripslashes if true, keys and values get stripslashed
3268 * @return string the hidden fields
3270 function build_hidden_fields($field_ary, $specialchar = false, $stripslashes = false)
3272 $s_hidden_fields = '';
3274 foreach ($field_ary as $name => $vars)
3276 $name = ($stripslashes) ? stripslashes($name) : $name;
3277 $name = ($specialchar) ? htmlspecialchars($name, ENT_COMPAT, 'UTF-8') : $name;
3279 $s_hidden_fields .= _build_hidden_fields($name, $vars, $specialchar, $stripslashes);
3282 return $s_hidden_fields;
3288 function parse_cfg_file($filename, $lines = false)
3290 $parsed_items = array();
3292 if ($lines === false)
3294 $lines = file($filename);
3297 foreach ($lines as $line)
3299 $line = trim($line);
3301 if (!$line || $line[0] == '#' || ($delim_pos = strpos($line, '=')) === false)
3306 // Determine first occurrence, since in values the equal sign is allowed
3307 $key = strtolower(trim(substr($line, 0, $delim_pos)));
3308 $value = trim(substr($line, $delim_pos + 1));
3310 if (in_array($value, array('off', 'false', '0')))
3314 else if (in_array($value, array('on', 'true', '1')))
3318 else if (!trim($value))
3322 else if (($value[0] == "'" && $value[sizeof($value) - 1] == "'") || ($value[0] == '"' && $value[sizeof($value) - 1] == '"'))
3324 $value = substr($value, 1, sizeof($value)-2);
3327 $parsed_items[$key] = $value;
3330 return $parsed_items;
3340 // In phpBB 3.1.x i want to have logging in a class to be able to control it
3341 // For now, we need a quite hakish approach to circumvent logging for some actions
3342 // @todo implement cleanly
3343 if (!empty($GLOBALS['skip_add_log']))
3348 $args = func_get_args();
3350 $mode = array_shift($args);
3351 $reportee_id = ($mode == 'user') ? intval(array_shift($args)) : '';
3352 $forum_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
3353 $topic_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
3354 $action = array_shift($args);
3355 $data = (!sizeof($args)) ? '' : serialize($args);
3358 'user_id' => (empty($user->data)) ? ANONYMOUS : $user->data['user_id'],
3359 'log_ip' => $user->ip,
3360 'log_time' => time(),
3361 'log_operation' => $action,
3362 'log_data' => $data,
3368 $sql_ary['log_type'] = LOG_ADMIN;
3373 'log_type' => LOG_MOD,
3374 'forum_id' => $forum_id,
3375 'topic_id' => $topic_id
3381 'log_type' => LOG_USERS,
3382 'reportee_id' => $reportee_id
3387 $sql_ary['log_type'] = LOG_CRITICAL;
3394 $db->sql_query('INSERT INTO ' . LOG_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
3396 return $db->sql_nextid();
3400 * Return a nicely formatted backtrace.
3402 * Turns the array returned by debug_backtrace() into HTML markup.
3403 * Also filters out absolute paths to phpBB root.
3405 * @return string HTML markup
3407 function get_backtrace()
3409 $output = '<div style="font-family: monospace;">';
3410 $backtrace = debug_backtrace();
3412 // We skip the first one, because it only shows this file/function
3413 unset($backtrace[0]);
3415 foreach ($backtrace as $trace)
3417 // Strip the current directory from path
3418 $trace['file'] = (empty($trace['file'])) ? '(not given by php)' : htmlspecialchars(phpbb_filter_root_path($trace['file']));
3419 $trace['line'] = (empty($trace['line'])) ? '(not given by php)' : $trace['line'];
3421 // Only show function arguments for include etc.
3422 // Other parameters may contain sensible information
3424 if (!empty($trace['args'][0]) && in_array($trace['function'], array('include', 'require', 'include_once', 'require_once')))
3426 $argument = htmlspecialchars(phpbb_filter_root_path($trace['args'][0]));
3429 $trace['class'] = (!isset($trace['class'])) ? '' : $trace['class'];
3430 $trace['type'] = (!isset($trace['type'])) ? '' : $trace['type'];
3432 $output .= '<br />';
3433 $output .= '<b>FILE:</b> ' . $trace['file'] . '<br />';
3434 $output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
3436 $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']);
3437 $output .= '(' . (($argument !== '') ? "'$argument'" : '') . ')<br />';
3439 $output .= '</div>';
3444 * This function returns a regular expression pattern for commonly used expressions
3445 * Use with / as delimiter for email mode and # for url modes
3446 * mode can be: email|bbcode_htm|url|url_inline|www_url|www_url_inline|relative_url|relative_url_inline|ipv4|ipv6
3448 function get_preg_expression($mode)
3453 // Regex written by James Watts and Francisco Jose Martin Moreno
3454 // http://fightingforalostcause.net/misc/2006/compare-email-regex.php
3455 return '([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*(?:[\w\!\#$\%\'\*\+\-\/\=\?\^\`{\|\}\~]|&)+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)';
3460 '#<!\-\- e \-\-><a href="mailto:(.*?)">.*?</a><!\-\- e \-\->#',
3461 '#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
3462 '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
3463 '#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
3464 '#<!\-\- .*? \-\->#s',
3469 // Whoa these look impressive!
3470 // The code to generate the following two regular expressions which match valid IPv4/IPv6 addresses
3471 // can be found in the develop directory
3473 return '#^(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$#';
3477 return '#^(?:(?:(?:[\dA-F]{1,4}:){6}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:::(?:[\dA-F]{1,4}:){0,5}(?:[\dA-F]{1,4}(?::[\dA-F]{1,4})?|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:):(?:[\dA-F]{1,4}:){4}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,2}:(?:[\dA-F]{1,4}:){3}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,3}:(?:[\dA-F]{1,4}:){2}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,4}:(?:[\dA-F]{1,4}:)(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,5}:(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,6}:[\dA-F]{1,4})|(?:(?:[\dA-F]{1,4}:){1,7}:)|(?:::))$#i';
3482 $inline = ($mode == 'url') ? ')' : '';
3483 $scheme = ($mode == 'url') ? '[a-z\d+\-.]' : '[a-z\d+]'; // avoid automatic parsing of "word" in "last word.http://..."
3484 // generated with regex generation file in the develop folder
3485 return "[a-z]$scheme*:/{2}(?:(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})+|[0-9.]+|\[[a-z0-9.]+:[a-z0-9.]+:[a-z0-9.:]+\])(?::\d*)?(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
3489 case 'www_url_inline':
3490 $inline = ($mode == 'www_url') ? ')' : '';
3491 return "www\.(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})+(?::\d*)?(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
3494 case 'relative_url':
3495 case 'relative_url_inline':
3496 $inline = ($mode == 'relative_url') ? ')' : '';
3497 return "(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
3500 case 'table_prefix':
3501 return '#^[a-zA-Z][a-zA-Z0-9_]*$#';
3509 * Generate regexp for naughty words censoring
3510 * Depends on whether installed PHP version supports unicode properties
3512 * @param string $word word template to be replaced
3513 * @param bool $use_unicode whether or not to take advantage of PCRE supporting unicode
3515 * @return string $preg_expr regex to use with word censor
3517 function get_censor_preg_expression($word, $use_unicode = true)
3519 static $unicode_support = null;
3521 // Check whether PHP version supports unicode properties
3522 if (is_null($unicode_support))
3524 $unicode_support = ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false) ? true : false;
3527 // Unescape the asterisk to simplify further conversions
3528 $word = str_replace('\*', '*', preg_quote($word, '#'));
3530 if ($use_unicode && $unicode_support)
3532 // Replace asterisk(s) inside the pattern, at the start and at the end of it with regexes
3533 $word = preg_replace(array('#(?<=[\p{Nd}\p{L}_])\*+(?=[\p{Nd}\p{L}_])#iu', '#^\*+#', '#\*+$#'), array('([\x20]*?|[\p{Nd}\p{L}_-]*?)', '[\p{Nd}\p{L}_-]*?', '[\p{Nd}\p{L}_-]*?'), $word);
3535 // Generate the final substitution
3536 $preg_expr = '#(?<![\p{Nd}\p{L}_-])(' . $word . ')(?![\p{Nd}\p{L}_-])#iu';
3540 // Replace the asterisk inside the pattern, at the start and at the end of it with regexes
3541 $word = preg_replace(array('#(?<=\S)\*+(?=\S)#iu', '#^\*+#', '#\*+$#'), array('(\x20*?\S*?)', '\S*?', '\S*?'), $word);
3543 // Generate the final substitution
3544 $preg_expr = '#(?<!\S)(' . $word . ')(?!\S)#iu';
3551 * Returns the first block of the specified IPv6 address and as many additional
3552 * ones as specified in the length paramater.
3553 * If length is zero, then an empty string is returned.
3554 * If length is greater than 3 the complete IP will be returned
3556 function short_ipv6($ip, $length)
3563 // extend IPv6 addresses
3564 $blocks = substr_count($ip, ':') + 1;
3567 $ip = str_replace('::', ':' . str_repeat('0000:', 9 - $blocks), $ip);
3575 $ip = implode(':', array_slice(explode(':', $ip), 0, 1 + $length));
3582 * Wrapper for php's checkdnsrr function.
3584 * @param string $host Fully-Qualified Domain Name
3585 * @param string $type Resource record type to lookup
3586 * Supported types are: MX (default), A, AAAA, NS, TXT, CNAME
3587 * Other types may work or may not work
3589 * @return mixed true if entry found,
3590 * false if entry not found,
3591 * null if this function is not supported by this environment
3593 * Since null can also be returned, you probably want to compare the result
3594 * with === true or === false,
3598 function phpbb_checkdnsrr($host, $type = 'MX')
3600 // The dot indicates to search the DNS root (helps those having DNS prefixes on the same domain)
3601 if (substr($host, -1) == '.')
3604 $host = substr($host, 0, -1);
3608 $host_fqdn = $host . '.';
3610 // $host has format some.host.example.com
3611 // $host_fqdn has format some.host.example.com.
3613 // If we're looking for an A record we can use gethostbyname()
3614 if ($type == 'A' && function_exists('gethostbyname'))
3616 return (@gethostbyname($host_fqdn) == $host_fqdn) ? false : true;
3619 // checkdnsrr() is available on Windows since PHP 5.3,
3620 // but until 5.3.3 it only works for MX records
3621 // See: http://bugs.php.net/bug.php?id=51844
3623 // Call checkdnsrr() if
3624 // we're looking for an MX record or
3625 // we're not on Windows or
3626 // we're running a PHP version where #51844 has been fixed
3628 // checkdnsrr() supports AAAA since 5.0.0
3629 // checkdnsrr() supports TXT since 5.2.4
3631 ($type == 'MX' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.3', '>=')) &&
3632 ($type != 'AAAA' || version_compare(PHP_VERSION, '5.0.0', '>=')) &&
3633 ($type != 'TXT' || version_compare(PHP_VERSION, '5.2.4', '>=')) &&
3634 function_exists('checkdnsrr')
3637 return checkdnsrr($host_fqdn, $type);
3640 // dns_get_record() is available since PHP 5; since PHP 5.3 also on Windows,
3641 // but on Windows it does not work reliable for AAAA records before PHP 5.3.1
3643 // Call dns_get_record() if
3644 // we're not looking for an AAAA record or
3645 // we're not on Windows or
3646 // we're running a PHP version where AAAA lookups work reliable
3648 ($type != 'AAAA' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.1', '>=')) &&
3649 function_exists('dns_get_record')
3652 // dns_get_record() expects an integer as second parameter
3653 // We have to convert the string $type to the corresponding integer constant.
3654 $type_constant = 'DNS_' . $type;
3655 $type_param = (defined($type_constant)) ? constant($type_constant) : DNS_ANY;
3657 // dns_get_record() might throw E_WARNING and return false for records that do not exist
3658 $resultset = @dns_get_record($host_fqdn, $type_param);
3660 if (empty($resultset) || !is_array($resultset))
3664 else if ($type_param == DNS_ANY)
3666 // $resultset is a non-empty array
3670 foreach ($resultset as $result)
3673 isset($result['host']) && $result['host'] == $host &&
3674 isset($result['type']) && $result['type'] == $type
3684 // If we're on Windows we can still try to call nslookup via exec() as a last resort
3685 if (DIRECTORY_SEPARATOR == '\\' && function_exists('exec'))
3687 @exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host_fqdn), $output);
3689 // If output is empty, the nslookup failed
3695 foreach ($output as $line)
3697 $line = trim($line);
3704 // Squash tabs and multiple whitespaces to a single whitespace.
3705 $line = preg_replace('/\s+/', ' ', $line);
3710 if (stripos($line, "$host MX") === 0)
3717 if (stripos($line, "$host nameserver") === 0)
3724 if (stripos($line, "$host text") === 0)
3731 if (stripos($line, "$host canonical name") === 0)
3739 // AAAA records returned by nslookup on Windows XP/2003 have this format.
3740 // Later Windows versions use the A record format below for AAAA records.
3741 if (stripos($line, "$host AAAA IPv6 address") === 0)
3748 if (!empty($host_matches))
3751 if (stripos($line, "Address: ") === 0)
3757 $host_matches = false;
3760 else if (stripos($line, "Name: $host") === 0)
3763 $host_matches = true;
3775 // Handler, header and footer
3778 * Error and message handler, call with trigger_error if reqd
3780 function msg_handler($errno, $msg_text, $errfile, $errline)
3782 global $cache, $db, $auth, $template, $config, $user;
3783 global $phpEx, $phpbb_root_path, $msg_title, $msg_long_text;
3785 // Do not display notices if we suppress them via @
3786 if (error_reporting() == 0 && $errno != E_USER_ERROR && $errno != E_USER_WARNING && $errno != E_USER_NOTICE)
3791 // Message handler is stripping text. In case we need it, we are possible to define long text...
3792 if (isset($msg_long_text) && $msg_long_text && !$msg_text)
3794 $msg_text = $msg_long_text;
3797 if (!defined('E_DEPRECATED'))
3799 define('E_DEPRECATED', 8192);
3807 // Check the error reporting level and return if the error level does not match
3808 // If DEBUG is defined the default level is E_ALL
3809 if (($errno & ((defined('DEBUG')) ? E_ALL : error_reporting())) == 0)
3814 if (strpos($errfile, 'cache') === false && strpos($errfile, 'template.') === false)
3816 $errfile = phpbb_filter_root_path($errfile);
3817 $msg_text = phpbb_filter_root_path($msg_text);
3818 $error_name = ($errno === E_WARNING) ? 'PHP Warning' : 'PHP Notice';
3819 echo '<b>[phpBB Debug] ' . $error_name . '</b>: in file <b>' . $errfile . '</b> on line <b>' . $errline . '</b>: <b>' . $msg_text . '</b><br />' . "\n";
3821 // we are writing an image - the user won't see the debug, so let's place it in the log
3822 if (defined('IMAGE_OUTPUT') || defined('IN_CRON'))
3824 add_log('critical', 'LOG_IMAGE_GENERATION_ERROR', $errfile, $errline, $msg_text);
3826 // echo '<br /><br />BACKTRACE<br />' . get_backtrace() . '<br />' . "\n";
3835 if (!empty($user) && !empty($user->lang))
3837 $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
3838 $msg_title = (!isset($msg_title)) ? $user->lang['GENERAL_ERROR'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
3840 $l_return_index = sprintf($user->lang['RETURN_INDEX'], '<a href="' . $phpbb_root_path . '">', '</a>');
3843 if (!empty($config['board_contact']))
3845 $l_notify = '<p>' . sprintf($user->lang['NOTIFY_ADMIN_EMAIL'], $config['board_contact']) . '</p>';
3850 $msg_title = 'General Error';
3851 $l_return_index = '<a href="' . $phpbb_root_path . '">Return to index page</a>';
3854 if (!empty($config['board_contact']))
3856 $l_notify = '<p>Please notify the board administrator or webmaster: <a href="mailto:' . $config['board_contact'] . '">' . $config['board_contact'] . '</a></p>';
3860 if ((defined('DEBUG') || defined('IN_CRON') || defined('IMAGE_OUTPUT')) && isset($db))
3862 // let's avoid loops
3863 $db->sql_return_on_error(true);
3864 add_log('critical', 'LOG_GENERAL_ERROR', $msg_title, $msg_text);
3865 $db->sql_return_on_error(false);
3868 // Do not send 200 OK, but service unavailable on errors
3869 send_status_line(503, 'Service Unavailable');
3871 garbage_collection();
3873 // Try to not call the adm page data...
3875 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
3876 echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
3878 echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
3879 echo '<title>' . $msg_title . '</title>';
3880 echo '<style type="text/css">' . "\n" . '/* <![CDATA[ */' . "\n";
3881 echo '* { margin: 0; padding: 0; } html { font-size: 100%; height: 100%; margin-bottom: 1px; background-color: #E4EDF0; } body { font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif; color: #536482; background: #E4EDF0; font-size: 62.5%; margin: 0; } ';
3882 echo 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
3883 echo '#wrap { padding: 0 20px 15px 20px; min-width: 615px; } #page-header { text-align: right; height: 40px; } #page-footer { clear: both; font-size: 1em; text-align: center; } ';
3884 echo '.panel { margin: 4px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
3885 echo '#errorpage #page-header a { font-weight: bold; line-height: 6em; } #errorpage #content { padding: 10px; } #errorpage #content h1 { line-height: 1.2em; margin-bottom: 0; color: #DF075C; } ';
3886 echo '#errorpage #content div { margin-top: 20px; margin-bottom: 5px; border-bottom: 1px solid #CCCCCC; padding-bottom: 5px; color: #333333; font: bold 1.2em "Lucida Grande", Arial, Helvetica, sans-serif; text-decoration: none; line-height: 120%; text-align: left; } ';
3887 echo "\n" . '/* ]]> */' . "\n";
3890 echo '<body id="errorpage">';
3891 echo '<div id="wrap">';
3892 echo ' <div id="page-header">';
3893 echo ' ' . $l_return_index;
3895 echo ' <div id="acp">';
3896 echo ' <div class="panel">';
3897 echo ' <div id="content">';
3898 echo ' <h1>' . $msg_title . '</h1>';
3900 echo ' <div>' . $msg_text . '</div>';
3907 echo ' <div id="page-footer">';
3908 echo ' Powered by <a href="http://www.phpbb.com/">phpBB</a>® Forum Software © phpBB Group';
3916 // On a fatal error (and E_USER_ERROR *is* fatal) we never want other scripts to continue and force an exit here.
3920 case E_USER_WARNING:
3923 define('IN_ERROR_HANDLER', true);
3925 if (empty($user->data))
3927 $user->session_begin();
3930 // We re-init the auth array to get correct results on login/logout
3931 $auth->acl($user->data);
3933 if (empty($user->lang))
3938 if ($msg_text == 'ERROR_NO_ATTACHMENT' || $msg_text == 'NO_FORUM' || $msg_text == 'NO_TOPIC' || $msg_text == 'NO_USER')
3940 send_status_line(404, 'Not Found');
3943 $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
3944 $msg_title = (!isset($msg_title)) ? $user->lang['INFORMATION'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
3946 if (!defined('HEADER_INC'))
3948 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
3950 adm_page_header($msg_title);
3954 page_header($msg_title, false);
3958 $template->set_filenames(array(
3959 'body' => 'message_body.html')
3962 $template->assign_vars(array(
3963 'MESSAGE_TITLE' => $msg_title,
3964 'MESSAGE_TEXT' => $msg_text,
3965 'S_USER_WARNING' => ($errno == E_USER_WARNING) ? true : false,
3966 'S_USER_NOTICE' => ($errno == E_USER_NOTICE) ? true : false)
3969 // We do not want the cron script to be called on error messages
3970 define('IN_CRON', true);
3972 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
3984 // PHP4 compatibility
3990 // If we notice an error not handled here we pass this back to PHP by returning false
3991 // This may not work for all php versions
3996 * Removes absolute path to phpBB root directory from error messages
3997 * and converts backslashes to forward slashes.
3999 * @param string $errfile Absolute file path
4000 * (e.g. /var/www/phpbb3/phpBB/includes/functions.php)
4001 * Please note that if $errfile is outside of the phpBB root,
4002 * the root path will not be found and can not be filtered.
4003 * @return string Relative file path
4004 * (e.g. /includes/functions.php)
4006 function phpbb_filter_root_path($errfile)
4010 if (empty($root_path))
4012 $root_path = phpbb_realpath(dirname(__FILE__) . '/../');
4015 return str_replace(array($root_path, '\\'), array('[ROOT]', '/'), $errfile);
4019 * Queries the session table to get information about online guests
4020 * @param int $item_id Limits the search to the item with this id
4021 * @param string $item The name of the item which is stored in the session table as session_{$item}_id
4022 * @return int The number of active distinct guest sessions
4024 function obtain_guest_count($item_id = 0, $item = 'forum')
4026 global $db, $config;
4030 $reading_sql = ' AND s.session_' . $item . '_id = ' . (int) $item_id;
4036 $time = (time() - (intval($config['load_online_time']) * 60));
4038 // Get number of online guests
4040 if ($db->sql_layer === 'sqlite')
4042 $sql = 'SELECT COUNT(session_ip) as num_guests
4044 SELECT DISTINCT s.session_ip
4045 FROM ' . SESSIONS_TABLE . ' s
4046 WHERE s.session_user_id = ' . ANONYMOUS . '
4047 AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
4053 $sql = 'SELECT COUNT(DISTINCT s.session_ip) as num_guests
4054 FROM ' . SESSIONS_TABLE . ' s
4055 WHERE s.session_user_id = ' . ANONYMOUS . '
4056 AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
4059 $result = $db->sql_query($sql);
4060 $guests_online = (int) $db->sql_fetchfield('num_guests');
4061 $db->sql_freeresult($result);
4063 return $guests_online;
4067 * Queries the session table to get information about online users
4068 * @param int $item_id Limits the search to the item with this id
4069 * @param string $item The name of the item which is stored in the session table as session_{$item}_id
4070 * @return array An array containing the ids of online, hidden and visible users, as well as statistical info
4072 function obtain_users_online($item_id = 0, $item = 'forum')
4074 global $db, $config, $user;
4079 $reading_sql = ' AND s.session_' . $item . '_id = ' . (int) $item_id;
4082 $online_users = array(
4083 'online_users' => array(),
4084 'hidden_users' => array(),
4085 'total_online' => 0,
4086 'visible_online' => 0,
4087 'hidden_online' => 0,
4088 'guests_online' => 0,
4091 if ($config['load_online_guests'])
4093 $online_users['guests_online'] = obtain_guest_count($item_id, $item);
4096 // a little discrete magic to cache this for 30 seconds
4097 $time = (time() - (intval($config['load_online_time']) * 60));
4099 $sql = 'SELECT s.session_user_id, s.session_ip, s.session_viewonline
4100 FROM ' . SESSIONS_TABLE . ' s
4101 WHERE s.session_time >= ' . ($time - ((int) ($time % 30))) .
4103 ' AND s.session_user_id <> ' . ANONYMOUS;
4104 $result = $db->sql_query($sql);
4106 while ($row = $db->sql_fetchrow($result))
4108 // Skip multiple sessions for one user
4109 if (!isset($online_users['online_users'][$row['session_user_id']]))
4111 $online_users['online_users'][$row['session_user_id']] = (int) $row['session_user_id'];
4112 if ($row['session_viewonline'])
4114 $online_users['visible_online']++;
4118 $online_users['hidden_users'][$row['session_user_id']] = (int) $row['session_user_id'];
4119 $online_users['hidden_online']++;
4123 $online_users['total_online'] = $online_users['guests_online'] + $online_users['visible_online'] + $online_users['hidden_online'];
4124 $db->sql_freeresult($result);
4126 return $online_users;
4130 * Uses the result of obtain_users_online to generate a localized, readable representation.
4131 * @param mixed $online_users result of obtain_users_online - array with user_id lists for total, hidden and visible users, and statistics
4132 * @param int $item_id Indicate that the data is limited to one item and not global
4133 * @param string $item The name of the item which is stored in the session table as session_{$item}_id
4134 * @return array An array containing the string for output to the template
4136 function obtain_users_online_string($online_users, $item_id = 0, $item = 'forum')
4138 global $config, $db, $user, $auth;
4140 $user_online_link = $online_userlist = '';
4141 // Need caps version of $item for language-strings
4142 $item_caps = strtoupper($item);
4144 if (sizeof($online_users['online_users']))
4146 $sql = 'SELECT username, username_clean, user_id, user_type, user_allow_viewonline, user_colour
4147 FROM ' . USERS_TABLE . '
4148 WHERE ' . $db->sql_in_set('user_id', $online_users['online_users']) . '
4149 ORDER BY username_clean ASC';
4150 $result = $db->sql_query($sql);
4152 while ($row = $db->sql_fetchrow($result))
4154 // User is logged in and therefore not a guest
4155 if ($row['user_id'] != ANONYMOUS)
4157 if (isset($online_users['hidden_users'][$row['user_id']]))
4159 $row['username'] = '<em>' . $row['username'] . '</em>';
4162 if (!isset($online_users['hidden_users'][$row['user_id']]) || $auth->acl_get('u_viewonline'))
4164 $user_online_link = get_username_string(($row['user_type'] <> USER_IGNORE) ? 'full' : 'no_profile', $row['user_id'], $row['username'], $row['user_colour']);
4165 $online_userlist .= ($online_userlist != '') ? ', ' . $user_online_link : $user_online_link;
4169 $db->sql_freeresult($result);
4172 if (!$online_userlist)
4174 $online_userlist = $user->lang['NO_ONLINE_USERS'];
4179 $online_userlist = $user->lang['REGISTERED_USERS'] . ' ' . $online_userlist;
4181 else if ($config['load_online_guests'])
4183 $l_online = ($online_users['guests_online'] === 1) ? $user->lang['BROWSING_' . $item_caps . '_GUEST'] : $user->lang['BROWSING_' . $item_caps . '_GUESTS'];
4184 $online_userlist = sprintf($l_online, $online_userlist, $online_users['guests_online']);
4188 $online_userlist = sprintf($user->lang['BROWSING_' . $item_caps], $online_userlist);
4190 // Build online listing
4191 $vars_online = array(
4192 'ONLINE' => array('total_online', 'l_t_user_s', 0),
4193 'REG' => array('visible_online', 'l_r_user_s', !$config['load_online_guests']),
4194 'HIDDEN' => array('hidden_online', 'l_h_user_s', $config['load_online_guests']),
4195 'GUEST' => array('guests_online', 'l_g_user_s', 0)
4198 foreach ($vars_online as $l_prefix => $var_ary)
4208 switch ($online_users[$var_ary[0]])
4211 ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_ZERO_TOTAL' . $l_suffix];
4215 ${$var_ary[1]} = $user->lang[$l_prefix . '_USER_TOTAL' . $l_suffix];
4219 ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_TOTAL' . $l_suffix];
4223 unset($vars_online);
4225 $l_online_users = sprintf($l_t_user_s, $online_users['total_online']);
4226 $l_online_users .= sprintf($l_r_user_s, $online_users['visible_online']);
4227 $l_online_users .= sprintf($l_h_user_s, $online_users['hidden_online']);
4229 if ($config['load_online_guests'])
4231 $l_online_users .= sprintf($l_g_user_s, $online_users['guests_online']);
4237 'online_userlist' => $online_userlist,
4238 'l_online_users' => $l_online_users,
4243 * Get option bitfield from custom data
4245 * @param int $bit The bit/value to get
4246 * @param int $data Current bitfield to check
4247 * @return bool Returns true if value of constant is set in bitfield, else false
4249 function phpbb_optionget($bit, $data)
4251 return ($data & 1 << (int) $bit) ? true : false;
4255 * Set option bitfield
4257 * @param int $bit The bit/value to set/unset
4258 * @param bool $set True if option should be set, false if option should be unset.
4259 * @param int $data Current bitfield to change
4261 * @return int The new bitfield
4263 function phpbb_optionset($bit, $set, $data)
4265 if ($set && !($data & 1 << $bit))
4269 else if (!$set && ($data & 1 << $bit))
4278 * Login using http authenticate.
4280 * @param array $param Parameter array, see $param_defaults array.
4284 function phpbb_http_login($param)
4286 global $auth, $user;
4289 $param_defaults = array(
4290 'auth_message' => '',
4292 'autologin' => false,
4293 'viewonline' => true,
4297 // Overwrite default values with passed values
4298 $param = array_merge($param_defaults, $param);
4300 // User is already logged in
4301 // We will not overwrite his session
4302 if (!empty($user->data['is_registered']))
4307 // $_SERVER keys to check
4308 $username_keys = array(
4311 'REMOTE_USER', 'REDIRECT_REMOTE_USER',
4312 'HTTP_AUTHORIZATION', 'REDIRECT_HTTP_AUTHORIZATION',
4313 'REMOTE_AUTHORIZATION', 'REDIRECT_REMOTE_AUTHORIZATION',
4317 $password_keys = array(
4324 foreach ($username_keys as $k)
4326 if (isset($_SERVER[$k]))
4328 $username = $_SERVER[$k];
4334 foreach ($password_keys as $k)
4336 if (isset($_SERVER[$k]))
4338 $password = $_SERVER[$k];
4343 // Decode encoded information (IIS, CGI, FastCGI etc.)
4344 if (!is_null($username) && is_null($password) && strpos($username, 'Basic ') === 0)
4346 list($username, $password) = explode(':', base64_decode(substr($username, 6)), 2);
4349 if (!is_null($username) && !is_null($password))
4351 set_var($username, $username, 'string', true);
4352 set_var($password, $password, 'string', true);
4354 $auth_result = $auth->login($username, $password, $param['autologin'], $param['viewonline'], $param['admin']);
4356 if ($auth_result['status'] == LOGIN_SUCCESS)
4360 else if ($auth_result['status'] == LOGIN_ERROR_ATTEMPTS)
4362 send_status_line(401, 'Unauthorized');
4364 trigger_error('NOT_AUTHORISED');
4368 // Prepend sitename to auth_message
4369 $param['auth_message'] = ($param['auth_message'] === '') ? $config['sitename'] : $config['sitename'] . ' - ' . $param['auth_message'];
4371 // We should probably filter out non-ASCII characters - RFC2616
4372 $param['auth_message'] = preg_replace('/[\x80-\xFF]/', '?', $param['auth_message']);
4374 header('WWW-Authenticate: Basic realm="' . $param['auth_message'] . '"');
4375 send_status_line(401, 'Unauthorized');
4377 trigger_error('NOT_AUTHORISED');
4381 * Generate page header
4383 function page_header($page_title = '', $display_online_list = true, $item_id = 0, $item = 'forum')
4385 global $db, $config, $template, $SID, $_SID, $_EXTRA_URL, $user, $auth, $phpEx, $phpbb_root_path;
4387 if (defined('HEADER_INC'))
4392 define('HEADER_INC', true);
4395 if ($config['gzip_compress'])
4397 // to avoid partially compressed output resulting in blank pages in
4398 // the browser or error messages, compression is disabled in a few cases:
4400 // 1) if headers have already been sent, this indicates plaintext output
4401 // has been started so further content must not be compressed
4402 // 2) the length of the current output buffer is non-zero. This means
4403 // there is already some uncompressed content in this output buffer
4404 // so further output must not be compressed
4405 // 3) if more than one level of output buffering is used because we
4406 // cannot test all output buffer level content lengths. One level
4407 // could be caused by php.ini output_buffering. Anything
4408 // beyond that is manual, so the code wrapping phpBB in output buffering
4409 // can easily compress the output itself.
4411 if (@extension_loaded('zlib') && !headers_sent() && ob_get_level() <= 1 && ob_get_length() == 0)
4413 ob_start('ob_gzhandler');
4417 // Generate logged in/logged out status
4418 if ($user->data['user_id'] != ANONYMOUS)
4420 $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=logout', true, $user->session_id);
4421 $l_login_logout = sprintf($user->lang['LOGOUT_USER'], $user->data['username']);
4425 $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login');
4426 $l_login_logout = $user->lang['LOGIN'];
4429 // Last visit date/time
4430 $s_last_visit = ($user->data['user_id'] != ANONYMOUS) ? $user->format_date($user->data['session_last_visit']) : '';
4432 // Get users online list ... if required
4433 $l_online_users = $online_userlist = $l_online_record = $l_online_time = '';
4435 if ($config['load_online'] && $config['load_online_time'] && $display_online_list)
4439 * For obtaining another session column use $item and $item_id in the function-parameter, whereby the column is session_{$item}_id.
4441 $item_id = max($item_id, 0);
4443 $online_users = obtain_users_online($item_id, $item);
4444 $user_online_strings = obtain_users_online_string($online_users, $item_id, $item);
4446 $l_online_users = $user_online_strings['l_online_users'];
4447 $online_userlist = $user_online_strings['online_userlist'];
4448 $total_online_users = $online_users['total_online'];
4450 if ($total_online_users > $config['record_online_users'])
4452 set_config('record_online_users', $total_online_users, true);
4453 set_config('record_online_date', time(), true);
4456 $l_online_record = sprintf($user->lang['RECORD_ONLINE_USERS'], $config['record_online_users'], $user->format_date($config['record_online_date'], false, true));
4458 $l_online_time = ($config['load_online_time'] == 1) ? 'VIEW_ONLINE_TIME' : 'VIEW_ONLINE_TIMES';
4459 $l_online_time = sprintf($user->lang[$l_online_time], $config['load_online_time']);
4462 $l_privmsgs_text = $l_privmsgs_text_unread = '';
4463 $s_privmsg_new = false;
4465 // Obtain number of new private messages if user is logged in
4466 if (!empty($user->data['is_registered']))
4468 if ($user->data['user_new_privmsg'])
4470 $l_message_new = ($user->data['user_new_privmsg'] == 1) ? $user->lang['NEW_PM'] : $user->lang['NEW_PMS'];
4471 $l_privmsgs_text = sprintf($l_message_new, $user->data['user_new_privmsg']);
4473 if (!$user->data['user_last_privmsg'] || $user->data['user_last_privmsg'] > $user->data['session_last_visit'])
4475 $sql = 'UPDATE ' . USERS_TABLE . '
4476 SET user_last_privmsg = ' . $user->data['session_last_visit'] . '
4477 WHERE user_id = ' . $user->data['user_id'];
4478 $db->sql_query($sql);
4480 $s_privmsg_new = true;
4484 $s_privmsg_new = false;
4489 $l_privmsgs_text = $user->lang['NO_NEW_PM'];
4490 $s_privmsg_new = false;
4493 $l_privmsgs_text_unread = '';
4495 if ($user->data['user_unread_privmsg'] && $user->data['user_unread_privmsg'] != $user->data['user_new_privmsg'])
4497 $l_message_unread = ($user->data['user_unread_privmsg'] == 1) ? $user->lang['UNREAD_PM'] : $user->lang['UNREAD_PMS'];
4498 $l_privmsgs_text_unread = sprintf($l_message_unread, $user->data['user_unread_privmsg']);
4502 $forum_id = request_var('f', 0);
4503 $topic_id = request_var('t', 0);
4505 $s_feed_news = false;
4507 // Get option for news
4508 if ($config['feed_enable'])
4510 $sql = 'SELECT forum_id
4511 FROM ' . FORUMS_TABLE . '
4512 WHERE ' . $db->sql_bit_and('forum_options', FORUM_OPTION_FEED_NEWS, '<> 0');
4513 $result = $db->sql_query_limit($sql, 1, 0, 600);
4514 $s_feed_news = (int) $db->sql_fetchfield('forum_id');
4515 $db->sql_freeresult($result);
4518 // Determine board url - we may need it later
4519 $board_url = generate_board_url() . '/';
4520 $web_path = (defined('PHPBB_USE_BOARD_URL_PATH') && PHPBB_USE_BOARD_URL_PATH) ? $board_url : $phpbb_root_path;
4523 $tz = ($user->data['user_id'] != ANONYMOUS) ? strval(doubleval($user->data['user_timezone'])) : strval(doubleval($config['board_timezone']));
4525 // Send a proper content-language to the output
4526 $user_lang = $user->lang['USER_LANG'];
4527 if (strpos($user_lang, '-x-') !== false)
4529 $user_lang = substr($user_lang, 0, strpos($user_lang, '-x-'));
4532 $s_search_hidden_fields = array();
4535 $s_search_hidden_fields['sid'] = $_SID;
4538 if (!empty($_EXTRA_URL))
4540 foreach ($_EXTRA_URL as $url_param)
4542 $url_param = explode('=', $url_param, 2);
4543 $s_hidden_fields[$url_param[0]] = $url_param[1];
4547 // The following assigns all _common_ variables that may be used at any point in a template.
4548 $template->assign_vars(array(
4549 'SITENAME' => $config['sitename'],
4550 'SITE_DESCRIPTION' => $config['site_desc'],
4551 'PAGE_TITLE' => $page_title,
4552 'SCRIPT_NAME' => str_replace('.' . $phpEx, '', $user->page['page_name']),
4553 'LAST_VISIT_DATE' => sprintf($user->lang['YOU_LAST_VISIT'], $s_last_visit),
4554 'LAST_VISIT_YOU' => $s_last_visit,
4555 'CURRENT_TIME' => sprintf($user->lang['CURRENT_TIME'], $user->format_date(time(), false, true)),
4556 'TOTAL_USERS_ONLINE' => $l_online_users,
4557 'LOGGED_IN_USER_LIST' => $online_userlist,
4558 'RECORD_USERS' => $l_online_record,
4559 'PRIVATE_MESSAGE_INFO' => $l_privmsgs_text,
4560 'PRIVATE_MESSAGE_INFO_UNREAD' => $l_privmsgs_text_unread,
4562 'S_USER_NEW_PRIVMSG' => $user->data['user_new_privmsg'],
4563 'S_USER_UNREAD_PRIVMSG' => $user->data['user_unread_privmsg'],
4564 'S_USER_NEW' => $user->data['user_new'],
4568 'SESSION_ID' => $user->session_id,
4569 'ROOT_PATH' => $phpbb_root_path,
4570 'BOARD_URL' => $board_url,
4572 'L_LOGIN_LOGOUT' => $l_login_logout,
4573 'L_INDEX' => $user->lang['FORUM_INDEX'],
4574 'L_ONLINE_EXPLAIN' => $l_online_time,
4576 'U_PRIVATEMSGS' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&folder=inbox'),
4577 'U_RETURN_INBOX' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&folder=inbox'),
4578 'U_POPUP_PM' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&mode=popup'),
4579 'UA_POPUP_PM' => addslashes(append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&mode=popup')),
4580 'U_MEMBERLIST' => append_sid("{$phpbb_root_path}memberlist.$phpEx"),
4581 'U_VIEWONLINE' => ($auth->acl_gets('u_viewprofile', 'a_user', 'a_useradd', 'a_userdel')) ? append_sid("{$phpbb_root_path}viewonline.$phpEx") : '',
4582 'U_LOGIN_LOGOUT' => $u_login_logout,
4583 'U_INDEX' => append_sid("{$phpbb_root_path}index.$phpEx"),
4584 'U_SEARCH' => append_sid("{$phpbb_root_path}search.$phpEx"),
4585 'U_REGISTER' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register'),
4586 'U_PROFILE' => append_sid("{$phpbb_root_path}ucp.$phpEx"),
4587 'U_MODCP' => append_sid("{$phpbb_root_path}mcp.$phpEx", false, true, $user->session_id),
4588 'U_FAQ' => append_sid("{$phpbb_root_path}faq.$phpEx"),
4589 'U_SEARCH_SELF' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=egosearch'),
4590 'U_SEARCH_NEW' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=newposts'),
4591 'U_SEARCH_UNANSWERED' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unanswered'),
4592 'U_SEARCH_UNREAD' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unreadposts'),
4593 'U_SEARCH_ACTIVE_TOPICS'=> append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=active_topics'),
4594 'U_DELETE_COOKIES' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=delete_cookies'),
4595 'U_TEAM' => ($user->data['user_id'] != ANONYMOUS && !$auth->acl_get('u_viewprofile')) ? '' : append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=leaders'),
4596 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
4597 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
4598 'U_RESTORE_PERMISSIONS' => ($user->data['user_perm_from'] && $auth->acl_get('a_switchperm')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=restore_perm') : '',
4599 'U_FEED' => generate_board_url() . "/feed.$phpEx",
4601 'S_USER_LOGGED_IN' => ($user->data['user_id'] != ANONYMOUS) ? true : false,
4602 'S_AUTOLOGIN_ENABLED' => ($config['allow_autologin']) ? true : false,
4603 'S_BOARD_DISABLED' => ($config['board_disable']) ? true : false,
4604 'S_REGISTERED_USER' => (!empty($user->data['is_registered'])) ? true : false,
4605 'S_IS_BOT' => (!empty($user->data['is_bot'])) ? true : false,
4606 'S_USER_PM_POPUP' => $user->optionget('popuppm'),
4607 'S_USER_LANG' => $user_lang,
4608 'S_USER_BROWSER' => (isset($user->data['session_browser'])) ? $user->data['session_browser'] : $user->lang['UNKNOWN_BROWSER'],
4609 'S_USERNAME' => $user->data['username'],
4610 'S_CONTENT_DIRECTION' => $user->lang['DIRECTION'],
4611 'S_CONTENT_FLOW_BEGIN' => ($user->lang['DIRECTION'] == 'ltr') ? 'left' : 'right',
4612 'S_CONTENT_FLOW_END' => ($user->lang['DIRECTION'] == 'ltr') ? 'right' : 'left',
4613 'S_CONTENT_ENCODING' => 'UTF-8',
4614 'S_TIMEZONE' => ($user->data['user_dst'] || ($user->data['user_id'] == ANONYMOUS && $config['board_dst'])) ? sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], $user->lang['tz']['dst']) : sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], ''),
4615 'S_DISPLAY_ONLINE_LIST' => ($l_online_time) ? 1 : 0,
4616 'S_DISPLAY_SEARCH' => (!$config['load_search']) ? 0 : (isset($auth) ? ($auth->acl_get('u_search') && $auth->acl_getf_global('f_search')) : 1),
4617 'S_DISPLAY_PM' => ($config['allow_privmsg'] && !empty($user->data['is_registered']) && ($auth->acl_get('u_readpm') || $auth->acl_get('u_sendpm'))) ? true : false,
4618 'S_DISPLAY_MEMBERLIST' => (isset($auth)) ? $auth->acl_get('u_viewprofile') : 0,
4619 'S_NEW_PM' => ($s_privmsg_new) ? 1 : 0,
4620 'S_REGISTER_ENABLED' => ($config['require_activation'] != USER_ACTIVATION_DISABLE) ? true : false,
4621 'S_FORUM_ID' => $forum_id,
4622 'S_TOPIC_ID' => $topic_id,
4624 'S_LOGIN_ACTION' => ((!defined('ADMIN_START')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login') : append_sid("index.$phpEx", false, true, $user->session_id)),
4625 'S_LOGIN_REDIRECT' => build_hidden_fields(array('redirect' => build_url())),
4627 'S_ENABLE_FEEDS' => ($config['feed_enable']) ? true : false,
4628 'S_ENABLE_FEEDS_OVERALL' => ($config['feed_overall']) ? true : false,
4629 'S_ENABLE_FEEDS_FORUMS' => ($config['feed_overall_forums']) ? true : false,
4630 'S_ENABLE_FEEDS_TOPICS' => ($config['feed_topics_new']) ? true : false,
4631 'S_ENABLE_FEEDS_TOPICS_ACTIVE' => ($config['feed_topics_active']) ? true : false,
4632 'S_ENABLE_FEEDS_NEWS' => ($s_feed_news) ? true : false,
4634 'S_LOAD_UNREADS' => ($config['load_unreads_search'] && ($config['load_anon_lastread'] || $user->data['is_registered'])) ? true : false,
4636 'S_SEARCH_HIDDEN_FIELDS' => build_hidden_fields($s_search_hidden_fields),
4638 'T_THEME_PATH' => "{$web_path}styles/" . $user->theme['theme_path'] . '/theme',
4639 'T_TEMPLATE_PATH' => "{$web_path}styles/" . $user->theme['template_path'] . '/template',
4640 'T_SUPER_TEMPLATE_PATH' => (isset($user->theme['template_inherit_path']) && $user->theme['template_inherit_path']) ? "{$web_path}styles/" . $user->theme['template_inherit_path'] . '/template' : "{$web_path}styles/" . $user->theme['template_path'] . '/template',
4641 'T_IMAGESET_PATH' => "{$web_path}styles/" . $user->theme['imageset_path'] . '/imageset',
4642 'T_IMAGESET_LANG_PATH' => "{$web_path}styles/" . $user->theme['imageset_path'] . '/imageset/' . $user->lang_name,
4643 'T_IMAGES_PATH' => "{$web_path}images/",
4644 'T_SMILIES_PATH' => "{$web_path}{$config['smilies_path']}/",
4645 'T_AVATAR_PATH' => "{$web_path}{$config['avatar_path']}/",
4646 'T_AVATAR_GALLERY_PATH' => "{$web_path}{$config['avatar_gallery_path']}/",
4647 'T_ICONS_PATH' => "{$web_path}{$config['icons_path']}/",
4648 'T_RANKS_PATH' => "{$web_path}{$config['ranks_path']}/",
4649 'T_UPLOAD_PATH' => "{$web_path}{$config['upload_path']}/",
4650 'T_STYLESHEET_LINK' => (!$user->theme['theme_storedb']) ? "{$web_path}styles/" . $user->theme['theme_path'] . '/theme/stylesheet.css' : append_sid("{$phpbb_root_path}style.$phpEx", 'id=' . $user->theme['style_id'] . '&lang=' . $user->lang_name),
4651 'T_STYLESHEET_NAME' => $user->theme['theme_name'],
4653 'T_THEME_NAME' => $user->theme['theme_path'],
4654 'T_TEMPLATE_NAME' => $user->theme['template_path'],
4655 'T_SUPER_TEMPLATE_NAME' => (isset($user->theme['template_inherit_path']) && $user->theme['template_inherit_path']) ? $user->theme['template_inherit_path'] : $user->theme['template_path'],
4656 'T_IMAGESET_NAME' => $user->theme['imageset_path'],
4657 'T_IMAGESET_LANG_NAME' => $user->data['user_lang'],
4658 'T_IMAGES' => 'images',
4659 'T_SMILIES' => $config['smilies_path'],
4660 'T_AVATAR' => $config['avatar_path'],
4661 'T_AVATAR_GALLERY' => $config['avatar_gallery_path'],
4662 'T_ICONS' => $config['icons_path'],
4663 'T_RANKS' => $config['ranks_path'],
4664 'T_UPLOAD' => $config['upload_path'],
4666 'SITE_LOGO_IMG' => $user->img('site_logo'),
4668 'A_COOKIE_SETTINGS' => addslashes('; path=' . $config['cookie_path'] . ((!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . $config['cookie_domain']) . ((!$config['cookie_secure']) ? '' : '; secure')),
4671 // application/xhtml+xml not used because of IE
4672 header('Content-type: text/html; charset=UTF-8');
4674 header('Cache-Control: private, no-cache="set-cookie"');
4675 header('Expires: 0');
4676 header('Pragma: no-cache');
4678 if (!empty($user->data['is_bot']))
4680 // Let reverse proxies know we detected a bot.
4681 header('X-PHPBB-IS-BOT: yes');
4688 * Generate page footer
4690 function page_footer($run_cron = true)
4692 global $db, $config, $template, $user, $auth, $cache, $starttime, $phpbb_root_path, $phpEx;
4694 // Output page creation time
4695 if (defined('DEBUG'))
4697 $mtime = explode(' ', microtime());
4698 $totaltime = $mtime[0] + $mtime[1] - $starttime;
4700 if (!empty($_REQUEST['explain']) && $auth->acl_get('a_') && defined('DEBUG_EXTRA') && method_exists($db, 'sql_report'))
4702 $db->sql_report('display');
4705 $debug_output = sprintf('Time : %.3fs | ' . $db->sql_num_queries() . ' Queries | GZIP : ' . (($config['gzip_compress'] && @extension_loaded('zlib')) ? 'On' : 'Off') . (($user->load) ? ' | Load : ' . $user->load : ''), $totaltime);
4707 if ($auth->acl_get('a_') && defined('DEBUG_EXTRA'))
4709 if (function_exists('memory_get_usage'))
4711 if ($memory_usage = memory_get_usage())
4713 global $base_memory_usage;
4714 $memory_usage -= $base_memory_usage;
4715 $memory_usage = get_formatted_filesize($memory_usage);
4717 $debug_output .= ' | Memory Usage: ' . $memory_usage;
4721 $debug_output .= ' | <a href="' . build_url() . '&explain=1">Explain</a>';
4725 $template->assign_vars(array(
4726 'DEBUG_OUTPUT' => (defined('DEBUG')) ? $debug_output : '',
4727 'TRANSLATION_INFO' => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
4729 'U_ACP' => ($auth->acl_get('a_') && !empty($user->data['is_registered'])) ? append_sid("{$phpbb_root_path}adm/index.$phpEx", false, true, $user->session_id) : '')
4732 // Call cron-type script
4734 if (!defined('IN_CRON') && $run_cron && !$config['board_disable'] && !$user->data['is_bot'])
4737 $time_now = (!empty($user->time_now) && is_int($user->time_now)) ? $user->time_now : time();
4739 // Any old lock present?
4740 if (!empty($config['cron_lock']))
4742 $cron_time = explode(' ', $config['cron_lock']);
4744 // If 1 hour lock is present we do not call cron.php
4745 if ($cron_time[0] + 3600 >= $time_now)
4757 if ($time_now - $config['queue_interval'] > $config['last_queue_run'] && !defined('IN_ADMIN') && file_exists($phpbb_root_path . 'cache/queue.' . $phpEx))
4759 // Process email queue
4760 $cron_type = 'queue';
4762 else if (method_exists($cache, 'tidy') && $time_now - $config['cache_gc'] > $config['cache_last_gc'])
4765 $cron_type = 'tidy_cache';
4767 else if ($config['warnings_expire_days'] && ($time_now - $config['warnings_gc'] > $config['warnings_last_gc']))
4769 $cron_type = 'tidy_warnings';
4771 else if ($time_now - $config['database_gc'] > $config['database_last_gc'])
4773 // Tidy the database
4774 $cron_type = 'tidy_database';
4776 else if ($time_now - $config['search_gc'] > $config['search_last_gc'])
4779 $cron_type = 'tidy_search';
4781 else if ($time_now - $config['session_gc'] > $config['session_last_gc'])
4783 $cron_type = 'tidy_sessions';
4788 $template->assign_var('RUN_CRON_TASK', '<img src="' . append_sid($phpbb_root_path . 'cron.' . $phpEx, 'cron_type=' . $cron_type) . '" width="1" height="1" alt="cron" />');
4792 $template->display('body');
4794 garbage_collection();
4799 * Closing the cache object and the database
4800 * Cool function name, eh? We might want to add operations to it later
4802 function garbage_collection()
4806 // Unload cache, must be done before the DB connection if closed
4812 // Close our DB connection.
4820 * Handler for exit calls in phpBB.
4821 * This function supports hooks.
4823 * Note: This function is called after the template has been outputted.
4825 function exit_handler()
4827 global $phpbb_hook, $config;
4829 if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
4831 if ($phpbb_hook->hook_return(__FUNCTION__))
4833 return $phpbb_hook->hook_return_result(__FUNCTION__);
4837 // As a pre-caution... some setups display a blank page if the flush() is not there.
4838 (ob_get_level() > 0) ? @ob_flush() : @flush();
4844 * Handler for init calls in phpBB. This function is called in user::setup();
4845 * This function supports hooks.
4847 function phpbb_user_session_handler()
4851 if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
4853 if ($phpbb_hook->hook_return(__FUNCTION__))
4855 return $phpbb_hook->hook_return_result(__FUNCTION__);