EmailAddress.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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-2009 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-2009 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 DOT_ATOM = 'emailAddressDotAtom';
  42. const QUOTED_STRING = 'emailAddressQuotedString';
  43. const INVALID_LOCAL_PART = 'emailAddressInvalidLocalPart';
  44. const LENGTH_EXCEEDED = 'emailAddressLengthExceeded';
  45. /**
  46. * @var array
  47. */
  48. protected $_messageTemplates = array(
  49. self::INVALID => "Invalid type given, value should be a string",
  50. self::INVALID_FORMAT => "'%value%' is not a valid email address in the basic format local-part@hostname",
  51. self::INVALID_HOSTNAME => "'%hostname%' is not a valid hostname for email address '%value%'",
  52. self::INVALID_MX_RECORD => "'%hostname%' does not appear to have a valid MX record for the email address '%value%'",
  53. self::DOT_ATOM => "'%localPart%' not matched against dot-atom format",
  54. self::QUOTED_STRING => "'%localPart%' not matched against quoted-string format",
  55. self::INVALID_LOCAL_PART => "'%localPart%' is not a valid local part for email address '%value%'",
  56. self::LENGTH_EXCEEDED => "'%value%' exceeds the allowed length"
  57. );
  58. /**
  59. * @var array
  60. */
  61. protected $_messageVariables = array(
  62. 'hostname' => '_hostname',
  63. 'localPart' => '_localPart'
  64. );
  65. /**
  66. * Local object for validating the hostname part of an email address
  67. *
  68. * @var Zend_Validate_Hostname
  69. * @depreciated
  70. */
  71. public $hostnameValidator;
  72. /**
  73. * Whether we check for a valid MX record via DNS
  74. *
  75. * @var boolean
  76. */
  77. protected $_validateMx = false;
  78. /**
  79. * @var string
  80. */
  81. protected $_hostname;
  82. /**
  83. * @var string
  84. */
  85. protected $_localPart;
  86. /**
  87. * Instantiates hostname validator for local use
  88. *
  89. * You can pass a bitfield to determine what types of hostnames are allowed.
  90. * These bitfields are defined by the ALLOW_* constants in Zend_Validate_Hostname
  91. * The default is to allow DNS hostnames only
  92. *
  93. * @param integer $allow OPTIONAL
  94. * @param bool $validateMx OPTIONAL
  95. * @param Zend_Validate_Hostname $hostnameValidator OPTIONAL
  96. * @return void
  97. */
  98. public function __construct($allow = Zend_Validate_Hostname::ALLOW_DNS, $validateMx = false, Zend_Validate_Hostname $hostnameValidator = null)
  99. {
  100. $this->setValidateMx($validateMx);
  101. $this->setHostnameValidator($hostnameValidator, $allow);
  102. }
  103. /**
  104. * Sets the validation failure message template for a particular key
  105. * Adds the ability to set messages to the attached hostname validator
  106. *
  107. * @param string $messageString
  108. * @param string $messageKey OPTIONAL
  109. * @return Zend_Validate_Abstract Provides a fluent interface
  110. * @throws Zend_Validate_Exception
  111. */
  112. public function setMessage($messageString, $messageKey = null)
  113. {
  114. $messageKeys = $messageKey;
  115. if ($messageKey === null) {
  116. $keys = array_keys($this->_messageTemplates);
  117. $messageKeys = current($keys);
  118. }
  119. if (!isset($this->_messageTemplates[$messageKeys])) {
  120. $this->hostnameValidator->setMessage($messageString, $messageKey);
  121. }
  122. $this->_messageTemplates[$messageKeys] = $messageString;
  123. return $this;
  124. }
  125. /**
  126. * Returns the set hostname validator
  127. *
  128. * @return Zend_Validate_Hostname
  129. */
  130. public function getHostnameValidator()
  131. {
  132. return $this->hostnameValidator;
  133. }
  134. /**
  135. * @param Zend_Validate_Hostname $hostnameValidator OPTIONAL
  136. * @param int $allow OPTIONAL
  137. * @return void
  138. */
  139. public function setHostnameValidator(Zend_Validate_Hostname $hostnameValidator = null, $allow = Zend_Validate_Hostname::ALLOW_DNS)
  140. {
  141. if ($hostnameValidator === null) {
  142. $hostnameValidator = new Zend_Validate_Hostname($allow);
  143. }
  144. $this->hostnameValidator = $hostnameValidator;
  145. }
  146. /**
  147. * Whether MX checking via dns_get_mx is supported or not
  148. *
  149. * This currently only works on UNIX systems
  150. *
  151. * @return boolean
  152. */
  153. public function validateMxSupported()
  154. {
  155. return function_exists('dns_get_mx');
  156. }
  157. /**
  158. * Set whether we check for a valid MX record via DNS
  159. *
  160. * This only applies when DNS hostnames are validated
  161. *
  162. * @param boolean $allowed Set allowed to true to validate for MX records, and false to not validate them
  163. */
  164. public function setValidateMx($allowed)
  165. {
  166. $this->_validateMx = (bool) $allowed;
  167. }
  168. /**
  169. * Defined by Zend_Validate_Interface
  170. *
  171. * Returns true if and only if $value is a valid email address
  172. * according to RFC2822
  173. *
  174. * @link http://www.ietf.org/rfc/rfc2822.txt RFC2822
  175. * @link http://www.columbia.edu/kermit/ascii.html US-ASCII characters
  176. * @param string $value
  177. * @return boolean
  178. */
  179. public function isValid($value)
  180. {
  181. if (!is_string($value)) {
  182. $this->_error(self::INVALID);
  183. return false;
  184. }
  185. $matches = array();
  186. $length = true;
  187. $this->_setValue($value);
  188. // Split email address up and disallow '..'
  189. if ((strpos($value, '..') !== false) or
  190. (!preg_match('/^(.+)@([^@]+)$/', $value, $matches))) {
  191. $this->_error(self::INVALID_FORMAT);
  192. return false;
  193. }
  194. $this->_localPart = $matches[1];
  195. $this->_hostname = $matches[2];
  196. if ((strlen($this->_localPart) > 64) || (strlen($this->_hostname) > 255)) {
  197. $length = false;
  198. $this->_error(self::LENGTH_EXCEEDED);
  199. }
  200. // Match hostname part
  201. $hostnameResult = $this->hostnameValidator->setTranslator($this->getTranslator())
  202. ->isValid($this->_hostname);
  203. if (!$hostnameResult) {
  204. $this->_error(self::INVALID_HOSTNAME);
  205. // Get messages and errors from hostnameValidator
  206. foreach ($this->hostnameValidator->getMessages() as $code => $message) {
  207. $this->_messages[$code] = $message;
  208. }
  209. foreach ($this->hostnameValidator->getErrors() as $error) {
  210. $this->_errors[] = $error;
  211. }
  212. } else if ($this->_validateMx) {
  213. // MX check on hostname via dns_get_record()
  214. if ($this->validateMxSupported()) {
  215. $mxHosts = array();
  216. dns_get_mx($this->_hostname, $mxHosts);
  217. if (count($mxHosts) < 1) {
  218. $hostnameResult = false;
  219. $this->_error(self::INVALID_MX_RECORD);
  220. }
  221. } else {
  222. /**
  223. * MX checks are not supported by this system
  224. * @see Zend_Validate_Exception
  225. */
  226. require_once 'Zend/Validate/Exception.php';
  227. throw new Zend_Validate_Exception('Internal error: MX checking not available on this system');
  228. }
  229. }
  230. // First try to match the local part on the common dot-atom format
  231. $localResult = false;
  232. // Dot-atom characters are: 1*atext *("." 1*atext)
  233. // atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*",
  234. // "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~"
  235. $atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d\x7e';
  236. if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $this->_localPart)) {
  237. $localResult = true;
  238. } else {
  239. // Try quoted string format
  240. // Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE
  241. // qtext: Non white space controls, and the rest of the US-ASCII characters not
  242. // including "\" or the quote character
  243. $noWsCtl = '\x01-\x08\x0b\x0c\x0e-\x1f\x7f';
  244. $qtext = $noWsCtl . '\x21\x23-\x5b\x5d-\x7e';
  245. $ws = '\x20\x09';
  246. if (preg_match('/^\x22([' . $ws . $qtext . '])*[$ws]?\x22$/', $this->_localPart)) {
  247. $localResult = true;
  248. } else {
  249. $this->_error(self::DOT_ATOM);
  250. $this->_error(self::QUOTED_STRING);
  251. $this->_error(self::INVALID_LOCAL_PART);
  252. }
  253. }
  254. // If both parts valid, return true
  255. if ($localResult && $hostnameResult && $length) {
  256. return true;
  257. } else {
  258. return false;
  259. }
  260. }
  261. }