#!/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 lib "../lib_files";
use bncLibCQPXML;

use DBI;

$username = $ENV{'REMOTE_USER'};
$thisProg='savedQueryAdmin.pl';
$referer=$ENV{'HTTP_REFERER'};
	
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");
}


# make sure only super-users can rename all saved queries
if ($username ne $params{username}) {
	setParam("username", "$username") unless (($username=~m/\A($bwSuperuser)\Z/) || (&checkSuperUser2()));
} else {
	setParam("username", "$username");
}


$title ='<TR><TD HEIGHT="27" COLSPAN="2" BGCOLOR="#CCCCFF"> <FONT SIZE="4"><B>Saved Queries Administration Page</B></FONT></TD></TR>';


if ($params{action} eq "choose") {
	&printTheHead();
	if ($params{oldName}) {
		$copy = $params{oldName} . "_copy";
	} else {
		$copy = "";
	}
	$copy=~s/\A${params{username}}_//i;
	
	print <<END;

	<FORM ACTION="/$bwCGIalias/${thisProg}" METHOD=GET>
	<INPUT TYPE="hidden" NAME="action" VALUE="enter">
	
	<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=2>
	$title
	<TR>
		<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#DDDDDD">
			Please enter a new name for your saved query '$params{oldName}':
		</TD>
	</TR>
	<TR>
		<TD HEIGHT="27" COLSPAN="1" BGCOLOR="#DDDDDD">
			<INPUT TYPE="text" NAME="newName" VALUE="$copy" SIZE=34 MAXLENGTH=34>
		</TD>
		<TD HEIGHT="27" COLSPAN="1" BGCOLOR="#DDDDDD">
			<INPUT TYPE="hidden" NAME="oldName" VALUE="$params{oldName}">
			<INPUT TYPE="hidden" NAME="username" VALUE="$params{username}">
			<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
			<INPUT TYPE="submit" VALUE="Submit name">
			</FORM>
		</TD>
	</TR>
	</TABLE>
END
	&printFooter();
	exit(0);


} elsif ($params{action}=~m/overwrite|enter/) {
	# 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>$bncHandle::errstr\n");
	
	$sqlQuery = "SELECT thMode FROM savedQueries where theName=concat('$params{username}', '_', '$params{newName}')";
	$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{action} ne "overwrite")) {
		# warn user that saved query already exists
		&printTheHead();
		print <<END;
		<TABLE BORDER="0" WIDTH="100%" CELLPADDING=3 CELLSPACING=3>
		<TR>
			<TD HEIGHT="27" COLSPAN="2" BGCOLOR="#FF6666"><FONT SIZE="4"><B>Saved Query Name Alert</B></FONT></TD>
		</TR>
		<TR>
			<TD BGCOLOR="#DDDDDD" COLSPAN="2" HEIGHT="37">
				<B>A saved query with the name <I>$params{newName}</I> already exists.</B><BR>
			</TD>
		</TR>
		
		<TR>
			<FORM ACTION="/$bwCGIalias/$thisProg" METHOD=GET>
				<TD BGCOLOR="#CCCCCC" WIDTH="50%">
					<INPUT TYPE="hidden" NAME="action" VALUE="overwrite">
					<INPUT TYPE="hidden" NAME="oldName" VALUE="$params{oldName}">
					<INPUT TYPE="hidden" NAME="newName" VALUE="$params{newName}">
					<INPUT TYPE="hidden" NAME="username" VALUE="$params{username}">
					<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
					<INPUT TYPE="submit" VALUE="Overwrite \'$params{newName}\'">
				</TD>
			</FORM>
			<FORM ACTION="/$bwCGIalias/$thisProg" METHOD=GET>
				<TD BGCOLOR="#CCCCCC">
					<INPUT TYPE="hidden" NAME="action" VALUE="choose">
					<INPUT TYPE="hidden" NAME="oldName" VALUE="$params{oldName}">
					<INPUT TYPE="hidden" NAME="newName" VALUE="$params{newName}">
					<INPUT TYPE="hidden" NAME="username" VALUE="$params{username}">
					<INPUT TYPE="hidden" NAME="urlTest" VALUE="yes">
					<INPUT TYPE="submit" VALUE="Change name">
				</TD>
			</FORM>
		</TR>
	</TABLE>
END
		&printFooter();
		exit(0);
	} else {
		
		$sqlQuery = "SELECT thMode FROM savedQueries where theName='$params{oldName}'";
		$sth1 = $bncHandle->prepare($sqlQuery) or bark("Can't prepare $sqlQuery:" . $bncHandle::errstr);
		$sth1->execute or bark("Can't execute $sqlQuery: $sth::errstr");
		@mysqlArray=$sth1->fetchrow_array;
		$thMode=$mysqlArray[0];
		
		$newName = $params{username} . "_" . $params{newName};
		
		if (($res) && ($params{action} eq "overwrite")) {
			$sqlQuery = "DELETE FROM savedQueries where theName = '$newName'";
			unlink("/$bwTempPath/$bwCorpus:$newName") if -f "/$bwTempPath/$bwCorpus:$newName";
			$bncHandle->do($sqlQuery) or bark("Can't do $sqlQuery: " . $bncHandle::errstr);			
		}
		
		if ($thMode=~s/(#+I)([^#]+)/$1$params{newName}/) {
			$thModeQuote = $bncHandle->quote($thMode);			
			$sqlQuery = "UPDATE savedQueries SET theName = '$newName', thMode = $thModeQuote where theName = '$params{oldName}'";
		} else {
			$sqlQuery = "UPDATE savedQueries SET theName = '$newName' where theName = '$params{oldName}'";
		}
		$bncHandle->do($sqlQuery) or bark("Can't do $sqlQuery:" . $bncHandle::errstr);
		qx{mv "/$bwTempPath/$bwCorpus:$params{oldName}" "/$bwTempPath/$bwCorpus:$newName"};

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


sub printTheHead {
	print "Content-type: text/html\n\n";
	print <<END;

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
	<HTML>
	<HEAD>
	
	<TITLE>Saved Queries Administration Page</TITLE>

	<META NAME="generator" CONTENT="BBEdit 4.5">
	<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=iso-8859-1">
	</HEAD>
	<BODY BGCOLOR="#FFFFFF">
END

}
