<?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 Post extends Catalog_Controller
{

	var $aHeaderVar = array();
	var $aFooterVar = array();
	var $PostCategoryId = 0;

/*
*
*	constructor
*
*/
	function Post()
	{
		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_post');

	}


/*
*
*	index
*
*/
	function index()
	{
		redirect('post/add');
	}



/*
*
*	add post
*
*	@param - id of category to add post
*
*/
	function add( $iCategoryId = 0, $aPreFill=array() )
	{

		$iCategoryId = (int)$iCategoryId;
		
		$aData = array();

		if ( empty($this->aSystemVar['current_user']['Id']) )
			redirect('user/login/post:add:' . $iCategoryId );
		
		// check if adding post allowed
		$sGrValue = $this->_grGetValue('post_total_num');

		if ( '-' != $sGrValue )
		{
			$iPostNum = $this->Catalog_model->GetUserPostNumById($this->aSystemVar['current_user']['Id']);
			if ( $iPostNum >= $sGrValue )
			{
				$this->load->view($this->aSystemVar['template_viewer_root'] . 'design_items/gr_noaccess', array());
				return false;
			}
		}

// get category list
		$aData['data']['Category']['CategoryList'] = $this->Catalog_model->GetCategoryTreeForPost($this->aSystemVar['cur_lang']);

// if category list empty - it means that adding post is restricted
		if ( 0 == count($aData['data']['Category']['CategoryList']) )
		{
			$this->load->view($this->aSystemVar['template_viewer_root'] . 'design_items/gr_noaccess', array());
			return false;
		}
		
		$this->load->library('validation');

		$this->aHeaderVar['page_title'] = ucwords(strtolower($this->lang->line('_add_post')));

		$aData['data']['Category']['Id'] = $iCategoryId;

		$aData['data']['Category']['BreadCrambList'] = array();
		$aPCat = $this->Catalog_model->getLocCategory($iCategoryId,$this->aSystemVar['cur_lang']);

		if (0 < count($aPCat))
		{
			$aData['data']['ParentCategory']['Id'] = $aPCat['Id'];
			$aData['data']['ParentCategory']['Title'] = $aPCat['Title'];
			$aData['data']['Category']['BreadCrambList'] = $this->Catalog_model->GetNamedBreadCramb($aPCat['BreadCramb'],$this->aSystemVar['cur_lang']);
		}
		else
			$aData['data']['ParentCategory']['Id'] = 0;


		$aData['data']['Post'] = array (
			'Id'		=> '',
			'Title' 	=> '',
			'Body'		=> '',
			'Keywords'	=> '',
			'SubType'	=> '',
			'PicArrange'=> '',
			'ImageList' => array(),
			'IconUrl'	=> '',
			'Country' 	=> '',
			'SDay'		=> '0',
			'SMonth'	=> '0',
			'SYear'		=> '0',
			'EDay'		=> '0',
			'EMonth'	=> '0',
			'EYear'		=> '0',
			'SecurityCode' => $this->bAdmin ? '' : $this->config->item('security_code')
		);

		// fill data array with default values
		foreach ( $aData['data']['Post'] as $key => $value )
			if ( !empty($aPreFill[$key]) )
				$aData['data']['Post'][$key] = $aPreFill[$key];

		$rRes = $this->db->query('DESCRIBE `zok_post` `PicArrange`');
		$aField = $rRes->row_array();
		preg_match_all( '/\'(.+?)\'/', $aField['Type'], $aOption );
		$aPicArrange = $aOption[1];

		$aData['data']['Post']['PicArrangeOption'] = $aPicArrange;

// get SubType list
		if ( $this->bAdmin )
		{
			$rRes = $this->db->query('DESCRIBE `zok_post` `SubType`');
			$aField = $rRes->row_array();
			preg_match_all( '/\'(.+?)\'/', $aField['Type'], $aOption );
			$aData['data']['SubType']['SubTypeList'] = $aOption[1];
		}


		$aCustomFields = $this->Catalog_model->GetCustomFields($iCategoryId);

		// fill custom fields values
		$aData['data']['CustomFields'] = array();

		foreach ( $aCustomFields as $aField )
		{
			if ( !empty($aPreFill['CustomField'][$aField['BaseName']]) )
			{
				if ('check'==$aField['FieldType'] && is_array($aPreFill['CustomField'][$aField['BaseName']]))
				{
					$sCheckVal = '';
					foreach ( $aPreFill['CustomField'][$aField['BaseName']] as $aItem )
					{
						$sCheckVal .= $aItem . "\n";
					}
					$aField['Value'] = $sCheckVal;
				}
				else
					$aField['Value'] = $aPreFill['CustomField'][$aField['BaseName']];
			}

			$aData['data']['CustomFields'][] = $aField;
		}

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

/*
*
*	save post
*
*/
	function save()
	{

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

			$this->db->select('`zok_post`.*');
			$this->db->where('`zok_post`.`Id` = \'' . $this->input->post('PostId') . '\'');
			$rRes = $this->db->get('`zok_post`');
			if ( 0 >= $rRes->num_rows() )
				redirect('');

			$aOriginalPost = $rRes->row_array();

// check for admin or owner rights if someone edit existing post
			if ( $aOriginalPost['UserId'] != $this->aSystemVar['current_user']['Id'] && !$this->bAdmin )
				redirect('');

// get pic list for post
			$this->db->select('`zok_post_pic`.*');
			$this->db->where('`zok_post_pic`.`PostId` = \'' . $this->input->post('PostId') . '\'');
			$rRes = $this->db->get('`zok_post_pic`');
			$aOriginalPostPic = array();
			foreach ( $rRes->result_array() as $aPic )
				$aOriginalPostPic[$aPic['Id']] = $aPic;

			$bEditMode = true;

		}
		else
		{

			if ( empty($this->aSystemVar['current_user']['Id']) )
				redirect('user/login');

			// check if adding post allowed
			$sGrValue = $this->_grGetValue('post_total_num');

			if ( false === $sGrValue )
				redirect();
				
			if ( '-' != $sGrValue )
			{
				$iPostNum = $this->Catalog_model->GetUserPostNumById($this->aSystemVar['current_user']['Id']);
				if ( $iPostNum >= $sGrValue )
				{
					$this->load->view($this->aSystemVar['template_viewer_root'] . 'design_items/gr_noaccess', array());
					return false;
				}
			}				
				
// rule for security code verification
			if ( $this->config->item('security_code') and !$this->bAdmin )
				$rules['SecurityCode']	= "required|strtoupper|callback__security_code_check";

			$bEditMode = false;

		}

		$this->load->library('validation');

		$rules['CategoryId']	= "trim|required|numeric";
		$rules['NewCategoryId']	= "trim|numeric|callback__gr_categ_check";		
		$rules['PostId']		= "trim|numeric";
		$rules['Title']			= "trim|required|xss_clean";
		$rules['Body']			= "trim|required|xss_clean";
		$rules['Keywords']		= "trim|xss_clean";
		$rules['PicArrange']	= "alfa";
//		$rules['CountryList']	= "required";

		// set category id for function "_customFieldsCheck"
		// NOTE: if category changed - cfields validation will be perfomed for NEW category
		if ( $this->input->post('NewCategoryId') )
			$this->PostCategoryId = (int)$this->input->post('NewCategoryId');
		else
			$this->PostCategoryId = (int)$this->input->post('CategoryId');
			
		// check custom fields
		$rules['CustomField']	= "callback__customFieldsCheck";

		$this->validation->set_rules($rules);
		$this->validation->set_error_delimiters('<div class="error">', '</div>');
		if ($this->validation->run() == FALSE)
		{
			if ( $bEditMode )
			{
				// send $this->PostCategoryId to be able to display different custom fields if they are exists
				$this->edit($aOriginalPost['Id'], $this->PostCategoryId);
				return true;
			}
			else
			{
				$this->add($this->input->post('CategoryId'), $_POST);
				return true;
			}
		}

// ===============================================		
// validation routine successfully passed,
// handle the post
// ===============================================		

		if ( $bEditMode )
			$iOwnerId = $aOriginalPost['UserId'];
		else
			$iOwnerId  = $this->aSystemVar['current_user']['Id'];


		$aPostData = array (
			'CategoryId'	=>	$this->PostCategoryId,
			'UserId'		=>	$iOwnerId,
//				'Title'			=>	htmlspecialchars(wordwrap( $this->input->post('Title'), 35, ' ', true), ENT_QUOTES, $this->config->item('catalog_charset')),
//				'Body'			=>	htmlspecialchars(wordwrap( $this->input->post('Body'), 35, ' ', true), ENT_QUOTES, $this->config->item('catalog_charset')),
//				'Keywords'		=>	htmlentities(wordwrap( $this->input->post('Keywords'), 35, ' ', true), ENT_QUOTES, $this->config->item('catalog_charset')),
			'PicArrange'	=>	$this->input->post('PicArrange'),
			'DateEdit'		=>	date("Y-m-d H:i:s"),
			'Country'		=>	( $this->input->post('CountryList') ? $this->input->post('CountryList') : 'all' ),
			'BaseName'		=>	$this->Catalog_model->GetUniqBaseName($this->input->post('Title'), 'zok_post', $this->input->post('PostId'))
		);

		if ( $this->bAdmin && ($sM = (int)$this->input->post('date_start_month'))
			&& ($sD = (int)$this->input->post('date_start_day'))
			&& ($sY = (int)$this->input->post('date_start_year')) )
				$aPostData['DateStart'] = $sY . '-' . $sM . '-' . $sD;
			else
				$aPostData['DateStart'] = date("Y-m-d");


		if ( $this->bAdmin && ($sM = (int)$this->input->post('date_end_month'))
			&& ($sD = (int)$this->input->post('date_end_day'))
			&& ($sY = (int)$this->input->post('date_end_year')) )
				$aPostData['DateEnd'] = $sY . '-' . $sM . '-' . $sD;
			else
			{
				$sGrValue = $this->_grGetValue('post_lifetime');
				if ( '-' != $sGrValue )
					$aPostData['DateEnd'] = date("Y-m-d",mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+$sGrValue, date("Y")));
			}

// set SubType if it has been submited by admin
		if ( $this->input->post('SubType') && $this->bAdmin )
		{
			$aPostData['SubType'] = $this->input->post('SubType');
			if ( 'news' == $aPostData['SubType'] )
			{
				$aPostData['CategoryId'] = 0;
			}
		}

// set post status = 'active' if it is posted by admin
		if ( $this->bAdmin )
			$aPostData['Status'] = 'active';
		elseif ( !$bEditMode )
			$aData['Status'] = $this->_grGetValue('new_post_status');

		// get post category
		$aPostCategory = $this->Catalog_model->getLocCategory($aPostData['CategoryId'],$this->aSystemVar['cur_lang']);				
		
		if ( !$bEditMode )
		{
			$aPostData['DateSubmit'] = date("Y-m-d H:i:s");
			$this->db->insert( 'zok_post', $aPostData );
			$iPostId = $this->db->insert_id();

			$sNow = date("Y-m-d H:i:s");
			$aStat = array(
				'PostId'	=>	$iPostId,
				'View'		=>	'1',
				'LastView'	=>	$sNow,
				'Rate'		=>	'1',
				'LastRate'	=>	$sNow

			);
			$this->db->insert( 'zok_post_stat', $aStat );
		}
		else
		{
			$iPostId = $aOriginalPost['Id'];
			
			// if post category has been changed - delete redundant data from custom fields
			if ( $this->input->post('NewCategoryId') && $this->input->post('NewCategoryId') != $this->input->post('CategoryId') )
			{
				$sId = str_replace('/',',',$aPostCategory['BreadCramb']);
				$sId = substr($sId,0,-1);
				
				$this->db->query("DELETE FROM `zok_post_clang` USING zok_post_clang, zok_post_cfield 
					WHERE `zok_post_clang`.`FieldId` = `zok_post_cfield`.`Id`
					AND `zok_post_cfield`.`CategoryId` NOT IN ({$sId})
					AND `zok_post_clang`.`PostId` = '{$iPostId}'");

			}

			$this->db->where('`Id` = \'' . $iPostId . '\'');
			$this->db->update( 'zok_post', $aPostData );
		}

// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// update post lang table

		$iPostLang = $this->input->post('PostLang')?$this->input->post('PostLang'):$this->aSystemVar['cur_lang'];

		$this->db->select('`Id`');
		$this->db->where('`PostId`=\''.$iPostId.'\' AND `Lang`=\''.$iPostLang.'\'');
		$rRes = $this->db->get('`zok_post_lang`');
		
		// admin can post with no limits
		if ( $this->bAdmin )
			$sPostBody = $this->input->post('Body', true);
		else
		{
			$sGrValue = $this->_grGetValue('post_text_len');
			if ( '-' != $sGrValue )
				$sPostBody = substr($this->input->post('Body', true),0,$sGrValue);
			else
				$sPostBody = $this->input->post('Body', true);
			
			$sPostBody = htmlspecialchars(wordwrap($sPostBody, 35, ' ', true));
		}
			
		
		$aData = array(
				'Title'		=>	htmlspecialchars(wordwrap( ucfirst($this->input->post('Title', true)), 35, ' ', true)),
				'Body'		=>	$sPostBody,
				'Keywords'	=>	htmlspecialchars(wordwrap( $this->input->post('Keywords', true), 35, ' ', true))
			);


		if ( 0 == $rRes->num_rows() )
		{
		// insert
			$aData['PostId']=$iPostId;
			$aData['Lang']=$iPostLang;

			$this->db->insert('`zok_post_lang`',$aData);
		}
		else
		{
		// update
			$aId = $rRes->row_array();
			$this->db->where('`zok_post_lang`.`Id`=\''.$aId['Id'].'\'');
			$this->db->update('`zok_post_lang`', $aData);
		}

// --------------------------------------------------------------------------
// Handle and save custom fields ----------------------------------------

	$aCustomFields = $this->Catalog_model->GetCustomFields($aPostData['CategoryId']);
	$aPostCustomFields = $this->input->post('CustomField');
	$aSaveCustomFields = array();

	// prepare save array
	$sId = 0;
	foreach ($aCustomFields as $aField)
	{
		$aSaveCustomFields[$aField['BaseName']]['Id'] = $aField['Id'];

		$sId .= ',' . $aField['Id'];

		if ( !empty($aPostCustomFields[$aField['BaseName']]) )
		{
			if ('check' == $aField['FieldType'])
			{
				$aSaveCustomFields[$aField['BaseName']]['Value'] = '';
				foreach ($aPostCustomFields[$aField['BaseName']] as $value )
				{
					$aSaveCustomFields[$aField['BaseName']]['Value'] .= $value . "\n";
				}
			}
			else
			{
				$aSaveCustomFields[$aField['BaseName']]['Value'] = $aPostCustomFields[$aField['BaseName']];
			}
		}
		else
			$aSaveCustomFields[$aField['BaseName']]['Value'] = '';

	}

	// get records that already exists
	$aOrigCustomFields = array();
	$this->db->where('`PostId`='.$iPostId.' AND `Lang`=\''.$iPostLang.'\'');
	$this->db->where('`FieldId` IN ('.$sId.')');
	$rRes = $this->db->get('`zok_post_clang`');
	foreach ( $rRes->result_array() as $cfield )
		$aOrigCustomFields[$cfield['FieldId']] = true;

	// save data
	foreach ( $aSaveCustomFields as $aItem )
	{
		if ( !empty($aOrigCustomFields[$aItem['Id']]) )
		{
			// record already exists, update it
			$this->db->where('`PostId`='.$iPostId.' AND `Lang`=\''.$iPostLang.'\'');
			$this->db->where('`FieldId`='.$aItem['Id']);
			$this->db->update('`zok_post_clang`',array('Value'=>$aItem['Value']));
		}
		else
		{
			// insert new record
			$this->db->insert('`zok_post_clang`',array('PostId'=>$iPostId,'Lang'=>$iPostLang,'FieldId'=>$aItem['Id'],'Value'=>$aItem['Value']));
		}
	}

// -----------------------------------------------------------------------
// -----------------------------------------------------------------------

		$aPostData['Id'] = $iPostId;

		$sPostPicPath = $this->config->item('post_pic_path') . $iPostId . '/';

// --------------------------------------------------------
// create post folder if it is not exists yet
		$this->Catalog_model->createFolder($iPostId,$this->config->item('post_pic_path'));
// --------------------------------------------------------

// delete pictures if necessary:
		if ( $bEditMode && is_array($this->input->post('DeletePicId')) )
		{
			$sId = '';
			foreach( $this->input->post('DeletePicId') as $iId )
			{
				if ( is_array($aOriginalPostPic[$iId]) )
				{
					@unlink( $sPostPicPath . $aOriginalPostPic[$iId]['Pic'] . $aOriginalPostPic[$iId]['Ext'] );
					@unlink( $sPostPicPath . $aOriginalPostPic[$iId]['Pic'] . '_thumb' . $aOriginalPostPic[$iId]['Ext'] );
					@unlink( $sPostPicPath . $aOriginalPostPic[$iId]['Pic'] . '_icon' . $aOriginalPostPic[$iId]['Ext'] );

					unset($aOriginalPostPic[$iId]);

					$sId .= $iId . ',';
// reset primary pic in zok_post table
					if ( $iId == $aOriginalPost['PrimaryPicId'] )
					{
						$this->db->where('`zok_post`.`Id` = \'' . $aOriginalPost['Id'] . '\'' );
						$this->db->update('`zok_post`', array( 'PrimaryPicId' => '' ) );
						$aOriginalPost['PrimaryPicId'] = '';
					}
				}
			}

			$sId .= 0;

			$this->db->where( '`Id` IN (' . $sId . ')');
			$this->db->delete('`zok_post_pic`');
		}
// --------------------------------------------------------
// update pic descriptions if they are differ from original
		if ( is_array($this->input->post('PicDescription')) )
		{
			$aUpdateDescription = $this->input->post('PicDescription');
			foreach ( $aUpdateDescription as $iId => $sValue )
			{
				// convert only double quotes (")
				$sValue = htmlentities($sValue,ENT_COMPAT,$this->config->item('catalog_charset'));
				if ( !empty($aOriginalPostPic[$iId]) && $sValue != $aOriginalPostPic[$iId]['Description'] )
				{
					$this->db->where('`zok_post_pic`.`Id` = \'' . (int)$iId . '\' AND `zok_post_pic`.`PostId` = \'' . $iPostId . '\'');
					$this->db->update('`zok_post_pic`', array( '`zok_post_pic`.`Description`' => $sValue ));
				}
			}
		}
// --------------------------------------------------------
// update pic order if it differ from original
		if ( is_array($this->input->post('PicOrder')) )
		{
			$aUpdateOrder = $this->input->post('PicOrder');
			foreach ( $aUpdateOrder as $iNum => $iId )
			{
				if ( !empty($aOriginalPostPic[$iId]) && $iNum != $aOriginalPostPic[$iId]['Seq'] )
				{
					$this->db->where('`zok_post_pic`.`Id` = \'' . (int)$iId . '\' AND `zok_post_pic`.`PostId` = \'' . $iPostId . '\'');
					$this->db->update('`zok_post_pic`', array( '`zok_post_pic`.`Seq`' => $iNum ));
				}
			}
		}
// --------------------------------------------------------
// update primary picture
		$iPrimaryPicId = $this->input->post('PrimaryPicId');
		if ( !empty($iPrimaryPicId) && !empty($aOriginalPostPic[$iPrimaryPicId]) && $aOriginalPost['PrimaryPicId'] != $iPrimaryPicId )
		{
			$this->db->where( '`zok_post`.`Id` = \'' . $iPostId . '\'' );
			$this->db->update( '`zok_post`', array ( '`PrimaryPicId`' => $iPrimaryPicId ) );
			$aOriginalPost['PrimaryPicId'] = $iPrimaryPicId;
		}
// --------------------------------------------------------

		$this->load->library('upload');
		$this->load->library('image_lib');

		$aDescription = $this->input->post('Desc');
		$aCopyright = $this->input->post('Copyright');

		if ( $bEditMode )
			$iPicNum = count($aOriginalPostPic);
		else
			$iPicNum = 0;

		$iNum = ( isset($_FILES['Picture']['name']) ) ? count($_FILES['Picture']['name']) : 0;

		$iPostPicMax = '-' == $this->_grGetValue('post_pic_num') ? 999 : $this->_grGetValue('post_pic_num');
		
		for ( $i = 0; $i < $iNum; $i++ )
		{

			if ( '' != $_FILES['Picture']['name'][$i] )
			{

				$iPicNum++;
				// number of pics more than allowed:
				if ( $iPicNum > $iPostPicMax )
					break;

				$config['upload_path'] = $sPostPicPath;
				$config['encrypt_name'] = TRUE;
				$config['allowed_types'] = $this->config->item('catalog_image_type');

				$iVal = $this->_grGetValue('pic_max_upload_size');
				if ( '-' != $iVal )
					$config['max_size']	= $iVal;

				$iVal = $this->_grGetValue('pic_max_upload_width');
				if ( '-' != $iVal )
					$config['max_width'] = $iVal;

				$iVal = $this->_grGetValue('pic_max_upload_height');
				if ( '-' != $iVal )
					$config['max_height'] = $iVal;
					
				$this->upload->initialize($config);

				if ( ! $this->upload->do_upload_by_index( 'Picture', $i ) )
				{
// simply skip this image :-)

//						$error = array('error' => $this->upload->display_errors());
//						print_r($error);
//						exit;
				}
				else
				{

					$aFileData = $this->upload->data();

// insert record about picture
					$aPicData = array (
						'PostId'		=> $iPostId,
						'Pic' 			=> $aFileData['raw_name'],
						'Ext' 			=> $aFileData['file_ext'],
						'Description'	=> htmlentities($aDescription[$i],ENT_COMPAT,$this->config->item('catalog_charset')),
						'Seq'			=> ($iPicNum+$i)
					);

					$this->db->insert( 'zok_post_pic', $aPicData );

// make record about post primary picrure Id if it not exist yet
					if ( empty($aOriginalPost['PrimaryPicId']) )
					{
						$iPicId = $this->db->insert_id();

						$this->db->where( '`zok_post`.`Id` = \'' . $iPostId . '\'' );
						$this->db->update( '`zok_post`', array ( '`PrimaryPicId`' => $iPicId ) );
						$aOriginalPost['PrimaryPicId'] = $iPicId;
					}

// create image thumb
					$config['image_library'] = $this->config->item('catalog_image_library');
					$config['source_image'] = $aFileData['full_path'];
					$config['new_image'] = $aFileData['raw_name'] . '_thumb' . $aFileData['file_ext'];
					$config['maintain_ratio'] = TRUE;
					$config['width'] = $this->config->item('post_thumb_width');
					$config['height'] = $this->config->item('post_thumb_height');

					$this->image_lib->initialize($config);
					$this->image_lib->resize();
					$this->image_lib->clear();


// create image icon
					$config['image_library'] = $this->config->item('catalog_image_library');
					$config['source_image'] = $aFileData['full_path'];
					$config['new_image'] = $aFileData['raw_name'] . '_icon' . $aFileData['file_ext'];
					$config['maintain_ratio'] = TRUE;
					$config['width'] = $this->config->item('post_icon_width');
					$config['height'] = $this->config->item('post_icon_height');

					$this->image_lib->initialize($config);
					$this->image_lib->resize();
					$this->image_lib->clear();

// create copyright if it is specified
					if ( !empty($aCopyright[$i]) )
					{

						$config['source_image'] = $aFileData['full_path'];
						$config['new_image'] = $aFileData['full_path'];
						$config['wm_text'] = $aCopyright[$i];
						$config['wm_type'] = 'text';
						$config['wm_font_path'] = $this->config->item('font_ttf_path');
						$config['wm_font_size'] = '10';
						$config['wm_font_color'] = 'dddddd';
						$config['wm_shadow_color'] = '222222';
						$config['wm_shadow_distance'] = 1;
						$config['wm_vrt_alignment'] = 'bottom';
						$config['wm_hor_alignment'] = 'center';
						$config['wm_padding'] = '0';

						$this->image_lib->initialize($config);
						$this->image_lib->watermark();
						$this->image_lib->clear();

						$config['source_image'] = $aFileData['file_path'] . $aFileData['raw_name'] . '_thumb' . $aFileData['file_ext'];
						$config['new_image'] = $aFileData['raw_name'] . '_thumb' . $aFileData['file_ext'];

						$this->image_lib->initialize($config);
						$this->image_lib->watermark();
						$this->image_lib->clear();
					}
				}
			}
		}

		$aData = array();

		// if this is root category
		if ( empty($aPostCategory['BaseName']) )
		{
			$aPostCategory['BaseName'] = '0';
			$aPostCategory['Title'] = 'home';
		}

		$aData['Msg']['Time'] = 15;

		$aData['Msg']['links']['view_post'] = array(
			'url' => site_url($this->config->item('uri_post').$iPostId),
			'title' => $this->lang->line('view_post')
		);
		$aData['Msg']['links']['back_cat'] = array(
			'url' => site_url($this->config->item('uri_category').@$aPostCategory['BaseName']),
			'title' => $this->lang->line('back_to').' <strong>' . @$aPostCategory['Title'] . '</strong>'
		);
		$aData['Msg']['links']['add_post'] = array(
			'url' => site_url('post/add/' . $aPostData['CategoryId']),
			'title' => $this->lang->line('add_post')
		);
		$aData['Msg']['links']['home'] = array(
			'url' => site_url(),
			'title' => $this->lang->line('home')
		);

		$aData['Msg']['Text'] = $this->lang->line('_post_saved');
		if ( '1' != $this->config->item('premoderation') )
			$aData['Msg']['Text'] .= $this->lang->line('_post_premod');

		if ( 0 == $this->input->post('CategoryId') )
			$aData['Msg']['Location'] = site_url();
		else
		{
			if ( !empty($aPostCategory['BaseName']) )
					$aData['Msg']['Location'] = site_url($this->config->item('uri_category').$aPostCategory['BaseName']);
				else
					$aData['Msg']['Location'] = site_url('catalog/index/' . $this->input->post('CategoryId'));
			}

// show message page
		$this->load->view($this->aSystemVar['template_viewer_root'].'design_items/msg_box', $aData);

		return true;
	}

/*
*
*	delete post
*
*	@param - post id
*
*/
	function remove( $iPostId = '' )
	{

		//$this->output->enable_profiler(TRUE);
		$sAction = 'deleted';

		$iPostId = (int)$iPostId;
		if ( empty($iPostId) )
			redirect('');

		$this->db->select('`zok_post`.`UserId`, `zok_post`.`CategoryId`');
		$this->db->where('`zok_post`.`Id` = \'' . $iPostId . '\'');
		$rRes = $this->db->get('`zok_post`');
		$aPost = $rRes->row_array();

		if ( $aPost['UserId'] != (int)$this->aSystemVar['current_user']['Id'] && !$this->bAdmin )
			redirect('');

		$this->db->where('`zok_post`.`Id` = \'' . $iPostId . '\'');
		$this->db->update('`zok_post`', array( 'Status' => $sAction ) );


		if ( 0 == $aPost['CategoryId'] )
			redirect( '' );
		else
			redirect( 'catalog/index/' . $aPost['CategoryId'] );


	}

/*
*
*	view post
*
*	@param - post id
*
*/
	function review($iPostId = '')
	{
		//phpinfo();
		//$this->output->enable_profiler(TRUE);

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

		$sDate = date("Y-m-d");

		$this->db->select('`zok_post`.*, `zok_post_lang`.`Title`, `zok_post_lang`.`Body`, `zok_post_lang`.`Keywords`, `zok_country`.`ISO2`, `zok_country`.`Country` AS zokCountry, `zok_category`.`BreadCramb`, `zok_category_lang`.`Title` as CategoryTitle, `zok_category`.`Id` as CategoryId, `zok_post_stat`.`View`, `zok_post_stat`.`Rate`');
		// Note: this is simple join, so, if there are no post translation exist - post will not be selected !!
		$this->db->join('`zok_post_lang`', '`zok_post`.`Id` = `zok_post_lang`.`PostId` AND `zok_post_lang`.`Lang`=\''.$sLang.'\'');
		$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');
		$this->db->join('`zok_country`', '`zok_post`.`Country` = `zok_country`.`ISO2`', 'left');
		if ( !is_numeric($iPostId) && preg_match('/^[\w\-\.]+$/', $iPostId) )
			$this->db->where('`zok_post`.`BaseName`', $iPostId);
		else
 			$this->db->where('`zok_post`.`Id`', (int)$iPostId);
		$this->db->where('`zok_post`.`DateStart` <= \''.$sDate.'\' AND (`zok_post`.`DateEnd` >= \''.$sDate.'\' OR `zok_post`.`DateEnd` = \'0000-00-00\' )');
		$rRes = $this->db->get('`zok_post`');
		
		$aData = array();
		$aData['data']['Post'] = $rRes->row_array();

		// group permission check
		// if post category is restricted - the post restricted too !!
		if ( !empty($aData['data']['Post']['CategoryId']) && !$this->_grIsAllowed('categ_to_hide',$aData['data']['Post']['CategoryId']) )
		{
			$aData = array();
			$this->load->view($this->aSystemVar['template_viewer_root'] . 'design_items/gr_noaccess', $aData);
			return false;
		}		

		if ( empty($aData['data']['Post']) )
		{
			// here can be 2 variants - or there are no post or there are no translation.
			// if the problem is absense of translation - redirect to post category
			$this->db->select('`zok_category`.`BaseName`');
			$this->db->join('`zok_category`','`zok_category`.`Id`=`zok_post`.`CategoryId`');
			if ( !is_numeric($iPostId) && preg_match('/^[\w\-\.]+$/', $iPostId) )
				$this->db->where('`zok_post`.`BaseName`', $iPostId);
			else
	 			$this->db->where('`zok_post`.`Id`', (int)$iPostId);
			$this->db->where('`zok_post`.`DateStart` <= \''.$sDate.'\' AND (`zok_post`.`DateEnd` >= \''.$sDate.'\' OR `zok_post`.`DateEnd` = \'0000-00-00\' )');
			$rRes = $this->db->get('`zok_post`');
			$aCategory = $rRes->row_array();

			if (!empty($aCategory['BaseName']))
			{
				redirect($this->config->item('uri_category').$aCategory['BaseName']);
			}
			else
			{
				show_404();
			}
			return false;
		}

		$aData['data']['top_categories'] = $this->Catalog_model->getCategoriesList(0,$this->aSystemVar['cur_lang']);

		$iPostId = $aData['data']['Post']['Id'];

		if(!$this->bAdmin)
		{
			if( 'deleted' == $aData['data']['Post']['Status'] )
			{
				show_404();
			}
		}

/*
*	post actions - add comments, etc
*/
		if ( $this->input->post('action') )
		{
			if ( 'comment_add' == $this->input->post('action') )
			{

				if ( !$this->config->item('security_code_comment') || $this->_security_code_check( strtoupper($this->input->post('SecurityCode')), false ) )
				{
					$sPost = $this->input->post('Body', true);
					if( !empty( $sPost ) )
					{
						$aComment = array(
							'`ParentId`'	=> (int)$this->input->post('ParentId'),
							'`UserId`'		=> (int)$this->input->post('UserId'),
							'`PostId`'		=> $iPostId,
							'`Body`'		=> htmlspecialchars( wordwrap( substr( $this->input->post('Body', true), 0, $this->config->item('comment_characters') ), 35, ' ', true)),
							'`Time`'		=> date($this->config->item('long_date_format'))
						);

						$this->db->insert( '`zok_comment`', $aComment );
					}
				}

			}
			elseif ( 'comment_report' == $this->input->post('action') && $this->input->post('CommentId') )
			{
				$this->db->where('`Id`', (int)$this->input->post('CommentId') );
				$this->db->update('`zok_comment`', array( 'Status' => 'reported' ) );
			}

		}


// header
		$this->aHeaderVar['meta_desc'] = htmlspecialchars(substr($aData['data']['Post']['Body'], 0, 250));
		$this->aHeaderVar['meta_key'] = htmlspecialchars($aData['data']['Post']['Keywords']);

		$aData['data']['Post']['Title'] = $aData['data']['Post']['Title'];
		$aData['data']['Post']['Body'] = nl2br($aData['data']['Post']['Body']);
		$aData['data']['Post']['Body'] = preg_replace( '/^\[link\]file\/review\/(.)+?\[\/link\]$/', '<a href="' . base_url() . 'file/review/$1" >download</a>', $aData['data']['Post']['Body'] );
		//$aData['data']['Post']['Body'] = str_replace( '[link]', '<a href="' . base_url(), $aData['data']['Post']['Body'] );//$aData['data']['Post']['Body']
		//$aData['data']['Post']['Body'] = str_replace( '[/link]', '">download</a>', $aData['data']['Post']['Body'] );//$aData['data']['Post']['Body']
		$aData['data']['Post']['BreadCrambList'] = $this->Catalog_model->GetNamedBreadCramb( $aData['data']['Post']['BreadCramb'], $sLang);

// header
		$this->aHeaderVar['page_title'] = $aData['data']['Post']['Title'];

// get user data
		//$aData['data']['User'] = $this->Catalog_model->GetUserArrayByPostId( $iPostId );
		$aData['data']['User'] = $this->Catalog_model->GetUserArrayById( $aData['data']['Post']['UserId'] );
//--------------------------------------------------

// check for owner
		if ( ( !empty( $aData['data']['User']['Name'] )
			&& $aData['data']['User']['Name'] == $this->aSystemVar['current_user']['Name'] )
			|| $this->bAdmin )
			$aData['data']['User']['Owner'] = true;
		else
			$aData['data']['User']['Owner'] = false;
//--------------------------------------------------

// get neigbour categories
		//$aData['data']['CategoryList'] = $this->Catalog_model->GetSubCategoryList($aData['data']['Post']['CategoryId']);
//--------------------------------------------------

// get pref and next posts ( get list ordered by date
		$this->db->select('`zok_post`.`Id`,`zok_post`.`BaseName`,`zok_post_lang`.`Title`');
		$this->db->join('`zok_post_lang`', '`zok_post`.`Id` = `zok_post_lang`.`PostId` AND `zok_post_lang`.`Lang`=\''.$sLang.'\'');
		$this->db->where('`zok_post`.`CategoryId`', $aData['data']['Post']['CategoryId']);
		$this->db->where('`zok_post`.`DateStart` <= \''.$sDate.'\' AND (`zok_post`.`DateEnd` >= \''.$sDate.'\' OR `zok_post`.`DateEnd` = \'0000-00-00\' )');
// pre or post moderation
		if ( '1' == $this->config->item('premoderation') )
			$this->db->where('`zok_post`.`Status` = \'active\'');
		else
		 	$this->db->where('`zok_post`.`Status` != \'deleted\'');
		$this->db->orderby('`zok_post`.`Id` ASC');
		$rRes = $this->db->get('`zok_post`');
		$aPostList = $rRes->result_array();
		$iNum = count($aPostList);
		for ($i=0; $i<$iNum; $i++)
			if ( $iPostId == $aPostList[$i]['Id'] )
				break;

		$aData['data']['PrevPost'] = array_key_exists($i-1,$aPostList) ? $aPostList[$i-1] : array();
		$aData['data']['NextPost'] = array_key_exists($i+1,$aPostList) ? $aPostList[$i+1] : array();
//--------------------------------------------------

// get pics
		$this->db->select('Pic, Ext, Description');
		$this->db->orderby('`Seq`', 'asc');
		$this->db->orderby('`Id`', 'asc');
		$rRes = $this->db->getwhere( 'zok_post_pic', array( 'PostId' => $iPostId ) );
		$aImages = $rRes->result_array();

		$sPostPicUrl = $this->config->item('post_pic_url');
		$sPostPicDir = $this->config->item('post_pic_path');
		foreach( $aImages as $aImage )
		{
// TODO: make check for file ( file_exists )
			$sPicBase = base_url() . $sPostPicUrl . $iPostId . '/' . $aImage['Pic'];
			$sPicBaseDir = $this->config->item('base_dir') . $sPostPicDir . $iPostId . '/' . $aImage['Pic'];
			if( $this->Catalog_model->ext_file_exists( $sPicBaseDir . $aImage['Ext'] ) &&
				$this->Catalog_model->ext_file_exists( $sPicBaseDir . '_thumb' .  $aImage['Ext'] ) &&
				$this->Catalog_model->ext_file_exists( $sPicBaseDir . '_icon' .  $aImage['Ext'] ) )
			{
				$aImage['UrlPic'] = $sPicBase . $aImage['Ext'];
				$aImage['UrlThumb'] = $sPicBase . '_thumb' . $aImage['Ext'];
				$aImage['UrlIcon'] = $sPicBase . '_icon' . $aImage['Ext'];
				$aData['data']['Post']['Images'][] = $aImage;
			}
		}
//--------------------------------------------------
//--------------------------------------------------

// get comments
		$aData['data']['Comment']['CommentList'] = $this->_getCommetsArray($iPostId);
		$aData['data']['Comment']['SecurityCode'] = $this->config->item('security_code_comment');

//			$aData['data']['CurrentUser']['UserId'] = $this->session->userdata('userid');
//--------------------------------------------------

// Statistic
		$sNow = date("Y-m-d H:i:s");
//		$this->db->query('INSERT INTO `zok_post_view` (`PostId`, `View`, `LastView`) VALUES (\'' . $iPostId . '\', \'1\', \'' . $sNow .'\') ON DUPLICATE KEY UPDATE `View`=`View`+1, `LastView`=\'' . $sNow . '\'');
		$this->db->query( 'UPDATE `zok_post_stat` SET `View`=`View`+1, `LastView`=\'' . $sNow . '\' WHERE `PostId`=' . $iPostId );

//----------------------------------------------------------------

		// get custom fields
		$aData['data']['CustomFields'] = $this->Catalog_model->GetCustomFields($aData['data']['Post']['CategoryId'],$iPostId,$sLang);

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

	}

/*
*
*	edit post
*
*	@param - post id
*
*/
	function edit( $iPostId = '', $iNewCategoryId=false)
	{

		$this->load->library('validation');

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

		$iPostId = (int)$iPostId;

		//$this->load->helper('form');

		$this->db->select( '`zok_post`.*,`zok_post_lang`.`Title`,`zok_post_lang`.`Body`,`zok_post_lang`.`Keywords`,
			DAY(`DateStart`) as SDay, MONTH(`DateStart`) as SMonth, YEAR(`DateStart`) as SYear,
			DAY(`DateEnd`) as EDay, MONTH(`DateEnd`) as EMonth, YEAR(`DateEnd`) as EYear' );
		$this->db->join('`zok_post_lang`', '`zok_post`.`Id` = `zok_post_lang`.`PostId` AND `zok_post_lang`.`Lang`=\''.$sLang.'\'');
		$rRes = $this->db->getwhere( 'zok_post', array( '`zok_post`.`Id`' => $iPostId ) );
		if ( 0 == $rRes->num_rows() )
			redirect('');

		$aData['data']['Post'] = $rRes->row_array();

		if ( $aData['data']['Post']['UserId']!=$this->aSystemVar['current_user']['Id'] && !$this->bAdmin )
		{
			redirect();
			return false;
		}

		$this->db->select('`Id`, `Pic`, `Ext`, `Description`');
		$this->db->orderby('`Seq`', 'asc');
		$this->db->orderby('`Id`', 'asc');
		$rRes = $this->db->getwhere( 'zok_post_pic', array( 'PostId' => $iPostId ) );
		$sPostPicUrl = base_url() . $this->config->item('post_pic_url') . $iPostId . '/';
		if ( 0 < $rRes->num_rows() )
		{
			$aImages = $rRes->result_array();
			foreach( $aImages as $aImage )
			{
				$aImage['UrlPic'] = $sPostPicUrl . $aImage['Pic'] . $aImage['Ext'];
				$aImage['UrlThumb'] = $sPostPicUrl . $aImage['Pic'] . '_thumb' . $aImage['Ext'];
				$aImage['UrlIcon'] = $sPostPicUrl . $aImage['Pic'] . '_icon' . $aImage['Ext'];
				$aData['data']['Post']['ImageList'][] = $aImage;
			}
		}
		else
			$aData['data']['Post']['ImageList'] = array();

//		if ( !isset($aData['data']['Post']['UrlIcon']) )
//			$aData['data']['Post']['UrlIcon'] = '';

		// if $iNewCategoryId specified it is supposed that function "edit" has beed run from function "save",  from validation routine.
		// it means that we should show NEW custom fields, though we DID NOT change post category yet !!
		if ( is_int($iNewCategoryId) )
			$aData['data']['Post']['CategoryId'] = $iNewCategoryId;
			
// description of post category
		$aData['data']['Category']['BreadCrambList'] = array();
		$aPCat = $this->Catalog_model->getLocCategory($aData['data']['Post']['CategoryId'],$sLang);
		if (0 < count($aPCat))
		{
			$aData['data']['Category']['Id'] = $aPCat['Id'];
			$aData['data']['Category']['Title'] = $aPCat['Title'];
			$aData['data']['Category']['BreadCrambList'] = $this->Catalog_model->GetNamedBreadCramb($aPCat['BreadCramb'],$sLang);
		}
		else
			$aData['data']['Category']['Id'] = 0;


// get category list
		$aData['data']['Category']['CategoryList'] = $this->Catalog_model->GetCategoryTreeForPost($sLang);

// get SubType list
		if ( $this->bAdmin )
		{
			$rRes = $this->db->query('DESCRIBE `zok_post` `SubType`');
			$aField = $rRes->row_array();
			preg_match_all( '/\'(.+?)\'/', $aField['Type'], $aOption );
			$aData['data']['SubType']['SubTypeList'] = $aOption[1];
		}


		$rRes = $this->db->query('DESCRIBE `zok_post` `PicArrange`');
		$aField = $rRes->row_array();
		preg_match_all( '/\'(.+?)\'/', $aField['Type'], $aOption );
		$aPicArrange = $aOption[1];

		$aData['data']['Post']['PicArrangeOption'] = $aPicArrange;

		$this->aHeaderVar['page_title'] = $this->lang->line('_edit_post') .  ' - ' . $aData['data']['Post']['Title'];

/*
		$this->db->select('Country, ISO2');
		$this->db->orderby( 'Country', 'asc');
		$rRes = $this->db->get( 'zok_country' );
		foreach ( $rRes->result_array() as $aRow )
			$aData['data']['CountryList'][] = array ( 'ISO2' => $aRow['ISO2'], 'Country' => $aRow['Country'] );
*/

		// get custom fields
		$aData['data']['CustomFields'] = $this->Catalog_model->GetCustomFields($aData['data']['Post']['CategoryId'],$iPostId,$sLang);

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

	}

/*
*
*	list of posts owned by user
*
*	@param - user nickname
*
*/
	function roll($sUserName = '', $iPage=1)
	{

		$aData = array();

		if ( empty($sUserName) || !preg_match('/^\w+$/', $sUserName) )
			redirect('');

		$aData['data']['User'] = $this->Catalog_model->getUserArrayByName( $sUserName, true );

		if ( empty($aData['data']['User']['Name']) )
			redirect('');

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

		$sDate = date("Y-m-d");

		if ( $aData['data']['User']['Name'] == $this->aSystemVar['current_user']['Name'] || $this->bAdmin )
			$aData['data']['User']['Owner'] = true;
		else
			$aData['data']['User']['Owner'] = false;

		$this->aHeaderVar['page_title'] = $aData['data']['User']['Name'] .'\'s post list';

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

		$sSelect = '
			SQL_CALC_FOUND_ROWS
			`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_post_stat`.`View`,
			`zok_user`.`Name` as UserName';

		$this->db->select($sSelect, false);
		$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`.`PrimaryPicId` = `zok_post_pic`.`Id`','left');
		$this->db->join('`zok_category`', '`zok_post`.`CategoryId` = `zok_category`.`Id`');
		$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`');
		$this->db->join('`zok_user`', '`zok_post`.`UserId` = `zok_user`.`Id`');
		if ( true !== $aData['data']['User']['Owner'] )
		{
			$sCondition = '1' == $this->config->item('premoderation') ? ' AND `zok_post`.`Status` = \'active\' ' : ' AND `zok_post`.`Status` != \'deleted\' ';
			$this->db->where('`zok_post`.`DateStart` <= \''.$sDate.'\' AND (`zok_post`.`DateEnd` >= \''.$sDate.'\' OR `zok_post`.`DateEnd` = \'0000-00-00\' )' . $sCondition );
		}
		$this->db->where('`zok_post`.`Status` != \'deleted\'');
		$this->db->where('`zok_post`.`UserId` = \'' . $aData['data']['User']['Id'] . '\'' );
		$this->db->limit($iPerPage,$iStart);
		$this->db->orderby('`zok_post`.`Status`', 'ASC');
		$rRes = $this->db->get();

// 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('post/roll/'.$sUserName), $this->lang, site_url('post/roll/'.$sUserName) );
		$iStart = $oPageNate->GetStart();
		$aData['data']['Pagination'] = $oPageNate->GeneratePageNateLine();
// end of pagination

		$aData['data']['PostList'] = array();
		foreach( $rRes->result_array() 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'];
//			else
//				$aPost['PicUrl'] = base_url().$this->config->item('design_pic_url').$this->config->item('thumb_no_post');

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

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

			$aData['data']['PostList'][] = $aPost;
		}

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

	}

/*
*
*	check for security code
*
*	@param - user's version of security code
*
*	@return bool
*
*/
	function _security_code_check( $sCode = '', $bValidationString = true )
	{
//echo '$sCode->' . $sCode . '<hr />';
//echo '$sMD5Code->' . md5($sCode) . '<hr />';
//echo '$sHash->' . $this->session->userdata('securityhash') . '<hr />';
		if ( empty($sCode) || md5($sCode) != $this->session->userdata('securityhash') )
		{
			if ( $bValidationString )
				$this->validation->set_message('_security_code_check', $this->lang->line('_security_code_check') );

			return FALSE;
		}
		else
		{
			return TRUE;
		}

	}


	function _replace_word_chars( $sString )
	{
		$aSearch = array( "/&ndash;/", "/&lsquo;/", "/&rsquo;/", "/&ldquo;/", "/&rdquo;/" );
		$aReplaces = array( "-", "&#039;", "&#039;", "&quot;", "&quot;" );
		return preg_replace( $aSearch, $aReplaces, $sString );
	}


    /**
	 *	@desc		-
	 *	@access		-
	 * 	@param		-
	 *
	 * 	@return		-
	 *
	 */
	function _getCommetsArray( $iPostId )
	{
		$aCommentList = array();

        $sSelect = '
			`zok_comment`.*,
			DATE_FORMAT(`zok_comment`.`Time`, \'%Y-%m-%d\') AS commentTime,
			IF( `zok_comment`.`UserId` = \'0\', \'\', `zok_user`.`Name` ) as Name,
			`zok_user`.`UserFolder`,
			`zok_user`.`Pic`,
			`zok_user`.`Ext`,
		';
		$this->db->select($sSelect);
		$this->db->join('`zok_user`', '`zok_comment`.`UserId` = `zok_user`.`Id`', 'left');
		$rRes = $this->db->getwhere( '`zok_comment`', array( 'PostId' => $iPostId ) );
		$aCommentList = $this->Catalog_model->GetHierarchyArray( $rRes->result_array() );

		foreach( $aCommentList as $iKey => $aValue )
		{
			$aCommentList[$iKey]['IconUrl'] = '';
			$sThumb = $this->config->item('base_dir') . $this->config->item('user_data_path') . $aValue['UserFolder'] . $aValue['Pic'] . '_icon' . $aValue['Ext'];
			if( $this->Catalog_model->ext_file_exists($sThumb) )
			{
				$aCommentList[$iKey]['IconUrl'] = $this->config->item('base_url') . $this->config->item('user_data_url') . $aValue['UserFolder'] . $aValue['Pic'] . '_icon' . $aValue['Ext'];
			}
		}

	    return $aCommentList;
	}

	// checks if required custom fields are set and generates errors if not
	function _customFieldsCheck($aPostCustomFields)
	{
	
		$aCustomFields = $this->Catalog_model->GetCustomFields($this->PostCategoryId);

		$aErrMsg = array();

		foreach ($aCustomFields as $aField)
		{
			// if field is numeric - it is required by default ;-)
			if ( 'num' == $aField['FieldType'] )
			{
				if ( empty($aPostCustomFields[$aField['BaseName']]) )
				{
					$aErrMsg[$aField['BaseName']]['Title']=$aField['Title'];
					$aErrMsg[$aField['BaseName']]['Msg']='required';
				}
				else if ( !is_numeric($aPostCustomFields[$aField['BaseName']]) )
				{
					$aErrMsg[$aField['BaseName']]['Title']=$aField['Title'];
					$aErrMsg[$aField['BaseName']]['Msg']='numeric';
				}
			}
			else if ( 'req'==$aField['Mode'] && 'check' != $aField['FieldType'] )
			{
				if ( empty($aPostCustomFields[$aField['BaseName']]) )
				{
					$aErrMsg[$aField['BaseName']]['Title']=$aField['Title'];
					$aErrMsg[$aField['BaseName']]['Msg']='required';
				}
			}
		}

		if ( 0 < count($aErrMsg) )
		{
			$sMsg = '';
			foreach ($aErrMsg as $Err)
			{
				$sMsg .= sprintf($this->lang->line($Err['Msg']),$Err['Title']) . '<br />';
			}

			$this->validation->set_message('_customFieldsCheck', $sMsg);

			return false;
		}

		return true;

	}
	
	
	function _gr_categ_check( $iCategoryId )
	{

		if ( false === $this->_grIsAllowed('categ_to_post',$iCategoryId) )
		{
			$this->validation->set_message('_gr_categ_check', 'this action restricted for your group');
			return false;
		}
		
		return true;
	}
	

}

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