<?php
/**
 * Cron handler
 *
 * @package		CSVIVirtueMart
 * @author 		Roland Dalmulder
 * @link 		http://www.csvimproved.com
 * @copyright 	Copyright (C) 2006 - 2012 RolandD Cyber Produksi
 * @license 	GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 * @version 	$Id: cron.php 1892 2012-02-11 11:01:09Z RolandD $
 */

/**
 * Cron handler
 */
// Get the Joomla framework
define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define('JPATH_BASE', substr(str_ireplace('administrator/components/com_csvivirtuemart/helpers/cron.php', '', str_ireplace('\\', '/', __FILE__)), 0, -1));
define('JPATH_COMPONENT_ADMINISTRATOR', JPATH_BASE.'/administrator/components/com_csvivirtuemart');
define('JPATH_COMPONENT', JPATH_COMPONENT_ADMINISTRATOR);

// Require files for the framework
require_once ( JPATH_BASE.'/includes/defines.php' );
require_once ( JPATH_BASE.'/includes/framework.php' );
require_once ( JPATH_BASE.'/administrator/includes/toolbar.php' );
require_once ( JPATH_COMPONENT_ADMINISTRATOR.'/helpers/csvi.php' );

// Load the cron details
$csvicron = new CsviCron();

// Create the Application
$mainframe = JFactory::getApplication('administrator');
$mainframe->initialise();

// Load the language file
$language = JFactory::getLanguage();
$language->load('com_csvivirtuemart', JPATH_BASE.'/administrator');

// Load the plugin system
JPluginHelper::importPlugin('system');

// trigger the onAfterInitialise events
$mainframe->triggerEvent('onAfterInitialise');

// Run the cron job
$csvicron->runCron();

/**
 * Handles all cron requests
 *
 * @package CSVIVirtueMart
 */
class CsviCron {

	/** @var $basepath string the base of the installation */
	var $basepath = '';

	/** @var $_variables array of user set variables to override template settins */
	var $_variables = '';

	/**
	 * Initialise the cron
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.5
	 */
	public function __construct() {
		// Load the posted variables
		$this->CollectVariables();

		// Fill the server global with necessary information
		$_SERVER['REQUEST_METHOD'] = 'post';
		$_SERVER['HTTP_HOST'] = 'example.com/';
		$_SERVER['REMOTE_ADDR'] = gethostbyname('localhost');
		$_SERVER['SERVER_PORT'] = '';
		$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0';
		$_SERVER['REQUEST_URI'] = 'administrator/index.php';
		$_SERVER['QUERY_STRING'] = '';
		// Admin Tools support
		if (isset($this->_variables['adminpw'])) {
			$_SERVER['QUERY_STRING'] = $this->_variables['adminpw'];
			$_SERVER['REQUEST_URI'] .= '?'.$this->_variables['adminpw'];
		}
		// Backend Token support
		if (isset($this->_variables['token'])) {
			$_SERVER['QUERY_STRING'] = $this->_variables['token'];
			$_SERVER['REQUEST_URI'] .= '?token='.$this->_variables['token'];
			$_SERVER['HTTP_REFERER'] = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		}
	}

	/**
	 * Initialise some settings
	 */
	public function runCron() {
		// Buffer all output to prevent conflicts with external software
		ob_start();
		// Start the clock
		$starttime = time();
		$db = JFactory::getDBO();

		// First check if we deal with a valid user
		if ($this->Login()) {
			// Set some global values
			// Get the parameters
			require_once(JPATH_COMPONENT_ADMINISTRATOR.'/models/settings.php');
			$settings = new CsvivirtuemartModelSettings();

			// Check if we are running cron mode and set some necessary variables
			$_SERVER['SERVER_ADDR'] = $_SERVER['HTTP_HOST'] = $settings->getSetting('hostname');
			$_SERVER['SCRIPT_NAME'] = '/index.php';
			$_SERVER['REQUEST_URI'] = '/';
			$_SERVER['PHP_SELF'] = '/index.php';

			// Get the task to do
			if (isset($this->_variables['task'])) $task = JFilterInput::clean($this->_variables['task']);
			else $task = '';

			// Perform the requested task
			switch ($task) {
				case 'maintenance':
					JRequest::setVar('task', $this->_variables['operation']);
					JRequest::setVar('view', 'maintenance' );
					// Fire CSVI VirtueMart
					$this->ExecuteJob();
					break;
				default:
					// Second check if any template is set to process
					if (array_key_exists('template_id', $this->_variables)) $template_id = JFilterInput::clean($this->_variables['template_id'], 'int');
					else $template_id = false;
					if (array_key_exists('template_name', $this->_variables)) $template_name = JFilterInput::clean($this->_variables['template_name']);
					else $template_name = false;

					if ($template_id || $template_name) {
						// There is a template_id or template name, get some details to streamline processing
						$where = empty($template_id) ? 'name='.$db->Quote($template_name) : 'id='.$template_id;

						// There is a template name, get some details to streamline processing
						$q = "SELECT id AS template_id, type AS template_type, name AS template_name, settings
							FROM #__csvivirtuemart_template_settings
							WHERE ".$where;
						$db->setQuery($q);
						$row = $db->loadObject();

						if (is_object($row)) {
							echo JText::sprintf('COM_CSVIVIRTUEMART_PROCESSING_STARTED', date('jS F Y, g:i a'))."\n";
							echo JText::sprintf('COM_CSVIVIRTUEMART_TEMPLATE', $row->template_name)."\n";
							if ($row->template_type) {
								// Set the template ID
								JRequest::setVar('template_id', $row->template_id);
								JRequest::setVar('template_name', $row->template_name);

								// Set the settings
								if (array_key_exists('jform', $this->_variables)) $settings = CsviHelper::arrayExtend(json_decode($row->settings, true), $this->_variables['jform']);
								else $settings = json_decode($row->settings, true);

								// Set some export settings
								if ($row->template_type == 'export') {
									// Export settings
									JRequest::setVar('task', 'exportfile');
									JRequest::setVar('view', 'exportfile');
									// Set export to
									if ($settings['general']['exportto'] == 'todownload') $settings['general']['exportto'] = 'tofile';
								}
								// Set some import settings
								else if ($row->template_type == 'import') {
									// Import settings
									JRequest::setVar('task', 'importfile');
									JRequest::setVar('view', 'importfile');
									// Turn off preview
									$settings['general']['show_preview'] = 0;
								}

								// Post the settings
								JRequest::setVar('jform', $settings, 'post');

								// Fire CSVI VirtueMart
								$this->ExecuteJob();
							}
						}
						else {
							if ($template_name) echo JText::sprintf('COM_CSVIVIRTUEMART_NO_TEMPLATE_FOUND', $template_name)."\n";
							else if ($template_id) echo JText::sprintf('COM_CSVIVIRTUEMART_NO_TEMPLATE_FOUND', $template_id)."\n";
						}
					}
					else echo JText::_('COM_CSVIVIRTUEMART_NO_TEMPLATE_SPECIFIED')."\n";
					break;
			}
		}
		else {
			$error = JError::getError();
			echo $error->message."\n";
		}
		echo sprintf(JText::_('COM_CSVIVIRTUEMART_PROCESSING_FINISHED'), date('jS F Y, g:i a'))."\n";
		$duration = time() - $starttime;
		if ($duration < 60) echo sprintf(JText::_('COM_CSVIVIRTUEMART_PROCESSING_SECONDS'), $duration)."\n";
		else echo sprintf(JText::_('COM_CSVIVIRTUEMART_PROCESSING_MINUTES'), (number_format($duration/60, 2)))."\n";
		// Done, lets log the user out
		$this->UserLogout();

		// Display any generated messages
		$messages = ob_get_contents();
		@ob_end_clean();
		echo $messages;
	}

	/**
	 * Collect the variables
	 *
	 * Running from the command line, the variables are stored in $argc and $argv.
	 * Here we put them in $_REQUEST so that they are available to the script
	 */
	private function CollectVariables() {
		$arguments = false;
		// Take the argument values and put them in $_REQUEST
		if (isset($_SERVER['argv'])) {
			foreach ($_SERVER['argv'] as $key => $argument) {
				if ($key > 0) {
					list($name, $value) = explode("=", $argument);
					if (strpos($value, '|')) $value = explode('|', $value);
					if (strpos($name, ':')) {
						$names = explode(':', $name);
						if (count($names) == 3 && $names[0] == 'jform') {
							$this->_variables['jform'][$names[1]][$names[2]] = $value;
						}
					}
					else $this->_variables[$name] = $value;
				}
			}
			$arguments = true;
		}

		// Get the _GET
		if (!empty($_GET)) {
			$this->_storeVariables($_GET);
			$arguments = true;
		}

		// Get the _POST
		if (!empty($_POST)) {
			$this->_storeVariables($_POST);
			$arguments = true;
		}
		if (!$arguments) echo JText::_('COM_CSVIVIRTUEMART_NO_ARGUMENTS')."\n";
	}

	/**
	 * Store the variables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		$vars	array	the variables to store
	 * @return
	 * @since 		3.2
	 */
	private function _storeVariables($vars) {
		foreach ($vars as $name => $value) {
			if (!empty($value)) {
				if (strpos($value, '|')) $value = explode('|', $value);
				if (substr($name, 0, 5) == 'jform') {
					if (strpos($name, ':')) $names = explode(':', $name);
					else $names = explode('_', $name);
					if (count($names) == 3 && $names[0] == 'jform') {
						$this->_variables['jform'][$names[1]][$names[2]] = $value;
					}
				}
				else $this->_variables[$name] = $value;
			}
		}
	}

	/**
	* Check if the user exists
	*/
	private function Login() {
		$mainframe = JFactory::getApplication();
		$credentials['username'] = JFilterInput::clean($this->_variables['username'], 'username');
		$credentials['password'] = JFilterInput::clean($this->_variables['passwd']);

		$result = $mainframe->login($credentials, array('entry_url' => ''));

		if (!JError::isError($result)) {
			return true;
		}
		else return false;
	}

	/**
	* Process the requested job
	*/
	function ExecuteJob() {
		JRequest::setVar('cron', true);
		require(JPATH_COMPONENT_ADMINISTRATOR.'/csvivirtuemart.php');
	}

	/**
	 * Log the user out
	 */
	private function UserLogout() {
		global $mainframe;
		ob_start();
		$error = $mainframe->logout();

		if(JError::isError($error)) {
			ob_end_clean();
			echo JText::_('COM_CSVIVIRTUEMART_PROBLEM_LOGOUT_USER')."\n";
		}
		else {
			ob_end_clean();
			echo JText::_('COM_CSVIVIRTUEMART_USER_LOGGED_OUT')."\n";
		}
	}
}
?>