Zend FR

Consultez la FAQ sur le ZF avant de poster une question

Vous n'êtes pas identifié.

#1 09-10-2008 12:50:51

Delprog
Administrateur
Date d'inscription: 29-09-2008
Messages: 670

Extension Zend_Validate_EmailAddress pour serveur Windows

Bonjour,

Si ça intéresse certains, j'ai étendu la classe Zend_Validate_EmailAddress pour que le test MX du nom de domaine puisse fonctionner sur des serveurs Windows. (et oui ça arrive, c'est imposé, *vomit*)

Code:

/**
 * MyLib_Validate_EmailAdress Add MX Validation support on Windows Server.
 *
 */
Zend_Loader::loadClass('Zend_Validate_EmailAddress');
class MyLib_Validate_EmailAddress extends Zend_Validate_EmailAddress
{
    
      /**
     * Check if a host is a valid MX  
     * @param string $host    
     * @return boolean
     */
        public function validateWinMX($host)
    {        
        if(!empty($host)) {          
          exec('nslookup -type=MX '.escapeshellcmd($host), $result);
          $it = new ArrayIterator($result);
          foreach(new RegexIterator($it, '~^'.$host.'~', RegexIterator::GET_MATCH) as $result){
              if($result){
                  return true;
              }               
          }
        }
        return false;
    }  
    
        /**
     * Whether MX checking via dns_get_mx is supported
     * if not, check if a local validateWinMx function exists     
     *
     * @return string or boolean false
     */
    public function validateMxSupported()
    {                
            if (function_exists('dns_get_mx')) {
            return 'unix';
        }        
        else if (method_exists($this,'validateWinMX')) {                        
            return 'win';
        }                
            return false;
    }

    
        /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if $value is a valid email address
     * according to RFC2822
     *
     * @link   http://www.ietf.org/rfc/rfc2822.txt RFC2822
     * @link   http://www.columbia.edu/kermit/ascii.html US-ASCII characters
     * @param  string $value
     * @return boolean
     */
    public function isValid($value)
    {
        $valueString = (string) $value;

        $this->_setValue($valueString);

        // Split email address up
        if (!preg_match('/^(.+)@([^@]+)$/', $valueString, $matches)) {
            $this->_error(self::INVALID);
            return false;
        }

        $this->_localPart = $matches[1];
        $this->_hostname  = $matches[2];
        
        die($this->_hostname);

        // Match hostname part
        $hostnameResult = $this->hostnameValidator->setTranslator($this->getTranslator())
                               ->isValid($this->_hostname);
        if (!$hostnameResult) {
            $this->_error(self::INVALID_HOSTNAME);

            // Get messages and errors from hostnameValidator
            foreach ($this->hostnameValidator->getMessages() as $message) {
                $this->_messages[] = $message;
            }
            foreach ($this->hostnameValidator->getErrors() as $error) {
                $this->_errors[] = $error;
            }
        }

        // MX check on hostname via dns_get_record()
        if ($this->_validateMx) {
              $mx_supported = $this->validateMxSupported();                            
            if (!$mx_supported===false) {  
                  if ($mx_supported == 'unix') {
                    $result = dns_get_mx($this->_hostname, $mxHosts);
                    if (count($mxHosts) < 1) {
                        $hostnameResult = false;
                        $this->_error(self::INVALID_MX_RECORD);
                    }
                  }
                  else if ($mx_supported == 'win') {
                      
                      if(!$this->validateWinMX($this->_hostname)) {                          
                              $hostnameResult = false;
                        $this->_error(self::INVALID_MX_RECORD);
                      }                                            
                  }                
            } else {
                /**
                 * MX checks are not supported by this system
                 * @see Zend_Validate_Exception
                 */
                require_once 'Zend/Validate/Exception.php';
                throw new Zend_Validate_Exception('Internal error: MX checking not available on this system');
            }
        }

        // First try to match the local part on the common dot-atom format
        $localResult = false;

        // Dot-atom characters are: 1*atext *("." 1*atext)
        // atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*",
        //        "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~"
        $atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d';
        if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $this->_localPart)) {
            $localResult = true;
        } else {
            // Try quoted string format

            // Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE
            // qtext: Non white space controls, and the rest of the US-ASCII characters not
            //   including "\" or the quote character
            $noWsCtl    = '\x01-\x08\x0b\x0c\x0e-\x1f\x7f';
            $qtext      = $noWsCtl . '\x21\x23-\x5b\x5d-\x7e';
            $ws         = '\x20\x09';
            if (preg_match('/^\x22([' . $ws . $qtext . '])*[$ws]?\x22$/', $this->_localPart)) {
                $localResult = true;
            } else {
                $this->_error(self::DOT_ATOM);
                $this->_error(self::QUOTED_STRING);
                $this->_error(self::INVALID_LOCAL_PART);
            }
        }

        // If both parts valid, return true
        if ($localResult && $hostnameResult) {
            return true;
        } else {
            return false;
        }
    }
}

Et on peut donc l'utiliser comme avant, ex. avec des validateurs pour Zend_Filter_Input :

Code:

$validators = array(                
  'fmMail' => array('NotEmpty',new MyLib_Validate_EmailAddress(Zend_Validate_Hostname::ALLOW_DNS, true),
                     'messages' => array(
                     'Champ <strong>E-mail</strong> non renseigné',
                       array(
                         MyLib_Validate_EmailAddress::INVALID => '<strong>Adresse e-mail saisie invalide !</strong>',
                         MyLib_Validate_EmailAddress::INVALID_MX_RECORD => '<strong>Adresse e-mail saisie invalide !</strong>'
                       )
                     )
              )
);

Voilà,

A+ benjamin.

Dernière modification par Delprog (09-10-2008 12:57:01)


http://www.anonymation.com/ - anonymation - Studio de création.
http://code.anonymation.com/ - anonymation - blog - développement et architecture web

Hors ligne

 

Pied de page des forums

Propulsé par PunBB
© Copyright 2002–2005 Rickard Andersson
Traduction par punbb.fr

Graphisme réalisé par l'agence Rodolphe Eveilleau
Développement par Kitpages