<?php
#-----------------------------------------------------#
#          ********* ROTORCMS *********               #
#              Made by  :  VANTUZ                     #
#               E-mail  :  visavi.net@mail.ru         #
#                 Site  :  http://pizdec.ru           #
#             WAP-Site  :  http://visavi.net          #
#                  ICQ  :  36-44-66                   #
#  Вы не имеете право вносить изменения в код скрипта #
#        для его дальнейшего распространения          #
#-----------------------------------------------------#	
require_once ('../includes/start.php');
require_once ('../includes/functions.php');
require_once ('../includes/header.php');
include_once ('../themes/' . $config['themes'] . '/index.php');

if (isset($_GET['start'])) {
  $start = abs(intval($_GET['start']));
} else {
  $start = 0;
} 
if (isset($_GET['act'])) {
  $act = check($_GET['act']);
} else {
  $act = 'index';
} 
if (isset($_GET['fid'])) {
  $fid = abs(intval($_GET['fid']));
} else {
  $fid = 0;
} 

show_title('site.png', 'Поиск по форуму');

if (is_user()) {
  switch ($act):
  # ###########################################################################################
  # #                                    Главная поиска                                      ##
  # ###########################################################################################
  case "index":

    $config['newtitle'] = 'Поиск по форуму';

    $queryforum = DB :: $dbh -> query("SELECT `forums_id`, `forums_parent`, `forums_title` FROM `forums` ORDER BY `forums_order` ASC;");
    $forums = $queryforum -> fetchAll();

    if (count($forums) > 0) {
      $output = array();
      foreach ($forums as $row) {
        $i = $row['forums_id'];
        $p = $row['forums_parent'];
        $output[$p][$i] = $row;
      } 

      echo '<div class="form" id="form"><form action="search.php?act=search&amp;' . SID . '" method="post">';
      echo 'Запрос:<br />';
      echo '<input type="text" name="find" /><br />';

      echo 'Раздел:<br />';
      echo '<select name="section">';
      echo '<option value="0">Не имеет значения</option>';

      foreach ($output[0] as $key => $data) {
        $selected = ($fid == $data['forums_id']) ? ' selected="selected"' : '';

        echo '<option value="' . $data['forums_id'] . '"' . $selected . '>' . $data['forums_title'] . '</option>';

        if (isset($output[$key])) {
          foreach($output[$key] as $datasub) {
            $selected = ($fid == $datasub['forums_id']) ? ' selected="selected"' : '';
            echo '<option value="' . $datasub['forums_id'] . '"' . $selected . '>– ' . $datasub['forums_title'] . '</option>';
          } 
        } 
      } 

      echo '</select><br />';

      echo 'Период:<br />';
      echo '<select name="period">';
      echo '<option value="0">За все время</option>';
      echo '<option value="7">Последние 7 дней</option>';
      echo '<option value="30">Последние 30 дней</option>';
      echo '<option value="60">Последние 60 дней</option>';
      echo '<option value="90">Последние 90 дней</option>';
      echo '<option value="180">Последние 180 дней</option>';
      echo '<option value="365">Последние 365 дней</option>';
      echo '</select><br /><br />';

      echo 'Искать:<br />';
      echo '<input name="where" type="radio" value="0" checked="checked" /> В темах<br />';
      echo '<input name="where" type="radio" value="1" /> В сообщениях<br /><br />';

      echo 'Тип запроса:<br />';
      echo '<input name="type" type="radio" value="0" checked="checked" /> И<br />';
      echo '<input name="type" type="radio" value="1" /> Или<br />';
      echo '<input name="type" type="radio" value="2" /> Полный<br /><br />';

      echo '<input type="submit" value="Поиск" /></form></div><br />';
    } else {
      show_error('Разделы форума еще не созданы!');
    } 
    break;
  # ###########################################################################################
  # #                                          Поиск                                         ##
  # ###########################################################################################
  case "search":

    if (isset($_POST['find'])) {
      $_SESSION['find'] = check(trim($_POST['find']));
      $_SESSION['findresult'] = '';
    } 
    if (isset($_POST['type'])) {
      $type = abs(intval($_POST['type']));
    } else {
      $type = abs(intval($_GET['type']));
    } 
    if (isset($_POST['where'])) {
      $where = abs(intval($_POST['where']));
    } else {
      $where = abs(intval($_GET['where']));
    } 
    if (isset($_POST['period'])) {
      $period = abs(intval($_POST['period']));
    } else {
      $period = abs(intval($_GET['period']));
    } 
    if (isset($_POST['section'])) {
      $section = abs(intval($_POST['section']));
    } else {
      $section = abs(intval($_GET['section']));
    } 

    if (utf_strlen($_SESSION['find']) < 50) {
      $findme = rus_utf_tolower($_SESSION['find']);
      $findmewords = explode(" ", $findme);

      $find = array();
      foreach ($findmewords as $valfind) {
        if (utf_strlen($valfind) >= 3) {
          $find[] = $valfind;
        } 
      } 
      array_splice($find, 3);

      if (count($find) > 0) {
        // -------------------------------- Кеширование запросов -----------------------------//
        $config['newtitle'] = $_SESSION['find'] . ' - Результаты поиска';

        $types = (empty($type)) ? 'AND' : 'OR';
        $wheres = (empty($where)) ? 'topics' : 'posts';
        // ----------------------------- Поиск в темах -------------------------------//
        if ($wheres == 'topics') {
          echo 'Поиск запроса <b>&quot;' . $_SESSION['find'] . '&quot;</b> в темах<br />';

          $searchsec = ($section > 0) ? "`topics_forums_id`=" . $section . " AND" : '';
          $searchper = ($period > 0) ? "`topics_time`>" . (SITETIME - ($period * 24 * 60 * 60)) . " AND" : '';

          if ($type == 2) {
            $find[0] = $findme;
          } 
          $search1 = (isset($find[1]) && $type != 2) ? $types . " `topics_title` LIKE '%" . $find[1] . "%'" : '';
          $search2 = (isset($find[2]) && $type != 2) ? $types . " `topics_title` LIKE '%" . $find[2] . "%'" : '';

          if (empty($_SESSION['findresult'])) {
            $querysearch = DB :: $dbh -> query("SELECT `topics_id` FROM `topics` WHERE " . $searchsec . " " . $searchper . " `topics_title` LIKE '%" . $find[0] . "%' " . $search1 . " " . $search2 . " LIMIT 500;");
            $result = $querysearch -> fetchAll(PDO :: FETCH_COLUMN);

            $_SESSION['findresult'] = $result;
          } 

          $total = count($_SESSION['findresult']);

          if ($total > 0) {
            if ($start >= $total) {
              $start = 0;
            } 

            echo 'Найдено совпадений: <b>' . $total . '</b><br /><br />';

            $result = implode(',', $_SESSION['findresult']);

            $querypost = DB :: $dbh -> query("SELECT * FROM `topics` WHERE `topics_id` IN (" . $result . ") ORDER BY `topics_last_time` DESC LIMIT " . $start . ", " . $config['forumtem'] . ";");

            while ($data = $querypost -> fetch()) {
              echo '<div class="b">';

              if ($data['topics_locked'] == 1) {
                echo '<img src="../images/img/lock.gif" alt="image" /> ';
              } elseif ($data['topics_closed'] == 1) {
                echo '<img src="../images/img/closed.gif" alt="image" /> ';
              } else {
                echo '<img src="../images/img/forums.gif" alt="image" /> ';
              } 

              echo '<b><a href="topic.php?tid=' . $data['topics_id'] . '&amp;' . SID . '">' . $data['topics_title'] . '</a></b> (' . $data['topics_posts'] . ')</div>';
              echo '<div>Страницы: ';
              forum_navigation('topic.php?tid=' . $data['topics_id'] . '&amp;', $config['forumpost'], $data['topics_posts']);
              echo 'Сообщение: ' . nickname($data['topics_last_user']) . ' (' . date_fixed($data['topics_last_time']) . ')</div>';
            } 

            page_strnavigation('search.php?act=search&amp;type=' . $type . '&amp;where=' . $where . '&amp;period=' . $period . '&amp;section=' . $section . '&amp;', $config['forumtem'], $start, $total);
          } else {
            show_error('По вашему запросу ничего не найдено!');
          } 
        } 
        // --------------------------- Поиск в сообщениях -------------------------------//
        if ($wheres == 'posts') {
          echo 'Поиск запроса <b>&quot;' . $_SESSION['find'] . '&quot;</b> в сообщениях<br />';

          $searchsec = ($section > 0) ? "`posts_forums_id`=" . $section . " AND" : '';
          $searchper = ($period > 0) ? "`posts_time`>" . (SITETIME - ($period * 24 * 60 * 60)) . " AND" : '';
          if ($type == 2) {
            $find[0] = $findme;
          } 
          $search1 = (isset($find[1]) && $type != 2) ? $types . " `posts_text` LIKE '%" . $find[1] . "%'" : '';
          $search2 = (isset($find[2]) && $type != 2) ? $types . " `posts_text` LIKE '%" . $find[2] . "%'" : '';

          if (empty($_SESSION['findresult'])) {
            $querysearch = DB :: $dbh -> query("SELECT `posts_id` FROM `posts` WHERE " . $searchsec . " " . $searchper . " `posts_text` LIKE '%" . $find[0] . "%' " . $search1 . " " . $search2 . " LIMIT 500;");
            $result = $querysearch -> fetchAll(PDO :: FETCH_COLUMN);

            $_SESSION['findresult'] = $result;
          } 

          $total = count($_SESSION['findresult']);

          if ($total > 0) {
            if ($start >= $total) {
              $start = 0;
            } 

            echo 'Найдено совпадений: <b>' . $total . '</b><br /><br />';

            $result = implode(',', $_SESSION['findresult']);

            $querypost = DB :: $dbh -> query("SELECT `posts`.*, `topics_title` FROM `posts` LEFT JOIN `topics` ON `posts`.`posts_topics_id`=`topics`.`topics_id` WHERE `posts_id` IN (" . $result . ") ORDER BY `posts_time` DESC LIMIT " . $start . ", " . $config['forumpost'] . ";");

            while ($data = $querypost -> fetch()) {
              echo '<div class="b">';

              echo '<img src="../images/img/forums.gif" alt="image" /> <b><a href="topic.php?act=viewpost&amp;tid=' . $data['posts_topics_id'] . '&amp;id=' . $data['posts_id'] . '&amp;' . SID . '">' . $data['topics_title'] . '</a></b></div>';

              echo '<div>' . bb_code($data['posts_text']) . '<br />';

              echo 'Написал: <a href="../pages/anketa.php?uz=' . $data['posts_user'] . '&amp;' . SID . '">' . nickname($data['posts_user']) . '</a> ' . user_online($data['posts_user']) . ' <small>(' . date_fixed($data['posts_time']) . ')</small><br />';

              if (is_admin() || empty($config['anonymity'])) {
                echo '<span class="data">(' . $data['posts_brow'] . ', ' . $data['posts_ip'] . ')</span>';
              } 

              echo '</div>';
            } 

            page_strnavigation('search.php?act=search&amp;type=' . $type . '&amp;where=' . $where . '&amp;period=' . $period . '&amp;section=' . $section . '&amp;', $config['forumpost'], $start, $total);
          } else {
            show_error('По вашему запросу ничего не найдено!');
          } 
        } 
      } else {
        show_error('Ошибка! Необходимо не менее 3-х символов в слове!');
      } 
    } else {
      show_error('Ошибка! Запрос должен содержать не более 50 символов!');
    } 

    echo '<img src="../images/img/back.gif" alt="image" /> <a href="search.php?' . SID . '">Вернуться</a><br />';
    break;

  default:
    header("location: search.php?" . SID);
    exit;
    endswitch;
  } else {
  show_login('Вы не авторизованы, чтобы использовать поиск, необходимо');
} 

echo '<img src="../images/img/reload.gif" alt="image" /> <a href="index.php?' . SID . '">К форумам</a><br />';
echo '<img src="../images/img/homepage.gif" alt="image" /> <a href="../index.php?' . SID . '">На главную</a>';

include_once ('../themes/' . $config['themes'] . '/foot.php');

?>