<?php
/**
* @version		$Id: helper.php 002 08.05.2008
* @copyright    Copyright (C) 2008 Joomla! Ukraine, http://www.joomla-ua.org. All rights reserved.
* @copyright    Copyright (C) 2008 Denys Nosov, http://www.denys.org.ua. All rights reserved.
* @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license		GNU/GPL, see LICENSE.php
*/

// no direct access
defined('_JEXEC') or die('Restricted access');

require_once (JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');

class modRelatedItemsHelper
{
	function getList($params)
	{
		global $mainframe;

		$db					=& JFactory::getDBO();
		$user				=& JFactory::getUser();

		$option				= JRequest::getCmd('option');
		$view				= JRequest::getCmd('view');

		$temp				= JRequest::getString('id');
		$temp				= explode(':', $temp);
		$id					= $temp[0];

        $count              = intval( $params->get( 'count', 5 ) );

        $selekt_secid_catid = $params->def('selekt_secid_catid', '1') ;
        $catid_select       = trim( $params->get( 'catid_select' ) );
        $secid_select       = trim( $params->get( 'secid_select' ) );
        $catid_text         = trim( $params->get( 'catid_text' ) );
        $secid_text         = trim( $params->get( 'secid_text' ) );

        $ordering = $params->get( 'ordering', 'created_desc' );

        if ($selekt_secid_catid == 1){
            $catid  = $catid_select;
            $secid  = $secid_select;
        } else{
            $catid  = $catid_text;
            $secid  = $secid_text;
        }

		$nullDate			= $db->getNullDate();


		$date =& JFactory::getDate();
		$now  = $date->toMySQL();

		$related			= array();

		if ($option == 'com_content' && $view == 'article' && $id)
		{

			// select the meta keywords from the item
			$query = 'SELECT metakey' .
					' FROM #__content' .
					' WHERE id = '.(int) $id;
			$db->setQuery($query);

			if ($metakey = trim($db->loadResult()))
			{
				// explode the meta keys on a comma
				$keys = explode(',', $metakey);
				$likes = array ();

				// assemble any non-blank word(s)
				foreach ($keys as $key)
				{
					$key = trim($key);
					if ($key) {
						$likes[] = $db->getEscaped($key);
					}
				}

				if (count($likes))
				{
                    // Ordering
                    switch ($ordering) {
                        case 'title':
                            $orderBy = 'title ASC';
                        break;
                        case 'title_desc':
                            $orderBy = 'title DESC';
                        break;
                        case 'id':
                            $orderBy = 'id';
                        break;
                        case 'id_desc':
                            $orderBy = 'id DESC';
                        break;
                        case 'hits':
                            $orderBy = 'hits DESC';
                        break;
                        case 'created':
                            $orderBy = 'created';
                        break;
                        case 'modified_desc':
                            $orderBy = 'modified DESC';
                        break;
                        case 'ordering':
                            $orderBy = 'ordering ASC';
                        break;
                        case 'ordering_desc':
                            $orderBy = 'ordering DESC';
                        break;
                        case 'rand':
                            $orderBy = 'rand()';
                        break;
                        case 'created_desc':
                        default:
                            $orderBy = 'created DESC';
                        break;
                    }

		            if ($catid){
			            $ids = explode( ',', $catid );
			            JArrayHelper::toInteger( $ids );
			            $catCondition = ' AND (cc.id=' . implode( ' OR cc.id=', $ids ) . ')';
		            }
		            if ($secid){
			            $ids = explode( ',', $secid );
			            JArrayHelper::toInteger( $ids );
			            $secCondition = ' AND (s.id=' . implode( ' OR s.id=', $ids ) . ')';
		            }

					// select other items based on the metakey field 'like' the keys found
					$query = 'SELECT a.id, a.title, DATE_FORMAT(a.created, "%Y-%m-%d") AS created, a.sectionid, a.catid, cc.id AS cc_id, cc.title AS cc_title, cc.access AS cat_access, s.access AS sec_access, cc.published AS cat_state, s.published AS sec_state,' .
							' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'.
							' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug'.
							' FROM #__content AS a' .
							' LEFT JOIN #__content_frontpage AS f ON f.content_id = a.id' .
							' LEFT JOIN #__categories AS cc ON cc.id = a.catid' .
							' LEFT JOIN #__sections AS s ON s.id = a.sectionid' .
							' WHERE a.id != '.(int) $id .
							' AND a.state = 1' .
							' AND a.access <= ' .(int) $user->get('aid', 0) .
							' AND ( a.metakey LIKE "%'.implode('%" OR a.metakey LIKE "%', $likes).'%" )' .
							' AND ( a.publish_up = '.$db->Quote($nullDate).' OR a.publish_up <= '.$db->Quote($now).' )' .
							' AND ( a.publish_down = '.$db->Quote($nullDate).' OR a.publish_down >= '.$db->Quote($now).')' .
                            ($catid ? $catCondition : '').
			                ($secid ? $secCondition : '').
                            ' ORDER BY '. $orderBy;

					$db->setQuery($query, 0, $count);
					$temp = $db->loadObjectList();

					if (count($temp))
					{
						foreach ($temp as $row)
						{
							if (($row->cat_state == 1 || $row->cat_state == '') && ($row->sec_state == 1 || $row->sec_state == '') && ($row->cat_access <= $user->get('aid', 0) || $row->cat_access == '') && ($row->sec_access <= $user->get('aid', 0) || $row->sec_access == ''))
							{
								$row->route = JRoute::_(ContentHelperRoute::getArticleRoute($row->slug, $row->catslug, $row->sectionid));
								$related[] = $row;
							}
						}
					}
					unset ($temp);
				}
			}
		}

		return $related;
	}
}

?>