Merge remote-tracking branch 'origin/master' into drizzle
[phpmyadmin/crack.git] / libraries / config / validate.lib.php
blob989b324eadba88ec12fc5a4a2db486d613eda72c
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Various validation functions
6 * Validation function takes two argument: id for which it is called
7 * and array of fields' values (usually values for entire formset, as defined
8 * in forms.inc.php).
9 * The function must always return an array with an error (or error array)
10 * assigned to a form element (formset name or field path). Even if there are
11 * no errors, key must be set with an empty value.
13 * Valdiation functions are assigned in $cfg_db['_validators'] (config.values.php).
15 * @package phpMyAdmin
18 /**
19 * Returns validator list
21 * @return array
23 function PMA_config_get_validators()
25 static $validators = null;
27 if ($validators === null) {
28 $cf = ConfigFile::getInstance();
29 $validators = $cf->getDbEntry('_validators', array());
30 if (!defined('PMA_SETUP')) {
31 // not in setup script: load additional validators for user preferences
32 // we need oryginal config values not overwritten by user preferences, creating a new PMA_Config
33 // instance is a better idea than hacking into its code
34 $org_cfg = $cf->getOrgConfigObj();
35 $uvs = $cf->getDbEntry('_userValidators', array());
36 foreach ($uvs as $field => $uv_list) {
37 $uv_list = (array)$uv_list;
38 foreach ($uv_list as &$uv) {
39 if (!is_array($uv)) {
40 continue;
42 for ($i = 1; $i < count($uv); $i++) {
43 if (substr($uv[$i], 0, 6) == 'value:') {
44 $uv[$i] = PMA_array_read(substr($uv[$i], 6), $org_cfg->settings);
48 $validators[$field] = isset($validators[$field])
49 ? array_merge((array)$validators[$field], $uv_list)
50 : $uv_list;
54 return $validators;
57 /**
58 * Runs validation $validator_id on values $values and returns error list.
60 * Return values:
61 * o array, keys - field path or formset id, values - array of errors
62 * when $isPostSource is true values is an empty array to allow for error list
63 * cleanup in HTML documen
64 * o false - when no validators match name(s) given by $validator_id
66 * @param string|array $validator_id
67 * @param array $values
68 * @param bool $isPostSource tells whether $values are directly from POST request
69 * @return bool|array
71 function PMA_config_validate($validator_id, &$values, $isPostSource)
73 // find validators
74 $validator_id = (array) $validator_id;
75 $validators = PMA_config_get_validators();
76 $vids = array();
77 $cf = ConfigFile::getInstance();
78 foreach ($validator_id as &$vid) {
79 $vid = $cf->getCanonicalPath($vid);
80 if (isset($validators[$vid])) {
81 $vids[] = $vid;
84 if (empty($vids)) {
85 return false;
88 // create argument list with canonical paths and remember path mapping
89 $arguments = array();
90 $key_map = array();
91 foreach ($values as $k => $v) {
92 $k2 = $isPostSource ? str_replace('-', '/', $k) : $k;
93 $k2 = strpos($k2, '/') ? $cf->getCanonicalPath($k2) : $k2;
94 $key_map[$k2] = $k;
95 $arguments[$k2] = $v;
98 // validate
99 $result = array();
100 foreach ($vids as $vid) {
101 // call appropriate validation functions
102 foreach ((array)$validators[$vid] as $validator) {
103 $vdef = (array) $validator;
104 $vname = array_shift($vdef);
105 $args = array_merge(array($vid, &$arguments), $vdef);
106 $r = call_user_func_array($vname, $args);
108 // merge results
109 if (is_array($r)) {
110 foreach ($r as $key => $error_list) {
111 // skip empty values if $isPostSource is false
112 if (!$isPostSource && empty($error_list)) {
113 continue;
115 if (!isset($result[$key])) {
116 $result[$key] = array();
118 $result[$key] = array_merge($result[$key], (array)$error_list);
124 // restore original paths
125 $new_result = array();
126 foreach ($result as $k => $v) {
127 $k2 = isset($key_map[$k]) ? $key_map[$k] : $k;
128 $new_result[$k2] = $v;
130 return empty($new_result) ? true : $new_result;
134 * Empty error handler, used to temporarily restore PHP internal error handler
136 * @return bool
138 function PMA_null_error_handler()
140 return false;
144 * Ensures that $php_errormsg variable will be registered in case of an error
145 * and enables output buffering (when $start = true).
146 * Called with $start = false disables output buffering end restores
147 * html_errors and track_errors.
149 * @param boolean $start
151 function test_php_errormsg($start = true)
153 static $old_html_errors, $old_track_errors, $old_error_reporting;
154 static $old_display_errors;
155 if ($start) {
156 $old_html_errors = ini_get('html_errors');
157 $old_track_errors = ini_get('track_errors');
158 $old_display_errors = ini_get('display_errors');
159 $old_error_reporting = error_reporting(E_ALL);
160 ini_set('html_errors', false);
161 ini_set('track_errors', true);
162 ini_set('display_errors', true);
163 set_error_handler("PMA_null_error_handler");
164 ob_start();
165 } else {
166 ob_end_clean();
167 restore_error_handler();
168 error_reporting($old_error_reporting);
169 ini_set('html_errors', $old_html_errors);
170 ini_set('track_errors', $old_track_errors);
171 ini_set('display_errors', $old_display_errors);
176 * Test database connection
178 * @param string $extension 'drizzle', 'mysql' or 'mysqli'
179 * @param string $connect_type 'tcp' or 'socket'
180 * @param string $host
181 * @param string $port
182 * @param string $socket
183 * @param string $user
184 * @param string $pass
185 * @param string $error_key
186 * @return bool|array
188 function test_db_connection($extension, $connect_type, $host, $port, $socket, $user, $pass = null, $error_key = 'Server')
190 // test_php_errormsg();
191 $socket = empty($socket) || $connect_type == 'tcp' ? null : $socket;
192 $port = empty($port) || $connect_type == 'socket' ? null : ':' . $port;
193 $error = null;
194 if ($extension == 'drizzle') {
195 while (1) {
196 $drizzle = @drizzle_create();
197 if (!$drizzle) {
198 $error = __('Could not initialize Drizzle connection library');
199 break;
201 $conn = $socket
202 ? @drizzle_con_add_uds($socket, $user, $pass, null, 0)
203 : @drizzle_con_add_tcp($drizzle, $host, $port, $user, $pass, null, 0);
204 if (!$conn) {
205 $error = __('Could not connect to Drizzle server');
206 drizzle_free($drizzle);
207 break;
209 // connection object is set up but we have to send some query to actually connect
210 $res = @drizzle_query($conn, 'SELECT 1');
211 if (!$res) {
212 $error = __('Could not connect to Drizzle server');
213 } else {
214 drizzle_result_free($res);
216 drizzle_con_free($conn);
217 drizzle_free($drizzle);
218 break;
220 } else if ($extension == 'mysql') {
221 $conn = @mysql_connect($host . $socket . $port, $user, $pass);
222 if (!$conn) {
223 $error = __('Could not connect to MySQL server');
224 } else {
225 mysql_close($conn);
227 } else {
228 $conn = @mysqli_connect($host, $user, $pass, null, $port, $socket);
229 if (!$conn) {
230 $error = __('Could not connect to MySQL server');
231 } else {
232 mysqli_close($conn);
235 // test_php_errormsg(false);
236 if (isset($php_errormsg)) {
237 $error .= " - $php_errormsg";
239 return is_null($error) ? true : array($error_key => $error);
243 * Validate server config
245 * @param string $path
246 * @param array $values
247 * @return array
249 function validate_server($path, $values)
251 $result = array('Server' => '', 'Servers/1/user' => '', 'Servers/1/SignonSession' => '', 'Servers/1/SignonURL' => '');
252 $error = false;
253 if ($values['Servers/1/auth_type'] == 'config' && empty($values['Servers/1/user'])) {
254 $result['Servers/1/user'] = __('Empty username while using config authentication method');
255 $error = true;
257 if ($values['Servers/1/auth_type'] == 'signon' && empty($values['Servers/1/SignonSession'])) {
258 $result['Servers/1/SignonSession'] = __('Empty signon session name while using signon authentication method');
259 $error = true;
261 if ($values['Servers/1/auth_type'] == 'signon' && empty($values['Servers/1/SignonURL'])) {
262 $result['Servers/1/SignonURL'] = __('Empty signon URL while using signon authentication method');
263 $error = true;
266 if (!$error && $values['Servers/1/auth_type'] == 'config') {
267 $password = $values['Servers/1/nopassword'] ? null : $values['Servers/1/password'];
268 $test = test_db_connection($values['Servers/1/extension'], $values['Servers/1/connect_type'], $values['Servers/1/host'], $values['Servers/1/port'], $values['Servers/1/socket'], $values['Servers/1/user'], $password, 'Server');
269 if ($test !== true) {
270 $result = array_merge($result, $test);
273 return $result;
277 * Validate pmadb config
279 * @param string $path
280 * @param array $values
281 * @return array
283 function validate_pmadb($path, $values)
285 //$tables = array('Servers/1/bookmarktable', 'Servers/1/relation', 'Servers/1/table_info', 'Servers/1/table_coords', 'Servers/1/pdf_pages', 'Servers/1/column_info', 'Servers/1/history', 'Servers/1/designer_coords');
286 $result = array('Server_pmadb' => '', 'Servers/1/controluser' => '', 'Servers/1/controlpass' => '');
287 $error = false;
289 if ($values['Servers/1/pmadb'] == '') {
290 return $result;
293 $result = array();
294 if ($values['Servers/1/controluser'] == '') {
295 $result['Servers/1/controluser'] = __('Empty phpMyAdmin control user while using pmadb');
296 $error = true;
298 if ($values['Servers/1/controlpass'] == '') {
299 $result['Servers/1/controlpass'] = __('Empty phpMyAdmin control user password while using pmadb');
300 $error = true;
302 if (!$error) {
303 $test = test_db_connection($values['Servers/1/extension'], $values['Servers/1/connect_type'],
304 $values['Servers/1/host'], $values['Servers/1/port'], $values['Servers/1/socket'],
305 $values['Servers/1/controluser'], $values['Servers/1/controlpass'], 'Server_pmadb');
306 if ($test !== true) {
307 $result = array_merge($result, $test);
310 return $result;
315 * Validates regular expression
317 * @param string $path
318 * @param array $values
319 * @return array
321 function validate_regex($path, $values)
323 $result = array($path => '');
325 if ($values[$path] == '') {
326 return $result;
329 test_php_errormsg();
331 $matches = array();
332 // in libraries/List_Database.class.php _checkHideDatabase(),
333 // a '/' is used as the delimiter for hide_db
334 preg_match('/' . $values[$path] . '/', '', $matches);
336 test_php_errormsg(false);
338 if (isset($php_errormsg)) {
339 $error = preg_replace('/^preg_match\(\): /', '', $php_errormsg);
340 return array($path => $error);
343 return $result;
347 * Validates TrustedProxies field
349 * @param string $path
350 * @param array $values
351 * @return array
353 function validate_trusted_proxies($path, $values)
355 $result = array($path => array());
357 if (empty($values[$path])) {
358 return $result;
361 if (is_array($values[$path])) {
362 // value already processed by FormDisplay::save
363 $lines = array();
364 foreach ($values[$path] as $ip => $v) {
365 $lines[] = preg_match('/^-\d+$/', $ip)
366 ? $v
367 : $ip . ': ' . $v;
369 } else {
370 // AJAX validation
371 $lines = explode("\n", $values[$path]);
373 foreach ($lines as $line) {
374 $line = trim($line);
375 $matches = array();
376 // we catch anything that may (or may not) be an IP
377 if (!preg_match("/^(.+):(?:[ ]?)\\w+$/", $line, $matches)) {
378 $result[$path][] = __('Incorrect value') . ': ' . $line;
379 continue;
381 // now let's check whether we really have an IP address
382 if (filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
383 && filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
384 $ip = htmlspecialchars(trim($matches[1]));
385 $result[$path][] = sprintf(__('Incorrect IP address: %s'), $ip);
386 continue;
390 return $result;
394 * Tests integer value
396 * @param string $path
397 * @param array $values
398 * @param bool $allow_neg allow negative values
399 * @param bool $allow_zero allow zero
400 * @param int $max_value max allowed value
401 * @param string $error_string error message key: $GLOBALS["strConfig$error_lang_key"]
402 * @return string empty string if test is successful
404 function test_number($path, $values, $allow_neg, $allow_zero, $max_value, $error_string)
406 if ($values[$path] === '') {
407 return '';
410 if (intval($values[$path]) != $values[$path] || (!$allow_neg && $values[$path] < 0) || (!$allow_zero && $values[$path] == 0) || $values[$path] > $max_value) {
411 return $error_string;
414 return '';
418 * Validates port number
420 * @param string $path
421 * @param array $values
422 * @return array
424 function validate_port_number($path, $values)
426 return array($path => test_number($path, $values, false, false, 65535, __('Not a valid port number')));
430 * Validates positive number
432 * @param string $path
433 * @param array $values
434 * @return array
436 function validate_positive_number($path, $values)
438 return array($path => test_number($path, $values, false, false, PHP_INT_MAX, __('Not a positive number')));
442 * Validates non-negative number
444 * @param string $path
445 * @param array $values
446 * @return array
448 function validate_non_negative_number($path, $values)
450 return array($path => test_number($path, $values, false, true, PHP_INT_MAX, __('Not a non-negative number')));
454 * Validates value according to given regular expression
455 * Pattern and modifiers must be a valid for PCRE <b>and</b> JavaScript RegExp
457 * @param string $path
458 * @param array $values
459 * @param string $regex
460 * @return void
462 function validate_by_regex($path, $values, $regex)
464 $result = preg_match($regex, $values[$path]);
465 return array($path => ($result ? '' : __('Incorrect value')));
469 * Validates upper bound for numeric inputs
471 * @param string $path
472 * @param array $values
473 * @param int $max_value
474 * @return array
476 function validate_upper_bound($path, $values, $max_value)
478 $result = $values[$path] <= $max_value;
479 return array($path => ($result ? '' : sprintf(__('Value must be equal or lower than %s'), $max_value)));