#!/usr/bin/perl
###################################################################################
#                                                                                 #
#                   PerlDesk - Customer Help Desk Software                        #
#                                                                                 #
###################################################################################
#                                                                                 #
#     Author: John Bennett	                                                      #
#      Email: j.bennett@perldesk.com                                              #
#        Web: http://www.perldesk.com                                             #
#   Filename: email.pl                                                            #
#    Details: The main email gateway file                                         #
#    Release: 1.5                                                                 #
#                                                                                 #
###################################################################################
# Please direct bug reports,suggestions or feedback to the perldesk forums.       #
# www.perldesk.com/board                                                          #
#                                                                                 #
# PerlDesk is free for both commercial and non-commercial use providing that the  #
# copyright headers remain intact and the links remain on the html pages.         #
# Re-distribution of this script without prior consent is strictly prohibited.    # 
#                                                                                 #
###################################################################################
# Please see the README/INSTALL files if you have any problems with this software #                                                            
###################################################################################

require "/home/perldesk/www/1.5/include/conf.pl"; 
require "/home/perldesk/www/1.5/include/lang/en.inc";


use CGI qw(:standard);
use DBI();

use MIME::Parser;
use Mail::Address;
use MIME::Entity;
use MIME::Body;
use Data::Dumper;

$parser = new MIME::Parser;

   $parser->ignore_errors(1);
   $parser->output_to_core(1);

  my $MIME_entity = $parser->parse(\*STDIN);
  my $error = ($@ || $parser->last_error);

  $header  = $MIME_entity->head;
  $subject = $header->get('Subject'); 
  $cto     = $header->get('To'); 

  $from = $header->get('From'); 

  @to_addresses   = Mail::Address->parse($cto);
  @from_addresses = Mail::Address->parse($from);

  my $address;


   if (@to_addresses) {
          $to = $to_addresses[0]->address();
    } else {
		exit;
	}

  if (@from_addresses) {
     $address = $from_addresses[0]->address();
    } else {
		exit;
	}

if ($MIME_entity->parts > 0) 
{
  for (my $i=0;$i<$MIME_entity->parts;$i++) 
  {
    my $subEntity = $MIME_entity->parts($i);
    my $ignore_plain = 0;
    my $ignore_html = 0;


    $ishtml = "1" if $subEntity->mime_type eq 'text/html';
    $ishtml = "0" if $subEntity->mime_type eq 'text/plain';

    if (($subEntity->mime_type eq 'text/html') &&
        ($ignore_html == 0))  
    {
       if (my $io = $subEntity->open("r"))
       {
           while (defined($_=$io->getline))
              { $_ =~ s/"/\"/g;
				$body .= $_;
			  }
           $io->close;
           $ignore_plain=1;
        }
    }
    if (($subEntity->mime_type eq 'text/plain') &&
         ($ignore_plain=0))  {
       if (my $io = $subEntity->open("r")) {
           while (defined($_=$io->getline))
              { $_ =~ s/"/\"/g;
				$body .= $_;
			  }
           $io->close;
           $ignore_html=1;
        }
     }
  }
}
else 
{
   $body = join "",  @{$MIME_entity->body};
}

   $to = $1 if $to =~ /<(\S+)>/;

    if ($from =~ /<(\S+)>/) { $newfrom = $1 } 
     else { $newfrom = $from } 

   $body =~ s/"/\"/g;

	if ((!$subject) || 
			($subject eq ""))
	 {
			open(MAIL, "|/usr/sbin/sendmail -t") || print "Unable to send mail: $!";
					print MAIL "To: $newfrom\n";
					print MAIL "From: $ticketad\n";
					print MAIL "Subject: Help Desk Response\n\n";
					print MAIL "Please resend your request with a subject line intact, if you ";
					print MAIL "are replying to a staff response, please keep the subject line intact for tracking purposes, if this is a new request, please give it a suitable subject line.";
					print MAIL "\n\n";
					print MAIL "Thank You.";
			close(MAIL);
           exit;
}



$dbh = DBI->connect("DBI:mysql:$dbname:$dbhost","$dbuser","$dbpass");

  my $statement = 'SELECT * FROM settings'; 
  my $sth       = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
     $sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
  while(my $ref = $sth->fetchrow_hashref()) 
       {
                  my $setting       = $ref->{'setting'};
                  $global{$setting} = $ref->{'value'};
       } 
  $sth->finish;

  $epre = $global{'epre'};



if ($subject =~ /\{$epre-/gi) {

    $callid = $1 if $subject =~ /\{(\S+)\}/;
	$callno = $callid;
	$callno =~ s/$epre-//g;

	$statement = 'SELECT * FROM `calls` WHERE id = ?'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 			$sth->execute($callno) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
		{
			$user      = $ref->{'username'};
			$callemail = $ref->{'email'};
			$status    = $ref->{'status'};
			$category  = $ref->{'category'};
			$subj      = $ref->{'subject'};
		}

	if ($status eq "CLOSED") 
       {
            $dbh->do(qq|UPDATE `calls` SET status = "OPEN" WHERE id = "$callno"|);
       }


	if ($callemail != $newfrom) {
			open(MAIL, "|/$global{'sendmail'} -t") || print "Impossibile inviare l\'email: $!";
					print MAIL "A: $newfrom\n";
					print MAIL "Da: $ticketad\n";
					print MAIL "Oggetto: \{$callid\} Nuova Richiesta Help Desk\n\n";
					print MAIL "Spiacente, ma sembra che tu stia rispondendo ad una richiesta non tua. ";
 					print MAIL "Se credi che sia un errore controlla che l\'email dalla quale stai spedendo il messaggio";
					print MAIL "sia l'\email utilizzata per inserire la richiesta.\n\n";
					print MAIL "Grazie.";
			close(MAIL);
	exit;
	}

      $sth = $dbh->prepare( "INSERT INTO notes VALUES ( ?, ?, ?, ?, ?, ?, ?, ? )" ) or die "couldnt prepare statement";
      $sth->execute( "NULL", "0", "1", "NULL", $callno, $user, $hdtime, $body ) or die "Couldnt execute statement";

  $statement = 'UPDATE `calls` SET aw = "1" WHERE id = ?';
        $sth = $dbh->prepare($statement)or die print "Couldn't prepare statement: $DBI::errstr; stopped";
        $sth->execute($callno);


  $statement = qq|SELECT * FROM staff WHERE access LIKE "%$category::%" OR access LIKE "%GLOB::%" OR access="admin"|;
        $sth = $dbh->prepare($statement)or die print "Couldn't prepare statement: $DBI::errstr; stopped";
        $sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
  while(my $ref = $sth->fetchrow_hashref()) {
  		if ($ref->{'notify'} eq "1") {
			open(MAIL, "|$global{'sendmail'} -t") || print "Imposssibile inviare l\'email: $!";
				print MAIL "A: $ref->{'email'}\n";
				print MAIL "Da: $adminemail\n";
				print MAIL "Oggetto: Nuova Risposta Help Desk (USER)\n\n";
				print MAIL "C\'è una nuova riposta inviata dall\'utente alla richiesta $callid. \n";
				print MAIL "\nDettagli Richiesta\n";
				print MAIL "---------------------------------------\n";
				print MAIL "\tRisposta inviata da......: $newfrom\n";
				print MAIL "\tCategoria.........: $category\n";
				print MAIL "\tOggetto..........: $subj\n";
				print MAIL "---------------------------------------\n";
				print MAIL "\n\nGrazie.";
			close(MAIL); 
		}
	}
	$sth->finish;
exit;
}

else {

	$statement = qq|SELECT * FROM em_forwarders WHERE address = "$to"|; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 			$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
		  {
			$category = $ref->{'category'};
		  }
	$sth->finish;



########################################################
# DOES THE EMAIL HAVE TO COME FROM A REGISTERED USER ??
#

	$statement = 'SELECT * FROM settings WHERE setting = "ereqreg"'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 			$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
		{
				$requirereg = "$ref->{'value'}";
		}
	$sth->finish;

	if ($requirereg eq "1") {


########################################################
# I REQUIRE REGISTRATION
#

        $current_time = time();
    	$statement = 'SELECT value FROM settings WHERE setting = "floodwait"'; 
		$sth       = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 			$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
		{
				$global{'floodwait'} = $ref->{'value'};
		}
    	$sth->finish;


    	$statement = 'SELECT * FROM users WHERE email = ?'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 			$sth->execute($newfrom) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
		{
				$username = $ref->{'username'};
				$name     = $ref->{'name'}; 
				$email    = $ref->{'email'};
				$url      = $ref->{'url'};

             my $newtime = $ref->{'lcall'};
                $newtime = $newtime + $global{'floodwait'};
      
                exit if $newtime > $current_time;
 		}
     	$sth->finish;
	
		if (!$email) 
         {
			open(MAIL, "|$global{'sendmail'} -t") || print "Unable to send mail: $!";
					print MAIL "A: $newfrom\n";
					print MAIL "Da: $ticketad\n";
					print MAIL "Oggetto: Nuova Richiesta Help Desk\n\n";
					print MAIL "Spiacente, ma non possiedi un account sull\'help desk Neikos. \n";
					print MAIL "Per inviare la tua richiesta di supporto è necessario registrarsi. Per Registrarti vai al seguente URL:\n\n";
					print MAIL "$global{'baseurl'}/$mainfile\n\n";
					print MAIL "Grazie.";
			close(MAIL);
	  	    exit;
		}

    $subject =~ s/\n//g;
    $body    =~ s/\r//g;
    $body    =~ s/\n/<br>/g if $ishtml == "0";
    $body    =~ s/\n//g     if $ishtml == "1";

	$mbody    = $dbh->quote($body);
	$msubject = $dbh->quote($subject);

	$current_time = time();

   my $dsth       = $dbh->prepare( "INSERT INTO `calls` VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" );
      $dsth->execute( "NULL", "OPEN", $username, "$newfrom", "3", $category, $subject, $body, $hdtime, "Unowned", "NULL", "em", $current_time, $current_time, "1", "0" );

      $trackno    = $dbh->{'mysql_insertid'}; 
 
   my $statement  = 'SELECT * FROM ticket_fields WHERE name = "email" LIMIT 1'; 
    my $sth       = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
       $sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
    while(my $ref = $sth->fetchrow_hashref()) 
      {	
         my $sth = $dbh->prepare( "INSERT INTO call_fields VALUES ( ?, ?, ?, ? )" ) or die $DBI->errstr;
            $sth->execute( "NULL", $trackno, $ref->{'id'}, "$newfrom" ) or die $DBI->errstr;              
      }
  
	notify_tech();

	open(MAIL, "|/usr/sbin/sendmail -t") || print "Unable to send mail: $!";
			print MAIL "To: $newfrom\n";
			print MAIL "From: $ticketad\n";
			print MAIL "Subject: \{$epre-$trackno\} Help Desk Submission\n\n";
			open (MAILNEWTPL,"$global{'data'}/include/tpl/newticket.txt");
				while (<MAILNEWTPL>) {
                 lang_parse();
				  if ($_ =~ /\{*\}/i) { 
					s/\{name\}/$name/g;
					s/\{baseurl\}/$global{'baseurl'}/g;
					s/\{subject\}/$subject/g;
					s/\{description\}/$body/g;
                    s/\{mainfile\}/pdesk\.cgi/g;
					s/\{date\}/$hdtime/g;					
				  }			
			print MAIL "$_";
			}
	close(MAIL);
	}
 
	elsif ($requirereg eq "0") {

########################################################
# DON'T REQUIRE REGISTRATION - STORE CALL IN DATABASE 

	$statement = 'SELECT * FROM users WHERE email = ?'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 			$sth->execute($newfrom) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
		{
				$username = $ref->{'username'};
				$name     = $ref->{'name'}; 
				$url      = $ref->{'url'};
		}
    	$sth->finish;


    if (!$username) {
    # This user is unregistered, should we auto-create an account for him?

	$statement = 'SELECT value FROM settings WHERE setting = "autoacc"'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 			$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
		{
				$create_account = $ref->{'value'};
		}
    	$sth->finish;
   
        if ($create_account == "1") {

        $newusername = $newfrom;

    # CREATE THIS USERS ACCOUNT          
 
	my @chars=(a..z,A..Z,0..9);
	$pass= $chars[rand(@chars)] . $chars[rand(@chars)] . $chars[rand(@chars)] . $chars[rand(@chars)] . $chars[rand(@chars)] . $chars[rand(@chars)];
	
	my $salt= $chars[rand(@chars)] . $chars[rand(@chars)];

	$password = crypt($pass, $salt);	
	my $rv = $dbh->do(qq{INSERT INTO users values (
			"$newusername", "$password", "Not Set", "$newfrom", "Not Set", "Not Set", "$salt")}
		);

    $registered = 1;
  
      $username = $newusername;
      $name     = "User";
      $url      = "Not Set";

   } else {

	if (!$username) { $username = "Unregistered"; 	}
	if (!$name) 	{ $name     = "Unregistered";	}
	if (!$url)		{ $url      = "Unregistered";	}

   }


    }


    $subject =~ s/\n//g;
    $body    =~ s/\r//g;
    $body    =~ s/\n/<br>/g if $ishtml == "0";
    $body    =~ s/\n//g     if $ishtml == "1";

	$mbody    = $dbh->quote($body);
	$msubject = $dbh->quote($subject);


	$current_time = time();

   my $dsth = $dbh->prepare( "INSERT INTO `calls` VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" );
      $dsth->execute( "NULL", "OPEN", $username, "$newfrom", "3", $category, $subject, $body, $hdtime, "Unowned", "NULL", "em", $current_time, $current_time, "1", "0" );

   $trackno = $dbh->{'mysql_insertid'}; 
 
    my $statement = 'SELECT * FROM ticket_fields WHERE name = "email" LIMIT 1'; 
    my $sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
       $sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
    while(my $ref = $sth->fetchrow_hashref()) 
      {	
         my $sth = $dbh->prepare( "INSERT INTO call_fields VALUES ( ?, ?, ?, ? )" ) or die $DBI->errstr;
            $sth->execute( "NULL", $trackno, $ref->{'id'}, "$newfrom" ) or die $DBI->errstr;              

      }


	notify_tech();

   if ($registered) {  

	open(MAIL, "|$global{'sendmail'} -t") || print "Unable to send mail: $!";
			print MAIL "To: $newfrom\n";
			print MAIL "From: $ticketad\n";
			print MAIL "Subject: \{$epre-$trackno\} Help Desk Submission\n\n";
			open (MAILNEWTPL,"$global{'data'}/include/tpl/newticket_registered.txt");
				while (<MAILNEWTPL>) {
                  lang_parse();
				  if ($_ =~ /\{*\}/i) { 
		      			s/\{name\}/$name/g;
				    	s/\{subject\}/$subject/g;
				    	s/\{baseurl\}/$global{'baseurl'}/g;
				    	s/\{description\}/$mbody/g;
				    	s/\{username\}/$username/g;
				    	s/\{password\}/$pass/g;
				    	s/\{date\}/$hdtime/g;
                        s/\{mainfile\}/pdesk\.cgi/g;				
				  }			
			print MAIL "$_";
			}
	close(MAIL);

   } else {

	open(MAIL, "|$global{'sendmail'} -t") || print "Unable to send mail: $!";
			print MAIL "To: $newfrom\n";
			print MAIL "From: $ticketad\n";
			print MAIL "Subject: \{$epre-$trackno\} Help Desk Submission\n\n";
			open (MAILNEWTPL,"$global{'data'}/include/tpl/newticket.txt");
				while (<MAILNEWTPL>) {
                  lang_parse();
				  if ($_ =~ /\{*\}/i) { 
		      			s/\{name\}/$name/g;
				    	s/\{subject\}/$subject/g;
				    	s/\{baseurl\}/$global{'baseurl'}/g;
				    	s/\{description\}/$mbody/g;
				    	s/\{date\}/$hdtime/g;				
                        s/\{mainfile\}/pdesk\.cgi/g;
				  }			
			print MAIL "$_";
			}
	close(MAIL);

   }






	}

 }

  $parser->filer->purge();

 sub notify_tech {
   $statement = 'SELECT * FROM staff WHERE access LIKE "%' . "$category" . '::%" OR access LIKE "%GLOB::%" OR access="admin"';
        $sth = $dbh->prepare($statement)or die print "Couldn't prepare statement: $DBI::errstr; stopped";
        $sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
   while(my $ref = $sth->fetchrow_hashref()) {
		if ($ref->{'notify'} eq "1") {
			open(MAIL, "|$global{'sendmail'} -t") || print "Impossibile inviare l\'email: $!";
				print MAIL "A: $ref->{'email'}\n";
				print MAIL "Da: $global{'adminemail'}\n";
				print MAIL "Oggetto: Nuova Richiesta Help Desk \n";
				print MAIL "C\'è una nuova richiesta sull\'Help Desk Neikos \n";
				print MAIL "\nDettagli Richiesta\n";
				print MAIL "-----------------------------------------\n";
				print MAIL "\tInviata da....: $newfrom\n";
				print MAIL "\tOggetto......: $subject\n\n";
				print MAIL "\n";
				print MAIL "-----------------------------------------\n";
				print MAIL "\n\nLogin URL: $global{'baseurl'}/staff.cgi\n\n";
				print MAIL "\n\nGrazie.";
			close(MAIL); 
		}
	}
	$sth->finish;
}


sub lang_parse {
    if ($_ =~ /\%*\%/) 
           {
               s/\%(\S+)\%/$LANG{$1}/g;
           }
  }

1;
