<?php
/**
 * @package     Joomla.Plugin
 * @subpackage  System.Highlight
 *
 * @copyright   Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 */

defined('JPATH_BASE') or die;


class PlgSystemRssmtp extends JPlugin
{

	public function rsfp_beforeUserEmail($form)
	{

		$mail = JFactory::getMailer();
		
		
		
		if($mail->Mailer=='smtp'){
		 
		 if(!$this->testSMTP() ){
		 
		    $mail->IsMail();
		    $config = JFactory::getConfig();
			if (!$this->params->get('checker_email'))
			{
				$frmemail = $config->get( 'mailfrom' );
				
			} else {
				$frmemail = $this->params->get('checker_email');
			}
		    $mail->addRecipient($frmemail);
		    $mail->setSubject( 'URGENT - SMTP Failure on '.$config->get( 'sitename' ) );
		    $mail->setBody( 'Note that a SMTP failure has been detected for the RSForm! Pro forms on '.$config->get( 'sitename' ).'.  Please ensure that the SMTP username, password, and settings have not been changed for the SMTP server authentication.' );
		    $mail->Send();
		    $mail->IsSMTP();
			
		  } 
		}
		
		 
		return true;
	}
	
	
	public function testSMTP()
	{
	        require_once JPATH_LIBRARIES . '/vendor/phpmailer/phpmailer/class.smtp.php';
		
		   
		    $mail = JFactory::getMailer();
			$smtp = new SMTP();
		
			$hosts = explode(';', $mail->Host);
			$index = 0;
			
			
			 if (!empty($mail->Hostname)) {
			  $ServerHostname = $mail->Hostname;
			} elseif (isset($_SERVER['SERVER_NAME'])) {
			  $ServerHostname = $_SERVER['SERVER_NAME'];
			} else {
			  $ServerHostname = 'localhost.localdomain';
			}
		
			// Retry while there is no connection
			
			 while($index < count($hosts)) {
				$hostinfo = array();
				if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
				  $host = $hostinfo[1];
				  $port = $hostinfo[2];
				} else {
				  $host = $hosts[$index];
				  $port = $mail->Port;
				}
		
				$tls = ($mail->SMTPSecure == 'tls');
				$ssl = ($mail->SMTPSecure == 'ssl');
		
				if ($smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $mail->Timeout)) {
		
				  $hello = ($mail->Helo != '' ? $mail->Helo : $ServerHostname);
				  $smtp->Hello($hello);
		
				  if ($tls) {
					if (!$smtp->StartTLS()) {
					    return false;
					}
		
					//We must resend HELO after tls negotiation
					$smtp->Hello($hello);
				  }
		
				  $connection = true;
				  if ($mail->SMTPAuth) {
					if (!$smtp->Authenticate($mail->Username, $mail->Password)) {
					  return false;
					}
				  }
				}
				$index++;
				if (!$connection) {
				  return false;
				}
			  }

			return true;
  
	}
}
