Ravens PHP Scripts: Forums
 

 

View next topic
View previous topic
Post new topic   Reply to topic    Ravens PHP Scripts And Web Hosting Forum Index -> Modules
Author Message
kadabram
Hangin' Around



Joined: Oct 29, 2007
Posts: 30

PostPosted: Wed Apr 29, 2009 6:37 pm Reply with quote

Hello,

I use a very useful module, called KwSearch. It performs a search directly on the database, including Web_Links.

When you do a search into Web_Links, and when you search for plain words like Britney Spears (lol) it displays the results correctly. But when you search for a URL like http://www.ravenphpscripts.com then it does not return any results (BTW, I noticed it's the same with the search field that comes with the Web_Links module).
Is there anything wrong with the code? I tried to add "url" variable but it didn't help.

Do you have an idea that will help?

Thanks a lot.


Last edited by kadabram on Wed May 06, 2009 7:03 am; edited 3 times in total 
View user's profile Send private message
kadabram







PostPosted: Wed Apr 29, 2009 6:46 pm Reply with quote

index page code:
Code:


<?php

/************************************************************************/
/* PHP-NUKE: Web Portal System                                          */
/* ===========================                                          */
/*                                                                      */
/* Copyright (c) 2002 by Francisco Burzi                                */
/* http://phpnuke.org                                                   */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/
/*         Additional security & Abstraction layer conversion           */
/*                           2003 chatserv                              */
/*      http://www.nukefixes.com -- http://www.nukeresources.com        */
/************************************************************************/
// Modified by Alessandro Trebbi (a.trebbi@gmail.com)

if (!eregi("modules.php", $_SERVER['PHP_SELF'])) {
    die ("You can't access this file directly...");
}

require_once("mainfile.php");
$module_name = basename(dirname(__FILE__));
get_lang($module_name);


require_once("modules/".$module_name."/lib/KwIndex.lib.php");


class NukeKwIndex extends KwIndex {

      function &document_sub($doc_ids) {
         global $db, $prefix;

         $docs = array();

         foreach($doc_ids as $doc_id) {
             switch (substr($doc_id,0,1)) {
                case '1':
                    // pagine
                    $query = "SELECT pid, title, subtitle, page_header, text, page_footer FROM ".$prefix."_pages WHERE pid=".substr($doc_id,1);
                    $res = $db->sql_query($query);
                    while($row = $db->sql_fetchrow($res)) {
                        $docs[$doc_id] =  strip_tags($row[1]." ".$row[2]." ".$row[3]." ".$row[4]." ".$row[5]);
                    }
                    break;

                case '2':
                    // news
                    $query = "SELECT sid, title, hometext, bodytext, notes FROM ".$prefix."_stories WHERE sid=".substr($doc_id,1);
                    $res = $db->sql_query($query);
                    while($row = $db->sql_fetchrow($res)) {
                        $docs[$doc_id] =  strip_tags($row[1]." ".$row[2]." ".$row[3]." ".$row[4]);
                    }
                    break;

                case '3':
                    // downloads
                    $query = "SELECT lid, title, description FROM ".$prefix."_downloads_downloads WHERE lid=".substr($doc_id,1);
                    $res = $db->sql_query($query);
                    while($row = $db->sql_fetchrow($res)) {
                        $docs[$doc_id] =  strip_tags($row[1]." ".$row[2]);
                    }
                    break;

                case '4':
                    // links
                    $query = "SELECT lid, title, description FROM ".$prefix."_links_links WHERE lid=".substr($doc_id,1);
                    $res = $db->sql_query($query);
                    while($row = $db->sql_fetchrow($res)) {
                        $docs[$doc_id] = strip_tags($row[1]." ".$row[2]);
                    }
                    break;

                case '5':
                    // eventi
                    $query = "SELECT eid, title, hometext FROM ".$prefix."_events WHERE eid=".substr($doc_id,1);
                    $res = $db->sql_query($query);
                    while($row = $db->sql_fetchrow($res)) {
                        $docs[$doc_id] = strip_tags($row[1]." ".$row[2]);
                    }
                    break;

                case '6':
                    // recensioni
                    $query = "SELECT id, title, text FROM ".$prefix."_reviews WHERE id=".substr($doc_id,1);
                    $res = $db->sql_query($query);
                    while($row = $db->sql_fetchrow($res)) {
                        $docs[$doc_id] = strip_tags($row[1]." ".$row[2]);
                    }
                    break;

                case '7':
                    // commenti
                    $query = "SELECT tid, subject, comment FROM ".$prefix."_comment WHERE tid=".substr($doc_id,1);
                    $res = $db->sql_query($query);
                    while($row = $db->sql_fetchrow($res)) {
                        $docs[$doc_id] = strip_tags($row[1]." ".$row[2]);
                    }
                    break;
             }

         }

         return $docs;
      }

}


global $admin, $prefix, $db, $module_name, $articlecomm, $multilingual, $days;


// se necessario ricrea l'indice del sito
rebuildIndex();


if ($fmt=="xml") {
    xmlheader();
} else {
   $ThemeSel = get_theme();
         $offset=10;
         if (!isset($min)) $min=0;
         if (!isset($max)) $max=$min+$offset;
         $query = stripslashes(check_html($query, nohtml));
   $pagetitle = "- "._SEARCH."";
         include("header.php");
         $topic = intval($topic);
   if ($topic>0) {
      $row = $db->sql_fetchrow($db->sql_query("SELECT topicimage, topictext from ".$prefix."_topics where topicid='$topic'"));
      $topicimage = $row['topicimage'];
      $topictext = $row['topictext'];
      if (file_exists("themes/$ThemeSel/images/topics/$topicimage")) {
      $topicimage = "themes/$ThemeSel/images/topics/$topicimage";
      } else {
      $topicimage = "$tipath/$topicimage";
      }
   } else {
      $topictext = ""._ALLTOPICS."";
      if (file_exists("themes/$ThemeSel/images/topics/AllTopics.gif")) {
      $topicimage = "themes/$ThemeSel/images/topics/AllTopics.gif";
      } else {
      $topicimage = "$tipath/AllTopics.gif";
      }
   }
   if (file_exists("themes/$ThemeSel/images/topics/AllTopics.gif")) {
      $alltop = "themes/$ThemeSel/images/topics/AllTopics.gif";
   } else {
      $alltop = "$tipath/AllTopics.gif";
   }
   OpenTable();
   if ($type == "users") {
      echo "<center><font class=\"title\"><b>"._SEARCHUSERS."</b></font></center><br>";
   } elseif ($type == "reviews") {
      echo "<center><font class=\"title\"><b>"._SEARCHREVIEWS."</b></font></center><br>";
   } elseif ($type == "comments" AND isset($sid)) {
      $res = $db->sql_query("select title from ".$prefix."_stories where sid='$sid'");
      list($st_title) = $db->sql_fetchrow($res);
         $instory = "AND sid='$sid'";
      echo "<center><font class=\"title\"><b>"._SEARCHINSTORY." $st_title</b></font></center><br>";
   } else {
      echo "<center><font class=\"title\"><b>"._SEARCHIN." $topictext</b></font></center><br>";
   }

   echo "<table width=\"100%\" border=\"0\"><TR><TD>";
   if (($type == "users") OR ($type == "reviews")) {
      echo "<img src=\"$alltop\" align=\"right\" border=\"0\" alt=\"\">";
         } else {
      echo "<img src=\"$topicimage\" align=\"right\" border=\"0\" alt=\"$topictext\">";
   }
   echo "<form action=\"modules.php?name=$module_name\" method=\"POST\">"
            ."<input size=\"25\" type=\"text\" name=\"query\" value=\"$query\">&nbsp;&nbsp;"
      ."<input type=\"submit\" value=\""._SEARCH."\"><br><br>";
   if (isset($sid)) {
      echo "<input type='hidden' name='sid' value='$sid'>";
   }
         echo "<!-- Topic Selection -->";
   $toplist = $db->sql_query("SELECT topicid, topictext from ".$prefix."_topics order by topictext");
   echo "<select name=\"topic\">";
         echo "<option value=\"\">"._ALLTOPICS."</option>\n";
         while($row2 = $db->sql_fetchrow($toplist)) {
         $topicid = intval($row2['topicid']);
         $topics = $row2['topictext'];
               if ($topicid==$topic) { $sel = "selected "; }
               echo "<option $sel value=\"$topicid\">$topics</option>\n";
      $sel = "";
         }
   echo "</select>";
   /* Category Selection */
   $category = intval($category);
   echo "&nbsp;<select name=\"category\">";
         echo "<option value=\"0\">"._ARTICLES."</option>\n";
   $result3 = $db->sql_query("SELECT catid, title from ".$prefix."_stories_cat order by title");
   while ($row3 = $db->sql_fetchrow($result3)) {
   $catid = intval($row3['catid']);
   $title = $row3['title'];
               if ($catid==$category) { $sel = "selected "; }
               echo "<option $sel value=\"$catid\">$title</option>\n";
      $sel = "";
         }
   echo "</select>";
   /* Authors Selection */
         $thing = $db->sql_query("SELECT aid from ".$prefix."_authors order by aid");
   echo "&nbsp;<select name=\"author\">";
         echo "<option value=\"\">"._ALLAUTHORS."</option>\n";
         while($row4 = $db->sql_fetchrow($thing)) {
         $authors = $row4['aid'];
               if ($authors==$author) { $sel = "selected "; }
      echo "<option value=\"$authors\">$authors</option>\n";
      $sel = "";
         }
         echo "</select>";
         /* Date Selection */
         ?>
   &nbsp;<select name="days">
               <option <?php echo $days == 0 ? "selected " : ""; ?> value="0"><?php echo _ALL ?></option>
               <option <?php echo $days == 7 ? "selected " : ""; ?> value="7">1 <?php echo _WEEK ?></option>
               <option <?php echo $days == 14 ? "selected " : ""; ?> value="14">2 <?php echo _WEEKS ?></option>
               <option <?php echo $days == 30 ? "selected " : ""; ?> value="30">1 <?php echo _MONTH ?></option>
      <option <?php echo $days == 60 ? "selected " : ""; ?> value="60">2 <?php echo _MONTHS ?></option>
               <option <?php echo $days == 90 ? "selected " : ""; ?> value="90">3 <?php echo _MONTHS ?></option>
         </select><br>
   <?php
   if (($type == "all") OR ($type == "")) {
         $sel0 = "checked";
   } elseif ($type == "stories") {
      $sel1 = "checked";
   } elseif ($type == "comments") {
      $sel2 = "checked";
   } elseif ($type == "users") {
      $sel3 = "checked";
   } elseif ($type == "reviews") {
      $sel4 = "checked";
   }
   $num_rev = $db->sql_numrows($db->sql_query("SELECT * from ".$prefix."_reviews"));
   echo ""._SEARCHON."";
   echo "<input type=\"radio\" name=\"type\" value=\"all\" $sel0> All";
   echo "<input type=\"radio\" name=\"type\" value=\"stories\" $sel1> "._SSTORIES."";
   if ($articlecomm == 1) {
      echo "<input type=\"radio\" name=\"type\" value=\"comments\" $sel2> "._SCOMMENTS."";
   }
   echo "<input type=\"radio\" name=\"type\" value=\"users\" $sel3> "._SUSERS."";
   if ($num_rev > 0) {
      echo "<input type=\"radio\" name=\"type\" value=\"reviews\" $sel4> "._REVIEWS."";
         }
   echo "</form></td></tr></table>";
}


// statistiche indice
echo "Ricerca  su ".getDocNumber()." documenti<br>";


if (is_admin($admin)) {
    echo "<a href=\"modules.php?name=$name&forcerebuild=1\">Ricostruzione indice</a>";
}


if (isset($query) && $query!="") {
       global $db, $prefix, $query, $currentlang;
      $doc_ids=array();

      echo "<br><hr noshade size=\"1\"><center><b>"._SEARCHRESULTS."</b></center><br><br>";

      $p = array (
            "index_name" => $prefix."_siteindex",
      );

      $kw = new NukeKwIndex($p);

      // ricerca...
      $p = array('words'=>$query,'boolean'=>'AND');
      $doc_ids = $kw->search($p);

      if (!isset($doc_ids))
            die("can't search: ".$kw->ERROR);

      // metto davanti quelli piu' recenti
      rsort($doc_ids, SORT_NUMERIC);

      // visualizzo solo quelli della pagina che stavo cercando
      /*
      $doc_ids = array_slice($doc_ids, ($pagina-1)*$risPerPg-$risultati+$trovati,
         $risPerPg-$trovati);
        */

        $time = time();

        foreach ($doc_ids as $doc_id) {
         switch (substr($doc_id,0,1)) {
            case '1':
                // pagine
                $stmt = "SELECT pid, title, subtitle, page_header, text, page_footer, clanguage, date, active FROM ".$prefix."_pages WHERE pid=".substr($doc_id,1);
                $res = $db->sql_query($stmt);
                while($row = $db->sql_fetchrow($res)) {
                      $subject = $row[1];
                      $link = "modules.php?name=Content&amp;pa=showpage&amp;pid=".substr($doc_id,1);
                     $a_body = $row[2]." ".$row[3]." ".$row[4]." ".$row[5];
                           $doclang = $row[clanguage];
                           $doctopic = "";
                           $docauthor = "";
                           $doctime = mktime(0,0,0,intval(substr($row[date],5,2)),intval(substr($row[date],8,2)),intval(substr($row[date],0,4)));

                           if ($row[active]!=1)
                               continue;
                }
                break;

            case '2':
                // news
                $stmt = "SELECT sid, title, hometext, bodytext, notes, alanguage, topic, aid, time FROM ".$prefix."_stories WHERE sid=".substr($doc_id,1);
                $res = $db->sql_query($stmt);
                while($row = $db->sql_fetchrow($res)) {
                      $subject = $row[1];
                      $link = "modules.php?name=News&amp;file=article&amp;sid=".substr($doc_id,1);
                     $a_body = $row[2]." ".$row[3]." ".$row[4];
                     $doclang = $row[alanguage];
                     $doctopic = $row[topic];
                     $docauthor = $row[aid];
                     $doctime = mktime(0,0,0,intval(substr($row[time],5,2)),intval(substr($row[time],8,2)),intval(substr($row[time],0,4)));
                }
                break;

            case '3':
                // downloads
                $stmt = "SELECT lid, title, description, cid, date FROM ".$prefix."_downloads_downloads WHERE lid=".substr($doc_id,1);
                $res = $db->sql_query($stmt);
                while($row = $db->sql_fetchrow($res)) {
                      $subject = $row[1];

                      //$link = "modules.php?name=Downloads&amp;d_op=viewdownloaddetails&amp;lid=".substr($doc_id,1)."&amp;title=".$row[1];
                     $link = "modules.php?name=Downloads&amp;d_op=viewdownload&amp;cid=".$row[cid];

                     $a_body = $row[2];
                     $doclang = "";
                     $doctopic = "";
                     $docauthor = "";
                     $doctime = mktime(0,0,0,intval(substr($row[date],5,2)),intval(substr($row[date],8,2)),intval(substr($row[date],0,4)));
                }
                break;

            case '4':
                // links
                $stmt = "SELECT lid, title, description, cid, date FROM ".$prefix."_links_links WHERE lid=".substr($doc_id,1);
                $res = $db->sql_query($stmt);
                while($row = $db->sql_fetchrow($res)) {
                      $subject = $row[1];

                      //$link = "links.html?amp;l_op=viewlinkdetails&amp;lid=".substr($doc_id,1)."&amp;ttitle=".$row[1];
                     $link = "links.html?amp;l_op=viewlink&amp;cid=".$row[cid];

                     $a_body = $row[2];
                     $doclang = "";
                     $doctopic = "";
                     $docauthor = "";
                     $doctime = mktime(0,0,0,intval(substr($row[date],5,2)),intval(substr($row[date],8,2)),intval(substr($row[date],0,4)));
                }
                break;

            case '5':
                // eventi
                $stmt = "SELECT eid, title, hometext, topic, aid, time FROM ".$prefix."_events WHERE eid=".substr($doc_id,1);
                $res = $db->sql_query($stmt);
                while($row = $db->sql_fetchrow($res)) {
                     $subject = $row[1];
                     $link = "modules.php?name=Calendar&amp;file=index&amp;type=view&amp;eid=".substr($doc_id,1);
                     $a_body = $row[2];
                     $doclang = "";
                     $doctopic = $row[topic];
                     $docauthor = $row[aid];
                     $doctime = mktime(0,0,0,intval(substr($row[time],5,2)),intval(substr($row[time],8,2)),intval(substr($row[time],0,4)));
                }
                break;

            case '6':
                // recensioni
                $stmt = "SELECT id, title, text, rlanguage, date FROM ".$prefix."_reviews WHERE id=".substr($doc_id,1);
                $res = $db->sql_query($stmt);
                while($row = $db->sql_fetchrow($res)) {
                     $subject = $row[1];
                     $link = "reviews.html?amp;rop=showcontent&amp;id=".substr($doc_id,1);
                     $a_body = $row[2];
                     $doclang = $row[rlanguage];
                     $doctopic = "";
                     $docauthor = "";
                     $doctime = mktime(0,0,0,intval(substr($row[date],5,2)),intval(substr($row[date],8,2)),intval(substr($row[date],0,4)));
                }
                break;

            case '7':
                // commenti
                $stmt = "SELECT tid, subject, comment, sid, pid, date FROM ".$prefix."_comments WHERE tid=".substr($doc_id,1);
                $res = $db->sql_query($stmt);
                while($row = $db->sql_fetchrow($res)) {
                       $subject = $row[1];
                       if ($row[sid] != "") {
                        $link = "modules.php?name=News&amp;file=article&amp;sid=".$row[sid];
                           }
                     $a_body = $row[2];
                     $doclang = "";
                     $docauthor = "";
                     $doctime = mktime(0,0,0,intval(substr($row[date],5,2)),intval(substr($row[date],8,2)),intval(substr($row[date],0,4)));
                }
                break;

         }

            // controllo su lingua del documento
            if ($multilingual == 1) {
               if ($doclang != "" && $doclang != $currentlang)
                   continue;
           }

            // controllo su topic
            if (isset($topic) && $topic != "") {
                 if ($doctopic != "" && $doctopic != $topic)
                     continue;
            }

            // controllo su autore
            if (isset($author) && $author != "") {
                 if ($docauthor != "" && $docauthor != $author)
                     continue;
            }

            // controllo su data
            if ($days != 0 && isset($doctime)) {
                 $docdays = ($time - $doctime) / 86400;
                 if ($docdays>$days) {
                     continue;
                 }
            }

         $trovati++;

         // faccio il display dei soli risultati della pagina corrente
         // 1-10 11-20 21-30 ...
         /*
         if ($risultati < ($pagina-1)*$risPerPg+1 ||
            $risultati > ($pagina)*$risPerPg)
            continue;
         */


         $a_body = strip_tags($a_body);
         //htmlspecialchars($abody);


         // elaboro $a_body, mi interessano solo le parti "intorno" alle stringhe cercate
         /*
         foreach($search_words as $search_word) {
            $string = eregi_replace("($search_word)",'<span style="background-color: '.$bgcolor.'">\\1</span>', $string);
         }
         */

         //$warr   = str_word_count($query, 1);
         $warr = preg_split("/[\s,]+/", $query);

         $bgcolor="#ffff00";
         foreach($warr as $w) {
            $a_body = eregi_replace("($w)",
              '<span style="background-color: '.$bgcolor.'">\\1</span>',
              $a_body);
            $subject = eregi_replace("($w)",
              '<span style="background-color: '.$bgcolor.'">\\1</span>',
              $subject);
         }

         $lenFrag=255;

         // taglio l'inizio e la fine di a_body
         $posword = strpos($a_body,'<');
         if (!$posword==false && $posword>$lenFrag)
            $a_body = "...".substr($a_body, $posword-$lenFrag);

         //$posword = strrpos($a_body,'</span>');
         // cerca solo un carattere singolo
         $posword = _strrpos_needle($a_body,'>');
         if (!$posword==false && $posword<strlen($a_body)-$lenFrag)
            $a_body = substr($a_body,0,$posword+$lenFrag)."...";

         // ultima cosa, andrebbero filtrate le parti in mezzo tra le varie
         // stringhe trovate

         $a_body = eregi_replace("(>[^\<\>]{".$lenFrag."})([^\<\>]+)([^\<\>]{".$lenFrag."}\<)",
         //$a_body = eregi_replace("(>[^\<\>]{255})([^\<\>]+)([^\<\>]{255}\<)",
              '\\1...\\3',
              $a_body);

           if ($fmt=="xml") {
               echo "<SearchResult>\n"
               ." <TITLE>$subject</TITLE>\n"
                ." <LINK>$link</LINK>\n"
                   ." <CONTENT>$a_body</CONTENT>\n"
                   ."</SearchResult>\n";
           } else {
               echo("<br><a href=\"$link\"><font class=\"title\">$subject</font></a>&nbsp;&nbsp;(".date("M-d-Y",$doctime).")<br><br>$a_body<br><br>");
           }
        }

        if ($fmt=="xml") {
            xmlfooter();
            die();
        }

      if ($trovati==0) {
            echo "<br>Nessuna pagina trovata<br>";
        }

        // altre ricerche
      echo "<br>";
      /*if (is_active("Downloads")) {
          $dcnt = $db->sql_numrows($db->sql_query("SELECT * from ".$prefix."_downloads_downloads WHERE title LIKE '%$query%' OR description LIKE '%$query%'"));
          $mod1 = "<li> <a href=\"modules.php?name=Downloads&amp;d_op=search&amp;query=$query\">"._DOWNLOADS."</a> ($dcnt "._SEARCHRESULTS.")";
      }
      /*if (is_active("Web_Links")) {
          $lcnt = $db->sql_numrows($db->sql_query("SELECT * from ".$prefix."_links_links WHERE title LIKE '%$query%' OR description LIKE '%$query%'"));
          $mod2 = "<li> <a href=\"links.html?amp;l_op=search&amp;query=$query\">"._WEBLINKS."</a> ($lcnt "._SEARCHRESULTS.")";
      }
      if (is_active("Encyclopedia")) {
          $ecnt1 = $db->sql_query("SELECT eid from ".$prefix."_encyclopedia WHERE active='1'");
          $ecnt = 0;
          while($row_e = $db->sql_fetchrow($ecnt1)) {
                   $eid = intval($row_e['eid']);
         $ecnt2 = $db->sql_numrows($db->sql_query("select * from ".$prefix."_encyclopedia WHERE title LIKE '%$query%' OR description LIKE '%$query%' AND eid='$eid'"));
         $ecnt3 = $db->sql_numrows($db->sql_query("select * from ".$prefix."_encyclopedia_text WHERE title LIKE '%$query%' OR text LIKE '%$query%' AND eid='$eid'"));
         $ecnt = $ecnt+$ecnt2+$ecnt3;
          }
          $mod3 = "<li> <a href=\"modules.php?name=Encyclopedia&amp;file=search&amp;query=$query\">"._ENCYCLOPEDIA."</a> ($ecnt "._SEARCHRESULTS.")";
      }*/

// YOU CAN'T MODIFY FOLLOWING LINES
// IF YOU NEED TO HIDE OR MODIFY ANY PART OF THE FOOLOWING LINES AND REMOVE
// COPYRIGHT.PHP AITTLE FEE IS REQUIRED
// FOR DETAILS PLEASE CHECK http://www.madeinpesaro.com/contentid-26.html

      echo "<font class=\"title\">"._FINDMORE."<br><br>"
          .""._DIDNOTFIND."</font><br><br>"
          .""._SEARCH." \"<b>$query</b>\" "._ON.":<br><br>"
          ."<ul>"
          ."$mod1"
          ."$mod2"
          ."$mod3";

        if (is_active("Amazon")) {
         echo "<li> <a href=\"modules.php?name=Amazon&op=ShowResults&page=1&mode=books&keyword=$query\">Amazon (Books,...)</a>";
        }

        if (is_active("NewsGroups")) {
         echo "<li> <a href=\"news.htmlGroups&file=search&words=$query&action=search_all\">$sitename NewsGroups</a>";
        }

        global $currentlang;

        if ($currentlang=="italian")
           $hl = "it";
        else
           $hl = "en";

        $cof = rawurlencode("GALT:#008000;GL:1;DIV:#336699;VLC:663399;AH:center;BGC:FFFFFF;LBGC:336699;ALC:0000FF;LC:0000FF;T:000000;GFNT:0000FF;GIMP:0000FF;FORID:1;");

      echo "<li> <a href=\"http://www.google.com/custom?q=$query&sa=Ricerca&client=pub-7926667066499508&forid=1&ie=ISO-8859-1&oe=ISO-8859-1&cof=$cof&hl=$hl\" target=\"new\">Google</a>"
          ."</ul>";

//."<li> <a href=\"http://groups.google.com/groups?q=$query&client=pub-7926667066499508&forid=1\" target=\"new\">Google Groups</a>"

}

echo "<br>Search engine provided by <a href=\"http://www.madeinpesaro.com\">Made In Pesaro</a>";
// END OF UNMODIFIABLE PART


CloseTable();

include "footer.php";


function rebuildIndex() {
    global $db, $prefix, $forcerebuild;
    $last_ids = array(0,0,0,0,0,0,0,0,0);

    $doc_ids=array();

    $p = array (
            "index_name" => $prefix."_siteindex",
    );

    $kw = new NukeKwIndex($p);

    // in caso di forcerebuild va ripulito l'indice
    if ($forcerebuild==1) {
        $kw->empty_index();
    }

    // determino l'ultimo documento indicizzato
    $result = $db->sql_query("SELECT substring( max( id ) , 2  )  AS last_id, left( id, 1  )  AS tipo"
         ." FROM  `".$prefix."_siteindex_doclist`"
         ." GROUP BY tipo");
    while ($row = $db->sql_fetchrow($result)) {
       $last_ids[$row[tipo]-1] = $row[last_id];
    }

    // ricostruzione indice
    // pagine
    $result = $db->sql_query("select pid from ".$prefix."_pages where pid>$last_ids[0] order by pid limit 0, 10");
    while ($row = $db->sql_fetchrow($result)) {
       array_push($doc_ids, "1".$row[0]);
    }

    // news
    $result = $db->sql_query("select sid from ".$prefix."_stories where sid>$last_ids[1] order by sid limit 0, 10");
    while ($row = $db->sql_fetchrow($result)) {
       array_push($doc_ids, "2".$row[0]);
    }

    // downloads
    $result = $db->sql_query("select lid from ".$prefix."_downloads_downloads where lid>$last_ids[2] order by lid limit 0, 10");
    while ($row = $db->sql_fetchrow($result)) {
       array_push($doc_ids, "3".$row[0]);
    }

    // links
    $result = $db->sql_query("select lid from ".$prefix."_links_links where lid>$last_ids[3] order by lid limit 0, 10");
    while ($row = $db->sql_fetchrow($result)) {
       array_push($doc_ids, "4".$row[0]);
    }

    // eventi
    $result = $db->sql_query("select eid from ".$prefix."_events where eid>$last_ids[4] order by eid limit 0, 10");
    while ($row = $db->sql_fetchrow($result)) {
       array_push($doc_ids, "5".$row[0]);
    }

    // recensioni
    $result = $db->sql_query("select id from ".$prefix."_reviews where id>$last_ids[5] order by id limit 0, 10");
    while ($row = $db->sql_fetchrow($result)) {
       array_push($doc_ids, "6".$row[0]);
    }

    // commenti
    $result = $db->sql_query("select tid from ".$prefix."_comments where tid>$last_ids[6] order by tid limit 0, 10");
    while ($row = $db->sql_fetchrow($result)) {
       array_push($doc_ids, "7".$row[0]);
    }

    // alla fine di tutto
    $kw->add_document($doc_ids);

    // ottimizzazione indice
    // se compare in almeno 1/3 dei documenti non la indicizzo
    // SOLO SE CI SONO ALMENO 100 DOCUMENTI
    /*
    $result = $db->sql_query("select count(*) from ".$prefix."_siteindex_doclist");
    if ($row = $db->sql_fetchrow($result) && intval(getDocNumber())>=100) {
       $comwords = $kw->common_word(40);

       $kw->add_stop_word($comwords);

       $kw->remove_word($comwords);
    }
    */
}


function xmlheader() {

      global $db, $sitename;

      // Send headers
      header('Content-Type: text/xml');

        echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>";

echo "<!--\n"
    ."-\n"
   ."- Produced by $sitename\n"
    ."-\n"
    ."-->\n";

        echo "<KWSEARCH>\n";


}


function xmlfooter() {
        echo "</KWSEARCH>\n";
}


function getDocNumber() {
     global $db, $prefix;

    $result = $db->sql_query("select count(*) from ".$prefix."_siteindex_doclist");
    if ($row = $db->sql_fetchrow($result)) {
         return $row[0];
    }

     // errore
     return -1;
}


?>
 
kadabram







PostPosted: Wed Apr 29, 2009 6:49 pm Reply with quote

and KwIndex.lib.php page code:

Code:


<?php

/* ====================================================================
 * Copyright (c) 2000 Steven Haryanto.  All rights reserved.
 *
 * KwIndex
 *   A PHP module to do full text indexing with MySQL database
 *
 * This module is released under the GNU General Public License. See:
 *   http://www.gnu.org/copyleft/gpl.html
 *
 * Version
 *   0.04, Sat Dec  2 14:54:41 2000
 *   based on DBIx::KwIndex 0.03
 *
 * For documentation, support and latest version, visit:
 *   http://steven.haryan.to/php/KwIndex.html
 *
 * ====================================================================
 *

// Table Name Member added by Txarly :)

// Mofified by Alessandro Trebbi :
     - uses Nuke global db connection


 */

$debug = 0;

if($debug) require "Dumper.lib.php";

function _debug() {
   global $debug;

   $args = func_get_args();
   if (!$debug) return;
   echo "<pre>debug: ", htmlentities(join("", $args)), "</pre><br>\n";
}

class KwIndex {

   # CONSTRUCTOR
   #############

   function KwIndex(&$args) {
        global $db;

      # check for argument type
      if (!is_array($args))
         die("KwIndex: constructor: syntax: KwIndex(array \$args)");

      # check for unknown arguments
      $known_arguments = array_flip(array(
         "linkid", /*"db_name", "hostname", "username", "password",*/
         "index_name", "wordlist_cardinality", "doclist_cardinality",
         "stoplist_cardinality", "vectorlist_cardinality",
         "max_word_length", "use_persistent_connection",
                        "table_name")); // Table Name Member added by Txarly :)

        /*
      while(list($k,$v) = each($args))
         if (!isset($known_arguments[$k]))
            die("KwIndex: constructor: unknown argument `$k'");
        */

      # required for required arguments
      /*
      if (!isset($args["db_name"]))
         die("KwIndex: constructor: You must specify 'db_name'");
      if (!isset($args["linkid"]) &&
          (!isset($args["hostname"]) || !isset($args["username"]) ||
           !isset($args["password"])))
         die("KwIndex: constructor: You must either specify 'linkid' or ".
             "arguments to mysql_connect ('hostname', 'username', and ".
               "'password')");
        */

      # supply default values for optional arguments
      if (!isset($args["index_name"]))
         $args["index_name"] = "kwindex";
                if (!isset($args["table_name"]))
         $args["table_name"] = "HOLA";

      if (!isset($args["wordlist_cardinality"]))
         $args["wordlist_cardinality"] = 100000;
      if (!isset($args["stoplist_cardinality"]))
         $args["stoplist_cardinality"] = 10000;
      if (!isset($args["vectorlist_cardinality"]))
         $args["vectorlist_cardinality"] = 100000000;
      if (!isset($args["doclist_cardinality"]))
         $args["doclist_cardinality"] = 1000000;
      if (!isset($args["max_word_length"]))
         $args["max_word_length"] = 32;
      if (!isset($args["use_persistent_connection"]))
         $args["use_persistent_connection"] = 1;
      if (!isset($args["grp_id"]))
         $args["grp_id"] = -1;

      # set object attributes
      $this->db_name = $args["db_name"];
      $this->index_name = $args["index_name"];
      $this->wordlist_cardinality = $args["wordlist_cardinality"];
      $this->stoplist_cardinality = $args["stoplist_cardinality"];
      $this->vectorlist_cardinality = $args["vectorlist_cardinality"];
      $this->doclist_cardinality = $args["doclist_cardinality"];
      $this->max_word_length = $args["max_word_length"];
      $this->grp_id = $args["grp_id"];

/*
      if (!isset($args["linkid"])) {
         if ($args["use_persistent_connection"]) {
            $linkid = mysql_pconnect($args["hostname"], $args["username"],
                                     $args["password"]);
         } else {
            $linkid = mysql_connect($args["hostname"], $args["username"],
                                    $args["password"]);
         }
         if (!$linkid)
            die("KwIndex: constructor: Can't connect to database: ".
                mysql_error());
      } else {
         $linkid = $args["linkid"];
      }
*/

      $linkid = $db->db_connect_id;

      $this->linkid = $linkid;
      $idx = $this->index_name;

        /*
      if (!mysql_select_db($this->db_name, $linkid))
         die("KwIndex: constructor: Can't select DB: ".
             mysql_error($linkid));
        */

      if (!$this->_index_exists()) $this->_create_index();

      # load stoplist as keys of array
      $this->stoplist = array();
      if (!($res = $db->sql_query("SELECT word FROM `${idx}_stoplist`")))
         die("KwIndex: constructor: Can't load stoplist: ".
             mysql_error($linkid));
      while($row = $db->sql_fetchrow($res)) {
         $this->stoplist[ strtolower($row[0]) ] = 1;
      }
   } // constructor


   # PUBLIC METHODS
   ################

   function &document_sub($doc_ids) {
      die("KwIndex: document_sub: this method must be overriden");
   }

   function add_document(&$doc_ids) {
        global $db;

      if (!is_array($doc_ids))
         die("KwIndex: syntax: add_document(array \$doc_ids)");

      if (!sizeof($doc_ids)) return 1;

      $wordlist = array();
         # structure: ( 'word1' => [ [doc_id,freq], ... ], ... )
      $doclist = array();
         # format: ( doc_id => n, ... ); # n = number of words in document

      # retrieve documents
      ####################
      $docs = $this->document_sub($doc_ids);

      if(!is_array($docs))
         die("KwIndex: add_document: ".
             "'document_sub' does not return an array");
      if (sizeof($doc_ids) < sizeof($docs))
         die("KwIndex: add_document: ".
             "'document_sub' does not return enough documents");
      if (sizeof($doc_ids) > sizeof($docs))
         die("KwIndex: add_document: ".
             "'document_sub' returns too many documents");

      # split documents into words
      ############################
      while(list($id, $doc) = each($docs)) {
         if (!isset($doc) || !strlen($doc)) continue;

         $words = $this->_split_to_words($doc);
         $num_of_words = sizeof($words);
            # note: this means that numbers, etc are counted
         $doclist[$id] = $num_of_words;

         # filter non-qualifying words: 1-char length, numbers, words
         # that are too long

         $w2 = array();
         while(list($k, $v) = each($words)) {
            $len = strlen($v);
            $lower_v = strtolower($v);
            if ($len > 1 &&
                $len <= $this->max_word_length &&
                preg_match("/[a-z]/", $lower_v) &&
                !isset($this->stoplist[$lower_v])) ++$w2[ $lower_v ];
         }

         while(list($k, $v) = each($w2)) {
            $lower_k = strtolower($k);
            if (!isset($wordlist[$lower_k]))
               $wordlist[$lower_k] = array();
            array_push($wordlist[$lower_k], array($id, $v/$num_of_words));
         }
      }

#_debug("wordlist: ", Dumper($wordlist));

      # submit to database
      ####################
      $linkid = $this->linkid;
      $idx = $this->index_name;

      # lock the tables in case some other process remove a certain word
      # between step 0 and 1 and 2 and 3
      if(!$db->sql_query("LOCK TABLES `${idx}_doclist` WRITE, ".
                                  "`${idx}_vectorlist` WRITE, ".
                                  "`${idx}_wordlist` WRITE")) {
         $this->ERROR = "Can't lock tables when adding documents: ".
                         mysql_error($linkid);
         return;
      }

      # 0
      # add the docs first
#_debug( "doclist = ", Dumper($doclist));
      while(list($k,$v) = each($doclist)) {
         if(!$db->sql_query("REPLACE INTO `${idx}_doclist` (id,n) VALUES (".
                            "'".(addslashes($k))."'".
                            ",".
                            "'".(addslashes($v))."'".
                            ")")) {
            $this->ERROR = "Can't add doc id=`$_' to doclist: ".
                           mysql_error($linkid);
            $db->sql_query("UNLOCK TABLES");
            return;
         }
      }

      # 1
      # and then add the words
      while(list($k,$v) = each($wordlist)) {
         if(!$db->sql_query("INSERT IGNORE INTO `${idx}_wordlist` (word) ".
                                 "VALUES (".
                                    "'".(addslashes($k))."'".
                                 ")")) {
            $this->ERROR = "Can't add word `$k' to wordlist: ".
                           mysql_error($linkid);
            $db->sql_query("UNLOCK TABLES");
            return;
         }
      }

      # 2
      # get the resulting word ids
      $word_ids = array();
      $e_wordlist = array();
      reset($wordlist);
      while(list($k,$v) = each($wordlist))
         array_push($e_wordlist, "'".addslashes($k)."'");

      if (sizeof($wordlist)) {
         if(!($res = $db->sql_query("SELECT id,word FROM `${idx}_wordlist` ".
                                    "WHERE word IN (".
                                       join(',', $e_wordlist).
                                    ")"))) {
            $this->ERROR = "Can't get data from wordlist: ".
                           mysql_error($linkid);
            $db->sql_query('UNLOCK TABLES');
            return;
         }
         while($row = $db->sql_fetchrow($res)) {
#echo "row = ", Dumper($row), "<br>\n";
            $word_ids[ $row[1] ] = $row[0];
         }
      }

      # 3
      # now add the vectors
#_debug("word_ids = ", Dumper($word_ids));
      reset($wordlist);
      while (list($word, $hitlist) = each($wordlist)) {
         while(list($i, $hit) = each($hitlist)) {
#echo "adding word=$word, hit = ($hit[0], $hit[1])<br>\n";
            if(!$db->sql_query("INSERT INTO `${idx}_vectorlist` (wid,did,f)".
                              "VALUES (".
                                 ("'".addslashes($word_ids[$word]))."',".
                                 ("'".addslashes($hit[0]))."',".
                                 ("'".addslashes($hit[1]))."')")) {
               $this->ERROR = "Can't add to vectorlist: ".
                              mysql_error($linkid);
               $db->sql_query('UNLOCK TABLES');
               return;
            }
         }
      }

      # if all goes well, return TRUE
      $db->sql_query('UNLOCK TABLES');
      return 1;
   }


   function remove_document(&$doc_ids) {
        global $db;

      if (!is_array($doc_ids))
         die("KwIndex: syntax: remove_document(array \$doc_ids)");

      if (!sizeof($doc_ids)) return 1;

      $linkid = $this->linkid;
      $idx = $this->index_name;

      if(!$db->sql_query("LOCK TABLES `${idx}_doclist` WRITE, ".
                                  "`${idx}_vectorlist` WRITE")) {
         $this->ERROR = "Can't lock tables when removing documents: ".
                         mysql_error($linkid);
         return;
      }

      if(!$db->sql_query("DELETE FROM `${idx}_doclist` WHERE id IN (".
                         join(',', $doc_ids).")")) {
         $this->ERROR = "Can't delete from doclist: ".
                        mysql_error($linkid);
         $db->sql_query('UNLOCK TABLES');
         return;
      }

      if(!$db->sql_query("DELETE FROM `${idx}_vectorlist` WHERE did IN (".
                         join(',', $doc_ids).")")) {
         $this->ERROR = "Can't delete from vectorlist: ".
                        mysql_error($linkid);
         $db->sql_query('UNLOCK TABLES');
         return;
      }

      # if all goes well, return TRUE
      $db->sql_query("UNLOCK TABLES");
      return 1;
   }


   function update_document(&$doc_ids) {
      if (!is_array($doc_ids))
         die("KwIndex: syntax: update_document(array \$doc_ids)");

      if (!sizeof($doc_ids)) return 1;

      return $this->remove_document($doc_ids) &&
             $this->add_document($doc_ids);
   }


   # find all words that are contained in at least $k % of all documents

   function &common_word($k = 80) {
        global $db;

      $linkid = $this->linkid;
      $idx = $this->index_name;

      # first select the number of documents
      $num = $this->document_count();
      if ($num == -1) {
         $this->ERROR = "Can't retrieve the number of documents: ".
                        mysql_error($linkid);
         return;
      }

      # get the statistics from vectorlist
      if(!($res1 = $db->sql_query("SELECT wid,COUNT(*)/$num as k FROM
                                   `${idx}_vectorlist` GROUP BY wid HAVING k>=".
                                   ($k/100)))) {
         $this->ERROR = "Can't retrieve common words: ".
                        mysql_error($linkid);
         return;
      }
      $wids = array();
      while($row = $db->sql_fetchrow($res1)) array_push($wids, $row[0]);

      // convert it to word by consulting the wordlist table
      $words = array();
      if (sizeof($wids)) {
         if (!($res2 = $db->sql_query("SELECT word FROM `${idx}_wordlist` ".
                                      "WHERE id IN (".join(',', $wids).
                                       ")"))) {
            $this->ERROR = "Can't retrieve common words: ".
                           mysql_error($linkid);
            return;
         }

         while($row = $db->sql_fetchrow($res2))
            array_push($words, $row[0]);
      }

      return $words;
   }


   // find all words that are not contained in all documents (vectorlist)
   // XXX not yet written

   function &orphan_word() {
      return array();
   }


   // remove words from index

   function remove_word(&$words) {
        global $db;

      if (!is_array($words))
         die("KwIndex: syntax: remove_word(array \$words)");

      $linkid = $this->linkid;
      $idx = $this->index_name;

      if(!$db->sql_query("LOCK TABLES `${idx}_wordlist` WRITE, ".
                                  "`${idx}_vectorlist` WRITE")) {
         $this->ERROR = "Can't lock tables when removing words: ".
                         mysql_error($linkid);
         return;
      }

      $e_words = array();
      foreach ($words as $v) {
         array_push($e_words, "'".addslashes(strtolower($v))."'");
        }

      # retrieve word ids
        $consulta = "SELECT id FROM `${idx}_wordlist` WHERE ".
                                  "word IN (".join(',', $e_words).")";

      if(!($res0 = $db->sql_query($consulta))) {
         $this->ERROR = "Can't delete from wordlist: ".
                        mysql_error($linkid);
         $db->sql_query('UNLOCK TABLES');
         return;
      }

      $word_ids = array();
      while($row = $db->sql_fetchrow($res0))
         array_push($word_ids, $row[0]);
      $word_ids = join(',', $word_ids); // we'll make it a string

      if (!strlen($word_ids)) return 1;

        $consulta = "DELETE FROM `${idx}_wordlist` WHERE id IN ".
                         "($word_ids)";

        // delete from wordlist
      if(!$db->sql_query($consulta)) {
         $this->ERROR = "Can't delete from wordlist: ".
                        mysql_error($linkid);
         $db->sql_query("UNLOCK TABLES");
         return;
      }
      if(!$db->sql_query("DELETE FROM `${idx}_vectorlist` WHERE wid IN ".
                         "($word_ids)")) {
         $this->ERROR = "Can't delete from vectorlist: ".
                        mysql_error($linkid);
         $db->sql_query("UNLOCK TABLES");
         return;
      }

      return 1;
   }

   // add stop words. note: you must manually delete previously indexed
   // words with delete_word()

   function add_stop_word(&$words) {
        global $db;

      if (!is_array($words))
         die("KwIndex: syntax: add_stop_word(array words)");

      if (!sizeof($words)) return 1;

      $linkid = $this->linkid;
      $idx = $this->index_name;

      while(list($k, $v) = each($words)) {
         $lv = strtolower($v);
         if(!$db->sql_query("REPLACE INTO `${idx}_stoplist` (word) VALUES (".
                            ("'".addslashes($lv)."'").
                            ")")) {
            $this->ERROR = "Can't add to stoplist: ".
                           mysql_error($linkid);
            return;
         }
         $this->stoplist[ $lv ] = 1;
      }

      return 1;
   }

   // remove stop words from index

   function remove_stop_word(&$words) {
        global $db;

      if (!is_array($words))
         die("KwIndex: syntax: remove_stop_word(array words)");

      if (!sizeof($words)) return 1;

      $linkid = $this->linkid;
      $idx = $this->index_name;

      $e_words = array();
      while(list($k,$v) = each($words))
         array_push($e_words, "'".addslashes(strtolower($v))."'");

      if(!$db->sql_query("DELETE FROM `${idx}_stoplist` WHERE word IN (".
                         join(',', $e_words).")")) {
         $this->ERROR = "Can't delete from stoplist: ".
                        mysql_error($linkid);
         return;
      }

      while(list($k,$v) = each($words))
         unset($this->stoplist[ strtolower($v) ]);

      return 1;
   }

   function is_stop_word($word) {
      return isset($this->stoplist[ strtolower($word) ]);
   }

   function &_search_or_match_count($is_count, &$args) {
        global $db;

      if (!isset($args["words"]))
         die("KwIndex: search: option 'words' must be defined");

      $linkid = $this->linkid;
      $idx = $this->index_name;

      // split the words if we are offered a single string/not array
      // (assume it's a phrase)

      $words = array();
      if (is_array($args["words"])) {
         $words = $args["words"];
      } else {
         $words = $this->_split_to_words($args["words"]);
      }

      # delete duplicate words, convert them all to lowercase
      $hashwords = array();
      while(list($k,$v) = each($words)) $hashwords[ strtolower($v) ] = 1;
      $words = array_keys($hashwords);

      if (!sizeof($words)) {
         if ($is_count) {
            return 0;
         } else {
            return array();
         }
      }

      # first we retrieve the word ids
      $op = $args["re"] ? 'REGEXP':'LIKE';
      $bool = isset($args['boolean']) && $args['boolean'] &&
              strtoupper($args['boolean']) == 'AND' ? 'AND':'OR';

      $op_phrases = array();
      while(list($k,$v) = each($words))
         array_push($op_phrases, "word $op '".addslashes($v)."'");

//die("SELECT id FROM `${idx}_wordlist` WHERE ".join(' OR ', $op_phrases));

      if (!($res0 = $db->sql_query("SELECT id FROM `${idx}_wordlist` WHERE ".
                                   join(' OR ', $op_phrases)))) {
         $this->ERROR = "Can't retrieve word ids: ".mysql_error($linkid);
         return;
      }
      $word_ids = array();
      while($row = $db->sql_fetchrow($res0)) array_push($word_ids, $row[0]);

      if (!sizeof($word_ids) ||
          ($bool == 'AND' && sizeof($word_ids) < sizeof($words))) {
         if ($is_count) {
            return 0;
         } else {
            return array();
         }
      }

      # and then we search the vectorlist
      $can_optimize=0;
      $stmt = '';

      if ($is_count) {

         if ($bool == 'AND' && !$args['re']) {
            $stmt = 'SELECT did,count(wid) as c '.
                    "FROM `${idx}_vectorlist` WHERE wid IN (".
                       join(',',$word_ids).
                     ") ".
                    "GROUP BY did ".
                    "HAVING c >= ".sizeof($word_ids);
         } else {
            $can_optimize=1;
            $stmt = "SELECT COUNT(DISTINCT did) ".
                    "FROM `${idx}_vectorlist` WHERE wid IN (".
                       join(',',$word_ids).
                    ")";
         }

      } else { // ! $is_count

         $stmt = "SELECT did, count(wid) as c, avg(f) as a, ".
                        "count(wid)*count(wid)*count(wid)*avg(f) as ca ".

                 "FROM `${idx}_vectorlist` WHERE wid IN (".
                     join(',',$word_ids).
                 ") ".

                 "GROUP BY did ".
                 ($bool == 'AND' && !$args['re'] ?
                 "HAVING c >= ".sizeof($word_ids):'').
                 " ORDER BY ca DESC ".
                 (isset($args['num']) ? "LIMIT " . (isset($args['start']) ?
                 (($args['start'] - 1).",".$args['num']) : $args['num'])
                 :'');

      }

_debug("search SQL: ", $stmt);

      if(!($res = $db->sql_query($stmt))) {
         $this->ERROR = "Can't search vectorlist: ".mysql_error($linkid);
         return;
      }

      if ($is_count) {

         if ($can_optimize) {
            $row = $db->sql_fetchrow($res);
            return $row[0];
         } else {
            return $db->sql_numrows($res);
         }

      } else { // ! $is_count

         $doc_ids = array();
         while($row = $db->sql_fetchrow($res)) array_push($doc_ids, $row[0]);
         return $doc_ids;
      }
   }

   function &search(&$args) {
      return $this->_search_or_match_count(0, $args);
   }

   function &match_count(&$args) {
      return $this->_search_or_match_count(1, $args);
   }

   function remove_index() {
        global $db;

      $linkid = $this->linkid;
       $idx = $this->index_name;

      if(!$db->sql_query("DROP TABLE IF EXISTS `${idx}_wordlist`")) {
         $this->ERROR = "Can't remove table ${idx}_wordlist: ".
                        mysql_error($linkid);
         return;
      }
      if(!$db->sql_query("DROP TABLE IF EXISTS `${idx}_doclist`")) {
         $this->ERROR = "Can't remove table ${idx}_doclist: ".
                        mysql_error($linkid);
         return;
      }
      if(!$db->sql_query("DROP TABLE IF EXISTS `${idx}_vectorlist`")) {
         $this->ERROR = "Can't remove table ${idx}_vectorlist: ".
                        mysql_error($linkid);
         return;
      }
      if(!$db->sql_query("DROP TABLE IF EXISTS `${idx}_stoplist`")) {
         $this->ERROR = "Can't remove table ${idx}_stoplist: ".
                        mysql_error($linkid);
         return;
      }

      return 1;
   }

   function empty_index() {
      return $this->remove_index() && $this->_create_index();
   }

   # number of documents in the collection
   function document_count() {
        global $db;

      $linkid = $this->linkid;
       $idx = $this->index_name;

         if (!($res = $db->sql_query("SELECT COUNT(*) FROM `${idx}_doclist`"))) return;
         $row = $db->sql_fetchrow($res);
         return $row[0];
   }

   # number of unique words
   function word_count() {
       global $db;

      $linkid = $this->linkid;
      $idx = $this->index_name;

      if (!($res = $db->sql_query("SELECT COUNT(*) FROM `${idx}_wordlist`"))) return;
      $row = $db->sql_fetchrow($res);
      return $row[0];
   }


   # PRIVATE METHODS
   #################

   function &_split_to_words($str) {
      preg_match_all("/\b(\w[\w']*\w+|\w+)\b/", $str, $matches);
      return $matches[1];
   }

   function _create_index() {
        global $db;

      $linkid = $this->linkid;
       $idx = $this->index_name;

      $stmt = '';


      # drop previous tables, if they exist
      if (!$this->remove_index()) return;

      # create doclist table
      $stmt = "CREATE TABLE `${idx}_doclist` " .
              '(id ' . $this->_int_column_type($this->doclist_cardinality).
              ' AUTO_INCREMENT PRIMARY KEY, ' .
              ' n ' . $this->_int_column_type($this->wordlist_cardinality).
              ' NOT NULL'.
              ')';


      if (!$db->sql_query($stmt))
         die("KwIndex: Can't create table ${idx}_doclist: ".
             mysql_error($linkid));

      # create wordlist table
      $stmt = "CREATE TABLE `${idx}_wordlist` " .
              '(id ' . $this->_int_column_type($this->wordlist_cardinality) .
              ' AUTO_INCREMENT PRIMARY KEY, ' .
              " word VARCHAR($this->max_word_length)" .
              ' BINARY NOT NULL, ' .
              "UNIQUE (word) " .
              ')';

      if(!$db->sql_query($stmt))
         die("KwIndex: Can't create table ${idx}_wordlist: ".
             mysql_error($linkid));

      # create stoplist table
      $stmt = "CREATE TABLE `${idx}_stoplist` " .
              '(id ' . $this->_int_column_type($this->wordlist_cardinality).
              ' AUTO_INCREMENT PRIMARY KEY, ' .
              " word VARCHAR($this->max_word_length)" .
              ' BINARY NOT NULL, ' .
              "UNIQUE (word) " .
              ')';

      if (!$db->sql_query($stmt))
         die("KwIndex: Can't create table ${idx}_stoplist: ".
             mysql_error($linkid));

      # create vectorlist table
      $stmt = "CREATE TABLE `${idx}_vectorlist` " .
              '(wid '. $this->_int_column_type($this->wordlist_cardinality).
              ' NOT NULL, ' .
              'did '. $this->_int_column_type($this->doclist_cardinality).
              ' NOT NULL, '.
              'UNIQUE (wid,did), '.
              'f FLOAT(10,4) NOT NULL'.
              ')';

      if (!$db->sql_query($stmt)) {
         die("KwIndex: Can't create table ${idx}_vectorlist: ".
             mysql_error($linkid));
       }

      $this->stoplist = array();

      return 1;
   }

   function _int_column_type($cardinality) {
                if ($cardinality >= 16*1024*1024) return 'INT UNSIGNED';
                if ($cardinality >= 64*1024) return 'MEDIUMINT UNSIGNED';
                if ($cardinality >= 256) return 'SMALLINT UNSIGNED';
                return 'TINYINT UNSIGNED';
   }

   function &_index_tables() {
      $idx = $this->index_name;

      $tables = array(
         "${idx}_doclist",
         "${idx}_wordlist",
         "${idx}_vectorlist",
         "${idx}_stoplist");

      return $tables;
   }

   function _index_exists() {
        global $db;

      $linkid = $this->linkid;
       $idx = $this->index_name;

      if (!($res = mysql_list_tables($db->dbname, $linkid)))
         die("Can't list table: ".mysql_error($linkid));

      $existing_tables = array();
      $i = 0;
      while ($i < $db->sql_numrows($res)) {
         $existing_tables[ mysql_tablename($res, $i) ] = 1;
         $i++;
      }

      $index_tables = $this->_index_tables();
      while(list($k,$v) = each($index_tables)) {
         if (!isset($existing_tables[$v])) return 0;
      }

      return 1;
   }

} // class


/*
// funzioni di utilita'
function searchabstract(&$a_body) {

   $bgcolor="#ffff00";
   foreach($warr as $w) {
      $a_body = eregi_replace("($w)",
         '<span style="background-color: '.$bgcolor.'">\\1</span>',
         $a_body);
      $subject = eregi_replace("($w)",
         '<span style="background-color: '.$bgcolor.'">\\1</span>',
         $subject);
   }

    $lenFrag=255;

    // taglio l'inizio e la fine di a_body
   $posword = strpos($a_body,'<');
   if (!$posword==false && $posword>$lenFrag)
       $a_body = "...".substr($a_body, $posword-$lenFrag);

   //$posword = strrpos($a_body,'</span>');
   // cerca solo un carattere singolo
   $posword = _strrpos_needle($a_body,'>');
   if (!$posword==false && $posword<strlen($a_body)-$lenFrag)
       $a_body = substr($a_body,0,$posword+$lenFrag)."...";

    // ultima cosa, andrebbero filtrate le parti in mezzo tra le varie
   // stringhe trovate

   $a_body = eregi_replace("(>[^\<\>]{".$lenFrag."})([^\<\>]+)([^\<\>]{".$lenFrag."}\<)",
      //$a_body = eregi_replace("(>[^\<\>]{255})([^\<\>]+)([^\<\>]{255}\<)",
         '\\1...\\3',
         $a_body);
    }

*/

function _strrpos_needle($sourcestring,$needle){
  $tempString=$sourcestring;

  do {
   $tempPos=strpos($tempString,$needle);
   $tempString=substr($tempString,$tempPos+strlen($needle));
   $realPos=$realPos+$tempPos;
  } while (!is_bool($tempPos));

  return $realPos;

 }

?>
 
Palbin
Site Admin



Joined: Mar 30, 2006
Posts: 2583
Location: Pittsburgh, Pennsylvania

PostPosted: Wed Apr 29, 2009 8:56 pm Reply with quote

I believe we are aware of problems with the search function, but I am not the one to try respond. Montego is probably the best one to give you an answer, but I don't know when he might see this.

_________________
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan. 
View user's profile Send private message
jakec
Site Admin



Joined: Feb 06, 2006
Posts: 3048
Location: United Kingdom

PostPosted: Thu Apr 30, 2009 12:18 am Reply with quote

One question that pops to mind is why would you want to search for a URL? If you know what the address is then you can type it directly into the browser.
 
View user's profile Send private message
kadabram







PostPosted: Thu Apr 30, 2009 6:27 am Reply with quote

Hello jakec. It's useful for the webmasters who want to know if their Website is indexed in mine Wink . The other reason is that urls often are useful by themselves, because they contain some keywords related to the subject that we make a seach on.
 
kadabram







PostPosted: Wed May 06, 2009 6:47 am Reply with quote

I did write to the author of the script. Even if it is a very long time ago, this smart person did answer to me. He wrote:

try something like this:

Code:
case '4':

        // links
        $query = "SELECT lid, title, description, url FROM ".$prefix."_links_links WHERE lid=".substr($doc_id,1);
        $res = $db->sql_query($query);
        while($row = $db->sql_fetchrow($res)) {
        $docs[$doc_id] = strip_tags($row[1]." ".$row[2]." ".$row[3]);
        }
        break;



I applied the changes and the code is working (yes!) fine!
 
Display posts from previous:       
Post new topic   Reply to topic    Ravens PHP Scripts And Web Hosting Forum Index -> Modules

View next topic
View previous topic
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You can attach files in this forum
You can download files in this forum


Powered by phpBB © 2001-2007 phpBB Group
All times are GMT - 6 Hours
 
Forums ©