#!/usr/bin/perl -w

use CGI qw/:standard -no_xhtml/;
use CGI::Carp qw ( fatalsToBrowser );
use DBI;
use MIME::Lite;
use Switch; 
use Text::Template;

# initier db
my $dsn = "DBI:mysql:database=dailydenada;host=localhost;port=3306";
my $dbh = DBI->connect($dsn, "daily", "strips");
my $drh = DBI->install_driver("mysql");
my $sth = "";

my $cgi = new CGI;

# der er angivet en nøgle og action, så kan det være der skal godkendes, eller unsubscribes
if ($cgi->param('key') && $cgi->param('action')) {
	switch ($cgi->param('action')) { 
		case "confirm"	{
			# verify if the key is still valid (is there an entry in the DB at all too, that would be nice to know)
			if ( checkID($cgi->param('key'))) { 
				print $cgi->header; 
				templater("subscribe","validation-key is no longer valid. Please sign up again from the <a href=\"http://daily.denada.dk/subscribe/\">website</a>");
			} else {
				print $cgi->header;

				templater("subscribe", "you have succesfully confirmed your emailaddress and will receive the strip the next time one becomes available (this usually happens at 5am CET");
				# update DB with confirmed = yes and update timestamps and clear the approval-key and make a new one (for removal)
				my $newkey = generateID(2,2);
				$sth = $dbh->prepare("update dailymail set laststatus = ?, statustime = now(), approved = 'yes', approvalkey = ? where approvalkey = ?");
				$sth->execute('email confirmed',$newkey,$cgi->param('key'));
				if ($dbh->errstr) { print $dbh->errstr; }
				$sth->finish;
			}
		}
		case "remove"	{
			# FIXME 
			# remove the user - delete regardless and report success even if the user wasn't on the list (or not... hmm)
			if (checkID($cgi->param('key'))) { 
				print $cgi->header; 
				print start_html(-title=>'The Daily Denada daily mail - unsubscribe',-style=>{-src=>'/style.css'});
				my $template = Text::Template->new(SOURCE => 'template.tpl') or die "the programmer sucks!: $Text::Template::ERROR";
				my $res = $template->fill_in(HASH=> { title =>'unsubscribe', message => 'invalid key, or you have already been removed from the list'});
				if (defined($res)) { print $res; } else { die("template-failure: $Text::Template::ERROR"); }
				print end_html;
			} else {
				# FIXME - hvem har unsubb'ed? gem email-addressen + tidspunktet for unsub
			        # $sth = $dbh->prepare("select * from dailymail where approvalkey = '".$i."' or rid ='".$i."'");
			        # $sth->execute;
				# drop de fundne oplysninger i en logfil - eller mail dem til mig..
				$sth = $dbh->prepare("delete from dailymail where approvalkey = ?");
				$sth->execute($cgi->param('key'));
				print $cgi->header; 
				print start_html(-title=>'The Daily Denada daily mail - unsubscribe',-style=>{-src=>'/style.css'});
				my $template = Text::Template->new(SOURCE => 'template.tpl') or die "the programmer sucks!: $Text::Template::ERROR";
				my $res = $template->fill_in(HASH=> { title => 'unsubscribe', message => 'You have been removed from the mailinglist. If you want to receive The Daily Denada by email again, you can always sign up again <a href="http://daily.denada.dk/subscribe">here</a>. Thank you and goodbye'});
				if (defined($res)) { print $res; } else { die("template-failure: $Text::Template::ERROR"); }
				print end_html;

			}
		}

		else	{ 
			print $cgi->header; 
			print "I am not sure what your intentions are..."; 
		}
	}
} elsif ($cgi->param('email')) {
	print $cgi->header;

	# kontroller at denne addresse ikke allerede er modtager:
	# FIXME - sanitize emailaddress first
	if(!is_valid_email($cgi->param('email'))) {
		templater("subscribe", "You have provided what seems to be an illegal email addresse. Please go back to the <a href=\"/subscribe\">subscription-page</a> and try again");
	} elsif (!checkID($cgi->param('email'))) { 
		my $msg = "The supplied address is already signed up"; 
		print start_html(-title=>'The Daily Denada daily mail - subscribe',-style=>{-src=>'/style.css'});
		my $template = Text::Template->new(SOURCE => 'template.tpl') or die "the programmer sucks!: $Text::Template::ERROR";
		my $res = $template->fill_in(HASH=> { title => 'subscribe', message => $msg});
		if (defined($res)) { print $res; } else { die("template-failure: $Text::Template::ERROR"); }
		print end_html;
	} else {
		# så skal der genereres approvalkey, indsættes i DB og mail skal sendes..
		my $msg = "Thank you! A validation email has been sent to the address you have supplied. It should arrive shortly.<br><br>Please check your trash/junk/unwanted mail folders for an email from <i>Daily Denada</i> as certain mailproviders classify this email as junk."; 
		templater('subscribe', $msg);
		my $akey = generateID(2,2) or die "fejl";

		# send mail

		$msg = MIME::Lite->new(
       	        	From    =>'Daily Denada <daily@denada.dk>',
       	        	To      =>$cgi->param('email'),
       	        	Subject =>'Confirm your emailaddress',
       	        	Type    =>'multipart/alternative',
           	);
	
		my $plain = $msg->attach(
			Type	=>'text/plain',
			Data	=>'click the following link to confirm your emailaddress: http://daily.denada.dk/subscribe/?key='.$akey."&action=confirm\n\nIf you did not request this email you can just ignore this message.",
		);
		

my $message = 'Click the following link to confirm your emaildress:<br>
<a href="http://daily.denada.dk/subscribe/?key='.$akey.'&action=confirm">http://daily.denada.dk/subscribe/?key='.$akey.'&action=confirm</a>
<br><br>If you are not the person asking to be subscribed to The Daily Denada mail, please ignore this message.
<br><br>You must respond to this message within 14 days or your request will be deleted.';


my $html = '<html>
<body style="background-color: #c0c0c0; text: black">
<center>
<div style="width 99%; background-color: #c0c0c0; padding-bottom: 10px; padding-top: 10px;">
	<div style="width: 600px; text-align: left; padding: 0px;">

		<div style="padding: 2px; margin-bottom: 4px; background-color: #dddddd; border: black solid 1px; color: black; font-weight: bold">Welcome to The Daily Denada</div>
		<div style="border: none; margin-bottom: 4px; float: left;"><img src="cid:myimage.gif" style="margin: 0px; border: none"></div>
		<div style="float:right; width: 470px; height: 164px; padding: 2px; padding-right: 2px; margin-bottom: 4px; background-color: #dddddd; border: black solid 1px; font-size: 9pt; color: black">'.$message.'</div>
		<div style="clear:both"></div>
		<div style="padding: 2px; margin-bottom: 4px; background-color: #dddddd; border: black solid 1px; color: black; font-weight: bold">&nbsp;<div>

	</div>
</div>

</center>

</body>
</html>';




        	my $fancy = $msg->attach(Type => 'multipart/related');


		$fancy = $msg->attach(
			Type	=>'text/html',
#			Data	=>'Click the following link to confirm your emaildress: <a href="http://daily.denada.dk/subscribe/?key='.$akey.'&action=confirm">http://daily.denada.dk/subscribe/?key='.$akey.'&action=confirm</a><br><br>If you are not the person asking to be subscribed to The Daily Denada mail, please ignore this message.<br><br>You must respond to this message within 14 days or your request will be deleted.',
			Data	=>$html,
		);

		$fancy->attach(
               	Type   => 'image/gif',
               Id   => 'myimage.gif',
               Path => '/var/www/virtual/daily.denada.dk/web/siteimages/face4welcomeemail.gif',
           );





		$msg->send;



		# indsæt i DB ..
		my $sth = $dbh->prepare("insert into dailymail (rid, added, laststatus, approved, approvalkey) values(?,now(),'conf email sent',?,?)");
		$sth->execute($cgi->param('email'), 'no', $akey);
		if ($sth->errstr) { print $sth->errstr; }
		$sth->finish;
	}


} else {
	print $cgi->header;
	my $t = "<div style=\"margin-top: 5px\">\n";
	$t = $t."<div style=\"text-align: justify\">\n";
	$t = $t."<div style=\"float:right; margin-left: 5px;\"><div><img src=\"/imgs/notthatkindofstrip.jpg\" alt=\"'Not that kind of strip'\" title=\"'Not that kind of strip'.\"></div><div><small>'Not <i>that</i> kind of strip'</small></div></div>\n";
	$t = $t."If you'd like to receive the Daily Denada by email every day, please enter your emailaddress in the field below. The strip will be sent to you every morning at 5am CET if there is a new strip available. Your email address will not be used for spam, sold to romanians or anyone else for that matter.</div>\n";
	$t = $t."<div>You will not receive any ads with the strip when you receive it by mail and you can unsubscribe any time you want (after receiving the first email)</div>\n";
	$t = $t."<div>After entering your address and hitting 'send' you will receive an email with a link you need to click, in order to verify that you are the person subscribing to the list.</div>\n";
	$t = $t."<div>&nbsp;</div>\n";
	$t = $t.start_form(-class=>'emailform',-id=>'emailform');
	$t = $t." <div style=\"float: left; width: 120px;\">Email Address: </div><div style=\"float:left\">".textfield({-class=>'email',-name=>'email'})." ".submit('subscribe')." </div>\n";
	$t = $t." <div style=\"clear:both\"></div>\n";
#	$t = $t." <div style=\"float: left; width: 120px;\">Verify: </div><div style=\"float: left\">".textfield({-class=>'email',-name=>'emailver',-onchange=>'checkadd(this)'})."</div>\n";
	$t = $t." <div style=\"clear:both\"></div>\n";
	$t = $t.end_form;
	$t = $t."</div>\n";
	$t = $t."<div>You can also subscribe to strip and the comments with your favourite rss-reader by using the links below:</div>\n";
	$t = $t."<div><a href=\"/rss\">The Daily Denada</a> - the strip<br><a href=\"/commentsrss\">Comments</a> - the comments</div>\n";

	templater("Subscribe to the 'The Daily Denada Strip Mail'",$t);
}



###############################################################################
sub generateID {
        my ($np,$npp) = @_;
        my $lid = "";
        my $aplha = "a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z";
        my @aplha = split(" ", $aplha);
        my ($r,$j,$i) = 0;
        for ($j = 0; $j < $np; $j++) {
                $r = int(rand(2));
                for ($i = 0; $i < $npp; $i++)
                {
                        if ($r == 1)
                        {
#                                // Generate random numbers
                                $lid .= int(rand(10));
                        }
                        else
                        {
 #                               // Generate random letters
                                $a = int(rand(52));
                                $lid .= $aplha[$a];
                        }
                }
        }
        # så skal vi tjekke om det her ID er brugt tidligere...
        #print "checker $lid\n";
        if (checkID($lid)) {
                #print "returnerer: $lid\n";
                return $lid;
        } else { $lid = generateID($np,$npp); }
}

sub checkID {
        my($i) = @_;
        $sth = $dbh->prepare("select * from dailymail where approvalkey = '".$i."' or rid ='".$i."'");
        $sth->execute;
        my $numrows = $sth->rows;
        $sth->finish;
        if ($numrows eq 0) {
                 return 1;
        } else { return 0; }
}


sub templater {
	my ($title, $message) = @_;
        print start_html(
		-title=>'The Daily Denada daily mail - '.$title,
		-style=>{-src=>'/style.css'},
		-head=>[
			Link({-rel=>'alternate',-title=>'The Daily Denada',-type=>'application/rss+xml',-href=>'http://daily.denada.dk/rss'}),
			Link({-rel=>'alternate',-title=>'Comments for The Daily Denada',-type=>'application/rss+xml',-href=>'http://daily.denada.dk'})   ]);
        my $template = Text::Template->new(SOURCE => 'template.tpl') or die "the programmer sucks!: $Text::Template::ERROR";
        my $res = $template->fill_in(HASH=> { title => $title, message => $message});
        if (defined($res)) { print $res; } else { print "template-failure: $Text::Template::ERROR"; }
        print end_html;
}

sub is_valid_email ($) {
        my ($addr) = @_;
        my $atext = qr/[A-Za-z0-9\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\+\~]/;
        my $dot_atom_text = qr/$atext+(\.$atext+)*/;

        my $no_ws_ctl_char = qr/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/;
        my $qtext_char = qr/([\x21\x23-\x5b\x5d-\x7e]|$no_ws_ctl_char)/;
        my $text = qr/[\x01-\x09\x0b\x0c\x0e-\x7f]/;
        my $qtext = qr/($qtext_char|\\$text)*/;
        my $quoted_string = qr/"$qtext"/;

        my $quotedpair = qr/\\$text/;
        my $dtext = qr/[\x21-\x5a\x5e-\x7e\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/;
        my $dcontent = qr/($dtext|$quotedpair)/;
        my $domain_literal = qr/\[(${dcontent})*\]/;

        if ( $addr =~ /^($dot_atom_text|$quoted_string)\@($dot_atom_text|$domain_literal)$/ ) {
                return 1;
        } else {
                return 0;
        }
    }

