Core.php 40 KB

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