EmailAddress.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Validate
  17. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * @see Zend_Validate_Abstract
  23. */
  24. #require_once 'Zend/Validate/Abstract.php';
  25. /**
  26. * @see Zend_Validate_Hostname
  27. */
  28. #require_once 'Zend/Validate/Hostname.php';
  29. /**
  30. * @category Zend
  31. * @package Zend_Validate
  32. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. */
  35. class Zend_Validate_EmailAddress extends Zend_Validate_Abstract
  36. {
  37. const INVALID = 'emailAddressInvalid';
  38. const INVALID_FORMAT = 'emailAddressInvalidFormat';
  39. const INVALID_HOSTNAME = 'emailAddressInvalidHostname';
  40. const INVALID_MX_RECORD = 'emailAddressInvalidMxRecord';
  41. const INVALID_SEGMENT = 'emailAddressInvalidSegment';
  42. const DOT_ATOM = 'emailAddressDotAtom';
  43. const QUOTED_STRING = 'emailAddressQuotedString';
  44. const INVALID_LOCAL_PART = 'emailAddressInvalidLocalPart';
  45. const LENGTH_EXCEEDED = 'emailAddressLengthExceeded';
  46. /**
  47. * @var array
  48. */
  49. protected $_messageTemplates = array(
  50. self::INVALID => "Invalid type given. String expected",
  51. self::INVALID_FORMAT => "'%value%' is not a valid email address in the basic format local-part@hostname",
  52. self::INVALID_HOSTNAME => "'%hostname%' is not a valid hostname for email address '%value%'",
  53. self::INVALID_MX_RECORD => "'%hostname%' does not appear to have a valid MX record for the email address '%value%'",
  54. self::INVALID_SEGMENT => "'%hostname%' is not in a routable network segment. The email address '%value%' should not be resolved from public network",
  55. self::DOT_ATOM => "'%localPart%' can not be matched against dot-atom format",
  56. self::QUOTED_STRING => "'%localPart%' can not be matched against quoted-string format",
  57. self::INVALID_LOCAL_PART => "'%localPart%' is not a valid local part for email address '%value%'",
  58. self::LENGTH_EXCEEDED => "'%value%' exceeds the allowed length",
  59. );
  60. /**
  61. * As of RFC5753 (JAN 2010), the following blocks are no longer reserved:
  62. * - 128.0.0.0/16
  63. * - 191.255.0.0/16
  64. * - 223.255.255.0/24
  65. * @see http://tools.ietf.org/html/rfc5735#page-6
  66. *
  67. * As of RFC6598 (APR 2012), the following blocks are now reserved:
  68. * - 100.64.0.0/10
  69. * @see http://tools.ietf.org/html/rfc6598#section-7
  70. *
  71. * @see http://en.wikipedia.org/wiki/IPv4
  72. * @var array
  73. */
  74. protected $_invalidIp = array(
  75. '0' => '0.0.0.0/8',
  76. '10' => '10.0.0.0/8',
  77. '100' => '100.64.0.0/10',
  78. '127' => '127.0.0.0/8',
  79. '169' => '169.254.0.0/16',
  80. '172' => '172.16.0.0/12',
  81. '192' => array(
  82. '192.0.0.0/24',
  83. '192.0.2.0/24',
  84. '192.88.99.0/24',
  85. '192.168.0.0/16'
  86. ),
  87. '198' => '198.18.0.0/15',
  88. '224' => '224.0.0.0/4',
  89. '240' => '240.0.0.0/4'
  90. );
  91. /**
  92. * @var array
  93. */
  94. protected $_messageVariables = array(
  95. 'hostname' => '_hostname',
  96. 'localPart' => '_localPart'
  97. );
  98. /**
  99. * @var string
  100. */
  101. protected $_hostname;
  102. /**
  103. * @var string
  104. */
  105. protected $_localPart;
  106. /**
  107. * Internal options array
  108. */
  109. protected $_options = array(
  110. 'mx' => false,
  111. 'deep' => false,
  112. 'domain' => true,
  113. 'allow' => Zend_Validate_Hostname::ALLOW_DNS,
  114. 'hostname' => null
  115. );
  116. /**
  117. * Instantiates hostname validator for local use
  118. *
  119. * The following option keys are supported:
  120. * 'hostname' => A hostname validator, see Zend_Validate_Hostname
  121. * 'allow' => Options for the hostname validator, see Zend_Validate_Hostname::ALLOW_*
  122. * 'mx' => If MX check should be enabled, boolean
  123. * 'deep' => If a deep MX check should be done, boolean
  124. *
  125. * @param array|string|Zend_Config $options OPTIONAL
  126. */
  127. public function __construct($options = array())
  128. {
  129. if ($options instanceof Zend_Config) {
  130. $options = $options->toArray();
  131. } else if (!is_array($options)) {
  132. $options = func_get_args();
  133. $temp['allow'] = array_shift($options);
  134. if (!empty($options)) {
  135. $temp['mx'] = array_shift($options);
  136. }
  137. if (!empty($options)) {
  138. $temp['hostname'] = array_shift($options);
  139. }
  140. $options = $temp;
  141. }
  142. $options += $this->_options;
  143. $this->setOptions($options);
  144. }
  145. /**
  146. * Returns all set Options
  147. *
  148. * @return array
  149. */
  150. public function getOptions()
  151. {
  152. return $this->_options;
  153. }
  154. /**
  155. * Set options for the email validator
  156. *
  157. * @param array $options
  158. * @return Zend_Validate_EmailAddress Provides a fluent inteface
  159. */
  160. public function setOptions(array $options = array())
  161. {
  162. if (array_key_exists('messages', $options)) {
  163. $this->setMessages($options['messages']);
  164. }
  165. if (array_key_exists('hostname', $options)) {
  166. if (array_key_exists('allow', $options)) {
  167. $this->setHostnameValidator($options['hostname'], $options['allow']);
  168. } else {
  169. $this->setHostnameValidator($options['hostname']);
  170. }
  171. } elseif ($this->_options['hostname'] == null) {
  172. $this->setHostnameValidator();
  173. }
  174. if (array_key_exists('mx', $options)) {
  175. $this->setValidateMx($options['mx']);
  176. }
  177. if (array_key_exists('deep', $options)) {
  178. $this->setDeepMxCheck($options['deep']);
  179. }
  180. if (array_key_exists('domain', $options)) {
  181. $this->setDomainCheck($options['domain']);
  182. }
  183. return $this;
  184. }
  185. /**
  186. * Sets the validation failure message template for a particular key
  187. * Adds the ability to set messages to the attached hostname validator
  188. *
  189. * @param string $messageString
  190. * @param string $messageKey OPTIONAL
  191. * @return Zend_Validate_Abstract Provides a fluent interface
  192. * @throws Zend_Validate_Exception
  193. */
  194. public function setMessage($messageString, $messageKey = null)
  195. {
  196. if ($messageKey === null) {
  197. $this->_options['hostname']->setMessage($messageString);
  198. parent::setMessage($messageString);
  199. return $this;
  200. }
  201. if (!isset($this->_messageTemplates[$messageKey])) {
  202. $this->_options['hostname']->setMessage($messageString, $messageKey);
  203. }
  204. $this->_messageTemplates[$messageKey] = $messageString;
  205. return $this;
  206. }
  207. /**
  208. * Returns the set hostname validator
  209. *
  210. * @return Zend_Validate_Hostname
  211. */
  212. public function getHostnameValidator()
  213. {
  214. return $this->_options['hostname'];
  215. }
  216. /**
  217. * @param Zend_Validate_Hostname $hostnameValidator OPTIONAL
  218. * @param int $allow OPTIONAL
  219. * @return $this
  220. */
  221. public function setHostnameValidator(Zend_Validate_Hostname $hostnameValidator = null, $allow = Zend_Validate_Hostname::ALLOW_DNS)
  222. {
  223. if (!$hostnameValidator) {
  224. $hostnameValidator = new Zend_Validate_Hostname($allow);
  225. }
  226. $this->_options['hostname'] = $hostnameValidator;
  227. $this->_options['allow'] = $allow;
  228. return $this;
  229. }
  230. /**
  231. * Whether MX checking via getmxrr is supported or not
  232. *
  233. * This currently only works on UNIX systems
  234. *
  235. * @return boolean
  236. */
  237. public function validateMxSupported()
  238. {
  239. return function_exists('getmxrr');
  240. }
  241. /**
  242. * Returns the set validateMx option
  243. *
  244. * @return boolean
  245. */
  246. public function getValidateMx()
  247. {
  248. return $this->_options['mx'];
  249. }
  250. /**
  251. * Set whether we check for a valid MX record via DNS
  252. *
  253. * This only applies when DNS hostnames are validated
  254. *
  255. * @param boolean $mx Set allowed to true to validate for MX records, and false to not validate them
  256. * @throws Zend_Validate_Exception
  257. * @return Zend_Validate_EmailAddress Provides a fluent inteface
  258. */
  259. public function setValidateMx($mx)
  260. {
  261. if ((bool) $mx && !$this->validateMxSupported()) {
  262. #require_once 'Zend/Validate/Exception.php';
  263. throw new Zend_Validate_Exception('MX checking not available on this system');
  264. }
  265. $this->_options['mx'] = (bool) $mx;
  266. return $this;
  267. }
  268. /**
  269. * Returns the set deepMxCheck option
  270. *
  271. * @return boolean
  272. */
  273. public function getDeepMxCheck()
  274. {
  275. return $this->_options['deep'];
  276. }
  277. /**
  278. * Set whether we check MX record should be a deep validation
  279. *
  280. * @param boolean $deep Set deep to true to perform a deep validation process for MX records
  281. * @return Zend_Validate_EmailAddress Provides a fluent inteface
  282. */
  283. public function setDeepMxCheck($deep)
  284. {
  285. $this->_options['deep'] = (bool) $deep;
  286. return $this;
  287. }
  288. /**
  289. * Returns the set domainCheck option
  290. *
  291. * @return unknown
  292. */
  293. public function getDomainCheck()
  294. {
  295. return $this->_options['domain'];
  296. }
  297. /**
  298. * Sets if the domain should also be checked
  299. * or only the local part of the email address
  300. *
  301. * @param boolean $domain
  302. * @return Zend_Validate_EmailAddress Provides a fluent inteface
  303. */
  304. public function setDomainCheck($domain = true)
  305. {
  306. $this->_options['domain'] = (boolean) $domain;
  307. return $this;
  308. }
  309. /**
  310. * Returns if the given host is reserved
  311. *
  312. * @param string $host
  313. * @return boolean
  314. */
  315. private function _isReserved($host){
  316. if (!preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $host)) {
  317. $host = gethostbyname($host);
  318. }
  319. $octet = explode('.',$host);
  320. if ((int)$octet[0] >= 224) {
  321. return true;
  322. } else if (array_key_exists($octet[0], $this->_invalidIp)) {
  323. foreach ((array)$this->_invalidIp[$octet[0]] as $subnetData) {
  324. // we skip the first loop as we already know that octet matches
  325. for ($i = 1; $i < 4; $i++) {
  326. if (strpos($subnetData, $octet[$i]) !== $i * 4) {
  327. break;
  328. }
  329. }
  330. $host = explode("/", $subnetData);
  331. $binaryHost = "";
  332. $tmp = explode(".", $host[0]);
  333. for ($i = 0; $i < 4 ; $i++) {
  334. $binaryHost .= str_pad(decbin($tmp[$i]), 8, "0", STR_PAD_LEFT);
  335. }
  336. $segmentData = array(
  337. 'network' => (int)$this->_toIp(str_pad(substr($binaryHost, 0, $host[1]), 32, 0)),
  338. 'broadcast' => (int)$this->_toIp(str_pad(substr($binaryHost, 0, $host[1]), 32, 1))
  339. );
  340. for ($j = $i; $j < 4; $j++) {
  341. if ((int)$octet[$j] < $segmentData['network'][$j] ||
  342. (int)$octet[$j] > $segmentData['broadcast'][$j]) {
  343. return false;
  344. }
  345. }
  346. }
  347. return true;
  348. } else {
  349. return false;
  350. }
  351. }
  352. /**
  353. * Converts a binary string to an IP address
  354. *
  355. * @param string $binary
  356. * @return mixed
  357. */
  358. private function _toIp($binary)
  359. {
  360. $ip = array();
  361. $tmp = explode(".", chunk_split($binary, 8, "."));
  362. for ($i = 0; $i < 4 ; $i++) {
  363. $ip[$i] = bindec($tmp[$i]);
  364. }
  365. return $ip;
  366. }
  367. /**
  368. * Internal method to validate the local part of the email address
  369. *
  370. * @return boolean
  371. */
  372. private function _validateLocalPart()
  373. {
  374. // First try to match the local part on the common dot-atom format
  375. $result = false;
  376. // Dot-atom characters are: 1*atext *("." 1*atext)
  377. // atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*",
  378. // "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~"
  379. $atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d\x7e';
  380. if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $this->_localPart)) {
  381. $result = true;
  382. } else {
  383. // Try quoted string format (RFC 5321 Chapter 4.1.2)
  384. // Quoted-string characters are: DQUOTE *(qtext/quoted-pair) DQUOTE
  385. $qtext = '\x20-\x21\x23-\x5b\x5d-\x7e'; // %d32-33 / %d35-91 / %d93-126
  386. $quotedPair = '\x20-\x7e'; // %d92 %d32-126
  387. if (preg_match('/^"(['. $qtext .']|\x5c[' . $quotedPair . '])*"$/', $this->localPart)) {
  388. $result = true;
  389. } else {
  390. $this->_error(self::DOT_ATOM);
  391. $this->_error(self::QUOTED_STRING);
  392. $this->_error(self::INVALID_LOCAL_PART);
  393. }
  394. }
  395. return $result;
  396. }
  397. /**
  398. * Internal method to validate the servers MX records
  399. *
  400. * @return boolean
  401. */
  402. private function _validateMXRecords()
  403. {
  404. $mxHosts = array();
  405. $hostname = $this->_hostname;
  406. //decode IDN domain name if possible
  407. if (function_exists('idn_to_ascii')) {
  408. $hostname = idn_to_ascii($this->_hostname);
  409. }
  410. $result = getmxrr($hostname, $mxHosts);
  411. if (!$result) {
  412. $this->_error(self::INVALID_MX_RECORD);
  413. } else if ($this->_options['deep'] && function_exists('checkdnsrr')) {
  414. $validAddress = false;
  415. $reserved = true;
  416. foreach ($mxHosts as $hostname) {
  417. $res = $this->_isReserved($hostname);
  418. if (!$res) {
  419. $reserved = false;
  420. }
  421. if (!$res
  422. && (checkdnsrr($hostname, "A")
  423. || checkdnsrr($hostname, "AAAA")
  424. || checkdnsrr($hostname, "A6"))) {
  425. $validAddress = true;
  426. break;
  427. }
  428. }
  429. if (!$validAddress) {
  430. $result = false;
  431. if ($reserved) {
  432. $this->_error(self::INVALID_SEGMENT);
  433. } else {
  434. $this->_error(self::INVALID_MX_RECORD);
  435. }
  436. }
  437. }
  438. return $result;
  439. }
  440. /**
  441. * Internal method to validate the hostname part of the email address
  442. *
  443. * @return boolean
  444. */
  445. private function _validateHostnamePart()
  446. {
  447. $hostname = $this->_options['hostname']->setTranslator($this->getTranslator())
  448. ->isValid($this->_hostname);
  449. if (!$hostname) {
  450. $this->_error(self::INVALID_HOSTNAME);
  451. // Get messages and errors from hostnameValidator
  452. foreach ($this->_options['hostname']->getMessages() as $code => $message) {
  453. $this->_messages[$code] = $message;
  454. }
  455. foreach ($this->_options['hostname']->getErrors() as $error) {
  456. $this->_errors[] = $error;
  457. }
  458. } else if ($this->_options['mx']) {
  459. // MX check on hostname
  460. $hostname = $this->_validateMXRecords();
  461. }
  462. return $hostname;
  463. }
  464. /**
  465. * Defined by Zend_Validate_Interface
  466. *
  467. * Returns true if and only if $value is a valid email address
  468. * according to RFC2822
  469. *
  470. * @link http://www.ietf.org/rfc/rfc2822.txt RFC2822
  471. * @link http://www.columbia.edu/kermit/ascii.html US-ASCII characters
  472. * @param string $value
  473. * @return boolean
  474. */
  475. public function isValid($value)
  476. {
  477. if (!is_string($value)) {
  478. $this->_error(self::INVALID);
  479. return false;
  480. }
  481. $matches = array();
  482. $length = true;
  483. $this->_setValue($value);
  484. // Split email address up and disallow '..'
  485. if ((strpos($value, '..') !== false) or
  486. (!preg_match('/^(.+)@([^@]+)$/', $value, $matches))) {
  487. $this->_error(self::INVALID_FORMAT);
  488. return false;
  489. }
  490. $this->_localPart = $matches[1];
  491. $this->_hostname = $matches[2];
  492. if ((strlen($this->_localPart) > 64) || (strlen($this->_hostname) > 255)) {
  493. $length = false;
  494. $this->_error(self::LENGTH_EXCEEDED);
  495. }
  496. // Match hostname part
  497. if ($this->_options['domain']) {
  498. $hostname = $this->_validateHostnamePart();
  499. }
  500. $local = $this->_validateLocalPart();
  501. // If both parts valid, return true
  502. if ($local && $length) {
  503. if (($this->_options['domain'] && $hostname) || !$this->_options['domain']) {
  504. return true;
  505. }
  506. }
  507. return false;
  508. }
  509. }