#!/usr/bin/perl
#  Copyright 2001-2011 Leslie Richardson

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.

my %lex = ('The file must be a .po file' => 'The file must be a .po file',
	   'Update Complete' => 'Update Complete',
	   'Eoy' => 'Eoy',
	   'Upload Translation file' => 'Upload Translation file',
	   'Main' => 'Main',
	   'Maximum File Upload size exceeded!' => 'Maximum File Upload size exceeded!',
	   'Error' => 'Error',
	   'Replace Existing Values' => 'Replace Existing Values',
	   'Import Translation' => 'Import Translation',
	   'Cannot open file' => 'Cannot open file',

);

my $self = 'xlatImportPO.pl';
my $maxbufcount = 250;


use DBI;
use CGI;

eval require "../../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}


my $q = new CGI;
print $q->header( -charset, $charset); 
my %arr = $q->Vars;

my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);



# Print Page Header
print "$doctype\n<html><head><title>$lex{'Import Translation'}</title>\n";
print "<link rel=\"stylesheet\" href=\"$css\" type=\"text/css\">\n";
print "$chartype\n</head><body>\n";

print "[ <a href=\"$homepage\">". $lex{Main}. "</a> |\n";
print "<a href=\"$eoypage\">". $lex{Eoy}. "</a> ]\n";
print "<center><h1>". $lex{'Import Translation'}. "</h1></center>\n";

if ( not $arr{page} ) {
    showStartPage();
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    importTranslation();
} 


#--------------------
sub importTranslation {
#--------------------

    my $replace; # replace existing translation values or not...
    if ( $arr{replace} ) {
	$replace = 1;
    }

    my $file = $q->param("filename");
    my $name; my $ext; 
    my $filename = $file;  # fileName is output filename, file is input.

    if ( $file ) {

	$filename =~ s!^.*(\\|\/)!!; 
	$filename = lc($filename);
	@name = split( /\./, $filename); # split on dots.
	$ext = $name[$#name];  # last element is the extension.
	unless ( $ext eq 'po' ){
	    print "<h3>$lex{'The file must be a .po file'}</h3>\n";
	    print "</body></html>\n";
	    exit;
	}

	pop(@name); # pull off extension.
	foreach $n (@name){ $name .= "$n.";} # assemble name 
	chop; # remove trailing dot
    
	#print "Name: $name Extension: $ext<br>\n";

	open ( OUTFILE, ">$filename") || 
	    die $lex{'Cannot open file'}. " $filename"; 
	my $bufcount = 0;
	while ( my $bytesread = read( $file, my $buffer, 1024) ) { 
	    print OUTFILE $buffer;
	    $bufcount++;
	    if ( $bufcount > $maxbufcount ) {
		print "<h1>$lex{'Maximum File Upload size exceeded'}";
		print " ($maxbufcount K)</h1>\n";
		print "</body></html>\n";
		exit;
	    }
	}

	close (OUTFILE);

    } else {
	print $lex{'Cannot open file'};
	print "</body></html>\n";
    }

    # We should now have the file in place.
    # Open PO file for reading

    unless ( open ( FH,"<$filename" ) ) {
	print $lex{'Cannot open file'}. ": $!\n";
	die $lex{'Cannot open file'}. ": $!\n";
    }

    my $transcount = 1;

    while ( my $line = <FH> ) {

	if ( $line =~ s/msgid//) {
	    my $transline = <FH>;
	    chomp $transline;
	    $transline =~ s/^\s*//; # strip leading whitespace
	    $transline =~ s/^msgstr//; # strip leading id.
	    $transline =~ s/^\s*//; # strip leading whitespace
	    $transline =~ s/^"//; # strip leading double quote
	    $transline =~ s/^'//; # strip leading single quote
	    $transline =~ s/"$//; # strip trailing double quote

	    chomp $line;
	    $line =~ s/^\s*//; # strip leading whitespace
	    $line =~ s/^"//; # strip leading double quote
  	    $line =~ s/^'//; # strip leading single quote
	    $line =~ s/"$//; # strip trailing double quote

	    # print "Line:$line -:$transline<br>\n";

	    my $sth = $dbh->prepare("select id, translation, phrase from xlat_lang 
              where phrase = ?");
	    $sth->execute( $line );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	    my ( $id, $translation, $testphrase );
	    while ( ( $id, $translation, $testphrase ) = $sth->fetchrow ) {
		if ( $line eq $testphrase ) { last; }
	    } 

	    if ( $id ) { # update existing record

		if ( $translation ne $transline and $replace ) { 
		    # replace if not same and $replace=1
		    my $sth1 = $dbh->prepare("update xlat_lang set translation = ?
                      where id = $id");
		    $sth1->execute( $line );
		    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		    print "TR1:$translation TR2:$transline<br> ";
		}

	    } else { # no existing value, insert a record

		$sth = $dbh->prepare("insert into xlat_lang ( phrase, translation ) 
                  values ( ?, ? )");
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		$sth->execute( $line, $transline );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

		# utf8::decode( $transline);

		print "$transcount. NEW $line | $transline<br>\n";
		$transcount++;
	    } 
	}

    }

    close FH;
    system("rm -f $filename"); # clean up.

    print "<h1>". $lex{'Update Complete'}. "</h1>\n";

    print "</center></body></html>\n";

    exit;

}


#----------------
sub showStartPage {
#----------------

    print "<center><table cellpadding=\"3\" cellspacing=\"0\" border=\"0\">\n";

    print "<form action=\"$self\" method=\"post\"  enctype=\"multipart/form-data\">\n";
    print "<input type=\"file\" name=\"filename\">\n";
    print "<input type=\"hidden\" name=\"page\" value=\"1\">\n";

    print "<tr><td align=\"right\">". $lex{'Replace Existing Values'};
    print "</td>\n<td><input type=\"checkbox\" name=\"replace\" value=\"1\">";
    print "</td></tr>\n";

    print "<tr><td colspan=\"2\" align=\"center\">";
    print "<input type=\"submit\" value=\"". $lex{'Upload Translation file'}. "\">\n";
    print "</td></tr></form></table></body></html>\n";

    exit;

}
