#!/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
#


# wird fuer sub solve benoetigt
use lib "../lib_files";
use bncLibCQPXML;
use DBI;
## ***DEL***
# use CWB;
# use CQP;
# use CL;

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

$username = $ENV{'REMOTE_USER'};

unless (getParams($ENV{'QUERY_STRING'})) {
	barkFull("incomplete transmition of URL<BR>This problem is likely to occur in combination with proxy servers<BR>turn off your web-proxy and try again");
}

barkFull("didn't get any information on the number of hits in $params{numOfSolutions}") unless ($params{numOfSolutions});

if ($params{action} eq "getName") {
	getName();
} elsif ($params{action} eq "save") {
	save();
}


sub getName {

	$theData2=&encodeForm($params{theData});
	
	print "Content-type: text/html\n\n";
	
	print <<END;
	
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
	<HTML>
	<HEAD>
	
	<TITLE>Saving a query result</TITLE>
	<META NAME="generator" CONTENT="BBEdit 4.5">
	<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
	</HEAD>
	<BODY BGCOLOR="#FFFFFF">
	
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	
		<TR>
			<TD HEIGHT="27" COLSPAN="3" BGCOLOR="#CCCCFF"> <FONT SIZE="4"><B>Saving a query result</B></FONT></TD>
		</TR>
		
		<FORM ACTION="/$bwCGIalias/save.pl" METHOD=GET>
			<INPUT TYPE="hidden" NAME="inst" VALUE="$params{inst}">
			<INPUT TYPE="hidden" NAME="max" VALUE="$params{max}">
			<INPUT TYPE="hidden" NAME="chunk" VALUE="$params{chunk}">
			<INPUT TYPE="hidden" NAME="qname" VALUE="$params{qname}">
			<INPUT TYPE="hidden" NAME="queryID" VALUE="$params{queryID}">
			<INPUT TYPE="hidden" NAME="thMode" VALUE="$params{thMode}">
			<INPUT TYPE="hidden" NAME="thin" VALUE="$params{thin}">
			<INPUT TYPE="hidden" NAME="theData" VALUE="$theData2">
			<INPUT TYPE="hidden" NAME="warned" VALUE="$params{warned}">
			<INPUT TYPE="hidden" NAME="numOfSolutions" VALUE="$params{numOfSolutions}">
			<INPUT TYPE="hidden" NAME="numOfFiles" VALUE="$params{numOfFiles}">
			<INPUT TYPE="hidden" NAME="view" VALUE="$params{view}">
			<INPUT TYPE="hidden" NAME="dbname" VALUE="$params{dbname}">
			<INPUT TYPE="hidden" NAME="SQL" VALUE="$params{SQL}">
			<INPUT TYPE="hidden" NAME="letter" VALUE="$params{letter}">
			<INPUT TYPE="hidden" NAME="tag" VALUE="$params{tag}">
			<INPUT TYPE="hidden" NAME="ot" VALUE="$params{ot}">
			<INPUT TYPE="hidden" NAME="display" VALUE="$params{display}">
			<INPUT TYPE="hidden" NAME="sortpos" VALUE="$params{sortpos}">
			<INPUT TYPE="hidden" NAME="exclude" VALUE="$params{exclude}">
			<INPUT TYPE="hidden" NAME="program" VALUE="$params{program}">
			<INPUT TYPE="hidden" NAME="action" VALUE="save">
			<INPUT TYPE="hidden" NAME="theID" VALUE="$params{theID}">
			
			
		<TR>
			<TD WIDTH="31%" HEIGHT="40" BGCOLOR="#DDDDDD">Please enter a name for your query:</TD>
			<TD COLSPAN="2" WIDTH="69%" BGCOLOR="#DDDDDD">
				<INPUT TYPE="TEXT" NAME="theName" SIZE="30" MAXLENGTH="30">
				<INPUT TYPE="SUBMIT" VALUE="Go!">
				<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
			</TD>
		</TR>
			<TR>
				<TD COLSPAN="3" BGCOLOR="#DDDDDD">
					The name for your saved query may be up to 30 characters long. After entering the word you will 
					be taken back to the previous query result display. The saved query can be accessed through the 
					"Saved queries" link on the main page.
				</TD>
			</TR>
		</FORM>
		</TABLE>
END
	
	# print footer
	&printFooter();
	
	exit(0);

}

sub save {

	my $error = 0;
	$error++ if ($params{theName}=~m/[^a-z0-9_]/);

	if ($error) {
		# 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);
	}

	$theName = $username . "_" . $params{theName};
	setParam("theName", "$theName");
	$theName=$bncHandle->quote($params{theName});
	
	# check name first
	$sqlQuery = "SELECT * FROM savedQueries WHERE theName=$theName 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) && (!$params{checkedDuplicate})) {
		
		$dispName = $params{theName};
		$dispName=~s/\A${username}_//;
		print "Content-type: text/html\n\n";
	
		print <<END;
	
		<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
		<HTML>
		<HEAD>
		
		<TITLE>Duplicate Name Alert!</TITLE>

		<META NAME="generator" CONTENT="BBEdit 4.5">
		<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
		</HEAD>
		<BODY BGCOLOR="#FFFFFF">
		
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
		
		<FORM ACTION="/$bwCGIalias/save.pl" METHOD=GET>
			<INPUT TYPE="hidden" NAME="inst" VALUE="$params{inst}">
			<INPUT TYPE="hidden" NAME="max" VALUE="$params{max}">
			<INPUT TYPE="hidden" NAME="chunk" VALUE="$params{chunk}">
			<INPUT TYPE="hidden" NAME="qname" VALUE="$params{qname}">
			<INPUT TYPE="hidden" NAME="queryID" VALUE="$params{queryID}">
			<INPUT TYPE="hidden" NAME="thMode" VALUE="$params{thMode}">
			<INPUT TYPE="hidden" NAME="thin" VALUE="$params{thin}">
			<INPUT TYPE="hidden" NAME="theData" VALUE="$params{theData}">
			<INPUT TYPE="hidden" NAME="warned" VALUE="$params{warned}">
			<INPUT TYPE="hidden" NAME="numOfSolutions" VALUE="$params{numOfSolutions}">
			<INPUT TYPE="hidden" NAME="numOfFiles" VALUE="$params{numOfFiles}">
			<INPUT TYPE="hidden" NAME="view" VALUE="$params{view}">
			<INPUT TYPE="hidden" NAME="dbname" VALUE="$params{dbname}">
			<INPUT TYPE="hidden" NAME="SQL" VALUE="$params{SQL}">
			<INPUT TYPE="hidden" NAME="letter" VALUE="$params{letter}">
			<INPUT TYPE="hidden" NAME="tag" VALUE="$params{tag}">
			<INPUT TYPE="hidden" NAME="ot" VALUE="$params{ot}">
			<INPUT TYPE="hidden" NAME="display" VALUE="$params{display}">
			<INPUT TYPE="hidden" NAME="sortpos" VALUE="$params{sortpos}">
			<INPUT TYPE="hidden" NAME="exclude" VALUE="$params{exclude}">
			<INPUT TYPE="hidden" NAME="program" VALUE="$params{program}">
			<INPUT TYPE="hidden" NAME="theName" VALUE="$dispName">
			<INPUT TYPE="hidden" NAME="randomThin" VALUE="$params{randomThin}">
			<INPUT TYPE="hidden" NAME="checkedDuplicate" VALUE="1">
			<INPUT TYPE="hidden" NAME="action" VALUE="save">
			<INPUT TYPE="hidden" NAME="theID" VALUE="$params{theID}">
			<TR>
				<TD HEIGHT="27" BGCOLOR="#FF0000"> <FONT SIZE="4"><B>Duplicate Name Alert!</B></FONT></TD>
			</TR>
			<TR>
				<TD BGCOLOR="#DDDDDD">
					A saved query with the name &quot;$dispName&quot; already exists. 
					It will be owerwritten if you choose the name name for the current set of hits. Please use the &quot;back&quot;-button 
					of your browser if you wish to change your input.
					<BR><B>This action cannot be undone!</B>
				</TD>
			</TR>
			
			<TR>
				<TD ALIGN="CENTER" BGCOLOR="#DDDDDD">
					<INPUT TYPE="SUBMIT" VALUE="Overwrite!">
					<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
				</TD>
			</TR>
		</FORM>
		</TABLE>
END
	
		# print the end of html
		&printFooter();
		exit(0);
		
	} elsif (($res) && ($params{checkedDuplicate})) {
		$sqlQuery = "DELETE FROM savedQueries WHERE theName=$theName and user='$username'";
		$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery: " . $bncHandle::errstr);
	}
	
	#setParam("theData", &decURL($params{theData}));
	
	$newQueryID = $username . "_" . time;
	
	#######################################	
	CQPconnect(full);
	
	
	$CQP->exec("set DataDirectory '/$bwTempPath/'");
	$CQP->exec("$bwCorpus");
	
	($numOfSolutions) = $CQP->exec("size $params{qname}");
	
	$CQP->exec("$params{theName} = $params{qname}");
	$CQP->exec("set DataDirectory '/$bwTempPath/'");
	$CQP->exec("$bwCorpus");
	
	$CQP->exec("save $params{theName}");
	
	@stat = stat("/$bwTempPath/$bwCorpus:$params{theName}");
	$fileSize = $stat[7];
	
	
	# when saving - make a copy of entry as unsaved query and give new queryID!!!
	# huh? Don't know what this means. SH 15.4.2006
	$sqlQuery = "SELECT user, query, thMode, hits, time_of_query, link, simpleQuery  FROM savedQueries WHERE queryID='$params{queryID}'";
	$sth= $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery: " . $bncHandle::errstr);
	$sth->execute or bark("Can't execute $sqlQuery: " . $sth::errstr);
	@array=$sth->fetchrow_array;
	$SQuser=$array[0];
	$SQquery=$array[1];
	$SQthMode=$array[2];
	$SQhits=$array[3];
	$SQtime_of_query=$array[4];
	$SQlink=$array[5];
	$SQsimpleQuery=$array[6];
	
	$SQquery = $bncHandle->quote($SQquery);
	$SQsimpleQuery = $bncHandle->quote($SQsimpleQuery);
	$SQlink = $bncHandle->quote($SQlink);
	
		
	$thModeInsert = $params{thMode};
	$thModeInsert = $bncHandle->quote($thModeInsert);
	$sqlQuery = "insert into savedQueries (user, queryID, query, simpleQuery, thMode, hits, time_of_query, saved, link, theName, initialQuery, fileSize) 
				values ('$username', '$newQueryID', $SQquery, $SQsimpleQuery, $thModeInsert, $params{numOfSolutions}, $SQtime_of_query, 1, $SQlink, $theName, 0, $fileSize)";
	$bncHandle->do($sqlQuery) or bark("Can't insert $sqlQuery: " . $bncHandle::errstr);
	
	
	#setParam("queryID", "$newQueryID");
	#setParam("qname", "$params{theName}");
	#setParam("action", "");
	
	&CQPdisconnect();
	
	$theURL = getURLparams();
	print "Location: /$bwCGIalias/main.pl?" . $theURL . "&urlTest=yes\n\n";
	
exit(0);
}


