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)
435 $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
437 $random_state = unique_id();
441 if (($fh = @fopen('/dev/urandom', 'rb')))
443 $random = fread($fh, $count);
447 if (strlen($random) < $count)
451 for ($i = 0; $i < $count; $i += 16)
453 $random_state = md5(unique_id() . $random_state);
454 $random .= pack('H*', md5($random_state));
456 $random = substr($random, 0, $count);
459 $hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64);
461 if (strlen($hash) == 34)
466 return md5($password);
470 * Check for correct password
472 * @param string $password The password in plain text
473 * @param string $hash The stored password hash
475 * @return bool Returns true if the password is correct, false if not.
477 function phpbb_check_hash($password, $hash)
479 $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
480 if (strlen($hash) == 34)
482 return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
485 return (md5($password) === $hash) ? true : false;
489 * Generate salt for hash generation
491 function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6)
493 if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
495 $iteration_count_log2 = 8;
499 $output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)];
500 $output .= _hash_encode64($input, 6, $itoa64);
508 function _hash_encode64($input, $count, &$itoa64)
515 $value = ord($input[$i++]);
516 $output .= $itoa64[$value & 0x3f];
520 $value |= ord($input[$i]) << 8;
523 $output .= $itoa64[($value >> 6) & 0x3f];
532 $value |= ord($input[$i]) << 16;
535 $output .= $itoa64[($value >> 12) & 0x3f];
542 $output .= $itoa64[($value >> 18) & 0x3f];
550 * The crypt function/replacement
552 function _hash_crypt_private($password, $setting, &$itoa64)
556 // Check for correct hash
557 if (substr($setting, 0, 3) != '$H$' && substr($setting, 0, 3) != '$P$')
562 $count_log2 = strpos($itoa64, $setting[3]);
564 if ($count_log2 < 7 || $count_log2 > 30)
569 $count = 1 << $count_log2;
570 $salt = substr($setting, 4, 8);
572 if (strlen($salt) != 8)
578 * We're kind of forced to use MD5 here since it's the only
579 * cryptographic primitive available in all versions of PHP
580 * currently in use. To implement our own low-level crypto
581 * in PHP would result in much worse performance and
582 * consequently in lower iteration counts and hashes that are
583 * quicker to crack (by non-PHP code).
585 if (PHP_VERSION >= 5)
587 $hash = md5($salt . $password, true);
590 $hash = md5($hash . $password, true);
596 $hash = pack('H*', md5($salt . $password));
599 $hash = pack('H*', md5($hash . $password));
604 $output = substr($setting, 0, 12);
605 $output .= _hash_encode64($hash, 16, $itoa64);
611 * Hashes an email address to a big integer
613 * @param string $email Email address
615 * @return string Unsigned Big Integer
617 function phpbb_email_hash($email)
619 return sprintf('%u', crc32(strtolower($email))) . strlen($email);
623 * Wrapper for version_compare() that allows using uppercase A and B
624 * for alpha and beta releases.
626 * See http://www.php.net/manual/en/function.version-compare.php
628 * @param string $version1 First version number
629 * @param string $version2 Second version number
630 * @param string $operator Comparison operator (optional)
632 * @return mixed Boolean (true, false) if comparison operator is specified.
633 * Integer (-1, 0, 1) otherwise.
635 function phpbb_version_compare($version1, $version2, $operator = null)
637 $version1 = strtolower($version1);
638 $version2 = strtolower($version2);
640 if (is_null($operator))
642 return version_compare($version1, $version2);
646 return version_compare($version1, $version2, $operator);
651 * Global function for chmodding directories and files for internal use
653 * This function determines owner and group whom the file belongs to and user and group of PHP and then set safest possible file permissions.
654 * The function determines owner and group from common.php file and sets the same to the provided file.
655 * The function uses bit fields to build the permissions.
656 * The function sets the appropiate execute bit on directories.
658 * Supported constants representing bit fields are:
660 * CHMOD_ALL - all permissions (7)
661 * CHMOD_READ - read permission (4)
662 * CHMOD_WRITE - write permission (2)
663 * CHMOD_EXECUTE - execute permission (1)
665 * NOTE: The function uses POSIX extension and fileowner()/filegroup() functions. If any of them is disabled, this function tries to build proper permissions, by calling is_readable() and is_writable() functions.
667 * @param string $filename The file/directory to be chmodded
668 * @param int $perms Permissions to set
670 * @return bool true on success, otherwise false
671 * @author faw, phpBB Group
673 function phpbb_chmod($filename, $perms = CHMOD_READ)
677 // Return if the file no longer exists.
678 if (!file_exists($filename))
683 // Determine some common vars
684 if (empty($_chmod_info))
686 if (!function_exists('fileowner') || !function_exists('filegroup'))
688 // No need to further determine owner/group - it is unknown
689 $_chmod_info['process'] = false;
693 global $phpbb_root_path, $phpEx;
695 // Determine owner/group of common.php file and the filename we want to change here
696 $common_php_owner = @fileowner($phpbb_root_path . 'common.' . $phpEx);
697 $common_php_group = @filegroup($phpbb_root_path . 'common.' . $phpEx);
699 // And the owner and the groups PHP is running under.
700 $php_uid = (function_exists('posix_getuid')) ? @posix_getuid() : false;
701 $php_gids = (function_exists('posix_getgroups')) ? @posix_getgroups() : false;
703 // If we are unable to get owner/group, then do not try to set them by guessing
704 if (!$php_uid || empty($php_gids) || !$common_php_owner || !$common_php_group)
706 $_chmod_info['process'] = false;
710 $_chmod_info = array(
712 'common_owner' => $common_php_owner,
713 'common_group' => $common_php_group,
714 'php_uid' => $php_uid,
715 'php_gids' => $php_gids,
721 if ($_chmod_info['process'])
723 $file_uid = @fileowner($filename);
724 $file_gid = @filegroup($filename);
727 if (@chown($filename, $_chmod_info['common_owner']))
730 $file_uid = @fileowner($filename);
734 if (@chgrp($filename, $_chmod_info['common_group']))
737 $file_gid = @filegroup($filename);
740 // If the file_uid/gid now match the one from common.php we can process further, else we are not able to change something
741 if ($file_uid != $_chmod_info['common_owner'] || $file_gid != $_chmod_info['common_group'])
743 $_chmod_info['process'] = false;
747 // Still able to process?
748 if ($_chmod_info['process'])
750 if ($file_uid == $_chmod_info['php_uid'])
754 else if (in_array($file_gid, $_chmod_info['php_gids']))
760 // Since we are setting the everyone bit anyway, no need to do expensive operations
761 $_chmod_info['process'] = false;
765 // We are not able to determine or change something
766 if (!$_chmod_info['process'])
771 // Owner always has read/write permission
772 $owner = CHMOD_READ | CHMOD_WRITE;
773 if (is_dir($filename))
775 $owner |= CHMOD_EXECUTE;
777 // Only add execute bit to the permission if the dir needs to be readable
778 if ($perms & CHMOD_READ)
780 $perms |= CHMOD_EXECUTE;
787 $result = @chmod($filename, ($owner << 6) + (0 << 3) + (0 << 0));
791 if (is_readable($filename) && phpbb_is_writable($filename))
797 $result = @chmod($filename, ($owner << 6) + ($perms << 3) + (0 << 0));
801 if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))
807 $result = @chmod($filename, ($owner << 6) + ($perms << 3) + ($perms << 0));
811 if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))
825 * Test if a file/directory is writable
827 * This function calls the native is_writable() when not running under
828 * Windows and it is not disabled.
830 * @param string $file Path to perform write test on
831 * @return bool True when the path is writable, otherwise false.
833 function phpbb_is_writable($file)
835 if (strtolower(substr(PHP_OS, 0, 3)) === 'win' || !function_exists('is_writable'))
837 if (file_exists($file))
839 // Canonicalise path to absolute path
840 $file = phpbb_realpath($file);
844 // Test directory by creating a file inside the directory
845 $result = @tempnam($file, 'i_w');
847 if (is_string($result) && file_exists($result))
851 // Ensure the file is actually in the directory (returned realpathed)
852 return (strpos($result, $file) === 0) ? true : false;
857 $handle = @fopen($file, 'r+');
859 if (is_resource($handle))
868 // file does not exist test if we can write to the directory
869 $dir = dirname($file);
871 if (file_exists($dir) && is_dir($dir) && phpbb_is_writable($dir))
881 return is_writable($file);
885 // Compatibility functions
887 if (!function_exists('array_combine'))
890 * A wrapper for the PHP5 function array_combine()
891 * @param array $keys contains keys for the resulting array
892 * @param array $values contains values for the resulting array
894 * @return Returns an array by using the values from the keys array as keys and the
895 * values from the values array as the corresponding values. Returns false if the
896 * number of elements for each array isn't equal or if the arrays are empty.
898 function array_combine($keys, $values)
900 $keys = array_values($keys);
901 $values = array_values($values);
904 $m = sizeof($values);
905 if (!$n || !$m || ($n != $m))
911 for ($i = 0; $i < $n; $i++)
913 $combined[$keys[$i]] = $values[$i];
919 if (!function_exists('str_split'))
922 * A wrapper for the PHP5 function str_split()
923 * @param array $string contains the string to be converted
924 * @param array $split_length contains the length of each chunk
926 * @return Converts a string to an array. If the optional split_length parameter is specified,
927 * the returned array will be broken down into chunks with each being split_length in length,
928 * otherwise each chunk will be one character in length. FALSE is returned if split_length is
929 * less than 1. If the split_length length exceeds the length of string, the entire string is
930 * returned as the first (and only) array element.
932 function str_split($string, $split_length = 1)
934 if ($split_length < 1)
938 else if ($split_length >= strlen($string))
940 return array($string);
944 preg_match_all('#.{1,' . $split_length . '}#s', $string, $matches);
950 if (!function_exists('stripos'))
953 * A wrapper for the PHP5 function stripos
954 * Find position of first occurrence of a case-insensitive string
956 * @param string $haystack is the string to search in
957 * @param string $needle is the string to search for
959 * @return mixed Returns the numeric position of the first occurrence of needle in the haystack string. Unlike strpos(), stripos() is case-insensitive.
960 * Note that the needle may be a string of one or more characters.
961 * If needle is not found, stripos() will return boolean FALSE.
963 function stripos($haystack, $needle)
965 if (preg_match('#' . preg_quote($needle, '#') . '#i', $haystack, $m))
967 return strpos($haystack, $m[0]);
975 * Checks if a path ($path) is absolute or relative
977 * @param string $path Path to check absoluteness of
980 function is_absolute($path)
982 return ($path[0] == '/' || (DIRECTORY_SEPARATOR == '\\' && preg_match('#^[a-z]:[/\\\]#i', $path))) ? true : false;
986 * @author Chris Smith <chris@project-minerva.org>
987 * @copyright 2006 Project Minerva Team
988 * @param string $path The path which we should attempt to resolve.
991 function phpbb_own_realpath($path)
993 // Now to perform funky shizzle
995 // Switch to use UNIX slashes
996 $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
999 // Determine what sort of path we have
1000 if (is_absolute($path))
1004 if ($path[0] == '/')
1006 // Absolute path, *NIX style
1011 // Absolute path, Windows style
1012 // Remove the drive letter and colon
1013 $path_prefix = $path[0] . ':';
1014 $path = substr($path, 2);
1020 // Prepend the current working directory
1021 if (function_exists('getcwd'))
1023 // This is the best method, hopefully it is enabled!
1024 $path = str_replace(DIRECTORY_SEPARATOR, '/', getcwd()) . '/' . $path;
1026 if (preg_match('#^[a-z]:#i', $path))
1028 $path_prefix = $path[0] . ':';
1029 $path = substr($path, 2);
1036 else if (isset($_SERVER['SCRIPT_FILENAME']) && !empty($_SERVER['SCRIPT_FILENAME']))
1038 // Warning: If chdir() has been used this will lie!
1039 // Warning: This has some problems sometime (CLI can create them easily)
1040 $path = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['SCRIPT_FILENAME'])) . '/' . $path;
1046 // We have no way of getting the absolute path, just run on using relative ones.
1052 // Remove any repeated slashes
1053 $path = preg_replace('#/{2,}#', '/', $path);
1055 // Remove the slashes from the start and end of the path
1056 $path = trim($path, '/');
1058 // Break the string into little bits for us to nibble on
1059 $bits = explode('/', $path);
1061 // Remove any . in the path, renumber array for the loop below
1062 $bits = array_values(array_diff($bits, array('.')));
1064 // Lets get looping, run over and resolve any .. (up directory)
1065 for ($i = 0, $max = sizeof($bits); $i < $max; $i++)
1068 if ($bits[$i] == '..' )
1070 if (isset($bits[$i - 1]))
1072 if ($bits[$i - 1] != '..')
1074 // We found a .. and we are able to traverse upwards, lets do it!
1076 unset($bits[$i - 1]);
1079 $bits = array_values($bits);
1082 else if ($absolute) // ie. !isset($bits[$i - 1]) && $absolute
1084 // We have an absolute path trying to descend above the root of the filesystem
1091 // Prepend the path prefix
1092 array_unshift($bits, $path_prefix);
1096 $max = sizeof($bits) - 1;
1098 // Check if we are able to resolve symlinks, Windows cannot.
1099 $symlink_resolve = (function_exists('readlink')) ? true : false;
1101 foreach ($bits as $i => $bit)
1103 if (@is_dir("$resolved/$bit") || ($i == $max && @is_file("$resolved/$bit")))
1106 if ($symlink_resolve && is_link("$resolved/$bit") && ($link = readlink("$resolved/$bit")))
1108 // Resolved a symlink.
1109 $resolved = $link . (($i == $max) ? '' : '/');
1115 // Something doesn't exist here!
1116 // This is correct realpath() behaviour but sadly open_basedir and safe_mode make this problematic
1119 $resolved .= $bit . (($i == $max) ? '' : '/');
1122 // @todo If the file exists fine and open_basedir only has one path we should be able to prepend it
1123 // because we must be inside that basedir, the question is where...
1124 // @internal The slash in is_dir() gets around an open_basedir restriction
1125 if (!@file_exists($resolved) || (!@is_dir($resolved . '/') && !is_file($resolved)))
1130 // Put the slashes back to the native operating systems slashes
1131 $resolved = str_replace('/', DIRECTORY_SEPARATOR, $resolved);
1133 // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
1134 if (substr($resolved, -1) == DIRECTORY_SEPARATOR)
1136 return substr($resolved, 0, -1);
1139 return $resolved; // We got here, in the end!
1142 if (!function_exists('realpath'))
1145 * A wrapper for realpath
1148 function phpbb_realpath($path)
1150 return phpbb_own_realpath($path);
1156 * A wrapper for realpath
1158 function phpbb_realpath($path)
1160 $realpath = realpath($path);
1162 // Strangely there are provider not disabling realpath but returning strange values. :o
1163 // We at least try to cope with them.
1164 if ($realpath === $path || $realpath === false)
1166 return phpbb_own_realpath($path);
1169 // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
1170 if (substr($realpath, -1) == DIRECTORY_SEPARATOR)
1172 $realpath = substr($realpath, 0, -1);
1179 if (!function_exists('htmlspecialchars_decode'))
1182 * A wrapper for htmlspecialchars_decode
1185 function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT)
1187 return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
1191 // functions used for building option fields
1194 * Pick a language, any language ...
1196 function language_select($default = '')
1200 $sql = 'SELECT lang_iso, lang_local_name
1201 FROM ' . LANG_TABLE . '
1202 ORDER BY lang_english_name';
1203 $result = $db->sql_query($sql);
1206 while ($row = $db->sql_fetchrow($result))
1208 $selected = ($row['lang_iso'] == $default) ? ' selected="selected"' : '';
1209 $lang_options .= '<option value="' . $row['lang_iso'] . '"' . $selected . '>' . $row['lang_local_name'] . '</option>';
1211 $db->sql_freeresult($result);
1213 return $lang_options;
1217 * Pick a template/theme combo,
1219 function style_select($default = '', $all = false)
1223 $sql_where = (!$all) ? 'WHERE style_active = 1 ' : '';
1224 $sql = 'SELECT style_id, style_name
1225 FROM ' . STYLES_TABLE . "
1227 ORDER BY style_name";
1228 $result = $db->sql_query($sql);
1230 $style_options = '';
1231 while ($row = $db->sql_fetchrow($result))
1233 $selected = ($row['style_id'] == $default) ? ' selected="selected"' : '';
1234 $style_options .= '<option value="' . $row['style_id'] . '"' . $selected . '>' . $row['style_name'] . '</option>';
1236 $db->sql_freeresult($result);
1238 return $style_options;
1244 function tz_select($default = '', $truncate = false)
1249 foreach ($user->lang['tz_zones'] as $offset => $zone)
1253 $zone_trunc = truncate_string($zone, 50, 255, false, '...');
1257 $zone_trunc = $zone;
1260 if (is_numeric($offset))
1262 $selected = ($offset == $default) ? ' selected="selected"' : '';
1263 $tz_select .= '<option title="' . $zone . '" value="' . $offset . '"' . $selected . '>' . $zone_trunc . '</option>';
1270 // Functions handling topic/post tracking/marking
1273 * Marks a topic/forum as read
1274 * Marks a topic as posted to
1276 * @param int $user_id can only be used with $mode == 'post'
1278 function markread($mode, $forum_id = false, $topic_id = false, $post_time = 0, $user_id = 0)
1280 global $db, $user, $config;
1284 if ($forum_id === false || !sizeof($forum_id))
1286 if ($config['load_db_lastread'] && $user->data['is_registered'])
1288 // Mark all forums read (index page)
1289 $db->sql_query('DELETE FROM ' . TOPICS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
1290 $db->sql_query('DELETE FROM ' . FORUMS_TRACK_TABLE . " WHERE user_id = {$user->data['user_id']}");
1291 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
1293 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1295 $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1296 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1298 unset($tracking_topics['tf']);
1299 unset($tracking_topics['t']);
1300 unset($tracking_topics['f']);
1301 $tracking_topics['l'] = base_convert(time() - $config['board_startdate'], 10, 36);
1303 $user->set_cookie('track', tracking_serialize($tracking_topics), time() + 31536000);
1304 $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking_topics)) : tracking_serialize($tracking_topics);
1306 unset($tracking_topics);
1308 if ($user->data['is_registered'])
1310 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . time() . " WHERE user_id = {$user->data['user_id']}");
1317 else if ($mode == 'topics')
1319 // Mark all topics in forums read
1320 if (!is_array($forum_id))
1322 $forum_id = array($forum_id);
1325 // Add 0 to forums array to mark global announcements correctly
1328 if ($config['load_db_lastread'] && $user->data['is_registered'])
1330 $sql = 'DELETE FROM ' . TOPICS_TRACK_TABLE . "
1331 WHERE user_id = {$user->data['user_id']}
1332 AND " . $db->sql_in_set('forum_id', $forum_id);
1333 $db->sql_query($sql);
1335 $sql = 'SELECT forum_id
1336 FROM ' . FORUMS_TRACK_TABLE . "
1337 WHERE user_id = {$user->data['user_id']}
1338 AND " . $db->sql_in_set('forum_id', $forum_id);
1339 $result = $db->sql_query($sql);
1341 $sql_update = array();
1342 while ($row = $db->sql_fetchrow($result))
1344 $sql_update[] = (int) $row['forum_id'];
1346 $db->sql_freeresult($result);
1348 if (sizeof($sql_update))
1350 $sql = 'UPDATE ' . FORUMS_TRACK_TABLE . '
1351 SET mark_time = ' . time() . "
1352 WHERE user_id = {$user->data['user_id']}
1353 AND " . $db->sql_in_set('forum_id', $sql_update);
1354 $db->sql_query($sql);
1357 if ($sql_insert = array_diff($forum_id, $sql_update))
1360 foreach ($sql_insert as $f_id)
1363 'user_id' => (int) $user->data['user_id'],
1364 'forum_id' => (int) $f_id,
1365 'mark_time' => time()
1369 $db->sql_multi_insert(FORUMS_TRACK_TABLE, $sql_ary);
1372 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1374 $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1375 $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
1377 foreach ($forum_id as $f_id)
1379 $topic_ids36 = (isset($tracking['tf'][$f_id])) ? $tracking['tf'][$f_id] : array();
1381 if (isset($tracking['tf'][$f_id]))
1383 unset($tracking['tf'][$f_id]);
1386 foreach ($topic_ids36 as $topic_id36)
1388 unset($tracking['t'][$topic_id36]);
1391 if (isset($tracking['f'][$f_id]))
1393 unset($tracking['f'][$f_id]);
1396 $tracking['f'][$f_id] = base_convert(time() - $config['board_startdate'], 10, 36);
1399 if (isset($tracking['tf']) && empty($tracking['tf']))
1401 unset($tracking['tf']);
1404 $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
1405 $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
1412 else if ($mode == 'topic')
1414 if ($topic_id === false || $forum_id === false)
1419 if ($config['load_db_lastread'] && $user->data['is_registered'])
1421 $sql = 'UPDATE ' . TOPICS_TRACK_TABLE . '
1422 SET mark_time = ' . (($post_time) ? $post_time : time()) . "
1423 WHERE user_id = {$user->data['user_id']}
1424 AND topic_id = $topic_id";
1425 $db->sql_query($sql);
1428 if (!$db->sql_affectedrows())
1430 $db->sql_return_on_error(true);
1433 'user_id' => (int) $user->data['user_id'],
1434 'topic_id' => (int) $topic_id,
1435 'forum_id' => (int) $forum_id,
1436 'mark_time' => ($post_time) ? (int) $post_time : time(),
1439 $db->sql_query('INSERT INTO ' . TOPICS_TRACK_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
1441 $db->sql_return_on_error(false);
1444 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1446 $tracking = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1447 $tracking = ($tracking) ? tracking_unserialize($tracking) : array();
1449 $topic_id36 = base_convert($topic_id, 10, 36);
1451 if (!isset($tracking['t'][$topic_id36]))
1453 $tracking['tf'][$forum_id][$topic_id36] = true;
1456 $post_time = ($post_time) ? $post_time : time();
1457 $tracking['t'][$topic_id36] = base_convert($post_time - $config['board_startdate'], 10, 36);
1459 // If the cookie grows larger than 10000 characters we will remove the smallest value
1460 // This can result in old topics being unread - but most of the time it should be accurate...
1461 if (isset($_COOKIE[$config['cookie_name'] . '_track']) && strlen($_COOKIE[$config['cookie_name'] . '_track']) > 10000)
1463 //echo 'Cookie grown too large' . print_r($tracking, true);
1465 // We get the ten most minimum stored time offsets and its associated topic ids
1466 $time_keys = array();
1467 for ($i = 0; $i < 10 && sizeof($tracking['t']); $i++)
1469 $min_value = min($tracking['t']);
1470 $m_tkey = array_search($min_value, $tracking['t']);
1471 unset($tracking['t'][$m_tkey]);
1473 $time_keys[$m_tkey] = $min_value;
1476 // Now remove the topic ids from the array...
1477 foreach ($tracking['tf'] as $f_id => $topic_id_ary)
1479 foreach ($time_keys as $m_tkey => $min_value)
1481 if (isset($topic_id_ary[$m_tkey]))
1483 $tracking['f'][$f_id] = $min_value;
1484 unset($tracking['tf'][$f_id][$m_tkey]);
1489 if ($user->data['is_registered'])
1491 $user->data['user_lastmark'] = intval(base_convert(max($time_keys) + $config['board_startdate'], 36, 10));
1492 $db->sql_query('UPDATE ' . USERS_TABLE . ' SET user_lastmark = ' . $user->data['user_lastmark'] . " WHERE user_id = {$user->data['user_id']}");
1496 $tracking['l'] = max($time_keys);
1500 $user->set_cookie('track', tracking_serialize($tracking), time() + 31536000);
1501 $_COOKIE[$config['cookie_name'] . '_track'] = (STRIP) ? addslashes(tracking_serialize($tracking)) : tracking_serialize($tracking);
1506 else if ($mode == 'post')
1508 if ($topic_id === false)
1513 $use_user_id = (!$user_id) ? $user->data['user_id'] : $user_id;
1515 if ($config['load_db_track'] && $use_user_id != ANONYMOUS)
1517 $db->sql_return_on_error(true);
1520 'user_id' => (int) $use_user_id,
1521 'topic_id' => (int) $topic_id,
1525 $db->sql_query('INSERT INTO ' . TOPICS_POSTED_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
1527 $db->sql_return_on_error(false);
1535 * Get topic tracking info by using already fetched info
1537 function get_topic_tracking($forum_id, $topic_ids, &$rowset, $forum_mark_time, $global_announce_list = false)
1539 global $config, $user;
1541 $last_read = array();
1543 if (!is_array($topic_ids))
1545 $topic_ids = array($topic_ids);
1548 foreach ($topic_ids as $topic_id)
1550 if (!empty($rowset[$topic_id]['mark_time']))
1552 $last_read[$topic_id] = $rowset[$topic_id]['mark_time'];
1556 $topic_ids = array_diff($topic_ids, array_keys($last_read));
1558 if (sizeof($topic_ids))
1560 $mark_time = array();
1562 // Get global announcement info
1563 if ($global_announce_list && sizeof($global_announce_list))
1565 if (!isset($forum_mark_time[0]))
1569 $sql = 'SELECT mark_time
1570 FROM ' . FORUMS_TRACK_TABLE . "
1571 WHERE user_id = {$user->data['user_id']}
1573 $result = $db->sql_query($sql);
1574 $row = $db->sql_fetchrow($result);
1575 $db->sql_freeresult($result);
1579 $mark_time[0] = $row['mark_time'];
1584 if ($forum_mark_time[0] !== false)
1586 $mark_time[0] = $forum_mark_time[0];
1591 if (!empty($forum_mark_time[$forum_id]) && $forum_mark_time[$forum_id] !== false)
1593 $mark_time[$forum_id] = $forum_mark_time[$forum_id];
1596 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
1598 foreach ($topic_ids as $topic_id)
1600 if ($global_announce_list && isset($global_announce_list[$topic_id]))
1602 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1606 $last_read[$topic_id] = $user_lastmark;
1615 * Get topic tracking info from db (for cookie based tracking only this function is used)
1617 function get_complete_topic_tracking($forum_id, $topic_ids, $global_announce_list = false)
1619 global $config, $user;
1621 $last_read = array();
1623 if (!is_array($topic_ids))
1625 $topic_ids = array($topic_ids);
1628 if ($config['load_db_lastread'] && $user->data['is_registered'])
1632 $sql = 'SELECT topic_id, mark_time
1633 FROM ' . TOPICS_TRACK_TABLE . "
1634 WHERE user_id = {$user->data['user_id']}
1635 AND " . $db->sql_in_set('topic_id', $topic_ids);
1636 $result = $db->sql_query($sql);
1638 while ($row = $db->sql_fetchrow($result))
1640 $last_read[$row['topic_id']] = $row['mark_time'];
1642 $db->sql_freeresult($result);
1644 $topic_ids = array_diff($topic_ids, array_keys($last_read));
1646 if (sizeof($topic_ids))
1648 $sql = 'SELECT forum_id, mark_time
1649 FROM ' . FORUMS_TRACK_TABLE . "
1650 WHERE user_id = {$user->data['user_id']}
1652 (($global_announce_list && sizeof($global_announce_list)) ? "IN (0, $forum_id)" : "= $forum_id");
1653 $result = $db->sql_query($sql);
1655 $mark_time = array();
1656 while ($row = $db->sql_fetchrow($result))
1658 $mark_time[$row['forum_id']] = $row['mark_time'];
1660 $db->sql_freeresult($result);
1662 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user->data['user_lastmark'];
1664 foreach ($topic_ids as $topic_id)
1666 if ($global_announce_list && isset($global_announce_list[$topic_id]))
1668 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1672 $last_read[$topic_id] = $user_lastmark;
1677 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1679 global $tracking_topics;
1681 if (!isset($tracking_topics) || !sizeof($tracking_topics))
1683 $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1684 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1687 if (!$user->data['is_registered'])
1689 $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
1693 $user_lastmark = $user->data['user_lastmark'];
1696 foreach ($topic_ids as $topic_id)
1698 $topic_id36 = base_convert($topic_id, 10, 36);
1700 if (isset($tracking_topics['t'][$topic_id36]))
1702 $last_read[$topic_id] = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
1706 $topic_ids = array_diff($topic_ids, array_keys($last_read));
1708 if (sizeof($topic_ids))
1710 $mark_time = array();
1711 if ($global_announce_list && sizeof($global_announce_list))
1713 if (isset($tracking_topics['f'][0]))
1715 $mark_time[0] = base_convert($tracking_topics['f'][0], 36, 10) + $config['board_startdate'];
1719 if (isset($tracking_topics['f'][$forum_id]))
1721 $mark_time[$forum_id] = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
1724 $user_lastmark = (isset($mark_time[$forum_id])) ? $mark_time[$forum_id] : $user_lastmark;
1726 foreach ($topic_ids as $topic_id)
1728 if ($global_announce_list && isset($global_announce_list[$topic_id]))
1730 $last_read[$topic_id] = (isset($mark_time[0])) ? $mark_time[0] : $user_lastmark;
1734 $last_read[$topic_id] = $user_lastmark;
1744 * Get list of unread topics
1746 * @param int $user_id User ID (or false for current user)
1747 * @param string $sql_extra Extra WHERE SQL statement
1748 * @param string $sql_sort ORDER BY SQL sorting statement
1749 * @param string $sql_limit Limits the size of unread topics list, 0 for unlimited query
1750 * @param string $sql_limit_offset Sets the offset of the first row to search, 0 to search from the start
1752 * @return array[int][int] Topic ids as keys, mark_time of topic as value
1754 function get_unread_topics($user_id = false, $sql_extra = '', $sql_sort = '', $sql_limit = 1001, $sql_limit_offset = 0)
1756 global $config, $db, $user;
1758 $user_id = ($user_id === false) ? (int) $user->data['user_id'] : (int) $user_id;
1760 // Data array we're going to return
1761 $unread_topics = array();
1763 if (empty($sql_sort))
1765 $sql_sort = 'ORDER BY t.topic_last_post_time DESC';
1768 if ($config['load_db_lastread'] && $user->data['is_registered'])
1770 // Get list of the unread topics
1771 $last_mark = (int) $user->data['user_lastmark'];
1774 'SELECT' => 't.topic_id, t.topic_last_post_time, tt.mark_time as topic_mark_time, ft.mark_time as forum_mark_time',
1776 'FROM' => array(TOPICS_TABLE => 't'),
1778 'LEFT_JOIN' => array(
1780 'FROM' => array(TOPICS_TRACK_TABLE => 'tt'),
1781 'ON' => "tt.user_id = $user_id AND t.topic_id = tt.topic_id",
1784 'FROM' => array(FORUMS_TRACK_TABLE => 'ft'),
1785 'ON' => "ft.user_id = $user_id AND t.forum_id = ft.forum_id",
1790 t.topic_last_post_time > $last_mark AND
1792 (tt.mark_time IS NOT NULL AND t.topic_last_post_time > tt.mark_time) OR
1793 (tt.mark_time IS NULL AND ft.mark_time IS NOT NULL AND t.topic_last_post_time > ft.mark_time) OR
1794 (tt.mark_time IS NULL AND ft.mark_time IS NULL)
1800 $sql = $db->sql_build_query('SELECT', $sql_array);
1801 $result = $db->sql_query_limit($sql, $sql_limit, $sql_limit_offset);
1803 while ($row = $db->sql_fetchrow($result))
1805 $topic_id = (int) $row['topic_id'];
1806 $unread_topics[$topic_id] = ($row['topic_mark_time']) ? (int) $row['topic_mark_time'] : (($row['forum_mark_time']) ? (int) $row['forum_mark_time'] : $last_mark);
1808 $db->sql_freeresult($result);
1810 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1812 global $tracking_topics;
1814 if (empty($tracking_topics))
1816 $tracking_topics = request_var($config['cookie_name'] . '_track', '', false, true);
1817 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1820 if (!$user->data['is_registered'])
1822 $user_lastmark = (isset($tracking_topics['l'])) ? base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate'] : 0;
1826 $user_lastmark = (int) $user->data['user_lastmark'];
1829 $sql = 'SELECT t.topic_id, t.forum_id, t.topic_last_post_time
1830 FROM ' . TOPICS_TABLE . ' t
1831 WHERE t.topic_last_post_time > ' . $user_lastmark . "
1834 $result = $db->sql_query_limit($sql, $sql_limit, $sql_limit_offset);
1836 while ($row = $db->sql_fetchrow($result))
1838 $forum_id = (int) $row['forum_id'];
1839 $topic_id = (int) $row['topic_id'];
1840 $topic_id36 = base_convert($topic_id, 10, 36);
1842 if (isset($tracking_topics['t'][$topic_id36]))
1844 $last_read = base_convert($tracking_topics['t'][$topic_id36], 36, 10) + $config['board_startdate'];
1846 if ($row['topic_last_post_time'] > $last_read)
1848 $unread_topics[$topic_id] = $last_read;
1851 else if (isset($tracking_topics['f'][$forum_id]))
1853 $mark_time = base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate'];
1855 if ($row['topic_last_post_time'] > $mark_time)
1857 $unread_topics[$topic_id] = $mark_time;
1862 $unread_topics[$topic_id] = $user_lastmark;
1865 $db->sql_freeresult($result);
1868 return $unread_topics;
1872 * Check for read forums and update topic tracking info accordingly
1874 * @param int $forum_id the forum id to check
1875 * @param int $forum_last_post_time the forums last post time
1876 * @param int $f_mark_time the forums last mark time if user is registered and load_db_lastread enabled
1877 * @param int $mark_time_forum false if the mark time needs to be obtained, else the last users forum mark time
1879 * @return true if complete forum got marked read, else false.
1881 function update_forum_tracking_info($forum_id, $forum_last_post_time, $f_mark_time = false, $mark_time_forum = false)
1883 global $db, $tracking_topics, $user, $config, $auth;
1885 // Determine the users last forum mark time if not given.
1886 if ($mark_time_forum === false)
1888 if ($config['load_db_lastread'] && $user->data['is_registered'])
1890 $mark_time_forum = (!empty($f_mark_time)) ? $f_mark_time : $user->data['user_lastmark'];
1892 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1894 $tracking_topics = (isset($_COOKIE[$config['cookie_name'] . '_track'])) ? ((STRIP) ? stripslashes($_COOKIE[$config['cookie_name'] . '_track']) : $_COOKIE[$config['cookie_name'] . '_track']) : '';
1895 $tracking_topics = ($tracking_topics) ? tracking_unserialize($tracking_topics) : array();
1897 if (!$user->data['is_registered'])
1899 $user->data['user_lastmark'] = (isset($tracking_topics['l'])) ? (int) (base_convert($tracking_topics['l'], 36, 10) + $config['board_startdate']) : 0;
1902 $mark_time_forum = (isset($tracking_topics['f'][$forum_id])) ? (int) (base_convert($tracking_topics['f'][$forum_id], 36, 10) + $config['board_startdate']) : $user->data['user_lastmark'];
1906 // Handle update of unapproved topics info.
1907 // Only update for moderators having m_approve permission for the forum.
1908 $sql_update_unapproved = ($auth->acl_get('m_approve', $forum_id)) ? '': 'AND t.topic_approved = 1';
1910 // Check the forum for any left unread topics.
1911 // If there are none, we mark the forum as read.
1912 if ($config['load_db_lastread'] && $user->data['is_registered'])
1914 if ($mark_time_forum >= $forum_last_post_time)
1916 // We do not need to mark read, this happened before. Therefore setting this to true
1921 $sql = 'SELECT t.forum_id FROM ' . TOPICS_TABLE . ' t
1922 LEFT JOIN ' . TOPICS_TRACK_TABLE . ' tt ON (tt.topic_id = t.topic_id AND tt.user_id = ' . $user->data['user_id'] . ')
1923 WHERE t.forum_id = ' . $forum_id . '
1924 AND t.topic_last_post_time > ' . $mark_time_forum . '
1925 AND t.topic_moved_id = 0 ' .
1926 $sql_update_unapproved . '
1927 AND (tt.topic_id IS NULL OR tt.mark_time < t.topic_last_post_time)
1928 GROUP BY t.forum_id';
1929 $result = $db->sql_query_limit($sql, 1);
1930 $row = $db->sql_fetchrow($result);
1931 $db->sql_freeresult($result);
1934 else if ($config['load_anon_lastread'] || $user->data['is_registered'])
1936 // Get information from cookie
1939 if (!isset($tracking_topics['tf'][$forum_id]))
1941 // We do not need to mark read, this happened before. Therefore setting this to true
1946 $sql = 'SELECT t.topic_id
1947 FROM ' . TOPICS_TABLE . ' t
1948 WHERE t.forum_id = ' . $forum_id . '
1949 AND t.topic_last_post_time > ' . $mark_time_forum . '
1950 AND t.topic_moved_id = 0 ' .
1951 $sql_update_unapproved;
1952 $result = $db->sql_query($sql);
1954 $check_forum = $tracking_topics['tf'][$forum_id];
1957 while ($row = $db->sql_fetchrow($result))
1959 if (!isset($check_forum[base_convert($row['topic_id'], 10, 36)]))
1965 $db->sql_freeresult($result);
1977 markread('topics', $forum_id);
1985 * Transform an array into a serialized format
1987 function tracking_serialize($input)
1990 foreach ($input as $key => $value)
1992 if (is_array($value))
1994 $out .= $key . ':(' . tracking_serialize($value) . ');';
1998 $out .= $key . ':' . $value . ';';
2005 * Transform a serialized array into an actual array
2007 function tracking_unserialize($string, $max_depth = 3)
2009 $n = strlen($string);
2012 die('Invalid data supplied');
2014 $data = $stack = array();
2018 for ($i = 0; $i < $n; ++$i)
2023 switch ($string[$i])
2031 $level = array_pop($stack);
2035 $key .= $string[$i];
2040 switch ($string[$i])
2043 if (sizeof($stack) >= $max_depth)
2045 die('Invalid data supplied');
2048 $level[$key] = array();
2049 $level = &$level[$key];
2054 $level[$key] = $string[$i];
2061 switch ($string[$i])
2065 $level = array_pop($stack);
2073 $level[$key] .= $string[$i];
2079 switch ($string[$i])
2083 $level = array_pop($stack);
2090 die('Invalid data supplied');
2097 if (sizeof($stack) != 0 || ($mode != 0 && $mode != 3))
2099 die('Invalid data supplied');
2105 // Pagination functions
2108 * Pagination routine, generates page number sequence
2109 * tpl_prefix is for using different pagination blocks at one page
2111 function generate_pagination($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = false, $tpl_prefix = '')
2113 global $template, $user;
2115 // Make sure $per_page is a valid value
2116 $per_page = ($per_page <= 0) ? 1 : $per_page;
2118 $seperator = '<span class="page-sep">' . $user->lang['COMMA_SEPARATOR'] . '</span>';
2119 $total_pages = ceil($num_items / $per_page);
2121 if ($total_pages == 1 || !$num_items)
2126 $on_page = floor($start_item / $per_page) + 1;
2127 $url_delim = (strpos($base_url, '?') === false) ? '?' : ((strpos($base_url, '?') === strlen($base_url) - 1) ? '' : '&');
2129 $page_string = ($on_page == 1) ? '<strong>1</strong>' : '<a href="' . $base_url . '">1</a>';
2131 if ($total_pages > 5)
2133 $start_cnt = min(max(1, $on_page - 4), $total_pages - 5);
2134 $end_cnt = max(min($total_pages, $on_page + 4), 6);
2136 $page_string .= ($start_cnt > 1) ? '<span class="page-dots"> ... </span>' : $seperator;
2138 for ($i = $start_cnt + 1; $i < $end_cnt; $i++)
2140 $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
2141 if ($i < $end_cnt - 1)
2143 $page_string .= $seperator;
2147 $page_string .= ($end_cnt < $total_pages) ? '<span class="page-dots"> ... </span>' : $seperator;
2151 $page_string .= $seperator;
2153 for ($i = 2; $i < $total_pages; $i++)
2155 $page_string .= ($i == $on_page) ? '<strong>' . $i . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($i - 1) * $per_page) . '">' . $i . '</a>';
2156 if ($i < $total_pages)
2158 $page_string .= $seperator;
2163 $page_string .= ($on_page == $total_pages) ? '<strong>' . $total_pages . '</strong>' : '<a href="' . $base_url . "{$url_delim}start=" . (($total_pages - 1) * $per_page) . '">' . $total_pages . '</a>';
2165 if ($add_prevnext_text)
2169 $page_string = '<a href="' . $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page) . '">' . $user->lang['PREVIOUS'] . '</a> ' . $page_string;
2172 if ($on_page != $total_pages)
2174 $page_string .= ' <a href="' . $base_url . "{$url_delim}start=" . ($on_page * $per_page) . '">' . $user->lang['NEXT'] . '</a>';
2178 $template->assign_vars(array(
2179 $tpl_prefix . 'BASE_URL' => $base_url,
2180 'A_' . $tpl_prefix . 'BASE_URL' => addslashes($base_url),
2181 $tpl_prefix . 'PER_PAGE' => $per_page,
2183 $tpl_prefix . 'PREVIOUS_PAGE' => ($on_page == 1) ? '' : $base_url . "{$url_delim}start=" . (($on_page - 2) * $per_page),
2184 $tpl_prefix . 'NEXT_PAGE' => ($on_page == $total_pages) ? '' : $base_url . "{$url_delim}start=" . ($on_page * $per_page),
2185 $tpl_prefix . 'TOTAL_PAGES' => $total_pages,
2188 return $page_string;
2192 * Return current page (pagination)
2194 function on_page($num_items, $per_page, $start)
2196 global $template, $user;
2198 // Make sure $per_page is a valid value
2199 $per_page = ($per_page <= 0) ? 1 : $per_page;
2201 $on_page = floor($start / $per_page) + 1;
2203 $template->assign_vars(array(
2204 'ON_PAGE' => $on_page)
2207 return sprintf($user->lang['PAGE_OF'], $on_page, max(ceil($num_items / $per_page), 1));
2210 // Server functions (building urls, redirecting...)
2213 * Append session id to url.
2214 * This function supports hooks.
2216 * @param string $url The url the session id needs to be appended to (can have params)
2217 * @param mixed $params String or array of additional url parameters
2218 * @param bool $is_amp Is url using & (true) or & (false)
2219 * @param string $session_id Possibility to use a custom session id instead of the global one
2223 * append_sid("{$phpbb_root_path}viewtopic.$phpEx?t=1&f=2");
2224 * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2');
2225 * append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2', false);
2226 * append_sid("{$phpbb_root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
2230 function append_sid($url, $params = false, $is_amp = true, $session_id = false)
2232 global $_SID, $_EXTRA_URL, $phpbb_hook;
2234 if ($params === '' || (is_array($params) && empty($params)))
2236 // Do not append the ? if the param-list is empty anyway.
2240 // Developers using the hook function need to globalise the $_SID and $_EXTRA_URL on their own and also handle it appropriately.
2241 // They could mimic most of what is within this function
2242 if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__, $url, $params, $is_amp, $session_id))
2244 if ($phpbb_hook->hook_return(__FUNCTION__))
2246 return $phpbb_hook->hook_return_result(__FUNCTION__);
2250 $params_is_array = is_array($params);
2254 if (strpos($url, '#') !== false)
2256 list($url, $anchor) = explode('#', $url, 2);
2257 $anchor = '#' . $anchor;
2259 else if (!$params_is_array && strpos($params, '#') !== false)
2261 list($params, $anchor) = explode('#', $params, 2);
2262 $anchor = '#' . $anchor;
2265 // Handle really simple cases quickly
2266 if ($_SID == '' && $session_id === false && empty($_EXTRA_URL) && !$params_is_array && !$anchor)
2268 if ($params === false)
2273 $url_delim = (strpos($url, '?') === false) ? '?' : (($is_amp) ? '&' : '&');
2274 return $url . ($params !== false ? $url_delim. $params : '');
2277 // Assign sid if session id is not specified
2278 if ($session_id === false)
2280 $session_id = $_SID;
2283 $amp_delim = ($is_amp) ? '&' : '&';
2284 $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
2286 // Appending custom url parameter?
2287 $append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';
2289 // Use the short variant if possible ;)
2290 if ($params === false)
2292 // Append session id
2295 return $url . (($append_url) ? $url_delim . $append_url : '') . $anchor;
2299 return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id . $anchor;
2303 // Build string if parameters are specified as array
2304 if (is_array($params))
2308 foreach ($params as $key => $item)
2317 $anchor = '#' . $item;
2321 $output[] = $key . '=' . $item;
2324 $params = implode($amp_delim, $output);
2327 // Append session id and parameters (even if they are empty)
2328 // If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
2329 return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
2333 * Generate board url (example: http://www.example.com/phpBB)
2335 * @param bool $without_script_path if set to true the script path gets not appended (example: http://www.example.com)
2337 * @return string the generated board url
2339 function generate_board_url($without_script_path = false)
2341 global $config, $user;
2343 $server_name = $user->host;
2344 $server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
2346 // Forcing server vars is the only way to specify/override the protocol
2347 if ($config['force_server_vars'] || !$server_name)
2349 $server_protocol = ($config['server_protocol']) ? $config['server_protocol'] : (($config['cookie_secure']) ? 'https://' : 'http://');
2350 $server_name = $config['server_name'];
2351 $server_port = (int) $config['server_port'];
2352 $script_path = $config['script_path'];
2354 $url = $server_protocol . $server_name;
2355 $cookie_secure = $config['cookie_secure'];
2359 // Do not rely on cookie_secure, users seem to think that it means a secured cookie instead of an encrypted connection
2360 $cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
2361 $url = (($cookie_secure) ? 'https://' : 'http://') . $server_name;
2363 $script_path = $user->page['root_script_path'];
2366 if ($server_port && (($cookie_secure && $server_port <> 443) || (!$cookie_secure && $server_port <> 80)))
2368 // HTTP HOST can carry a port number (we fetch $user->host, but for old versions this may be true)
2369 if (strpos($server_name, ':') === false)
2371 $url .= ':' . $server_port;
2375 if (!$without_script_path)
2377 $url .= $script_path;
2380 // Strip / from the end
2381 if (substr($url, -1, 1) == '/')
2383 $url = substr($url, 0, -1);
2390 * Redirects the user to another page then exits the script nicely
2391 * This function is intended for urls within the board. It's not meant to redirect to cross-domains.
2393 * @param string $url The url to redirect to
2394 * @param bool $return If true, do not redirect but return the sanitized URL. Default is no return.
2395 * @param bool $disable_cd_check If true, redirect() will redirect to an external domain. If false, the redirect point to the boards url if it does not match the current domain. Default is false.
2397 function redirect($url, $return = false, $disable_cd_check = false)
2399 global $db, $cache, $config, $user, $phpbb_root_path;
2401 $failover_flag = false;
2403 if (empty($user->lang))
2405 $user->add_lang('common');
2410 garbage_collection();
2413 // Make sure no &'s are in, this will break the redirect
2414 $url = str_replace('&', '&', $url);
2416 // Determine which type of redirect we need to handle...
2417 $url_parts = @parse_url($url);
2419 if ($url_parts === false)
2421 // Malformed url, redirect to current page...
2422 $url = generate_board_url() . '/' . $user->page['page'];
2424 else if (!empty($url_parts['scheme']) && !empty($url_parts['host']))
2426 // Attention: only able to redirect within the same domain if $disable_cd_check is false (yourdomain.com -> www.yourdomain.com will not work)
2427 if (!$disable_cd_check && $url_parts['host'] !== $user->host)
2429 $url = generate_board_url();
2432 else if ($url[0] == '/')
2434 // Absolute uri, prepend direct url...
2435 $url = generate_board_url(true) . $url;
2440 $pathinfo = pathinfo($url);
2442 if (!$disable_cd_check && !file_exists($pathinfo['dirname'] . '/'))
2444 $url = str_replace('../', '', $url);
2445 $pathinfo = pathinfo($url);
2447 if (!file_exists($pathinfo['dirname'] . '/'))
2449 // fallback to "last known user page"
2450 // at least this way we know the user does not leave the phpBB root
2451 $url = generate_board_url() . '/' . $user->page['page'];
2452 $failover_flag = true;
2456 if (!$failover_flag)
2458 // Is the uri pointing to the current directory?
2459 if ($pathinfo['dirname'] == '.')
2461 $url = str_replace('./', '', $url);
2463 // Strip / from the beginning
2464 if ($url && substr($url, 0, 1) == '/')
2466 $url = substr($url, 1);
2469 if ($user->page['page_dir'])
2471 $url = generate_board_url() . '/' . $user->page['page_dir'] . '/' . $url;
2475 $url = generate_board_url() . '/' . $url;
2480 // Used ./ before, but $phpbb_root_path is working better with urls within another root path
2481 $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($phpbb_root_path)));
2482 $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($pathinfo['dirname'])));
2483 $intersection = array_intersect_assoc($root_dirs, $page_dirs);
2485 $root_dirs = array_diff_assoc($root_dirs, $intersection);
2486 $page_dirs = array_diff_assoc($page_dirs, $intersection);
2488 $dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
2490 // Strip / from the end
2491 if ($dir && substr($dir, -1, 1) == '/')
2493 $dir = substr($dir, 0, -1);
2496 // Strip / from the beginning
2497 if ($dir && substr($dir, 0, 1) == '/')
2499 $dir = substr($dir, 1);
2502 $url = str_replace($pathinfo['dirname'] . '/', '', $url);
2504 // Strip / from the beginning
2505 if (substr($url, 0, 1) == '/')
2507 $url = substr($url, 1);
2510 $url = (!empty($dir) ? $dir . '/' : '') . $url;
2511 $url = generate_board_url() . '/' . $url;
2516 // Make sure no linebreaks are there... to prevent http response splitting for PHP < 4.4.2
2517 if (strpos(urldecode($url), "\n") !== false || strpos(urldecode($url), "\r") !== false || strpos($url, ';') !== false)
2519 trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
2522 // Now, also check the protocol and for a valid url the last time...
2523 $allowed_protocols = array('http', 'https', 'ftp', 'ftps');
2524 $url_parts = parse_url($url);
2526 if ($url_parts === false || empty($url_parts['scheme']) || !in_array($url_parts['scheme'], $allowed_protocols))
2528 trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
2536 // Redirect via an HTML form for PITA webservers
2537 if (@preg_match('#Microsoft|WebSTAR|Xitami#', getenv('SERVER_SOFTWARE')))
2539 header('Refresh: 0; URL=' . $url);
2541 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
2542 echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="' . $user->lang['DIRECTION'] . '" lang="' . $user->lang['USER_LANG'] . '" xml:lang="' . $user->lang['USER_LANG'] . '">';
2544 echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
2545 echo '<meta http-equiv="refresh" content="0; url=' . str_replace('&', '&', $url) . '" />';
2546 echo '<title>' . $user->lang['REDIRECT'] . '</title>';
2549 echo '<div style="text-align: center;">' . sprintf($user->lang['URL_REDIRECT'], '<a href="' . str_replace('&', '&', $url) . '">', '</a>') . '</div>';
2556 // Behave as per HTTP/1.1 spec for others
2557 header('Location: ' . $url);
2562 * Re-Apply session id after page reloads
2564 function reapply_sid($url)
2566 global $phpEx, $phpbb_root_path;
2568 if ($url === "index.$phpEx")
2570 return append_sid("index.$phpEx");
2572 else if ($url === "{$phpbb_root_path}index.$phpEx")
2574 return append_sid("{$phpbb_root_path}index.$phpEx");
2577 // Remove previously added sid
2578 if (strpos($url, 'sid=') !== false)
2580 // All kind of links
2581 $url = preg_replace('/(\?)?(&|&)?sid=[a-z0-9]+/', '', $url);
2582 // if the sid was the first param, make the old second as first ones
2583 $url = preg_replace("/$phpEx(&|&)+?/", "$phpEx?", $url);
2586 return append_sid($url);
2590 * Returns url from the session/current page with an re-appended SID with optionally stripping vars from the url
2592 function build_url($strip_vars = false)
2594 global $user, $phpbb_root_path;
2597 $redirect = append_sid($user->page['page'], false, false);
2599 // Add delimiter if not there...
2600 if (strpos($redirect, '?') === false)
2606 if ($strip_vars !== false && strpos($redirect, '?') !== false)
2608 if (!is_array($strip_vars))
2610 $strip_vars = array($strip_vars);
2613 $query = $_query = array();
2615 $args = substr($redirect, strpos($redirect, '?') + 1);
2616 $args = ($args) ? explode('&', $args) : array();
2617 $redirect = substr($redirect, 0, strpos($redirect, '?'));
2619 foreach ($args as $argument)
2621 $arguments = explode('=', $argument);
2622 $key = $arguments[0];
2623 unset($arguments[0]);
2630 $query[$key] = implode('=', $arguments);
2633 // Strip the vars off
2634 foreach ($strip_vars as $strip)
2636 if (isset($query[$strip]))
2638 unset($query[$strip]);
2642 // Glue the remaining parts together... already urlencoded
2643 foreach ($query as $key => $value)
2645 $_query[] = $key . '=' . $value;
2647 $query = implode('&', $_query);
2649 $redirect .= ($query) ? '?' . $query : '';
2652 // We need to be cautious here.
2653 // On some situations, the redirect path is an absolute URL, sometimes a relative path
2654 // For a relative path, let's prefix it with $phpbb_root_path to point to the correct location,
2655 // else we use the URL directly.
2656 $url_parts = @parse_url($redirect);
2659 if ($url_parts !== false && !empty($url_parts['scheme']) && !empty($url_parts['host']))
2661 return str_replace('&', '&', $redirect);
2664 return $phpbb_root_path . str_replace('&', '&', $redirect);
2668 * Meta refresh assignment
2669 * Adds META template variable with meta http tag.
2671 * @param int $time Time in seconds for meta refresh tag
2672 * @param string $url URL to redirect to. The url will go through redirect() first before the template variable is assigned
2673 * @param bool $disable_cd_check If true, meta_refresh() will redirect to an external domain. If false, the redirect point to the boards url if it does not match the current domain. Default is false.
2675 function meta_refresh($time, $url, $disable_cd_check = false)
2679 $url = redirect($url, true, $disable_cd_check);
2680 $url = str_replace('&', '&', $url);
2682 // For XHTML compatibility we change back & to &
2683 $template->assign_vars(array(
2684 'META' => '<meta http-equiv="refresh" content="' . $time . ';url=' . $url . '" />')
2691 * Outputs correct status line header.
2693 * Depending on php sapi one of the two following forms is used:
2695 * Status: 404 Not Found
2697 * HTTP/1.x 404 Not Found
2699 * HTTP version is taken from HTTP_VERSION environment variable,
2700 * and defaults to 1.0.
2704 * send_status_line(404, 'Not Found');
2706 * @param int $code HTTP status code
2707 * @param string $message Message for the status code
2710 function send_status_line($code, $message)
2712 if (substr(strtolower(@php_sapi_name()), 0, 3) === 'cgi')
2714 // in theory, we shouldn't need that due to php doing it. Reality offers a differing opinion, though
2715 header("Status: $code $message", true, $code);
2719 if (!empty($_SERVER['SERVER_PROTOCOL']))
2721 $version = $_SERVER['SERVER_PROTOCOL'];
2725 $version = 'HTTP/1.0';
2727 header("$version $code $message", true, $code);
2735 * Add a secret hash for use in links/GET requests
2736 * @param string $link_name The name of the link; has to match the name used in check_link_hash, otherwise no restrictions apply
2737 * @return string the hash
2740 function generate_link_hash($link_name)
2744 if (!isset($user->data["hash_$link_name"]))
2746 $user->data["hash_$link_name"] = substr(sha1($user->data['user_form_salt'] . $link_name), 0, 8);
2749 return $user->data["hash_$link_name"];
2754 * checks a link hash - for GET requests
2755 * @param string $token the submitted token
2756 * @param string $link_name The name of the link
2757 * @return boolean true if all is fine
2759 function check_link_hash($token, $link_name)
2761 return $token === generate_link_hash($link_name);
2765 * Add a secret token to the form (requires the S_FORM_TOKEN template variable)
2766 * @param string $form_name The name of the form; has to match the name used in check_form_key, otherwise no restrictions apply
2768 function add_form_key($form_name)
2770 global $config, $template, $user;
2773 $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
2774 $token = sha1($now . $user->data['user_form_salt'] . $form_name . $token_sid);
2776 $s_fields = build_hidden_fields(array(
2777 'creation_time' => $now,
2778 'form_token' => $token,
2781 $template->assign_vars(array(
2782 'S_FORM_TOKEN' => $s_fields,
2787 * Check the form key. Required for all altering actions not secured by confirm_box
2788 * @param string $form_name The name of the form; has to match the name used in add_form_key, otherwise no restrictions apply
2789 * @param int $timespan The maximum acceptable age for a submitted form in seconds. Defaults to the config setting.
2790 * @param string $return_page The address for the return link
2791 * @param bool $trigger If true, the function will triger an error when encountering an invalid form
2793 function check_form_key($form_name, $timespan = false, $return_page = '', $trigger = false)
2795 global $config, $user;
2797 if ($timespan === false)
2799 // we enforce a minimum value of half a minute here.
2800 $timespan = ($config['form_token_lifetime'] == -1) ? -1 : max(30, $config['form_token_lifetime']);
2803 if (isset($_POST['creation_time']) && isset($_POST['form_token']))
2805 $creation_time = abs(request_var('creation_time', 0));
2806 $token = request_var('form_token', '');
2808 $diff = time() - $creation_time;
2810 // If creation_time and the time() now is zero we can assume it was not a human doing this (the check for if ($diff)...
2811 if ($diff && ($diff <= $timespan || $timespan === -1))
2813 $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : '';
2814 $key = sha1($creation_time . $user->data['user_form_salt'] . $form_name . $token_sid);
2816 if ($key === $token)
2825 trigger_error($user->lang['FORM_INVALID'] . $return_page);
2831 // Message/Login boxes
2835 * @param boolean $check True for checking if confirmed (without any additional parameters) and false for displaying the confirm box
2836 * @param string $title Title/Message used for confirm box.
2837 * message text is _CONFIRM appended to title.
2838 * If title cannot be found in user->lang a default one is displayed
2839 * If title_CONFIRM cannot be found in user->lang the text given is used.
2840 * @param string $hidden Hidden variables
2841 * @param string $html_body Template used for confirm box
2842 * @param string $u_action Custom form action
2844 function confirm_box($check, $title = '', $hidden = '', $html_body = 'confirm_body.html', $u_action = '')
2846 global $user, $template, $db;
2847 global $phpEx, $phpbb_root_path;
2849 if (isset($_POST['cancel']))
2855 if (isset($_POST['confirm']))
2857 // language frontier
2858 if ($_POST['confirm'] === $user->lang['YES'])
2864 if ($check && $confirm)
2866 $user_id = request_var('confirm_uid', 0);
2867 $session_id = request_var('sess', '');
2868 $confirm_key = request_var('confirm_key', '');
2870 if ($user_id != $user->data['user_id'] || $session_id != $user->session_id || !$confirm_key || !$user->data['user_last_confirm_key'] || $confirm_key != $user->data['user_last_confirm_key'])
2875 // Reset user_last_confirm_key
2876 $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = ''
2877 WHERE user_id = " . $user->data['user_id'];
2878 $db->sql_query($sql);
2887 $s_hidden_fields = build_hidden_fields(array(
2888 'confirm_uid' => $user->data['user_id'],
2889 'sess' => $user->session_id,
2890 'sid' => $user->session_id,
2893 // generate activation key
2894 $confirm_key = gen_rand_string(10);
2896 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
2898 adm_page_header((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]);
2902 page_header(((!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title]), false);
2905 $template->set_filenames(array(
2906 'body' => $html_body)
2909 // If activation key already exist, we better do not re-use the key (something very strange is going on...)
2910 if (request_var('confirm_key', ''))
2912 // This should not occur, therefore we cancel the operation to safe the user
2916 // re-add sid / transform & to & for user->page (user->page is always using &)
2917 $use_page = ($u_action) ? $phpbb_root_path . $u_action : $phpbb_root_path . str_replace('&', '&', $user->page['page']);
2918 $u_action = reapply_sid($use_page);
2919 $u_action .= ((strpos($u_action, '?') === false) ? '?' : '&') . 'confirm_key=' . $confirm_key;
2921 $template->assign_vars(array(
2922 'MESSAGE_TITLE' => (!isset($user->lang[$title])) ? $user->lang['CONFIRM'] : $user->lang[$title],
2923 'MESSAGE_TEXT' => (!isset($user->lang[$title . '_CONFIRM'])) ? $title : $user->lang[$title . '_CONFIRM'],
2925 'YES_VALUE' => $user->lang['YES'],
2926 'S_CONFIRM_ACTION' => $u_action,
2927 'S_HIDDEN_FIELDS' => $hidden . $s_hidden_fields)
2930 $sql = 'UPDATE ' . USERS_TABLE . " SET user_last_confirm_key = '" . $db->sql_escape($confirm_key) . "'
2931 WHERE user_id = " . $user->data['user_id'];
2932 $db->sql_query($sql);
2934 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
2945 * Generate login box or verify password
2947 function login_box($redirect = '', $l_explain = '', $l_success = '', $admin = false, $s_display = true)
2949 global $db, $user, $template, $auth, $phpEx, $phpbb_root_path, $config;
2951 if (!class_exists('phpbb_captcha_factory'))
2953 include($phpbb_root_path . 'includes/captcha/captcha_factory.' . $phpEx);
2958 // Make sure user->setup() has been called
2959 if (empty($user->lang))
2964 // Print out error if user tries to authenticate as an administrator without having the privileges...
2965 if ($admin && !$auth->acl_get('a_'))
2968 // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
2969 if ($user->data['is_registered'])
2971 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2973 trigger_error('NO_AUTH_ADMIN');
2976 if (isset($_POST['login']))
2981 $credential = request_var('credential', '');
2983 if (strspn($credential, 'abcdef0123456789') !== strlen($credential) || strlen($credential) != 32)
2985 if ($user->data['is_registered'])
2987 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
2989 trigger_error('NO_AUTH_ADMIN');
2992 $password = request_var('password_' . $credential, '', true);
2996 $password = request_var('password', '', true);
2999 $username = request_var('username', '', true);
3000 $autologin = (!empty($_POST['autologin'])) ? true : false;
3001 $viewonline = (!empty($_POST['viewonline'])) ? 0 : 1;
3002 $admin = ($admin) ? 1 : 0;
3003 $viewonline = ($admin) ? $user->data['session_viewonline'] : $viewonline;
3005 // Check if the supplied username is equal to the one stored within the database if re-authenticating
3006 if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
3008 // We log the attempt to use a different username...
3009 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
3010 trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
3013 // If authentication is successful we redirect user to previous page
3014 $result = $auth->login($username, $password, $autologin, $viewonline, $admin);
3016 // If admin authentication and login, we will log if it was a success or not...
3017 // We also break the operation on the first non-success login - it could be argued that the user already knows
3020 if ($result['status'] == LOGIN_SUCCESS)
3022 add_log('admin', 'LOG_ADMIN_AUTH_SUCCESS');
3026 // Only log the failed attempt if a real user tried to.
3027 // anonymous/inactive users are never able to go to the ACP even if they have the relevant permissions
3028 if ($user->data['is_registered'])
3030 add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
3035 // The result parameter is always an array, holding the relevant information...
3036 if ($result['status'] == LOGIN_SUCCESS)
3038 $redirect = request_var('redirect', "{$phpbb_root_path}index.$phpEx");
3039 $message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
3040 $l_redirect = ($admin) ? $user->lang['PROCEED_TO_ACP'] : (($redirect === "{$phpbb_root_path}index.$phpEx" || $redirect === "index.$phpEx") ? $user->lang['RETURN_INDEX'] : $user->lang['RETURN_PAGE']);
3042 // append/replace SID (may change during the session for AOL users)
3043 $redirect = reapply_sid($redirect);
3045 // Special case... the user is effectively banned, but we allow founders to login
3046 if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != USER_FOUNDER)
3051 $redirect = meta_refresh(3, $redirect);
3052 trigger_error($message . '<br /><br />' . sprintf($l_redirect, '<a href="' . $redirect . '">', '</a>'));
3055 // Something failed, determine what...
3056 if ($result['status'] == LOGIN_BREAK)
3058 trigger_error($result['error_msg']);
3061 // Special cases... determine
3062 switch ($result['status'])
3064 case LOGIN_ERROR_ATTEMPTS:
3066 $captcha = phpbb_captcha_factory::get_instance($config['captcha_plugin']);
3067 $captcha->init(CONFIRM_LOGIN);
3068 // $captcha->reset();
3070 $template->assign_vars(array(
3071 'CAPTCHA_TEMPLATE' => $captcha->get_template(),
3074 $err = $user->lang[$result['error_msg']];
3077 case LOGIN_ERROR_PASSWORD_CONVERT:
3079 $user->lang[$result['error_msg']],
3080 ($config['email_enable']) ? '<a href="' . append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') . '">' : '',
3081 ($config['email_enable']) ? '</a>' : '',
3082 ($config['board_contact']) ? '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">' : '',
3083 ($config['board_contact']) ? '</a>' : ''
3087 // Username, password, etc...
3089 $err = $user->lang[$result['error_msg']];
3091 // Assign admin contact to some error messages
3092 if ($result['error_msg'] == 'LOGIN_ERROR_USERNAME' || $result['error_msg'] == 'LOGIN_ERROR_PASSWORD')
3094 $err = (!$config['board_contact']) ? sprintf($user->lang[$result['error_msg']], '', '') : sprintf($user->lang[$result['error_msg']], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>');
3101 // Assign credential for username/password pair
3102 $credential = ($admin) ? md5(unique_id()) : false;
3104 $s_hidden_fields = array(
3105 'sid' => $user->session_id,
3110 $s_hidden_fields['redirect'] = $redirect;
3115 $s_hidden_fields['credential'] = $credential;
3118 $s_hidden_fields = build_hidden_fields($s_hidden_fields);
3120 $template->assign_vars(array(
3121 'LOGIN_ERROR' => $err,
3122 'LOGIN_EXPLAIN' => $l_explain,
3124 'U_SEND_PASSWORD' => ($config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=sendpassword') : '',
3125 'U_RESEND_ACTIVATION' => ($config['require_activation'] == USER_ACTIVATION_SELF && $config['email_enable']) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=resend_act') : '',
3126 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
3127 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
3129 'S_DISPLAY_FULL_LOGIN' => ($s_display) ? true : false,
3130 'S_HIDDEN_FIELDS' => $s_hidden_fields,
3132 'S_ADMIN_AUTH' => $admin,
3133 'USERNAME' => ($admin) ? $user->data['username'] : '',
3135 'USERNAME_CREDENTIAL' => 'username',
3136 'PASSWORD_CREDENTIAL' => ($admin) ? 'password_' . $credential : 'password',
3139 page_header($user->lang['LOGIN'], false);
3141 $template->set_filenames(array(
3142 'body' => 'login_body.html')
3144 make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"));
3150 * Generate forum login box
3152 function login_forum_box($forum_data)
3154 global $db, $config, $user, $template, $phpEx;
3156 $password = request_var('password', '', true);
3158 $sql = 'SELECT forum_id
3159 FROM ' . FORUMS_ACCESS_TABLE . '
3160 WHERE forum_id = ' . $forum_data['forum_id'] . '
3161 AND user_id = ' . $user->data['user_id'] . "
3162 AND session_id = '" . $db->sql_escape($user->session_id) . "'";
3163 $result = $db->sql_query($sql);
3164 $row = $db->sql_fetchrow($result);
3165 $db->sql_freeresult($result);
3174 // Remove expired authorised sessions
3175 $sql = 'SELECT f.session_id
3176 FROM ' . FORUMS_ACCESS_TABLE . ' f
3177 LEFT JOIN ' . SESSIONS_TABLE . ' s ON (f.session_id = s.session_id)
3178 WHERE s.session_id IS NULL';
3179 $result = $db->sql_query($sql);
3181 if ($row = $db->sql_fetchrow($result))
3186 $sql_in[] = (string) $row['session_id'];
3188 while ($row = $db->sql_fetchrow($result));
3190 // Remove expired sessions
3191 $sql = 'DELETE FROM ' . FORUMS_ACCESS_TABLE . '
3192 WHERE ' . $db->sql_in_set('session_id', $sql_in);
3193 $db->sql_query($sql);
3195 $db->sql_freeresult($result);
3197 if (phpbb_check_hash($password, $forum_data['forum_password']))
3200 'forum_id' => (int) $forum_data['forum_id'],
3201 'user_id' => (int) $user->data['user_id'],
3202 'session_id' => (string) $user->session_id,
3205 $db->sql_query('INSERT INTO ' . FORUMS_ACCESS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
3210 $template->assign_var('LOGIN_ERROR', $user->lang['WRONG_PASSWORD']);
3213 page_header($user->lang['LOGIN'], false);
3215 $template->assign_vars(array(
3216 'S_LOGIN_ACTION' => build_url(array('f')),
3217 'S_HIDDEN_FIELDS' => build_hidden_fields(array('f' => $forum_data['forum_id'])))
3220 $template->set_filenames(array(
3221 'body' => 'login_forum.html')
3230 * Little helper for the build_hidden_fields function
3232 function _build_hidden_fields($key, $value, $specialchar, $stripslashes)
3234 $hidden_fields = '';
3236 if (!is_array($value))
3238 $value = ($stripslashes) ? stripslashes($value) : $value;
3239 $value = ($specialchar) ? htmlspecialchars($value, ENT_COMPAT, 'UTF-8') : $value;
3241 $hidden_fields .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />' . "\n";
3245 foreach ($value as $_key => $_value)
3247 $_key = ($stripslashes) ? stripslashes($_key) : $_key;
3248 $_key = ($specialchar) ? htmlspecialchars($_key, ENT_COMPAT, 'UTF-8') : $_key;
3250 $hidden_fields .= _build_hidden_fields($key . '[' . $_key . ']', $_value, $specialchar, $stripslashes);
3254 return $hidden_fields;
3258 * Build simple hidden fields from array
3260 * @param array $field_ary an array of values to build the hidden field from
3261 * @param bool $specialchar if true, keys and values get specialchared
3262 * @param bool $stripslashes if true, keys and values get stripslashed
3264 * @return string the hidden fields
3266 function build_hidden_fields($field_ary, $specialchar = false, $stripslashes = false)
3268 $s_hidden_fields = '';
3270 foreach ($field_ary as $name => $vars)
3272 $name = ($stripslashes) ? stripslashes($name) : $name;
3273 $name = ($specialchar) ? htmlspecialchars($name, ENT_COMPAT, 'UTF-8') : $name;
3275 $s_hidden_fields .= _build_hidden_fields($name, $vars, $specialchar, $stripslashes);
3278 return $s_hidden_fields;
3284 function parse_cfg_file($filename, $lines = false)
3286 $parsed_items = array();
3288 if ($lines === false)
3290 $lines = file($filename);
3293 foreach ($lines as $line)
3295 $line = trim($line);
3297 if (!$line || $line[0] == '#' || ($delim_pos = strpos($line, '=')) === false)
3302 // Determine first occurrence, since in values the equal sign is allowed
3303 $key = strtolower(trim(substr($line, 0, $delim_pos)));
3304 $value = trim(substr($line, $delim_pos + 1));
3306 if (in_array($value, array('off', 'false', '0')))
3310 else if (in_array($value, array('on', 'true', '1')))
3314 else if (!trim($value))
3318 else if (($value[0] == "'" && $value[sizeof($value) - 1] == "'") || ($value[0] == '"' && $value[sizeof($value) - 1] == '"'))
3320 $value = substr($value, 1, sizeof($value)-2);
3323 $parsed_items[$key] = $value;
3326 return $parsed_items;
3336 // In phpBB 3.1.x i want to have logging in a class to be able to control it
3337 // For now, we need a quite hakish approach to circumvent logging for some actions
3338 // @todo implement cleanly
3339 if (!empty($GLOBALS['skip_add_log']))
3344 $args = func_get_args();
3346 $mode = array_shift($args);
3347 $reportee_id = ($mode == 'user') ? intval(array_shift($args)) : '';
3348 $forum_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
3349 $topic_id = ($mode == 'mod') ? intval(array_shift($args)) : '';
3350 $action = array_shift($args);
3351 $data = (!sizeof($args)) ? '' : serialize($args);
3354 'user_id' => (empty($user->data)) ? ANONYMOUS : $user->data['user_id'],
3355 'log_ip' => $user->ip,
3356 'log_time' => time(),
3357 'log_operation' => $action,
3358 'log_data' => $data,
3364 $sql_ary['log_type'] = LOG_ADMIN;
3369 'log_type' => LOG_MOD,
3370 'forum_id' => $forum_id,
3371 'topic_id' => $topic_id
3377 'log_type' => LOG_USERS,
3378 'reportee_id' => $reportee_id
3383 $sql_ary['log_type'] = LOG_CRITICAL;
3390 $db->sql_query('INSERT INTO ' . LOG_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
3392 return $db->sql_nextid();
3396 * Return a nicely formatted backtrace.
3398 * Turns the array returned by debug_backtrace() into HTML markup.
3399 * Also filters out absolute paths to phpBB root.
3401 * @return string HTML markup
3403 function get_backtrace()
3405 $output = '<div style="font-family: monospace;">';
3406 $backtrace = debug_backtrace();
3408 // We skip the first one, because it only shows this file/function
3409 unset($backtrace[0]);
3411 foreach ($backtrace as $trace)
3413 // Strip the current directory from path
3414 $trace['file'] = (empty($trace['file'])) ? '(not given by php)' : htmlspecialchars(phpbb_filter_root_path($trace['file']));
3415 $trace['line'] = (empty($trace['line'])) ? '(not given by php)' : $trace['line'];
3417 // Only show function arguments for include etc.
3418 // Other parameters may contain sensible information
3420 if (!empty($trace['args'][0]) && in_array($trace['function'], array('include', 'require', 'include_once', 'require_once')))
3422 $argument = htmlspecialchars(phpbb_filter_root_path($trace['args'][0]));
3425 $trace['class'] = (!isset($trace['class'])) ? '' : $trace['class'];
3426 $trace['type'] = (!isset($trace['type'])) ? '' : $trace['type'];
3428 $output .= '<br />';
3429 $output .= '<b>FILE:</b> ' . $trace['file'] . '<br />';
3430 $output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
3432 $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']);
3433 $output .= '(' . (($argument !== '') ? "'$argument'" : '') . ')<br />';
3435 $output .= '</div>';
3440 * This function returns a regular expression pattern for commonly used expressions
3441 * Use with / as delimiter for email mode and # for url modes
3442 * mode can be: email|bbcode_htm|url|url_inline|www_url|www_url_inline|relative_url|relative_url_inline|ipv4|ipv6
3444 function get_preg_expression($mode)
3449 // Regex written by James Watts and Francisco Jose Martin Moreno
3450 // http://fightingforalostcause.net/misc/2006/compare-email-regex.php
3451 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})?)';
3456 '#<!\-\- e \-\-><a href="mailto:(.*?)">.*?</a><!\-\- e \-\->#',
3457 '#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
3458 '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
3459 '#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
3460 '#<!\-\- .*? \-\->#s',
3465 // Whoa these look impressive!
3466 // The code to generate the following two regular expressions which match valid IPv4/IPv6 addresses
3467 // can be found in the develop directory
3469 return '#^(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$#';
3473 return '#^(?:(?:(?:[\dA-F]{1,4}:){6}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:::(?:[\dA-F]{1,4}:){0,5}(?:[\dA-F]{1,4}(?::[\dA-F]{1,4})?|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:):(?:[\dA-F]{1,4}:){4}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,2}:(?:[\dA-F]{1,4}:){3}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,3}:(?:[\dA-F]{1,4}:){2}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,4}:(?:[\dA-F]{1,4}:)(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,5}:(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,6}:[\dA-F]{1,4})|(?:(?:[\dA-F]{1,4}:){1,7}:)|(?:::))$#i';
3478 $inline = ($mode == 'url') ? ')' : '';
3479 $scheme = ($mode == 'url') ? '[a-z\d+\-.]' : '[a-z\d+]'; // avoid automatic parsing of "word" in "last word.http://..."
3480 // generated with regex generation file in the develop folder
3481 return "[a-z]$scheme*:/{2}(?:(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})+|[0-9.]+|\[[a-z0-9.]+:[a-z0-9.]+:[a-z0-9.:]+\])(?::\d*)?(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
3485 case 'www_url_inline':
3486 $inline = ($mode == 'www_url') ? ')' : '';
3487 return "www\.(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})+(?::\d*)?(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
3490 case 'relative_url':
3491 case 'relative_url_inline':
3492 $inline = ($mode == 'relative_url') ? ')' : '';
3493 return "(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*(?:/(?:[a-z0-9\-._~!$&'($inline*+,;=:@|]+|%[\dA-F]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'($inline*+,;=:@/?|]+|%[\dA-F]{2})*)?";
3496 case 'table_prefix':
3497 return '#^[a-zA-Z][a-zA-Z0-9_]*$#';
3505 * Generate regexp for naughty words censoring
3506 * Depends on whether installed PHP version supports unicode properties
3508 * @param string $word word template to be replaced
3509 * @param bool $use_unicode whether or not to take advantage of PCRE supporting unicode
3511 * @return string $preg_expr regex to use with word censor
3513 function get_censor_preg_expression($word, $use_unicode = true)
3515 static $unicode_support = null;
3517 // Check whether PHP version supports unicode properties
3518 if (is_null($unicode_support))
3520 $unicode_support = ((version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>='))) && @preg_match('/\p{L}/u', 'a') !== false) ? true : false;
3523 // Unescape the asterisk to simplify further conversions
3524 $word = str_replace('\*', '*', preg_quote($word, '#'));
3526 if ($use_unicode && $unicode_support)
3528 // Replace asterisk(s) inside the pattern, at the start and at the end of it with regexes
3529 $word = preg_replace(array('#(?<=[\p{Nd}\p{L}_])\*+(?=[\p{Nd}\p{L}_])#iu', '#^\*+#', '#\*+$#'), array('([\x20]*?|[\p{Nd}\p{L}_-]*?)', '[\p{Nd}\p{L}_-]*?', '[\p{Nd}\p{L}_-]*?'), $word);
3531 // Generate the final substitution
3532 $preg_expr = '#(?<![\p{Nd}\p{L}_-])(' . $word . ')(?![\p{Nd}\p{L}_-])#iu';
3536 // Replace the asterisk inside the pattern, at the start and at the end of it with regexes
3537 $word = preg_replace(array('#(?<=\S)\*+(?=\S)#iu', '#^\*+#', '#\*+$#'), array('(\x20*?\S*?)', '\S*?', '\S*?'), $word);
3539 // Generate the final substitution
3540 $preg_expr = '#(?<!\S)(' . $word . ')(?!\S)#iu';
3547 * Returns the first block of the specified IPv6 address and as many additional
3548 * ones as specified in the length paramater.
3549 * If length is zero, then an empty string is returned.
3550 * If length is greater than 3 the complete IP will be returned
3552 function short_ipv6($ip, $length)
3559 // extend IPv6 addresses
3560 $blocks = substr_count($ip, ':') + 1;
3563 $ip = str_replace('::', ':' . str_repeat('0000:', 9 - $blocks), $ip);
3571 $ip = implode(':', array_slice(explode(':', $ip), 0, 1 + $length));
3578 * Wrapper for php's checkdnsrr function.
3580 * @param string $host Fully-Qualified Domain Name
3581 * @param string $type Resource record type to lookup
3582 * Supported types are: MX (default), A, AAAA, NS, TXT, CNAME
3583 * Other types may work or may not work
3585 * @return mixed true if entry found,
3586 * false if entry not found,
3587 * null if this function is not supported by this environment
3589 * Since null can also be returned, you probably want to compare the result
3590 * with === true or === false,
3594 function phpbb_checkdnsrr($host, $type = 'MX')
3596 // The dot indicates to search the DNS root (helps those having DNS prefixes on the same domain)
3597 if (substr($host, -1) == '.')
3600 $host = substr($host, 0, -1);
3604 $host_fqdn = $host . '.';
3606 // $host has format some.host.example.com
3607 // $host_fqdn has format some.host.example.com.
3609 // If we're looking for an A record we can use gethostbyname()
3610 if ($type == 'A' && function_exists('gethostbyname'))
3612 return (@gethostbyname($host_fqdn) == $host_fqdn) ? false : true;
3615 // checkdnsrr() is available on Windows since PHP 5.3,
3616 // but until 5.3.3 it only works for MX records
3617 // See: http://bugs.php.net/bug.php?id=51844
3619 // Call checkdnsrr() if
3620 // we're looking for an MX record or
3621 // we're not on Windows or
3622 // we're running a PHP version where #51844 has been fixed
3624 // checkdnsrr() supports AAAA since 5.0.0
3625 // checkdnsrr() supports TXT since 5.2.4
3627 ($type == 'MX' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.3', '>=')) &&
3628 ($type != 'AAAA' || version_compare(PHP_VERSION, '5.0.0', '>=')) &&
3629 ($type != 'TXT' || version_compare(PHP_VERSION, '5.2.4', '>=')) &&
3630 function_exists('checkdnsrr')
3633 return checkdnsrr($host_fqdn, $type);
3636 // dns_get_record() is available since PHP 5; since PHP 5.3 also on Windows,
3637 // but on Windows it does not work reliable for AAAA records before PHP 5.3.1
3639 // Call dns_get_record() if
3640 // we're not looking for an AAAA record or
3641 // we're not on Windows or
3642 // we're running a PHP version where AAAA lookups work reliable
3644 ($type != 'AAAA' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.1', '>=')) &&
3645 function_exists('dns_get_record')
3648 // dns_get_record() expects an integer as second parameter
3649 // We have to convert the string $type to the corresponding integer constant.
3650 $type_constant = 'DNS_' . $type;
3651 $type_param = (defined($type_constant)) ? constant($type_constant) : DNS_ANY;
3653 // dns_get_record() might throw E_WARNING and return false for records that do not exist
3654 $resultset = @dns_get_record($host_fqdn, $type_param);
3656 if (empty($resultset) || !is_array($resultset))
3660 else if ($type_param == DNS_ANY)
3662 // $resultset is a non-empty array
3666 foreach ($resultset as $result)
3669 isset($result['host']) && $result['host'] == $host &&
3670 isset($result['type']) && $result['type'] == $type
3680 // If we're on Windows we can still try to call nslookup via exec() as a last resort
3681 if (DIRECTORY_SEPARATOR == '\\' && function_exists('exec'))
3683 @exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host_fqdn), $output);
3685 // If output is empty, the nslookup failed
3691 foreach ($output as $line)
3693 $line = trim($line);
3700 // Squash tabs and multiple whitespaces to a single whitespace.
3701 $line = preg_replace('/\s+/', ' ', $line);
3706 if (stripos($line, "$host MX") === 0)
3713 if (stripos($line, "$host nameserver") === 0)
3720 if (stripos($line, "$host text") === 0)
3727 if (stripos($line, "$host canonical name") === 0)
3735 // AAAA records returned by nslookup on Windows XP/2003 have this format.
3736 // Later Windows versions use the A record format below for AAAA records.
3737 if (stripos($line, "$host AAAA IPv6 address") === 0)
3744 if (!empty($host_matches))
3747 if (stripos($line, "Address: ") === 0)
3753 $host_matches = false;
3756 else if (stripos($line, "Name: $host") === 0)
3759 $host_matches = true;
3771 // Handler, header and footer
3774 * Error and message handler, call with trigger_error if reqd
3776 function msg_handler($errno, $msg_text, $errfile, $errline)
3778 global $cache, $db, $auth, $template, $config, $user;
3779 global $phpEx, $phpbb_root_path, $msg_title, $msg_long_text;
3781 // Do not display notices if we suppress them via @
3782 if (error_reporting() == 0 && $errno != E_USER_ERROR && $errno != E_USER_WARNING && $errno != E_USER_NOTICE)
3787 // Message handler is stripping text. In case we need it, we are possible to define long text...
3788 if (isset($msg_long_text) && $msg_long_text && !$msg_text)
3790 $msg_text = $msg_long_text;
3793 if (!defined('E_DEPRECATED'))
3795 define('E_DEPRECATED', 8192);
3803 // Check the error reporting level and return if the error level does not match
3804 // If DEBUG is defined the default level is E_ALL
3805 if (($errno & ((defined('DEBUG')) ? E_ALL : error_reporting())) == 0)
3810 if (strpos($errfile, 'cache') === false && strpos($errfile, 'template.') === false)
3812 $errfile = phpbb_filter_root_path($errfile);
3813 $msg_text = phpbb_filter_root_path($msg_text);
3814 $error_name = ($errno === E_WARNING) ? 'PHP Warning' : 'PHP Notice';
3815 echo '<b>[phpBB Debug] ' . $error_name . '</b>: in file <b>' . $errfile . '</b> on line <b>' . $errline . '</b>: <b>' . $msg_text . '</b><br />' . "\n";
3817 // we are writing an image - the user won't see the debug, so let's place it in the log
3818 if (defined('IMAGE_OUTPUT') || defined('IN_CRON'))
3820 add_log('critical', 'LOG_IMAGE_GENERATION_ERROR', $errfile, $errline, $msg_text);
3822 // echo '<br /><br />BACKTRACE<br />' . get_backtrace() . '<br />' . "\n";
3831 if (!empty($user) && !empty($user->lang))
3833 $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
3834 $msg_title = (!isset($msg_title)) ? $user->lang['GENERAL_ERROR'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
3836 $l_return_index = sprintf($user->lang['RETURN_INDEX'], '<a href="' . $phpbb_root_path . '">', '</a>');
3839 if (!empty($config['board_contact']))
3841 $l_notify = '<p>' . sprintf($user->lang['NOTIFY_ADMIN_EMAIL'], $config['board_contact']) . '</p>';
3846 $msg_title = 'General Error';
3847 $l_return_index = '<a href="' . $phpbb_root_path . '">Return to index page</a>';
3850 if (!empty($config['board_contact']))
3852 $l_notify = '<p>Please notify the board administrator or webmaster: <a href="mailto:' . $config['board_contact'] . '">' . $config['board_contact'] . '</a></p>';
3856 if ((defined('DEBUG') || defined('IN_CRON') || defined('IMAGE_OUTPUT')) && isset($db))
3858 // let's avoid loops
3859 $db->sql_return_on_error(true);
3860 add_log('critical', 'LOG_GENERAL_ERROR', $msg_title, $msg_text);
3861 $db->sql_return_on_error(false);
3864 // Do not send 200 OK, but service unavailable on errors
3865 send_status_line(503, 'Service Unavailable');
3867 garbage_collection();
3869 // Try to not call the adm page data...
3871 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
3872 echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
3874 echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
3875 echo '<title>' . $msg_title . '</title>';
3876 echo '<style type="text/css">' . "\n" . '/* <![CDATA[ */' . "\n";
3877 echo '* { margin: 0; padding: 0; } html { font-size: 100%; height: 100%; margin-bottom: 1px; background-color: #E4EDF0; } body { font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif; color: #536482; background: #E4EDF0; font-size: 62.5%; margin: 0; } ';
3878 echo 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
3879 echo '#wrap { padding: 0 20px 15px 20px; min-width: 615px; } #page-header { text-align: right; height: 40px; } #page-footer { clear: both; font-size: 1em; text-align: center; } ';
3880 echo '.panel { margin: 4px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
3881 echo '#errorpage #page-header a { font-weight: bold; line-height: 6em; } #errorpage #content { padding: 10px; } #errorpage #content h1 { line-height: 1.2em; margin-bottom: 0; color: #DF075C; } ';
3882 echo '#errorpage #content div { margin-top: 20px; margin-bottom: 5px; border-bottom: 1px solid #CCCCCC; padding-bottom: 5px; color: #333333; font: bold 1.2em "Lucida Grande", Arial, Helvetica, sans-serif; text-decoration: none; line-height: 120%; text-align: left; } ';
3883 echo "\n" . '/* ]]> */' . "\n";
3886 echo '<body id="errorpage">';
3887 echo '<div id="wrap">';
3888 echo ' <div id="page-header">';
3889 echo ' ' . $l_return_index;
3891 echo ' <div id="acp">';
3892 echo ' <div class="panel">';
3893 echo ' <div id="content">';
3894 echo ' <h1>' . $msg_title . '</h1>';
3896 echo ' <div>' . $msg_text . '</div>';
3903 echo ' <div id="page-footer">';
3904 echo ' Powered by <a href="http://www.phpbb.com/">phpBB</a>® Forum Software © phpBB Group';
3912 // On a fatal error (and E_USER_ERROR *is* fatal) we never want other scripts to continue and force an exit here.
3916 case E_USER_WARNING:
3919 define('IN_ERROR_HANDLER', true);
3921 if (empty($user->data))
3923 $user->session_begin();
3926 // We re-init the auth array to get correct results on login/logout
3927 $auth->acl($user->data);
3929 if (empty($user->lang))
3934 if ($msg_text == 'ERROR_NO_ATTACHMENT' || $msg_text == 'NO_FORUM' || $msg_text == 'NO_TOPIC' || $msg_text == 'NO_USER')
3936 send_status_line(404, 'Not Found');
3939 $msg_text = (!empty($user->lang[$msg_text])) ? $user->lang[$msg_text] : $msg_text;
3940 $msg_title = (!isset($msg_title)) ? $user->lang['INFORMATION'] : ((!empty($user->lang[$msg_title])) ? $user->lang[$msg_title] : $msg_title);
3942 if (!defined('HEADER_INC'))
3944 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
3946 adm_page_header($msg_title);
3950 page_header($msg_title, false);
3954 $template->set_filenames(array(
3955 'body' => 'message_body.html')
3958 $template->assign_vars(array(
3959 'MESSAGE_TITLE' => $msg_title,
3960 'MESSAGE_TEXT' => $msg_text,
3961 'S_USER_WARNING' => ($errno == E_USER_WARNING) ? true : false,
3962 'S_USER_NOTICE' => ($errno == E_USER_NOTICE) ? true : false)
3965 // We do not want the cron script to be called on error messages
3966 define('IN_CRON', true);
3968 if (defined('IN_ADMIN') && isset($user->data['session_admin']) && $user->data['session_admin'])
3980 // PHP4 compatibility
3986 // If we notice an error not handled here we pass this back to PHP by returning false
3987 // This may not work for all php versions
3992 * Removes absolute path to phpBB root directory from error messages
3993 * and converts backslashes to forward slashes.
3995 * @param string $errfile Absolute file path
3996 * (e.g. /var/www/phpbb3/phpBB/includes/functions.php)
3997 * Please note that if $errfile is outside of the phpBB root,
3998 * the root path will not be found and can not be filtered.
3999 * @return string Relative file path
4000 * (e.g. /includes/functions.php)
4002 function phpbb_filter_root_path($errfile)
4006 if (empty($root_path))
4008 $root_path = phpbb_realpath(dirname(__FILE__) . '/../');
4011 return str_replace(array($root_path, '\\'), array('[ROOT]', '/'), $errfile);
4015 * Queries the session table to get information about online guests
4016 * @param int $item_id Limits the search to the item with this id
4017 * @param string $item The name of the item which is stored in the session table as session_{$item}_id
4018 * @return int The number of active distinct guest sessions
4020 function obtain_guest_count($item_id = 0, $item = 'forum')
4022 global $db, $config;
4026 $reading_sql = ' AND s.session_' . $item . '_id = ' . (int) $item_id;
4032 $time = (time() - (intval($config['load_online_time']) * 60));
4034 // Get number of online guests
4036 if ($db->sql_layer === 'sqlite')
4038 $sql = 'SELECT COUNT(session_ip) as num_guests
4040 SELECT DISTINCT s.session_ip
4041 FROM ' . SESSIONS_TABLE . ' s
4042 WHERE s.session_user_id = ' . ANONYMOUS . '
4043 AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
4049 $sql = 'SELECT COUNT(DISTINCT s.session_ip) as num_guests
4050 FROM ' . SESSIONS_TABLE . ' s
4051 WHERE s.session_user_id = ' . ANONYMOUS . '
4052 AND s.session_time >= ' . ($time - ((int) ($time % 60))) .
4055 $result = $db->sql_query($sql);
4056 $guests_online = (int) $db->sql_fetchfield('num_guests');
4057 $db->sql_freeresult($result);
4059 return $guests_online;
4063 * Queries the session table to get information about online users
4064 * @param int $item_id Limits the search to the item with this id
4065 * @param string $item The name of the item which is stored in the session table as session_{$item}_id
4066 * @return array An array containing the ids of online, hidden and visible users, as well as statistical info
4068 function obtain_users_online($item_id = 0, $item = 'forum')
4070 global $db, $config, $user;
4075 $reading_sql = ' AND s.session_' . $item . '_id = ' . (int) $item_id;
4078 $online_users = array(
4079 'online_users' => array(),
4080 'hidden_users' => array(),
4081 'total_online' => 0,
4082 'visible_online' => 0,
4083 'hidden_online' => 0,
4084 'guests_online' => 0,
4087 if ($config['load_online_guests'])
4089 $online_users['guests_online'] = obtain_guest_count($item_id, $item);
4092 // a little discrete magic to cache this for 30 seconds
4093 $time = (time() - (intval($config['load_online_time']) * 60));
4095 $sql = 'SELECT s.session_user_id, s.session_ip, s.session_viewonline
4096 FROM ' . SESSIONS_TABLE . ' s
4097 WHERE s.session_time >= ' . ($time - ((int) ($time % 30))) .
4099 ' AND s.session_user_id <> ' . ANONYMOUS;
4100 $result = $db->sql_query($sql);
4102 while ($row = $db->sql_fetchrow($result))
4104 // Skip multiple sessions for one user
4105 if (!isset($online_users['online_users'][$row['session_user_id']]))
4107 $online_users['online_users'][$row['session_user_id']] = (int) $row['session_user_id'];
4108 if ($row['session_viewonline'])
4110 $online_users['visible_online']++;
4114 $online_users['hidden_users'][$row['session_user_id']] = (int) $row['session_user_id'];
4115 $online_users['hidden_online']++;
4119 $online_users['total_online'] = $online_users['guests_online'] + $online_users['visible_online'] + $online_users['hidden_online'];
4120 $db->sql_freeresult($result);
4122 return $online_users;
4126 * Uses the result of obtain_users_online to generate a localized, readable representation.
4127 * @param mixed $online_users result of obtain_users_online - array with user_id lists for total, hidden and visible users, and statistics
4128 * @param int $item_id Indicate that the data is limited to one item and not global
4129 * @param string $item The name of the item which is stored in the session table as session_{$item}_id
4130 * @return array An array containing the string for output to the template
4132 function obtain_users_online_string($online_users, $item_id = 0, $item = 'forum')
4134 global $config, $db, $user, $auth;
4136 $user_online_link = $online_userlist = '';
4137 // Need caps version of $item for language-strings
4138 $item_caps = strtoupper($item);
4140 if (sizeof($online_users['online_users']))
4142 $sql = 'SELECT username, username_clean, user_id, user_type, user_allow_viewonline, user_colour
4143 FROM ' . USERS_TABLE . '
4144 WHERE ' . $db->sql_in_set('user_id', $online_users['online_users']) . '
4145 ORDER BY username_clean ASC';
4146 $result = $db->sql_query($sql);
4148 while ($row = $db->sql_fetchrow($result))
4150 // User is logged in and therefore not a guest
4151 if ($row['user_id'] != ANONYMOUS)
4153 if (isset($online_users['hidden_users'][$row['user_id']]))
4155 $row['username'] = '<em>' . $row['username'] . '</em>';
4158 if (!isset($online_users['hidden_users'][$row['user_id']]) || $auth->acl_get('u_viewonline'))
4160 $user_online_link = get_username_string(($row['user_type'] <> USER_IGNORE) ? 'full' : 'no_profile', $row['user_id'], $row['username'], $row['user_colour']);
4161 $online_userlist .= ($online_userlist != '') ? ', ' . $user_online_link : $user_online_link;
4165 $db->sql_freeresult($result);
4168 if (!$online_userlist)
4170 $online_userlist = $user->lang['NO_ONLINE_USERS'];
4175 $online_userlist = $user->lang['REGISTERED_USERS'] . ' ' . $online_userlist;
4177 else if ($config['load_online_guests'])
4179 $l_online = ($online_users['guests_online'] === 1) ? $user->lang['BROWSING_' . $item_caps . '_GUEST'] : $user->lang['BROWSING_' . $item_caps . '_GUESTS'];
4180 $online_userlist = sprintf($l_online, $online_userlist, $online_users['guests_online']);
4184 $online_userlist = sprintf($user->lang['BROWSING_' . $item_caps], $online_userlist);
4186 // Build online listing
4187 $vars_online = array(
4188 'ONLINE' => array('total_online', 'l_t_user_s', 0),
4189 'REG' => array('visible_online', 'l_r_user_s', !$config['load_online_guests']),
4190 'HIDDEN' => array('hidden_online', 'l_h_user_s', $config['load_online_guests']),
4191 'GUEST' => array('guests_online', 'l_g_user_s', 0)
4194 foreach ($vars_online as $l_prefix => $var_ary)
4204 switch ($online_users[$var_ary[0]])
4207 ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_ZERO_TOTAL' . $l_suffix];
4211 ${$var_ary[1]} = $user->lang[$l_prefix . '_USER_TOTAL' . $l_suffix];
4215 ${$var_ary[1]} = $user->lang[$l_prefix . '_USERS_TOTAL' . $l_suffix];
4219 unset($vars_online);
4221 $l_online_users = sprintf($l_t_user_s, $online_users['total_online']);
4222 $l_online_users .= sprintf($l_r_user_s, $online_users['visible_online']);
4223 $l_online_users .= sprintf($l_h_user_s, $online_users['hidden_online']);
4225 if ($config['load_online_guests'])
4227 $l_online_users .= sprintf($l_g_user_s, $online_users['guests_online']);
4233 'online_userlist' => $online_userlist,
4234 'l_online_users' => $l_online_users,
4239 * Get option bitfield from custom data
4241 * @param int $bit The bit/value to get
4242 * @param int $data Current bitfield to check
4243 * @return bool Returns true if value of constant is set in bitfield, else false
4245 function phpbb_optionget($bit, $data)
4247 return ($data & 1 << (int) $bit) ? true : false;
4251 * Set option bitfield
4253 * @param int $bit The bit/value to set/unset
4254 * @param bool $set True if option should be set, false if option should be unset.
4255 * @param int $data Current bitfield to change
4257 * @return int The new bitfield
4259 function phpbb_optionset($bit, $set, $data)
4261 if ($set && !($data & 1 << $bit))
4265 else if (!$set && ($data & 1 << $bit))
4274 * Login using http authenticate.
4276 * @param array $param Parameter array, see $param_defaults array.
4280 function phpbb_http_login($param)
4282 global $auth, $user;
4285 $param_defaults = array(
4286 'auth_message' => '',
4288 'autologin' => false,
4289 'viewonline' => true,
4293 // Overwrite default values with passed values
4294 $param = array_merge($param_defaults, $param);
4296 // User is already logged in
4297 // We will not overwrite his session
4298 if (!empty($user->data['is_registered']))
4303 // $_SERVER keys to check
4304 $username_keys = array(
4307 'REMOTE_USER', 'REDIRECT_REMOTE_USER',
4308 'HTTP_AUTHORIZATION', 'REDIRECT_HTTP_AUTHORIZATION',
4309 'REMOTE_AUTHORIZATION', 'REDIRECT_REMOTE_AUTHORIZATION',
4313 $password_keys = array(
4320 foreach ($username_keys as $k)
4322 if (isset($_SERVER[$k]))
4324 $username = $_SERVER[$k];
4330 foreach ($password_keys as $k)
4332 if (isset($_SERVER[$k]))
4334 $password = $_SERVER[$k];
4339 // Decode encoded information (IIS, CGI, FastCGI etc.)
4340 if (!is_null($username) && is_null($password) && strpos($username, 'Basic ') === 0)
4342 list($username, $password) = explode(':', base64_decode(substr($username, 6)), 2);
4345 if (!is_null($username) && !is_null($password))
4347 set_var($username, $username, 'string', true);
4348 set_var($password, $password, 'string', true);
4350 $auth_result = $auth->login($username, $password, $param['autologin'], $param['viewonline'], $param['admin']);
4352 if ($auth_result['status'] == LOGIN_SUCCESS)
4356 else if ($auth_result['status'] == LOGIN_ERROR_ATTEMPTS)
4358 send_status_line(401, 'Unauthorized');
4360 trigger_error('NOT_AUTHORISED');
4364 // Prepend sitename to auth_message
4365 $param['auth_message'] = ($param['auth_message'] === '') ? $config['sitename'] : $config['sitename'] . ' - ' . $param['auth_message'];
4367 // We should probably filter out non-ASCII characters - RFC2616
4368 $param['auth_message'] = preg_replace('/[\x80-\xFF]/', '?', $param['auth_message']);
4370 header('WWW-Authenticate: Basic realm="' . $param['auth_message'] . '"');
4371 send_status_line(401, 'Unauthorized');
4373 trigger_error('NOT_AUTHORISED');
4377 * Generate page header
4379 function page_header($page_title = '', $display_online_list = true, $item_id = 0, $item = 'forum')
4381 global $db, $config, $template, $SID, $_SID, $_EXTRA_URL, $user, $auth, $phpEx, $phpbb_root_path;
4383 if (defined('HEADER_INC'))
4388 define('HEADER_INC', true);
4391 if ($config['gzip_compress'])
4393 // to avoid partially compressed output resulting in blank pages in
4394 // the browser or error messages, compression is disabled in a few cases:
4396 // 1) if headers have already been sent, this indicates plaintext output
4397 // has been started so further content must not be compressed
4398 // 2) the length of the current output buffer is non-zero. This means
4399 // there is already some uncompressed content in this output buffer
4400 // so further output must not be compressed
4401 // 3) if more than one level of output buffering is used because we
4402 // cannot test all output buffer level content lengths. One level
4403 // could be caused by php.ini output_buffering. Anything
4404 // beyond that is manual, so the code wrapping phpBB in output buffering
4405 // can easily compress the output itself.
4407 if (@extension_loaded('zlib') && !headers_sent() && ob_get_level() <= 1 && ob_get_length() == 0)
4409 ob_start('ob_gzhandler');
4413 // Generate logged in/logged out status
4414 if ($user->data['user_id'] != ANONYMOUS)
4416 $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=logout', true, $user->session_id);
4417 $l_login_logout = sprintf($user->lang['LOGOUT_USER'], $user->data['username']);
4421 $u_login_logout = append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login');
4422 $l_login_logout = $user->lang['LOGIN'];
4425 // Last visit date/time
4426 $s_last_visit = ($user->data['user_id'] != ANONYMOUS) ? $user->format_date($user->data['session_last_visit']) : '';
4428 // Get users online list ... if required
4429 $l_online_users = $online_userlist = $l_online_record = $l_online_time = '';
4431 if ($config['load_online'] && $config['load_online_time'] && $display_online_list)
4435 * For obtaining another session column use $item and $item_id in the function-parameter, whereby the column is session_{$item}_id.
4437 $item_id = max($item_id, 0);
4439 $online_users = obtain_users_online($item_id, $item);
4440 $user_online_strings = obtain_users_online_string($online_users, $item_id, $item);
4442 $l_online_users = $user_online_strings['l_online_users'];
4443 $online_userlist = $user_online_strings['online_userlist'];
4444 $total_online_users = $online_users['total_online'];
4446 if ($total_online_users > $config['record_online_users'])
4448 set_config('record_online_users', $total_online_users, true);
4449 set_config('record_online_date', time(), true);
4452 $l_online_record = sprintf($user->lang['RECORD_ONLINE_USERS'], $config['record_online_users'], $user->format_date($config['record_online_date'], false, true));
4454 $l_online_time = ($config['load_online_time'] == 1) ? 'VIEW_ONLINE_TIME' : 'VIEW_ONLINE_TIMES';
4455 $l_online_time = sprintf($user->lang[$l_online_time], $config['load_online_time']);
4458 $l_privmsgs_text = $l_privmsgs_text_unread = '';
4459 $s_privmsg_new = false;
4461 // Obtain number of new private messages if user is logged in
4462 if (!empty($user->data['is_registered']))
4464 if ($user->data['user_new_privmsg'])
4466 $l_message_new = ($user->data['user_new_privmsg'] == 1) ? $user->lang['NEW_PM'] : $user->lang['NEW_PMS'];
4467 $l_privmsgs_text = sprintf($l_message_new, $user->data['user_new_privmsg']);
4469 if (!$user->data['user_last_privmsg'] || $user->data['user_last_privmsg'] > $user->data['session_last_visit'])
4471 $sql = 'UPDATE ' . USERS_TABLE . '
4472 SET user_last_privmsg = ' . $user->data['session_last_visit'] . '
4473 WHERE user_id = ' . $user->data['user_id'];
4474 $db->sql_query($sql);
4476 $s_privmsg_new = true;
4480 $s_privmsg_new = false;
4485 $l_privmsgs_text = $user->lang['NO_NEW_PM'];
4486 $s_privmsg_new = false;
4489 $l_privmsgs_text_unread = '';
4491 if ($user->data['user_unread_privmsg'] && $user->data['user_unread_privmsg'] != $user->data['user_new_privmsg'])
4493 $l_message_unread = ($user->data['user_unread_privmsg'] == 1) ? $user->lang['UNREAD_PM'] : $user->lang['UNREAD_PMS'];
4494 $l_privmsgs_text_unread = sprintf($l_message_unread, $user->data['user_unread_privmsg']);
4498 $forum_id = request_var('f', 0);
4499 $topic_id = request_var('t', 0);
4501 $s_feed_news = false;
4503 // Get option for news
4504 if ($config['feed_enable'])
4506 $sql = 'SELECT forum_id
4507 FROM ' . FORUMS_TABLE . '
4508 WHERE ' . $db->sql_bit_and('forum_options', FORUM_OPTION_FEED_NEWS, '<> 0');
4509 $result = $db->sql_query_limit($sql, 1, 0, 600);
4510 $s_feed_news = (int) $db->sql_fetchfield('forum_id');
4511 $db->sql_freeresult($result);
4514 // Determine board url - we may need it later
4515 $board_url = generate_board_url() . '/';
4516 $web_path = (defined('PHPBB_USE_BOARD_URL_PATH') && PHPBB_USE_BOARD_URL_PATH) ? $board_url : $phpbb_root_path;
4519 $tz = ($user->data['user_id'] != ANONYMOUS) ? strval(doubleval($user->data['user_timezone'])) : strval(doubleval($config['board_timezone']));
4521 // Send a proper content-language to the output
4522 $user_lang = $user->lang['USER_LANG'];
4523 if (strpos($user_lang, '-x-') !== false)
4525 $user_lang = substr($user_lang, 0, strpos($user_lang, '-x-'));
4528 $s_search_hidden_fields = array();
4531 $s_search_hidden_fields['sid'] = $_SID;
4534 if (!empty($_EXTRA_URL))
4536 foreach ($_EXTRA_URL as $url_param)
4538 $url_param = explode('=', $url_param, 2);
4539 $s_hidden_fields[$url_param[0]] = $url_param[1];
4543 // The following assigns all _common_ variables that may be used at any point in a template.
4544 $template->assign_vars(array(
4545 'SITENAME' => $config['sitename'],
4546 'SITE_DESCRIPTION' => $config['site_desc'],
4547 'PAGE_TITLE' => $page_title,
4548 'SCRIPT_NAME' => str_replace('.' . $phpEx, '', $user->page['page_name']),
4549 'LAST_VISIT_DATE' => sprintf($user->lang['YOU_LAST_VISIT'], $s_last_visit),
4550 'LAST_VISIT_YOU' => $s_last_visit,
4551 'CURRENT_TIME' => sprintf($user->lang['CURRENT_TIME'], $user->format_date(time(), false, true)),
4552 'TOTAL_USERS_ONLINE' => $l_online_users,
4553 'LOGGED_IN_USER_LIST' => $online_userlist,
4554 'RECORD_USERS' => $l_online_record,
4555 'PRIVATE_MESSAGE_INFO' => $l_privmsgs_text,
4556 'PRIVATE_MESSAGE_INFO_UNREAD' => $l_privmsgs_text_unread,
4558 'S_USER_NEW_PRIVMSG' => $user->data['user_new_privmsg'],
4559 'S_USER_UNREAD_PRIVMSG' => $user->data['user_unread_privmsg'],
4560 'S_USER_NEW' => $user->data['user_new'],
4564 'SESSION_ID' => $user->session_id,
4565 'ROOT_PATH' => $phpbb_root_path,
4566 'BOARD_URL' => $board_url,
4568 'L_LOGIN_LOGOUT' => $l_login_logout,
4569 'L_INDEX' => $user->lang['FORUM_INDEX'],
4570 'L_ONLINE_EXPLAIN' => $l_online_time,
4572 'U_PRIVATEMSGS' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&folder=inbox'),
4573 'U_RETURN_INBOX' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&folder=inbox'),
4574 'U_POPUP_PM' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&mode=popup'),
4575 'UA_POPUP_PM' => addslashes(append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&mode=popup')),
4576 'U_MEMBERLIST' => append_sid("{$phpbb_root_path}memberlist.$phpEx"),
4577 'U_VIEWONLINE' => ($auth->acl_gets('u_viewprofile', 'a_user', 'a_useradd', 'a_userdel')) ? append_sid("{$phpbb_root_path}viewonline.$phpEx") : '',
4578 'U_LOGIN_LOGOUT' => $u_login_logout,
4579 'U_INDEX' => append_sid("{$phpbb_root_path}index.$phpEx"),
4580 'U_SEARCH' => append_sid("{$phpbb_root_path}search.$phpEx"),
4581 'U_REGISTER' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=register'),
4582 'U_PROFILE' => append_sid("{$phpbb_root_path}ucp.$phpEx"),
4583 'U_MODCP' => append_sid("{$phpbb_root_path}mcp.$phpEx", false, true, $user->session_id),
4584 'U_FAQ' => append_sid("{$phpbb_root_path}faq.$phpEx"),
4585 'U_SEARCH_SELF' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=egosearch'),
4586 'U_SEARCH_NEW' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=newposts'),
4587 'U_SEARCH_UNANSWERED' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unanswered'),
4588 'U_SEARCH_UNREAD' => append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=unreadposts'),
4589 'U_SEARCH_ACTIVE_TOPICS'=> append_sid("{$phpbb_root_path}search.$phpEx", 'search_id=active_topics'),
4590 'U_DELETE_COOKIES' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=delete_cookies'),
4591 'U_TEAM' => ($user->data['user_id'] != ANONYMOUS && !$auth->acl_get('u_viewprofile')) ? '' : append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=leaders'),
4592 'U_TERMS_USE' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'),
4593 'U_PRIVACY' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'),
4594 'U_RESTORE_PERMISSIONS' => ($user->data['user_perm_from'] && $auth->acl_get('a_switchperm')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=restore_perm') : '',
4595 'U_FEED' => generate_board_url() . "/feed.$phpEx",
4597 'S_USER_LOGGED_IN' => ($user->data['user_id'] != ANONYMOUS) ? true : false,
4598 'S_AUTOLOGIN_ENABLED' => ($config['allow_autologin']) ? true : false,
4599 'S_BOARD_DISABLED' => ($config['board_disable']) ? true : false,
4600 'S_REGISTERED_USER' => (!empty($user->data['is_registered'])) ? true : false,
4601 'S_IS_BOT' => (!empty($user->data['is_bot'])) ? true : false,
4602 'S_USER_PM_POPUP' => $user->optionget('popuppm'),
4603 'S_USER_LANG' => $user_lang,
4604 'S_USER_BROWSER' => (isset($user->data['session_browser'])) ? $user->data['session_browser'] : $user->lang['UNKNOWN_BROWSER'],
4605 'S_USERNAME' => $user->data['username'],
4606 'S_CONTENT_DIRECTION' => $user->lang['DIRECTION'],
4607 'S_CONTENT_FLOW_BEGIN' => ($user->lang['DIRECTION'] == 'ltr') ? 'left' : 'right',
4608 'S_CONTENT_FLOW_END' => ($user->lang['DIRECTION'] == 'ltr') ? 'right' : 'left',
4609 'S_CONTENT_ENCODING' => 'UTF-8',
4610 'S_TIMEZONE' => ($user->data['user_dst'] || ($user->data['user_id'] == ANONYMOUS && $config['board_dst'])) ? sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], $user->lang['tz']['dst']) : sprintf($user->lang['ALL_TIMES'], $user->lang['tz'][$tz], ''),
4611 'S_DISPLAY_ONLINE_LIST' => ($l_online_time) ? 1 : 0,
4612 'S_DISPLAY_SEARCH' => (!$config['load_search']) ? 0 : (isset($auth) ? ($auth->acl_get('u_search') && $auth->acl_getf_global('f_search')) : 1),
4613 'S_DISPLAY_PM' => ($config['allow_privmsg'] && !empty($user->data['is_registered']) && ($auth->acl_get('u_readpm') || $auth->acl_get('u_sendpm'))) ? true : false,
4614 'S_DISPLAY_MEMBERLIST' => (isset($auth)) ? $auth->acl_get('u_viewprofile') : 0,
4615 'S_NEW_PM' => ($s_privmsg_new) ? 1 : 0,
4616 'S_REGISTER_ENABLED' => ($config['require_activation'] != USER_ACTIVATION_DISABLE) ? true : false,
4617 'S_FORUM_ID' => $forum_id,
4618 'S_TOPIC_ID' => $topic_id,
4620 'S_LOGIN_ACTION' => ((!defined('ADMIN_START')) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login') : append_sid("index.$phpEx", false, true, $user->session_id)),
4621 'S_LOGIN_REDIRECT' => build_hidden_fields(array('redirect' => build_url())),
4623 'S_ENABLE_FEEDS' => ($config['feed_enable']) ? true : false,
4624 'S_ENABLE_FEEDS_OVERALL' => ($config['feed_overall']) ? true : false,
4625 'S_ENABLE_FEEDS_FORUMS' => ($config['feed_overall_forums']) ? true : false,
4626 'S_ENABLE_FEEDS_TOPICS' => ($config['feed_topics_new']) ? true : false,
4627 'S_ENABLE_FEEDS_TOPICS_ACTIVE' => ($config['feed_topics_active']) ? true : false,
4628 'S_ENABLE_FEEDS_NEWS' => ($s_feed_news) ? true : false,
4630 'S_LOAD_UNREADS' => ($config['load_unreads_search'] && ($config['load_anon_lastread'] || $user->data['is_registered'])) ? true : false,
4632 'S_SEARCH_HIDDEN_FIELDS' => build_hidden_fields($s_search_hidden_fields),
4634 'T_THEME_PATH' => "{$web_path}styles/" . $user->theme['theme_path'] . '/theme',
4635 'T_TEMPLATE_PATH' => "{$web_path}styles/" . $user->theme['template_path'] . '/template',
4636 'T_SUPER_TEMPLATE_PATH' => (isset($user->theme['template_inherit_path']) && $user->theme['template_inherit_path']) ? "{$web_path}styles/" . $user->theme['template_inherit_path'] . '/template' : "{$web_path}styles/" . $user->theme['template_path'] . '/template',
4637 'T_IMAGESET_PATH' => "{$web_path}styles/" . $user->theme['imageset_path'] . '/imageset',
4638 'T_IMAGESET_LANG_PATH' => "{$web_path}styles/" . $user->theme['imageset_path'] . '/imageset/' . $user->lang_name,
4639 'T_IMAGES_PATH' => "{$web_path}images/",
4640 'T_SMILIES_PATH' => "{$web_path}{$config['smilies_path']}/",
4641 'T_AVATAR_PATH' => "{$web_path}{$config['avatar_path']}/",
4642 'T_AVATAR_GALLERY_PATH' => "{$web_path}{$config['avatar_gallery_path']}/",
4643 'T_ICONS_PATH' => "{$web_path}{$config['icons_path']}/",
4644 'T_RANKS_PATH' => "{$web_path}{$config['ranks_path']}/",
4645 'T_UPLOAD_PATH' => "{$web_path}{$config['upload_path']}/",
4646 'T_STYLESHEET_LINK' => (!$user->theme['theme_storedb']) ? "{$web_path}styles/" . $user->theme['theme_path'] . '/theme/stylesheet.css' : append_sid("{$phpbb_root_path}style.$phpEx", 'id=' . $user->theme['style_id'] . '&lang=' . $user->lang_name),
4647 'T_STYLESHEET_NAME' => $user->theme['theme_name'],
4649 'T_THEME_NAME' => $user->theme['theme_path'],
4650 'T_TEMPLATE_NAME' => $user->theme['template_path'],
4651 'T_SUPER_TEMPLATE_NAME' => (isset($user->theme['template_inherit_path']) && $user->theme['template_inherit_path']) ? $user->theme['template_inherit_path'] : $user->theme['template_path'],
4652 'T_IMAGESET_NAME' => $user->theme['imageset_path'],
4653 'T_IMAGESET_LANG_NAME' => $user->data['user_lang'],
4654 'T_IMAGES' => 'images',
4655 'T_SMILIES' => $config['smilies_path'],
4656 'T_AVATAR' => $config['avatar_path'],
4657 'T_AVATAR_GALLERY' => $config['avatar_gallery_path'],
4658 'T_ICONS' => $config['icons_path'],
4659 'T_RANKS' => $config['ranks_path'],
4660 'T_UPLOAD' => $config['upload_path'],
4662 'SITE_LOGO_IMG' => $user->img('site_logo'),
4664 'A_COOKIE_SETTINGS' => addslashes('; path=' . $config['cookie_path'] . ((!$config['cookie_domain'] || $config['cookie_domain'] == 'localhost' || $config['cookie_domain'] == '127.0.0.1') ? '' : '; domain=' . $config['cookie_domain']) . ((!$config['cookie_secure']) ? '' : '; secure')),
4667 // application/xhtml+xml not used because of IE
4668 header('Content-type: text/html; charset=UTF-8');
4670 header('Cache-Control: private, no-cache="set-cookie"');
4671 header('Expires: 0');
4672 header('Pragma: no-cache');
4674 if (!empty($user->data['is_bot']))
4676 // Let reverse proxies know we detected a bot.
4677 header('X-PHPBB-IS-BOT: yes');
4684 * Generate page footer
4686 function page_footer($run_cron = true)
4688 global $db, $config, $template, $user, $auth, $cache, $starttime, $phpbb_root_path, $phpEx;
4690 // Output page creation time
4691 if (defined('DEBUG'))
4693 $mtime = explode(' ', microtime());
4694 $totaltime = $mtime[0] + $mtime[1] - $starttime;
4696 if (!empty($_REQUEST['explain']) && $auth->acl_get('a_') && defined('DEBUG_EXTRA') && method_exists($db, 'sql_report'))
4698 $db->sql_report('display');
4701 $debug_output = sprintf('Time : %.3fs | ' . $db->sql_num_queries() . ' Queries | GZIP : ' . (($config['gzip_compress'] && @extension_loaded('zlib')) ? 'On' : 'Off') . (($user->load) ? ' | Load : ' . $user->load : ''), $totaltime);
4703 if ($auth->acl_get('a_') && defined('DEBUG_EXTRA'))
4705 if (function_exists('memory_get_usage'))
4707 if ($memory_usage = memory_get_usage())
4709 global $base_memory_usage;
4710 $memory_usage -= $base_memory_usage;
4711 $memory_usage = get_formatted_filesize($memory_usage);
4713 $debug_output .= ' | Memory Usage: ' . $memory_usage;
4717 $debug_output .= ' | <a href="' . build_url() . '&explain=1">Explain</a>';
4721 $template->assign_vars(array(
4722 'DEBUG_OUTPUT' => (defined('DEBUG')) ? $debug_output : '',
4723 'TRANSLATION_INFO' => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
4725 'U_ACP' => ($auth->acl_get('a_') && !empty($user->data['is_registered'])) ? append_sid("{$phpbb_root_path}adm/index.$phpEx", false, true, $user->session_id) : '')
4728 // Call cron-type script
4730 if (!defined('IN_CRON') && $run_cron && !$config['board_disable'] && !$user->data['is_bot'])
4733 $time_now = (!empty($user->time_now) && is_int($user->time_now)) ? $user->time_now : time();
4735 // Any old lock present?
4736 if (!empty($config['cron_lock']))
4738 $cron_time = explode(' ', $config['cron_lock']);
4740 // If 1 hour lock is present we do not call cron.php
4741 if ($cron_time[0] + 3600 >= $time_now)
4753 if ($time_now - $config['queue_interval'] > $config['last_queue_run'] && !defined('IN_ADMIN') && file_exists($phpbb_root_path . 'cache/queue.' . $phpEx))
4755 // Process email queue
4756 $cron_type = 'queue';
4758 else if (method_exists($cache, 'tidy') && $time_now - $config['cache_gc'] > $config['cache_last_gc'])
4761 $cron_type = 'tidy_cache';
4763 else if ($config['warnings_expire_days'] && ($time_now - $config['warnings_gc'] > $config['warnings_last_gc']))
4765 $cron_type = 'tidy_warnings';
4767 else if ($time_now - $config['database_gc'] > $config['database_last_gc'])
4769 // Tidy the database
4770 $cron_type = 'tidy_database';
4772 else if ($time_now - $config['search_gc'] > $config['search_last_gc'])
4775 $cron_type = 'tidy_search';
4777 else if ($time_now - $config['session_gc'] > $config['session_last_gc'])
4779 $cron_type = 'tidy_sessions';
4784 $template->assign_var('RUN_CRON_TASK', '<img src="' . append_sid($phpbb_root_path . 'cron.' . $phpEx, 'cron_type=' . $cron_type) . '" width="1" height="1" alt="cron" />');
4788 $template->display('body');
4790 garbage_collection();
4795 * Closing the cache object and the database
4796 * Cool function name, eh? We might want to add operations to it later
4798 function garbage_collection()
4802 // Unload cache, must be done before the DB connection if closed
4808 // Close our DB connection.
4816 * Handler for exit calls in phpBB.
4817 * This function supports hooks.
4819 * Note: This function is called after the template has been outputted.
4821 function exit_handler()
4823 global $phpbb_hook, $config;
4825 if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
4827 if ($phpbb_hook->hook_return(__FUNCTION__))
4829 return $phpbb_hook->hook_return_result(__FUNCTION__);
4833 // As a pre-caution... some setups display a blank page if the flush() is not there.
4834 (ob_get_level() > 0) ? @ob_flush() : @flush();
4840 * Handler for init calls in phpBB. This function is called in user::setup();
4841 * This function supports hooks.
4843 function phpbb_user_session_handler()
4847 if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__))
4849 if ($phpbb_hook->hook_return(__FUNCTION__))
4851 return $phpbb_hook->hook_return_result(__FUNCTION__);