Current File : //scripts/CheckSpfDkimDmarcRecord.php
<?php
$obj = new CheckSpfDkimDmarcRecord();
$obj->spfDkimDmarcCheck();

class CheckSpfDkimDmarcRecord {
	private $conn;
	private $hostctl_path="";
	private $grep_path="";
	private $static_hostname="";
	private $server_hostname="";
	private $data_to_send=[];
	private $hostname_error="";
	private $host_name="";
	private $ip="";
	public function __construct() {
		require('/etc/sentora/panel/cnf/db.php');
        include('/etc/sentora/panel/dryden/db/driver.class.php');
        include('/etc/sentora/panel/dryden/debug/logger.class.php');
        include('/etc/sentora/panel/dryden/runtime/dataobject.class.php');
        include('/etc/sentora/panel/dryden/runtime/hook.class.php');
        include('/etc/sentora/panel/dryden/sys/versions.class.php');
        include('/etc/sentora/panel/dryden/ctrl/options.class.php');
        include('/etc/sentora/panel/dryden/fs/director.class.php');
        include('/etc/sentora/panel/dryden/fs/filehandler.class.php');
        include('/etc/sentora/panel/inc/dbc.inc.php');
        try
        {
                $this->zdbh = new db_driver("mysql:host=" . $host . ";dbname=" . $dbname . "", $user, $pass);
        }
        catch (PDOException $e)
        {
            // exit();
        }
	}

	public function spfDkimDmarcCheck() {
	    // Check connection
	    /*if (mysqli_connect_errno()) {
		echo "Failed to connect to MySQL: " . mysqli_connect_error();
	    } else {*/
		$sql    = "SELECT vh_name_vc FROM x_vhosts WHERE vh_type_in = '1' AND vh_deleted_ts is NULL";
		$dom_result = $this->zdbh->prepare($sql);
		$dom_result->execute();
		$dom_count = $dom_result->rowCount();
		$record_check_res[]="";
		if($dom_count) 
		{ 
		    	$domain_array = $dom_result->fetchAll();
		    	foreach ($domain_array as $domain) 
			{
			    	$domain_name = $domain['vh_name_vc'];
			    	$record_check_res[$domain_name] = self::recordCheck($domain_name, false);
		    	}
			self::sendTicket($record_check_res);
		} else {
		    echo "NO_DOMAINS_FOUND \n";
		}
	   //}
	}
	public function recordCheck($domain_name, $flag) {
		echo "\nDomain Name: ".$domain_name."\n";
		$spf=""; $dkim=""; $dmarc="";$spf_error="";$dkim_error="";$dmarc_error="";$rdns_error="";
		$spf_record  = dns_get_record($domain_name, DNS_TXT);
		$spf = $spf_record ? $spf_record[0]['txt'] : "";
		$dkim_record  = dns_get_record("default._domainkey.".$domain_name, DNS_TXT);
		$dkim = $dkim_record ? $dkim_record[0]['txt'] : "";
		$dmarc_record  = dns_get_record("_dmarc.".$domain_name, DNS_TXT);
		$dmarc = $dmarc_record ? $dmarc_record[0]['txt'] : "";

		$ptr_record  = dns_get_record($domain_name, DNS_PTR);
		$rdns = $ptr_record ? $ptr_record[0]['txt'] : "";
		$rdns_error = $rdns ? "" : "RDNS_RECORD_NOT_FOUND";
		$return = array("domain"=>$domain_name, "spf"=>$spf, "dkim"=>$dkim, "dmarc"=>$dmarc);
		print_r($return);
		if(!strpos($spf, "spf1")) {
			$spf_error = "SPF_RECORD_NOT_FOUND";
		}
		if(!strpos($dkim, "DKIM1")) {
			$dkim_error = "DKIM_RECORD_NOT_FOUND";
		}
		if(!strpos($dmarc, "DMARC1")) {
			$dmarc_error = "DMARC_RECORD_NOT_FOUND";
		}
		if(!$flag) {
			$check_hostname_res = self::checkHostname();
			if($check_hostname_res != "HOSTNAME_ALREADY_ADDED_PERMANENTLY" || $check_hostname_res != "PERMANENT_HOSTNAME_ADDED_SUCCESSFULLY") {
              			$this->hostname_error = $check_hostname_res;
				$this->data_to_send['hostname_error'] = $this->hostname_error;
            		} else {
				$this->hostname_error = "";
				//$rdns_point_res = self::pointHostnameInReverseDNS($this->static_hostname);				
			}
			$hostname_point_res = self::checkHostnameIsPointed($this->static_hostname);
		}
		if($spf_error!="" || $dkim_error!="" || $dmarc_error!="" || $this->hostname_error!="" ) 
		{
			if(!$flag) 
			{
				$php_path = trim(shell_exec("whereis php | awk '{print $2}'"));
				shell_exec($php_path.' /etc/sentora/panel/spfdkim.php '.$domain_name);
				$res = self::recordCheck($domain_name, true);
				return $res;
			} 
			else {
				if($spf_error){	$this->data_to_send['spf_error'] = $spf_error; }
				if($dkim_error){ $this->data_to_send['dkim_error'] = $dkim_error; }
				if($dmarc_error){ $this->data_to_send['dmarc_error'] = $dmarc_error; }
				//self::sendTicket($domain_name, $this->data_to_send);
				$res = implode(",",$this->data_to_send);
				return $res;
			}
		}
	}

	public function checkHostname() {
        $server_ip = ctrl_options::GetSystemOption('server_ip');
        $this->ip = $server_ip ? $server_ip : trim(shell_exec('host myip.opendns.com resolver1.opendns.com | grep "myip.opendns.com has" | awk \'{print $4}\''));
        $get_host_by_ip = gethostbyaddr($this->ip);
        $get_ip_of_host = gethostbyname($get_host_by_ip);
        echo "\nip: ".$this->ip."\n";
        echo "\nget_host_by_ip: ".$get_host_by_ip."\n";
        echo "\nget_ip_of_host: ".$get_ip_of_host."\n";
        $cmd="whereis hostname | awk '{print $2}'";
        $this->server_hostname=trim(shell_exec(trim(shell_exec($cmd))));
        echo "server_hostname: ".$this->server_hostname."\n";

        $this->hostctl_path     = trim(shell_exec("whereis hostnamectl | awk '{print $2}'"));
        $this->grep_path        =trim(shell_exec("whereis grep | awk '{print $2}'"));
        $this->static_hostname  = trim(shell_exec($this->hostctl_path." | ".$this->grep_path." 'Static hostname' | awk '{print $3}'"));
        if($this->static_hostname != $this->server_hostname) {
            $return =  "HOSTNAME_NOT_ADDED_PERMANENTLY";
            $perm_hostname_add_res = self::addPermanentHostname();
            $return = $perm_hostname_add_res; 					
        } else {
            $return = "HOSTNAME_ALREADY_ADDED_PERMANENTLY";
        }
		return $return;
	}

	public function addPermanentHostname() {
        $cmd_to_add_permanent_hostname = $this->hostctl_path." set-hostname ".$this->server_hostname;
        echo $cmd_to_add_permanent_hostname;
        //shell_exec($cmd_to_add_permanent_hostname);
		$this->static_hostname  = trim(shell_exec($this->hostctl_path." | ".$this->grep_path." 'Static hostname' | awk '{print $3}'"));
		if($this->static_hostname != $this->server_hostname) {
			return "HOSTNAME_CANNOT_BE_ADD_PERMANENTLY";
		} else {
			return "PERMANENT_HOSTNAME_ADDED_SUCCESSFULLY";
		}
    }
	
	public function checkHostnameIsPointed($hostname) {
		$split_hostname=explode(".",$hostname);
        $sub_domain_name=$split_hostname[0];
        unset($split_hostname[0]);
        $host_domain_name = trim(implode(".",$split_hostname));
        
		$host_dns_record = dns_get_record($hostname, DNS_A);
		if($host_dns_record) {
			return true;
		} else {
			$domain_dns_record = dns_get_record($host_domain_name, DNS_NS);
			$domain_ns_record = $domain_dns_record[0]['target'];
			$ns_rec_ip_addr   = dns_get_record($domain_ns_record, DNS_A);
			$ns_rec_ip_addr   = $ns_rec_ip_addr[0]['ip'];
			echo "\nns_rec_ip_addr ".$ns_rec_ip_addr."\n";
			if($ns_rec_ip_addr !=$this->server_ip) {
				$this->data_to_send['Hostname_point'] = "The NS record is not pointing with us. So please try to point the hostname with this server IP ".$this->ip; 
				//self::sendTicket($this->hostname, $message);
			} else {
				$point_hostname_res = self::pointHostName($this->hostname);
				if($point_hostname_res == 'DOMAIN_NOT_CREATED') {
					$this->data_to_send['Hostname_point'] = "Hostname is not pointed. We tried to point the hostname with this server IP. But couldn't add.";
					//self::sendTicket($this->hostname, "Hostname NOT Pointed");
				}
			}
		}
	}
	
	static function pointHostnameInReverseDNS($hostname)
    {
        $server_ip = ctrl_options::GetSystemOption('server_ip');
        $url = 'http://hostingraja.info/api/SetReverseDnsHostname.php';
        //$key = "Ais_@2017!tEcHChatAuth2017";
        $postvalues="ip=$this->ip&hostname=$new_hostname";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$postvalues);
        $output = curl_exec($ch);
        $output = trim($output);
        //write_aisa_log(LOG_DEBUG, "Output of Reverse DNS Pointing using P1 API : $output \n");
        curl_close($ch);
        return $output;
    }

	public function pointHostName($hostname) {
        echo "Hostname pointing is start here...\n";
		$split_hostname=explode(".",$hostname);
        $sub_domain_name=$split_hostname[0];
        unset($split_hostname[0]);
		$domain_name = trim(implode(".",$split_hostname));
		$targetIP = $this->ip;
		
        /* /////////////////////////// Code for adding A record if it does not exists started HERE  ////////////////////// */
        $check_ssl = "SELECT vh_acc_fk,vh_id_pk FROM x_vhosts WHERE vh_name_vc='".$domain_name."' AND vh_deleted_ts IS NULL";
        $numcheck = $this->zdbh->prepare($check_ssl);
        $numcheck->execute();
        $count = $numcheck->rowCount();
        $check_num = $numcheck->fetchColumn();
        if ($count)
        {
            $dbvals = $numcheck->fetch();
            $domainID=$dbvals['vh_id_pk'];
            $user_id=$dbvals['vh_acc_fk'];
            $dsql=$this->zdbh->prepare("SELECT count(*) as rcd_cnt FROM x_dns WHERE dn_acc_fk=:userid AND dn_name_vc=:domainName AND dn_vhost_fk=:domainID AND dn_type_vc='A' AND dn_host_vc=:subDomain AND dn_target_vc=:target_new AND dn_deleted_ts is NULL");
            $dsql->bindParam(':userid', $user_id);
            $dsql->bindParam(':domainName', $domain_name);
            $dsql->bindParam(':domainID', $domainID);
            $dsql->bindParam(':subDomain', $sub_domain_name);
            $dsql->bindParam(':target_new', $targetIP);
            $dsql->execute();
            $dres=$dsql->fetch();
            if($dres['rcd_cnt']==0)
            {
                $sql = $this->zdbh->prepare("INSERT INTO x_dns (dn_acc_fk,
                    dn_name_vc,
                    dn_vhost_fk,
                    dn_type_vc,
                    dn_host_vc,
                    dn_ttl_in,
                    dn_target_vc,
                    dn_priority_in,
                    dn_weight_in,
                    dn_port_in,
                    dn_created_ts) VALUES (
                    :userid,
                    :domainName,
                    :domainID,
                    'A',
                    :hostName_new,
                    '3600',
                    :target_new,
                    '0',
                    '0',
                    '0',
                    :time)"
                    );
                $sql->bindParam(':userid', $user_id);
                $sql->bindParam(':domainName', $domain_name);
                $sql->bindParam(':domainID', $domainID);
                $sql->bindParam(':hostName_new', $sub_domain_name);
                $sql->bindParam(':target_new', $targetIP);
                $time = time();
                $sql->bindParam(':time', $time);
                $sql->execute();
                unset($sql);

                $sql = $this->zdbh->prepare("INSERT INTO x_dns (dn_acc_fk,
                    dn_name_vc,
                    dn_vhost_fk,
                    dn_type_vc,
                    dn_host_vc,
                    dn_ttl_in,
                    dn_target_vc,
                    dn_priority_in,
                    dn_weight_in,
                    dn_port_in,
                    dn_created_ts) VALUES (
                    :userid,
                    :domainName,
                    :domainID,
                    'A',
                    :hostName_new,
                    '3600',
                    :target_new,
                    '0',
                    '0',
                    '0',
                    :time)"
                    );
                $sql->bindParam(':userid', $user_id);
                $sql->bindParam(':domainName', $domain_name);
                $sql->bindParam(':domainID', $domainID);
                $serv_alias="www.".$sub_domain_name;
                $sql->bindParam(':hostName_new',$serv_alias);
                $sql->bindParam(':target_new', $targetIP);
                $time = time();
                $sql->bindParam(':time', $time);
                $sql->execute();
                unset($sql);

                $records_list = ctrl_options::GetSystemOption('dns_hasupdates');
                $record_array = explode(',', $records_list);
                if (!in_array($domainID, $record_array))
                {
                    if (empty($records_list))
                    {
                        $records_list .= $domainID;
                    }
                    else
                    {
                        $records_list .= ',' . $domainID;
                    }
                    $sql = "UPDATE x_settings SET so_value_tx=:newlist WHERE so_name_vc='dns_hasupdates'";
                    $sql = $this->zdbh->prepare($sql);
                    $sql->bindParam(':newlist', $records_list);
                    $sql->execute();
                }
                $sql = $this->zdbh->prepare("UPDATE x_settings SET so_value_tx='true' WHERE so_name_vc='apache_changed'");
                $sql->execute();
                echo "DOMAIN_NAME_CREATED\n";
                $php_service = shell_exec('whereis php | \'awk {print $2}\'');
                shell_exec($php_service.' /etc/sentora/panel/bin/daemon.php');
                //$this->HRPanelAISALib->SetWriteApacheConfigTrue();
                //$this->HRPanelAISALib->SetCallDaemon();
                $hostname_pointed = "DOMAIN_NAME_CREATED";
            }
            else
            {
                echo "HOSTNAME_ALREADY_ADDED\n";
                $hostname_pointed = "HOSTNAME_ALREADY_ADDED";
            }
            /* /////////////////////// Code for adding A record if it does not exists Ended HERE  /////////////////////// */
        }
        else
        {
            echo "DOMAIN_NOT_CREATED\n";
            $hostname_pointed = "DOMAIN_NOT_CREATED";
        }
        return $hostname_pointed;
    }

	public function sendTicket($record_check_res) 
    	{
		echo "Sending Ticket...\n";
		$record_check_res = array_filter($record_check_res);
        	$ip = $this->ip;
		$mail_body = "<html>";
        	$mail_body .= "<body>";
		foreach($record_check_res as $key => $error) {		
			$mail_body .= "<div>";
			$mail_body .= "<div>ISSUE: ".$error."</div>" ;
        		$mail_body .= "<div>Domain Name : $key</div>";
		}
		$mail_body .= "<div>IP address : $ip</div>";
		$mail_body .= "</body>";
		$mail_body .= "</html>";
	    	echo $mail_body."\n";	
		$email  = 'ovihosting@gmail.com';
		// To send HTML mail, the 'Content-type' header must be set
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

		// Additional headers
		$headers .= 'From: Support <support@hostingraja.in>' . "\r\n";
		if(mail($email,"TXT RECORD NOT FOUND",$mail_body, $headers))
            		echo "Mail sent to $email\n";
        	else
            		echo "Mail sent failed to $email\n";
	}
}
?>