#!/usr/bin/perl 
# ConfReg:  Conference paper form
# (c) NTREM, 2005-2010
# Vaclav Stepan, Vit Zyka
#
# Arrange paper info including abstract to printing
# 2007-11-25 VZ new
# 2008-10-15 VZ modus
# 2008-10-22 VZ script copyright header
# 2008-10-23 VZ submission formulation
# 2009-09-19 VZ form.cgi -> form_paper.cgi
# 2009-09-21 VZ locales
# 2010-03-23 VZ little border
# 2010-10-09 VZ parse_name better checking

use locale;
use POSIX qw(locale_h);

use CGI qw(-utf8 :standard);
#use CGI::Carp qw/fatalsToBrowser/;
use DBI;
use File::stat;

require "./lib/server_conf.pl"; # Server specific settings
require "./lib/defaults.pl"; # Default settings
require "./lib/lib_log.pl"; # Default settings
require "./lib/lib_util.pl"; # Utility functions

set_locale('cs_CZ.utf8');

#$debug = 1;

#============================================================
hlavicka_print('white');

$id = param('id');
if( !$id )
  {
    chybka('Paper ID not given for printing.');
    print
      $chyby,
      konec();
    exit;
  }

$dbh = connect_to_db();

$row = print_paper_with_abstract( $id );

$dbh->disconnect()
  or warn("Disconnection from $DSN failed: $DBI::errstr\n");

print
  hr,
  table({-class=>'max small'},
	TR(
	   td({-class=>'left'},"ID: $id, Contact: $row->{'keyworker'}, $row->{'email'}"),
	   td({-class=>'right'},"NTREM $year"),
	  )
       );

konec_print();

#======================================================================
sub hlavicka_print {
  my ($barva) = @_;

  print
#    header(-charset=>'iso-8859-2','Cache-Control: max-age=10'),
    header(-charset=>'utf-8','Cache-Control: max-age=10'),
    start_html(-title=>'New Trends in Research of Energetic Materials',
	       -author=>'Vaclav Stepan <w@linux.fjfi.cvut.cz>',
	       -style=>{'src'=>'./ntrem.css'},
#	       -encoding=>'iso-8859-2', -bgcolor=>$barva,
	       -encoding=>'utf-8', -bgcolor=>$barva,
	       -class=>'print',
	      );
}

sub konec_print {
  print end_html;
}

#======================================================================
sub print_paper_with_abstract {
  my ($id) = @_;

  my @paper_fields = qw/id ptitle keyworker email pass keywords mode/;
  my @author_fields = qw/pretitle fname lname posttitle orglist email salutation von/;
  my @org_fields = qw/org_id dept inst city state country /;

  # Vytahneme si zaznamy k danemu ID
  my $sql = sprintf("SELECT %s FROM papers WHERE id=%i;",
		    join(", ", @paper_fields), $id);
  $sth = $dbh->prepare($sql);
  $sth->execute();
  ($row = $sth->fetchrow_hashref('NAME_lc')) or die("The row for ID $id vanished.");
  $sth->finish();

  # Vytahneme si k ID autory
  my $nau=0;
  my $sql = sprintf("SELECT %s FROM authors WHERE id=%i;",
		    join(",",@author_fields), $id);
  print "$sql\n" if ($debug>0);
  $sth = $dbh->prepare($sql);
  $sth->execute();
  $author_str = '';
  while( $author = $sth->fetchrow_hashref('NAME_lc') )
    {
      $author_str .= ', ' if($author_str);
      $author_str .= $author->{'fname'}.' ' if($author->{'fname'});
      $author_str .= $author->{'von'}.' ' if($author->{'von'});
      $author_str .= $author->{'lname'} if($author->{'lname'});
      $author_str .= sup($author->{'orglist'});
    }

  # Vytahneme si organizace
  my $nor=1; # Organizace potrebujeme cislovane od jedne
  my $sql = sprintf("SELECT %s FROM org WHERE id=%i;",
		    join(", ", @org_fields),
		    $id);
  $sth = $dbh->prepare($sql);
  $sth->execute();
  $org_str = '';
  while( $org= $sth->fetchrow_hashref('NAME_lc') )
    {
      $org_str .= sup($org->{'org_id'}).' ';
      $org_str .= $org->{'inst'}.', ';
      $org_str .= $org->{'city'}.', ' if($org->{'city'});
      $org_str .= $org->{'country'};
      $org_str .= br;
    }

  # Vytahneme abstract
  $abstract = get_last_upload( 'a', $id, $dbh );

  print
    "<div class='center'>",
    h1({-class=>'print'},$row->{'ptitle'}),
    p($author_str),
    p($org_str),
    "</div>",
    "<div class='block'>",
    p(strong('Abstract. ').$abstract),
    "</div>",
    "<div class='left'>",
    p(strong('Keywords: ').$row->{'keywords'});

  return $row;
};



sub check_combination {
  # Check the validity of e-mail/password combination
  my $sql;
  my $stav;
  my $id;

  $sql = sprintf("SELECT id, stav FROM papers WHERE email=%s and pass=%s;",
		 $dbh->quote(param('e')),
		 $dbh->quote(param('t')));
  my $sth = $dbh->prepare($sql);
  $sth->execute() or die("Unable to issue a SQL command to database: $DBI::errstr\n");
  ($id, $stav) = $sth->fetchrow_array();
  $sth->finish();

  if( defined($stav) )
    {
      if( ($stav eq "C") || ($stav eq "F") )
	{ # Dobry, muzeme editovat
	  $id;
	}
      elsif( $stav eq "P" )
	{ # Tahle jeste neni potvrzena. No tak ji potvrdime...
	  $sql = sprintf("UPDATE papers SET stav='C' where id=%i;", $id);
	  $dbh->do($sql) or die("Trouble updating status for $id.\n");
	  set_notconfirmed_modus($dbh,'papers',$id,$mod_registered);
	  $notice=em("Your conference paper details were confirmed, thank you.").p;
	  if( $param_a )
	    {
	      write_log($dbh, $id, 'Paper registration confirmed by administrator.');
	    }
	  else
	    {
	      write_log($dbh, $id, 'Paper registration confirmed by user.');
	    }
	  $id;
	}
      else
	{
	  chybka("This paper can not be edited at the moment. Please contact the administrator: ".$admin);
	  0;
	}
    }
  else
    { # Bad e-mail/password combination. Either mis-typed or a cheat
      chybka('This e-mail/password combination is not valid <BR>Please check the spelling and try again.');
      write_log($dbh, -1, 'edit_paper.cgi: Login failed for '.$dbh->quote(param('e')).'/'.$dbh->quote(param('t')));
      warn('Invalid login.'.param(e));
      0;
    }
}

sub retrieve_paper {
    my ($id) = @_;
    my @fields = qw/id ptitle keyworker email pass keywords mode/;
    my @author_fields = qw/pretitle fname lname posttitle orglist email salutation von/;
    my @org_fields = qw/org_id dept inst city state country /;

    # Vytahneme si zaznamy k danemu ID
    my $sql = sprintf("SELECT %s FROM papers WHERE id=%i;",
		      join(", ", @fields),
		      1*$id);

    $sth = $dbh->prepare($sql);
    $sth->execute();
    # Vytahneme si hash reference na radek vysledku
    ($row = $sth->fetchrow_hashref('NAME_lc')) or die("The row for ID $id vanished.");
    $sth->finish();

    print h3("Paper details");
    print start_form(-action=>'form_paper.cgi');
    print hidden('a', $param_a) if ($param_a);

    foreach $field (@fields) {
	if ($row->{$field}) {
	    print hidden($field, $row->{$field});
	    param($field, $row->{$field});
	    #print $field." : ".$row->{$field}.br;
	}
    }

    #============================================================
    # Vytahneme si k ID autory
    my $nau=0;
    my $sql = sprintf("SELECT %s FROM authors WHERE id=%i;",
		      join(",",@author_fields),
		      $id);

    $sth = $dbh->prepare($sql);
    $sth->execute();

    while( $author = $sth->fetchrow_hashref('NAME_lc') )
      {
	foreach $af (@author_fields)
	  {
	    print hidden($af.$nau, $author->{$af});
	    param($af.$nau, $author->{$af});
	  }
	$nau++;
      }
    # Set number of authors
    print hidden('nau', $nau);

    #============================================================
    # Vytahneme si organizace
    my $nor=1; # Organizace potrebujeme cislovane od jedne
    my $sql = sprintf("SELECT %s FROM org WHERE id=%i;",
		      join(", ", @org_fields),
		      $id);
    #print "$sql";

    $sth = $dbh->prepare($sql);
    $sth->execute();

    while( $org= $sth->fetchrow_hashref('NAME_lc') )
      {
	foreach $af (@org_fields)
	  {
	    print hidden($af.$nor, $org->{$af});
	    param($af.$nor, $org->{$af});
	  }
	$nor++;
      }

    # Save as parameter
    print hidden('nor', --$nor);
    #print "NOR is $nor".p;

    # Set the action to edit
    print hidden('Action','Edit');

    # Vypiseme viditelnou tabulku
    show_paper();
    #print hidden('a', $param_a) if ($param_a);
    print submit(-name=>"Edit").end_form;

    print p;
}

sub upload_form {
  my ($typ) = @_;
  my ($what) = $vt{$typ};
  my $mask;
  my @uploads;

  die("Prazdny typ v upload form") unless ($typ);
  die('Nulove id v check_prev_uploads.') unless ($id);

  $mask = sprintf("%s/%s%03i*", $upload_directory, $typ, $id);
  my @uploads = glob($mask);

  if( @uploads > 0 )
    {
      $last_upload = $uploads[$#uploads];
      $sb = stat($last_upload);
    }
  if( $typ eq 'a' )
    {
      $last_abstract_content = get_last_upload( $typ, $id, $dbh );
      my @words = split(/\s/,$last_abstract_content);
      $word_count = $#words + 1;
    }

  print
    TR(td(b(ucfirst($what).':')),
       td({-width=>20},img{-src=>(@uploads>0?$mark{'checked'}:$mark{'unchecked'})}),
       ($typ eq 'a'
	?
	start_multipart_form(-action=>'upload.cgi').
	($param_a ? hidden('a', $param_a) : '').
	hidden('typ', $typ).
	hidden('e', param('e')).
	hidden('t', param('t'))
	:
	''
       ),
       ( @uploads>0
	 ?
	 ($typ eq 'a'
	  ?
	  td((scalar(@uploads)-1).'x')
	  :
	  td((scalar(@uploads)).'x')
	 ).
	 td("Word count=$word_count, ".$sb->size.'B').
	 td(scalar(localtime($sb->mtime))).
	 ($typ eq 'a'
	  ?
	  td({-class=>'bottom right'},submit('submit','(Re)upload'))
	  :
	  td(show_last_doc_form($typ))
	 )
	 :
	 ($typ eq 'a'
	  ?
	  td({-colspan=>3},'was not uploaded yet').
	  td({-class=>'bottom right'},submit('submit','(Re)upload'))
	  :
	  td({-colspan=>4},'was not uploaded yet')
	 )
       ),
      ),
    TR(#{-class=>'botborder'},
       ($typ eq 'a'
	?
	''
	:
	start_multipart_form(-action=>'upload.cgi').
	($param_a ? hidden('a', $param_a) : "").
	hidden('typ', $typ).
	hidden('e', param('e')).
	hidden('t', param('t'))
       ),
       td(($pt{$typ}?".$pt{$typ}":"")),
       ($typ eq 'a'
	? # abstract
	td({-colspan=>5},
	   textarea(-name=>'abstract_text',
		    -default=>$last_abstract_content,
		    -rows=>24, -columns=>90, -class=>'small'))
	: # paper
	td({-colspan=>5},
	   filefield('abstract_file','',45),
	   submit('submit','(Re)upload'),
	  )
       ),
       ($typ eq 'a'
	?
	''
	:
	end_form
       ),
      );

  if( $typ eq 'a' )
    {
      print TR(td('&nbsp;'),
	       td({-colspan=>3},submit('submit','(Re)upload')),
	       td({-colspan=>2},
		 ($word_count>400?'Your abstract is too long. Please shorten it.':'&nbsp;')),
	       end_form,
	      );
    }
}

sub format_size {
    my ($what) = @_;
    my @j = qw/B kB MB GB/;
    my $rad = 0;

    while( $what > 1024 )
      {
	$rad++;
	$what /= 1024;
	return sprintf(" (%.0f&nbsp;%s)", $what, $j[$rad]);
      }
    return "";
}

sub show_last {
    my ($typ, $text) = @_;
    my $s;
    die("Prazdny typ v show_last.") unless ($typ);

    $s .= '<tr><td>'.$text.'</td><td>';
    $s .= start_form(-action=>'show_submit.cgi');
    $s .= ($param_a ? hidden('a', $param_a) : "");
    $s .= hidden('e', param('e'));
    $s .= hidden('t', param('t'));
    $s .= hidden('typ', $typ);
    $s .= submit(-name=>"Show last version");
    $s .= end_form.'</td></tr>';
}

sub show_last_doc_form {
  my ($typ) = @_;
  my $s;

  die("Prazdny typ v show_last_doc_form.") unless ($typ);

  $s .= start_form(-action=>'show_submit.cgi');
  $s .= ($param_a ? hidden('a', $param_a) : "");
  $s .= hidden('e', param('e'));
  $s .= hidden('t', param('t'));
  $s .= hidden('typ', $typ);
  $s .= submit(-name=>"Show last version");
  $s .= end_form;
}

sub check_prev_uploads {
    my ($typ) = @_;
    my $mask;
    my @uploads;
    my $what = $vt{$typ};

    die('Prazdny typ v check_prev_uploads') unless ($typ);
    die('Nulove id v check_prev_uploads.') unless ($id);

    $mask = sprintf("%s/%s%03i*", $upload_directory, $typ, $id);
    my @uploads = glob($mask);

    if( @uploads > 0 )
      {
	$last_upload = $uploads[$#uploads];
	$sb = stat($last_upload);
	my $text;
	$text = ucfirst($what)." uploaded ".scalar(@uploads)."x, ";
	$text .= "last time on ".scalar(localtime($sb->mtime)).", ";
	$text .= "size: ".$sb->size.'&nbsp;B'.format_size($sb->size).'.';
	print show_last($typ, $text);
      }
    else
      {
	print '<tr><td>'.ucfirst($what).' was not uploaded yet. </td><td></td></tr>';
      }
}

sub show_the_upload_form {
    my $typ;
    my $upload_forms="";

#    print "<table>\n";
#    for $typ ( sort keys %vt )
#      {
#	check_prev_uploads($typ);
#      }
#    print "</table>\n";

    print h3("Upload");

#    print p.'Before you upload your abstract or camera ready paper, please read the ';
#    print a({-href=>"http://www.ntrem.com/instruction.htm"},"instructions").'.'.p;

    print "<table>\n";
    for $typ ( sort keys %vt )
      {
	if( $typ eq 'a' )
	  {
	    print TR(td({-colspan=>6},
		       'Please fill in (or paste) your abstract with about 300 words, 400 is a maximum.'));
	  }
	elsif( $typ eq 'd' )
	  {
	    print TR(td({-colspan=>6},
			'Please read the '.
			a({-href=>"http://www.ntrem.com/instruction.htm"},"instructions").
			' before uploading camera ready paper.'));
	  }
	upload_form($typ);
      }
    print "</table>\n";
}

sub show_the_back_form {
  if( $param_a )
    {
      start_form(-action=>'admin/index.cgi') .
      submit("Back to the List of Papers") .
      end_form;
    }
  else
    {
      '';
    }
}

sub show_the_logout_form {
  start_form(-action=>'index.cgi') .
  submit(-name=>"Logout") .
  end_form;
}

sub check_login {
    parse_email('e', 'Login', $max_dp, 0);
    parse_name('t', 'Password', $max_dp, $Check_None);
    if (length($chyby) > 0)
      {
	return 0;
      }
    else
      {
	return 1;
      }
}

sub show_the_form {
  # Any errors?
  print $chyby if (length($chyby) > 0);

  print start_form;
  print table(
	      radka('E-mail address:', 'e', 40),
	      heslo('Password:', 't', 40),
	     );
  print submit(-name=>'Login'), reset;
  print end_form;
  print
    br.
    'Login data was delivered to a contact person by e-mail during the paper registration.'.
    p;
}

# --- show (move to lib_util.cgi)
#sub get_last_upload {
#  my ($typ, $id, $dbh) = @_;
#  my $mask;
#  my @uploads;
#  my $last_upload = '';
#
#  # Vytvorime si mask pro glob - bere se libovolna pripona, takze
#  # zalezi jenom na typu
#  $mask = sprintf("%s/%s%03i.*", $upload_directory, $typ, $id);
#
#  @uploads = glob($mask);
#  if( @uploads > 1 )
#    {
#      write_log($dbh, $id, "ERROR: ".$vt{$typ}." download failed.");
#      die("Two uploads for the same id and type. This should not happen.");
#    }
#  elsif( @uploads==1 )
#    { # Mame jeden upload - tj to je on.
#      my $fname = $uploads[0];
#      $fname =~ s/.*\///;
#      # Dump the file
#      if( open(INFILE, '<'.$uploads[0]) )
#	{
#	  while(<INFILE>)
#	    {
#	      $last_upload .= $_;
#	    }
##	  if( $param_a )
##	    {
##	      write_log($dbh, $id, ucfirst($vt{$typ})." $fname retrieved by administrator.");
##	    }
##	  else
##	    {
##	      write_log($dbh, $id, ucfirst($vt{$typ})." $fname retrieved by user.");
##	    }
#	}
#    }
#  return $last_upload;
#}

# end of print_paper.cgi
