<?php


defined('_IN_JOHNCMS') or die('Error: restricted access');

if ($user_id){
  $lastPost = explode(':|:', $topicRes['lastpost']);
  $readedReq = mysql_query("SELECT * FROM `forum_readed` WHERE `topic` = '$topic' AND `user_id` = '$user_id' LIMIT 1 ");
  if (mysql_num_rows($readedReq) > 0){
    $readedRes = mysql_fetch_assoc($readedReq);
    if ($topicRes['time'] > $readedRes['time'] || $readedRes['page'] != $page)
      mysql_query("UPDATE `forum_readed` SET `time` = '".time()."', `lastpost` = '".$lastPost['1']."' WHERE `topic` = '$topic' AND `user_id` = '$user_id' ");
  }else{
    mysql_query("INSERT INTO `forum_readed` SET  `topic` = '$topic', `user_id` = '$user_id', `time` = '".time()."', `lastpost` = '".$lastPost['1']."' ");
  }
}

echo forum_counter();

$tree = array('<a href="index.php">Форум</a>', '<a href="index.php?forum='.$topicRes['forum'].'">'.functions::checkout($topicRefid['forumname']).'</a>');
echo '<div name="up" id="up" class="phdr"><a href="#down"><img src="../images/down.png" alt="Вниз" width="20" height="10" border="0"/></a> '.functions::display_menu($tree).'</div>';
echo '<div class="themn" style=" font-weight:bold; padding:10px; font-size:16px; ">';
echo functions::checkout($topicRes['topicname']);
echo'</div>';
if ($topicRes['close'])
  echo '<div class="rmenu">Тема закрыта!</div>';

if ($topicRes['poll_name']){
  if ($user_id)
    $pollCheck = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_polled` WHERE `topic` = '$topic' AND `user_id` = '$user_id' LIMIT 1 "), 0);
  
  echo '<div class="gmenu"><strong>'.functions::checkout($topicRes['poll_name']).'</strong><br />';
  if (!$pollSet['poll_close'] && !isset($_GET['results']) && $user_id && $pollCheck == 0 && !$topicRes['close']){
    echo '<form action="index.php?act=poll&amp;topic='.$topic.'&amp;page='.$page.'" method="post">';
    while ($pollRes = mysql_fetch_assoc($pollReq)){
      echo '<label><input type="'.($pollSet['poll_mod'] < 1 ? 'radio' : 'checkbox').'" name="var[]" value="'.$pollRes['id'].'" /> '.functions::checkout($pollRes['variantname']).'</label><br />';          
    }
    echo '<input type="submit" name="poll" value="Отдать голос" /><br /><a href="index.php?topic='.$topic.'&amp;page='.$page.'&amp;results"><strong>Результаты</strong></a></form>';  
  }else{
    echo '<style type="text/css">
.scale {
  border: 1px solid #636869;
  height: 5px;
  margin-bottom: 3px;
  width: 1%;
}

.scaleborder {
  width: 70%;
}</style>';
    echo '<small>';
    while ($pollRes = mysql_fetch_assoc($pollReq)){
      $count = $pollSet['total_polls'] ? round(100 / $pollSet['total_polls'] * $pollRes['count']) : 0;
      if ($count < 30 || $count == 0)
        $color = '#fe5429';
      elseif($count < 60)
        $color = '#fc8b30';
      else
        $color = '#7cca35';
      echo functions::checkout($pollRes['variantname']).' ('.$pollRes['count'].' - '.$count.'%)<div class="scaleborder"><div class="scale" style="'.($count ? 'width: '.$count.'%;' : '').' background: '.$color.'"></div></div>';
    }
    echo '</small><strong>Проголосовало: '.($user_id ? '<a href="index.php?act=polled&amp;topic='.$topic.'">'.$pollSet['total_polled'].'</a>' : $pollSet['total_polled']).'</strong>';
    if ($user_id && !$pollCheck && !$pollSet['poll_close'])
      echo '<br /><a href="index.php?topic='.$topic.'&amp;page='.$page.'"><strong>Отдать голос</strong></a>';
  }
  echo '</div>';
}

$total = $topicRes['count'];
if ($start >= $total){
  // Исправляем запрос на несуществующую страницу
  $start = max(0, $total - (($total % $kmess) == 0 ? $kmess : ($total % $kmess)));
}

if ($total){
  if ($total > $kmess)
    echo '<div class="topmenu">'.functions::display_pagination('index.php?topic='.$topic.'&amp;', $start, $total, $kmess).'</div>';

if ($set_forum['upfp']){
  if (($user_id && !$ban['1'] && !$ban['11'] && !$topicRes['close']) || ($rights == 3 || $rights >= 6)){
    echo '<form id="form" name="form" action="index.php?act=addpost&amp;topic='.$topic.'&amp;page='.$page.'" method="post"><div class="gmenu">';
    if ($set_forum['farea']){
      echo 'Быстрый ответ <img style="cursor: pointer;" onclick="alert(this.title);" src="images/question.png" alt="?" title="Для предпросмотра или прикрепления файлов нажмите на кнопку: Расшир. форма" />:<br />'.bbcode::auto_bb('form', 'text').'<textarea name="text" cols="30" rows="'.$set_user['field_h'].'"></textarea>';
      echo '<br /><input type="submit" name="send" value="Отправить" /> <input type="submit" name="preview" value="Расшир. форма" />';
    }else{
      echo '<input type="submit" value="Написать" />';
    }
    echo '</div></form>';
  }  
}

  if ($topicRes['clip'] && ($set_forum['upfp'] ? $start < (ceil($total - $kmess)) : $start > 0)){
    echo '<div class="user">';
    $firstPost = mysql_fetch_array(mysql_query("SELECT `forum_posts`.*, `forum_posts`.`user` AS `name`, `forum_posts`.`user_id` AS `id`, `users`.`sex`, `users`.`name`, `users`.`rights`, `users`.`lastdate`, `users`.`status`, `users`.`datereg` FROM `forum_posts` LEFT JOIN `users` ON `forum_posts`.`user_id` = `users`.`id` WHERE `forum_posts`.`topic` = '$topic' ORDER BY `forum_posts`.`time` ASC LIMIT 1 "));

    $postHeader .= ' <span class="gray">'.functions::display_date($firstPost['time']).'</span> <a href="index.php?post='.$firstPost['post'].'" title="Ссылка на пост">#1</a>';
    
    $postText = quote(functions::checkout($firstPost['text'], 1, 1));
    if ($set_user['smileys'])
      $postText = functions::smileys($postText, $firstPost['rights'] >= 1 ? 1 : 0);

    if ($firstPost['files']){
      $postFile = mysql_query("SELECT * FROM `forum_files` WHERE `post` = '".$firstPost['post']."' LIMIT ".$firstPost['files']." ");
      $postText .= '<div class="func">Файл(ы):<br />';
      while ($postFileRes = mysql_fetch_array($postFile)){
        $postText .= show_file($postFileRes).'<br />';
      }
      $postText .= '</div>';
    }

    if ($firstPost['edit']){
      $edit = explode(':|:', $firstPost['edit']);
      $postText .= '<div style="font-size: x-small; color: gray">Изменил(а) '.$edit['0'].' '.functions::display_date($edit['1']).($edit['2'] ? '<br />Причина: '.functions::checkout($edit['2'], 2) : '').'</div>';
    }
    
    
    $postSub = '';
    if ((($user_id == $firstPost['user_id']) && !$topicRes['close'] && (!$ban['1'] || !$ban['11'])) || ($rights == 3 || $rights >= 6)){
      $postSub .= '<a href="index.php?act=editpost&amp;topic='.$topic.'&amp;post='.$firstPost['post'].'&amp;page='.$page.'">Изменить</a> <a href="index.php?act=delpost&amp;topic='.$topic.'&amp;post='.$firstPost['post'].'&amp;page='.$page.'">Удалить</a>';
    }

    $postArray = array('header' => $postHeader, 'body' => $postText, 'sub' => $postSub);
    echo functions::display_user($firstPost, $postArray);
    echo '</div>';
  }

  if ($rights == 3 || $rights >= 6){
    echo '<form name="form1" action="index.php?act=delpost&amp;topic='.$topic.'&amp;page='.$page.'" method="post">';
    echo '';
  }    
  
  $i = $set_forum['upfp'] ? ($total - $start) + 1 : $start;   
  
  $req = mysql_query("SELECT `forum_posts`.*, `forum_posts`.`user` AS `name`, `forum_posts`.`user_id` AS `id`, `users`.`sex`, `users`.`rights`, `users`.`lastdate`, `users`.`status`, `users`.`datereg` FROM `forum_posts` LEFT JOIN `users` ON `forum_posts`.`user_id` = `users`.`id` WHERE `forum_posts`.`topic` = '$topic' ORDER BY `forum_posts`.`time` $postOrder LIMIT $start, $kmess ");
  
  while ($res = mysql_fetch_array($req)){
    
    if ($set_forum['upfp']) --$i;
    else ++$i;
    
    echo $i % 2 ? '<div name="p'.$res['post'].'" id="p'.$res['post'].'" class="list2">' : '<div name="p'.$res['post'].'" id="p'.$res['post'].'" class="list1">';
   
    
    $text = quote(functions::checkout($res['text'], 1, 1));
    if ($set_user['smileys'])
      $text = functions::smileys($text, $res['rights'] >= 1 ? 1 : 0);

    if ($res['files']){
      $file = mysql_query("SELECT * FROM `forum_files` WHERE `post` = '".$res['post']."' LIMIT ".$res['files']." ");
      $text .= '<div class="func">Файл(ы):<br />';
      while($fileRes = mysql_fetch_array($file)){
        $text .= show_file($fileRes).'<br />';
      }
      $text .= '</div>';
    }
    
    if ($res['edit']){
      $edit = explode(':|:', $res['edit']);
      $text .= '<div style="font-size: x-small; color: gray">Изменил(а) '.$edit['0'].' '.functions::display_date($edit['1']).($edit['2'] ? '<br />Причина: '.functions::checkout($edit['2'], 2) : '').'</div>';
    }
    
  
    ?>
	<style>.sub {
    border-top: 0px;
    font-size: 16px;
    margin-top: 4px;
}
.sub a{ margin-left:8px; margin-right:8px;}</style><?
    
    $sub = '<a href="index.php?post='.$res['post'].'" title="Ссылка на пост"><i class="fa fa-external-link but" aria-hidden="true"></i></a>';
    if (($user_id && $user_id != $res['user_id'] && !$ban['1'] && !$ban['11'] && !$topicRes['close']) || ($user_id != $res['user_id'] && ($rights == 3 || $rights >= 6))){
      $sub .= '<a href="index.php?act=addpost&amp;post='.$res['post'].'&amp;topic='.$topic.'&amp;page='.$page.'"><i class="fa fa-reply but" aria-hidden="true"></i></a> <a href="index.php?act=addpost&amp;quote&amp;post='.$res['post'].'&amp;topic='.$topic.'&amp;page='.$page.'"><i class="fa fa-quote-right but ska" aria-hidden="true"></i></a>';
    }

    if ((($user_id == $res['user_id'] && !$topicRes['close'] && (!$ban['1'] || !$ban['11']) && $res['time'] > time() - 300) || ($user_id == $res['user_id'] && (!$i && (!$page || $page == 1)))) || ($rights == 3 || $rights >=6)){
      $sub .= ' <a href="index.php?act=editpost&amp;topic='.$topic.'&amp;post='.$res['post'].'&amp;page='.$page.'"><i class="fa fa-pencil" aria-hidden="true"></i></a> <a href="index.php?act=delpost&amp;topic='.$topic.'&amp;post='.$res['post'].'&amp;page='.$page.'"><i class="fa fa-trash" aria-hidden="true"></i></a>';
    }
    if ($rights == 3 || $rights >= 6)
      $sub .= '   <input type="checkbox" name="massdel['.$i.']" value="'.$res['post'].'" /> ';

$sub .='<span style="float:right; font-size:13px;"><i class="fa fa-clock-o" aria-hidden="true"></i> '.functions::display_date($res['time']).'</span>';


    $array = array('header' => $header, 'body' => $text, 'sub' => $sub, 'iphide' => 1,);
 
	echo functions::display_user($res, $array, $arg);
	
    echo '</div>';
    
  }
  
  if ($rights == 3 || $rights >= 6)
    echo '<div class="rmenu"><input type="submit" class="btn btn-default" value="Удал. отмеч." /></div></form>';

}else{
  echo '<div class="list1">Пусто</div>';
}
if (!$set_forum['upfp']){
  if (($user_id && !$ban['1'] && !$ban['11'] && !$topicRes['close']) || ($rights == 3 || $rights >= 6)){
    echo '<form id="form" name="form" action="index.php?act=addpost&amp;topic='.$topic.'&amp;page='.$page.'" method="post"><div class="gmenu">';
    if ($set_forum['farea']){
      echo 'Быстрый ответ <img style="cursor: pointer;" onclick="alert(this.title);" src="images/question.png" alt="?" title="Для предпросмотра или прикрепления файлов нажмите на кнопку: Расшир. форма" />:<br />'.bbcode::auto_bb('form', 'text').'<textarea name="text" cols="30" rows="'.$set_user['field_h'].'"></textarea>';
      echo '<br /><input type="submit" name="send" value="Отправить" /> <input type="submit" name="preview" value="Расшир. форма" />';
    }else{
      echo '<input type="submit" value="Написать" />';
    }
    echo '</div></form>';
  }  
}


if ($total){
  echo '<div  name="down" id="down" class="phdr"><a href="#up"><img src="../images/up.png" alt="Вверх" width="20" height="10" border="0"/></a> Сообщений: '.$total.'</div>';
  if ($total > $kmess){
    echo '<div class="topmenu">'.functions::display_pagination('index.php?topic='.$topic.'&amp;', $start, $total, $kmess).'</div>';
  }
}
echo '<div class="clear"></div';
$onltime = time() - 300;
$online_u = mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `lastdate` > $onltime AND `place` = 'forum,$topic' "), 0);
$online_g = mysql_result(mysql_query("SELECT COUNT(*) FROM `cms_sessions` WHERE `lastdate` > $onltime AND `place` = 'forum,$topic' "), 0);

if ($topicRes['curator']){
  $curator = mysql_fetch_assoc(mysql_query("SELECT `lastdate`, `sex`, `datereg`, `id`, `name` FROM `users` WHERE `id` = '".$topicRes['curator']."' LIMIT 1 "));
  $arrayCurator = array('header' => '', 'body' => '', 'sub' => '', 'iphide' => 1);
  core::$user_set['avatar'] = 0;
  echo '<p>Куратор темы: '.functions::display_user($curator, $arrayCurator).'</p>';
}
$req = mysql_query("SELECT `forum_posts`.*, `forum_posts`.`user` AS `name`, `forum_posts`.`user_id` AS `id`, `users`.`sex`, `users`.`rights`, `users`.`lastdate`, `users`.`status`, `users`.`datereg` FROM `forum_posts` LEFT JOIN `users` ON `forum_posts`.`user_id` = `users`.`id` WHERE `forum_posts`.`topic` = '$topic' ORDER BY `forum_posts`.`time` $postOrder LIMIT $start, $kmess ");
 echo '</a>';
  if ((($user_id == $topicRes['user_id'] && !$topicRes['close'] && (!$ban['1'] || !$ban['11'])) || ($user_id == $res['user_id'] && (!$i && (!$page || $page == 1)))) || ($rights == 3 || $rights >=6)){
   
 echo '
<div class="topmenu"><a href="index.php?act=up&amp;topic='.$topic.'">Поднять тему</a></div>
<div class="topmenu"><a href="index.php?act=top&amp;topic='.$topic.'">Закрепить в топ</a></div>
';

	 }

	 
echo '<div class="topmenu"><a href="index.php?act=search&amp;topic='.$topic.'">Поиск</a></div>
<div class="topmenu"><a href="index.php?act=onforum&amp;topic='.$topic.'">Кто в теме</a> ('.$online_u.'/'.$online_g.')</div>
<div class="topmenu"><a href="index.php?act=loadtopic&amp;topic='.$topic.'&amp;page='.$page.'">Скачать тему</a></div>
';

if ($user_id){
  $favourites = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_favourites` WHERE `topic` = '$topic' AND `user_id` = '$user_id' LIMIT 1 "), 0);
  echo $favourites ? '<div class="topmenu"><a href="index.php?act=my&amp;delfavourite&amp;topic='.$topic.'&amp;page='.$page.'">Из избранного</a></div>' : '<div class="topmenu"><a href="index.php?act=my&amp;addfavourite&amp;topic='.$topic.'&amp;page='.$page.'">В избранное</a></div>';
}

echo '<div class="topmenu"><a href="index.php?act=files&amp;topic='.$topic.'">Файлы темы</a></div>';
echo '</div>';

if (!$user_id)
  echo '<p>'.($postOrder == 'DESC' ? '<div class="topmenu"><a href="index.php?act=postorder&amp;asc&amp;topic='.$topic.'&amp;page='.$page.'">Новые внизу</a></div>' : '<div class="topmenu"><a href="index.php?act=postorder&amp;desc&amp;topic='.$topic.'&amp;page='.$page.'">Новые вверху</a>').'</div>';

if ($rights == 3 || $rights >= 6){
  echo '<div class="topmenu"><a href="index.php?act=edittopic&amp;topic='.$topic.'&amp;page='.$page.'">Изменить</a></div>'.
  '<div class="topmenu"><a href="index.php?act=edittopic&amp;topic='.$topic.'&amp;page='.$page.'&amp;'.($topicRes['close'] ? 'open">Открыть' : 'close">Закрыть').'</a></div>'.
  ($rights >= 6 ? '<div class="topmenu"><a href="index.php?act=deltopic&amp;topic='.$topic.'">Удалить</a></div>' : '').
  '<div class="topmenu"><a href="index.php?act=movetopic&amp;topic='.$topic.'&amp;page='.$page.'">Перенести</a></div>'.
  '<div class="topmenu"><a href="index.php?act=pollsettings&amp;topic='.$topic.'&amp;page='.$page.'">Голосование</a></div>';
  
}