#!/usr/bin/perl

	#**************************************************************************
	#**************************************************************************
	# Project          :  ANGLER Herald               Started       : 24 Apr 2002     
	# Module           :  Signature                   Last Modified : 22 Jul 2002
	# Version		 :  1.0
	# Domain           :  www.jayanthra.com                                   
	# Programmer       :  J Poornima                       
	# Inprogress       :  \\Angler3\d\Projects\InProgress\Herald0202           
	# Backup           :  \\Angler2\d\Projects\InProgress\Herald0202                            
	#**************************************************************************
	# Description      :  This program sends html mails     
	#			     								            	          
	# Input	        :       
	#**************************************************************************

$url="www.anglerherald.com";
#####################################################################################
#######################    Files used                    ############################
#####################################################################################
#------------- htmlfile1.html - sentmail html contents -----------------------------#
#------------- htmlfile.html - html contents to be sent in mail --------------------#
#------------- count.dat - Total number of images in the html page uploaded --------#
#------------- images.txt - image names present in the html page uploaded ----------#




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

#$mailprog       = '/usr/sbin/sendmail';

#use MIME::Lite; 

use CGI;
use CGI::Carp qw(fatalsToBrowser);

#use integer;
use File::Copy;

use Mail::POP3Client;

require "mimetypes.cfg";

require "../cgi-local/Mail/POP3Client.pm";


$opt_ion="h";

########## GET THE SMTP SERVER DETAILS FROM THE Cpcode Herald Users table ############

$smtp_details=$db->prepare("select Smtp_Servername,Pop_Username,Pop_Password from $cpcode"."_Herald_Users");
$smtp_details->execute;
($smtp_servername,$pop_username,$pop_password)=$smtp_details->fetchrow_array();
$smtp_details->finish();

########## GET THE SMTP SERVER DETAILS FROM THE Cpcode Herald Users table ############


$pop1 = new Mail::POP3Client( USER     => "$pop_username", PASSWORD => "$pop_password", HOST  =>"$smtp_servername" );


$delivery_count = $pop1->Count();

use Mail::Sender;

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


$html_type = 'text/html';


$auto_type1 = 'image/jpg';

$auto_encoding = 'base64';

$auto_encoding1 = '7bit';

$message_type = 'multipart/related';


$basedir = "..";



######### GET EMAIL IDS, SENDER NAME, SENDER EMAIL, SUBJECT ####################

#open(MAIL,"../admin/herald/emails.txt") or die "Can't Open File";

#	while(read(MAIL,$mail_details,1024))
#	{
#		$all_mail_details.=$mail_details;
#	}
#close(MAIL);

#print "FINE SPLIT";



#@final_mail_details = split(/\^/,$all_mail_details);


#$only_emails = $final_mail_details[0];

#$Name = $final_mail_details[1];
#$sender = $final_mail_details[2];
#$subject = $final_mail_details[3];

#@recepientid = split(/\&/,$only_emails);

#print"RECPIENT ID - @recepientid <BR>";
#print"Name - $Name<BR>";
#print"SENDER EMAIL- $sender<BR>";
#print"SUBJECT - $subject<BR>";

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

$sender_name = "\"$Name\" <$sender>";               ###### SENDER NAME & EMAIL

$mail_name        =        $query->param("mail_name");            ###### MAIL NAME

#print "SENDER -$sender_name<br>";


############# GET ALL THE IMAGE NAMES #######################

#open(FILE,"../jayanthra/admin/htmlattach/images.txt") or die "Can't Open File";
open(FILE,"$htmlattachdir/$cpcode/images.txt") or die "Can't Open File";

	while(read(FILE,$buffer,1024))
	{
		$images.=$buffer;
	}
close(FILE);




@imgarr = split(/\n/g,$images);


for($i=0;$i<$#imgarr;$i++)
{
	#print "IMAGE NAMES -- $imgarr[$i]<br>";
	$imgarr[$i] = $imgarr[$i];
}






############# READ THE BACKGROUND IMAGE ####################

#open(FILE,"../jayanthra/admin/htmlattach/bg.txt") or die "Can't Open File";
#open(FILE,"$htmlattachdir/$cpcode/bg.txt") or die "Can't Open File";

#	while(read(FILE,$buffer,1024))
#	{
#		$bg.=$buffer;
#	}
#close(FILE);

#print "BG IMAGE -- $bg<br>";

########### IF BACKGROUND IMAGE IS PRESENT ##################
#if($bg ne "")
#{
	
#	push(@imgarr,$bg);
#}


############## COUNT OF IMAGES ###############################

open(FILE,"$htmlattachdir/$cpcode/count.dat") or die "Can't Open File";

	while(read(FILE,$buffer,1024))
	{
		$total.=$buffer;
	}
close(FILE);


################# READ THE HTML FILE TO BE SENT IN MAIL #############

open(FILE,"$htmlattachdir/$cpcode/htmlfile.html") or die "Can't Open File";
	while(read(FILE,$buffer,1024))
	{
		$htmlcontent.=$buffer;
	}
close(FILE);




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

############# ATTACHMENTS ###########################

$pathing="$attach_dir/$cpcode";	#### PATH OF THE ATTACHMENT DIRECTORY 

############## CHECK FOR THE MAIL SIZE ####################################3


####### ATTACHMENTS SIZE ############


######## SIZE OF IMAGES IN HTMLATTACH FOLDER #################

opendir(PICFILES,"$pathing") || die "error";

@files = grep !/^\.\.?$/,readdir(PICFILES);

closedir(PICFILES);


opendir(HTMLFILES,"$htmlattachdir/$cpcode") || die "error cannot open the Attachment directory";

@html_files = grep !/^\.\.?$/,readdir(HTMLFILES);

closedir(HTMLFILES);


#foreach $html_files(@html_files)
#{
#if(($html_files eq "bg.txt")||($html_files eq "count.dat")||($html_files eq "htmlfile1.html")||($html_files eq "images.txt"))
	#{
	#	next;
	#}


#push(@final_html_files,$html_files);

#}


$totalsize = fsize("$pathing") + fsize("$htmlattachdir/$cpcode");

$file_kbsize = $totalsize/1024;



#@org_filesize = split(/\./,$file_kbsize);



###### To calculate the Bandwidth due to Administrators mail, One is added ############

$tot_rec = $tot_rec+1;

$calculate_bw=(($file_kbsize*$tot_rec)/(1024*1024));


#################### GET THE ALLOTED MAIL SIZE FOR THE USER ######################

$get_mailsize=$db->prepare("select First_name,User_name,Max_Mailsize,Bw_Usage  from $cpcode"."_Herald_Users where Company_id='$cpcode'");
$get_mailsize->execute;

($admin_name,$admin_email,$given_mailsize,$remain_bw_size)=$get_mailsize->fetchrow_array;


############### CHECK IF SIZE EXCEEDS ############
#$org_filesize[0]>$given_mailsize or
if( $calculate_bw>$remain_bw_size)
{
#print "FILE SIZE EXCEEDS";
#if($org_filesize[0]>$given_mailsize)
#	{
#	 $msg.="Mail File size exceeds the alloted size of $given_mailsize KB";
#	}
#	if($calculate_bw>$remain_bw_size)
#	{

	 $msg.="Your current mail size and the number of selected email ids exceeds your alloted bandwidth.Kindly reduce either the mail size or the number of mail ids";

#	}


################ DELETE ALL THE ATTACHMENTS #######################
############### UNLINK THE ATTACHMENTS ########################


unlink "$attach_dir/$cpcode/$files[0]";
unlink "$attach_dir/$cpcode/$files[1]";
unlink "$attach_dir/$cpcode/$files[2]";

################# DELETE  ALL THE IMAGES IN HTML ATTACH DIRECTORY #############

#unlink "$sendmaildir/$cpcode/bg/$image1";
#unlink "$sendmaildir/$cpcode/pic1/$image2";
#unlink "$sendmaildir/$cpcode/pic2/$image3";

#foreach $html_files(@html_files)
#{
#unlink "$htmlattachdir/$cpcode/$html_files";

#}

$confirm_msg = $msg;

require "confirmations.pl";


exit;
}

###########

sub fsize()
{
	my($a,$b)=@_;
	opendir(FILES,"$a");
	@files1 = grep !/^\.\.?$/,readdir(FILES);
	closedir(FILES);

	$size=0;

	foreach $temp(@files1)
	{

		if($a eq "$htmlattachdir/$cpcode")
		{
		if(($temp eq "bg.txt")||($temp eq "count.dat")||($temp eq "htmlfile1.html")||($temp eq "images.txt"))
			{
			next;
			}
	
		}
		@file_size=stat("$a/$temp");
		$size=$size+$file_size[7];
	}

	return $size;
}

############## CHECK FOR THE MAIL SIZE ####################################3


############# GET ALL FILES FROM ATTACH DIRECTORY IF THERE ARE ATTACHMENTS#####


	$nameing=1;

	#$path1="$basedir/jayanthra/admin/attach/$files[0]";
	#$path2="$basedir/jayanthra/admin/attach/$files[1]";
	#$path3="$basedir/jayanthra/admin/attach/$files[2]";


	$path1="$pathing/$files[0]";
	$path2="$pathing/$files[1]";
	$path3="$pathing/$files[2]";

#print "ATTACHMENTS1 - $path1<BR>";
#print "ATTACHMENTS2 - $path2<BR>";
#print "ATTACHMENTS3 - $path3<BR>";

#$mailids="<hr> <br><table width=\"80%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\" align='center'><tr>   <td align=\"center\"><font face=\"Verdana\" size=\"2\"><b><u>Mail has been     sent to the following E-Mail Ids.</u></b></font></td></tr><tr>  <td>&nbsp;</td></tr></table><table width=\"80%\" border=\"1\" cellspacing=\"1\" cellpadding=\"5\" bordercolor=\"#DDDDDD\" align='center'>  <tr valign=\"top\" bgcolor=\"#CCCCCC\">     <td width=\"4%\"><b><font face=\"verdana\" size=\"2\">S.No</font></b></td>    <td width=\"32%\"><b><font face=\"verdana\" size=\"2\">Name</font></b></td>    <td width=\"32%\"><b><font face=\"verdana\" size=\"2\">Organization</font></b></td>    <td width=\"32%\"><b><font face=\"verdana\" size=\"2\">E-Mail       ID</font></b></td>  </tr>";
#print "STARTED SENDING MAILS";


############# GET ALL THE SENTMAIL CONTENTS ##########################
############# GET THE DATE TIME FOR THIS MAIL ########################

############# INSERT THE SENTMAIL CONTENTS  ##########################
################ INSERT THE FOLLG DETAILS INTO THE SENTMAIL TABLE ############
################ Mail name
################ Mail sent date
################ Mail subject
################ Sender name
################ Sender Email
############# GET ALL THE EMAIL IDS IN AN ARRAY ######################

$mail_type = "h";                                ########## MAIL TYPE IS h for HTML MAIL
$tot_ids = $#recepientid + 1;                ########## TOTAL NO OF EMAIL IDS
$mails_inq = $tot_ids;                        ########## MAILS IN QUEQUE

########### IF UNSUBSCRIBE OPTION HAS BEEN CHOSEN - $spam would be 1 ####

########## ATTACHMENTS IF ANY #################

foreach $files(@files)
{
	$attach_files.=$files;
	$attach_files.=",";
}

########### REMOVE THE COMMA AT THE LAST ##################################

$attach_files =~ s/,$//;



############# GET THE DATE, TIME IN THIS FORMAT - 2003-04-02 16:11:30 ##########################

$present_date = "$ind_year-$ind_mon-$ind_day "."$ind_hour:$ind_min:$ind_sec";

$datetime=$present_date;

if($unsubscribe)
{
		$unsub_txt="<br><table width='80%' border='0' align='center'><tr><td><font face='Verdana, Arial, Helvetica, sans-serif' size='1'>Click here to <a href='#'>unsubscribe</a></font></td></tr></table><br>";
		$spam=1;
}




$insert_mail=$db->prepare("insert into $cpcode"."_Sentmail set Mail_Name='$mail_name',Mail_Date='$datetime', Mail_Subject='$subject',Sender_Name='$Name',Sender_Email ='$sender',Salutation ='$salutation',Unsubscribe='$spam',Signature_Id='$signature_no',Attachments='$attach_files',Mails_sent='',Mails_in_Q='$mails_inq',Mail_Type='$mail_type',Total_Emailids='$tot_ids',Send_Mode='$choice',Bw_Usage=$calculate_bw");


$insert_mail->execute;

################ GET THE SENTMAIL ID ####################################################


$get_mailid=$db->prepare("select Mail_Id from $cpcode"."_Sentmail where Mail_Name='$mail_name' and Mail_Date='$datetime'");
$get_mailid->execute;

($mail_id=$get_mailid->fetchrow_array);


############# GET ALL THE PERSON NAMES IN AN ARRAY ###################

############# PUSH ALL THE RELEVANT CONTENTS SUCH AS ATTACHMENTS, PICTURES IF ANY INSIDE THE DIRECTORIES ########

############## PUT THE INFORMATION IN EMAIL QUEQUE TABLE ###################

#------------------ ADMINISTRATOR EMAIL ID WILL BE THE LAST ---------------#
$get_username=$db->prepare("select User_name from $cpcode"."_Herald_Users");
$get_username->execute;

($admin_mailid=$get_username->fetchrow_array);


if(($cpcode eq "angtec")||($cpcode eq "angexp"))
{
	$db=DBI->connect("DBI:mysql:$other_dbname:$other_hostname",$other_uname,$other_password);
}


#------- TO USE THE PREVIOUS FOR LOOP WHEN ADMIN MAIL IS USED -------------#
for($k=0;$k<=$#recepientid;$k++)

{


        #---------- if the first choice is selected ----------

       #---------- if nickname is available, display nick name instead of name ----------

	if($dbnick[$k] ne "")
	{
			$disp_name=$dbnick[$k];
	}
	else
	{
			$disp_name=$dbname[$k];
	}
		
	#---------- if the first choice is selected ----------

	if($choice == 1)
	{
		$dbuser[$k]="";
		$dbname[$k]="";
		$dbcompany[$k]="";
		$disp_name="Sir/Madam";

	}

	&Current_IST();


	$present_date = "$ind_year-$ind_mon-$ind_day "."$ind_hour:$ind_min:$ind_sec";
	$insert_mailq=$db->prepare("insert into Email_Queque set Cpcode='$cpcode',Email_Id='$recepientid[$k]',Person_Name='$disp_name',Cpname='$dbcompany[$k]',Mail_Sent='0',Sentmail_Id='$mail_id',Mail_Date='$present_date',User_Id='$dbuser[$k]'");

	$insert_mailq->execute;


}

########## RESET THE DB VALUES OF ANGLER ACCOUNTS TO ORIGINAL ONES ########

if(($cpcode eq "angtec")||($cpcode eq "angexp"))
{
	$db=DBI->connect("DBI:mysql:$ang_dbname:$ang_hostname",$ang_uname,$ang_password);
}
########## RESET THE DB VALUES OF ANGLER ACCOUNTS TO ORIGINAL ONES ########


$mails_sent = 0;

##################### PATH OF THE DIRECTORY ######################################

$folder_name="$sentmaildir/$cpcode/$mail_id";


###################### MAKE A DIRECTORY BASED ON THE MAIL ID #####################

mkdir("$folder_name", 0755);


######## CHECK IF THE HTML DRAFT IS TO BE STORED #######################

open(FILE,"$htmlattachdir/$cpcode/htmlfile1.html") or die "Can't Open File";

while(read(FILE,$buffy,1024))
{
	$admin_cons.=$buffy;
}
close(FILE);

if($draft_name)
{
	###############Get TOTAL NUMBER OF HTML DRAFTS ALLOWED FOR THIS ACCOUNT#########3
	
	$tot_draft=$db->prepare("select Tot_Htmldrafts from $cpcode"."_Herald_Users");
	$tot_draft->execute;
	($total_draft_allowed=$tot_draft->fetchrow_array);		###### DRAFT ID	
	
	############### Get total number of html draft alreay created for this account#######
	
	$created_draft=$db->prepare("select Draft_Id from $cpcode"."_Draft where Draft_Type='2'");
	$created_draft->execute;
	$created_draft_count=0;
	while($draft_id=$created_draft->fetchrow_array())
	{
		$created_draft_count=$created_draft_count+1;
	}
	$created_draft_count=$created_draft_count-1;


	############## checking if created draft <= allowed draft if less the allow to insert new draft####	
	if($created_draft_count<$total_draft_allowed)
	{
		################ INSERT THE DRAFT NAME INTO THE DRAFT TABLE ############
		################ DRAFT TYPE IS 2 FOR HTML MAILERS ######################
		
		$insert_draft=$db->prepare("insert into $cpcode"."_Draft values ('','$draft_name','2')");
		$insert_draft->execute;
		#----------- GET THE DRAFT ID BASED ON THE DRAFT NAME --------#

		$sel_query=$db->prepare("select Draft_Id from $cpcode"."_Draft where Draft_Name = '$draft_name'");
		$sel_query->execute;

		($draft_fname=$sel_query->fetchrow_array);		###### DRAFT ID	

		#------------ MAKE A DIRECTORY FOR THE DRAFT -----------------#

		$folder_name="$draftsdir/$cpcode/$draft_fname";
	

		#----------------- OPEN THE  DIRECTORY ----------------------#

		if(opendir(DIR, "$folder_name"))
		{
			  $nothing="";
		}
		else
		{
			  mkdir("$folder_name", 0755);
		}
	

		################# READ THE HTML FILE TO BE STORED IN SENT MAIL FOLDER #############

		
		############## WRITE THE HTML CONTENTS ############################################
		$file="$draftsdir/$cpcode/$draft_fname/$draft_fname.html";
	
		open(DRAFTCONTENTS,">$file");
		print DRAFTCONTENTS $admin_cons;
		close(DRAFTCONTENTS);

		#---------- If there are any images to be stored move to the drfats folder ----------#

		#---------- If there are any images to be stored move to the drfats folder ----------#

	}

	foreach $imgname(@imgarr)
	{
	
		$dest = $folder_name;
		$draft_dest = "$draftsdir/$cpcode/$draft_fname";
		$home_path  = "$htmlattachdir/$cpcode/$imgname";

		copy("$home_path","$dest");			##### COPY IMAGES PRESENT IN HTML TO SENTMAIL
		if($draft_name)
		{
			copy("$home_path","$draft_dest");		##### COPY IMAGES PRESENT IN HTML TO HTML DRAFT
		}

	}


	if($files[0])

	{

		$attach1="$folder_name/$files[0]";          
       
		copy("$path1","$attach1");			###### COPY FIRST ATTACHMENT

		$attach1_cons = "<tr><td><font face='Verdana, Arial, Helvetica, sans-serif' size='2'><b>Attachments</b></td></tr>
<tr><td> <font face='Verdana, Arial, Helvetica, sans-serif' size='2'><a href='$files[0]' target='_blank'>$files[0]</a></font></td></tr>";

	}

	############### IF SECOND ATTACHMENT IS PRESENT ###################################

	if($files[1])

	{

		$attach2="$folder_name/$files[1]";          
       
		copy("$path2","$attach2");			###### COPY SECOND  ATTACHMENT


		$attach2_cons = "<tr><td> <font face='Verdana, Arial, Helvetica, sans-serif' size='2'><a href='$files[1]' target='_blank'>$files[1]</a></font></td></tr>";

	}


	############### IF THIRD ATTACHMENT IS PRESENT ###################################

	if($files[2])

	{

		$attach3="$folder_name/$files[2]";          
       
		copy("$path3","$attach3");			###### COPY THIRD ATTACHMENT


		$attach3_cons = "<tr><td> <font face='Verdana, Arial, Helvetica, sans-serif' size='2'><a href='$files[2]' target='_blank'>$files[2]</a></font></td></tr>";

	}

}
######## THE HTML DRAFT IS FINALLY STORED #######################


##################### PATH OF THE DIRECTORY ######################################

$folder_name="$sentmaildir/$cpcode/$mail_id";

############### COPY ALL THE ATTACHEMENT IMAGES TO THE SENTMAIL DIRECTORY #####


################ CREATE A HTML FOR SENT MAIL MODULE ###############################

################ CONTENTS OF THE MAIL SENT ########################################
############### COPY ALL THE BG,PIC1 & PIC2 IMAGES TO THE SENTMAIL DIRECTORY #####

foreach $imgname(@imgarr)
{

	$dest = $folder_name;
	$draft_dest = "$draftsdir/$cpcode/$draft_fname";
	$home_path  = "$htmlattachdir/$cpcode/$imgname";

	copy("$home_path","$dest");			##### COPY IMAGES PRESENT IN HTML TO SENTMAIL
	if($draft_name)
	{
		copy("$home_path","$draft_dest");		##### COPY IMAGES PRESENT IN HTML TO HTML DRAFT
	}

}


if($files[0])

{

	$attach1="$folder_name/$files[0]";          
       
	copy("$path1","$attach1");			###### COPY FIRST ATTACHMENT

	$attach1_cons = "<tr><td><font face='Verdana, Arial, Helvetica, sans-serif' size='2'><b>Attachments</b></td></tr>
<tr><td> <font face='Verdana, Arial, Helvetica, sans-serif' size='2'><a href='$files[0]' target='_blank'>$files[0]</a></font></td></tr>";

}

############### IF SECOND ATTACHMENT IS PRESENT ###################################

if($files[1])

{

	$attach2="$folder_name/$files[1]";          
       
	copy("$path2","$attach2");			###### COPY SECOND  ATTACHMENT


	$attach2_cons = "<tr><td> <font face='Verdana, Arial, Helvetica, sans-serif' size='2'><a href='$files[1]' target='_blank'>$files[1]</a></font></td></tr>";

}


############### IF THIRD ATTACHMENT IS PRESENT ###################################

if($files[2])

{

	$attach3="$folder_name/$files[2]";          
       
	copy("$path3","$attach3");			###### COPY THIRD ATTACHMENT


	$attach3_cons = "<tr><td> <font face='Verdana, Arial, Helvetica, sans-serif' size='2'><a href='$files[2]' target='_blank'>$files[2]</a></font></td></tr>";

}


#----------- FINISHED PUSHING ALL ATTACHMENTS, FILES INSIDE THE DIRECTORIES --------------#

##################### MESSAGE CONTENTS OF THE MAIL TO BE STORED IN SENTMAIL ################

if($unsubscribe)
{
	$admin_cons=~s/<!--unsubscribe-->/$unsub_txt/g;
}
if($signature_no)
{
	$admin_cons=~s/<!--sign-->/$sign/g;
}

$admin_cons=~s/<!--name-->/$admin_name/g;


#------ Since we do not have the Company Name in Herald Users table this has been commented  ---------#

#	$admin_cons=~s/<!--companyname-->/$dbcompany[$k]/g;

#------ Since we do not have the Company Name in Herald Users table this has been commented  ---------#


$sentmail_cons = "$admin_cons";

#$sentmail_cons.="$sign<br><table width='80%' border='0' cellspacing='3' cellpadding='3' align='center'>"."$attach1_cons"."$attach2_cons"."$attach3_cons"."</table><br>"
#."$unsub_txt"."$mailids<br>";

$sentmail_cons.="<br><table width='80%' border='0' cellspacing='3' cellpadding='3' align='center'>"."$attach1_cons"."$attach2_cons"."$attach3_cons"."</table><br>";


#print "SENTMAIL CONTENTS - $sentmail_cons<BR>";


################### WRITING THE MESSAGE CONTENTS INTO THE SENTMAIL FOLDER ##########
$sentmail_cons=~s/<!--action-->/http:\/\/www\.anglerherald\.com\/cgi-local\/Subscription\.pl/gi;

open(MAILCONTENTS,">$sentmaildir/$cpcode/$mail_id/$mail_id.html") or die "CANNOT WRITE INTO SENTMAIL FILE";
print MAILCONTENTS $sentmail_cons;
close(MAILCONTENTS);

################### WRITING THE MESSAGE CONTENTS INTO THE SENTMAIL FOLDER ##########

#open(MAILCONTENTS,">$sentmaildir/$cpcode/$mail_id/htmlfile1.html");
#print MAILCONTENTS $sentmail_cons;
#close(MAILCONTENTS);

################### WRITING THE MESSAGE CONTENTS INTO THE SENTMAIL FOLDER ##########

open(MAILCONTENTS,">$sentmaildir/$cpcode/$mail_id/htmlfile.html");
print MAILCONTENTS $htmlcontent;
close(MAILCONTENTS);
$fname="htmlfile";
&TrackUrl;
$htmlcontent=$finalcontent;

open(MAILCONTENTS,">$sentmaildir/$cpcode/$mail_id/htmlfile.html");
print MAILCONTENTS $htmlcontent;
close(MAILCONTENTS);
################ FINISH CREATING A HTML FOR SENT MAIL MODULE ###########

####################update  Bandwidth###################

$select_bandwidth=$db->prepare("select Bw_Usage from $cpcode"."_Herald_Users");
$select_bandwidth->execute;
($remain_bw)=$select_bandwidth->fetchrow_array;
$remain_bw=$remain_bw-$calculate_bw;

$update_bandwidth=$db->prepare("update $cpcode"."_Herald_Users set Bw_Usage=$remain_bw");
$update_bandwidth->execute;

############### GET THE NUMBER OF MAIL IDS TO WHOM MAIL WAS SENT #####################

$get_tot_mailids=$db->prepare("select Emailids_Usage,Mail_Usage from $cpcode"."_Herald_Users where Company_id='$cpcode'");
$get_tot_mailids->execute;


($prev_no_ids,$prev_mails_sent)=$get_tot_mailids->fetchrow_array;

$tot_ids_sent = $tot_ids + $prev_no_ids + 1;	### Last addding 1 is for Administrator mail sent

$tot_mails_sent = $prev_mails_sent + 1;


############### UPDATE THE MAILS SENT IN THE ACCOUNT DATABASE #####################
$table1_status=$db->prepare("update $cpcode"."_Herald_Users set Emailids_Usage='$tot_ids_sent',Mail_Usage='$tot_mails_sent' where Company_id='$cpcode'");
$table1_status->execute;

############### FINISHED CREATING THE SENTMAIL CONTENTS #################

$send_admin_mail=0;


########## If the no of email Ids to whom mail is to be sent is less than or equal to 100 #############

if($tot_ids <= $mails_oneshot)
{
	$mail_limit = $#recepientid;
}
########## If the no of email ids is more than 100 ###############
else
{
	$mail_limit = $mails_oneshot-1;
}

################# AFTER MAIL IS SENT TO ALL recipients & THE ADMINISTRATOR #########



$admin_mailer=1;

if(($cpcode eq "angtec")||($cpcode eq "angexp"))
{
	$db=DBI->connect("DBI:mysql:$other_dbname:$other_hostname",$other_uname,$other_password);
}

&Send_Mails;                                        ######## CALL THE SUBROUTINE

############## END OF CHECK IF STILL MAIL IS TO BE SENT TO ANYONE IN THE LIST ####

$send_admin_mail=1;

#------------ SEND ADMIN MAIL -------------------#

if($send_admin_mail==1)
{


	&Emails_inq();			###  CALL THE SUBROUTINE TO FORMAT THE EMAIL IDS TO WHOM MAIL WAS SENT

	#---------- GET THE ADMINISTRATOR NAME & EMAIL ID ------------#

	$#recepientid=-1;
	$#dbname=-1;
	$#dbcompany=-1;
	$#dbuser=-1;
	

	push(@recepientid,$admin_email);
	push(@dbname,$admin_name);
	push(@recepientid,$admin_email);
	push(@dbname,$admin_name);


	#---------- FINISH GETTING THE ADMINISTRATOR NAME & EMAIL ID ------------#


	$mail_limit=$#recepientid;

	$admin_mailer=1;
	&Send_Mails();			### Call the subroutine to send mails


}

#------------ SEND ADMIN MAIL -------------------#

#-------- DELETE THE ENTRIES FROM Email_Queque TABLE AFTER SENDING MAILS TO ALL EMAIL IDS IN THE LIST ---------#

$del_ids=$db->prepare("delete from Email_Queque where Cpcode='$cpcode' && Sentmail_Id='$mail_id'");
$del_ids->execute;

$db = DBI->connect("DBI:mysql:$dbname:$ipadd",$dbus,$dbpass);


################# AFTER MAIL IS SENT TO ALL recipients & THE ADMINISTRATOR #########

################ Update bandwidth ###########################


################### WRITING THE EMAIL IDS INTO THE EXCEL FILE ##########

open(MAILCONTENTS,">$sentmaildir/$cpcode/$mail_id/$mail_id.xls");
print MAILCONTENTS $mailids;
close(MAILCONTENTS);



################# DELETE  THE ATTACHMENTS ############

unlink "$attach_dir/$cpcode/$files[0]";
unlink "$attach_dir/$cpcode/$files[1]";
unlink "$attach_dir/$cpcode/$files[2]";

################# DELETE  THE BG IMAGE, PICTURE1, PICTURE2 ############



#$last = "angler\@coimbatore.net";

#push(@recepientid,$last);


#foreach $imgname(@imgarr)
#{
	#unlink("$basedir/jayanthra/admin/htmlattach/$imgname");
#	unlink("$basedir/admin/herald/htmlattach/$imgname");
#}



#unlink("$basedir/jayanthra/admin/htmlattach/images.txt");
#unlink("$basedir/jayanthra/admin/htmlattach/bg.txt");
#unlink("$basedir/jayanthra/admin/htmlattach/htmlfile.html");
#unlink("$basedir/jayanthra/admin/htmlattach/htmlfile1.html");
#unlink("$basedir/jayanthra/admin/htmlattach/count.dat");

#unlink("$htmlattachdir/$cpcode/images.txt");
#unlink("$htmlattachdir/$cpcode/bg.txt");
#unlink("$htmlattachdir/$cpcode/htmlfile.html");
#unlink("$htmlattachdir/$cpcode/htmlfile1.html");
#unlink("$htmlattachdir/$cpcode/count.dat");

#require "herald_mailstatus.pl";
##############


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

print"<html>
<head>
<title>ANGLER Herald</title>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>

<script language='javascript' src='$jsdir/jsfns.js'></script>

<script language='javascript'>

function valid()
	{
	self.location='$scriptsdir/html_fileupload.php';
	return false;
	}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf(\"#\")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf(\"?\"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}

}

</script>

</head>

<body bgcolor='#FFFFFF' text='#000000' onLoad=\"MM_preloadImages('$imagesdir/top_r2_c2_f2.gif','$imagesdir/top_r2_c3_f2.gif','$imagesdir/top_r2_c4_f2.gif','$imagesdir/top_r2_c5_f2.gif','$imagesdir/top_r2_c1_f2.gif','$imagesdir/groups_mo.gif','$imagesdir/festivals_mo.gif','$imagesdir/drafts_mo.gif','$imagesdir/sent_mo.gif','$imagesdir/signature_mo.gif','$imagesdir/address_mo.gif','$imagesdir/import_mo.gif','$imagesdir/export_mo.gif','$imagesdir/unsubscribe_mo.gif','$imagesdir/compose_mo.gif','$imagesdir/drafted_mo.gif','$imagesdir/htmlmail_mo.gif','$imagesdir/send_mo.gif','$imagesdir/birthdays_mo.gif','$imagesdir/anniversaries_mo.gif','$imagesdir/festivals2_mo.gif','$imagesdir/menu_mo.gif')\" leftmargin='0' topmargin='0' marginwidth='0' marginheight='0' link='#000000' vlink='#000000' alink='#000000' onResize='javascript:location.reload()'>

<script language='javascript' src='$jsdir/mail_menu.js'></script>


<form name='form1'>

<br><br>

<table width='100%' border='0' cellspacing='0' cellpadding='0' align='center'>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>

<table width='100%' border='0' cellspacing='0' cellpadding='0' align='center'>
  <tr align='center'> 
    <td height='30'><b><font face='Verdana, Arial, Helvetica, sans-serif' size='3'>Mail Sent</font></b></td>
  </tr>
</table>
<br>

<table width='50%' border='1' cellspacing='0' cellpadding='0' align='center' bordercolor='#FFCC99'>
  <tr>
    <td>
      <table width='100%' border='1' cellspacing='1' cellpadding='2' align='center' bordercolor='#FFCC99' >
        <tr bgcolor='#FFF4EA' align='center'> 
          <td height='19' bgcolor='#FFF4EA'><b><font face='Verdana, Arial, Helvetica, sans-serif' size='2'><b>Mail has been sent</b></font></td>
        </tr>
      </table>
    </td>
  </tr>
</table>
<br>";


print "$invalid_msg
<br>
<table align='center' cellpadding='3' cellspacing='3'>

    <tr align='center'> 
      <td height='30'> <a href='#' onFocus='this.blur()' onClick='return valid()' onMouseOut='MM_swapImgRestore()' onMouseOver=\"MM_swapImage('Menu','','$imagesdir/menu_mo.gif',1)\"><img src='$imagesdir/menu.gif' width='91' height='28' border='0' alt='Menu' name='Menu'></a></td>
    </tr>

</table>

</form>
<table border='0' align='center' cellpadding='0' cellspacing='0'  width='100%'>
  <tr> 
    <td   align='center' valign='top'> <font face='Arial, Helvetica, sans-serif' size='1' color='#000000'>Web 
        Solution Architecture Powered by <a href='http://www.angleritech.com' target='_blank'><font color='#000000'>ANGLER 
        Technologies</font></a></font>
    </td>
  </tr>
</table>
</body>
</html>";
1;


##################################################################
################### SUBROUTINE AREA ##############################
##################################################################


#--------------- SUBROUTINE TO CALCULATE THE CURRENT TIME -------#

sub Current_IST
{
	###################################### TIME CALCULATION ################################

	#-------------Getting GMT in variable $time---------------------#

	$time=gmctime();


	#------------Parsing time for Year,Month,Day,Hour,Sec-----------#

	$time=~/(Mon|Tue|Wed|Thu|Fri|Sat|Sun)/;
	$Weekday=$1;

	$time=~/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/;
	$Month=$1;

	$time=~/(..):(..):(..)/;
	$hour=$1;
	$min=$2;
	$sec=$3;

	$time=~/ (\d+) /;
	$mday=$1;

	$time=~/ (\d+)$/;
	$year=$1;

	%month=(
Jan=>0,Feb=>1,Mar=>2,Apr=>3,May=>4,Jun=>5,Jul=>6,Aug=>7,Sep=>8,Oct=>9,Nov=>10,Dec=>11,);

	$dmonth=$month{$Month};



	$plus_time=5*60*60+30*60;

	$secs_ahead=timelocal($sec,$min,$hour,$mday,$dmonth,$year)+$plus_time;

	#---Finally India Time is got ----------------------#

	$india_time=localtime($secs_ahead);


	$india_time=~/ (\d+) /;
	$ind_day=$1;


	$india_time=~/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/;
	$ind_mon=$1;

	if($ind_mon eq "Jan")
	{
		$ind_mon="01";

	}

	if($ind_mon eq "Feb")
	{
		$ind_mon="02";
	}
	if($ind_mon eq "Mar")
	{
		$ind_mon="03";
	}
	if($ind_mon eq "Apr")
	{
		$ind_mon="04";
	}
	if($ind_mon eq "May")
	{
		$ind_mon="05";
	}
	if($ind_mon eq "Jun")
	{
		$ind_mon="06";
	}
	if($ind_mon eq "Jul")
	{
		$ind_mon="07";
	}
	if($ind_mon eq "Aug")
	{
		$ind_mon="08";
	}

	if($ind_mon eq "Sep")
	{
		$ind_mon="09";
	}
	if($ind_mon eq "Oct")
	{
		$ind_mon="10";
	}

	if($ind_mon eq "Nov")
	{
		$ind_mon="11";
	}
	if($ind_mon eq "Dec")
	{
		$ind_mon="12";
	}
	$india_time=~/ (\d+)$/;
	$ind_year=$1;


	$india_time=~/(..):(..):(..)/;
	$ind_hour=$1;
	$ind_min=$2;
	$ind_sec=$3;
	
}

##################################### END OF TIME CALCULATION ##########################


#--------------- END OF SUBROUTINE TO CALCULATE TIME ------------#


#-------------- SUBROUTINE TO SEND MAILS ------------------------#

sub Send_Mails
{


	if($smtp_servername=~/(^[A-Z])/gi)
	{
		$smtp_value="smtp.".$smtp_servername;
	}
	else
	{
		$smtp_value=$smtp_servername;
	}

	for($k=0;$k<=$mail_limit;$k++)
	{

		&Current_IST();

		#---------- if nickname is available, display nick name instead of name ----------

		if($dbnick[$k] ne "")
		{
			$disp_name=$dbnick[$k];
		}
		else
		{
			$disp_name=$dbname[$k];
		}
		
		if($dbcompany[$k] eq "")
		{
			$dbcompany[$k]="";
		}
		else
		{
			$dbcompany[$k]="M\/s. ".$dbcompany[$k];
		}

		#---------- if the first choice is selected ----------

		if($choice == 1)
		{
			$dbuser[$k]="";
			$dbname[$k]="";
			$dbcompany[$k]="";
		
			$disp_name="Sir/Madam";

		}


		############ IF THE OPTION UNSUBSCRIBE IS SELECTED ############
  	
		if($unsubscribe)
			{
				$unsub_txt="<table align='center' width='80%'><tr align='center'><td align='center'><font face='Verdana, Arial, Helvetica, sans-serif' size='1'>Click here to <a href='http://www.anglerherald.com/scripts/unsubscribe.php?em=$dbuser[$k]&cpcode=$cpcode' target='_blank'>unsubscribe</a> 
</font></td></tr></table>";
			}

		 if($send_admin_mail == 1)
              {
                       $unsub_txt="<br><table align='center' width='80%'><tr align='center'><td align='center'><font face='Verdana, Arial, Helvetica, sans-serif' size='1'>Click here to <a href='#'>unsubscribe</a></font></td></tr></table><br>";
              }
	
	    $new_content = $htmlcontent;
	    $new_content=~s/<\/body>/$unsub_txt$admin_mail<\/body>/g;


		########## SEARCH & REPLACE NAME & COMPANY TAGS #############################

		$new_content=~s/<!--emailid-->/$recepientid[$k]/g;
		$new_content=~s/<!--name-->/$disp_name/g;
	
		$new_content=~s/<!--companyname-->/$dbcompany[$k]/g;
	
		if($unsubscribe)
		{
			
			$new_content=~s/<!--unsubscribe-->/$unsub_txt/g;
		}
		if($signature_no)
		{
			$new_content=~s/<!--sign-->/$sign/g;
		}	

		#######this helps to replace the userid of receipent in individual mail
		$new_content=~s/<!--userid-->/$dbuser[$k]/gi;
		

		#######this helps to replace the recemailid of receipent in individual mail
		$new_content=~s/<!--recemailid-->/$recepientid[$k]/gi;




		$sender = new Mail::Sender
		  {smtp => "$smtp_value", from => "$sender_name"};


       
                if (ref $sender->OpenMultipart({
                        from => "$sender_name",to => "$recepientid[$k]",
                        subject => "$subject",
                        multipart => 'related'
                })){
		
					 $sender->Part({ctype => 'multipart/alternative'});
                               $sender ->Part({ ctype => 'text/plain', disposition => 'NONE', msg => "$new_content" });
        
                                $sender->Part({ctype => 'text/html', disposition => 'NONE', msg => "$new_content"});
        
                        $sender->EndPart("multipart/alternative");



	
				foreach $imgname(@imgarr)
				{

					$ext = split("\.",$imgarr[$i]);

					############ TO GET THE EXTENSION ############

					$ctype ="";

					$#file_exts = -1;

					@file_exts = split(/\./, $imgname);

	
					$ctype = $mimetypes{"$file_exts[1]"};


					############ TO GET THE EXTENSION ############

					$sender->Attach({
                                description => 'ed\'s jpg',
      		              ctype => "$ctype",
                                encoding => 'base64',
                                disposition => "inline; filename=\"$imgname\";\r\nContent-ID: <$imgname>",
                                file => "$htmlattachdir/$cpcode/$imgname"
                        	});

				}
				foreach $files(@files)
				{

					############ TO GET THE EXTENSION ############

					$ctype ="";



					$#file_exts = -1;

					@file_exts = split(/\./, $files);


					$ctype = $mimetypes{"$file_exts[1]"};



					############ TO GET THE EXTENSION ############

					$path = "$pathing/$files";

				 $sender->Attach(
			  	{description => 'Perl module Mail::Sender.pm',
				   ctype => "$ctype",
				   encoding => 'Base64',
				   disposition => "attachment; filename=$files; type=$files",
				   file => "$path"
				  });


			}
			############# UPDATE THE STATUS IN EMAIL QUEUE TABLE ##########################
	

			&Current_IST();

			$present_date = "$ind_year-$ind_mon-$ind_day "."$ind_hour:$ind_min:$ind_sec";


			if($send_admin_mail == 0)
			{
			
				$sent_status=$db->prepare("update Email_Queque set Mail_Sent=1, Mail_Date='$present_date' where Cpcode='$cpcode' && Email_Id='$recepientid[$k]' && Person_Name='$dbname[$k]' && Sentmail_Id='$mail_id'");
				$sent_status->execute;
			}

			############# FINISH UPDATING THE STATUS IN EMAIL QUEUE TABLE #################
                       
		}
	else
	{

		if($send_admin_mail == 1)
		{
			$admin_mailer=0;
			$admin_sent=0;
		}
		$mail_not.=$i;
		$mail_not.='<br>';

	}

	if($k % 10 == 0)
        {
                sleep(5);
        }

        #$sender->Close();
	
	$count++;
	$final_ids.=$to_email[$i];

	$new_content = "";

}

############## CHECK IF STILL MAIL IS TO BE SENT TO ANYONE IN THE LIST ################


$mail_count=$db->prepare("select count(*) from Email_Queque where Mail_Sent=0 && Cpcode='$cpcode' && Sentmail_Id='$mail_id'");
$mail_count->execute;
($actual_count=$mail_count->fetchrow_array);


if(($actual_count > 0)||($admin_mailer == 0))
{


	&Current_IST();

	################# DELETE  THE ATTACHMENTS ############

	unlink "$attach_dir/$cpcode/$files[0]";
	unlink "$attach_dir/$cpcode/$files[1]";
	unlink "$attach_dir/$cpcode/$files[2]";


       ########## Delay the program for say 10 seconds #########

        sleep($sleep_time);

	&Current_IST();


       ######### Call the Program to send mails #############



	 &Redir_Url();

       exit;
      
	 ############ CALL THE SUBROUTINE TO FORMAT THE EMAIL IDS TO WHOM MAIL HAS TO BE SENT ##############
       #&Format_Mails;                                        ######## CALL THE SUBROUTINE
       ############ END OF SUBROUTINE TO FORMAT THE EMAIL IDS TO WHOM MAIL HAS TO BE SENT ##############


       ############ CALL THE SUBROUTINE TO SEND MAILS ##############
       #&Send_Mails;                                        ######## CALL THE SUBROUTINE
       ############ END OF SUBROUTINE TO SEND MAILS ##############
}

############## END OF CHECK IF STILL MAIL IS TO BE SENT TO ANYONE IN THE LIST ####

}

#---------- SUBROUTINE TO FORMAT THE EMAIL IDS WHICH HAVE BEEN LEFT OUT WHILE SENDING THE MAIL --------------#

sub Format_Mails
{
	$#recepientid=-1;
	$#dbname=-1;
	$#dbcompany=-1;

	@recepientid = @left_ids;
	@dbname = @left_names;
	@dbcompany = @left_companies;

	$#left_ids=-1;
	$#left_names=-1;
	$#left_companies=-1;


}

#---------- END OF SUBROUTINE TO FORMAT THE EMAIL IDS WHICH HAVE BEEN LEFT OUT WHILE SENDING THE MAIL --------------#

######### SUBROUTINE TO GET THE LIST OF EMAIL IDS TO WHOM MAIL HAS TO BE SENT ###############

sub Emails_inq
{
	$mail_flag=1;

	#--------- MAIL CONTENTS TO BE SENT ONLY TO THE ADMINISTARTOR ----------------#

	$mailids="<hr><br><table width=\"80%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\" align='center'>
  <tr> 
    <td align='center'><font face=\"Verdana\" size=\"2\"><b><u>Mail has been 

      sent to the following E-Mail Ids.</u></b></font></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table>
<table width=\"80%\" border=\"1\" cellspacing=\"1\" cellpadding=\"3\" bordercolor=\"#DDDDDD\" align='center'>
  <tr valign=\"top\" bgcolor=\"#CCCCCC\"> 
    <td width=\"4%\"><b><font face=\"verdana\" size=\"2\">Sl.No</font></b></td>
    <td width=\"32%\"><b><font face=\"verdana\" size=\"2\">Name</font></b></td>
    <td width=\"32%\"><b><font face=\"verdana\" size=\"2\">Organization</font></b></td>
    <td width=\"32%\"><b><font face=\"verdana\" size=\"2\">E-Mail 
      ID</font></b></td>
  </tr>";
	$serno=1;

#--------- MAIL CONTENTS TO BE SENT TO THE ADMINISTARTOR ----------------#

	$email_ids=$db->prepare("select Email_Id,Person_Name,Cpname, Mail_Sent,Mail_Date from Email_Queque where Mail_Sent='$mail_flag' && Cpcode='$cpcode' && Sentmail_Id='$mail_id'");

	$email_ids->execute;
	while(($email,$person_name,$cpname,$mail_sent,$mail_date)=$email_ids->fetchrow_array)
	{
	
		if($cpname eq "")
		{
			$cpname="-";
		}

		#---------- FORMAT THE MAIL CONTENTS ----------------#
		$mailids.="  <tr valign=\"top\"> 
    <td width=\"4%\"><font face=\"verdana\" size=\"2\">$serno) </font></td>
    <td width=\"32%\"><font face=\"verdana\" size=\"2\">$person_name</font></td>
    <td width=\"32%\"><font face=\"verdana\" size=\"2\">$cpname</font></td>
    <td width=\"32%\"><a href=\"mailto:$email\"><font face=\"verdana\" size=\"2\">$email</font></a></td>
  </tr>";
		#---------- FORMAT THE MAIL CONTENTS ----------------#

		$serno = $serno + 1;

	}

	$mailids.="</table>";

	$admin_mail = $mailids;

}

######### SUBROUTINE TO GET THE LIST OF EMAIL IDS TO WHOM MAIL HAS TO BE SENT ###############



#---------- END OF SUBROUTINE TO DETERMINE THE FILE SIZE ---------#

sub Redir_Url
{

   print"<script>
  self.location = 'http://www.anglerherald.com/cgi-local/herald_continue_mail.pl?cpcode=$cpcode&mail_id=$mail_id';
   </script>";
}

sub TrackUrl
{
	open(FILE,"$sentmaildir/$cpcode/$mail_id/$fname.html") or die "Can't Open File";
	$finalcontent="";
	while (<FILE>)
	{
	
		$content=$_;
		$content1=$_;
		$flag=0;
		#################Replace <!--mailid--> with mailid value

		$content=~s/<!--mailid-->/$mail_id/gi;
		$content1=$content;
	
		#############this used to find product promotion links

		############ i should replace the ang with www when i take this to online
		while($content=~/<a\shref\s*=\s*"*'*\s*(http:\/\/www\.anglerherald\.com\/cgi-local\/Tracking\.pl\?[^\s|^"]+)"*'*\s*(.*)>(.*)/gi)
		{

			if($content=~/<a\shref\s*=\s*"*'*\s*(http:\/\/www\.anglerherald\.com\/cgi-local\/Tracking\.pl\?[^\s|^"]+)"*'*\s*(.*)>(.*)/i)
			{
				$flag=1;	
				$item=$1;
				@main_arr=split(/\?/,$item);
	
				@in_qry_string=split("&",$main_arr[1]);
				$sub_query1="";
				$sub_query2="";

				foreach $qry_item (@in_qry_string)		
				{
			
					@var_value=split(/=/,$qry_item);
					if(@var_value[0] eq "mailid")
					{
						$sub_query1.="Mail_Id=@var_value[1]";
						$sub_query2.="Mail_Id=@var_value[1]";
					}
					if(@var_value[0] eq "itemid")
					{
						$sub_query1.="Item_ID=@var_value[1] , ";
						$sub_query2.="Item_ID=@var_value[1] and ";
					}
					if(@var_value[0] eq "url")
					{
						$sub_query1.="Url='@var_value[1]' , ";
						$sub_query2.="Url='@var_value[1]' and ";
					}
					if(@var_value[0] eq "prodid")
					{
						$sub_query1.="Product_ID='@var_value[1]' , ";
						$sub_query2.="Product_ID='@var_value[1]' and ";
					}
				}
		
				$select_qry=$db->prepare("select * from $cpcode"."_PP_File_Path where $sub_query2");
				$select_qry->execute;
				@details=$select_qry->fetchrow_array();
				if($#details<=0)
				{
					$sub_query=" insert into $cpcode"."_PP_File_Path set ".$sub_query1;	
			
					$url_qry=$db->prepare($sub_query);
					$url_qry->execute;
				}
			}
		}
		############this used to avoid replacement of mailto:
		while($content=~/<a\shref\s*=\s*"*'*\s*(mailto:.*[@].*)"*'*\s*>(.*)/i)
		{
	
			if($content=~/<a\shref\s*=\s*"*'*\s*(mailto:.*[@].*)"*'*\s*>(.*)/gi)
			{

				$content=$2;
				$flag=1;
			}
		}


		if(!$flag)
		{
			#######this will help to find a href link and store it in database $1 will give the linkname
			while($content=~/<a\shref\s*=\s*"*'*\s*([^>]+)"*'*\s*>(.*)/i)
			{
			
				##################################[^\s"]+
				if($content=~/<a\shref\s*=\s*"*'*\s*([^>]+)"*'*\s*>(.*)/i)
				{
					$content=$2;
					$flag=1;
					$temp=$1;
					@tem=split(" ",$temp);
					@it=split("\"",$tem[0]);
					#27-02-04		$red=$1;
					$red=$tem[0];
					
					$red=~s/http:\/\///g;
					$red=~s/\"//g;
		
		
					$content1=~s/<a\shref\s*=\s*"*'*\s*($it[0]+)"*'*\s*(.*)>/\<a href=http:\/\/$url\/cgi-local\/Tracking.pl?url=http:\/\/$red\&cpcode=$cpcode\&mailid=$mail_id\&userid=<!--userid-->\&emailid=<!--recemailid--> $2\>/i;
				}
			}

		#####  this will replace all ahref to Tracking.pl
		#$content1=~s/<a\shref\s*=\s*"*\s*([^>|^\s|^"]+)"*\s*(.*)>/\<a href=\"http:\/\/$url\/cgi-local\/Tracking.pl?url=http:\/\/$1\&cpcode=$cpcode\&mailid=$mail_id\&userid=<!--userid-->\" $2\>/gi;
		}
	if (!$flag)
	{
		$content=$content1;
		###########this used to find and replace the maps
		while($content=~/\shref\s*=\s*"*'*\s*([^>]+)"*'*\s*>(.*)/i)
		{
			if($content=~/\shref\s*=\s*"*'*\s*([^>]+)"*'*\s*>(.*)/i)
			{
				$content=$2;
				$flag=1;
				$temp=$1;
				@tem=split(" ",$temp);
				@it=split("\"",$tem[0]);
				#27-02-04			$red=$1;
				$red=$tem[0];
		
				$red=~s/http:\/\///g;
				$red=~s/\"//g;

				$content1=~s/\shref\s*=\s*"*'*\s*($it[0]+)"*'*\s*(.*)>/\<a href=http:\/\/$url\/cgi-local\/Tracking.pl?url=http:\/\/$red\&cpcode=$cpcode\&mailid=$mail_id\&userid=<!--userid-->\&emailid=<!--recemailid--> $2\>/i;
			}

		}

	}





	###########################to find and replace the http
	if(!$flag)
	{
		$content=$content1;
		while($content=~/http:\/\/([^\s]+)\s/i)
		{
			if($content=~/http:\/\/([^\s]+)\s(.*)/i)
			{
				$content=$2;
				$flag=1;
				$temp=$1;
				@tem=split(" ",$temp);
				@it=split("\"",$tem[0]);
				$content1=~s/http:\/\/($it[0]+)\s/\<a href=\"http:\/\/$url\/cgi-local\/Tracking.pl?url=http:\/\/$1\&cpcode=$cpcode\&mailid=$mail_id\&userid=<!--userid-->\&emailid=<!--recemailid-->\"\>http:\/\/$1\<\/a\>/i;

			}
		}
		#$content1=~s/http:\/\/([^\s|^"]+)\s/\<a href=\"http:\/\/$url\/cgi-local\/Tracking.pl?url=http:\/\/$1\&cpcode=$cpcode\&mailid=$mail_id\&userid=<!--userid-->\"\>http:\/\/$1\<\/a\>/gi;
	}


	if(!$flag)
	{
		$content=$content1;
		###########this is used find the www...... and store it in db by using $1
		while($content=~/www\.([^\s]+)\s/i)
		{
			if($content=~/www\.([^\s]+)\s(.*)/i)
			{
				$content=$2;
				$temp=$1;
				@tem=split(" ",$temp);
				@it=split("\"",$tem[0]);
				$content1=~s/www\.($it[0]+)\s/<a href=\"http:\/\/$url\/cgi-local\/Tracking.pl?url=http:\/\/www\.$1\&cpcode=$cpcode\&mailid=$mail_id\&userid=<!--userid-->\&emailid=<!--recemailid-->\"\>www\.$1<\/a>/i;
			}

		}
		#	$content1=~s/www\.([^\s|^"]+)\s/<a href=\"http:\/\/$url\/cgi-local\/Tracking.pl?url=http:\/\/www\.$1\&cpcode=$cpcode\&mailid=$mail_id\&userid=<!--userid-->\"\>www\.$1<\/a>/ig;
	}	

$finalcontent.=$content1;
}

$finalcontent=~s/<!--cpcode-->/$cpcode/gi;
$finalcontent=~s/<!--action-->/http:\/\/www\.anglerherald\.com\/cgi-local\/Subscription\.pl/gi;


}


exit;

################
print <<__HTMLCONT__;

<script>
//self.location = "../scripts/compose.php?op=h";
self.location = "$scriptsdir/compose.php?op=h";

</script>

__HTMLCONT__


=begin


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

print"<html>
<head>
<title>ANGLER Herald</title>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>

<script language='javascript' src='$jsdir/jsfns.js'></script>

<script language='javascript'>

function valid()
	{
	self.location='$scriptsdir/html_fileupload.php';
	return false;
	}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf(\"#\")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf(\"?\"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}

}

</script>

</head>

<body bgcolor='#FFFFFF' text='#000000' onLoad=\"MM_preloadImages('$imagesdir/top_r2_c2_f2.gif','$imagesdir/top_r2_c3_f2.gif','$imagesdir/top_r2_c4_f2.gif','$imagesdir/top_r2_c5_f2.gif','$imagesdir/top_r2_c1_f2.gif','$imagesdir/groups_mo.gif','$imagesdir/festivals_mo.gif','$imagesdir/drafts_mo.gif','$imagesdir/sent_mo.gif','$imagesdir/signature_mo.gif','$imagesdir/address_mo.gif','$imagesdir/import_mo.gif','$imagesdir/export_mo.gif','$imagesdir/unsubscribe_mo.gif','$imagesdir/compose_mo.gif','$imagesdir/drafted_mo.gif','$imagesdir/htmlmail_mo.gif','$imagesdir/send_mo.gif','$imagesdir/birthdays_mo.gif','$imagesdir/anniversaries_mo.gif','$imagesdir/festivals2_mo.gif','$imagesdir/menu_mo.gif')\" leftmargin='0' topmargin='0' marginwidth='0' marginheight='0' link='#000000' vlink='#000000' alink='#000000' onResize='javascript:location.reload()'>

<script language='javascript' src='$jsdir/mail_menu.js'></script>


<form name='form1'>

<br><br>

<table width='100%' border='0' cellspacing='0' cellpadding='0' align='center'>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>

<table width='100%' border='0' cellspacing='0' cellpadding='0' align='center'>
  <tr align='center'> 
    <td height='30'><b><font face='Verdana, Arial, Helvetica, sans-serif' size='3'>Mail Sent</font></b></td>
  </tr>
</table>
<br>

<table width='50%' border='1' cellspacing='0' cellpadding='0' align='center' bordercolor='#FFCC99'>
  <tr>
    <td>
      <table width='100%' border='1' cellspacing='1' cellpadding='2' align='center' bordercolor='#FFCC99' >
        <tr bgcolor='#FFF4EA' align='center'> 
          <td height='19' bgcolor='#FFF4EA'><b><font face='Verdana, Arial, Helvetica, sans-serif' size='2'><b>Mail has been sent</b></font></td>
        </tr>
      </table>
    </td>
  </tr>
</table>
<br>";


print "$invalid_msg
<br>
<table align='center' cellpadding='3' cellspacing='3'>

    <tr align='center'> 
      <td height='30'> <a href='#' onFocus='this.blur()' onClick='return valid()' onMouseOut='MM_swapImgRestore()' onMouseOver=\"MM_swapImage('Menu','','$imagesdir/menu_mo.gif',1)\"><img src='$imagesdir/menu.gif' width='91' height='28' border='0' alt='Menu' name='Menu'></a></td>
    </tr>

</table>

</form>
<table border='0' align='center' cellpadding='0' cellspacing='0'  width='100%'>
  <tr> 
    <td   align='center' valign='top'> <font face='Arial, Helvetica, sans-serif' size='1' color='#000000'>Web 
        Solution Architecture Powered by <a href='http://www.angleritech.com' target='_blank'><font color='#000000'>ANGLER 
        Technologies</font></a></font>
    </td>
  </tr>
</table>
</body>
</html>";
1;

