Validation.php 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license https://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 InvalidArgumentException;
  20. use LogicException;
  21. use NumberFormatter;
  22. use Psr\Http\Message\UploadedFileInterface;
  23. use RuntimeException;
  24. /**
  25. * Validation Class. Used for validation of model data
  26. *
  27. * Offers different validation methods.
  28. */
  29. class Validation
  30. {
  31. /**
  32. * Default locale
  33. */
  34. const DEFAULT_LOCALE = 'en_US';
  35. /**
  36. * Same as operator.
  37. */
  38. const COMPARE_SAME = '===';
  39. /**
  40. * Not same as comparison operator.
  41. */
  42. const COMPARE_NOT_SAME = '!==';
  43. /**
  44. * Equal to comparison operator.
  45. */
  46. const COMPARE_EQUAL = '==';
  47. /**
  48. * Not equal to comparison operator.
  49. */
  50. const COMPARE_NOT_EQUAL = '!=';
  51. /**
  52. * Greater than comparison operator.
  53. */
  54. const COMPARE_GREATER = '>';
  55. /**
  56. * Greater than or equal to comparison operator.
  57. */
  58. const COMPARE_GREATER_OR_EQUAL = '>=';
  59. /**
  60. * Less than comparison operator.
  61. */
  62. const COMPARE_LESS = '<';
  63. /**
  64. * Less than or equal to comparison operator.
  65. */
  66. const COMPARE_LESS_OR_EQUAL = '<=';
  67. /**
  68. * Some complex patterns needed in multiple places
  69. *
  70. * @var array
  71. */
  72. protected static $_pattern = [
  73. '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,})',
  74. 'latitude' => '[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)',
  75. 'longitude' => '[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)',
  76. ];
  77. /**
  78. * Holds an array of errors messages set in this class.
  79. * These are used for debugging purposes
  80. *
  81. * @var array
  82. */
  83. public static $errors = [];
  84. /**
  85. * Backwards compatibility wrapper for Validation::notBlank().
  86. *
  87. * @param string $check Value to check.
  88. * @return bool Success.
  89. * @deprecated 3.0.2 Use Validation::notBlank() instead.
  90. * @see \Cake\Validation\Validation::notBlank()
  91. */
  92. public static function notEmpty($check)
  93. {
  94. deprecationWarning(
  95. 'Validation::notEmpty() is deprecated. ' .
  96. 'Use Validation::notBlank() instead.'
  97. );
  98. return static::notBlank($check);
  99. }
  100. /**
  101. * Checks that a string contains something other than whitespace
  102. *
  103. * Returns true if string contains something other than whitespace
  104. *
  105. * @param string $check Value to check
  106. * @return bool Success
  107. */
  108. public static function notBlank($check)
  109. {
  110. if (empty($check) && !is_bool($check) && !is_numeric($check)) {
  111. return false;
  112. }
  113. return static::_check($check, '/[^\s]+/m');
  114. }
  115. /**
  116. * Checks that a string contains only integer or letters
  117. *
  118. * Returns true if string contains only integer or letters
  119. *
  120. * @param string $check Value to check
  121. * @return bool Success
  122. */
  123. public static function alphaNumeric($check)
  124. {
  125. if (empty($check) && $check !== '0') {
  126. return false;
  127. }
  128. return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du');
  129. }
  130. /**
  131. * Checks that a string length is within specified range.
  132. * Spaces are included in the character count.
  133. * Returns true if string matches value min, max, or between min and max,
  134. *
  135. * @param string $check Value to check for length
  136. * @param int $min Minimum value in range (inclusive)
  137. * @param int $max Maximum value in range (inclusive)
  138. * @return bool Success
  139. */
  140. public static function lengthBetween($check, $min, $max)
  141. {
  142. if (!is_string($check)) {
  143. return false;
  144. }
  145. $length = mb_strlen($check);
  146. return ($length >= $min && $length <= $max);
  147. }
  148. /**
  149. * Returns true if field is left blank -OR- only whitespace characters are present in its value
  150. * Whitespace characters include Space, Tab, Carriage Return, Newline
  151. *
  152. * @param string $check Value to check
  153. * @return bool Success
  154. * @deprecated 3.0.2 Validation::blank() is deprecated.
  155. */
  156. public static function blank($check)
  157. {
  158. deprecationWarning(
  159. 'Validation::blank() is deprecated.'
  160. );
  161. return !static::_check($check, '/[^\\s]/');
  162. }
  163. /**
  164. * Backwards compatibility wrapper for Validation::creditCard().
  165. *
  166. * @param string $check credit card number to validate
  167. * @param string|array $type 'all' may be passed as a string, defaults to fast which checks format of most major credit cards
  168. * if an array is used only the values of the array are checked.
  169. * Example: ['amex', 'bankcard', 'maestro']
  170. * @param bool $deep set to true this will check the Luhn algorithm of the credit card.
  171. * @param string|null $regex A custom regex can also be passed, this will be used instead of the defined regex values
  172. * @return bool Success
  173. * @deprecated 3.7.0 Use Validation::creditCard() instead.
  174. * @see \Cake\Validation\Validation::creditCard()
  175. */
  176. public static function cc($check, $type = 'fast', $deep = false, $regex = null)
  177. {
  178. deprecationWarning(
  179. 'Validation::cc() is deprecated. ' .
  180. 'Use Validation::creditCard() instead.'
  181. );
  182. return static::creditCard($check, $type, $deep, $regex);
  183. }
  184. /**
  185. * Validation of credit card numbers.
  186. * Returns true if $check is in the proper credit card format.
  187. *
  188. * @param string $check credit card number to validate
  189. * @param string|array $type 'all' may be passed as a string, defaults to fast which checks format of most major credit cards
  190. * if an array is used only the values of the array are checked.
  191. * Example: ['amex', 'bankcard', 'maestro']
  192. * @param bool $deep set to true this will check the Luhn algorithm of the credit card.
  193. * @param string|null $regex A custom regex can also be passed, this will be used instead of the defined regex values
  194. * @return bool Success
  195. * @see \Cake\Validation\Validation::luhn()
  196. */
  197. public static function creditCard($check, $type = 'fast', $deep = false, $regex = null)
  198. {
  199. if (!is_scalar($check)) {
  200. return false;
  201. }
  202. $check = str_replace(['-', ' '], '', $check);
  203. if (mb_strlen($check) < 13) {
  204. return false;
  205. }
  206. if ($regex !== null && static::_check($check, $regex)) {
  207. return !$deep || static::luhn($check);
  208. }
  209. $cards = [
  210. 'all' => [
  211. 'amex' => '/^3[47]\\d{13}$/',
  212. 'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
  213. 'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
  214. 'disc' => '/^(?:6011|650\\d)\\d{12}$/',
  215. 'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
  216. 'enroute' => '/^2(?:014|149)\\d{11}$/',
  217. 'jcb' => '/^(3\\d{4}|2131|1800)\\d{11}$/',
  218. 'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/',
  219. 'mc' => '/^(5[1-5]\\d{14})|(2(?:22[1-9]|2[3-9][0-9]|[3-6][0-9]{2}|7[0-1][0-9]|720)\\d{12})$/',
  220. 'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
  221. '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})?)$/',
  222. 'visa' => '/^4\\d{12}(\\d{3})?$/',
  223. 'voyager' => '/^8699[0-9]{11}$/'
  224. ],
  225. '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})$/'
  226. ];
  227. if (is_array($type)) {
  228. foreach ($type as $value) {
  229. $regex = $cards['all'][strtolower($value)];
  230. if (static::_check($check, $regex)) {
  231. return static::luhn($check);
  232. }
  233. }
  234. } elseif ($type === 'all') {
  235. foreach ($cards['all'] as $value) {
  236. $regex = $value;
  237. if (static::_check($check, $regex)) {
  238. return static::luhn($check);
  239. }
  240. }
  241. } else {
  242. $regex = $cards['fast'];
  243. if (static::_check($check, $regex)) {
  244. return static::luhn($check);
  245. }
  246. }
  247. return false;
  248. }
  249. /**
  250. * Used to check the count of a given value of type array or Countable.
  251. *
  252. * @param array|\Countable $check The value to check the count on.
  253. * @param string $operator Can be either a word or operand
  254. * is greater >, is less <, greater or equal >=
  255. * less or equal <=, is less <, equal to ==, not equal !=
  256. * @param int $expectedCount The expected count value.
  257. * @return bool Success
  258. */
  259. public static function numElements($check, $operator, $expectedCount)
  260. {
  261. if (!is_array($check) && !$check instanceof \Countable) {
  262. return false;
  263. }
  264. return self::comparison(count($check), $operator, $expectedCount);
  265. }
  266. /**
  267. * Used to compare 2 numeric values.
  268. *
  269. * @param string $check1 The left value to compare.
  270. * @param string $operator Can be either a word or operand
  271. * is greater >, is less <, greater or equal >=
  272. * less or equal <=, is less <, equal to ==, not equal !=
  273. * @param int $check2 The right value to compare.
  274. * @return bool Success
  275. */
  276. public static function comparison($check1, $operator, $check2)
  277. {
  278. if ((float)$check1 != $check1) {
  279. return false;
  280. }
  281. $message = 'Operator `%s` is deprecated, use constant `Validation::%s` instead.';
  282. $operator = str_replace([' ', "\t", "\n", "\r", "\0", "\x0B"], '', strtolower($operator));
  283. switch ($operator) {
  284. case 'isgreater':
  285. /*
  286. * @deprecated 3.6.0 Use Validation::COMPARE_GREATER instead.
  287. */
  288. deprecationWarning(sprintf($message, $operator, 'COMPARE_GREATER'));
  289. // no break
  290. case static::COMPARE_GREATER:
  291. if ($check1 > $check2) {
  292. return true;
  293. }
  294. break;
  295. case 'isless':
  296. /*
  297. * @deprecated 3.6.0 Use Validation::COMPARE_LESS instead.
  298. */
  299. deprecationWarning(sprintf($message, $operator, 'COMPARE_LESS'));
  300. // no break
  301. case static::COMPARE_LESS:
  302. if ($check1 < $check2) {
  303. return true;
  304. }
  305. break;
  306. case 'greaterorequal':
  307. /*
  308. * @deprecated 3.6.0 Use Validation::COMPARE_GREATER_OR_EQUAL instead.
  309. */
  310. deprecationWarning(sprintf($message, $operator, 'COMPARE_GREATER_OR_EQUAL'));
  311. // no break
  312. case static::COMPARE_GREATER_OR_EQUAL:
  313. if ($check1 >= $check2) {
  314. return true;
  315. }
  316. break;
  317. case 'lessorequal':
  318. /*
  319. * @deprecated 3.6.0 Use Validation::COMPARE_LESS_OR_EQUAL instead.
  320. */
  321. deprecationWarning(sprintf($message, $operator, 'COMPARE_LESS_OR_EQUAL'));
  322. // no break
  323. case static::COMPARE_LESS_OR_EQUAL:
  324. if ($check1 <= $check2) {
  325. return true;
  326. }
  327. break;
  328. case 'equalto':
  329. /*
  330. * @deprecated 3.6.0 Use Validation::COMPARE_EQUAL instead.
  331. */
  332. deprecationWarning(sprintf($message, $operator, 'COMPARE_EQUAL'));
  333. // no break
  334. case static::COMPARE_EQUAL:
  335. if ($check1 == $check2) {
  336. return true;
  337. }
  338. break;
  339. case 'notequal':
  340. /*
  341. * @deprecated 3.6.0 Use Validation::COMPARE_NOT_EQUAL instead.
  342. */
  343. deprecationWarning(sprintf($message, $operator, 'COMPARE_NOT_EQUAL'));
  344. // no break
  345. case static::COMPARE_NOT_EQUAL:
  346. if ($check1 != $check2) {
  347. return true;
  348. }
  349. break;
  350. case static::COMPARE_SAME:
  351. if ($check1 === $check2) {
  352. return true;
  353. }
  354. break;
  355. case static::COMPARE_NOT_SAME:
  356. if ($check1 !== $check2) {
  357. return true;
  358. }
  359. break;
  360. default:
  361. static::$errors[] = 'You must define the $operator parameter for Validation::comparison()';
  362. }
  363. return false;
  364. }
  365. /**
  366. * Compare one field to another.
  367. *
  368. * If both fields have exactly the same value this method will return true.
  369. *
  370. * @param mixed $check The value to find in $field.
  371. * @param string $field The field to check $check against. This field must be present in $context.
  372. * @param array $context The validation context.
  373. * @return bool
  374. */
  375. public static function compareWith($check, $field, $context)
  376. {
  377. return self::compareFields($check, $field, static::COMPARE_SAME, $context);
  378. }
  379. /**
  380. * Compare one field to another.
  381. *
  382. * Return true if the comparison matches the expected result.
  383. *
  384. * @param mixed $check The value to find in $field.
  385. * @param string $field The field to check $check against. This field must be present in $context.
  386. * @param string $operator Comparison operator.
  387. * @param array $context The validation context.
  388. * @return bool
  389. * @since 3.6.0
  390. */
  391. public static function compareFields($check, $field, $operator, $context)
  392. {
  393. if (!isset($context['data'][$field])) {
  394. return false;
  395. }
  396. return static::comparison($check, $operator, $context['data'][$field]);
  397. }
  398. /**
  399. * Checks if a string contains one or more non-alphanumeric characters.
  400. *
  401. * Returns true if string contains at least the specified number of non-alphanumeric characters
  402. *
  403. * @param string $check Value to check
  404. * @param int $count Number of non-alphanumerics to check for
  405. * @return bool Success
  406. */
  407. public static function containsNonAlphaNumeric($check, $count = 1)
  408. {
  409. if (!is_scalar($check)) {
  410. return false;
  411. }
  412. $matches = preg_match_all('/[^a-zA-Z0-9]/', $check);
  413. return $matches >= $count;
  414. }
  415. /**
  416. * Used when a custom regular expression is needed.
  417. *
  418. * @param string $check The value to check.
  419. * @param string|null $regex If $check is passed as a string, $regex must also be set to valid regular expression
  420. * @return bool Success
  421. */
  422. public static function custom($check, $regex = null)
  423. {
  424. if ($regex === null) {
  425. static::$errors[] = 'You must define a regular expression for Validation::custom()';
  426. return false;
  427. }
  428. return static::_check($check, $regex);
  429. }
  430. /**
  431. * Date validation, determines if the string passed is a valid date.
  432. * keys that expect full month, day and year will validate leap years.
  433. *
  434. * Years are valid from 1800 to 2999.
  435. *
  436. * ### Formats:
  437. *
  438. * - `dmy` 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
  439. * - `mdy` 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
  440. * - `ymd` 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
  441. * - `dMy` 27 December 2006 or 27 Dec 2006
  442. * - `Mdy` December 27, 2006 or Dec 27, 2006 comma is optional
  443. * - `My` December 2006 or Dec 2006
  444. * - `my` 12/2006 or 12/06 separators can be a space, period, dash, forward slash
  445. * - `ym` 2006/12 or 06/12 separators can be a space, period, dash, forward slash
  446. * - `y` 2006 just the year without any separators
  447. *
  448. * @param string|\DateTimeInterface $check a valid date string/object
  449. * @param string|array $format Use a string or an array of the keys above.
  450. * Arrays should be passed as ['dmy', 'mdy', etc]
  451. * @param string|null $regex If a custom regular expression is used this is the only validation that will occur.
  452. * @return bool Success
  453. */
  454. public static function date($check, $format = 'ymd', $regex = null)
  455. {
  456. if ($check instanceof DateTimeInterface) {
  457. return true;
  458. }
  459. if (is_object($check)) {
  460. return false;
  461. }
  462. if (is_array($check)) {
  463. $check = static::_getDateString($check);
  464. $format = 'ymd';
  465. }
  466. if ($regex !== null) {
  467. return static::_check($check, $regex);
  468. }
  469. $month = '(0[123456789]|10|11|12)';
  470. $separator = '([- /.])';
  471. $fourDigitYear = '(([1][8-9][0-9][0-9])|([2][0-9][0-9][0-9]))';
  472. $twoDigitYear = '([0-9]{2})';
  473. $year = '(?:' . $fourDigitYear . '|' . $twoDigitYear . ')';
  474. $regex['dmy'] = '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)' .
  475. $separator . '(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29' .
  476. $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])' .
  477. $separator . '(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  478. $regex['mdy'] = '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|1[0-2])' .
  479. $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]))' .
  480. $separator . '(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  481. $regex['ymd'] = '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))' .
  482. $separator . '(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})' .
  483. $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]))))$%';
  484. $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})$/';
  485. $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}))$/';
  486. $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)?)' .
  487. $separator . '((1[6-9]|[2-9]\\d)\\d{2})$%';
  488. $regex['my'] = '%^(' . $month . $separator . $year . ')$%';
  489. $regex['ym'] = '%^(' . $year . $separator . $month . ')$%';
  490. $regex['y'] = '%^(' . $fourDigitYear . ')$%';
  491. $format = is_array($format) ? array_values($format) : [$format];
  492. foreach ($format as $key) {
  493. if (static::_check($check, $regex[$key]) === true) {
  494. return true;
  495. }
  496. }
  497. return false;
  498. }
  499. /**
  500. * Validates a datetime value
  501. *
  502. * All values matching the "date" core validation rule, and the "time" one will be valid
  503. *
  504. * @param string|\DateTimeInterface $check Value to check
  505. * @param string|array $dateFormat Format of the date part. See Validation::date() for more information.
  506. * @param string|null $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur.
  507. * @return bool True if the value is valid, false otherwise
  508. * @see \Cake\Validation\Validation::date()
  509. * @see \Cake\Validation\Validation::time()
  510. */
  511. public static function datetime($check, $dateFormat = 'ymd', $regex = null)
  512. {
  513. if ($check instanceof DateTimeInterface) {
  514. return true;
  515. }
  516. if (is_object($check)) {
  517. return false;
  518. }
  519. $valid = false;
  520. if (is_array($check)) {
  521. $check = static::_getDateString($check);
  522. $dateFormat = 'ymd';
  523. }
  524. $parts = explode(' ', $check);
  525. if (!empty($parts) && count($parts) > 1) {
  526. $date = rtrim(array_shift($parts), ',');
  527. $time = implode(' ', $parts);
  528. $valid = static::date($date, $dateFormat, $regex) && static::time($time);
  529. }
  530. return $valid;
  531. }
  532. /**
  533. * Time validation, determines if the string passed is a valid time.
  534. * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m)
  535. * Does not allow/validate seconds.
  536. *
  537. * @param string|\DateTimeInterface $check a valid time string/object
  538. * @return bool Success
  539. */
  540. public static function time($check)
  541. {
  542. if ($check instanceof DateTimeInterface) {
  543. return true;
  544. }
  545. if (is_array($check)) {
  546. $check = static::_getDateString($check);
  547. }
  548. 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}$%');
  549. }
  550. /**
  551. * Date and/or time string validation.
  552. * Uses `I18n::Time` to parse the date. This means parsing is locale dependent.
  553. *
  554. * @param string|\DateTime $check a date string or object (will always pass)
  555. * @param string $type Parser type, one out of 'date', 'time', and 'datetime'
  556. * @param string|int|null $format any format accepted by IntlDateFormatter
  557. * @return bool Success
  558. * @throws \InvalidArgumentException when unsupported $type given
  559. * @see \Cake\I18n\Time::parseDate(), \Cake\I18n\Time::parseTime(), \Cake\I18n\Time::parseDateTime()
  560. */
  561. public static function localizedTime($check, $type = 'datetime', $format = null)
  562. {
  563. if ($check instanceof DateTimeInterface) {
  564. return true;
  565. }
  566. if (is_object($check)) {
  567. return false;
  568. }
  569. static $methods = [
  570. 'date' => 'parseDate',
  571. 'time' => 'parseTime',
  572. 'datetime' => 'parseDateTime',
  573. ];
  574. if (empty($methods[$type])) {
  575. throw new InvalidArgumentException('Unsupported parser type given.');
  576. }
  577. $method = $methods[$type];
  578. return (Time::$method($check, $format) !== null);
  579. }
  580. /**
  581. * Validates if passed value is boolean-like.
  582. *
  583. * The list of what is considered to be boolean values, may be set via $booleanValues.
  584. *
  585. * @param bool|int|string $check Value to check.
  586. * @param array $booleanValues List of valid boolean values, defaults to `[true, false, 0, 1, '0', '1']`.
  587. * @return bool Success.
  588. */
  589. public static function boolean($check, array $booleanValues = [])
  590. {
  591. if (!$booleanValues) {
  592. $booleanValues = [true, false, 0, 1, '0', '1'];
  593. }
  594. return in_array($check, $booleanValues, true);
  595. }
  596. /**
  597. * Validates if given value is truthy.
  598. *
  599. * The list of what is considered to be truthy values, may be set via $truthyValues.
  600. *
  601. * @param bool|int|string $check Value to check.
  602. * @param array $truthyValues List of valid truthy values, defaults to `[true, 1, '1']`.
  603. * @return bool Success.
  604. */
  605. public static function truthy($check, array $truthyValues = [])
  606. {
  607. if (!$truthyValues) {
  608. $truthyValues = [true, 1, '1'];
  609. }
  610. return in_array($check, $truthyValues, true);
  611. }
  612. /**
  613. * Validates if given value is falsey.
  614. *
  615. * The list of what is considered to be falsey values, may be set via $falseyValues.
  616. *
  617. * @param bool|int|string $check Value to check.
  618. * @param array $falseyValues List of valid falsey values, defaults to `[false, 0, '0']`.
  619. * @return bool Success.
  620. */
  621. public static function falsey($check, array $falseyValues = [])
  622. {
  623. if (!$falseyValues) {
  624. $falseyValues = [false, 0, '0'];
  625. }
  626. return in_array($check, $falseyValues, true);
  627. }
  628. /**
  629. * Checks that a value is a valid decimal. Both the sign and exponent are optional.
  630. *
  631. * Valid Places:
  632. *
  633. * - null => Any number of decimal places, including none. The '.' is not required.
  634. * - true => Any number of decimal places greater than 0, or a float|double. The '.' is required.
  635. * - 1..N => Exactly that many number of decimal places. The '.' is required.
  636. *
  637. * @param float $check The value the test for decimal.
  638. * @param int|bool|null $places Decimal places.
  639. * @param string|null $regex If a custom regular expression is used, this is the only validation that will occur.
  640. * @return bool Success
  641. */
  642. public static function decimal($check, $places = null, $regex = null)
  643. {
  644. if ($regex === null) {
  645. $lnum = '[0-9]+';
  646. $dnum = "[0-9]*[\.]{$lnum}";
  647. $sign = '[+-]?';
  648. $exp = "(?:[eE]{$sign}{$lnum})?";
  649. if ($places === null) {
  650. $regex = "/^{$sign}(?:{$lnum}|{$dnum}){$exp}$/";
  651. } elseif ($places === true) {
  652. if (is_float($check) && floor($check) === $check) {
  653. $check = sprintf('%.1f', $check);
  654. }
  655. $regex = "/^{$sign}{$dnum}{$exp}$/";
  656. } elseif (is_numeric($places)) {
  657. $places = '[0-9]{' . $places . '}';
  658. $dnum = "(?:[0-9]*[\.]{$places}|{$lnum}[\.]{$places})";
  659. $regex = "/^{$sign}{$dnum}{$exp}$/";
  660. }
  661. }
  662. // account for localized floats.
  663. $locale = ini_get('intl.default_locale') ?: static::DEFAULT_LOCALE;
  664. $formatter = new NumberFormatter($locale, NumberFormatter::DECIMAL);
  665. $decimalPoint = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
  666. $groupingSep = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
  667. $check = str_replace([$groupingSep, $decimalPoint], ['', '.'], $check);
  668. return static::_check($check, $regex);
  669. }
  670. /**
  671. * Validates for an email address.
  672. *
  673. * Only uses getmxrr() checking for deep validation, or
  674. * any PHP version on a non-windows distribution
  675. *
  676. * @param string $check Value to check
  677. * @param bool $deep Perform a deeper validation (if true), by also checking availability of host
  678. * @param string|null $regex Regex to use (if none it will use built in regex)
  679. * @return bool Success
  680. */
  681. public static function email($check, $deep = false, $regex = null)
  682. {
  683. if (!is_string($check)) {
  684. return false;
  685. }
  686. if ($regex === null) {
  687. $regex = '/^[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+)*@' . self::$_pattern['hostname'] . '$/ui';
  688. }
  689. $return = static::_check($check, $regex);
  690. if ($deep === false || $deep === null) {
  691. return $return;
  692. }
  693. if ($return === true && preg_match('/@(' . static::$_pattern['hostname'] . ')$/i', $check, $regs)) {
  694. if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) {
  695. return true;
  696. }
  697. if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) {
  698. return true;
  699. }
  700. return is_array(gethostbynamel($regs[1] . '.'));
  701. }
  702. return false;
  703. }
  704. /**
  705. * Checks that value is exactly $comparedTo.
  706. *
  707. * @param mixed $check Value to check
  708. * @param mixed $comparedTo Value to compare
  709. * @return bool Success
  710. */
  711. public static function equalTo($check, $comparedTo)
  712. {
  713. return ($check === $comparedTo);
  714. }
  715. /**
  716. * Checks that value has a valid file extension.
  717. *
  718. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check
  719. * @param array $extensions file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg'
  720. * @return bool Success
  721. */
  722. public static function extension($check, $extensions = ['gif', 'jpeg', 'png', 'jpg'])
  723. {
  724. if ($check instanceof UploadedFileInterface) {
  725. return static::extension($check->getClientFilename(), $extensions);
  726. }
  727. if (is_array($check)) {
  728. $check = isset($check['name']) ? $check['name'] : array_shift($check);
  729. return static::extension($check, $extensions);
  730. }
  731. $extension = strtolower(pathinfo($check, PATHINFO_EXTENSION));
  732. foreach ($extensions as $value) {
  733. if ($extension === strtolower($value)) {
  734. return true;
  735. }
  736. }
  737. return false;
  738. }
  739. /**
  740. * Validation of an IP address.
  741. *
  742. * @param string $check The string to test.
  743. * @param string $type The IP Protocol version to validate against
  744. * @return bool Success
  745. */
  746. public static function ip($check, $type = 'both')
  747. {
  748. $type = strtolower($type);
  749. $flags = 0;
  750. if ($type === 'ipv4') {
  751. $flags = FILTER_FLAG_IPV4;
  752. }
  753. if ($type === 'ipv6') {
  754. $flags = FILTER_FLAG_IPV6;
  755. }
  756. return (bool)filter_var($check, FILTER_VALIDATE_IP, ['flags' => $flags]);
  757. }
  758. /**
  759. * Checks whether the length of a string (in characters) is greater or equal to a minimal length.
  760. *
  761. * @param string $check The string to test
  762. * @param int $min The minimal string length
  763. * @return bool Success
  764. */
  765. public static function minLength($check, $min)
  766. {
  767. if (!is_scalar($check)) {
  768. return false;
  769. }
  770. return mb_strlen($check) >= $min;
  771. }
  772. /**
  773. * Checks whether the length of a string (in characters) is smaller or equal to a maximal length.
  774. *
  775. * @param string $check The string to test
  776. * @param int $max The maximal string length
  777. * @return bool Success
  778. */
  779. public static function maxLength($check, $max)
  780. {
  781. if (!is_scalar($check)) {
  782. return false;
  783. }
  784. return mb_strlen($check) <= $max;
  785. }
  786. /**
  787. * Checks whether the length of a string (in bytes) is greater or equal to a minimal length.
  788. *
  789. * @param string $check The string to test
  790. * @param int $min The minimal string length (in bytes)
  791. * @return bool Success
  792. */
  793. public static function minLengthBytes($check, $min)
  794. {
  795. if (!is_scalar($check)) {
  796. return false;
  797. }
  798. return strlen($check) >= $min;
  799. }
  800. /**
  801. * Checks whether the length of a string (in bytes) is smaller or equal to a maximal length.
  802. *
  803. * @param string $check The string to test
  804. * @param int $max The maximal string length
  805. * @return bool Success
  806. */
  807. public static function maxLengthBytes($check, $max)
  808. {
  809. if (!is_scalar($check)) {
  810. return false;
  811. }
  812. return strlen($check) <= $max;
  813. }
  814. /**
  815. * Checks that a value is a monetary amount.
  816. *
  817. * @param string $check Value to check
  818. * @param string $symbolPosition Where symbol is located (left/right)
  819. * @return bool Success
  820. */
  821. public static function money($check, $symbolPosition = 'left')
  822. {
  823. $money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{1,2})?';
  824. if ($symbolPosition === 'right') {
  825. $regex = '/^' . $money . '(?<!\x{00a2})\p{Sc}?$/u';
  826. } else {
  827. $regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u';
  828. }
  829. return static::_check($check, $regex);
  830. }
  831. /**
  832. * Validates a multiple select. Comparison is case sensitive by default.
  833. *
  834. * Valid Options
  835. *
  836. * - in => provide a list of choices that selections must be made from
  837. * - max => maximum number of non-zero choices that can be made
  838. * - min => minimum number of non-zero choices that can be made
  839. *
  840. * @param array $check Value to check
  841. * @param array $options Options for the check.
  842. * @param bool $caseInsensitive Set to true for case insensitive comparison.
  843. * @return bool Success
  844. */
  845. public static function multiple($check, array $options = [], $caseInsensitive = false)
  846. {
  847. $defaults = ['in' => null, 'max' => null, 'min' => null];
  848. $options += $defaults;
  849. $check = array_filter((array)$check, function ($value) {
  850. return ($value || is_numeric($value));
  851. });
  852. if (empty($check)) {
  853. return false;
  854. }
  855. if ($options['max'] && count($check) > $options['max']) {
  856. return false;
  857. }
  858. if ($options['min'] && count($check) < $options['min']) {
  859. return false;
  860. }
  861. if ($options['in'] && is_array($options['in'])) {
  862. if ($caseInsensitive) {
  863. $options['in'] = array_map('mb_strtolower', $options['in']);
  864. }
  865. foreach ($check as $val) {
  866. $strict = !is_numeric($val);
  867. if ($caseInsensitive) {
  868. $val = mb_strtolower($val);
  869. }
  870. if (!in_array((string)$val, $options['in'], $strict)) {
  871. return false;
  872. }
  873. }
  874. }
  875. return true;
  876. }
  877. /**
  878. * Checks if a value is numeric.
  879. *
  880. * @param string $check Value to check
  881. * @return bool Success
  882. */
  883. public static function numeric($check)
  884. {
  885. return is_numeric($check);
  886. }
  887. /**
  888. * Checks if a value is a natural number.
  889. *
  890. * @param string $check Value to check
  891. * @param bool $allowZero Set true to allow zero, defaults to false
  892. * @return bool Success
  893. * @see https://en.wikipedia.org/wiki/Natural_number
  894. */
  895. public static function naturalNumber($check, $allowZero = false)
  896. {
  897. $regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
  898. return static::_check($check, $regex);
  899. }
  900. /**
  901. * Validates that a number is in specified range.
  902. *
  903. * If $lower and $upper are set, the range is inclusive.
  904. * If they are not set, will return true if $check is a
  905. * legal finite on this platform.
  906. *
  907. * @param string $check Value to check
  908. * @param int|float|null $lower Lower limit
  909. * @param int|float|null $upper Upper limit
  910. * @return bool Success
  911. */
  912. public static function range($check, $lower = null, $upper = null)
  913. {
  914. if (!is_numeric($check)) {
  915. return false;
  916. }
  917. if ((float)$check != $check) {
  918. return false;
  919. }
  920. if (isset($lower, $upper)) {
  921. return ($check >= $lower && $check <= $upper);
  922. }
  923. return is_finite($check);
  924. }
  925. /**
  926. * Checks that a value is a valid URL according to https://www.w3.org/Addressing/URL/url-spec.txt
  927. *
  928. * The regex checks for the following component parts:
  929. *
  930. * - a valid, optional, scheme
  931. * - a valid ip address OR
  932. * a valid domain name as defined by section 2.3.1 of https://www.ietf.org/rfc/rfc1035.txt
  933. * with an optional port number
  934. * - an optional valid path
  935. * - an optional query string (get parameters)
  936. * - an optional fragment (anchor tag) as defined in RFC 3986
  937. *
  938. * @param string $check Value to check
  939. * @param bool $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
  940. * @return bool Success
  941. * @link https://tools.ietf.org/html/rfc3986
  942. */
  943. public static function url($check, $strict = false)
  944. {
  945. static::_populateIp();
  946. $emoji = '\x{1F190}-\x{1F9EF}';
  947. $alpha = '0-9\p{L}\p{N}' . $emoji;
  948. $hex = '(%[0-9a-f]{2})';
  949. $subDelimiters = preg_quote('/!"$&\'()*+,-.@_:;=~[]', '/');
  950. $path = '([' . $subDelimiters . $alpha . ']|' . $hex . ')';
  951. $fragmentAndQuery = '([\?' . $subDelimiters . $alpha . ']|' . $hex . ')';
  952. $regex = '/^(?:(?:https?|ftps?|sftp|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') .
  953. '(?:' . static::$_pattern['IPv4'] . '|\[' . static::$_pattern['IPv6'] . '\]|' . static::$_pattern['hostname'] . ')(?::[1-9][0-9]{0,4})?' .
  954. '(?:\/' . $path . '*)?' .
  955. '(?:\?' . $fragmentAndQuery . '*)?' .
  956. '(?:#' . $fragmentAndQuery . '*)?$/iu';
  957. return static::_check($check, $regex);
  958. }
  959. /**
  960. * Checks if a value is in a given list. Comparison is case sensitive by default.
  961. *
  962. * @param string $check Value to check.
  963. * @param array $list List to check against.
  964. * @param bool $caseInsensitive Set to true for case insensitive comparison.
  965. * @return bool Success.
  966. */
  967. public static function inList($check, array $list, $caseInsensitive = false)
  968. {
  969. if ($caseInsensitive) {
  970. $list = array_map('mb_strtolower', $list);
  971. $check = mb_strtolower($check);
  972. } else {
  973. $list = array_map('strval', $list);
  974. }
  975. return in_array((string)$check, $list, true);
  976. }
  977. /**
  978. * Runs an user-defined validation.
  979. *
  980. * @param string|array $check value that will be validated in user-defined methods.
  981. * @param object $object class that holds validation method
  982. * @param string $method class method name for validation to run
  983. * @param array|null $args arguments to send to method
  984. * @return mixed user-defined class class method returns
  985. * @deprecated 3.0.2 You can just set a callable for `rule` key when adding validators.
  986. */
  987. public static function userDefined($check, $object, $method, $args = null)
  988. {
  989. deprecationWarning(
  990. 'Validation::userDefined() is deprecated. ' .
  991. 'You can just set a callable for `rule` key when adding validators.'
  992. );
  993. return $object->$method($check, $args);
  994. }
  995. /**
  996. * Checks that a value is a valid UUID - https://tools.ietf.org/html/rfc4122
  997. *
  998. * @param string $check Value to check
  999. * @return bool Success
  1000. */
  1001. public static function uuid($check)
  1002. {
  1003. $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}$/';
  1004. return self::_check($check, $regex);
  1005. }
  1006. /**
  1007. * Runs a regular expression match.
  1008. *
  1009. * @param string $check Value to check against the $regex expression
  1010. * @param string $regex Regular expression
  1011. * @return bool Success of match
  1012. */
  1013. protected static function _check($check, $regex)
  1014. {
  1015. return is_string($regex) && is_scalar($check) && preg_match($regex, $check);
  1016. }
  1017. /**
  1018. * Luhn algorithm
  1019. *
  1020. * @param string|array $check Value to check.
  1021. * @return bool Success
  1022. * @see https://en.wikipedia.org/wiki/Luhn_algorithm
  1023. */
  1024. public static function luhn($check)
  1025. {
  1026. if (!is_scalar($check) || (int)$check === 0) {
  1027. return false;
  1028. }
  1029. $sum = 0;
  1030. $length = strlen($check);
  1031. for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
  1032. $sum += $check[$position];
  1033. }
  1034. for ($position = ($length % 2); $position < $length; $position += 2) {
  1035. $number = (int)$check[$position] * 2;
  1036. $sum += ($number < 10) ? $number : $number - 9;
  1037. }
  1038. return ($sum % 10 === 0);
  1039. }
  1040. /**
  1041. * Checks the mime type of a file.
  1042. *
  1043. * Will check the mimetype of files/UploadedFileInterface instances
  1044. * by checking the using finfo on the file, not relying on the content-type
  1045. * sent by the client.
  1046. *
  1047. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check.
  1048. * @param array|string $mimeTypes Array of mime types or regex pattern to check.
  1049. * @return bool Success
  1050. * @throws \RuntimeException when mime type can not be determined.
  1051. * @throws \LogicException when ext/fileinfo is missing
  1052. */
  1053. public static function mimeType($check, $mimeTypes = [])
  1054. {
  1055. $file = static::getFilename($check);
  1056. if ($file === false) {
  1057. return false;
  1058. }
  1059. if (!function_exists('finfo_open')) {
  1060. throw new LogicException('ext/fileinfo is required for validating file mime types');
  1061. }
  1062. if (!is_file($file)) {
  1063. throw new RuntimeException('Cannot validate mimetype for a missing file');
  1064. }
  1065. $finfo = finfo_open(FILEINFO_MIME);
  1066. $finfo = finfo_file($finfo, $file);
  1067. if (!$finfo) {
  1068. throw new RuntimeException('Can not determine the mimetype.');
  1069. }
  1070. list($mime) = explode(';', $finfo);
  1071. if (is_string($mimeTypes)) {
  1072. return self::_check($mime, $mimeTypes);
  1073. }
  1074. foreach ($mimeTypes as $key => $val) {
  1075. $mimeTypes[$key] = strtolower($val);
  1076. }
  1077. return in_array($mime, $mimeTypes);
  1078. }
  1079. /**
  1080. * Helper for reading the file out of the various file implementations
  1081. * we accept.
  1082. *
  1083. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check The data to read a filename out of.
  1084. * @return string|bool Either the filename or false on failure.
  1085. */
  1086. protected static function getFilename($check)
  1087. {
  1088. if ($check instanceof UploadedFileInterface) {
  1089. try {
  1090. // Uploaded files throw exceptions on upload errors.
  1091. return $check->getStream()->getMetadata('uri');
  1092. } catch (RuntimeException $e) {
  1093. return false;
  1094. }
  1095. }
  1096. if (is_array($check) && isset($check['tmp_name'])) {
  1097. return $check['tmp_name'];
  1098. }
  1099. if (is_string($check)) {
  1100. return $check;
  1101. }
  1102. return false;
  1103. }
  1104. /**
  1105. * Checks the filesize
  1106. *
  1107. * Will check the filesize of files/UploadedFileInterface instances
  1108. * by checking the filesize() on disk and not relying on the length
  1109. * reported by the client.
  1110. *
  1111. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check.
  1112. * @param string|null $operator See `Validation::comparison()`.
  1113. * @param int|string|null $size Size in bytes or human readable string like '5MB'.
  1114. * @return bool Success
  1115. */
  1116. public static function fileSize($check, $operator = null, $size = null)
  1117. {
  1118. $file = static::getFilename($check);
  1119. if ($file === false) {
  1120. return false;
  1121. }
  1122. if (is_string($size)) {
  1123. $size = Text::parseFileSize($size);
  1124. }
  1125. $filesize = filesize($file);
  1126. return static::comparison($filesize, $operator, $size);
  1127. }
  1128. /**
  1129. * Checking for upload errors
  1130. *
  1131. * @param string|array|\Psr\Http\Message\UploadedFileInterface $check Value to check.
  1132. * @param bool $allowNoFile Set to true to allow UPLOAD_ERR_NO_FILE as a pass.
  1133. * @return bool
  1134. * @see https://secure.php.net/manual/en/features.file-upload.errors.php
  1135. */
  1136. public static function uploadError($check, $allowNoFile = false)
  1137. {
  1138. if ($check instanceof UploadedFileInterface) {
  1139. $code = $check->getError();
  1140. } elseif (is_array($check) && isset($check['error'])) {
  1141. $code = $check['error'];
  1142. } else {
  1143. $code = $check;
  1144. }
  1145. if ($allowNoFile) {
  1146. return in_array((int)$code, [UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE], true);
  1147. }
  1148. return (int)$code === UPLOAD_ERR_OK;
  1149. }
  1150. /**
  1151. * Validate an uploaded file.
  1152. *
  1153. * Helps join `uploadError`, `fileSize` and `mimeType` into
  1154. * one higher level validation method.
  1155. *
  1156. * ### Options
  1157. *
  1158. * - `types` - An array of valid mime types. If empty all types
  1159. * will be accepted. The `type` will not be looked at, instead
  1160. * the file type will be checked with ext/finfo.
  1161. * - `minSize` - The minimum file size in bytes. Defaults to not checking.
  1162. * - `maxSize` - The maximum file size in bytes. Defaults to not checking.
  1163. * - `optional` - Whether or not this file is optional. Defaults to false.
  1164. * If true a missing file will pass the validator regardless of other constraints.
  1165. *
  1166. * @param array|\Psr\Http\Message\UploadedFileInterface $file The uploaded file data from PHP.
  1167. * @param array $options An array of options for the validation.
  1168. * @return bool
  1169. */
  1170. public static function uploadedFile($file, array $options = [])
  1171. {
  1172. $options += [
  1173. 'minSize' => null,
  1174. 'maxSize' => null,
  1175. 'types' => null,
  1176. 'optional' => false,
  1177. ];
  1178. if (!is_array($file) && !($file instanceof UploadedFileInterface)) {
  1179. return false;
  1180. }
  1181. $error = $isUploaded = false;
  1182. if ($file instanceof UploadedFileInterface) {
  1183. $error = $file->getError();
  1184. $isUploaded = true;
  1185. }
  1186. if (is_array($file)) {
  1187. $keys = ['error', 'name', 'size', 'tmp_name', 'type'];
  1188. ksort($file);
  1189. if (array_keys($file) != $keys) {
  1190. return false;
  1191. }
  1192. $error = (int)$file['error'];
  1193. $isUploaded = is_uploaded_file($file['tmp_name']);
  1194. }
  1195. if (!static::uploadError($file, $options['optional'])) {
  1196. return false;
  1197. }
  1198. if ($options['optional'] && $error === UPLOAD_ERR_NO_FILE) {
  1199. return true;
  1200. }
  1201. if (isset($options['minSize']) && !static::fileSize($file, static::COMPARE_GREATER_OR_EQUAL, $options['minSize'])) {
  1202. return false;
  1203. }
  1204. if (isset($options['maxSize']) && !static::fileSize($file, static::COMPARE_LESS_OR_EQUAL, $options['maxSize'])) {
  1205. return false;
  1206. }
  1207. if (isset($options['types']) && !static::mimeType($file, $options['types'])) {
  1208. return false;
  1209. }
  1210. return $isUploaded;
  1211. }
  1212. /**
  1213. * Validates the size of an uploaded image.
  1214. *
  1215. * @param array|\Psr\Http\Message\UploadedFileInterface $file The uploaded file data from PHP.
  1216. * @param array $options Options to validate width and height.
  1217. * @return bool
  1218. * @throws \InvalidArgumentException
  1219. */
  1220. public static function imageSize($file, $options)
  1221. {
  1222. if (!isset($options['height']) && !isset($options['width'])) {
  1223. throw new InvalidArgumentException('Invalid image size validation parameters! Missing `width` and / or `height`.');
  1224. }
  1225. $filename = static::getFilename($file);
  1226. list($width, $height) = getimagesize($filename);
  1227. $validHeight = $validWidth = null;
  1228. if (isset($options['height'])) {
  1229. $validHeight = self::comparison($height, $options['height'][0], $options['height'][1]);
  1230. }
  1231. if (isset($options['width'])) {
  1232. $validWidth = self::comparison($width, $options['width'][0], $options['width'][1]);
  1233. }
  1234. if ($validHeight !== null && $validWidth !== null) {
  1235. return ($validHeight && $validWidth);
  1236. }
  1237. if ($validHeight !== null) {
  1238. return $validHeight;
  1239. }
  1240. if ($validWidth !== null) {
  1241. return $validWidth;
  1242. }
  1243. throw new InvalidArgumentException('The 2nd argument is missing the `width` and / or `height` options.');
  1244. }
  1245. /**
  1246. * Validates the image width.
  1247. *
  1248. * @param array $file The uploaded file data from PHP.
  1249. * @param string $operator Comparison operator.
  1250. * @param int $width Min or max width.
  1251. * @return bool
  1252. */
  1253. public static function imageWidth($file, $operator, $width)
  1254. {
  1255. return self::imageSize($file, [
  1256. 'width' => [
  1257. $operator,
  1258. $width
  1259. ]
  1260. ]);
  1261. }
  1262. /**
  1263. * Validates the image width.
  1264. *
  1265. * @param array $file The uploaded file data from PHP.
  1266. * @param string $operator Comparison operator.
  1267. * @param int $height Min or max width.
  1268. * @return bool
  1269. */
  1270. public static function imageHeight($file, $operator, $height)
  1271. {
  1272. return self::imageSize($file, [
  1273. 'height' => [
  1274. $operator,
  1275. $height
  1276. ]
  1277. ]);
  1278. }
  1279. /**
  1280. * Validates a geographic coordinate.
  1281. *
  1282. * Supported formats:
  1283. *
  1284. * - `<latitude>, <longitude>` Example: `-25.274398, 133.775136`
  1285. *
  1286. * ### Options
  1287. *
  1288. * - `type` - A string of the coordinate format, right now only `latLong`.
  1289. * - `format` - By default `both`, can be `long` and `lat` as well to validate
  1290. * only a part of the coordinate.
  1291. *
  1292. * @param string $value Geographic location as string
  1293. * @param array $options Options for the validation logic.
  1294. * @return bool
  1295. */
  1296. public static function geoCoordinate($value, array $options = [])
  1297. {
  1298. $options += [
  1299. 'format' => 'both',
  1300. 'type' => 'latLong'
  1301. ];
  1302. if ($options['type'] !== 'latLong') {
  1303. throw new RuntimeException(sprintf(
  1304. 'Unsupported coordinate type "%s". Use "latLong" instead.',
  1305. $options['type']
  1306. ));
  1307. }
  1308. $pattern = '/^' . self::$_pattern['latitude'] . ',\s*' . self::$_pattern['longitude'] . '$/';
  1309. if ($options['format'] === 'long') {
  1310. $pattern = '/^' . self::$_pattern['longitude'] . '$/';
  1311. }
  1312. if ($options['format'] === 'lat') {
  1313. $pattern = '/^' . self::$_pattern['latitude'] . '$/';
  1314. }
  1315. return (bool)preg_match($pattern, $value);
  1316. }
  1317. /**
  1318. * Convenience method for latitude validation.
  1319. *
  1320. * @param string $value Latitude as string
  1321. * @param array $options Options for the validation logic.
  1322. * @return bool
  1323. * @link https://en.wikipedia.org/wiki/Latitude
  1324. * @see \Cake\Validation\Validation::geoCoordinate()
  1325. */
  1326. public static function latitude($value, array $options = [])
  1327. {
  1328. $options['format'] = 'lat';
  1329. return self::geoCoordinate($value, $options);
  1330. }
  1331. /**
  1332. * Convenience method for longitude validation.
  1333. *
  1334. * @param string $value Latitude as string
  1335. * @param array $options Options for the validation logic.
  1336. * @return bool
  1337. * @link https://en.wikipedia.org/wiki/Longitude
  1338. * @see \Cake\Validation\Validation::geoCoordinate()
  1339. */
  1340. public static function longitude($value, array $options = [])
  1341. {
  1342. $options['format'] = 'long';
  1343. return self::geoCoordinate($value, $options);
  1344. }
  1345. /**
  1346. * Check that the input value is within the ascii byte range.
  1347. *
  1348. * This method will reject all non-string values.
  1349. *
  1350. * @param string $value The value to check
  1351. * @return bool
  1352. */
  1353. public static function ascii($value)
  1354. {
  1355. if (!is_string($value)) {
  1356. return false;
  1357. }
  1358. return strlen($value) <= mb_strlen($value, 'utf-8');
  1359. }
  1360. /**
  1361. * Check that the input value is a utf8 string.
  1362. *
  1363. * This method will reject all non-string values.
  1364. *
  1365. * # Options
  1366. *
  1367. * - `extended` - Disallow bytes higher within the basic multilingual plane.
  1368. * MySQL's older utf8 encoding type does not allow characters above
  1369. * the basic multilingual plane. Defaults to false.
  1370. *
  1371. * @param string $value The value to check
  1372. * @param array $options An array of options. See above for the supported options.
  1373. * @return bool
  1374. */
  1375. public static function utf8($value, array $options = [])
  1376. {
  1377. if (!is_string($value)) {
  1378. return false;
  1379. }
  1380. $options += ['extended' => false];
  1381. if ($options['extended']) {
  1382. return true;
  1383. }
  1384. return preg_match('/[\x{10000}-\x{10FFFF}]/u', $value) === 0;
  1385. }
  1386. /**
  1387. * Check that the input value is an integer
  1388. *
  1389. * This method will accept strings that contain only integer data
  1390. * as well.
  1391. *
  1392. * @param string $value The value to check
  1393. * @return bool
  1394. */
  1395. public static function isInteger($value)
  1396. {
  1397. if (!is_scalar($value) || is_float($value)) {
  1398. return false;
  1399. }
  1400. if (is_int($value)) {
  1401. return true;
  1402. }
  1403. return (bool)preg_match('/^-?[0-9]+$/', $value);
  1404. }
  1405. /**
  1406. * Check that the input value is an array.
  1407. *
  1408. * @param array $value The value to check
  1409. * @return bool
  1410. */
  1411. public static function isArray($value)
  1412. {
  1413. return is_array($value);
  1414. }
  1415. /**
  1416. * Check that the input value is a scalar.
  1417. *
  1418. * This method will accept integers, floats, strings and booleans, but
  1419. * not accept arrays, objects, resources and nulls.
  1420. *
  1421. * @param mixed $value The value to check
  1422. * @return bool
  1423. */
  1424. public static function isScalar($value)
  1425. {
  1426. return is_scalar($value);
  1427. }
  1428. /**
  1429. * Check that the input value is a 6 digits hex color.
  1430. *
  1431. * @param string|array $check The value to check
  1432. * @return bool Success
  1433. */
  1434. public static function hexColor($check)
  1435. {
  1436. return static::_check($check, '/^#[0-9a-f]{6}$/iD');
  1437. }
  1438. /**
  1439. * Check that the input value has a valid International Bank Account Number IBAN syntax
  1440. * Requirements are uppercase, no whitespaces, max length 34, country code and checksum exist at right spots,
  1441. * body matches against checksum via Mod97-10 algorithm
  1442. *
  1443. * @param string $check The value to check
  1444. *
  1445. * @return bool Success
  1446. */
  1447. public static function iban($check)
  1448. {
  1449. if (!preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/', $check)) {
  1450. return false;
  1451. }
  1452. $country = substr($check, 0, 2);
  1453. $checkInt = intval(substr($check, 2, 2));
  1454. $account = substr($check, 4);
  1455. $search = range('A', 'Z');
  1456. $replace = [];
  1457. foreach (range(10, 35) as $tmp) {
  1458. $replace[] = strval($tmp);
  1459. }
  1460. $numStr = str_replace($search, $replace, $account . $country . '00');
  1461. $checksum = intval(substr($numStr, 0, 1));
  1462. $numStrLength = strlen($numStr);
  1463. for ($pos = 1; $pos < $numStrLength; $pos++) {
  1464. $checksum *= 10;
  1465. $checksum += intval(substr($numStr, $pos, 1));
  1466. $checksum %= 97;
  1467. }
  1468. return ((98 - $checksum) === $checkInt);
  1469. }
  1470. /**
  1471. * Converts an array representing a date or datetime into a ISO string.
  1472. * The arrays are typically sent for validation from a form generated by
  1473. * the CakePHP FormHelper.
  1474. *
  1475. * @param array $value The array representing a date or datetime.
  1476. * @return string
  1477. */
  1478. protected static function _getDateString($value)
  1479. {
  1480. $formatted = '';
  1481. if (isset($value['year'], $value['month'], $value['day']) &&
  1482. (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
  1483. ) {
  1484. $formatted .= sprintf('%d-%02d-%02d ', $value['year'], $value['month'], $value['day']);
  1485. }
  1486. if (isset($value['hour'])) {
  1487. if (isset($value['meridian']) && (int)$value['hour'] === 12) {
  1488. $value['hour'] = 0;
  1489. }
  1490. if (isset($value['meridian'])) {
  1491. $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
  1492. }
  1493. $value += ['minute' => 0, 'second' => 0];
  1494. if (is_numeric($value['hour']) && is_numeric($value['minute']) && is_numeric($value['second'])) {
  1495. $formatted .= sprintf('%02d:%02d:%02d', $value['hour'], $value['minute'], $value['second']);
  1496. }
  1497. }
  1498. return trim($formatted);
  1499. }
  1500. /**
  1501. * Lazily populate the IP address patterns used for validations
  1502. *
  1503. * @return void
  1504. */
  1505. protected static function _populateIp()
  1506. {
  1507. if (!isset(static::$_pattern['IPv6'])) {
  1508. $pattern = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}';
  1509. $pattern .= '(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})';
  1510. $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})';
  1511. $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}:)';
  1512. $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}))';
  1513. $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}';
  1514. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|';
  1515. $pattern .= '((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}';
  1516. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
  1517. $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4})';
  1518. $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})?)';
  1519. $pattern .= '|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]';
  1520. $pattern .= '\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4})';
  1521. $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})))(%.+)?';
  1522. static::$_pattern['IPv6'] = $pattern;
  1523. }
  1524. if (!isset(static::$_pattern['IPv4'])) {
  1525. $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])';
  1526. static::$_pattern['IPv4'] = $pattern;
  1527. }
  1528. }
  1529. /**
  1530. * Reset internal variables for another validation run.
  1531. *
  1532. * @return void
  1533. */
  1534. protected static function _reset()
  1535. {
  1536. static::$errors = [];
  1537. }
  1538. }