<?php

/**
 * Email address validator
 * 
 * Validates user input ensuring it respects the format of a valid e-mail address.
 *
 * @version DR1.6
 */
class EmailValidator extends LengthValidator {



	/**
	 * Constructs an EmailValidator instance
	 * 
	 * @param value : the user input to be validated
	 * @param view : the View where any error shall be posted
	 */
	public function __construct($value, IReadableView $view) {
		parent::__construct($value, $view, 1, 320);
	}



	/**
	 * Validates user input ensuring it respects the format of a valid e-mail address.
	 * 
	 * @return true if the user input respects the format of a valid e-mail address.
	 */
	public function valid() {
		// Always check parent validity first
		if (!parent::valid()) {
			return false;
		}
		// First, we check that there's one @ symbol, and that the lengths are right
		if (!ereg("[^@]{1,64}@[^@]{1,255}", $this->value)) {
			// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
			$this->view->errorMessage(__('Invalid e-mail address: check length and @ symbol'));
			return false;
		}
		// Split it into sections to make life easier
		$emailArray = explode("@", $this->value);
		$localArray = explode(".", $emailArray[0]);
		for ($i = 0; $i < sizeof($localArray); $i++) {
			if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $localArray[$i])) {
				$this->view->errorMessage(__('Invalid e-mail address: check name'));
				return false;
			}
		}
		// Check if domain is IP. If not, it should be valid domain name
		if (!ereg("^\[?[0-9\.]+\]?$", $emailArray[1])) {
			$domainArray = explode(".", $emailArray[1]);
			if (sizeof($domainArray) < 2) {
				$this->view->errorMessage(__('Invalid e-mail address: check domain'));
				return false; // Not enough parts to domain
			}
			for ($i = 0; $i < sizeof($domainArray); $i++) {
				if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domainArray[$i])) {
					$this->view->errorMessage(__('Invalid e-mail address: check domain'));
					return false;
				}
			}
		}
		// E-mail is valid
		return true;
	}



} // EmailValidator

?>