CEmailValidator.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. <?php
  2. /**
  3. * CEmailValidator class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CEmailValidator validates that the attribute value is a valid email address.
  12. *
  13. * @author Qiang Xue <qiang.xue@gmail.com>
  14. * @package system.validators
  15. * @since 1.0
  16. */
  17. class CEmailValidator extends CValidator
  18. {
  19. /**
  20. * @var string the regular expression used to validate the attribute value.
  21. * @see http://www.regular-expressions.info/email.html
  22. */
  23. public $pattern='/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/';
  24. /**
  25. * @var string the regular expression used to validate email addresses with the name part.
  26. * This property is used only when {@link allowName} is true.
  27. * @see allowName
  28. */
  29. public $fullPattern='/^[^@]*<[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?>$/';
  30. /**
  31. * @var boolean whether to allow name in the email address (e.g. "Qiang Xue <qiang.xue@gmail.com>"). Defaults to false.
  32. * @see fullPattern
  33. */
  34. public $allowName=false;
  35. /**
  36. * @var boolean whether to check the MX record for the email address.
  37. * Defaults to false. To enable it, you need to make sure the PHP function 'checkdnsrr'
  38. * exists in your PHP installation.
  39. * Please note that this check may fail due to temporary problems even if email is deliverable.
  40. */
  41. public $checkMX=false;
  42. /**
  43. * @var boolean whether to check port 25 for the email address.
  44. * Defaults to false. To enable it, ensure that the PHP functions 'dns_get_record' and
  45. * 'fsockopen' are available in your PHP installation.
  46. * Please note that this check may fail due to temporary problems even if email is deliverable.
  47. */
  48. public $checkPort=false;
  49. /**
  50. * @var boolean whether the attribute value can be null or empty. Defaults to true,
  51. * meaning that if the attribute is empty, it is considered valid.
  52. */
  53. public $allowEmpty=true;
  54. /**
  55. * @var boolean whether validation process should care about IDN (internationalized domain names). Default
  56. * value is false which means that validation of emails containing IDN will always fail.
  57. * @since 1.1.13
  58. */
  59. public $validateIDN=false;
  60. /**
  61. * Validates the attribute of the object.
  62. * If there is any error, the error message is added to the object.
  63. * @param CModel $object the object being validated
  64. * @param string $attribute the attribute being validated
  65. */
  66. protected function validateAttribute($object,$attribute)
  67. {
  68. $value=$object->$attribute;
  69. if(!$this->validateValue($value))
  70. {
  71. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is not a valid email address.');
  72. $this->addError($object,$attribute,$message);
  73. }
  74. }
  75. /**
  76. * Validates a static value to see if it is a valid email.
  77. * Note that this method does not respect {@link allowEmpty} property.
  78. * This method is provided so that you can call it directly without going through the model validation rule mechanism.
  79. * @param mixed $value the value to be validated
  80. * @return boolean whether the value is a valid email
  81. * @since 1.1.1
  82. */
  83. public function validateValue($value)
  84. {
  85. if($this->allowEmpty && $this->isEmpty($value))
  86. return true;
  87. if(is_string($value) && $this->validateIDN)
  88. $value=$this->encodeIDN($value);
  89. // make sure string length is limited to avoid DOS attacks
  90. $valid=is_string($value) && strlen($value)<=254 && (preg_match($this->pattern,$value) || $this->allowName && preg_match($this->fullPattern,$value));
  91. if($valid)
  92. $domain=rtrim(substr($value,strpos($value,'@')+1),'>');
  93. if($valid && $this->checkMX && function_exists('checkdnsrr'))
  94. $valid=checkdnsrr($domain,'MX');
  95. if($valid && $this->checkPort && function_exists('fsockopen') && function_exists('dns_get_record'))
  96. $valid=$this->checkMxPorts($domain);
  97. return $valid;
  98. }
  99. /**
  100. * Returns the JavaScript needed for performing client-side validation.
  101. * @param CModel $object the data object being validated
  102. * @param string $attribute the name of the attribute to be validated.
  103. * @return string the client-side validation script.
  104. * @see CActiveForm::enableClientValidation
  105. * @since 1.1.7
  106. */
  107. public function clientValidateAttribute($object,$attribute)
  108. {
  109. if($this->validateIDN)
  110. {
  111. Yii::app()->getClientScript()->registerCoreScript('punycode');
  112. // punycode.js works only with the domains - so we have to extract it before punycoding
  113. $validateIDN='
  114. var info = value.match(/^(.[^@]+)@(.+)$/);
  115. if (info)
  116. value = info[1] + "@" + punycode.toASCII(info[2]);
  117. ';
  118. }
  119. else
  120. $validateIDN='';
  121. $message=$this->message!==null ? $this->message : Yii::t('yii','{attribute} is not a valid email address.');
  122. $message=strtr($message, array(
  123. '{attribute}'=>$object->getAttributeLabel($attribute),
  124. ));
  125. $condition="!value.match({$this->pattern})";
  126. if($this->allowName)
  127. $condition.=" && !value.match({$this->fullPattern})";
  128. return "
  129. $validateIDN
  130. if(".($this->allowEmpty ? "jQuery.trim(value)!='' && " : '').$condition.") {
  131. messages.push(".CJSON::encode($message).");
  132. }
  133. ";
  134. }
  135. /**
  136. * Retrieves the list of MX records for $domain and checks if port 25
  137. * is opened on any of these.
  138. * @since 1.1.11
  139. * @param string $domain domain to be checked
  140. * @return boolean true if a reachable MX server has been found
  141. */
  142. protected function checkMxPorts($domain)
  143. {
  144. $records=dns_get_record($domain, DNS_MX);
  145. if($records===false || empty($records))
  146. return false;
  147. usort($records,array($this,'mxSort'));
  148. foreach($records as $record)
  149. {
  150. $handle=@fsockopen($record['target'],25);
  151. if($handle!==false)
  152. {
  153. fclose($handle);
  154. return true;
  155. }
  156. }
  157. return false;
  158. }
  159. /**
  160. * Determines if one MX record has higher priority as another
  161. * (i.e. 'pri' is lower). Used by {@link checkMxPorts}.
  162. * @since 1.1.11
  163. * @param mixed $a first item for comparison
  164. * @param mixed $b second item for comparison
  165. * @return boolean
  166. */
  167. protected function mxSort($a, $b)
  168. {
  169. return $a['pri']-$b['pri'];
  170. }
  171. /**
  172. * Converts given IDN to the punycode.
  173. * @param string $value IDN to be converted.
  174. * @return string resulting punycode.
  175. * @since 1.1.13
  176. */
  177. private function encodeIDN($value)
  178. {
  179. if(preg_match_all('/^(.*)@(.*)$/',$value,$matches))
  180. {
  181. if(function_exists('idn_to_ascii'))
  182. $value=$matches[1][0].'@'.idn_to_ascii($matches[2][0]);
  183. else
  184. {
  185. require_once(Yii::getPathOfAlias('system.vendors.Net_IDNA2.Net').DIRECTORY_SEPARATOR.'IDNA2.php');
  186. $idna=new Net_IDNA2();
  187. $value=$matches[1][0].'@'.@$idna->encode($matches[2][0]);
  188. }
  189. }
  190. return $value;
  191. }
  192. }