<?
  Global $sape_links;

  require_once('define.php');
  require_once('functions.php');
  require_once('funcs2.php');
  require_once('fuphotos.php');
  require_once('forgroups.php');
  require_once('connect.php');

  $mainurl = '/f/';
  $rec_type_forums = array(1=>10);

  $wronglist = array('small','materialy-del.ru','w.sarov24.ru','foreign-countries','vesti.','gazeta-');

  $forum = 0;
  $topic = isset($_GET['t'])?intval($_GET['t']):0;
  $edid = isset($_GET['edid'])?intval($_GET['edid']):(isset($_POST['edid'])?intval($_POST['edid']):0);
  $act	= isset($_GET['act'])?$_GET['act']:(isset($_POST['act'])?$_POST['act']:'');
  $form = isset($_GET['f'])?trim($_GET['f']):(isset($_POST['f'])?trim($_POST['f']):'');
  $page = isset($_GET['p'])?intval($_GET['p']):0;
  $s	= isset($_GET['s'])?trim($_GET['s']):'';
  $num  = 50; // тем на странице
  if($page<1)$page=1;

  $uri = getenv('REQUEST_URI');
  $uri = str_replace($mainurl,'',$uri);
  $uri = trim($uri,'/');
  $caturi = search('/'.$uri.'/','/','/');
  
  //
  // Список форумов
  //
  $forlist = array();	// сохраним список для дальнейшей работы
  $foroptions = '';		// формируем выпадающий список в виде html
  $curgroup = -1;
  $r = my_mysql_query('SELECT * FROM com_list ORDER BY ord');
  while($fetch = mysql_fetch_object($r))
   {
	if($curgroup != $fetch->group)
	 {
	  $curgroup = $fetch->group;
	  $foroptions.= '<option value="">- - - '.$forgroups[$curgroup].'</option>';
	 }
	$forlist[$fetch->id] = $fetch;
	if($caturi && $caturi==$fetch->url)
	  $forum = $fetch->id;
	if($fetch->show4all)
	  $foroptions.= '<option value="'.$mainurl.$fetch->url.'/"'.($forum==$fetch->id?' selected':'').'>'
	  	.$fetch->name.(intval($fetch->last_comment)?' - '.ShortMonth($fetch->last_comment,'nospan'):'')
		.'</option>';
   }
  $forselect = '<select style="font-size:11px" onChange="window.location=this.value">'.$foroptions.'</select>';;
  $forum_new = '<a href="?f=new">Новая тема</a>';
  $forum_menu = $forselect.' | '.$forum_new;

  // RSS
  if(substr($uri,strlen($uri)-3)=='rss' || isset($RSS) || isset($RSSFULL) )
   {
	$title = 'Форумы Саров.Net'.($forum? ': '.$forlist[$forum]->name :'');
	$desc = 'Новые темы на форумах www.sarov.net';
	$kolvo = 30;
	$list = array();
	$r = my_mysql_query('SELECT id,forum_id,title,time,comments,mess FROM com_topics WHERE '
		.($forum?'forum_id='.$forum.' AND ':'')
		.'published=1 ORDER BY time DESC LIMIT '.$kolvo);
	$userurl = trim($httpwwwsarovnet,'/').$mainurl;
	while($item = mysql_fetch_object($r))
	 {
	  $url = $userurl.$forlist[$item->forum_id]->url.'/?t='.$item->id;
	  $mess = mess_cut(pre_message($item->mess,false)).' <a href="'.$url.'">далее &raquo;</a>';
	  $temp = array(
    	'url'		=> $url,
    	'time'		=> $item->time,
    	'subject'	=> $item->title,
    	'mess'		=> $mess
		);
	  $list[] = $temp;
	 }
	$imageurl = $httpwwwsarovnet.'i/l.gif';
	include('rssfeed.php');
	return;
   }

  //
  // Сохраняем новый или старый топик
  //
  if($act=='savetopic')
   {
	$tit = isset($_POST['title'])?$_POST['title']:'';
	$messid = isset($_POST['mess'])?intval($_POST['mess']):'';
	$mess   = isset($_POST['mess'.$messid])?$_POST['mess'.$messid]:'';
	$errmess = '';
	if(!$login_id)
	 {
	  $errmess = '<a href="#" onclick="login_form()">Войдите на сайт</a>';
 	 }
	elseif(!$forum)
	 {
	  $errmess = 'Не удалось определить форум';
 	 }
	elseif(empty($tit))
	 {
	  $errmess = 'Не указан заголовок';
 	 }
	elseif(empty($mess))
	 {
	  $errmess = 'Пустое поле текста';
 	 }
	// проверка бана
	$r=my_mysql_query("SELECT date2 FROM comments_ban WHERE date2>'".date('Y-m-d')."' AND nick_id=".$login_id);
	if($fetch=mysql_fetch_array($r))
	 {
	  $errmess = 'Вам запрещено оставлять сообщения на сайте до '.FullDate($fetch['date2']);
	 }
	// сохраняе
	if(!$errmess)
	 {
	  $badwords = mystrtolower(file_get_contents('../c/badwords.txt'));
	  $badwords = explode("\n", $badwords);
	  $tmpmess = mystrtolower($mess);
	  foreach($badwords as $tmp)
	   if(strpos($tmpmess, $tmp)!==false)
	    return;

	  if(!$edid) // новый топик
	   {
		my_mysql_query('INSERT INTO com_topics SET forum_id='.$forum.', 
			nick_id='.$login_id.', nick_txt="'.sql($c_l).'", nick_avatar="'.sql($login_avatar).'", 
			time=NOW(), title="'.sql($tit).'", mess="'.sql($mess).'", 
			published=1, last_comment=NOW()');
		$edid = mysql_insert_id();
		if($forum) // обновление в записи форума
			my_mysql_query('UPDATE com_list 
				SET topics=topics+1, last_comment=NOW(),
				last_topic_id='.$edid.',
				last_topic_title="'.sql($tit).'" WHERE id='.$forum);
		uphotos_addnew('com_topics',$edid);
	   }
	  else // правка старого
		my_mysql_query('UPDATE com_topics SET et=NOW(), title="'.sql($tit).'", mess="'.sql($mess).'" WHERE id='.$edid);
	  header('Location: '.$mainurl.$forlist[$forum]->url.'/?t='.$edid,true,301);
	  exit();
     } else $form='new';
	$edid = 0;
   }

  //
  // Задан топик
  //
  $topic_not_found = false;
  if($topic)
   {
	$r = my_mysql_query('SELECT * FROM com_topics WHERE id='.$topic.($login_level<5?' AND published=1':''));
	$topic_rec = mysql_fetch_object($r);
	if($topic_rec && $forum==0)
	 {
	  header('Location: '.$mainurl.$forlist[$topic_rec->forum_id]->url.'/?t='.$topic,true,301);
	  exit();
 	 }
	elseif(!$topic_rec)
	 {
	  $topic=0;
	  $topic_not_found = true;
	 }
   }

  $correct_uri = '';
  if($forum) $correct_uri .= $forlist[$forum]->url.'/';
  if($topic) 
   {
	 $correct_uri .= '?t='.$topic;
	 if($uri != $correct_uri)
	  {
		header('Location: '.$mainurl.$correct_uri,true,301);
		return;
	  }
   }





  $TITLE = ($topic? my_htmlspecialchars($topic_rec->title).' :: ':'') 
  		 . 'Форумы'.($forum? ': '.$forlist[$forum]->name :'');
  $SCRIPT_STYLE = '<STYLE type="text/css">
#content th{
	padding:5px;
}
.forum img {
	max-width:600px;
	max-height:800px;
}
.frow td {
	border-top:1px solid #ccc;
}
.frow:hover {
	background-color:#f4f4f4;
	cursor:pointer;
}
.frow a {
    color:#009;
	text-decoration:none;
}
.frow:hover a, .frow a:visited:hover {
	color:#ef2929;
}
.frow a:visited, .frow a.v {
	color:#b0b;
}
.ftitle {
	width:450px; /* mobile: */
	font-size:13px;
}
.ftitle a,.ftitle a:hover{
	text-decoration:none;
	display:block;
	padding:7px 0 7px 3px;
}
.frow td.fcol{
	width:70px;
	padding-left:15px;
	color:#999;
	font-size:17px;
}
.fcol small{
	font-size:10px;
}
.leftlist a{
	display:block;
	font-size:11px;
	text-decoration:none;
	border-top:1px solid #ddd;
	padding-top:5px;
	margin-top:10px;
}
.leftlist a:visited{
	color:#b0b;
}
.leftlist a:visited:hover{
	color:#ef2929;
}
.leftlist a small{
	color:#999;
}

.asel {
    background:url("/i/asel.gif") no-repeat scroll right center transparent;
    cursor:pointer;
    padding-right:20px;
    display:inline;
}
</STYLE>
<script type="text/javascript">
function for_sel()
{
  
}
</script>
';
  $RSSFEED = trim($httpwwwsarovnet,'/').$mainurl.($forum?$forlist[$forum]->url.'/':'').'rss';
  $RSSTITLE = 'Новые темы '.($forum?'этого раздела ':'всех разделов ').'форума по RSS';
  require_once('html_1.php');

  echo '<h1><a href="'.$mainurl.'">Форумы</a>';
  if($forum)
  	echo ': <a href="'.$mainurl.$forlist[$forum]->url.'/">'.$forlist[$forum]->name.'</a>'
	  			.($page>1?': Страница '.$page:'');
  echo '</span>';
  echo ' &nbsp;'.rss_button($RSSFEED,$RSSTITLE);
  echo '</h1>';






  //
  // Новая тема
  //  
  if(($form=='new'||$edid)&&!$login_id)
   {
	echo '<h1>Создать новую тему</h1><p>Если вы уже зарегистрированы на сайте &mdash; просто <a href="#" onClick="login_form()">войдите</a>.</p><p>Если у вас есть аккаунт в одной из социальных сетей, войдите через него:</p><p>';
	echo ss_buttons();
	echo '</p><p>Или зарегистрируйтесь у нас <a href="'.$httpwwwsarovnet.'register/">обычным способом</a>.</p>';
   }
  elseif($form=='new'||$edid)
   {
   	if($edid)
   	 {	 	
	  $r = my_mysql_query('SELECT * FROM com_topics WHERE id='.$edid);
	  $edit = mysql_fetch_object($r);
 	 }
?>
<script type="text/javascript">
function check_form(frm)
{
	if(frm.title.value.replace(/\s/gi,'')=='')
     {
	  alert('Вы не указали заголовок вашего сообщения.');
	  frm.title.focus();
      return false;
     }
	if(frm.mess.value.replace(/\s/gi,'')=='')
     {
	  alert('Вы должны ввести текст.');
	  frm.mess.focus();
      return false;
     }
	if(frm.mess.length>65000)
     {
	  alert('Ну оооочень большое сообщение. Попробуйте разбить его на части.');
	  frm.mess.focus();
      return false;
     }
	return true;
}

</script>
<h2><?=($edid?'Редактирование':'Создать новую тему')?></h2>
<form action="" method="post" onsubmit="return check_form(this)" onkeypress="ctrlEnter(event,this)">
<input type="hidden" name="act" value="savetopic">
<input type="hidden" name="mess" value="<?=($messid=rand(1,999999))?>">
<input type="hidden" name="edid" value="<?=($edid?$edid:0)?>" autocomplete="off">
<h3>Заголовок:</h3>
<input type="text" name="title" style="width:500px" value="<?=($edid?my_htmlspecialchars($edit->title):'')?>" size="70"><br>
<small style="color:#888">Постарайтесь кратко сформулировать о чем ваше сообщение. <span onclick="this.removeNode(1);$('hid123').style.display='inline'" class="a">еще...</span><div id="hid123" style="display:none"><br>
Не надо называть его "помогите!!!" или "вопрос???". <br>
Если вам нужна помощь &mdash; объясните: с чем именно: "помогите выбрать ноутбук".<br> 
Если вы хотите задать вопрос &mdash; задавайте сразу в заголовке: "Где купить коньки?"</small></div><br>
<br>
<h3>Текст:</h3>
<textarea name="mess<?=$messid?>" rows="5" cols="70" style="width:500px" id="comment_area"><?=($edid?my_htmlspecialchars($edit->mess):'')?></textarea>
<script type="text/javascript">load_e()</script>
<br>
<input type="submit" value="Готово">
</form>
<?
	upload_form('com_topics',$edid);
   }






  //
  // Страница одной темы
  //
  elseif($topic_not_found)
   {
	echo '<h1>Тема не найдена. Возможно, она была удалена.</h1>';
   }
  elseif($topic)
   {
    if(!defined('MOBILE'))
     {
	echo '<table cellspacing="0" cellpadding="0" border="0"><tr valign="top"><td width="170"><div class="leftlist"><h3>Последние на форуме:</h3>';
	$cachefile = WorkDir.'_cache/f'.$forum;
	if(false)//file_exists($cachefile))
	  echo file_get_contents($cachefile);
	else
	 {
		//$tmp = '';
		$r = my_mysql_query('SELECT id,title,comments,last_comment FROM com_topics WHERE forum_id='.$forum.' AND published=1 ORDER BY last_comment DESC LIMIT 15');
		while($f = mysql_fetch_object($r))
		  echo '<a href="?t='.$f->id.'#'.$f->comments.'">'.my_htmlspecialchars($f->title).'<br><small>'.ShortMonth($f->last_comment).'</small></a> ';
		echo '<a style="text-align:right" href="">Все темы форума&nbsp;&raquo;</a>';
		//file_put_contents($cachefile,$tmp);
		//echo $tmp;
	 }
	echo '</div>';
	if( isset($sape_links) && !empty($sape_links) )
		echo '<div class="clearfix"><br><hr><small>Реклама: '.$sape_links.'</small></div>';
	$sape_links = '';
	echo '</td><td width=20>&nbsp;</td><td width="500" class="forum">';
	} //     if(!defined('MOBILE'))

	//// / / /
	// 
	//
	echo '<div class="smallh" style="background-color:#eee;padding:5px">';
	$userlink = $topic_rec->nick_id? '<a target="_blank" href="/users/?id='.$topic_rec->nick_id.'">' : '';
	if($topic_rec->nick_avatar)
	  echo $userlink.'<img src="'
	  	.(strpos($topic_rec->nick_avatar,'/')!==false?'':'/p/u/').$topic_rec->nick_avatar
 		.'" width="50" alt="" align="left" style="padding:5px 10px 0 0">'.($userlink?'</a>':'');
	echo '<h1 style="padding-top:0">'.my_htmlspecialchars($topic_rec->title).'</h1>';
	echo $userlink.'<b>'.my_htmlspecialchars($topic_rec->nick_txt).'</b>'.($userlink?'</a>':'');
	echo ' - '.ShortMonth($topic_rec->time);
	echo (intval($topic_rec->et)?' [правка: '.ShortMonth($topic_rec->et).']':'');
	if($topic_rec->published==0)
	  echo ' - <span style="color:red"><b>УДАЛЕН</b></span>';
	if(!$topic_rec->rec_type)
	 if(($topic_rec->nick_id&&$topic_rec->nick_id==$login_id)||$login_level>4)
	  echo ' - <a href="?edid='.$topic.'">Правка</a>';
	echo '</div>';

	if($login_level>4) // Модераторская панелька
	 {
	  echo '<div style="border:6px solid #ccc;padding:5px">Модератор: 
		<a href="'.$mainurl.'mod.php?c=pinm&t='.$topic.'">[-]</a> ('.$topic_rec->pinned.')
		<a href="'.$mainurl.'mod.php?c=pinp&t='.$topic.'">[+]</a>
		| <a href="'.$mainurl.'mod.php?c=del&t='.$topic.'">Удалить</a>
		| Перенести в <select style="font-size:11px" onChange="window.location=\''.$mainurl.'mod.php?c=move&t='.$topic.'&f=\'+this.value"><option value="">- - -</option>';
	  foreach($forlist as $f)
	   if($f->show4all)
	    echo '<option value="'.$f->id.'">'.$f->name.'</option>';
	  echo '</select></div>';
	 }
	
	// текст
	echo '<div style="padding:15px 0">';
	echo pre_message($topic_rec->mess);
	// mess_cut($topic_rec->mess).' <a href="'.rec_type_url($topic_rec_type,$topic).'">Читать далее &raquo;</a>'
	echo '</div>';

	$rec_type = $topic_rec->rec_type?$topic_rec->rec_type:'com_topics';
	$rec_id	  = $topic_rec->rec_type?$topic_rec->rec_id:$topic;

	votes($rec_type,$rec_id, 
		$topic_rec->rec_type?'':$topic_rec->vminus, 
		$topic_rec->rec_type?'':$topic_rec->vplus, '','');
	share_buttons($mainurl.$forlist[$forum]->url.'/?t='.$topic, $topic_rec->title);

	uphotos_view($rec_type,$rec_id);

	comments($rec_type,$rec_id,array('nocomment'=>'','comments'=>''));

	echo '<hr>'.$forum_menu;
	
    if(!defined('MOBILE'))
	  echo '</td><td>';
	echo '<div style="float:right">';
	include('banner_right.php');
	echo '</div>';
  
    if(!defined('MOBILE'))
	  echo '</td></tr></table>';

	my_mysql_query('UPDATE com_topics SET views=views+1 WHERE id='.$topic);
   }






  //
  // Список тем форума
  //
  
  elseif($forum)
   {
	$limit = ($page==1) ? $num : ($page-1)*$num.','.$num;
	
	if($page==1 && empty($s) && $forum==10)
	  $pages = 6;
	else
	  list($page,$pages) = paginationcnt('SELECT COUNT(*) FROM com_topics WHERE forum_id='.$forum.' AND published=1',$page,$num);

	$list = array();
	$r = my_mysql_query('SELECT id,rec_type,rec_id,pinned,movedto,nick_id,nick_txt,time,title,mess,comments,last_comment,views FROM com_topics WHERE forum_id='.$forum.' AND published=1 ORDER BY pinned DESC,last_comment DESC LIMIT '.$limit);
	while($fetch = mysql_fetch_object($r))
	  $list[$fetch->time.$fetch->id] = $fetch;

	echo $forum_new.'<hr>';

	if(count($list)==0)
	 {
	  echo '<h1>В этом форуме пока нет ни одной темы</h1>';
 	 }
	else
	 {
	  echo '<table cellspacing="0" cellpadding="0" border="0">';
	  echo '<tr><th>тема</th><th colspan=2>сообщения</th></tr>';
	  foreach($list as $item)
	   {
		$prev_visit = comments_readed($item->rec_type,$item->rec_id);
		if($item->movedto)
		  $url = $mainurl.'?t='.$item->movedto;
		else
		  $url = '?t='.$item->id;
		//if(isset($item->rec_type)&&$item->rec_type) 
		  //$url = '?r='.$item->rec_type.'&t='.$item->id;
		echo '<tr class="frow" onClick="window.location=\'?t='.$item->id.'\'"><td class="ftitle">'
			.'<a '.(timeSQL2UNIX($item->last_comment)<$prev_visit?'class="v" ':'')
				.'href="'.$url.'#'.$item->comments.'">'
				.($item->pinned?str_repeat('&raquo;&raquo;',$item->pinned).' ':'')
				.($item->movedto?'Перемещена: ':'')
				.$item->title.'</a></td><td class="fcol">'.$item->comments
			.(isset($item->views)?'<small>...' . ($item->views>10000 ? round($item->views/1000,0).'K' : $item->views) .'</small>':'')
			.'&nbsp;&nbsp;</td><td width="120">'.ShortMonth($item->last_comment).'</td></td>';
	   }
	  echo '<tr><td colspan="3" style="border-top:1px solid #ccc"><img src="/i/b.gif" width="1" height="1" alt="1"></td></tr>';
	  echo '</table>';
	 }
	pagination('<a href="'.$mainurl.$forlist[$forum]->url.'/?p=',$page,$pages);

	echo '<hr>'.$forum_menu;
   }






  //
  // Главная страница
  //
  else
   {
    if($login_level>4)
      echo '<a href="update.php">Обновить список</a><hr>';
	echo '<table cellspacing="0" cellpadding="5" border="0">
		<tr><td width="450">&nbsp;</td><td>тем</td><td>последняя</td></tr>';
	$curgroup =-1;
	foreach($forlist as $fid=>$f)
	if($f->show4all)
	 {
	  if($curgroup != $f->group)
	   {
		$curgroup = $f->group;
		echo '<tr><td colspan="3" style="background-color:#f4f4f4;text-align:center">'.$forgroups[$curgroup].'</td></tr>';
	   }
	  echo '<tr><td><h1 style="padding:0"><a href="'.$mainurl.$f->url.'/">'.$f->name.'</a></h1>';
	  echo pre_message($f->mess).'</td><td><h3>'.$f->topics.'</h3></td><td width="120">'.ShortMonth($f->last_comment).'<br><small><a class="n" href="'.$mainurl.$f->url.'/?t='.$f->last_topic_id.'">'.my_htmlspecialchars($f->last_topic_title).'</a></small></td></tr>';
	 }
	echo '</table>';
	echo '<hr><a href="/forums/"><small>Старые форумы</small></a>';
   }

  require_once('html_2.php');
?>