#!/usr/bin/perl -w
###################################################################################
#                                                                                 #
#                   PerlDesk - Customer Help Desk Software                        #
#                                                                                 #
###################################################################################
#                                                                                 #
#     Author: John Bennett	                                                  #
#      Email: j.bennett@perldesk.com                                              #
#        Web: http://www.perldesk.com                                             #
#   Filename: admin_subs.pl                                                       #
#    Details: The main admin file                                                 #
#    Release: 1.5.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 #                                                            
###################################################################################
# LOAD MODULES

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

   $uname = $q->cookie('admin');
   $apass = $q->cookie('apass');

%Cookies  = (
    admin => $uname,
    apass => $apass);


sub check_user 
  {

	if ((! $Cookies{'admin'}) || ($Cookies{'admin'} eq "")) 
         {
              print "Content-type: text/html\n\n";
	      print "<font face=Verdana size=2>Please login to access your account <a href=\"$global{'baseurl'}/admin.cgi\">Login</a>";
              exit;	
	 }

	$statement = 'SELECT * FROM staff WHERE username = ?'; 
	$sth       = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 	$sth->execute("$Cookies{'admin'}") or die "Couldn't execute statement: $DBI::errstr; stopped";
	   while(my $ref = $sth->fetchrow_hashref()) 
             {   
	            $username      =   $ref->{'username'};
                    $password      =   $ref->{'password'};
                    $name          =   $ref->{'name'};
                    $accesslevel   =   $ref->{'access'};
                    $email         =   $ref->{'email'};
 		    $rkey          =   $ref->{'rkey'};
		    $sig           =   $ref->{'signature'};
             }

	$md5 = new Digest::MD5 ;
	$md5->reset ;

	$yday     = (localtime)[7];
	$certif   = $Cookies{'admin'} . $yday . "pd-$rkey" . $ENV{'HTTP_USER_AGENT'}  . $ENV{'REMOTE_ADDR'}  ;
	$md5->add($certif);
	$enc_cert = $md5->hexdigest() ;

	if($enc_cert eq $Cookies{'apass'}) 
               {
   			# we're logged in !!
               } else {
         			print "Content-type: text/html\n\n";
        			print "<font face=Verdana size=2>Please login to access your account <a href=\"$global{'baseurl'}/admin.cgi\">Login</a>";
            	                exit;
                      }
   }

sub die_nice 
 {
        my $error = "@_";

        print "Content-type: text/html\n\n";
        print qq|<html><head><title>Error</title></head><body bgcolor="#FFFFFF"><p>&nbsp;</p><table width="400" border="0" cellspacing="1" cellpadding="0" align="center"><tr bgcolor="#666666"><td colspan="3"><table width="100%" border="0" cellspacing="1" cellpadding="0"><tr bgcolor="#E0E6ED"><td><table width="100%" border="0" cellspacing="1" cellpadding="4"><tr><td rowspan="2" width="21%"><div align="center"></div></td><td width="79%" height="2"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>FATAL HELPDESK ERROR </b></font></td></tr><tr><td width="79%" height="33"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$error</font></td></tr></table></td></tr></table></td></tr></table></body></html>|;
        exit;
 }




sub section {

 my $section = "@_";

  if ($section eq "login")
    {
           print "Content-type: text/html\n\n";

           print qq|<html><head><title>PerlDesk Administration Login</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><STYLE type=text/css>
                A:active  { COLOR: #006699; TEXT-DECORATION: none      }
                A:visited { COLOR: #334A9B; TEXT-DECORATION: none      }
                A:hover   { COLOR: #334A9B; TEXT-DECORATION: underline }
                A:link    { COLOR: #334A9B; TEXT-DECORATION: none      }
                .gbox         { FONT-SIZE: 11px; FONT-FAMILY: Verdana; COLOR: #000000; BACKGROUND-COLOR: #EEEEEE }
                .forminput    { font-size: 8pt; background-color: #CCCCCC; font-family: verdana, helvetica, sans-serif; vertical-align:middle } 
                .tbox         { FONT-SIZE: 11px; FONT-FAMILY: Verdana; COLOR: #000000; BACKGROUND-COLOR: #ffffff }
                </STYLE></head><body bgcolor="#FFFFFF" text="#000000"><p>&nbsp;</p><table width="400" border="0" cellspacing="0" cellpadding="0" align="center"><tr><td colspan="2"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><img src="$global{'imgbase'}/logo.gif"><br><div align=right>Remote IP: $ENV{'REMOTE_ADDR'}</div></font></td></tr><tr> <td colspan="2"><form name="form1" method="post" action="admin.cgi"><table width="66%" border="0" align="center" cellpadding="0" cellspacing="1"><tr><td width="42%">&nbsp;</td><td width="58%">&nbsp;</td></tr><tr><td width="42%"><div align="center"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Username</font></div></td><td width="58%"><input type="text" name="username" class="gbox"></td></tr><tr><td width="42%"><div align="center"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Password</font></div></td><td width="58%"><input type="password" name="password" class="gbox"></td></tr><tr><td colspan="2">&nbsp;</td></tr><tr> 
                <td colspan="2"><div align="center"><input type="hidden" name="do" value="plogin">
                <div align=center><input type="submit" name="Submit" value="Entra" class="forminput"></div></div></td></tr></table></form></td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr></table></body></html>|;

    }

 if ($section eq "plogin")
   {
      my $pass      = $q->param('password');
      my $user      = $q->param('username');
      my $error     = "0";
      my $statement = 'SELECT * FROM staff WHERE username = "admin"'; 

	# by Ago
      &identity_control($user);
      # fine by Ago

      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()) 
	  {	
	      $salt = $ref->{'rkey'};
	   my $cpass = crypt($pass, $salt);

			if ($cpass ne $ref->{'password'}) 
                          {
				$errorm = "1";
			  } else {
				$username =  $ref->{'username'};
				$password =  $ref->{'password'};
				$name     =  $ref->{'name'};
				$email    =  $ref->{'email'};
			} 		
	} 
	if ($error ne "1") 
      {
	       if ((!$username) || ($user ne "admin")) {  $errorm = "1";  }
	  }
    die_nice("Invalid Login") if $errorm;

	my $md5    = new Digest::MD5 ;
	   $md5->reset ;

	my $yday   = (localtime)[7];
	my $certif = $user . $yday .  "pd-$salt" . $ENV{'HTTP_USER_AGENT'}  .  $ENV{'REMOTE_ADDR'} ;
	   $md5->add($certif);
 	my $enc_cert = $md5->hexdigest() ;

      my $cookie1 = $q->cookie(-name=>'admin',
                               -value=>$user,
                               -path    => '/',
                               -domain  => '');

      my $cookie2 = $q->cookie(-name=>'apass',
                               -value=>$enc_cert,
                               -path    =>  '/',
                               -domain  =>  '');

      print $q->header(-cookie=>[$cookie1,$cookie2]);

		print qq|
					<html><p>&nbsp;</p><p>&nbsp;</p><meta http-equiv="refresh" content="1;URL=admin.cgi?do=main"><p align="center"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>Login</b>, stai entrando nell'area amministrazione.</font><br><br>
					<font size="1" face="Verdana, Arial, Helvetica, sans-serif"><a href="admin.cgi?do=main">clicca 
					qui</a> se non riesci ad entrare automaticamente</font></p></html>
                        |;
   }
 

 if ($section eq "main")
  {

	my ($sth);
    
    check_user();    
    print "Content-type: text/html\n\n";
   
	$sth = $dbh->prepare( "SELECT COUNT(*) FROM staff WHERE username != \"admin\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
	( $staff ) = $sth->fetchrow_array();
	$sth->finish;

	$sth = $dbh->prepare( "SELECT COUNT(*) FROM users" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
	( $users ) = $sth->fetchrow_array();
	$sth->finish;

	$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls`" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
	( $calls ) = $sth->fetchrow_array();
	$sth->finish;

	$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE status = \"OPEN\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
	( $open ) = $sth->fetchrow_array();
	$sth->finish;

	 $template{'total'} = $users + $staff;

	$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE status = \"HOLD\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
	( $hold ) = $sth->fetchrow_array();
	$sth->finish;

	$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE status = \"CLOSED\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
	( $closed ) = $sth->fetchrow_array();
	$sth->finish;

   $template{'open'}   = $open;
   $template{'hold'}   = $hold;
   $template{'closed'} = $closed;
   $template{'calls'}  = $calls;
   $template{'users'}  = $users;
   $template{'staff'}  = $staff;   
   print parse("$global{'data'}/include/tpl/admin/adminmain");
 
 }

 if ($section eq "logout")
  {


      my $cookie1 = $q->cookie(-name=>'admin',
                               -value=>'',
                               -path    => '/',
                               -domain  => '');

      my $cookie2 = $q->cookie(-name=>'apass',
                               -value=>'',
                               -path    =>  '/',
                               -domain  =>  '');

      print $q->header(-cookie=>[$cookie1,$cookie2]);

            $response = "<b>You are now logged out.</b>";
            $template{'response'}  = $response;

     my $output = parse("$global{'data'}/include/tpl/admin/general");
     print $output;

  }

  
 if ($section eq "anc_save")
  {
     check_user();
     print "Content-type: text/html\n\n";

	my $instaff  =  $q->param('staff');
	my $inusers  =  $q->param('users');
	my $inemail  =  $q->param('email');

	if ($instaff eq "yes") { $staff = 1; } else { $staff = 0; }
	if ($inusers eq "yes") { $users = 1; } else { $users = 0; }
	
	my $message  = $q->param('message');
	my $subject  = $q->param('subject');

    my $emessage = $message;

       $message  =~ s/\n/<br>/g;
 

      $sth = $dbh->prepare( "INSERT INTO announce VALUES ( ?, ?, ?, ?, ?, ?, ? )" ) or die "couldnt prepare statement";
      $sth->execute( "NULL", "$Cookies{'admin'}", $subject, $message, $staff, $users, $hdtime ) or die "Couldnt execute statement";


	if ($instaff eq "yes" && $inemail eq "yes" && $enablemail) {
           
	$statement = 'SELECT email FROM staff'; 
		$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 ($enablemail) {	
			open(MAIL, "|$global{'sendmail'} -t") || print "Unable to send mail: $!";
				print MAIL "To: $ref->{'email'}\n";
				print MAIL "From: $global{'adminemail'}\n";
				print MAIL "Subject: $subject\n\n";
				print MAIL "$emessage\n";
    		close(MAIL); 
         }
	} }


	if ($inemail eq "yes" && $inusers eq "yes" && $enablemail) {

		$statement = 'SELECT email FROM users'; 
		$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()) {	
			open(MAIL, "|$global{'sendmail'} -t") || print "Unable to send mail: $!";
				print MAIL "To: $ref->{'email'}\n";
				print MAIL "From: $global{'adminemail'}\n";
				print MAIL "Subject: $subject\n\n";
				print MAIL "$emessage\n";
			close(MAIL); 
		
	} }

	$response = 'Annuncio modificato. <a href="admin.cgi?do=announcements">Ritorna agli Annunci</a>';
    $template{'response'} = $response;

   print parse("$global{'data'}/include/tpl/admin/general");
   
  }


 if ($section eq "validate")
  {

     check_user();
     print "Content-type: text/html\n\n";

		$statement = 'SELECT * FROM users WHERE pending = "1"'; 
		$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()) 
         {	

            $template{'users'} .= qq|<form action="admin.cgi" method="post"><table width="85%" border="1" cellspacing="0" cellpadding="1" align="center" bgcolor="#EAEAEA" bordercolor="#F7F7F7" bordercolorlight="#CCCCCC"><tr bgcolor="#DBDBDB"> 
                <td colspan="3" height="25"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">$ref->{'username'}</font></td></tr><tr> 
                <td colspan="2"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">Name</font></td>
                <td width="60%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">$ref->{'name'}</font></td>
                </tr><tr><td colspan="2" height="14"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">Indirizzo E-mail</font></td><td width="60%" height="14"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">$ref->{'email'}</font></td>
                </tr><tr><td colspan="2" height="14"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">URL</font></td><td width="60%" height="14"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">$ref->{'url'}</font></td>
                </tr><tr><td width="29%"> <font size="1" face="Verdana, Arial, Helvetica, sans-serif"> <input type="radio" name="approve" value="1" checked>Approve</font></td>
                <td colspan="2"> <font size="1" face="Verdana, Arial, Helvetica, sans-serif"><input type="radio" name="approve" value="0">Decline Reason</font></td></tr><tr> 
                <td width="29%">&nbsp;</td><td colspan="2"> <input type="hidden" name="user" value="$ref->{'username'}"> <input type="hidden" name="email" value="$ref->{'email'}"><input type="hidden" name="do" value="approve"><textarea name="reason"  class="tbox" cols="48" rows="2"></textarea></td></tr></table><input type=Submit name=Submit value=Invia></form><br>|;

         }
 
       $template{'users'} = qq|<font size=2>Nessun utente in attesa di approvazione!</font>| if !$template{'users'};
        print parse("$global{'data'}/include/tpl/admin/pending");
  }


 
 if ($section eq "approve") 
  {

     check_user();
     print "Content-type: text/html\n\n";
     $user  = $q->param('user');
     $email = $q->param('email');

    if ($q->param('approve') == "1")
     {
        $dbh->do(qq|UPDATE users SET pending = "0" WHERE username = "$user"|);
        my $msg = qq|
Il tuo account su $global{'title'} è stato approvato. Puoi entrare usando username/password selezionati che sono stati scelti al momento della registrazione.

$global{'baseurl'}/pdesk.cgi

Grazie

$global{'title'}
|;
        email ( To => "$email", From => "$global{'adminemail'}", Subject => "Account Approved", Body => "$msg" );
        $template{'response'} = "Grazie, $user è stato approvato";
    }

  elsif ($q->param('approve') == "0")
   {
        $reason = $q->param('reason');

      $dbh->do(qq|DELETE FROM users WHERE username = "$user"|);
      my $msg = qq|
Spiacente, ma la tua richiesta di account su $global{'title'} è stata rifiutata per i seguenti motivi:

$reason
|;
        email ( To => "$email", From => "$global{'adminemail'}", Subject => "Account Declined", Body => "$msg" );
        $template{'response'} = "Grazie, $user è stato rifiutato dal sistema";
   } 

    print parse("$global{'data'}/include/tpl/admin/general");

 
  }


  
 if ($section eq "announcements")
  {

     check_user();
     print "Content-type: text/html\n\n";

	$statement = 'SELECT * FROM announce'; 
	$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())  
       {	
          	$notice .= '<table width="100%" border="0" cellspacing="1" cellpadding="2"><tr><td width="5%"> <div align="center"><img src="' . "$global{'imgbase'}" . '/note.gif" width="11" height="11"></div></td><td width="42%"><a href="admin.cgi?do=anc_view&nid=' . "$ref->{'id'}\"><font size=\"1\" face=\"Verdana, Arial, Helvetica, sans-serif\">$ref->{'subject'}" . '</font></a></td>
            		    <td width="25%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">' . "$ref->{'time'}" . '</font></td><td width="28%"> <font size="1" face="Verdana, Arial, Helvetica, sans-serif"><div align=right><a href="admin.cgi?do=anc_edit&nid=' . "$ref->{'id'}" . '">Modifica</a> | <a href="admin.cgi?do=anc_del&nid=' . "$ref->{'id'}" . '">Elimina</a></font></div></td></tr></table>';
       }
 
       $notice                   =  '<font face="verdana" size="1">0 Annunci</font>' if !$notice;
       $template{'announcement'} =   $notice;

     print parse("$global{'data'}/include/tpl/admin/anounce");
     
  }


 if ($section eq "anc_del")
  {
     check_user();
     print "Content-type: text/html\n\n";

    $nid = $q->param('nid');

	$statement = 'DELETE FROM announce WHERE id = ?'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($nid) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	$response = 'Announcement Deleted. <a href="admin.cgi?do=announcements">Ritorna agli Annunci</a>';

   $template{'response'} = $response;
   my $output = parse("$global{'data'}/include/tpl/admin/general");
   print $output;

  }
  

 if ($section eq "anc_view")
  {

     check_user();
     print "Content-type: text/html\n\n";

    $nid = $q->param('nid');

	  $statement = 'SELECT * FROM announce WHERE id = ?'; 
	  $sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 	  $sth->execute($nid) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	     while(my $ref = $sth->fetchrow_hashref()) 
           {	
            	$notice .= '<table width="100%" border="0" cellspacing="1" cellpadding="0">
                            <tr><td width="24%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Author:</font></td>
                            <td width="76%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">' . "$ref->{'author'}" . '</font></td>
                            </tr><tr><td width="24%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Published:</font></td>
                            <td width="76%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">' . "$ref->{'time'}" . '</font></td>
                            </tr><tr><td width="24%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"></font></td>
                            <td width="76%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"></font></td>
                            </tr><tr><td width="24%" valign="top"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Subject:</font></td>
                            <td width="76%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>' . "$ref->{'subject'}" . '</b><br><br></font></td>
                            </tr><tr><td width="24%" valign="top"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Announcement</font></td>
                            <td width="76%"></td></tr><tr><td width="100%" colspan=2><hr size=1 width="85%" color="cccccc" align="left"></td><tr><td width="100%" colspan=2><font size="2" face="Verdana, Arial, Helvetica, sans-serif">' . "$ref->{'message'}" . '</font></td></table>';
        	}

   $template{'announcement'} = $notice;

   my $output = parse("$global{'data'}/include/tpl/admin/viewannouncement");

   print $output;

  }




 if ($section eq "anc_edit")
  {
     check_user();
     print "Content-type: text/html\n\n";

      $nid       =  $q->param('nid');
	  $statement =  'SELECT * FROM announce WHERE id = ?'; 
	  $sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 	  $sth->execute($nid) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	     while(my $ref = $sth->fetchrow_hashref()) 
           {	
              $template{'subject'} =  $ref->{'subject'};
              $template{'note'}    =  $ref->{'message'}; 
              $template{'note'}    =~ s/<br>/\n/g;

              $template{'nid'}     = $nid;
           }

   print parse("$global{'data'}/include/tpl/admin/anc_edit");

  }



if ($section eq "anc_esave")
 {
     check_user();
     print "Content-type: text/html\n\n";

     my $nid     =  $q->param('nid');
     my $subject =  $q->param('subject');
     my $message =  $q->param('notes');
        $message =~ s/\n/<br>/g;
     
	  $statement =  'UPDATE announce SET subject = ?, message = ? WHERE id = ?'; 
	  $sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 	  $sth->execute( $subject, $message, $nid ) or die print "Couldn't execute statement: $DBI::errstr; stopped";
 
    $template{'response'} = qq|<font face=Verdana size="2">Annunci aggiornati <a href=admin.cgi?do=announcements> Annunci</a>|;     
    print parse("$global{'data'}/include/tpl/admin/general");

 }




if ($section eq "adduser")
 {
     check_user();
     print "Content-type: text/html\n\n";
     print parse("$global{'data'}/include/tpl/admin/adduser");

 }


if ($section eq "saveuser")
 {
   
     check_user();

     my $name     =   $q->param('name');
        $email    =   $q->param('email');
     my $company  =   $q->param('company');
     my $url      =   $q->param('url');
     my $user     =   $q->param('username');
     my $pass1    =   $q->param('pass1');
     my $pass2    =   $q->param('pass2');

    die_nice("Passwords do not match") if $pass1 != $pass2;

	my  $sth = $dbh->prepare("SELECT * FROM users WHERE username = ?") or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($user) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref())  { }
        
        if ($sth->rows != "0") 
           {
                $error = "Username <b>$user</b> exists<br>";
           }
        
     	$sth->finish;   

           $error  = "$LANG{'error5'} $LANG{'name'}<br>"              if !$name;
           $error .= "$LANG{'error5'} $LANG{'email'}<br>"             if !$email;
           $error .= "$LANG{'error5'} URL<br>"                        if !$url;
           $error .= "The username cannot contain spaces<br>"         if $user =~ / /;
           $error .= "$LANG{'username'} <b>$user</b> $LANG{'error2'}" if $user =~ /^unregistered\b/i;
           
           die_nice("$error") if $error;

    	my @chars    =  (A..Z);
     	my $salt     =  $chars[rand(@chars)] . $chars[rand(@chars)];
    	 $password =   crypt($pass1, $salt);	
         $pending  = '0'; 
         $code     = '0';


    my $rv = $dbh->do(qq{
                  INSERT INTO users values ("NULL", "$user", "$password", "$name", "$email", "$url", "$company", "$salt", "$pending", "0", "$code", "0")}
         );

     $template{'user'}     = $user;    
     $template{'username'} = $user;
     $template{'password'} = $pass1;
     $template{'cname'}    = $name; 
     $template{'baseurl'}  = $global{'baseurl'};
     $template{'mainfile'} = 'pdesk.cgi';

      if ($q->param('notify') == "yes") {

         my $body;
  		 open (MAILTPL, "$global{'data'}/include/tpl/welcome.txt");
			while (<MAILTPL>) 
                {
                    lang_parse() if $_ =~ /%*%/;
                       s/\{(\S+)\}/$template{$1}/g;
            	       $body .= $_;
		 	    }  
		 close(MAILTPL);	
         email ( To => "$email", From => "$global{'adminemail'}", Subject => "Help Desk Registration", Body => "$body");
       }

     print "Content-type: text/html\n\n";
     $template{'response'} = qq|<font size="2">Grazie, <b>$user</b> è stato aggiunto all\' help desk.|;        
     print parse("$global{'data'}/include/tpl/admin/general");   
 }


if ($section eq "hdsettings")
 {
     check_user();
     print "Content-type: text/html\n\n";

   $template{'achecked'} = ' checked' if $global{'validate'} == "1";
   $template{'bchecked'} = ' checked' if $global{'reqvalid'} == "1";

   $template{'achecked'} = '' if $global{'validate'} == "0";
   $template{'bchecked'} = '' if $global{'reqvalid'} == "0";

    my $statement = 'SELECT * FROM ticket_fields ORDER BY dorder'; 
    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()) 
      {	
          $template{'fields'} .= qq|<form action="admin.cgi" method="post"><input type="hidden" name="id" value="$ref->{'id'}"><table width="90%" border="0" cellspacing="0" cellpadding="0">
                    <tr> 
                      <td width="19%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">CAMPO 
                        TICKET</font></td>
                      <td width="40%"> <font size="1" face="Verdana, Arial, Helvetica, sans-serif"> 
                        <input type="text" name="field" value="$ref->{'name'}">
                        </font></td>
                         <td width="10%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">ORDINE</font></td>
                         <td width="11%"> <font size="1" face="Verdana, Arial, Helvetica, sans-serif"> 
                         <input type="text" name="order" value="$ref->{'dorder'}" size="2"><input type=hidden name=do value=upform>
                         </font></td>
                         <td width="18%"> <font size="1" face="Verdana, Arial, Helvetica, sans-serif"> 
                          <input type=image src="$global{'imgbase'}/go.gif">
                        </font></td></tr>
                  </table></form>|;
      }
    $sth->finish;


   print parse("$global{'data'}/include/tpl/admin/websettings");


 }








 if ($section eq "tpl")
  {

     check_user();
     print "Content-type: text/html\n\n";

	opendir(FRL, "$global{'data'}/include/tpl");
			@files = readdir FRL;
	closedir(FRL);	

	foreach $fil (@files) 
	{
		next if $fil =~ /^\.+$/;
		if ($fil =~ /\./) 
		{
			if ($fil =~ /txt/i) { $img = "$global{'imgbase'}/txt.gif"; }
			if ($fil =~ /tpl/i) { $img = "$global{'imgbase'}/tpl.gif"; }
			$file .= '<table width="60%" border="0" cellspacing="1" cellpadding="0" align="center"><tr><td width="24%">
             		  <div align="center"><img src="' . "$img" . '"></div></td><td width="76%">' . "<a href=\"admin.cgi?do=edittpl&file=$fil\">$fil</a>" . '</td>
        		 	  <tr></table>';

		} 
	}

   $template{'files'}  =   $file;

   my $output = parse("$global{'data'}/include/tpl/admin/temp");

   print $output;

  }




 if ($section eq "upus")
 {
     check_user();
     print "Content-type: text/html\n\n";

   
      $reqvalid  =  $q->param('usvalid');
      $emvalid   =  $q->param('sendvalid');
      $reqvalid  =  "0" if !$reqvalid;
      $emvalid   =  "0" if !$emvalid;

    $dbh->do(qq|UPDATE settings SET value = "$emvalid"  WHERE setting = "reqvalid"|);
    $dbh->do(qq|UPDATE settings SET value = "$reqvalid" WHERE setting = "validate"|);

    $template{'response'} = qq|<font size=2>Sign up settings saved <a href=admin.cgi?do=hdsettings> Back</a>|;

   my $output = parse("$global{'data'}/include/tpl/admin/general");
   print $output;

 }




 if ($section eq "settings")
  {
     check_user();
     print "Content-type: text/html\n\n";

     $template{'pri1'}       =  $global{'pri1'}; 
     $template{'pri2'}       =  $global{'pri2'}; 
     $template{'pri3'}       =  $global{'pri3'}; 
     $template{'pri4'}       =  $global{'pri4'}; 
     $template{'pri5'}       =  $global{'pri5'}; 
     $template{'sendmail'}   =  $global{'sendmail'};
     $template{'adminemail'} =  $global{'adminemail'};   
     $template{'name'}       =  $name;
     $template{'offset'}     =  $global{'timeoffset'};
     $template{'hdtime'}     =  $hdtime;

     print parse("$global{'data'}/include/tpl/admin/settings");
  }














 if ($section eq "edittpl")
  {
     check_user();
     print "Content-type: text/html\n\n";
 
        my $vfile = $q->param('file');    

		open (FILE, "$global{'data'}/include/tpl/$vfile");
                    while (<FILE>) {  $content .= $_;  }
		close (FILE);

                $content =~ s/</&lt\;/gi;
                $content =~ s/>/&gt\;/gi;

                $content =~ s/\{/&#123;/gi;
                $content =~ s/\}/&#125;/gi;

		$template{'response'} = '<table width="100%" border="0" align="center"><tr><td valign="top"> <font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>MODIFICA FILE 
                                        ' . "$vfile" . ' </b></font></td></tr><tr><td><div align="right"><font size="2"><font size="2"><font face="Verdana, Arial, Helvetica, sans-serif"></font></font></font></div></td></tr><tr><td height="20"><form name="form1" method="post" action="admin.cgi">
                                         <div align="center"><textarea name="textfield" class="tbox" cols="80" rows="40">' . "$content" . '</textarea><br><br><input type="hidden" name="file" value="' . "$vfile" . '"><input type=hidden name=do value=savetpl><input type="submit" name="Submit" value="Save"></div></form></td></tr><tr><td>&nbsp;</td></tr></table>';

                print parse("$global{'data'}/include/tpl/admin/general");
  }


 if ($section eq "ticket")
  {
   check_user(); 
    print "Content-type: text/html\n\n";

    my $trackedcall=$q->param('cid');

       $statement = 'SELECT * FROM `calls` WHERE  id = ? ORDER BY id'; 
        $sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($trackedcall) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		$number=0;
			  while(my $ref = $sth->fetchrow_hashref()) 
				{	
						$template{'trackno'}     =   $ref->{'id'};
						$template{'date'}        =   $ref->{'time'};
						$template{'uname'}       =   $ref->{'username'};
						$template{'username'}    =   $ref->{'username'};
						$template{'priority'}    =   $ref->{'priority'};
						$template{'status'}      =   $ref->{'status'};
						$template{'subject'}     =   $ref->{'subject'};
						$template{'category'}    =   $ref->{'category'};
						$template{'description'} =   $ref->{'description'};
						$template{'owned'}       =   $ref->{'ownership'};
						$template{'number'}      =   0;
			  			$template{'email'}       =   $ref->{'email'};
						$template{'url'}         =   $ref->{'url'};
						$template{'name'}        =   $ref->{'name'};

			}
	if (@errors) 
	{
   			@content = @errors;
   			print @content;
		$dbh->disconnect;
   		exit;
	}

    my $statement = 'SELECT * FROM ticket_fields ORDER BY dorder'; 
    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 $tatement = qq|SELECT * FROM call_fields WHERE cid = "$trackedcall" AND fid = "$ref->{'id'}"|; 
            my $th = $dbh->prepare($tatement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
               $th->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
                 while(my $ef = $th->fetchrow_hashref()) 
                   {	
                        $template{'fields'} .= qq|
                                                    <tr> <td width="19%" height="2"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$ref->{'name'}</font></td>
                                                    <td width="72%" height="2"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$ef->{'value'}</font> </td></tr>
                                                 |;
      
                   }
      }
    $sth->finish;

   $template{'fields'} = '' if !$template{'fields'};
  
	my $statement = 'SELECT * FROM settings WHERE setting = "allowhtml"'; 
		$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 $htmlcode = "$ref->{'value'}";
		   }
	$statemente = 'SELECT * FROM notes WHERE `call` = ? ORDER BY id;'; 
	$sth = $dbh->prepare($statemente) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 	$sth->execute($trackedcall) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	      while(my $ref = $sth->fetchrow_hashref()) {
        
            	$body = $ref->{'comment'};

	if ($body =~ /^</) {	} else 
      {
    		$body =~ s/\n/<br>/g;
      }

	if ($ref->{'owner'} eq 0) 
			{
				$notes .= '<table width="100%" border="0" cellspacing="1" cellpadding="2"><tr class="userresponse"> 
   						   <td width="30%" height="14" valign="top"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>' . "$ref->{'author'}" . '<br>
   						   </b></font><font face="Verdana, Arial, Helvetica, sans-serif" size="1">' . "$ref->{'time'}" . '<br><br></font></td>
   						   <td width="70%" height="14" valign="top"><font face="Verdana, Arial, Helvetica, sans-serif" size="1">' . "$body" . '</font></td></tr></table>';
			} 

	if ($ref->{'owner'} eq 3) 
			{
				$notes .= '<table width="100%" border="0" cellspacing="1" cellpadding="2"><tr class="staffaction"> 
  						   <td width="30%" height="14" valign="top"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>' . "$ref->{'author'}" . '<br>
   						   </b></font><font face="Verdana, Arial, Helvetica, sans-serif" size="1">' . "$ref->{'time'}" . '<br><br></font></td>
   						   <td width="70%" height="14" valign="top"><font face="Verdana, Arial, Helvetica, sans-serif" size="1">' . "<b>STAFF ACTION: $ref->{'action'}</b><br>$body" . '</font></td></tr></table>';
			} 

	if ($ref->{'owner'} eq 1) 
			{
				if ($ref->{'visible'} eq 0) { $notice = '<b>PRIVATE STAFF NOTE</b><br>'; } else { $notice = ''; }
					   $notes .= '<table width="100%" border="0" cellspacing="1" cellpadding="2"><tr class="staffresponse"> 
   						   <td width="30%" height="14" valign="top"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>' . "$ref->{'author'}" . '<br>
   						   </b></font><font face="Verdana, Arial, Helvetica, sans-serif" size="1">' . "$ref->{'time'}" . '<br><br> </font></td>
   						   <td width="70%" height="14" valign="top"><font face="Verdana, Arial, Helvetica, sans-serif" size="1">' . "$notice $body" . '</font></td></tr></table>';
			}
			
		}
	if (!$notes) 
	{
                	$notes = '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr class="stafftab"><td class="stafftab"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">No 
                                  user/staff responses.</font></td></tr></table>';
	}

	if ($template{'description'} =~ /^</) {	} else 
     {
	 	# This is a Text Email, format it!
	    	$template{'description'} =~ s/\n/<br>/g;
	 }
  
    $template{'notes'}    =  $notes;

    my $output = parse("$global{'data'}/include/tpl/admin/viewticket");
    print $output;

  }



 if ($section eq "viewuser")
   {

     check_user();
     print "Content-type: text/html\n\n";

        $uusername =  $q->param('user');
        $uusername =~ s/_/\_/g;
		
     	$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE username = ?" ) or die DBI->errstr;
		$sth->execute($uusername) or die print "Couldn't execute statement: $DBI::errstr; stopped";
        	( $requests ) = $sth->fetchrow_array();
     	$sth->finish;

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

   $template{'requests'}        =   $requests;
   my $output = parse("$global{'data'}/include/tpl/admin/userview");
   print $output;

   } 
 


 if ($section eq "usercalls")
  {

     check_user();
     print "Content-type: text/html\n\n";

	$cusername = $q->param('user');

	$statement = 'SELECT * FROM `calls` WHERE  username = ? ORDER BY id'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($cusername) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		$number=0;
			  while(my $ref = $sth->fetchrow_hashref()) {	
					
					if (($ref->{'category'} eq $accesslevel) || ($accesslevel = 'GLOB')) {
 				$number++;
					
            	if ($ref->{'priority'} eq 1) { $font = '#990000'; } else { $font = '#000000'; }			

     			if ($ref->{'method'}  eq "cc") { $img   = "phone.gif";     } elsif ($ref->{'method'} eq "em") { $img = "mail.gif"; } else { $img = "ticket.gif"; }

       			$subject="$ref->{'subject'}"; 
       			$subject=substr($subject,0,18).'..' if length($subject) > 20;

                 $call .= display_ticket($ref->{'id'}, $ref->{'username'}, $ref->{'category'}, $ref->{'status'}, $ref->{'time'});
   		  
					}
			}

      $template{'username'}    =   $cusername;
      $template{'numcalls'}    =   $number;   
      $template{'listcalls'}   =   $call;
   my $output = parse("$global{'data'}/include/tpl/admin/usercalls");
   print $output;

  }


 if ($section eq "emailusers")
  {

     check_user();
     print "Content-type: text/html\n\n";

     my $output = parse("$global{'data'}/include/tpl/admin/emailusers");
     print $output;

  }

 if ($section eq "emailstaff")
  {

     check_user();
     print "Content-type: text/html\n\n";

     my $output = parse("$global{'data'}/include/tpl/admin/emailstaff");
     print $output;

  }

 if ($section eq "usersend")
  {

     check_user();
     print "Content-type: text/html\n\n";

	$email = $q->param('email');
	$subje = $q->param('subject');
	$messg = $q->param('message');

	$statement = 'SELECT email FROM users'; 
		$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 ($enablemail) {
		open(MAIL, "|$global{'sendmail'} -t") || print "Unable to send mail: $!";
			print MAIL "To: $ref->{'email'}\n";
			print MAIL "From: $email\n";
			print MAIL "Subject: $subje\n\n";
			print MAIL "$messg\n";
		close(MAIL); 
      }
	}

    $response              = 'Sent ! <a href="admin.cgi?do=users"> User Admin </a>';
    $template{'response'}  =   $response;

   print parse("$global{'data'}/include/tpl/admin/general");
   
  }


 if ($section eq "edituser")
  {
     check_user();
     print "Content-type: text/html\n\n";
 
    $uusername = $q->param('user');
	$statement = 'SELECT * FROM users WHERE username = ?'; 

		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($uusername) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
                  {	
			$template{'username'} =  $ref->{'username'};
			$template{'email'}    =  $ref->{'email'};
			$template{'company'}  =  $ref->{'company'};
			$template{'url'}      =  $ref->{'url'};
			$template{'name'}     =  $ref->{'name'};
	          }

   $template{'staff'}        =   $staff;

   my $output = parse("$global{'data'}/include/tpl/admin/edituser");
   print $output;

  }







 if ($section eq "savesettings")
  {
     check_user();
 
	$alert     =  $q->param('alert');
	$email     =  $q->param('email');
	$name      =  $q->param('name');
	$allowhtml =  "yes";
	$pass      =  $q->param('password');
    $title     =  $q->param('title');
	$pri1      =  $q->param('pri1');
	$pri2      =  $q->param('pri2');
	$pri3      =  $q->param('pri3');
	$pri4      =  $q->param('pri4');
	$pri5      =  $q->param('pri5');
	$sig       =  $q->param('sig');
    $sendmail  =  $q->param('sendmail');
    $baseurl   =  $q->param('baseurl');
    $imgbase   =  $q->param('imgbase');
    $language  =  $q->param('language');
    $adminemail = $q->param('email');
    $timeo      = $q->param('time');

    if (! $langdetails{$language}) { die_nice("Invalid Language File <b>$language.inc</b>"); }

    $dbh->do(qq|UPDATE settings SET value = "$adminemail" WHERE setting = "adminemail"|);
    $dbh->do(qq|UPDATE settings SET value = "$sendmail" WHERE setting = "sendmail"|);
    $dbh->do(qq|UPDATE settings SET value = "$baseurl" WHERE setting = "baseurl"|);
    $dbh->do(qq|UPDATE settings SET value = "$imgbase" WHERE setting = "imgbase"|);
    $dbh->do(qq|UPDATE settings SET value = "$language" WHERE setting = "language"|);
    $dbh->do(qq|UPDATE settings SET value = "$timeo" WHERE setting = "timeoffset"|);

	$statement = 'UPDATE settings SET value  = ? WHERE setting = "title"'; 
	$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
	$sth->execute($title) or die print "Couldn't execute statement: $DBI::errstr; stopped";


	# UPDATE CALL SHADING

	$statement = 'UPDATE settings SET value  = ? WHERE setting = "pri1"'; 
	$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
	$sth->execute($pri1) or die print "Couldn't execute statement: $DBI::errstr; stopped";

	$statement = 'UPDATE settings SET value  = ? WHERE setting = "pri2"'; 
	$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
	$sth->execute($pri2) or die print "Couldn't execute statement: $DBI::errstr; stopped";

	$statement = 'UPDATE settings SET value  = ? WHERE setting = "pri3"'; 
	$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
	$sth->execute($pri3) or die print "Couldn't execute statement: $DBI::errstr; stopped";

	$statement = 'UPDATE settings SET value  = ? WHERE setting = "pri4"'; 
	$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
	$sth->execute($pri4) or die print "Couldn't execute statement: $DBI::errstr; stopped";

	$statement = 'UPDATE settings SET value  = ? WHERE setting = "pri5"'; 
	$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
	$sth->execute($pri5) or die print "Couldn't execute statement: $DBI::errstr; stopped";

	# UPDATE STAFF DELETE ACCESS

	$sdelete = $q->param('staffdelete');

	if ($sdelete eq "yes") { $snum = 1; } else { $snum = 0; }

	$statement = 'UPDATE settings SET value  = ? WHERE setting = "sdelete"'; 
	$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
	$sth->execute($snum) or die print "Couldn't execute statement: $DBI::errstr; stopped";


	# UPDATE STAFF LOCK ACCESS

	$slock = $q->param('stafflock');

	if ($slock eq "yes") { $slnum = 1; } else { $slnum = 0; }

	$statement = 'UPDATE settings SET value  = ? WHERE setting = "slock"'; 
	$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
	$sth->execute($slnum) or die print "Couldn't execute statement: $DBI::errstr; stopped";


	# UPDATE PROFILE

	if ($alert eq "yes") { $notify = 1; } else { $notify = 0; }
		$statement = 'UPDATE staff SET name = "' . "$name" . '", email = "' . "$email" . '", notify = "' . "$notify" . '", signature = "' . "$sig" . '" WHERE username = "' . "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";


	# UPDATE PASSWORD

	if ($pass ne "") 
     {
			my @chars=(A..Z);

				$salt      =  $chars[rand(@chars)] . $chars[rand(@chars)];
				$epass     =  crypt($pass, $salt);

				$tatement =  qq|UPDATE staff SET password = "$epass", rkey = "$salt" WHERE username = "admin"|; 
				$sth       =  $dbh->prepare($tatement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 				$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
				$sth->finish;
	 }

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

	$response = 'Saved. Back to <a href="admin.cgi?do=settings">Settings</a>';
	
    $template{'response'}  =   $response;
     my $output = parse("$global{'data'}/include/tpl/admin/general");
     print $output;
  }



if ($section eq "savedd")
 {
     check_user();
     print "Content-type: text/html\n\n";

	my $department = $q->param('adddepartment');
		my $rv = $dbh->do(qq{INSERT INTO departments values (
			"$department")}
		);

	$response = 'Department Added <a href="admin.cgi?do=settings">Back to Settings</a>';

    $template{'response'}  =   $response;
    my $output = parse("$global{'data'}/include/tpl/admin/general");
    print $output;
 }


if ($section eq "upform")
 {
     check_user();
     print "Content-type: text/html\n\n";

     $form_id = $q->param('id');
     $name    = $q->param('field');
     $order   = $q->param('order');

       if (!$name) 
        {
           $dbh->do(qq~DELETE FROM ticket_fields WHERE id = "$form_id"~);
        } 
       else {
              $dbh->do(qq|UPDATE ticket_fields SET name = "$name", dorder = "$order" WHERE id = "$form_id"|);
            }
       
     my $status = "deleted" if !$name;
        $status = "updated" if  $name;
   
     $template{'response'} = qq|<font face="Verdana" size="2">Ticket Field <b>$form_id</b> has been $status|;
     print parse("$global{'data'}/include/tpl/admin/general");
}


if ($section eq "adform")
 {
     check_user();
     print "Content-type: text/html\n\n";

     my $name  = $q->param('field');
     my $order = $q->param('order');

     my $value = '{name}'  if  $name eq "name";
        $value = '{email}' if  $name eq "email";
        $value = '{url}'   if  $name eq "url";
        $value = ''        if !$value;

     $dbh->do(qq~INSERT INTO ticket_fields VALUES ( "NULL", "$name", "$value", "$order" )~);

     $template{'response'} = qq|<font face="Verdana" size="2">Ticket Field <b>$name</b> has been saved|;
     print parse("$global{'data'}/include/tpl/admin/general");

 }






if ($section eq "departments")
 {

     check_user();
     print "Content-type: text/html\n\n";

	$statement = 'SELECT * FROM departments'; 
	$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()) 
		{	
		$link = "$ref->{'level'}";

		chomp($link);

		$link =~ s/ /_/g;
		
 		$list .= '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td width="2%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"></font></td>
    				<td width="28%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Modifica Area</font></td>
    				<td width="36%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>' . "$ref->{'level'}" . '</b></font></td><td width="34%"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">[ 
      				<a href="admin.cgi?do=editdep&cat=' . "$link" . '">MODIFICA</a> | <a href="admin.cgi?do=removedep&cat=' . "$link" . '">ELIMINA</a> ] </font></td></tr></table>';
		}
	$sth->finish;


    $template{'departments'}  =   $list;
    my $output = parse("$global{'data'}/include/tpl/admin/departments");
    print $output;
}




 if ($section eq "editdep")
  {

     check_user();
     print "Content-type: text/html\n\n";

    $category = $q->param('cat');
  	 chomp($category);

    $category =~ s/_/ /g;

	$content = '<table width="100%" border="0"><tr><td></td></tr><tr><td>&nbsp;</td></tr><tr><td bgcolor="#C4C1DB"><p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>AMMINISTRAZIONE: 
    		    MODIFICA AREE</b></font></p></td></tr><tr><td height="36" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="0">
      		    <tr><td colspan="3"><div align="center"></div></td></tr><tr><td colspan="3"><form name="form1" method="post" action="admin.cgi"><table width="100%" border="0" cellspacing="1" cellpadding="0">
                <tr> <td width="4%">&nbsp;</td><td width="28%">&nbsp;</td><td colspan="2" width="68%">&nbsp;</td>
                </tr><tr><td colspan="4"><div align="center"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> 
                <input type="hidden" name="old" value="' . "$category" . '">Modifica</font><font size="2" face="Verdana, Arial, Helvetica, sans-serif"> <input type=hidden name=do value=savedep>
                Department <input type="text" name="department" size="30" value="' . "$category" . '"><input type="submit" name="Submit" value="Submit"></font></div></td></tr><tr><td colspan="4">&nbsp;</td></tr></table></form></td></tr></table><table width="100%" border="0" cellspacing="1" cellpadding="0"><tr><td></td></tr></table></td></tr></table>';
	
    $template{'response'}  =   $content;
    my $output = parse("$global{'data'}/include/tpl/admin/general");

    print $output;

  }


if ($section eq "savedep")
 {

     check_user();
     print "Content-type: text/html\n\n";

		$department = $q->param('department');
		$old = $q->param('old');

		$statementd = 'UPDATE departments SET level = "' . "$department" . '" WHERE  level = "' . "$old" . '";'; 
		$sth = $dbh->prepare($statementd) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
	$sth->finish;

		$statementd = 'UPDATE `calls` SET category = "' . "$department" . '" WHERE  category = "' . "$old" . '";'; 
		$sth = $dbh->prepare($statementd) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
	$sth->finish;

	$response = 'Department Saved <a href="admin.cgi?do=settings">Back to Settings</a>';

    $template{'response'}  =   $response;
    my $output = parse("$global{'data'}/include/tpl/admin/general");

    print $output;
 }
 



 if ($section eq "removedep")
 {
   
     check_user();
     print "Content-type: text/html\n\n";    

        $category =  $q->param('cat');
		$link     =  $category;
    	$category =~ s/_/ /g;
		$response = 'Are you sure you want to remove this department? Doing so will affect all techs which have access to this area. Please alter the staff profile for those techs in this area before clicking below. <br><br><a href="admin.cgi?do=rdep&cat=' . "$link" . '">Yes, Delete</a>';

    $template{'response'}  =   $response;
    my $output = parse("$global{'data'}/include/tpl/admin/general");

    print $output;

 }


 if ($section eq "rdep")
  {

     check_user();
     print "Content-type: text/html\n\n";    
      
        $category   =   $q->param('cat');
    	$category   =~  s/_/ /g;
		$statementd =  'DELETE FROM departments WHERE level = ?'; 
		$sth = $dbh->prepare($statementd) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
		$sth->execute($category) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	$sth->finish;

	$response = 'Department Removed';

    $template{'response'}  =   $response;
    my $output = parse("$global{'data'}/include/tpl/admin/general");

    print $output;

  }



 if ($section eq "saveeuser")
  {
     check_user();
     print "Content-type: text/html\n\n";
 
        $user    =  $q->param('uname');
	$name    =  $q->param('name');
	$email   =  $q->param('email');
	$url     =  $q->param('url');
	$company =  $q->param('company');
        $pass    =  $q->param('pass1');
        $pass2   =  $q->param('pass2');
    
  
     if ($pass1 && $pass2)
      {
    	   my @chars    =  (A..Z);
              $salt     =  $chars[rand(@chars)] . $chars[rand(@chars)];
    	      $password =   crypt($pass1, $salt);	
    
              $dbh->do(qq|UPDATE users SET password ="$password", rkey = "$salt" WHERE username = "$user"|); 
     }


	$statement = 'UPDATE users SET name = "' . "$name" . '", email = "' . "$email" . '", url = "' . "$url" . '", company = "' . "$company" . '" WHERE username = "' . "$user" . '";'; 
	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";

    $response = 'Saved <a href="admin.cgi?do=users">Users Main</a>';

   $template{'response'}        =   $response;

   my $output = parse("$global{'data'}/include/tpl/admin/general");

   print $output;

  }



if ($section eq "emailsettings")
 {

     check_user();
     print "Content-type: text/html\n\n";

	if (defined $q->param('address')) {

	my $address = $q->param('address');
	my $categor = $q->param('select');

    if ($categor && $address)
      {
	    	my $rv = $dbh->do(qq{INSERT INTO em_forwarders values (
	      		"$address", "$categor")}
	     	);
      }
	}
	if (defined $q->param('delete')) {
	$address = $q->param('email');
		$statementd = 'DELETE FROM em_forwarders WHERE address = ?'; 
		$sth = $dbh->prepare($statementd) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
		$sth->execute($address) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	$sth->finish;
	}

	
if (defined $q->param('reqreg')) {

	$reqreg = $q->param('reqreg');
	if ($reqreg eq "Yes") { $new = "1"; } else { $new = "0"; }
	$statement = 'UPDATE settings SET value  = ? WHERE setting = "ereqreg"'; 
	$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
	$sth->execute($new) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	$result = "<br><b><font color=red>Saved</font></b><br>";
	}

	$statement = 'SELECT * FROM em_forwarders'; 
	$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()) 
		{	
		$link = "$ref->{'address'}";
		chomp($link);
		$link =~ s/ /_/g;
		
 	$option .= '<form action="admin.cgi" method="post"><input type=hidden name=do value=emailsettings><table width="90%" border="0" cellspacing="1" cellpadding="0"><tr> 
    <td height="16" width="42%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><b>' . "$ref->{'address'}" . '</b></font></td>
    <td height="16" width="6%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">' . "<img src=$global{'imgbase'}/arrow.gif>" . '</font></td>
    <td height="16" width="32%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><b>' . "$ref->{'category'}" . '</b></font></td>
    <td height="16" width="20%"><div align="right"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><input type="hidden" name="email" value="' . "$ref->{'address'}" . '"><input type="Submit" style="font-size: 12px" name="delete" value="Delete"></font></div></td></tr></table></form>';

		}
	$sth->finish;


	$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()) {	
		if ($ref->{'value'} eq "0") { 
				$selected = '<option value="Yes">Yes</option><option value="No" selected>No</option>';
		 } else { 
                $selected = '<option value="Yes" selected>Yes</option><option value="No">No</option>';
		 }

	}
	$sth->finish;

	$statement = 'SELECT level FROM departments'; 
	$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()) {	
			$menu .= "<option value=\"$ref->{'level'}\">$ref->{'level'}</option>";

	}
	$sth->finish;


	if (!$result) { $result = ''; }


    $template{'directs'}    =   $option;
    $template{'selected'}   =   $selected;
    $template{'categories'} =   $menu;
    $template{'ifresult'}   =   $result;

    my $output = parse("$global{'data'}/include/tpl/admin/email");

    print $output;
}












 if ($section eq "deluser")
  {

     check_user();
     print "Content-type: text/html\n\n";

    $uusername =  $q->param('user');
    $confirm   =  $q->param('confirm');

	if ($confirm eq "yes") 
      {
			$page = "Username $uusername, completely deleted!";
			$statement = 'DELETE FROM users WHERE username = "' . "$uusername" . '"'; 
			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";
	  }  
	    else {
		         $page = '<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Are you sure you want to delete ' . "$uusername" . '? (Deleting this user will remove all their requests from the help desk.</font></p><p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><a href="admin.cgi?do=deluser&user=' . "$uusername" . '&confirm=yes">Yes, Im sure. Delete ' . "$uusername" . '</a></font></p>';
		     }
   
   $template{'username'} = $uusername;
   $template{'main'}    = $page;
 
   my $output = parse("$global{'data'}/include/tpl/admin/deluser");
   print $output;

  }


 if ($section eq "users")
  {

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

     check_user();
     print "Content-type: text/html\n\n";
 
     $sth = $dbh->prepare( "SELECT COUNT(*) FROM users" ) or die DBI->errstr;
     $sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
         my ( $count ) = $sth->fetchrow_array();
  
 
         $total = $count;

         $limit = "30";  # Results per page
      my $pages = ($total/$limit);
         $pages = ($pages+0.5);
      my $nume  = sprintf("%.0f",$pages);
         $page  = $q->param('page') || "0";
         $nume  = "1" if !$nume;
         $to    = ($limit * $page) if  $page;
         $to    = "0"              if !$page;

     $tpage     =  $page;
     $tpage     =  $tpage + 1;
     $location  =  $page;
     $location  =  $location + 1;
     $lboundary = "1" if $location < 4;
     $lboundary =  $location - 3  if !$lboundary;

     $nav .= qq|<font face=Verdana size=1>$nume Pagina(e): </font>|;

      if ($location + 2 < $nume) { $tboundary = 3 + $location; } else { $tboundary = $nume; }

      $string =  $ENV{'QUERY_STRING'};
      $string =~ s/&page=(.*)//g;        
      $prev   =  $page;
      $prev   =  $prev - 1;

      if ($nume > 1 && $tpage > 1 ) { $nav .= qq|<font face="verdana" size="1"><a href="admin.cgi?$string&page=0" alt="First Page">&laquo;</a> <a href="admin.cgi?$string&page=$prev" alt="First Page">&#139;</a> </font>|; }   
 
      foreach ($lboundary..$tboundary) 
          {       
             my $nu     =  $_ -1;
                 if ($nu eq $page) { $link = "[<b>$_</b>]"; } else { $link = "$_"; }          
                $nav   .= qq|<font face="verdana" size="1"><a href="admin.cgi?$string&page=$nu">$link</a> </font>|;
          }

      $next = $page;
      $next = $next + 1;
      $last = $nume;
      $last = $last - 1;

      if ($tpage < $nume && $tpage >= 1) { $nav .= qq|<font face="verdana" size="1"><a href="admin.cgi?$string&page=$next" alt="Next Page">&#155;</a> <a href="admin.cgi?$string&page=$last" alt="Next Page">&raquo;</a></font>|; }   


            $template{'nav'} = $nav;
         my $show  = $limit *  $page;

		$statement = 'SELECT * FROM users WHERE username != "admin" LIMIT ' . "$show, $limit"; 
		$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";
		$number=$show;
                $i = 1;
		while(my $ref = $sth->fetchrow_hashref()) {	
           my $user =  $ref->{'username'};
              $user =~ s/ /_/g;

 		 if ($i == "2") 
                   {
      			$bgcol = '#FFFFFF';
    			$i = 0;
     	 	   }
                  else {
			           $bgcol = '#F0F0F0';
             	  	}

        	$users .= qq|<table width="95%" border="0" cellspacing="1" cellpadding="5" align="center"> <tr bgcolor="$bgcol"><td width="22%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><a href="admin.cgi?do=viewuser&user=$user">$ref->{'username'}</a></font></td><td width="33%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">$ref->{'name'}</font></td><td width="45%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><a href="mailto:$ref->{'email'}">$ref->{'email'}</a></font></td></tr></table>|;
		$number++;			
                $i++
	}

   $template{'navbar'}    =   $bar;
   $template{'userlist'}  =   $users;

  my $too = $number;

  $template{'from'}  = $show;
  $template{'to'}    = $too;
  $template{'total'} = $count;

   my $output = parse("$global{'data'}/include/tpl/admin/userlist");
   print $output;

  }



 if ($section eq "staffactive")
  {
     check_user();
     print "Content-type: text/html\n\n";
 
    	$statement = 'SELECT * FROM staff WHERE username != "admin" ORDER BY callsclosed DESC LIMIT 10'; 
		$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()) {	
				
				$staff .= '<table width="75%" border="0" cellspacing="1" cellpadding="3" align="center"><tr bgcolor="#F0F0F0"> 
                  <td width="42%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">' . "$ref->{'name'}" . '</font></td>
                  <td colspan="2" bgcolor="#F0F0F0" width="58%"><div align="right"></div><div align="right"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><b>' . "$ref->{'callsclosed'}" . '</b> 
                  RICHIESTE CHIUSE</font></div></td></tr></table>';
				
			}

    $template{'navbar'}    = '';
    $template{'stafflist'} = $staff;

     my $output = parse("$global{'data'}/include/tpl/admin/staff");
     print $output;

  }



 if ($section eq "staff")
 {
     check_user();
     print "Content-type: text/html\n\n";

	$sth = $dbh->prepare( "SELECT COUNT(*) FROM staff" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
		my ( $count ) = $sth->fetchrow_array();
		if (!$ENV{'QUERY_STRING'}) { $pae = 0; }
 
	$showp = $pae*30;

  $i = 1;
	$statement = 'SELECT * FROM staff WHERE username != "admin"  LIMIT ?,30'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($showp) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) {	


	        $statement = 'SELECT * FROM staffactive WHERE username = ?'; 
		$sthb = $dbh->prepare($statement) or die print "Couldnt prepare statement: $DBI::errstr; stopped";
 		$sthb->execute($ref->{'username'}) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $refb = $sthb->fetchrow_hashref()) 
                  {	
				$time_last_active = $refb->{'date'};
		  }

	       $current_time = time();
	       $newtime =	$time_last_active + 900;

    		if ($newtime > $current_time) 
                    {
			        # Staff Member is online
			     	$status = "<img src=\"$global{'imgbase'}/online.gif\" width=\"6\" height=\"6\">";
		    } else {
		                 # Staff Member is offline
		               	$status = "<img src=\"$global{'imgbase'}/offline.gif\" width=\"6\" height=\"6\">";
		           }

 		 if ($i == "2") 
                   {
      			 $bgcol = '#FFFFFF';
    		  	 $i = 0;
     	 	   }
                  else {
			 $bgcol = '#F0F0F0';
             	       }

                        	$staff .= '<table width="100%" border="0" cellspacing="1" cellpadding="3" align="center"><tr bgcolor="' . "$bgcol" . '"><td width="4%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><div align="center">' . "$status" . '</div></font></td><td width="30%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif">' . "$ref->{'name'}" . '</font></td><td width="66%"> <font size="1" face="Verdana, Arial, Helvetica, sans-serif"><a href="admin.cgi?do=editstaff&user=' . "$ref->{'username'}" . '"></a></font><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr> <td width="6%"><img src="' . "$global{'imgbase'}" . '/profile.gif" width="16" height="16"></td><td width="20%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><a href="admin.cgi?do=editstaff&user=' . "$ref->{'username'}" . '">Profilo</a></font></td>
				<td width="6%"><img src="' . "$global{'imgbase'}" . '/answered.gif" width="14" height="10"></td><td width="31%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><a href="admin.cgi?do=staffcalls&user=' . "$ref->{'username'}" . '">Richieste Soddisfatte</a></font></td>
				<td width="6%"><img src="' . "$global{'imgbase'}" . '/perf.gif" width="15" height="15"></td><td width="31%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><a href="admin.cgi?do=staffperf&user=' . "$ref->{'username'}" . '">Prestazioni</a></font></td>
				</tr></table></td></tr></table>';
                      $i++;
 
	}

 
    $staff .= "<br><br><font size=1><img src=\"$global{'imgbase'}/online.gif\" width=\"7\" height=\"7\"> Attivo <img src=\"$global{'imgbase'}/offline.gif\" width=\"7\" height=\"7\"> Inattivo";

   $template{'navbar'}    = $bar;
   $template{'stafflist'} = $staff;

   my $output = parse("$global{'data'}/include/tpl/admin/staff");
   print $output;

 }


 if ($section eq "addstaff")
  {

     check_user();
     print "Content-type: text/html\n\n";

  	$statement = 'SELECT level FROM departments'; 
		$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 ($accesslevel =~ /$ref->{'level'}::/) 
                  {	
				        	$list .= "<input type=\"checkbox\" name=\"$ref->{'level'}\" value=\"yes\" checked> $ref->{'level'}<br>";
				  } else {
				         	$list .= "<input type=\"checkbox\" name=\"$ref->{'level'}\" value=\"yes\"> $ref->{'level'}<br>";
				         }
		push @list, $option;
		}

     if ($accesslevel =~ /GLOB::/) 
        {	
                   $list .= "<input type=\"checkbox\" name=\"glob\" value=\"yes\" checked> <b>Global Access</b>";
        } else {
                   $list .= "<input type=\"checkbox\" name=\"glob\" value=\"yes\"> <b>Global Access</b>";
               }
  
   $template{'category'}    = $list;
   my $output = parse("$global{'data'}/include/tpl/admin/addstaff");
   print $output;
 }



 if ($section eq "savestaff")
  {


     check_user();
     print "Content-type: text/html\n\n";
 
	$pass1    =   $q->param('pass1');
	$pass2    =   $q->param('pass2');
	$notinfy  =   $q->param('notify');
	$username =   $q->param('username');
	$name     =   $q->param('name');
	$email    =   $q->param('email');

	$statement = 'SELECT level FROM departments'; 
		$sth = $dbh->prepare($statement) or die print "Couldnt prepare statement: $DBI::errstr; stopped";
 		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
		{
	       if ($q->param($ref->{'level'}) eq "yes") {  $add = "$ref->{'level'}::"; push @area,$add;  }
		}

    if ($q->param('glob') eq "yes") {  $add = "GLOB::"; push @area,$add;  }
	
	die print "Passwords do not match" if $pass1 ne $pass2;

	if ($notinfy eq "yes") 	{	$notify = 1;	}
	else 	{		$notify = 0;	}


	my @chars = ("a..z","A..Z","0..9",'.','/');
	my $salt  = $chars[rand(@chars)] . $chars[rand(@chars)];


	$cdpass = crypt($pass1, $salt);

	 $rv = $dbh->do(qq{INSERT INTO staff values (
			"$username", "$cdpass", "$name", "$email", "@area", "$notify", "0", "0", "", "$salt")}
	 );
	 $rv = $dbh->do(qq{INSERT INTO stafflogin values (
	 		"$username", "Never")}
	 );
	 $rv = $dbh->do(qq{INSERT INTO staffactive values (
			"$username", "0")}
	 );
	 $rv = $dbh->do(qq{INSERT INTO staffread values (
			"$username", "0")}
 	 );

    $response = 'Il membro dello Staff è stato aggiunto.';

    $template{'response'} = $response;
    my $output = parse("$global{'data'}/include/tpl/admin/general");
    print $output;
 }





 if ($section eq "savetpl")
  {

     check_user();
     print "Content-type: text/html\n\n";
 
  		my $textfield = $q->param('textfield');
        my $vfile     = $q->param('file');

		open (FILE, ">$global{'data'}/include/tpl/$vfile") || ($response = "Error: $!");
			print FILE "$textfield";
		close (FILE);

		$response = qq|Grazie, $vfile Saved! <a href="admin.cgi?do=tpl">Ritorna ai Templates</a>| if !$response;

        $template{'response'} = $response;
        print parse("$global{'data'}/include/tpl/admin/general");
    }


 if ($section eq "staffperf")
  {
     check_user();
     print "Content-type: text/html\n\n";

    $user = $q->param('user');

    $template{'name'} = $user;

	$statemente = 'SELECT * FROM stafflogin WHERE username = ?'; 
		$sth = $dbh->prepare($statemente) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($user) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	while(my $ref = $sth->fetchrow_hashref()) 
	{	
		$lastlogin = $ref->{'date'};
	}
	$sth->finish;

	$statement = 'SELECT * FROM staff WHERE username = ?'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($user) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	while(my $ref = $sth->fetchrow_hashref()) 
	{	
    	$statement = 'SELECT * FROM staffactive WHERE username = ?'; 
		$sth2  = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth2->execute($ref->{'username'}) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		  while(my $ref2 = $sth2->fetchrow_hashref()) 
             {	
				$time_last_active = $ref2->{'date'};
             }
	$sth2->finish;

	 $current_time = time();
	 $newtime      = $time_last_active + 900;

 		if ($newtime > $current_time) 
             { 
                       # Staff Member is offline
			           $status = "<font color=green><b>ONLINE</b></font>";
		     } else {
              	       # Staff Member is online
				       $status = "<font color=red><b>OFFLINE</b></font>";
		     }

	$sth = $dbh->prepare('SELECT COUNT(*) FROM `calls` WHERE closedby = ?' ) or die DBI->errstr;
	$sth->execute($ref->{'username'}) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	 $closed = $sth->fetchrow_array();
	$sth->finish;

	$tsec = $ref->{'responsetime'};

 if ($closed > 0) {
 
     $sec = ($tsec/$closed);	
     $days    = int($sec/(24*60*60));
     $hours   = ($sec/(60*60))%24;
     $mins    = ($sec/60)%60;
     $secs    = $sec%60;
     $restime = "$hours hr(s) $mins min(s) $secs seconds";
 
 } else {
           $restime = "Nessuna richiesta chiusa";
        }

   $template{'name'}        = $ref->{'name'};
   $template{'lastlogin'}   = $lastlogin;
   $template{'status'}      = $status;
   $template{'callsclosed'} = $closed;
   $template{'avgtime'}     = $restime;

   my $output = parse("$global{'data'}/include/tpl/admin/staffperf");
   print $output;
}
  }



 if ($section eq "sendstaff")
  {

     check_user();
     print "Content-type: text/html\n\n";

	$email   = $q->param('email');
	$subject = $q->param('subject');
	$message = $q->param('message'); 

	$statement = 'SELECT * FROM staff'; 
		$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 ($enablemail) {
		open(MAIL, "|$global{'sendmail'} -t") || print "Unable to send mail: $!";
			print MAIL "To: $ref->{'email'}\n";
			print MAIL "From: $email\n";
			print MAIL "Subject: $subject\n\n";
			print MAIL "$message \n";
		close(MAIL); 
      }
	}
	$response = 'Inviato! <a href="admin.cgi?do=staff">Torna alla Pagina dello Staff</a>';

     $template{'response'}     = $response;
     my $output = parse("$global{'data'}/include/tpl/admin/general");
     print $output;
  }


 
 if ($section eq "editstaff")
  {

     check_user();
     print "Content-type: text/html\n\n";

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

	$statement = 'SELECT * FROM staff WHERE username = ?'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($user) or die print "Couldn't execute statement: $DBI::errstr; stopped";
		while(my $ref = $sth->fetchrow_hashref()) 
		{
			$sname     =  $ref->{'name'};
			$suser     =  $ref->{'username'};
			$semail    =  $ref->{'email'};
			$notif     =  $ref->{'notify'};
			$assigned  =  $ref->{'access'};
		}

	$statement = 'SELECT level FROM departments'; 
		$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 ($assigned =~ /$ref->{'level'}::/) 
                  {	
			          		$list .= "<input type=\"checkbox\" name=\"$ref->{'level'}\" value=\"yes\" checked> $ref->{'level'}<br>";
			      } else {
			         		$list .= "<input type=\"checkbox\" name=\"$ref->{'level'}\" value=\"yes\"> $ref->{'level'}<br>";
			             }
		 }

       if ($assigned =~ /GLOB::/) 
             {	
                            $list .= "<input type=\"checkbox\" name=\"glob\" value=\"yes\" checked> <b>Global Access</b>";
             } else {
                            $list .= "<input type=\"checkbox\" name=\"glob\" value=\"yes\"> <b>Global Access</b>";
                    }


       if ($notif eq "1") 	
           {
                           $box ='<input type="checkbox" name="notify" value="yes" checked>';
           } else {
                           $box = '<input type="checkbox" name="notify" value="yes">';
                  }

   $template{'notify'}    = $box;
   $template{'sname'}      = $sname;
   $template{'user'}      = $suser;
   $template{'semail'}     = $semail;
   $template{'category'}  = $list;

   print parse("$global{'data'}/include/tpl/admin/editstaff");
  
  }



 if ($section eq "saveeditstaff")
  {

     check_user();
     print "Content-type: text/html\n\n";

    $user     = $q->param('user');
	$notinput = $q->param('notify');

	if ($notinput eq "yes") {
                                		$notify = 1;
                         	} else 	{ 
                                		$notify = 0;
                                  	}
	$name  = $q->param('name');
	$email = $q->param('email'); 

    my (@area);

	$statement = 'SELECT level FROM departments'; 
		$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 ($q->param($ref->{'level'}) eq "yes") {  $add = "$ref->{'level'}::"; push @area,$add;  }
		}

    if ($q->param('glob') eq "yes") {  $add = "GLOB::"; push @area,$add;  }

	$statement = 'UPDATE staff SET name = "' . "$name" . '", email = "' . "$email" . '", notify = "' . "$notify" . '", access = "' . "@area" . '" WHERE username = "' . "$user" . '"'; 
		$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()) {	
		}
	$response = 'Salvato! <a href="admin.cgi?do=staff">Torna alla Pagina dello Staff</a>';

    $template{'response'}  = $response;
    my $output = parse("$global{'data'}/include/tpl/admin/general");
    print $output;

  }
 

 if ($section eq "delstaff")
  {

     check_user();
     print "Content-type: text/html\n\n";

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

    $response = '<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Sei sicuro di voler eliminare ' . "$user" . '? (Questo membro dello Staff sarà rimosso completamente dall\' help desk.</font></p><p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><a href="admin.cgi?do=cdel&user=' . "$user" . '">Elimina ' . "$user" . '</a></font></p>';
    $template{'response'}  = $response;
    my $output = parse("$global{'data'}/include/tpl/admin/general");
    print $output;

  }


 if ($section eq "cdel")
  {

     check_user();
     print "Content-type: text/html\n\n";

    $user = $q->param('user');
	$statement = 'DELETE FROM staff WHERE username = ?'; 
		$sth = $dbh->prepare($statement) or die print "Couldn't prepare statement: $DBI::errstr; stopped";
 		$sth->execute($user) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	$response = "<font size=2>$user" . ' Eliminato! <a href="admin.cgi?do=staff">Torna alla Pagina dello Staff</a>';

      $template{'response'}  = $response;
   my $output = parse("$global{'data'}/include/tpl/admin/general");
   print $output;

  }




 if ($section eq "staffcalls")
  {

     check_user();
     print "Content-type: text/html\n\n";

     $user = $q->param('user');

   	$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE status = \"CLOSED\" AND closedby = ? ORDER BY id" ) or die DBI->errstr;	
	$sth->execute($user) or die print "Couldn't execute statement: $DBI::errstr; stopped";
	my ( $count ) = $sth->fetchrow_array();
	if ($ENV{'QUERY_STRING'} !~ /show/) { $pae = 0; }

	$showp = $pae*30;

	$statement = "SELECT * FROM `calls` WHERE status = \"CLOSED\" AND closedby = \"$user\" ORDER BY id LIMIT $showp,30\;"; 
		$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";
		$number=0;
		  while(my $ref = $sth->fetchrow_hashref()) 
			{	
			$number++;
			$subject="$ref->{'subject'}"; 
			$subject=substr($subject,0,20).'..' if length($subject) > 22;
			if ($ref->{'priority'} == "1") { $font = '#990000'; } else { $font = '#000000'; }

     			if ($ref->{'method'}  eq "cc") { $img   = "phone.gif";     } elsif ($ref->{'method'} eq "em") { $img = "mail.gif"; } else { $img = "ticket.gif"; }


            $calls .= display_ticket($ref->{'id'}, $ref->{'username'}, $ref->{'category'}, $ref->{'status'}, $ref->{'time'});
   		  }
		if (!$calls) 
		{
				$calls = '<font face=Verdana size=2><b>0 Richieste</b></font>';
		}

      $template{'viewtickets'}  = $calls;
      $template{'user'}  = $user;
   my $output = parse("$global{'data'}/include/tpl/admin/staffview");
   print $output;

 }


 if ($section eq "listcalls")
  {

       check_user();  
       print "Content-type: text/html\n\n";
     
      $status = $q->param('status');
      $type   = $status;

       if (defined $q->param('sort')) {  $sort = $q->param('sort');  }
       else { $sort = "id"; }

       if (defined $q->param('method')) { 
          if ($q->param('method') eq "asc") { $method = "ASC"; } else { $method = "DESC"; } 
       }
      else { $method = "ASC"; }

     if ($status eq "open") 
       {
 	      	$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE status != \"CLOSED\"" ) or die DBI->errstr;
       } else 
         {
 	        $sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE status = \"CLOSED\"" ) or die DBI->errstr;	
         }

        $sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
      	my ( $total ) = $sth->fetchrow_array();


         $limit = "30";  # Results per page
      my $pages = ($total/$limit);
         $pages = ($pages+0.5);
      my $nume  = sprintf("%.0f",$pages);
         $page  = $q->param('page') || "0";
         $nume  = "1" if !$nume;
         $to    = ($limit * $page) if  $page;
         $to    = "0"              if !$page;

     $tpage     =  $page;
     $tpage     =  $tpage + 1;
     $location  =  $page;
     $location  =  $location + 1;
     $lboundary = "1" if $location < 4;
     $lboundary =  $location - 3  if !$lboundary;

     $nav .= qq|<font face=Verdana size=1>$nume Pagina(e): </font>|;

      if ($location + 2 < $nume) { $tboundary = 3 + $location; } else { $tboundary = $nume; }

      $string =  $ENV{'QUERY_STRING'};
      $string =~ s/&page=(.*)//g;        
      $prev   =  $page;
      $prev   =  $prev - 1;

      if ($nume > 1 && $tpage > 1 ) { $nav .= qq|<font face="verdana" size="1"><a href="admin.cgi?$string&page=0" alt="First Page">&laquo;</a> <a href="admin.cgi?$string&page=$prev" alt="First Page">&#139;</a> </font>|; }   
 
      foreach ($lboundary..$tboundary) 
          {       
             my $nu     =  $_ -1;
                 if ($nu eq $page) { $link = "[<b>$_</b>]"; } else { $link = "$_"; }          
                $nav   .= qq|<font face="verdana" size="1"><a href="admin.cgi?$string&page=$nu">$link</a> </font>|;
          }

      $next = $page;
      $next = $next + 1;
      $last = $nume;
      $last = $last - 1;

      if ($tpage < $nume && $tpage >= 1) { $nav .= qq|<font face="verdana" size="1"><a href="admin.cgi?$string&page=$next" alt="Next Page">&#155;</a> <a href="admin.cgi?$string&page=$last" alt="Next Page">&raquo;</a></font>|; }   


            $template{'nav'} = $nav;
         my $show  = $limit *  $page;


    if ($status eq "open") 
     { 
              	$statement = 'SELECT * FROM `calls` WHERE status != "' . "CLOSED" . '" ORDER BY ' . "$sort $method LIMIT $show, $limit"; 
     }
      else {
            	$statement = "SELECT * FROM `calls` WHERE status = \"CLOSED\" ORDER BY $sort $method LIMIT $show,$limit"; 
           }
   
 	$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";
		$number=0;
 	    while($ref = $sth->fetchrow_hashref()) 
         {	
			$number++;
     		$subject = "$ref->{'subject'}"; 
			$subject = substr($subject,0,20).'..' if length($subject) > 22;

			$font   = '#000000';

     			if ($ref->{'method'}  eq "cc") { $img   = "phone.gif";     } elsif ($ref->{'method'} eq "em") { $img = "mail.gif"; } else { $img = "ticket.gif"; }
    			if ($ref->{'priority'} eq "1") { $color = $global{'pri1'}; } 
     			if ($ref->{'priority'} eq "2") { $color = $global{'pri2'}; } 
    			if ($ref->{'priority'} eq "3") { $color = $global{'pri3'}; } 
    			if ($ref->{'priority'} eq "4") { $color = $global{'pri4'}; } 
    			if ($ref->{'priority'} eq "5") { $color = $global{'pri5'}; } 

            $current_time = time();
            $difference = $current_time - $ref->{'track'};

            if ($difference >= 86400) 
               {
                   $period = "day";
                   $count = $difference / 86400;
               } 
            elsif ($difference >= 3600) 
               {
                   $period = "hour";
                   $count = $difference / 3600;
               }
            elsif ($difference >= 60)  
               {
                   $period = "minute";
                   $count = $difference / 60;
               }
            else {
                     $period = "second";
                     $count = $difference;
                 }

            $count = sprintf("%.0f", $count);

            if ($count != 1) { $period .= "s"; }
            $period .= " Ago";

            if ($ref->{'ownership'} eq $Cookies{'staff'}) { $otag = "<b>"; $ctag = "</b>"; } else { $otag = ''; $ctag=''; }

            $opencalls .= display_ticket($ref->{'id'}, $ref->{'username'}, $ref->{'category'}, $ref->{'status'}, $ref->{'time'});

     	 }
		
		$opencalls = '<font face=Verdana size=2><b>0 Richieste</b></font>' if !$opencalls;
		
        $template{'listcalls'}  = $opencalls;
        $template{'navbar'}     = $bar;
        $template{'type'}       = $status;
 
      my $output = parse("$global{'data'}/include/tpl/admin/listcalls");
      print $output;
  }


 if ($section eq "stats")
   {
  
       check_user();  
       print "Content-type: text/html\n\n";
     
     my ($sth);

		$sth = $dbh->prepare( "SELECT COUNT(*) FROM staff WHERE username != \"admin\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
			my ( $staff ) = $sth->fetchrow_array();
        $sth->finish;

		$sth = $dbh->prepare( "SELECT COUNT(*) FROM users" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
			my ( $users ) = $sth->fetchrow_array();
        $sth->finish;

		$sth = $dbh->prepare( "SELECT COUNT(*) FROM calls" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
			my ( $calls ) = $sth->fetchrow_array();
        $sth->finish;

		$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE status = \"OPEN\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
			my ( $open ) = $sth->fetchrow_array();
        $sth->finish;

		$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE status = \"HOLD\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
			my ( $hold ) = $sth->fetchrow_array();
        $sth->finish;

		$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE status = \"CLOSED\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
			my ( $tclosed ) = $sth->fetchrow_array();
        $sth->finish;

		$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE method = \"em\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
			my ( $em ) = $sth->fetchrow_array();
        $sth->finish;	

		$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE method = \"cc\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
			my ( $cc ) = $sth->fetchrow_array();
        $sth->finish;

		$sth = $dbh->prepare( "SELECT COUNT(*) FROM `calls` WHERE method = \"hd\"" ) or die DBI->errstr;
		$sth->execute() or die print "Couldn't execute statement: $DBI::errstr; stopped";
 			my ( $hd ) = $sth->fetchrow_array();
        $sth->finish;


       $statemente = 'SELECT value FROM settings WHERE setting = "ssi_closed"'; 
       $sth = $dbh->prepare($statemente) 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())  
             {
           		$closed = $ref->{'value'};
             }
       $sth->finish;

       $statement = 'SELECT value FROM settings WHERE setting = "avgtime"'; 
       $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()) 
            {	
                $tsec = $ref->{'value'};
            }
       $sth->finish;

       if ($closed > 0) 
        {
            $sec      =  ($tsec/$closed);
            $days     =  int($sec/(24*60*60));
            $hours    =  ($sec/(60*60))%24;
            $mins     =  ($sec/60)%60;
            $secs     =  $sec%60;
            $restime  =  "$hours hr(s) $mins min(s) $secs seconds";
        } else {
                  $restime = "Nessuna Richiesta Chiusa";
               }

      $template{'ud'}            =   $hd;
      $template{'em'}            =   $em;
      $template{'cc'}            =   $cc;
      $template{'avgresponse'}   =   $restime;
      $template{'open'}          =   $open;
      $template{'hold'}          =   $hold;
      $template{'closed'}        =   $tclosed;
      $template{'calls'}         =   $calls;
      $template{'users'}         =   $users;
      $template{'staff'}         =   $staff;

      print parse("$global{'data'}/include/tpl/admin/stats");
   
 } 
 



 }


sub display_ticket 
 {
    my ($id, $username, $category, $status, $date) = @_;
    my $ticket = qq| <table width="100%" border="0" cellpadding="5" cellspacing="1"><tr bgcolor="#F1F1F8"><td width="3%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><img src="$global{'imgbase'}/$img"></font></td>
                     <td width="6%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif" color=$font>$otag <div align="center">$id</div>  $ctag</font></td>
                     <td width="17%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif" color=$font>$otag $username $ctag</font></td><td width="25%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif" color=$font><a href="admin.cgi?do=ticket&cid=$id">$otag $subject $ctag</a></font></td>
                     <td width="22%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif" color=$font>$otag $category $ctag</font></td><td width="8%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif" color=$font>$otag <div align="center">$status</div> $ctag</font></td><td width="19%"><font size="1" face="Verdana, Arial, Helvetica, sans-serif" color=$font>$otag $date $ctag</font></td>
                     </tr></table>
                   |;
    return $ticket;
 }







1;
