Validation.php 32 KB

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