/includes/functions.php
PHP | 6703 lines | 5117 code | 716 blank | 870 comment | 877 complexity | 47d2b88399eefdc07ffa8394687c33bf MD5 | raw file
Possible License(s): AGPL-1.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- *
- * @package Icy Phoenix
- * @version $Id$
- * @copyright (c) 2008 Icy Phoenix
- * @license http://opensource.org/licenses/gpl-license.php GNU Public License
- *
- */
- /**
- *
- * @Icy Phoenix is based on phpBB
- * @copyright (c) 2008 phpBB Group
- *
- */
- if (!defined('IN_ICYPHOENIX'))
- {
- die('Hacking attempt');
- }
- if (!defined('STRIP'))
- {
- // If we are on PHP >= 6.0.0 we do not need some code
- if (version_compare(PHP_VERSION, '6.0.0-dev', '>='))
- {
- define('STRIP', false);
- }
- else
- {
- define('STRIP', (@get_magic_quotes_gpc()) ? true : false);
- }
- }
- /*
- * Append $SID to a url. Borrowed from phplib and modified. This is an extra routine utilised by the session code and acts as a wrapper around every single URL and form action.
- * If you replace the session code you must include this routine, even if it's empty.
- */
- function append_sid($url, $non_html_amp = false, $char_conversion = false, $params = false, $session_id = false)
- {
- global $SID, $_SID, $_EXTRA_URL, $phpbb_hook;
- $_SID = (empty($_SID) && !empty($SID) || (!empty($SID) && ($SID != ('sid=' . $_SID)))) ? str_replace('sid=', '', $SID) : $_SID;
- $is_amp = empty($non_html_amp) ? true : false;
- $amp_delim = !empty($is_amp) ? '&' : '&';
- $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
- if (empty($params))
- {
- $amp_delim = (!empty($char_conversion) ? '%26' : $amp_delim);
- $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
- if (!empty($SID) && !preg_match('#sid=#', $url))
- {
- $url .= $url_delim . $SID;
- }
- return $url;
- }
- // Developers using the hook function need to globalise the $_SID and $_EXTRA_URL on their own and also handle it appropriately.
- // They could mimick most of what is within this function
- if (!empty($phpbb_hook) && $phpbb_hook->call_hook(__FUNCTION__, $url, $params, $is_amp, $session_id))
- {
- if ($phpbb_hook->hook_return(__FUNCTION__))
- {
- return $phpbb_hook->hook_return_result(__FUNCTION__);
- }
- }
- $params_is_array = is_array($params);
- // Get anchor
- $anchor = '';
- if (strpos($url, '#') !== false)
- {
- list($url, $anchor) = explode('#', $url, 2);
- $anchor = '#' . $anchor;
- }
- elseif (!$params_is_array && strpos($params, '#') !== false)
- {
- list($params, $anchor) = explode('#', $params, 2);
- $anchor = '#' . $anchor;
- }
- // Handle really simple cases quickly
- if (($_SID == '') && ($session_id === false) && empty($_EXTRA_URL) && !$params_is_array && !$anchor)
- {
- if ($params === false)
- {
- return $url;
- }
- return $url . (($params !== false) ? $url_delim . $params : '');
- }
- // Assign sid if session id is not specified
- if ($session_id === false)
- {
- $session_id = $_SID;
- }
- // Appending custom url parameter?
- $append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';
- // Use the short variant if possible ;)
- if ($params === false)
- {
- // Append session id
- if (!$session_id)
- {
- return $url . (($append_url) ? $url_delim . $append_url : '') . $anchor;
- }
- else
- {
- return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . 'sid=' . $session_id . $anchor;
- }
- }
- // Build string if parameters are specified as array
- if (is_array($params))
- {
- $output = array();
- foreach ($params as $key => $item)
- {
- if ($item === NULL)
- {
- continue;
- }
- if ($key == '#')
- {
- $anchor = '#' . $item;
- continue;
- }
- $output[] = $key . '=' . $item;
- }
- $params = implode($amp_delim, $output);
- }
- // Append session id and parameters (even if they are empty)
- // If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
- return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . 'sid=' . $session_id) . $anchor;
- }
- /**
- * Re-Apply session id after page reloads
- */
- function reapply_sid($url)
- {
- // Remove previously added sid
- if (strpos($url, 'sid=') !== false)
- {
- $phpEx = PHP_EXT;
- // All kind of links
- $url = preg_replace('/(\?)?(&|&)?sid=[a-z0-9]+/', '', $url);
- // if the sid was the first param, make the old second as first ones
- $url = preg_replace("/$phpEx(&|&)+?/", "$phpEx?", $url);
- }
- return append_sid($url);
- }
- /**
- * Build an URL with params
- */
- function ip_build_url($url, $params = false, $html_amp = false)
- {
- $amp_delim = !empty($html_amp) ? '&' : '&';
- $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
- if (!empty($params) && is_array($params))
- {
- foreach ($params as $param)
- {
- $url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;
- if (!empty($param))
- {
- $url .= $url_delim . $param;
- }
- }
- }
- return $url;
- }
- /*
- * extract_current_page
- * function backported from phpBB3 - Olympus
- * @param string $root_path current root path (IP_ROOT_PATH)
- */
- function extract_current_page($root_path)
- {
- $page_array = array();
- // First of all, get the request uri...
- $script_name = (!empty($_SERVER['SCRIPT_NAME'])) ? $_SERVER['SCRIPT_NAME'] : getenv('SCRIPT_NAME');
- $args = (!empty($_SERVER['QUERY_STRING'])) ? explode('&', $_SERVER['QUERY_STRING']) : explode('&', getenv('QUERY_STRING'));
- // If we are unable to get the script name we use REQUEST_URI as a failover and note it within the page array for easier support...
- if (!$script_name)
- {
- $script_name = (!empty($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI');
- $script_name = (($pos = strpos($script_name, '?')) !== false) ? substr($script_name, 0, $pos) : $script_name;
- $page_array['failover'] = 1;
- }
- // Replace backslashes and doubled slashes (could happen on some proxy setups)
- $script_name = str_replace(array('\\', '//'), '/', $script_name);
- // Now, remove the sid and let us get a clean query string...
- $use_args = array();
- // Since some browser do not encode correctly we need to do this with some "special" characters...
- // " -> %22, ' => %27, < -> %3C, > -> %3E
- $find = array('"', "'", '<', '>');
- $replace = array('%22', '%27', '%3C', '%3E');
- foreach ($args as $key => $argument)
- {
- if (strpos($argument, 'sid=') === 0)
- {
- continue;
- }
- $use_args[] = str_replace($find, $replace, $argument);
- }
- unset($args);
- // The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2
- // The current query string
- $query_string = trim(implode('&', $use_args));
- // basenamed page name (for example: index.php)
- $page_name = (substr($script_name, -1, 1) == '/') ? '' : basename($script_name);
- $page_name = urlencode(htmlspecialchars($page_name));
- // current directory within the phpBB root (for example: adm)
- $root_dirs = explode('/', str_replace('\\', '/', phpbb_realpath($root_path)));
- $page_dirs = explode('/', str_replace('\\', '/', phpbb_realpath('./')));
- $intersection = array_intersect_assoc($root_dirs, $page_dirs);
- $root_dirs = array_diff_assoc($root_dirs, $intersection);
- $page_dirs = array_diff_assoc($page_dirs, $intersection);
- $page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);
- if ($page_dir && substr($page_dir, -1, 1) == '/')
- {
- $page_dir = substr($page_dir, 0, -1);
- }
- $page_full = $page_name . (($query_string) ? '?' . $query_string : '');
- // Current page from Icy Phoenix root (for example: adm/index.php?i=10&b=2)
- $page = (($page_dir) ? $page_dir . '/' : '') . $page_full;
- // The script path from the webroot to the current directory (for example: /ip/adm/) : always prefixed with / and ends in /
- $script_path = trim(str_replace('\\', '/', dirname($script_name)));
- // The script path from the webroot to the Icy Phoenix root (for example: /ip/)
- $script_dirs = explode('/', $script_path);
- array_splice($script_dirs, -sizeof($page_dirs));
- $root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ? '/' . implode('/', $root_dirs) : '');
- // We are on the base level (Icy Phoenix root == webroot), lets adjust the variables a bit...
- if (!$root_script_path)
- {
- $root_script_path = ($page_dir) ? str_replace($page_dir, '', $script_path) : $script_path;
- }
- $script_path .= (substr($script_path, -1, 1) == '/') ? '' : '/';
- $root_script_path .= (substr($root_script_path, -1, 1) == '/') ? '' : '/';
- $post_forum_url = (defined('POST_FORUM_URL') ? POST_FORUM_URL : 'f');
- $post_topic_url = (defined('POST_TOPIC_URL') ? POST_TOPIC_URL : 't');
- $page_array += array(
- 'root_script_path' => str_replace(' ', '%20', htmlspecialchars($root_script_path)),
- 'script_path' => str_replace(' ', '%20', htmlspecialchars($script_path)),
- 'page_dir' => $page_dir,
- 'page_name' => $page_name,
- 'page' => $page,
- 'query_string' => $query_string,
- 'forum' => (isset($_REQUEST[$post_forum_url]) && $_REQUEST[$post_forum_url] > 0) ? (int) $_REQUEST[$post_forum_url] : 0,
- 'topic' => (isset($_REQUEST[$post_topic_url]) && $_REQUEST[$post_topic_url] > 0) ? (int) $_REQUEST[$post_topic_url] : 0,
- 'page_full' => $page_full,
- );
- return $page_array;
- }
- /**
- * Get valid hostname/port. HTTP_HOST is used, SERVER_NAME if HTTP_HOST not present.
- * function backported from phpBB3 - Olympus
- */
- function extract_current_hostname()
- {
- global $config;
- // Get hostname
- $host = (!empty($_SERVER['HTTP_HOST'])) ? $_SERVER['HTTP_HOST'] : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
- // Should be a lowercase string
- $host = (string) strtolower($host);
- // If host is equal the cookie domain or the server name (if config is set), then we assume it is valid
- if ((isset($config['cookie_domain']) && ($host === $config['cookie_domain'])) || (isset($config['server_name']) && ($host === $config['server_name'])))
- {
- return $host;
- }
- // Is the host actually a IP? If so, we use the IP... (IPv4)
- if (long2ip(ip2long($host)) === $host)
- {
- return $host;
- }
- // Now return the hostname (this also removes any port definition). The http:// is prepended to construct a valid URL, hosts never have a scheme assigned
- $host = @parse_url('http://' . $host);
- $host = (!empty($host['host'])) ? $host['host'] : '';
- // Remove any portions not removed by parse_url (#)
- $host = str_replace('#', '', $host);
- // If, by any means, the host is now empty, we will use a "best approach" way to guess one
- if (empty($host))
- {
- if (!empty($config['server_name']))
- {
- $host = $config['server_name'];
- }
- elseif (!empty($config['cookie_domain']))
- {
- $host = (strpos($config['cookie_domain'], '.') === 0) ? substr($config['cookie_domain'], 1) : $config['cookie_domain'];
- }
- else
- {
- // Set to OS hostname or localhost
- $host = (function_exists('php_uname')) ? php_uname('n') : 'localhost';
- }
- }
- // It may be still no valid host, but for sure only a hostname (we may further expand on the cookie domain... if set)
- return $host;
- }
- /**
- * Set variable, used by {@link request_var the request_var function}
- * function backported from phpBB3 - Olympus
- * @access private
- */
- function set_var(&$result, $var, $type, $multibyte = false)
- {
- settype($var, $type);
- $result = $var;
- if ($type == 'string')
- {
- // normalize UTF-8 data
- if ($multibyte)
- {
- $result = utf8_normalize_nfc($result);
- }
- $result = trim(htmlspecialchars(str_replace(array("\r\n", "\r"), array("\n", "\n"), $result), ENT_COMPAT, 'UTF-8'));
- if (!empty($result))
- {
- // Make sure multibyte characters are wellformed
- if ($multibyte)
- {
- if (!preg_match('/^./u', $result))
- {
- $result = '';
- }
- }
- else
- {
- // no multibyte, allow only ASCII (0-127)
- $result = preg_replace('/[\x80-\xFF]/', '?', $result);
- }
- }
- $result = (STRIP) ? stripslashes($result) : $result;
- }
- }
- /**
- * Get passed variable
- * function backported from phpBB3 - Olympus
- */
- function request_var($var_name, $default, $multibyte = false, $cookie = false)
- {
- if (!$cookie && isset($_COOKIE[$var_name]))
- {
- if (!isset($_GET[$var_name]) && !isset($_POST[$var_name]))
- {
- return (is_array($default)) ? array() : $default;
- }
- $_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name];
- }
- $super_global = ($cookie) ? '_COOKIE' : '_REQUEST';
- if (!isset($GLOBALS[$super_global][$var_name]) || is_array($GLOBALS[$super_global][$var_name]) != is_array($default))
- {
- return (is_array($default)) ? array() : $default;
- }
- $var = $GLOBALS[$super_global][$var_name];
- if (!is_array($default))
- {
- $type = gettype($default);
- }
- else
- {
- list($key_type, $type) = each($default);
- $type = gettype($type);
- $key_type = gettype($key_type);
- if ($type == 'array')
- {
- reset($default);
- $default = current($default);
- list($sub_key_type, $sub_type) = each($default);
- $sub_type = gettype($sub_type);
- $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type;
- $sub_key_type = gettype($sub_key_type);
- }
- }
- if (is_array($var))
- {
- $_var = $var;
- $var = array();
- foreach ($_var as $k => $v)
- {
- set_var($k, $k, $key_type);
- if (($type == 'array') && is_array($v))
- {
- foreach ($v as $_k => $_v)
- {
- if (is_array($_v))
- {
- $_v = null;
- }
- set_var($_k, $_k, $sub_key_type, $multibyte);
- set_var($var[$k][$_k], $_v, $sub_type, $multibyte);
- }
- }
- else
- {
- if (($type == 'array') || is_array($v))
- {
- $v = null;
- }
- set_var($var[$k], $v, $type, $multibyte);
- }
- }
- }
- else
- {
- set_var($var, $var, $type, $multibyte);
- }
- return $var;
- }
- /**
- * Request the var value but returns only true of false, useful for forms validations
- */
- function request_boolean_var($var_name, $default, $multibyte = false, $post_only = false)
- {
- if ($post_only)
- {
- $return = request_post_var($var_name, $default, $multibyte);
- }
- else
- {
- $return = request_var($var_name, $default, $multibyte);
- }
- $return = !empty($return) ? true : false;
- return $return;
- }
- /**
- * Gets only POST vars
- */
- function request_post_var($var_name, $default, $multibyte = false)
- {
- $return = $default;
- if (isset($_POST[$var_name]))
- {
- $return = request_var($var_name, $default, $multibyte);
- }
- return $return;
- }
- /**
- * Get only GET vars
- */
- function request_get_var($var_name, $default, $multibyte = false)
- {
- $return = $default;
- if (isset($_GET[$var_name]))
- {
- $temp_post_var = isset($_POST[$var_name]) ? $_POST[$var_name] : '';
- $_POST[$var_name] = $_GET[$var_name];
- $return = request_var($var_name, $default, $multibyte);
- $_POST[$var_name] = $temp_post_var;
- }
- return $return;
- }
- /**
- * Check GET POST vars exists
- */
- function check_http_var_exists($var_name, $empty_var = false)
- {
- if ($empty_var)
- {
- if (isset($_GET[$var_name]) || isset($_POST[$var_name]))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- else
- {
- if (!empty($_GET[$var_name]) || !empty($_POST[$var_name]))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- return false;
- }
- /**
- * Check variable value against default array
- */
- function check_var_value($var, $var_array, $var_default = false)
- {
- if (!is_array($var_array) || empty($var_array))
- {
- return $var;
- }
- $var_default = (($var_default === false) ? $var_array[0] : $var_default);
- $var = in_array($var, $var_array) ? $var : $var_default;
- return $var;
- }
- /**
- * Function to add slashes to vars array, may be used to globally escape HTTP vars if needed
- */
- function slash_data(&$data)
- {
- if (is_array($data))
- {
- foreach ($data as $k => $v)
- {
- $data[$k] = (is_array($v)) ? slash_data($v) : addslashes($v);
- }
- }
- return $data;
- }
- /**
- * Set config value. Creates missing config entry.
- */
- function set_config($config_name, $config_value, $clear_cache = true, $return = false)
- {
- global $db, $cache, $config;
- $sql = "UPDATE " . CONFIG_TABLE . "
- SET config_value = '" . $db->sql_escape($config_value) . "'
- WHERE config_name = '" . $db->sql_escape($config_name) . "'";
- $db->sql_return_on_error($return);
- $db->sql_query($sql);
- $db->sql_return_on_error(false);
- if (!$db->sql_affectedrows() && !isset($config[$config_name]))
- {
- $sql = "INSERT INTO " . CONFIG_TABLE . " (`config_name`, `config_value`)
- VALUES ('" . $db->sql_escape($config_name) . "', '" . $db->sql_escape($config_value) . "')";
- $db->sql_return_on_error($return);
- $db->sql_query($sql);
- $db->sql_return_on_error(false);
- }
- $config[$config_name] = $config_value;
- if ($clear_cache)
- {
- $cache->destroy('config');
- //$db->clear_cache('config_');
- }
- }
- /**
- * Get config values
- */
- function get_config($from_cache = true)
- {
- global $db;
- $config = array();
- $from_cache = ($from_cache && (CACHE_CFG == true) && !defined('IN_ADMIN') && !defined('IN_CMS')) ? true : false;
- $sql = "SELECT * FROM " . CONFIG_TABLE;
- $result = $from_cache ? $db->sql_query($sql, 0, 'config_') : $db->sql_query($sql);
- while ($row = $db->sql_fetchrow($result))
- {
- $config[$row['config_name']] = stripslashes($row['config_value']);
- }
- $db->sql_freeresult($result);
- return $config;
- }
- /**
- * Get layouts config values
- */
- function get_layouts_config($from_cache = true)
- {
- global $db;
- $cms_config_layouts = array();
- $from_cache = $from_cache ? true : false;
- $sql = "SELECT lsid, page_id, filename, global_blocks, page_nav, view FROM " . CMS_LAYOUT_SPECIAL_TABLE . " ORDER BY page_id";
- $result = $from_cache ? $db->sql_query($sql, 0, 'cms_config_', CMS_CACHE_FOLDER) : $db->sql_query($sql);
- while ($row = $db->sql_fetchrow($result))
- {
- $cms_config_layouts[$row['page_id']] = $row;
- }
- $db->sql_freeresult($result);
- return $cms_config_layouts;
- }
- /**
- * Get CMS config values
- */
- function get_cms_config($from_cache = true)
- {
- global $db;
- $cms_config_vars = array();
- $from_cache = $from_cache ? true : false;
- $sql = "SELECT bid, config_name, config_value FROM " . CMS_CONFIG_TABLE;
- $result = $from_cache ? $db->sql_query($sql, 0, 'cms_config_', CMS_CACHE_FOLDER) : $db->sql_query($sql);
- while ($row = $db->sql_fetchrow($result))
- {
- if ($row['bid'] > 0)
- {
- $cms_config_vars[$row['config_name']][$row['bid']] = $row['config_value'];
- }
- else
- {
- $cms_config_vars[$row['config_name']] = $row['config_value'];
- }
- }
- $db->sql_freeresult($result);
- return $cms_config_vars;
- }
- if (!function_exists('htmlspecialchars_decode'))
- {
- /**
- * A wrapper for htmlspecialchars_decode
- */
- function htmlspecialchars_decode($string, $quote_style = ENT_NOQUOTES)
- {
- return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
- }
- }
- /**
- * html_entity_decode replacement (from php manual)
- */
- if (!function_exists('html_entity_decode'))
- {
- function html_entity_decode($given_html, $quote_style = ENT_QUOTES)
- {
- $trans_table = array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style));
- $trans_table['''] = "'";
- return (strtr($given_html, $trans_table));
- }
- }
- /**
- * HTML Special Chars markup cleaning
- */
- function htmlspecialchars_clean($string, $quote_style = ENT_NOQUOTES)
- {
- // Old version, to be verified why & gets converted twice...
- //return trim(str_replace(array('& ', '<', '%3C', '>', '%3E'), array('& ', '<', '<', '>', '>'), htmlspecialchars_decode($string, $quote_style)));
- return trim(str_replace(array('& ', '<', '%3C', '>', '%3E', '{IP_EAMP_ESCAPE}'), array('& ', '<', '<', '>', '>', '&'), htmlspecialchars_decode(str_replace('&', '{IP_EAMP_ESCAPE}', $string), $quote_style)));
- }
- /**
- * Add slashes only if needed
- */
- function ip_addslashes($string)
- {
- return (STRIP ? addslashes($string) : $string);
- }
- /**
- * Strip slashes only if needed
- */
- function ip_stripslashes($string)
- {
- return (STRIP ? stripslashes($string) : $string);
- }
- /**
- * Escape single quotes for MySQL
- */
- function ip_mysql_escape($string)
- {
- return $db->sql_escape($string);
- }
- /**
- * Icy Phoenix UTF8 Conditional Decode
- */
- function ip_utf8_decode($string)
- {
- global $lang;
- $string = ($lang['ENCODING'] == 'utf8') ? $string : utf8_decode($string);
- return $string;
- }
- /**
- * Get option bitfield from custom data
- *
- * @param int $bitThe bit/value to get
- * @param int $data Current bitfield to check
- * @return bool Returns true if value of constant is set in bitfield, else false
- */
- function phpbb_optionget($bit, $data)
- {
- return ($data & 1 << (int) $bit) ? true : false;
- }
- /**
- * Set option bitfield
- *
- * @param int $bit The bit/value to set/unset
- * @param bool $set True if option should be set, false if option should be unset.
- * @param int $data Current bitfield to change
- * @return int The new bitfield
- */
- function phpbb_optionset($bit, $set, $data)
- {
- if ($set && !($data & 1 << $bit))
- {
- $data += 1 << $bit;
- }
- elseif (!$set && ($data & 1 << $bit))
- {
- $data -= 1 << $bit;
- }
- return $data;
- }
- /*
- * Get user data, $target_user can be username or user_id.
- * If force_str is true, the username will be forced.
- */
- function get_userdata($target_user, $force_str = false)
- {
- global $db;
- $target_user = (!is_numeric($target_user) || $force_str) ? phpbb_clean_username($target_user) : intval($target_user);
- $sql = "SELECT *
- FROM " . USERS_TABLE . "
- WHERE ";
- $sql .= (is_integer($target_user) ? ("user_id = " . (int) $target_user) : ("username_clean = '" . $db->sql_escape(utf8_clean_string($target_user)) . "'")) . " AND user_id <> " . ANONYMOUS;
- $result = $db->sql_query($sql);
- if ($db->sql_affectedrows() == 0)
- {
- //message_die(GENERAL_ERROR, 'User does not exist.');
- return false;
- }
- if ($row = $db->sql_fetchrow($result))
- {
- if (isset($row['user_level']) && ($row['user_level'] == JUNIOR_ADMIN))
- {
- $row['user_level'] = (!defined('IN_ADMIN') && !defined('IN_CMS')) ? ADMIN : MOD;
- }
- return $row;
- }
- else
- {
- return false;
- }
- }
- /*
- * Generate an SQL to get users based on a search string
- */
- function get_users_sql($username, $sql_like = false, $all_data = false, $data_escape = true, $clean_username = false)
- {
- global $config, $cache, $db;
- $username = (!empty($clean_username) ? phpbb_clean_username($username) : $username);
- $sql = "SELECT " . (!empty($all_data) ? "*" : ("user_id, username, username_clean, user_active, user_color, user_level")) . " FROM " . USERS_TABLE . "
- WHERE username_clean " . (!empty($sql_like) ? (" LIKE ") : (" = ")) . "'" . (!empty($data_escape) ? $db->sql_escape(utf8_clean_string($username)) : $username) . "'" . (!empty($sql_like) ? "" : (" LIMIT 1"));
- return $sql;
- }
- /*
- * Get founder id
- */
- function get_founder_id($clear_cache = false)
- {
- global $db, $config;
- if ($clear_cache)
- {
- $db->clear_cache('founder_id_');
- }
- $founder_id = (intval($config['main_admin_id']) >= 2) ? (int) $config['main_admin_id'] : 2;
- if ($founder_id != 2)
- {
- $sql = "SELECT user_id
- FROM " . USERS_TABLE . "
- WHERE user_id = '" . $founder_id . "'
- LIMIT 1";
- $result = $db->sql_query($sql, 0, 'founder_id_');
- $founder_id = 2;
- while ($row = $db->sql_fetchrow($result))
- {
- $founder_id = $row['user_id'];
- }
- $db->sql_freeresult($result);
- }
- return $founder_id;
- }
- /*
- * Get groups data
- */
- function get_groups_data($full_data = false, $sort_by_name = false, $sql_groups = array())
- {
- global $db, $cache, $config;
- $groups_data = array();
- $sql_select = !empty($full_data) ? '*' : 'g.group_id, g.group_name, g.group_color, g.group_legend, g.group_legend_order';
- $sql_where = '';
- if (!empty($sql_groups))
- {
- if (!is_array($sql_groups))
- {
- $sql_groups = array($sql_groups);
- }
- $sql_where = !empty($sql_groups) ? (' AND ' . $db->sql_in_set('g.group_id', $sql_groups)) : '';
- }
- $sql_sort = !empty($sort_by_name) ? ' ORDER BY g.group_name ASC' : ' ORDER BY g.group_legend DESC, g.group_legend_order ASC, g.group_name ASC';
- $sql = "SELECT " . $sql_select . "
- FROM " . GROUPS_TABLE . " g
- WHERE g.group_single_user = 0" .
- $sql_where .
- $sql_sort;
- $result = $db->sql_query($sql, 0, 'groups_', USERS_CACHE_FOLDER);
- $groups_data = $db->sql_fetchrowset($result);
- $db->sql_freeresult($result);
- return $groups_data;
- }
- /*
- * Get groups data for a specific user
- */
- function get_groups_data_user($user_id, $full_data = false, $sort_by_name = false, $sql_groups = array())
- {
- global $db, $cache, $config;
- $groups_data = array();
- $sql_select = !empty($full_data) ? 'g.*, ug.*' : 'g.group_id, g.group_name, g.group_color, g.group_legend, g.group_legend_order, ug.user_pending';
- $sql_where = '';
- if (!empty($sql_groups))
- {
- if (!is_array($sql_groups))
- {
- $sql_groups = array($sql_groups);
- }
- $sql_where = !empty($sql_groups) ? (' AND ' . $db->sql_in_set('g.group_id', $sql_groups)) : '';
- }
- $sql = "SELECT " . $sql_select . "
- FROM " . GROUPS_TABLE . " g, " . USER_GROUP_TABLE . " ug " . "
- WHERE g.group_single_user = 0" .
- $sql_where . "
- AND g.group_id = ug.group_id
- AND ug.user_id = " . (int) $user_id;
- $result = $db->sql_query($sql, 0, 'groups_', USERS_CACHE_FOLDER);
- $groups_data = $db->sql_fetchrowset($result);
- $db->sql_freeresult($result);
- return $groups_data;
- }
- /*
- * Founder protection
- */
- function founder_protect($founder_id)
- {
- global $db;
- // Activate Main Admin Account
- $sql = "UPDATE " . USERS_TABLE . "
- SET user_active = 1
- WHERE user_id = " . $founder_id;
- $result = $db->sql_query($sql);
- // Delete Main Admin Ban
- $sql = "DELETE FROM " . BANLIST_TABLE . "
- WHERE ban_userid = " . $founder_id;
- $result = $db->sql_query($sql);
- $db->clear_cache('ban_', USERS_CACHE_FOLDER);
- return true;
- }
- /**
- * Generates an alphanumeric random string of given length
- */
- function gen_rand_string($num_chars = 8)
- {
- $rand_str = unique_id();
- $rand_str = str_replace('0', 'Z', strtoupper(base_convert($rand_str, 16, 35)));
- return substr($rand_str, 0, $num_chars);
- }
- /**
- * Return unique id
- * @param string $extra additional entropy
- */
- function unique_id($extra = 'c')
- {
- static $dss_seeded = false;
- global $config, $cache;
- $val = $config['rand_seed'] . microtime();
- $val = md5($val);
- $config['rand_seed'] = md5($config['rand_seed'] . $val . $extra);
- if(($dss_seeded !== true) && ($config['rand_seed_last_update'] < (time() - rand(1, 10))))
- {
- // Maybe we can avoid emptying cache every random seed generation...
- set_config('rand_seed', $config['rand_seed'], false);
- set_config('rand_seed_last_update', time(), false);
- $dss_seeded = true;
- }
- return substr($val, 4, 16);
- }
- // Modified by MG
- /**
- * Return formatted string for filesizes
- *
- * @param int $value filesize in bytes
- * @param bool $string_only true if language string should be returned
- * @param array $allowed_units only allow these units (data array indexes)
- *
- * @return mixed data array if $string_only is false
- * @author bantu
- */
- function get_formatted_filesize($value, $string_only = true, $allowed_units = false)
- {
- global $lang;
- $available_units = array(
- 'gb' => array(
- 'min' => 1073741824, // pow(2, 30)
- 'index' => 3,
- 'si_unit' => 'GB',
- 'iec_unit' => 'GIB',
- 'precision' => 2
- ),
- 'mb' => array(
- 'min' => 1048576, // pow(2, 20)
- 'index' => 2,
- 'si_unit' => 'MB',
- 'iec_unit' => 'MIB',
- 'precision' => 2
- ),
- 'kb' => array(
- 'min' => 1024, // pow(2, 10)
- 'index' => 1,
- 'si_unit' => 'KB',
- 'iec_unit' => 'KIB',
- 'precision' => 0
- ),
- 'b' => array(
- 'min' => 0,
- 'index' => 0,
- 'si_unit' => 'BYTES', // Language index
- 'iec_unit' => 'BYTES', // Language index
- 'precision' => 0
- ),
- );
- foreach ($available_units as $si_identifier => $unit_info)
- {
- if (!empty($allowed_units) && ($si_identifier != 'b') && !in_array($si_identifier, $allowed_units))
- {
- continue;
- }
- if ($value >= $unit_info['min'])
- {
- $unit_info['si_identifier'] = $si_identifier;
- break;
- }
- }
- unset($available_units);
- for ($i = 0; $i < $unit_info['index']; $i++)
- {
- $value /= 1024;
- }
- $value = round($value, $unit_info['precision']);
- // Lookup units in language dictionary
- $unit_info['si_unit'] = (isset($lang[$unit_info['si_unit']])) ? $lang[$unit_info['si_unit']] : $unit_info['si_unit'];
- $unit_info['iec_unit'] = (isset($lang[$unit_info['iec_unit']])) ? $lang[$unit_info['iec_unit']] : $unit_info['iec_unit'];
- // Default to SI
- $unit_info['unit'] = $unit_info['si_unit'];
- if (!$string_only)
- {
- $unit_info['value'] = $value;
- return $unit_info;
- }
- return $value . $unit_info['unit'];
- }
- /**
- *
- * @version Version 0.1 / slightly modified for phpBB 3.0.x (using $H$ as hash type identifier)
- *
- * Portable PHP password hashing framework.
- *
- * Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
- * the public domain.
- *
- * There's absolutely no warranty.
- *
- * The homepage URL for this framework is:
- *
- * http://www.openwall.com/phpass/
- *
- * Please be sure to update the Version line if you edit this file in any way.
- * It is suggested that you leave the main version number intact, but indicate
- * your project name (after the slash) and add your own revision information.
- *
- * Please do not change the "private" password hashing method implemented in
- * here, thereby making your hashes incompatible. However, if you must, please
- * change the hash type identifier (the "$P$") to something different.
- *
- * Obviously, since this code is in the public domain, the above are not
- * requirements (there can be none), but merely suggestions.
- *
- *
- * Hash the password
- */
- function phpbb_hash($password)
- {
- $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
- $random_state = unique_id();
- $random = '';
- $count = 6;
- if (($fh = @fopen('/dev/urandom', 'rb')))
- {
- $random = fread($fh, $count);
- fclose($fh);
- }
- if (strlen($random) < $count)
- {
- $random = '';
- for ($i = 0; $i < $count; $i += 16)
- {
- $random_state = md5(unique_id() . $random_state);
- $random .= pack('H*', md5($random_state));
- }
- $random = substr($random, 0, $count);
- }
- $hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64);
- if (strlen($hash) == 34)
- {
- return $hash;
- }
- return md5($password);
- }
- /**
- * Check for correct password
- *
- * @param string $password The password in plain text
- * @param string $hash The stored password hash
- *
- * @return bool Returns true if the password is correct, false if not.
- */
- function phpbb_check_hash($password, $hash)
- {
- if (strlen($hash) == 34)
- {
- $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
- return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
- }
- return (md5($password) === $hash) ? true : false;
- }
- /**
- * Generate salt for hash generation
- */
- function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6)
- {
- if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
- {
- $iteration_count_log2 = 8;
- }
- $output = '$H$';
- $output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)];
- $output .= _hash_encode64($input, 6, $itoa64);
- return $output;
- }
- /**
- * Encode hash
- */
- function _hash_encode64($input, $count, &$itoa64)
- {
- $output = '';
- $i = 0;
- do
- {
- $value = ord($input[$i++]);
- $output .= $itoa64[$value & 0x3f];
- if ($i < $count)
- {
- $value |= ord($input[$i]) << 8;
- }
- $output .= $itoa64[($value >> 6) & 0x3f];
- if ($i++ >= $count)
- {
- break;
- }
- if ($i < $count)
- {
- $value |= ord($input[$i]) << 16;
- }
- $output .= $itoa64[($value >> 12) & 0x3f];
- if ($i++ >= $count)
- {
- break;
- }
- $output .= $itoa64[($value >> 18) & 0x3f];
- }
- while ($i < $count);
- return $output;
- }
- /**
- * The crypt function/replacement
- */
- function _hash_crypt_private($password, $setting, &$itoa64)
- {
- $output = '*';
- // Check for correct hash
- if (substr($setting, 0, 3) != '$H$')
- {
- return $output;
- }
- $count_log2 = strpos($itoa64, $setting[3]);
- if ($count_log2 < 7 || $count_log2 > 30)
- {
- return $output;
- }
- $count = 1 << $count_log2;
- $salt = substr($setting, 4, 8);
- if (strlen($salt) != 8)
- {
- return $output;
- }
- /**
- * We're kind of forced to use MD5 here since it's the only
- * cryptographic primitive available in all versions of PHP
- * currently in use. To implement our own low-level crypto
- * in PHP would result in much worse performance and
- * consequently in lower iteration counts and hashes that are
- * quicker to crack (by non-PHP code).
- */
- if (PHP_VERSION >= 5)
- {
- $hash = md5($salt . $password, true);
- do
- {
- $hash = md5($hash . $password, true);
- }
- while (--$count);
- }
- else
- {
- $hash = pack('H*', md5($salt . $password));
- do
- {
- $hash = pack('H*', md5($hash . $password));
- }
- while (--$count);
- }
- $output = substr($setting, 0, 12);
- $output .= _hash_encode64($hash, 16, $itoa64);
- return $output;
- }
- /**
- * Hashes an email address to a big integer
- *
- * @param string $email Email address
- * @return string Big Integer
- */
- function phpbb_email_hash($email)
- {
- return sprintf('%u', crc32(strtolower($email))) . strlen($email);
- }
- //Form validation
- /**
- * Add a secret hash for use in links/GET requests
- * @param string $link_name The name of the link; has to match the name used in check_link_hash, otherwise no restrictions apply
- * @return string the hash
- */
- function generate_link_hash($link_name)
- {
- global $user;
- if (!isset($user->data["hash_$link_name"]))
- {
- $user->data["hash_$link_name"] = substr(sha1($user->data['user_form_salt'] . $link_name), 0, 8);
- }
- return $user->data["hash_$link_name"];
- }
- /**
- * checks a link hash - for GET requests
- * @param string $token the submitted token
- * @param string $link_name The name of the link
- * @return boolean true if all is fine
- */
- function check_link_hash($token, $link_name)
- {
- return $token === generate_link_hash($link_name);
- }
- /**
- * Add a secret token to the form (requires the S_FORM_TOKEN template variable)
- * @param string $form_name The name of the form; has to match the name used in check_form_key, otherwise no restrictions apply
- */
- function add_form_key($form_name)
- {
- global $config, $template, $user;
- $now = time();
- $token_sid = (($user->data['user_id'] == ANONYMOUS) && !empty($config['form_token_sid_guests'])) ? $user->data['session_id'] : '';
- $token = sha1($now . $user->data['user_form_salt'] . $form_name . $token_sid);
- $s_fields = build_hidden_fields(array(
- 'creation_time' => $now,
- 'form_token' => $token,
- )
- );
- $template->assign_vars(array(
- 'S_FORM_TOKEN' => $s_fields,
- )
- );
- }
- /**
- * Check the form key. Required for all altering actions not secured by confirm_box
- * @param string $form_name The name of the form; has to match the name used in add_form_key, otherwise no restrictions apply
- * @param int $timespan The maximum acceptable age for a submitted form in seconds. Defaults to the config setting.
- * @param string $return_page The address for the return link
- * @param bool $trigger If true, the function will triger an error when encountering an invalid form
- */
- function check_form_key($form_name, $timespan = false, $return_page = '', $trigger = false)
- {
- global $config, $user, $lang;
- if ($timespan === false)
- {
- // we enforce a minimum value of half a minute here.
- $timespan = ($config['form_token_lifetime'] == -1) ? -1 : max(30, $config['form_token_lifetime']);
- }
- if (isset($_POST['creation_time']) && isset($_POST['form_token']))
- {
- $creation_time = abs(request_var('creation_time', 0));
- $token = request_var('form_token', '');
- $diff = time() - $creation_time;
- // If creation_time and the time() now is zero we can assume it was not a human doing this (the check for if ($diff)...
- if ($diff && (($diff <= $timespan) || ($timespan === -1)))
- {
- $token_sid = (($user->data['user_id'] == ANONYMOUS) && !empty($config['form_token_sid_guests'])) ? $user->data['session_id'] : '';
- $key = sha1($creation_time . $user->data['user_form_salt'] . $form_name . $token_sid);
- if ($key === $token)
- {
- return true;
- }
- }
- }
- if ($trigger)
- {
- trigger_error($lang['FORM_INVALID'] . $return_page);
- }
- return false;
- }
- // added at phpBB 2.0.11 to properly format the username
- function phpbb_clean_username($username)
- {
- $username = substr(htmlspecialchars(trim($username)), 0, 36);
- $username = rtrim($username, "\\");
- return $username;
- }
- /*
- * Function to clear all unwanted chars in username
- */
- function ip_clean_username($username)
- {
- $username = preg_replace('/[^A-Za-z0-9\-_. ]+/', '', trim($username));
- return $username;
- }
- /*
- * Create email signature
- */
- function create_signature($signature = '')
- {
- global $config;
- $signature = !empty($signature) ? $signature : $config['board_email_sig'];
- $email_sig = (!empty($signature) ? str_replace('<br />', "\n", $config['sig_line'] . " \n" . $signature) : '');
- if (!empty($config['html_email']))
- {
- $email_sig = nl2br($email_sig);
- }
- return $email_sig;
- }
- /*
- * Clean string
- */
- function ip_clean_string($text, $charset = false, $extra_chars = false, $is_filename = false)
- {
- $charset = empty($charset) ? 'utf-8' : $charset;
- // Function needed to convert some of the German characters into Latin correspondent characters
- $text = utf_ger_to_latin($text, false);
- // Function needed to convert some of the Cyrillic characters into Latin correspondent characters
- $text = utf_cyr_to_latin($text, false);
- // Remove all HTML tags and convert to lowercase
- $text = strtolower(strip_tags($text));
- // Convert &
- $text = str_replace(array('&', ' ', '"'), array('&', ' ', ''), $text);
- // Decode all HTML entities
- $text = html_entity_decode($text, ENT_COMPAT, $charset);
- // Some common chars replacements... are we sure we want to replace "&"???
- $find = array('&', '@', '©', '®', '€', '$', '£');
- $repl = array('and', 'at', 'copyright', 'rights', 'euro', 'dollar', 'pound');
- $text = str_replace($find, $repl, $text);
- // Attempt to convert all HTML numeric entities.
- if (preg_match('@\&\#\d+;@s', $text))
- {
- $text = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $text);
- }
- // Convert back all HTML entities into their aliases
- // Mighty Gorgon: added a workaround for some special case... :-(
- $text_tmp = $text;
- $text = @htmlentities($text, ENT_COMPAT, $charset);
- if (!empty($text_tmp) && empty($text))
- {
- $text = htmlentities($text_tmp);
- }
- // Replace some known HTML entities
- $find = array(
- 'Č', 'č', // c
- 'Ť', 'ť', // t
- 'Ď', 'ď', // d
- 'Ľ', 'ľ', // L, l
- 'Ň', 'ň', // N, n
- 'Ž', 'ž', 'Ž', 'ž', // z
- 'ß', 'β', 'ß', // ß
- 'œ', 'Œ', 'œ', // OE, oe
- 'Æ', 'æ', // AE, ae
- 'š', 'Š', // 'š','Š'
- 'đ', 'Đ', // ?', '?', // 'dj','dj'
- '`', '‘', '’',
- );
- $repl = array(
- 'c', 'c',
- 't', 't',
- 'd', 'd',
- 'l', 'l',
- 'n', 'n',
- 'z', 'z', 'z', 'z',
- 'ss', 'ss', 'ss',
- 'oe', 'oe', 'oe',
- 'ae', 'ae',
- 's', 's',
- 'dj', 'dj',
- '-', '-', '-',
- );
- $text = str_replace($find, $repl, $text);
- // Convert localized special chars
- $text = preg_replace('/&([a-z][ez]?)(?:acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig);/','$1', $text);
- // Convert all remaining special chars
- $text = preg_replace('/&([a-z]+);/', '$1', $text);
- // If still some unrecognized HTML entities are there... kill them!!!
- $text = preg_replace('@\&\#\d+;@s', '', $text);
- // Replace all illegal chars with '-'
- if ($extra_chars || $is_filename)
- {
- // if $extra_chars is true then we will allow spaces, underscores and dots
- $text = preg_replace('![^a-z0-9\-._ ]!s', '-', $text);
- if ($is_filename)
- {
- $text = str_replace(' ', '_', $text);
- }
- }
- else
- {
- $text = preg_replace('![^a-z0-9\-]!s', '-', $text);
- // Convert every white space char with "-"
- $text = preg_replace('!\s+!s', '-', $text);
- }
- // Replace multiple "-"
- $text = preg_replace('!-+!s', '-', $text);
- // Replace multiple "_"
- $text = preg_replace('!_+!s', '_', $text);
- // Remove leading / trailing "-"/"_"...
- $text = preg_replace('!^[-_]|[-_]$!s', '', $text);
- if ($is_filename)
- {
- // Remove any trailing dot at the end, to avoid messing up Windows naming system...
- $text = rtrim($text, '.');
- }
- return $text;
- }
- /**
- * German to Latin chars conversion
- */
- function utf_ger_to_latin($string, $reverse = false)
- {
- $ger = array(
- 'ß', 'β', 'ß', // ß
- 'Ä', 'ä', 'Ä', 'ä', // Ä, ä
- 'Ö', 'ö', 'Ö', 'ö', // Ö, ö
- 'Ü', 'ü', 'Ü', 'ü', // Ü, ü
- );
- $lat = array(
- 'ss', 'ss', 'ss',
- 'ae', 'ae', 'ae', 'ae',
- 'oe', 'oe', 'oe', 'oe',
- 'ue', 'ue', 'ue', 'ue',
- );
- $string = !empty($reverse) ? str_replace($lat, $ger, $string) : str_replace($ger, $lat, $string);
- return $string;
- }
- /**
- * Cyrillic to Latin chars conversion
- */
- function utf_cyr_to_latin($string, $reverse = false)
- {
- $cyr = array(
- 'а', 'б', 'в', 'г', 'д',
- 'e', 'ж', 'з', 'и', 'й',
- 'к', 'л', 'м', 'н', 'о',
- 'п', 'р', 'с', 'т', 'у',
- 'ф', 'х', 'ц', 'ч', 'ш',
- 'щ', 'ъ', 'ь', 'ю', 'я',
- 'А', 'Б', 'В', 'Г', 'Д',
- 'Е', 'Ж', 'З', 'И', 'Й',
- 'К', 'Л', 'М', 'Н', 'О',
- 'П', 'Р', 'С', 'Т', 'У',
- 'Ф', 'Х', 'Ц', 'Ч', 'Ш',
- 'Щ', 'Ъ', 'Ь', 'Ю', 'Я'
- );
- $lat = array(
- 'a', 'b', 'v', 'g', 'd',
- 'e', 'zh', 'z', 'i', 'y',
- 'k', 'l', 'm', 'n', 'o',
- 'p', 'r', 's', 't', 'u',
- 'f', 'h', 'ts', 'ch', 'sh',
- 'sht', 'a', 'y', 'yu', 'ya',
- 'A', 'B', 'V', 'G', 'D',
- 'E', 'Zh', 'Z', 'I', 'Y',
- 'K', 'L', 'M', 'N', 'O',
- 'P', 'R', 'S', 'T', 'U',
- 'F', 'H', 'Ts', 'Ch', 'Sh',
- 'Sht', 'A', 'Y', 'Yu', 'Ya'
- );
- $string = !empty($reverse) ? str_replace($lat, $cyr, $string) : str_replace($cyr, $lat, $string);
- return $string;
- }
- /**
- * Generate back link
- */
- function page_back_link($u_action)
- {
- global $lang;
- return '<br /><br /><a href="' . $u_action . '">« ' . $lang['BACK_TO_PREV'] . '</a>';
- }
- /**
- * Build Confirm box
- * @param boolean $check True for checking if confirmed (without any additional parameters) and false for displaying the confirm box
- * @param string $title Title/Message used for confirm box.
- * message text is _CONFIRM appended to title.
- * If title cannot be found in user->lang a default one is displayed
- * If title_CONFIRM cannot be found in user->lang the text given is used.
- * @param string $hidden Hidden variables
- * @param string $html_body Template used for confirm box
- * @param string $u_action Custom form action
- */
- function confirm_box($check, $title = '', $hidden = '', $html_body = 'confirm_body.tpl', $u_action = '')
- {
- global $db, $user, $lang, $template;
- if (isset($_POST['cancel']))
- {
- return false;
- }
- $confirm = false;
- if (isset($_POST['confirm']))
- {
- // language frontier
- if ($_POST['confirm'] === $lang['YES'])
- {
- $confirm = true;
- }
- }
- if ($check && $confirm)
- {
- $user_id = request_var('confirm_uid', 0);
- $session_id = request_var('sess', '');
- if (($user_id != $user->data['user_id']) || ($session_id != $user->session_id))
- {
- return false;
- }
- return true;
- }
- elseif ($check)
- {
- return false;
- }
- $s_hidden_fields = build_hidden_fields(array(
- 'confirm_uid' => $user->data['user_id'],
- 'sess' => $user->session_id,
- 'sid' => $user->session_id,
- )
- );
- // re-add sid / transform & to & for user->page (user->page is always using &)
- $use_page = ($u_action) ? IP_ROOT_PATH . $u_action : IP_ROOT_PATH . str_replace('&', '&', $user->page['page']);
- $u_action = reapply_sid($use_page);
- $u_action .= ((strpos($u_action, '?') === false) ? '?' : '&');
- $confirm_title = (!isset($lang[$title])) ? $lang['Confirm'] : $lang[$title];
- $template->assign_vars(array(
- 'MESSAGE_TITLE' => $confirm_title,
- 'MESSAGE_TEXT' => (!isset($lang[$title . '_CONFIRM'])) ? $title : $lang[$title . '_CONFIRM'],
- 'YES_VALUE' => $lang['YES'],
- 'S_CONFIRM_ACTION' => $u_action,
- 'S_HIDDEN_FIELDS' => $hidden . $s_hidden_fields
- )
- );
- full_page_generation($html_body, $confirm_title, '', '');
- }
- /*
- * jumpbox() : replace the original phpBB make_jumpbox()
- */
- function jumpbox($action, $match_forum_id = 0)
- {
- global $db, $template, $user, $lang;
- // build the jumpbox
- $boxstring = '<select name="selected_id" onchange="if(this.options[this.selectedIndex].value != -1){ forms[\'jumpbox\'].submit() }">';
- $boxstring .= get_tree_option(POST_FORUM_URL . $match_forum_id);
- $boxstring .= '</select>';
- $boxstring .= '<input type="hidden" name="sid" value="' . $user->data['session_id'] . '" />';
- // dump this to template
- $template->set_filenames(array('jumpbox' => 'jumpbox.tpl'));
- $template->assign_vars(array(
- 'L_GO' => $lang['Go'],
- 'L_JUMP_TO' => $lang['Jump_to'],
- 'L_SELECT_FORUM' => $lang['Select_forum'],
- 'S_JUMPBOX_SELECT' => $boxstring,
- 'S_JUMPBOX_ACTION' => append_sid($action)
- )
- );
- $template->assign_var_from_handle('JUMPBOX', 'jumpbox');
- return;
- }
- /*
- * Creates forum jumpbox
- */
- function make_jumpbox($action, $match_forum_id = 0)
- {
- return jumpbox($action, $match_forum_id);
- }
- /**
- * Checks if a path ($path) is absolute or relative
- *
- * @param string $path Path to check absoluteness of
- * @return boolean
- */
- function is_absolute($path)
- {
- return ($path[0] == '/' || (DIRECTORY_SEPARATOR == '\\' && preg_match('#^[a-z]:/#i', $path))) ? true : false;
- }
- /**
- * @author Chris Smith <chris@project-minerva.org>
- * @copyright 2006 Project Minerva Team
- * @param string $path The path which we should attempt to resolve.
- * @return mixed
- */
- function phpbb_own_realpath($path)
- {
- // Now to perform funky shizzle
- // Switch to use UNIX slashes
- $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
- $path_prefix = '';
- // Determine what sort of path we have
- if (is_absolute($path))
- {
- $absolute = true;
- if ($path[0] == '/')
- {
- // Absolute path, *NIX style
- $path_prefix = '';
- }
- else
- {
- // Absolute path, Windows style
- // Remove the drive letter and colon
- $path_prefix = $path[0] . ':';
- $path = substr($path, 2);
- }
- }
- else
- {
- // Relative Path
- // Prepend the current working directory
- if (function_exists('getcwd'))
- {
- // This is the best method, hopefully it is enabled!
- $path = str_replace(DIRECTORY_SEPARATOR, '/', getcwd()) . '/' . $path;
- $absolute = true;
- if (preg_match('#^[a-z]:#i', $path))
- {
- $path_prefix = $path[0] . ':';
- $path = substr($path, 2);
- }
- else
- {
- $path_prefix = '';
- }
- }
- elseif (isset($_SERVER['SCRIPT_FILENAME']) && !empty($_SERVER['SCRIPT_FILENAME']))
- {
- // Warning: If chdir() has been used this will lie!
- // Warning: This has some problems sometime (CLI can create them easily)
- $path = str_replace(DIRECTORY_SEPARATOR, '/', dirname($_SERVER['SCRIPT_FILENAME'])) . '/' . $path;
- $absolute = true;
- $path_prefix = '';
- }
- else
- {
- // We have no way of getting the absolute path, just run on using relative ones.
- $absolute = false;
- $path_prefix = '.';
- }
- }
- // Remove any repeated slashes
- $path = preg_replace('#/{2,}#', '/', $path);
- // Remove the slashes from the start and end of the path
- $path = trim($path, '/');
- // Break the string into little bits for us to nibble on
- $bits = explode('/', $path);
- // Remove any . in the path, renumber array for the loop below
- $bits = array_values(array_diff($bits, array('.')));
- // Lets get looping, run over and resolve any .. (up directory)
- for ($i = 0, $max = sizeof($bits); $i < $max; $i++)
- {
- // @todo Optimise
- if ($bits[$i] == '..')
- {
- if (isset($bits[$i - 1]))
- {
- if ($bits[$i - 1] != '..')
- {
- // We found a .. and we are able to traverse upwards, lets do it!
- unset($bits[$i]);
- unset($bits[$i - 1]);
- $i -= 2;
- $max -= 2;
- $bits = array_values($bits);
- }
- }
- else if ($absolute) // ie. !isset($bits[$i - 1]) && $absolute
- {
- // We have an absolute path trying to descend above the root of the filesystem
- // ... Error!
- return false;
- }
- }
- }
- // Prepend the path prefix
- array_unshift($bits, $path_prefix);
- $resolved = '';
- $max = sizeof($bits) - 1;
- // Check if we are able to resolve symlinks, Windows cannot.
- $symlink_resolve = (function_exists('readlink')) ? true : false;
- foreach ($bits as $i => $bit)
- {
- if (@is_dir("$resolved/$bit") || ($i == $max && @is_file("$resolved/$bit")))
- {
- // Path Exists
- if ($symlink_resolve && is_link("$resolved/$bit") && ($link = readlink("$resolved/$bit")))
- {
- // Resolved a symlink.
- $resolved = $link . (($i == $max) ? '' : '/');
- continue;
- }
- }
- else
- {
- // Something doesn't exist here!
- // This is correct realpath() behaviour but sadly open_basedir and safe_mode make this problematic
- // return false;
- }
- $resolved .= $bit . (($i == $max) ? '' : '/');
- }
- // @todo If the file exists fine and open_basedir only has one path we should be able to prepend it
- // because we must be inside that basedir, the question is where...
- // @internal The slash in is_dir() gets around an open_basedir restriction
- if (!@file_exists($resolved) || (!is_dir($resolved . '/') && !is_file($resolved)))
- {
- return false;
- }
- // Put the slashes back to the native operating systems slashes
- $resolved = str_replace('/', DIRECTORY_SEPARATOR, $resolved);
- // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
- if (substr($resolved, -1) == DIRECTORY_SEPARATOR)
- {
- return substr($resolved, 0, -1);
- }
- return $resolved; // We got here, in the end!
- }
- /**
- * A wrapper for realpath
- * @ignore
- */
- function phpbb_realpath($path)
- {
- if (!function_exists('realpath'))
- {
- return phpbb_own_realpath($path);
- }
- else
- {
- $realpath = realpath($path);
- // Strangely there are provider not disabling realpath but returning strange values. :o
- // We at least try to cope with them.
- if ($realpath === $path || $realpath === false)
- {
- return phpbb_own_realpath($path);
- }
- // Check for DIRECTORY_SEPARATOR at the end (and remove it!)
- if (substr($realpath, -1) == DIRECTORY_SEPARATOR)
- {
- $realpath = substr($realpath, 0, -1);
- }
- return $realpath;
- }
- }
- /*
- * Creates a full server path
- */
- function create_server_url($without_script_path = false)
- {
- // usage: $server_url = create_server_url();
- global $config;
- $server_protocol = ($config['cookie_secure']) ? 'https://' : 'http://';
- $server_name = preg_replace('#^\/?(.*?)\/?$#', '\1', trim($config['server_name']));
- $server_port = ($config['server_port'] <> 80) ? ':' . trim($config['server_port']) : '';
- $script_name = preg_replace('/^\/?(.*?)\/?$/', '\1', trim($config['script_path']));
- $script_name = ($script_name == '') ? '' : '/' . $script_name;
- $server_url = $server_protocol . $server_name . $server_port . ($without_sc…
Large files files are truncated, but you can click here to view the full file