Validation.php 32 KB

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