<?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('Articles.ArticleSearchStruct');
AriKernel::import('Mambot.MambotProcessHelper');
AriKernel::import('Joomla.JoomlaUtils');
AriKernel::import('Web.JSON.JSON');

require_once JPATH_ROOT . '/components/com_content/helpers/route.php';

class AriJoomlaArticleController
{
	function getCategories($extension = 'com_content', $config = array('filter.published' => array(0,1))) 
	{
		$database =& JFactory::getDBO();

		$extension = 'com_content';
		$query = $database->getQuery(true);

		$query->select('C.id, C.title, C.level, C.parent_id');
		$query->from('#__categories AS C');
		$query->where('C.parent_id > 0');
		
		$query->where('extension = ' . $database->quote($extension));
		
		// Filter on the published state
		if (isset($config['filter.published'])) 
		{
			if (is_numeric($config['filter.published'])) 
			{
				$query->where('C.published = '.(int) $config['filter.published']);
			} 
			else if (is_array($config['filter.published'])) 
			{
				JArrayHelper::toInteger($config['filter.published']);
				$query->where('C.published IN ('.implode(',', $config['filter.published']).')');
			}
		}

		$query->order('C.lft'); 
		
		$database->setQuery($query);
		$categories = $database->loadObjectList();
		if ($database->getErrorNum()) 
		{
			return null; 
		}

		return $categories;
	}
	
	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())
		{
			$subCategories = $this->subCategories($categoryIdList);
			if ($subCategories)
			{
				$categoryIdList = array_merge($categoryIdList, $subCategories);
				$categoryIdList = array_unique($categoryIdList);
			}
		}

		$query = 'SELECT C.*,CC.title AS category_title,U.name AS author_name,U.username AS author_username,' .
			' CASE WHEN CHAR_LENGTH(C.alias) THEN CONCAT_WS(":", C.id, C.alias) ELSE C.id END AS Slug'.
			' FROM #__content C';

		if ($excFrontend)
			$query .= ' LEFT JOIN #__content_frontpage CF ON C.id = CF.content_id';

		$query .= ' LEFT JOIN #__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.state = 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' 
					? 'CF.content_id IS NOT NULL AND'
					: 'CF.content_id IS NULL 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)
		{
            if ($processTag)
                JPluginHelper::importPlugin('content');

			for ($i = 0, $c = count($articleList); $i < $c; $i++)
			{
				$article = $articleList[$i]; 
				if ($processTag)
                {
                    $article['introtext'] = JHtml::_('content.prepare', $article['introtext'], '');
                    $article['fulltext'] = JHtml::_('content.prepare', $article['fulltext'], '');
                }

				$article['readmore_link'] = JRoute::_(ContentHelperRoute::getArticleRoute($article['Slug'], $article['catid']));
				if (J2_5)
					$article = $this->resolveArticleImages($article);
				
				$articleList[$i] = $article;
			}
		}
		
		return $articleList;
	}
	
	function resolveArticleImages($article)
	{
		$imageKeys = array('intro', 'fulltext');
		foreach ($imageKeys as $imageKey)
		{
			$key = 'image_' . $imageKey;
			$article[$key] = '';
		}
		
		$images = $article['images'];
		if (!empty($images))
		{
			$images = json_decode($images, true);
			foreach ($imageKeys as $imageKey)
			{
				$imgKey = 'image_' . $imageKey;
				$imageSrc = 'image_' . $imageKey;
				if (empty($images[$imageSrc]))
					continue ;

				$imageSrc = $images[$imageSrc];
				$imageAlt = $images['image_' . $imageKey . '_alt'];
				
				$article[$imgKey] = sprintf('<img src="%1$s" alt="%2$s" />',
					$imageSrc,
					$imageAlt
				);
			}
		}

		return $article;
	}
	
	function subCategories($categoryIdList)
	{
		$database = JFactory::getDBO();
	
		$query = $database->getQuery(true);
		$query->select('id, lft, rgt');
		$query->from('#__categories');
		$query->where('id IN (' . join(',', $this->_quoteValues($categoryIdList)) . ')');

		$database->setQuery($query);
		$categories = $database->loadObjectList();

		if (empty($categories))
			return null;

		$query = $database->getQuery(true);
		$query->select('id');
		$query->from('#__categories');
		
		foreach ($categories as $category)
		{
			$query->where(
				sprintf('(lft > %d AND rgt < %d)',
					$category->lft,
					$category->rgt),
				'OR'
			);
		}
		
		$database->setQuery($query);
		$subCategories = J3_0 ? $database->loadColumn() : $database->loadResultArray();

		return $subCategories;
	}
	
	function getArticleLink($article)
	{
		$link = 'index.php?option=com_content&view=article&id=' . $article->id;
		if ($article->catid)
			$link .= '&catid=' . $article->catid;  

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

		return $arr;
	}
}