Advisor: properly handle concurrent_insert on MySQL 5.5.3
[phpmyadmin.git] / libraries / config / validate.lib.php
blob2b60725ed8e5d9188f4277670a29e7c9abd7f206
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 '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 == 'mysql') {
195 $conn = @mysql_connect($host . $socket . $port, $user, $pass);
196 if (!$conn) {
197 $error = __('Could not connect to MySQL server');
198 } else {
199 mysql_close($conn);
201 } else {
202 $conn = @mysqli_connect($host, $user, $pass, null, $port, $socket);
203 if (!$conn) {
204 $error = __('Could not connect to MySQL server');
205 } else {
206 mysqli_close($conn);
209 // test_php_errormsg(false);
210 if (isset($php_errormsg)) {
211 $error .= " - $php_errormsg";
213 return is_null($error) ? true : array($error_key => $error);
217 * Validate server config
219 * @param string $path
220 * @param array $values
221 * @return array
223 function validate_server($path, $values)
225 $result = array('Server' => '', 'Servers/1/user' => '', 'Servers/1/SignonSession' => '', 'Servers/1/SignonURL' => '');
226 $error = false;
227 if ($values['Servers/1/auth_type'] == 'config' && empty($values['Servers/1/user'])) {
228 $result['Servers/1/user'] = __('Empty username while using config authentication method');
229 $error = true;
231 if ($values['Servers/1/auth_type'] == 'signon' && empty($values['Servers/1/SignonSession'])) {
232 $result['Servers/1/SignonSession'] = __('Empty signon session name while using signon authentication method');
233 $error = true;
235 if ($values['Servers/1/auth_type'] == 'signon' && empty($values['Servers/1/SignonURL'])) {
236 $result['Servers/1/SignonURL'] = __('Empty signon URL while using signon authentication method');
237 $error = true;
240 if (!$error && $values['Servers/1/auth_type'] == 'config') {
241 $password = $values['Servers/1/nopassword'] ? null : $values['Servers/1/password'];
242 $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');
243 if ($test !== true) {
244 $result = array_merge($result, $test);
247 return $result;
251 * Validate pmadb config
253 * @param string $path
254 * @param array $values
255 * @return array
257 function validate_pmadb($path, $values)
259 //$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');
260 $result = array('Server_pmadb' => '', 'Servers/1/controluser' => '', 'Servers/1/controlpass' => '');
261 $error = false;
263 if ($values['Servers/1/pmadb'] == '') {
264 return $result;
267 $result = array();
268 if ($values['Servers/1/controluser'] == '') {
269 $result['Servers/1/controluser'] = __('Empty phpMyAdmin control user while using pmadb');
270 $error = true;
272 if ($values['Servers/1/controlpass'] == '') {
273 $result['Servers/1/controlpass'] = __('Empty phpMyAdmin control user password while using pmadb');
274 $error = true;
276 if (!$error) {
277 $test = test_db_connection($values['Servers/1/extension'], $values['Servers/1/connect_type'],
278 $values['Servers/1/host'], $values['Servers/1/port'], $values['Servers/1/socket'],
279 $values['Servers/1/controluser'], $values['Servers/1/controlpass'], 'Server_pmadb');
280 if ($test !== true) {
281 $result = array_merge($result, $test);
284 return $result;
289 * Validates regular expression
291 * @param string $path
292 * @param array $values
293 * @return array
295 function validate_regex($path, $values)
297 $result = array($path => '');
299 if ($values[$path] == '') {
300 return $result;
303 test_php_errormsg();
305 $matches = array();
306 // in libraries/List_Database.class.php _checkHideDatabase(),
307 // a '/' is used as the delimiter for hide_db
308 preg_match('/' . $values[$path] . '/', '', $matches);
310 test_php_errormsg(false);
312 if (isset($php_errormsg)) {
313 $error = preg_replace('/^preg_match\(\): /', '', $php_errormsg);
314 return array($path => $error);
317 return $result;
321 * Validates TrustedProxies field
323 * @param string $path
324 * @param array $values
325 * @return array
327 function validate_trusted_proxies($path, $values)
329 $result = array($path => array());
331 if (empty($values[$path])) {
332 return $result;
335 if (is_array($values[$path])) {
336 // value already processed by FormDisplay::save
337 $lines = array();
338 foreach ($values[$path] as $ip => $v) {
339 $lines[] = preg_match('/^-\d+$/', $ip)
340 ? $v
341 : $ip . ': ' . $v;
343 } else {
344 // AJAX validation
345 $lines = explode("\n", $values[$path]);
347 foreach ($lines as $line) {
348 $line = trim($line);
349 $matches = array();
350 // we catch anything that may (or may not) be an IP
351 if (!preg_match("/^(.+):(?:[ ]?)\\w+$/", $line, $matches)) {
352 $result[$path][] = __('Incorrect value') . ': ' . $line;
353 continue;
355 // now let's check whether we really have an IP address
356 if (filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
357 && filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
358 $ip = htmlspecialchars(trim($matches[1]));
359 $result[$path][] = sprintf(__('Incorrect IP address: %s'), $ip);
360 continue;
364 return $result;
368 * Tests integer value
370 * @param string $path
371 * @param array $values
372 * @param bool $allow_neg allow negative values
373 * @param bool $allow_zero allow zero
374 * @param int $max_value max allowed value
375 * @param string $error_string error message key: $GLOBALS["strConfig$error_lang_key"]
376 * @return string empty string if test is successful
378 function test_number($path, $values, $allow_neg, $allow_zero, $max_value, $error_string)
380 if ($values[$path] === '') {
381 return '';
384 if (intval($values[$path]) != $values[$path] || (!$allow_neg && $values[$path] < 0) || (!$allow_zero && $values[$path] == 0) || $values[$path] > $max_value) {
385 return $error_string;
388 return '';
392 * Validates port number
394 * @param string $path
395 * @param array $values
396 * @return array
398 function validate_port_number($path, $values)
400 return array($path => test_number($path, $values, false, false, 65535, __('Not a valid port number')));
404 * Validates positive number
406 * @param string $path
407 * @param array $values
408 * @return array
410 function validate_positive_number($path, $values)
412 return array($path => test_number($path, $values, false, false, PHP_INT_MAX, __('Not a positive number')));
416 * Validates non-negative number
418 * @param string $path
419 * @param array $values
420 * @return array
422 function validate_non_negative_number($path, $values)
424 return array($path => test_number($path, $values, false, true, PHP_INT_MAX, __('Not a non-negative number')));
428 * Validates value according to given regular expression
429 * Pattern and modifiers must be a valid for PCRE <b>and</b> JavaScript RegExp
431 * @param string $path
432 * @param array $values
433 * @param string $regex
434 * @return void
436 function validate_by_regex($path, $values, $regex)
438 $result = preg_match($regex, $values[$path]);
439 return array($path => ($result ? '' : __('Incorrect value')));
443 * Validates upper bound for numeric inputs
445 * @param string $path
446 * @param array $values
447 * @param int $max_value
448 * @return array
450 function validate_upper_bound($path, $values, $max_value)
452 $result = $values[$path] <= $max_value;
453 return array($path => ($result ? '' : sprintf(__('Value must be equal or lower than %s'), $max_value)));