<?php
# Script by seg0ro http://mobilarts.ru
# Not for sale!!!

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

$textl .= ' | Поиск';
require_once('../incfiles/head.php');

/*
if (!$user_id){
  echo functions::display_error('Только для авторизованных!<br /><a href="index.php">Форум</a>');
  require_once('../incfiles/end.php');
  exit;
}
*/

$search = strtr($_GET['text'], array('_' => '\\_','%' => '\\%'));
$searchT = $_GET['t'] == 1 ? 1 : 0;
$searchU = ($_GET['u'] == 1 && !$search_t) ? 1 : 0;

if ($topic){
  $tree = array('<a href="index.php">Форум</a>', '<a href="index.php?topic='.$topic.'">'.functions::checkout($topicRes['topicname']).'</a>', 'Поиск в теме');
  $num = 2;
}else{
  $tree = array('<a href="index.php">Форум</a>', 'Поиск');
  $num = 1;
}

if ($searchU){
  $tree[$num] = 'Поиск сообщений пользователя';
  if ($search){
    $userReq = mysql_query("SELECT * FROM `users` WHERE `name` LIKE '".mysql_real_escape_string($search)."' LIMIT 1 ");
    if (!mysql_num_rows($userReq)){
      $error .= 'Такого пользователя не существует!<br />';
    }
    $userRes = mysql_fetch_assoc($userReq);
  }
}

echo '<div class="phdr">'.functions::display_menu($tree).'</div>';

if ($search && !$searchU && (mb_strlen($search) < 4 || mb_strlen($search) > 64))
  $error .= 'Некорректная длинна запроса (для тем и сообщений от 4 символов)!';
  
if ($search && $searchU && (mb_strlen($search) < 3 || mb_strlen($search) > 32))
  $error .= 'Некорректная длинна запроса (для ника от 3 символов)!';  

if ($error)
  echo functions::display_error($error);

echo '<form action="index.php?act=search'.($topic ? '&amp;topic='.$topic : '').'" method="get"><div class="gmenu">';
echo '<input type="hidden" name="act" value="search" />';
if ($topic)
  echo '<input type="hidden" name="topic" value="'.$topic.'" />';
echo 'Запрос <img style="cursor: pointer;" onclick="alert(this.title);" src="images/question.png" alt="?" title="От 4 до 64 символов" />:<br /><input type="text" value="'.text($search).'" name="text" /><input type="submit" value="Поиск" /><br />';
if ($rights == 3 || $rights >= 6)
  echo '<label><input name="u" type="checkbox" value="1" '.($searchU ? 'checked="checked"' : '').' /> Поиск сообщений пользователя</label><br />';
if (!$topic)
  echo '<label><input name="t" type="checkbox" value="1" '.($searchT ? 'checked="checked"' : '').' /> Искать в названии темы</label>';
echo '</div></form>';

if ($search && !$error){
  if ($searchT){
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_topics` WHERE `topicname` LIKE '%".mysql_real_escape_string($search)."%' "), 0);
  }elseif($searchU){
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_posts` WHERE `user_id` = '".$userRes['id']."'".($topic ? " AND `topic` = '$topic'" : "")." "), 0);
  }else{
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_posts` WHERE MATCH (`text`) AGAINST ('".mysql_real_escape_string($search)."' IN BOOLEAN MODE)".($topic ? " AND `forum_posts`.`topic` = '$topic'" : "")." "), 0);
  }
  
  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?act=search&amp;'.($topic ? 'topic='.$topic.'&amp;' : '').'text='.$search.'&amp;'.($searchT ? 't=1&amp;' : '').($searchU ? 'u=1&amp;' : ''), $start, $total, $kmess).'</div>';
    
    if ($searchT){
      $req = mysql_query("SELECT * FROM `forum_topics` WHERE `topicname` LIKE '%".mysql_real_escape_string($search)."%' ORDER BY `time` DESC LIMIT $start, $kmess ");
    }elseif($searchU){
      $req = mysql_query("SELECT * FROM `forum_posts` WHERE `user_id` = '".$userRes['id']."'".($topic ? " AND `topic` = '$topic'" : "")." ORDER BY `time` DESC LIMIT $start, $kmess ");
    }else{
      $req = mysql_query("SELECT `forum_posts`.*, `users`.`id`, `users`.`name`, `users`.`sex`, `users`.`rights`, `users`.`lastdate`, `users`.`status`, `users`.`datereg` FROM `forum_posts` LEFT JOIN `users` ON `forum_posts`.`user_id`=`users`.`id`  WHERE MATCH (`text`) AGAINST ('".mysql_real_escape_string($search)."' IN BOOLEAN MODE) ".($topic ? " AND `forum_posts`.`topic` = '".$topic."'" : "")." ORDER BY `time` DESC LIMIT $start, $kmess ");
    }
    
    if ($searchT && !$topic){
      while ($res = mysql_fetch_array($req)){
        echo $i % 2 ? '<div class="list2">' : '<div class="list1">';

        $sub = 'Автор: '.$res['user'];
        if ($res['count'] > 1){
          $lastPost = explode(':|:', $res['lastpost']);
          $sub .= ' <a href="index.php?post='.$lastPost[1].'&amp;find">Последн.</a>: '.$lastPost[0];
        }
        $sub .= ' '.functions::display_date($res['time']).'<br />';

        $sub .= 'Подфорум: <a href="index.php?forum='.$res['forum'].'">'.functions::checkout($res['forumname']).'</a>';
        echo show_topic($res, $sub);
        echo '</div>';
        ++$i;
      }
    }elseif($searchU){
      
      while ($res = mysql_fetch_array($req)){
        echo $i % 2 ? '<div class="list2">' : '<div class="list1">';
        
        $header = functions::display_date($res['time']).' <a href="index.php?post='.$res['post'].'&amp;find" title="Перейти к сообщению">&gt;&gt;</a> '.'<br />';
        
        $text = quote(functions::checkout($res['text'], 1, 1));
        if ($set_user['smileys'])
          $text = functions::smileys($text, $userRes['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>';
        }
        
        $sub = false;
        if (!$topic){
          $topicRes = mysql_fetch_array(mysql_query("SELECT * FROM `forum_topics` WHERE `topic` = '".$res['topic']."' LIMIT 1 "));
          $sub = 'Тема: <a href="index.php?topic='.$topicRes['topic'].'">'.functions::checkout($topicRes['topicname']).'</a>';  
        }
                
        $array = array('header' => $header, 'body' => $text, 'sub' => $sub);
        echo functions::display_user($userRes, $array);
        echo '</div>';
        ++$i;
      }
      
    }else{
      while ($res = mysql_fetch_array($req)){
        echo $i % 2 ? '<div class="list2">' : '<div class="list1">';

        $header = ' '.functions::display_date($res['time']).' <a href="index.php?post='.$res['post'].'&amp;find" title="Перейти к сообщению">&gt;&gt;</a>';

        $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']." ");
          if (mysql_num_rows($file)){
            $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>';
        }

        $sub = false;
        if (!$topic){
          $topicRes = mysql_fetch_array(mysql_query("SELECT * FROM `forum_topics` WHERE `topic` = '".$res['topic']."' LIMIT 1 "));
          $sub = 'Тема: <a href="index.php?topic='.$topicRes['topic'].'">'.functions::checkout($topicRes['topicname']).'</a>';
        }
        $array = array('header' => $header, 'body' => $text, 'sub' => $sub);
        echo functions::display_user($res, $array).'</div>';
        ++$i;
      }
      
    }
    echo '<div class="phdr">Найдено: '.$total.'</div>';
    if ($total > $kmess)
      echo '<div class="topmenu">'.functions::display_pagination('index.php?act=search&amp;'.($topic ? 'topic='.$topic.'&amp;' : '').'text='.$search.'&amp;'.($searchT ? 't=1&amp;' : '').($searchU ? 'u=1&amp;' : ''), $start, $total, $kmess).'</div>';
  }else{
    echo '<div class="list1">Ничего не надено</div>';
  }

}

if ($search)
  echo '<p><a href="index.php?act=search'.($topic ? '&amp;topic='.$topic : '').'">Новый поиск</a></p>';

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