<?php
/* ======================================================
# Monthly Archive - Joomla! Component v4.3.3 (PRO version)
# -------------------------------------------------------
# For Joomla! 3.x
# Author: Yiannis Christodoulou (yiannis@web357.eu)
# Copyright (©) 2009-2018 Web357. All rights reserved.
# License: GNU/GPLv3, http://www.gnu.org/licenses/gpl-3.0.html
# Website: https://www.web357.eu/
# Demo: http://demo.web357.eu/?item=monthlyarchive
# Support: support@web357.eu
# Last modified: 09 Feb 2018, 13:55:18
========================================================= */

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

jimport('joomla.application.component.view');

class MonthlyarchiveViewArchive extends JViewLegacy
{
	protected $items;

	protected $pagination;

	protected $state;

	protected $params;

	public function display($tpl = null)
	{
		if (!defined("DS")):
			define("DS", DIRECTORY_SEPARATOR);
		endif;
		
		$app = JFactory::getApplication();
		$params = $app->getParams('com_monthlyarchive');
		$this->document = JFactory::getDocument();
		$menu = JFactory::getApplication()->getMenu();
		$active = $menu->getActive();

		$this->state      		= $this->get('State');
		$this->items 	  		= $this->get('Items');
		//$this->content_items 	= $this->get('ContentItems');
		$this->pagination 		= $this->get('Pagination');
		$this->params     		= $app->getParams('com_monthlyarchive');
		$this->filterForm 		= $this->get('FilterForm');

		// config
		$config = JFactory::getConfig();
		$this->sef = $config->get('sef');

		// Load model
		JModelLegacy::addIncludePath(JPATH_SITE . '/components/com_monthlyarchive/models', 'MonthlyarchiveModel');
		$ma_model = JModelLegacy::getInstance( 'Archive', 'MonthlyarchiveModel' );

		//$this->items = $ma_model->getItemsForModule($params, true); //$this->getItems();
		$this->content_items = $ma_model->getItems($params, true); //$this->getItems();

		// get filter search
		$this->filter_search = $this->getState('filter.search');

		// remove the view 'archive' from the url after clicking on pagination links
		$this->pagination->setAdditionalUrlParam('view', '');

		// get com_content params
		$this->com_content_params = $app->getParams('com_content');

		// ***** BEGIN: Get Params ***** 
		//$params 												= $app->getParams('com_monthlyarchive');
		$this->display_type 									= $params->get('display_type', 'list_of_months_and_years');
		$this->ma_language 										= $params->get('ma_language', '*');
		$this->content_type 									= $params->get('content_type', 'default');
		
		// Page title & Welcome Message for months and years
		$this->show_page_title_list_of_months_and_years 		= $params->get('show_page_title_list_of_months_and_years', '1');
		$this->page_title_list_of_months_and_years 				= $params->get('page_title_list_of_months_and_years', JText::_('COM_MONTHLYARCHIVE_PAGE_TITLE'));
		$this->show_welcome_message_list_of_months_and_years 	= $params->get('show_welcome_message_list_of_months_and_years', '1');
		$this->welcome_message_list_of_months_and_years 		= $params->get('welcome_message_list_of_months_and_years', 'Welcome to our Archives page. On this page you will find totaly <strong>%u</strong> of our articles broken down into Months and Years.');

		// Page title & Welcome Message for articles list
		$this->show_page_title_list_of_all_articles 			= $params->get('show_page_title_list_of_all_articles', '1');
		$this->page_title_list_of_all_articles 					= $params->get('page_title_list_of_all_articles', JText::_('COM_MONTHLYARCHIVE_PAGE_TITLE'));
		$this->show_welcome_message_list_of_all_articles 		= $params->get('show_welcome_message_list_of_all_articles', '1');
		$this->welcome_message_list_of_all_articles 			= $params->get('welcome_message_list_of_all_articles', 'Welcome to our Archives page. On this page you will find totaly <strong>%u</strong> of our articles broken down into Months and Years.');

		// back button
		$this->show_back_btn 									= $params->get('show_back_btn', '1');

		// Page Heading
		$show_page_heading 										= (!empty($active)) ? $active->params->get('show_page_heading') : 1;
		$page_heading 											= (!empty($active) && $show_page_heading) ? $active->params->get('page_heading') : '';
		$this->menu_page_heading 								= (!empty($page_heading)) ? $page_heading : '';

		// Browser Page Title
		$browser_page_title 									= (!empty($active)) ? $active->params->get('page_title') : '';
		$this->menu_browser_page_title 							= (!empty($browser_page_title)) ? $browser_page_title : '';

		// SEARCH OPTIONS
		$this->select_author_home 								= $params->get('select_author_home', '1');
		$this->select_category_home 							= $params->get('select_category_home', '1');
		$this->search_input_home 								= $params->get('search_input_home', '1');
		$this->select_months_page 								= $params->get('select_months_page', '1');
		$this->select_order_page 								= $params->get('select_order_page', '1');
		$this->select_author_page 								= $params->get('select_author_page', '1');
		$this->select_category_page 							= $params->get('select_category_page', '1');
		$this->search_input_page 								= $params->get('search_input_page', '1');

		// LAYOUT: LIST OF ALL MONTHS & YEARS
		$this->ma_layout 										= $params->get('ma_layout', 'default');
		$this->show_year 										= $params->get('show_year', '1');
		$this->sort_years_by 									= $params->get('sort_years_by', 'newest_first');
		$this->limit_of_years 									= $params->get('limit_of_years', '24');
		$this->show_month 										= $params->get('show_month', '1');
		$this->sort_months_by 									= $params->get('sort_months_by', 'desc');
		$this->limit_of_months 									= $params->get('limit_of_months', '12');
		$this->show_count_of_articles_beside_years 				= $params->get('show_count_of_articles_beside_years', '1');
		$this->show_count_of_articles_beside_months 			= $params->get('show_count_of_articles_beside_months', '1');

		// LAYOUT: LIST OF ALL ARTICLES OF A YEAR OR A MONTH
		$this->show_category_beside_article 					= $params->get('show_category_beside_article', '1');
		$this->show_author_beside_article 						= $params->get('show_author_beside_article', '1');
		$this->author_name_type 								= $params->get('author_name_type', 'author_name');
		$this->show_date_beside_articles 						= $params->get('show_date_beside_articles', '1');
		$this->show_date_beside_articles_type 					= $params->get('show_date_beside_articles_type', 'created');
		$this->default_date_format 								= $params->get('default_date_format', 'd M');
		$this->custom_date_format 								= $params->get('custom_date_format', '');
		$this->default_date_format_for_tooltip 					= $params->get('default_date_format_for_tooltip', 'l d F Y, H:i');
		$this->custom_date_format_for_tooltip 					= $params->get('custom_date_format_for_tooltip', '');
		$this->show_hits 										= $params->get('show_hits', '1');
		$this->link_type 										= $params->get('link_type', 'default');
		$this->link_to_article 									= $params->get('link_to_article', '1');
		$this->display_pagination 								= $params->get('display_pagination', '1');
		$this->display_content_type 							= $params->get('display_content_type', 'introtext');
		$this->article_limit_chars								= $params->get('article_limit_chars', '200');
		$this->allowed_html_tags 								= $params->get('allowed_html_tags', '');
		$this->show_readmore_link 								= $params->get('show_readmore_link', '1');

		// IMAGES
		$this->display_image 									= $params->get('display_image', '1');
		$this->display_image_in_modal 							= $params->get('display_image_in_modal', '1');
		$this->link_to_image 									= $params->get('link_to_image', '1');
		$this->image_priority_1 								= $params->get('image_priority_1', 'full');
		$this->image_priority_2 								= $params->get('image_priority_2', 'intro');
		$this->image_priority_3 								= $params->get('image_priority_3', 'auto');
		$this->image_priority_4 								= $params->get('image_priority_4', 'blank');
		$this->auto_image_order 								= $params->get('auto_image_order', 'first_image');
		$this->img_width 										= $params->get('img_width', '');
		$this->img_height 										= $params->get('img_height', '');
		
		// COMMENTS
		$this->show_count_comments 								= $params->get('show_count_comments', '1');

		// SEO SETTINGS
		$this->ma_robots 										= $params->get('ma_robots', '');
		$this->follow_links 									= $params->get('follow_links', 'follow');

		// Copyright message
		$this->copyright 										= $params->get('copyright', '1');

		// ***** END: Get Params ***** 

		// menu item
		$menu_item 												= JFactory::getApplication()->getMenu()->getItems( 'link', 'index.php?option=com_monthlyarchive&view=archive', true );
		$default_menu_item_id 									= (!empty($menu_item)) ? $menu_item->id : '';
		$menu_item_id 											= JFactory::getApplication()->input->get('Itemid', $default_menu_item_id, 'INT');
		$this->menu_item_id_value 								= (int) (!empty($menu_item_id)) ? $menu_item_id : '';
		$this->menu_item_id 									= (!empty($menu_item_id)) ? '&Itemid='.$menu_item_id : '';
		
		// load url
		jimport('joomla.environment.uri' );
		$host = JURI::root();
		
		// load jQuery
		JHtml::_('jquery.framework', false);

		// Avoid conflicts with other jQuery versions
		$this->document->addScript($host.'components/com_monthlyarchive/assets/js/jquery.no-conflict.js');

		// UIkit 3.0.0-beta.21
		$this->document->addStyleSheet($host.'components/com_monthlyarchive/assets/uikit/uikit.min.css');
		$this->document->addScript($host.'components/com_monthlyarchive/assets/uikit/uikit.min.js');
		$this->document->addScript($host.'components/com_monthlyarchive/assets/uikit/uikit-icons.min.js');

		// Custom css
		$this->document->addStyleSheet($host.'components/com_monthlyarchive/views/archive/tmpl/default.css');

		// Routing
		if ($this->content_type == 'k2' && $this->isActive('com_k2'))
		{
			// com_k2 route (for the correct link of content item)
			require_once(JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'route.php');
		}
		else
		{
			// com_content route (for the correct link of content item)
			JLoader::register('ContentHelperRoute', JPATH_SITE . '/components/com_content/helpers/route.php');
		}

		// get month and year from URL
		$this->get_year = JFactory::getApplication()->input->get('year', '', 'STRING');
		$this->get_month = JFactory::getApplication()->input->get('month', '', 'INT');
		$this->get_month = (is_numeric($this->get_month)) ? sprintf("%02d", $this->get_month) : $this->get_month;

		// Block the entire page from Search Engines
		if (!empty($this->ma_robots)):
			$this->document->setMetaData("robots", $this->ma_robots);
		endif;
		
		// Tell search engines to follow or no follow the links https://support.google.com/webmasters/answer/96569?hl=en
		$this->rel_nofollow = ($this->follow_links == 'nofollow') ? ' rel="nofollow"' : '';

		// Search input
		$filters = $this->filterForm->getGroup('filter');
		$filter_search = $filters['filter_search'];
		$this->search_input = $filter_search->input;

		// Filter Ordering
		$options = array();
		$options[0] = new stdClass();
		$options[0]->value = "";
		$options[0]->text = JText::_('COM_MONTHLYARCHIVE_ORDERING');
		$options[1] = new stdClass();
		$options[1]->value = "most_recent_first";
		$options[1]->text = JText::_('COM_MONTHLYARCHIVE_MOST_RECENT_FIRST');
		$options[2] = new stdClass();
		$options[2]->value = "oldest_first";
		$options[2]->text = JText::_('COM_MONTHLYARCHIVE_OLDEST_FIRST');
		$options[3] = new stdClass();
		$options[3]->value = "most_hits";
		$options[3]->text = JText::_('COM_MONTHLYARCHIVE_MOST_HITS');
		$options[4] = new stdClass();
		$options[4]->value = "least_hits";
		$options[4]->text = JText::_('COM_MONTHLYARCHIVE_LEAST_HITS');
		$this->orderby_list = JHTML::_( 'select.genericlist',
                    $options, 
                    'filter[orderby]', 
					'class="uk-select ma-select"',
                    'value', 
					'text', 
					$this->getState('filter.orderby'), 
					'filter_orderby', 
                    true);

		// Filter Authors
		$selectlist_data = array();
		$selectlist_data[] = JHTML::_('select.option', '', JText::_('COM_MONTHLYARCHIVE_SELECT_AUTHOR'), 'author_id', 'author_name' );
		$selectlist_data = array_merge( $selectlist_data, $this->get('Authors'));
		$this->authors_list = JHTML::_('select.genericlist',
							$selectlist_data, 
							'filter[author]', 
							'class="uk-select ma-select"',
							'author_id', 
							'author_name', 
							$this->getState('filter.author'), 
							'filter_author', 
							true);

		// Filter Categories
		$selectlist_data = array();
		$selectlist_data[] = JHTML::_('select.option', '', JText::_('COM_MONTHLYARCHIVE_SELECT_CATEGORY'), 'category_id', 'category_name' );
		$selectlist_data = array_merge( $selectlist_data, $this->get('Categories'));
		$this->categories_list = JHTML::_('select.genericlist',
							$selectlist_data, 
							'filter[category]', 
							'class="uk-select ma-select"',
							'category_id', 
							'category_name', 
							$this->getState('filter.category'), 
							'filter_category', 
							true);

		// Filter Months/Years
		$monthsyears_arr = array();
		foreach ($this->content_items as $i => $item)
		{
			if ($this->show_date_beside_articles_type == 'publish_up')
			{
				if ($item->publish_up != JFactory::getDbo()->getNullDate()):
					$year = JHTML::_('date', $item->publish_up, "Y");
					$month = JHTML::_('date', $item->publish_up, "m");
				endif;
			}
			else
			{
				if ($item->created != JFactory::getDbo()->getNullDate()):
					$year = JHTML::_('date', $item->created, "Y");
					$month = JHTML::_('date', $item->created, "m");
				endif;
			}
			$monthsyears_arr[$year][] = $month;
			$monthsyears_arr_count_years[$year][] = $item->id;
			$monthsyears_arr_count_months[$year][$month][] = $item->id;
		}

		$options = array();
		$options[0] = new stdClass();
		$options[0]->class = 'uk-select ma-select uk-text-bold ma-filter-date-all';
		$options[0]->value = 'all';
		$options[0]->text =  JText::_('COM_MONTHLYARCHIVE_ALL_MONTHS_AND_YEARS_SELECT_OPTION');

		// Years ordering
		if ($this->sort_years_by == 'newest_first'):
			krsort($monthsyears_arr); // high to low (most recent years first)
		elseif ($this->sort_years_by == 'oldest_first'):
			ksort($monthsyears_arr); // low to high (oldest years first)
		endif;
		
		foreach ($monthsyears_arr as $year=>$months)
		{
			$count_articles_by_year = count($monthsyears_arr_count_years[$year]);

			$options[$year] = new stdClass();
			$options[$year]->class = 'uk-select ma-select uk-text-muted uk-text-bold ma-filter-date-year';
			$options[$year]->value = $year;
			$options[$year]->text = $year. ' ('.$count_articles_by_year.')';

			$months_arr_reverse = array_reverse(array_values(array_unique($months)));
			$months_arr = array_values(array_unique($months));

			// Months ordering
			if ($this->sort_months_by == 'asc'):
				asort($months_arr); // low to high (order months desc)
			elseif ($this->sort_months_by == 'desc'):
				arsort($months_arr); // high to low (order months asc)
			endif;
				
			// re-index array
			$months_arr = array_values($months_arr);

			for ($i=0;$i<count($months_arr);$i++)
			{
				$month = $months_arr[$i] < 10 ? '0'. (int) $months_arr[$i] : (int) $months_arr[$i];
				$count_articles_by_month = count($monthsyears_arr_count_months[$year][$month]);

				$year_month = $year.'-'.$month;
				$options[$year_month] = new stdClass();
				$options[$year_month]->class = 'uk-select ma-select ma-filter-date-month';
				$options[$year_month]->value = $year_month;

				$dateObj   = DateTime::createFromFormat('!m', (int) $month);
				$month_name = $dateObj->format('F');
				$month_name = JText::_($month_name."_FULL");

				$options[$year_month]->text = $month_name.' '.$year.' ('.$count_articles_by_month.')';
			}
		}

		// Get the variables from URL
		$get_year = JFactory::getApplication()->input->get('year', '', 'STRING');
		$get_month = JFactory::getApplication()->input->get('month', '', 'INT');
		$get_month = (is_numeric($get_month) && $get_month > 0) ? sprintf("%02d", $get_month) : $get_month;

		$this->date_list = JHTML::_( 'select.genericlist',
                    $options, 
                    'filter[date]', 
					'class="uk-select ma-select"',
                    'value', 
					'text', 
                    $get_year.(!empty($get_month) ? '-'.$get_month : ''),
					'filter_date', 
                    true);

		// Check for errors.
		if (count($errors = $this->get('Errors')))
		{
			throw new Exception(implode("\n", $errors));
		}

		$this->_prepareDocument();

		parent::display($tpl);
	}

	/**
	 * Check if state is set
	 *
	 * @param   mixed  $state  State
	 *
	 * @return bool
	 */
	public function getState($state)
	{
		return isset($this->state->{$state}) ? $this->state->{$state} : false;
	}

	// Check if the component is installed and is enabled
	public function isActive($option) // e.g. $option = com_k2
	{
		jimport('joomla.component.helper');
		if(!JComponentHelper::isInstalled($option) || !JComponentHelper::isEnabled($option))
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	// Highlight the matched search word
	public function maHighlight($content, $filter_search) 
	{
		if (!empty($filter_search))
		{
			$filter_search = (array) $filter_search;

			$content = strip_tags($content); // do not allow html tags

			// for all words in array
			foreach ($filter_search as $word)
			{
				$lastPos = 0;
				$positions = array();

				// find all positions of word
				while (($lastPos = stripos($content, $word, $lastPos))!== false) 
				{
					$positions[] = $lastPos;
					$lastPos = $lastPos + strlen($word);
				}

				//reverse sort numeric array 
				rsort($positions);
		
				// highlight all occurances
				foreach ($positions as $pos) 
				{
					$content = $this->maHighlightString($content, $word, $pos);
				}
			}
		
			// apply span html code to occurances  
			$content = str_replace('#####', '</span>', $content);
			$content = str_replace('*****', '<span class="ma-highlight-search-word">', $content);
			
			return $content; // return highlighted data
		}
		else
		{
			return $content;
		}
	}
	
	private function maHighlightString($content, $filter_search, $pos)
	{	
		$content = substr_replace($content, '#####', $pos+strlen($filter_search), 0) ;
		$content = substr_replace($content, '*****', $pos, 0) ;
	
		return $content;
	} 

	/**
	 * Prepares the document
	 *
	 * @return void
	 *
	 * @throws Exception
	 */
	protected function _prepareDocument()
	{
		$app   = JFactory::getApplication();
		$menus = $app->getMenu();
		$title = null;

		// Because the application sets a default page title,
		// we need to get it from the menu item itself
		$menu = $menus->getActive();

		if ($menu)
		{
			$this->params->def('page_heading', $this->params->get('page_title', $menu->title));
		}
		else
		{
			$this->params->def('page_heading', JText::_('COM_MONTHLYARCHIVE_PAGE_TITLE'));
		}

		$title = $this->params->get('page_title', '');

		if (empty($title))
		{
			$title = $app->get('sitename');
		}
		elseif ($app->get('sitename_pagetitles', 0) == 1)
		{
			$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
		}
		elseif ($app->get('sitename_pagetitles', 0) == 2)
		{
			$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
		}

		$this->document->setTitle($title);

		if ($this->params->get('menu-meta_description'))
		{
			$this->document->setDescription($this->params->get('menu-meta_description'));
		}

		if ($this->params->get('menu-meta_keywords'))
		{
			$this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords'));
		}

		if ($this->params->get('robots'))
		{
			$this->document->setMetadata('robots', $this->params->get('robots'));
		}
	}
}