#!/usr/bin/perl -w -T
#*******************************************************************************
#* Copyright (c) 2013 Forschungszentrum Juelich GmbH.
#* All rights reserved. This program and the accompanying materials
#* are made available under the terms of the Eclipse Public License v1.0
#* which accompanies this distribution, and is available at
#* http://www.eclipse.org/legal/epl-v10.html
#*
#* Contributors:
#*    Carsten Karbach (Forschungszentrum Juelich GmbH) 
#*******************************************************************************/ 
use strict;
use Time::HiRes;
use CGI::Carp 'fatalsToBrowser';

#Overwrite environment with safe paths
local $ENV{"PATH"} = ""; 
local $ENV{"BASH_ENV"}="";

#Read post arguments
my $buffer;
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
	read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}

my @pairs = split(/&/, $buffer);
my %FORM;
foreach my $pair (@pairs)
{
	my ($name, $value) = split(/=/, $pair);
	$value =~ tr/+/ /;
	$value =~ s/%(..)/pack("C", hex($1))/eg;
	$FORM{$name} = $value;
}

print "Content-type: text/html\n\n";
print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta content="text/html; charset=ISO-8859-1"
 http-equiv="Content-Type">
  <title>lmldoc</title>
</head>
<body>';

print '<h1>Online LML validator</h1><br/><br/>';
print 'Just place your LML file into the text box and press <b>validate</b> 
to start the validation process described <a href="lmlvalidation.html">here</a><br/><br/>';

print '<form action="onlinevalidator.cgi" method="post">
LML-File:<br/>
<textarea name="lmlfile" cols="80" rows="25">';
#Print the previously sent LML file into input text area if available, otherwise default simple LML file
if(! isInputValid()){
	print '<?xml version="1.0" encoding="UTF-8"?>
<lml:lgui xmlns:lml="http://eclipse.org/ptp/lml" 
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  xsi:schemaLocation="http://eclipse.org/ptp/lml lgui.xsd"
	  version="1.0">
    <request>
        <driver name="TORQUE"/>
        <layoutManagement getDefaultData="true"/>
    </request>
</lml:lgui>';
}
else{
	print $FORM{lmlfile};
}
print '</textarea>
<br/>
<input type="submit" value=" validate ">
</form><br/><br/>';

#Handle LML sent via POST

if(isInputValid() ){
	#Save post lml file to a tmp file
	my $time = time;
	my $lmlName = "/tmp/lml_$time.lml";
	
	open LML, ">", $lmlName or die $!;
	print LML $FORM{lmlfile};
	
	close LML;
	#Call java 1.7 
	my $cmd = "/usr/bin/java";

	my $valid = 0;
	open(VAL, "-|") or exec ($cmd, "-jar", "/home/karbach/tools/Validator/lmlcheck.jar", "$lmlName");
	my @details = <VAL>;
	#Check if file is evaluated to be valid
	foreach my $line(@details){
		if($line =~ /LML-File is valid/){
			$valid = 1;
		}
	}

	if($valid){
		print '<font color="#00BB00">This LML file is valid</font>';
	}
	else{
		print '<font color="#FF0000">This LML file is invalid</font>';
	}
	#Print detailed results provided by lmlcheck.jar
	print '<br/><br/>Detailed results:<br/>';
	
	print '<textarea name="validatorResults" cols="80" rows="25">';
	print join("", @details);
	print '</textarea><br/>';
	
	#Delete lml file afterwards
	my $status = system("/bin/rm", "$lmlName");
}
elsif(defined $FORM{lmlfile}){
	print '<font color="#FF0000">';
	print "Your input LML file is not valid. It might be too long or contains not allowed characters.<br/>";
	print "Please use the lml validator locally, which you can download from this page.<br/>";
	print "Or try to adapt your LML file.<br/>";
	print '</font>';
}

open LOG, ">>", "/home/karbach/tools/onlinevalidator.log" or die $!;
print LOG localtime()."\n";
close LOG;

#Print footer
open IN, "<", "footer.html" or die $!;

while(my $line=<IN>){
	print $line;
}

print '</body>
</html>';

#**********************
# @return true, if user input is allowed, false otherwise
#**********************
sub isInputValid{
	if(defined $FORM{lmlfile}){
		#Do not allow characters, which are not valid in XML files
		if($FORM{lmlfile} =~ /[\x01-\x08\x0B-\x0C\x0E-\x1F\x7F-\x84\x86-\x9F]/){
			return 0;
		}
		#Allow a maximum input length of 500 KByte
		return $ENV{'CONTENT_LENGTH'}<500000;
	}
	else{
		return 0;
	}
}

1;
