"; //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", $page); } // ======================================================================= function clean_query($qs) { $pat = array("/(\D)[\.,]/", // убираем: точки, у которых слева нет цифр "/[\.,](\D)/", // точки, у которых справа нет цифр "/[^a-zа-я0-9\.,]/", // все остальные ненормальные символы "/[ ]\d[ ]/", // однозначные числа "/\b[a-zа-я]{1,3}\b/", // слова где нет цифр короче 3 символов "/[\s]+/"); // пробелы $rep = array("$1 ", " $1", " ", " ", " ", " "); $qs = preg_replace($pat, $rep, " $qs "); return trim(preg_replace($pat, $rep, " $qs ")); // ещё разок } // ======================================================================= function echo_result($id, $number) { global $results, $aquery, $acount; $text = $results[$id]['text']; // начальные и конечные слова удалить, они могут быть обрезаны $text = preg_replace("/^[^ ]+[ ]|[ ][^ ]+$/", "", $results[$id]['text']); $wordrel = ""; // строчка о релевантности каждого слова // выделяем слова for ($i = 0; $i < $acount; $i++) { $code = $i < 3 ? 3 - $i : 1; $qpat[$i] = "/".preg_quote($aquery[$i])."/i"; $qrep[$i] = "$0"; $wordrel = $wordrel."; {$aquery[$i]} = ".$results[$id][$i]; } $text = preg_replace($qpat, $qrep, $text); // заголовок - ссылка $path = $results[$id]['path']; $hl_path = "/search/search.php?file=".rawurlencode($path)."&query=". rawurlencode($_GET['query']); echo "".$results[$id]['title']."\n"; echo "[Выделить слова]\n"; // манинькая строчка echo "

Релевантность = ".$results[$id]['rel'].$wordrel."

\n\n"; // кусок текста echo "

…$text …

\n\n"; } function echo_pages($pcount, $curpage) { if ($pcount == 0) return; echo "
Страницы: \n"; for ($i = 0; $i < $pcount; $i++) { echo ($i == $curpage) ? "".($i + 1)."\n" : "".($i + 1)."\n"; } echo "
\n\n"; } function echo_message($msg) { echo "

$msg

\n\n"; } function echo_error($msg) { echo "

$msg

\n\n"; } function echo_tip($tip) { if ($tip == "") { $tip = join('', file("tip.txt")); $tip = str_replace("\n", "
", $tip); } echo "
$tip
\n\n"; } function echo_head($squery) { echo join('', file("../_header.shtml")); echo "
\n\n

Поиск по сайту

\n"; echo_tip(""); ?>
"; echo join('', file("../_footer.inc")); } ?>