Validation.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Validation;
  16. use Cake\Utility\Text;
  17. use LogicException;
  18. use NumberFormatter;
  19. use RuntimeException;
  20. /**
  21. * Validation Class. Used for validation of model data
  22. *
  23. * Offers different validation methods.
  24. *
  25. */
  26. class Validation
  27. {
  28. /**
  29. * Some complex patterns needed in multiple places
  30. *
  31. * @var array
  32. */
  33. protected static $_pattern = [
  34. 'hostname' => '(?:[_\p{L}0-9][-_\p{L}0-9]*\.)*(?:[\p{L}0-9][-\p{L}0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,})'
  35. ];
  36. /**
  37. * Holds an array of errors messages set in this class.
  38. * These are used for debugging purposes
  39. *
  40. * @var array
  41. */
  42. public static $errors = [];
  43. /**
  44. * Backwards compatibility wrapper for Validation::notBlank().
  45. *
  46. * @param string|array $check Value to check.
  47. * @return bool Success.
  48. * @deprecated 3.0.2 Use Validation::notBlank() instead.
  49. * @see Validation::notBlank()
  50. */
  51. public function notEmpty($check)
  52. {
  53. trigger_error('Validation::notEmpty() is deprecated. Use Validation::notBlank() instead.', E_USER_DEPRECATED);
  54. return static::notBlank($check);
  55. }
  56. /**
  57. * Checks that a string contains something other than whitespace
  58. *
  59. * Returns true if string contains something other than whitespace
  60. *
  61. * $check can be passed as an array:
  62. * ['check' => 'valueToCheck'];
  63. *
  64. * @param string|array $check Value to check
  65. * @return bool Success
  66. */
  67. public static function notBlank($check)
  68. {
  69. if (is_array($check)) {
  70. extract(static::_defaults($check));
  71. }
  72. if (empty($check) && $check != '0') {
  73. return false;
  74. }
  75. return static::_check($check, '/[^\s]+/m');
  76. }
  77. /**
  78. * Checks that a string contains only integer or letters
  79. *
  80. * Returns true if string contains only integer or letters
  81. *
  82. * $check can be passed as an array:
  83. * ['check' => 'valueToCheck'];
  84. *
  85. * @param string|array $check Value to check
  86. * @return bool Success
  87. */
  88. public static function alphaNumeric($check)
  89. {
  90. if (is_array($check)) {
  91. extract(static::_defaults($check));
  92. }
  93. if (empty($check) && $check != '0') {
  94. return false;
  95. }
  96. return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du');
  97. }
  98. /**
  99. * Checks that a string length is within specified range.
  100. * Spaces are included in the character count.
  101. * Returns true if string matches value min, max, or between min and max,
  102. *
  103. * @param string $check Value to check for length
  104. * @param int $min Minimum value in range (inclusive)
  105. * @param int $max Maximum value in range (inclusive)
  106. * @return bool Success
  107. */
  108. public static function lengthBetween($check, $min, $max)
  109. {
  110. $length = mb_strlen($check);
  111. return ($length >= $min && $length <= $max);
  112. }
  113. /**
  114. * Returns true if field is left blank -OR- only whitespace characters are present in its value
  115. * Whitespace characters include Space, Tab, Carriage Return, Newline
  116. *
  117. * $check can be passed as an array:
  118. * ['check' => 'valueToCheck'];
  119. *
  120. * @param string|array $check Value to check
  121. * @return bool Success
  122. */
  123. public static function blank($check)
  124. {
  125. if (is_array($check)) {
  126. extract(static::_defaults($check));
  127. }
  128. return !static::_check($check, '/[^\\s]/');
  129. }
  130. /**
  131. * Validation of credit card numbers.
  132. * Returns true if $check is in the proper credit card format.
  133. *
  134. * @param string|array $check credit card number to validate
  135. * @param string|array $type 'all' may be passed as a string, defaults to fast which checks format of most major credit cards
  136. * if an array is used only the values of the array are checked.
  137. * Example: ['amex', 'bankcard', 'maestro']
  138. * @param bool $deep set to true this will check the Luhn algorithm of the credit card.
  139. * @param string|null $regex A custom regex can also be passed, this will be used instead of the defined regex values
  140. * @return bool Success
  141. * @see Validation::luhn()
  142. */
  143. public static function cc($check, $type = 'fast', $deep = false, $regex = null)
  144. {
  145. if (is_array($check)) {
  146. extract(static::_defaults($check));
  147. }
  148. $check = str_replace(['-', ' '], '', $check);
  149. if (mb_strlen($check) < 13) {
  150. return false;
  151. }
  152. if ($regex !== null) {
  153. if (static::_check($check, $regex)) {
  154. return static::luhn($check, $deep);
  155. }
  156. }
  157. $cards = [
  158. 'all' => [
  159. 'amex' => '/^3[4|7]\\d{13}$/',
  160. 'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
  161. 'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
  162. 'disc' => '/^(?:6011|650\\d)\\d{12}$/',
  163. 'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
  164. 'enroute' => '/^2(?:014|149)\\d{11}$/',
  165. 'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/',
  166. 'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/',
  167. 'mc' => '/^5[1-5]\\d{14}$/',
  168. 'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
  169. 'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
  170. 'visa' => '/^4\\d{12}(\\d{3})?$/',
  171. 'voyager' => '/^8699[0-9]{11}$/'
  172. ],
  173. 'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'
  174. ];
  175. if (is_array($type)) {
  176. foreach ($type as $value) {
  177. $regex = $cards['all'][strtolower($value)];
  178. if (static::_check($check, $regex)) {
  179. return static::luhn($check, $deep);
  180. }
  181. }
  182. } elseif ($type === 'all') {
  183. foreach ($cards['all'] as $value) {
  184. $regex = $value;
  185. if (static::_check($check, $regex)) {
  186. return static::luhn($check, $deep);
  187. }
  188. }
  189. } else {
  190. $regex = $cards['fast'];
  191. if (static::_check($check, $regex)) {
  192. return static::luhn($check, $deep);
  193. }
  194. }
  195. return false;
  196. }
  197. /**
  198. * Used to compare 2 numeric values.
  199. *
  200. * @param string|array $check1 if string is passed for, a string must also be passed for $check2
  201. * used as an array it must be passed as ['check1' => value, 'operator' => 'value', 'check2' => value]
  202. * @param string $operator Can be either a word or operand
  203. * is greater >, is less <, greater or equal >=
  204. * less or equal <=, is less <, equal to ==, not equal !=
  205. * @param int $check2 only needed if $check1 is a string
  206. * @return bool Success
  207. */
  208. public static function comparison($check1, $operator = null, $check2 = null)
  209. {
  210. if (is_array($check1)) {
  211. extract($check1, EXTR_OVERWRITE);
  212. }
  213. $operator = str_replace([' ', "\t", "\n", "\r", "\0", "\x0B"], '', strtolower($operator));
  214. switch ($operator) {
  215. case 'isgreater':
  216. case '>':
  217. if ($check1 > $check2) {
  218. return true;
  219. }
  220. break;
  221. case 'isless':
  222. case '<':
  223. if ($check1 < $check2) {
  224. return true;
  225. }
  226. break;
  227. case 'greaterorequal':
  228. case '>=':
  229. if ($check1 >= $check2) {
  230. return true;
  231. }
  232. break;
  233. case 'lessorequal':
  234. case '<=':
  235. if ($check1 <= $check2) {
  236. return true;
  237. }
  238. break;
  239. case 'equalto':
  240. case '==':
  241. if ($check1 == $check2) {
  242. return true;
  243. }
  244. break;
  245. case 'notequal':
  246. case '!=':
  247. if ($check1 != $check2) {
  248. return true;
  249. }
  250. break;
  251. default:
  252. static::$errors[] = 'You must define the $operator parameter for Validation::comparison()';
  253. }
  254. return false;
  255. }
  256. /**
  257. * Compare one field to another.
  258. *
  259. * If both fields have exactly the same value this method will return true.
  260. *
  261. * @param mixed $check The value to find in $field.
  262. * @param string $field The field to check $check against. This field must be present in $context.
  263. * @param array $context The validation context.
  264. * @return bool
  265. */
  266. public static function compareWith($check, $field, $context)
  267. {
  268. if (!isset($context['data'][$field])) {
  269. return false;
  270. }
  271. return $context['data'][$field] === $check;
  272. }
  273. /**
  274. * Used when a custom regular expression is needed.
  275. *
  276. * @param string|array $check When used as a string, $regex must also be a valid regular expression.
  277. * As and array: ['check' => value, 'regex' => 'valid regular expression']
  278. * @param string|null $regex If $check is passed as a string, $regex must also be set to valid regular expression
  279. * @return bool Success
  280. */
  281. public static function custom($check, $regex = null)
  282. {
  283. if (is_array($check)) {
  284. extract(static::_defaults($check));
  285. }
  286. if ($regex === null) {
  287. static::$errors[] = 'You must define a regular expression for Validation::custom()';
  288. return false;
  289. }
  290. return static::_check($check, $regex);
  291. }
  292. /**
  293. * Date validation, determines if the string passed is a valid date.
  294. * keys that expect full month, day and year will validate leap years.
  295. *
  296. * Years are valid from 1800 to 2999.
  297. *
  298. * ### Formats:
  299. *
  300. * - `dmy` 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
  301. * - `mdy` 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
  302. * - `ymd` 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
  303. * - `dMy` 27 December 2006 or 27 Dec 2006
  304. * - `Mdy` December 27, 2006 or Dec 27, 2006 comma is optional
  305. * - `My` December 2006 or Dec 2006
  306. * - `my` 12/2006 or 12/06 separators can be a space, period, dash, forward slash
  307. * - `ym` 2006/12 or 06/12 separators can be a space, period, dash, forward slash
  308. * - `y` 2006 just the year without any separators
  309. *
  310. * @param string|\DateTime $check a valid date string/object
  311. * @param string|array $format Use a string or an array of the keys above.
  312. * Arrays should be passed as ['dmy', 'mdy', etc]
  313. * @param string|null $regex If a custom regular expression is used this is the only validation that will occur.
  314. * @return bool Success
  315. */
  316. public static function date($check, $format = 'ymd', $regex = null)
  317. {
  318. if ($check instanceof \DateTime) {
  319. return true;
  320. }
  321. if (is_array($check)) {
  322. $check = static::_getDateString($check);
  323. $format = 'ymd';
  324. }
  325. if ($regex !== null) {
  326. return static::_check($check, $regex);
  327. }
  328. $month = '(0[123456789]|10|11|12)';
  329. $separator = '([- /.])';
  330. $fourDigitYear = '(([1][8-9][0-9][0-9])|([2][0-9][0-9][0-9]))';
  331. $twoDigitYear = '([0-9]{2})';
  332. $year = '(?:' . $fourDigitYear . '|' . $twoDigitYear . ')';
  333. $regex['dmy'] = '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)' .
  334. $separator . '(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29' .
  335. $separator . '0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])' .
  336. $separator . '(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  337. $regex['mdy'] = '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|1[0-2])' .
  338. $separator . '(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:0?2' . $separator . '29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))' .
  339. $separator . '(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  340. $regex['ymd'] = '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))' .
  341. $separator . '(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})' .
  342. $separator . '(?:(?:(?:0?[13578]|1[02])\\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])\\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\\2(?:0?[1-9]|1\\d|2[0-8]))))$%';
  343. $regex['dMy'] = '/^((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\ Feb(ruary)?\\ (((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]|[2-9]\\d)\\d{2})$/';
  344. $regex['Mdy'] = '/^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep)(tember)?|(Nov|Dec)(ember)?)\\ (0?[1-9]|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,?\\ ((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))))\\,?\\ ((1[6-9]|[2-9]\\d)\\d{2}))$/';
  345. $regex['My'] = '%^(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)' .
  346. $separator . '((1[6-9]|[2-9]\\d)\\d{2})$%';
  347. $regex['my'] = '%^(' . $month . $separator . $year . ')$%';
  348. $regex['ym'] = '%^(' . $year . $separator . $month . ')$%';
  349. $regex['y'] = '%^(' . $fourDigitYear . ')$%';
  350. $format = (is_array($format)) ? array_values($format) : [$format];
  351. foreach ($format as $key) {
  352. if (static::_check($check, $regex[$key]) === true) {
  353. return true;
  354. }
  355. }
  356. return false;
  357. }
  358. /**
  359. * Validates a datetime value
  360. *
  361. * All values matching the "date" core validation rule, and the "time" one will be valid
  362. *
  363. * @param string|\DateTime $check Value to check
  364. * @param string|array $dateFormat Format of the date part. See Validation::date for more information.
  365. * @param string|null $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur.
  366. * @return bool True if the value is valid, false otherwise
  367. * @see Validation::date
  368. * @see Validation::time
  369. */
  370. public static function datetime($check, $dateFormat = 'ymd', $regex = null)
  371. {
  372. if ($check instanceof \DateTime) {
  373. return true;
  374. }
  375. $valid = false;
  376. if (is_array($check)) {
  377. $check = static::_getDateString($check);
  378. $dateFormat = 'ymd';
  379. }
  380. $parts = explode(' ', $check);
  381. if (!empty($parts) && count($parts) > 1) {
  382. $time = array_pop($parts);
  383. $date = implode(' ', $parts);
  384. $valid = static::date($date, $dateFormat, $regex) && static::time($time);
  385. }
  386. return $valid;
  387. }
  388. /**
  389. * Time validation, determines if the string passed is a valid time.
  390. * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m)
  391. * Does not allow/validate seconds.
  392. *
  393. * @param string|\DateTime $check a valid time string/object
  394. * @return bool Success
  395. */
  396. public static function time($check)
  397. {
  398. if ($check instanceof \DateTime) {
  399. return true;
  400. }
  401. if (is_array($check)) {
  402. $check = static::_getDateString($check);
  403. }
  404. return static::_check($check, '%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%');
  405. }
  406. /**
  407. * Boolean validation, determines if value passed is a boolean integer or true/false.
  408. *
  409. * @param string $check a valid boolean
  410. * @return bool Success
  411. */
  412. public static function boolean($check)
  413. {
  414. $booleanList = [0, 1, '0', '1', true, false];
  415. return in_array($check, $booleanList, true);
  416. }
  417. /**
  418. * Checks that a value is a valid decimal. Both the sign and exponent are optional.
  419. *
  420. * Valid Places:
  421. *
  422. * - null => Any number of decimal places, including none. The '.' is not required.
  423. * - true => Any number of decimal places greater than 0, or a float|double. The '.' is required.
  424. * - 1..N => Exactly that many number of decimal places. The '.' is required.
  425. *
  426. * @param float $check The value the test for decimal.
  427. * @param int $places Decimal places.
  428. * @param string|null $regex If a custom regular expression is used, this is the only validation that will occur.
  429. * @return bool Success
  430. */
  431. public static function decimal($check, $places = null, $regex = null)
  432. {
  433. if ($regex === null) {
  434. $lnum = '[0-9]+';
  435. $dnum = "[0-9]*[\.]{$lnum}";
  436. $sign = '[+-]?';
  437. $exp = "(?:[eE]{$sign}{$lnum})?";
  438. if ($places === null) {
  439. $regex = "/^{$sign}(?:{$lnum}|{$dnum}){$exp}$/";
  440. } elseif ($places === true) {
  441. if (is_float($check) && floor($check) === $check) {
  442. $check = sprintf("%.1f", $check);
  443. }
  444. $regex = "/^{$sign}{$dnum}{$exp}$/";
  445. } elseif (is_numeric($places)) {
  446. $places = '[0-9]{' . $places . '}';
  447. $dnum = "(?:[0-9]*[\.]{$places}|{$lnum}[\.]{$places})";
  448. $regex = "/^{$sign}{$dnum}{$exp}$/";
  449. }
  450. }
  451. // account for localized floats.
  452. $locale = ini_get('intl.default_locale') ?: 'en_US';
  453. $formatter = new NumberFormatter($locale, NumberFormatter::DECIMAL);
  454. $decimalPoint = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
  455. $groupingSep = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
  456. $check = str_replace($groupingSep, '', $check);
  457. $check = str_replace($decimalPoint, '.', $check);
  458. return static::_check($check, $regex);
  459. }
  460. /**
  461. * Validates for an email address.
  462. *
  463. * Only uses getmxrr() checking for deep validation, or
  464. * any PHP version on a non-windows distribution
  465. *
  466. * @param string $check Value to check
  467. * @param bool $deep Perform a deeper validation (if true), by also checking availability of host
  468. * @param string $regex Regex to use (if none it will use built in regex)
  469. * @return bool Success
  470. */
  471. public static function email($check, $deep = false, $regex = null)
  472. {
  473. if (is_array($check)) {
  474. extract(static::_defaults($check));
  475. }
  476. if ($regex === null) {
  477. $regex = '/^[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+)*@' . self::$_pattern['hostname'] . '$/ui';
  478. }
  479. $return = static::_check($check, $regex);
  480. if ($deep === false || $deep === null) {
  481. return $return;
  482. }
  483. if ($return === true && preg_match('/@(' . static::$_pattern['hostname'] . ')$/i', $check, $regs)) {
  484. if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) {
  485. return true;
  486. }
  487. if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) {
  488. return true;
  489. }
  490. return is_array(gethostbynamel($regs[1]));
  491. }
  492. return false;
  493. }
  494. /**
  495. * Checks that value is exactly $comparedTo.
  496. *
  497. * @param mixed $check Value to check
  498. * @param mixed $comparedTo Value to compare
  499. * @return bool Success
  500. */
  501. public static function equalTo($check, $comparedTo)
  502. {
  503. return ($check === $comparedTo);
  504. }
  505. /**
  506. * Checks that value has a valid file extension.
  507. *
  508. * @param string|array $check Value to check
  509. * @param array $extensions file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg'
  510. * @return bool Success
  511. */
  512. public static function extension($check, $extensions = ['gif', 'jpeg', 'png', 'jpg'])
  513. {
  514. if (is_array($check)) {
  515. return static::extension(array_shift($check), $extensions);
  516. }
  517. $extension = strtolower(pathinfo($check, PATHINFO_EXTENSION));
  518. foreach ($extensions as $value) {
  519. if ($extension === strtolower($value)) {
  520. return true;
  521. }
  522. }
  523. return false;
  524. }
  525. /**
  526. * Validation of an IP address.
  527. *
  528. * @param string $check The string to test.
  529. * @param string $type The IP Protocol version to validate against
  530. * @return bool Success
  531. */
  532. public static function ip($check, $type = 'both')
  533. {
  534. $type = strtolower($type);
  535. $flags = 0;
  536. if ($type === 'ipv4') {
  537. $flags = FILTER_FLAG_IPV4;
  538. }
  539. if ($type === 'ipv6') {
  540. $flags = FILTER_FLAG_IPV6;
  541. }
  542. return (bool)filter_var($check, FILTER_VALIDATE_IP, ['flags' => $flags]);
  543. }
  544. /**
  545. * Checks whether the length of a string is greater or equal to a minimal length.
  546. *
  547. * @param string $check The string to test
  548. * @param int $min The minimal string length
  549. * @return bool Success
  550. */
  551. public static function minLength($check, $min)
  552. {
  553. return mb_strlen($check) >= $min;
  554. }
  555. /**
  556. * Checks whether the length of a string is smaller or equal to a maximal length..
  557. *
  558. * @param string $check The string to test
  559. * @param int $max The maximal string length
  560. * @return bool Success
  561. */
  562. public static function maxLength($check, $max)
  563. {
  564. return mb_strlen($check) <= $max;
  565. }
  566. /**
  567. * Checks that a value is a monetary amount.
  568. *
  569. * @param string $check Value to check
  570. * @param string $symbolPosition Where symbol is located (left/right)
  571. * @return bool Success
  572. */
  573. public static function money($check, $symbolPosition = 'left')
  574. {
  575. $money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{1,2})?';
  576. if ($symbolPosition === 'right') {
  577. $regex = '/^' . $money . '(?<!\x{00a2})\p{Sc}?$/u';
  578. } else {
  579. $regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u';
  580. }
  581. return static::_check($check, $regex);
  582. }
  583. /**
  584. * Validates a multiple select. Comparison is case sensitive by default.
  585. *
  586. * Valid Options
  587. *
  588. * - in => provide a list of choices that selections must be made from
  589. * - max => maximum number of non-zero choices that can be made
  590. * - min => minimum number of non-zero choices that can be made
  591. *
  592. * @param array $check Value to check
  593. * @param array $options Options for the check.
  594. * @param bool $caseInsensitive Set to true for case insensitive comparison.
  595. * @return bool Success
  596. */
  597. public static function multiple($check, array $options = [], $caseInsensitive = false)
  598. {
  599. $defaults = ['in' => null, 'max' => null, 'min' => null];
  600. $options += $defaults;
  601. $check = array_filter((array)$check);
  602. if (empty($check)) {
  603. return false;
  604. }
  605. if ($options['max'] && count($check) > $options['max']) {
  606. return false;
  607. }
  608. if ($options['min'] && count($check) < $options['min']) {
  609. return false;
  610. }
  611. if ($options['in'] && is_array($options['in'])) {
  612. if ($caseInsensitive) {
  613. $options['in'] = array_map('mb_strtolower', $options['in']);
  614. }
  615. foreach ($check as $val) {
  616. $strict = !is_numeric($val);
  617. if ($caseInsensitive) {
  618. $val = mb_strtolower($val);
  619. }
  620. if (!in_array((string)$val, $options['in'], $strict)) {
  621. return false;
  622. }
  623. }
  624. }
  625. return true;
  626. }
  627. /**
  628. * Checks if a value is numeric.
  629. *
  630. * @param string $check Value to check
  631. * @return bool Success
  632. */
  633. public static function numeric($check)
  634. {
  635. return is_numeric($check);
  636. }
  637. /**
  638. * Checks if a value is a natural number.
  639. *
  640. * @param string $check Value to check
  641. * @param bool $allowZero Set true to allow zero, defaults to false
  642. * @return bool Success
  643. * @see http://en.wikipedia.org/wiki/Natural_number
  644. */
  645. public static function naturalNumber($check, $allowZero = false)
  646. {
  647. $regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
  648. return static::_check($check, $regex);
  649. }
  650. /**
  651. * Validates that a number is in specified range.
  652. *
  653. * If $lower and $upper are set, the range is inclusive.
  654. * If they are not set, will return true if $check is a
  655. * legal finite on this platform.
  656. *
  657. * @param string $check Value to check
  658. * @param int|float|null $lower Lower limit
  659. * @param int|float|null $upper Upper limit
  660. * @return bool Success
  661. */
  662. public static function range($check, $lower = null, $upper = null)
  663. {
  664. if (!is_numeric($check)) {
  665. return false;
  666. }
  667. if (isset($lower) && isset($upper)) {
  668. return ($check >= $lower && $check <= $upper);
  669. }
  670. return is_finite($check);
  671. }
  672. /**
  673. * Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt
  674. *
  675. * The regex checks for the following component parts:
  676. *
  677. * - a valid, optional, scheme
  678. * - a valid ip address OR
  679. * a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt
  680. * with an optional port number
  681. * - an optional valid path
  682. * - an optional query string (get parameters)
  683. * - an optional fragment (anchor tag)
  684. *
  685. * @param string $check Value to check
  686. * @param bool $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
  687. * @return bool Success
  688. */
  689. public static function url($check, $strict = false)
  690. {
  691. static::_populateIp();
  692. $validChars = '([' . preg_quote('!"$&\'()*+,-.@_:;=~[]') . '\/0-9\p{L}\p{N}]|(%[0-9a-f]{2}))';
  693. $regex = '/^(?:(?:https?|ftps?|sftp|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') .
  694. '(?:' . static::$_pattern['IPv4'] . '|\[' . static::$_pattern['IPv6'] . '\]|' . static::$_pattern['hostname'] . ')(?::[1-9][0-9]{0,4})?' .
  695. '(?:\/?|\/' . $validChars . '*)?' .
  696. '(?:\?' . $validChars . '*)?' .
  697. '(?:#' . $validChars . '*)?$/iu';
  698. return static::_check($check, $regex);
  699. }
  700. /**
  701. * Checks if a value is in a given list. Comparison is case sensitive by default.
  702. *
  703. * @param string $check Value to check.
  704. * @param array $list List to check against.
  705. * @param bool $caseInsensitive Set to true for case insensitive comparison.
  706. * @return bool Success.
  707. */
  708. public static function inList($check, array $list, $caseInsensitive = false)
  709. {
  710. if ($caseInsensitive) {
  711. $list = array_map('mb_strtolower', $list);
  712. $check = mb_strtolower($check);
  713. } else {
  714. $list = array_map('strval', $list);
  715. }
  716. return in_array((string)$check, $list, true);
  717. }
  718. /**
  719. * Runs an user-defined validation.
  720. *
  721. * @param string|array $check value that will be validated in user-defined methods.
  722. * @param object $object class that holds validation method
  723. * @param string $method class method name for validation to run
  724. * @param array|null $args arguments to send to method
  725. * @return mixed user-defined class class method returns
  726. */
  727. public static function userDefined($check, $object, $method, $args = null)
  728. {
  729. return call_user_func_array([$object, $method], [$check, $args]);
  730. }
  731. /**
  732. * Checks that a value is a valid UUID - http://tools.ietf.org/html/rfc4122
  733. *
  734. * @param string $check Value to check
  735. * @return bool Success
  736. */
  737. public static function uuid($check)
  738. {
  739. $regex = '/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[0-5][a-fA-F0-9]{3}-[089aAbB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/';
  740. return self::_check($check, $regex);
  741. }
  742. /**
  743. * Runs a regular expression match.
  744. *
  745. * @param string $check Value to check against the $regex expression
  746. * @param string $regex Regular expression
  747. * @return bool Success of match
  748. */
  749. protected static function _check($check, $regex)
  750. {
  751. if (is_string($regex) && preg_match($regex, $check)) {
  752. return true;
  753. }
  754. return false;
  755. }
  756. /**
  757. * Get the values to use when value sent to validation method is
  758. * an array.
  759. *
  760. * @param array $params Parameters sent to validation method
  761. * @return array
  762. */
  763. protected static function _defaults($params)
  764. {
  765. static::_reset();
  766. $defaults = [
  767. 'check' => null,
  768. 'regex' => null,
  769. 'country' => null,
  770. 'deep' => false,
  771. 'type' => null
  772. ];
  773. $params += $defaults;
  774. if ($params['country'] !== null) {
  775. $params['country'] = mb_strtolower($params['country']);
  776. }
  777. return $params;
  778. }
  779. /**
  780. * Luhn algorithm
  781. *
  782. * @param string|array $check Value to check.
  783. * @param bool $deep If true performs deep check.
  784. * @return bool Success
  785. * @see http://en.wikipedia.org/wiki/Luhn_algorithm
  786. */
  787. public static function luhn($check, $deep = false)
  788. {
  789. if (is_array($check)) {
  790. extract(static::_defaults($check));
  791. }
  792. if ($deep !== true) {
  793. return true;
  794. }
  795. if ((int)$check === 0) {
  796. return false;
  797. }
  798. $sum = 0;
  799. $length = strlen($check);
  800. for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
  801. $sum += $check[$position];
  802. }
  803. for ($position = ($length % 2); $position < $length; $position += 2) {
  804. $number = $check[$position] * 2;
  805. $sum += ($number < 10) ? $number : $number - 9;
  806. }
  807. return ($sum % 10 === 0);
  808. }
  809. /**
  810. * Checks the mime type of a file.
  811. *
  812. * @param string|array $check Value to check.
  813. * @param array|string $mimeTypes Array of mime types or regex pattern to check.
  814. * @return bool Success
  815. * @throws \RuntimeException when mime type can not be determined.
  816. * @throws \LogicException when ext/fileinfo is missing
  817. */
  818. public static function mimeType($check, $mimeTypes = [])
  819. {
  820. if (is_array($check) && isset($check['tmp_name'])) {
  821. $check = $check['tmp_name'];
  822. }
  823. if (!function_exists('finfo_open')) {
  824. throw new LogicException('ext/fileinfo is required for validating file mime types');
  825. }
  826. if (!is_file($check)) {
  827. throw new RuntimeException('Cannot validate mimetype for a missing file');
  828. }
  829. $finfo = finfo_open(FILEINFO_MIME);
  830. $finfo = finfo_file($finfo, $check);
  831. if (!$finfo) {
  832. throw new RuntimeException('Can not determine the mimetype.');
  833. }
  834. list($mime) = explode(';', $finfo);
  835. if (is_string($mimeTypes)) {
  836. return self::_check($mime, $mimeTypes);
  837. }
  838. foreach ($mimeTypes as $key => $val) {
  839. $mimeTypes[$key] = strtolower($val);
  840. }
  841. return in_array($mime, $mimeTypes);
  842. }
  843. /**
  844. * Checks the filesize
  845. *
  846. * @param string|array $check Value to check.
  847. * @param string|null $operator See `Validation::comparison()`.
  848. * @param int|string|null $size Size in bytes or human readable string like '5MB'.
  849. * @return bool Success
  850. */
  851. public static function fileSize($check, $operator = null, $size = null)
  852. {
  853. if (is_array($check) && isset($check['tmp_name'])) {
  854. $check = $check['tmp_name'];
  855. }
  856. if (is_string($size)) {
  857. $size = Text::parseFileSize($size);
  858. }
  859. $filesize = filesize($check);
  860. return static::comparison($filesize, $operator, $size);
  861. }
  862. /**
  863. * Checking for upload errors
  864. *
  865. * @param string|array $check Value to check.
  866. * @param bool $allowNoFile Set to true to allow UPLOAD_ERR_NO_FILE as a pass.
  867. * @return bool
  868. * @see http://www.php.net/manual/en/features.file-upload.errors.php
  869. */
  870. public static function uploadError($check, $allowNoFile = false)
  871. {
  872. if (is_array($check) && isset($check['error'])) {
  873. $check = $check['error'];
  874. }
  875. if ($allowNoFile) {
  876. return in_array((int)$check, [UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE], true);
  877. }
  878. return (int)$check === UPLOAD_ERR_OK;
  879. }
  880. /**
  881. * Validate an uploaded file.
  882. *
  883. * Helps join `uploadError`, `fileSize` and `mimeType` into
  884. * one higher level validation method.
  885. *
  886. * ### Options
  887. *
  888. * - `types` - An array of valid mime types. If empty all types
  889. * will be accepted. The `type` will not be looked at, instead
  890. * the file type will be checked with ext/finfo.
  891. * - `minSize` - The minimum file size in bytes. Defaults to not checking.
  892. * - `maxSize` - The maximum file size in bytes. Defaults to not checking.
  893. * - `optional` - Whether or not this file is optional. Defaults to false.
  894. * If true a missing file will pass the validator regardless of other constraints.
  895. *
  896. * @param array $file The uploaded file data from PHP.
  897. * @param array $options An array of options for the validation.
  898. * @return bool
  899. */
  900. public static function uploadedFile($file, array $options = [])
  901. {
  902. $options += [
  903. 'minSize' => null,
  904. 'maxSize' => null,
  905. 'types' => null,
  906. 'optional' => false,
  907. ];
  908. if (!is_array($file)) {
  909. return false;
  910. }
  911. $keys = ['error', 'name', 'size', 'tmp_name', 'type'];
  912. ksort($file);
  913. if (array_keys($file) != $keys) {
  914. return false;
  915. }
  916. if (!static::uploadError($file, $options['optional'])) {
  917. return false;
  918. }
  919. if ($options['optional'] && (int)$file['error'] === UPLOAD_ERR_NO_FILE) {
  920. return true;
  921. }
  922. if (isset($options['minSize']) && !static::fileSize($file, '>=', $options['minSize'])) {
  923. return false;
  924. }
  925. if (isset($options['maxSize']) && !static::fileSize($file, '<=', $options['maxSize'])) {
  926. return false;
  927. }
  928. if (isset($options['types']) && !static::mimeType($file, $options['types'])) {
  929. return false;
  930. }
  931. return true;
  932. }
  933. /**
  934. * Converts an array representing a date or datetime into a ISO string.
  935. * The arrays are typically sent for validation from a form generated by
  936. * the CakePHP FormHelper.
  937. *
  938. * @param array $value The array representing a date or datetime.
  939. * @return string
  940. */
  941. protected static function _getDateString($value)
  942. {
  943. $formatted = '';
  944. if (isset($value['year'], $value['month'], $value['day']) &&
  945. (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
  946. ) {
  947. $formatted .= sprintf('%d-%02d-%02d ', $value['year'], $value['month'], $value['day']);
  948. }
  949. if (isset($value['hour'])) {
  950. if (isset($value['meridian'])) {
  951. $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
  952. }
  953. $value += ['minute' => 0, 'second' => 0];
  954. if (is_numeric($value['hour']) && is_numeric($value['minute']) && is_numeric($value['second'])) {
  955. $formatted .= sprintf('%02d:%02d:%02d', $value['hour'], $value['minute'], $value['second']);
  956. }
  957. }
  958. return trim($formatted);
  959. }
  960. /**
  961. * Lazily populate the IP address patterns used for validations
  962. *
  963. * @return void
  964. */
  965. protected static function _populateIp()
  966. {
  967. if (!isset(static::$_pattern['IPv6'])) {
  968. $pattern = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}';
  969. $pattern .= '(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})';
  970. $pattern .= '|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})';
  971. $pattern .= '(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)';
  972. $pattern .= '{4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
  973. $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}';
  974. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|';
  975. $pattern .= '((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}';
  976. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
  977. $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4})';
  978. $pattern .= '{0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)';
  979. $pattern .= '|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]';
  980. $pattern .= '\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4})';
  981. $pattern .= '{1,2})))|(((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))(%.+)?';
  982. static::$_pattern['IPv6'] = $pattern;
  983. }
  984. if (!isset(static::$_pattern['IPv4'])) {
  985. $pattern = '(?:(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])';
  986. static::$_pattern['IPv4'] = $pattern;
  987. }
  988. }
  989. /**
  990. * Reset internal variables for another validation run.
  991. *
  992. * @return void
  993. */
  994. protected static function _reset()
  995. {
  996. static::$errors = [];
  997. }
  998. }