search.php 8.18 KB
Newer Older
dimitri's avatar
dimitri committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
function readInt($file)
{
  $b1 = ord(fgetc($file)); $b2 = ord(fgetc($file));
  $b3 = ord(fgetc($file)); $b4 = ord(fgetc($file));
  return ($b1<<24)|($b2<<16)|($b3<<8)|$b4;
}

function readString($file)
{
  $result="";
  while (ord($c=fgetc($file))) $result.=$c;
  return $result;
}

function readHeader($file)
{
dimitri's avatar
dimitri committed
17 18 19
  $header =fgetc($file); $header.=fgetc($file);
  $header.=fgetc($file); $header.=fgetc($file);
  return $header;
dimitri's avatar
dimitri committed
20 21 22 23
}

function computeIndex($word)
{
dimitri's avatar
dimitri committed
24 25 26 27 28 29 30 31 32
  // Fast string hashing
  //$lword = strtolower($word);
  //$l = strlen($lword);
  //for ($i=0;$i<$l;$i++)
  //{
  //  $c = ord($lword{$i});
  //  $v = (($v & 0xfc00) ^ ($v << 6) ^ $c) & 0xffff;
  //}
  //return $v;
dimitri's avatar
dimitri committed
33

dimitri's avatar
dimitri committed
34 35
  // Simple hashing that allows for substring search
  if (strlen($word)<2) return -1;
dimitri's avatar
dimitri committed
36
  // high char of the index
dimitri's avatar
dimitri committed
37 38
  $hi = ord($word{0});
  if ($hi==0) return -1;
dimitri's avatar
dimitri committed
39
  // low char of the index
dimitri's avatar
dimitri committed
40 41
  $lo = ord($word{1});
  if ($lo==0) return -1;
dimitri's avatar
dimitri committed
42
  // return index
dimitri's avatar
dimitri committed
43
  return $hi*256+$lo;
dimitri's avatar
dimitri committed
44 45 46 47 48 49 50 51 52
}

function search($file,$word,&$statsList)
{
  $index = computeIndex($word);
  if ($index!=-1) // found a valid index
  {
    fseek($file,$index*4+4); // 4 bytes per entry, skip header
    $index = readInt($file);
dimitri's avatar
dimitri committed
53
    if ($index) // found words matching the hash key
dimitri's avatar
dimitri committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    {
      $start=sizeof($statsList);
      $count=$start;
      fseek($file,$index);
      $w = readString($file);
      while ($w)
      {
        $statIdx = readInt($file);
        if ($word==substr($w,0,strlen($word)))
        { // found word that matches (as substring)
          $statsList[$count++]=array(
              "word"=>$word,
              "match"=>$w,
              "index"=>$statIdx,
              "full"=>strlen($w)==strlen($word),
              "docs"=>array()
              );
        }
        $w = readString($file);
      }
dimitri's avatar
dimitri committed
74 75 76
      $totalHi=0;
      $totalFreqHi=0;
      $totalFreqLo=0;
dimitri's avatar
dimitri committed
77 78 79
      for ($count=$start;$count<sizeof($statsList);$count++)
      {
        $statInfo = &$statsList[$count];
dimitri's avatar
dimitri committed
80 81 82
        $multiplier = 1;
        // whole word matches have a double weight
        if ($statInfo["full"]) $multiplier=2;
dimitri's avatar
dimitri committed
83 84 85 86 87 88 89 90
        fseek($file,$statInfo["index"]); 
        $numDocs = readInt($file);
        $docInfo = array();
        // read docs info + occurrence frequency of the word
        for ($i=0;$i<$numDocs;$i++)
        {
          $idx=readInt($file); 
          $freq=readInt($file); 
dimitri's avatar
dimitri committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104
          $docInfo[$i]=array("idx"  => $idx,
                             "freq" => $freq>>1,
                             "rank" => 0.0,
                             "hi"   => $freq&1
                            );
          if ($freq&1) // word occurs in high priority doc
          {
            $totalHi++;
            $totalFreqHi+=$freq*$multiplier;
          }
          else // word occurs in low priority doc
          {
            $totalFreqLo+=$freq*$multiplier;
          }
dimitri's avatar
dimitri committed
105
        }
dimitri's avatar
dimitri committed
106
        // read name and url info for the doc
dimitri's avatar
dimitri committed
107 108 109 110 111 112 113 114
        for ($i=0;$i<$numDocs;$i++)
        {
          fseek($file,$docInfo[$i]["idx"]);
          $docInfo[$i]["name"]=readString($file);
          $docInfo[$i]["url"]=readString($file);
        }
        $statInfo["docs"]=$docInfo;
      }
dimitri's avatar
dimitri committed
115
      $totalFreq=($totalHi+1)*$totalFreqLo + $totalFreqHi;
dimitri's avatar
dimitri committed
116 117 118
      for ($count=$start;$count<sizeof($statsList);$count++)
      {
        $statInfo = &$statsList[$count];
dimitri's avatar
dimitri committed
119 120 121
        $multiplier = 1;
        // whole word matches have a double weight
        if ($statInfo["full"]) $multiplier=2;
dimitri's avatar
dimitri committed
122 123 124 125
        for ($i=0;$i<sizeof($statInfo["docs"]);$i++)
        {
          $docInfo = &$statInfo["docs"];
          // compute frequency rank of the word in each doc
dimitri's avatar
dimitri committed
126 127 128 129 130 131 132 133 134 135 136
          $freq=$docInfo[$i]["freq"];
          if ($docInfo[$i]["hi"])
          {
            $statInfo["docs"][$i]["rank"]=
              (float)($freq*$multiplier+$totalFreqLo)/$totalFreq;
          }
          else
          {
            $statInfo["docs"][$i]["rank"]=
              (float)($freq*$multiplier)/$totalFreq;
          }
dimitri's avatar
dimitri committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        }
      }
    }
  }
  return $statsList;
}

function combine_results($results,&$docs)
{
  foreach ($results as $wordInfo)
  {
    $docsList = &$wordInfo["docs"];
    foreach ($docsList as $di)
    {
      $key=$di["url"];
      $rank=$di["rank"];
      if (in_array($key, array_keys($docs)))
      {
        $docs[$key]["rank"]+=$rank;
      }
      else
      {
        $docs[$key] = array("url"=>$key,
            "name"=>$di["name"],
            "rank"=>$rank
            );
      }
      $docs[$key]["words"][] = array(
               "word"=>$wordInfo["word"],
               "match"=>$wordInfo["match"],
               "freq"=>$di["freq"]
               );
    }
  }
  return $docs;
}

function filter_results($docs,&$requiredWords,&$forbiddenWords)
{
  $filteredDocs=array();
  while (list ($key, $val) = each ($docs)) 
  {
    $words = &$docs[$key]["words"];
    $copy=1; // copy entry by default
    if (sizeof($requiredWords)>0)
    {
      foreach ($requiredWords as $reqWord)
      {
        $found=0;
        foreach ($words as $wordInfo)
        { 
          $found = $wordInfo["word"]==$reqWord;
          if ($found) break;
        }
        if (!$found) 
        {
          $copy=0; // document contains none of the required words
          break;
        }
      }
    }
    if (sizeof($forbiddenWords)>0)
    {
      foreach ($words as $wordInfo)
      {
        if (in_array($wordInfo["word"],$forbiddenWords))
        {
          $copy=0; // document contains a forbidden word
          break;
        }
      }
    }
    if ($copy) $filteredDocs[$key]=$docs[$key];
  }
  return $filteredDocs;
}

function compare_rank($a,$b)
{
dimitri's avatar
dimitri committed
216 217 218 219
  if ($a["rank"] == $b["rank"]) 
  {
    return 0;
  }
dimitri's avatar
dimitri committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  return ($a["rank"]>$b["rank"]) ? -1 : 1; 
}

function sort_results($docs,&$sorted)
{
  $sorted = $docs;
  usort($sorted,"compare_rank");
  return $sorted;
}

function report_results(&$docs)
{
  echo "<table cellspacing=\"2\">\n";
  echo "  <tr>\n";
  echo "    <td colspan=\"2\"><h2>".search_results()."</h2></td>\n";
  echo "  </tr>\n";
  $numDocs = sizeof($docs);
  if ($numDocs==0)
  {
    echo "  <tr>\n";
    echo "    <td colspan=\"2\">".matches_text(0)."</td>\n";
    echo "  </tr>\n";
  }
  else
  {
    echo "  <tr>\n";
    echo "    <td colspan=\"2\">".matches_text($numDocs);
    echo "\n";
    echo "    </td>\n";
    echo "  </tr>\n";
    $num=1;
    foreach ($docs as $doc)
    {
      echo "  <tr>\n";
      echo "    <td align=\"right\">$num.</td>";
      echo     "<td><a class=\"el\" href=\"".$doc["url"]."\">".$doc["name"]."</a></td>\n";
      echo "  <tr>\n";
      echo "    <td></td><td class=\"tiny\">".report_matches()." ";
      foreach ($doc["words"] as $wordInfo)
      {
        $word = $wordInfo["word"];
        $matchRight = substr($wordInfo["match"],strlen($word));
        echo "<b>$word</b>$matchRight(".$wordInfo["freq"].") ";
      }
      echo "    </td>\n";
      echo "  </tr>\n";
      $num++;
    }
  }
  echo "</table>\n";
}

function main()
{
  if(strcmp('4.1.0', phpversion()) > 0) 
  {
    die("Error: PHP version 4.1.0 or above required!");
  }
  if (!($file=fopen("search.idx","rb"))) 
  {
    die("Error: Search index file could NOT be opened!");
  }
  if (readHeader($file)!="DOXS")
  {
    die("Error: Header of index file is invalid!");
  }
  $query="";
  if (array_key_exists("query", $_GET))
  {
    $query=$_GET["query"];
  }
  echo "<input class=\"search\" type=\"text\" name=\"query\" value=\"$query\" size=\"20\" accesskey=\"s\"/>\n";
  echo "</span>\n";
  echo "</form>\n";
  echo "</div>\n";
  $results = array();
  $requiredWords = array();
  $forbiddenWords = array();
  $foundWords = array();
dimitri's avatar
dimitri committed
299
  $word=strtok($query," ");
dimitri's avatar
dimitri committed
300 301 302 303 304 305 306
  while ($word) // for each word in the search query
  {
    if (($word{0}=='+')) { $word=substr($word,1); $requiredWords[]=$word; }
    if (($word{0}=='-')) { $word=substr($word,1); $forbiddenWords[]=$word; }
    if (!in_array($word,$foundWords))
    {
      $foundWords[]=$word;
dimitri's avatar
dimitri committed
307
      search($file,$word,$results);
dimitri's avatar
dimitri committed
308
    }
dimitri's avatar
dimitri committed
309
    $word=strtok(" ");
dimitri's avatar
dimitri committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
  }
  $docs = array();
  combine_results($results,$docs);
  // filter out documents with forbidden word or that do not contain
  // required words
  $filteredDocs = filter_results($docs,$requiredWords,$forbiddenWords);
  // sort the results based on rank
  $sorted = array();
  sort_results($filteredDocs,$sorted);
  // report results to the user
  report_results($sorted);
  fclose($file);
}

main();