<?php
/*
 * ARI Framework Lite
 *
 * @package		ARI Framework Lite
 * @version		1.0.0
 * @author		ARI Soft
 * @copyright	Copyright (c) 2009 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.Integration.K2.ArticleSearchStruct');
AriKernel::import('Web.JSON.JSON');

if (file_exists(JPATH_ROOT . '/components/com_k2/helpers/route.php'))
	require_once JPATH_ROOT . '/components/com_k2/helpers/route.php';

class AriK2ArticleController
{
	function getCategories() 
	{
		$database = JFactory::getDBO();

		$query = $database->getQuery(true);

		$query->select('C.id, C.name, C.parent');
		$query->from('#__k2_categories AS C');
		$query->where('C.published = 1');		
		$query->order('C.ordering ASC'); 
		
		$database->setQuery($query);
		$categories = $database->loadObjectList('id');
		if ($database->getErrorNum()) 
		{
			return null; 
		}
		
		$categoriesByParent = array();
		foreach ($categories as &$category)
		{
			$parentId = $category->parent;
			if (!isset($categoriesByParent[$parentId]))
				$categoriesByParent[$parentId] = array();

			$categoriesByParent[$parentId][] =& $category;
		}
		
		if (!isset($categoriesByParent[0]))
			return null;
			
		foreach ($categoriesByParent as $parentId => &$childCategories)
		{
			$level = 0;
			$currentParentId = $parentId;
			while ($currentParentId > 0)
			{
				$currentParentId = $categories[$currentParentId]->parent;
				++$level;
			}
			
			foreach ($childCategories as &$childCategory)
				$childCategory->level = $level;
		}

		foreach ($categories as &$category)
		{
			$category->childs = null;
			if (isset($categoriesByParent[$category->id]))
				$category->childs =& $categoriesByParent[$category->id];
		}

		return $categories;
	}
	
	function getCategoriesTree() 
	{
		$categories = $this->getCategories();
		$tree = array();
		
		if (is_array($categories))
		{
			foreach ($categories as &$category)
			{
				if ($category->parent == 0)
					$tree[] =& $category;
			}
		}

		return $tree;
	}
	
	function subCategories($categoryIdList)
	{
		$subCategories = array();
		$categories = $this->getCategories();
		
		foreach ($categoryIdList as $categoryId)
		{
			if (!isset($categories[$categoryId]))
				continue ;

			$this->subCategoriesInt($categories[$categoryId], $subCategories);
		}

		return $subCategories;
	}
	
	private function subCategoriesInt(&$category, &$idList)
	{
		if ($category && $category->childs)
		{
			foreach ($category->childs as &$childCategory)
			{
				$idList[] = $childCategory->id;
				$this->subCategoriesInt($childCategory, $idList);
			}
		}
	}
	
	function getArticleList($searchStruct, $processTag = true)
	{
		$my = JFactory::getUser();
		$database = JFactory::getDBO();
		
		$userId = $my->get('id');
		
		$config = JFactory::getConfig();
    	$nullDate = $database->getNullDate();
		$now = JFactory::getDate('now', J3_0 ? $config->get('offset') : $config->getValue('config.offset'));
		
		$excFrontend = $searchStruct->getExcludeFrontend();
		$categoryIdList = $searchStruct->getCategoryIdList();
		$creatorIdList = $searchStruct->getCreatorIdList();
		$incArticleIdList = $searchStruct->getIncludeArticleIdList();
		$excArticleIdList = $searchStruct->getExcludeArticleIdList();
		
		if ($categoryIdList && $searchStruct->getIncludeSubCategory())
		{
			$categoriesTree = $this->getCategoriesTree();
			$subCategoryIdList = $this->subCategories($categoryIdList);

			if ($subCategoryIdList)
			{
				$categoryIdList = array_merge($categoryIdList, $subCategoryIdList);
				$categoryIdList = array_unique($categoryIdList);
			}
		}

		$query = 'SELECT C.*,CC.name AS category_title,CC.alias AS cat_alias,U.name AS author_name,U.username AS author_username' .
			' FROM #__k2_items C';

		$query .= ' LEFT JOIN #__k2_categories CC ON C.catid = CC.id';
		$query .= ' LEFT JOIN #__users U ON U.id = C.created_by';
		$query .= ' WHERE';
		
		if (J2_5)
		{
			$lang =& JFactory::getLanguage(); 
			$langTag = $lang->get('tag');
			
			$query .= sprintf(' C.language IN("*",%s) AND ',
				$database->Quote($langTag));
		}

		$query .= sprintf(' (%4$s(C.published = 1) AND (IFNULL(CC.published,1) = 1)' .
			' AND (C.publish_up = %1$s OR C.publish_up <= %2$s) AND (C.publish_down = %1$s OR C.publish_down >= %2$s)' .
			' AND (%3$s > 0 OR (IFNULL(C.access,1) = 1 AND IFNULL(CC.access,1) = 1)))',
			$database->Quote($nullDate),
			$database->Quote(J3_0 ? $now->toSql() : $now->toMySql()),
			$userId,
			$excFrontend 
				? $excFrontend == 'only' 
					? 'C.featured = 1 AND'
					: 'C.featured = 0 AND ' 
				: ''
		);

		$whereArticle = array();
		if ($categoryIdList)
		{
			$whereArticle[] = sprintf('(C.catid %s IN (%s))',
				$searchStruct->getExcludeCategory() ? 'NOT' : '',
				join(',', $this->_quoteValues($categoryIdList)));
		}
		
		if ($creatorIdList)
		{
			$whereArticle[] = sprintf('(C.created_by %s IN (%s))',
				$searchStruct->getExcludeCreator() ? 'NOT' : '',
				join(',', $this->_quoteValues($creatorIdList)));
		}
		
		if ($excArticleIdList)
		{
			$whereArticle[] = sprintf('(C.id NOT IN (%s))',
					join(',', $this->_quoteValues($excArticleIdList)));
		}
		
		$whereArticle = join(' AND ', $whereArticle);
		if ($incArticleIdList)
		{
			if ($whereArticle)
				$whereArticle = '(' . $whereArticle . ') OR ';
					
			$whereArticle .= sprintf('(C.id IN (%s))',
				join(',', $this->_quoteValues($incArticleIdList)));
		}
		
		if ($whereArticle)
			$query .= ' AND (' . $whereArticle . ')';

		if ($searchStruct->getIsRandom())
		{
			$query .= ' ORDER BY RAND()';
		}
		else
		{		
			$sort = $searchStruct->getSort();
			if (is_array($sort) && count($sort) > 0)
			{
				$sortPart = array();
				foreach ($sort as $sortItem)
				{
					$sortPart[] = 'C.`' . $sortItem['field'] . '` ' . $sortItem['dir'];
				}

				$query .= ' ORDER BY ' . join(',', $sortPart);
			}
		}
		
		$itemCount = $searchStruct->getItemCount();
		if ($itemCount > 0)
		{
			$query .= ' LIMIT 0,' . $itemCount;
		}

		$database->setQuery($query);
		$articleList = $database->loadAssocList();

		if ($database->getErrorNum())
		{
			return null;
		}

		if ($articleList)
		{
			for ($i = 0, $c = count($articleList); $i < $c; $i++)
			{
				$article = $articleList[$i]; 
				//if ($processTag) $article = AriMambotProcessHelper::processArticle($article);
				$article['readmore_link'] = JRoute::_(K2HelperRoute::getItemRoute($article['id'] . ':' . urlencode($article['alias']), $article['catid'] . ':' . urlencode($article['cat_alias'])));
				
				$articleList[$i] = $article;
			}
		}
		
		return $articleList;
	}

	function _quoteValues($arr)
	{
		$database = JFactory::getDBO();
		if (!empty($arr))
		{
			foreach ($arr as $key => $value)
				$arr[$key] = $database->Quote($value);
		}

		return $arr;
	}
}