<?php
###############################################################################
# custom-dkim-scanner-sample.php
# Custom DKIM / TXT record scanner. 
# Copyright Softnik Technologies https://softnik.com/
#
# Author: Anil Kumar
# CodePunch Solutions
# https://codepunch.com/
#
###############################################################################
# Usage
#
# 1. Copy this file to another name and put in lib/php/custom folder of
#    Watch My Domains SED.
#
# 2. Create a text file containing the selectors you want to scan (one entry
#    per line) and name it selectors.txt
#    You can have entries like
#
#    dkim1
#    dkim2
#    google
#    mail
#    scph0817
#
#    There is a sample selectors.txt in this folder.
#    You can specify the path to selector text file using the 'f' 
#    parameter. Remember to provide the full path to the file if you do  
#    this. If the file name is not specified the script will look
#    for selectors.txt in it's own folder
#    
#    php custom-dkim-scanner.php f=/home/wmdsed/work/selectors.txt
#
#    The script will append ._domainkey to each of the selectors before 
#    checking. If you don't want this, specify -nodk as a command line
#    parameter
#
#    php custom-dkim-scanner.php -nodk
#
# 3. Run it on shell command line for scanning all domains
#
#    php custom-dkim-scanner.php
#
#    This could take a while. If you are on a remote connection you may want 
#    to use the screen command before running the script.
#
# 4. Open in browser to see a simple report
#
#    http://<your install folder>/lib/php/custom/custom-dkim-scanner.php
#    http://<your install folder>/lib/php/custom/custom-dkim-scanner.php?sort=domain
#    http://<your install folder>/lib/php/custom/custom-dkim-scanner.php?sort=hostname
#    http://<your install folder>/lib/php/custom/custom-dkim-scanner.php?sort=hostname&desc&dkim
#
#    The sort option could be domain,subdomain,hostname,record_value or added_on
#    The dkim option if used will display only the TXT records that start with v=DKIM in it
#
###############################################################################

$maxlimit		= 1000;
$htmlheadfile 	= "reports-htmlhead-sample.htm";
$header       	= "DKIM Report";
$footer       	= "";			# may contain simple HTML
$sorton 		= "domain";

###############################################################################

require_once(dirname(__FILE__) . "/../basic.php");
require_once(dirname(__FILE__) . "/../config.check.php");
require_once(dirname(__FILE__) . "/../version.php");
require_once(dirname(__FILE__) . "/../mailer.inc.php");
require_once(dirname(__FILE__) . "/../pdo/dbinit.php");
require_once(dirname(__FILE__) . "/reports.helper.php");

#########################################################################################################
# Parse command line if running in CLI

if(is_cli())
	parse_str(implode('&', array_slice($argv, 1)), $_REQUEST);

#########################################################################################################

loginIfRequired(true);

#########################################################################################################

$pdo = init_db(false);
if($pdo === false)
{
	echo "<p>Unable to connect to database</p>";
	exit;
}

###############################################################################

if(is_cli()) {
	$append_dk = true;
	if(isset($_REQUEST['-nodk']))
		$append_dk = false;
	$subdomains = array();
	$sdfile = dirname(__FILE__) . "/selectors.txt";
	$sdfile = getRequestVariable("f", $sdfile);
	if(is_file($sdfile)) {
		$contents = file_get_contents($sdfile);
		if($contents !== false) {
			$contents = str_replace("\r", "\n", $contents);
			$subdomains = explode("\n", $contents);
			$subdomains = array_filter($subdomains);
		}
	}
	else
		echo "Please provide the selector list in a file named selectors.txt\n";
	if(count($subdomains)) {
		$domains = $pdo->getDomainsFromWhereSQL("1=1");
		$count = count($domains);
		echo "\nTesting " . count($subdomains) . " selectors for $count domains.\n";
		echo "Please wait, this could take a while...\n";
		$index = 0;
		$added = 0;
		$modified = array();
		foreach($domains as $domain) {
			$output = check_dns_text_records_for_domain($pdo, $subdomains, $domain, $append_dk, false);
			$added += $output['count'];
			$modified = array_merge($modified, $output['modified']);
			$index++;
			$perc = intval(($index/$count)*100);
			echo "\t($perc%)\t$index/$count] $domain                                \r";
		}
		echo "\t\t                                                            \r";
		
		echo "\n$added records added to subdomain table\n\n";
		echo "The following entries were found\n";
		foreach($modified as $m)
			echo "\t$m\n";
	}
	else
		echo "Empty selector list\n";
	echo "\n";
}
else {
	// Show all DKIM entries in a table.
	$tablename = $pdo->getSubdomainTableName();
	$sql = "WHERE record_type='TXT' AND subdomain != '@'";
	if(isset($_REQUEST['dkim']))
		$sql .= " AND record_value like 'v=dkim%'";
	$sql .= " LIMIT $maxlimit";
	$records = $pdo->getTableData($tablename, "sid,subdomain,record_value,record_type,added_on", $sql);
	//printArray($records);
	$columns = array();
	$fields = array();
	foreach($records as &$r) {
		$sid = $r['sid'];
		$domain = $pdo->getSingleEntry($pdo->getDomainTableName(), "sid", $sid, "domain");
		$r['domain'] = $domain;
		if($r['subdomain'] == "@")
			$r['hostname'] = $domain;
		else
			$r['hostname'] = $r['subdomain'] . ".$domain";
		unset($r['sid']);
		if(!count($columns)) {
			foreach($r as $key=>$v) {
				$columns[] = $key;
				$fields[] = $key;
			}
		}
		$r['record_value'] = substr($r['record_value'], 0, 50);
	}
	
	$dinfo['data'] = $records;
	$dinfo['fields'] = array('domain','subdomain','hostname','record_type', 'record_value', 'added_on');
	$dinfo['columns'] = array('Domain','Subdomain','Hostname','Type', 'Value', 'Last Refresh');
	$sortorder = SORT_ASC;
	if(isset($_REQUEST['desc'])) 
		$sortorder = SORT_DESC;
	if(isset($_REQUEST['sort'])) {
		$newsortcol = strtolower($_REQUEST['sort']);
		$newsortcol = str_replace(" ", "_", $newsortcol);
		if(in_array($newsortcol, $dinfo['fields']))
			$sorton = $newsortcol;
	}
	$tablehtml = $pdo->convertToTable($dinfo, $sorton, "domaintable", "colorCodeExpiryRows", $sortorder);
	$message  = "<html>\n" . file_get_contents(get_install_folder_path() . "lib/php/custom/" . $htmlheadfile);
	$message .= "<h1 class=\"header\">$header</h1>\n";
	$message .= $tablehtml;
	if($footer == "")
		$footer = getSimpleFooterForReports($header);
	$message .= $footer . "\n" . "</body>\n</html>\n";
	echo($message);
}

###############################################################################

function check_dns_text_records_for_domain($pdo, $sdarray, $domain, $dkim=false, $spit_out=false)
{
	$output = array();
	$sid = $pdo->getDomainID($domain);
	if($sid === false)
		$sid = 0;
	$added = 0;
	foreach($sdarray as $sd) {
		if(mb_strlen($sd) > 0) {
			$od = check_dns_txt_record($pdo, $sd, $domain, $dkim);
			if($sid > 0) {
				// Delete Existing and Add Again
				$delcl = "subdomain=? AND sid=? AND (record_type='TXT') AND auto_added=1";
				$host = $sd;
				if($dkim)
					$host .= "._domainkey";
				if($pdo->deleteFromTable($pdo->getSubdomainTableName(), $delcl, array($host,$sid)) !== false) {
					foreach($od as $data_array) {
						if($spit_out)
							print_r($data_array);
						$hid = $pdo->insertIntoTable($pdo->getSubdomainTableName(), $data_array, "hid");
						if($hid !== false)
							$added++;
						$output[] = "$host.$domain";
					}
				}
			}
		}
	}
	if($added) {
		$domain_data = array();
		$domain_data['dns_checked_at'] = date("Y-m-d H:i:s");
		update_domain_table($domain_data, $domain);
	}
	return array('count'=>$added, 'modified'=>$output);
}

###############################################################################

function check_dns_txt_record($pdo, $subdomain, $domain, $dkim=false)
{
	$output_data = array();
	$host = $subdomain;
	if($dkim)
		$host .= "._domainkey";
	if(mb_strlen($host) > 1) {
		$hostname = "$host.$domain";
		$rdata = dns_get_record($hostname, DNS_TXT);
		foreach($rdata as $r)
		{
			$data_array = array();
			$data_array['subdomain'] = $host;
			if(isset($r['type']))
			{
				if($r['type'] == "TXT")
				{
					if(isset($r['txt']))
						$data_array['record_value'] = substr($r['txt'], 0, 254);
				}
				if(isset($r['ttl']))
					$data_array['ttl'] = $r['ttl'];
				
				$data_array['auto_added'] = 1;
				$data_array['record_type'] = $r['type'];
			}
			
			$data_array['added_on'] = date("Y-m-d H:i:s");
			$sid = $pdo->getDomainID($domain);
			if($sid !== false && $sid > 0) {
				$data_array['sid'] = $sid;
			}
			else
				$data_array['domain'] = $domain;
			$output_data[] = $data_array;
			unset($data_array);
		}
	}
	return $output_data;
}

###############################################################################
?>
