* // $_REQUEST['db'] not set
* echo Core::ifSetOr($_REQUEST['db'], ''); // ''
* // $_POST['sql_query'] not set
* echo Core::ifSetOr($_POST['sql_query']); // null
* // $cfg['EnableFoo'] not set
* echo Core::ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
* echo Core::ifSetOr($cfg['EnableFoo']); // null
* // $cfg['EnableFoo'] set to 1
* echo Core::ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
* echo Core::ifSetOr($cfg['EnableFoo'], false, 'similar'); // 1
* echo Core::ifSetOr($cfg['EnableFoo'], false); // 1
* // $cfg['EnableFoo'] set to true
* echo Core::ifSetOr($cfg['EnableFoo'], false, 'boolean'); // true
*
*
* @param mixed &$var param to check
* @param mixed $default default value
* @param mixed $type var type or array of values to check against $var
*
* @return mixed $var or $default
*
* @see self::isValid()
*/
public static function ifSetOr(&$var, $default = null, $type = 'similar')
{
if (! self::isValid($var, $type, $default)) {
return $default;
}
return $var;
}
/**
* checks given $var against $type or $compare
*
* $type can be:
* - false : no type checking
* - 'scalar' : whether type of $var is integer, float, string or boolean
* - 'numeric' : whether type of $var is any number representation
* - 'length' : whether type of $var is scalar with a string length > 0
* - 'similar' : whether type of $var is similar to type of $compare
* - 'equal' : whether type of $var is identical to type of $compare
* - 'identical' : whether $var is identical to $compare, not only the type!
* - or any other valid PHP variable type
*
*
* // $_REQUEST['doit'] = true;
* Core::isValid($_REQUEST['doit'], 'identical', 'true'); // false
* // $_REQUEST['doit'] = 'true';
* Core::isValid($_REQUEST['doit'], 'identical', 'true'); // true
*
*
* NOTE: call-by-reference is used to not get NOTICE on undefined vars,
* but the var is not altered inside this function, also after checking a var
* this var exists nut is not set, example:
*
* // $var is not set
* isset($var); // false
* functionCallByReference($var); // false
* isset($var); // true
* functionCallByReference($var); // true
*
*
* to avoid this we set this var to null if not isset
*
* @param mixed &$var variable to check
* @param mixed $type var type or array of valid values to check against $var
* @param mixed $compare var to compare with $var
*
* @return boolean whether valid or not
*
* @todo add some more var types like hex, bin, ...?
* @see https://secure.php.net/gettype
*/
public static function isValid(&$var, $type = 'length', $compare = null)
{
if (! isset($var)) {
// var is not even set
return false;
}
if ($type === false) {
// no vartype requested
return true;
}
if (is_array($type)) {
return in_array($var, $type);
}
// allow some aliases of var types
$type = strtolower($type);
switch ($type) {
case 'identic' :
$type = 'identical';
break;
case 'len' :
$type = 'length';
break;
case 'bool' :
$type = 'boolean';
break;
case 'float' :
$type = 'double';
break;
case 'int' :
$type = 'integer';
break;
case 'null' :
$type = 'NULL';
break;
}
if ($type === 'identical') {
return $var === $compare;
}
// whether we should check against given $compare
if ($type === 'similar') {
switch (gettype($compare)) {
case 'string':
case 'boolean':
$type = 'scalar';
break;
case 'integer':
case 'double':
$type = 'numeric';
break;
default:
$type = gettype($compare);
}
} elseif ($type === 'equal') {
$type = gettype($compare);
}
// do the check
if ($type === 'length' || $type === 'scalar') {
$is_scalar = is_scalar($var);
if ($is_scalar && $type === 'length') {
return strlen($var) > 0;
}
return $is_scalar;
}
if ($type === 'numeric') {
return is_numeric($var);
}
return gettype($var) === $type;
}
/**
* Removes insecure parts in a path; used before include() or
* require() when a part of the path comes from an insecure source
* like a cookie or form.
*
* @param string $path The path to check
*
* @return string The secured path
*
* @access public
*/
public static function securePath($path)
{
// change .. to .
$path = preg_replace('@\.\.*@', '.', $path);
return $path;
} // end function
/**
* displays the given error message on phpMyAdmin error page in foreign language,
* ends script execution and closes session
*
* loads language file if not loaded already
*
* @param string $error_message the error message or named error message
* @param string|array $message_args arguments applied to $error_message
*
* @return void
*/
public static function fatalError($error_message, $message_args = null) {
/* Use format string if applicable */
if (is_string($message_args)) {
$error_message = sprintf($error_message, $message_args);
} elseif (is_array($message_args)) {
$error_message = vsprintf($error_message, $message_args);
}
/*
* Avoid using Response class as config does not have to be loaded yet
* (this can happen on early fatal error)
*/
if (isset($GLOBALS['dbi']) && !is_null($GLOBALS['dbi']) && isset($GLOBALS['PMA_Config']) && $GLOBALS['PMA_Config']->get('is_setup') === false && Response::getInstance()->isAjax()) {
$response = Response::getInstance();
$response->setRequestStatus(false);
$response->addJSON('message', Message::error($error_message));
} elseif (! empty($_REQUEST['ajax_request'])) {
// Generate JSON manually
self::headerJSON();
echo json_encode(
array(
'success' => false,
'message' => Message::error($error_message)->getDisplay(),
)
);
} else {
$error_message = strtr($error_message, array('
' => '[br]'));
$error_header = __('Error');
$lang = isset($GLOBALS['lang']) ? $GLOBALS['lang'] : 'en';
$dir = isset($GLOBALS['text_dir']) ? $GLOBALS['text_dir'] : 'ltr';
// Displays the error message
include './libraries/error.inc.php';
}
if (! defined('TESTSUITE')) {
exit;
}
}
/**
* Returns a link to the PHP documentation
*
* @param string $target anchor in documentation
*
* @return string the URL
*
* @access public
*/
public static function getPHPDocLink($target)
{
/* List of PHP documentation translations */
$php_doc_languages = array(
'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr'
);
$lang = 'en';
if (in_array($GLOBALS['lang'], $php_doc_languages)) {
$lang = $GLOBALS['lang'];
}
return self::linkURL('https://secure.php.net/manual/' . $lang . '/' . $target);
}
/**
* Warn or fail on missing extension.
*
* @param string $extension Extension name
* @param bool $fatal Whether the error is fatal.
* @param string $extra Extra string to append to message.
*
* @return void
*/
public static function warnMissingExtension($extension, $fatal = false, $extra = '')
{
/* Gettext does not have to be loaded yet here */
if (function_exists('__')) {
$message = __(
'The %s extension is missing. Please check your PHP configuration.'
);
} else {
$message
= 'The %s extension is missing. Please check your PHP configuration.';
}
$doclink = self::getPHPDocLink('book.' . $extension . '.php');
$message = sprintf(
$message,
'[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
);
if ($extra != '') {
$message .= ' ' . $extra;
}
if ($fatal) {
self::fatalError($message);
return;
}
$GLOBALS['error_handler']->addError(
$message,
E_USER_WARNING,
'',
'',
false
);
}
/**
* returns count of tables in given db
*
* @param string $db database to count tables for
*
* @return integer count of tables in $db
*/
public static function getTableCount($db)
{
$tables = $GLOBALS['dbi']->tryQuery(
'SHOW TABLES FROM ' . Util::backquote($db) . ';',
DatabaseInterface::CONNECT_USER,
DatabaseInterface::QUERY_STORE
);
if ($tables) {
$num_tables = $GLOBALS['dbi']->numRows($tables);
$GLOBALS['dbi']->freeResult($tables);
} else {
$num_tables = 0;
}
return $num_tables;
}
/**
* Converts numbers like 10M into bytes
* Used with permission from Moodle (https://moodle.org) by Martin Dougiamas
* (renamed with PMA prefix to avoid double definition when embedded
* in Moodle)
*
* @param string|int $size size (Default = 0)
*
* @return integer $size
*/
public static function getRealSize($size = 0)
{
if (! $size) {
return 0;
}
$binaryprefixes = array(
'T' => 1099511627776,
't' => 1099511627776,
'G' => 1073741824,
'g' => 1073741824,
'M' => 1048576,
'm' => 1048576,
'K' => 1024,
'k' => 1024,
);
if (preg_match('/^([0-9]+)([KMGT])/i', $size, $matches)) {
return $matches[1] * $binaryprefixes[$matches[2]];
}
return (int) $size;
} // end getRealSize()
/**
* boolean phpMyAdmin.Core::checkPageValidity(string &$page, array $whitelist)
*
* checks given $page against given $whitelist and returns true if valid
* it optionally ignores query parameters in $page (script.php?ignored)
*
* @param string &$page page to check
* @param array $whitelist whitelist to check page against
* @param boolean $include whether the page is going to be included
*
* @return boolean whether $page is valid or not (in $whitelist or not)
*/
public static function checkPageValidity(&$page, array $whitelist = [], $include = false)
{
if (empty($whitelist)) {
$whitelist = self::$goto_whitelist;
}
if (! isset($page) || !is_string($page)) {
return false;
}
if (in_array($page, $whitelist)) {
return true;
}
if ($include) {
return false;
}
$_page = mb_substr(
$page,
0,
mb_strpos($page . '?', '?')
);
if (in_array($_page, $whitelist)) {
return true;
}
$_page = urldecode($page);
$_page = mb_substr(
$_page,
0,
mb_strpos($_page . '?', '?')
);
if (in_array($_page, $whitelist)) {
return true;
}
return false;
}
/**
* tries to find the value for the given environment variable name
*
* searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
* in this order
*
* @param string $var_name variable name
*
* @return string value of $var or empty string
*/
public static function getenv($var_name)
{
if (isset($_SERVER[$var_name])) {
return $_SERVER[$var_name];
}
if (isset($_ENV[$var_name])) {
return $_ENV[$var_name];
}
if (getenv($var_name)) {
return getenv($var_name);
}
if (function_exists('apache_getenv')
&& apache_getenv($var_name, true)
) {
return apache_getenv($var_name, true);
}
return '';
}
/**
* Send HTTP header, taking IIS limits into account (600 seems ok)
*
* @param string $uri the header to send
* @param bool $use_refresh whether to use Refresh: header when running on IIS
*
* @return void
*/
public static function sendHeaderLocation($uri, $use_refresh = false)
{
if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && mb_strlen($uri) > 600) {
Response::getInstance()->disable();
echo Template::get('header_location')
->render(array('uri' => $uri));
return;
}
/*
* Avoid relative path redirect problems in case user entered URL
* like /phpmyadmin/index.php/ which some web servers happily accept.
*/
if ($uri[0] == '.') {
$uri = $GLOBALS['PMA_Config']->getRootPath() . substr($uri, 2);
}
$response = Response::getInstance();
session_write_close();
if ($response->headersSent()) {
trigger_error(
'Core::sendHeaderLocation called when headers are already sent!',
E_USER_ERROR
);
}
// bug #1523784: IE6 does not like 'Refresh: 0', it
// results in a blank page
// but we need it when coming from the cookie login panel)
if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && $use_refresh) {
$response->header('Refresh: 0; ' . $uri);
} else {
$response->header('Location: ' . $uri);
}
}
/**
* Outputs application/json headers. This includes no caching.
*
* @return void
*/
public static function headerJSON()
{
if (defined('TESTSUITE')) {
return;
}
// No caching
self::noCacheHeader();
// MIME type
header('Content-Type: application/json; charset=UTF-8');
// Disable content sniffing in browser
// This is needed in case we include HTML in JSON, browser might assume it's
// html to display
header('X-Content-Type-Options: nosniff');
}
/**
* Outputs headers to prevent caching in browser (and on the way).
*
* @return void
*/
public static function noCacheHeader()
{
if (defined('TESTSUITE')) {
return;
}
// rfc2616 - Section 14.21
header('Expires: ' . gmdate(DATE_RFC1123));
// HTTP/1.1
header(
'Cache-Control: no-store, no-cache, must-revalidate,'
. ' pre-check=0, post-check=0, max-age=0'
);
header('Pragma: no-cache'); // HTTP/1.0
// test case: exporting a database into a .gz file with Safari
// would produce files not having the current time
// (added this header for Safari but should not harm other browsers)
header('Last-Modified: ' . gmdate(DATE_RFC1123));
}
/**
* Sends header indicating file download.
*
* @param string $filename Filename to include in headers if empty,
* none Content-Disposition header will be sent.
* @param string $mimetype MIME type to include in headers.
* @param int $length Length of content (optional)
* @param bool $no_cache Whether to include no-caching headers.
*
* @return void
*/
public static function downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
{
if ($no_cache) {
self::noCacheHeader();
}
/* Replace all possibly dangerous chars in filename */
$filename = Sanitize::sanitizeFilename($filename);
if (!empty($filename)) {
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
header('Content-Type: ' . $mimetype);
// inform the server that compression has been done,
// to avoid a double compression (for example with Apache + mod_deflate)
$notChromeOrLessThan43 = PMA_USR_BROWSER_AGENT != 'CHROME' // see bug #4942
|| (PMA_USR_BROWSER_AGENT == 'CHROME' && PMA_USR_BROWSER_VER < 43);
if (strpos($mimetype, 'gzip') !== false && $notChromeOrLessThan43) {
header('Content-Encoding: gzip');
}
header('Content-Transfer-Encoding: binary');
if ($length > 0) {
header('Content-Length: ' . $length);
}
}
/**
* Returns value of an element in $array given by $path.
* $path is a string describing position of an element in an associative array,
* eg. Servers/1/host refers to $array[Servers][1][host]
*
* @param string $path path in the array
* @param array $array the array
* @param mixed $default default value
*
* @return mixed array element or $default
*/
public static function arrayRead($path, array $array, $default = null)
{
$keys = explode('/', $path);
$value =& $array;
foreach ($keys as $key) {
if (! isset($value[$key])) {
return $default;
}
$value =& $value[$key];
}
return $value;
}
/**
* Stores value in an array
*
* @param string $path path in the array
* @param array &$array the array
* @param mixed $value value to store
*
* @return void
*/
public static function arrayWrite($path, array &$array, $value)
{
$keys = explode('/', $path);
$last_key = array_pop($keys);
$a =& $array;
foreach ($keys as $key) {
if (! isset($a[$key])) {
$a[$key] = array();
}
$a =& $a[$key];
}
$a[$last_key] = $value;
}
/**
* Removes value from an array
*
* @param string $path path in the array
* @param array &$array the array
*
* @return void
*/
public static function arrayRemove($path, array &$array)
{
$keys = explode('/', $path);
$keys_last = array_pop($keys);
$path = array();
$depth = 0;
$path[0] =& $array;
$found = true;
// go as deep as required or possible
foreach ($keys as $key) {
if (! isset($path[$depth][$key])) {
$found = false;
break;
}
$depth++;
$path[$depth] =& $path[$depth - 1][$key];
}
// if element found, remove it
if ($found) {
unset($path[$depth][$keys_last]);
$depth--;
}
// remove empty nested arrays
for (; $depth >= 0; $depth--) {
if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
unset($path[$depth][$keys[$depth]]);
} else {
break;
}
}
}
/**
* Returns link to (possibly) external site using defined redirector.
*
* @param string $url URL where to go.
*
* @return string URL for a link.
*/
public static function linkURL($url)
{
if (!preg_match('#^https?://#', $url)) {
return $url;
}
$params = array();
$params['url'] = $url;
$url = Url::getCommon($params);
//strip off token and such sensitive information. Just keep url.
$arr = parse_url($url);
parse_str($arr["query"], $vars);
$query = http_build_query(array("url" => $vars["url"]));
if (!is_null($GLOBALS['PMA_Config']) && $GLOBALS['PMA_Config']->get('is_setup')) {
$url = '../url.php?' . $query;
} else {
$url = './url.php?' . $query;
}
return $url;
}
/**
* Checks whether domain of URL is whitelisted domain or not.
* Use only for URLs of external sites.
*
* @param string $url URL of external site.
*
* @return boolean True: if domain of $url is allowed domain,
* False: otherwise.
*/
public static function isAllowedDomain($url)
{
$arr = parse_url($url);
// We need host to be set
if (! isset($arr['host']) || strlen($arr['host']) == 0) {
return false;
}
// We do not want these to be present
$blocked = array('user', 'pass', 'port');
foreach ($blocked as $part) {
if (isset($arr[$part]) && strlen($arr[$part]) != 0) {
return false;
}
}
$domain = $arr["host"];
$domainWhiteList = array(
/* Include current domain */
$_SERVER['SERVER_NAME'],
/* phpMyAdmin domains */
'wiki.phpmyadmin.net',
'www.phpmyadmin.net',
'phpmyadmin.net',
'demo.phpmyadmin.net',
'docs.phpmyadmin.net',
/* mysql.com domains */
'dev.mysql.com','bugs.mysql.com',
/* mariadb domains */
'mariadb.org', 'mariadb.com',
/* php.net domains */
'php.net',
'secure.php.net',
/* Github domains*/
'github.com','www.github.com',
/* Percona domains */
'www.percona.com',
/* Following are doubtful ones. */
'mysqldatabaseadministration.blogspot.com',
);
return in_array($domain, $domainWhiteList);
}
/**
* Replace some html-unfriendly stuff
*
* @param string $buffer String to process
*
* @return string Escaped and cleaned up text suitable for html
*/
public static function mimeDefaultFunction($buffer)
{
$buffer = htmlspecialchars($buffer);
$buffer = str_replace(' ', ' ', $buffer);
$buffer = preg_replace("@((\015\012)|(\015)|(\012))@", '
' . "\n", $buffer);
return $buffer;
}
/**
* Displays SQL query before executing.
*
* @param array|string $query_data Array containing queries or query itself
*
* @return void
*/
public static function previewSQL($query_data)
{
$retval = '