<?php
/**
 * @package JAdmin!
 * @version 1.5.3.0
 * @copyright (C) Copyright 2008-2010 CMS Fruit, CMSFruit.com. All rights reserved.
 * @license GNU/LGPL http://www.gnu.org/licenses/lgpl-3.0.txt

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU Lesser 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 Lesser General Public
 License for more details.

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

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

if(JRequest::getVar('debug', null, 'method'))
{
    ini_set('display_errors', 'On');
    ini_set('error_reporting', E_ALL);
}
else
{
    ini_set('display_errors', 'Off');
}

jimport('joomla.plugin.plugin');

class plgSystemJAdmin extends JPlugin
{
    var $_initialized = false;
    var $_processPlugin = false;
    var $_comPath = null;
    var $_setting = null;
    var $_tracked = false;

    function plgSystemJAdmin( &$subject, $config )
    {
	parent::__construct( $subject, $config );

	jimport('joomla.application.component.model');
    }

    function _initPlugin()
    {
	if($this->_initialized) return true;

	$this->_initialized = true;

	$this->_comPath = JPATH_SITE.DS.'components'.DS.'com_jadmin';

	$app =& JFactory::getApplication();

	if($app->getName() != 'site') return false;

	$settingsPath = $this->_comPath.DS.'models'.DS.'setting.php';

	if(!file_exists($settingsPath)) return false;

	require_once $settingsPath;

	if($app->getName() != 'site')
	{
	    $this->_processPlugin = false;
	}
	else
	{
	    $this->_processPlugin = true;
	}

	$this->_setting =& JModel::getInstance('Setting', 'JAdminModel');

	//  If the settings object was not found, don't continue
	if(!is_object($this->_setting)) $this->_processPlugin = false;

	$uri =& JFactory::getURI();

	if(strpos($uri->toString(), 'do_not_log')) $this->_processPlugin = false;
    }

    function onAfterRoute()
    {
	$app =& JFactory::getApplication();

	if($app->getName() == 'administrator')
	{
	    // For admin site
	    $modelPath = JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_jadmin'.DS.'models'.DS.'useradmin.php';

	    if(!file_exists($modelPath)) return false;

	    require_once $modelPath;

	    $userObj =& JModel::getInstance('UserAdmin', 'JAdminModel');

	    $userObj->enforceAdminPermissions();

	    $action = JRequest::getVar('action', null, 'method');

	    switch($action)
	    {
		case 'login_as_admin':
		    $adminAuthKey = JRequest::getVar('k', null, 'method');

		    $authKeyDetails = $userObj->isGatewayAuthKeyValid($adminAuthKey);

		    if(!$authKeyDetails || empty($adminAuthKey) || empty($action)) jexit('Access Denied');

		    $userObj->loginAsAdminUser($authKeyDetails['user_id']);

		    $returnUrl = urldecode(JRequest::getVar('r', null, 'method'));
		    
		    global $mainframe;

		    $mainframe->redirect($returnUrl);
		    
		    jexit();
	    }
	}
	elseif($app->getName() == 'site')
	{
	    if(JRequest::getCmd('option') == 'com_jadmin' && JRequest::getCmd('view') == 'api' && JRequest::getCmd('task') == 'api')
	    {
		$lang =& JFactory::getLanguage();
		$lang->load('com_jadmin');

		$modelPath = JPATH_SITE.DS.'components'.DS.'com_jadmin'.DS.'models'.DS.'server.php';

		if(!file_exists($modelPath)) return false;

		require_once $modelPath;

		$model =& JModel::getInstance('Server', 'JAdminModel');
		$model->api_serve();
	    }
	    elseif(JRequest::getCmd('option') == 'com_jadmin' && JRequest::getCmd('view') == 'api' && JRequest::getCmd('task') == 'gateway')
	    {
		global $mainframe;

		$modelPath = JPATH_SITE.DS.'components'.DS.'com_jadmin'.DS.'models'.DS.'user.php';

		if(!file_exists($modelPath)) return false;

		require_once $modelPath;

		$userObj =& JModel::getInstance('User', 'JAdminModel');

		$adminAuthKey = JRequest::getVar('k', null, 'method');
		$action = JRequest::getVar('action', null, 'method');

		if(!$userObj->isGatewayAuthKeyValid($adminAuthKey) || empty($adminAuthKey) || empty($action)) jexit('Access Denied');

		switch($action)
		{
		    case 'login_as_user':
			$userId = JRequest::getInt('uid', null, 'method');

			if(!empty($userId))
			{
			    $options = array();

			    $user =& JUser::getInstance($userId);

			    $response = new stdClass();
			    $response->email = $user->email;
			    $response->username = $user->username;
			    $response->fullname = $user->name;
			    $response->status = 1;
			    $response->error_message = '';

			    // Import the user plugin group
			    jimport('joomla.plugin.helper');

			    JPluginHelper::importPlugin('user');

			    // OK, the credentials are authenticated.  Lets fire the onLogin event
			    $mainframe->triggerEvent('onLoginUser', array((array)$response, $options));

			    $mainframe->redirect('index.php', 'You are now logged in as '.$response->username.'!');

			    jexit();
			}

			break;
		}
	    }
	}
    }

    function onAfterInitialise()
    {
	$this->_checkIPBlockerRules();
    }

    function _checkIPBlockerRules()
    {
	$this->_initPlugin();

	$modelPath = $this->_comPath.DS.'models'.DS.'ipblocker.php';

	if(!file_exists($modelPath)) return false;

	require_once $modelPath;

	$ipblocker =& JModel::getInstance('IPBlocker', 'JAdminModel');

	if(is_object($ipblocker)) $ipblocker->enforce();
    }

    function _trackVisitor()
    {
	if($this->_tracked) return true;

	if(!is_object($this->_setting)) return false;

	$this->_tracked = true;

	$modelPath = $this->_comPath.DS.'models'.DS.'visitor.php';

	if(!file_exists($modelPath)) return false;

	require_once $modelPath;

	$visitor =& JModel::getInstance('Visitor', 'JAdminModel');
	$visitor->track();
    }

    function onAfterRender()
    {
	$this->_initPlugin();

	if(!$this->_processPlugin) return false;

	$this->_trackVisitor();
    }
}