<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2012 - 2013 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flFormValidatorMultiEmail Class
 *
 * Verify the input is a valid email address, multiple email addresses can be given with a comma between each.
 *
 * @package fusionLib
 */
class flFormValidatorMultiEmail extends flFormValidatorRegex {
	/**
	 * Construct the validator.
	 *
	 * @param string $message The massage to give on failure.
	 */
	function __construct($message = null) {
		parent::__construct("/^([a-z0-9](?:[a-z0-9&'+=_\.-]+)?)@([a-z0-9_-]+)(\.[a-z0-9_-]+)*(\.[a-z]{2,})+(,([a-z0-9](?:[a-z0-9&'+=_\.-]+)?)@([a-z0-9_-]+)(\.[a-z0-9_-]+)*(\.[a-z]{2,})+)*$/i",
							$message, __('{label} must contain valid working email addresses, multiple email addresses can be given if separated by a comma.', 'fusionLib'));
	}

	/**
	 * Validate the input.
	 *
	 * @param flFormElement $elem The form element to validate.
	 * @return bool true if the input is valid; else false.
	 */
	function validate($elem) {
		if(parent::validate($elem)) {
			// If have an email address check DNS settings, domain must have MX or A record.
			$value = $elem->getValue();
			if(!empty($value)) {
				$addrs = explode(',', $value);
				foreach($addrs as $email) {
					$mxHosts = array();
					list($local, $domain) = explode('@', strtolower($email), 2);
					if(function_exists('getmxrr') && function_exists('checkdnsrr') && !getmxrr($domain, $mxHosts) && !checkdnsrr($domain, 'A'))
						return false;
				}
			}
			return true;
		}
		return false;
	}

	/**
	 * Get the client side rule for validation.
	 *
	 * @return array [0] The string holding the rule information for use with fusionLib.validation.js
	 * [1] true to use ajax or false, if false is returned instead of an array then no client side validation is done
	 */
	function getClientRule() {
		return array('multiemail: {' . ($this->message === null ? '' : $this->getClientMsg()) . '}', function_exists('getmxrr') && function_exists('checkdnsrr'));
	}
}
