Validation.php 33 KB

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