#!/usr/bin/perl
#!c:/Perl/bin/Perl.exe

# swap the first line and second line if the script runs on UNIX System

###############################################
###                                                                                  
###     (c) 2012, John Jan Popovic, All Rights Reserved    http://1stmuse.com
###                                         
###                                                                                 
###     This script may be used and modified freely
###     as long as this message remains intact.
# (C)2003      1st Muse
#              www.1stmuse.com
# Author       John J. Popovic
#              v3.0 Aug  9,  2003      
#              v4.0 Feb  13, 2008                                                                          
###############################################                                        

BEGIN {
    my $b__dir = (-d '/home/loyaltyh/perl'?'/home/loyaltyh/perl':( getpwuid($>) )[7].'/perl');
    unshift @INC,$b__dir.'5/lib/perl5',$b__dir.'5/lib/perl5/x86_64-linux-thread-multi',map { $b__dir . $_ } @INC;
}


use CGI qw (:standard);
use CGI::Carp qw(fatalsToBrowser);
use lib qw(.);
use CGI qw(nph);

$js_path = 'http://1stmuse.com/resources';

my $q = new CGI;

$script_name ="$ENV{'SCRIPT_NAME'}";


# sendmail setup
$SENDMAIL = "/usr/sbin/sendmail -t";
$FROM = "fido2_News <info\@1stmuse.com>";
$REPLY_TO = "fido2_News <info\@1stmuse.com>";

# access control
$ACCESS_CONTROL = 1; # set to 0 to turn off if you're using .htaccess

# templates
$TEMPLATE_ADD_PAGE    = $INSTDIR."/mailing_templates/add.html";
$TEMPLATE_ENTER_PAGE  = $INSTDIR."/mailing_templates/enter.html";
$TEMPLATE_REMOVE_PAGE = $INSTDIR."/mailing_templates/remove.html";
$TEMPLATE_ERROR_PAGE  = $INSTDIR."/mailing_templates/error.html";
$TEMPLATE_ENTER_MAIL  = $INSTDIR."/mailing_templates/entermail.txt";
$ENTERMAIL_SUBJECT    = "fido2 NEWS - Richiesta d'iscrizione";
$TEMPLATE_ADD_MAIL    = $INSTDIR."/mailing_templates/addmail.txt";
$ADDMAIL_SUBJECT      = "fido2 NEWS - Iscrizione confermata ";


### Specify NEWSLETTER_database fields in the array below 

@fields = 
( 
"NEWSLETTER_subject",
"NEWSLETTER_body",
);









### Set URL and email fields to be hyperlinks 
### The number used corresponds to its placement in the array above 
### Remeber to start your count at zero
### Leave the variables empty to remove the hyperlink
# $index_of_image_url = "17";
# $index2_of_image_url= "18";
$index_of_email = "15";
$index_of_URL = "16";	  
$homedir = $ENV{'DOCUMENT_ROOT'};
### Specify the required fields below. This may be left empty 
@required = ();

### Specify the filtered words below.  This may be left empty 
@filter = ("word1","word2");
$database = "$ENV{'DOCUMENT_ROOT'}/fido2/fido2_newsletters.txt";	# Data file OPERE name and path
$MAILING_LIST = "$ENV{'DOCUMENT_ROOT'}/fido2/fido2_mailinglist.txt";
$user_file   = "$ENV{'DOCUMENT_ROOT'}/fido2/users.txt";			   # User file name and path

# installation location
$INSTDIR = "$ENV{'DOCUMENT_ROOT'}/cgi-bin/";
$INSTURL = "http://1stmuse.com/cgi-bin/";

$db_name     = "Newsletter Mailer ... Constellation Systems";	   	   # The database name
$table_width = "90%";		       # The display width of the entire table
$record_width = "80%";			   # The display width of the database records
$max_rows_returned = "20";	   # Max number of rows displayed per page
$filter_html_tags = "no";		   # Removes HTML tags from record entries
$check_user_duplicates = "yes";		   # Checks for duplicate user names in user file
@extra_user_fields = ("Email");	   	   # Additional info needed when registering users
$use_external_html = "no";		   # Set to "yes" to use your own html template
$external_html_header = "header.html";     # File name and path to html template header
$external_html_footer = "footer.html";	   # File name and path to html template footer
$authenticate = "yes";	  # Prompts users for a user name and password
$register	= "yes";		    # Allows new user registration
$record_ownership = "no"; # Users can modify/delete only their records
$admin_user_name = "admin";		   # This is the default Administrator user name
$default_user_permission_search = "yes";   # Gives newly registered users Search permission
$default_user_permission_add = "yes";	   # Gives newly registered users Add permission
$default_user_permission_modify = "no";    # Gives newly registered users Modify permission
$default_user_permission_delete = "no";    # Gives newly registered users Delete permission
$defult_search_index = "0";


###############################################
###            Change Nothing Below This Line                 
###############################################


############## Global Viariables ##################


$field_count = @fields;
$colspan = $field_count+1;
$EXCLUSIVE = 2;
$UNLOCK    = 8;
$user = $q->param(user);
$user   = $q->cookie(user) if($user eq "");
$user_search = $q->param(user_search);
$user_search = "yes" if($authenticate eq "no");
$user_add = $q->param(user_add);
$user_add = "yes" if($authenticate eq "no");
$user_trans = $q->param(user_trans);
$user_trans = "yes" if($authenticate eq "no");
$user_modify = $q->param(user_modify);
$user_modify = "yes" if($authenticate eq "no");
$user_delete = $q->param(user_delete);
$user_delete = "yes" if($authenticate eq "no");
$selected_user = $q->param(selected_user);
$admin_add    = $q->param(admin_add);
$sort         = $q->param(sort_on);
$search_for   = $q->param(search_for);
$Supply       = $q->param(Supply);
$search_field = $q->param(search_field);
$action       = $q->param(action);
$display      = $q->param(display);
@keys         = $q->param(key);
$key          = $q->param(key);
$key_matches  = @keys;
$search_field = "all" if($search_field eq "");
$search_for   = '.'   if ($search_for eq "");
$action = $q->param(which_search) if($action =~ /^View/i);
$find_           = $q->param(find_);
$id_             = $q->param(id_);
$filter_         = $q->param(filter_);
$search_field_   = $q->param(search_field_);
################# Main Logic ##################
if($q->param('operation') eq 'opere')  { $action='opere'};
if($q->param('operation') eq 'logout') { $action='logout'};
if($q->param('operation') eq 'main_menu')  { $action='Main Menu'};
if($q->param('operation') eq 'search')  { $action='search'};
########



########
if($action =~ /add administrator/i){ &add_user; exit;}
if ($authenticate eq "yes"){ unless (-e $user_file){ $title="Set Administrative Password"; &create_admin; } }
if($register eq "yes" && $action =~ /register/i){ &register; exit;}
if($action =~ /add user/i){ &add_user; exit;}
if($action =~ /submit login/i){ &authenticate; exit;}
if ($authenticate eq "yes" && $user eq ""){ &login; exit;}
if($action =~ /logout/i){ &logout; exit;}

if($authenticate eq "yes"){
# the following operations can be performed, only if AUTHENTICATION IS VALID
	if($q->param('operation') eq 'search')
	  { 
	    $action='search';
	    my $buffer;
	    my $id = 0;
	    my $filter_ = $q->param('filter_');
	    my $find_   = $q->param('find_');
	    my $search_field_   = $q->param('search_field_');
	    my $id_     = $q->param('id_');
	    my $user_   = $q->param('user_');
	    $search_for = $find_;
	    $user=$user_;
	    $search_field = $search_field_;
#	    $id = 12345;
	}

	if($q->param('operation') eq 'email_search_')
	  { 
	    $action='email_search_';
	    my $buffer;
	    my $id = 0;
	    my $filter_ = $q->param('filter_');
	    my $find_   = $q->param('find_');
	    my $search_field_   = $q->param('search_field_');
	    my $id_     = $q->param('id_');
	    my $user_   = $q->param('user_');
	    $search_for = $find_;
	    $user=$user_;
	    $search_field = $search_field_;
#	    $id = 12345;
	}


	if($q->param('operation') eq 'main_menu')
	  { 
	    $action='main_menu';
	    my $buffer;
	    my $user_   = $q->param('user_');
	    $search_for = $find_;
	    $user=$user_;
	}
	
	if($q->param('operation') eq 'send_newsletter')
  {
  	$action='send_newsletter';
	}
	
	if($action =~ /nuovo/i){ &print_add_screen;}
	elsif($action =~ /add this record/i){ &add_record; $message="Record Added"; $title="Main Menu"; &print_default($title, $message);}
	elsif($action =~ /conferma opera/i){ &add_record; $message="Record Added"; $title="Main Menu"; &print_default($title, $message);}
	
	elsif($action =~ /opere/i){ $title="opere"; &print_default($title,$message); }
	
	elsif($action =~ /create_newsletter/i){$title="create_newsletter"; &create_newsletter_page($title,$message); }
	elsif($action =~ /send_newsletter/i){$title="send_newsletter"; &broadcast_newsletter($title,$message); }
	
	elsif($action =~ /salva_scheda/i){ &add_record; $message="Newsletter added to archive"; $title="Main Menu"; &print_default($title, $message);}
  
	elsif($action =~ /modify record/i){ $title="Modification Error"; $error_message="You forgot to select a record to modify!"; &access_problem if($key < 1); &search_db($key);  &print_modify_page;}
	elsif($action =~ /modifica_opera/i){ $title="Modification Error"; $error_message="You forgot to select a record to modify!"; &access_problem if($key < 1); &search_db($key);  &print_modify_page;}
	elsif($action =~ /modify this record/i){ $title="Modify"; &delete_records; $key=$keys[0]; &add_record; &print_default($title, $message);}
	elsif($action =~ /conferma_modifica/i){ $title="Modify"; &delete_records; $key=$keys[0]; &add_record; &print_default($title, $message);}
	elsif($action =~ /delete record/i){ $title="Delete Record"; $error_message="You forgot to select a record to delete!"; &access_problem if($key < 1); &delete_records; $message="Record Deleted"; $title="Main Menu"; &print_default($title, $message);}
	elsif($action =~ /modify/i){ &search_db($search_for); $title="Modify Which Record?"; $button_text="Modify Record"; $choose="modify"; &search_results;}
	elsif($action =~ /avanti/i){ &search_db($search_for); $title="Modify Which Record?"; $button_text="Modify Record"; $choose="modify"; &search_results;}
	elsif($action =~ /delete/i){ &search_db($search_for); $title="Delete Which Record?"; $button_text="Elimina scheda"; $choose="delete"; &search_results;}
	elsif($action =~ /search/i){ &search_db($search_for); $title="Main menu"; $button_text = "";  $choose="search"; $what="search"; &search_results;}
	elsif($action =~ /email_search_/i){ &search_db($search_for); $title="Main menu"; $button_text = "";  $choose="email_search_"; $what="email_search_"; &search_email_results;}
	elsif($action =~ /user manager/i){ $title="User Manager"; &user_manager;}
	elsif($action =~ /create new user/i){ $title="User Manager - Create New User"; $perform="add"; $button_text ="Add User"; &edit_user;}
	elsif($action =~ /edit selected user/i){ $title="User Manager - Edit Selected User"; $perform="edit"; $button_text ="Edit User"; &edit_user;}
	elsif($action =~ /edit user/i){ $old_password = $q->param(old_password); &delete_user; $perform="edit"; &add_user;}
	elsif($action =~ /remove selected user/i){ $perform="delete"; &delete_user; $title="User Manager"; &user_manager;}
	else { $title="Main Menu"; &print_default($title); }
}

exit;

################# Add Record ##################

sub add_record {
  foreach $required (@required){
  if($q->param($required) eq "") { 
  $title = "Add A Record"; $error_message = "You did not fill out the required information!"; &access_problem($error_message); exit; } }
  $when_added = &get_date;
  $key   = time();
  $record=$key;
  $record  .= "\|$user";
  $record  .= "\|$when_added";
  foreach $field (@fields){ ${$field}  = $q->param($field); ${$field}  = filter(${$field}); $record  .= "\|${$field}"; }
   unless (-e $database){ open (DB, ">$database") || die "Error creating database a.  $!\n"; }
   else { open (DB, ">>$database") || die "Error opening database.  $!\n"; }
   flock DB, $EXCLUSIVE;
   seek DB, 0, 2;
   print DB "$record\n";
   flock DB, $UNLOCK;
  close(DB);
} # End of add_record subroutine.






############## Delete Records #################

sub delete_records
  {              
  open (DATABASE, "$database") or die "Error opening file: $!\n";
  while (<DATABASE>)
    {
    $line = $_;
    chop $line;
    @dbfields = split (/\|/, $line);
    $deleted = "no";
    if ($dbfields[0] eq $q->param(key)) { $deleted = "yes"; if ($user eq $dbfields[1]) { $security_satisfied = "yes"; } }
    elsif ($deleted ne "yes") { $new_data .= "$line\n"; }
    } #end of while
  close (DATABASE);
  if ($authenticate ne "yes") { $security_satisfied = "yes"; }
  if ($security_satisfied ne "yes" && $record_ownership eq "yes" && $admin_user_name ne "$user")
    {
    $error_message = "Lei non ha le permessi necessari per l\92accesso a questa scheda!";
    &access_problem($error_message);
    exit;
    }  else  {
    flock DATABASE, $EXCLUSIVE;
    open (DATABASE, ">$database") or die "Error opening file: $!\n";
    print DATABASE "$new_data";
    close (DATABASE);
    flock DATABASE, $UNLOCK;
    }
  } 






############# Results Screen ################
sub search_results{
&html_header($title);
  $rows_left_to_view = $total_row_count - $new_hits_seen;
  $start_hit = $hits_seen + 1;
  $end_hit = $new_hits_seen;
  $hits_displayed = $end_hit - $start_hit + 1;
  if ($total_row_count > 1) {
    print qq~<P>Found: <B>$total_row_count</B> records<BR>~;
    if ($total_row_count > $max_rows_returned) {
      if ($hits_displayed == 2) {  print qq~<B>Last two</B> records shown below<BR>~;  }
      elsif ($hits_displayed == 1) {  print qq~<B>Last</B> record shown below<BR>~;  }
      else { print qq~In questa pagina: <B>$start_hit</B> - <B>$end_hit</B><BR>~;  }
    } #end if
  } #end if ... > 1
  else { print qq~<P>Found: <B>1</B> record\n~; }


############### PRINT BUTTON which_search #######

$cerca = $search_for;
print "<br>";
if ($button_text ne "")
{ 
   if ($button_text eq "Modify Record") {
     print "<INPUT TYPE=button  onClick=\"myForm.action.value='nuovo';this.form.submit(  );\"  VALUE=\"Nuovo\" >";
  };
}

$which_search = $choose;

############### next page buttons 
&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";

############### end PRINT BUTTON which_search #######

if($display =~/columns/i) {
 print<<HTML;
	<p><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
    <TR BGCOLOR="#e0e0e0">
HTML

if($user eq "admin"){
  print "
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit(  );\"  VALUE=\"Elimina Scheda\" >
  ";
}
  if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit(  );\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='nuovo';this.form.submit(  );\" VALUE=\"aggiungere scheda\" >
</TD></TR>\n";
  }

  foreach $field (@fields){
    print "<TD ALIGN=CENTER><B>\u$field</B></TD>\n";
  } # End of foreach


  print "</TR>";
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 
    print "<TR BGCOLOR=\"#efefef\">\n";
if($user eq "admin"){
  print "
     <INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit(  );\"  VALUE=\"Elimina Scheda\" >
  ";
}
    if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit(  );\"  VALUE=\"Modify Record\" >
</TD></TR>\n";
    } # End of if.
      for($x=0;$x<$field_count;$x++){
      $item = &check_item($field_vals[$x], $x);
      print "<TD>$item</TD>\n";
    }
     print "</TR> ";
  } # End of foreach loop.
  print<<HTML;
</TR></TABLE>
HTML
} else {
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 
### intervention
print<<HTML;
	<P><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
HTML

  $x=0;
  foreach $field (@fields){
  $item = &check_item($field_vals[$x], $x);
$collon_cr = "\;<br>";

# color fields
$background_color="#e0e0e0";
$line= "<TD BGCOLOR='#efefef' WIDTH=100%>$item</TD>";
if ($x > 7) {$background_color='#B6DB91'; $line= "<TD BGCOLOR='#D5FFD5' WIDTH=100%>$item</TD>" };
if ($x > 19) {$background_color='#dcb691'; $line= "<TD BGCOLOR='#ffd5D5' WIDTH=100%>$item</TD>" };
if ($x > 22) {$background_color='#dcec91'; $line= "<TD BGCOLOR='#dcecD5' WIDTH=100%>$item</TD>"};
if ($x > 24) {$background_color='#b6b691'; $line= "<TD BGCOLOR='#ffffD5' WIDTH=100%>$item</TD>"};

# end of color fields

$campo = $field;

if ($x < 7) { 
print<<HTML;
     <TR>
      <TD BGCOLOR=$background_color><B>\u$campo</B></TD>
      $line
     </TR>
HTML
};


   $x++;
 	 } # End of foreach field loop.
######## buttons on the end of record
  if($choose =~ /(modify|delete|search)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2> ";

if($user eq "admin"){
  print "<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit(  );\"  VALUE=\"Delete\" >
  ";
}
    print "<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='modifica_opera';this.form.submit(  );\"  VALUE=\"Edit and Broadcast\" >";

};

######## end of buttons 
  print "</TABLE><P>";

  } # End of foreach record loop.

### intervention

} # End of if display loop

if ($button_text ne "")
{ 
  if ($button_text eq "Modify Record") {
     print " <INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit(  );\"  VALUE=\"nuovo\" >";
  };
}

$which_search = $choose;
############### next page buttons 
&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_field\" VALUE=\"$search_field\">\n";
print "<p>";
if ($s_somma_costo_a_noi > 0.) { $s_profit_percentage = 100*(($s_somma_importo / $s_somma_costo_a_noi) - 1.0);};
$s_profit_percentage = sprintf("%4.2f",$s_profit_percentage);
$cerca_t=$cerca;
if ($cerca eq '.') {$cerca_t='all'};

&html_footer;
} # End of search_results subroutine.



################ Default Screen ##################
sub print_default {
### intervention
$i_analisi =0;
if ($action eq 'Avanti') { &print_add_screen;exit;};
&html_header;
 print<<HTML;
  <TABLE BORDER=0 CELLSPACING="0" CELLPADDING="3"><TR><TD COLSPAN=3>
  <TR><TD width="210"><B>Search:</B><BR>
<INPUT TYPE="text" NAME="search_for" SIZE="35" 
onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
           {myForm.action.value='search';this.form.submit(  );return false;} 
else return true;" ></TD>
          <TD width="234"></TD>
        
        </TR>
<TR>
    <TD><B>in:</B><BR>
    <SELECT NAME="search_field">
    <OPTION VALUE="all">all 

     <OPTION VALUE=0 >Title
     <OPTION VALUE=1 >Content

     </SELECT></TD><TD>
     
     <B>Sort by:</B><BR>
     <SELECT NAME="sort_on">
     <OPTION VALUE=0 >Title
     <OPTION VALUE=1 >Content
</SELECT></TD>
	<TD><B>Show: </B><BR><SELECT NAME="display">
HTML
if($display eq "rows") { print "<OPTION VALUE=\"rows\" SELECTED>Cards"; }
else { print "<OPTION VALUE=\"rows\">Cards"; }
if($display eq "columns") { print "<OPTION VALUE=\"columns\" SELECTED>Tabellone"; }
else { print "<OPTION VALUE=\"columns\">Tabellone"; }
  print<<HTML;
</SELECT></TD></TR></TABLE><br>
HTML
$footer="default";
&html_footer;
} # End of print_default subroutine.


########### Search & Sort Database #############
sub search_db{
  my $search_for = $_[0];
   unless (-e $database){ open (DB, ">$database") || die "Error creating database b. $!\n"; }
   else { open (DB, "$database") || die "Error opening database.  $!\n"; }
    while(<DB>){
      if($search_field =~ /all/i) {
        if($filter_ eq "Nessun filtro applicato") {
          if (/$search_for/oi){ push @results, $_};
        } else {
          if ((/$search_for/oi) && (/$filter_/oi) ){ push @results, $_};
        }
      } else {
        ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $_);
        
        if($filter_ eq "Nessun filtro applicato") {
          if ($field_vals[$search_field] =~ /$search_for/oi) { push @results, $_};
        } else {
          if (($field_vals[$search_field] =~ /$search_for/oi)  && (/$filter_/oi) ){ push @results, $_};
        }

      } # End of else.
    } # End of while.
  close (DB);
  foreach $curr (@results){
    ($key,$dbuser,$when_added,@rest) = split(/\|/, $curr);
     $max = @fields;
     $code='$record{$key} = { key => "$key", ';
     $code .='dbuser => "$dbuser", ';
     $code .='when_added => "$when_added", ';
     for($x=0;$x<$max;$x++){
      $code .= "\$fields[$x] => \"\$rest[$x]\",\n";
    } # End of for
     $code .= '};';
    eval $code;
  } # End of foreach curr
   $sort_on = "$fields[$sort]";
   @results=();
  foreach $rp (sort { $a->{$sort_on} cmp $b->{$sort_on} } values %record){
    $new_rec = $rp->{key};
    $new_rec .= "\|$rp->{dbuser}";
    $new_rec .= "\|$rp->{when_added}";
    for($x=0;$x<$max;$x++){
      $new_rec .= "\|$rp->{$fields[$x]}";
    } # End of for
    push @results, $new_rec;
  } # End of foreach
$count = @results;
if($count < 1){ 
  $message="No Matches Found For '$search_for'";
  $title="Main Menu";
  &print_default($title, $message);  
### intervention
  exit;
}
$total_row_count = @results;
if ($total_row_count > $max_rows_returned) {
$hits_seen = $q->param(new_hits_seen);
  for ($i = 1; $i <= $hits_seen; $i++)
    { $seen_row = shift (@results);  }
  $length_of_database_rows = @results;
  for ($i = $length_of_database_rows-1; $i >= $max_rows_returned; $i--)
    { $extra_row = pop (@results); }
  $new_hits_seen = $hits_seen + @results; } else { $show="no"; }
} # End of search_db subroutine.



################### Filter ####################
sub filter{
  $temp  = $_[0];



#  $temp  =~ s/\80/\&euro\;/g;
  $temp  =~ s/\A7/\&sect\;/g;
  $temp  =~ s/\A9/\&copy\;/g;
  
  $temp  =~ s/\'/\&\#0039\;/g;
  $temp  =~ s/\B0/\&deg\;/g;
  
  $temp  =~ s/\n/<br>/g;
  $temp  =~ s/\r/<br>/g;
  $temp  =~ s/<br><br>/<br>/g;
#  $quote = "&quot;";
#  $temp  =~ s/\"/$quote/g;
  $temp  =~ s/\s+/ /g;
  $temp  =~ s/ \./\./g;
  $temp  =~ s/ \,/\,/g;
  $temp  =~ s/\'/\92/g;
  
  foreach $removed (@filter) { $temp =~ s/$removed/\?\$\%\&/gi; }
  if ($filter_html_tags eq "yes") { $temp =~ s/<[^>]*>//gs;  }
  return ($temp);
}
############# end of Filter ####################


############### Check Item #################

sub check_item{
  $r_val = $_[0];
  $index = $_[1];
  if($r_val =~ /^\s*$/){$r_val="&nbsp;"; return($r_val);}
  if( ($index_of_image_url ne "") && (($index eq $index_of_image_url)|($index eq $index2_of_image_url)) ) { 
  if ($r_val =~ /http:\/\//i){ $link = "$r_val"; }                        
  else { $link = $js_path; $link .= "$r_val";  }
  $r_val2 = "<a href=\"$link\">$r_val</a>"; $r_val = $r_val2; 
   }
  if($index_of_URL ne "" && $index eq $index_of_URL) { $r_val2 = "<a href=\"$r_val\">$r_val</a>"; $r_val = $r_val2; }
  if($index_of_email ne "" && $index eq $index_of_email) { $r_val2 = "<a href=\"mailto:$r_val\">$r_val</a>"; $r_val = $r_val2; }
  return($r_val);
}
################### Login ###################
sub login {
$message = $_[0];
$title = "Login";
&html_header($title,$message);
print<<HTML;
<TABLE><TR>
<TD><B>User Name</B><BR><INPUT TYPE="text" NAME="user" SIZE="30"></TD></TR>
<TR><TD><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30" onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
    {myForm.action.value='Submit Login';this.form.submit(  );return false;} 
    else return true;"></TD>
</TR>
<TR><TD ALIGN=MIDDLE><BR>
<INPUT TYPE=button  onClick=\" myForm.action.value='Submit Login';this.form.submit(  );\"  VALUE="Submit Login" >

</TD>
</TR>
</TABLE>
HTML
$footer = "login";
&html_footer;
}

################ Authenticate ################

sub authenticate {
    $form_password = $q->param(password);
    open (USERFILE, "$user_file") || die "Error opening user file.  $!\n";
    $user_matched = 0;
    while (<USERFILE>) {
	chop($_);
	($password, $user, $u_search, $u_add, $u_modify, $u_delete, @extra_user_fields) = split(/\|/, $_);
	if ($q->param(user) eq $user) {
	    $user_matched = 1;
	    $username = $user;
	    $user_add = $u_add;
	    $user_modify = $u_modify;
	    $user_search = $u_search;
	    $user_delete = $u_delete;
	if (&auth_encrypt ($form_password, $password) eq $password) {
  	    $cookie = cookie(-NAME=>'user',-VALUE=>"$user",-EXPIRES=>'+3d');
	} # End of if passwords match
	} # End of if username matches
    } # End of While
    close (USERFILE);
    if ($user_matched == 1 && $cookie eq "") {
	    $footer = "login";
	    $title = "Login";
	    $error_message = "Your password did not match your user name!";
	    &access_problem($error_message);
	    exit;    }
    if ($user_matched == 0) {
	    $footer = "login";
	    $title = "Login";
	    $error_message = "Your user name was not found!";
	    &access_problem($error_message);
	    exit;    }
print header(-cookie=>[$cookie]);
$set_cookie = "yes";
$message = "User \"$username\" is now logged in";
$title = "Main Menu"; 
$user = $username;
&print_default($title, $message);
exit;
}

############### Register Form ################

sub register {
$title = "Register A New User";
&html_header($title);
 print<<HTML;
<TABLE><TR>
<TD><B>User Name</B><BR><INPUT TYPE="text" NAME="user" SIZE="30"></TD></TR>
<TR><TD><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
<TR><TD><B>Re-Type Password</B><BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML
  foreach $extra (@extra_user_fields){
    print "<TR><TD><B>\u$extra</B><BR><INPUT TYPE=\"text\" NAME=\"$extra\" SIZE=\"30\"></TD></TR>";
  }
 print<<HTML;
<TR><TD ALIGN=MIDDLE><BR>
<INPUT TYPE="hidden" NAME="search" value="$default_user_permission_search">
<INPUT TYPE="hidden" NAME="add" value="$default_user_permission_add">
<INPUT TYPE="hidden" NAME="modify" value="$default_user_permission_modify">
<INPUT TYPE="hidden" NAME="delete" value="$default_user_permission_delete">
<INPUT TYPE=button  onClick=" myForm.action.value='Add User';this.form.submit();"  VALUE="Add User" >
<INPUT TYPE=button  onClick=" myForm.action.value='Back To Login';this.form.submit();"  VALUE="Back To Login" >
</TD>
</TR>
</TABLE>
HTML
$footer = "login";
&html_footer;
}

################ Add User ##################

sub add_user {
$user = $q->param(user);
$password = $q->param(password);
$password2 = $q->param(password2);
if ($perform eq "edit" && $password eq "") { $use_old = "yes"; $password = "$old_password"; $password2 = "$old_password";}
	if ($password ne $password2 || $password eq "" || $password2 eq "") {
	    $footer = "login";
	    $title = "Register A New User";
	    $error_message = "Your passwords didn't match!";
	    &access_problem($error_message);
	    exit;	}
@form_vars = ('user', 'search', 'add', 'modify', 'delete', @extra_user_fields);
    foreach $x (@form_vars) {
	if ($q->param($x) eq "" || $q->param($x) =~ /\|/) {
             $footer = "login";
	    $title = "Register A New User";
	    $error_message = "You must fill in all of the fields in the registration form!";
	    &access_problem($error_message);
	    exit;	}     }
    if ($check_user_duplicates eq "yes") {
	open (USERFILE, "$user_file");
	$user_matched = 0;
	while (<USERFILE>) {
	    chop($_);
	    @f = split(/\|/, $_);
	    if ($f[1] eq $user) {
		$user_matched = 1;
		last;	    }	} # End of while userfile open
	close (USERFILE);
	if ($user_matched == 1) {
	    $footer = "login";
	    $title = "Register A New User";
	    $error_message = "That user name is already taken!";
	    &access_problem($error_message);
	    exit;	} # End of user matched (found duplicate)    
	} # End of if check duplicates on
    srand(time|$$);
    $random = "abcdefghijklmnopqrstuvwxyz1234567890";
    $real_password = $password;
    $salt = "";
    for (1..2) { $salt .= substr($random,int(rand(36)),1); }
  if ($use_old ne "yes") {  $password = &auth_encrypt ($password, $salt); }
  $auth=$password;
  foreach $field (@form_vars){
    ${$field}  = $q->param($field);
    $auth   .= "\|${$field}";  }
   unless (-e $user_file){
    open (AUTH_FILE, ">$user_file") || die "Error creating user file.  $!\n";
  } else {
    open (AUTH_FILE, ">>$user_file") || die "Error opening user file.  $!\n";
  }
   flock AUTH_FILE, $EXCLUSIVE;
   seek AUTH_FILE, 0, 2;
   print AUTH_FILE "$auth\n";
   flock AUTH_FILE, $UNLOCK;
  close(AUTH_FILE);
if ($admin_add eq ""){
   $message = "New User Added<br>You may now login with your new user name below.";
   &login($message);
   } else { 
   $title = "User Manager";
   $message = "User Added/Modified";
   &user_manager($message);
   }
}

################ Create Admin ###############

sub create_admin{
&html_header($title);
 print<<HTML;
<center><TABLE WIDTH=275>
<TR>
<TD>Please start out by setting the Administrator information below.  When logged in as the below user, you will be able to access additional options which are only available to the database administrator.</TD>
</TR><TR>
<TD><br><B>User Name:</B> $admin_user_name<br>This can be changed in the script configurations.</TD></TR>
<TR><TD><br><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
<TR><TD><B>Re-Type Password</B><BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML
  foreach $extra (@extra_user_fields){
    print "<TR><TD><B>\u$extra</B><BR><INPUT TYPE=\"text\" NAME=\"$extra\" SIZE=\"30\"></TD></TR>";
  }
 print<<HTML;
<TR><TD ALIGN=MIDDLE><BR><INPUT TYPE="hidden" NAME="user" value="$admin_user_name">
<INPUT TYPE="hidden" NAME="search" value="yes">
<INPUT TYPE="hidden" NAME="add" value="yes">
<INPUT TYPE="hidden" NAME="modify" value="yes">
<INPUT TYPE="hidden" NAME="delete" value="yes">
<INPUT TYPE=button  onClick=" myForm.action.value='Add Administrator';this.form.submit(  );"  VALUE="Add Administrator" >
</TD>
</TR>
</TABLE></center>
HTML
$footer = "login";
&html_footer;
exit;
}

################ User Manager ###############

sub user_manager{
$message = $_[0];
&html_header($title,$message);
 print<<HTML;
<center>
<TABLE>
<TR>
<TD><select name="selected_user" size=8>
HTML
    open (USERFILE, "$user_file") || die "Error opening user file.  $!\n";
    while (<USERFILE>) {
	chop($_);
	($password, $user, $u_search, $u_add, $u_modify, $u_delete, @extra_user_fields) = split(/\|/, $_);
	print "<option value=\"$user\">$user</option>\n";
    } # End of While
    close (USERFILE);
  print<<HTML;
</select></TD>
<td valign=top>
<input TYPE=button onClick=" myForm.action.value='Create New User';this.form.submit(  );" value="Create New User"><p>
<input TYPE=button onClick=" myForm.action.value='Edit Selected User';this.form.submit(  );" value="Edit Selected User"><p>
<input TYPE=button onClick=" myForm.action.value='Remove Selected User';this.form.submit(  );" value="Remove Selected User">
</TR>
</TABLE>
</center>
HTML
&html_footer;
exit;
}

############### Add/Edit User ################

sub edit_user {
if ($perform eq "edit" && $selected_user eq "" ) {
	    $title = "User Manager - Edit Selected User";
	    $error_message = "You forgot to select a user record to edit!";
	    &access_problem($error_message);
	    exit;
}
if ($perform eq "edit") {
    open (USERFILE, "$user_file") || die "Error opening user file.  $!\n";
    while (<USERFILE>) {
	chop($_);
	($password, $userfound, $u_search, $u_add, $u_modify, $u_delete, @other_user_fields) = split(/\|/, $_);
	if ($selected_user eq $userfound) {
	    @found_other_fields = @other_user_fields;
	    $edit_user = $userfound;
	    $edit_user_add = $u_add;
	    $edit_user_modify = $u_modify;
	    $edit_user_search = $u_search;
	    $edit_user_delete = $u_delete;
	    $old_password = $password;
	} # End of if username matches
    } # End of While
    close (USERFILE);
}
&html_header($title);
 print<<HTML;
<TABLE><TR>
<TD><B>User Name</B><BR><INPUT TYPE="text" NAME="user" SIZE="30" value="$edit_user"></TD></TR>
HTML
if ($perform eq "edit") {
  print<<HTML;
<TR><TD><B>New Password</B><br>Leave blank if you aren't changing passwords.<BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
HTML
} else {
  print<<HTML;
<TR><TD><B>Password</B><BR><INPUT TYPE="password" NAME="password" SIZE="30"></TD></TR>
HTML
}
if ($perform eq "edit") {
  print<<HTML;
<TR><TD><B>Re-Type New Password</B><br>Leave blank if you aren't changing passwords.<BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML
} else {
  print<<HTML;
<TR><TD><B>Re-Type Password</B><BR><INPUT TYPE="password" NAME="password2" SIZE="30"></TD></TR>
HTML
}
$extra_fields_count = @found_other_fields;
      for($x=0;$x<$extra_fields_count;$x++){
print "<TR><TD><B>\u$extra_user_fields[$x]</B><BR><INPUT TYPE=\"text\" NAME=\"$extra_user_fields[$x]\" SIZE=\"30\" value=\"$found_other_fields[$x]\"></TD></TR>";
    }
if ($perform eq "add") {
  foreach $extra (@extra_user_fields){
    print "<TR><TD><B>\u$extra</B><BR><INPUT TYPE=\"text\" NAME=\"$extra\" SIZE=\"30\"></TD></TR>";
  }
}
 print<<HTML;
<tr><td><br><b>User Permissions</b></td></tr>
HTML

if ($edit_user_search eq "no"){
  print<<HTML;
<tr><td>Search: <input type="radio" name="search" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="search" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Search: <input type="radio" name="search" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="search" value="no"> No</td></tr>
HTML
}
if ($edit_user_add eq "no"){
  print<<HTML;
<tr><td>Add: <input type="radio" name="add" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="add" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Add: <input type="radio" name="add" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="add" value="no"> No</td></tr>
HTML
}
if ($edit_user_modify eq "no"){
  print<<HTML;
<tr><td>Modify: <input type="radio" name="modify" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="modify" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Modify: <input type="radio" name="modify" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="modify" value="no"> No</td></tr>
HTML
}
if ($edit_user_delete eq "no"){
  print<<HTML;
<tr><td>Delete: <input type="radio" name="delete" value="yes"> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="delete" value="no" checked> No</td></tr>
HTML
} else {
  print<<HTML;
<tr><td>Delete: <input type="radio" name="delete" value="yes" checked> Yes &nbsp;&nbsp;&nbsp;<input type="radio" name="delete" value="no"> No</td></tr>
HTML
}
  print<<HTML;
<TR><TD ALIGN=MIDDLE><BR><input type=hidden name="old_password" value="$old_password"><input type=hidden name="selected_user" value="$edit_user"><input type=hidden name="admin_add" value="yes">
<INPUT TYPE=button  onClick=" myForm.action.value='$button_text';this.form.submit(  );"  VALUE="$button_text" >
</TD>
</TR>
</TABLE>
HTML
&html_footer;
}

################ Delete User ###############

sub delete_user{
if ($selected_user eq "" ) {
	    $title = "User Manager - Remove Selected User";
	    $error_message = "You forgot to select a user record to remove!";
	    &access_problem($error_message);
	    exit;
}
if ($selected_user eq "$admin_user_name" && $perform eq "delete") {
	    $title = "User Manager - Remove Selected User";
	    $error_message = "You are not allowed to remove the administrator!";
	    &access_problem($error_message);
	    exit;
}
  open (USERFILE, "$user_file") or die "Error opening file: $!\n";
  while (<USERFILE>)
    {
    $line = $_;
    chop $line;
    @dbfields = split (/\|/, $line);
    $deleted = "no";
    if ($dbfields[1] eq $selected_user) { $deleted = "yes"; }
    elsif ($deleted ne "yes") { $new_data .= "$line\n"; }
    } #end of while
  close (USERFILE);
    flock USERFILE, $EXCLUSIVE;
    open (USERFILE, ">$user_file") or die "Error opening file: $!\n";
    print USERFILE "$new_data";
    close (USERFILE);
}

################# Logout ###################

sub logout {
$cookie = cookie(-NAME=>'user',-VALUE=>"$user",-EXPIRES=>'-1d');
print header(-cookie=>[$cookie]);
$set_cookie = "yes";
$message = "User \"$user\" logged out";
&login($message);
 } # end of logout

############ Encrypt Password ###############

sub auth_encrypt {
    local ($field, $salt) = @_;
    $field = crypt ($field, $salt);
    $field;
 } # end of encrypt

############## Access Problem ##############

sub access_problem {
&html_header($title);
 print<<HTML;
<BR>
<FONT SIZE=4 FACE="ARIAL" COLOR=RED><B>Error!</B></FONT><P>
<FONT SIZE=4 FACE="ARIAL">$error_message</FONT><P>
<INPUT TYPE="button" VALUE="  Back  " onClick="history.go(-1)"><br><br>
HTML
&html_footer;
exit;
}

################ Get Date ##################

sub get_date  {
  local ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst,$date);   
  local (@days, @months);
  @days = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
  @months = ('January','February','March','April','May','June','July','August','September','October','November','December');
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
  if ($hour < 10)    {    $hour = "0$hour";    }
  if ($min < 10)     {    $min = "0$min";    }
  if ($sec < 10)    { $sec = "0$sec";    }
  $mon++;
 $year += 1900;
 $date = "$mon/$mday/$year at $hour\:$min\:$sec";
  return $date;
  }

############## Form Header #################

sub form_header {
print<<HTML;
<FORM name="myForm" METHOD="post" ACTION="$script_name">
<INPUT TYPE="hidden" NAME="action" VALUE="$action">
HTML
}

############## Form Footer #################

sub form_footer {
if($footer eq "default") {
# if ($user_search eq "yes") {print "<INPUT TYPE=button  onClick=\"myForm.action.value='search';this.form.submit(  );\"  VALUE=\"Search\" > "; }
# if ($user_add eq "yes") {print "<INPUT TYPE=button  onClick=\" myForm.action.value='opere';this.form.submit(  );\"  VALUE=\"Opere\" > "; }
if ($authenticate eq "yes") {print "<INPUT TYPE=button  onClick=\"myForm.action.value='search';this.form.submit(  );\"  VALUE=\"Find\" > "; }
# if ($authenticate eq "yes") {print "<INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit(  );\"  VALUE=\"Nuova Scheda\" > "; }
if ($authenticate eq "yes") {print "<INPUT TYPE=button  onClick=\" myForm.action.value='create_newsletter';this.form.submit(  );\"  VALUE=\"Newsletter\" > "; }

if ($authenticate eq "yes") { print "<INPUT TYPE=button  onClick=\" myForm.action.value='Logout';this.form.submit(  );\"  VALUE=\"Logout\" >\n"; }
}
elsif($footer eq "login") { print "\&nbsp\;"; }
 else { print "<INPUT TYPE=button  onClick=\" myForm.action.value='Main Menu';this.form.submit(  );\"  VALUE=\"Main menu \" >";
if ($authenticate eq "yes") { print "<INPUT TYPE=button  onClick=\"myForm.action.value='Logout';this.form.submit(  );\"  VALUE=\"Logout\" >";} }
print "<input type=hidden name=\"user_search\" value=\"$user_search\">\n";
print "<input type=hidden name=\"user_add\" value=\"$user_add\">\n";
print "<input type=hidden name=\"user_modify\" value=\"$user_modify\">\n";
print "<input type=hidden name=\"user_delete\" value=\"$user_delete\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"user\" VALUE=\"$user\">\n";
    print "<input type=hidden name=\"user_trans\" value=\"$user_trans\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"authenticate\" VALUE=\"$authenticate\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"message\" VALUE=\"$message\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"filter_\" VALUE=\"$filter_\">\n";
}


############## HTML Header #################

sub html_header{
if($set_cookie eq "") { print $q->header; }
$set_cookie = "";

 print<<HTML;
<HTML><HEAD>
   <TITLE>$db_name - $_[0]</TITLE>
  </HEAD><BODY BGCOLOR="#FFFFFF">
  	<script language="javascript" src="$js_path/js/global.js"></script>	
	<script language="javascript" src="$js_path/js/style.js"></script>
  <CENTER><B>
   $db_name
  </B><p><FONT SIZE=3 FACE="ARIAL" COLOR=RED><B>$_[1]</B></FONT></CENTER><P>
   <CENTER>
   <TABLE BORDER=1 WIDTH="$table_width" CELLSPACING="0" CELLPADDING="3">
    <TR> 
    <TD BGCOLOR="#e0e0e0"> 
     <CENTER> 
          <B>$_[0]</B>
     </CENTER>
    </TD>
   </TR>
    <TR> 
     <TD align="center"><BR>

HTML
&form_header;

}

sub html_header_left{
if($set_cookie eq "") { print $q->header; }
$set_cookie = "";

 print<<HTML;
<HTML><HEAD>
   <TITLE>$db_name - $_[0]</TITLE>
  </HEAD><BODY BGCOLOR="#FFFFFF">
  	<script language="javascript" src="$js_path/js/global.js"></script>	
	<script language="javascript" src="$js_path/js/style.js"></script>
  <CENTER><B>
   $db_name
  </B><p><FONT SIZE=3 FACE="ARIAL" COLOR=RED><B>$_[1]</B></FONT></CENTER><P>
   <CENTER>
   <TABLE BORDER=1 WIDTH="$table_width" CELLSPACING="0" CELLPADDING="3">
    <TR> 
    <TD BGCOLOR="#e0e0e0"> 
     <CENTER> 
          <B>$_[0]</B>
     </CENTER>
    </TD>
   </TR>
    <TR> 
     <TD align="left"><BR>

HTML
&form_header;

}

############## HTML Footer #################

sub html_footer{
if($use_external_html eq "yes") { 
%external_variables = (title=>$title, message=>$message,);
&form_footer;
print html_template("$external_html_footer", \%external_variables); 
print "<center><p>Powered by <a href=\"http://www.1stmuse.com\">Constellation Systems</a><br>\&copy\; Constellation Systems<br><br></center>";
} else {
 print<<HTML;
    <BR></TD></TR>
  <TR> 
    <TD BGCOLOR="#e0e0e0"><CENTER> 
HTML
&form_footer;
 print<<HTML;
     </CENTER>
    </TD>
  </TR>
</TABLE><P>




</BODY></HTML>
HTML
	}
}






############ Print Next Page Buttons ###########################
sub next_page_buttons {

if ($rows_left_to_view > 0 && $show ne "no") {
    print "<P><INPUT TYPE=\"hidden\" NAME=\"new_hits_seen\" VALUE=\"$new_hits_seen\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"which_search\" VALUE=\"$which_search\">";

if ($rows_left_to_view == 1){ 
print<<HTML;
<INPUT TYPE=button  onClick=" myForm.action.value='$what';this.form.submit(  );"  VALUE="Mostra la ultima scheda" >
HTML
}; 

if ($rows_left_to_view <= $max_rows_returned){ 
print<<HTML;
<INPUT TYPE=button  onClick=" myForm.action.value='$what';this.form.submit(  );"  VALUE="Mostra le ultime $rows_left_to_view schede" >
HTML
};

if ($rows_left_to_view > $max_rows_returned) { 
print<<HTML;
<INPUT TYPE=button  onClick=" myForm.action.value='$what';this.form.submit(  );"  VALUE="Mostra le prossime $max_rows_returned schede" >
HTML
} ; 
}

}




################ Back Screen ##################

sub print_back {

&html_header;
 print<<HTML;
<script language="JavaScript">
window.history.go(-3);
</script>
HTML
&html_footer;
} # End of print_default subroutine.




############# Results Screen ################
sub search_email_results{

$display = "columns"; 

# header
&html_header($title);
  $rows_left_to_view = $total_row_count - $new_hits_seen;
  $start_hit = $hits_seen + 1;
  $end_hit = $new_hits_seen;
  $hits_displayed = $end_hit - $start_hit + 1;
  if ($total_row_count > 1) {
    print qq~<P>Total Found: <B>$total_row_count</B> records<BR>~;
    if ($total_row_count > $max_rows_returned) {
      if ($hits_displayed == 2) {  print qq~<B>Last two</B> records shown below<BR>~;  }
      elsif ($hits_displayed == 1) {  print qq~<B>Last</B> record shown below<BR>~;  }
      else { print qq~<B>$start_hit</B> - <B>$end_hit</B> shown below<BR>~;  }
    } #end if
  } #end if ... > 1
  else { print qq~<P>Found: <B>1</B> record\n~; }
    print "<br>nel campo: <b>$search_field_ </b> Cerca: <b> $find_ </b>";
$cerca = $search_for;
print "<br>";

if ($button_text ne "")
{ 
   if ($button_text eq "Modify Record") {
     print "<INPUT TYPE=button  onClick=\"myForm.action.value='nuovo';this.form.submit();\"  VALUE=\"nuovo\" >";
  };
}
$which_search = $choose;
&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"key\" VALUE='0'>\n";
# end of header


$display = "columns"; 
if($display =~/columns/i) {
 print<<HTML;
	<p><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
    <TR BGCOLOR="#e0e0e0">
HTML

if($user eq "admin"){
  print "<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit(  );\"  VALUE=\"Elimina Scheda\" >
  ";
}
  if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit(  );\"  VALUE=\"Modify Record\" >
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='nuovo';this.form.submit(  );\" VALUE=\"aggiungere scheda\" >
</TD></TR>\n";
  }

  foreach $field (@fields){
    print "<TD ALIGN=CENTER><B>\u$field</B></TD>\n";
  } # End of foreach


  print "</TR>";
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 
    print "<TR BGCOLOR=\"#efefef\">\n";
    
if($user eq "admin"){
  print "<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit(  );\"  VALUE=\"Elimina Scheda\" >
  ";
}
    if($choose =~ /(modify|delete)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2>
<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Modify Record';this.form.submit(  );\"  VALUE=\"Modify Record\" >
</TD></TR>\n";
}
 # End of if $display =~columns
      for($x=0;$x<$field_count;$x++){
      $item = &check_item($field_vals[$x], $x);
      print "<TD>$item</TD>\n";
    }
     print "</TR> ";
  } # End of foreach loop.
  print<<HTML;
</TR></TABLE>
HTML
} 
else 
# do rows
{
  foreach $record (@results){
    ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $record); 
### intervention
print<<HTML;
	<P><TABLE BORDER=0 CELLSPACING=2 CELLPADDING=2 WIDTH=$record_width>
HTML

  $x=0;
  foreach $field (@fields){
  $item = &check_item($field_vals[$x], $x);


$background_color="#e0e0e0";
$line= "<TD BGCOLOR='#efefef' WIDTH=100%>$item</TD>";
if ($x > 11) {$background_color='#B6DB91'; $line= "<TD BGCOLOR='#D5FFD5' WIDTH=100%>$item</TD>" };
if ($x > 24) {$background_color='#dcb691'; $line= "<TD BGCOLOR='#ffd5D5' WIDTH=100%>$item</TD>" };
if ($x > 32) {$background_color='#b6b691'; $line= "<TD BGCOLOR='#ffffD5' WIDTH=100%>$item</TD>"};
if ($x > 41) {$background_color='#dcec91'; $line= "<TD BGCOLOR='#dcecD5' WIDTH=100%>$item</TD>"};




$campo = $field;

print<<HTML;
     <TR>
      <TD BGCOLOR=$background_color><B>\u$campo</B></TD>
      $line
     </TR>
HTML



   $x++;
 	 } # End of foreach field loop.
######## buttons on the end of record
  if($choose =~ /(modify|delete|search)/){
    print "<TR BGCOLOR=\"\#e0e0e0\"><TD ALIGN=CENTER COLSPAN=2> ";
if($user eq "admin"){
  print "<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='Delete Record';this.form.submit(  );\"  VALUE=\"Elimina\" >
  ";
}
    print "<INPUT TYPE=button  onClick=\"myForm.key.value='$key';myForm.search_field.value='all'; myForm.action.value='modifica_opera';this.form.submit(  );\"  VALUE=\"Modifica\" >";

};

######## end of buttons 
  print "</TABLE><P>";

  } # End of foreach record loop.

# end of rows display
} # End of if display loop

if ($button_text ne "")
{ 
  if ($button_text eq "Modify Record") {
     print " <INPUT TYPE=button  onClick=\" myForm.action.value='nuovo';this.form.submit(  );\"  VALUE=\"nuovo\" >";
  };
}

$which_search = $choose;
############### next page buttons 
&next_page_buttons($rows_left_to_view);

    print "<INPUT TYPE=\"hidden\" NAME=\"sort_on\" VALUE=\"$sort\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"display\" VALUE=\"$display\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_for\" VALUE=\"$search_for\">\n";
    print "<INPUT TYPE=\"hidden\" NAME=\"search_field\" VALUE=\"$search_field\">\n";
print "<p>";
$cerca_t=$cerca;
if ($cerca eq '.') {$cerca_t='all'};

&html_footer;
} # End of search_results_email subroutine.





################### Unwrap ####################
sub unwrap{
  $temp  = $_[0];
  $temp  =~ s/<br>/\r\n/ig;
  $temp  =~ s/\|//g;
  return ($temp);
}
############# end of Unwrap ####################





################# MODIFICA I PARAMETRI DELLA NEWSLETTER ##################
############### Modify Screen ################
sub print_modify_page{
  ($key,$dbuser,$when_added,@field_vals) = split(/\|/, $results[0]); 
$title="Edit and Broadcast NEWSLETTER";
# assign and transform the relevant values of each field in the record
$x=0;
foreach $field (@fields){
  ${$field}  =  &unwrap($field_vals[$x]);
  $x++;
} 
# End of foreach assign field loop.
&html_header($title);
  print<<HTML;
 <style type="text/css">
<!--
.Stile1 {
	color: #FFFFFF;
	font-weight: bold;
}
.Stile2 {color: #FFFFFF}
-->
</style>

  <center>

   </tr>
    <tr> 
     <td align="center"><br>
  
  <script language="JavaScript">

<!-- This script locksout <CR> i.e. Enter Key and requires the SUBMIT button to be clicked to send form -->
<!-- Begin

function tabOnEnter (field, evt) {
      var keyCode = document.layers ? evt.which : document.all ? 
     evt.keyCode : evt.keyCode;
      if (keyCode != 13)
        return true;
      else {
        getNextElement(field).focus();
        return false;
      }
}


function getNextElement (field) 
{
    var frm = field.form;
    var bIs = false;
    for (var e=0;e<frm.length;e++)
    {
      if(frm[e].type!="hidden" && bIs) return frm.elements[e];
      if (field==frm[e]) bIs=true;
    }
}

//  End -->
  </script>
  
     <input name="key" value="$key" type="hidden">
  <table width="90%" border="0" cellspacing="0">
    <tbody>
      <tr bgcolor="#009900">
        <td height="21" colspan="8"><div align="center" class="Stile1">MODIFICA LA NEWSLETTER</div></td>
      </tr>
      <tr bgcolor="#d5ffd5">
        <td width="29%" height="21"><b>NEWSLETTER_subject:</b></td>
        <td width="71%" colspan="7"><input name="NEWSLETTER_subject" value="$NEWSLETTER_subject" type="text" id="NEWSLETTER_subject" onkeydown="return tabOnEnter (this, event);"  size="40"></td>
      </tr>
      <tr bgcolor="#d5ffd5">
        <td><b>NEWSLETTER_body:</b></td>
        <td colspan="7"><textarea name="NEWSLETTER_body" rows="25" cols="80">
$NEWSLETTER_body
</textarea>
      </tr>

        <tr bgcolor="#FFFFF4">
          <td>&nbsp;</td>
          <td colspan="8">&nbsp;</td>
        </tr>
       	</tbody></table>
	<p>&nbsp;</p>
	<p>
      <input onclick="myForm.action.value='Modify This Record';this.form.submit();" value="Save" type="button">
      <INPUT TYPE=\"button\"  onClick=\"myForm.action.value='send_newsletter';this.form.submit();\"  VALUE=\"Broadcast NewsLetter\" >

          <br>
          <br>
        </p>

HTML
&html_footer;
} # End of print_modify_screen subroutine.








############### create_newsletter Screen ################

sub create_newsletter_page{

my %mlist;

$title="NEWSLETTER MAILING - BACKEND ";
$key   = time();

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

print<<HTML;
<HTML><HEAD>
   <TITLE>BACKEND - MAILING_LIST - Invio</TITLE>
  </HEAD><BODY BGCOLOR="#FFFFFF">
  	<script language="javascript" src="$js_path/js/global.js"></script>	
	  <script language="javascript" src="$js_path/js/style.js"></script>
		<script language="javascript" src="$js_path/js/calculus.js"></script>
  <CENTER><B>
   Newsletter Mailer
  </B><p><FONT SIZE=3 FACE="ARIAL" COLOR=RED><B></B></FONT></CENTER><P>
   <CENTER>
<form name="myForm" method="post" action="$script_name">
<INPUT TYPE="hidden" NAME="key" VALUE="$key">

   <TABLE BORDER=1 WIDTH="90%" CELLSPACING="0" CELLPADDING="3">
    <TR> 
    <TD BGCOLOR="#e0e0e0"> 
     <CENTER> 
          <B>create_newsletter - Invio</B>
     </CENTER>
    </TD>
   </TR>
    <TR> 
     <TD align=middle><BR>

<INPUT TYPE="hidden" NAME="action" VALUE="$action">
<INPUT TYPE=HIDDEN NAME=key value="$key">
<script language="JavaScript">
<!-- hide

var myWind = ""

function doNew() {
// either open, or put on the top if it is already existing
	if (myWind == "" || myWind.closed || myWind.name == undefined) {

           pics = window.open("../upload.html","subWindow","HEIGHT=200,WIDTH=620,status=yes,toolbar=no,menubar=no,scrollbars=yes,resizable=yes").focus();

	} else{	myWind.focus();	}
}

function Modify_Parere(form) {
	form.Parere.value = form.Parere_m.value;
}


// -->
</script>

</b>
HTML



print "<HTML><TITLE>NewsLetter v$VERSION</TITLE>
<BODY BGCOLOR=\"#ffffff\" LINK=\"#003366\" VLINK=\"#003366\">
<CENTER>

<INPUT TYPE=\"hidden\" NAME=\"op\" VALUE=\"send\">
<TABLE WIDTH=\"500\" ALIGN=\"center\" BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"1\">
<TR><TD BGCOLOR=\"#003366\">
<TABLE WIDTH=\"100%\" ALIGN=\"center\" BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"5\">
<TR><TD ALIGN=\"center\" BGCOLOR=\"#003366\">
<B>Periodical News v$VERSION</B>
</TD></TR>
<TR><TD ALIGN=\"left\" BGCOLOR=\"#eeeeee\">

</TD></TR>
<TR><TD ALIGN=\"center\" BGCOLOR=\"#eeeeee\">

<b>Titolo: <INPUT TYPE=\"text\" size=\"60\" NAME=\"NEWSLETTER_subject\" VALUE=\"\">

</TD></TR>
<TR><TD ALIGN=\"center\" BGCOLOR=\"#eeeeee\">

<TEXTAREA NAME=\"NEWSLETTER_body\" COLS=\"140\" ROWS=\"25\"></TEXTAREA>

</TD></TR>
<TR><TD ALIGN=\"center\" BGCOLOR=\"#eeeeee\">
<INPUT TYPE=\"button\"  onClick=\"myForm.action.value='send_newsletter';this.form.submit();\"  VALUE=\"Invio NewsLetter\" >
 <INPUT TYPE=button  onClick=\"myForm.key.value=$key;myForm.action.value='salva_scheda';this.form.submit();\"  VALUE=\"Save\" >
</TD></TR>
<TR><TD ALIGN=\"right\" BGCOLOR=\"#cccccc\">

</TD></TR>
</TABLE>
</TD></TR>
</TABLE>

";


print<<HTML;
</b>
<p>

    <BR></TD></TR>

  <TR> 
    <TD BGCOLOR="#e0e0e0"><center>
<INPUT TYPE=button  onClick="myForm.action.value='Main Menu';this.form.submit(  );"  VALUE="Main Menu" >
<INPUT TYPE=button  onClick="myForm.action.value='Logout';this.form.submit(  );"  VALUE="Logout" ><input type=hidden name="user_search" value="">
<input type=hidden name="user_add" value="">
<input type=hidden name="user_modify" value="">
<input type=hidden name="user_delete" value="">
<INPUT TYPE="hidden" NAME="user" VALUE="$user">
<input type=hidden name="user_trans" value="">
<INPUT TYPE="hidden" NAME="authenticate" VALUE="yes">
<INPUT TYPE="hidden" NAME="message" VALUE="">
</p></center>
    </TD>
  </TR>

</TABLE><P>
</form>
</BODY></HTML>
HTML

}

############### end of create_newsletter Screen ################










sub error_page_new  {


print<<HTML;

ERROR: There are no e-mail addresses in the mailing list or there is no mailinglist.
<p>
<!--cgi:error-->

HTML

    exit;
  }




sub member
  {
    my ($ar, $el) = @_;
    foreach (@$ar)
      {
	return 1 if(lc($_) eq lc($el));
      }
    return 0;
  }







############### send_newsletter Screen ################
sub broadcast_newsletter{
$pause =3;
$packet_length =80;

my %mlist;

$title="NEWSLETTER MAILING - BACKEND";
&html_header_left($title);



# send the newsletter
print "<p align='left'><pre>fido2 NewsLetter  \n";
    print "Sending mail...Pause is $pause seconds after each packet of $packet_length emails.\n";
    my $subject = $q->param('NEWSLETTER_subject');
    my $body = $q->param('NEWSLETTER_body');
    open(LIST, "$MAILING_LIST")
      or error_page_new("Failed to open $MAILING_LIST: $!\n");
    $counter=0;
    while(<LIST>)    {
    chomp; #  removes newline characters <CR><LF> from the end of a line
# if line matches to the following mask (string):(number):(string) then perform the code , if(m/(\S+):\d+:(.*)/)
    if(m/(.*)\|(.*)\|(.*)/)    {
# jjpcondor@gmail.com|64758|fido2_News
       $counter++;
       $email =$1;
       $unique_key =$2;
       $customer =$3;
       if ($email =~ /^\w[\w\.\-]*\w\@\w[\w\.\-]*\w(\.\w{2,4})$/) {

         print "$counter: $email, $unique_key, $customer ";
	 unless(open(MAIL, "|$SENDMAIL"))  {
	      print "sendmail error ($!)\n";
	      next;
	 }
	 $module_ratio = $total % $packet_length;
           if ($module_ratio == 0) {sleep($pause)};
	   print MAIL "From: $FROM\n";
	   print MAIL "Reply-to: $REPLY_TO\n";
	   print MAIL "To: $email\n";
	   print MAIL "Subject: $subject\n";
	   print MAIL "X-Mailer: fido2 News\n";
	   print MAIL "Content-type: text/plain\n\n";
	   print MAIL $body;
#           print MAIL "\n\nTo be deleted from the mailing list, just click here:\n  $INSTURL/fido2_newsregistration.cgi?op=remove&email=$email&id=$unique_key&list=fido2_news";
	   close MAIL; 
	   print "ok\n";
        }
        else {
           print "WARNING: Email syntax error - $counter: $email, $2, $3 \n";
        }

      }

     } # end of while loop
print "\n Mailing broadcadt is terminated successfully. In total $counter  messages sent. </pre></p>";



print<<HTML;
</b>
<p>

    <BR></TD></TR>

  <TR> 
    <TD BGCOLOR="#e0e0e0"><center>
<INPUT TYPE=button  onClick="myForm.action.value='Main Menu';this.form.submit(  );"  VALUE="Main Menu" >
<INPUT TYPE=button  onClick="myForm.action.value='Logout';this.form.submit(  );"  VALUE="Logout" ><input type=hidden name="user_search" value="">
<input type=hidden name="user_add" value="">
<input type=hidden name="user_modify" value="">
<input type=hidden name="user_delete" value="">
<INPUT TYPE="hidden" NAME="user" VALUE="$user">
<input type=hidden name="user_trans" value="">
<INPUT TYPE="hidden" NAME="authenticate" VALUE="yes">
<INPUT TYPE="hidden" NAME="message" VALUE="">
</p></center>
    </TD>
  </TR>

</TABLE><P>
</form>
</BODY></HTML>
HTML

}

############### end of send_newsletter Screen ################



