Fix some coding standard issues detected by PHPCS
[phpmyadmin.git] / libraries / classes / Core.php
blobbf5edde41a0e1f0767532267db66e7ba51a4d320
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Core functions used all over the scripts.
5 * This script is distinct from libraries/common.inc.php because this
6 * script is called from /test.
8 * @package PhpMyAdmin
9 */
10 namespace PhpMyAdmin;
12 use PhpMyAdmin\DatabaseInterface;
13 use PhpMyAdmin\Message;
14 use PhpMyAdmin\Response;
15 use PhpMyAdmin\Sanitize;
16 use PhpMyAdmin\Template;
17 use PhpMyAdmin\Url;
18 use PhpMyAdmin\Util;
20 /**
21 * Core class
23 * @package PhpMyAdmin
25 class Core
27 /**
28 * the whitelist for goto parameter
29 * @static array $goto_whitelist
31 public static $goto_whitelist = array(
32 'db_datadict.php',
33 'db_sql.php',
34 'db_events.php',
35 'db_export.php',
36 'db_importdocsql.php',
37 'db_multi_table_query.php',
38 'db_qbe.php',
39 'db_structure.php',
40 'db_import.php',
41 'db_operations.php',
42 'db_search.php',
43 'db_routines.php',
44 'export.php',
45 'import.php',
46 'index.php',
47 'pdf_pages.php',
48 'pdf_schema.php',
49 'server_binlog.php',
50 'server_collations.php',
51 'server_databases.php',
52 'server_engines.php',
53 'server_export.php',
54 'server_import.php',
55 'server_privileges.php',
56 'server_sql.php',
57 'server_status.php',
58 'server_status_advisor.php',
59 'server_status_monitor.php',
60 'server_status_queries.php',
61 'server_status_variables.php',
62 'server_variables.php',
63 'sql.php',
64 'tbl_addfield.php',
65 'tbl_change.php',
66 'tbl_create.php',
67 'tbl_import.php',
68 'tbl_indexes.php',
69 'tbl_sql.php',
70 'tbl_export.php',
71 'tbl_operations.php',
72 'tbl_structure.php',
73 'tbl_relation.php',
74 'tbl_replace.php',
75 'tbl_row_action.php',
76 'tbl_select.php',
77 'tbl_zoom_select.php',
78 'transformation_overview.php',
79 'transformation_wrapper.php',
80 'user_password.php',
83 /**
84 * checks given $var and returns it if valid, or $default of not valid
85 * given $var is also checked for type being 'similar' as $default
86 * or against any other type if $type is provided
88 * <code>
89 * // $_REQUEST['db'] not set
90 * echo Core::ifSetOr($_REQUEST['db'], ''); // ''
91 * // $_POST['sql_query'] not set
92 * echo Core::ifSetOr($_POST['sql_query']); // null
93 * // $cfg['EnableFoo'] not set
94 * echo Core::ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
95 * echo Core::ifSetOr($cfg['EnableFoo']); // null
96 * // $cfg['EnableFoo'] set to 1
97 * echo Core::ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
98 * echo Core::ifSetOr($cfg['EnableFoo'], false, 'similar'); // 1
99 * echo Core::ifSetOr($cfg['EnableFoo'], false); // 1
100 * // $cfg['EnableFoo'] set to true
101 * echo Core::ifSetOr($cfg['EnableFoo'], false, 'boolean'); // true
102 * </code>
104 * @param mixed &$var param to check
105 * @param mixed $default default value
106 * @param mixed $type var type or array of values to check against $var
108 * @return mixed $var or $default
110 * @see self::isValid()
112 public static function ifSetOr(&$var, $default = null, $type = 'similar')
114 if (! self::isValid($var, $type, $default)) {
115 return $default;
118 return $var;
122 * checks given $var against $type or $compare
124 * $type can be:
125 * - false : no type checking
126 * - 'scalar' : whether type of $var is integer, float, string or boolean
127 * - 'numeric' : whether type of $var is any number representation
128 * - 'length' : whether type of $var is scalar with a string length > 0
129 * - 'similar' : whether type of $var is similar to type of $compare
130 * - 'equal' : whether type of $var is identical to type of $compare
131 * - 'identical' : whether $var is identical to $compare, not only the type!
132 * - or any other valid PHP variable type
134 * <code>
135 * // $_REQUEST['doit'] = true;
136 * Core::isValid($_REQUEST['doit'], 'identical', 'true'); // false
137 * // $_REQUEST['doit'] = 'true';
138 * Core::isValid($_REQUEST['doit'], 'identical', 'true'); // true
139 * </code>
141 * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
142 * but the var is not altered inside this function, also after checking a var
143 * this var exists nut is not set, example:
144 * <code>
145 * // $var is not set
146 * isset($var); // false
147 * functionCallByReference($var); // false
148 * isset($var); // true
149 * functionCallByReference($var); // true
150 * </code>
152 * to avoid this we set this var to null if not isset
154 * @param mixed &$var variable to check
155 * @param mixed $type var type or array of valid values to check against $var
156 * @param mixed $compare var to compare with $var
158 * @return boolean whether valid or not
160 * @todo add some more var types like hex, bin, ...?
161 * @see https://secure.php.net/gettype
163 public static function isValid(&$var, $type = 'length', $compare = null)
165 if (! isset($var)) {
166 // var is not even set
167 return false;
170 if ($type === false) {
171 // no vartype requested
172 return true;
175 if (is_array($type)) {
176 return in_array($var, $type);
179 // allow some aliases of var types
180 $type = strtolower($type);
181 switch ($type) {
182 case 'identic' :
183 $type = 'identical';
184 break;
185 case 'len' :
186 $type = 'length';
187 break;
188 case 'bool' :
189 $type = 'boolean';
190 break;
191 case 'float' :
192 $type = 'double';
193 break;
194 case 'int' :
195 $type = 'integer';
196 break;
197 case 'null' :
198 $type = 'NULL';
199 break;
202 if ($type === 'identical') {
203 return $var === $compare;
206 // whether we should check against given $compare
207 if ($type === 'similar') {
208 switch (gettype($compare)) {
209 case 'string':
210 case 'boolean':
211 $type = 'scalar';
212 break;
213 case 'integer':
214 case 'double':
215 $type = 'numeric';
216 break;
217 default:
218 $type = gettype($compare);
220 } elseif ($type === 'equal') {
221 $type = gettype($compare);
224 // do the check
225 if ($type === 'length' || $type === 'scalar') {
226 $is_scalar = is_scalar($var);
227 if ($is_scalar && $type === 'length') {
228 return strlen($var) > 0;
230 return $is_scalar;
233 if ($type === 'numeric') {
234 return is_numeric($var);
237 return gettype($var) === $type;
241 * Removes insecure parts in a path; used before include() or
242 * require() when a part of the path comes from an insecure source
243 * like a cookie or form.
245 * @param string $path The path to check
247 * @return string The secured path
249 * @access public
251 public static function securePath($path)
253 // change .. to .
254 $path = preg_replace('@\.\.*@', '.', $path);
256 return $path;
257 } // end function
260 * displays the given error message on phpMyAdmin error page in foreign language,
261 * ends script execution and closes session
263 * loads language file if not loaded already
265 * @param string $error_message the error message or named error message
266 * @param string|array $message_args arguments applied to $error_message
268 * @return void
270 public static function fatalError($error_message, $message_args = null) {
271 /* Use format string if applicable */
272 if (is_string($message_args)) {
273 $error_message = sprintf($error_message, $message_args);
274 } elseif (is_array($message_args)) {
275 $error_message = vsprintf($error_message, $message_args);
279 * Avoid using Response class as config does not have to be loaded yet
280 * (this can happen on early fatal error)
282 if (isset($GLOBALS['dbi']) && !is_null($GLOBALS['dbi']) && isset($GLOBALS['PMA_Config']) && $GLOBALS['PMA_Config']->get('is_setup') === false && Response::getInstance()->isAjax()) {
283 $response = Response::getInstance();
284 $response->setRequestStatus(false);
285 $response->addJSON('message', Message::error($error_message));
286 } elseif (! empty($_REQUEST['ajax_request'])) {
287 // Generate JSON manually
288 self::headerJSON();
289 echo json_encode(
290 array(
291 'success' => false,
292 'message' => Message::error($error_message)->getDisplay(),
295 } else {
296 $error_message = strtr($error_message, array('<br />' => '[br]'));
297 $error_header = __('Error');
298 $lang = isset($GLOBALS['lang']) ? $GLOBALS['lang'] : 'en';
299 $dir = isset($GLOBALS['text_dir']) ? $GLOBALS['text_dir'] : 'ltr';
301 // Displays the error message
302 include './libraries/error.inc.php';
304 if (! defined('TESTSUITE')) {
305 exit;
310 * Returns a link to the PHP documentation
312 * @param string $target anchor in documentation
314 * @return string the URL
316 * @access public
318 public static function getPHPDocLink($target)
320 /* List of PHP documentation translations */
321 $php_doc_languages = array(
322 'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr'
325 $lang = 'en';
326 if (in_array($GLOBALS['lang'], $php_doc_languages)) {
327 $lang = $GLOBALS['lang'];
330 return self::linkURL('https://secure.php.net/manual/' . $lang . '/' . $target);
334 * Warn or fail on missing extension.
336 * @param string $extension Extension name
337 * @param bool $fatal Whether the error is fatal.
338 * @param string $extra Extra string to append to message.
340 * @return void
342 public static function warnMissingExtension($extension, $fatal = false, $extra = '')
344 /* Gettext does not have to be loaded yet here */
345 if (function_exists('__')) {
346 $message = __(
347 'The %s extension is missing. Please check your PHP configuration.'
349 } else {
350 $message
351 = 'The %s extension is missing. Please check your PHP configuration.';
353 $doclink = self::getPHPDocLink('book.' . $extension . '.php');
354 $message = sprintf(
355 $message,
356 '[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
358 if ($extra != '') {
359 $message .= ' ' . $extra;
361 if ($fatal) {
362 self::fatalError($message);
363 return;
366 $GLOBALS['error_handler']->addError(
367 $message,
368 E_USER_WARNING,
371 false
376 * returns count of tables in given db
378 * @param string $db database to count tables for
380 * @return integer count of tables in $db
382 public static function getTableCount($db)
384 $tables = $GLOBALS['dbi']->tryQuery(
385 'SHOW TABLES FROM ' . Util::backquote($db) . ';',
386 DatabaseInterface::CONNECT_USER,
387 DatabaseInterface::QUERY_STORE
389 if ($tables) {
390 $num_tables = $GLOBALS['dbi']->numRows($tables);
391 $GLOBALS['dbi']->freeResult($tables);
392 } else {
393 $num_tables = 0;
396 return $num_tables;
400 * Converts numbers like 10M into bytes
401 * Used with permission from Moodle (https://moodle.org) by Martin Dougiamas
402 * (renamed with PMA prefix to avoid double definition when embedded
403 * in Moodle)
405 * @param string|int $size size (Default = 0)
407 * @return integer $size
409 public static function getRealSize($size = 0)
411 if (! $size) {
412 return 0;
415 $binaryprefixes = array(
416 'T' => 1099511627776,
417 't' => 1099511627776,
418 'G' => 1073741824,
419 'g' => 1073741824,
420 'M' => 1048576,
421 'm' => 1048576,
422 'K' => 1024,
423 'k' => 1024,
426 if (preg_match('/^([0-9]+)([KMGT])/i', $size, $matches)) {
427 return $matches[1] * $binaryprefixes[$matches[2]];
430 return (int) $size;
431 } // end getRealSize()
434 * boolean phpMyAdmin.Core::checkPageValidity(string &$page, array $whitelist)
436 * checks given $page against given $whitelist and returns true if valid
437 * it optionally ignores query parameters in $page (script.php?ignored)
439 * @param string &$page page to check
440 * @param array $whitelist whitelist to check page against
441 * @param boolean $include whether the page is going to be included
443 * @return boolean whether $page is valid or not (in $whitelist or not)
445 public static function checkPageValidity(&$page, array $whitelist = [], $include = false)
447 if (empty($whitelist)) {
448 $whitelist = self::$goto_whitelist;
450 if (! isset($page) || !is_string($page)) {
451 return false;
454 if (in_array($page, $whitelist)) {
455 return true;
457 if ($include) {
458 return false;
461 $_page = mb_substr(
462 $page,
464 mb_strpos($page . '?', '?')
466 if (in_array($_page, $whitelist)) {
467 return true;
470 $_page = urldecode($page);
471 $_page = mb_substr(
472 $_page,
474 mb_strpos($_page . '?', '?')
476 if (in_array($_page, $whitelist)) {
477 return true;
480 return false;
484 * tries to find the value for the given environment variable name
486 * searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
487 * in this order
489 * @param string $var_name variable name
491 * @return string value of $var or empty string
493 public static function getenv($var_name)
495 if (isset($_SERVER[$var_name])) {
496 return $_SERVER[$var_name];
499 if (isset($_ENV[$var_name])) {
500 return $_ENV[$var_name];
503 if (getenv($var_name)) {
504 return getenv($var_name);
507 if (function_exists('apache_getenv')
508 && apache_getenv($var_name, true)
510 return apache_getenv($var_name, true);
513 return '';
517 * Send HTTP header, taking IIS limits into account (600 seems ok)
519 * @param string $uri the header to send
520 * @param bool $use_refresh whether to use Refresh: header when running on IIS
522 * @return void
524 public static function sendHeaderLocation($uri, $use_refresh = false)
526 if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && mb_strlen($uri) > 600) {
527 Response::getInstance()->disable();
529 echo Template::get('header_location')
530 ->render(array('uri' => $uri));
532 return;
536 * Avoid relative path redirect problems in case user entered URL
537 * like /phpmyadmin/index.php/ which some web servers happily accept.
539 if ($uri[0] == '.') {
540 $uri = $GLOBALS['PMA_Config']->getRootPath() . substr($uri, 2);
543 $response = Response::getInstance();
545 session_write_close();
546 if ($response->headersSent()) {
547 trigger_error(
548 'Core::sendHeaderLocation called when headers are already sent!',
549 E_USER_ERROR
552 // bug #1523784: IE6 does not like 'Refresh: 0', it
553 // results in a blank page
554 // but we need it when coming from the cookie login panel)
555 if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && $use_refresh) {
556 $response->header('Refresh: 0; ' . $uri);
557 } else {
558 $response->header('Location: ' . $uri);
563 * Outputs application/json headers. This includes no caching.
565 * @return void
567 public static function headerJSON()
569 if (defined('TESTSUITE')) {
570 return;
572 // No caching
573 self::noCacheHeader();
574 // MIME type
575 header('Content-Type: application/json; charset=UTF-8');
576 // Disable content sniffing in browser
577 // This is needed in case we include HTML in JSON, browser might assume it's
578 // html to display
579 header('X-Content-Type-Options: nosniff');
583 * Outputs headers to prevent caching in browser (and on the way).
585 * @return void
587 public static function noCacheHeader()
589 if (defined('TESTSUITE')) {
590 return;
592 // rfc2616 - Section 14.21
593 header('Expires: ' . gmdate(DATE_RFC1123));
594 // HTTP/1.1
595 header(
596 'Cache-Control: no-store, no-cache, must-revalidate,'
597 . ' pre-check=0, post-check=0, max-age=0'
600 header('Pragma: no-cache'); // HTTP/1.0
601 // test case: exporting a database into a .gz file with Safari
602 // would produce files not having the current time
603 // (added this header for Safari but should not harm other browsers)
604 header('Last-Modified: ' . gmdate(DATE_RFC1123));
609 * Sends header indicating file download.
611 * @param string $filename Filename to include in headers if empty,
612 * none Content-Disposition header will be sent.
613 * @param string $mimetype MIME type to include in headers.
614 * @param int $length Length of content (optional)
615 * @param bool $no_cache Whether to include no-caching headers.
617 * @return void
619 public static function downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
621 if ($no_cache) {
622 self::noCacheHeader();
624 /* Replace all possibly dangerous chars in filename */
625 $filename = Sanitize::sanitizeFilename($filename);
626 if (!empty($filename)) {
627 header('Content-Description: File Transfer');
628 header('Content-Disposition: attachment; filename="' . $filename . '"');
630 header('Content-Type: ' . $mimetype);
631 // inform the server that compression has been done,
632 // to avoid a double compression (for example with Apache + mod_deflate)
633 $notChromeOrLessThan43 = PMA_USR_BROWSER_AGENT != 'CHROME' // see bug #4942
634 || (PMA_USR_BROWSER_AGENT == 'CHROME' && PMA_USR_BROWSER_VER < 43);
635 if (strpos($mimetype, 'gzip') !== false && $notChromeOrLessThan43) {
636 header('Content-Encoding: gzip');
638 header('Content-Transfer-Encoding: binary');
639 if ($length > 0) {
640 header('Content-Length: ' . $length);
645 * Returns value of an element in $array given by $path.
646 * $path is a string describing position of an element in an associative array,
647 * eg. Servers/1/host refers to $array[Servers][1][host]
649 * @param string $path path in the array
650 * @param array $array the array
651 * @param mixed $default default value
653 * @return mixed array element or $default
655 public static function arrayRead($path, array $array, $default = null)
657 $keys = explode('/', $path);
658 $value =& $array;
659 foreach ($keys as $key) {
660 if (! isset($value[$key])) {
661 return $default;
663 $value =& $value[$key];
665 return $value;
669 * Stores value in an array
671 * @param string $path path in the array
672 * @param array &$array the array
673 * @param mixed $value value to store
675 * @return void
677 public static function arrayWrite($path, array &$array, $value)
679 $keys = explode('/', $path);
680 $last_key = array_pop($keys);
681 $a =& $array;
682 foreach ($keys as $key) {
683 if (! isset($a[$key])) {
684 $a[$key] = array();
686 $a =& $a[$key];
688 $a[$last_key] = $value;
692 * Removes value from an array
694 * @param string $path path in the array
695 * @param array &$array the array
697 * @return void
699 public static function arrayRemove($path, array &$array)
701 $keys = explode('/', $path);
702 $keys_last = array_pop($keys);
703 $path = array();
704 $depth = 0;
706 $path[0] =& $array;
707 $found = true;
708 // go as deep as required or possible
709 foreach ($keys as $key) {
710 if (! isset($path[$depth][$key])) {
711 $found = false;
712 break;
714 $depth++;
715 $path[$depth] =& $path[$depth - 1][$key];
717 // if element found, remove it
718 if ($found) {
719 unset($path[$depth][$keys_last]);
720 $depth--;
723 // remove empty nested arrays
724 for (; $depth >= 0; $depth--) {
725 if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
726 unset($path[$depth][$keys[$depth]]);
727 } else {
728 break;
734 * Returns link to (possibly) external site using defined redirector.
736 * @param string $url URL where to go.
738 * @return string URL for a link.
740 public static function linkURL($url)
742 if (!preg_match('#^https?://#', $url)) {
743 return $url;
746 $params = array();
747 $params['url'] = $url;
749 $url = Url::getCommon($params);
750 //strip off token and such sensitive information. Just keep url.
751 $arr = parse_url($url);
752 parse_str($arr["query"], $vars);
753 $query = http_build_query(array("url" => $vars["url"]));
755 if (!is_null($GLOBALS['PMA_Config']) && $GLOBALS['PMA_Config']->get('is_setup')) {
756 $url = '../url.php?' . $query;
757 } else {
758 $url = './url.php?' . $query;
761 return $url;
765 * Checks whether domain of URL is whitelisted domain or not.
766 * Use only for URLs of external sites.
768 * @param string $url URL of external site.
770 * @return boolean True: if domain of $url is allowed domain,
771 * False: otherwise.
773 public static function isAllowedDomain($url)
775 $arr = parse_url($url);
776 // We need host to be set
777 if (! isset($arr['host']) || strlen($arr['host']) == 0) {
778 return false;
780 // We do not want these to be present
781 $blocked = array('user', 'pass', 'port');
782 foreach ($blocked as $part) {
783 if (isset($arr[$part]) && strlen($arr[$part]) != 0) {
784 return false;
787 $domain = $arr["host"];
788 $domainWhiteList = array(
789 /* Include current domain */
790 $_SERVER['SERVER_NAME'],
791 /* phpMyAdmin domains */
792 'wiki.phpmyadmin.net',
793 'www.phpmyadmin.net',
794 'phpmyadmin.net',
795 'demo.phpmyadmin.net',
796 'docs.phpmyadmin.net',
797 /* mysql.com domains */
798 'dev.mysql.com','bugs.mysql.com',
799 /* mariadb domains */
800 'mariadb.org', 'mariadb.com',
801 /* php.net domains */
802 'php.net',
803 'secure.php.net',
804 /* Github domains*/
805 'github.com','www.github.com',
806 /* Percona domains */
807 'www.percona.com',
808 /* Following are doubtful ones. */
809 'mysqldatabaseadministration.blogspot.com',
812 return in_array($domain, $domainWhiteList);
816 * Replace some html-unfriendly stuff
818 * @param string $buffer String to process
820 * @return string Escaped and cleaned up text suitable for html
822 public static function mimeDefaultFunction($buffer)
824 $buffer = htmlspecialchars($buffer);
825 $buffer = str_replace(' ', ' &nbsp;', $buffer);
826 $buffer = preg_replace("@((\015\012)|(\015)|(\012))@", '<br />' . "\n", $buffer);
828 return $buffer;
832 * Displays SQL query before executing.
834 * @param array|string $query_data Array containing queries or query itself
836 * @return void
838 public static function previewSQL($query_data)
840 $retval = '<div class="preview_sql">';
841 if (empty($query_data)) {
842 $retval .= __('No change');
843 } elseif (is_array($query_data)) {
844 foreach ($query_data as $query) {
845 $retval .= Util::formatSql($query);
847 } else {
848 $retval .= Util::formatSql($query_data);
850 $retval .= '</div>';
851 $response = Response::getInstance();
852 $response->addJSON('sql_data', $retval);
853 exit;
857 * recursively check if variable is empty
859 * @param mixed $value the variable
861 * @return bool true if empty
863 public static function emptyRecursive($value)
865 $empty = true;
866 if (is_array($value)) {
867 array_walk_recursive(
868 $value,
869 function ($item) use (&$empty) {
870 $empty = $empty && empty($item);
873 } else {
874 $empty = empty($value);
876 return $empty;
880 * Creates some globals from $_POST variables matching a pattern
882 * @param array $post_patterns The patterns to search for
884 * @return void
886 public static function setPostAsGlobal(array $post_patterns)
888 foreach (array_keys($_POST) as $post_key) {
889 foreach ($post_patterns as $one_post_pattern) {
890 if (preg_match($one_post_pattern, $post_key)) {
891 $GLOBALS[$post_key] = $_POST[$post_key];
898 * Creates some globals from $_REQUEST
900 * @param string $param db|table
902 * @return void
904 public static function setGlobalDbOrTable($param)
906 $GLOBALS[$param] = '';
907 if (self::isValid($_REQUEST[$param])) {
908 // can we strip tags from this?
909 // only \ and / is not allowed in db names for MySQL
910 $GLOBALS[$param] = $_REQUEST[$param];
911 $GLOBALS['url_params'][$param] = $GLOBALS[$param];
916 * PATH_INFO could be compromised if set, so remove it from PHP_SELF
917 * and provide a clean PHP_SELF here
919 * @return void
921 public static function cleanupPathInfo()
923 global $PMA_PHP_SELF;
925 $PMA_PHP_SELF = self::getenv('PHP_SELF');
926 if (empty($PMA_PHP_SELF)) {
927 $PMA_PHP_SELF = urldecode(self::getenv('REQUEST_URI'));
929 $_PATH_INFO = self::getenv('PATH_INFO');
930 if (! empty($_PATH_INFO) && ! empty($PMA_PHP_SELF)) {
931 $question_pos = mb_strpos($PMA_PHP_SELF, '?');
932 if ($question_pos != false) {
933 $PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $question_pos);
935 $path_info_pos = mb_strrpos($PMA_PHP_SELF, $_PATH_INFO);
936 if ($path_info_pos !== false) {
937 $path_info_part = mb_substr($PMA_PHP_SELF, $path_info_pos, mb_strlen($_PATH_INFO));
938 if ($path_info_part == $_PATH_INFO) {
939 $PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $path_info_pos);
944 $path = [];
945 foreach(explode('/', $PMA_PHP_SELF) as $part) {
946 // ignore parts that have no value
947 if (empty($part) || $part === '.') continue;
949 if ($part !== '..') {
950 // cool, we found a new part
951 array_push($path, $part);
952 } elseif (count($path) > 0) {
953 // going back up? sure
954 array_pop($path);
956 // Here we intentionall ignore case where we go too up
957 // as there is nothing sane to do
960 $PMA_PHP_SELF = htmlspecialchars('/' . join('/', $path));
964 * Checks that required PHP extensions are there.
965 * @return void
967 public static function checkExtensions()
970 * Warning about mbstring.
972 if (! function_exists('mb_detect_encoding')) {
973 self::warnMissingExtension('mbstring');
977 * We really need this one!
979 if (! function_exists('preg_replace')) {
980 self::warnMissingExtension('pcre', true);
984 * JSON is required in several places.
986 if (! function_exists('json_encode')) {
987 self::warnMissingExtension('json', true);
991 * ctype is required for Twig.
993 if (! function_exists('ctype_alpha')) {
994 self::warnMissingExtension('ctype', true);
998 * hash is required for cookie authentication.
1000 if (! function_exists('hash_hmac')) {
1001 self::warnMissingExtension('hash', true);
1006 * Gets the "true" IP address of the current user
1008 * @return string the ip of the user
1010 * @access private
1012 public static function getIp()
1014 /* Get the address of user */
1015 if (empty($_SERVER['REMOTE_ADDR'])) {
1016 /* We do not know remote IP */
1017 return false;
1020 $direct_ip = $_SERVER['REMOTE_ADDR'];
1022 /* Do we trust this IP as a proxy? If yes we will use it's header. */
1023 if (!isset($GLOBALS['cfg']['TrustedProxies'][$direct_ip])) {
1024 /* Return true IP */
1025 return $direct_ip;
1029 * Parse header in form:
1030 * X-Forwarded-For: client, proxy1, proxy2
1032 // Get header content
1033 $value = self::getenv($GLOBALS['cfg']['TrustedProxies'][$direct_ip]);
1034 // Grab first element what is client adddress
1035 $value = explode(',', $value)[0];
1036 // checks that the header contains only one IP address,
1037 $is_ip = filter_var($value, FILTER_VALIDATE_IP);
1039 if ($is_ip !== false) {
1040 // True IP behind a proxy
1041 return $value;
1044 // We could not parse header
1045 return false;
1046 } // end of the 'getIp()' function
1049 * Sanitizes MySQL hostname
1051 * * strips p: prefix(es)
1053 * @param string $name User given hostname
1055 * @return string
1057 public static function sanitizeMySQLHost($name)
1059 while (strtolower(substr($name, 0, 2)) == 'p:') {
1060 $name = substr($name, 2);
1063 return $name;
1067 * Sanitizes MySQL username
1069 * * strips part behind null byte
1071 * @param string $name User given username
1073 * @return string
1075 public static function sanitizeMySQLUser($name)
1077 $position = strpos($name, chr(0));
1078 if ($position !== false) {
1079 return substr($name, 0, $position);
1081 return $name;
1085 * Safe unserializer wrapper
1087 * It does not unserialize data containing objects
1089 * @param string $data Data to unserialize
1091 * @return mixed
1093 public static function safeUnserialize($data)
1095 if (! is_string($data)) {
1096 return null;
1099 /* validate serialized data */
1100 $length = strlen($data);
1101 $depth = 0;
1102 for ($i = 0; $i < $length; $i++) {
1103 $value = $data[$i];
1105 switch ($value)
1107 case '}':
1108 /* end of array */
1109 if ($depth <= 0) {
1110 return null;
1112 $depth--;
1113 break;
1114 case 's':
1115 /* string */
1116 // parse sting length
1117 $strlen = intval(substr($data, $i + 2));
1118 // string start
1119 $i = strpos($data, ':', $i + 2);
1120 if ($i === false) {
1121 return null;
1123 // skip string, quotes and ;
1124 $i += 2 + $strlen + 1;
1125 if ($data[$i] != ';') {
1126 return null;
1128 break;
1130 case 'b':
1131 case 'i':
1132 case 'd':
1133 /* bool, integer or double */
1134 // skip value to sepearator
1135 $i = strpos($data, ';', $i);
1136 if ($i === false) {
1137 return null;
1139 break;
1140 case 'a':
1141 /* array */
1142 // find array start
1143 $i = strpos($data, '{', $i);
1144 if ($i === false) {
1145 return null;
1147 // remember nesting
1148 $depth++;
1149 break;
1150 case 'N':
1151 /* null */
1152 // skip to end
1153 $i = strpos($data, ';', $i);
1154 if ($i === false) {
1155 return null;
1157 break;
1158 default:
1159 /* any other elements are not wanted */
1160 return null;
1164 // check unterminated arrays
1165 if ($depth > 0) {
1166 return null;
1169 return unserialize($data);
1173 * Applies changes to PHP configuration.
1175 * @return void
1177 public static function configure()
1180 * Set utf-8 encoding for PHP
1182 ini_set('default_charset', 'utf-8');
1183 mb_internal_encoding('utf-8');
1186 * Set precision to sane value, with higher values
1187 * things behave slightly unexpectedly, for example
1188 * round(1.2, 2) returns 1.199999999999999956.
1190 ini_set('precision', 14);
1193 * check timezone setting
1194 * this could produce an E_WARNING - but only once,
1195 * if not done here it will produce E_WARNING on every date/time function
1197 date_default_timezone_set(@date_default_timezone_get());
1201 * Check whether PHP configuration matches our needs.
1203 * @return void
1205 public static function checkConfiguration()
1208 * As we try to handle charsets by ourself, mbstring overloads just
1209 * break it, see bug 1063821.
1211 * We specifically use empty here as we are looking for anything else than
1212 * empty value or 0.
1214 if (extension_loaded('mbstring') && !empty(ini_get('mbstring.func_overload'))) {
1215 self::fatalError(
1217 'You have enabled mbstring.func_overload in your PHP '
1218 . 'configuration. This option is incompatible with phpMyAdmin '
1219 . 'and might cause some data to be corrupted!'
1225 * The ini_set and ini_get functions can be disabled using
1226 * disable_functions but we're relying quite a lot of them.
1228 if (! function_exists('ini_get') || ! function_exists('ini_set')) {
1229 self::fatalError(
1231 'You have disabled ini_get and/or ini_set in php.ini. '
1232 . 'This option is incompatible with phpMyAdmin!'
1239 * prints list item for main page
1241 * @param string $name displayed text
1242 * @param string $listId id, used for css styles
1243 * @param string $url make item as link with $url as target
1244 * @param string $mysql_help_page display a link to MySQL's manual
1245 * @param string $target special target for $url
1246 * @param string $a_id id for the anchor,
1247 * used for jQuery to hook in functions
1248 * @param string $class class for the li element
1249 * @param string $a_class class for the anchor element
1251 * @return void
1253 public static function printListItem($name, $listId = null, $url = null,
1254 $mysql_help_page = null, $target = null, $a_id = null, $class = null,
1255 $a_class = null
1257 echo Template::get('list/item')
1258 ->render(
1259 array(
1260 'content' => $name,
1261 'id' => $listId,
1262 'class' => $class,
1263 'url' => array(
1264 'href' => $url,
1265 'target' => $target,
1266 'id' => $a_id,
1267 'class' => $a_class,
1269 'mysql_help_page' => $mysql_help_page,
1275 * Checks request and fails with fatal error if something problematic is found
1277 * @return void
1279 public static function checkRequest()
1281 if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
1282 self::fatalError(__("GLOBALS overwrite attempt"));
1286 * protect against possible exploits - there is no need to have so much variables
1288 if (count($_REQUEST) > 1000) {
1289 self::fatalError(__('possible exploit'));
1294 * Sign the sql query using hmac using the session token
1296 * @param string $sqlQuery The sql query
1297 * @return string
1299 public static function signSqlQuery($sqlQuery)
1301 /** @var array $cfg */
1302 global $cfg;
1303 return hash_hmac('sha256', $sqlQuery, $_SESSION[' HMAC_secret '] . $cfg['blowfish_secret']);
1307 * Check that the sql query has a valid hmac signature
1309 * @param string $sqlQuery The sql query
1310 * @param string $signature The Signature to check
1311 * @return bool
1313 public static function checkSqlQuerySignature($sqlQuery, $signature)
1315 /** @var array $cfg */
1316 global $cfg;
1317 $hmac = hash_hmac('sha256', $sqlQuery, $_SESSION[' HMAC_secret '] . $cfg['blowfish_secret']);
1318 return hash_equals($hmac, $signature);