#!/usr/bin/perl
#
# BNCweb: A user-friendly interface to the British National Corpus - Version 4.3
# Copyright (C) 2005-10 Hoffmann/Evert/Lehmann
#
# Updates and information available at http://www.bncweb.info
#
# This file is part of BNCweb.
# 
# BNCweb 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 3 of the License, or
# (at your option) any later version.
# 
# BNCweb is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

#
# based on BNCweb Version 2.0:
# © 1996/2004 Lehmann/Hoffmann/Schneider
#

use CGI;

use lib "../lib_files";
use bncLibCQPXML;
use DBI;

$query = new CGI; 

$username = $ENV{'REMOTE_USER'};

$filename = $query->param("corpusPositions"); 
$theName = $query->param("name"); 
$filename =~ s/.*[\/\\](.*)/$1/; 

# connect to mysql
$bncHandle = DBI->connect("DBI:mysql:$bwMYSQLtable:$bwMYSQLhost:$bwMysqlPort", "$bwMysqlUser", "$bwMysqlPwd") or bark("Can't connect to mysql on $bwMYSQLhost at port: $bwMysqlPort <BR>" . $userHandle::errstr);

if ($theName=~m/[^a-zA-Z0-9_]/) {
	# print error message
	&printHeader("Error message");
	print <<END;
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Error message</B></FONT></TD>
	</TR>
	<TR>
		<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
			<BR><B>Names for saved queries can only contain letters, numbers and the underscore character (&quot;_&quot;)!</B><BR><BR>
			Please use the &quot;back&quot;-button of your browser and change your input 
			accordingly.<BR><BR>
		</TD>
	</TR>
	</TABLE>
END
	&printFooter();
	exit(0);
}


$theNameFull = $username . "_" . $theName;
$theNameFull=$bncHandle->quote($theNameFull);

# check name
$sqlQuery = "SELECT * FROM savedQueries WHERE theName=$theNameFull and user='$username'";
$sth= $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
$sth->execute or bark("Can't execute $sqlQuery: " . $sth::errstr);
$res = $sth->rows;
if ($res) {
	

	&printHeader("Error message");
	print <<END;
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Error message</B></FONT></TD>
	</TR>
	<TR>
		<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
			<BR><B>A saved query with the name &quot;$theName&quot; already exists.</B><BR><BR>
			This feature does not support automatic overwrite of existing files. Please use the &quot;back&quot;-button of your browser and change your input 
			accordingly. Alternatively, first delete the existing saved query in the \"<A HREF=\"/$bwCGIalias/BNCquery.pl?theQuery=savedQueries&user=$username&chunk=1&urlTest=yes\">Saved queries</A>\" feature.<BR><BR>
		</TD>
	</TR>
	</TABLE>
END


	# print the end of html
	&printFooter();
	exit(0);
	
}

$upload_filehandle = $query->upload("corpusPositions"); 

$theNameFull = $username . "_" . $theName;


open UPLOADFILE, ">/$bwTempPath/${theNameFull}_temp" or die "can't open $bwTempPath/$bwCorpus:$theNameFull_temp"; 

binmode UPLOADFILE; 

while ( <$upload_filehandle> )  { 
	print UPLOADFILE; 
}

close UPLOADFILE; 

qx{cat /$bwTempPath/${theNameFull}_temp | perl -pe 's/\\x0d\\x0a?/\x0a/g' > /$bwTempPath/${theNameFull}_temp2};

# check input format and add number of lines at the beginning.
open IN, "</$bwTempPath/${theNameFull}_temp2" or die "can't open $bwTempPath/$bwCorpus:$theNameFull_temp2"; 
open OUT, ">/$bwTempPath/${theNameFull}_temp3" or die "can't open $bwTempPath/$bwCorpus:$theNameFull_temp3"; 


$theCount = 0;
$numOfSolutions = 0;
$firstLine = 1;
while (<IN>) {
	$line = $_;
	$theCount++;
	warn $theCount;
	$check = $line=~m/\A(\d+\t\d+)\012*\Z/;
	if ($check) {
		$numOfSolutions++;
		print OUT "$line";
	} else {
		warn $line;
		unless ($firstLine) {
			$error = 1;
			last;
		}
	}
	$firstLine = 0;
}
close(IN);
close(OUT);


if ($error) {
	&printHeader("Error message");
	print <<END;
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Error message</B></FONT></TD>
	</TR>
	<TR>
		<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
			<BR><B>Your uploaded file has a format error.</B><BR><BR>
			The file must only consist of two columns of numbers (separated by a tab-stop).<BR><BR>
		</TD>
	</TR>
	</TABLE>
END


	# print the end of html
	&printFooter();
	exit(0);
	

}


#######################################	
CQPconnect(full);


qx{echo $numOfSolutions | cat - '/$bwTempPath/${theNameFull}_temp3' > '/$bwTempPath/$theNameFull'};


$CQP->exec("undump $theNameFull < '/$bwTempPath/$theNameFull'");


$CQP->exec("set DataDirectory '/$bwTempPath/'");
$CQP->exec("$bwCorpus");

$CQP->exec("save $theNameFull");
@lines = $CQP->exec("group $theNameFull match text_id");	# list of documents with frequencies
$numOfFiles = @lines;
@stat = stat("/$bwTempPath/$bwCorpus:$theNameFull");
$fileSize = $stat[7];


# put query in saved queries database 
$theTime = int(time);
$thModeInsert = "M${numOfSolutions}#${numOfFiles}#no_subcorpus####I$theName";
$thModeInsert = $bncHandle->quote($thModeInsert);

$theDataLink = "theData=dummy&chunk=1&inst=50&max=INIT";
$theDataLinkQuote = $bncHandle->quote($theDataLink);

$insertTheData = $bncHandle->quote($sQuery);
$insertTheDataSimple = $bncHandle->quote($sSimpleQuery);
$time = time;

$sqlQuery = "insert into savedQueries (user, queryID, thMode, hits, time_of_query, saved, theName, initialQuery, fileSize, originalFile, theID, link, simpleQuery, query, subcorpus) 
			values ('$username', '$theNameFull', $thModeInsert, $numOfSolutions, $time, 1, '$theNameFull', 0, $fileSize, '$theNameFull', '$theNameFull', $theDataLinkQuote, 'dummy', 'dummy', '###')";
$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery: " . $bncHandle::errstr);

&CQPdisconnect();

# remove all temporary files
unlink("/$bwTempPath/${theNameFull}_temp") if -f "/$bwTempPath/${theNameFull}_temp";
unlink("/$bwTempPath/${theNameFull}_temp2") if -f "/$bwTempPath/${theNameFull}_temp2";
unlink("/$bwTempPath/${theNameFull}_temp3") if -f "/$bwTempPath/${theNameFull}_temp3";
unlink("/$bwTempPath/$theNameFull") if -f "/$bwTempPath/$theNameFull";


print "Location: /$bwCGIalias/BNCquery.pl?theQuery=savedQueries&user=$username&chunk=1&urlTest=yes\n\n";

exit(0);

