Validate.php 34 KB

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