<?php
/*
	Copyright © Alexander Sunvas*
	http://eleanor-cms.ru
	a@eleanor-cms.ru
	*Pseudonym
*/
defined('CMS')||die;
$no=false;
switch($ev)
{
	case'new-post':#Новый пост
		$t=isset($_POST['t']) ? (int)$_POST['t'] : 0;
		$R=Eleanor::$Db->Query('SELECT `id`,`f`,`status`,`author_id`,`state`,`pinned`>\''.date('Y-m-d H:i:s').'\' `_topic_pinned` FROM `'.$Eleanor->mconfig['ft'].'` WHERE `id`='.$t.' LIMIT 1');
		if(!$topic=$R->fetch_assoc() or !$Forum->CheckTopicAccess($topic) or !$forum=$Forum->Forums->GetForum($topic['f']))
		{
			Error();
			break;
		}

		$rights=$Forum->ForumRights($forum['id']);
		$fu=$Eleanor->Url->furl ? $Forum->Forums->GetUrl($forum['id']) : array();
		$trash=$Forum->GetOption('trash');

		if($Forum->user and $Forum->user['restrict_post'] or $forum['is_category'] or $forum['id']==$trash or !in_array(1,$rights['access']) or in_array($topic['state'],array('moved','merged')))
		{
			Error();
			break;
		}

		#В этой переменной хранятся все модераторы форума + наши права, как модератора
		if($forum['moderators'])
			list($forum['moderators'],$forum['_moderator'])=$Forum->Moderator->ByIds($forum['moderators'],array('movet','move','deletet','delete','edit','chstatust','chstatus','pin','mmove','mdelete','user_warn','viewip','opcl','merge','editq','mchstatus'),$Eleanor->mconfig['n'].'_moders_t'.$forum['id']);
		else
			$forum['moderators']=$forum['_moderator']=array();

		if($Forum->user)
		{
			$gp=$gt=array();
			$ingp=false;
		}
		else
		{
			$gp=$Forum->GuestSign();
			$gt=$Forum->GuestSign('t');
			$ingp=$gp ? Eleanor::$Db->In($gp) : false;
		}

		$forum['_mstatus']=$Forum->ugr['supermod'] || ($forum['_moderator'] ? (in_array(1,$forum['_moderator']['chstatus']) or in_array(1,$forum['_moderator']['mchstatus'])) : false);
		$topic['_ismy']=$Forum->user ? $Forum->user['id']==$topic['author_id'] : in_array($topic['id'],$gt);
		$topic['_open']=$topic['state']=='open' || $Forum->ugr['supermod'] || in_array(1,$rights['canclose']);

		if($topic['_ismy'] and !in_array(1,$rights['post']) or $topic['_ismy'] and !in_array(1,$rights['apost']))
		{
			Error('Вы не можете публиковать посты в эту тему!');
			break;
		}

		if($ch=$Eleanor->TimeCheck->Check($Eleanor->mconfig['n'],false))
		{
			Error(sprintf('Писать посты можно раз в %s секунд! Подождите еще %s секунд.',Eleanor::$Permissions->FloodLimit(),$ch['_datets']-time()));
			break;
		}

		if(!isset(OwnBB::$replace['quote']))
		{
			if(!class_exists('ForumBBQoute',false))
				include$Eleanor->module['path'].'Misc/bb-quote.php';
			OwnBB::$replace['quote']='ForumBBQoute';
		}

		$values=array(
			'text'=>trim($Eleanor->Editor->GetHTML('text')),
			'status'=>Eleanor::$Permissions->Moderate() || $Forum->user && $Forum->user['moderate'] || $Forum->ugr['moderate'] ? -1 : 1,
		);

		if(mb_strlen($values['text'])<5)
		{
			Error(sprintf('Минимальная длина поста составляет %s символов.',5));
			break;
		}

		if($Forum->user)
			$me=Eleanor::$Login->GetUserValue(array('name','id'));
		else
		{
			$me=array(
				'id'=>0,
				'name'=>isset($_POST['_name']) ? (string)Eleanor::$POST['_name'] : false,
			);
			if($me['name'])
				Eleanor::SetCookie($Eleanor->mconfig['n'].'-name',$me['name']);
			else
			{
				Error('Пожалуйста, представьтесь!');
				break;
			}
		}

		$cach=$Eleanor->Captcha->Check(isset($_POST['_check']) ? (string)$_POST['_check'] : '');
		$Eleanor->Captcha->Destroy();
		if(!$cach)
		{
			Error(array('error'=>'Неправильно введен код защиты','captcha'=>true));
			break;
		}

		try
		{
			OwnBB::$opts['you_quoted']=true;
			$values+=array(
				'id'=>false,
				'f'=>$forum['id'],
				't'=>$topic['id'],
				'author'=>$me['name'],
				'author_id'=>$me['id'],
				'ip'=>Eleanor::$ip,
				'language'=>$forum['language'],
				'_topic_status'=>$topic['status'],
				'_topic_pinned'=>$topic['_topic_pinned'],
				'_gp'=>$gp,
			);
			$newpost=$Forum->Post->SavePost($values);
			if(!$Forum->user and !$newpost['_merged'])
			{
				$gp=$Forum->GuestSign('p',$newpost['id']);
				$ingp=$gp ? Eleanor::$Db->In($gp) : false;
			}
			if($fl=Eleanor::$Permissions->FloodLimit())
				$Eleanor->TimeCheck->Add($Eleanor->mconfig['n'],1,true,$fl);
		}
		catch(EE_SQL$E)
		{
			$E->LogIt($E->addon['logfile'],$E->getMessage());
			{
				Error($E->getMessage());
				break;
			}
		}
		catch(EE$E)
		{
			Error($E->getMessage());
			break;
		}
		if(isset($_POST['redirect']) ? $_POST['redirect'] : false)
		{
			Result(htmlspecialchars_decode($Eleanor->Url->Construct(array('do'=>'getnewpost','id'=>$t),true,'')));
			break;
		}
		$post=array('merged'=>$newpost['_merged'],'text'=>$newpost['_merged'] ? $newpost['text'] : false);
		if($newpost['_merged'])
		{
			Result($post);
			break;
		}
		$post['subs']=$values['status']==1 && isset($newpost['_subs']);
	case'lnp':
		$sd=isset($_POST['lp']) ? (int)$_POST['lp'] : 0;
		$n=isset($_POST['n']) ? abs((int)$_POST['n']) : 0;

		if(!isset($t))
		{
			$t=isset($_POST['t']) ? (int)$_POST['t'] : 0;
			$R=Eleanor::$Db->Query('SELECT `id`,`f`,`status`,`author_id`,`state` FROM `'.$Eleanor->mconfig['ft'].'` WHERE `id`='.$t.' LIMIT 1');
			if(!$topic=$R->fetch_assoc() or !$Forum->CheckTopicAccess($topic) or !$forum=$Forum->Forums->GetForum($topic['f']))
			{
				Error();
				break;
			}

			$rights=$Forum->ForumRights($forum['id']);
			$fu=$Eleanor->Url->furl ? $Forum->Forums->GetUrl($forum['id']) : array();

			if($forum['is_category'] or !in_array(1,$rights['access']) or in_array($topic['state'],array('moved','merged')))
			{
				Error();
				break;
			}

			#В этой переменной хранятся все модераторы форума + наши права, как модератора
			if($forum['moderators'])
				list($forum['moderators'],$forum['_moderator'])=$Forum->Moderator->ByIds($forum['moderators'],array('movet','move','deletet','delete','edit','chstatust','chstatus','pin','mmove','mdelete','user_warn','viewip','opcl','merge','editq','mchstatus'),$Eleanor->mconfig['n'].'_moders_t'.$forum['id']);
			else
				$forum['moderators']=$forum['_moderator']=array();

			if($Forum->user)
			{
				$gp=$gt=array();
				$ingp=false;
			}
			else
			{
				$gp=$Forum->GuestSign();
				$gt=$Forum->GuestSign('t');
				$ingp=$gp ? Eleanor::$Db->In($gp) : false;
			}

			$forum['_mstatus']=$Forum->ugr['supermod'] || ($forum['_moderator'] ? (in_array(1,$forum['_moderator']['chstatus']) or in_array(1,$forum['_moderator']['mchstatus'])) : false);
			$topic['_ismy']=$Forum->user ? $Forum->user['id']==$topic['author_id'] : in_array($topic['id'],$gt);
			$topic['_open']=$topic['state']=='open' || $Forum->ugr['supermod'] || in_array(1,$rights['canclose']);

			if(!isset(OwnBB::$replace['quote']))
			{
				if(!class_exists('ForumBBQoute',false))
					include$Eleanor->module['path'].'Misc/bb-quote.php';
				OwnBB::$replace['quote']='ForumBBQoute';
			}
		}

		if($Forum->user)
		{
			$topic['_read']=$Forum->user['allread'];
			$R=Eleanor::$Db->Query('SELECT UNIX_TIMESTAMP(`allread`),`topics` FROM `'.$Eleanor->mconfig['re'].'` WHERE `f`='.$forum['id'].' AND `uid`='.$Forum->user['id'].' LIMIT 1');
			if(list($allr,$trs)=$R->fetch_row())
			{
				$trs=$trs ? (array)unserialize($trs) : array();
				$tr=isset($trs[$topic['id']]) ? $trs[$topic['id']] : 0;
				$topic['_read']=max($topic['_read'],$tr,$allr);
			}
			else
			{
				$trs=array();
				$allr=0;
			}
		}

		$authors=$attaches=$posts=$waitposts=array();
		$pp=$Forum->GetOption('ppp');

		$esd=Eleanor::$Db->Escape($sd);
		if($Forum->user)
			$lq='SELECT `id`,`status`,`author`,`author_id`,`ip`,`created`,`sortdate`,`who_edit`,`who_edit_id`,`edit_date`,`edit_reason`,`text`,UNIX_TIMESTAMP(`sortdate`) `_sd` FROM `'.$Eleanor->mconfig['fp'].'` WHERE 't'='.$topic['id'].' AND `status`='.($topic['status']==1 ? -1 : -3).($forum['_mstatus'] ? '' : ' AND `author_id`='.$Forum->user['id']).' AND `sortdate`>FROM_UNIXTIME('.$esd.') ORDER BY `sortdate` ASC LIMIT '.$pp;
		elseif($ingp)
			$lq='SELECT `id`,`status`,`author`,`author_id`,`ip`,`created`,`sortdate`,`who_edit`,`who_edit_id`,`edit_date`,`edit_reason`,`text`,UNIX_TIMESTAMP(`sortdate`) `_sd` FROM `'.$Eleanor->mconfig['fp'].'` WHERE 't'='.$topic['id'].' AND `status`='.($topic['status']==1 ? -1 : -3).' AND `id`'.$ingp.' AND `sortdate`>FROM_UNIXTIME('.$esd.') ORDER BY `sortdate` ASC LIMIT '.$pp;
		else
			$lq=false;

		#($topic['status']==1 ? '>=0' : 'IN(0,-2)')>=0 эквивалентно IN (0,1)
		$fq='SELECT `id`,`status`,`author`,`author_id`,`ip`,`created`,`sortdate`,`who_edit`,`who_edit_id`,`edit_date`,`edit_reason`,`text`,UNIX_TIMESTAMP(`sortdate`) `_sd` FROM `'.$Eleanor->mconfig['fp'].'` WHERE 't'='.$topic['id'].($forum['_mstatus'] ? ' AND `status`'.($topic['status']==1 ? '>=0' : 'IN(0,-2)') : ' AND `status`='.($topic['status']==1 ? 1 : -2)).' AND `sortdate`>FROM_UNIXTIME('.$esd.') ORDER BY `sortdate` ASC LIMIT '.$pp;

		$sd=0;
		$forum['_rights']=$Forum->ForumRights($forum['id']);
		$R=Eleanor::$Db->Query($fq && $lq ? '('.$fq.')UNION ALL('.$lq.')' : $fq.$lq);
		while($a=$R->fetch_assoc())
		{
			if($a['author_id'])
				$authors[]=(int)$a['author_id'];
			$attaches[]=$a['id'];
			switch($a['status'])
			{
				case -3;
					$a['status']=-1;
				break;
				case -2:
					$a['status']=1;
			}
			$a['_n']=++$n;
			$a['text']=OwnBB::Parse($a['text']);
			$a['_rights']=array();
			$a['_rights']['mod']=$a['_rights']['edit']=$a['_rights']['delete']=$a['_rights']['move']=$a['_rights']['post']=$Forum->ugr['supermod'];
			if(!$Forum->ugr['supermod'])
			{
				if($Forum->user and $a['author_id']==$Forum->user['id'] or !$Forum->user and in_array($a['id'],$gp))
				{
					$mined=min($forum['_rights']['editlimit']);
					if($mined==0 or time()-strtotime($values['created'])<=$mined)
					{
						$a['_rights']['edit']=in_array(1,$forum['_rights']['edit']);
						$a['_rights']['delete']=in_array(1,$forum['_rights']['delete']);
					}
				}
				if($topic['_ismy'] and in_array(1,$forum['_rights']['mod']))
					$a['_rights']['mod']=true;
				$a['_rights']['post']=($topic['_ismy'] and in_array(1,$forum['_rights']['post']) or !$topic['_ismy'] and in_array(1,$forum['_rights']['apost']));
				if($forum['_moderator'])
				{
					$a['_rights']['edit']|=in_array(1,$forum['_moderator']['edit']);
					$a['_rights']['delete']|=in_array(1,$forum['_moderator']['delete']);
					$a['_rights']['move']=in_array(1,$forum['_moderator']['move']);
				}
			}
			if($Forum->user)
				$topic['_read']=max($topic['_read'],strtotime($a['created']));
			if($sd<$a['_sd'])
				$sd=$a['_sd'];
			$posts[]=$a;
		}

		if(!$posts)
		{
			Result(false);
			break;
		}

		if($Forum->user and (!isset($tr) or $tr<$topic['_read']))
		{
			$trs[$topic['id']]=$topic['_read'];
			asort($trs,SORT_NUMERIC);
			if(count($trs)>$Eleanor->mconfig['readslimit'])
			{
				$allr=max($allr,min($trs));
				array_splice($trs,$Eleanor->mconfig['readslimit']);
			}
			Eleanor::$Db->Replace($Eleanor->mconfig['re'],array('uid'=>$Forum->user['id'],'f'=>$forum['id'],'allread'=>$allr,'topics'=>serialize($trs)));
		}
		unset($allr,$trs);

		$first=reset($attaches);
		$R=Eleanor::$Db->Query('SELECT `id`,`p`,`downloads`,`filesize`,`filename`,`file`,`preview` FROM `'.$Eleanor->mconfig['fa'].'` WHERE `p`'.Eleanor::$Db->In($attaches));
		$uposts=$ag=$attaches=array();
		while($a=$R->fetch_assoc())
			$attaches[$a['p']][$a['id']]=array_slice($a,1);

		if($attaches)
			foreach($posts as &$v)
				if(isset($attaches[$v['id']]))
					$Forum->Attach->ParseAttaches($v['text'],$attaches[$v['id']]);

		Eleanor::LoadOptions('user-profile');
		if($authors)
		{
			$do=false;
			include_once$Eleanor->module['path'].'user/topic.php';
			$ag=GetAuthors($authors,$forum);
			foreach($ag[0] as $k=>&$v)
				$uposts[$k]=$v['posts'];
		}

		Eleanor::$Template->queue[]='ForumTopic';
		unset(OwnBB::$replace['quote']);
		Result(array(
			'posts'=>Eleanor::$Template->AjaxLNP($posts,$attaches,$ag,$topic,$forum),
			'lp'=>$sd,
			'n'=>$n,
			'uposts'=>$uposts,
			'first'=>$first,
			'post'=>isset($post) ? $post : false,
		));
	break;
	default:
		$no=true;
}
if($no)
{
	$no=false;
	switch($ev)
	{
		case'edit':#Правка поста
			$values=GetPost();
			if(!$values)
			{
				Error();
				break;
			}

			if(!isset(OwnBB::$replace['quote']))
			{
				if(!class_exists('ForumBBQoute',false))
					include$Eleanor->module['path'].'Misc/bb-quote.php';
				OwnBB::$replace['quote']='ForumBBQoute';
			}

			$values['_uploader']='temp/'.($Forum->user ? $Forum->user['id'].'-' : '').$Eleanor->mconfig['n'].'-post-'.$values['id'];
			try
			{
				$values+=$Forum->Post->EditPost($values['id'],$values['_uploader']);
			}
			catch(EE$E)
			{
				Error();
				break;
			}
			$hidden=array(
				'postsign'=>md5(md5($values['text']).$values['edit_reason']),
			);

			if(Eleanor::$Permissions->MaxUpload()!==false)
			{
				$Eleanor->Uploader->watermark=$Eleanor->Uploader->previews=true;
				$Eleanor->Uploader->allow_walk=false;
				$Eleanor->Uploader->buttons_top=array('update'=>true,'show_previews'=>true);
				$values['_uploader']=$Eleanor->Uploader->Show($values['_uploader']);
				$hidden['s']=session_id();
			}
			else
				unset($values['_uploader']);

			Eleanor::$Template->queue[]='ForumPost';
			Result(Eleanor::$Template->AjaxEditPost($values,$hidden));
		break;
		case'save':#Сохранение поста
			$values=GetPost('s');
			if(!$values)
			{
				Error();
				break;
			}

			if(!isset(OwnBB::$replace['quote']))
			{
				if(!class_exists('ForumBBQoute',false))
					include$Eleanor->module['path'].'Misc/bb-quote.php';
				OwnBB::$replace['quote']='ForumBBQoute';
			}

			$values['edit_reason']=isset($_POST['edit_reason']) ? (string)Eleanor::$POST['edit_reason'] : '';
			$values['text']=trim($Eleanor->Editor->GetHTML('text'));
			if(mb_strlen($values['text'])<5)
			{
				Error(sprintf('Минимальная длина поста составляет %s символов.',5));
				break;
			}
			$hidden=isset($_POST['h']) ? (array)$_POST['h'] : array();
			$files=(Eleanor::$Permissions->MaxUpload()!==false and isset($hidden['s']));
			if($files)
				$values['_files']=$Eleanor->Uploader->WorkingPath('',$hidden['s']);

			if(isset($hidden['postsign']) and $hidden['postsign']!=md5(md5($values['text']).$values['edit_reason']))
			{
				$me=$Forum->user ? Eleanor::$Login->GetUserValue(array('name','id')) : array('name'=>$values['author'],'id'=>0);
				$values+=array(
					'who_edit'=>$me['name'],
					'who_edit_id'=>$me['id'],
					'edit_date'=>date('Y-m-d H:i:s'),
				);
			}

			Eleanor::$Template->queue[]='ForumPost';
			try
			{
				$values=$Forum->Post->SavePost($values);
				Result(array('text'=>OwnBB::Parse($values['text']),'edited'=>isset($values['who_edit']) ? Eleanor::$Template->Edited($values) : false));
			}
			catch(EE_SQL$E)
			{
				$E->LogIt($E->addon['logfile'],$E->getMessage());
				Error($E->getMessage());
			}
			catch(EE$E)
			{
				Error($E->getMessage());
			}
		break;
		case'delete':#Удаление поста
			$values=GetPost('d');
			if(!$values)
			{
				Error();
				break;
			}
			$Forum->Moderate->DeletePost($values['id']);
			Result('ok');
		break;
		default:
			$no=true;
	}
}

if($no)
	Error();

/*
	e - правка
	s - сохранение
	d - удаление
*/
function GetPost($t='e')
{global$Eleanor;
	$do=false;
	include_once$Eleanor->module['path'].'user/post.php';
	$id=isset($_POST['id']) ? (int)$_POST['id'] : 0;
	$R=Eleanor::$Db->Query('SELECT `id`,'t',`status`,`author_id`'.($t=='s' ? ',`author`,`edit_reason`' : '').($t=='d' ? ',`sortdate`' : '').' FROM `'.$Eleanor->mconfig['fp'].'` WHERE `id`='.$id.' LIMIT 1');
	if(!$values=$R->fetch_assoc())
		return false;

	$R=Eleanor::$Db->Query('SELECT `id`,`uri`,`f`,`status`,`author_id`,`state`,`title` FROM `'.$Eleanor->mconfig['ft'].'` WHERE `id`='.$values['t'].' LIMIT 1');
	if(!$topic=$R->fetch_assoc() or !$Forum->CheckTopicAccess($topic))
		return false;

	if(!list($forum,$rights)=GetForum($topic['f']))
		return false;

	$trights=TopicRights($topic,$forum['_moderator'],$rights);
	$prights=PostRights($values,$forum['_moderator'],$rights);

	if($t=='d')
	{
		if(!$prights['mod'] and (!$trights['delete'] or !$prights['delete']))
			return false;
		if(!$trights['deletet'] and $values['author_id']==$topic['author_id'])
		{
			$R=Eleanor::$Db->Query('SELECT `id` FROM `'.$Eleanor->mconfig['fp'].'` WHERE 't'='.$values['t'].' AND `sortdate`<=\''.$values['sortdate'].'\' AND `id`!='.$id.' LIMIT 1');
			if($R->num_rows()==0)
				return false;
		}
	}
	else
	{
		if(!$prights['mod'] and (!$trights['edit'] or !$prights['edit']))
			return false;

		if(!isset(OwnBB::$replace['quote']))
		{
			if(!class_exists('ForumBBQoute',false))
				include$Eleanor->module['path'].'Misc/bb-quote.php';
			OwnBB::$replace['quote']='ForumBBQoute';
		}
	}
	return$values;
}