#!/usr/bin/perl

	#**************************************************************************
	#**************************************************************************
	# Project          :  ANGLER Herald               Started       : 22 Apr 2002     
	# Module           :  Send mail                   Last Modified : 19 Jul 2002
	# Version		 :  1.0
	# Domain           :  www.jayanthra.com                                   
	# Programmer       :  Urmila Murali                       
	# Inprogress       :  \\Angler3\d\Projects\InProgress\Herald0202           
	# Backup           :  \\Angler2\d\Projects\InProgress\Herald0202                            
	#**************************************************************************
	# Description      :  This program checks which kind of mail has to be sent - compose,drafted or html mail    
	#			    All the recipient id's are collected to whom the mail has to be sent.	            	          
	# Input	        :       
	#**************************************************************************



####################################################################
print "Content-type: text/html\n\n";

$basedir="..";

use CGI;
use CGI::Carp qw(fatalsToBrowser);
use DBI;
$query = new CGI;

use Date::Calc qw(:all);

use CGI qw(:standard);

#use Time::localtime;
#use Time::gmtime;

########## DATABASE CONNECTIVITY ##########

#require "../jayanthra/cgi-bin/dataconn.pl";

#require "../jayanthra/cgi-bin/sign.pl";


require "config.inc";

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

     	$Name      = $query->param('name1');       #--------name------------------------#
	$sender    = $query->param('email');	 #-------- email 	 -------------------#
	$subject   = $query->param('subject');	 #-------- subject -------------------#
	$choice    = $query->param('choice');	 #-------- Choice  -------------------#
	$mailtype  =  $query->param('message');	 #---- whether draft or new message---#
	$htmlmail  =  $query->param('html1');	 #----- If html mail -----------------#
	#$query1  =  $query->param('query');	 #----- Query passed for third option #
	$send_date = $query->param('send_date');	 #----- when to send the mail --------#
	$send_mon  = $query->param('send_mon');	 #----- when to send the mail --------#
	$send_year = $query->param('send_year');	 #----- when to send the mail --------#
	$email_shot = $query->param('alloted_shot');     #----- No of Email Ids sent at 1 shot --------#
	$ipadd = $query->param('ipadd');     #----- IP ADDRESS--------#
	$dbus = $query->param('dbus');      #----- DB USERNAME --------#
	$dbname = $query->param('dbname');     #----- DB NAME --------#
	$dbpass = $query->param('dbpass');     #----- DB PASSWORD --------#
	$cpcode = $query->param('cpcode');     #----- CODE--------#
	
	$all_ids = $query->param('all_ids');     #----- CODE--------#

	$all_mails = $query->param('all_mails');     #----- CODE--------#

	$alr_sentids = $query->param('alr_sentids');     #----- CODE--------#

	$alr_sentmails = $query->param('alr_sentmails');     #----- CODE--------#
	$signature_no=$query->param('sign');


require "herald_dataconn1.pl";
#require "herald_dataconn.pl";

require "herald_sign.pl";

#print "select Bw_Usage from $cpcode"."_Herald_Users";

$bandwidth=$db->prepare("select Bw_Usage from $cpcode"."_Herald_Users");
$bandwidth->execute;

($bandwidth_usage)=$bandwidth->fetchrow_array;
 #print "band width:$bandwidth_usage";
 &check_bandwidth_db($bandwidth_usage);

require "timestamp.pl";





#require "../jayanthra/cgi-bin/herald_get_time.pl";



#require "../jayanthra/cgi-bin/date_check.pl";
#require "herald_date_check.pl";

if($htmlmail == 1)
{
$opt_ion="h";
}
elsif($mailtype)
{
$opt_ion="d";
}
else
{
$opt_ion="c";
}
################### GET THE DATABASE USERNAME & PASSWORD TO CONNECT TO THAT DATABASE #########################

	#$sel_dbinfo=$db->prepare("select Ip_address,Db_usname,Db_pass from Herald_Companies where Company_id=$cpcode");
	#$sel_dbinfo->execute;
	#($ip_address,$db_name,$db_pass)=$sel_dbinfo->fetchrow_array;

      #$acc_db = DBI->connect("DBI:mysql:$db_name:$ip_address",$db_name,$db_pass);
	$acc_db = DBI->connect("DBI:mysql:$dbname:$ipadd",$dbname,$dbpass);


	$folder_name = "$send_date"."$send_mon"."$send_year";		######## used to save the details in this folder


$sign = "<br><table align='center' width='100%'><hr></table><table align='center' width='80%'><tr><td align='left' colspan='2'><font face='Verdana, Arial, Helvetica, sans-serif' size='2'>$signature_contents</font></td></tr></table>";



#--------- check if the mail is to be sent today or later -----------#

if($send_date == $ind_day && $send_mon == $ind_mon && $send_year == $ind_year)

	{
	$mail_time=0;
	}
else
	{
	$mail_time = 1;
	}


#print"Mail_time = $mailtime<br>";


#print"Mailtype = $mailtype<br>";
require "herald_get_time.pl";
################ GET THE RECiPIENTS #################################

############## OPTION 1	############################################
########### IF OPTION IS KEY IN ADDRESS #############################
	

	if($choice == 1)
	{
	 $all_emails = $query->param('recepient');		#-------- recipients ----------------#
	 @test_recipients = split(",",$all_emails);

	 $tot_rec = $#test_recipients + 1;		########### TOATL NO OF RECEPIENTS TO WHOM MAIL SHOULD BE SENT 
	 &check_emails($tot_rec,$email_shot,$all_ids,$alr_sentids);
	
################## CHECK FOR THE NO OF RECEPIENTS TO BE SENT AT 1 SHOT ##########################
		
	 foreach $ids(@test_recipients)
		{

		if($ids =~ "(.*)\@(.*)\.")
			{
			#print "ok";
			push(@recepientid,$ids);
			}
		else
			{
			push(@invalid_ids,$ids);
	
			}



		}

#exit;


################### CHECK IF THE NO OF EMAIL IDS TO BE SENT DOES NOT EXCEED THE QUOTA ###################



#print "RECEPIENTS - $recepientid[0],$recepientid[1],$recepientid[2],$recepientid[3],$recepientid[4]<BR>";

################### CHECK IF THE NO OF EMAIL IDS TO BE SENT DOES NOT EXCEED THE QUOTA ###################
	
	}


############## END OF OPTION 1 ############################################



############## OPTION 2	############################################
########### IF OPTION IS ALL MEMBERS IN ADDRESS BOOK #############################

	if($choice == 2)
	{

#print "QUERY - select a.User_Id,a.Name,a.Nickname,a.Company,b.Email,a.Prefix from $cpcode"."_Address a,$cpcode"."_Email b where a.User_Id=b.User_Id<BR>";
	$sel_ids=$db->prepare("select a.User_Id,a.Name,a.Nickname,a.Company,b.Email,a.Prefix from $cpcode"."_Address a,$cpcode"."_Email b where a.User_Id=b.User_Id");

	$sel_ids->execute;

		$tot_rec=0;
#		print "QUERY RESULT - $sel_ids<BR>";
#		print "DB - $db - $database - $hostname - $username - $upass<BR>";
		while(($db_user,$db_name,$db_nick,$db_company,$db_email,$db_prefix)=$sel_ids->fetchrow_array)
		{
	#	print"INSIDE WHILE LOOP- $db_user,$db_name,$db_nick,$db_company,$db_email<br>";
		push(@dbuser,$db_user);
		$len= length($db_prefix);
		if($len!=0)
		{
			push(@dbname,$db_prefix."\.$db_name");
		}
		else
		{
			push(@dbname,$db_name);

		}
		push(@dbnick,$db_nick);
		push(@dbcompany,$db_company);
		push(@recepientid,$db_email);
		$tot_rec=$tot_rec+1;
		}
	
#	 &check_emails($tot_rec,$email_shot,$all_ids,$alr_sentids);

#print "RECEPIENTS - $recepientid[0],$recepientid[1],$recepientid[2],$recepientid[3],$recepientid[4]<BR>";
	}

############## END OF OPTION 2 ############################################


############## OPTION 3	############################################
########### IF OPTION IS ALL MEMBERS FROM SELECTED OPTION #############################

	if($choice == 3)
	{

	########### READ QUERY.TXT FILE ###########

#	open(FILE,"$basedir/jayanthra/admin/sendmail/query.txt") or die "Can't Open File";
	open(FILE,"$sendmaildir/$cpcode/query.txt") or die "Can't Open File";
	while(read(FILE,$buffer,1024))
	{
		$query1.=$buffer;
	}
	close(FILE);

	#$query1 = chop($query);

	#print "QUERY1 - $query1<br>";
	#exit;
	#$query1=urldecode($query1);
	$tot_rec=0;
	$sel_ids=$db->prepare("$query1");
	$sel_ids->execute;
	while(($db_user,$db_name,$db_nick,$db_company,$db_prefix)=$sel_ids->fetchrow_array)
		{
		$sel_email=$db->prepare("select Email from $cpcode"."_Email where User_Id='$db_user'");
		$sel_email->execute;
		while(($db_email)=$sel_email->fetchrow_array)
			{
			#print"$db_user,$db_name,$db_company,$db_email<br>";
			push(@dbuser,$db_user);
			$len= length($db_prefix);
			if($len!=0)
			{
				push(@dbname,$db_prefix."\.$db_name");
			}
			else
			{
				push(@dbname,$db_name);

			}

#			push(@dbname,$prefix."\.$db_name");
			push(@dbnick,$db_nick);
			push(@dbcompany,$db_company);
			push(@recepientid,$db_email);
			}
			$tot_rec=$tot_rec+1;
		}

#print "RECEPIENTS - OP3- $recepientid[0],$recepientid[1],$recepientid[2],$recepientid[3],$recepientid[4]<BR>";
	
#	 &check_emails($tot_rec,$email_shot,$all_ids,$alr_sentids);


	}

############## END OF OPTION 3 ############################################






############## OPTION 4	############################################
########### IF OPTION IS SELECTED MEMBERS FROM SELECTED OPTION #############################

	if($choice == 4)
	{
	$tot_rec=0;
        #print "ENTERING CHOICE 4<BR>";

	########### GET user id and EMAIL IDS FROM THE LIST BOX ###########

	 @selected_recipients = $query->param('email_select');		#-------- recipients ----------------#

	#print "SELECTED RECE - @selected_recipients<br>";
	

	#&check_emails($tot_rec,$email_shot);


	#-------- contains the user id and email, split to get them seperately ----------

	foreach $selected_email(@selected_recipients)
		{
		@split_items=split("~",$selected_email);
		#print "@split_items - $split_items[0] - $split_items[1]<br>";

		#print "QUERY - select Name,Nickname,Company,Prefix from $cpcode"."_Address where User_Id='$split_items[0]'<BR>";
		#----Get the name and company of selected emails using the user id -----------

		$sel_email=$db->prepare("select Name,Nickname,Company,Prefix from $cpcode"."_Address where User_Id='$split_items[0]'");
		$sel_email->execute;

		($db_name,$db_nick,$db_company,$db_prefix)=$sel_email->fetchrow_array;
		
		#print"$split_items[0],$db_name,$db_company,$split_items[1]<br>";
		push(@dbuser,$split_items[0]);
			$len= length($db_prefix);
		if($len!=0)
		{
			push(@dbname,$db_prefix."\.$db_name");
		}
		else
		{
			push(@dbname,$db_name);

		}

		#	push(@dbname,$prefix."\.$db_name");
		push(@dbnick,$db_nick);
		push(@dbcompany,$db_company);
		push(@recepientid,$split_items[1]);

		$tot_rec=$tot_rec+1;	

		}
	 
#	 &check_emails($tot_rec,$email_shot,$all_ids,$alr_sentids);
	#print "RECEPIENTS - OP4 - $recepientid[0],$recepientid[1],$recepientid[2],$recepientid[3],$recepientid[4]<BR>";

	}

############## END OF OPTION 4 ############################################









############## OPTION 5	############################################
########### IF OPTION IS ALL MEMBERS FROM SELECTED OPTION Of Occasions #############################

	if($choice == 5)
	{

	########### READ QUERY.TXT FILE ###########

#	open(FILE,"$basedir/jayanthra/admin/sendmail/query.txt") or die "Can't Open File";
	open(FILE,"$sendmaildir/$cpcode/query.txt") or die "Can't Open File";
	while(read(FILE,$buffer,1024))
	{
		$query1.=$buffer;
	}
	close(FILE);

	#$query1 = chop($query);

	#print "QUERY1 - $query1<br>";
	#exit;
	#$query1=urldecode($query1);
	$tot_rec=0;
	$sel_ids=$db->prepare("$query1");
	$sel_ids->execute;
	while(($db_user,$db_name,$db_nick,$db_company,$db_prefix)=$sel_ids->fetchrow_array)
		{
		$sel_email=$db->prepare("select Email from $cpcode"."_Email where User_Id='$db_user'");
		$sel_email->execute;
		while(($db_email)=$sel_email->fetchrow_array)
			{
			#print"$db_user,$db_name,$db_company,$db_email<br>";
			push(@dbuser,$db_user);
			$len= length($db_prefix);
			if($len!=0)
			{
				push(@dbname,$db_prefix."\.$db_name");
			}
			else
			{
				push(@dbname,$db_name);

			}

#			push(@dbname,$prefix."\.$db_name");
			push(@dbnick,$db_nick);
			push(@dbcompany,$db_company);
			push(@recepientid,$db_email);
			}
			$tot_rec=$tot_rec+1;
		}

#print "RECEPIENTS - OP5- $recepientid[0],$recepientid[1],$recepientid[2],$recepientid[3],$recepientid[4]<BR>";
	
#	 &check_emails($tot_rec,$email_shot,$all_ids,$alr_sentids);


	}

############## END OF OPTION 5 ############################################














################# CHECK IF UNSUBSCRIBE IS TO BE SENT ##############

$unsubscribe = $query->param('unsubscribe');

############## GET THE MAIL ID OF THE ADMIN FROM THE SIGNATURE FOLDER ###########

$admin_email='angler@coimbatore.net';

#push(@recepientid,$admin_email);

#	foreach $test(@recepientid)
#		{
#		print "Rece - $test<br>";
#		}


#print "HTMLMAIL -- $htmlmail<br>";
#print "mail type = $mailtype";


############# WRITE ALL THE SELECTED RECEPIENT EMAIL IDS INTO A TEXT FILE ##############

#foreach $recip_id(@recepientid)
#{
#$format_reci.="$recip_id"."&";
#}

#$format_reci.="^"."$Name"."^"."$sender"."^"."$subject";

#open(EMAILLOG,">$basedir/admin/herald/emails.txt") || die "error";

#print EMAILLOG  $format_reci;

#close(EMAILLOG);
		#print "MAIL TIME - correct";
############ IF THE MAIL HAS TO BE SENT IN A LATER DATE ########

	if($mail_time == 1)
		{
		#print "correct";
		require "herald_sendmail_later.pl";
		exit;		
		}


############# IF HTML MAIL TO BE SENT ##################################

if($htmlmail == 1)
{
     	$draft_name      = $query->param('html_draft');    #-------- Draft name-------------#

#print "DRAFT NAME - $draft_name<BR>";

#print "started calling the HTML Mailer<br>";


#print "YES";

require "herald_send_htmlmail.pl";

#print "Location: http://www.angleritech.com/admin/herald/send_html.shtml\n\n";
exit;
}

######### IF DRAFTED MAIL ##########################################
elsif($mailtype)
{
#print "started calling the Drafted Mailer<br>";

require "herald_send_dmail.pl";
exit;		

}

######### IF NEW MAIL ##########################################

else
{

#print "OK - New Mail";

require "herald_send_cmail.pl";
exit;		

}

sub check_emails
{

  my $tot_rec=$_[0];
  my $email_shot=$_[1];
 my $all_emailids=$_[2];

 my $prev_sentids=$_[3];


if($tot_rec > $email_shot)	
{
$confirm_msg = "You cannot send mails to $tot_rec email ids at 1 shot";
require "confirmations.pl";
exit;
print "";
exit;
}

$cal_presentids = $tot_rec + $prev_sentids;

if($cal_presentids > $all_emailids)	
{
$confirm_msg = "You can send mails only to $all_emailids Email Ids during your Trial Version.<br><br> You have already sent to $prev_sentids Email ids.<br>Kindly reduce the Number of Email Ids & then send the mail";
require "confirmations.pl";
exit;
print "";
exit;
}
}


sub check_bandwidth_db
{
	my $bandwidth_usage=$_[0];
	
	if($bandwidth_usage<=0)
	{
		$confirm_msg = "You have used the alloted quota of bandwidth.Kindly contact marketing team-mktg\@angleritech.com to renew your account";
		require "confirmations.pl";
		exit;
		print "";
		exit;
	}		

}

