<?php
class Validateemail
{

	var $sock;

	var $user;
	var $domain;
	var $port = 25;
	var $max_conn_time = 30;
	var $max_read_time = 5;
	
	var $from_user = 'user';
	var $from_domain = 'localhost';
	
	var $verifierType = '';
	var $apiUsername='';
	var $apiPassword='';
	
	var $debug = false;

	function __construct($settings=array())
	{
		$this->verifierType=$settings['verify_email_using'];
		if($this->verifierType=="verify_email_api_verify_email_org")
		{
			$this->apiUsername=$settings['verify_email_org_username'];
			$this->apiPassword=$settings['verify_email_org_password'];
		}	
	}	
	/**
	* Validate an Email Address
	* @param String $email Email to validate
	* @param String $sender Senders Email
	*/
	function validate($email = false, $sender = false) 
	{				
		$returnVar = false;
		if($this->verifierType=="disabled")
		{
			$returnVar = true;
		}
		elseif($this->verifierType=="verify_email_local_smtp")
		{
			$returnVar = $this->validateLocalSMTP($email,$sender);
		}
		elseif($this->verifierType=="verify_email_api_verify_email_org")
		{
			$returnVar = $this->validateVerifyEmailOrg($email);
		}
		return $returnVar;
	}
	function debug($str) 
	{
		if ($this->debug)
		{
			echo $str;
		}
	}
	
	/////////////////////////////////////////////////////////////////////////////////////
	//Validate Using Local SMTP
	/////////////////////////////////////////////////////////////////////////////////////
	
	function validateLocalSMTP($email,$sender)
	{
		if ($email)
		{
			$this->setEmail($email);
			//Check domain
			if(!checkdnsrr($this->domain))
			{
				return false;		
			}
		}
		if ($sender) 
		{
			$this->setSenderEmail($sender);
		}
		exec("nslookup -type=MX $this->domain", $result); 		
		// retrieve SMTP Server via MX query on domain
		$result = getmxrr($this->domain, $hosts);
		// last fallback is the original domain
		array_push($hosts, $this->domain);
		
		$this->debug(print_r($hosts,1 ));
		
		$timeout = $this->max_conn_time/count($hosts);
			
		// try each host
		foreach($hosts as $host)
		{
			// connect to SMTP server
			$this->debug("try $host:$this->port\n");
			if ($this->sock = fsockopen($host, $this->port, $errno, $errstr, (float) $timeout))
			{
				socket_set_blocking($this->sock, false);
				break;
			}
		}
	
		// did we get a TCP socket
		if ($this->sock)
		{
			// say helo
			$this->send("HELO ".$this->from_domain);
			// tell of sender
			$this->send("MAIL FROM: <".$this->from_user.'@'.$this->from_domain.">");
			// ask of recepient
			$reply = $this->send("RCPT TO: <".$this->user.'@'.$this->domain.">");
			// quit
			$reply = $this->send("quit");
			// close socket
			fclose($this->sock);
			// get code and msg from response
			list($code, $msg) = explode(' ', $reply);
			
			if ($code == '250') 
			{
				// you received 250 so the email address was accepted
				return true;
			}		
		}		
		return false;	
	}
	function send($msg) 
	{
		fwrite($this->sock, $msg."\n");
		$resp = '';
		$start = $this->microtime_float();
		while(1) {
			$reply = fread($this->sock, 2082);
			$resp .= $reply;
			if (($resp != '' && trim($reply) == '') 
			|| ($this->microtime_float() - $start > $this->max_read_time )) {
				break;
			}
		}
		
		$this->debug(">>>\n$msg\n");
		$this->debug("<<<\n$resp");
		
		
		return $resp;
	}
	function microtime_float()
	{
		list($usec, $sec) = explode(" ", microtime());
		return ((float)$usec + (float)$sec);
	}
	function setEmail($email)
	{
		list($user, $domain) = explode('@', $email);
		$this->user = $user;
		$this->domain = $domain;
	}
	
	function setSenderEmail($email)
	{
		list($user, $domain) = explode('@', $email);
		$this->from_user = $user;
		$this->from_domain = $domain;
	}
	
	/////////////////////////////////////////////////////////////////////////////////////
	//Validate Using API : verify-email.org
	/////////////////////////////////////////////////////////////////////////////////////
	
	function validateVerifyEmailOrg($email)
	{
		if($email)
		{
			$api_url	= 'http://api.verify-email.org/api.php?';		
			$url		= $api_url.'usr='.$this->apiUsername.'&amp;pwd='.$this->apiPassword.'&amp;check='.$email;
			$object		= json_decode(remote_get_contents($url));
			$this->debug(print_r($object,1 ));
			return $object->verify_status;
		}
		return false;	
	}
	// Get remote file contents, preferring faster cURL if available
	function remote_get_contents($url)
	{
		if (function_exists('curl_get_contents') AND function_exists('curl_init'))
		{
			return curl_get_contents($url);
		}
		else
		{
			// A litte slower, but (usually) gets the job done
			return file_get_contents($url);
		}
	}

	function curl_get_contents($url)
	{
		// Initiate the curl session
		$ch = curl_init();
		
		// Set the URL
		curl_setopt($ch, CURLOPT_URL, $url);
		
		// Removes the headers from the output
		curl_setopt($ch, CURLOPT_HEADER, 0);
		
		// Return the output instead of displaying it directly
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		
		// Execute the curl session
		$output = curl_exec($ch);
		
		// Close the curl session
		curl_close($ch);
		
		// Return the output as a variable
		return $output;
	}
}