Validate.php 34 KB

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