Your IP : 216.73.216.84


Current Path : /home/h/e/l/helpink/www/administrator/components/com_jbusinessdirectory/models/
Upload File :
Current File : /home/h/e/l/helpink/www/administrator/components/com_jbusinessdirectory/models/updates.php

<?php
/**
* @copyright	Copyright (C) 2008-2009 CMSJunkie. All rights reserved.
*
* This program 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
* 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

defined('_JEXEC') or die('Restricted access');

jimport('joomla.updater.update');

use Joomla\Utilities\ArrayHelper;
use Joomla\CMS\Installer\InstallerHelper;

class JBusinessDirectoryModelUpdates extends JModelList {
/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'name', 'u.name',
				'client_id', 'u.client_id', 'client_translated',
				'type', 'u.type', 'type_translated',
				'folder', 'u.folder', 'folder_translated',
				'extension_id', 'u.extension_id',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'u.name', $direction = 'asc')
	{
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.client_id', $this->getUserStateFromRequest($this->context . '.filter.client_id', 'filter_client_id', null, 'int'));
		$this->setState('filter.type', $this->getUserStateFromRequest($this->context . '.filter.type', 'filter_type', '', 'string'));
		$this->setState('filter.folder', $this->getUserStateFromRequest($this->context . '.filter.folder', 'filter_folder', '', 'string'));

		$app = JFactory::getApplication();
		$this->setState('message', $app->getUserState('com_installer.message'));
		$this->setState('extension_message', $app->getUserState('com_installer.extension_message'));
		$app->setUserState('com_installer.message', '');
		$app->setUserState('com_installer.extension_message', '');

		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get the database query
	 *
	 * @return  JDatabaseQuery  The database query
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		$db = $this->getDbo();

		// Grab updates ignoring new installs
		$query = $db->getQuery(true)
			->select('u.*')
			->select($db->quoteName('e.manifest_cache'))
			->from($db->quoteName('#__updates', 'u'))
			->join('LEFT', $db->quoteName('#__extensions', 'e') . ' ON ' . $db->quoteName('e.extension_id') . ' = ' . $db->quoteName('u.extension_id'))
			->where($db->quoteName('u.extension_id') . ' != ' . $db->quote(0));

		// Process select filters.
		$clientId    = $this->getState('filter.client_id');
		$type        = $this->getState('filter.type');
		$folder      = $this->getState('filter.folder');
		$extensionId = $this->getState('filter.extension_id');

		if ($type)
		{
			$query->where($db->quoteName('u.type') . ' = ' . $db->quote($type));
		}

		if ($clientId != '')
		{
			$query->where($db->quoteName('u.client_id') . ' = ' . (int) $clientId);
		}

		if ($folder != '' && in_array($type, array('plugin', 'library', '')))
		{
			$query->where($db->quoteName('u.folder') . ' = ' . $db->quote($folder == '*' ? '' : $folder));
		}

		if ($extensionId)
		{
			$query->where($db->quoteName('u.extension_id') . ' = ' . $db->quote((int) $extensionId));
		}
		else
		{
			$query->where($db->quoteName('u.extension_id') . ' != ' . $db->quote(0))
				->where($db->quoteName('u.extension_id') . ' != ' . $db->quote(700));
		}

		// Process search filter.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'eid:') !== false)
			{
				$query->where($db->quoteName('u.extension_id') . ' = ' . (int) substr($search, 4));
			}
			else
			{
				if (stripos($search, 'uid:') !== false)
				{
					$query->where($db->quoteName('u.update_site_id') . ' = ' . (int) substr($search, 4));
				}
				elseif (stripos($search, 'id:') !== false)
				{
					$query->where($db->quoteName('u.update_id') . ' = ' . (int) substr($search, 3));
				}
				else
				{
					$query->where($db->quoteName('u.name') . ' LIKE ' . $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true)) . '%'));
				}
			}
		}

		return $query;
	}

	/**
	 * Translate a list of objects
	 *
	 * @param   array  $items  The array of objects
	 *
	 * @return  array The array of translated objects
	 *
	 * @since   3.5
	 */
	protected function translate(&$items)
	{
		foreach ($items as &$item)
		{
			$item->client_translated  = $item->client_id ? JText::_('JADMINISTRATOR') : JText::_('JSITE');
			$manifest                 = json_decode($item->manifest_cache);
			$item->current_version    = isset($manifest->version) ? $manifest->version : JText::_('JLIB_UNKNOWN');
			$item->type_translated    = JText::_('COM_INSTALLER_TYPE_' . strtoupper($item->type));
			$item->folder_translated  = $item->folder ?: JText::_('COM_INSTALLER_TYPE_NONAPPLICABLE');
			$item->install_type       = $item->extension_id ? JText::_('COM_INSTALLER_MSG_UPDATE_UPDATE') : JText::_('COM_INSTALLER_NEW_INSTALL');
		}

		return $items;
	}

	/**
	 * Returns an object list
	 *
	 * @param   string  $query       The query
	 * @param   int     $limitstart  Offset
	 * @param   int     $limit       The number of records
	 *
	 * @return  array
	 *
	 * @since   3.5
	 */
	protected function _getList($query, $limitstart = 0, $limit = 0)
	{
		$db = $this->getDbo();
		$listOrder = $this->getState('list.ordering', 'u.name');
		$listDirn  = $this->getState('list.direction', 'asc');

		// Process ordering.
		if (in_array($listOrder, array('client_translated', 'folder_translated', 'type_translated')))
		{
			$db->setQuery($query);
			$result = $db->loadObjectList();
			$this->translate($result);
			$result = ArrayHelper::sortObjects($result, $listOrder, strtolower($listDirn) === 'desc' ? -1 : 1, true, true);
			$total = count($result);

			if ($total < $limitstart)
			{
				$limitstart = 0;
				$this->setState('list.start', 0);
			}

			return array_slice($result, $limitstart, $limit ?: null);
		}
		else
		{
			$query->order($db->quoteName($listOrder) . ' ' . $db->escape($listDirn));

			$result = parent::_getList($query, $limitstart, $limit);
			$this->translate($result);

			return $result;
		}
	}

	/**
	 * Get the count of disabled update sites
	 *
	 * @return  integer
	 *
	 * @since   3.4
	 */
	public function getDisabledUpdateSites()
	{
		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->select('COUNT(*)')
			->from($db->quoteName('#__update_sites'))
			->where($db->quoteName('enabled') . ' = 0');

		$db->setQuery($query);

		return $db->loadResult();
	}

	/**
	 * Finds updates for an extension.
	 *
	 * @param   int  $eid               Extension identifier to look for
	 * @param   int  $cacheTimeout      Cache timout
	 * @param   int  $minimumStability  Minimum stability for updates {@see JUpdater} (0=dev, 1=alpha, 2=beta, 3=rc, 4=stable)
	 *
	 * @return  boolean Result
	 *
	 * @since   1.6
	 */
	public function findUpdates($eid = 0, $cacheTimeout = 0, $minimumStability = JUpdater::STABILITY_STABLE)
	{
		JUpdater::getInstance()->findUpdates($eid, $cacheTimeout, $minimumStability);

		return true;
	}

	/**
	 * Removes all of the updates from the table.
	 *
	 * @return  boolean result of operation
	 *
	 * @since   1.6
	 */
	public function purge()
	{
		$db = $this->getDbo();

		// Note: TRUNCATE is a DDL operation
		// This may or may not mean depending on your database
		$db->setQuery('TRUNCATE TABLE #__updates');

		try
		{
			$db->execute();
		}
		catch (JDatabaseExceptionExecuting $e)
		{
			$this->_message = JText::_('JLIB_INSTALLER_FAILED_TO_PURGE_UPDATES');

			return false;
		}

		// Reset the last update check timestamp
		$query = $db->getQuery(true)
			->update($db->quoteName('#__update_sites'))
			->set($db->quoteName('last_check_timestamp') . ' = ' . $db->quote(0));
		$db->setQuery($query);
		$db->execute();

		// Clear the administrator cache
		$this->cleanCache('_system', 1);

		$this->_message = JText::_('JLIB_INSTALLER_PURGED_UPDATES');

		return true;
	}

	/**
	 * Enables any disabled rows in #__update_sites table
	 *
	 * @return  boolean result of operation
	 *
	 * @since   1.6
	 */
	public function enableSites()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->update($db->quoteName('#__update_sites'))
			->set($db->quoteName('enabled') . ' = 1')
			->where($db->quoteName('enabled') . ' = 0');
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (JDatabaseExceptionExecuting $e)
		{
			$this->_message .= JText::_('COM_INSTALLER_FAILED_TO_ENABLE_UPDATES');

			return false;
		}

		if ($rows = $db->getAffectedRows())
		{
			$this->_message .= JText::plural('COM_INSTALLER_ENABLED_UPDATES', $rows);
		}

		return true;
	}
	
	
	public function store($post) {
		$table = $this->getTable("ApplicationSettings");
		if ($table->updateOrder(trim($post['orderId']), trim($post['orderEmail']))) {
			return true;
		} else {
			return false;
		}
	}
	
	public function update($uids, $minimum_stability = JUpdater::STABILITY_STABLE) {
		$result = true;
		foreach ($uids as $uid) {
			$update = new JUpdate;
			$instance = JTable::getInstance('update');
			$instance->load($uid);
			$update->loadFromXML($instance->detailsurl);
			$update->set('extra_query', $instance->extra_query);
	
			// Install sets state and enqueues messages
			$res = $this->install($update);
	
			if ($res) {
				$instance->delete($uid);
			}
	
			$result = $res & $result;
		}
	
		// Set the final state
		$this->setState('result', $result);
	}
	
	private function install($update) {
		try {
			$app = JFactory::getApplication();
			if (isset($update->get('downloadurl')->_data)) {
				$url = $update->downloadurl->_data;
	
				$extra_query = $update->get('extra_query');
	
				if ($extra_query) {
					if (strpos($url, '?') === false) {
						$url .= '?';
					} else {
						$url .= '&amp;';
					}
	
					$url .= $extra_query;
				}
			} else {
				JFactory::getApplication()->enqueueMessage(JText::_('COM_INSTALLER_INVALID_EXTENSION_UPDATE'), 'warning');
				return false;
			}
			
			$url .="&orderId=".JBusinessUtil::getApplicationSettings()->order_id."&orderEmail=".JBusinessUtil::getApplicationSettings()->order_email."&clientData=".urlencode(JBusinessUtil::getWebsiteUrl(true)." - ".$_SERVER['REMOTE_ADDR']);
	
			$p_file = JInstallerHelper::downloadPackage($url);
			// Was the package downloaded?
			if (!$p_file) {
				JFactory::getApplication()->enqueueMessage(JText::_('COM_INSTALLER_PACKAGE_DOWNLOAD_FAILED'), 'warning');
				return false;
			}
	
			$config		= JBusinessUtil::getSiteConfig();
			$tmp_dest	= $config->tmp_path;
	
			// Unpack the downloaded package file
			$package	= JInstallerHelper::unpack($tmp_dest . '/' . $p_file);
	
			// Get an installer instance
			$installer	= JInstaller::getInstance();
			$update->set('type', $package['type']);
	
			if (empty($package['dir'])) {
				throw new Exception("");
			}
			// Install the package
			if (!$installer->update($package['dir'])) {
				// There was an error updating the package
				$msg = JText::sprintf('COM_INSTALLER_MSG_UPDATE_ERROR', JText::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type'])));
				$result = false;
			} else {
				// Package updated successfully
				$msg = JText::sprintf('COM_INSTALLER_MSG_UPDATE_SUCCESS', JText::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type'])));
				$result = true;
			}
			
			if (!$result) {
				$msg = JText::_('LNG_INVALID_ORDER_OR_EXPIRED_SUPPORT');
			}
			
	
			// Quick change
			$this->type = $package['type'];
	
			// Set some model state values
			$app->enqueueMessage($msg);
	
			// TODO: Reconfigure this code when you have more battery life left
			$this->setState('name', $installer->get('name'));
			$this->setState('result', $result);
			$app->setUserState('com_installer.message', $installer->message);
			$app->setUserState('com_installer.extension_message', $installer->get('extension_message'));
	
			// Cleanup the install files
			if (!is_file($package['packagefile'])) {
				$config = JBusinessUtil::getSiteConfig();
				$package['packagefile'] = $config->tmp_path . '/' . $package['packagefile'];
			}
	
			JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']);
		} catch (Exception $e) {
			$msg = JText::_('LNG_INSTALL_UPDATE_ERROR');
			$app->enqueueMessage($msg);
		}

		return $result;
	}
	
	public function getExpirationDate() {
		try {
			$url = "https://updates.cmsjunkie.com/security/productinfo.php?sku=j-businessdirectory";
			$url.="&orderId=".JBusinessUtil::getApplicationSettings()->order_id."&orderEmail=".JBusinessUtil::getApplicationSettings()->order_email;
			//echo $url;
			$ch = curl_init();
			$timeout = 10;
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$rawdata = curl_exec($ch);
			curl_close($ch);
			return $rawdata;
		} catch (Exception $e) {
			echo "sdsd";
			exit;
		}
	}
	
	public function getCurrentVersion() {
		// get current version from the component settings in Joomla
		$module = JComponentHelper::getComponent('com_jbusinessdirectory');
		$extension = JTable::getInstance('extension');
		$extension->load($module->id);
		$data = json_decode($extension->manifest_cache, true);
		return trim($data['version']);
	}
	
	public function getUpdateVersion() {
		$table = JTable::getInstance('Updates');
		$module = JComponentHelper::getComponent('com_jbusinessdirectory');
		$this->findUpdates(array($module->id), 0);
		$items = $this->getItems();
		foreach ($items as $i => $item) {
			if ($module->id==$item->extension_id) {//if found return version
				return trim($item->version);
			}
		}
		return "0.0.0";//return default if not found
	}
	
	
	
	public function getVersionStatus() {
		$expirationData = array();
	
		//check if order data is set. If not show message.
		if (empty(JBusinessUtil::getApplicationSettings()->order_id) || empty(JBusinessUtil::getApplicationSettings()->order_email)) {
			$expirationData['message'] = "<font color='red'>".JText::_("LNG_UPDATES_NOTICE_MISSING")."</font>";
			$expirationData['currentVersion'] = "N/A";
			$expirationData['currentStatus'] = "N/A";
			$expirationData['updateVersion'] = "N/A";
			return json_encode($expirationData);
		}
		//get current version
		$version = $this->getCurrentVersion();
		$expirationData['currentVersion'] = $version;
	
	
		//get update versions if any
		$updateVersion = $this->getUpdateVersion();
		$expirationData['updateVersion'] = $updateVersion;
	
		if (version_compare($updateVersion, $version, ">")) { //check if current version is up to date
			$expirationData['currentStatus'] = "<font color='red'><b>".JText::_("LNG_OUT_OF_DATE")."</b></font>";
		} else {
			$expirationData['currentStatus'] = "<font color='green'><b>".JText::_("LNG_UP_TO_DATE")."</b></font>";
			$expirationData['updateVersion'] = JText::_("LNG_NONE");
		}
	
		//get expiration date
		$expirationData['message'] = $this->getExpirationDate();
	
		//return encoded data
		return json_encode($expirationData);
	}
}