<?php
/*
 *
 * @package		ARI Smart Content
 * @author		ARI Soft
 * @copyright	Copyright (c) 2011 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 */

(defined('_JEXEC') && defined('ARI_FRAMEWORK_LOADED')) or die;

AriKernel::import('Joomla.Controllers.Controller');

class AriSmartContentControllerAjaxdispatcher extends AriController 
{
	function ajaxCall()
	{
		$result = null;

		$jInput = JFactory::getApplication()->input;
		$dispatcher = $jInput->request->get('__dispatcher', null, 'RAW');
		$method = $jInput->request->get('__method', null, 'RAW');

		if (empty($dispatcher) || empty($method))
			return $result;
			
		$dispatcher = explode(':', $dispatcher);
		if (count($dispatcher) < 2)
			return $result;
			
		$pathToDispatcher = null;
		switch ($dispatcher[0])
		{
			case 'library':
				$pathToDispatcher = JPATH_LIBRARIES;
				break;
				
			case 'module':
				$pathToDispatcher = JPATH_ROOT . '/modules';
				break;
				
			case 'plugin':
				$pathToDispatcher = JPATH_PLUGINS;
				break;
		}

		if (empty($pathToDispatcher))
			return $result;

		$extPrefix = '';
		$extPath = explode('$', $dispatcher[1]);
		for ($i = 0; $i < count($extPath); $i++)
		{
			if (!preg_match('/^[A-z0-9_-]+$/i', $extPath[$i]))
				return $result;

			$extPrefix .= ucfirst($extPath[$i]);
		}

		$extPath = join('/', $extPath);
		$pathToDispatcher .= '/' . $extPath . '/ajax/dispatcher.php';

		if (!file_exists($pathToDispatcher))
			return $result;

		require_once $pathToDispatcher;

		$className = 'AriSmartContent' . ucfirst($dispatcher[0]) . $extPrefix . 'AjaxDispatcher';
		if (!class_exists($className))
			return $result;

		$dispatcherInstance = new $className();
		$methodName = 'ajax_' . $method;
		if (!method_exists($dispatcherInstance, $methodName))
			return $result;

		$result = $dispatcherInstance->$methodName();
		
		return $result;
	}
}