[feature/request-class] Add server(), header() and is_ajax() to request

Extend the request class with helpers for reading server vars (server())
and HTTP request headers (header()). Refactor the existing code base
to make use of these helpers, make $_SERVER a deactivated super global.

Also introduce an is_ajax() method, which checks the X-Requested-With
header for the value 'XMLHttpRequest', which is sent by JavaScript
libraries, such as jQuery.

PHPBB3-9716
This commit is contained in:
Igor Wiedler 2011-07-13 19:20:16 +02:00
parent 09e0460e5b
commit 0bf6966c52
23 changed files with 318 additions and 152 deletions

View file

@ -63,7 +63,7 @@ if (isset($_GET['avatar']))
unset($dbpasswd);
// worst-case default
$browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : 'msie 6.0';
$browser = strtolower($request->header('User-Agent', 'msie 6.0'));
$config = new phpbb_config_db($db, $cache->get_driver(), CONFIG_TABLE);
set_config(null, null, null, $config);

View file

@ -486,6 +486,8 @@ class base_extractor
function base_extractor($download = false, $store = false, $format, $filename, $time)
{
global $request;
$this->download = $download;
$this->store = $store;
$this->time = $time;
@ -530,7 +532,7 @@ class base_extractor
break;
case 'gzip':
if ((isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) && strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'msie') === false)
if (strpos($request->header('Accept-Encoding'), 'gzip') !== false && strpos(strtolower($request->header('User-Agent')), 'msie') === false)
{
ob_start('ob_gzhandler');
}
@ -1580,7 +1582,7 @@ class mssql_extractor extends base_extractor
}
$this->flush($sql_data);
}
function write_data_mssqlnative($table_name)
{
global $db;
@ -1606,7 +1608,7 @@ class mssql_extractor extends base_extractor
$row = new result_mssqlnative($result_fields);
$i_num_fields = $row->num_fields();
for ($i = 0; $i < $i_num_fields; $i++)
{
$ary_type[$i] = $row->field_type($i);
@ -1619,7 +1621,7 @@ class mssql_extractor extends base_extractor
WHERE COLUMNPROPERTY(object_id('$table_name'), COLUMN_NAME, 'IsIdentity') = 1";
$result2 = $db->sql_query($sql);
$row2 = $db->sql_fetchrow($result2);
if (!empty($row2['has_identity']))
{
$sql_data .= "\nSET IDENTITY_INSERT $table_name ON\nGO\n";
@ -1683,8 +1685,8 @@ class mssql_extractor extends base_extractor
$sql_data .= "\nSET IDENTITY_INSERT $table_name OFF\nGO\n";
}
$this->flush($sql_data);
}
}
function write_data_odbc($table_name)
{
global $db;

View file

@ -28,9 +28,9 @@ if (!defined('IN_PHPBB'))
*/
function init_apache()
{
global $user;
global $user, $request;
if (!isset($_SERVER['PHP_AUTH_USER']) || $user->data['username'] !== $_SERVER['PHP_AUTH_USER'])
if (!$request->is_set('PHP_AUTH_USER', phpbb_request_interface::SERVER) || $user->data['username'] !== $request->server('PHP_AUTH_USER'))
{
return $user->lang['APACHE_SETUP_BEFORE_USE'];
}
@ -42,7 +42,7 @@ function init_apache()
*/
function login_apache(&$username, &$password)
{
global $db;
global $db, $request;
// do not allow empty password
if (!$password)
@ -63,7 +63,7 @@ function login_apache(&$username, &$password)
);
}
if (!isset($_SERVER['PHP_AUTH_USER']))
if (!$request->is_set('PHP_AUTH_USER', phpbb_request_interface::SERVER))
{
return array(
'status' => LOGIN_ERROR_EXTERNAL_AUTH,
@ -72,8 +72,8 @@ function login_apache(&$username, &$password)
);
}
$php_auth_user = $_SERVER['PHP_AUTH_USER'];
$php_auth_pw = $_SERVER['PHP_AUTH_PW'];
$php_auth_user = $request->server('PHP_AUTH_USER');
$php_auth_pw = $request->server('PHP_AUTH_PW');
if (!empty($php_auth_user) && !empty($php_auth_pw))
{
@ -136,15 +136,15 @@ function login_apache(&$username, &$password)
*/
function autologin_apache()
{
global $db;
global $db, $request;
if (!isset($_SERVER['PHP_AUTH_USER']))
if (!$request->is_set('PHP_AUTH_USER', phpbb_request_interface::SERVER))
{
return array();
}
$php_auth_user = $_SERVER['PHP_AUTH_USER'];
$php_auth_pw = $_SERVER['PHP_AUTH_PW'];
$php_auth_user = $request->server('PHP_AUTH_USER');
$php_auth_pw = $request->server('PHP_AUTH_PW');
if (!empty($php_auth_user) && !empty($php_auth_pw))
{
@ -228,11 +228,12 @@ function user_row_apache($username, $password)
*/
function validate_session_apache(&$user)
{
global $request;
// Check if PHP_AUTH_USER is set and handle this case
if (isset($_SERVER['PHP_AUTH_USER']))
if ($request->is_set('PHP_AUTH_USER', phpbb_request_interface::SERVER))
{
$php_auth_user = '';
set_var($php_auth_user, $_SERVER['PHP_AUTH_USER'], 'string', true);
$php_auth_user = $request->server('PHP_AUTH_USER', '', true);
return ($php_auth_user === $user['username']) ? true : false;
}

View file

@ -41,7 +41,8 @@ class phpbb_recaptcha extends phpbb_default_captcha
// PHP4 Constructor
function phpbb_recaptcha()
{
$this->recaptcha_server = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? $this->recaptcha_server_secure : $this->recaptcha_server;
global $request;
$this->recaptcha_server = $request->server('HTTPS') == 'on' ? $this->recaptcha_server_secure : $this->recaptcha_server;
}
function init($type)

View file

@ -781,6 +781,8 @@ function is_absolute($path)
*/
function phpbb_own_realpath($path)
{
global $request;
// Now to perform funky shizzle
// Switch to use UNIX slashes
@ -824,11 +826,11 @@ function phpbb_own_realpath($path)
$path_prefix = '';
}
}
else if (isset($_SERVER['SCRIPT_FILENAME']) && !empty($_SERVER['SCRIPT_FILENAME']))
else if ($request->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;
$path = str_replace(DIRECTORY_SEPARATOR, '/', dirname($request->server('SCRIPT_FILENAME'))) . '/' . $path;
$absolute = true;
$path_prefix = '';
}
@ -2048,10 +2050,10 @@ function append_sid($url, $params = false, $is_amp = true, $session_id = false)
*/
function generate_board_url($without_script_path = false)
{
global $config, $user;
global $config, $user, $request;
$server_name = $user->host;
$server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
$server_port = $request->server('SERVER_PORT', 0);
// Forcing server vars is the only way to specify/override the protocol
if ($config['force_server_vars'] || !$server_name)
@ -2067,7 +2069,7 @@ function generate_board_url($without_script_path = false)
else
{
// Do not rely on cookie_secure, users seem to think that it means a secured cookie instead of an encrypted connection
$cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
$cookie_secure = $request->server('HTTPS') == 'on' ? 1 : 0;
$url = (($cookie_secure) ? 'https://' : 'http://') . $server_name;
$script_path = $user->page['root_script_path'];
@ -2419,6 +2421,8 @@ function meta_refresh($time, $url, $disable_cd_check = false)
*/
function send_status_line($code, $message)
{
global $request;
if (substr(strtolower(@php_sapi_name()), 0, 3) === 'cgi')
{
// in theory, we shouldn't need that due to php doing it. Reality offers a differing opinion, though
@ -2426,15 +2430,15 @@ function send_status_line($code, $message)
}
else
{
if (!empty($_SERVER['SERVER_PROTOCOL']))
if ($request->server('SERVER_PROTOCOL'))
{
$version = $_SERVER['SERVER_PROTOCOL'];
$version = $request->server('SERVER_PROTOCOL');
}
else if (!empty($_SERVER['HTTP_VERSION']))
else if ($request->server('HTTP_VERSION'))
{
// I cannot remember where I got this from.
// This code path may never be reachable in reality.
$version = $_SERVER['HTTP_VERSION'];
$version = $request->server('HTTP_VERSION');
}
else
{
@ -4144,7 +4148,7 @@ function phpbb_optionset($bit, $set, $data)
*/
function phpbb_http_login($param)
{
global $auth, $user;
global $auth, $user, $request;
global $config;
$param_defaults = array(
@ -4184,9 +4188,9 @@ function phpbb_http_login($param)
$username = null;
foreach ($username_keys as $k)
{
if (isset($_SERVER[$k]))
if ($request->is_set($k, phpbb_request_interface::SERVER))
{
$username = $_SERVER[$k];
$username = $request->server($k);
break;
}
}
@ -4194,9 +4198,9 @@ function phpbb_http_login($param)
$password = null;
foreach ($password_keys as $k)
{
if (isset($_SERVER[$k]))
if ($request->is_set($k, phpbb_request_interface::SERVER))
{
$password = $_SERVER[$k];
$password = $request->server($k);
break;
}
}

View file

@ -274,7 +274,9 @@ function send_file_to_browser($attachment, $upload_dir, $category)
*/
function header_filename($file)
{
$user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
global $request;
$user_agent = $request->header('User-Agent', '', true);
// There be dragons here.
// Not many follows the RFC...
@ -292,14 +294,14 @@ function header_filename($file)
*/
function download_allowed()
{
global $config, $user, $db;
global $config, $user, $db, $request;
if (!$config['secure_downloads'])
{
return true;
}
$url = (!empty($_SERVER['HTTP_REFERER'])) ? trim($_SERVER['HTTP_REFERER']) : trim(getenv('HTTP_REFERER'));
$url = trim($request->header('Referer'));
if (!$url)
{
@ -404,8 +406,10 @@ function download_allowed()
*/
function set_modified_headers($stamp, $browser)
{
global $request;
// let's see if we have to send the file at all
$last_load = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime(trim($_SERVER['HTTP_IF_MODIFIED_SINCE'])) : false;
$last_load = $request->header('Modified-Since') ? strtotime(trim($request->header('Modified-Since'))) : false;
if ((strpos(strtolower($browser), 'msie 6.0') === false) && (strpos(strtolower($browser), 'msie 8.0') === false))
{
if ($last_load !== false && $last_load >= $stamp)
@ -473,12 +477,12 @@ function phpbb_http_byte_range($filesize)
{
$request_array = phpbb_find_range_request();
}
return (empty($request_array)) ? false : phpbb_parse_range_request($request_array, $filesize);
}
/**
* Searches for HTTP range request in super globals.
* Searches for HTTP range request in request headers.
*
* @return mixed false if no request found
* array of strings containing the requested ranges otherwise
@ -486,23 +490,16 @@ function phpbb_http_byte_range($filesize)
*/
function phpbb_find_range_request()
{
$globals = array(
array('_SERVER', 'HTTP_RANGE'),
array('_ENV', 'HTTP_RANGE'),
);
global $request;
foreach ($globals as $array)
$value = $request->header('Range');
// Make sure range request starts with "bytes="
if (strpos($value, 'bytes=') === 0)
{
$global = $array[0];
$key = $array[1];
// Make sure range request starts with "bytes="
if (isset($GLOBALS[$global][$key]) && strpos($GLOBALS[$global][$key], 'bytes=') === 0)
{
// Strip leading 'bytes='
// Multiple ranges can be separated by a comma
return explode(',', substr($GLOBALS[$global][$key], 6));
}
// Strip leading 'bytes='
// Multiple ranges can be separated by a comma
return explode(',', substr($value, 6));
}
return false;

View file

@ -333,7 +333,7 @@ class messenger
*/
function error($type, $msg)
{
global $user, $phpEx, $phpbb_root_path, $config;
global $user, $phpEx, $phpbb_root_path, $config, $request;
// Session doesn't exist, create it
if (!isset($user->session_id) || $user->session_id === '')
@ -341,7 +341,7 @@ class messenger
$user->session_begin();
}
$calling_page = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : $_ENV['PHP_SELF'];
$calling_page = $request->server('PHP_SELF');
$message = '';
switch ($type)

View file

@ -148,23 +148,15 @@ class phpbb_questionnaire_system_data_provider
*/
function get_data()
{
global $request;
// Start discovering the IPV4 server address, if available
$server_address = '0.0.0.0';
if (!empty($_SERVER['SERVER_ADDR']))
{
$server_address = $_SERVER['SERVER_ADDR'];
}
// Running on IIS?
if (!empty($_SERVER['LOCAL_ADDR']))
{
$server_address = $_SERVER['LOCAL_ADDR'];
}
// Try apache, IIS, fall back to 0.0.0.0
$server_address = $request->server('SERVER_ADDR', $request->server('LOCAL_ADDR', '0.0.0.0'));
return array(
'os' => PHP_OS,
'httpd' => $_SERVER['SERVER_SOFTWARE'],
'httpd' => $request->server('SERVER_SOFTWARE'),
// we don't want the real IP address (for privacy policy reasons) but only
// a network address to see whether your installation is running on a private or public network.
'private_ip' => $this->is_private_ip($server_address),
@ -482,7 +474,7 @@ class phpbb_questionnaire_phpbb_data_provider
}
}
global $db;
global $db, $request;
$result['dbms'] = $dbms;
$result['acm_type'] = $acm_type;
@ -492,7 +484,7 @@ class phpbb_questionnaire_phpbb_data_provider
// Try to get user agent vendor and version
$match = array();
$user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])) ? (string) $_SERVER['HTTP_USER_AGENT'] : '';
$user_agent = $request->header('User-Agent');
$agents = array('firefox', 'msie', 'opera', 'chrome', 'safari', 'mozilla', 'seamonkey', 'konqueror', 'netscape', 'gecko', 'navigator', 'mosaic', 'lynx', 'amaya', 'omniweb', 'avant', 'camino', 'flock', 'aol');
// We check here 1 by 1 because some strings occur after others (for example Mozilla [...] Firefox/)

View file

@ -29,6 +29,7 @@ interface phpbb_request_interface
const GET = 1;
const REQUEST = 2;
const COOKIE = 3;
const SERVER = 4;
/**#@-*/
/**
@ -60,11 +61,34 @@ interface phpbb_request_interface
* Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks
* @param phpbb_request_interface::POST|GET|REQUEST|COOKIE $super_global
* Specifies which super global should be used
* @param bool $html_encode When true, html encoding will be applied
*
* @return mixed The value of $_REQUEST[$var_name] run through {@link set_var set_var} to ensure that the type is the
* the same as that of $default. If the variable is not set $default is returned.
*/
public function variable($var_name, $default, $multibyte = false, $super_global = phpbb_request_interface::REQUEST);
public function variable($var_name, $default, $multibyte = false, $super_global = phpbb_request_interface::REQUEST, $html_encode = true);
/**
* Shortcut method to retrieve SERVER variables.
*
* @param string|array $var_name See phpbb_request_interface::variable
* @param mixed $default See phpbb_request_interface::variable
* @param bool $html_encode See phpbb_request_interface::variable
*
* @return mixed The server variable value.
*/
public function server($var_name, $default = '', $html_encode = false);
/**
* Shortcut method to retrieve the value of client HTTP headers.
*
* @param string|array $header_name The name of the header to retrieve.
* @param mixed $default See phpbb_request_interface::variable
* @param bool $html_encode See phpbb_request_interface::variable
*
* @return mixed The header value.
*/
public function header($var_name, $default = '', $html_encode = false);
/**
* Checks whether a certain variable was sent via POST.
@ -90,6 +114,13 @@ interface phpbb_request_interface
*/
public function is_set($var, $super_global = phpbb_request_interface::REQUEST);
/**
* Checks whether the current request is an AJAX request (XMLHttpRequest)
*
* @return bool True if the current request is an ajax request
*/
public function is_ajax();
/**
* Returns all variable names for a given super global
*

View file

@ -32,7 +32,8 @@ class phpbb_request implements phpbb_request_interface
phpbb_request_interface::POST => '_POST',
phpbb_request_interface::GET => '_GET',
phpbb_request_interface::REQUEST => '_REQUEST',
phpbb_request_interface::COOKIE => '_COOKIE'
phpbb_request_interface::COOKIE => '_COOKIE',
phpbb_request_interface::SERVER => '_SERVER',
);
/**
@ -193,11 +194,12 @@ class phpbb_request implements phpbb_request_interface
* Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks
* @param phpbb_request_interface::POST|GET|REQUEST|COOKIE $super_global
* Specifies which super global should be used
* @param bool $html_encode When true, html encoding will be applied
*
* @return mixed The value of $_REQUEST[$var_name] run through {@link set_var set_var} to ensure that the type is the
* the same as that of $default. If the variable is not set $default is returned.
*/
public function variable($var_name, $default, $multibyte = false, $super_global = phpbb_request_interface::REQUEST)
public function variable($var_name, $default, $multibyte = false, $super_global = phpbb_request_interface::REQUEST, $html_encode = true)
{
$path = false;
@ -236,11 +238,54 @@ class phpbb_request implements phpbb_request_interface
}
}
$this->type_cast_helper->recursive_set_var($var, $default, $multibyte);
$this->type_cast_helper->recursive_set_var($var, $default, $multibyte, $html_encode);
return $var;
}
/**
* Shortcut method to retrieve SERVER variables.
*
* Also fall back to getenv(), some CGI setups may need it (probably not, but
* whatever).
*
* @param string|array $var_name See phpbb_request_interface::variable
* @param mixed $Default See phpbb_request_interface::variable
* @param bool $html_encode See phpbb_request_interface::variable
*
* @return mixed The server variable value.
*/
public function server($var_name, $default = '', $html_encode = false)
{
$multibyte = true;
if ($this->is_set($var_name, phpbb_request_interface::SERVER))
{
return $this->variable($var_name, $default, $multibyte, phpbb_request_interface::SERVER);
}
else
{
$var = getenv($var_name);
$this->type_cast_helper->recursive_set_var($var, $default, $multibyte);
return $var;
}
}
/**
* Shortcut method to retrieve the value of client HTTP headers.
*
* @param string|array $header_name The name of the header to retrieve.
* @param mixed $default See phpbb_request_interface::variable
* @param bool $html_encode See phpbb_request_interface::variable
*
* @return mixed The header value.
*/
public function header($header_name, $default = '', $html_encode = true)
{
$var_name = 'HTTP_'.str_replace('-', '_', strtoupper($header_name));
return $this->server($var_name, $default, $html_encode);
}
/**
* Checks whether a certain variable was sent via POST.
* To make sure that a request was sent using POST you should call this function
@ -271,6 +316,16 @@ class phpbb_request implements phpbb_request_interface
return isset($this->input[$super_global][$var]);
}
/**
* Checks whether the current request is an AJAX request (XMLHttpRequest)
*
* @return bool True if the current request is an ajax request
*/
public function is_ajax()
{
return $this->header('X-Requested-With') == 'XMLHttpRequest';
}
/**
* Returns all variable names for a given super global
*

View file

@ -88,20 +88,26 @@ class phpbb_request_type_cast_helper implements phpbb_request_type_cast_helper_i
/**
* Set variable $result to a particular type.
*
* @param mixed &$result The variable to fill
* @param mixed $var The contents to fill with
* @param mixed $type The variable type. Will be used with {@link settype()}
* @param bool $multibyte Indicates whether string values may contain UTF-8 characters.
* Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks.
* @param mixed &$result The variable to fill
* @param mixed $var The contents to fill with
* @param mixed $type The variable type. Will be used with {@link settype()}
* @param bool $multibyte Indicates whether string values may contain UTF-8 characters.
* Default is false, causing all bytes outside the ASCII range (0-127) to be replaced with question marks.
* @param bool $html_encode When true, html encoding will be applied
*/
public function set_var(&$result, $var, $type, $multibyte = false)
public function set_var(&$result, $var, $type, $multibyte = false, $html_encode = true)
{
settype($var, $type);
$result = $var;
if ($type == 'string')
{
$result = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $result), ENT_COMPAT, 'UTF-8'));
$result = trim(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $result));
if ($html_encode)
{
$result = htmlspecialchars($result, ENT_COMPAT, 'UTF-8');
}
if ($multibyte)
{
@ -140,8 +146,9 @@ class phpbb_request_type_cast_helper implements phpbb_request_type_cast_helper_i
* @param bool $multibyte Indicates whether string keys and values may contain UTF-8 characters.
* Default is false, causing all bytes outside the ASCII range (0-127) to
* be replaced with question marks.
* @param bool $html_encode When true, html encoding will be applied
*/
public function recursive_set_var(&$var, $default, $multibyte)
public function recursive_set_var(&$var, $default, $multibyte, $html_encode = true)
{
if (is_array($var) !== is_array($default))
{
@ -152,7 +159,7 @@ class phpbb_request_type_cast_helper implements phpbb_request_type_cast_helper_i
if (!is_array($default))
{
$type = gettype($default);
$this->set_var($var, $var, $type, $multibyte);
$this->set_var($var, $var, $type, $multibyte, $html_encode);
}
else
{
@ -173,9 +180,9 @@ class phpbb_request_type_cast_helper implements phpbb_request_type_cast_helper_i
foreach ($_var as $k => $v)
{
$this->set_var($k, $k, $key_type, $multibyte, $multibyte);
$this->set_var($k, $k, $key_type, $multibyte, $multibyte, $html_encode);
$this->recursive_set_var($v, $default_value, $multibyte);
$this->recursive_set_var($v, $default_value, $multibyte, $html_encode);
$var[$k] = $v;
}
}

View file

@ -41,16 +41,18 @@ class session
*/
static function extract_current_page($root_path)
{
global $request;
$page_array = array();
// First of all, get the request uri...
$script_name = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : getenv('PHP_SELF');
$args = (!empty($_SERVER['QUERY_STRING'])) ? explode('&', $_SERVER['QUERY_STRING']) : explode('&', getenv('QUERY_STRING'));
$script_name = $request->server('PHP_SELF');
$args = explode('&', $request->server('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 = $request->server('REQUEST_URI');
$script_name = (($pos = strpos($script_name, '?')) !== false) ? substr($script_name, 0, $pos) : $script_name;
$page_array['failover'] = 1;
}
@ -141,10 +143,10 @@ class session
*/
function extract_current_hostname()
{
global $config;
global $config, $request;
// Get hostname
$host = (!empty($_SERVER['HTTP_HOST'])) ? $_SERVER['HTTP_HOST'] : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
$host = $request->header('Host', $request->server('SERVER_NAME'));
// Should be a string and lowered
$host = (string) strtolower($host);
@ -212,9 +214,9 @@ class session
$this->time_now = time();
$this->cookie_data = array('u' => 0, 'k' => '');
$this->update_session_page = $update_session_page;
$this->browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
$this->referer = (!empty($_SERVER['HTTP_REFERER'])) ? htmlspecialchars((string) $_SERVER['HTTP_REFERER']) : '';
$this->forwarded_for = (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) ? htmlspecialchars((string) $_SERVER['HTTP_X_FORWARDED_FOR']) : '';
$this->browser = $request->header('User-Agent', '', true);
$this->referer = $request->header('Referer', '', true);
$this->forwarded_for = $request->header('X-Forwarded-For', '', true);
$this->host = $this->extract_current_hostname();
$this->page = $this->extract_current_page($phpbb_root_path);
@ -268,7 +270,7 @@ class session
// Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests
// it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip.
$this->ip = (!empty($_SERVER['REMOTE_ADDR'])) ? (string) $_SERVER['REMOTE_ADDR'] : '';
$this->ip = $request->server('REMOTE_ADDR');
$this->ip = preg_replace('# {2,}#', ' ', str_replace(',', ' ', $this->ip));
// split the list of IPs
@ -382,7 +384,7 @@ class session
$referer_valid = true;
// we assume HEAD and TRACE to be foul play and thus only whitelist GET
if (@$config['referer_validation'] && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) !== 'get')
if (@$config['referer_validation'] && $request->server('REQUEST_METHOD') && strtolower($request->server('REQUEST_METHOD')) !== 'get')
{
$referer_valid = $this->validate_referer($check_referer_path);
}
@ -1449,7 +1451,7 @@ class session
*/
function validate_referer($check_script_path = false)
{
global $config;
global $config, $request;
// no referer - nothing to validate, user's fault for turning it off (we only check on POST; so meta can't be the reason)
if (empty($this->referer) || empty($this->host))
@ -1467,7 +1469,7 @@ class session
else if ($check_script_path && rtrim($this->page['root_script_path'], '/') !== '')
{
$ref = substr($ref, strlen($host));
$server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
$server_port = $request->server('SERVER_PORT', 0);
if ($server_port !== 80 && $server_port !== 443 && stripos($ref, ":$server_port") === 0)
{
@ -1592,9 +1594,9 @@ class user extends session
* If re-enabled we need to make sure only those languages installed are checked
* Commented out so we do not loose the code.
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
if ($request->header('Accept-Language'))
{
$accept_lang_ary = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$accept_lang_ary = explode(',', $request->header('Accept-Language'));
foreach ($accept_lang_ary as $accept_lang)
{

View file

@ -144,9 +144,9 @@ $db->sql_connect($dbhost, $dbuser, $dbpasswd, $dbname, $dbport, false, false);
unset($dbpasswd);
$user->ip = '';
if (!empty($_SERVER['REMOTE_ADDR']))
if ($request->server('REMOTE_ADDR'))
{
$user->ip = (function_exists('phpbb_ip_normalise')) ? phpbb_ip_normalise($_SERVER['REMOTE_ADDR']) : htmlspecialchars($_SERVER['REMOTE_ADDR']);
$user->ip = (function_exists('phpbb_ip_normalise')) ? phpbb_ip_normalise($request->server('REMOTE_ADDR')) : $request->server('REMOTE_ADDR', '', true);
}
$sql = "SELECT config_value

View file

@ -100,9 +100,9 @@ request_var('', 0, false, false, $request); // "dependency injection" for a func
// Try and load an appropriate language if required
$language = basename(request_var('language', ''));
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) && !$language)
if ($request->header('Accept-Language') && !$language)
{
$accept_lang_ary = explode(',', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']));
$accept_lang_ary = explode(',', strtolower($request->header('Accept-Language')));
foreach ($accept_lang_ary as $accept_lang)
{
// Set correct format ... guess full xx_yy form
@ -428,15 +428,17 @@ class module
*/
function redirect($page)
{
// HTTP_HOST is having the correct browser url in most cases...
$server_name = (!empty($_SERVER['HTTP_HOST'])) ? strtolower($_SERVER['HTTP_HOST']) : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
$server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');
$secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 1 : 0;
global $request;
$script_name = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : getenv('PHP_SELF');
// HTTP_HOST is having the correct browser url in most cases...
$server_name = strtolower($request->header('Host', $request->server('SERVER_NAME')));
$server_port = $request->server('SERVER_PORT', 0);
$secure = ($request->server('HTTPS') == 'on') ? 1 : 0;
$script_name = $request->server('PHP_SELF');
if (!$script_name)
{
$script_name = (!empty($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI');
$script_name = $request->server('REQUEST_URI');
}
// Replace backslashes and doubled slashes (could happen on some proxy setups)

View file

@ -999,7 +999,7 @@ class install_install extends module
*/
function obtain_advanced_settings($mode, $sub)
{
global $lang, $template, $phpEx;
global $lang, $template, $phpEx, $request;
$this->page_title = $lang['STAGE_ADVANCED'];
@ -1017,7 +1017,7 @@ class install_install extends module
$s_hidden_fields .= '<input type="hidden" name="language" value="' . $data['language'] . '" />';
// HTTP_HOST is having the correct browser url in most cases...
$server_name = (!empty($_SERVER['HTTP_HOST'])) ? strtolower($_SERVER['HTTP_HOST']) : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
$server_name = strtolower($request->header('Host', $request->server('SERVER_NAME')));
// HTTP HOST can carry a port number...
if (strpos($server_name, ':') !== false)
@ -1027,16 +1027,16 @@ class install_install extends module
$data['email_enable'] = ($data['email_enable'] !== '') ? $data['email_enable'] : true;
$data['server_name'] = ($data['server_name'] !== '') ? $data['server_name'] : $server_name;
$data['server_port'] = ($data['server_port'] !== '') ? $data['server_port'] : ((!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT'));
$data['server_protocol'] = ($data['server_protocol'] !== '') ? $data['server_protocol'] : ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://');
$data['cookie_secure'] = ($data['cookie_secure'] !== '') ? $data['cookie_secure'] : ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? true : false);
$data['server_port'] = ($data['server_port'] !== '') ? $data['server_port'] : $request->server('SERVER_PORT', 0);
$data['server_protocol'] = ($data['server_protocol'] !== '') ? $data['server_protocol'] : ($request->server('HTTPS') == 'on' ? 'https://' : 'http://');
$data['cookie_secure'] = ($data['cookie_secure'] !== '') ? $data['cookie_secure'] : ($request->server('HTTPS') == 'on' ? true : false);
if ($data['script_path'] === '')
{
$name = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : getenv('PHP_SELF');
$name = $request->server('PHP_SELF');
if (!$name)
{
$name = (!empty($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI');
$name = $request->server('REQUEST_URI');
}
// Replace backslashes and doubled slashes (could happen on some proxy setups)
@ -1101,7 +1101,7 @@ class install_install extends module
*/
function load_schema($mode, $sub)
{
global $db, $lang, $template, $phpbb_root_path, $phpEx;
global $db, $lang, $template, $phpbb_root_path, $phpEx, $request;
$this->page_title = $lang['STAGE_CREATE_TABLE'];
$s_hidden_fields = '';
@ -1117,8 +1117,8 @@ class install_install extends module
}
// HTTP_HOST is having the correct browser url in most cases...
$server_name = (!empty($_SERVER['HTTP_HOST'])) ? strtolower($_SERVER['HTTP_HOST']) : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
$referer = (!empty($_SERVER['HTTP_REFERER'])) ? strtolower($_SERVER['HTTP_REFERER']) : getenv('HTTP_REFERER');
$server_name = strtolower($request->header('Host', $request->server('SERVER_NAME')));
$referer = strtolower($request->header('Referer'));
// HTTP HOST can carry a port number...
if (strpos($server_name, ':') !== false)
@ -1235,7 +1235,7 @@ class install_install extends module
$current_time = time();
$user_ip = (!empty($_SERVER['REMOTE_ADDR'])) ? phpbb_ip_normalise($_SERVER['REMOTE_ADDR']) : '';
$user_ip = $request->server('REMOTE_ADDR') ? phpbb_ip_normalise($request->server('REMOTE_ADDR')) : '';
if ($data['script_path'] !== '/')
{

View file

@ -152,7 +152,7 @@ if ($id)
if ($config['gzip_compress'])
{
// IE6 is not able to compress the style (do not ask us why!)
$browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? strtolower(htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT'])) : '';
$browser = strtolower($request->header('User-Agent', '', true));
if ($browser && strpos($browser, 'msie 6.0') === false && @extension_loaded('zlib') && !headers_sent())
{

View file

@ -12,6 +12,7 @@ require_once dirname(__FILE__) . '/../../phpBB/includes/functions_content.php';
require_once dirname(__FILE__) . '/../../phpBB/includes/bbcode.php';
require_once dirname(__FILE__) . '/../../phpBB/includes/message_parser.php';
require_once dirname(__FILE__) . '/../mock_user.php';
require_once dirname(__FILE__) . '/../mock/request.php';
class phpbb_url_bbcode_test extends phpbb_test_case
{
@ -51,8 +52,9 @@ class phpbb_url_bbcode_test extends phpbb_test_case
*/
public function test_url($description, $message, $expected)
{
global $user;
global $user, $request;
$user = new phpbb_mock_user;
$request = new phpbb_mock_request;
$bbcode = new bbcode_firstpass();
$bbcode->message = $message;

View file

@ -8,23 +8,27 @@
*/
require_once dirname(__FILE__) . '/../../phpBB/includes/functions_download.php';
require_once dirname(__FILE__) . '/../mock/request.php';
class phpbb_download_http_byte_range_test extends phpbb_test_case
{
public function test_find_range_request()
{
// Missing 'bytes=' prefix
$_SERVER['HTTP_RANGE'] = 'bztes=';
$GLOBALS['request'] = new phpbb_mock_request();
$GLOBALS['request']->set_header('Range', 'bztes=');
$this->assertEquals(false, phpbb_find_range_request());
unset($_SERVER['HTTP_RANGE']);
unset($GLOBALS['request']);
$GLOBALS['request'] = new phpbb_mock_request();
$_ENV['HTTP_RANGE'] = 'bztes=';
$this->assertEquals(false, phpbb_find_range_request());
unset($_ENV['HTTP_RANGE']);
$_SERVER['HTTP_RANGE'] = 'bytes=0-0,123-125';
$GLOBALS['request'] = new phpbb_mock_request();
$GLOBALS['request']->set_header('Range', 'bytes=0-0,123-125');
$this->assertEquals(array('0-0', '123-125'), phpbb_find_range_request());
unset($_SERVER['HTTP_RANGE']);
unset($GLOBALS['request']);
}
/**

View file

@ -11,12 +11,13 @@ class phpbb_mock_request implements phpbb_request_interface
{
protected $data;
public function __construct($get = array(), $post = array(), $cookie = array(), $request = false)
public function __construct($get = array(), $post = array(), $cookie = array(), $server = array(), $request = false)
{
$this->data[phpbb_request_interface::GET] = $get;
$this->data[phpbb_request_interface::POST] = $post;
$this->data[phpbb_request_interface::COOKIE] = $cookie;
$this->data[phpbb_request_interface::REQUEST] = ($request === false) ? $post + $get : $request;
$this->data[phpbb_request_interface::SERVER] = $server;
}
public function overwrite($var_name, $value, $super_global = phpbb_request_interface::REQUEST)
@ -24,11 +25,23 @@ class phpbb_mock_request implements phpbb_request_interface
$this->data[$super_global][$var_name] = $value;
}
public function variable($var_name, $default, $multibyte = false, $super_global = phpbb_request_interface::REQUEST)
public function variable($var_name, $default, $multibyte = false, $super_global = phpbb_request_interface::REQUEST, $html_encode = true)
{
return isset($this->data[$super_global][$var_name]) ? $this->data[$super_global][$var_name] : $default;
}
public function server($var_name, $default = '', $html_encode = false)
{
$super_global = phpbb_request_interface::SERVER;
return isset($this->data[$super_global][$var_name]) ? $this->data[$super_global][$var_name] : $default;
}
public function header($header_name, $default = '', $html_encode = false)
{
$var_name = 'HTTP_'.str_replace('-', '_', strtoupper($header_name));
return $this->server($var_name, $default, $html_encode);
}
public function is_set_post($name)
{
return $this->is_set($name, phpbb_request_interface::POST);
@ -39,8 +52,26 @@ class phpbb_mock_request implements phpbb_request_interface
return isset($this->data[$super_global][$var]);
}
public function is_ajax()
{
return false;
}
public function variable_names($super_global = phpbb_request_interface::REQUEST)
{
return array_keys($this->data[$super_global]);
}
/* custom methods */
public function set_header($header_name, $value)
{
$var_name = 'HTTP_'.str_replace('-', '_', strtoupper($header_name));
$this->data[phpbb_request_interface::SERVER][$var_name] = $value;
}
public function merge($super_global = phpbb_request_interface::REQUEST, $values)
{
$this->data[$super_global] = array_merge($this->data[$super_global], $values);
}
}

View file

@ -23,7 +23,6 @@ class phpbb_request_test extends phpbb_test_case
$_GET['unset'] = '';
$this->type_cast_helper = $this->getMock('phpbb_request_type_cast_helper_interface');
$this->request = new phpbb_request($this->type_cast_helper);
}
@ -60,6 +59,20 @@ class phpbb_request_test extends phpbb_test_case
$this->assertFalse($this->request->is_set_post('unset'));
}
public function test_is_ajax_without_ajax()
{
$this->assertFalse($this->request->is_ajax());
}
public function test_is_ajax_with_ajax()
{
$this->request->enable_super_globals();
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->request = new phpbb_request($this->type_cast_helper);
$this->assertTrue($this->request->is_ajax());
}
public function test_variable_names()
{
$expected = array('test', 'unset');

View file

@ -48,4 +48,14 @@ class phpbb_type_cast_helper_test extends phpbb_test_case
$this->assertEquals($expected, $data);
}
public function test_simple_set_var_without_html_encoding()
{
$data = 'eviL<3';
$expected = 'eviL<3';
$this->type_cast_helper->recursive_set_var($data, '', true, false);
$this->assertEquals($expected, $data);
}
}

View file

@ -7,6 +7,8 @@
*
*/
require_once dirname(__FILE__) . '/../mock/request.php';
abstract class phpbb_security_test_base extends phpbb_test_case
{
/**
@ -14,20 +16,20 @@ abstract class phpbb_security_test_base extends phpbb_test_case
*/
protected function setUp()
{
global $user, $phpbb_root_path;
global $user, $phpbb_root_path, $request;
// Put this into a global function being run by every test to init a proper user session
$_SERVER['HTTP_HOST'] = 'localhost';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['SERVER_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_PORT'] = 80;
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['QUERY_STRING'] = '';
$_SERVER['REQUEST_URI'] = '/tests/';
$_SERVER['SCRIPT_NAME'] = '/tests/index.php';
$_SERVER['PHP_SELF'] = '/tests/index.php';
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14';
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'de-de,de;q=0.8,en-us;q=0.5,en;q=0.3';
$server['HTTP_HOST'] = 'localhost';
$server['SERVER_NAME'] = 'localhost';
$server['SERVER_ADDR'] = '127.0.0.1';
$server['SERVER_PORT'] = 80;
$server['REMOTE_ADDR'] = '127.0.0.1';
$server['QUERY_STRING'] = '';
$server['REQUEST_URI'] = '/tests/';
$server['SCRIPT_NAME'] = '/tests/index.php';
$server['PHP_SELF'] = '/tests/index.php';
$server['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows; U; Windows NT 6.0; de; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14';
$server['HTTP_ACCEPT_LANGUAGE'] = 'de-de,de;q=0.8,en-us;q=0.5,en;q=0.3';
/*
[HTTP_ACCEPT_ENCODING] => gzip,deflate
@ -36,13 +38,15 @@ abstract class phpbb_security_test_base extends phpbb_test_case
[SCRIPT_FILENAME] => /var/www/tests/index.php
*/
$request = new phpbb_mock_request(array(), array(), array(), $server);
// Set no user and trick a bit to circumvent errors
$user = new user();
$user->lang = true;
$user->browser = (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars((string) $_SERVER['HTTP_USER_AGENT']) : '';
$user->referer = (!empty($_SERVER['HTTP_REFERER'])) ? htmlspecialchars((string) $_SERVER['HTTP_REFERER']) : '';
$user->forwarded_for = (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) ? (string) $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
$user->host = (!empty($_SERVER['HTTP_HOST'])) ? (string) strtolower($_SERVER['HTTP_HOST']) : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
$user->browser = $server['HTTP_USER_AGENT'];
$user->referer = '';
$user->forwarded_for = '';
$user->host = $server['HTTP_HOST'];
$user->page = session::extract_current_page($phpbb_root_path);
}

View file

@ -27,8 +27,12 @@ class phpbb_security_extract_current_page_test extends phpbb_security_test_base
*/
public function test_query_string_php_self($url, $query_string, $expected)
{
$_SERVER['PHP_SELF'] = $url;
$_SERVER['QUERY_STRING'] = $query_string;
global $request;
$request->merge(phpbb_request_interface::SERVER, array(
'PHP_SELF' => $url,
'QUERY_STRING' => $query_string,
));
$result = session::extract_current_page('./');
@ -41,8 +45,12 @@ class phpbb_security_extract_current_page_test extends phpbb_security_test_base
*/
public function test_query_string_request_uri($url, $query_string, $expected)
{
$_SERVER['REQUEST_URI'] = $url . '?' . $query_string;
$_SERVER['QUERY_STRING'] = $query_string;
global $request;
$request->merge(phpbb_request_interface::SERVER, array(
'PHP_SELF' => $url,
'QUERY_STRING' => $query_string,
));
$result = session::extract_current_page('./');