Validation.php 37 KB

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