XSS with IE <= 8.x (semicolon and attachment headers
[phpmyadmin/alexukf.git] / libraries / core.lib.php
blob80c1f12046c8232406e0ef9282f31ad2714380e9
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Core functions used all over the scripts.
5 * This script is distinct from libraries/common.inc.php because this
6 * script is called from /test.
8 * @package phpMyAdmin
9 */
11 /**
12 * checks given $var and returns it if valid, or $default of not valid
13 * given $var is also checked for type being 'similar' as $default
14 * or against any other type if $type is provided
16 * <code>
17 * // $_REQUEST['db'] not set
18 * echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
19 * // $_REQUEST['sql_query'] not set
20 * echo PMA_ifSetOr($_REQUEST['sql_query']); // null
21 * // $cfg['ForceSSL'] not set
22 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
23 * echo PMA_ifSetOr($cfg['ForceSSL']); // null
24 * // $cfg['ForceSSL'] set to 1
25 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
26 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'similar'); // 1
27 * echo PMA_ifSetOr($cfg['ForceSSL'], false); // 1
28 * // $cfg['ForceSSL'] set to true
29 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // true
30 * </code>
32 * @uses PMA_isValid()
33 * @see PMA_isValid()
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 * @return mixed $var or $default
39 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
41 if (! PMA_isValid($var, $type, $default)) {
42 return $default;
45 return $var;
48 /**
49 * checks given $var against $type or $compare
51 * $type can be:
52 * - false : no type checking
53 * - 'scalar' : whether type of $var is integer, float, string or boolean
54 * - 'numeric' : whether type of $var is any number repesentation
55 * - 'length' : whether type of $var is scalar with a string length > 0
56 * - 'similar' : whether type of $var is similar to type of $compare
57 * - 'equal' : whether type of $var is identical to type of $compare
58 * - 'identical' : whether $var is identical to $compare, not only the type!
59 * - or any other valid PHP variable type
61 * <code>
62 * // $_REQUEST['doit'] = true;
63 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
64 * // $_REQUEST['doit'] = 'true';
65 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
66 * </code>
68 * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
69 * but the var is not altered inside this function, also after checking a var
70 * this var exists nut is not set, example:
71 * <code>
72 * // $var is not set
73 * isset($var); // false
74 * functionCallByReference($var); // false
75 * isset($var); // true
76 * functionCallByReference($var); // true
77 * </code>
79 * to avoid this we set this var to null if not isset
81 * @todo create some testsuites
82 * @todo add some more var types like hex, bin, ...?
83 * @uses is_scalar()
84 * @uses is_numeric()
85 * @uses is_array()
86 * @uses in_array()
87 * @uses gettype()
88 * @uses strtolower()
89 * @see http://php.net/gettype
90 * @param mixed $var variable to check
91 * @param mixed $type var type or array of valid values to check against $var
92 * @param mixed $compare var to compare with $var
93 * @return boolean whether valid or not
95 function PMA_isValid(&$var, $type = 'length', $compare = null)
97 if (! isset($var)) {
98 // var is not even set
99 return false;
102 if ($type === false) {
103 // no vartype requested
104 return true;
107 if (is_array($type)) {
108 return in_array($var, $type);
111 // allow some aliaes of var types
112 $type = strtolower($type);
113 switch ($type) {
114 case 'identic' :
115 $type = 'identical';
116 break;
117 case 'len' :
118 $type = 'length';
119 break;
120 case 'bool' :
121 $type = 'boolean';
122 break;
123 case 'float' :
124 $type = 'double';
125 break;
126 case 'int' :
127 $type = 'integer';
128 break;
129 case 'null' :
130 $type = 'NULL';
131 break;
134 if ($type === 'identical') {
135 return $var === $compare;
138 // whether we should check against given $compare
139 if ($type === 'similar') {
140 switch (gettype($compare)) {
141 case 'string':
142 case 'boolean':
143 $type = 'scalar';
144 break;
145 case 'integer':
146 case 'double':
147 $type = 'numeric';
148 break;
149 default:
150 $type = gettype($compare);
152 } elseif ($type === 'equal') {
153 $type = gettype($compare);
156 // do the check
157 if ($type === 'length' || $type === 'scalar') {
158 $is_scalar = is_scalar($var);
159 if ($is_scalar && $type === 'length') {
160 return (bool) strlen($var);
162 return $is_scalar;
165 if ($type === 'numeric') {
166 return is_numeric($var);
169 if (gettype($var) === $type) {
170 return true;
173 return false;
177 * Removes insecure parts in a path; used before include() or
178 * require() when a part of the path comes from an insecure source
179 * like a cookie or form.
181 * @param string The path to check
183 * @return string The secured path
185 * @access public
187 function PMA_securePath($path)
189 // change .. to .
190 $path = preg_replace('@\.\.*@', '.', $path);
192 return $path;
193 } // end function
196 * displays the given error message on phpMyAdmin error page in foreign language,
197 * ends script execution and closes session
199 * loads language file if not loaded already
201 * @todo use detected argument separator (PMA_Config)
202 * @uses $GLOBALS['session_name']
203 * @uses $GLOBALS['text_dir']
204 * @uses $GLOBALS['available_languages']
205 * @uses $GLOBALS['lang']
206 * @uses $GLOBALS['PMA_Config']->removeCookie()
207 * @uses select_lang.lib.php
208 * @uses $_COOKIE
209 * @uses substr()
210 * @uses header()
211 * @uses http_build_query()
212 * @uses is_string()
213 * @uses sprintf()
214 * @uses vsprintf()
215 * @uses strtr()
216 * @uses defined()
217 * @param string $error_message the error message or named error message
218 * @param string|array $message_args arguments applied to $error_message
219 * @return exit
221 function PMA_fatalError($error_message, $message_args = null)
223 /* Use format string if applicable */
224 if (is_string($message_args)) {
225 $error_message = sprintf($error_message, $message_args);
226 } elseif (is_array($message_args)) {
227 $error_message = vsprintf($error_message, $message_args);
229 $error_message = strtr($error_message, array('<br />' => '[br]'));
231 if (function_exists('__')) {
232 $error_header = __('Error');
233 } else {
234 $error_header = 'Error';
237 // Displays the error message
238 $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][1];
239 $dir = $GLOBALS['text_dir'];
240 $type = $error_header;
241 $error = $error_message;
243 // on fatal errors it cannot hurt to always delete the current session
244 if (isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
245 $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
248 require('./libraries/error.inc.php');
250 exit;
254 * Returns a link to the PHP documentation
256 * @param string anchor in documentation
258 * @return string the URL
260 * @access public
262 function PMA_getPHPDocLink($target) {
263 /* l10n: Language to use for PHP documentation, please use only languages which do exist in official documentation. */
264 $lang = _pgettext('PHP documentation language', 'en');
266 return 'http://php.net/manual/' . $lang . '/' . $target;
270 * Warn or fail on missing extension.
272 * @param string $extension Extension name
273 * @param bool $fatal Whether the error is fatal.
274 / @param string $extra Extra string to append to messsage.
276 function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
278 /* Gettext does not have to be loaded yet here */
279 if (function_exists('__')) {
280 $message = __('The %s extension is missing. Please check your PHP configuration.');
281 } else {
282 $message = 'The %s extension is missing. Please check your PHP configuration.';
284 $message = sprintf($message,
285 '[a@' . PMA_getPHPDocLink('book.' . $extension . '.php') . '@Documentation][em]' . $extension . '[/em][/a]');
286 if ($extra != '') {
287 $message .= ' ' . $extra;
289 if ($fatal) {
290 PMA_fatalError($message);
291 } else {
292 trigger_error($message, E_USER_WARNING);
297 * returns count of tables in given db
299 * @uses PMA_DBI_try_query()
300 * @uses PMA_backquote()
301 * @uses PMA_DBI_QUERY_STORE()
302 * @uses PMA_DBI_num_rows()
303 * @uses PMA_DBI_free_result()
304 * @param string $db database to count tables for
305 * @return integer count of tables in $db
307 function PMA_getTableCount($db)
309 $tables = PMA_DBI_try_query(
310 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
311 null, PMA_DBI_QUERY_STORE);
312 if ($tables) {
313 $num_tables = PMA_DBI_num_rows($tables);
315 // do not count hidden blobstreaming tables
316 while ((($num_tables > 0)) && $data = PMA_DBI_fetch_assoc($tables)) {
317 if (PMA_BS_IsHiddenTable($data['Tables_in_' . $db])) {
318 $num_tables--;
322 PMA_DBI_free_result($tables);
323 } else {
324 $num_tables = 0;
327 return $num_tables;
331 * Converts numbers like 10M into bytes
332 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
333 * (renamed with PMA prefix to avoid double definition when embedded
334 * in Moodle)
336 * @uses each()
337 * @uses strlen()
338 * @uses substr()
339 * @param string $size
340 * @return integer $size
342 function PMA_get_real_size($size = 0)
344 if (! $size) {
345 return 0;
348 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
349 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
350 $scan['mb'] = 1048576;
351 $scan['m'] = 1048576;
352 $scan['kb'] = 1024;
353 $scan['k'] = 1024;
354 $scan['b'] = 1;
356 foreach ($scan as $unit => $factor) {
357 if (strlen($size) > strlen($unit)
358 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit) {
359 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
363 return $size;
364 } // end function PMA_get_real_size()
367 * merges array recursive like array_merge_recursive() but keyed-values are
368 * always overwritten.
370 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
372 * @see http://php.net/array_merge
373 * @see http://php.net/array_merge_recursive
374 * @uses func_num_args()
375 * @uses func_get_arg()
376 * @uses is_array()
377 * @uses call_user_func_array()
378 * @param array array to merge
379 * @param array array to merge
380 * @param array ...
381 * @return array merged array
383 function PMA_array_merge_recursive()
385 switch(func_num_args()) {
386 case 0 :
387 return false;
388 break;
389 case 1 :
390 // when does that happen?
391 return func_get_arg(0);
392 break;
393 case 2 :
394 $args = func_get_args();
395 if (!is_array($args[0]) || !is_array($args[1])) {
396 return $args[1];
398 foreach ($args[1] as $key2 => $value2) {
399 if (isset($args[0][$key2]) && !is_int($key2)) {
400 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
401 $value2);
402 } else {
403 // we erase the parent array, otherwise we cannot override a directive that
404 // contains array elements, like this:
405 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
406 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
407 if (is_int($key2) && $key2 == 0) {
408 unset($args[0]);
410 $args[0][$key2] = $value2;
413 return $args[0];
414 break;
415 default :
416 $args = func_get_args();
417 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
418 array_shift($args);
419 return call_user_func_array('PMA_array_merge_recursive', $args);
420 break;
425 * calls $function vor every element in $array recursively
427 * this function is protected against deep recursion attack CVE-2006-1549,
428 * 1000 seems to be more than enough
430 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
431 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
433 * @uses PMA_arrayWalkRecursive()
434 * @uses is_array()
435 * @uses is_string()
436 * @param array $array array to walk
437 * @param string $function function to call for every array element
439 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
441 static $recursive_counter = 0;
442 if (++$recursive_counter > 1000) {
443 die('possible deep recursion attack');
445 foreach ($array as $key => $value) {
446 if (is_array($value)) {
447 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
448 } else {
449 $array[$key] = $function($value);
452 if ($apply_to_keys_also && is_string($key)) {
453 $new_key = $function($key);
454 if ($new_key != $key) {
455 $array[$new_key] = $array[$key];
456 unset($array[$key]);
460 $recursive_counter--;
464 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
466 * checks given given $page against given $whitelist and returns true if valid
467 * it ignores optionaly query paramters in $page (script.php?ignored)
469 * @uses in_array()
470 * @uses urldecode()
471 * @uses substr()
472 * @uses strpos()
473 * @param string &$page page to check
474 * @param array $whitelist whitelist to check page against
475 * @return boolean whether $page is valid or not (in $whitelist or not)
477 function PMA_checkPageValidity(&$page, $whitelist)
479 if (! isset($page) || !is_string($page)) {
480 return false;
483 if (in_array($page, $whitelist)) {
484 return true;
485 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
486 return true;
487 } else {
488 $_page = urldecode($page);
489 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
490 return true;
493 return false;
497 * trys to find the value for the given environment vriable name
499 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
500 * in this order
502 * @uses $_SERVER
503 * @uses $_ENV
504 * @uses getenv()
505 * @uses function_exists()
506 * @uses apache_getenv()
507 * @param string $var_name variable name
508 * @return string value of $var or empty string
510 function PMA_getenv($var_name) {
511 if (isset($_SERVER[$var_name])) {
512 return $_SERVER[$var_name];
513 } elseif (isset($_ENV[$var_name])) {
514 return $_ENV[$var_name];
515 } elseif (getenv($var_name)) {
516 return getenv($var_name);
517 } elseif (function_exists('apache_getenv')
518 && apache_getenv($var_name, true)) {
519 return apache_getenv($var_name, true);
522 return '';
526 * Send HTTP header, taking IIS limits into account (600 seems ok)
528 * @uses PMA_IS_IIS
529 * @uses PMA_COMING_FROM_COOKIE_LOGIN
530 * @uses PMA_get_arg_separator()
531 * @uses SID
532 * @uses strlen()
533 * @uses strpos()
534 * @uses header()
535 * @uses session_write_close()
536 * @uses headers_sent()
537 * @uses function_exists()
538 * @uses debug_print_backtrace()
539 * @uses trigger_error()
540 * @uses defined()
541 * @param string $uri the header to send
542 * @return boolean always true
544 function PMA_sendHeaderLocation($uri)
546 if (PMA_IS_IIS && strlen($uri) > 600) {
547 require_once './libraries/js_escape.lib.php';
549 echo '<html><head><title>- - -</title>' . "\n";
550 echo '<meta http-equiv="expires" content="0">' . "\n";
551 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
552 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
553 echo '<meta http-equiv="Refresh" content="0;url=' . htmlspecialchars($uri) . '">' . "\n";
554 echo '<script type="text/javascript">' . "\n";
555 echo '//<![CDATA[' . "\n";
556 echo 'setTimeout("window.location = unescape(\'"' . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
557 echo '//]]>' . "\n";
558 echo '</script>' . "\n";
559 echo '</head>' . "\n";
560 echo '<body>' . "\n";
561 echo '<script type="text/javascript">' . "\n";
562 echo '//<![CDATA[' . "\n";
563 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">' . __('Go') . '</a></p>\');' . "\n";
564 echo '//]]>' . "\n";
565 echo '</script></body></html>' . "\n";
567 } else {
568 if (SID) {
569 if (strpos($uri, '?') === false) {
570 header('Location: ' . $uri . '?' . SID);
571 } else {
572 $separator = PMA_get_arg_separator();
573 header('Location: ' . $uri . $separator . SID);
575 } else {
576 session_write_close();
577 if (headers_sent()) {
578 if (function_exists('debug_print_backtrace')) {
579 echo '<pre>';
580 debug_print_backtrace();
581 echo '</pre>';
583 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
585 // bug #1523784: IE6 does not like 'Refresh: 0', it
586 // results in a blank page
587 // but we need it when coming from the cookie login panel)
588 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
589 header('Refresh: 0; ' . $uri);
590 } else {
591 header('Location: ' . $uri);
598 * Returns value of an element in $array given by $path.
599 * $path is a string describing position of an element in an associative array,
600 * eg. Servers/1/host refers to $array[Servers][1][host]
602 * @param string $path
603 * @param array $array
604 * @param mixed $default
605 * @return mixed array element or $default
607 function PMA_array_read($path, $array, $default = null)
609 $keys = explode('/', $path);
610 $value =& $array;
611 foreach ($keys as $key) {
612 if (!isset($value[$key])) {
613 return $default;
615 $value =& $value[$key];
617 return $value;
621 * Stores value in an array
623 * @param string $path
624 * @param array &$array
625 * @param mixed $value
627 function PMA_array_write($path, &$array, $value)
629 $keys = explode('/', $path);
630 $last_key = array_pop($keys);
631 $a =& $array;
632 foreach ($keys as $key) {
633 if (!isset($a[$key])) {
634 $a[$key] = array();
636 $a =& $a[$key];
638 $a[$last_key] = $value;
642 * Removes value from an array
644 * @param string $path
645 * @param array &$array
646 * @param mixed $value
648 function PMA_array_remove($path, &$array)
650 $keys = explode('/', $path);
651 $keys_last = array_pop($keys);
652 $path = array();
653 $depth = 0;
655 $path[0] =& $array;
656 $found = true;
657 // go as deep as required or possible
658 foreach ($keys as $key) {
659 if (!isset($path[$depth][$key])) {
660 $found = false;
661 break;
663 $depth++;
664 $path[$depth] =& $path[$depth-1][$key];
666 // if element found, remove it
667 if ($found) {
668 unset($path[$depth][$keys_last]);
669 $depth--;
672 // remove empty nested arrays
673 for (; $depth >= 0; $depth--) {
674 if (!isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
675 unset($path[$depth][$keys[$depth]]);
676 } else {
677 break;
683 * Returns link to (possibly) external site using defined redirector.
685 * @param string $url URL where to go.
687 * @return string URL for a link.
689 function PMA_linkURL($url) {
690 if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
691 return $url;
692 } else {
693 $params = array();
694 $params['url'] = $url;
695 return './url.php' . PMA_generate_common_url($params);
700 * Returns HTML code to include javascript file.
702 * @param string $url Location of javascript, relative to js/ folder.
704 * @return string HTML code for javascript inclusion.
706 function PMA_includeJS($url) {
707 if (strpos($url, '?') === FALSE) {
708 return '<script src="./js/' . $url . '?ts=' . filemtime('./js/' . $url) . '" type="text/javascript"></script>' . "\n";
709 } else {
710 return '<script src="./js/' . $url . '" type="text/javascript"></script>' . "\n";