3.3.10-rc1
[phpmyadmin/crack.git] / libraries / core.lib.php
blobfa4f007199988d1f69b11a76829fa011bbe6d00b
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 * @version $Id$
9 * @package phpMyAdmin
12 /**
13 * checks given $var and returns it if valid, or $default of not valid
14 * given $var is also checked for type being 'similar' as $default
15 * or against any other type if $type is provided
17 * <code>
18 * // $_REQUEST['db'] not set
19 * echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
20 * // $_REQUEST['sql_query'] not set
21 * echo PMA_ifSetOr($_REQUEST['sql_query']); // null
22 * // $cfg['ForceSSL'] not set
23 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
24 * echo PMA_ifSetOr($cfg['ForceSSL']); // null
25 * // $cfg['ForceSSL'] set to 1
26 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // false
27 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'similar'); // 1
28 * echo PMA_ifSetOr($cfg['ForceSSL'], false); // 1
29 * // $cfg['ForceSSL'] set to true
30 * echo PMA_ifSetOr($cfg['ForceSSL'], false, 'boolean'); // true
31 * </code>
33 * @uses PMA_isValid()
34 * @see PMA_isValid()
35 * @param mixed $var param to check
36 * @param mixed $default default value
37 * @param mixed $type var type or array of values to check against $var
38 * @return mixed $var or $default
40 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
42 if (! PMA_isValid($var, $type, $default)) {
43 return $default;
46 return $var;
49 /**
50 * checks given $var against $type or $compare
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
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>
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>
80 * to avoid this we set this var to null if not isset
82 * @todo create some testsuites
83 * @todo add some more var types like hex, bin, ...?
84 * @uses is_scalar()
85 * @uses is_numeric()
86 * @uses is_array()
87 * @uses in_array()
88 * @uses gettype()
89 * @uses strtolower()
90 * @see http://php.net/gettype
91 * @param mixed $var variable to check
92 * @param mixed $type var type or array of valid values to check against $var
93 * @param mixed $compare var to compare with $var
94 * @return boolean whether valid or not
96 function PMA_isValid(&$var, $type = 'length', $compare = null)
98 if (! isset($var)) {
99 // var is not even set
100 return false;
103 if ($type === false) {
104 // no vartype requested
105 return true;
108 if (is_array($type)) {
109 return in_array($var, $type);
112 // allow some aliaes of var types
113 $type = strtolower($type);
114 switch ($type) {
115 case 'identic' :
116 $type = 'identical';
117 break;
118 case 'len' :
119 $type = 'length';
120 break;
121 case 'bool' :
122 $type = 'boolean';
123 break;
124 case 'float' :
125 $type = 'double';
126 break;
127 case 'int' :
128 $type = 'integer';
129 break;
130 case 'null' :
131 $type = 'NULL';
132 break;
135 if ($type === 'identical') {
136 return $var === $compare;
139 // whether we should check against given $compare
140 if ($type === 'similar') {
141 switch (gettype($compare)) {
142 case 'string':
143 case 'boolean':
144 $type = 'scalar';
145 break;
146 case 'integer':
147 case 'double':
148 $type = 'numeric';
149 break;
150 default:
151 $type = gettype($compare);
153 } elseif ($type === 'equal') {
154 $type = gettype($compare);
157 // do the check
158 if ($type === 'length' || $type === 'scalar') {
159 $is_scalar = is_scalar($var);
160 if ($is_scalar && $type === 'length') {
161 return (bool) strlen($var);
163 return $is_scalar;
166 if ($type === 'numeric') {
167 return is_numeric($var);
170 if (gettype($var) === $type) {
171 return true;
174 return false;
178 * Removes insecure parts in a path; used before include() or
179 * require() when a part of the path comes from an insecure source
180 * like a cookie or form.
182 * @param string The path to check
184 * @return string The secured path
186 * @access public
187 * @author Marc Delisle (lem9@users.sourceforge.net)
189 function PMA_securePath($path)
191 // change .. to .
192 $path = preg_replace('@\.\.*@', '.', $path);
194 return $path;
195 } // end function
198 * displays the given error message on phpMyAdmin error page in foreign language,
199 * ends script execution and closes session
201 * loads language file if not loaded already
203 * @todo use detected argument separator (PMA_Config)
204 * @uses $GLOBALS['session_name']
205 * @uses $GLOBALS['text_dir']
206 * @uses $GLOBALS['strError']
207 * @uses $GLOBALS['available_languages']
208 * @uses $GLOBALS['lang']
209 * @uses PMA_removeCookie()
210 * @uses select_lang.lib.php
211 * @uses $_COOKIE
212 * @uses substr()
213 * @uses header()
214 * @uses http_build_query()
215 * @uses is_string()
216 * @uses sprintf()
217 * @uses vsprintf()
218 * @uses strtr()
219 * @uses defined()
220 * @param string $error_message the error message or named error message
221 * @param string|array $message_args arguments applied to $error_message
222 * @return exit
224 function PMA_fatalError($error_message, $message_args = null)
226 // it could happen PMA_fatalError() is called before language file is loaded
227 if (! isset($GLOBALS['available_languages'])) {
228 $GLOBALS['cfg'] = array(
229 'DefaultLang' => 'en-utf-8',
230 'AllowAnywhereRecoding' => false);
232 // Loads the language file
233 require_once './libraries/select_lang.lib.php';
235 if (isset($strError)) {
236 $GLOBALS['strError'] = $strError;
237 } else {
238 $GLOBALS['strError'] = 'Error';
241 // $text_dir is set in lang/language-utf-8.inc.php
242 if (isset($text_dir)) {
243 $GLOBALS['text_dir'] = $text_dir;
247 // $error_message could be a language string identifier: strString
248 if (substr($error_message, 0, 3) === 'str') {
249 if (isset($$error_message)) {
250 $error_message = $$error_message;
251 } elseif (isset($GLOBALS[$error_message])) {
252 $error_message = $GLOBALS[$error_message];
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);
261 $error_message = strtr($error_message, array('<br />' => '[br]'));
263 // Displays the error message
264 $lang = $GLOBALS['available_languages'][$GLOBALS['lang']][2];
265 $dir = $GLOBALS['text_dir'];
266 $type = $GLOBALS['strError'];
267 $error = $error_message;
269 // on fatal errors it cannot hurt to always delete the current session
270 if (isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
271 PMA_removeCookie($GLOBALS['session_name']);
274 require('./libraries/error.inc.php');
276 exit;
280 * returns count of tables in given db
282 * @uses PMA_DBI_try_query()
283 * @uses PMA_backquote()
284 * @uses PMA_DBI_QUERY_STORE()
285 * @uses PMA_DBI_num_rows()
286 * @uses PMA_DBI_free_result()
287 * @param string $db database to count tables for
288 * @return integer count of tables in $db
290 function PMA_getTableCount($db)
292 $tables = PMA_DBI_try_query(
293 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
294 null, PMA_DBI_QUERY_STORE);
295 if ($tables) {
296 $num_tables = PMA_DBI_num_rows($tables);
298 // for blobstreaming - get blobstreaming tables
299 // for use in determining if a table here is a blobstreaming table - rajk
301 // load PMA configuration
302 $PMA_Config = $_SESSION['PMA_Config'];
304 // if PMA configuration exists
305 if (!empty($PMA_Config))
307 // load BS tables
308 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
310 // if BS tables exist
311 if (isset ($session_bs_tables))
312 while ($data = PMA_DBI_fetch_assoc($tables))
313 foreach ($session_bs_tables as $table_key=>$table_val)
314 // if the table is a blobstreaming table, reduce the table count
315 if ($data['Tables_in_' . $db] == $table_key)
317 if ($num_tables > 0)
318 $num_tables--;
320 break;
322 } // end if PMA configuration exists
324 PMA_DBI_free_result($tables);
325 } else {
326 $num_tables = 0;
329 return $num_tables;
333 * Converts numbers like 10M into bytes
334 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
335 * (renamed with PMA prefix to avoid double definition when embedded
336 * in Moodle)
338 * @uses each()
339 * @uses strlen()
340 * @uses substr()
341 * @param string $size
342 * @return integer $size
344 function PMA_get_real_size($size = 0)
346 if (! $size) {
347 return 0;
350 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
351 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
352 $scan['mb'] = 1048576;
353 $scan['m'] = 1048576;
354 $scan['kb'] = 1024;
355 $scan['k'] = 1024;
356 $scan['b'] = 1;
358 foreach ($scan as $unit => $factor) {
359 if (strlen($size) > strlen($unit)
360 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit) {
361 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
365 return $size;
366 } // end function PMA_get_real_size()
369 * merges array recursive like array_merge_recursive() but keyed-values are
370 * always overwritten.
372 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
374 * @see http://php.net/array_merge
375 * @see http://php.net/array_merge_recursive
376 * @uses func_num_args()
377 * @uses func_get_arg()
378 * @uses is_array()
379 * @uses call_user_func_array()
380 * @param array array to merge
381 * @param array array to merge
382 * @param array ...
383 * @return array merged array
385 function PMA_array_merge_recursive()
387 switch(func_num_args()) {
388 case 0 :
389 return false;
390 break;
391 case 1 :
392 // when does that happen?
393 return func_get_arg(0);
394 break;
395 case 2 :
396 $args = func_get_args();
397 if (!is_array($args[0]) || !is_array($args[1])) {
398 return $args[1];
400 foreach ($args[1] as $key2 => $value2) {
401 if (isset($args[0][$key2]) && !is_int($key2)) {
402 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
403 $value2);
404 } else {
405 // we erase the parent array, otherwise we cannot override a directive that
406 // contains array elements, like this:
407 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
408 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
409 if (is_int($key2) && $key2 == 0) {
410 unset($args[0]);
412 $args[0][$key2] = $value2;
415 return $args[0];
416 break;
417 default :
418 $args = func_get_args();
419 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
420 array_shift($args);
421 return call_user_func_array('PMA_array_merge_recursive', $args);
422 break;
427 * calls $function vor every element in $array recursively
429 * this function is protected against deep recursion attack CVE-2006-1549,
430 * 1000 seems to be more than enough
432 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
433 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
435 * @uses PMA_arrayWalkRecursive()
436 * @uses is_array()
437 * @uses is_string()
438 * @param array $array array to walk
439 * @param string $function function to call for every array element
441 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
443 static $recursive_counter = 0;
444 if (++$recursive_counter > 1000) {
445 die('possible deep recursion attack');
447 foreach ($array as $key => $value) {
448 if (is_array($value)) {
449 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
450 } else {
451 $array[$key] = $function($value);
454 if ($apply_to_keys_also && is_string($key)) {
455 $new_key = $function($key);
456 if ($new_key != $key) {
457 $array[$new_key] = $array[$key];
458 unset($array[$key]);
462 $recursive_counter--;
466 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
468 * checks given given $page against given $whitelist and returns true if valid
469 * it ignores optionaly query paramters in $page (script.php?ignored)
471 * @uses in_array()
472 * @uses urldecode()
473 * @uses substr()
474 * @uses strpos()
475 * @param string &$page page to check
476 * @param array $whitelist whitelist to check page against
477 * @return boolean whether $page is valid or not (in $whitelist or not)
479 function PMA_checkPageValidity(&$page, $whitelist)
481 if (! isset($page) || !is_string($page)) {
482 return false;
485 if (in_array($page, $whitelist)) {
486 return true;
487 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
488 return true;
489 } else {
490 $_page = urldecode($page);
491 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
492 return true;
495 return false;
499 * trys to find the value for the given environment vriable name
501 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
502 * in this order
504 * @uses $_SERVER
505 * @uses $_ENV
506 * @uses getenv()
507 * @uses function_exists()
508 * @uses apache_getenv()
509 * @param string $var_name variable name
510 * @return string value of $var or empty string
512 function PMA_getenv($var_name) {
513 if (isset($_SERVER[$var_name])) {
514 return $_SERVER[$var_name];
515 } elseif (isset($_ENV[$var_name])) {
516 return $_ENV[$var_name];
517 } elseif (getenv($var_name)) {
518 return getenv($var_name);
519 } elseif (function_exists('apache_getenv')
520 && apache_getenv($var_name, true)) {
521 return apache_getenv($var_name, true);
524 return '';
528 * removes cookie
530 * @uses PMA_Config::isHttps()
531 * @uses PMA_Config::getCookiePath()
532 * @uses setcookie()
533 * @uses time()
534 * @param string $cookie name of cookie to remove
535 * @return boolean result of setcookie()
537 function PMA_removeCookie($cookie)
539 return setcookie($cookie, '', time() - 3600,
540 PMA_Config::getCookiePath(), '', PMA_Config::isHttps());
544 * sets cookie if value is different from current cokkie value,
545 * or removes if value is equal to default
547 * @uses PMA_Config::isHttps()
548 * @uses PMA_Config::getCookiePath()
549 * @uses $_COOKIE
550 * @uses PMA_removeCookie()
551 * @uses setcookie()
552 * @uses time()
553 * @param string $cookie name of cookie to remove
554 * @param mixed $value new cookie value
555 * @param string $default default value
556 * @param int $validity validity of cookie in seconds (default is one month)
557 * @param bool $httponlt whether cookie is only for HTTP (and not for scripts)
558 * @return boolean result of setcookie()
560 function PMA_setCookie($cookie, $value, $default = null, $validity = null, $httponly = true)
562 if ($validity == null) {
563 $validity = 2592000;
565 if (strlen($value) && null !== $default && $value === $default
566 && isset($_COOKIE[$cookie])) {
567 // remove cookie, default value is used
568 return PMA_removeCookie($cookie);
571 if (! strlen($value) && isset($_COOKIE[$cookie])) {
572 // remove cookie, value is empty
573 return PMA_removeCookie($cookie);
576 if (! isset($_COOKIE[$cookie]) || $_COOKIE[$cookie] !== $value) {
577 // set cookie with new value
578 /* Calculate cookie validity */
579 if ($validity == 0) {
580 $v = 0;
581 } else {
582 $v = time() + $validity;
584 return setcookie($cookie, $value, $v,
585 PMA_Config::getCookiePath(), '', PMA_Config::isHttps(), $httponly);
588 // cookie has already $value as value
589 return true;
593 * Send HTTP header, taking IIS limits into account (600 seems ok)
595 * @uses PMA_IS_IIS
596 * @uses PMA_COMING_FROM_COOKIE_LOGIN
597 * @uses PMA_get_arg_separator()
598 * @uses SID
599 * @uses strlen()
600 * @uses strpos()
601 * @uses header()
602 * @uses session_write_close()
603 * @uses headers_sent()
604 * @uses function_exists()
605 * @uses debug_print_backtrace()
606 * @uses trigger_error()
607 * @uses defined()
608 * @param string $uri the header to send
609 * @return boolean always true
611 function PMA_sendHeaderLocation($uri)
613 if (PMA_IS_IIS && strlen($uri) > 600) {
614 require_once './libraries/js_escape.lib.php';
616 echo '<html><head><title>- - -</title>' . "\n";
617 echo '<meta http-equiv="expires" content="0">' . "\n";
618 echo '<meta http-equiv="Pragma" content="no-cache">' . "\n";
619 echo '<meta http-equiv="Cache-Control" content="no-cache">' . "\n";
620 echo '<meta http-equiv="Refresh" content="0;url=' . htmlspecialchars($uri) . '">' . "\n";
621 echo '<script type="text/javascript">' . "\n";
622 echo '//<![CDATA[' . "\n";
623 echo 'setTimeout("window.location = unescape(\'"' . PMA_escapeJsString($uri) . '"\')", 2000);' . "\n";
624 echo '//]]>' . "\n";
625 echo '</script>' . "\n";
626 echo '</head>' . "\n";
627 echo '<body>' . "\n";
628 echo '<script type="text/javascript">' . "\n";
629 echo '//<![CDATA[' . "\n";
630 echo 'document.write(\'<p><a href="' . htmlspecialchars($uri) . '">' . $GLOBALS['strGo'] . '</a></p>\');' . "\n";
631 echo '//]]>' . "\n";
632 echo '</script></body></html>' . "\n";
634 } else {
635 if (SID) {
636 if (strpos($uri, '?') === false) {
637 header('Location: ' . $uri . '?' . SID);
638 } else {
639 $separator = PMA_get_arg_separator();
640 header('Location: ' . $uri . $separator . SID);
642 } else {
643 session_write_close();
644 if (headers_sent()) {
645 if (function_exists('debug_print_backtrace')) {
646 echo '<pre>';
647 debug_print_backtrace();
648 echo '</pre>';
650 trigger_error('PMA_sendHeaderLocation called when headers are already sent!', E_USER_ERROR);
652 // bug #1523784: IE6 does not like 'Refresh: 0', it
653 // results in a blank page
654 // but we need it when coming from the cookie login panel)
655 if (PMA_IS_IIS && defined('PMA_COMING_FROM_COOKIE_LOGIN')) {
656 header('Refresh: 0; ' . $uri);
657 } else {
658 header('Location: ' . $uri);