Validator.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Form validation for configuration editor
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin\Config;
  9. use PhpMyAdmin\Config\ConfigFile;
  10. use PhpMyAdmin\Core;
  11. use PhpMyAdmin\DatabaseInterface;
  12. use PhpMyAdmin\Util;
  13. /**
  14. * Validation class for various validation functions
  15. *
  16. * Validation function takes two argument: id for which it is called
  17. * and array of fields' values (usually values for entire formset, as defined
  18. * in forms.inc.php).
  19. * The function must always return an array with an error (or error array)
  20. * assigned to a form element (formset name or field path). Even if there are
  21. * no errors, key must be set with an empty value.
  22. *
  23. * Validation functions are assigned in $cfg_db['_validators'] (config.values.php).
  24. *
  25. * @package PhpMyAdmin
  26. */
  27. class Validator
  28. {
  29. /**
  30. * Returns validator list
  31. *
  32. * @param ConfigFile $cf Config file instance
  33. *
  34. * @return array
  35. */
  36. public static function getValidators(ConfigFile $cf)
  37. {
  38. static $validators = null;
  39. if ($validators !== null) {
  40. return $validators;
  41. }
  42. $validators = $cf->getDbEntry('_validators', array());
  43. if ($GLOBALS['PMA_Config']->get('is_setup')) {
  44. return $validators;
  45. }
  46. // not in setup script: load additional validators for user
  47. // preferences we need original config values not overwritten
  48. // by user preferences, creating a new PhpMyAdmin\Config instance is a
  49. // better idea than hacking into its code
  50. $uvs = $cf->getDbEntry('_userValidators', array());
  51. foreach ($uvs as $field => $uv_list) {
  52. $uv_list = (array)$uv_list;
  53. foreach ($uv_list as &$uv) {
  54. if (!is_array($uv)) {
  55. continue;
  56. }
  57. for ($i = 1, $nb = count($uv); $i < $nb; $i++) {
  58. if (mb_substr($uv[$i], 0, 6) == 'value:') {
  59. $uv[$i] = Core::arrayRead(
  60. mb_substr($uv[$i], 6),
  61. $GLOBALS['PMA_Config']->base_settings
  62. );
  63. }
  64. }
  65. }
  66. $validators[$field] = isset($validators[$field])
  67. ? array_merge((array)$validators[$field], $uv_list)
  68. : $uv_list;
  69. }
  70. return $validators;
  71. }
  72. /**
  73. * Runs validation $validator_id on values $values and returns error list.
  74. *
  75. * Return values:
  76. * o array, keys - field path or formset id, values - array of errors
  77. * when $isPostSource is true values is an empty array to allow for error list
  78. * cleanup in HTML document
  79. * o false - when no validators match name(s) given by $validator_id
  80. *
  81. * @param ConfigFile $cf Config file instance
  82. * @param string|array $validator_id ID of validator(s) to run
  83. * @param array &$values Values to validate
  84. * @param bool $isPostSource tells whether $values are directly from
  85. * POST request
  86. *
  87. * @return bool|array
  88. */
  89. public static function validate(
  90. ConfigFile $cf, $validator_id, array &$values, $isPostSource
  91. ) {
  92. // find validators
  93. $validator_id = (array) $validator_id;
  94. $validators = static::getValidators($cf);
  95. $vids = array();
  96. foreach ($validator_id as &$vid) {
  97. $vid = $cf->getCanonicalPath($vid);
  98. if (isset($validators[$vid])) {
  99. $vids[] = $vid;
  100. }
  101. }
  102. if (empty($vids)) {
  103. return false;
  104. }
  105. // create argument list with canonical paths and remember path mapping
  106. $arguments = array();
  107. $key_map = array();
  108. foreach ($values as $k => $v) {
  109. $k2 = $isPostSource ? str_replace('-', '/', $k) : $k;
  110. $k2 = mb_strpos($k2, '/')
  111. ? $cf->getCanonicalPath($k2)
  112. : $k2;
  113. $key_map[$k2] = $k;
  114. $arguments[$k2] = $v;
  115. }
  116. // validate
  117. $result = array();
  118. foreach ($vids as $vid) {
  119. // call appropriate validation functions
  120. foreach ((array)$validators[$vid] as $validator) {
  121. $vdef = (array) $validator;
  122. $vname = array_shift($vdef);
  123. $vname = 'PhpMyAdmin\Config\Validator::' . $vname;
  124. $args = array_merge(array($vid, &$arguments), $vdef);
  125. $r = call_user_func_array($vname, $args);
  126. // merge results
  127. if (!is_array($r)) {
  128. continue;
  129. }
  130. foreach ($r as $key => $error_list) {
  131. // skip empty values if $isPostSource is false
  132. if (! $isPostSource && empty($error_list)) {
  133. continue;
  134. }
  135. if (! isset($result[$key])) {
  136. $result[$key] = array();
  137. }
  138. $result[$key] = array_merge(
  139. $result[$key], (array)$error_list
  140. );
  141. }
  142. }
  143. }
  144. // restore original paths
  145. $new_result = array();
  146. foreach ($result as $k => $v) {
  147. $k2 = isset($key_map[$k]) ? $key_map[$k] : $k;
  148. $new_result[$k2] = $v;
  149. }
  150. return empty($new_result) ? true : $new_result;
  151. }
  152. /**
  153. * Test database connection
  154. *
  155. * @param string $host host name
  156. * @param string $port tcp port to use
  157. * @param string $socket socket to use
  158. * @param string $user username to use
  159. * @param string $pass password to use
  160. * @param string $error_key key to use in return array
  161. *
  162. * @return bool|array
  163. */
  164. public static function testDBConnection(
  165. $host,
  166. $port,
  167. $socket,
  168. $user,
  169. $pass = null,
  170. $error_key = 'Server'
  171. ) {
  172. if ($GLOBALS['cfg']['DBG']['demo']) {
  173. // Connection test disabled on the demo server!
  174. return true;
  175. }
  176. $error = null;
  177. $host = Core::sanitizeMySQLHost($host);
  178. if (function_exists('error_clear_last')) {
  179. /* PHP 7 only code */
  180. error_clear_last();
  181. }
  182. if (DatabaseInterface::checkDbExtension('mysqli')) {
  183. $socket = empty($socket) ? null : $socket;
  184. $port = empty($port) ? null : $port;
  185. $extension = 'mysqli';
  186. } else {
  187. $socket = empty($socket) ? null : ':' . ($socket[0] == '/' ? '' : '/') . $socket;
  188. $port = empty($port) ? null : ':' . $port;
  189. $extension = 'mysql';
  190. }
  191. if ($extension == 'mysql') {
  192. $conn = @mysql_connect($host . $port . $socket, $user, $pass);
  193. if (! $conn) {
  194. $error = __('Could not connect to the database server!');
  195. } else {
  196. mysql_close($conn);
  197. }
  198. } else {
  199. $conn = @mysqli_connect($host, $user, $pass, null, $port, $socket);
  200. if (! $conn) {
  201. $error = __('Could not connect to the database server!');
  202. } else {
  203. mysqli_close($conn);
  204. }
  205. }
  206. if (! is_null($error)) {
  207. $error .= ' - ' . error_get_last();
  208. }
  209. return is_null($error) ? true : array($error_key => $error);
  210. }
  211. /**
  212. * Validate server config
  213. *
  214. * @param string $path path to config, not used
  215. * keep this parameter since the method is invoked using
  216. * reflection along with other similar methods
  217. * @param array $values config values
  218. *
  219. * @return array
  220. */
  221. public static function validateServer($path, array $values)
  222. {
  223. $result = array(
  224. 'Server' => '',
  225. 'Servers/1/user' => '',
  226. 'Servers/1/SignonSession' => '',
  227. 'Servers/1/SignonURL' => ''
  228. );
  229. $error = false;
  230. if (empty($values['Servers/1/auth_type'])) {
  231. $values['Servers/1/auth_type'] = '';
  232. $result['Servers/1/auth_type'] = __('Invalid authentication type!');
  233. $error = true;
  234. }
  235. if ($values['Servers/1/auth_type'] == 'config'
  236. && empty($values['Servers/1/user'])
  237. ) {
  238. $result['Servers/1/user'] = __(
  239. 'Empty username while using [kbd]config[/kbd] authentication method!'
  240. );
  241. $error = true;
  242. }
  243. if ($values['Servers/1/auth_type'] == 'signon'
  244. && empty($values['Servers/1/SignonSession'])
  245. ) {
  246. $result['Servers/1/SignonSession'] = __(
  247. 'Empty signon session name '
  248. . 'while using [kbd]signon[/kbd] authentication method!'
  249. );
  250. $error = true;
  251. }
  252. if ($values['Servers/1/auth_type'] == 'signon'
  253. && empty($values['Servers/1/SignonURL'])
  254. ) {
  255. $result['Servers/1/SignonURL'] = __(
  256. 'Empty signon URL while using [kbd]signon[/kbd] authentication '
  257. . 'method!'
  258. );
  259. $error = true;
  260. }
  261. if (! $error && $values['Servers/1/auth_type'] == 'config') {
  262. $password = '';
  263. if (! empty($values['Servers/1/password'])) {
  264. $password = $values['Servers/1/password'];
  265. }
  266. $test = static::testDBConnection(
  267. empty($values['Servers/1/host']) ? '' : $values['Servers/1/host'],
  268. empty($values['Servers/1/port']) ? '' : $values['Servers/1/port'],
  269. empty($values['Servers/1/socket']) ? '' : $values['Servers/1/socket'],
  270. empty($values['Servers/1/user']) ? '' : $values['Servers/1/user'],
  271. $password,
  272. 'Server'
  273. );
  274. if ($test !== true) {
  275. $result = array_merge($result, $test);
  276. }
  277. }
  278. return $result;
  279. }
  280. /**
  281. * Validate pmadb config
  282. *
  283. * @param string $path path to config, not used
  284. * keep this parameter since the method is invoked using
  285. * reflection along with other similar methods
  286. * @param array $values config values
  287. *
  288. * @return array
  289. */
  290. public static function validatePMAStorage($path, array $values)
  291. {
  292. $result = array(
  293. 'Server_pmadb' => '',
  294. 'Servers/1/controluser' => '',
  295. 'Servers/1/controlpass' => ''
  296. );
  297. $error = false;
  298. if (empty($values['Servers/1/pmadb'])) {
  299. return $result;
  300. }
  301. $result = array();
  302. if (empty($values['Servers/1/controluser'])) {
  303. $result['Servers/1/controluser'] = __(
  304. 'Empty phpMyAdmin control user while using phpMyAdmin configuration '
  305. . 'storage!'
  306. );
  307. $error = true;
  308. }
  309. if (empty($values['Servers/1/controlpass'])) {
  310. $result['Servers/1/controlpass'] = __(
  311. 'Empty phpMyAdmin control user password while using phpMyAdmin '
  312. . 'configuration storage!'
  313. );
  314. $error = true;
  315. }
  316. if (! $error) {
  317. $test = static::testDBConnection(
  318. empty($values['Servers/1/host']) ? '' : $values['Servers/1/host'],
  319. empty($values['Servers/1/port']) ? '' : $values['Servers/1/port'],
  320. empty($values['Servers/1/socket']) ? '' : $values['Servers/1/socket'],
  321. empty($values['Servers/1/controluser']) ? '' : $values['Servers/1/controluser'],
  322. empty($values['Servers/1/controlpass']) ? '' : $values['Servers/1/controlpass'],
  323. 'Server_pmadb'
  324. );
  325. if ($test !== true) {
  326. $result = array_merge($result, $test);
  327. }
  328. }
  329. return $result;
  330. }
  331. /**
  332. * Validates regular expression
  333. *
  334. * @param string $path path to config
  335. * @param array $values config values
  336. *
  337. * @return array
  338. */
  339. public static function validateRegex($path, array $values)
  340. {
  341. $result = array($path => '');
  342. if (empty($values[$path])) {
  343. return $result;
  344. }
  345. if (function_exists('error_clear_last')) {
  346. /* PHP 7 only code */
  347. error_clear_last();
  348. $last_error = null;
  349. } else {
  350. // As fallback we trigger another error to ensure
  351. // that preg error will be different
  352. @strpos();
  353. $last_error = error_get_last();
  354. }
  355. $matches = array();
  356. // in libraries/ListDatabase.php _checkHideDatabase(),
  357. // a '/' is used as the delimiter for hide_db
  358. @preg_match('/' . Util::requestString($values[$path]) . '/', '', $matches);
  359. $current_error = error_get_last();
  360. if ($current_error !== $last_error) {
  361. $error = preg_replace('/^preg_match\(\): /', '', $current_error['message']);
  362. return array($path => $error);
  363. }
  364. return $result;
  365. }
  366. /**
  367. * Validates TrustedProxies field
  368. *
  369. * @param string $path path to config
  370. * @param array $values config values
  371. *
  372. * @return array
  373. */
  374. public static function validateTrustedProxies($path, array $values)
  375. {
  376. $result = array($path => array());
  377. if (empty($values[$path])) {
  378. return $result;
  379. }
  380. if (is_array($values[$path]) || is_object($values[$path])) {
  381. // value already processed by FormDisplay::save
  382. $lines = array();
  383. foreach ($values[$path] as $ip => $v) {
  384. $v = Util::requestString($v);
  385. $lines[] = preg_match('/^-\d+$/', $ip)
  386. ? $v
  387. : $ip . ': ' . $v;
  388. }
  389. } else {
  390. // AJAX validation
  391. $lines = explode("\n", $values[$path]);
  392. }
  393. foreach ($lines as $line) {
  394. $line = trim($line);
  395. $matches = array();
  396. // we catch anything that may (or may not) be an IP
  397. if (!preg_match("/^(.+):(?:[ ]?)\\w+$/", $line, $matches)) {
  398. $result[$path][] = __('Incorrect value:') . ' '
  399. . htmlspecialchars($line);
  400. continue;
  401. }
  402. // now let's check whether we really have an IP address
  403. if (filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
  404. && filter_var($matches[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false
  405. ) {
  406. $ip = htmlspecialchars(trim($matches[1]));
  407. $result[$path][] = sprintf(__('Incorrect IP address: %s'), $ip);
  408. continue;
  409. }
  410. }
  411. return $result;
  412. }
  413. /**
  414. * Tests integer value
  415. *
  416. * @param string $path path to config
  417. * @param array $values config values
  418. * @param bool $allow_neg allow negative values
  419. * @param bool $allow_zero allow zero
  420. * @param int $max_value max allowed value
  421. * @param string $error_string error message string
  422. *
  423. * @return string empty string if test is successful
  424. */
  425. public static function validateNumber(
  426. $path,
  427. array $values,
  428. $allow_neg,
  429. $allow_zero,
  430. $max_value,
  431. $error_string
  432. ) {
  433. if (empty($values[$path])) {
  434. return '';
  435. }
  436. $value = Util::requestString($values[$path]);
  437. if (intval($value) != $value
  438. || (! $allow_neg && $value < 0)
  439. || (! $allow_zero && $value == 0)
  440. || $value > $max_value
  441. ) {
  442. return $error_string;
  443. }
  444. return '';
  445. }
  446. /**
  447. * Validates port number
  448. *
  449. * @param string $path path to config
  450. * @param array $values config values
  451. *
  452. * @return array
  453. */
  454. public static function validatePortNumber($path, array $values)
  455. {
  456. return array(
  457. $path => static::validateNumber(
  458. $path,
  459. $values,
  460. false,
  461. false,
  462. 65535,
  463. __('Not a valid port number!')
  464. )
  465. );
  466. }
  467. /**
  468. * Validates positive number
  469. *
  470. * @param string $path path to config
  471. * @param array $values config values
  472. *
  473. * @return array
  474. */
  475. public static function validatePositiveNumber($path, array $values)
  476. {
  477. return array(
  478. $path => static::validateNumber(
  479. $path,
  480. $values,
  481. false,
  482. false,
  483. PHP_INT_MAX,
  484. __('Not a positive number!')
  485. )
  486. );
  487. }
  488. /**
  489. * Validates non-negative number
  490. *
  491. * @param string $path path to config
  492. * @param array $values config values
  493. *
  494. * @return array
  495. */
  496. public static function validateNonNegativeNumber($path, array $values)
  497. {
  498. return array(
  499. $path => static::validateNumber(
  500. $path,
  501. $values,
  502. false,
  503. true,
  504. PHP_INT_MAX,
  505. __('Not a non-negative number!')
  506. )
  507. );
  508. }
  509. /**
  510. * Validates value according to given regular expression
  511. * Pattern and modifiers must be a valid for PCRE <b>and</b> JavaScript RegExp
  512. *
  513. * @param string $path path to config
  514. * @param array $values config values
  515. * @param string $regex regular expression to match
  516. *
  517. * @return array
  518. */
  519. public static function validateByRegex($path, array $values, $regex)
  520. {
  521. if (!isset($values[$path])) {
  522. return '';
  523. }
  524. $result = preg_match($regex, Util::requestString($values[$path]));
  525. return array($path => ($result ? '' : __('Incorrect value!')));
  526. }
  527. /**
  528. * Validates upper bound for numeric inputs
  529. *
  530. * @param string $path path to config
  531. * @param array $values config values
  532. * @param int $max_value maximal allowed value
  533. *
  534. * @return array
  535. */
  536. public static function validateUpperBound($path, array $values, $max_value)
  537. {
  538. $result = $values[$path] <= $max_value;
  539. return array($path => ($result ? ''
  540. : sprintf(__('Value must be equal or lower than %s!'), $max_value)));
  541. }
  542. }