core.lib.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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 representation
  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 void
  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. /* Load gettext for fatal errors */
  207. if (!function_exists('__')) {
  208. include_once './libraries/php-gettext/gettext.inc';
  209. }
  210. // these variables are used in the included file libraries/error.inc.php
  211. $error_header = __('Error');
  212. $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][1];
  213. $dir = $GLOBALS['text_dir'];
  214. // on fatal errors it cannot hurt to always delete the current session
  215. if ($delete_session
  216. && isset($GLOBALS['session_name'])
  217. && isset($_COOKIE[$GLOBALS['session_name']])
  218. ) {
  219. $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
  220. }
  221. // Displays the error message
  222. include './libraries/error.inc.php';
  223. }
  224. if (! defined('TESTSUITE')) {
  225. exit;
  226. }
  227. }
  228. /**
  229. * Returns a link to the PHP documentation
  230. *
  231. * @param string $target anchor in documentation
  232. *
  233. * @return string the URL
  234. *
  235. * @access public
  236. */
  237. function PMA_getPHPDocLink($target)
  238. {
  239. /* List of PHP documentation translations */
  240. $php_doc_languages = array(
  241. 'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr'
  242. );
  243. $lang = 'en';
  244. if (in_array($GLOBALS['lang'], $php_doc_languages)) {
  245. $lang = $GLOBALS['lang'];
  246. }
  247. return PMA_linkURL('http://php.net/manual/' . $lang . '/' . $target);
  248. }
  249. /**
  250. * Warn or fail on missing extension.
  251. *
  252. * @param string $extension Extension name
  253. * @param bool $fatal Whether the error is fatal.
  254. * @param string $extra Extra string to append to messsage.
  255. *
  256. * @return void
  257. */
  258. function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
  259. {
  260. /* Gettext does not have to be loaded yet here */
  261. if (function_exists('__')) {
  262. $message = __(
  263. 'The %s extension is missing. Please check your PHP configuration.'
  264. );
  265. } else {
  266. $message
  267. = 'The %s extension is missing. Please check your PHP configuration.';
  268. }
  269. $doclink = PMA_getPHPDocLink('book.' . $extension . '.php');
  270. $message = sprintf(
  271. $message,
  272. '[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
  273. );
  274. if ($extra != '') {
  275. $message .= ' ' . $extra;
  276. }
  277. if ($fatal) {
  278. PMA_fatalError($message);
  279. return;
  280. }
  281. $GLOBALS['error_handler']->addError(
  282. $message,
  283. E_USER_WARNING,
  284. '',
  285. '',
  286. false
  287. );
  288. }
  289. /**
  290. * returns count of tables in given db
  291. *
  292. * @param string $db database to count tables for
  293. *
  294. * @return integer count of tables in $db
  295. */
  296. function PMA_getTableCount($db)
  297. {
  298. $tables = $GLOBALS['dbi']->tryQuery(
  299. 'SHOW TABLES FROM ' . PMA_Util::backquote($db) . ';',
  300. null, PMA_DatabaseInterface::QUERY_STORE
  301. );
  302. if ($tables) {
  303. $num_tables = $GLOBALS['dbi']->numRows($tables);
  304. $GLOBALS['dbi']->freeResult($tables);
  305. } else {
  306. $num_tables = 0;
  307. }
  308. return $num_tables;
  309. }
  310. /**
  311. * Converts numbers like 10M into bytes
  312. * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
  313. * (renamed with PMA prefix to avoid double definition when embedded
  314. * in Moodle)
  315. *
  316. * @param string|int $size size (Default = 0)
  317. *
  318. * @return integer $size
  319. */
  320. function PMA_getRealSize($size = 0)
  321. {
  322. if (! $size) {
  323. return 0;
  324. }
  325. $scan = array();
  326. $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
  327. $scan['g'] = 1073741824; //1024 * 1024 * 1024;
  328. $scan['mb'] = 1048576;
  329. $scan['m'] = 1048576;
  330. $scan['kb'] = 1024;
  331. $scan['k'] = 1024;
  332. $scan['b'] = 1;
  333. foreach ($scan as $unit => $factor) {
  334. if (strlen($size) > strlen($unit)
  335. && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit
  336. ) {
  337. return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
  338. }
  339. }
  340. return $size;
  341. } // end function PMA_getRealSize()
  342. /**
  343. * merges array recursive like array_merge_recursive() but keyed-values are
  344. * always overwritten.
  345. *
  346. * array PMA_arrayMergeRecursive(array $array1[, array $array2[, array ...]])
  347. *
  348. * @return array merged array
  349. *
  350. * @see http://php.net/array_merge
  351. * @see http://php.net/array_merge_recursive
  352. */
  353. function PMA_arrayMergeRecursive()
  354. {
  355. switch(func_num_args()) {
  356. case 0 :
  357. return false;
  358. break;
  359. case 1 :
  360. // when does that happen?
  361. return func_get_arg(0);
  362. break;
  363. case 2 :
  364. $args = func_get_args();
  365. if (! is_array($args[0]) || ! is_array($args[1])) {
  366. return $args[1];
  367. }
  368. foreach ($args[1] as $key2 => $value2) {
  369. if (isset($args[0][$key2]) && !is_int($key2)) {
  370. $args[0][$key2] = PMA_arrayMergeRecursive(
  371. $args[0][$key2], $value2
  372. );
  373. } else {
  374. // we erase the parent array, otherwise we cannot override
  375. // a directive that contains array elements, like this:
  376. // (in config.default.php)
  377. // $cfg['ForeignKeyDropdownOrder']= array('id-content','content-id');
  378. // (in config.inc.php)
  379. // $cfg['ForeignKeyDropdownOrder']= array('content-id');
  380. if (is_int($key2) && $key2 == 0) {
  381. unset($args[0]);
  382. }
  383. $args[0][$key2] = $value2;
  384. }
  385. }
  386. return $args[0];
  387. break;
  388. default :
  389. $args = func_get_args();
  390. $args[1] = PMA_arrayMergeRecursive($args[0], $args[1]);
  391. array_shift($args);
  392. return call_user_func_array('PMA_arrayMergeRecursive', $args);
  393. break;
  394. }
  395. }
  396. /**
  397. * calls $function for every element in $array recursively
  398. *
  399. * this function is protected against deep recursion attack CVE-2006-1549,
  400. * 1000 seems to be more than enough
  401. *
  402. * @param array &$array array to walk
  403. * @param string $function function to call for every array element
  404. * @param bool $apply_to_keys_also whether to call the function for the keys also
  405. *
  406. * @return void
  407. *
  408. * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
  409. * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
  410. */
  411. function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
  412. {
  413. static $recursive_counter = 0;
  414. $walked_keys = array();
  415. if (++$recursive_counter > 1000) {
  416. PMA_fatalError(__('possible deep recursion attack'));
  417. }
  418. foreach ($array as $key => $value) {
  419. if (isset($walked_keys[$key])) {
  420. continue;
  421. }
  422. $walked_keys[$key] = true;
  423. if (is_array($value)) {
  424. PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
  425. } else {
  426. $array[$key] = $function($value);
  427. }
  428. if ($apply_to_keys_also && is_string($key)) {
  429. $new_key = $function($key);
  430. if ($new_key != $key) {
  431. $array[$new_key] = $array[$key];
  432. unset($array[$key]);
  433. $walked_keys[$new_key] = true;
  434. }
  435. }
  436. }
  437. $recursive_counter--;
  438. }
  439. /**
  440. * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
  441. *
  442. * checks given $page against given $whitelist and returns true if valid
  443. * it optionally ignores query parameters in $page (script.php?ignored)
  444. *
  445. * @param string &$page page to check
  446. * @param array $whitelist whitelist to check page against
  447. *
  448. * @return boolean whether $page is valid or not (in $whitelist or not)
  449. */
  450. function PMA_checkPageValidity(&$page, $whitelist)
  451. {
  452. if (! isset($page) || !is_string($page)) {
  453. return false;
  454. }
  455. if (in_array($page, $whitelist)) {
  456. return true;
  457. }
  458. if (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
  459. return true;
  460. }
  461. $_page = urldecode($page);
  462. if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
  463. return true;
  464. }
  465. return false;
  466. }
  467. /**
  468. * tries to find the value for the given environment variable name
  469. *
  470. * searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
  471. * in this order
  472. *
  473. * @param string $var_name variable name
  474. *
  475. * @return string value of $var or empty string
  476. */
  477. function PMA_getenv($var_name)
  478. {
  479. if (isset($_SERVER[$var_name])) {
  480. return $_SERVER[$var_name];
  481. }
  482. if (isset($_ENV[$var_name])) {
  483. return $_ENV[$var_name];
  484. }
  485. if (getenv($var_name)) {
  486. return getenv($var_name);
  487. }
  488. if (function_exists('apache_getenv')
  489. && apache_getenv($var_name, true)
  490. ) {
  491. return apache_getenv($var_name, true);
  492. }
  493. return '';
  494. }
  495. /**
  496. * Send HTTP header, taking IIS limits into account (600 seems ok)
  497. *
  498. * @param string $uri the header to send
  499. * @param bool $use_refresh whether to use Refresh: header when running on IIS
  500. *
  501. * @return boolean always true
  502. */
  503. function PMA_sendHeaderLocation($uri, $use_refresh = false)
  504. {
  505. if (PMA_IS_IIS && strlen($uri) > 600) {
  506. include_once './libraries/js_escape.lib.php';
  507. PMA_Response::getInstance()->disable();
  508. echo '<html><head><title>- - -</title>' . "\n";
  509. echo '<meta http-equiv="expires" content="0">' . "\n";
  510. echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
  511. echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
  512. echo '<meta http-equiv="Refresh" content="0;url='
  513. . htmlspecialchars($uri) . '">' . "\n";
  514. echo '<script type="text/javascript">' . "\n";
  515. echo '//<![CDATA[' . "\n";
  516. echo 'setTimeout("window.location = unescape(\'"'
  517. . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
  518. echo '//]]>' . "\n";
  519. echo '</script>' . "\n";
  520. echo '</head>' . "\n";
  521. echo '<body>' . "\n";
  522. echo '<script type="text/javascript">' . "\n";
  523. echo '//<![CDATA[' . "\n";
  524. echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">'
  525. . __('Go') . '</a></p>\');' . "\n";
  526. echo '//]]>' . "\n";
  527. echo '</script></body></html>' . "\n";
  528. return;
  529. }
  530. if (SID) {
  531. if (strpos($uri, '?') === false) {
  532. header('Location: ' . $uri . '?' . SID);
  533. } else {
  534. $separator = PMA_URL_getArgSeparator();
  535. header('Location: ' . $uri . $separator . SID);
  536. }
  537. return;
  538. }
  539. session_write_close();
  540. if (headers_sent()) {
  541. if (function_exists('debug_print_backtrace')) {
  542. echo '<pre>';
  543. debug_print_backtrace();
  544. echo '</pre>';
  545. }
  546. trigger_error(
  547. 'PMA_sendHeaderLocation called when headers are already sent!',
  548. E_USER_ERROR
  549. );
  550. }
  551. // bug #1523784: IE6 does not like 'Refresh: 0', it
  552. // results in a blank page
  553. // but we need it when coming from the cookie login panel)
  554. if (PMA_IS_IIS && $use_refresh) {
  555. header('Refresh: 0; ' . $uri);
  556. } else {
  557. header('Location: ' . $uri);
  558. }
  559. }
  560. /**
  561. * Outputs headers to prevent caching in browser (and on the way).
  562. *
  563. * @return void
  564. */
  565. function PMA_noCacheHeader()
  566. {
  567. if (defined('TESTSUITE')) {
  568. return;
  569. }
  570. // rfc2616 - Section 14.21
  571. header('Expires: ' . date(DATE_RFC1123));
  572. // HTTP/1.1
  573. header(
  574. 'Cache-Control: no-store, no-cache, must-revalidate,'
  575. . ' pre-check=0, post-check=0, max-age=0'
  576. );
  577. if (PMA_USR_BROWSER_AGENT == 'IE') {
  578. /* On SSL IE sometimes fails with:
  579. *
  580. * Internet Explorer was not able to open this Internet site. The
  581. * requested site is either unavailable or cannot be found. Please
  582. * try again later.
  583. *
  584. * Adding Pragma: public fixes this.
  585. */
  586. header('Pragma: public');
  587. return;
  588. }
  589. header('Pragma: no-cache'); // HTTP/1.0
  590. // test case: exporting a database into a .gz file with Safari
  591. // would produce files not having the current time
  592. // (added this header for Safari but should not harm other browsers)
  593. header('Last-Modified: ' . date(DATE_RFC1123));
  594. }
  595. /**
  596. * Sends header indicating file download.
  597. *
  598. * @param string $filename Filename to include in headers if empty,
  599. * none Content-Disposition header will be sent.
  600. * @param string $mimetype MIME type to include in headers.
  601. * @param int $length Length of content (optional)
  602. * @param bool $no_cache Whether to include no-caching headers.
  603. *
  604. * @return void
  605. */
  606. function PMA_downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
  607. {
  608. if ($no_cache) {
  609. PMA_noCacheHeader();
  610. }
  611. /* Replace all possibly dangerous chars in filename */
  612. $filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename);
  613. if (!empty($filename)) {
  614. header('Content-Description: File Transfer');
  615. header('Content-Disposition: attachment; filename="' . $filename . '"');
  616. }
  617. header('Content-Type: ' . $mimetype);
  618. // inform the server that compression has been done,
  619. // to avoid a double compression (for example with Apache + mod_deflate)
  620. if (strpos($mimetype, 'gzip') !== false) {
  621. header('Content-Encoding: gzip');
  622. }
  623. header('Content-Transfer-Encoding: binary');
  624. if ($length > 0) {
  625. header('Content-Length: ' . $length);
  626. }
  627. }
  628. /**
  629. * Checks whether element given by $path exists in $array.
  630. * $path is a string describing position of an element in an associative array,
  631. * eg. Servers/1/host refers to $array[Servers][1][host]
  632. *
  633. * @param string $path path in the arry
  634. * @param array $array the array
  635. *
  636. * @return mixed array element or $default
  637. */
  638. function PMA_arrayKeyExists($path, $array)
  639. {
  640. $keys = explode('/', $path);
  641. $value =& $array;
  642. foreach ($keys as $key) {
  643. if (! isset($value[$key])) {
  644. return false;
  645. }
  646. $value =& $value[$key];
  647. }
  648. return true;
  649. }
  650. /**
  651. * Returns value of an element in $array given by $path.
  652. * $path is a string describing position of an element in an associative array,
  653. * eg. Servers/1/host refers to $array[Servers][1][host]
  654. *
  655. * @param string $path path in the arry
  656. * @param array $array the array
  657. * @param mixed $default default value
  658. *
  659. * @return mixed array element or $default
  660. */
  661. function PMA_arrayRead($path, $array, $default = null)
  662. {
  663. $keys = explode('/', $path);
  664. $value =& $array;
  665. foreach ($keys as $key) {
  666. if (! isset($value[$key])) {
  667. return $default;
  668. }
  669. $value =& $value[$key];
  670. }
  671. return $value;
  672. }
  673. /**
  674. * Stores value in an array
  675. *
  676. * @param string $path path in the array
  677. * @param array &$array the array
  678. * @param mixed $value value to store
  679. *
  680. * @return void
  681. */
  682. function PMA_arrayWrite($path, &$array, $value)
  683. {
  684. $keys = explode('/', $path);
  685. $last_key = array_pop($keys);
  686. $a =& $array;
  687. foreach ($keys as $key) {
  688. if (! isset($a[$key])) {
  689. $a[$key] = array();
  690. }
  691. $a =& $a[$key];
  692. }
  693. $a[$last_key] = $value;
  694. }
  695. /**
  696. * Removes value from an array
  697. *
  698. * @param string $path path in the array
  699. * @param array &$array the array
  700. *
  701. * @return void
  702. */
  703. function PMA_arrayRemove($path, &$array)
  704. {
  705. $keys = explode('/', $path);
  706. $keys_last = array_pop($keys);
  707. $path = array();
  708. $depth = 0;
  709. $path[0] =& $array;
  710. $found = true;
  711. // go as deep as required or possible
  712. foreach ($keys as $key) {
  713. if (! isset($path[$depth][$key])) {
  714. $found = false;
  715. break;
  716. }
  717. $depth++;
  718. $path[$depth] =& $path[$depth-1][$key];
  719. }
  720. // if element found, remove it
  721. if ($found) {
  722. unset($path[$depth][$keys_last]);
  723. $depth--;
  724. }
  725. // remove empty nested arrays
  726. for (; $depth >= 0; $depth--) {
  727. if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
  728. unset($path[$depth][$keys[$depth]]);
  729. } else {
  730. break;
  731. }
  732. }
  733. }
  734. /**
  735. * Returns link to (possibly) external site using defined redirector.
  736. *
  737. * @param string $url URL where to go.
  738. *
  739. * @return string URL for a link.
  740. */
  741. function PMA_linkURL($url)
  742. {
  743. if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
  744. return $url;
  745. }
  746. if (!function_exists('PMA_URL_getCommon')) {
  747. include_once './libraries/url_generating.lib.php';
  748. }
  749. $params = array();
  750. $params['url'] = $url;
  751. $url = PMA_URL_getCommon($params);
  752. //strip off token and such sensitive information. Just keep url.
  753. $arr = parse_url($url);
  754. parse_str($arr["query"], $vars);
  755. $query = http_build_query(array("url" => $vars["url"]));
  756. $url = './url.php?' . $query;
  757. return $url;
  758. }
  759. /**
  760. * Checks whether domain of URL is whitelisted domain or not.
  761. * Use only for URLs of external sites.
  762. *
  763. * @param string $url URL of external site.
  764. *
  765. * @return boolean.True:if domain of $url is allowed domain, False:otherwise.
  766. */
  767. function PMA_isAllowedDomain($url)
  768. {
  769. $arr = parse_url($url);
  770. $domain = $arr["host"];
  771. $domainWhiteList = array(
  772. /* Include current domain */
  773. $_SERVER['SERVER_NAME'],
  774. /* phpMyAdmin domains */
  775. 'wiki.phpmyadmin.net', 'www.phpmyadmin.net', 'phpmyadmin.net',
  776. 'docs.phpmyadmin.net',
  777. /* mysql.com domains */
  778. 'dev.mysql.com','bugs.mysql.com',
  779. /* php.net domains */
  780. 'php.net',
  781. /* Github domains*/
  782. 'github.com','www.github.com',
  783. /* Following are doubtful ones. */
  784. 'www.primebase.com','pbxt.blogspot.com'
  785. );
  786. if (in_array(strtolower($domain), $domainWhiteList)) {
  787. return true;
  788. }
  789. return false;
  790. }
  791. /**
  792. * Adds JS code snippets to be displayed by the PMA_Response class.
  793. * Adds a newline to each snippet.
  794. *
  795. * @param string $str Js code to be added (e.g. "token=1234;")
  796. *
  797. * @return void
  798. */
  799. function PMA_addJSCode($str)
  800. {
  801. $response = PMA_Response::getInstance();
  802. $header = $response->getHeader();
  803. $scripts = $header->getScripts();
  804. $scripts->addCode($str);
  805. }
  806. /**
  807. * Adds JS code snippet for variable assignment
  808. * to be displayed by the PMA_Response class.
  809. *
  810. * @param string $key Name of value to set
  811. * @param mixed $value Value to set, can be either string or array of strings
  812. * @param bool $escape Whether to escape value or keep it as it is
  813. * (for inclusion of js code)
  814. *
  815. * @return void
  816. */
  817. function PMA_addJSVar($key, $value, $escape = true)
  818. {
  819. PMA_addJSCode(PMA_getJsValue($key, $value, $escape));
  820. }
  821. ?>