PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/concreteOLD/libraries/3rdparty/Zend/Validate/EmailAddress.php

https://bitbucket.org/selfeky/xclusivescardwebsite
PHP | 560 lines | 310 code | 63 blank | 187 comment | 60 complexity | 4f4874d9498bece25df563fa0b4aa4cc MD5 | raw file
  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-2011 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id: EmailAddress.php 23775 2011-03-01 17:25:24Z ralph $
  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-2011 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 no valid email address in the basic format local-part@hostname",
  52. self::INVALID_HOSTNAME => "'%hostname%' is no 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 no 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. }
  165. if (array_key_exists('mx', $options)) {
  166. $this->setValidateMx($options['mx']);
  167. }
  168. if (array_key_exists('deep', $options)) {
  169. $this->setDeepMxCheck($options['deep']);
  170. }
  171. if (array_key_exists('domain', $options)) {
  172. $this->setDomainCheck($options['domain']);
  173. }
  174. return $this;
  175. }
  176. /**
  177. * Sets the validation failure message template for a particular key
  178. * Adds the ability to set messages to the attached hostname validator
  179. *
  180. * @param string $messageString
  181. * @param string $messageKey OPTIONAL
  182. * @return Zend_Validate_Abstract Provides a fluent interface
  183. * @throws Zend_Validate_Exception
  184. */
  185. public function setMessage($messageString, $messageKey = null)
  186. {
  187. $messageKeys = $messageKey;
  188. if ($messageKey === null) {
  189. $keys = array_keys($this->_messageTemplates);
  190. $messageKeys = current($keys);
  191. }
  192. if (!isset($this->_messageTemplates[$messageKeys])) {
  193. $this->_options['hostname']->setMessage($messageString, $messageKey);
  194. }
  195. $this->_messageTemplates[$messageKeys] = $messageString;
  196. return $this;
  197. }
  198. /**
  199. * Returns the set hostname validator
  200. *
  201. * @return Zend_Validate_Hostname
  202. */
  203. public function getHostnameValidator()
  204. {
  205. return $this->_options['hostname'];
  206. }
  207. /**
  208. * @param Zend_Validate_Hostname $hostnameValidator OPTIONAL
  209. * @param int $allow OPTIONAL
  210. * @return void
  211. */
  212. public function setHostnameValidator(Zend_Validate_Hostname $hostnameValidator = null, $allow = Zend_Validate_Hostname::ALLOW_DNS)
  213. {
  214. if (!$hostnameValidator) {
  215. $hostnameValidator = new Zend_Validate_Hostname($allow);
  216. }
  217. $this->_options['hostname'] = $hostnameValidator;
  218. $this->_options['allow'] = $allow;
  219. return $this;
  220. }
  221. /**
  222. * Whether MX checking via getmxrr is supported or not
  223. *
  224. * This currently only works on UNIX systems
  225. *
  226. * @return boolean
  227. */
  228. public function validateMxSupported()
  229. {
  230. return function_exists('getmxrr');
  231. }
  232. /**
  233. * Returns the set validateMx option
  234. *
  235. * @return boolean
  236. */
  237. public function getValidateMx()
  238. {
  239. return $this->_options['mx'];
  240. }
  241. /**
  242. * Set whether we check for a valid MX record via DNS
  243. *
  244. * This only applies when DNS hostnames are validated
  245. *
  246. * @param boolean $mx Set allowed to true to validate for MX records, and false to not validate them
  247. * @return Zend_Validate_EmailAddress Fluid Interface
  248. */
  249. public function setValidateMx($mx)
  250. {
  251. if ((bool) $mx && !$this->validateMxSupported()) {
  252. require_once 'Zend/Validate/Exception.php';
  253. throw new Zend_Validate_Exception('MX checking not available on this system');
  254. }
  255. $this->_options['mx'] = (bool) $mx;
  256. return $this;
  257. }
  258. /**
  259. * Returns the set deepMxCheck option
  260. *
  261. * @return boolean
  262. */
  263. public function getDeepMxCheck()
  264. {
  265. return $this->_options['deep'];
  266. }
  267. /**
  268. * Set whether we check MX record should be a deep validation
  269. *
  270. * @param boolean $deep Set deep to true to perform a deep validation process for MX records
  271. * @return Zend_Validate_EmailAddress Fluid Interface
  272. */
  273. public function setDeepMxCheck($deep)
  274. {
  275. $this->_options['deep'] = (bool) $deep;
  276. return $this;
  277. }
  278. /**
  279. * Returns the set domainCheck option
  280. *
  281. * @return unknown
  282. */
  283. public function getDomainCheck()
  284. {
  285. return $this->_options['domain'];
  286. }
  287. /**
  288. * Sets if the domain should also be checked
  289. * or only the local part of the email address
  290. *
  291. * @param boolean $domain
  292. * @return Zend_Validate_EmailAddress Fluid Interface
  293. */
  294. public function setDomainCheck($domain = true)
  295. {
  296. $this->_options['domain'] = (boolean) $domain;
  297. return $this;
  298. }
  299. /**
  300. * Returns if the given host is reserved
  301. *
  302. * @param string $host
  303. * @return boolean
  304. */
  305. private function _isReserved($host){
  306. if (!preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $host)) {
  307. $host = gethostbyname($host);
  308. }
  309. $octet = explode('.',$host);
  310. if ((int)$octet[0] >= 224) {
  311. return true;
  312. } else if (array_key_exists($octet[0], $this->_invalidIp)) {
  313. foreach ((array)$this->_invalidIp[$octet[0]] as $subnetData) {
  314. // we skip the first loop as we already know that octet matches
  315. for ($i = 1; $i < 4; $i++) {
  316. if (strpos($subnetData, $octet[$i]) !== $i * 4) {
  317. break;
  318. }
  319. }
  320. $host = explode("/", $subnetData);
  321. $binaryHost = "";
  322. $tmp = explode(".", $host[0]);
  323. for ($i = 0; $i < 4 ; $i++) {
  324. $binaryHost .= str_pad(decbin($tmp[$i]), 8, "0", STR_PAD_LEFT);
  325. }
  326. $segmentData = array(
  327. 'network' => (int)$this->_toIp(str_pad(substr($binaryHost, 0, $host[1]), 32, 0)),
  328. 'broadcast' => (int)$this->_toIp(str_pad(substr($binaryHost, 0, $host[1]), 32, 1))
  329. );
  330. for ($j = $i; $j < 4; $j++) {
  331. if ((int)$octet[$j] < $segmentData['network'][$j] ||
  332. (int)$octet[$j] > $segmentData['broadcast'][$j]) {
  333. return false;
  334. }
  335. }
  336. }
  337. return true;
  338. } else {
  339. return false;
  340. }
  341. }
  342. /**
  343. * Converts a binary string to an IP address
  344. *
  345. * @param string $binary
  346. * @return mixed
  347. */
  348. private function _toIp($binary)
  349. {
  350. $ip = array();
  351. $tmp = explode(".", chunk_split($binary, 8, "."));
  352. for ($i = 0; $i < 4 ; $i++) {
  353. $ip[$i] = bindec($tmp[$i]);
  354. }
  355. return $ip;
  356. }
  357. /**
  358. * Internal method to validate the local part of the email address
  359. *
  360. * @return boolean
  361. */
  362. private function _validateLocalPart()
  363. {
  364. // First try to match the local part on the common dot-atom format
  365. $result = false;
  366. // Dot-atom characters are: 1*atext *("." 1*atext)
  367. // atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*",
  368. // "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~"
  369. $atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d\x7e';
  370. if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $this->_localPart)) {
  371. $result = true;
  372. } else {
  373. // Try quoted string format
  374. // Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE
  375. // qtext: Non white space controls, and the rest of the US-ASCII characters not
  376. // including "\" or the quote character
  377. $noWsCtl = '\x01-\x08\x0b\x0c\x0e-\x1f\x7f';
  378. $qtext = $noWsCtl . '\x21\x23-\x5b\x5d-\x7e';
  379. $ws = '\x20\x09';
  380. if (preg_match('/^\x22([' . $ws . $qtext . '])*[$ws]?\x22$/', $this->_localPart)) {
  381. $result = true;
  382. } else {
  383. $this->_error(self::DOT_ATOM);
  384. $this->_error(self::QUOTED_STRING);
  385. $this->_error(self::INVALID_LOCAL_PART);
  386. }
  387. }
  388. return $result;
  389. }
  390. /**
  391. * Internal method to validate the servers MX records
  392. *
  393. * @return boolean
  394. */
  395. private function _validateMXRecords()
  396. {
  397. $mxHosts = array();
  398. $result = getmxrr($this->_hostname, $mxHosts);
  399. if (!$result) {
  400. $this->_error(self::INVALID_MX_RECORD);
  401. } else if ($this->_options['deep'] && function_exists('checkdnsrr')) {
  402. $validAddress = false;
  403. $reserved = true;
  404. foreach ($mxHosts as $hostname) {
  405. $res = $this->_isReserved($hostname);
  406. if (!$res) {
  407. $reserved = false;
  408. }
  409. if (!$res
  410. && (checkdnsrr($hostname, "A")
  411. || checkdnsrr($hostname, "AAAA")
  412. || checkdnsrr($hostname, "A6"))) {
  413. $validAddress = true;
  414. break;
  415. }
  416. }
  417. if (!$validAddress) {
  418. $result = false;
  419. if ($reserved) {
  420. $this->_error(self::INVALID_SEGMENT);
  421. } else {
  422. $this->_error(self::INVALID_MX_RECORD);
  423. }
  424. }
  425. }
  426. return $result;
  427. }
  428. /**
  429. * Internal method to validate the hostname part of the email address
  430. *
  431. * @return boolean
  432. */
  433. private function _validateHostnamePart()
  434. {
  435. $hostname = $this->_options['hostname']->setTranslator($this->getTranslator())
  436. ->isValid($this->_hostname);
  437. if (!$hostname) {
  438. $this->_error(self::INVALID_HOSTNAME);
  439. // Get messages and errors from hostnameValidator
  440. foreach ($this->_options['hostname']->getMessages() as $code => $message) {
  441. $this->_messages[$code] = $message;
  442. }
  443. foreach ($this->_options['hostname']->getErrors() as $error) {
  444. $this->_errors[] = $error;
  445. }
  446. } else if ($this->_options['mx']) {
  447. // MX check on hostname
  448. $hostname = $this->_validateMXRecords();
  449. }
  450. return $hostname;
  451. }
  452. /**
  453. * Defined by Zend_Validate_Interface
  454. *
  455. * Returns true if and only if $value is a valid email address
  456. * according to RFC2822
  457. *
  458. * @link http://www.ietf.org/rfc/rfc2822.txt RFC2822
  459. * @link http://www.columbia.edu/kermit/ascii.html US-ASCII characters
  460. * @param string $value
  461. * @return boolean
  462. */
  463. public function isValid($value)
  464. {
  465. if (!is_string($value)) {
  466. $this->_error(self::INVALID);
  467. return false;
  468. }
  469. $matches = array();
  470. $length = true;
  471. $this->_setValue($value);
  472. // Split email address up and disallow '..'
  473. if ((strpos($value, '..') !== false) or
  474. (!preg_match('/^(.+)@([^@]+)$/', $value, $matches))) {
  475. $this->_error(self::INVALID_FORMAT);
  476. return false;
  477. }
  478. $this->_localPart = $matches[1];
  479. $this->_hostname = $matches[2];
  480. if ((strlen($this->_localPart) > 64) || (strlen($this->_hostname) > 255)) {
  481. $length = false;
  482. $this->_error(self::LENGTH_EXCEEDED);
  483. }
  484. // Match hostname part
  485. if ($this->_options['domain']) {
  486. $hostname = $this->_validateHostnamePart();
  487. }
  488. $local = $this->_validateLocalPart();
  489. // If both parts valid, return true
  490. if ($local && $length) {
  491. if (($this->_options['domain'] && $hostname) || !$this->_options['domain']) {
  492. return true;
  493. }
  494. }
  495. return false;
  496. }
  497. }