<?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['act'])) {
  $act = check($_GET['act']);
} else {
  $act = 'index';
} 
if (isset($_GET['start'])) {
  $start = abs(intval($_GET['start']));
} else {
  $start = 0;
} 

show_title('site.png', 'Поиск в блогах');

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

    $config['newtitle'] = 'Поиск в блогах';

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

    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 (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)) ? 'title' : 'text';
        // ----------------------------- Поиск в названии -------------------------------//
        if ($wheres == 'title') {
          echo 'Поиск запроса <b>&quot;' . $_SESSION['find'] . '&quot;</b> в заголовке<br />';

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

          if (empty($_SESSION['findresult'])) {
            $querysearch = DB :: $dbh -> query("SELECT `blogs_id` FROM `blogs` WHERE `blogs_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']);

            $queryblog = DB :: $dbh -> query("SELECT `blogs`.*, `cats_id`, `cats_name` FROM `blogs` LEFT JOIN `catsblog` ON `blogs`.`blogs_cats_id`=`catsblog`.`cats_id` WHERE `blogs_id` IN (" . $result . ") ORDER BY `blogs_time` DESC LIMIT " . $start . ", " . $config['blogpost'] . ";");

            while ($data = $queryblog -> fetch()) {
              if ($data['blogs_rating'] > 0) {
                $data['blogs_rating'] = '<span style="color:#00aa00">+' . $data['blogs_rating'] . '</span>';
              } 
              if ($data['blogs_rating'] < 0) {
                $data['blogs_rating'] = '<span style="color:#ff0000">' . $data['blogs_rating'] . '</span>';
              } 

              echo '<div class="b"><img src="../images/img/edit.gif" alt="image" /> ';
              echo '<b><a href="blog.php?act=view&amp;id=' . $data['blogs_id'] . '&amp;' . SID . '">' . $data['blogs_title'] . '</a></b> (' . $data['blogs_rating'] . ')</div>';

              echo '<div>Категория: <a href="blog.php?cid=' . $data['cats_id'] . '&amp;' . SID . '">' . $data['cats_name'] . '</a><br />';
              echo 'Просмотров: ' . $data['blogs_read'] . '<br />';
              echo 'Автор: <a href="../pages/anketa.php?uz=' . $data['blogs_user'] . '&amp;' . SID . '">' . nickname($data['blogs_user']) . '</a>  (' . date_fixed($data['blogs_time']) . ')</div>';
            } 

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

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

          if (empty($_SESSION['findresult'])) {
            $querysearch = DB :: $dbh -> query("SELECT `blogs_id` FROM `blogs` WHERE `blogs_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']);

            $queryblog = DB :: $dbh -> query("SELECT `blogs`.*, `cats_id`, `cats_name` FROM `blogs` LEFT JOIN `catsblog` ON `blogs`.`blogs_cats_id`=`catsblog`.`cats_id` WHERE `blogs_id` IN (" . $result . ") ORDER BY `blogs_time` DESC LIMIT " . $start . ", " . $config['blogpost'] . ";");

            while ($data = $queryblog -> fetch()) {
              if ($data['blogs_rating'] > 0) {
                $data['blogs_rating'] = '<span style="color:#00aa00">+' . $data['blogs_rating'] . '</span>';
              } 
              if ($data['blogs_rating'] < 0) {
                $data['blogs_rating'] = '<span style="color:#ff0000">' . $data['blogs_rating'] . '</span>';
              } 

              echo '<div class="b"><img src="../images/img/edit.gif" alt="image" /> ';
              echo '<b><a href="blog.php?act=view&amp;id=' . $data['blogs_id'] . '&amp;' . SID . '">' . $data['blogs_title'] . '</a></b> (' . $data['blogs_rating'] . ')</div>';

              if (utf_strlen($data['blogs_text']) > 200) {
                $data['blogs_text'] = strip_tags(bb_code($data['blogs_text']), '<br>');
                $data['blogs_text'] = utf_substr($data['blogs_text'], 0, 200) . '...';
              } 

              echo '<div>' . $data['blogs_text'] . '<br />';

              echo 'Категория: <a href="blog.php?cid=' . $data['cats_id'] . '&amp;' . SID . '">' . $data['cats_name'] . '</a><br />';
              echo 'Автор: <a href="../pages/anketa.php?uz=' . $data['blogs_user'] . '&amp;' . SID . '">' . nickname($data['blogs_user']) . '</a>  (' . date_fixed($data['blogs_time']) . ')</div>';
            } 

            page_strnavigation('search.php?act=search&amp;type=' . $type . '&amp;where=' . $where . '&amp;', $config['blogpost'], $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');

?>