Validation.php 60 KB

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