<?php
ini_set('display_errors',0);
// add mz 2014-12-30
// new EntryPoint to handle ajax request sending to /include/ECM
// based on: http://support.sugarcrm.com/02_Documentation/04_Sugar_Developer/Sugar_Developer_Guide_6.7/02_Application_Framework/Entry_Points/02_Creating_Custom_Entry_Points/

// check basic params
if (! $_REQUEST ['ecmclass'] || $_REQUEST ['ecmclass'] == "" || ! is_dir ( "include/ECM/" . $_REQUEST ['ecmclass'] )) 
	myDie ('No class specified.');

$controller = $_REQUEST['ecmclass'].'Controller';
$path = 'include/ECM/'.$_REQUEST['ecmclass'].'/'.$controller.'.php';

include_once $path;
if (!class_exists($controller, false))
	myDie('Missing class controler');

$c = new $controller();
if (! is_object($c))
	myDie('Class controller exception');

if (! $_REQUEST ['job'] || $_REQUEST ['job'] == "" || !method_exists($c, $_REQUEST['job']))
	myDie('No method specified');

$rc = new ReflectionClass($controller);
$pCount = $rc->getMethod($_REQUEST['job'])->getNumberOfRequiredParameters();
unset($rc);

if ($pCount > 0 && (!$_REQUEST['params'] || $_REQUEST['params']==""))
	myDie('Params exception');

$params = json_decode(base64_decode($_REQUEST['params']));

if ($pCount>0 && ! is_array($params) && $pCount > sizeof($params))
	myDie('Params exception ');

//REQUEST data checked, now execute job
if (! defined ( 'sugarEntry' ))
	define ( 'sugarEntry', true );

if (is_array($params) && sizeof($params) > 0)
	$res = call_user_func_array(array($c,$_REQUEST['job']), $params);
else 
	$res = $c->$_REQUEST['job']();
echo json_encode($res);

sugar_cleanup();
exit();

//little helper fn
function myDie($msg) {
	echo json_encode(array ($msg));
	sugar_cleanup();
	exit;
}