<?php

# Forum by seg0ro (http://mobilarts.ru)
# Not for sale! Не для продажи!

define('_IN_JOHNCMS', 1);

require_once ('../incfiles/core.php');

$headmod = isset($_GET['topic']) ? 'forum,'.intval($_GET['topic']) : 'forum';
require_once ('includes/functoins.php');

$textl = 'Форум';
  
if (!$set['mod_forum'] && $rights < 7)
  $error = 'Форум закрыт!';
elseif ($set['mod_forum'] == 1 && !$user_id)
  $error = 'Доступ на форум открыт только авторизованным посетителям!';
if ($error){
  require_once('../incfiles/head.php');
  echo functions::display_error($error);
  require_once('../incfiles/end.php');
  exit;
}

if ($forum){
  $forumReq = mysql_query("SELECT * FROM `forum_forums` WHERE `forum` = '$forum' LIMIT 1 ");
  if (!mysql_num_rows($forumReq)){
    require_once('../incfiles/head.php');
    echo functions::display_error('Такого форума не существует!<br /><a href="index.php">Форум</a>');
    require_once('../incfiles/end.php');
    exit;
  }
  $forumRes = mysql_fetch_array($forumReq);
  if ($forumRes['keyw']) $set['meta_key'] = $forumRes['keyw'];
  if ($forumRes['descw']) $set['meta_desc'] = $forumRes['descw'];
  $textl = title($forumRes['forumname']);
  
  if ($forumRes['parent'])
    $parentForum = mysql_fetch_array(mysql_query("SELECT `forumname` FROM `forum_forums` WHERE `forum` = '".$forumRes['parent']."' LIMIT 1 "));
  
}

if($topic){
  $topicReq = mysql_query("SELECT * FROM `forum_topics` WHERE `topic` = '$topic' LIMIT 1 ");
  if (!mysql_num_rows($topicReq)){
    require_once('../incfiles/head.php');
    echo functions::display_error('Такой темы не существует!<br /><a href="index.php">Форум</a>');
    require_once('../incfiles/end.php');
    exit;
  }
  $topicRes = mysql_fetch_array($topicReq);

  if (!empty($topicRes['poll_name'])){
    $pollReq = mysql_query("SELECT * FROM `forum_polls` WHERE `topic` = '$topic' ORDER BY `id` ASC LIMIT 20 ");
    $pollSet = unserialize($topicRes['poll_set']);
  }

  $textl = title($topicRes['topicname']);

  if($post){
    $postReq = mysql_query("SELECT * FROM `forum_posts` WHERE `post` = '$post' LIMIT 1 ");
    if (!mysql_num_rows($postReq)){
      require_once('../incfiles/head.php');
      echo functions::display_error('Такого сообщения не существует!<br /><a href="index.php">Форум</a>');
      require_once('../incfiles/end.php');
      exit;
    }
    $postRes = mysql_fetch_array($postReq);

    $textl = title($topicRes['topicname']).' | Сообщение: '.$post;
  }
    $topicRefid = mysql_fetch_array(mysql_query("SELECT `parent`, `forumname` FROM `forum_forums` WHERE `forum` = '".$topicRes['forum']."' LIMIT 1 "));
    
  if ($user_id && $topicRes['curator'] == $user_id)
    $rights = 3;

}

if($file){
  $fileReq = mysql_query("SELECT * FROM `forum_files` WHERE `file` = '$file' LIMIT 1 ");
  if (!mysql_num_rows($fileReq)){
    require_once('../incfiles/head.php');
    echo functions::display_error('Такого файла не существует!<br /><a href="index.php">Форум</a>');
    require_once('../incfiles/end.php');
    exit;
  }
  $fileRes = mysql_fetch_array($fileReq);

  $fileRefid = mysql_fetch_array(mysql_query("SELECT `file`, `forumname` FROM `forum_topics` WHERE `topic` = '".$fileRes['topic']."' LIMIT 1 "));

  $textl = title($fileRefid['topicname']).' | Файл: '.$file;
}

if (!$user_id)
  $set_forum['upfp'] = $_SESSION['uppost'] == 1 ? 1 : 0;

$postOrder = $set_forum['upfp'] ? 'DESC' : 'ASC';

$arrayIncludes = array('addforum', 'addpost', 'addtopic', 'clean', 'delfile', 'delforum', 'delpost', 'deltopic', 'download', 'editforum', 'editpost', 'edittopic', 'files', 'last',  'up', 'top','loadtopic', 'movetopic', 'moveforum', 'my', 'onforum', 'poll', 'polled', 'pollsettings', 'postorder', 'rating', 'search');

if (in_array($act, $arrayIncludes) && file_exists($act.'.php')){
  require_once ($act.'.php');
}else{
  
  require_once('../incfiles/head.php');
  if (!$set['mod_forum'])
    echo '<div class="rmenu">Форум закрыт!</div>';
    
  if ($topic){
    if (isset($_GET['unread'])){
      $resReaded = mysql_fetch_assoc(mysql_query("SELECT `time`, `lastpost` FROM `forum_readed` WHERE `topic` = '$topic' AND `user_id` = '$user_id' LIMIT 1 "));
      if ($resReaded['time'] && $resReaded['lastpost'] > 0){
        $goPage = ceil(mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_posts` WHERE `topic` = '$topic' AND `post` ".($set_forum['upfp'] ? '>=' : '<=')." '".$resReaded['lastpost']."' "), 0) / $kmess);
        header ('Location: index.php?topic='.$topic.'&page='.$goPage.'#p'.$resReaded['lastpost']);
      }else{
        header ('Location: index.php?topic='.$topic);
      }
      require_once('../incfiles/end.php');
      exit;
    }
        
    require_once('includes/showtopic.php');
    require_once('../incfiles/end.php');
    exit;
  }
  
  if ($post){
    
    $postReq = 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`.`post` = '$post' ORDER BY `forum_posts`.`time` ASC LIMIT 1 ");
    
    if (!mysql_num_rows($postReq)){
      echo functions::display_error('Такого сообщения не существует!<br /><a href="index.php">Форум</a>');
      require_once('../incfiles/end.php');
      exit;
    }
     
    $postRes = mysql_fetch_array($postReq);
    
    if(isset($_GET['find'])){
      $go = ceil(mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_posts` WHERE `topic` = '".$postRes['topic']."' AND `post` ".($set_forum['upfp'] ? '>=' : '<=')." '$post' "), 0) / $kmess);
      header('Location: index.php?topic='.$postRes['topic'].'&page='.$go.'#p'.$post);
      require_once('../incfiles/end.php');
      exit;
    }
    
    $topicReq = mysql_query("SELECT * FROM `forum_topics` WHERE `topic` = '".$postRes['topic']."' LIMIT 1 ");
    if (!mysql_num_rows($topicReq)){
      echo functions::display_error('Такой темы не существует!<br /><a href="index.php">Форум</a>');
      require_once('../incfiles/end.php');
      exit;
    }
    
    $topicRes = mysql_fetch_array($topicReq);
    
    echo forum_counter();
    
    $tree = array('<a href="index.php">Форум</a>', '<a href="index.php?post='.$post.'&amp;find">'.functions::checkout($topicRes['topicname']).'</a>', 'Cообщение #'.$post);
    echo '<div class="phdr">'.functions::display_menu($tree).'</div>';
    echo '<div class="list1">';
    $postHeader .= ' <span class="gray">'.functions::display_date($postRes['time']).'</span>';
    
    $postText = quote(functions::checkout($postRes['text'], 1, 1));
    if ($set_user['smileys'])
      $postText = functions::smileys($postText, $postRes['rights'] >= 1 ? 1 : 0);

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

    if ($postRes['edit']){
      $edit = explode(':|:', $postRes['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>';
    }
    
    if ($postRes['rating'] > 0) $color = 'C0FFC0';
    elseif ($postRes['rating'] < 0) $color = 'F196A8';
    else $color = 'CCCCCC';
    if ($user_id && $postRes['user_id'] != $user_id){
      $postText .= '<div style="font-size: x-small; margin-top: 7px;">Рейтинг: <a href="index.php?act=rating&amp;topic='.$postRes['topic'].'&amp;post='.$postRes['post'].'&amp;minus"><img src="images/minus.png" alt="-" /></a> <span style="background:#'.$color.'">&nbsp;'.$postRes['rating'].'&nbsp;</span> <a href="index.php?act=rating&amp;topic='.$postRes['topic'].'&amp;post='.$postRes['post'].'&amp;plus"><img src="images/plus.png" alt="+" /></a></div>';
    }else{
      $postText .= '<div style="font-size: x-small; margin-top: 7px;">Рейтинг: <span style="background:#'.$color.'">&nbsp;'.$postRes['rating'].'&nbsp;</span></div>';
    }
    
    $postSub = '';
    if ($rights == 3 || $rights >= 6){
      $postSub .= '<a href="index.php?act=editpost&amp;topic='.$postRes['topic'].'&amp;post='.$postRes['post'].'&amp;page='.$page.'">Изменить</a> <a href="index.php?act=delpost&amp;topic='.$postRes['topic'].'&amp;post='.$postRes['post'].'&amp;page='.$page.'">Удалить</a>';
    }

    $postArray = array('header' => $postHeader, 'body' => $postText, 'sub' => $postSub);
    echo functions::display_user($postRes, $postArray);
    echo '<div><input type="text" value="'.$set['homeurl'].'/forum/index.php?post='.$post.'" /></div>';
    echo '</div>';
    require_once('../incfiles/end.php');
    exit;
  }
  $th = mysql_fetch_assoc(mysql_query("SELECT * FROM `cms_settings` WHERE `key` = 'them' LIMIT 1"));
  $ps = mysql_fetch_assoc(mysql_query("SELECT * FROM `cms_settings` WHERE `key` = 'post' LIMIT 1"));
$upp = mysql_fetch_assoc(mysql_query("SELECT * FROM `cms_settings` WHERE `key` = 'upc' LIMIT 1"));
  $topp = mysql_fetch_assoc(mysql_query("SELECT * FROM `cms_settings` WHERE `key` = 'topcost' LIMIT 1"));

  	echo '<div class="gmenu"><p>
	<p style="color:#9acd32; font-size:18px; font-weight:bold;">Расценки за постинг </p>
	Оплата за тему: <font color="#9acd32"><strong>' . $th['val'] . '</strong>    руб</font></p>';
	echo '<p>Оплата за посты: <font color="#9acd32"><strong>' . $ps['val'] . '</strong>   руб</font></p></div>';
echo '<div class="gmenu"><p>
<p style="color:#9acd32; font-size:18px; font-weight:bold;">Платные услуги </p>
Поднятие темы: <font color="#9acd32"><strong>' . $upp['val'] . '</strong>    руб</font></p>';
	echo '<p>Закрепление в топ: <font color="#9acd32"><strong>' . $topp['val'] . '</strong>   руб</font></p>';
echo '</div> <br />';

  echo forum_counter();
  
  if ($forum && $forumRes['type']){
    
    if ($forumRes['parent'])
      $tree = array('<a href="index.php">Форум</a>', '<a href="index.php?forum='.$forumRes['parent'].'">'.functions::checkout($parentForum['forumname']).'</a>', functions::checkout($forumRes['forumname']));
    else
      $tree = array('<a href="index.php">Форум</a>', functions::checkout($forumRes['forumname']));
    echo '<div class="phdr">'.functions::display_menu($tree).'</div>';
    
    if ($user_id && (!$ban['1'] || !$ban['11']) && (!$forumRes['close'] || $rights))
      echo '<div class="gmenu"><form action="index.php?act=addtopic&amp;forum='.$forum.'" method="post"><input type="submit" value="Новая тема"></form></div>';

    
    $total = $forumRes['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?forum='.$forum.'&amp;', $start, $total, $kmess).'</div>';
      
      $req = mysql_query("SELECT * FROM `forum_topics` WHERE `forum` = '$forum' ORDER BY `sticky` DESC, `time` DESC LIMIT $start, $kmess ");
      
      while ($res = mysql_fetch_assoc($req)){
        echo $i % 2 ? '<div class="list2">' : '<div class="list1">';
        $sub = ''.$res['user'];
          if ($res['count'] > 1){
            $lastPost = explode(':|:', $res['lastpost']);
            $sub .= ' / '.$lastPost[0];
          }
          $sub .= ' '.functions::display_date($res['time']).'<br />';
        echo show_topic($res, $sub);  
        echo '</div>';
        ++$i;
      }
      echo '<div class="phdr">Тем: '.$total.'</div>';
      if ($total > $kmess && $forumRes['type'])
        echo '<div class="topmenu">'.functions::display_pagination('index.php?forum='.$forum.'&amp;', $start, $total, $kmess).'</div>';
          
    }else{
      echo '<div class="list1">Пусто</div>';
    }
  }else{
    if ($forum)
      echo '<div class="phdr">'.functions::display_menu(array('<a href="index.php">Форум</a>', ($forumRes['parent'] ? '<a href="index.php?forum='.$forumRes['parent'].'">'.functions::checkout($parentForum['forumname']).'</a>' : ''), functions::checkout($forumRes['forumname']))).'</div>';
    else
      echo '<div class="phdr">Форум</div>';
    
    $req = mysql_query("SELECT * FROM `forum_forums` WHERE `parent` = '$forum' ORDER BY `sort` ASC ");
    $total = mysql_num_rows($req);
    
    if ($total){
      while ($res = mysql_fetch_assoc($req)){
        echo $i % 2 ? '<div class="list2">' : '<div class="list1">';
        echo '<a href="index.php?forum='.$res['forum'].'">'.functions::checkout($res['forumname']).'</a> ['.$res['count'].''.($res['type'] ? '' : '').']';
        
        if ($rights == 9){
          echo ' <span style="font-size: x-small;"><span style="cursor:pointer;" onclick="var _n=this.parentNode.getElementsByTagName(\'span\')[1];if(_n.style.display==\'none\'){_n.style.display=\'\';}else{_n.style.display=\'none\';}" title="Управление">Адм.(+/-)</span><span style="display:none"> <a href="index.php?act=moveforum&amp;forum='.$res['forum'].'&amp;up">Вверх</a> <a href="index.php?act=moveforum&amp;forum='.$res['forum'].'&amp;down">Вниз</a> <a href="index.php?act=editforum&amp;forum='.$res['forum'].'">Изменить</a> <a href="index.php?act=delforum&amp;forum='.$res['forum'].'">Удалить</a></span></span>';
        }
        
        if ($res['desc'] || $res['last_topic']){
          echo '<div class="sub">';
          if ($res['desc'])
            echo functions::checkout($res['desc'], 1, 1).'<br />';
         
          echo '</div>';  
        }
        echo '</div>';
        ++$i;
      }
      if (!$forum){
        $topics = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_topics` "), 0);
        $posts = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_posts` "), 0);
        echo '<div class="phdr">Тем: '.$topics.', Сообщений: '.$posts.'</div>';
      }else{
        echo '<div class="phdr">Форумов: '.$total.'</div>';
      }
      
    }else{
      echo '<div class="list1">Пусто</div>';
    }
  }
  
  $onltime = time() - 300;
  $onlineU = mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `lastdate` > $onltime AND `place` LIKE 'forum%'"), 0);
  $onlineG = mysql_result(mysql_query("SELECT COUNT(*) FROM `cms_sessions` WHERE `lastdate` > $onltime AND `place` LIKE 'forum%'"), 0);
  echo '<div class="topmenu"><a href="index.php?act=search">Поиск</a><br /></div>
<div class="topmenu"><a href="index.php?act=onforum">Кто на форуме</a> ('.$onlineU.'/'.$onlineG.')'.(!$forum ? '<br /></div><div class="topmenu"><a href="index.php?act=files">Файлы форума</a>' : '').'</div>';
  

  
  if ($rights == 9){
    echo '<div class="func">';
    if ($forumRes['type'] == 0)
      echo '<div class="topmenu"><a href="index.php?act=addforum&amp;forum='.$forum.'">Создать форум</a></div>'.($forum ? '' : '<div class="topmenu"><a href="index.php?act=clean">Чистка форума</a></div>');
    else
      echo '<div class="topmenu"><a href="index.php?act=editforum&amp;forum='.$forum.'">Изменить</a></div><div class="topmenu"><a href="index.php?act=delforum&amp;forum='.$forum.'">Удалить</a></div>'; 
  echo '</div>';
  }
  
}

require_once('../incfiles/end.php');