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

class Catalog_Controller extends Controller
{

	var $aHeaderVar		= array();
	var $aFooterVar		= array();
	var $aContentVar	= array();
	var $aSystemVar		= array();

	var $bAdmin 		= false;
	var $bLogIn			= false;

	/**
	 *	constructor
	 */
	function Catalog_Controller()
	{
		parent::Controller();
        $this->load->helper('url');
		$this->load->helper('form');

		$this->load->model('Catalog_model');
		$this->load->library('session');

// rewrite Template if it is set in cookie
		if ( $this->session->userdata('template') )
			$this->config->set_item('ctemplate',$this->session->userdata('template'));
		
// load catalog config files:
		$this->config->load('config_catalog');
		$this->config->load( $this->config->item('config_custom_name'), false, true);

		$this->aSystemVar['current_location'] = base_url() . $this->_parse_request_uri();
		$this->aSystemVar['current_location_wl'] = rtrim(preg_replace("/\/?lang-[A-Za-z]+/",'',$this->aSystemVar['current_location']),'/');

		$this->aHeaderVar['catalog_charset'] = $this->config->item('catalog_charset');

// generate path to current viewer directory
//		$this->_get_theme();

		$this->_getCurrentUserArray();

		// set default lang
		$this->_prepLang();

		// get list of stat pages
		$this->_getStatPageList();

	}

   	/**
	 *	generate
	 *
	 *	@param
	 *	@return
	 *
	 */
	function _getCurrentUserArray()
	{

		$sUsername = $this->session->userdata('username');
		
		if( $this->session->userdata('loggedin') === true && !empty($sUsername) && preg_match('/^[\w\-\.]+$/',$sUsername) )
		{
			$this->aSystemVar['current_user'] = $this->Catalog_model->GetUserArrayByName($sUsername, true);
			
			$this->bLogIn = true;
			
			if( $this->aSystemVar['current_user']['GroupName'] == 'admin' )
			{
				$this->bAdmin = true;
			}
		}
		else
		{

			$this->aSystemVar['current_user'] = array(
				'Id'		=> '',
				'Name'		=> '',
				'GroupName'	=> 'guest',
				'Status'	=> '');
				
			$this->db->select('`Data`');
			$rRes = $this->db->getwhere('`zok_user_group`', array('`GroupName`' => 'guest'));
			
			$aItem = $rRes->row_array();

			$this->aSystemVar['current_user']['GroupData'] = unserialize($aItem['Data']);
					
		}
		
		return true;

	}


/*
*	set lang and gets lang list
*/
	function _prepLang()
	{

		// get langs
		$rRes = $this->db->get('`zok_lang`');
		$aLangList = $rRes->result_array();

		$this->aSystemVar['lang_list'] = $aLangList;
		$aSegList = $this->uri->segment_array();

		// set lang if there are more than 1 lang installed
		if ( 1 < count($this->aSystemVar['lang_list']) )
		{
			foreach ( $aSegList as $value )
			{
				// if lang specified in this segment
				if ( 1 == preg_match("/lang-([A-Za-z]+)\/?/",$value,$matches) )
				{
					// check if this lang exists:
					foreach ($aLangList as $aLang)
					{
						// ... and set it
						if ($matches[1] == $aLang['BaseName'])
						{
							$this->aSystemVar['cur_lang']=$aLang['BaseName'];
							if (0==$aLang['Def'])
								$this->aSystemVar['cur_lang_postfix'] = 'lang-'.$this->aSystemVar['cur_lang'];
							else
								$this->aSystemVar['cur_lang_postfix'] = '';
							$this->lang->load('catalog',$aLang['BaseName']);

							// change default language in config
							$this->config->set_item('language',$this->aSystemVar['cur_lang']);

							return true;
						}
					}
					break;
				}
			}
		}

		// get def lang from config file
		//$this->aSystemVar['cur_lang'] = $this->config->item('language');
		//$this->lang->load('catalog');


		// get def lang from lang table
		foreach ($aLangList as $aLang)
		{
			$aDefLang = $aLang;
			if ( 1==$aLang['Def'] )
				break;
		}

		$this->aSystemVar['cur_lang'] = $aDefLang['BaseName'];
		if (0==$aDefLang['Def'])
			$this->aSystemVar['cur_lang_postfix'] = 'lang-'.$this->aSystemVar['cur_lang'];
		else
			$this->aSystemVar['cur_lang_postfix'] = '';
		$this->lang->load('catalog',$aDefLang['BaseName']);

		// change default language in config
		$this->config->set_item('language',$this->aSystemVar['cur_lang']);

		return true;
	}


	function _getStatPageList()
	{
		$this->db->select('`zok_static_content`.*,`zok_static_lang`.`Lang`,`zok_static_lang`.`Title`,`zok_static_lang`.`Content`');
		$this->db->join('`zok_static_lang`','`zok_static_content`.`Id`=`zok_static_lang`.`PageId` AND `Lang`=\''.$this->aSystemVar['cur_lang'].'\'');
		$rRes = $this->db->get('`zok_static_content`');

		$this->aContentVar['stat_page_list'] = $rRes->result_array();
	}

/*
*
*	template switch
*
*	@param - template
*	@param - Path to return ( with undescores instead of slashes )
*
*/
	function set_template( $sTemplate, $sReturnPath = '' )
	{

		if ( preg_match('/^\w+$/', $sTemplate ) )
			$this->session->set_userdata(array( 'template' => $sTemplate ));

		// redirect back
		if ( !empty($sReturnPath) )
		{
			$sReturnPath = str_replace( ':', '/', $sReturnPath );
			redirect( $sReturnPath );
		}
		else
		{
			redirect('');
		}

	}


    /**
	 * Parse the REQUEST_URI
	 *
	 * Due to the way REQUEST_URI works it usually contains path info
	 * that makes it unusable as URI data.  We'll trim off the unnecessary
	 * data, hopefully arriving at a valid URI that we can use.
	 *
	 * @access	private
	 * @return	string
	 */
	function _parse_request_uri()
	{
		if ( ! isset($_SERVER['REQUEST_URI']) OR $_SERVER['REQUEST_URI'] == '')
		{
			return '';
		}

		$request_uri = preg_replace("|/(.*)|", "\\1", str_replace("\\", "/", $_SERVER['REQUEST_URI']));

		if ($request_uri == '' OR $request_uri == SELF)
		{
			return '';
		}

		$fc_path = FCPATH;
		if (strpos($request_uri, '?') !== FALSE)
		{
			$fc_path .= '?';
		}

		$parsed_uri = explode("/", $request_uri);

		$i = 0;
		foreach(explode("/", $fc_path) as $segment)
		{
			if (isset($parsed_uri[$i]) AND $segment == $parsed_uri[$i])
			{
				$i++;
			}
		}

		$parsed_uri = implode("/", array_slice($parsed_uri, $i));

		return $parsed_uri;
	}

    /**
	 *	@desc set path to current viewer directory
	 *	@access privat
	 *	@return void
	 *
	 */
	 /* under construction
	function _get_theme()
	{
		$this->sViewerDir = $this->config->item('viewer', 'design') . strtolower($this->sCurrentContr) . '/';
	}
	*/
	
	
	function _grIsAllowed($sAction,$sValue='')
	{

		$aGrValues = $this->aSystemVar['current_user']['GroupData'];

		if ( !array_key_exists($sAction, $aGrValues) ) 
			exit('group action "' . $sAction . '" not found');
			
		$sGrValue = $aGrValues[$sAction];

		// if 'no limit' sign specified - return true
		if ( '-' == $sGrValue )
			return true;
		
		// load group model
		$this->load->model('Catalog_grmodel');
		
		switch ( $sAction )
		{
			case 'categ_to_hide':
					return $this->Catalog_grmodel->isCategoryViewAllowed($sGrValue,$sValue);
					break;
			case 'categ_to_categ':
					return $this->Catalog_grmodel->isCategoryAddAllowed($sGrValue,$sValue);
					break;
			case 'categ_to_post':
					return $this->Catalog_grmodel->isPostAddAllowed($sGrValue,$sValue);
					break;
			default:			
					return false;
					break;
		}
		
	
		return false;
	
	}
	
	
	function _grGetValue($sAction)
	{

		$aGrValues = @$this->aSystemVar['current_user']['GroupData'];

		if ( !array_key_exists($sAction, $aGrValues) )
			exit('group action "' . $sAction . '" not found');
			
		$sGrValue = $aGrValues[$sAction];

		return $sGrValue;
	
	}
	

}

/* End of file Catalog_Controller.php */
/* Location: ./system/application/libraries/Catalog_Controller.php */