Validate.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. <?php
  2. declare(strict_types = 1);
  3. /**
  4. * Validation class
  5. *
  6. * Copyright (c) 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox, Amir Saied
  7. *
  8. * This source file is subject to the New BSD license, That is bundled
  9. * with this package in the file LICENSE, and is available through
  10. * the world-wide-web at
  11. * http://www.opensource.org/licenses/bsd-license.php
  12. * If you did not receive a copy of the new BSDlicense and are unable
  13. * to obtain it through the world-wide-web, please send a note to
  14. * pajoye@php.net so we can mail you a copy immediately.
  15. *
  16. * Author: Tomas V.V.Cox <cox@idecnet.com>
  17. * Pierre-Alain Joye <pajoye@php.net>
  18. * Amir Mohammad Saied <amir@php.net>
  19. *
  20. *
  21. * Package to validate various datas. It includes :
  22. * - numbers (min/max, decimal or not)
  23. * - email (syntax, domain check)
  24. * - string (predifined type alpha upper and/or lowercase, numeric,...)
  25. * - date (min, max, rfc822 compliant)
  26. * - uri (RFC2396)
  27. * - possibility valid multiple data with a single method call (::multiple)
  28. *
  29. * @category Validate
  30. * @package Validate
  31. *
  32. * @author Tomas V.V.Cox <cox@idecnet.com>
  33. * @author Pierre-Alain Joye <pajoye@php.net>
  34. * @author Amir Mohammad Saied <amir@php.net>
  35. * @copyright 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox,Amir Mohammad Saied
  36. * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
  37. *
  38. * @version CVS: $Id$
  39. *
  40. * @see http://pear.php.net/package/Validate
  41. */
  42. // {{{ Constants
  43. /**
  44. * Methods for common data validations
  45. */
  46. \define('VALIDATE_NUM', '0-9');
  47. \define('VALIDATE_SPACE', '\s');
  48. \define('VALIDATE_ALPHA_LOWER', 'a-z');
  49. \define('VALIDATE_ALPHA_UPPER', 'A-Z');
  50. \define('VALIDATE_ALPHA', VALIDATE_ALPHA_LOWER . VALIDATE_ALPHA_UPPER);
  51. \define('VALIDATE_EALPHA_LOWER', VALIDATE_ALPHA_LOWER . 'áéíóúýàèìòùäëïöüÿâêîôûãñõ¨åæç½ðøþß');
  52. \define('VALIDATE_EALPHA_UPPER', VALIDATE_ALPHA_UPPER . 'ÁÉÍÓÚÝÀÈÌÒÙÄËÏÖܾÂÊÎÔÛÃÑÕ¦ÅÆǼÐØÞ');
  53. \define('VALIDATE_EALPHA', VALIDATE_EALPHA_LOWER . VALIDATE_EALPHA_UPPER);
  54. \define('VALIDATE_PUNCTUATION', VALIDATE_SPACE . '\.,;\:&"\'\?\!\(\)');
  55. \define('VALIDATE_NAME', VALIDATE_EALPHA . VALIDATE_SPACE . "'" . '\-');
  56. \define('VALIDATE_STREET', VALIDATE_NUM . VALIDATE_NAME . '/\\ºª\\.');
  57. \define('VALIDATE_ITLD_EMAILS', 1);
  58. \define('VALIDATE_GTLD_EMAILS', 2);
  59. \define('VALIDATE_CCTLD_EMAILS', 4);
  60. \define('VALIDATE_ALL_EMAILS', 8);
  61. // }}}
  62. /**
  63. * Validation class
  64. *
  65. * Package to validate various datas. It includes :
  66. * - numbers (min/max, decimal or not)
  67. * - email (syntax, domain check)
  68. * - string (predifined type alpha upper and/or lowercase, numeric,...)
  69. * - date (min, max)
  70. * - uri (RFC2396)
  71. * - possibility valid multiple data with a single method call (::multiple)
  72. *
  73. * @category Validate
  74. * @package Validate
  75. *
  76. * @author Tomas V.V.Cox <cox@idecnet.com>
  77. * @author Pierre-Alain Joye <pajoye@php.net>
  78. * @author Amir Mohammad Saied <amir@php.net>
  79. * @author Diogo Cordeiro <diogo@fc.up.pt>
  80. * @copyright 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox,Amir Mohammad Saied
  81. * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
  82. *
  83. * @version Release: @package_version@
  84. *
  85. * @see http://pear.php.net/package/Validate
  86. */
  87. class Validate
  88. {
  89. // {{{ International, Generic and Country code TLDs
  90. /**
  91. * International Top-Level Domain
  92. *
  93. * This is an array of the known international
  94. * top-level domain names.
  95. *
  96. * @var array $itld (International top-level domains)
  97. */
  98. protected static array $itld = [
  99. 'arpa',
  100. 'root',
  101. ];
  102. /**
  103. * Generic top-level domain
  104. *
  105. * This is an array of the official
  106. * generic top-level domains.
  107. *
  108. * @var array $gtld (Generic top-level domains)
  109. */
  110. protected static array $gtld = [
  111. 'aero',
  112. 'biz',
  113. 'cat',
  114. 'com',
  115. 'coop',
  116. 'edu',
  117. 'gov',
  118. 'info',
  119. 'int',
  120. 'jobs',
  121. 'mil',
  122. 'mobi',
  123. 'museum',
  124. 'name',
  125. 'net',
  126. 'org',
  127. 'pro',
  128. 'travel',
  129. 'asia',
  130. 'post',
  131. 'tel',
  132. 'geo',
  133. ];
  134. /**
  135. * Country code top-level domains
  136. *
  137. * This is an array of the official country
  138. * codes top-level domains
  139. *
  140. * @var array $cctld (Country Code Top-Level Domain)
  141. */
  142. protected static array $cctld = [
  143. 'ac',
  144. 'ad', 'ae', 'af', 'ag',
  145. 'ai', 'al', 'am', 'an',
  146. 'ao', 'aq', 'ar', 'as',
  147. 'at', 'au', 'aw', 'ax',
  148. 'az', 'ba', 'bb', 'bd',
  149. 'be', 'bf', 'bg', 'bh',
  150. 'bi', 'bj', 'bm', 'bn',
  151. 'bo', 'br', 'bs', 'bt',
  152. 'bu', 'bv', 'bw', 'by',
  153. 'bz', 'ca', 'cc', 'cd',
  154. 'cf', 'cg', 'ch', 'ci',
  155. 'ck', 'cl', 'cm', 'cn',
  156. 'co', 'cr', 'cs', 'cu',
  157. 'cv', 'cx', 'cy', 'cz',
  158. 'de', 'dj', 'dk', 'dm',
  159. 'do', 'dz', 'ec', 'ee',
  160. 'eg', 'eh', 'er', 'es',
  161. 'et', 'eu', 'fi', 'fj',
  162. 'fk', 'fm', 'fo', 'fr',
  163. 'ga', 'gb', 'gd', 'ge',
  164. 'gf', 'gg', 'gh', 'gi',
  165. 'gl', 'gm', 'gn', 'gp',
  166. 'gq', 'gr', 'gs', 'gt',
  167. 'gu', 'gw', 'gy', 'hk',
  168. 'hm', 'hn', 'hr', 'ht',
  169. 'hu', 'id', 'ie', 'il',
  170. 'im', 'in', 'io', 'iq',
  171. 'ir', 'is', 'it', 'je',
  172. 'jm', 'jo', 'jp', 'ke',
  173. 'kg', 'kh', 'ki', 'km',
  174. 'kn', 'kp', 'kr', 'kw',
  175. 'ky', 'kz', 'la', 'lb',
  176. 'lc', 'li', 'lk', 'lr',
  177. 'ls', 'lt', 'lu', 'lv',
  178. 'ly', 'ma', 'mc', 'md',
  179. 'me', 'mg', 'mh', 'mk',
  180. 'ml', 'mm', 'mn', 'mo',
  181. 'mp', 'mq', 'mr', 'ms',
  182. 'mt', 'mu', 'mv', 'mw',
  183. 'mx', 'my', 'mz', 'na',
  184. 'nc', 'ne', 'nf', 'ng',
  185. 'ni', 'nl', 'no', 'np',
  186. 'nr', 'nu', 'nz', 'om',
  187. 'pa', 'pe', 'pf', 'pg',
  188. 'ph', 'pk', 'pl', 'pm',
  189. 'pn', 'pr', 'ps', 'pt',
  190. 'pw', 'py', 'qa', 're',
  191. 'ro', 'rs', 'ru', 'rw',
  192. 'sa', 'sb', 'sc', 'sd',
  193. 'se', 'sg', 'sh', 'si',
  194. 'sj', 'sk', 'sl', 'sm',
  195. 'sn', 'so', 'sr', 'st',
  196. 'su', 'sv', 'sy', 'sz',
  197. 'tc', 'td', 'tf', 'tg',
  198. 'th', 'tj', 'tk', 'tl',
  199. 'tm', 'tn', 'to', 'tp',
  200. 'tr', 'tt', 'tv', 'tw',
  201. 'tz', 'ua', 'ug', 'uk',
  202. 'us', 'uy', 'uz', 'va',
  203. 'vc', 've', 'vg', 'vi',
  204. 'vn', 'vu', 'wf', 'ws',
  205. 'ye', 'yt', 'yu', 'za',
  206. 'zm', 'zw',
  207. ];
  208. // }}}
  209. /**
  210. * Validate a tag URI (RFC4151)
  211. *
  212. * @param string $uri tag URI to validate
  213. *
  214. * @throws Exception
  215. *
  216. * @return bool true if valid tag URI, false if not
  217. */
  218. private static function uriRFC4151(string $uri): bool
  219. {
  220. $datevalid = false;
  221. if (preg_match(
  222. '/^tag:(?<name>.*),(?<date>\d{4}-?\d{0,2}-?\d{0,2}):(?<specific>.*)(.*:)*$/',
  223. $uri,
  224. $matches,
  225. )) {
  226. $date = $matches['date'];
  227. $date6 = strtotime($date);
  228. if ((mb_strlen($date) == 4) && $date <= date('Y')) {
  229. $datevalid = true;
  230. } elseif ((mb_strlen($date) == 7) && ($date6 < strtotime('now'))) {
  231. $datevalid = true;
  232. } elseif ((mb_strlen($date) == 10) && ($date6 < strtotime('now'))) {
  233. $datevalid = true;
  234. }
  235. if (self::email($matches['name'])) {
  236. $namevalid = true;
  237. } else {
  238. $namevalid = self::email('info@' . $matches['name']);
  239. }
  240. return $datevalid && $namevalid;
  241. } else {
  242. return false;
  243. }
  244. }
  245. /**
  246. * Validate a number
  247. *
  248. * @param string $number Number to validate
  249. * @param array $options array where:
  250. * 'decimal' is the decimal char or false when decimal
  251. * not allowed.
  252. * i.e. ',.' to allow both ',' and '.'
  253. * 'dec_prec' Number of allowed decimals
  254. * 'min' minimum value
  255. * 'max' maximum value
  256. *
  257. * @return bool true if valid number, false if not
  258. */
  259. public static function number(string $number, array $options = []): bool
  260. {
  261. $decimal = $dec_prec = $min = $max = null;
  262. if (\is_array($options)) {
  263. extract($options);
  264. }
  265. $dec_prec = $dec_prec ? "{1,{$dec_prec}}" : '+';
  266. $dec_regex = $decimal ? "[{$decimal}][0-9]{$dec_prec}" : '';
  267. if (!preg_match("|^[-+]?\\s*[0-9]+({$dec_regex})?\$|", $number)) {
  268. return false;
  269. }
  270. if ($decimal != '.') {
  271. $number = strtr($number, $decimal, '.');
  272. }
  273. $number = (float) str_replace(' ', '', $number);
  274. if ($min !== null && $min > $number) {
  275. return false;
  276. }
  277. return !($max !== null && $max < $number);
  278. }
  279. /**
  280. * Converting a string to UTF-7 (RFC 2152)
  281. *
  282. * @param string $string string to be converted
  283. *
  284. * @return string converted string
  285. */
  286. private static function stringToUtf7(string $string): string
  287. {
  288. $return = '';
  289. $utf7 = [
  290. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  291. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
  292. 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  293. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
  294. 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
  295. '3', '4', '5', '6', '7', '8', '9', '+', ',',
  296. ];
  297. $state = 0;
  298. if (!empty($string)) {
  299. $i = 0;
  300. while ($i <= mb_strlen($string)) {
  301. $char = mb_substr($string, $i, 1);
  302. if ($state == 0) {
  303. if ((\ord($char) >= 0x7F) || (\ord($char) <= 0x1F)) {
  304. if ($char) {
  305. $return .= '&';
  306. }
  307. $state = 1;
  308. } elseif ($char == '&') {
  309. $return .= '&-';
  310. } else {
  311. $return .= $char;
  312. }
  313. } elseif (($i == mb_strlen($string)
  314. || !((\ord($char) >= 0x7F)) || (\ord($char) <= 0x1F))) {
  315. if ($state != 1) {
  316. if (\ord($char) > 64) {
  317. $return .= '';
  318. } else {
  319. $return .= $utf7[\ord($char)];
  320. }
  321. }
  322. $return .= '-';
  323. $state = 0;
  324. } else {
  325. switch ($state) {
  326. case 1:
  327. $return .= $utf7[\ord($char) >> 2];
  328. $residue = (\ord($char) & 0x03) << 4;
  329. $state = 2;
  330. break;
  331. case 2:
  332. $return .= $utf7[$residue | (\ord($char) >> 4)];
  333. $residue = (\ord($char) & 0x0F) << 2;
  334. $state = 3;
  335. break;
  336. case 3:
  337. $return .= $utf7[$residue | (\ord($char) >> 6)];
  338. $return .= $utf7[\ord($char) & 0x3F];
  339. $state = 1;
  340. break;
  341. }
  342. }
  343. ++$i;
  344. }
  345. return $return;
  346. }
  347. return '';
  348. }
  349. /**
  350. * Validate an email according to full RFC822 (inclusive human readable part)
  351. *
  352. * @param string $email email to validate,
  353. * will return the address for optional dns validation
  354. * @param array $options email() options
  355. *
  356. * @return bool true if valid email, false if not
  357. */
  358. private static function emailRFC822(string &$email, array &$options): bool
  359. {
  360. static $address = null;
  361. static $uncomment = null;
  362. if (!$address) {
  363. // atom = 1*<any CHAR except specials, SPACE and CTLs>
  364. $atom = '[^][()<>@,;:\\".\s\000-\037\177-\377]+\s*';
  365. // qtext = <any CHAR excepting <">, ; => may be folded
  366. // "\" & CR, and including linear-white-space>
  367. $qtext = '[^"\\\\\r]';
  368. // quoted-pair = "\" CHAR ; may quote any char
  369. $quoted_pair = '\\\\.';
  370. // quoted-string = <"> *(qtext/quoted-pair) <">; Regular qtext or
  371. // ; quoted chars.
  372. $quoted_string = '"(?:' . $qtext . '|' . $quoted_pair . ')*"\s*';
  373. // word = atom / quoted-string
  374. $word = '(?:' . $atom . '|' . $quoted_string . ')';
  375. // local-part = word *("." word) ; uninterpreted
  376. // ; case-preserved
  377. $local_part = $word . '(?:\.\s*' . $word . ')*';
  378. // dtext = <any CHAR excluding "[", ; => may be folded
  379. // "]", "\" & CR, & including linear-white-space>
  380. $dtext = '[^][\\\\\r]';
  381. // domain-literal = "[" *(dtext / quoted-pair) "]"
  382. $domain_literal = '\[(?:' . $dtext . '|' . $quoted_pair . ')*\]\s*';
  383. // sub-domain = domain-ref / domain-literal
  384. // domain-ref = atom ; symbolic reference
  385. $sub_domain = '(?:' . $atom . '|' . $domain_literal . ')';
  386. // domain = sub-domain *("." sub-domain)
  387. $domain = $sub_domain . '(?:\.\s*' . $sub_domain . ')*';
  388. // addr-spec = local-part "@" domain ; global address
  389. $addr_spec = $local_part . '@\s*' . $domain;
  390. // route = 1#("@" domain) ":" ; path-relative
  391. $route = '@' . $domain . '(?:,@\s*' . $domain . ')*:\s*';
  392. // route-addr = "<" [route] addr-spec ">"
  393. $route_addr = '<\s*(?:' . $route . ')?' . $addr_spec . '>\s*';
  394. // phrase = 1*word ; Sequence of words
  395. $phrase = $word . '+';
  396. // mailbox = addr-spec ; simple address
  397. // / phrase route-addr ; name & addr-spec
  398. $mailbox = '(?:' . $addr_spec . '|' . $phrase . $route_addr . ')';
  399. // group = phrase ":" [#mailbox] ";"
  400. $group = $phrase . ':\s*(?:' . $mailbox . '(?:,\s*' . $mailbox . ')*)?;\s*';
  401. // address = mailbox ; one addressee
  402. // / group ; named list
  403. $address = '/^\s*(?:' . $mailbox . '|' . $group . ')$/';
  404. $uncomment
  405. = '/((?:(?:\\\\"|[^("])*(?:' . $quoted_string
  406. . ')?)*)((?<!\\\\)\((?:(?2)|.)*?(?<!\\\\)\))/';
  407. }
  408. // strip comments
  409. $email = preg_replace($uncomment, '$1 ', $email);
  410. return preg_match($address, $email);
  411. }
  412. /**
  413. * Full TLD Validation function
  414. *
  415. * This function is used to make a much more proficient validation
  416. * against all types of official domain names.
  417. *
  418. * @param string $email the email address to check
  419. * @param array $options The options for validation
  420. *
  421. * @return bool True if validating succeeds
  422. */
  423. protected static function fullTLDValidation(
  424. string $email,
  425. array $options,
  426. ): bool {
  427. $validate = [];
  428. if (!empty($options['VALIDATE_ITLD_EMAILS'])) {
  429. $validate[] = 'itld';
  430. }
  431. if (!empty($options['VALIDATE_GTLD_EMAILS'])) {
  432. $validate[] = 'gtld';
  433. }
  434. if (!empty($options['VALIDATE_CCTLD_EMAILS'])) {
  435. $validate[] = 'cctld';
  436. }
  437. if (\count($validate) === 0) {
  438. array_push($validate, 'itld', 'gtld', 'cctld');
  439. }
  440. $toValidate = [];
  441. foreach ($validate as $valid) {
  442. $tmpVar = (string) $valid;
  443. $toValidate[$valid] = self::${$tmpVar};
  444. }
  445. $e = self::executeFullEmailValidation($email, $toValidate);
  446. return $e;
  447. }
  448. /**
  449. * Execute the validation
  450. *
  451. * This function will execute the full email vs tld
  452. * validation using an array of tlds passed to it.
  453. *
  454. * @param string $email the email to validate
  455. * @param array $arrayOfTLDs The array of the TLDs to validate
  456. *
  457. * @return bool true or false (Depending on if it validates or if it does not)
  458. */
  459. public static function executeFullEmailValidation(
  460. string $email,
  461. array $arrayOfTLDs,
  462. ): bool {
  463. $emailEnding = explode('.', $email);
  464. $emailEnding = $emailEnding[\count($emailEnding) - 1];
  465. foreach ($arrayOfTLDs as $validator => $keys) {
  466. if (\in_array($emailEnding, $keys)) {
  467. return true;
  468. }
  469. }
  470. return false;
  471. }
  472. /**
  473. * Validate an email
  474. *
  475. * @param string $email email to validate
  476. * @param mixed bool (BC) $check_domain Check or not if the domain exists
  477. * array $options associative array of options
  478. * 'check_domain' boolean Check or not if the domain exists
  479. * 'use_rfc822' boolean Apply the full RFC822 grammar
  480. *
  481. * Ex.
  482. * $options = [
  483. * 'check_domain' => 'true',
  484. * 'fullTLDValidation' => 'true',
  485. * 'use_rfc822' => 'true',
  486. * 'VALIDATE_GTLD_EMAILS' => 'true',
  487. * 'VALIDATE_CCTLD_EMAILS' => 'true',
  488. * 'VALIDATE_ITLD_EMAILS' => 'true',
  489. * ];
  490. * @param null|mixed $options
  491. *
  492. * @throws Exception
  493. *
  494. * @return bool true if valid email, false if not
  495. */
  496. public static function email(string $email, $options = null): bool
  497. {
  498. $check_domain = false;
  499. $use_rfc822 = false;
  500. if (\is_bool($options)) {
  501. $check_domain = $options;
  502. } elseif (\is_array($options)) {
  503. extract($options);
  504. }
  505. /**
  506. * Check for IDN usage so we can encode the domain as Punycode
  507. * before continuing.
  508. */
  509. $hasIDNA = false;
  510. if (self::includePathFileExists('Net/IDNA2.php')) {
  511. include_once('Net/IDNA2.php');
  512. $hasIDNA = true;
  513. }
  514. if ($hasIDNA === true) {
  515. if (str_contains($email, '@')) {
  516. $tmpEmail = explode('@', $email);
  517. $domain = array_pop($tmpEmail);
  518. // Check if the domain contains characters > 127 which means
  519. // it's an idn domain name.
  520. $chars = count_chars($domain, 1);
  521. if (!empty($chars) && max(array_keys($chars)) > 127) {
  522. $idna = &Net_IDNA2::singleton();
  523. $domain = $idna->encode($domain);
  524. }
  525. $tmpEmail[] = $domain;
  526. $email = implode('@', $tmpEmail);
  527. }
  528. }
  529. /**
  530. * @todo Fix bug here.. even if it passes this, it won't be passing
  531. * The regular expression below
  532. */
  533. if (isset($fullTLDValidation)) {
  534. //$valid = self::fullTLDValidation($email, $fullTLDValidation);
  535. $valid = self::fullTLDValidation($email, $options);
  536. if (!$valid) {
  537. return false;
  538. }
  539. }
  540. // the base regexp for address
  541. $regex = '&^(?: # recipient:
  542. ("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+")| #1 quoted name
  543. ([-\w!\#\$%\&\'*+~/^`|{}]+(?:\.[-\w!\#\$%\&\'*+~/^`|{}]+)*)) #2 OR dot-atom
  544. @(((\[)? #3 domain, 4 as IPv4, 5 optionally bracketed
  545. (?:(?:(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))\.){3}
  546. (?:(?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))))(?(5)\])|
  547. ((?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)*[a-z0-9](?:[-a-z0-9]*[a-z0-9])?) #6 domain as hostname
  548. \.((?:([^- ])[-a-z]*[-a-z]))) #7 TLD
  549. $&xi';
  550. //checks if exists the domain (MX or A)
  551. if ($use_rfc822 ? self::emailRFC822($email, $options)
  552. : preg_match($regex, $email)) {
  553. if ($check_domain && \function_exists('checkdnsrr')) {
  554. $domain = preg_replace('/[^-a-z.0-9]/i', '', array_pop(explode('@', $email)));
  555. return (bool) (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A'));
  556. }
  557. return true;
  558. }
  559. return false;
  560. }
  561. /**
  562. * Validate a string using the given format 'format'
  563. *
  564. * @param string $string String to validate
  565. * @param array|string $options Options array where:
  566. * 'format' is the format of the string
  567. * Ex:VALIDATE_NUM . VALIDATE_ALPHA (see constants)
  568. * 'min_length' minimum length
  569. * 'max_length' maximum length
  570. *
  571. * @return bool true if valid string, false if not
  572. */
  573. public static function string(string $string, $options): bool
  574. {
  575. $format = null;
  576. $min_length = 0;
  577. $max_length = 0;
  578. if (\is_array($options)) {
  579. extract($options);
  580. }
  581. if ($format && !preg_match("|^[{$format}]*\$|s", $string)) {
  582. return false;
  583. }
  584. if ($min_length && mb_strlen($string) < $min_length) {
  585. return false;
  586. }
  587. return !($max_length && mb_strlen($string) > $max_length);
  588. }
  589. /**
  590. * Validate an URI (RFC2396)
  591. * This function will validate 'foobarstring' by default, to get it to validate
  592. * only http, https, ftp and such you have to pass it in the allowed_schemes
  593. * option, like this:
  594. * <code>
  595. * $options = ['allowed_schemes' => ['http', 'https', 'ftp']]
  596. * var_dump(Validate::uri('http://www.example.org', $options));
  597. * </code>
  598. *
  599. * NOTE 1: The rfc2396 normally allows middle '-' in the top domain
  600. * e.g. http://example.co-m should be valid
  601. * However, as '-' is not used in any known TLD, it is invalid
  602. * NOTE 2: As double shlashes // are allowed in the path part, only full URIs
  603. * including an authority can be valid, no relative URIs
  604. * the // are mandatory (optionally preceeded by the 'sheme:' )
  605. * NOTE 3: the full complience to rfc2396 is not achieved by default
  606. * the characters ';/?:@$,' will not be accepted in the query part
  607. * if not urlencoded, refer to the option "strict'"
  608. *
  609. * @param string $url URI to validate
  610. * @param null|array $options Options used by the validation method.
  611. * key => type
  612. * 'domain_check' => boolean
  613. * Whether to check the DNS entry or not
  614. * 'allowed_schemes' => array, list of protocols
  615. * List of allowed schemes ('http',
  616. * 'ssh+svn', 'mms')
  617. * 'strict' => string the refused chars
  618. * in query and fragment parts
  619. * default: ';/?:@$,'
  620. * empty: accept all rfc2396 foreseen chars
  621. *
  622. * @throws Exception
  623. *
  624. * @return bool true if valid uri, false if not
  625. */
  626. public static function uri(string $url, ?array $options = null): bool
  627. {
  628. $strict = ';/?:@$,';
  629. $domain_check = false;
  630. $allowed_schemes = null;
  631. if (\is_array($options)) {
  632. extract($options);
  633. }
  634. if (\is_array($allowed_schemes)
  635. && \in_array('tag', $allowed_schemes)
  636. ) {
  637. if (str_starts_with($url, 'tag:')) {
  638. return self::uriRFC4151($url);
  639. }
  640. }
  641. if (preg_match(
  642. '&^(?:([a-z][-+.a-z0-9]*):)? # 1. scheme
  643. (?:// # authority start
  644. (?:((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();:\&=+$,])*)@)? # 2. authority-userinfo
  645. (?:((?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)*[a-z](?:[a-z0-9]+)?\.?) # 3. authority-hostname OR
  646. |([0-9]{1,3}(?:\.[0-9]{1,3}){3})) # 4. authority-ipv4
  647. (?::([0-9]*))?) # 5. authority-port
  648. ((?:/(?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'():@\&=+$,;])*)*/?)? # 6. path
  649. (?:\?([^#]*))? # 7. query
  650. (?:\#((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();/?:@\&=+$,])*))? # 8. fragment
  651. $&xi',
  652. $url,
  653. $matches,
  654. )) {
  655. $scheme = $matches[1] ?? '';
  656. $authority = $matches[3] ?? '';
  657. if (\is_array($allowed_schemes)
  658. && !\in_array($scheme, $allowed_schemes)
  659. ) {
  660. return false;
  661. }
  662. if (!empty($matches[4])) {
  663. $parts = explode('.', $matches[4]);
  664. foreach ($parts as $part) {
  665. if ($part > 255) {
  666. return false;
  667. }
  668. }
  669. } elseif ($domain_check && \function_exists('checkdnsrr')) {
  670. if (!checkdnsrr($authority, 'A')) {
  671. return false;
  672. }
  673. }
  674. if ($strict) {
  675. $strict = '#[' . preg_quote($strict, '#') . ']#';
  676. if ((!empty($matches[7]) && preg_match($strict, $matches[7]))
  677. || (!empty($matches[8]) && preg_match($strict, $matches[8]))) {
  678. return false;
  679. }
  680. }
  681. return true;
  682. }
  683. return false;
  684. }
  685. /**
  686. * Substr
  687. *
  688. * @param string &$date Date
  689. * @param string $num Length
  690. * @param false|string $opt Unknown
  691. */
  692. private static function substr(
  693. string &$date,
  694. string $num,
  695. $opt = false,
  696. ): string {
  697. if (
  698. $opt
  699. && mb_strlen($date) >= $opt
  700. && preg_match('/^[0-9]{' . $opt . '}/', $date, $m)
  701. ) {
  702. $ret = $m[0];
  703. } else {
  704. $ret = mb_substr($date, 0, $num);
  705. }
  706. $date = mb_substr($date, mb_strlen($ret));
  707. return $ret;
  708. }
  709. protected static function modf($val, $div)
  710. {
  711. if (\function_exists('bcmod')) {
  712. return bcmod($val, $div);
  713. } elseif (\function_exists('fmod')) {
  714. return fmod($val, $div);
  715. }
  716. $r = $val / $div;
  717. $i = (int) $r;
  718. return (int) ($val - $i * $div + .1);
  719. }
  720. /**
  721. * Calculates sum of product of number digits with weights
  722. *
  723. * @param string $number number string
  724. * @param array $weights reference to array of weights
  725. *
  726. * @return int returns product of number digits with weights
  727. */
  728. protected static function multWeights(
  729. string $number,
  730. array &$weights,
  731. ): int {
  732. if (!\is_array($weights)) {
  733. return -1;
  734. }
  735. $sum = 0;
  736. $count = min(\count($weights), mb_strlen($number));
  737. if ($count == 0) { // empty string or weights array
  738. return -1;
  739. }
  740. for ($i = 0; $i < $count; ++$i) {
  741. $sum += (int) (mb_substr($number, $i, 1)) * $weights[$i];
  742. }
  743. return $sum;
  744. }
  745. /**
  746. * Calculates control digit for a given number
  747. *
  748. * @param string $number number string
  749. * @param array $weights reference to array of weights
  750. * @param int $modulo (optionsl) number
  751. * @param int $subtract (optional) number
  752. * @param bool $allow_high (optional) true if function can return number higher than 10
  753. *
  754. * @return int -1 calculated control number is returned
  755. */
  756. protected static function getControlNumber(
  757. string $number,
  758. array &$weights,
  759. int $modulo = 10,
  760. int $subtract = 0,
  761. bool $allow_high = false,
  762. ): int {
  763. // calc sum
  764. $sum = self::multWeights($number, $weights);
  765. if ($sum == -1) {
  766. return -1;
  767. }
  768. $mod = self::modf($sum, $modulo); // calculate control digit
  769. if ($subtract > $mod && $mod > 0) {
  770. $mod = $subtract - $mod;
  771. }
  772. if ($allow_high === false) {
  773. $mod %= 10; // change 10 to zero
  774. }
  775. return $mod;
  776. }
  777. /**
  778. * Validates a number
  779. *
  780. * @param string $number number to validate
  781. * @param array $weights reference to array of weights
  782. * @param int $modulo (optional) number
  783. * @param int $subtract (optional) number
  784. *
  785. * @return bool true if valid, false if not
  786. */
  787. protected static function checkControlNumber(
  788. string $number,
  789. array &$weights,
  790. int $modulo = 10,
  791. int $subtract = 0,
  792. ): bool {
  793. if (mb_strlen($number) < \count($weights)) {
  794. return false;
  795. }
  796. $target_digit = mb_substr($number, \count($weights), 1);
  797. $control_digit = self::getControlNumber(
  798. $number,
  799. $weights,
  800. $modulo,
  801. $subtract,
  802. ($modulo > 10),
  803. );
  804. if ($control_digit == -1) {
  805. return false;
  806. }
  807. if ($target_digit === 'X' && $control_digit == 10) {
  808. return true;
  809. }
  810. return !($control_digit != $target_digit);
  811. }
  812. /**
  813. * Bulk data validation for data introduced in the form of an
  814. * assoc array in the form $var_name => $value.
  815. * Can be used on any of Validate subpackages
  816. *
  817. * @param array $data Ex: ['name' => 'toto', 'email' => 'toto@thing.info'];
  818. * @param array $val_type Contains the validation type and all parameters used in.
  819. * 'val_type' is not optional
  820. * others validations properties must have the same name as the function
  821. * parameters.
  822. * Ex: ['toto' => ['type'=>'string','format'='toto@thing.info','min_length'=>5]];
  823. * @param bool $remove if set, the elements not listed in data will be removed
  824. *
  825. * @return array value name => true|false the value name comes from the data key
  826. */
  827. public static function multiple(
  828. array &$data,
  829. array &$val_type,
  830. bool $remove = false,
  831. ): array {
  832. $keys = array_keys($data);
  833. $valid = [];
  834. foreach ($keys as $var_name) {
  835. if (!isset($val_type[$var_name])) {
  836. if ($remove) {
  837. unset($data[$var_name]);
  838. }
  839. continue;
  840. }
  841. $opt = $val_type[$var_name];
  842. $methods = get_class_methods('Validate');
  843. $val2check = $data[$var_name];
  844. // core validation method
  845. if (\in_array(mb_strtolower($opt['type']), $methods)) {
  846. //$opt[$opt['type']] = $data[$var_name];
  847. $method = $opt['type'];
  848. unset($opt['type']);
  849. if (sizeof($opt) == 1 && \is_array(reset($opt))) {
  850. $opt = array_pop($opt);
  851. }
  852. $valid[$var_name] = \call_user_func(['Validate', $method], $val2check, $opt);
  853. /**
  854. * external validation method in the form:
  855. * "<class name><underscore><method name>"
  856. * Ex: us_ssn will include class Validate/US.php and call method ssn()
  857. */
  858. } elseif (str_contains($opt['type'], '_')) {
  859. $validateType = explode('_', $opt['type']);
  860. $method = array_pop($validateType);
  861. $class = implode('_', $validateType);
  862. $classPath = str_replace('_', \DIRECTORY_SEPARATOR, $class);
  863. $class = 'Validate_' . $class;
  864. if (self::includePathFileExists("Validate/{$classPath}.php")) {
  865. include_once "Validate/{$classPath}.php";
  866. } else {
  867. trigger_error("{$class} isn't installed or you may have some permission issues", \E_USER_ERROR);
  868. }
  869. $ce = mb_substr(phpversion(), 0, 1) > 4
  870. ? class_exists($class, false) : class_exists($class);
  871. if (!$ce
  872. || !\in_array($method, get_class_methods($class))
  873. ) {
  874. trigger_error(
  875. "Invalid validation type {$class}::{$method}",
  876. \E_USER_WARNING,
  877. );
  878. continue;
  879. }
  880. unset($opt['type']);
  881. if (sizeof($opt) == 1) {
  882. $opt = array_pop($opt);
  883. }
  884. $valid[$var_name] = \call_user_func(
  885. [$class, $method],
  886. $data[$var_name],
  887. $opt,
  888. );
  889. } else {
  890. trigger_error(
  891. "Invalid validation type {$opt['type']}",
  892. \E_USER_WARNING,
  893. );
  894. }
  895. }
  896. return $valid;
  897. }
  898. /**
  899. * Determine whether specified file exists along the include path.
  900. *
  901. * @param string $filename file to search for
  902. *
  903. * @return bool true if file exists
  904. */
  905. private static function includePathFileExists(string $filename): bool
  906. {
  907. $paths = explode(':', ini_get('include_path'));
  908. $result = false;
  909. foreach ($paths as $val) {
  910. $result = file_exists($val . '/' . $filename);
  911. if ($result) {
  912. break;
  913. }
  914. }
  915. return $result;
  916. }
  917. }