<?php
/**
 * @package XpertScroller
 * @version 2.5.5
 * @author ThemeXpert http://www.themexpert.com
 * @copyright Copyright (C) 2009 - 2011 ThemeXpert
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
 *
 */

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

abstract class modXpertScrollerHelper{
    
    public $moduleId = 0; //hold module unique id
    public $content = ''; //hold all content
    
    public static function getList(&$params){

        $total_items = (int) $params->get('count', 4) ;
        $content_source = $params->get('content_source','joomla');

        switch($content_source){
            case 'joomla':
                $lists = self::_getJoomlaItems($params,$total_items);
                break;
            case 'k2':
                $lists = self::_getK2Items($params, $total_items);
                break;
        }
        return $lists;

    }

    private static function _getJoomlaItems($params,$total_items)
    {
        require_once JPATH_SITE.'/components/com_content/helpers/route.php';
        jimport('joomla.application.component.model');
        JModel::addIncludePath(JPATH_SITE.'/components/com_content/models');

        // Get the dbo
        $db = JFactory::getDbo();

        // Get an instance of the generic articles model
        $model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));

        // Set application parameters in model
        $app = JFactory::getApplication();
        $appParams = $app->getParams();
        $model->setState('params', $appParams);

        // Set the filters based on the module params
        $model->setState('list.start', 0);
        $model->setState('list.limit', $total_items);
        $model->setState('filter.published', 1);

        // 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()));

        // User filter
        $userId = JFactory::getUser()->get('id');
        switch ($params->get('user_id'))
        {
                case 'by_me':
                        $model->setState('filter.author_id', (int) $userId);
                        break;
                case 'not_me':
                        $model->setState('filter.author_id', $userId);
                        $model->setState('filter.author_id.include', false);
                        break;

                case '0':
                        break;

                default:
                        $model->setState('filter.author_id', (int) $params->get('user_id'));
                        break;
        }
        // Filter by language
        $model->setState('filter.language',$app->getLanguageFilter());

        //  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;
        }

        // Set ordering
        $order_map = array(
                'm_dsc' => 'a.modified DESC, a.created',
                'mc_dsc' => 'CASE WHEN (a.modified = '.$db->quote($db->getNullDate()).') THEN a.created ELSE a.modified END',
                'c_dsc' => 'a.created',
                'p_dsc' => 'a.publish_up',
        );
        $ordering = JArrayHelper::getValue($order_map, $params->get('ordering'), 'a.publish_up');
        $dir = 'DESC';

        $model->setState('list.ordering', $ordering);
        $model->setState('list.direction', $dir);
        $items = $model->getItems();

        $dimensions = array(
            'width'  => $params->get('image_width',100),
            'height' => $params->get('image_height',100)
        );

       foreach ($items as &$item) {
            $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->catslug));
            }
            else {
                    $item->link = JRoute::_('index.php?option=com_users&view=login');
            }

            //Introtext
            $item->introtext = self::prepareIntroText($item->introtext,$params->get('intro_text_limit',100));

            //Take advantage from joomla default Intro image system
            $images = json_decode($item->images);

            if( isset($images->image_intro) and !empty($images->image_intro))
            {
                $item->image = self::getResizedImage($images->image_intro, $dimensions, $params);
            }else{
                //get image from article intro text
                $item->image = self::getResizedImage(self::getImage($item->introtext), $dimensions, $params);
            }

        }

        return $items;
    }

    private static function _getK2Items($params,$total_items)
    {
        require_once(JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'route.php');
        require_once(JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'utilities.php');

        jimport('joomla.filesystem.file');
        $mainframe = &JFactory::getApplication();
        $limit = $total_items;
        $cid = $params->get('category_id', NULL);
        $ordering = $params->get('itemsOrdering','');
        /*$componentParams = &JComponentHelper::getParams('com_k2');
        $limitstart = JRequest::getInt('limitstart');*/

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

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

        $query = "SELECT i.*, c.name AS categoryname,c.id AS categoryid, c.alias AS categoryalias, c.params AS categoryparams";

        if ($ordering == 'best')
        $query .= ", (r.rating_sum/r.rating_count) AS rating";

        if ($ordering == 'comments')
        $query .= ", COUNT(comments.id) AS numOfComments";

        $query .= " FROM #__k2_items as i LEFT JOIN #__k2_categories c ON c.id = i.catid";

        if ($ordering == 'best')
        $query .= " LEFT JOIN #__k2_rating r ON r.itemID = i.id";

        if ($ordering == 'comments')
        $query .= " LEFT JOIN #__k2_comments comments ON comments.itemID = i.id";

        $query .= " WHERE i.published = 1 AND i.access IN(".implode(',', $user->getAuthorisedViewLevels()).") AND i.trash = 0 AND c.published = 1 AND c.access IN(".implode(',', $user->getAuthorisedViewLevels()).")  AND c.trash = 0";
        $query .= " AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )";
        $query .= " AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )";


        if ($params->get('catfilter')) {
            if (!is_null($cid)) {
                if (is_array($cid)) {
                    if ($params->get('getChildren')) {
                        require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'models'.DS.'itemlist.php');
                        $categories = K2ModelItemlist::getCategoryTree($cid);
                        $sql = @implode(',', $categories);
                        $query .= " AND i.catid IN ({$sql})";

                    } else {
                        JArrayHelper::toInteger($cid);
                        $query .= " AND i.catid IN(".implode(',', $cid).")";
                    }

                } else {
                    if ($params->get('getChildren')) {
                        require_once (JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'models'.DS.'itemlist.php');
                        $categories = K2ModelItemlist::getCategoryTree($cid);
                        $sql = @implode(',', $categories);
                        $query .= " AND i.catid IN ({$sql})";
                    } else {
                        $query .= " AND i.catid=".(int)$cid;
                    }

                }
            }
        }

        if ($params->get('FeaturedItems') == '0')
        $query .= " AND i.featured != 1";

        if ($params->get('FeaturedItems') == '2')
        $query .= " AND i.featured = 1";

        if ($ordering == 'comments')
        $query .= " AND comments.published = 1";


        if($mainframe->getLanguageFilter()) {
            $languageTag = JFactory::getLanguage()->getTag();
            $query .= " AND c.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
        }


        switch ($ordering) {

            case 'date':
                $orderby = 'i.created ASC';
                break;

            case 'rdate':
                $orderby = 'i.created DESC';
                break;

            case 'alpha':
                $orderby = 'i.title';
                break;

            case 'ralpha':
                $orderby = 'i.title DESC';
                break;

            case 'order':
                if ($params->get('FeaturedItems') == '2')
                $orderby = 'i.featured_ordering';
                else
                $orderby = 'i.ordering';
                break;

            case 'rorder':
                if ($params->get('FeaturedItems') == '2')
                $orderby = 'i.featured_ordering DESC';
                else
                $orderby = 'i.ordering DESC';
                break;

            case 'hits':
                if ($params->get('popularityRange')){
                    $datenow = &JFactory::getDate();
                    $date = $datenow->toSQL();
                    $query.=" AND i.created > DATE_SUB('{$date}',INTERVAL ".$params->get('popularityRange')." DAY) ";
                }
                $orderby = 'i.hits DESC';
                break;

            case 'rand':
                $orderby = 'RAND()';
                break;

            case 'best':
                $orderby = 'rating DESC';
                break;

            case 'comments':
                if ($params->get('popularityRange')){
                    $datenow = &JFactory::getDate();
                    $date = $datenow->toSQL();
                    $query.=" AND i.created > DATE_SUB('{$date}',INTERVAL ".$params->get('popularityRange')." DAY) ";
                }
                $query.=" GROUP BY i.id ";
                $orderby = 'numOfComments DESC';
                break;

            case 'modified':
                $orderby = 'i.modified DESC';
                break;

            default:
                $orderby = 'i.id DESC';
                break;
        }

        $query .= " ORDER BY ".$orderby;
        $db->setQuery($query, 0, $limit);
        $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) {

                //Clean title
                $item->title = JFilterOutput::ampReplace($item->title);

                //Read more link
                $item->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias), $item->catid.':'.urlencode($item->categoryalias))));

                //Item Image
                $item->image = self::getK2Images($item->id,$item->title,$item->introtext);

                //Preapere introtext
                $item->introtext = self::prepareIntroText($item->introtext,$params->get('intro_text_limit',100));

            }
        }

        return $items;
    }

    /***
     *
     * Get only large image from k2 image source, if failed then search for introtext.
     *
     * @params $id
     * @params $title
     * @params $text
     * @return $image_path
     *
     **/
    public static function getK2Images($id, $title, $text)
    {
        if (file_exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$id).'_L.jpg')) {
            $image_path = 'media/k2/items/cache/'.md5("Image".$id).'_L.jpg';
            $image_path = JURI::Root(true).'/'.$image_path;
            return $image_path;
        }
        elseif($text != NULL){

            return self::getImage($text);
        }
        else{
            echo "Image not found for article $title \n";
        }

    }

    /***
     *
     * Get image from given text.
     *
     * @params $text
     * @return $image path
     *
     */
    public static function getImage($text)
    {
        if(preg_match("/\<img.+?src=\"(.+?)\".+?\>/", $text, $matches)){
            $image_path='';

            $paths = array();

            if (isset($matches[1])) {
                $image_path = $matches[1];
                //$image_path = JURI::Root(True)."/".$image_path;
            }
            return $image_path;
        }
        return false;

    }

    /***
     *
     * Stripe unnecessary html tags from given text and trim according to given limit.
     *
     * @params $text
     * @params $num_character
     * @return $text
     *
     */
    public static function prepareIntroText ($text, $num_character)
    {
        $text = strip_tags($text,"</strong></em></a></span></p>");

        if(strlen($text)>$num_character && $num_character!=0){
            $text1 = substr ($text, 0, $num_character) . "..";
            return $text1;
        }
        else return $text;
    }
        
    
   /*
    * Load add script settings
    * and push it to document head
    */
    public function load_script(&$params,$module)
    {
        $doc =& JFactory::getDocument();
        //set moduleid
        $moduleId = ($params->get('auto_module_id',0)==1) ? 'xs_'.$module->id : $params->get('module_unique_id');

        //Load jQuery
        modXpertScrollerHelper::load_jquery($params);
        //modXpertScrollerHelper::load_scroller();
        
        $animationMode = ($params->get('animation_style') == 'animation_h') ? 'false' : 'true';
        $speed = (int)$params->get('animation_speed');
        $repeat = ( (int)$params->get('repeat') ) ? 'true' : 'false';
        $keyboardNav = ( (int)$params->get('keyboard_navigation') ) ? 'true' : 'false';
        
        //auto scroll plugin config
        $autoScroll = '';
        if ( (int)$params->get('auto_play') ){
            $autoPlay   = ( (int)$params->get('auto_play') ) ? 'true' : 'false';
            $interval   = (int)$params->get('interval');
            $autoPause  = ( (int)$params->get('auto_pause') ) ? 'true' : 'false';
            
            $autoScroll = ".autoscroll({ autoplay: {$autoPlay} , interval: {$interval}, autopause:{$autoPause} })";
        }
        //navigator plugin config
        $navigator='';
        if($params->get('navigator')) $navigator = ".navigator()";

        $js = "
            jQuery(document).ready(function(){
                jQuery('#{$moduleId}').scrollable({
                    vertical: {$animationMode},
                    speed: {$speed},
                    circular: {$repeat},
                    keyboard: {$keyboardNav}
                }){$autoScroll}{$navigator};
            });
        ";
        $doc->addScriptDeclaration($js);
    }
    
    /*Load jQuery with scroller js engine*/
    protected function load_jquery(&$params)
    {
        $doc =& JFactory::getDocument();
        $app =& JFactory::getApplication();
        
        static $jqLoaded;
        
        if ($jqLoaded) {
            return;
        }   
   
        if($params->get('load_jquery') AND !$app->get('jQuery')){
            //get the cdn
            $cdn = $params->get('jquery_source');
            switch ($cdn){
                case 'google_cdn':
                    $file = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js';
                    break;
                case 'local':
                    $file = JURI::root(true).'/modules/mod_xpertscroller/assets/js/jquery-1.7.2.min.js';
                    break;
            }
            $app->set('jQuery',1);
            $doc->addScript($file);
            $doc->addScriptDeclaration("jQuery.noConflict();");
            $jqLoaded = TRUE;
        }
        
        if(!defined('XPERT_SCROLLER')){
            //add scroller js file
            $doc->addScript(JURI::root(true).'/modules/mod_xpertscroller/assets/js/xpertscroller.js');
            $doc->addScript(JURI::root(true).'/modules/mod_xpertscroller/assets/js/script.js');
            define('XPERT_SCROLLER',1);
        }
    }
        
    /*
    * Load necesery style.
    * take all css settings and push it on document head
    */
    
    public function load_style(&$params,$module)
    {
        $doc =& JFactory::getDocument();
        //set moduleid
        $module_id = ($params->get('auto_module_id',0)==1) ? 'xs_'.$module->id : $params->get('module_unique_id');
        $moduleId = '#'.$module_id;
        $moduleClass = '.'. $module_id;
        
        $scrollerLayout = $params->get('scroller_layout');
        
        /*
        * module unique id will only assign on horizontl style. 
        * this unique class will only use for navigation arrow styling
        * vertical style will auto adjuct arrow position to middle using css file.
        */
        $selectorClass = ($scrollerLayout == 'basic_h') ? '.' . $moduleId : '';
        
        //scroller wrapper widtha nd height. this width and height will effect on .pane class also.
        $moduleWidth = $paneWidth = (int)$params->get('module_width');
        $moduleHeight = (int)$params->get('module_height');
        
        /*
        * In horizontal style item width will calculated by persentage value
        * In vertical style item height will calculate on module height and num of columns
        */
        if($scrollerLayout == 'basic_h') $itemDimensions = 'width:'. 100 / (int)$params->get('col_amount') . '%';
        else $itemDimensions = 'width: 100%; height:' . $moduleHeight / $params->get('col_amount') .'px' ;
        
        $controlMargin = $params->get('control_margin');
        
        //items div always higher value thats way we will check animatin style and determine the proper css property
        $animationStyle = ($params->get('animation_style') == 'animation_h') ? 'width' : 'height';
        
        //resize image forcefully when image resize settings is turn on. later version will add auto thums generator engine.
        $imgWidth = NULL;
        $imgHeight = NULL;
        if ( $params->get('image_resize') ){
            $imgWidth   = (int)$params->get('image_width');
            $imgHeight  = (int)$params->get('image_height');
        }
        //preaper all css settings
        $css = "
            {$moduleId} {height: {$moduleHeight}px;}

            {$moduleId} .items { {$animationStyle}:20000em; }
            {$moduleId} .pane .item{{$itemDimensions}; overflow:hidden; }

            {$moduleClass} a.browse{ margin:{$controlMargin}; }
            
        ";
        //push this css on document head
        $doc->addStyleDeclaration($css);
        
        //load stylesheet
        modXpertScrollerHelper::load_stylesheet($params);
        
    }
    /*
    * Load Stylesheet
    * 
    */    
    public function load_stylesheet(&$params)
    {
        $app = &JApplication::getInstance('site', array(), 'J');
        $template = $app->getTemplate();
        $doc =& JFactory::getDocument();
        static $loadedBasicStyle;
        
        if ($loadedBasicStyle){
            return;
        }
        
        if($params->get('scroller_layout') == 'basic_h' || $params->get('scroller_layout') == 'basic_v'){
            if (file_exists(JPATH_SITE.DS.'templates'.DS.$template.'/css/xpertscroller.css')) {
               $doc->addStyleSheet(JURI::root(true).'/templates/'.$template.'/css/xpertscroller.css');
            }    
            else {
                $doc->addStyleSheet(JURI::root(true).'/modules/mod_xpertscroller/assets/css/xpertscroller.css');
            }
            
            $loadedBasicStyle = TRUE;
        }
    }
    
    public static function getResizedImage($path, $dimensions = array(), $params){
    
        jimport('joomla.filesystem.folder');
        jimport('joomla.filesystem.file');

        if( !file_exists($path) ) return ;

        if(!class_exists('XpertThumb')){
            include_once 'libs/xpertthumb.php';
        }
        
        $xt = new XpertThumb($path);

        $image_info = pathinfo($path);
        $image_size = getimagesize($path);

        $cache_path = JPATH_ROOT. '/cache/mod_xpertscroller';

        // create cache folder if not exist
        JFolder::create($cache_path, 0755);

        $name = md5( $image_info['basename'].$dimensions['width'].$dimensions['height']).'_resized';

        $newpath = $cache_path . '/' . $name . '.' . $image_info['extension'];

        $image_uri = JURI::base(true). '/cache/mod_xpertscroller/'  . $name . '.' . $image_info['extension'];

        if(!file_exists($newpath))
        {
            $xt->resize( $dimensions['width'], $dimensions['height'] , true, 1 )
                ->toFile( $newpath );
        }
        return $image_uri;
    }
}