<?php
/**

 * @package  mod_ju_articleslider
 *
 * @copyright   Copyright (C) 2005 - 2015 joomla2you.com. All rights reserved.
 * @license     GNU General Public License version 2 or later.
 */

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

//jimport('joomla.filesystem.folder');
require_once JPATH_SITE . '/components/com_content/helpers/route.php';
JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_content/models', 'ContentModel');

/**
 * Helper for mod_ju_articleslider
 */
abstract class modJuArticleSlider
{
	
	/**
    *    @return       array of articles
    *    @called by    template
    */
   
	public static function getList($params)
	{

		$app = JFactory::getApplication();
		// Set the filters based on the module params
		$model = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));

		// Set application parameters in model
		$appParams = JFactory::getApplication()->getParams();

		if ($params->get('source') == 'categories_source')
		{
			// Get an instance of the generic articles model
			
			$model->setState('params', $appParams);
			$model->setState('list.start', 0);
			$model->setState('list.limit', (int) $params->get('limit_items', 5));
	
			$model->setState('filter.published', 1);

			//  Featured switch
			switch ($params->get('show_featured'))
			{
				case '1' :
					$model->setState('filter.featured', 'only');
					break;
				case '0' :
					$model->setState('filter.featured', 'hide');
					break;
				default :
					$model->setState('filter.featured', 'show');
					break;
			}
	
			$model->setState('list.select', 'a.fulltext, a.id, a.title, a.alias, a.introtext, a.state, a.catid, a.created, a.created_by, a.created_by_alias,' .
				' a.modified, a.modified_by, a.publish_up, a.publish_down, a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access,' .
				' a.hits, a.featured' );
	
			// Access filter
			$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
			$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
			$model->setState('filter.access', $access);
	
			// Category filter
			$model->setState('filter.category_id', $params->get('catid', array()));
	
			// Filter by language
			$model->setState('filter.language', $app->getLanguageFilter());
	
			// Set ordering
			$ordering = $params->get('ordering', 'a.publish_up');
			$model->setState('list.ordering', $ordering);
			if (trim($ordering) == 'rand()')
			{
				$model->setState('list.direction', '');
			}
			else
			{
				$model->setState('list.direction', $params->get('sortby'));
			}
			//	Retrieve Content		
			$items = $model->getItems();

		} else {
			$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
			$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
						
			$db = JFactory::getDbo();
			$query = $db->getQuery(true);
			$user = JFactory::getUser();
			$query->select(
				$model->getState(
					'list.select',
					'a.id, a.title, a.alias, a.introtext, a.fulltext, a.images, a.checked_out, a.checked_out_time, a.catid' .
						', a.state, a.access, a.created, a.created_by, a.created_by_alias, a.ordering, a.featured, a.language, a.hits' .
						', a.publish_up, a.publish_down'
				)
			);
			
			$query->from('#__content AS a');	
			
			// Join over the language
			$query->select('l.title AS language_title')
				->join('LEFT', $db->quoteName('#__languages') . ' AS l ON l.lang_code = a.language');
	
			// Join over the users for the checked out user.
			$query->select('uc.name AS editor')
				->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');
	
			// Join over the asset groups.
			$query->select('ag.title AS access_level')
				->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access');
	
			// Join over the categories.
			$query->select('c.title AS category_title')
				->join('LEFT', '#__categories AS c ON c.id = a.catid');
	
			// Join over the users for the author.
			$query->select('ua.name AS author_name')
				->join('LEFT', '#__users AS ua ON ua.id = a.created_by');
	
			if($params->get('items')!=''){				
				$items_id = implode(',', $params->get('items'));
				$query->where('a.id IN (' . $items_id . ')');
			}	
			$db->setQuery($query);

			$items = $db->loadObjectList();
		}		
			
				
		foreach ($items as &$item)
		{
			$title = '';
			// Word limit
			if ($params->get('title_limit'))
			{						
				$title .= modJuArticleSlider::subString(JFilterOutput::ampReplace($item->title), $params->get('title_limit'));
			}
			else
			{
				$title .= JFilterOutput::ampReplace($item->title);
			}
			$item->title = $title;
						
			preg_match_all('/src="([^"]+)"/i', $item->introtext.$item->fulltext, $matches);
			
			$images = json_decode($item->images);
			
			if (!empty($images->image_fulltext)){				
				$item->item_image = JURI::root().$images->image_fulltext;									
			}elseif (!empty($matches[1][0])) {
				$item->item_image = $matches[1][0];				
			}else{
				$item->item_image = '';
			}	
			
			$item->slug = $item->id.':'.$item->alias;
			//$item->catslug = $item->catid.':'.$item->category_alias;

			if ($access || in_array($item->access, $authorised))
			{
				// We know that user has the privilege to view the article
				$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catid));
				$item->linkText = JText::_('MOD_JU_CONTENT_SLIDER_READMORE');
			}
			else {
				$item->link = JRoute::_('index.php?option=com_users&view=login');
				$item->linkText = JText::_('MOD_JU_CONTENT_SLIDER_READMORE_REGISTER');
			}
			
			// Category link
			if ($params->get('item_category'))
				$item->categoryLink = urldecode(JRoute::_(ContentHelperRoute::getCategoryRoute($item->catid)));			
			
			$item->default_introtext = strip_tags(preg_replace('/<img([^>]+)>/i',"",$item->introtext));		
			// Introtext
			
			$item->text = '';
			// Introtext limit
			if ($params->get('introtext_limit'))
			{						
				$item->text = modJuArticleSlider::subString(strip_tags(preg_replace('/<img([^>]+)>/i',"",$item->introtext)), $params->get('introtext_limit'));
			}
			else
			{
				$item->text .= strip_tags(preg_replace('/<img([^>]+)>/i',"",$item->introtext));						
			}
			$item->introtext = $item->text;
			
			// Item Author
			if ($params->get('item_author'))
			{
				if (!empty($item->created_by_alias)){
					$item->author = $item->created_by_alias;					
				}else{
					$author = JFactory::getUser($item->created_by);
					$item->author = $author->name;					
				}
			}

			$rows[] = $item;
		}
		return $rows;
	}
	
	public static function subString($str,$leng){
		
		if(JString::strlen($str)<=$leng)	{

		  return $str;

		} else {

	    if(JString::strpos($str," ",$leng) > $leng) {
	    	
				$new_leng=JString::strpos($str," ",$leng);
				$new_str = JString::substr($str,0,$new_leng)."...";

				return $new_str;
	    }
	    $new_str = JString::substr($str,0,$leng)."...";

	    return $new_str;
		}
	}
}