<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class lc_chat_main extends ModuleTools
{
	public function lc_main()
	{
		if (!access('read')) return self::_error(_m('Вы не можете просматривать чат.'));
		$max=Db::i()->selectCell("SELECT id FROM ?_lc_chat ORDER BY id DESC LIMIT 50, 1");
		if ($max) Db::i()->query("DELETE FROM ?_lc_chat WHERE id <? AND moderator=0", $max);
		$this->_setUserOnline();
		self::_setTpl('main');
	}
	
	public function lc_post()
	{
		User::checkToken();
		if (trim($_POST['msg']) && access('write')) {
			if (!$post=$this->_checkPost($_POST['msg'])) return false;
			if (!$this->_post(User::i()->login, $post)) return self::_error(_m('Ошибка добавления сообщения'));
		}
		return $this->lc_get();
	}
	
	public function lc_get()
	{
		if (!access('read')) return self::_error(_m("Недостаточно прав для просмотра сообщений"));
		return array('posts'=>$this->_get($_POST['id']));
	}
	
	public function lc_getOnliners()
	{
		if (!access('read')) return self::_error(_m('Вы не можете просматривать чат.'));
		$this->_setUserOnline();
		$users=Db::i()->selectCol(
			"SELECT user_id AS ARRAY_KEY, login FROM ?_lc_chat_online
			WHERE `time`<NOW()-INTERVAL 2 MINUTE"
		);
		if ($users) {
			foreach ($users as $user_id=>$login) {
				$this->_postInfoMessage($login.' вышел из чата.');
			}
			Db::i()->query("DELETE FROM ?_lc_chat_online WHERE user_id IN (?a)", array_keys($users));
		}
		$onliners=Db::i()->select("SELECT login, user_id FROM ?_lc_chat_online ORDER BY login");
		return array('onliners'=>$onliners);
	}

	protected function _postInfoMessage($mess)
	{
		$this->_post('', $mess, 1);
	}
	
	protected function _setUserOnline()
	{
		$new=Db::i()->query(
			"INSERT INTO ?_lc_chat_online (login, user_id, `time`) VALUES(?, ?, NOW())
			ON DUPLICATE KEY UPDATE `time`=NOW()", User::i()->login, User::i()->id
		);
		if ($new==1) $this->_postInfoMessage(sprintf(_m('%s вошел в чат'), User::i()->login));
	}
	
	protected function _get($id)
	{
		return Db::i()->select(
			"SELECT * FROM ?_lc_chat
			{WHERE id>?} AND moderator=0 ORDER BY id", $id
		);
	}
	
	protected function _post($login, $post, $info=0)
	{
		//добавляем сообщение
		return Db::i()->query(
			"INSERT INTO ?_lc_chat (login, text, `time`, `info`)
			VALUES(?, ?, NOW(), ?)", $login, $post, $info
		);
	}
	
	protected function _checkPost($post)
	{
		return getbb($post);
	}
}