<?php
/*---------------------------------------------\
|											   |
| Author:       Andrey Brykin (Drunya)         |
| Version:      1.4.5                          |
| Project:      CMS                            |
| package       CMS Fapos                      |
| subpackege    Chat Module                    |
| copyright     ©Andrey Brykin 2010-2011       |
|----------------------------------------------|
|											   |
| any partial or not partial extension         |
| CMS Fapos,without the consent of the         |
| author, is illegal                           |
|----------------------------------------------|
| Любое распространение                        |
| CMS Fapos или ее частей,                     |
| без согласия автора, является не законным    |
\---------------------------------------------*/



class ChatModule extends Module {
	/**
	* @template  layout for module
	*/
	var $template = 'chat';
	/**
	* @module_title  title of module
	*/
	var $module_title = 'Чат';
	/**
	* @module module indentifier
	*/
	var $module = 'chat';

	

	
	/**
	* default action ( show add form and iframe for messages )
	*
	* @return view content
	*/
	public function index() {
		$content = '';
		if ($this->ACL->turn(array('chat', 'add_materials'), false)) {
			$content = $this->add_form();
		} else {
			$content = __('Permission denied');
		}
		return $this->_view($content);
	}
	
	
	
	/**
	*  show messages list 
	*
	* @return view content
	*/
	public function view_messages() {
		$content = '';
		$this->template = '';
		
		
		if (file_exists(R . 'sys/tmp/chat/messages.dat')) {
			$data = unserialize(file_get_contents(R . 'sys/tmp/chat/messages.dat'));
			if (!empty($data)) {
				$template = $this->Parser->getAndParse('viewmat.html');
				$data = array_reverse($data);
				
				
				foreach ($data as $key => $record) {
					$markets = array();
					$markets['{DATE}'] = h($record['date']);
					$markets['{TIME}'] = h($record['time']);
					$markets['{MESSAGE}'] = h($record['message']);

					/* view ip adres if admin */
					if ($this->ACL->turn(array('chat', 'delete_materials'), false)) {
						$markets['{IP}'] = get_img('/sys/img/ip.png', array('title' => h($record['ip'])));
					} else {
						$markets['{IP}'] = '';
					}
					$markets['{UID}'] = h($record['uid']);

					if($record['uid']=='0') {
						$markets['{USER_PROFILE_URL}'] = '';
					} else {
						$markets['{USER_PROFILE_URL}'] = '<a href="/users/info/'.h($record['uid']).'"><img alt="#" class="mprofile" src="/sys/img/mprofile.png" border="0" /></a>';
					}
					
					$markets['{NAME}'] = h($record['name']);
					$content .= $this->_replaceMarkets($markets, $template);
				}
			}
		}
		header('Refresh: 10; url=' . get_url('/chat/view_messages/'));
		echo $content;
	}
	
	
	

	/**
	* add message form
	*
	* @return  none
	*/
	public function add() {
		$Parser = new Document_Parser;
		$ACL = new ACL;
	
		if (!$ACL->turn(array('chat', 'add_materials'), false)) {
			return;
		}
		if (!isset($_POST['message'])) {
			die(__('Needed fields is empty'));
		}
		
		/* cut and trim values */
		$uid    = (!empty($_SESSION['user']['id'])) ? $_SESSION['user']['id'] : 0;
		$name    = (!empty($_SESSION['user']['name'])) ? $_SESSION['user']['name'] : 'Гость';
		$message = mb_substr( $_POST['message'], 0, Config::read('max_lenght', 'chat'));
		$message = trim( $message );
		$ip      = (!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : '';
		$keystring = (isset($_POST['captcha_keystring'])) ? trim($_POST['captcha_keystring']) : '';
		
		
		// Check fields
		$error  = '';
		$valobj = new Validate;
		if (empty($message))                       
			$error = $error . '<li>' . __('Empty field "text"') . '</li>' . "\n";
			
			
			
		// Check captcha if need exists	 
		if (!$ACL->turn(array('other', 'no_captcha'), false)) {
			if (empty($keystring))                      
				$error = $error . '<li>' . __('Empty field "code"') . '</li>' . "\n";

				
			// Проверяем поле "код"
			if (!empty($keystring)) {
				// Проверяем поле "код" на недопустимые символы
				if (!$valobj->cha_val($keystring, V_CAPTCHA))
					$error = $error . '<li>' . __('Wrong chars in field "code"') . '</li>' . "\n";					
				if (!isset($_SESSION['captcha_keystring'])) {
					if (file_exists(R . 'sys/logs/captcha_keystring_' . session_id() . '-' . date("Y-m-d") . '.dat')) {
						$_SESSION['captcha_keystring'] = file_get_contents(R . 'sys/logs/captcha_keystring_' . session_id() . '-' . date("Y-m-d") . '.dat');
					}
				}
				if (!isset($_SESSION['captcha_keystring']) || $_SESSION['captcha_keystring'] != $keystring)
					$error = $error . '<li>' . __('Wrong protection code') . '</li>' . "\n";
			}
			unset($_SESSION['captcha_keystring']);
		}
		
		
		/* remember name */
		$_SESSION['chat_name'] = $name;
		
		/* if an errors */
		if (!empty($error)) {
			$_SESSION['addForm']            = array();
			$_SESSION['addForm']['error']   = '<p class="errorMsg">' . __('Some error in form') . '</p>' . 
				"\n" . '<ul class="errorMsg">' . "\n" . $error . '</ul>' . "\n";
			$_SESSION['addForm']['message'] = $message;
			die($_SESSION['addForm']['error']);
		}
		
		/* create dir for chat tmp file if not exists */
		if (!file_exists(R . 'sys/tmp/chat/')) mkdir(R . 'sys/tmp/chat/', 0777, true);
		/* get data */
		if (file_exists(R . 'sys/tmp/chat/messages.dat')) {
			$data = unserialize(file_get_contents(R . 'sys/tmp/chat/messages.dat'));
		} else {
			$data = array();
		}
		
		
		/* cut data (no more 50 messages */
		while (count($data) > 50) {
			array_shift($data);
		}
		$data[] = array(
			'uid' => $uid,
			'name' => $name,
			'message' => $message,
			'ip' => $ip,
			'date' => date("Y-m-d h:i"),
			'time' => date("h:i"),
		);
		
		
		/* save messages */
		$file = fopen(R . 'sys/tmp/chat/messages.dat', 'w+');
		fwrite($file, serialize($data));
		fclose($file);
		die('ok');
		
	}
	
	
	
	/**
	* view add message form
	*
	* @return (str)  add form
	*/
	public static function add_form() {
		$Parser = new Document_Parser;
		$Parser->templateDir = 'chat';
		$ACL = new ACL;
		if (!$ACL->turn(array('chat', 'add_materials'), false)) 
			return __('Dont have permission to write post');
	
	
		$content = '';
		$markets = array();

		/* if an errors */
		if (isset($_SESSION['addForm'])) {
			$message  = $Parser->quoteTags($_SESSION['addForm']['message']);
			unset( $_SESSION['addForm'] );
		} else if (isset($_SESSION['chat_name'])) {
			$message = '';
			$name    = (!empty($_SESSION['chat_name'])) ? $_SESSION['chat_name'] : '';
		} else {
			$message = '';
			$name = (!empty($_SESSION['user']['name'])) ? $_SESSION['user']['name'] : '';
		}
		
		
		$tpl = $Parser->getAndParse('addform.html');
		$kcaptcha = '';
		
		
		if (!$ACL->turn(array('other', 'no_captcha'), false)) {
			$kcaptcha = getCaptcha();
		}
		$markets['{ACTION}'] = get_url('/chat/add/');
		$markets['{LOGIN}'] = h($name);
		$markets['{MESSAGE}'] = h($message);
		$markets['{CAPTCHA}'] = $kcaptcha;
		


		$content = $content . str_replace(array_keys($markets), $markets, $tpl);
		return $content;
	}
	

}

?>
