Validation.php 44 KB

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