<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/***************************************************************************
 *	PROJECT: ZokiSoft Smart Catalog
 *
 *	This program is a commercial software and any kind of using
 *	it must agree to ZokiSoft License Agreement.
 *
 *	This notice may not be removed from the code.
 *
 *	Copyright 2007-2008 ZokiSoft
 *	http://www.zokisoft.com/
 ***************************************************************************/

class Catalog extends Catalog_Controller
{
/*
	var $aHeaderVar = array();
	var $aFooterVar = array();
*/
/*
*
*	Constructor
*
*/
	function Catalog()
	{

		$this->sCurrentContr = 'catalog';
		parent::Catalog_Controller();

		$this->aHeaderVar['catalog_charset'] = $this->config->item('catalog_charset');
		$this->aSystemVar['template_viewer_root'] = $this->config->item('template_module_viewer');
		$this->aSystemVar['template_viewer_current'] = $this->config->item('template_viewer_catalog');

	}


/*
*
*	Main page of catalog.
*
*	@param - current category;
*	@param - paginate page number;
*
*/
	function index( $iCurrentCategory = 0, $iPage = 1 )
	{

		$this->load->helper('text');

		// check if this is category Id or BaseName
		if ( !is_numeric($iCurrentCategory) && preg_match('/^[\w\-\.]+$/', $iCurrentCategory) )
		{
			$this->db->select('`zok_category`.`Id`');
			$this->db->where('`zok_category`.`BaseName` = \'' . $iCurrentCategory . '\'');
			$rRes = $this->db->get('`zok_category`');
			$iCurrentCategory = $rRes->row_array();
// category with this basename does not exist
			if ( empty($iCurrentCategory['Id']) )
			{
				show_404('page');
				//redirect('');
			}

			$iCurrentCategory = $iCurrentCategory['Id'];
		}
		else
		{
			$iCurrentCategory = (int)$iCurrentCategory;
		}

		$iPage = (int)$iPage;

		if ( 0 == $iCurrentCategory )
		{
// root category
			$this->_makeIndexPage();
		}
		else
		{
// any other category
			$this->_makeSubCategoryPage($iCurrentCategory, $iPage);
		}


	}


	function _makeIndexPage()
	{


		$iCurrentCategory = 0;

		$this->aSystemVar['category_id'] = $iCurrentCategory;
		$aData['data'] = array();
		$sDate = date("Y-m-d");

// ================================================================

		$aData['data']['CurrentCategory']['Id'] = $iCurrentCategory;
		$aData['data']['CurrentCategory']['BaseName'] = '';

// ================================================================
/* header info */
		$this->aHeaderVar['page_title'] = $this->lang->line('home');

// ================================================================
// country list
/*
		$sCount = 'COUNT(`zok_post`.`Id`)';
		$this->db->select('`zok_country`.`ISO2`, `zok_country`.`Country`, SUBSTR(`zok_country`.`Country`, 1, 15) as Snipet, ' . $sCount . ' as PostNum', false);
		$this->db->from('`zok_country`');
		$sCondition = '1' == $this->config->item('premoderation') ? ' AND `zok_post`.`status` = \'active\' ' : ' AND `zok_post`.`Status` != \'deleted\' ';
		$this->db->join('`zok_post`', '( `zok_country`.`ISO2` = `zok_post`.`Country` AND `zok_post`.`DateStart` <= \''.$sDate.'\' AND (`zok_post`.`DateEnd` >= \''.$sDate.'\' OR `zok_post`.`DateEnd` = \'0000-00-00\') )' . $sCondition, 'left' );
		if ( isset($aData['data']['CurrentCategory']['BreadCramb']) )
		{
			$this->db->join('`zok_category`', '( `zok_post`.`CategoryId` = `zok_category`.`Id`
				AND `zok_category`.`BreadCramb` LIKE \'' . str_replace('\\', '\\\\\\\\', $aData['data']['CurrentCategory']['BreadCramb'] ) . '%\' )', 'left' );
// show countries with posts > than 0
			$this->db->where('`zok_category`.`Id` IS NOT NULL');
		}
		else
		{
// show countries with posts > than 0
			$this->db->where('`zok_post`.`Id` IS NOT NULL');
		}
*/
// localization
//		if ( !empty($this->aSystemVar['localization']) )
//		$this->db->where('`zok_country`.`ISO2` = \'' . $this->aSystemVar['localization'] . '\'');
/*
		$this->db->groupby('`zok_country`.`Country`');
		$rRes = $this->db->get();
		$aData['data']['CountryList'] = $rRes->result_array();
*/
// ================================================================
// category list
		//$aData['data']['CategoryList'] = $this->Catalog_model->GetSubCategoryList($iCurrentCategory);
		$aData['data']['CategoryList'] = $this->Catalog_model->getCategoriesList($iCurrentCategory,$this->aSystemVar['cur_lang']);

// ================================================================
// ================================================================
// news list:
		if ( 0 < $this->config->item('num_news') )
		{
			$aPostList = $this->Catalog_model->GetPostList( 'news', $this->config->item('num_news') );
			$aData['data']['NewsList'] = $this->_wrapPostArray( $aPostList );
		}
		else
			$aData['data']['NewsList'] = array();

// ================================================================
// featured list:

		if ( 0 < $this->config->item('num_featured') )
		{
			$aPostList = $this->Catalog_model->GetPostList( 'featured', $this->config->item('num_featured') );
			$aData['data']['FeaturedList'] = $this->_wrapPostArray( $aPostList );
		}
		else
			$aData['data']['FeaturedList'] = array();

// ================================================================
// recent list:

		if ( 0 < $this->config->item('num_recent') )
		{
			$aPostList = $this->Catalog_model->GetPostList( 'recent', $this->config->item('num_recent') );
			$aData['data']['RecentList'] = $this->_wrapPostArray( $aPostList );
		}
		else
			$aData['data']['RecentList'] = array();

// ================================================================
// Top list:

		if ( 0 < $this->config->item('num_top') )
		{
			$aPostList = $this->Catalog_model->GetPostList( 'top', $this->config->item('num_top') );
			$aData['data']['TopList'] = $this->_wrapPostArray( $aPostList );
		}
		else
			$aData['data']['TopList'] = array();

// ================================================================
// Random list:

		if ( 0 < $this->config->item('num_random') )
		{
			$aPostList = $this->Catalog_model->GetPostList( 'random', $this->config->item('num_random') );
			$aData['data']['RandomList'] = $this->_wrapPostArray( $aPostList );
		}
		else
			$aData['data']['RandomList'] = array();

// ================================================================
// user list

		$aData['data']['UserList'] = $this->Catalog_model->GetUserList('name');

// ================================================================

//		$aData['data']['User']['Localization'] = $this->aSystemVar['localization'];

		$this->load->view($this->aSystemVar['template_viewer_current'] . 'index_page', $aData);

	}




	function _makeSubCategoryPage( $iCurrentCategory, $iPage )
	{

//==============================
// group permission check
		if ( !$this->_grIsAllowed('categ_to_hide',$iCurrentCategory) )
		{
			$aData = array();
			$this->load->view($this->aSystemVar['template_viewer_root'] . 'design_items/gr_noaccess', $aData);
			return false;
		}
//==============================

		$this->aSystemVar['category_id'] = $iCurrentCategory;
		$aData['data'] = array();
		$sDate = date("Y-m-d");

		$aData['data']['CurrentCategory'] = $this->Catalog_model->getLocCategory($iCurrentCategory,$this->aSystemVar['cur_lang']);

//		$aData['data']['CurrentCategory']['Id'] = $iCurrentCategory;
/*
		if ( empty($aData['data']['CurrentCategory']['BaseName']) )
			$aData['data']['CurrentCategory']['BaseName'] = '';
*/
		$aData['data']['CurrentCategory']['IconUrl'] = '';
		$cat_icon = $this->config->item('base_dir') . $this->config->item('category_pic_path') . $aData['data']['CurrentCategory']['Id'] . '/' . $aData['data']['CurrentCategory']['Pic'] . $aData['data']['CurrentCategory']['Ext'];
		if( $this->Catalog_model->ext_file_exists($cat_icon) )
			$aData['data']['CurrentCategory']['IconUrl'] = $this->config->item('base_url') . $this->config->item('category_pic_url') . $aData['data']['CurrentCategory']['Id'] . '/' . $aData['data']['CurrentCategory']['Pic'] . $aData['data']['CurrentCategory']['Ext'];

		$aData['data']['CurrentCategory']['BreadCrambList'] = $this->Catalog_model->GetNamedBreadCramb(@$aData['data']['CurrentCategory']['BreadCramb'],$this->aSystemVar['cur_lang']);

// ================================================================
/* header info */
		$this->aHeaderVar['page_title'] = $aData['data']['CurrentCategory']['Title'];
		$this->aHeaderVar['meta_desc'] = $aData['data']['CurrentCategory']['Description'];
		$this->aHeaderVar['meta_key'] = $aData['data']['CurrentCategory']['Keywords'];

// ================================================================
// country list
/*
		if ( isset($aData['data']['CurrentCategory']['BreadCramb']) )
			$sCount = 'COUNT(`zok_category`.`BreadCramb`)';
		else
			$sCount = 'COUNT(`zok_post`.`Id`)';
		$this->db->select('`zok_country`.`ISO2`, `zok_country`.`Country`, SUBSTR(`zok_country`.`Country`, 1, 15) as Snipet, ' . $sCount . ' as PostNum', false);
		$this->db->from('`zok_country`');
		$sCondition = '1' == $this->config->item('premoderation') ? ' AND `zok_post`.`status` = \'active\' ' : ' AND `zok_post`.`Status` != \'deleted\' ';
		$this->db->join('`zok_post`', '( `zok_country`.`ISO2` = `zok_post`.`Country` AND `zok_post`.`DateStart` <= \''.$sDate.'\' AND (`zok_post`.`DateEnd` >= \''.$sDate.'\' OR `zok_post`.`DateEnd` = \'0000-00-00\') )' . $sCondition, 'left' );
		if ( isset($aData['data']['CurrentCategory']['BreadCramb']) )
		{
			$this->db->join('`zok_category`', '( `zok_post`.`CategoryId` = `zok_category`.`Id`
				AND `zok_category`.`BreadCramb` LIKE \'' . str_replace('\\', '\\\\\\\\', $aData['data']['CurrentCategory']['BreadCramb'] ) . '%\' )', 'left' );
// show countries with posts > than 0
			$this->db->where('`zok_category`.`Id` IS NOT NULL');
		}
		else
		{
// show countries with posts > than 0
			$this->db->where('`zok_post`.`Id` IS NOT NULL');
		}
*/
// localization
//		if ( !empty($this->aSystemVar['localization']) )
//		$this->db->where('`zok_country`.`ISO2` = \'' . $this->aSystemVar['localization'] . '\'');
/*
		$this->db->groupby('`zok_country`.`Country`');
		$rRes = $this->db->get();
		$aData['data']['CountryList'] = $rRes->result_array();
*/
// ================================================================
// category list
		//$aData['data']['CategoryList'] = $this->Catalog_model->GetSubCategoryList($iCurrentCategory);
		$aData['data']['CategoryList'] = $this->Catalog_model->getCategoriesList($iCurrentCategory,$this->aSystemVar['cur_lang']);
		$aData['data']['top_categories'] = $this->Catalog_model->getCategoriesList(0,$this->aSystemVar['cur_lang']);

// ================================================================
// post list

// pagination
		$iPerPage = $this->config->item('pagination_item_per_page');
		$iStart = ($iPage-1)*$iPerPage;
// -----------

		$aPostList = $this->Catalog_model->GetPostList( 'normal', $iPerPage, $iStart, $aData['data']['CurrentCategory']['Id'], $this->config->item('browse_mod'), true);

// pagination: get num rows
		$this->db->select("FOUND_ROWS() as PostNum");
		$rRes2 = $this->db->get();
		$iPostNum = $rRes2->row_array();
		$iPostNum = $iPostNum['PostNum'];
		//build pagination string
		$this->load->library('pagination');
		$oPageNate = new Pagination();
		$oPageNate->SetParams($iPerPage, $iPostNum, $iPage, site_url( $this->config->item('uri_category') . $aData['data']['CurrentCategory']['BaseName']), $this->lang, site_url($this->config->item('uri_category') . $aData['data']['CurrentCategory']['BaseName']) );
		$iStart = $oPageNate->GetStart();
		$aData['data']['Pagination'] = $oPageNate->GeneratePageNateLine();
// end of pagination

		$aData['data']['PostList'] = $this->_wrapPostArray( $aPostList );





/*
// count number of posts:
		$iPostNum = $this->Catalog_model->GetPostList( 'normal', '', '', $aData['data']['CurrentCategory']['Id'], $this->config->item('browse_mod'), true);
		$iPostNum = $iPostNum['PostNum'];

// make paginatation string
		$iPerPage = $this->config->item('pagination_item_per_page');
		$this->load->library('pagination');
		$oPageNate = new Pagination();
// url with category basename
		$oPageNate->SetParams($iPerPage, $iPostNum, $iPage, site_url( $aData['data']['CurrentCategory']['BaseName']), $this->lang, site_url($aData['data']['CurrentCategory']['BaseName']) );
// url with category id
//		$oPageNate->SetParams($iPerPage, $iPostNum, $iPage, site_url('catalog/index/' . $iCurrentCategory), $this->lang, site_url($aData['data']['CurrentCategory']['Id']) );
		$iStart = $oPageNate->GetStart();
		$aData['data']['Pagination'] = $oPageNate->GeneratePageNateLine();

// get posts itself
		$aPostList = $this->Catalog_model->GetPostList( 'normal', $iPerPage, $iStart, $aData['data']['CurrentCategory']['Id'], $this->config->item('browse_mod'));
		$aData['data']['PostList'] = $this->_wrapPostArray( $aPostList );
*/
// ================================================================
// user list

		$aData['data']['UserList'] = $this->Catalog_model->GetUserList('name');

// ================================================================

//		$aData['data']['User']['Localization'] = $this->aSystemVar['localization'];

		$this->load->view($this->aSystemVar['template_viewer_current'] . 'catalog', $aData);

	}


/*
*
*	Search function
*
*/
		function search_result()
		{

			$sLang = $this->aSystemVar['cur_lang'];

			$aData['data'] = array();

//			$this->aHeaderVar['page_location'] = strtolower( __class__ . '/' . __function__ );
			$this->aHeaderVar['page_title'] = $this->config->item('site_title') . ' :: ' . $this->lang->line('search_result');
			
			// post body and title handles with "htmlspecialchars" function, without ENT_QUOTES. So here we need to use it too
			if ( $sSearchText = addslashes(htmlspecialchars($this->input->post('search_text', true))) )
			{

				if ( $this->input->post('search_post') )
				{

					$this->db->select('`zok_post`.*,
										`zok_post_lang`.`Title`, `zok_post_lang`.`Body`, `zok_post_lang`.`Keywords`, SUBSTR(`zok_post_lang`.`Body`, 1, 500) as Snipet,
										`zok_post_pic`.`Pic`, `zok_post_pic`.`Ext`, `zok_post_pic`.`Description` AS picDesc,
										`zok_category_lang`.`Title` as CategoryTitle,
										`zok_category`.`Id` as CategoryId, `zok_category`.`BaseName` as CategoryBaseName,
										`zok_user`.`Name` as UserName,
										`zok_post_stat`.`View`, `zok_post_stat`.`LastView`, `zok_post_stat`.`Rate`, `zok_post_stat`.`LastRate`', false);

//					$this->db->select('`zok_post`.`Id`, `zok_post`.`Title`, `zok_post`.`Body`, `zok_post_pic`.`Description`,  SUBSTR(`zok_post`.`Body`, 1, 200) as Snipet');
					$this->db->from('`zok_post`');
					$this->db->join('`zok_post_lang`', '`zok_post`.`Id` = `zok_post_lang`.`PostId` AND `zok_post_lang`.`Lang`=\''.$sLang.'\'');
					$this->db->join('`zok_post_pic`', '`zok_post`.`Id` = `zok_post_pic`.`PostId`', 'left');
					$this->db->join('`zok_user`', '`zok_post`.`UserId` = `zok_user`.`Id`', 'left');
					$this->db->join('`zok_category`', '`zok_post`.`CategoryId` = `zok_category`.`Id`', 'left');
					$this->db->join('`zok_category_lang`', '`zok_post`.`CategoryId` = `zok_category_lang`.`CategoryId` AND `zok_category_lang`.`Lang`=\''.$sLang.'\'','left');
					$this->db->join('`zok_post_stat`', '`zok_post`.`Id` = `zok_post_stat`.`PostId`', 'left');

					$sCondition = '1' == $this->config->item('premoderation') ? ' AND `zok_post`.`Status` = \'active\'' : ' AND `zok_post`.`Status` != \'deleted\' ';
					$this->db->where('( `zok_post_lang`.`Title` LIKE \'%' . $sSearchText . '%\'
									OR `zok_post_lang`.`Body` LIKE \'%' . $sSearchText . '%\'
									OR `zok_post_pic`.`Description` LIKE \'%' . $sSearchText . '%\'
									OR `zok_post_lang`.`Keywords` LIKE \'%' . $sSearchText . '%\' )'
									. $sCondition );
// localization
/*
					if ( !empty($this->aSystemVar['localization']) )
					$this->db->where('`zok_post`.`Country` = \'' . $this->aSystemVar['localization'] . '\' OR `zok_post`.`Country` = \'all\'');
*/
					$this->db->groupby('`zok_post`.`Id`');
					$rRes = $this->db->get();

					$aData['data']['PostList'] = $this->_wrapPostArray( $rRes->result_array() );

				}

				if ( $this->input->post('search_comment') )
				{

					$this->db->select('`zok_comment`.`Body`, `zok_comment`.`PostId`');
					$this->db->from('`zok_comment`');
					$this->db->like('`zok_comment`.`Body`', $sSearchText );
					$rRes = $this->db->get();

					$aData['data']['CommentList'] = $rRes->result_array();

				}

				if ( $this->input->post('search_category') )
				{

					$this->db->select('`zok_category`.`Id`, `zok_category`.`BaseName`, `zok_category_lang`.`Title`, `zok_category_lang`.`Description`');
					$this->db->join('`zok_category_lang`',' `zok_category`.`Id`=`zok_category_lang`.`CategoryId` AND `zok_category_lang`.`Lang`=\''.$sLang.'\'','left');
					$this->db->from('`zok_category`');
					$sCondition = '1' == $this->config->item('premoderation') ? ' AND `zok_category`.`Status` = \'active\'' : ' AND `zok_category`.`Status` != \'deleted\' ';
					$this->db->where('( `zok_category_lang`.`Title` LIKE \'%' . $sSearchText . '%\'
									OR `zok_category_lang`.`Description` LIKE \'%' . $sSearchText . '%\' )'
									. $sCondition );
					$rRes = $this->db->get();

					$aData['data']['CategoryList'] = $rRes->result_array();

				}

				if ( $this->input->post('search_user') )
				{

					$this->db->select('`zok_user`.`Id`, `zok_user`.`Name`, `zok_user_data`.`RealName`, `zok_user_data`.`Description`');
					$this->db->from('`zok_user`');
					$this->db->join('`zok_user_data`', '`zok_user`.`Id` = `zok_user_data`.`UserId`', 'inner');
					$sCondition = '1' == $this->config->item('premoderation') ? ' AND `zok_user`.`Status` = \'active\'' : ' AND `zok_user`.`Status` != \'deleted\' AND `zok_user`.`Status` != \'unconfirmed\' ';
					$this->db->where('( `zok_user`.`Name` LIKE \'%' . $sSearchText . '%\'
									OR `zok_user_data`.`RealName` LIKE \'%' . $sSearchText . '%\'
									OR `zok_user_data`.`Description` LIKE \'%' . $sSearchText . '%\' )'
									. $sCondition );
					$rRes = $this->db->get();

					$aData['data']['UserList'] = $rRes->result_array();
				}

			}

			$aData['data']['SearchText'] = $sSearchText;

			$this->load->view( $this->aSystemVar['template_viewer_current'] . 'search_result', $aData);

		}


/*
*
*	Set or reset localization
*
*	@param - localization country
*	@param - current category for proper redirect back
*
*/
	function localization( $sCountry = '', $iCurrentCategory = 0 )
	{

		if ( preg_match('/^[a-zA-Z]{2,3}$/', $sCountry ) )
			$this->session->set_userdata( array( 'localization' => strtoupper($sCountry) ) );
		else
			$this->session->set_userdata( array( 'localization' => false ) );

		if ( 0 == $iCurrentCategory )
			redirect('');
		else
			redirect('catalog/index/' . $iCurrentCategory );

	}

/*
*
*	Output .png sequrity image
*
*	@return image data stream
*
*/
	function get_security_image()
	{

		$config['image_library'] = 'GD';
		$config['dynamic_output'] = true;
		$config['si_font_path'] = $this->config->item('font_ttf_path');

		$config['si_text'] = $this->Catalog_model->GetRandomText( $this->config->item('security_code_length') );

		$sHashText = md5($config['si_text']);
		$this->session->set_userdata( array( 'securityhash' => $sHashText ) );

		$this->load->library('image_lib', $config);

		return $this->image_lib->security_image();

	}


/*
*
*	Wrap array with post with additional data
*
*/

	function _wrapPostArray( $aPostArray = array() )
	{

		if ( !is_array($aPostArray) )
			return array();

		$aWrapPostArray = array();

		foreach( $aPostArray as $aPost )
		{
			$aPost['PicUrl'] = '';
			if ( !empty($aPost['Pic']) && $this->Catalog_model->ext_file_exists( $this->config->item('base_dir') . $this->config->item('post_pic_url') . $aPost['Id'] . '/' . $aPost['Pic'] . $aPost['Ext'] ) )
			{
				$aPost['PicUrl'] = base_url() . $this->config->item('post_pic_url') . $aPost['Id'] . '/' . $aPost['Pic'] . '_icon' . $aPost['Ext'];
			}

			$aPost['Body'] = nl2br($aPost['Body']);

// show in snipet not more than 4 strings:
			$iPos = -1;
			$iBreakLine = 0;
			do
			{
				$iPos = strpos( $aPost['Snipet'], "\n", ($iPos+1) );
				$iBreakLine++;
			}
			while ( $iPos && 4 > $iBreakLine );

			if ( $iPos && $iBreakLine >= 4 ) $aPost['Snipet'] = substr( $aPost['Snipet'], 0, $iPos );

			// remove opened, but not closed html tags.
			// WARNING - this option shuld work only for news, because in posts html symbols like '<' and '>' replaces to &gt; and &lt;
			// TODO: make check for double and single tags. Now, string '<a href="">zxc<a href="">asd</a>' considered as normal because every single tag is closed ))
			if ( 'news' == $aPost['SubType'] )
				$aPost['Snipet'] = preg_replace("/(<[^>]+?)(<|$)/s", '$2', $aPost['Snipet']);

// ------------------------------------------------------------
			$aPost['Snipet'] = nl2br($aPost['Snipet']);

			// if no title - use basename instead
			if (empty($aPost['CategoryTitle']) && @$aPost['CategoryBaseName'])
				$aPost['CategoryTitle'] = $aPost['CategoryBaseName'];

			$this->db->select('COUNT(`zok_comment`.`Id`) as CommentNum');
			$this->db->from('`zok_comment`');
			$this->db->where('`zok_comment`.`PostId` = \'' . $aPost['Id'] . '\'');
			$rRes = $this->db->get();
			$aCommentNum = $rRes->row_array();
			$aPost['CommentNum'] = $aCommentNum['CommentNum'];

			$aWrapPostArray[] = $aPost;
		}

		return $aWrapPostArray;
	}
}


/* End of file catalog.php */
/* Location: ./system/application/controllers/catalog.php */