Chinese-simplified update
[phpmyadmin/crack.git] / libraries / core.lib.php
blob6e764dd2456c2f8d678abbc2f1f45cf6f303b125
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 * @todo create some testsuites
34 * @uses PMA_isValid()
35 * @see PMA_isValid()
36 * @param mixed $var param to check
37 * @param mixed $default default value
38 * @param mixed $type var type or array of values to check against $var
39 * @return mixed $var or $default
41 function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
43 if (! PMA_isValid($var, $type, $default)) {
44 return $default;
47 return $var;
50 /**
51 * checks given $var against $type or $compare
53 * $type can be:
54 * - false : no type checking
55 * - 'scalar' : whether type of $var is integer, float, string or boolean
56 * - 'numeric' : whether type of $var is any number repesentation
57 * - 'length' : whether type of $var is scalar with a string length > 0
58 * - 'similar' : whether type of $var is similar to type of $compare
59 * - 'equal' : whether type of $var is identical to type of $compare
60 * - 'identical' : whether $var is identical to $compare, not only the type!
61 * - or any other valid PHP variable type
63 * <code>
64 * // $_REQUEST['doit'] = true;
65 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
66 * // $_REQUEST['doit'] = 'true';
67 * PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
68 * </code>
70 * NOTE: call-by-reference is used to not get NOTICE on undefined vars,
71 * but the var is not altered inside this function, also after checking a var
72 * this var exists nut is not set, example:
73 * <code>
74 * // $var is not set
75 * isset($var); // false
76 * functionCallByReference($var); // false
77 * isset($var); // true
78 * functionCallByReference($var); // true
79 * </code>
81 * to avoid this we set this var to null if not isset
83 * @todo create some testsuites
84 * @todo add some more var types like hex, bin, ...?
85 * @uses is_scalar()
86 * @uses is_numeric()
87 * @uses is_array()
88 * @uses in_array()
89 * @uses gettype()
90 * @uses strtolower()
91 * @see http://php.net/gettype
92 * @param mixed $var variable to check
93 * @param mixed $type var type or array of valid values to check against $var
94 * @param mixed $compare var to compare with $var
95 * @return boolean whether valid or not
97 function PMA_isValid(&$var, $type = 'length', $compare = null)
99 if (! isset($var)) {
100 // var is not even set
101 return false;
104 if ($type === false) {
105 // no vartype requested
106 return true;
109 if (is_array($type)) {
110 return in_array($var, $type);
113 // allow some aliaes of var types
114 $type = strtolower($type);
115 switch ($type) {
116 case 'identic' :
117 $type = 'identical';
118 break;
119 case 'len' :
120 $type = 'length';
121 break;
122 case 'bool' :
123 $type = 'boolean';
124 break;
125 case 'float' :
126 $type = 'double';
127 break;
128 case 'int' :
129 $type = 'integer';
130 break;
131 case 'null' :
132 $type = 'NULL';
133 break;
136 if ($type === 'identical') {
137 return $var === $compare;
140 // whether we should check against given $compare
141 if ($type === 'similar') {
142 switch (gettype($compare)) {
143 case 'string':
144 case 'boolean':
145 $type = 'scalar';
146 break;
147 case 'integer':
148 case 'double':
149 $type = 'numeric';
150 break;
151 default:
152 $type = gettype($compare);
154 } elseif ($type === 'equal') {
155 $type = gettype($compare);
158 // do the check
159 if ($type === 'length' || $type === 'scalar') {
160 $is_scalar = is_scalar($var);
161 if ($is_scalar && $type === 'length') {
162 return (bool) strlen($var);
164 return $is_scalar;
167 if ($type === 'numeric') {
168 return is_numeric($var);
171 if (gettype($var) === $type) {
172 return true;
175 return false;
179 * Removes insecure parts in a path; used before include() or
180 * require() when a part of the path comes from an insecure source
181 * like a cookie or form.
183 * @param string The path to check
185 * @return string The secured path
187 * @access public
188 * @author Marc Delisle (lem9@users.sourceforge.net)
190 function PMA_securePath($path)
192 // change .. to .
193 $path = preg_replace('@\.\.*@', '.', $path);
195 return $path;
196 } // end function
199 * displays the given error message on phpMyAdmin error page in foreign language,
200 * ends script execution and closes session
202 * loads language file if not loaded already
204 * @todo use detected argument separator (PMA_Config)
205 * @uses $GLOBALS['session_name']
206 * @uses $GLOBALS['text_dir']
207 * @uses $GLOBALS['strError']
208 * @uses $GLOBALS['available_languages']
209 * @uses $GLOBALS['lang']
210 * @uses PMA_removeCookie()
211 * @uses select_lang.lib.php
212 * @uses $_COOKIE
213 * @uses substr()
214 * @uses header()
215 * @uses http_build_query()
216 * @uses is_string()
217 * @uses sprintf()
218 * @uses vsprintf()
219 * @uses strtr()
220 * @uses defined()
221 * @param string $error_message the error message or named error message
222 * @param string|array $message_args arguments applied to $error_message
223 * @return exit
225 function PMA_fatalError($error_message, $message_args = null)
227 // it could happen PMA_fatalError() is called before language file is loaded
228 if (! isset($GLOBALS['available_languages'])) {
229 $GLOBALS['cfg'] = array(
230 'DefaultLang' => 'en-utf-8',
231 'AllowAnywhereRecoding' => false);
233 // Loads the language file
234 require_once './libraries/select_lang.lib.php';
236 if (isset($strError)) {
237 $GLOBALS['strError'] = $strError;
238 } else {
239 $GLOBALS['strError'] = 'Error';
242 // $text_dir is set in lang/language-utf-8.inc.php
243 if (isset($text_dir)) {
244 $GLOBALS['text_dir'] = $text_dir;
248 // $error_message could be a language string identifier: strString
249 if (substr($error_message, 0, 3) === 'str') {
250 if (isset($$error_message)) {
251 $error_message = $$error_message;
252 } elseif (isset($GLOBALS[$error_message])) {
253 $error_message = $GLOBALS[$error_message];
257 if (is_string($message_args)) {
258 $error_message = sprintf($error_message, $message_args);
259 } elseif (is_array($message_args)) {
260 $error_message = vsprintf($error_message, $message_args);
262 $error_message = strtr($error_message, array('<br />' => '[br]'));
264 // Displays the error message
265 // (do not use &amp; for parameters sent by header)
266 $query_params = array(
267 'lang' => $GLOBALS['available_languages'][$GLOBALS['lang']][2],
268 'dir' => $GLOBALS['text_dir'],
269 'type' => $GLOBALS['strError'],
270 'error' => $error_message,
272 header('Location: ' . (defined('PMA_SETUP') ? '../' : '') . 'error.php?'
273 . http_build_query($query_params, null, '&'));
275 // on fatal errors it cannot hurt to always delete the current session
276 if (isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
277 PMA_removeCookie($GLOBALS['session_name']);
280 exit;
284 * returns count of tables in given db
286 * @uses PMA_DBI_try_query()
287 * @uses PMA_backquote()
288 * @uses PMA_DBI_QUERY_STORE()
289 * @uses PMA_DBI_num_rows()
290 * @uses PMA_DBI_free_result()
291 * @param string $db database to count tables for
292 * @return integer count of tables in $db
294 function PMA_getTableCount($db)
296 $tables = PMA_DBI_try_query(
297 'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
298 null, PMA_DBI_QUERY_STORE);
299 if ($tables) {
300 $num_tables = PMA_DBI_num_rows($tables);
302 // for blobstreaming - get blobstreaming tables
303 // for use in determining if a table here is a blobstreaming table - rajk
305 // load PMA configuration
306 $PMA_Config = $_SESSION['PMA_Config'];
308 // if PMA configuration exists
309 if (!empty($PMA_Config))
311 // load BS tables
312 $session_bs_tables = $_SESSION['PMA_Config']->get('BLOBSTREAMING_TABLES');
314 // if BS tables exist
315 if (isset ($session_bs_tables))
316 while ($data = PMA_DBI_fetch_assoc($tables))
317 foreach ($session_bs_tables as $table_key=>$table_val)
318 // if the table is a blobstreaming table, reduce the table count
319 if ($data['Tables_in_' . $db] == $table_key)
321 if ($num_tables > 0)
322 $num_tables--;
324 break;
326 } // end if PMA configuration exists
328 PMA_DBI_free_result($tables);
329 } else {
330 $num_tables = 0;
333 return $num_tables;
337 * Converts numbers like 10M into bytes
338 * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
339 * (renamed with PMA prefix to avoid double definition when embedded
340 * in Moodle)
342 * @uses each()
343 * @uses strlen()
344 * @uses substr()
345 * @param string $size
346 * @return integer $size
348 function PMA_get_real_size($size = 0)
350 if (! $size) {
351 return 0;
354 $scan['gb'] = 1073741824; //1024 * 1024 * 1024;
355 $scan['g'] = 1073741824; //1024 * 1024 * 1024;
356 $scan['mb'] = 1048576;
357 $scan['m'] = 1048576;
358 $scan['kb'] = 1024;
359 $scan['k'] = 1024;
360 $scan['b'] = 1;
362 foreach ($scan as $unit => $factor) {
363 if (strlen($size) > strlen($unit)
364 && strtolower(substr($size, strlen($size) - strlen($unit))) == $unit) {
365 return substr($size, 0, strlen($size) - strlen($unit)) * $factor;
369 return $size;
370 } // end function PMA_get_real_size()
373 * merges array recursive like array_merge_recursive() but keyed-values are
374 * always overwritten.
376 * array PMA_array_merge_recursive(array $array1[, array $array2[, array ...]])
378 * @see http://php.net/array_merge
379 * @see http://php.net/array_merge_recursive
380 * @uses func_num_args()
381 * @uses func_get_arg()
382 * @uses is_array()
383 * @uses call_user_func_array()
384 * @param array array to merge
385 * @param array array to merge
386 * @param array ...
387 * @return array merged array
389 function PMA_array_merge_recursive()
391 switch(func_num_args()) {
392 case 0 :
393 return false;
394 break;
395 case 1 :
396 // when does that happen?
397 return func_get_arg(0);
398 break;
399 case 2 :
400 $args = func_get_args();
401 if (!is_array($args[0]) || !is_array($args[1])) {
402 return $args[1];
404 foreach ($args[1] as $key2 => $value2) {
405 if (isset($args[0][$key2]) && !is_int($key2)) {
406 $args[0][$key2] = PMA_array_merge_recursive($args[0][$key2],
407 $value2);
408 } else {
409 // we erase the parent array, otherwise we cannot override a directive that
410 // contains array elements, like this:
411 // (in config.default.php) $cfg['ForeignKeyDropdownOrder'] = array('id-content','content-id');
412 // (in config.inc.php) $cfg['ForeignKeyDropdownOrder'] = array('content-id');
413 if (is_int($key2) && $key2 == 0) {
414 unset($args[0]);
416 $args[0][$key2] = $value2;
419 return $args[0];
420 break;
421 default :
422 $args = func_get_args();
423 $args[1] = PMA_array_merge_recursive($args[0], $args[1]);
424 array_shift($args);
425 return call_user_func_array('PMA_array_merge_recursive', $args);
426 break;
431 * calls $function vor every element in $array recursively
433 * this function is protected against deep recursion attack CVE-2006-1549,
434 * 1000 seems to be more than enough
436 * @see http://www.php-security.org/MOPB/MOPB-02-2007.html
437 * @see http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-1549
439 * @uses PMA_arrayWalkRecursive()
440 * @uses is_array()
441 * @uses is_string()
442 * @param array $array array to walk
443 * @param string $function function to call for every array element
445 function PMA_arrayWalkRecursive(&$array, $function, $apply_to_keys_also = false)
447 static $recursive_counter = 0;
448 if (++$recursive_counter > 1000) {
449 die('possible deep recursion attack');
451 foreach ($array as $key => $value) {
452 if (is_array($value)) {
453 PMA_arrayWalkRecursive($array[$key], $function, $apply_to_keys_also);
454 } else {
455 $array[$key] = $function($value);
458 if ($apply_to_keys_also && is_string($key)) {
459 $new_key = $function($key);
460 if ($new_key != $key) {
461 $array[$new_key] = $array[$key];
462 unset($array[$key]);
466 $recursive_counter--;
470 * boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
472 * checks given given $page against given $whitelist and returns true if valid
473 * it ignores optionaly query paramters in $page (script.php?ignored)
475 * @uses in_array()
476 * @uses urldecode()
477 * @uses substr()
478 * @uses strpos()
479 * @param string &$page page to check
480 * @param array $whitelist whitelist to check page against
481 * @return boolean whether $page is valid or not (in $whitelist or not)
483 function PMA_checkPageValidity(&$page, $whitelist)
485 if (! isset($page) || !is_string($page)) {
486 return false;
489 if (in_array($page, $whitelist)) {
490 return true;
491 } elseif (in_array(substr($page, 0, strpos($page . '?', '?')), $whitelist)) {
492 return true;
493 } else {
494 $_page = urldecode($page);
495 if (in_array(substr($_page, 0, strpos($_page . '?', '?')), $whitelist)) {
496 return true;
499 return false;
503 * trys to find the value for the given environment vriable name
505 * searchs in $_SERVER, $_ENV than trys getenv() and apache_getenv()
506 * in this order
508 * @uses $_SERVER
509 * @uses $_ENV
510 * @uses getenv()
511 * @uses function_exists()
512 * @uses apache_getenv()
513 * @param string $var_name variable name
514 * @return string value of $var or empty string
516 function PMA_getenv($var_name) {
517 if (isset($_SERVER[$var_name])) {
518 return $_SERVER[$var_name];
519 } elseif (isset($_ENV[$var_name])) {
520 return $_ENV[$var_name];
521 } elseif (getenv($var_name)) {
522 return getenv($var_name);
523 } elseif (function_exists('apache_getenv')
524 && apache_getenv($var_name, true)) {
525 return apache_getenv($var_name, true);
528 return '';
532 * removes cookie
534 * @uses PMA_Config::isHttps()
535 * @uses PMA_Config::getCookiePath()
536 * @uses setcookie()
537 * @uses time()
538 * @param string $cookie name of cookie to remove
539 * @return boolean result of setcookie()
541 function PMA_removeCookie($cookie)
543 return setcookie($cookie, '', time() - 3600,
544 PMA_Config::getCookiePath(), '', PMA_Config::isHttps());
548 * sets cookie if value is different from current cokkie value,
549 * or removes if value is equal to default
551 * @uses PMA_Config::isHttps()
552 * @uses PMA_Config::getCookiePath()
553 * @uses $_COOKIE
554 * @uses PMA_removeCookie()
555 * @uses setcookie()
556 * @uses time()
557 * @param string $cookie name of cookie to remove
558 * @param mixed $value new cookie value
559 * @param string $default default value
560 * @param int $validity validity of cookie in seconds (default is one month)
561 * @param bool $httponlt whether cookie is only for HTTP (and not for scripts)
562 * @return boolean result of setcookie()
564 function PMA_setCookie($cookie, $value, $default = null, $validity = null, $httponly = true)
566 if ($validity == null) {
567 $validity = 2592000;
569 if (strlen($value) && null !== $default && $value === $default
570 && isset($_COOKIE[$cookie])) {
571 // remove cookie, default value is used
572 return PMA_removeCookie($cookie);
575 if (! strlen($value) && isset($_COOKIE[$cookie])) {
576 // remove cookie, value is empty
577 return PMA_removeCookie($cookie);
580 if (! isset($_COOKIE[$cookie]) || $_COOKIE[$cookie] !== $value) {
581 // set cookie with new value
582 /* Calculate cookie validity */
583 if ($validity == 0) {
584 $v = 0;
585 } else {
586 $v = time() + $validity;
588 return setcookie($cookie, $value, $v,
589 PMA_Config::getCookiePath(), '', PMA_Config::isHttps(), $httponly);
592 // cookie has already $value as value
593 return true;