<?php
#########################################################################################################
#  domain-report-sample.php
#
#  Copyright (C) Softnik Technologies. All rights reserved.
#
#  Simple PHP script to list domain names that were added within the last 30 days.
#  You can use this in your crontab to generate daily/weekly/monthly domain expiry reports.
#  Remember to copy and or rename this file before making changes. This will protect your modifications 
#  from getting over-written. The best place to keep custom scripts is the 'lib/php/custom/' folder.
#
#  Before using this
#  -----------------
#  The script will require that you login if you have password protected the application. However this
#  will be a problem when running this script as a cronjob. To overcome this we use the
#  'CLI Authorization Key'. The 'CLI Authorization Key' is a unique string / password you set from the 
# 'Basic App Setup > Authentication' screen.
#  After you have specified the key, use it in your cron entry as follows.
#
#  php /path/to/script/recently-added-report.php key=xxxxxx
#  OR
#  wget http://server/path/recently-added-report.php?key=xxxxxx
#
#  You can set your email preferences in 'Basic App Setup > Email options'
#########################################################################################################

# Specify email address, columns to show in table, etc.

$toemail      = "example@example.com";
$toname       = "Domain Portfolio Manager";
$emailsubject = "Domains Added in Last 30 days";

$sendemail    = false;  # Specify proper email settings and change to true.
$screendump   = true;  # true to see on screen. Password protect this folder if you set this to true.
$maxcount     = 1000;   # Maximum domains to list. Set this to a reasonable limit.

# specify a "writable" folder path. Empty if you don't want to save the report to disk.
$savefolder   = ""; 
$reportprefix = "recent";  # file name prefix added to the report.

# customer_name is a custom column. You can replace it with your own custom column name.
$columns      = "domain,customer_name,registry_expiry,registrar_expiry,lookedup,status,added_on";

$showdays     = false;   # false if you want the actual date to be shown (instead of days left/past)

$htmlheadfile = "reports-htmlhead-sample.htm";

$header       = $emailsubject;
$footer       = "";					# may contain simple HTML

#########################################################################################################
# You probably won't need to edit below this line, unless you want to modify the data display formating.
#########################################################################################################

require_once(dirname(__FILE__) . "/../../../config.php");
require_once(dirname(__FILE__) . "/../base.php");
require_once(dirname(__FILE__) . "/../version.php");
require_once(dirname(__FILE__) . "/../mailer.inc.php");

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

# Parse command line if running in CLI
if(is_cli())
	parse_str(implode('&', array_slice($argv, 1)), $_REQUEST);

session_start();
cli_mode_authentication_check();

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

function get_base_dir()
{
	return realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR;
}

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

connect_to_mysql_and_select_db();
global $db_config_domain_table, $db_allowed_domain_columns, $domain_table_date_fields;

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

$colarray = explode(",", strtolower($columns));
$required_columns = array("added_on", "domain");
foreach($required_columns as $entry)
{
	if(!in_array($entry, $colarray))
		array_unshift($colarray, $entry);
}
SetupAllowableFields();

#########################################################################################################
# Do SQL Query

$sql = "SELECT ";
$fields = array();
$labels = array();
foreach($colarray as $c)
{
	if(in_array($c, $db_allowed_domain_columns))
	{
		$sql .= " $c,";
		$fields[] = $c;
		$label = getLabelFromFieldName($c);
		get_column_label_and_width($c, $label, $width);
		$labels[] = $label;
	}
}
$sql = trim($sql, ",");
$sql .= " FROM $db_config_domain_table WHERE added_on > [TODAY-30] ORDER BY added_on desc LIMIT $maxcount";
$sql  = parse_custom_sql_query($sql);
$result = mysql_query($sql) or die("Couldn't execute your query.".mysql_error());

#########################################################################################################
# Construct the data table. 

$message  = file_get_contents(get_base_dir() . $htmlheadfile);
$message .= "<h1 class=\"header\">$header</h1>\n";
$message .= '<table class="domaintable" border="0" cellspacing="0" cellpadding="4"  width="100%">' . "\n";

#########################################################################################################
# The heading row

$message .= "<tr>\n";
foreach($labels as $l)
{
	if(strtolower($l) == "domain")
		$message .= "<th class=\"domain\"><p><b>$l</b></p></th>\n";
	else
		$message .= "<th><p><b>$l</b></p></th>\n";
}
$message .= "</tr>\n";

#########################################################################################################
# The actual data

$tabsep = array('7'=>0, '30'=>0, '60'=>0, '90'=>0);
$num_rows = mysql_num_rows($result);
$rindex = 0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
{	
	$trclass = "";
	$tdentry = "";
	$expdays = 99999;
	foreach($fields as $f)
	{
		$is_an_expiry_date = false;
		if(isset($row[$f]))
		{
			if(in_array($f, $domain_table_date_fields))
			{
				if(strtolower($f) == "registry_expiry" || strtolower($f) == "registrar_expiry")
					$is_an_expiry_date = true;
					
				$days = get_date_difference(strtotime($row[$f]));					
				if($is_an_expiry_date)
					$expdays = min($expdays, $days);
				
				$v = $row[$f];
				if($showdays)
				{
					if($days >= 0)
						$v = "in $days days";
					else if($days < 0)
					{
						$d = $days*-1;
						$v = "$d days ago";
					}
				}
			}
			else
			{
				$v = $row[$f];
				if(strtolower($f) == "status")
					$v = str_replace(",", ", ", $v);
			}
		}
		else
			$v = "-";
		$tdentry .= "<td><p>$v</p></td>\n";
	}
	if($expdays <= 0)
		$trclass .= " bgalert";
	
	if($rindex == ($num_rows-1))
		$trclass .= " lastrow";
	$rindex++;
	
	$trclass = trim($trclass);
	$message .= "<tr";
	if($trclass != "")
		$message .= " class=\"$trclass\">\n";
	else
		$message .= ">\n";
	$message .= $tdentry;
	$message .= "</tr>\n";
}

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

$message .= "</table>\n";

if($footer == "")
	$footer = "<br><br><p class=\"footer\"><a href=\"" . get_base_path() . "\" target=\"_blank\">$emailsubject</a> " . get_version() . ", Build: " . get_build_date() . "</p>";
$message .= $footer . "\n";

#########################################################################################################
# Send email, dump to screen or save to folder.

if($screendump)
	echo $message;
else
	echo "<p class=\"infomsg\">On-screen display is disabled in the script. Open in a text editor and enable if you want to see the report on screen.</p>";

if($sendemail)
{
	$estatus = send_email($message, $emailsubject, $toemail, $toname);
	if($estatus !== true)
		echo "<p>Email was not sent.</p>";
	else
		echo "<p>Email was sent.</p>";
}
else
	echo "<p class=\"infomsg\">Emailing is disabled in the script. Open in a text editor and enable the email option.</p>";

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

if($savefolder != "")
{
	if(strstr($savefolder, DIRECTORY_SEPARATOR) === false)
	{
		$basefolder = get_base_dir();
		$basefolder .= $savefolder;
		$savefolder = $basefolder;
	}
	if(substr($savefolder, -1) != DIRECTORY_SEPARATOR)
		$savefolder .= DIRECTORY_SEPARATOR;
	$savepath = $savefolder . "$reportprefix-" . date("Y-m-d") . ".htm";  
	$findex = 1;
	while(is_file($savepath) && $findex < 20)
	{
		$savepath = $savefolder . "$reportprefix-" . date("Y-m-d") . "-$findex" . ".htm";  
		$findex++;
	}
	if(file_put_contents($savepath, $message) === false)
		echo "<p>File was not saved.</p>";
}
	
#########################################################################################################

?>
