<?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
*/
$mod_template="edit_post.tpl";

if ($_SERVER["REQUEST_METHOD"]=='POST')
{
	User::checkToken();
	if ($_POST['name']) {sleep(20); exit();} //если постит робот, то посылаем его нафиг
	$_POST['name']=$_POST[LabConfig::$cfg['catcher']];
	unset($_POST[LabConfig::$cfg['catcher']]);

	$mail=new Mailer(LabConfig::$cfg['admin_mail']);

	// Проверяем правильность ввода информации в поля формы
	if (empty($_POST["msg"]))
	{
		LabCMS::i()->error("Вы не ввели сообщение");
	}
	if (trim($_POST["name"])=='' && User::i()->id<0)
	{
		LabCMS::i()->error("Вы не ввели имя");
	}
	elseif(User::i()->id<1 && trim($_POST["name"]))
	{
		$result=Db::i()->selectCell("SELECT COUNT(login) FROM ?_users WHERE login IN (?a)", possible_logins($_POST["name"]));
		if ($result) LabCMS::i()->error("Пользователь с таким именем уже зарегистрирован!");
	}

	if ($_POST['subj'] && $forum_info['theme_id'])
	{
		$first_post=Db::i()->selectCell("SELECT MIN(post_id) FROM ?_forum_posts WHERE theme_id=?", $forum_info['theme_id']);
		if ($forum_info['post_id']!=$first_post) unset($_POST['subj']);
	}
	
	if (($mode=='new' || $first_post) && trim($_POST['subj'])=="")
	{
		LabCMS::i()->error("Вы не ввели тему");
	}
	
	if (LabCMS::i()->no_errors)
	{
		$user_id=(User::i()->id>0)?User::i()->id:0; //используем при добавлении тем и сообщений
		$name=(User::i()->id<0)?$_POST['name']:'';
		
		if (LabConfig::$mcfg['forum_email_notify'] && LabConfig::$cfg['admin_mail'])
		{
			$mail->From = 'forum@'.preg_replace('/^www\./i', '', $_SERVER["SERVER_NAME"]);
			$mail->FromName = "Робот форума";
			$mail->AddReplyTo('forum@'.preg_replace('/^www\./i', '', $_SERVER["SERVER_NAME"]), "Робот форума");
			$mail->WordWrap = 80;                                 // set word wrap to 50 characters
		}

		//если режим редактирования и есть доступ для редактирования
		if ($mode=="edit")
		{
			if (User::i()->id==$forum_info['user_id']) //если редактируем свое сообещние
			{
				Db::i()->query("UPDATE ?_forum_posts SET msg=?, edited=NULL WHERE post_id=?", $_POST['msg'], $forum_info['post_id']);
			}
			elseif(access('moderator')) //в принципе, вроде как можно и не проверять
			{
				Db::i()->query("UPDATE ?_forum_posts SET msg=?, email=?, user_name=?, edited=? WHERE post_id=?", $_POST['msg'], $_POST['email'], $_POST['name'], User::i()->login, $forum_info['post_id']);
			}
			
			if ($_POST['subj'])
			{
				if($_POST['move_to_forum']!=$forum_info['forum_id'] && access('moderator'))
				{
					Db::i()->query("UPDATE ?_forum_themes SET subject=? , forum_id=? WHERE theme_id=?", $_POST['subj'], $_POST['move_to_forum'],$forum_info['theme_id']);
					//если тему перенесли в другой форум, то обновляем данные об обоих форумах
					update_forum($forum_info['forum_id']);
					update_forum($_POST['move_to_forum']);
				}
				else
				{
					Db::i()->query("UPDATE ?_forum_themes SET subject=? WHERE theme_id=?", $_POST['subj'],$forum_info['theme_id']);
				}
			}
			refresh('', LabCMS::i()->url(array($forum_info['theme_id'], 999), 'theme')."#last");
		}
		
		//если добавляем тему
		if ($mode=="new")
		{
			$theme_id=Db::i()->query("INSERT INTO ?_forum_themes (forum_id, subject, author, author_id, last_user, last_user_id, total_posts, last_post) VALUES(?, ?, ?, ?, ?, ?, 1, NOW())", 	$forum_info['forum_id'],	$_POST['subj'],	$name,	$user_id,	$name,	$user_id);
			Db::i()->query("INSERT INTO ?_forum_posts (theme_id, user_name, user_id, msg, email, putdate, ip) VALUES(?, ?, ?, ?, ? ,NOW(), INET_ATON(?))", $theme_id, $name, $user_id, $_POST['msg'], $_POST['email'], $_SERVER['REMOTE_ADDR']);
			Db::i()->query("UPDATE ?_forum_forums SET  forum_total_posts=forum_total_posts+1, total_themes=total_themes+1, forum_last_post=NOW(),  forum_last_user=?, forum_last_user_id=? WHERE forum_id=?", $name, $user_id,  $forum_info['forum_id']);
			if (LabConfig::$mcfg['forum_email_notify'] && LabConfig::$cfg['admin_mail'])
			{
				$mail->Subject = 'Новая тема в форуме '.$_SERVER["SERVER_NAME"];
				Tpl::i()->assign(array('subject'=>$_POST['subj'], 'msg'=>$_POST['msg'], 'theme_id'=>$theme_id));
				if (!Tpl::i()->templateExists(LabCMS::i()->getModuleName()."/email_notify_new.tpl")) $default='../default/';
				$mail->Body    = Tpl::i()->fetch($default.LabCMS::i()->getModuleName()."/email_notify_new.tpl");
				$mail->Send();
			}
			refresh('', LabCMS::i()->url(array($theme_id, 999), 'theme')."#last");
		}
		
		if ($mode=="reply")
		{
			Db::i()->query("INSERT INTO ?_forum_posts (theme_id, user_name, user_id, msg, email, putdate, ip) VALUES(?, ?, ?, ?, ?, NOW(), INET_ATON(?))", $forum_info['theme_id'], $name, $user_id, $_POST['msg'], $_POST['email'], $_SERVER['REMOTE_ADDR']);
			Db::i()->query("UPDATE ?_forum_themes SET  total_posts=total_posts+1, last_post=NOW(),  last_user=?, last_user_id=? WHERE theme_id=?",  $name, $user_id, $forum_info['theme_id']);
			Db::i()->query("UPDATE ?_forum_forums SET  forum_total_posts=forum_total_posts+1, forum_last_post=NOW(),  forum_last_user=?, forum_last_user_id=? WHERE forum_id=?", $name, $user_id, $forum_info['forum_id']);
			if (LabConfig::$mcfg['forum_email_notify'] && LabConfig::$cfg['admin_mail'])
			{
				$mail->Subject = 'Новый ответ форуме '.$_SERVER["SERVER_NAME"];
				Tpl::i()->assign(array('subject'=>$forum_info['subject'], 'msg'=>$_POST['msg'], 'theme_id'=>$forum_info['theme_id']));
				if (!Tpl::i()->templateExists(LabCMS::i()->getModuleName()."/email_notify_reply.tpl")) $default='../default/';
				$mail->Body    = Tpl::i()->fetch($default.LabCMS::i()->getModuleName()."/email_notify_reply.tpl");
				$mail->Send();
			}
			refresh('', LabCMS::i()->url(array($forum_info['theme_id'], 999), 'theme')."#last");
		}
	}
}

 //удаление сообщения
if ($mode=="delete")
{
	User::checkToken();
	Db::i()->query("DELETE FROM ?_forum_posts WHERE post_id=?", $forum_info['post_id']);
	update_theme($forum_info['theme_id']);
	update_forum($forum_info['forum_id']);
	refresh('', LabCMS::i()->url(array($forum_info['theme_id'], 999), 'theme')."#last");
}

//удаление темы
if ($mode=="delete_theme")
{
	User::checkToken();
	Db::i()->query("DELETE p,t FROM ?_forum_themes t LEFT JOIN ?_forum_posts p ON t.theme_id=p.theme_id WHERE t.theme_id=?", $forum_info['theme_id']);
	update_forum($forum_info['forum_id']);
	refresh('', LabCMS::i()->url($forum_info['forum_id']));
}

 //удаление сообщения
if ($mode=="delete_hidden")
{
	User::checkToken();
	Db::i()->query("DELETE FROM ?_forum_hposts WHERE post_id=?", $forum_info['post_id']);
	refresh('', LabCMS::i()->url(array($forum_info['theme_id'], 999), 'theme')."#last");
}

//удаление темы
if ($mode=="delete_theme_hidden")
{
	User::checkToken();
	Db::i()->query("DELETE p,t FROM ?_forum_hthemes t LEFT JOIN ?_forum_posts p ON t.theme_id=p.theme_id WHERE t.theme_id=?", $forum_info['theme_id']);
	refresh('', LabCMS::i()->url($forum_info['forum_id']));
}

//вывод смайликов
Tpl::i()->assign("js_smiles", bbcode_smiles_js(4,4));

 //ответ на сообщение
 if ($mode=="reply")
 {
	Tpl::i()->assign('reply_info', array('msg_html'=>getbb($forum_info['msg']), 'user_name'=>$forum_info['user_name'], 'email'=>$forum_info['email'], 'putdate'=>$forum_info['putdate'], 'subject_html'=>getbb($forum_info['subject'], 'nolinks'), 'user_id'=>$forum_info['user_id']));
	if ($_SERVER['REQUEST_METHOD']=="GET" && $_GET['action']=='quote')	Tpl::i()->assign("msg", '[quote="'.$forum_info['user_name'].'"]'.$forum_info['msg']."[/quote]");
 }

//редактирование собщения
if ($mode=="edit")
{
	//проверяем, является ли это сообщение первым
	$first_post=Db::i()->selectCell("SELECT post_id FROM ?_forum_posts WHERE theme_id=? ORDER BY putdate LIMIT 1", $forum_info['theme_id']);
	if ($first_post==$forum_info['post_id']) Tpl::i()->assign('edit_subj',1);
	if ($_SERVER["REQUEST_METHOD"]!='POST') Tpl::i()->assign($forum_info);
}

//если передан forum_id, значит добавляем новую тему
if ($mode=="new")
{
	Tpl::i()->assign('edit_subj',1);
}
Tpl::i()->assign('mode', $mode);

function update_theme($theme_id)
{
	Db::i()->query("UPDATE ?_forum_themes t,
				(SELECT putdate, user_name, user_id FROM ?_forum_posts WHERE theme_id=? ORDER BY putdate DESC LIMIT 1) p
				SET t.last_post=p.putdate, t.last_user=p.user_name, t.last_user_id=p.user_id, total_posts=(SELECT COUNT(*) FROM ?_forum_posts WHERE theme_id=?) WHERE
				t.theme_id=?", $theme_id, $theme_id, $theme_id);
}

function update_forum($forum_id)
{
	Db::i()->query("UPDATE ?_forum_forums,
						(SELECT last_post, last_user_id, last_user FROM ?_forum_themes WHERE forum_id=? ORDER BY last_post DESC LIMIT 1) t
						SET forum_last_user_id=t.last_user_id, forum_last_user=t.last_user, forum_last_post=t.last_post,
						forum_total_posts=(SELECT SUM(total_posts) FROM ?_forum_themes WHERE forum_id=?),
						total_themes=(SELECT COUNT(*) FROM ?_forum_themes WHERE forum_id=?) WHERE forum_id=?", $forum_id, $forum_id, $forum_id, $forum_id);
}
