core.lib.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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. if (! defined('PHPMYADMIN')) {
  11. exit;
  12. }
  13. /**
  14. * checks given $var and returns it if valid, or $default of not valid
  15. * given $var is also checked for type being 'similar' as $default
  16. * or against any other type if $type is provided
  17. *
  18. * <code>
  19. * // $_REQUEST['db'] not set
  20. * echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
  21. * // $_REQUEST['sql_query'] not set
  22. * echo PMA_ifSetOr($_REQUEST['sql_query']); // null
  23. * // $cfg['ForceSSL'] not set
  24. * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
  25. * echo PMA_ifSetOr($cfg['ForceSSL']); // null
  26. * // $cfg['ForceSSL'] set to 1
  27. * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
  28. * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'similar'); // 1
  29. * echo PMA_ifSetOr($cfg['ForceSSL'], false); // 1
  30. * // $cfg['ForceSSL'] set to true
  31. * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // true
  32. * </code>
  33. *
  34. * @param mixed &$var param to check
  35. * @param mixed $default default value
  36. * @param mixed $type var type or array of values to check against $var
  37. *
  38. * @return mixed $var or $default
  39. *
  40. * @see PMA_isValid()
  41. */
  42. function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
  43. {
  44. if (! PMA_isValid($var, $type, $default)) {
  45. return $default;
  46. }
  47. return $var;
  48. }
  49. /**
  50. * checks given $var against $type or $compare
  51. *
  52. * $type can be:
  53. * - false : no type checking
  54. * - 'scalar' : whether type of $var is integer, float, string or boolean
  55. * - 'numeric' : whether type of $var is any number repesentation
  56. * - 'length' : whether type of $var is scalar with a string length > 0
  57. * - 'similar' : whether type of $var is similar to type of $compare
  58. * - 'equal' : whether type of $var is identical to type of $compare
  59. * - 'identical' : whether $var is identical to $compare, not only the type!
  60. * - or any other valid PHP variable type
  61. *
  62. * <code>
  63. * // $_REQUEST['doit'] = true;
  64. * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
  65. * // $_REQUEST['doit'] = 'true';
  66. * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
  67. * </code>
  68. *
  69. * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
  70. * but the var is not altered inside this function, also after checking a var
  71. * this var exists nut is not set, example:
  72. * <code>
  73. * // $var is not set
  74. * isset($var); // false
  75. * functionCallByReference($var); // false
  76. * isset($var); // true
  77. * functionCallByReference($var); // true
  78. * </code>
  79. *
  80. * to avoid this we set this var to null if not isset
  81. *
  82. * @param mixed &$var variable to check
  83. * @param mixed $type var type or array of valid values to check against $var
  84. * @param mixed $compare var to compare with $var
  85. *
  86. * @return boolean whether valid or not
  87. *
  88. * @todo add some more var types like hex, bin, ...?
  89. * @see http://php.net/gettype
  90. */
  91. function PMA_isValid(&$var, $type = 'length', $compare = null)
  92. {
  93. if (! isset($var)) {
  94. // var is not even set
  95. return false;
  96. }
  97. if ($type === false) {
  98. // no vartype requested
  99. return true;
  100. }
  101. if (is_array($type)) {
  102. return in_array($var, $type);
  103. }
  104. // allow some aliaes of var types
  105. $type = strtolower($type);
  106. switch ($type) {
  107. case 'identic' :
  108. $type = 'identical';
  109. break;
  110. case 'len' :
  111. $type = 'length';
  112. break;
  113. case 'bool' :
  114. $type = 'boolean';
  115. break;
  116. case 'float' :
  117. $type = 'double';
  118. break;
  119. case 'int' :
  120. $type = 'integer';
  121. break;
  122. case 'null' :
  123. $type = 'NULL';
  124. break;
  125. }
  126. if ($type === 'identical') {
  127. return $var === $compare;
  128. }
  129. // whether we should check against given $compare
  130. if ($type === 'similar') {
  131. switch (gettype($compare)) {
  132. case 'string':
  133. case 'boolean':
  134. $type = 'scalar';
  135. break;
  136. case 'integer':
  137. case 'double':
  138. $type = 'numeric';
  139. break;
  140. default:
  141. $type = gettype($compare);
  142. }
  143. } elseif ($type === 'equal') {
  144. $type = gettype($compare);
  145. }
  146. // do the check
  147. if ($type === 'length' || $type === 'scalar') {
  148. $is_scalar = is_scalar($var);
  149. if ($is_scalar && $type === 'length') {
  150. return (bool) strlen($var);
  151. }
  152. return $is_scalar;
  153. }
  154. if ($type === 'numeric') {
  155. return is_numeric($var);
  156. }
  157. if (gettype($var) === $type) {
  158. return true;
  159. }
  160. return false;
  161. }
  162. /**
  163. * Removes insecure parts in a path; used before include() or
  164. * require() when a part of the path comes from an insecure source
  165. * like a cookie or form.
  166. *
  167. * @param string $path The path to check
  168. *
  169. * @return string The secured path
  170. *
  171. * @access public
  172. */
  173. function PMA_securePath($path)
  174. {
  175. // change .. to .
  176. $path = preg_replace('@\.\.*@', '.', $path);
  177. return $path;
  178. } // end function
  179. /**
  180. * displays the given error message on phpMyAdmin error page in foreign language,
  181. * ends script execution and closes session
  182. *
  183. * loads language file if not loaded already
  184. *
  185. * @param string $error_message the error message or named error message
  186. * @param string|array $message_args arguments applied to $error_message
  187. * @param boolean $delete_session whether to delete session cookie
  188. *
  189. * @return exit
  190. */
  191. function PMA_fatalError(
  192. $error_message, $message_args = null, $delete_session = true
  193. ) {
  194. /* Use format string if applicable */
  195. if (is_string($message_args)) {
  196. $error_message = sprintf($error_message, $message_args);
  197. } elseif (is_array($message_args)) {
  198. $error_message = vsprintf($error_message, $message_args);
  199. }
  200. if ($GLOBALS['is_ajax_request']) {
  201. $response = PMA_Response::getInstance();
  202. $response->isSuccess(false);
  203. $response->addJSON('message', PMA_Message::error($error_message));
  204. } else {
  205. $error_message = strtr($error_message, array('<br />' => '[br]'));
  206. /* Define fake gettext for fatal errors */
  207. if (!function_exists('__')) {
  208. function __($text)
  209. {
  210. return $text;
  211. }
  212. }
  213. // these variables are used in the included file libraries/error.inc.php
  214. $error_header = __('Error');
  215. $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][1];
  216. $dir = $GLOBALS['text_dir'];
  217. // on fatal errors it cannot hurt to always delete the current session
  218. if ($delete_session
  219. && isset($GLOBALS['session_name'])
  220. && isset($_COOKIE[$GLOBALS['session_name']])
  221. ) {
  222. $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
  223. }
  224. // Displays the error message
  225. include './libraries/error.inc.php';
  226. }
  227. if (! defined('TESTSUITE')) {
  228. exit;
  229. }
  230. }
  231. /**
  232. * Returns a link to the PHP documentation
  233. *
  234. * @param string $target anchor in documentation
  235. *
  236. * @return string the URL
  237. *
  238. * @access public
  239. */
  240. function PMA_getPHPDocLink($target)
  241. {
  242. /* List of PHP documentation translations */
  243. $php_doc_languages = array(
  244. 'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr'
  245. );
  246. $lang = 'en';
  247. if (in_array($GLOBALS['lang'], $php_doc_languages)) {
  248. $lang = $GLOBALS['lang'];
  249. }
  250. return PMA_linkURL('http://php.net/manual/' . $lang . '/' . $target);
  251. }
  252. /**
  253. * Warn or fail on missing extension.
  254. *
  255. * @param string $extension Extension name
  256. * @param bool $fatal Whether the error is fatal.
  257. * @param string $extra Extra string to append to messsage.
  258. *
  259. * @return void
  260. */
  261. function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
  262. {
  263. /* Gettext does not have to be loaded yet here */
  264. if (function_exists('__')) {
  265. $message = __(
  266. 'The %s extension is missing. Please check your PHP configuration.'
  267. );
  268. } else {
  269. $message
  270. = 'The %s extension is missing. Please check your PHP configuration.';
  271. }
  272. $doclink = PMA_getPHPDocLink('book.' . $extension . '.php');
  273. $message = sprintf(
  274. $message,
  275. '[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
  276. );
  277. if ($extra != '') {
  278. $message .= ' ' . $extra;
  279. }
  280. if ($fatal) {
  281. PMA_fatalError($message);
  282. } else {
  283. $GLOBALS['error_handler']->addError(
  284. $message,
  285. E_USER_WARNING,
  286. '',
  287. '',
  288. false
  289. );
  290. }
  291. }
  292. /**
  293. * returns count of tables in given db
  294. *
  295. * @param string $db database to count tables for
  296. *
  297. * @return integer count of tables in $db
  298. */
  299. function PMA_getTableCount($db)
  300. {
  301. $tables = PMA_DBI_try_query(
  302. 'SHOW TABLES FROM ' . PMA_Util::backquote($db) . ';',
  303. null, PMA_DBI_QUERY_STORE
  304. );
  305. if ($tables) {
  306. $num_tables = PMA_DBI_num_rows($tables);
  307. PMA_DBI_free_result($tables);
  308. } else {
  309. $num_tables = 0;
  310. }
  311. return $num_tables;
  312. }
  313. /**
  314. * Converts numbers like 10M into bytes
  315. * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
  316. * (renamed with PMA prefix to avoid double definition when embedded
  317. * in Moodle)
  318. *
  319. * @param string $size size
  320. *
  321. * @return integer $size
  322. */
  323. function PMA_getRealSize($size = 0)
  324. {
  325. if (! $size) {
  326. return 0;
  327. }
  328. $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
  329. $scan['g'] = 1073741824; //1024 * 1024 * 1024;
  330. $scan['mb'] = 1048576;
  331. $scan['m'] = 1048576;
  332. $scan['kb'] = 1024;
  333. $scan['k'] = 1024;
  334. $scan['b'] = 1;
  335. foreach ($scan as $unit => $factor) {
  336. if (strlen($size) > strlen($unit)
  337. && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit
  338. ) {
  339. return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
  340. }
  341. }
  342. return $size;
  343. } // end function PMA_getRealSize()
  344. /**
  345. * merges array recursive like array_merge_recursive() but keyed-values are
  346. * always overwritten.
  347. *
  348. * array PMA_arrayMergeRecursive(array $array1[, array $array2[, array ...]])
  349. *
  350. * @return array merged array
  351. *
  352. * @see http://php.net/array_merge
  353. * @see http://php.net/array_merge_recursive
  354. */
  355. function PMA_arrayMergeRecursive()
  356. {
  357. switch(func_num_args()) {
  358. case 0 :
  359. return false;
  360. break;
  361. case 1 :
  362. // when does that happen?
  363. return func_get_arg(0);
  364. break;
  365. case 2 :
  366. $args = func_get_args();
  367. if (! is_array($args[0]) || ! is_array($args[1])) {
  368. return $args[1];
  369. }
  370. foreach ($args[1] as $key2 => $value2) {
  371. if (isset($args[0][$key2]) && !is_int($key2)) {
  372. $args[0][$key2] = PMA_arrayMergeRecursive(
  373. $args[0][$key2], $value2
  374. );
  375. } else {
  376. // we erase the parent array, otherwise we cannot override
  377. // a directive that contains array elements, like this:
  378. // (in config.default.php)
  379. // $cfg['ForeignKeyDropdownOrder']= array('id-content','content-id');
  380. // (in config.inc.php)
  381. // $cfg['ForeignKeyDropdownOrder']= array('content-id');
  382. if (is_int($key2) && $key2 == 0) {
  383. unset($args[0]);
  384. }
  385. $args[0][$key2] = $value2;
  386. }
  387. }
  388. return $args[0];
  389. break;
  390. default :
  391. $args = func_get_args();
  392. $args[1] = PMA_arrayMergeRecursive($args[0], $args[1]);
  393. array_shift($args);
  394. return call_user_func_array('PMA_arrayMergeRecursive', $args);
  395. break;
  396. }
  397. }
  398. /**
  399. * calls $function for every element in $array recursively
  400. *
  401. * this function is protected against deep recursion attack CVE-2006-1549,
  402. * 1000 seems to be more than enough
  403. *
  404. * @param array &$array array to walk
  405. * @param string $function function to call for every array element
  406. * @param bool $apply_to_keys_also whether to call the function for the keys also
  407. *
  408. * @return void
  409. *
  410. * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
  411. * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
  412. */
  413. function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
  414. {
  415. static $recursive_counter = 0;
  416. if (++$recursive_counter > 1000) {
  417. PMA_fatalError(__('possible deep recursion attack'));
  418. }
  419. foreach ($array as $key => $value) {
  420. if (is_array($value)) {
  421. PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
  422. } else {
  423. $array[$key] = $function($value);
  424. }
  425. if ($apply_to_keys_also && is_string($key)) {
  426. $new_key = $function($key);
  427. if ($new_key != $key) {
  428. $array[$new_key] = $array[$key];
  429. unset($array[$key]);
  430. }
  431. }
  432. }
  433. $recursive_counter--;
  434. }
  435. /**
  436. * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
  437. *
  438. * checks given given $page against given $whitelist and returns true if valid
  439. * it ignores optionaly query paramters in $page (script.php?ignored)
  440. *
  441. * @param string &$page page to check
  442. * @param array $whitelist whitelist to check page against
  443. *
  444. * @return boolean whether $page is valid or not (in $whitelist or not)
  445. */
  446. function PMA_checkPageValidity(&$page, $whitelist)
  447. {
  448. if (! isset($page) || !is_string($page)) {
  449. return false;
  450. }
  451. if (in_array($page, $whitelist)) {
  452. return true;
  453. } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
  454. return true;
  455. } else {
  456. $_page = urldecode($page);
  457. if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
  458. return true;
  459. }
  460. }
  461. return false;
  462. }
  463. /**
  464. * tries to find the value for the given environment variable name
  465. *
  466. * searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
  467. * in this order
  468. *
  469. * @param string $var_name variable name
  470. *
  471. * @return string value of $var or empty string
  472. */
  473. function PMA_getenv($var_name)
  474. {
  475. if (isset($_SERVER[$var_name])) {
  476. return $_SERVER[$var_name];
  477. } elseif (isset($_ENV[$var_name])) {
  478. return $_ENV[$var_name];
  479. } elseif (getenv($var_name)) {
  480. return getenv($var_name);
  481. } elseif (function_exists('apache_getenv')
  482. && apache_getenv($var_name, true)) {
  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 boolean always true
  494. */
  495. function PMA_sendHeaderLocation($uri, $use_refresh = false)
  496. {
  497. if (PMA_IS_IIS && strlen($uri) > 600) {
  498. include_once './libraries/js_escape.lib.php';
  499. PMA_Response::getInstance()->disable();
  500. echo '<html><head><title>- - -</title>' . "\n";
  501. echo '<meta http-equiv="expires" content="0">' . "\n";
  502. echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
  503. echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
  504. echo '<meta http-equiv="Refresh" content="0;url='
  505. . htmlspecialchars($uri) . '">' . "\n";
  506. echo '<script type="text/javascript">' . "\n";
  507. echo '//<![CDATA[' . "\n";
  508. echo 'setTimeout("window.location = unescape(\'"'
  509. . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
  510. echo '//]]>' . "\n";
  511. echo '</script>' . "\n";
  512. echo '</head>' . "\n";
  513. echo '<body>' . "\n";
  514. echo '<script type="text/javascript">' . "\n";
  515. echo '//<![CDATA[' . "\n";
  516. echo 'document.write(\'<p><a href="' . PMA_escapeJsString(htmlspecialchars($uri)) . '">'
  517. . __('Go') . '</a></p>\');' . "\n";
  518. echo '//]]>' . "\n";
  519. echo '</script></body></html>' . "\n";
  520. } else {
  521. if (SID) {
  522. if (strpos($uri, '?') === false) {
  523. header('Location: ' . $uri . '?' . SID);
  524. } else {
  525. $separator = PMA_get_arg_separator();
  526. header('Location: ' . $uri . $separator . SID);
  527. }
  528. } else {
  529. session_write_close();
  530. if (headers_sent()) {
  531. trigger_error(
  532. 'PMA_sendHeaderLocation called when headers are already sent!',
  533. E_USER_ERROR
  534. );
  535. }
  536. // bug #1523784: IE6 does not like 'Refresh: 0', it
  537. // results in a blank page
  538. // but we need it when coming from the cookie login panel)
  539. if (PMA_IS_IIS && $use_refresh) {
  540. header('Refresh: 0; ' . $uri);
  541. } else {
  542. header('Location: ' . $uri);
  543. }
  544. }
  545. }
  546. }
  547. /**
  548. * Outputs headers to prevent caching in browser (and on the way).
  549. *
  550. * @return void
  551. */
  552. function PMA_noCacheHeader()
  553. {
  554. if (defined('TESTSUITE')) {
  555. return;
  556. }
  557. // rfc2616 - Section 14.21
  558. header('Expires: ' . date(DATE_RFC1123));
  559. // HTTP/1.1
  560. header(
  561. 'Cache-Control: no-store, no-cache, must-revalidate,'
  562. . ' pre-check=0, post-check=0, max-age=0'
  563. );
  564. if (PMA_USR_BROWSER_AGENT == 'IE') {
  565. /* On SSL IE sometimes fails with:
  566. *
  567. * Internet Explorer was not able to open this Internet site. The
  568. * requested site is either unavailable or cannot be found. Please
  569. * try again later.
  570. *
  571. * Adding Pragma: public fixes this.
  572. */
  573. header('Pragma: public');
  574. } else {
  575. header('Pragma: no-cache'); // HTTP/1.0
  576. // test case: exporting a database into a .gz file with Safari
  577. // would produce files not having the current time
  578. // (added this header for Safari but should not harm other browsers)
  579. header('Last-Modified: ' . date(DATE_RFC1123));
  580. }
  581. }
  582. /**
  583. * Sends header indicating file download.
  584. *
  585. * @param string $filename Filename to include in headers if empty,
  586. * none Content-Disposition header will be sent.
  587. * @param string $mimetype MIME type to include in headers.
  588. * @param int $length Length of content (optional)
  589. * @param bool $no_cache Whether to include no-caching headers.
  590. *
  591. * @return void
  592. */
  593. function PMA_downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
  594. {
  595. if ($no_cache) {
  596. PMA_noCacheHeader();
  597. }
  598. /* Replace all possibly dangerous chars in filename */
  599. $filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename);
  600. if (!empty($filename)) {
  601. header('Content-Description: File Transfer');
  602. header('Content-Disposition: attachment; filename="' . $filename . '"');
  603. }
  604. header('Content-Type: ' . $mimetype);
  605. header('Content-Transfer-Encoding: binary');
  606. if ($length > 0) {
  607. header('Content-Length: ' . $length);
  608. }
  609. }
  610. /**
  611. * Returns value of an element in $array given by $path.
  612. * $path is a string describing position of an element in an associative array,
  613. * eg. Servers/1/host refers to $array[Servers][1][host]
  614. *
  615. * @param string $path path in the arry
  616. * @param array $array the array
  617. * @param mixed $default default value
  618. *
  619. * @return mixed array element or $default
  620. */
  621. function PMA_arrayRead($path, $array, $default = null)
  622. {
  623. $keys = explode('/', $path);
  624. $value =& $array;
  625. foreach ($keys as $key) {
  626. if (! isset($value[$key])) {
  627. return $default;
  628. }
  629. $value =& $value[$key];
  630. }
  631. return $value;
  632. }
  633. /**
  634. * Stores value in an array
  635. *
  636. * @param string $path path in the array
  637. * @param array &$array the array
  638. * @param mixed $value value to store
  639. *
  640. * @return void
  641. */
  642. function PMA_arrayWrite($path, &$array, $value)
  643. {
  644. $keys = explode('/', $path);
  645. $last_key = array_pop($keys);
  646. $a =& $array;
  647. foreach ($keys as $key) {
  648. if (! isset($a[$key])) {
  649. $a[$key] = array();
  650. }
  651. $a =& $a[$key];
  652. }
  653. $a[$last_key] = $value;
  654. }
  655. /**
  656. * Removes value from an array
  657. *
  658. * @param string $path path in the array
  659. * @param array &$array the array
  660. *
  661. * @return void
  662. */
  663. function PMA_arrayRemove($path, &$array)
  664. {
  665. $keys = explode('/', $path);
  666. $keys_last = array_pop($keys);
  667. $path = array();
  668. $depth = 0;
  669. $path[0] =& $array;
  670. $found = true;
  671. // go as deep as required or possible
  672. foreach ($keys as $key) {
  673. if (! isset($path[$depth][$key])) {
  674. $found = false;
  675. break;
  676. }
  677. $depth++;
  678. $path[$depth] =& $path[$depth-1][$key];
  679. }
  680. // if element found, remove it
  681. if ($found) {
  682. unset($path[$depth][$keys_last]);
  683. $depth--;
  684. }
  685. // remove empty nested arrays
  686. for (; $depth >= 0; $depth--) {
  687. if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
  688. unset($path[$depth][$keys[$depth]]);
  689. } else {
  690. break;
  691. }
  692. }
  693. }
  694. /**
  695. * Returns link to (possibly) external site using defined redirector.
  696. *
  697. * @param string $url URL where to go.
  698. *
  699. * @return string URL for a link.
  700. */
  701. function PMA_linkURL($url)
  702. {
  703. if (!preg_match('#^https?://#', $url)) {
  704. return $url;
  705. } else {
  706. if (!function_exists('PMA_generate_common_url')) {
  707. include_once './libraries/url_generating.lib.php';
  708. }
  709. $params = array();
  710. $params['url'] = $url;
  711. if (defined('PMA_SETUP')) {
  712. return '../url.php' . PMA_generate_common_url($params);
  713. } else {
  714. return './url.php' . PMA_generate_common_url($params);
  715. }
  716. }
  717. }
  718. /**
  719. * Adds JS code snippets to be displayed by the PMA_Response class.
  720. * Adds a newline to each snippet.
  721. *
  722. * @param string $str Js code to be added (e.g. "token=1234;")
  723. *
  724. * @return void
  725. */
  726. function PMA_addJSCode($str)
  727. {
  728. $response = PMA_Response::getInstance();
  729. $header = $response->getHeader();
  730. $scripts = $header->getScripts();
  731. $scripts->addCode($str);
  732. }
  733. /**
  734. * Adds JS code snippet for variable assignment
  735. * to be displayed by the PMA_Response class.
  736. *
  737. * @param string $key Name of value to set
  738. * @param mixed $value Value to set, can be either string or array of strings
  739. * @param bool $escape Whether to escape value or keep it as it is
  740. * (for inclusion of js code)
  741. *
  742. * @return void
  743. */
  744. function PMA_addJSVar($key, $value, $escape = true)
  745. {
  746. PMA_addJSCode(PMA_getJsValue($key, $value, $escape));
  747. }
  748. /* Compatibility with PHP < 5.6 */
  749. if(! function_exists('hash_equals')) {
  750. function hash_equals($a, $b) {
  751. $ret = strlen($a) ^ strlen($b);
  752. $ret |= array_sum(unpack("C*", $a ^ $b));
  753. return ! $ret;
  754. }
  755. }
  756. /**
  757. * Checks whether domain of URL is whitelisted domain or not.
  758. * Use only for URLs of external sites.
  759. *
  760. * @param string $url URL of external site.
  761. *
  762. * @return boolean.True:if domain of $url is allowed domain, False:otherwise.
  763. */
  764. function PMA_isAllowedDomain($url)
  765. {
  766. $arr = parse_url($url);
  767. // We need host to be set
  768. if (! isset($arr['host']) || strlen($arr['host']) == 0) {
  769. return false;
  770. }
  771. // We do not want these to be present
  772. $blocked = array('user', 'pass', 'port');
  773. foreach ($blocked as $part) {
  774. if (isset($arr[$part]) && strlen($arr[$part]) != 0) {
  775. return false;
  776. }
  777. }
  778. $domain = $arr["host"];
  779. $domainWhiteList = array(
  780. /* Include current domain */
  781. $_SERVER['SERVER_NAME'],
  782. /* phpMyAdmin domains */
  783. 'wiki.phpmyadmin.net', 'www.phpmyadmin.net', 'phpmyadmin.net',
  784. 'docs.phpmyadmin.net',
  785. 'demo.phpmyadmin.net',
  786. /* mysql.com domains */
  787. 'dev.mysql.com','bugs.mysql.com',
  788. /* mariadb domains */
  789. 'mariadb.org', 'mariadb.com',
  790. /* php.net domains */
  791. 'php.net',
  792. /* sourceforge.net domain */
  793. 'sourceforge.net',
  794. /* Github domains*/
  795. 'github.com','www.github.com',
  796. /* Percona domains */
  797. 'www.percona.com',
  798. /* Following are doubtful ones. */
  799. 'www.primebase.com','pbxt.blogspot.com',
  800. 'mysqldatabaseadministration.blogspot.com',
  801. /* CVE */
  802. 'cve.mitre.org',
  803. );
  804. if (in_array($domain, $domainWhiteList)) {
  805. return true;
  806. }
  807. return false;
  808. }
  809. /* Compatibility with PHP < 5.1 or PHP without hash extension */
  810. if (! function_exists('hash_hmac')) {
  811. function hash_hmac($algo, $data, $key, $raw_output = false)
  812. {
  813. $algo = strtolower($algo);
  814. $pack = 'H'.strlen($algo('test'));
  815. $size = 64;
  816. $opad = str_repeat(chr(0x5C), $size);
  817. $ipad = str_repeat(chr(0x36), $size);
  818. if (strlen($key) > $size) {
  819. $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
  820. } else {
  821. $key = str_pad($key, $size, chr(0x00));
  822. }
  823. for ($i = 0; $i < strlen($key) - 1; $i++) {
  824. $opad[$i] = $opad[$i] ^ $key[$i];
  825. $ipad[$i] = $ipad[$i] ^ $key[$i];
  826. }
  827. $output = $algo($opad.pack($pack, $algo($ipad.$data)));
  828. return ($raw_output) ? pack($pack, $output) : $output;
  829. }
  830. }
  831. /**
  832. * Sanitizes MySQL hostname
  833. *
  834. * * strips p: prefix(es)
  835. *
  836. * @param string $name User given hostname
  837. *
  838. * @return string
  839. */
  840. function PMA_sanitizeMySQLHost($name)
  841. {
  842. while (strtolower(substr($name, 0, 2)) == 'p:') {
  843. $name = substr($name, 2);
  844. }
  845. return $name;
  846. }
  847. /**
  848. * Sanitizes MySQL username
  849. *
  850. * * strips part behind null byte
  851. *
  852. * @param string $name User given username
  853. *
  854. * @return string
  855. */
  856. function PMA_sanitizeMySQLUser($name)
  857. {
  858. $position = strpos($name, chr(0));
  859. if ($position !== false) {
  860. return substr($name, 0, $position);
  861. }
  862. return $name;
  863. }
  864. /**
  865. * Safe unserializer wrapper
  866. *
  867. * It does not unserialize data containing objects
  868. *
  869. * @param string $data Data to unserialize
  870. *
  871. * @return mixed
  872. */
  873. function PMA_safeUnserialize($data)
  874. {
  875. if (! is_string($data)) {
  876. return null;
  877. }
  878. /* validate serialized data */
  879. $length = strlen($data);
  880. $depth = 0;
  881. for ($i = 0; $i < $length; $i++) {
  882. $value = $data[$i];
  883. switch ($value)
  884. {
  885. case '}':
  886. /* end of array */
  887. if ($depth <= 0) {
  888. return null;
  889. }
  890. $depth--;
  891. break;
  892. case 's':
  893. /* string */
  894. // parse sting length
  895. $strlen = intval(substr($data, $i + 2));
  896. // string start
  897. $i = strpos($data, ':', $i + 2);
  898. if ($i === false) {
  899. return null;
  900. }
  901. // skip string, quotes and ;
  902. $i += 2 + $strlen + 1;
  903. if ($data[$i] != ';') {
  904. return null;
  905. }
  906. break;
  907. case 'b':
  908. case 'i':
  909. case 'd':
  910. /* bool, integer or double */
  911. // skip value to sepearator
  912. $i = strpos($data, ';', $i);
  913. if ($i === false) {
  914. return null;
  915. }
  916. break;
  917. case 'a':
  918. /* array */
  919. // find array start
  920. $i = strpos($data, '{', $i);
  921. if ($i === false) {
  922. return null;
  923. }
  924. // remember nesting
  925. $depth++;
  926. break;
  927. case 'N':
  928. /* null */
  929. // skip to end
  930. $i = strpos($data, ';', $i);
  931. if ($i === false) {
  932. return null;
  933. }
  934. break;
  935. default:
  936. /* any other elements are not wanted */
  937. return null;
  938. }
  939. }
  940. // check unterminated arrays
  941. if ($depth > 0) {
  942. return null;
  943. }
  944. return unserialize($data);
  945. }
  946. ?>