PageRenderTime 36ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/validators/CEmailValidator.php

https://github.com/LosYear/FluentCMS
PHP | 204 lines | 100 code | 10 blank | 94 comment | 28 complexity | 70aace2f24cf5a6610c2dbe8c4929041 MD5 | raw file
  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->allowEmpty && $this->isEmpty($value))
  70. return;
  71. if(!$this->validateValue($value))
  72. {
  73. $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is not a valid email address.');
  74. $this->addError($object,$attribute,$message);
  75. }
  76. }
  77. /**
  78. * Validates a static value to see if it is a valid email.
  79. * Note that this method does not respect {@link allowEmpty} property.
  80. * This method is provided so that you can call it directly without going through the model validation rule mechanism.
  81. * @param mixed $value the value to be validated
  82. * @return boolean whether the value is a valid email
  83. * @since 1.1.1
  84. */
  85. public function validateValue($value)
  86. {
  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. if($a['pri']==$b['pri'])
  170. return 0;
  171. return ($a['pri']<$b['pri'])?-1:1;
  172. }
  173. /**
  174. * Converts given IDN to the punycode.
  175. * @param string $value IDN to be converted.
  176. * @return string resulting punycode.
  177. * @since 1.1.13
  178. */
  179. private function encodeIDN($value)
  180. {
  181. if(preg_match_all('/^(.*)@(.*)$/',$value,$matches))
  182. {
  183. if(function_exists('idn_to_ascii'))
  184. $value=$matches[1][0].'@'.idn_to_ascii($matches[2][0]);
  185. else
  186. {
  187. require_once(Yii::getPathOfAlias('system.vendors.Net_IDNA2.Net').DIRECTORY_SEPARATOR.'IDNA2.php');
  188. $idna=new Net_IDNA2();
  189. $value=$matches[1][0].'@'.@$idna->encode($matches[2][0]);
  190. }
  191. }
  192. return $value;
  193. }
  194. }