setlocale (LC_ALL, array ('ru_RU.CP1251', 'rus_RUS.1251'));
if (!isset($_GET['query'])) {
// не передавали параметров
echo_head("");
echo_foot();
exit();
}
$squery = substr(trim($_GET['query']), 0, 80);
$fquery = htmlspecialchars($squery); // исходная строка
if ($fquery === "") {
echo_head("");
echo_error("Не указана строка для поиска!");
echo_foot();
exit();
}
$squery = clean_query(strtolower($squery)); // то что действительно ищем
if ($squery === "") {
echo_head($fquery);
echo_error("Строка для поиска слишком коротка.");
echo_foot();
exit();
}
// слова для поиска - в массив
$aquery = explode(' ', $squery);
$acount = count($aquery);
$exceptions = join('', file("exceptions.txt"));
// передали имя файла?
$showfile = "";
if (isset($_GET['file'])) {
$showfile = $_GET['file'];
//echo "\"$showfile\"
";
//if (!get_magic_quotes_gpc()) {
// $showfile = addslashes($showfile); // може не надо
//}
//echo "\"$showfile\"
";
if (strpos($exceptions, "..".$showfile) !== false) $showfile = "!";
if (!file_exists("..".$showfile)) $showfile = "!";
if (eregi("html$", $showfile)) {
create_highlight($showfile);
exit();
}
}
echo_head($fquery);
// Наконец-то! Тута поиск!
$files_count = 0; // общее число файлов
$files_found = 0;
global $results;
// засекли время
list($usec, $sec) = explode(" ", microtime());
$time_search = ((float)$usec + (float)$sec);
do_search('..');
list($usec, $sec) = explode(" ", microtime());
$time_search = ((float)$usec + (float)$sec) - $time_search;
//
if ($files_found != 0) {
// последние приготовления
for ($i = 0; $i < $files_found; $i++) {
// имя нужно заменить?
$path = preg_replace
("/\/(text_[a-zA-Z0-9_]+\.shtml)/", "/index.shtml", $results[$i]['path']);
// название нужно сменить?
if (($results[$i]['title'] == "") || eregi("index.shtml", $path)) {
if (file_exists($path) && eregi("html$", $path)) {
$page = join('', file($path));
// можно оптимизировать, но неохота!
preg_match("/<[hH]\d>.*<\/[hH]\d>/Us", $page, $matches);
if (isset($matches[0])) {
$h1 = trim(strip_tags($matches[0]));
if ($h1 != "") {
$eos = strlen($h1) - 1;
if ($h1[$eos] == ":") $h1[$eos] = " ";
$results[$i]['title'] = rtrim($h1);
}
}
unset($page);
}
if ($results[$i]['title'] == "") $results[$i]['title'] = "Нет заголовка";
}
// теперь можно окончательно и две точки удалить
$results[$i]['path'] = strstr($path, '/');
$result_redir[] = $results[$i]['rel'];
}
// какие результаты будем показывать
$offset = isset($_GET['offset']) ? abs(floor($_GET['offset'])) * 10 : 0;
$offset = $offset > $files_found ? floor($files_found - 1) : $offset;
$rcount = $files_found - $offset < 10 ? $files_found - $offset : 10;
// длиннющая строка
$msg = "Поиск по строке: \"$squery\", найдено $files_found результатов ";
$msg .= "из $files_count документов за ";
$msg .= number_format($time_search, 2, ',', '');
$msg .= ($files_found > 10) ? (" секунд, показаны результаты с ".
($offset + 1)." по ".($offset + $rcount).".") : " секунд.";
echo_message($msg);
// в порядке убывания релевантности
arsort($result_redir);
reset($result_redir);
// пропускаем первые результаты
for ($i = 0; $i < $offset; $i++) next($result_redir);
for ($i = 0; $i < $rcount; $i++) {
echo_result(key($result_redir), $i + $offset + 1);
next($result_redir);
}
// старая версия
/*foreach ($result_redir as $id => $relev) {
echo_result($id);
}*/
echo_pages($files_found / 10, $offset / 10);
}
else {
echo_error("Поиск по строке \"$squery\" не дал результатов.");
}
echo_foot();
exit();
// =======================================================================
function do_search($dir) {
global $files_count, $files_found, $exceptions, $results, $aquery, $acount;
$dir_handle = opendir($dir);
$dir .= "/";
while (($nextfile = readdir($dir_handle)) !== false) {
if (is_dir($dir.$nextfile)) {
// это каталог, который мы не исключили
if ((strpos($exceptions, $dir.$nextfile) === false) &&
($nextfile !== '.') && ($nextfile !== '..'))
{
do_search($dir.$nextfile);
}
}
// это файл, причём *html, ищем в нём
elseif (eregi("html$", $nextfile) && ($nextfile != "index.shtml")) {
$files_count++;
$page = join('', file($dir.$nextfile));
// находим заголовок
$results[$files_found]['title'] = "";
preg_match("/<[hH]\d>.*<\/[hH]\d>/Us", $page, $matches);
if (isset($matches[0])) {
$h1 = trim(strip_tags($matches[0]));
if ($h1 != "") {
$eos = strlen($h1) - 1;
if ($h1[$eos] == ":") $h1[$eos] = " ";
$results[$files_found]['title'] = rtrim($h1);
}
}
// редактируем страницу, удаляя ненужное
$page = preg_replace("/[\s]+/", " ", strip_tags($page));
// делаем регистро-независимую копию
$pagei = strtolower($page);
$i = 0;
$f = false;
// метрики релевантности
$relevsum = 0;
$relevmul = 1;
// кусок текста, который мы будем показывать
for (; ($i < $acount); $i++) {
if (($st = strpos($pagei, $aquery[$i])) !== false) {
$f = true;
$st = $st < 70 ? 0 : $st - 70;
$results[$files_found]['text'] = substr($page, $st, 150);
break;
}
// если сюда добрались, значит нескольких слов нету
// и мы обязаны прописать их количество
$results[$files_found][$i] = 0;
// и метрика произведения уже не должна работать
$relevmul = 0;
}
// начинаем с найденного слововхождения
for (; $i < $acount; $i++) {
$cnt = $results[$files_found][$i] = substr_count($pagei, $aquery[$i]);
//$relev += ($i < 3 ? 3 - $i : 1) * $cnt;
$relevsum += $cnt;
$relevmul *= $cnt;
}
if ($relevsum > 0) {
$results[$files_found]['path'] = $dir.$nextfile;
$results[$files_found]['rel'] = $relevsum + $relevmul * 2;
$files_found++;
}
}
}
}
// =======================================================================
function create_highlight($showfile) {
global $aquery, $acount;
// он существует, уже проверяли
// истинная директория
$basex = dirname($showfile);
$showfile = "..".$showfile;
$page = join('', file($showfile));
// директория относительно нашего скрипта
$base = "..".$basex;
if (($basex != "") and
($basex[strlen($basex) - 1] != "/") and
($basex[strlen($basex) - 1] != "\\")) $basex = $basex."/";
// количество инклудов
$incl_count = preg_match_all
("/<\!--[ ]?\#include[ ]+virtual[ ]?=[ ]?\"([^\"]+)\"[ ]?-->/U", $page, $includes, PREG_SET_ORDER);
// все кроме хедера/футера
for($i = 0; $i < $incl_count ; $i++) {
$bn = basename($includes[$i][1]);
if (($bn != "_header.shtml") && ($bn != "_footer.inc")) {
$fn = ($includes[$i][1][0] == "/") ? "..".$includes[$i][1] : $base."/".$includes[$i][1];
if (file_exists($fn)) {
$page = str_replace($includes[$i][0], join('', file($fn)), $page);
}
}
}
$page = preg_replace("/<(?=[^a-zA-Z\/\!])/", "<", $page);
for ($i = 0; $i < $acount; $i++) {
$code = $i < 3 ? 3 - $i : 1;
$qpat[$i] = "/(>[^<]*)(".preg_quote($aquery[$i]).")/i";
$qrep[$i] = "$1$2";
}
$page = preg_replace($qpat, $qrep, $page);
// теперь хедер/футер
$style = "\n".'';
for($i = 0; $i < $incl_count ; $i++) {
$bn = basename($includes[$i][1]);
$fn = ($includes[$i][1][0] == "/") ? "..".$includes[$i][1] : $base."/".$includes[$i][1];
if (($bn == "_header.shtml") and (file_exists($fn))) {
$page = str_replace($includes[$i][0], join('', file($fn)), $page);
// хедер есть, значит стиль уже определён
$style = "";
}
elseif (($bn == "_footer.inc") and (file_exists($fn))) {
$page = str_replace($includes[$i][0], join('', file($fn)), $page);
}
}
echo preg_replace("/<[Hh][Ee][Aa][Dd]>/", "$0$style\n
Релевантность = ".$results[$id]['rel'].$wordrel."
\n\n"; // кусок текста echo "…$text …
\n\n"; } function echo_pages($pcount, $curpage) { if ($pcount == 0) return; echo "$msg
\n\n"; } function echo_tip($tip) { if ($tip == "") { $tip = join('', file("tip.txt")); $tip = str_replace("\n", "