Core.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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.
  7. *
  8. * @package PhpMyAdmin
  9. */
  10. declare(strict_types=1);
  11. namespace PhpMyAdmin;
  12. use PhpMyAdmin\Di\Migration;
  13. use PhpMyAdmin\Display\Error as DisplayError;
  14. /**
  15. * Core class
  16. *
  17. * @package PhpMyAdmin
  18. */
  19. class Core
  20. {
  21. /**
  22. * the whitelist for goto parameter
  23. * @static array $goto_whitelist
  24. */
  25. public static $goto_whitelist = [
  26. 'db_datadict.php',
  27. 'db_sql.php',
  28. 'db_events.php',
  29. 'db_export.php',
  30. 'db_importdocsql.php',
  31. 'db_multi_table_query.php',
  32. 'db_qbe.php',
  33. 'db_structure.php',
  34. 'db_import.php',
  35. 'db_operations.php',
  36. 'db_search.php',
  37. 'db_routines.php',
  38. 'export.php',
  39. 'import.php',
  40. 'index.php',
  41. 'pdf_pages.php',
  42. 'pdf_schema.php',
  43. 'server_binlog.php',
  44. 'server_collations.php',
  45. 'server_databases.php',
  46. 'server_engines.php',
  47. 'server_export.php',
  48. 'server_import.php',
  49. 'server_privileges.php',
  50. 'server_sql.php',
  51. 'server_status.php',
  52. 'server_status_advisor.php',
  53. 'server_status_monitor.php',
  54. 'server_status_queries.php',
  55. 'server_status_variables.php',
  56. 'server_variables.php',
  57. 'sql.php',
  58. 'tbl_addfield.php',
  59. 'tbl_change.php',
  60. 'tbl_create.php',
  61. 'tbl_import.php',
  62. 'tbl_indexes.php',
  63. 'tbl_sql.php',
  64. 'tbl_export.php',
  65. 'tbl_operations.php',
  66. 'tbl_structure.php',
  67. 'tbl_relation.php',
  68. 'tbl_replace.php',
  69. 'tbl_row_action.php',
  70. 'tbl_select.php',
  71. 'tbl_zoom_select.php',
  72. 'transformation_overview.php',
  73. 'transformation_wrapper.php',
  74. 'user_password.php',
  75. ];
  76. /**
  77. * checks given $var and returns it if valid, or $default of not valid
  78. * given $var is also checked for type being 'similar' as $default
  79. * or against any other type if $type is provided
  80. *
  81. * <code>
  82. * // $_REQUEST['db'] not set
  83. * echo Core::ifSetOr($_REQUEST['db'], ''); // ''
  84. * // $_POST['sql_query'] not set
  85. * echo Core::ifSetOr($_POST['sql_query']); // null
  86. * // $cfg['EnableFoo'] not set
  87. * echo Core::ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
  88. * echo Core::ifSetOr($cfg['EnableFoo']); // null
  89. * // $cfg['EnableFoo'] set to 1
  90. * echo Core::ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
  91. * echo Core::ifSetOr($cfg['EnableFoo'], false, 'similar'); // 1
  92. * echo Core::ifSetOr($cfg['EnableFoo'], false); // 1
  93. * // $cfg['EnableFoo'] set to true
  94. * echo Core::ifSetOr($cfg['EnableFoo'], false, 'boolean'); // true
  95. * </code>
  96. *
  97. * @param mixed $var param to check
  98. * @param mixed $default default value
  99. * @param mixed $type var type or array of values to check against $var
  100. *
  101. * @return mixed $var or $default
  102. *
  103. * @see self::isValid()
  104. */
  105. public static function ifSetOr(&$var, $default = null, $type = 'similar')
  106. {
  107. if (! self::isValid($var, $type, $default)) {
  108. return $default;
  109. }
  110. return $var;
  111. }
  112. /**
  113. * checks given $var against $type or $compare
  114. *
  115. * $type can be:
  116. * - false : no type checking
  117. * - 'scalar' : whether type of $var is integer, float, string or boolean
  118. * - 'numeric' : whether type of $var is any number representation
  119. * - 'length' : whether type of $var is scalar with a string length > 0
  120. * - 'similar' : whether type of $var is similar to type of $compare
  121. * - 'equal' : whether type of $var is identical to type of $compare
  122. * - 'identical' : whether $var is identical to $compare, not only the type!
  123. * - or any other valid PHP variable type
  124. *
  125. * <code>
  126. * // $_REQUEST['doit'] = true;
  127. * Core::isValid($_REQUEST['doit'], 'identical', 'true'); // false
  128. * // $_REQUEST['doit'] = 'true';
  129. * Core::isValid($_REQUEST['doit'], 'identical', 'true'); // true
  130. * </code>
  131. *
  132. * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
  133. * but the var is not altered inside this function, also after checking a var
  134. * this var exists nut is not set, example:
  135. * <code>
  136. * // $var is not set
  137. * isset($var); // false
  138. * functionCallByReference($var); // false
  139. * isset($var); // true
  140. * functionCallByReference($var); // true
  141. * </code>
  142. *
  143. * to avoid this we set this var to null if not isset
  144. *
  145. * @param mixed $var variable to check
  146. * @param mixed $type var type or array of valid values to check against $var
  147. * @param mixed $compare var to compare with $var
  148. *
  149. * @return boolean whether valid or not
  150. *
  151. * @todo add some more var types like hex, bin, ...?
  152. * @see https://secure.php.net/gettype
  153. */
  154. public static function isValid(&$var, $type = 'length', $compare = null): bool
  155. {
  156. if (! isset($var)) {
  157. // var is not even set
  158. return false;
  159. }
  160. if ($type === false) {
  161. // no vartype requested
  162. return true;
  163. }
  164. if (is_array($type)) {
  165. return in_array($var, $type);
  166. }
  167. // allow some aliases of var types
  168. $type = strtolower($type);
  169. switch ($type) {
  170. case 'identic':
  171. $type = 'identical';
  172. break;
  173. case 'len':
  174. $type = 'length';
  175. break;
  176. case 'bool':
  177. $type = 'boolean';
  178. break;
  179. case 'float':
  180. $type = 'double';
  181. break;
  182. case 'int':
  183. $type = 'integer';
  184. break;
  185. case 'null':
  186. $type = 'NULL';
  187. break;
  188. }
  189. if ($type === 'identical') {
  190. return $var === $compare;
  191. }
  192. // whether we should check against given $compare
  193. if ($type === 'similar') {
  194. switch (gettype($compare)) {
  195. case 'string':
  196. case 'boolean':
  197. $type = 'scalar';
  198. break;
  199. case 'integer':
  200. case 'double':
  201. $type = 'numeric';
  202. break;
  203. default:
  204. $type = gettype($compare);
  205. }
  206. } elseif ($type === 'equal') {
  207. $type = gettype($compare);
  208. }
  209. // do the check
  210. if ($type === 'length' || $type === 'scalar') {
  211. $is_scalar = is_scalar($var);
  212. if ($is_scalar && $type === 'length') {
  213. return strlen((string) $var) > 0;
  214. }
  215. return $is_scalar;
  216. }
  217. if ($type === 'numeric') {
  218. return is_numeric($var);
  219. }
  220. return gettype($var) === $type;
  221. }
  222. /**
  223. * Removes insecure parts in a path; used before include() or
  224. * require() when a part of the path comes from an insecure source
  225. * like a cookie or form.
  226. *
  227. * @param string $path The path to check
  228. *
  229. * @return string The secured path
  230. *
  231. * @access public
  232. */
  233. public static function securePath(string $path): string
  234. {
  235. // change .. to .
  236. return preg_replace('@\.\.*@', '.', $path);
  237. } // end function
  238. /**
  239. * displays the given error message on phpMyAdmin error page in foreign language,
  240. * ends script execution and closes session
  241. *
  242. * loads language file if not loaded already
  243. *
  244. * @param string $error_message the error message or named error message
  245. * @param string|array $message_args arguments applied to $error_message
  246. *
  247. * @return void
  248. */
  249. public static function fatalError(
  250. string $error_message,
  251. $message_args = null
  252. ): void {
  253. /* Use format string if applicable */
  254. if (is_string($message_args)) {
  255. $error_message = sprintf($error_message, $message_args);
  256. } elseif (is_array($message_args)) {
  257. $error_message = vsprintf($error_message, $message_args);
  258. }
  259. /*
  260. * Avoid using Response class as config does not have to be loaded yet
  261. * (this can happen on early fatal error)
  262. */
  263. if (isset($GLOBALS['dbi']) && $GLOBALS['dbi'] !== null && isset($GLOBALS['PMA_Config']) && $GLOBALS['PMA_Config']->get('is_setup') === false && Response::getInstance()->isAjax()) {
  264. $response = Response::getInstance();
  265. $response->setRequestStatus(false);
  266. $response->addJSON('message', Message::error($error_message));
  267. } elseif (! empty($_REQUEST['ajax_request'])) {
  268. // Generate JSON manually
  269. self::headerJSON();
  270. echo json_encode(
  271. [
  272. 'success' => false,
  273. 'message' => Message::error($error_message)->getDisplay(),
  274. ]
  275. );
  276. } else {
  277. $error_message = strtr($error_message, ['<br>' => '[br]']);
  278. $error_header = __('Error');
  279. $lang = isset($GLOBALS['lang']) ? $GLOBALS['lang'] : 'en';
  280. $dir = isset($GLOBALS['text_dir']) ? $GLOBALS['text_dir'] : 'ltr';
  281. echo DisplayError::display(new Template(), $lang, $dir, $error_header, $error_message);
  282. }
  283. if (! defined('TESTSUITE')) {
  284. exit;
  285. }
  286. }
  287. /**
  288. * Returns a link to the PHP documentation
  289. *
  290. * @param string $target anchor in documentation
  291. *
  292. * @return string the URL
  293. *
  294. * @access public
  295. */
  296. public static function getPHPDocLink(string $target): string
  297. {
  298. /* List of PHP documentation translations */
  299. $php_doc_languages = [
  300. 'pt_BR',
  301. 'zh',
  302. 'fr',
  303. 'de',
  304. 'it',
  305. 'ja',
  306. 'pl',
  307. 'ro',
  308. 'ru',
  309. 'fa',
  310. 'es',
  311. 'tr',
  312. ];
  313. $lang = 'en';
  314. if (isset($GLOBALS['lang']) && in_array($GLOBALS['lang'], $php_doc_languages)) {
  315. $lang = $GLOBALS['lang'];
  316. }
  317. return self::linkURL('https://secure.php.net/manual/' . $lang . '/' . $target);
  318. }
  319. /**
  320. * Warn or fail on missing extension.
  321. *
  322. * @param string $extension Extension name
  323. * @param bool $fatal Whether the error is fatal.
  324. * @param string $extra Extra string to append to message.
  325. *
  326. * @return void
  327. */
  328. public static function warnMissingExtension(
  329. string $extension,
  330. bool $fatal = false,
  331. string $extra = ''
  332. ): void {
  333. /** @var ErrorHandler $error_handler */
  334. global $error_handler;
  335. /* Gettext does not have to be loaded yet here */
  336. if (function_exists('__')) {
  337. $message = __(
  338. 'The %s extension is missing. Please check your PHP configuration.'
  339. );
  340. } else {
  341. $message
  342. = 'The %s extension is missing. Please check your PHP configuration.';
  343. }
  344. $doclink = self::getPHPDocLink('book.' . $extension . '.php');
  345. $message = sprintf(
  346. $message,
  347. '[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
  348. );
  349. if ($extra != '') {
  350. $message .= ' ' . $extra;
  351. }
  352. if ($fatal) {
  353. self::fatalError($message);
  354. return;
  355. }
  356. $error_handler->addError(
  357. $message,
  358. E_USER_WARNING,
  359. '',
  360. 0,
  361. false
  362. );
  363. }
  364. /**
  365. * returns count of tables in given db
  366. *
  367. * @param string $db database to count tables for
  368. *
  369. * @return integer count of tables in $db
  370. */
  371. public static function getTableCount(string $db): int
  372. {
  373. $tables = $GLOBALS['dbi']->tryQuery(
  374. 'SHOW TABLES FROM ' . Util::backquote($db) . ';',
  375. DatabaseInterface::CONNECT_USER,
  376. DatabaseInterface::QUERY_STORE
  377. );
  378. if ($tables) {
  379. $num_tables = $GLOBALS['dbi']->numRows($tables);
  380. $GLOBALS['dbi']->freeResult($tables);
  381. } else {
  382. $num_tables = 0;
  383. }
  384. return $num_tables;
  385. }
  386. /**
  387. * Converts numbers like 10M into bytes
  388. * Used with permission from Moodle (https://moodle.org) by Martin Dougiamas
  389. * (renamed with PMA prefix to avoid double definition when embedded
  390. * in Moodle)
  391. *
  392. * @param string|int $size size (Default = 0)
  393. *
  394. * @return integer
  395. */
  396. public static function getRealSize($size = 0): int
  397. {
  398. if (! $size) {
  399. return 0;
  400. }
  401. $binaryprefixes = [
  402. 'T' => 1099511627776,
  403. 't' => 1099511627776,
  404. 'G' => 1073741824,
  405. 'g' => 1073741824,
  406. 'M' => 1048576,
  407. 'm' => 1048576,
  408. 'K' => 1024,
  409. 'k' => 1024,
  410. ];
  411. if (preg_match('/^([0-9]+)([KMGT])/i', $size, $matches)) {
  412. return (int) ($matches[1] * $binaryprefixes[$matches[2]]);
  413. }
  414. return (int) $size;
  415. } // end getRealSize()
  416. /**
  417. * Checks given $page against given $whitelist and returns true if valid
  418. * it optionally ignores query parameters in $page (script.php?ignored)
  419. *
  420. * @param string $page page to check
  421. * @param array $whitelist whitelist to check page against
  422. * @param boolean $include whether the page is going to be included
  423. *
  424. * @return boolean whether $page is valid or not (in $whitelist or not)
  425. */
  426. public static function checkPageValidity(&$page, array $whitelist = [], $include = false): bool
  427. {
  428. if (empty($whitelist)) {
  429. $whitelist = self::$goto_whitelist;
  430. }
  431. if (empty($page)) {
  432. return false;
  433. }
  434. if (in_array($page, $whitelist)) {
  435. return true;
  436. }
  437. if ($include) {
  438. return false;
  439. }
  440. $_page = mb_substr(
  441. $page,
  442. 0,
  443. mb_strpos($page . '?', '?')
  444. );
  445. if (in_array($_page, $whitelist)) {
  446. return true;
  447. }
  448. $_page = urldecode($page);
  449. $_page = mb_substr(
  450. $_page,
  451. 0,
  452. mb_strpos($_page . '?', '?')
  453. );
  454. if (in_array($_page, $whitelist)) {
  455. return true;
  456. }
  457. return false;
  458. }
  459. /**
  460. * tries to find the value for the given environment variable name
  461. *
  462. * searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
  463. * in this order
  464. *
  465. * @param string $var_name variable name
  466. *
  467. * @return string value of $var or empty string
  468. */
  469. public static function getenv(string $var_name): string
  470. {
  471. if (isset($_SERVER[$var_name])) {
  472. return (string) $_SERVER[$var_name];
  473. }
  474. if (isset($_ENV[$var_name])) {
  475. return (string) $_ENV[$var_name];
  476. }
  477. if (getenv($var_name)) {
  478. return getenv($var_name);
  479. }
  480. if (function_exists('apache_getenv')
  481. && apache_getenv($var_name, true)
  482. ) {
  483. return apache_getenv($var_name, true);
  484. }
  485. return '';
  486. }
  487. /**
  488. * Send HTTP header, taking IIS limits into account (600 seems ok)
  489. *
  490. * @param string $uri the header to send
  491. * @param bool $use_refresh whether to use Refresh: header when running on IIS
  492. *
  493. * @return void
  494. */
  495. public static function sendHeaderLocation(string $uri, bool $use_refresh = false): void
  496. {
  497. if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && mb_strlen($uri) > 600) {
  498. Response::getInstance()->disable();
  499. $template = new Template();
  500. echo $template->render('header_location', ['uri' => $uri]);
  501. return;
  502. }
  503. /*
  504. * Avoid relative path redirect problems in case user entered URL
  505. * like /phpmyadmin/index.php/ which some web servers happily accept.
  506. */
  507. if ($uri[0] == '.') {
  508. $uri = $GLOBALS['PMA_Config']->getRootPath() . substr($uri, 2);
  509. }
  510. $response = Response::getInstance();
  511. session_write_close();
  512. if ($response->headersSent()) {
  513. trigger_error(
  514. 'Core::sendHeaderLocation called when headers are already sent!',
  515. E_USER_ERROR
  516. );
  517. }
  518. // bug #1523784: IE6 does not like 'Refresh: 0', it
  519. // results in a blank page
  520. // but we need it when coming from the cookie login panel)
  521. if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && $use_refresh) {
  522. $response->header('Refresh: 0; ' . $uri);
  523. } else {
  524. $response->header('Location: ' . $uri);
  525. }
  526. }
  527. /**
  528. * Outputs application/json headers. This includes no caching.
  529. *
  530. * @return void
  531. */
  532. public static function headerJSON(): void
  533. {
  534. if (defined('TESTSUITE')) {
  535. return;
  536. }
  537. // No caching
  538. self::noCacheHeader();
  539. // MIME type
  540. header('Content-Type: application/json; charset=UTF-8');
  541. // Disable content sniffing in browser
  542. // This is needed in case we include HTML in JSON, browser might assume it's
  543. // html to display
  544. header('X-Content-Type-Options: nosniff');
  545. }
  546. /**
  547. * Outputs headers to prevent caching in browser (and on the way).
  548. *
  549. * @return void
  550. */
  551. public static function noCacheHeader(): void
  552. {
  553. if (defined('TESTSUITE')) {
  554. return;
  555. }
  556. // rfc2616 - Section 14.21
  557. header('Expires: ' . gmdate(DATE_RFC1123));
  558. // HTTP/1.1
  559. header(
  560. 'Cache-Control: no-store, no-cache, must-revalidate,'
  561. . ' pre-check=0, post-check=0, max-age=0'
  562. );
  563. header('Pragma: no-cache'); // HTTP/1.0
  564. // test case: exporting a database into a .gz file with Safari
  565. // would produce files not having the current time
  566. // (added this header for Safari but should not harm other browsers)
  567. header('Last-Modified: ' . gmdate(DATE_RFC1123));
  568. }
  569. /**
  570. * Sends header indicating file download.
  571. *
  572. * @param string $filename Filename to include in headers if empty,
  573. * none Content-Disposition header will be sent.
  574. * @param string $mimetype MIME type to include in headers.
  575. * @param int $length Length of content (optional)
  576. * @param bool $no_cache Whether to include no-caching headers.
  577. *
  578. * @return void
  579. */
  580. public static function downloadHeader(
  581. string $filename,
  582. string $mimetype,
  583. int $length = 0,
  584. bool $no_cache = true
  585. ): void {
  586. if ($no_cache) {
  587. self::noCacheHeader();
  588. }
  589. /* Replace all possibly dangerous chars in filename */
  590. $filename = Sanitize::sanitizeFilename($filename);
  591. if (! empty($filename)) {
  592. header('Content-Description: File Transfer');
  593. header('Content-Disposition: attachment; filename="' . $filename . '"');
  594. }
  595. header('Content-Type: ' . $mimetype);
  596. // inform the server that compression has been done,
  597. // to avoid a double compression (for example with Apache + mod_deflate)
  598. $notChromeOrLessThan43 = PMA_USR_BROWSER_AGENT != 'CHROME' // see bug #4942
  599. || (PMA_USR_BROWSER_AGENT == 'CHROME' && PMA_USR_BROWSER_VER < 43);
  600. if (strpos($mimetype, 'gzip') !== false && $notChromeOrLessThan43) {
  601. header('Content-Encoding: gzip');
  602. }
  603. header('Content-Transfer-Encoding: binary');
  604. if ($length > 0) {
  605. header('Content-Length: ' . $length);
  606. }
  607. }
  608. /**
  609. * Returns value of an element in $array given by $path.
  610. * $path is a string describing position of an element in an associative array,
  611. * eg. Servers/1/host refers to $array[Servers][1][host]
  612. *
  613. * @param string $path path in the array
  614. * @param array $array the array
  615. * @param mixed $default default value
  616. *
  617. * @return mixed array element or $default
  618. */
  619. public static function arrayRead(string $path, array $array, $default = null)
  620. {
  621. $keys = explode('/', $path);
  622. $value =& $array;
  623. foreach ($keys as $key) {
  624. if (! isset($value[$key])) {
  625. return $default;
  626. }
  627. $value =& $value[$key];
  628. }
  629. return $value;
  630. }
  631. /**
  632. * Stores value in an array
  633. *
  634. * @param string $path path in the array
  635. * @param array $array the array
  636. * @param mixed $value value to store
  637. *
  638. * @return void
  639. */
  640. public static function arrayWrite(string $path, array &$array, $value): void
  641. {
  642. $keys = explode('/', $path);
  643. $last_key = array_pop($keys);
  644. $a =& $array;
  645. foreach ($keys as $key) {
  646. if (! isset($a[$key])) {
  647. $a[$key] = [];
  648. }
  649. $a =& $a[$key];
  650. }
  651. $a[$last_key] = $value;
  652. }
  653. /**
  654. * Removes value from an array
  655. *
  656. * @param string $path path in the array
  657. * @param array $array the array
  658. *
  659. * @return void
  660. */
  661. public static function arrayRemove(string $path, array &$array): void
  662. {
  663. $keys = explode('/', $path);
  664. $keys_last = array_pop($keys);
  665. $path = [];
  666. $depth = 0;
  667. $path[0] =& $array;
  668. $found = true;
  669. // go as deep as required or possible
  670. foreach ($keys as $key) {
  671. if (! isset($path[$depth][$key])) {
  672. $found = false;
  673. break;
  674. }
  675. $depth++;
  676. $path[$depth] =& $path[$depth - 1][$key];
  677. }
  678. // if element found, remove it
  679. if ($found) {
  680. unset($path[$depth][$keys_last]);
  681. $depth--;
  682. }
  683. // remove empty nested arrays
  684. for (; $depth >= 0; $depth--) {
  685. if (! isset($path[$depth + 1]) || count($path[$depth + 1]) === 0) {
  686. unset($path[$depth][$keys[$depth]]);
  687. } else {
  688. break;
  689. }
  690. }
  691. }
  692. /**
  693. * Returns link to (possibly) external site using defined redirector.
  694. *
  695. * @param string $url URL where to go.
  696. *
  697. * @return string URL for a link.
  698. */
  699. public static function linkURL(string $url): string
  700. {
  701. if (! preg_match('#^https?://#', $url)) {
  702. return $url;
  703. }
  704. $params = [];
  705. $params['url'] = $url;
  706. $url = Url::getCommon($params);
  707. //strip off token and such sensitive information. Just keep url.
  708. $arr = parse_url($url);
  709. parse_str($arr["query"], $vars);
  710. $query = http_build_query(["url" => $vars["url"]]);
  711. if ($GLOBALS['PMA_Config'] !== null && $GLOBALS['PMA_Config']->get('is_setup')) {
  712. $url = '../url.php?' . $query;
  713. } else {
  714. $url = './url.php?' . $query;
  715. }
  716. return $url;
  717. }
  718. /**
  719. * Checks whether domain of URL is whitelisted domain or not.
  720. * Use only for URLs of external sites.
  721. *
  722. * @param string $url URL of external site.
  723. *
  724. * @return boolean True: if domain of $url is allowed domain,
  725. * False: otherwise.
  726. */
  727. public static function isAllowedDomain(string $url): bool
  728. {
  729. $arr = parse_url($url);
  730. // We need host to be set
  731. if (! isset($arr['host']) || strlen($arr['host']) == 0) {
  732. return false;
  733. }
  734. // We do not want these to be present
  735. $blocked = [
  736. 'user',
  737. 'pass',
  738. 'port',
  739. ];
  740. foreach ($blocked as $part) {
  741. if (isset($arr[$part]) && strlen((string) $arr[$part]) != 0) {
  742. return false;
  743. }
  744. }
  745. $domain = $arr["host"];
  746. $domainWhiteList = [
  747. /* Include current domain */
  748. $_SERVER['SERVER_NAME'],
  749. /* phpMyAdmin domains */
  750. 'wiki.phpmyadmin.net',
  751. 'www.phpmyadmin.net',
  752. 'phpmyadmin.net',
  753. 'demo.phpmyadmin.net',
  754. 'docs.phpmyadmin.net',
  755. /* mysql.com domains */
  756. 'dev.mysql.com',
  757. 'bugs.mysql.com',
  758. /* mariadb domains */
  759. 'mariadb.org',
  760. 'mariadb.com',
  761. /* php.net domains */
  762. 'php.net',
  763. 'secure.php.net',
  764. /* Github domains*/
  765. 'github.com',
  766. 'www.github.com',
  767. /* Percona domains */
  768. 'www.percona.com',
  769. /* Following are doubtful ones. */
  770. 'mysqldatabaseadministration.blogspot.com',
  771. ];
  772. return in_array($domain, $domainWhiteList);
  773. }
  774. /**
  775. * Replace some html-unfriendly stuff
  776. *
  777. * @param string $buffer String to process
  778. *
  779. * @return string Escaped and cleaned up text suitable for html
  780. */
  781. public static function mimeDefaultFunction(string $buffer): string
  782. {
  783. $buffer = htmlspecialchars($buffer);
  784. $buffer = str_replace(' ', ' &nbsp;', $buffer);
  785. return preg_replace("@((\015\012)|(\015)|(\012))@", '<br>' . "\n", $buffer);
  786. }
  787. /**
  788. * Displays SQL query before executing.
  789. *
  790. * @param array|string $query_data Array containing queries or query itself
  791. *
  792. * @return void
  793. */
  794. public static function previewSQL($query_data): void
  795. {
  796. $retval = '<div class="preview_sql">';
  797. if (empty($query_data)) {
  798. $retval .= __('No change');
  799. } elseif (is_array($query_data)) {
  800. foreach ($query_data as $query) {
  801. $retval .= Util::formatSql($query);
  802. }
  803. } else {
  804. $retval .= Util::formatSql($query_data);
  805. }
  806. $retval .= '</div>';
  807. $response = Response::getInstance();
  808. $response->addJSON('sql_data', $retval);
  809. exit;
  810. }
  811. /**
  812. * recursively check if variable is empty
  813. *
  814. * @param mixed $value the variable
  815. *
  816. * @return bool true if empty
  817. */
  818. public static function emptyRecursive($value): bool
  819. {
  820. $empty = true;
  821. if (is_array($value)) {
  822. array_walk_recursive(
  823. $value,
  824. function ($item) use (&$empty) {
  825. $empty = $empty && empty($item);
  826. }
  827. );
  828. } else {
  829. $empty = empty($value);
  830. }
  831. return $empty;
  832. }
  833. /**
  834. * Creates some globals from $_POST variables matching a pattern
  835. *
  836. * @param array $post_patterns The patterns to search for
  837. *
  838. * @return void
  839. */
  840. public static function setPostAsGlobal(array $post_patterns): void
  841. {
  842. foreach (array_keys($_POST) as $post_key) {
  843. foreach ($post_patterns as $one_post_pattern) {
  844. if (preg_match($one_post_pattern, $post_key)) {
  845. Migration::getInstance()->setGlobal($post_key, $_POST[$post_key]);
  846. }
  847. }
  848. }
  849. }
  850. /**
  851. * Creates some globals from $_REQUEST
  852. *
  853. * @param string $param db|table
  854. *
  855. * @return void
  856. */
  857. public static function setGlobalDbOrTable(string $param): void
  858. {
  859. $value = '';
  860. if (self::isValid($_REQUEST[$param])) {
  861. $value = $_REQUEST[$param];
  862. }
  863. Migration::getInstance()->setGlobal($param, $value);
  864. Migration::getInstance()->setGlobal('url_params', [$param => $value] + $GLOBALS['url_params']);
  865. }
  866. /**
  867. * PATH_INFO could be compromised if set, so remove it from PHP_SELF
  868. * and provide a clean PHP_SELF here
  869. *
  870. * @return void
  871. */
  872. public static function cleanupPathInfo(): void
  873. {
  874. global $PMA_PHP_SELF;
  875. $PMA_PHP_SELF = self::getenv('PHP_SELF');
  876. if (empty($PMA_PHP_SELF)) {
  877. $PMA_PHP_SELF = urldecode(self::getenv('REQUEST_URI'));
  878. }
  879. $_PATH_INFO = self::getenv('PATH_INFO');
  880. if (! empty($_PATH_INFO) && ! empty($PMA_PHP_SELF)) {
  881. $question_pos = mb_strpos($PMA_PHP_SELF, '?');
  882. if ($question_pos != false) {
  883. $PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $question_pos);
  884. }
  885. $path_info_pos = mb_strrpos($PMA_PHP_SELF, $_PATH_INFO);
  886. if ($path_info_pos !== false) {
  887. $path_info_part = mb_substr($PMA_PHP_SELF, $path_info_pos, mb_strlen($_PATH_INFO));
  888. if ($path_info_part == $_PATH_INFO) {
  889. $PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $path_info_pos);
  890. }
  891. }
  892. }
  893. $path = [];
  894. foreach (explode('/', $PMA_PHP_SELF) as $part) {
  895. // ignore parts that have no value
  896. if (empty($part) || $part === '.') {
  897. continue;
  898. }
  899. if ($part !== '..') {
  900. // cool, we found a new part
  901. $path[] = $part;
  902. } elseif (count($path) > 0) {
  903. // going back up? sure
  904. array_pop($path);
  905. }
  906. // Here we intentionall ignore case where we go too up
  907. // as there is nothing sane to do
  908. }
  909. $PMA_PHP_SELF = htmlspecialchars('/' . implode('/', $path));
  910. }
  911. /**
  912. * Checks that required PHP extensions are there.
  913. * @return void
  914. */
  915. public static function checkExtensions(): void
  916. {
  917. /**
  918. * Warning about mbstring.
  919. */
  920. if (! function_exists('mb_detect_encoding')) {
  921. self::warnMissingExtension('mbstring');
  922. }
  923. /**
  924. * We really need this one!
  925. */
  926. if (! function_exists('preg_replace')) {
  927. self::warnMissingExtension('pcre', true);
  928. }
  929. /**
  930. * JSON is required in several places.
  931. */
  932. if (! function_exists('json_encode')) {
  933. self::warnMissingExtension('json', true);
  934. }
  935. /**
  936. * ctype is required for Twig.
  937. */
  938. if (! function_exists('ctype_alpha')) {
  939. self::warnMissingExtension('ctype', true);
  940. }
  941. /**
  942. * hash is required for cookie authentication.
  943. */
  944. if (! function_exists('hash_hmac')) {
  945. self::warnMissingExtension('hash', true);
  946. }
  947. }
  948. /**
  949. * Gets the "true" IP address of the current user
  950. *
  951. * @return string|bool the ip of the user
  952. *
  953. * @access private
  954. */
  955. public static function getIp()
  956. {
  957. /* Get the address of user */
  958. if (empty($_SERVER['REMOTE_ADDR'])) {
  959. /* We do not know remote IP */
  960. return false;
  961. }
  962. $direct_ip = $_SERVER['REMOTE_ADDR'];
  963. /* Do we trust this IP as a proxy? If yes we will use it's header. */
  964. if (! isset($GLOBALS['cfg']['TrustedProxies'][$direct_ip])) {
  965. /* Return true IP */
  966. return $direct_ip;
  967. }
  968. /**
  969. * Parse header in form:
  970. * X-Forwarded-For: client, proxy1, proxy2
  971. */
  972. // Get header content
  973. $value = self::getenv($GLOBALS['cfg']['TrustedProxies'][$direct_ip]);
  974. // Grab first element what is client adddress
  975. $value = explode(',', $value)[0];
  976. // checks that the header contains only one IP address,
  977. $is_ip = filter_var($value, FILTER_VALIDATE_IP);
  978. if ($is_ip !== false) {
  979. // True IP behind a proxy
  980. return $value;
  981. }
  982. // We could not parse header
  983. return false;
  984. } // end of the 'getIp()' function
  985. /**
  986. * Sanitizes MySQL hostname
  987. *
  988. * * strips p: prefix(es)
  989. *
  990. * @param string $name User given hostname
  991. *
  992. * @return string
  993. */
  994. public static function sanitizeMySQLHost(string $name): string
  995. {
  996. while (strtolower(substr($name, 0, 2)) == 'p:') {
  997. $name = substr($name, 2);
  998. }
  999. return $name;
  1000. }
  1001. /**
  1002. * Sanitizes MySQL username
  1003. *
  1004. * * strips part behind null byte
  1005. *
  1006. * @param string $name User given username
  1007. *
  1008. * @return string
  1009. */
  1010. public static function sanitizeMySQLUser(string $name): string
  1011. {
  1012. $position = strpos($name, chr(0));
  1013. if ($position !== false) {
  1014. return substr($name, 0, $position);
  1015. }
  1016. return $name;
  1017. }
  1018. /**
  1019. * Safe unserializer wrapper
  1020. *
  1021. * It does not unserialize data containing objects
  1022. *
  1023. * @param string $data Data to unserialize
  1024. *
  1025. * @return mixed
  1026. */
  1027. public static function safeUnserialize(string $data)
  1028. {
  1029. if (! is_string($data)) {
  1030. return null;
  1031. }
  1032. /* validate serialized data */
  1033. $length = strlen($data);
  1034. $depth = 0;
  1035. for ($i = 0; $i < $length; $i++) {
  1036. $value = $data[$i];
  1037. switch ($value) {
  1038. case '}':
  1039. /* end of array */
  1040. if ($depth <= 0) {
  1041. return null;
  1042. }
  1043. $depth--;
  1044. break;
  1045. case 's':
  1046. /* string */
  1047. // parse sting length
  1048. $strlen = intval(substr($data, $i + 2));
  1049. // string start
  1050. $i = strpos($data, ':', $i + 2);
  1051. if ($i === false) {
  1052. return null;
  1053. }
  1054. // skip string, quotes and ;
  1055. $i += 2 + $strlen + 1;
  1056. if ($data[$i] != ';') {
  1057. return null;
  1058. }
  1059. break;
  1060. case 'b':
  1061. case 'i':
  1062. case 'd':
  1063. /* bool, integer or double */
  1064. // skip value to sepearator
  1065. $i = strpos($data, ';', $i);
  1066. if ($i === false) {
  1067. return null;
  1068. }
  1069. break;
  1070. case 'a':
  1071. /* array */
  1072. // find array start
  1073. $i = strpos($data, '{', $i);
  1074. if ($i === false) {
  1075. return null;
  1076. }
  1077. // remember nesting
  1078. $depth++;
  1079. break;
  1080. case 'N':
  1081. /* null */
  1082. // skip to end
  1083. $i = strpos($data, ';', $i);
  1084. if ($i === false) {
  1085. return null;
  1086. }
  1087. break;
  1088. default:
  1089. /* any other elements are not wanted */
  1090. return null;
  1091. }
  1092. }
  1093. // check unterminated arrays
  1094. if ($depth > 0) {
  1095. return null;
  1096. }
  1097. return unserialize($data);
  1098. }
  1099. /**
  1100. * Applies changes to PHP configuration.
  1101. *
  1102. * @return void
  1103. */
  1104. public static function configure(): void
  1105. {
  1106. /**
  1107. * Set utf-8 encoding for PHP
  1108. */
  1109. ini_set('default_charset', 'utf-8');
  1110. mb_internal_encoding('utf-8');
  1111. /**
  1112. * Set precision to sane value, with higher values
  1113. * things behave slightly unexpectedly, for example
  1114. * round(1.2, 2) returns 1.199999999999999956.
  1115. */
  1116. ini_set('precision', '14');
  1117. /**
  1118. * check timezone setting
  1119. * this could produce an E_WARNING - but only once,
  1120. * if not done here it will produce E_WARNING on every date/time function
  1121. */
  1122. date_default_timezone_set(@date_default_timezone_get());
  1123. }
  1124. /**
  1125. * Check whether PHP configuration matches our needs.
  1126. *
  1127. * @return void
  1128. */
  1129. public static function checkConfiguration(): void
  1130. {
  1131. /**
  1132. * As we try to handle charsets by ourself, mbstring overloads just
  1133. * break it, see bug 1063821.
  1134. *
  1135. * We specifically use empty here as we are looking for anything else than
  1136. * empty value or 0.
  1137. */
  1138. if (extension_loaded('mbstring') && ! empty(ini_get('mbstring.func_overload'))) {
  1139. self::fatalError(
  1140. __(
  1141. 'You have enabled mbstring.func_overload in your PHP '
  1142. . 'configuration. This option is incompatible with phpMyAdmin '
  1143. . 'and might cause some data to be corrupted!'
  1144. )
  1145. );
  1146. }
  1147. /**
  1148. * The ini_set and ini_get functions can be disabled using
  1149. * disable_functions but we're relying quite a lot of them.
  1150. */
  1151. if (! function_exists('ini_get') || ! function_exists('ini_set')) {
  1152. self::fatalError(
  1153. __(
  1154. 'The ini_get and/or ini_set functions are disabled in php.ini. '
  1155. . 'phpMyAdmin requires these functions!'
  1156. )
  1157. );
  1158. }
  1159. }
  1160. /**
  1161. * Checks request and fails with fatal error if something problematic is found
  1162. *
  1163. * @return void
  1164. */
  1165. public static function checkRequest(): void
  1166. {
  1167. if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
  1168. self::fatalError(__("GLOBALS overwrite attempt"));
  1169. }
  1170. /**
  1171. * protect against possible exploits - there is no need to have so much variables
  1172. */
  1173. if (count($_REQUEST) > 1000) {
  1174. self::fatalError(__('possible exploit'));
  1175. }
  1176. }
  1177. /**
  1178. * Sign the sql query using hmac using the session token
  1179. *
  1180. * @param string $sqlQuery The sql query
  1181. * @return string
  1182. */
  1183. public static function signSqlQuery($sqlQuery)
  1184. {
  1185. /** @var array $cfg */
  1186. global $cfg;
  1187. $secret = $_SESSION[' HMAC_secret '] ?? '';
  1188. return hash_hmac('sha256', $sqlQuery, $secret . $cfg['blowfish_secret']);
  1189. }
  1190. /**
  1191. * Check that the sql query has a valid hmac signature
  1192. *
  1193. * @param string $sqlQuery The sql query
  1194. * @param string $signature The Signature to check
  1195. * @return bool
  1196. */
  1197. public static function checkSqlQuerySignature($sqlQuery, $signature)
  1198. {
  1199. /** @var array $cfg */
  1200. global $cfg;
  1201. $secret = $_SESSION[' HMAC_secret '] ?? '';
  1202. $hmac = hash_hmac('sha256', $sqlQuery, $secret . $cfg['blowfish_secret']);
  1203. return hash_equals($hmac, $signature);
  1204. }
  1205. }