<?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_pm_main extends ModuleTools
{
	static $in_statuses=array(0, 1);
	static $out_statuses=array(0, 2);

	public $status;
	
	public function __construct()
	{
		self::_assign('pm_stat', $this->pm_status());
	}
	
	public function pm_users()
	{
		if ($_SERVER['REQUEST_METHOD']=='POST') {
			if ($_POST['login']) {
				$users=Db::i()->selectCol(
					"SELECT user_id
					FROM ?_users
					WHERE login
					LIKE ? LIMIT 100",
					'%'.addcslashes($_POST['login'], '_%').'%'
				);
				$users=User::i()->getUsersByIds($users);
				self::_assign('users', $users);
			}
		}
		self::_setTpl('users');
		addBreadcrumb(_m('Найти пользователя'));
	}
	
	public function pm_list()
	{
		$this->_getList();
		addBreadcrumb(_m('Принятые'));
	}
	
	public function pm_sended()
	{
		$this->_getList(false);
		addBreadcrumb(_m('Отправленные'));
	}

	protected function _getList($inbox=true)
	{
		if ($_SERVER['REQUEST_METHOD']=='POST') {
			if (is_array($_POST['delete'])) {
				$lm=$this->_getMessageObject();
				$lm->inbox=$inbox;
				$lm->deleteMessage(array_keys($_POST['delete']));
			}
			refresh('', _url(false, $lm->inbox?null:'sended'));
		}
		
		self::_setTpl("msg_list");
		$page=empty($_GET['var1'])?0:$_GET['var1'];
		$pl=$this->_getMessageListObject($page, $inbox?0:1);
		if ($inbox) {
			$messages=$pl->getInboxList(User::i());
		} else {
			$messages=$pl->getOutboxList(User::i());
		}
		
		self::_assign('messages', $messages);
		self::_assign('pager', $pl->pager);
	}
		
	public function pm_msg()
	{
		$msg=$this->_getMessageObject($_GET['var1'], true);
		if (!$msg->id) return self::_error(_m('Сообщение не найдено'));

		if ($msg->unread) $msg->markAsReaded();
		
		self::_setTpl("show_msg");
		self::_assign(array('next'=>$msg->getNext(), 'prev'=>$msg->getPrev()));
		self::_assign('msg', $msg);
		addBreadcrumb(_m('Принятые'), _url());
		addBreadcrumb($msg->subj, _url($msg->id, 'msg'));
	}
	
	public function pm_sended_msg()
	{
		$msg=$this->_getMessageObject($_GET['var1'], false);
		if (!$msg->id) return self::_error(_m('Сообщение не найдено'));
		
		self::_setTpl("show_msg");
		self::_assign(array('next'=>$msg->getNext(), 'prev'=>$msg->getPrev()));
		self::_assign('msg', $msg);
		addBreadcrumb(_m('Отправленные'), _url(false, 'sended'));
		addBreadcrumb($msg->subj, _url($msg->id, 'msg'));
	}
	
	public function pm_delete()
	{
		User::checkToken();
		$lm=$this->_getMessageObject($_GET['var1']);
		if ($lm->id && $lm->deleteMessage()) {
			$next=$lm->getNext();
			if ($next) refresh('', _url($next, 'msg'));
			else refresh();
		}
		self::_error(_m('Сообщение не найдено!'));
	}
	
	public function pm_sended_delete()
	{
		User::checkToken();
		$lm=$this->_getMessageObject($_GET['var1'], false);
		if ($lm->deleteMessage()) {
			$next=$lm->getNext();
			if ($next) refresh('', _url($next, 'sended_msg'));
			else refresh('', _url('', 'sended'));
		}
		self::_error(_m('Сообщение не найдено!'));
	}
	
	public function pm_ignore_remove()
	{
		User::checkToken();
		$il=$this->_getIgnoreObject();
		$user=User::getUser($_GET['var1']);
		if ($user->isGuest()) return self::_error(_m('Пользователь не найден'));
		$il->removeFromIgnore($user);
		refresh('', _url(false, 'ignore'));
	}
	
	public function pm_ignore_add()
	{
		User::checkToken();
		$il=$this->_getIgnoreObject();
		$user=User::getUser($_GET['var1']);
		if ($user->isGuest()) return self::_error(_m('Пользователь не найден'));
		$il->addToIgnore($user);
		refresh('', _url(false, 'ignore'));
	}
	
	public function pm_ignore()
	{
		$il=$this->_getIgnoreObject();
		self::_setTpl("ignore");
		self::_assign('ignores', $il->getIgnoreList());
		addBreadcrumb(_m('игнор'));
	}
	
	public function pm_send()
	{
		$lm=$this->_getMessageObject();
		if (!$receiver=User::getUser($_GET['var1'])) return;

		if (!$lm->isSendPossible(User::i(), $receiver)) return;

		if ($_SERVER['REQUEST_METHOD']=='POST') {
			if ($lm->send($receiver, User::i(), $_POST['subj'], $_POST['msg']))
				refresh();
		}
		
		self::_setTpl("msg_edit");
		self::_assign('receiver', $receiver);
		addBreadcrumb(_m('Написать сообщение'), _url($_GET['var1'], 'send'));
	}
	
	public function pm_reply()
	{
		$msg=$this->_getMessageObject($_GET['var1'], User::i());
		if (!$msg->id) return self::_error(_m('Сообщение не найдено'));

		if ($_SERVER['REQUEST_METHOD']=='POST') {
			if ($msg->send($msg->sender, $msg->receiver, $_POST['subj'], $_POST['msg']))
				refresh();
		}
		
		preg_match('/^RE(\[(\d+)\])?:/is', $msg->subj, $subj_tmp);
		if (!empty($subj_tmp[2])) {
			$msg['subj']=preg_replace(
				'/^'.preg_quote($subj_tmp[0], '/')
				.'/', 'RE['.($subj_tmp[2]+1).']:', $msg->subj
			);
		} elseif (!empty($subj_tmp[0])) {
			$msg->subj=preg_replace('/^RE/', 'RE[2]', $msg->subj);
		} else {
			$msg->subj='RE: '.$msg->subj;
		}
		
		self::_setTpl("msg_edit");
		self::_assign('receiver', $msg->sender);
		self::_assign('msg', $msg);
		addBreadcrumb($msg->subj, _url($msg->id, 'msg'));
		addBreadcrumb(_m('ответить'));
	}
	
	public function pm_status()
	{
		if ($this->status) return $this->status;
		$stat=Db::i()->selectRow("SELECT * FROM ?_lc_pm_stat WHERE user_id=?", User::i()->id);
		$this->status=array(
			'mess'=>empty($stat['mess'])?0:intval($stat['mess']),
			'umess'=>empty($stat['umess'])?0:intval($stat['umess'])
		);
		return $this->status;
	}
	
	protected function _getMessageObject($id=null, $inbox=true)
	{
		return Factory::create('lc_pm.message', $id, $inbox);
	}
	
	protected function _getMessageListObject($page, $box_id=0)
	{
		return Factory::create('lc_pm.list', $page, $box_id);
	}
	
	protected function _getIgnoreObject()
	{
		return Factory::create('lc_pm.ignore_list');
	}

}