<?php
/*
# ------------------------------------------------------------------------
# SlideShow Pro SP2 module for Joomla 2.5
# ------------------------------------------------------------------------
# Copyright (C) 2010 - 2012 JoomShaper.com. All Rights Reserved.
# @license - PHP files are GNU/GPL V2. CSS / JS are Copyrighted Commercial,
# Author: JoomShaper.com
# Websites:  http://www.joomshaper.com
# Redistribution, Modification or Re-licensing of this file in part of full, 
# is bound by the License applied. 
# ------------------------------------------------------------------------
*/

// no direct access
defined('_JEXEC') or die('Restricted access');
$k2route = JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'route.php';
$k2utilities = JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'utilities.php';
if (file_exists($k2route))
	require_once($k2route);
	
if (file_exists($k2utilities))
	require_once($k2utilities);
	
abstract class modSlideShowSP2K2Helper {

	static function getList($params){
	
			$count		    = $params->get('max_article',3); 
			$thumbratio		= $params->get('thumbratio', 1) ? true : false;
			$thumbwidth		= trim($params->get('thumbwidth', 50));
			$thumbheight	= trim($params->get('thumbheight', 50));
			$titleas		= $params->get('titleas');
			$desclimitas	= $params->get('desclimitas');
			$titlelimit		= (int) $params->get('titlelimit');
			$desclimit		= (int) $params->get('desclimit');
			$c_titleas		= $params->get('c_titleas');
			$c_desclimitas	= $params->get('c_desclimitas');		
			$c_titlelimit	= (int) $params->get('c_titlelimit');
			$c_desclimit	= (int) $params->get('c_desclimit');
			
			//newly added
			$catids								= $params->get('k2catids', array());
			$ordering							= $params->get('ordering', 'a.ordering');
			$ordering_direction					= $params->get('ordering_direction', 'ASC');
			$user_id							= $params->get('user_id');
			$show_featured						= $params->get('show_featured');

			$user 		= JFactory::getUser();
			$aid 		= $user->get('aid');
			$db 		= JFactory::getDBO();

			$jnow 		= JFactory::getDate();
			$now 		= $jnow->toMySQL();
			$nullDate 	= $db->getNullDate();

			$query = "SELECT a.*, c.name as categoryname,c.id as categoryid, c.alias as categoryalias, c.params as categoryparams".
			" FROM #__k2_items as a".
			" LEFT JOIN #__k2_categories c ON c.id = a.catid";
			$query .= " WHERE a.published = 1 AND a.access IN(".implode(',', $user->authorisedLevels()).") AND a.trash = 0 AND c.published = 1 AND c.access IN(".implode(',', $user->authorisedLevels()).")  AND c.trash = 0";
			
			// User filter
			$userId = JFactory::getUser()->get('id');
			switch ($params->get('user_id'))
			{
				case 'by_me':
					$query .= ' AND (a.created_by = ' . (int) $userId . ' OR a.modified_by = ' . (int) $userId . ')';
					break;
				case 'not_me':
					$query .= ' AND (a.created_by <> ' . (int) $userId . ' AND a.modified_by <> ' . (int) $userId . ')';
					break;

				case '0':
					break;

				default:
					$query .= ' AND (a.created_by = ' . (int) $userId . ' OR a.modified_by = ' . (int) $userId . ')';
					break;				
			}

			//Added Category
			if (!is_null($catids)) {
				if (is_array($catids)) {
					JArrayHelper::toInteger($catids);
					$query .= " AND a.catid IN(".implode(',', $catids).")";
				} else {
					$query .= " AND a.catid=".(int)$catids;
				}
			}		
			
			//  Featured items filter
			if ($show_featured == '0')
			$query .= " AND a.featured != 1";

			if ($show_featured == '1')
			$query .= " AND a.featured = 1";

			// ensure should be published
			$query .= " AND ( a.publish_up = ".$db->Quote($nullDate)." OR a.publish_up <= ".$db->Quote($now)." )";
			$query .= " AND ( a.publish_down = ".$db->Quote($nullDate)." OR a.publish_down >= ".$db->Quote($now)." )";
			
			//Ordering
			$orderby = $ordering . ' ' . $ordering_direction; //ordering

			$query .= " ORDER BY ".$orderby;
			$db->setQuery($query, 0, $count);
			$items = $db->loadObjectList();
			
			require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'models'.DS.'item.php');
			$model = new K2ModelItem;
			if (count($items)) {
				foreach ($items as $item) {
				
					if (! empty($item->created_by_alias)) {
						$item->author = $item->created_by_alias;
					} else {
						$author = &JFactory::getUser($item->created_by);
						$item->author = $author->name;
					}
	
					$item->created 		= JHTML::_('date', $item->created, JText::_('DATE_FORMAT_LC3'));
					$item->hits 		= $item->hits;
					
					$item->image 		= JURI::base().self::getImage($item->id, $item->introtext, $thumbwidth, $thumbheight, $thumbratio)->image;
					$item->thumb 		= JURI::base().self::getImage($item->id, $item->introtext, $thumbwidth, $thumbheight, $thumbratio)->thumb;
					$item->none 		= JURI::base().'modules/mod_slideshow_pro_sp2/assets/images/none.gif';
					$item->title 		= self::cText(htmlspecialchars($item->title),$titlelimit,$titleas);
					$item->text 		= self::cText(JHtml::_('content.prepare', $item->introtext),$desclimit,$desclimitas);	
					$item->c_title 		= self::cText(htmlspecialchars($item->title),$c_titlelimit,$c_titleas);
					$item->c_text 		= self::cText(JHtml::_('content.prepare', $item->introtext),$c_desclimit,$c_desclimitas);
					$item->link 		= urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias), $item->catid.':'.urlencode($item->categoryalias))));
					
					$rows[] = $item;
				}
				return $rows;
			}
	}
	
	static function cText($text, $limit, $limitas) {
		
		switch ($limitas) {
			case 0 :
				$text = JFilterOutput::cleanText($text);
				$text = explode(' ',$text);
				$sep = (count($text)>$limit) ? '...' : '';
				$text=implode(' ', array_slice($text,0,$limit)) . $sep;
				break;
			case 1 :
				$text = JFilterOutput::cleanText($text);
				$sep  = (strlen($text)>$limit) ? '...' : '';
				$text =utf8_substr($text,0,$limit) . $sep;
				break;
			case 2 :
				$allowed_tags = '<p><span><b><i><a><small><h1><h2><h3><h4><h5><h6><sup><sub><em><strong><u><br>';
				$text = strip_tags( $text, $allowed_tags );
				$text = $text;
				break;
			default :
				$text = JFilterOutput::cleanText($text);
				$text = explode(' ',$text);
				$sep = (count($text)>$limit) ? '...' : '';
				$text=implode(' ', array_slice($text,0,$limit)) . $sep;
				break;
		}		
		
		return $text;
	}	
	
	//retrive k2 image
	static function getImage($id, $text, $thumbwidth=50, $thumbheight=50, $thumbratio) {
	
		if (JFile::exists(JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache' . DS . md5("Image" . $id) . '_XL.jpg')) {
			$image_path = 'media/k2/items/cache/' . md5("Image" . $id) . '_XL.jpg';
		} else {
			preg_match('/< *img[^>]*src *= *["\']?([^"\']*)/i', $text, $matches);	
			if (isset($matches[1])) {
				$image_path = $matches[1];
			}		
		}

		$images = new stdClass();
		$images->image = false;
		
		$paths = array();
		if ($image_path) {
			// remove any / that begins the path
			if (substr($image_path, 0 , 1) == '/') $image_path = substr($image_path, 1);
			
			// create a thumb filename
			$file_div = strrpos($image_path,'.');
			$thumb_ext = substr($image_path, $file_div);
			$thumb_prev = substr($image_path, 0, $file_div);
			$thumb_path = $thumb_prev . "_thumb" . $thumb_ext;
				
			// check to see if this file exists, if so we don't need to create it
			if (function_exists("gd_info")) {
				// file doens't exist, so create it and save it
				if (!class_exists("spThumbnail")) include_once('class.spThumbnail.php');
				
				//Check existing thumbnails dimensions
				if (file_exists($thumb_path)) {
					$size = GetImageSize( $thumb_path );
					$currentWidth=$size[0];
					$currentHeight=$size[1];
				}
				
				//Creating thumbnails		
                if (!file_exists($thumb_path) || $currentWidth!=$thumbwidth || $currentHeight!=$thumbheight ) {
					$thumb = new spThumbnail;
					$thumb->new_width = $thumbwidth;
					$thumb->new_height = $thumbheight;
					$thumb->image_to_resize = $image_path; // Full Path to the file
					$thumb->ratio = $thumbratio; // Keep Aspect Ratio?
					$thumb->save = $thumb_path;
					$thumb->resize();
    			}
			}
			
			$images->image = $image_path;
			$images->thumb = $thumb_path;
		} 
		return $images;		
	}	
}