<?php
/*
PiAnoS (Picture Annotation System), A fingerprint examiner training tool
Copyright (C) 2011-2012 University of Lausanne, Switzerland
https://ips-labs.unil.ch/pianos

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program 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 Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see http://www.gnu.org/licenses/.
*/


function handleError($errno, $errstr, $errfile, $errline, $errcontext)
{
	throw new Exception("PHP error in ".$errfile."(".$errline."): ".$errstr." (errno=".$errno.")");
}
set_error_handler('handleError');

header("Content-Type: text/plain; charset=utf-8");

try
{	
	if (!isset($_GET['action']))
		throw new Exception("Invalid parameters");

	$filename = NULL;
	if (isset($_GET['filename']) && strlen($_GET['filename']))
	{
		$filename = trim(preg_replace("/[^A-Za-z0-9\\.]/", "", $_GET['filename']), '.');
		if (strlen($filename) == 0)
			$filename = NULL;
	}

	if ($filename === NULL)
		$filename = 'res.json';
		
	$res = array('status'=>'ok');
	switch ($_GET['action'])
	{
	case 'save':
		$data = file_get_contents("php://input");
		file_put_contents($filename, $data);
		break;
	case 'load':
		$res['ret'] = json_decode(file_get_contents($filename));
		break;
	default:
		throw new Exception("Invalid parameters");
	}
	echo json_encode($res);
}
catch (Exception $e)
{
	$message = 	$e->getMessage()."\n".'exception \''.get_class($e).'\' in '.$e->getFile().':'.$e->getLine()."\nStack trace:\n".$e->getTraceAsString();
	echo json_encode(array('status'=>'error', 'message'=>$message));
}
	
?>
