<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/var/www/installer/public_html/officity-source/apps/system/call-operation.php` is part of Officity.

Sushee 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.

Officity and Sushee are distributed in the hope that they 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 Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
	require_once(dirname('__FILE__').'/system.include.php');

	try
	{
		/* 1st. include operation class file */
		if ((URLParam::exists('editor')) && (URLParam::exists('module')))
		{
			$editor_path = APPS_PATH.URLParam::fetch('editor').'/';			
			$module = strtolower(URLParam::fetch('module'));

			// get rid of the namespace	
			$module_parts = explode(':', $module, 2);
			if (isset($module_parts[1]))
			{
				$module = $module_parts[1]; 
			}
						
			$op_script_path = $editor_path.'shared/'.$module.'/'.$module.'-op.class.php';
		}
		else 
		{
			if ((URLParam::exists('editor')) || (URLParam::exists('module')))
			{
				// throw exception
				URLParam::fetch('editor');
				URLParam::fetch('module');
			}
			
			$op_script_path = APPS_PATH.URLParam::fetch('opScriptURI');
		}

		if (!is_file($op_script_path)) 
		{
			throw OfficityException::scriptNotFound(basename($op_script_path), $op_script_path);	
		}
			
		require_once($op_script_path);
		
		/* 2nd. create class instance */
		$OP_CLASS = URLParam::fetch('opObject');
		if (!class_exists($OP_CLASS, false)) 
		{
			throw new OfficityAppException("Unknow object '{$OP_CLASS}'");
		}
		
		$class_instance = new $OP_CLASS();		
		if (!$class_instance instanceOf AbstractOperation) 
		{
			throw new OfficityAppException("'{$OP_CLASS}' is not a valid operation object");
		}
		
		/* 3rd. execute desired class method */
		if ($class_instance->execute(URLParam::fetch('op'), URLParam::fetch('output', 'json')) === false)
		{
			$class_instance->error();
		}
		else
		{
			$class_instance->success();
		}
	}
	catch (OfficityException $e)
	{
		if (URLParam::fetch('output', 'json') == 'json')
		{
			$e->getJSONResponse()->outputError();
		}
		else
		{
			die($e->getHTMLMessage());
		}
	}
?>