<?php
/*
 * @package		Joomla.Framework
 * @copyright	Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 *
 * @component Phoca Component
 * @copyright Copyright (C) Jan Pavelka www.phoca.cz
 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License version 2 or later;
 */
defined('_JEXEC') or die();
jimport('joomla.application.component.model');

class PhocaDownloadModelCategory extends JModel
{
	var $_document 			= null;
	var $_category 			= null;
	var $_subcategories 	= null;
	var $_filename			= null;
	var $_directlink		= 0;
	var $_file_ordering		= null;
	var $_category_ordering	= null;
	var $_pagination		= null;
	var $_total				= null;

	function __construct() {
		
		$app	= JFactory::getApplication();
		
		parent::__construct();
		
		$config = JFactory::getConfig();		
		
		$paramsC 			= JComponentHelper::getParams('com_phocadownload') ;
		$defaultPagination	= $paramsC->get( 'default_pagination', '20' );
		
		// Get the pagination request variables
		$this->setState('limit', $app->getUserStateFromRequest('com_phocadownload.limit', 'limit', $defaultPagination, 'int'));
		$this->setState('limitstart', JRequest::getVar('limitstart', 0, '', 'int'));

		// In case limit has been changed, adjust limitstart accordingly
		$this->setState('limitstart', ($this->getState('limit') != 0 ? (floor($this->getState('limitstart') / $this->getState('limit')) * $this->getState('limit')) : 0));

		// Get the filter request variables
		$this->setState('filter_order', JRequest::getCmd('filter_order', 'ordering'));
		$this->setState('filter_order_dir', JRequest::getCmd('filter_order_Dir', 'ASC'));
		
	}
	
	function getPagination($categoryId) {
		if (empty($this->_pagination)) {
			jimport('joomla.html.pagination');
			$this->_pagination = new PhocaPagination( $this->getTotal($categoryId), $this->getState('limitstart'), $this->getState('limit') );
		}
		return $this->_pagination;
	}
	
	function getTotal($categoryId) {
		if (empty($this->_total)) {
			$query = $this->_getFileListQuery($categoryId);
			$this->_total = $this->_getListCount($query);
		}
		return $this->_total;
	}

	function getFileList($categoryId) {
		if (empty($this->_document)) {	
			$query			= $this->_getFileListQuery( $categoryId);
			$this->_document= $this->_getList( $query ,$this->getState('limitstart'), $this->getState('limit'));
		}
		return $this->_document;
	}
	
	function getCategory($categoryId) {	
		if (empty($this->_category)) {			
			$query					= $this->_getCategoriesQuery( $categoryId, FALSE );
			$this->_category 		= $this->_getList( $query, 0, 1 );
		}
		return $this->_category;
	}
	
	function getSubcategories($categoryId) {	
		if (empty($this->_subcategories)) {			
			$query					= $this->_getCategoriesQuery( $categoryId, TRUE );
			$this->_subcategories 	= $this->_getList( $query );
		}
		return $this->_subcategories;
	}
	
	function _getFileListQuery( $categoryId ) {
	
		$wheres		= array();
		$app		= JFactory::getApplication();
		$params 	= $app->getParams();
		$user 		= JFactory::getUser();
		$userLevels	= implode (',', $user->authorisedLevels());
	
		
		$pQ			= $params->get( 'enable_plugin_query', 0 );
		
		$wheres[]	= ' c.catid= '.(int)$categoryId;
		
		
		$wheres[] = '( (unaccessible_file = 1 ) OR (unaccessible_file = 0 AND c.access IN ('.$userLevels.') ) )';
		$wheres[] = '( (unaccessible_file = 1 ) OR (unaccessible_file = 0 AND cc.access IN ('.$userLevels.') ) )';
		
		$wheres[] = ' c.published = 1';
		$wheres[] = ' c.approved = 1';
		$wheres[] = ' cc.published = 1';
		
		// Active
		$jnow		=& JFactory::getDate();
		$now		= $jnow->toMySQL();
		$nullDate	= $this->_db->getNullDate();
		$wheres[] = ' ( c.publish_up = '.$this->_db->Quote($nullDate).' OR c.publish_up <= '.$this->_db->Quote($now).' )';
		$wheres[] = ' ( c.publish_down = '.$this->_db->Quote($nullDate).' OR c.publish_down >= '.$this->_db->Quote($now).' )';
		
		if ($pQ == 1) {
			// GWE MOD - to allow for access restrictions
			JPluginHelper::importPlugin("phoca");
			$dispatcher	   =& JDispatcher::getInstance();
			$joins = array();
			$results = $dispatcher->trigger('onGetFileList', array (&$wheres, &$joins,$categoryId , $params));	
			// END GWE MOD
		}
		
		$fileOrdering = $this->_getFileOrdering();
		
		$query = ' SELECT c.*, cc.id AS categoryid, cc.title AS categorytitle, cc.alias AS categoryalias, cc.access as cataccess, cc.accessuserid as cataccessuserid '
				.' FROM #__phocadownload AS c'
				.' LEFT JOIN #__phocadownload_categories AS cc ON cc.id = c.catid'
				. ($pQ == 1 ? ((count($joins)>0?( " LEFT JOIN " .implode( " LEFT JOIN ", $joins )):"")):"") // GWE MOD
				. ' WHERE ' . implode( ' AND ', $wheres )
				. ' ORDER BY c.'.$fileOrdering;
				
		return $query;
	}
	
	
	
	function _getCategoriesQuery( $categoryId, $subcategories = FALSE ) {
		
		$wheres		= array();
		$app		= JFactory::getApplication();
		$params 	= $app->getParams();
		$user 		= JFactory::getUser();
		$userLevels	= implode (',', $user->authorisedLevels());
		
		$pQ			= $params->get( 'enable_plugin_query', 0 );
		
		
		// Get the current category or get parent categories of the current category
		if ($subcategories) {
			$wheres[]			= " cc.parent_id = ".(int)$categoryId;
			$categoryOrdering 	= $this->_getCategoryOrdering();
		} else {
			$wheres[]	= " cc.id= ".(int)$categoryId;
		}
		
		$wheres[] = " cc.access IN (".$userLevels.")";
		$wheres[] = " cc.published = 1";
		
		
		if ($pQ == 1) {
			// GWE MOD - to allow for access restrictions
			JPluginHelper::importPlugin("phoca");
			$dispatcher	   =& JDispatcher::getInstance();
			$joins = array();
			$results = $dispatcher->trigger('onGetCategory', array (&$wheres, &$joins,$categoryId , $params));	
			// END GWE MOD
		}
		
		if ($subcategories) {
			$query = " SELECT  cc.id, cc.title, cc.alias, cc.access as cataccess, cc.accessuserid as cataccessuserid, COUNT(c.id) AS numdoc"
				. " FROM #__phocadownload_categories AS cc"
				. " LEFT JOIN #__phocadownload AS c ON c.catid = cc.id AND c.published = 1 AND c.textonly = 0"
				. ($pQ == 1 ? ((count($joins)>0?( " LEFT JOIN " .implode( " LEFT JOIN ", $joins )):"")):"") // GWE MOD
				. " WHERE " . implode( " AND ", $wheres )
				. " GROUP BY cc.id"
				. " ORDER BY cc.".$categoryOrdering;
		} else {
			$query = " SELECT cc.id, cc.title, cc.alias, cc.access as cataccess, cc.accessuserid as cataccessuserid, cc.description, cc.metakey, cc.metadesc, pc.title as parenttitle, cc.parent_id as parentid, pc.alias as parentalias"
				. " FROM #__phocadownload_categories AS cc"
				. " LEFT JOIN #__phocadownload_categories AS pc ON pc.id = cc.parent_id"
				. ($pQ == 1 ? ((count($joins)>0?( " LEFT JOIN " .implode( " LEFT JOIN ", $joins )):"")):"") // GWE MOD
				. " WHERE " . implode( " AND ", $wheres )
				. " ORDER BY cc.ordering";
		}
		
		return $query;
	}
	
	
	function _getFileOrdering() {
		if (empty($this->_file_ordering)) {
			$app						= JFactory::getApplication();
			$params						= $app->getParams();
			$ordering					= $params->get( 'file_ordering', 1 );
			$this->_file_ordering 		= PhocaDownloadHelperFront::getOrderingText($ordering);

		}
		return $this->_file_ordering;
	}
	
	function _getCategoryOrdering() {
		if (empty($this->_category_ordering)) {
	
			
			$app						= JFactory::getApplication();
			$params						= $app->getParams();
			$ordering					= $params->get( 'category_ordering', 1 );
			$this->_category_ordering 	= PhocaDownloadHelperFront::getOrderingText($ordering);

		}
		return $this->_category_ordering;
	}
}
?>