EmailAddress.php 17 KB

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