1<?php 2/** 3 * Functions to create the fulltext search index 4 * 5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 6 * @author Andreas Gohr <andi@splitbrain.org> 7 * @author Tom N Harris <tnharris@whoopdedo.org> 8 */ 9 10if(!defined('DOKU_INC')) die('meh.'); 11 12// Version tag used to force rebuild on upgrade 13define('INDEXER_VERSION', 8); 14 15// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens) 16if (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2); 17 18// Asian characters are handled as words. The following regexp defines the 19// Unicode-Ranges for Asian characters 20// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block 21// I'm no language expert. If you think some ranges are wrongly chosen or 22// a range is missing, please contact me 23define('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai 24define('IDX_ASIAN2','['. 25 '\x{2E80}-\x{3040}'. // CJK -> Hangul 26 '\x{309D}-\x{30A0}'. 27 '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'. 28 '\x{F900}-\x{FAFF}'. // CJK Compatibility Ideographs 29 '\x{FE30}-\x{FE4F}'. // CJK Compatibility Forms 30 "\xF0\xA0\x80\x80-\xF0\xAA\x9B\x9F". // CJK Extension B 31 "\xF0\xAA\x9C\x80-\xF0\xAB\x9C\xBF". // CJK Extension C 32 "\xF0\xAB\x9D\x80-\xF0\xAB\xA0\x9F". // CJK Extension D 33 "\xF0\xAF\xA0\x80-\xF0\xAF\xAB\xBF". // CJK Compatibility Supplement 34 ']'); 35define('IDX_ASIAN3','['. // Hiragana/Katakana (can be two characters) 36 '\x{3042}\x{3044}\x{3046}\x{3048}'. 37 '\x{304A}-\x{3062}\x{3064}-\x{3082}'. 38 '\x{3084}\x{3086}\x{3088}-\x{308D}'. 39 '\x{308F}-\x{3094}'. 40 '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'. 41 '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'. 42 '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'. 43 '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'. 44 ']['. 45 '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'. 46 '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'. 47 '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'. 48 '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'. 49 '\x{31F0}-\x{31FF}'. 50 ']?'); 51define('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')'); 52 53/** 54 * Version of the indexer taking into consideration the external tokenizer. 55 * The indexer is only compatible with data written by the same version. 56 * 57 * @triggers INDEXER_VERSION_GET 58 * Plugins that modify what gets indexed should hook this event and 59 * add their version info to the event data like so: 60 * $data[$plugin_name] = $plugin_version; 61 * 62 * @author Tom N Harris <tnharris@whoopdedo.org> 63 * @author Michael Hamann <michael@content-space.de> 64 */ 65function idx_get_version(){ 66 static $indexer_version = null; 67 if ($indexer_version == null) { 68 $version = INDEXER_VERSION; 69 70 // DokuWiki version is included for the convenience of plugins 71 $data = array('dokuwiki'=>$version); 72 trigger_event('INDEXER_VERSION_GET', $data, null, false); 73 unset($data['dokuwiki']); // this needs to be first 74 ksort($data); 75 foreach ($data as $plugin=>$vers) 76 $version .= '+'.$plugin.'='.$vers; 77 $indexer_version = $version; 78 } 79 return $indexer_version; 80} 81 82/** 83 * Measure the length of a string. 84 * Differs from strlen in handling of asian characters. 85 * 86 * @author Tom N Harris <tnharris@whoopdedo.org> 87 */ 88function wordlen($w){ 89 $l = strlen($w); 90 // If left alone, all chinese "words" will get put into w3.idx 91 // So the "length" of a "word" is faked 92 if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) { 93 foreach($leadbytes[0] as $b) 94 $l += ord($b) - 0xE1; 95 } 96 return $l; 97} 98 99/** 100 * Class that encapsulates operations on the indexer database. 101 * 102 * @author Tom N Harris <tnharris@whoopdedo.org> 103 */ 104class Doku_Indexer { 105 /** 106 * @var array $pidCache Cache for getPID() 107 */ 108 protected $pidCache = array(); 109 110 /** 111 * Adds the contents of a page to the fulltext index 112 * 113 * The added text replaces previous words for the same page. 114 * An empty value erases the page. 115 * 116 * @param string $page a page name 117 * @param string $text the body of the page 118 * @return boolean the function completed successfully 119 * @author Tom N Harris <tnharris@whoopdedo.org> 120 * @author Andreas Gohr <andi@splitbrain.org> 121 */ 122 public function addPageWords($page, $text) { 123 if (!$this->lock()) 124 return "locked"; 125 126 // load known documents 127 $pid = $this->getPIDNoLock($page); 128 if ($pid === false) { 129 $this->unlock(); 130 return false; 131 } 132 133 $pagewords = array(); 134 // get word usage in page 135 $words = $this->getPageWords($text); 136 if ($words === false) { 137 $this->unlock(); 138 return false; 139 } 140 141 if (!empty($words)) { 142 foreach (array_keys($words) as $wlen) { 143 $index = $this->getIndex('i', $wlen); 144 foreach ($words[$wlen] as $wid => $freq) { 145 $idx = ($wid<count($index)) ? $index[$wid] : ''; 146 $index[$wid] = $this->updateTuple($idx, $pid, $freq); 147 $pagewords[] = "$wlen*$wid"; 148 } 149 if (!$this->saveIndex('i', $wlen, $index)) { 150 $this->unlock(); 151 return false; 152 } 153 } 154 } 155 156 // Remove obsolete index entries 157 $pageword_idx = $this->getIndexKey('pageword', '', $pid); 158 if ($pageword_idx !== '') { 159 $oldwords = explode(':',$pageword_idx); 160 $delwords = array_diff($oldwords, $pagewords); 161 $upwords = array(); 162 foreach ($delwords as $word) { 163 if ($word != '') { 164 list($wlen,$wid) = explode('*', $word); 165 $wid = (int)$wid; 166 $upwords[$wlen][] = $wid; 167 } 168 } 169 foreach ($upwords as $wlen => $widx) { 170 $index = $this->getIndex('i', $wlen); 171 foreach ($widx as $wid) { 172 $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 173 } 174 $this->saveIndex('i', $wlen, $index); 175 } 176 } 177 // Save the reverse index 178 $pageword_idx = join(':', $pagewords); 179 if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) { 180 $this->unlock(); 181 return false; 182 } 183 184 $this->unlock(); 185 return true; 186 } 187 188 /** 189 * Split the words in a page and add them to the index. 190 * 191 * @param string $text content of the page 192 * @return array list of word IDs and number of times used 193 * @author Andreas Gohr <andi@splitbrain.org> 194 * @author Christopher Smith <chris@jalakai.co.uk> 195 * @author Tom N Harris <tnharris@whoopdedo.org> 196 */ 197 protected function getPageWords($text) { 198 199 $tokens = $this->tokenizer($text); 200 $tokens = array_count_values($tokens); // count the frequency of each token 201 202 $words = array(); 203 foreach ($tokens as $w=>$c) { 204 $l = wordlen($w); 205 if (isset($words[$l])){ 206 $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0); 207 }else{ 208 $words[$l] = array($w => $c); 209 } 210 } 211 212 // arrive here with $words = array(wordlen => array(word => frequency)) 213 $word_idx_modified = false; 214 $index = array(); //resulting index 215 foreach (array_keys($words) as $wlen) { 216 $word_idx = $this->getIndex('w', $wlen); 217 foreach ($words[$wlen] as $word => $freq) { 218 $word = (string)$word; 219 $wid = array_search($word, $word_idx, true); 220 if ($wid === false) { 221 $wid = count($word_idx); 222 $word_idx[] = $word; 223 $word_idx_modified = true; 224 } 225 if (!isset($index[$wlen])) 226 $index[$wlen] = array(); 227 $index[$wlen][$wid] = $freq; 228 } 229 // save back the word index 230 if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx)) 231 return false; 232 } 233 234 return $index; 235 } 236 237 /** 238 * Add/update keys to/of the metadata index. 239 * 240 * Adding new keys does not remove other keys for the page. 241 * An empty value will erase the key. 242 * The $key parameter can be an array to add multiple keys. $value will 243 * not be used if $key is an array. 244 * 245 * @param string $page a page name 246 * @param mixed $key a key string or array of key=>value pairs 247 * @param mixed $value the value or list of values 248 * @return boolean the function completed successfully 249 * @author Tom N Harris <tnharris@whoopdedo.org> 250 * @author Michael Hamann <michael@content-space.de> 251 */ 252 public function addMetaKeys($page, $key, $value=null) { 253 if (!is_array($key)) { 254 $key = array($key => $value); 255 } elseif (!is_null($value)) { 256 // $key is array, but $value is not null 257 trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING); 258 } 259 260 if (!$this->lock()) 261 return "locked"; 262 263 // load known documents 264 $pid = $this->getPIDNoLock($page); 265 if ($pid === false) { 266 $this->unlock(); 267 return false; 268 } 269 270 // Special handling for titles so the index file is simpler 271 if (array_key_exists('title', $key)) { 272 $value = $key['title']; 273 if (is_array($value)) 274 $value = $value[0]; 275 $this->saveIndexKey('title', '', $pid, $value); 276 unset($key['title']); 277 } 278 279 foreach ($key as $name => $values) { 280 $metaname = idx_cleanName($name); 281 $this->addIndexKey('metadata', '', $metaname); 282 $metaidx = $this->getIndex($metaname.'_i', ''); 283 $metawords = $this->getIndex($metaname.'_w', ''); 284 $addwords = false; 285 286 if (!is_array($values)) $values = array($values); 287 288 $val_idx = $this->getIndexKey($metaname.'_p', '', $pid); 289 if ($val_idx != '') { 290 $val_idx = explode(':', $val_idx); 291 // -1 means remove, 0 keep, 1 add 292 $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1)); 293 } else { 294 $val_idx = array(); 295 } 296 297 foreach ($values as $val) { 298 $val = (string)$val; 299 if ($val !== "") { 300 $id = array_search($val, $metawords, true); 301 if ($id === false) { 302 $id = count($metawords); 303 $metawords[$id] = $val; 304 $addwords = true; 305 } 306 // test if value is already in the index 307 if (isset($val_idx[$id]) && $val_idx[$id] <= 0) 308 $val_idx[$id] = 0; 309 else // else add it 310 $val_idx[$id] = 1; 311 } 312 } 313 314 if ($addwords) 315 $this->saveIndex($metaname.'_w', '', $metawords); 316 $vals_changed = false; 317 foreach ($val_idx as $id => $action) { 318 if ($action == -1) { 319 $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0); 320 $vals_changed = true; 321 unset($val_idx[$id]); 322 } elseif ($action == 1) { 323 $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1); 324 $vals_changed = true; 325 } 326 } 327 328 if ($vals_changed) { 329 $this->saveIndex($metaname.'_i', '', $metaidx); 330 $val_idx = implode(':', array_keys($val_idx)); 331 $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx); 332 } 333 334 unset($metaidx); 335 unset($metawords); 336 } 337 338 $this->unlock(); 339 return true; 340 } 341 342 /** 343 * Rename a page in the search index without changing the indexed content. This function doesn't check if the 344 * old or new name exists in the filesystem. It returns an error if the old page isn't in the page list of the 345 * indexer and it deletes all previously indexed content of the new page. 346 * 347 * @param string $oldpage The old page name 348 * @param string $newpage The new page name 349 * @return string|bool If the page was successfully renamed, can be a message in the case of an error 350 */ 351 public function renamePage($oldpage, $newpage) { 352 if (!$this->lock()) return 'locked'; 353 354 $pages = $this->getPages(); 355 356 $id = array_search($oldpage, $pages, true); 357 if ($id === false) { 358 $this->unlock(); 359 return 'page is not in index'; 360 } 361 362 $new_id = array_search($newpage, $pages, true); 363 if ($new_id !== false) { 364 // make sure the page is not in the index anymore 365 if ($this->deletePageNoLock($newpage) !== true) { 366 return false; 367 } 368 369 $pages[$new_id] = 'deleted:'.time().rand(0, 9999); 370 } 371 372 $pages[$id] = $newpage; 373 374 // update index 375 if (!$this->saveIndex('page', '', $pages)) { 376 $this->unlock(); 377 return false; 378 } 379 380 // reset the pid cache 381 $this->pidCache = array(); 382 383 $this->unlock(); 384 return true; 385 } 386 387 /** 388 * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages 389 * will be updated. 390 * 391 * @param string $key The metadata key of which a value shall be changed 392 * @param string $oldvalue The old value that shall be renamed 393 * @param string $newvalue The new value to which the old value shall be renamed, can exist (then values will be merged) 394 * @return bool|string If renaming the value has been successful, false or error message on error. 395 */ 396 public function renameMetaValue($key, $oldvalue, $newvalue) { 397 if (!$this->lock()) return 'locked'; 398 399 // change the relation references index 400 $metavalues = $this->getIndex($key, '_w'); 401 $oldid = array_search($oldvalue, $metavalues, true); 402 if ($oldid !== false) { 403 $newid = array_search($newvalue, $metavalues, true); 404 if ($newid !== false) { 405 // free memory 406 unset ($metavalues); 407 408 // okay, now we have two entries for the same value. we need to merge them. 409 $indexline = $this->getIndexKey($key.'_i', '', $oldid); 410 if ($indexline != '') { 411 $newindexline = $this->getIndexKey($key.'_i', '', $newid); 412 $pagekeys = $this->getIndex($key.'_p', ''); 413 $parts = explode(':', $indexline); 414 foreach ($parts as $part) { 415 list($id, $count) = explode('*', $part); 416 $newindexline = $this->updateTuple($newindexline, $id, $count); 417 418 $keyline = explode(':', $pagekeys[$id]); 419 // remove old meta value 420 $keyline = array_diff($keyline, array($oldid)); 421 // add new meta value when not already present 422 if (!in_array($newid, $keyline)) { 423 array_push($keyline, $newid); 424 } 425 $pagekeys[$id] = implode(':', $keyline); 426 } 427 $this->saveIndex($key.'_p', '', $pagekeys); 428 unset($pagekeys); 429 $this->saveIndexKey($key.'_i', '', $oldid, ''); 430 $this->saveIndexKey($key.'_i', '', $newid, $newindexline); 431 } 432 } else { 433 $metavalues[$oldid] = $newvalue; 434 if (!$this->saveIndex($key.'_w', '', $metavalues)) { 435 $this->unlock(); 436 return false; 437 } 438 } 439 } 440 441 $this->unlock(); 442 return true; 443 } 444 445 /** 446 * Remove a page from the index 447 * 448 * Erases entries in all known indexes. 449 * 450 * @param string $page a page name 451 * @return boolean the function completed successfully 452 * @author Tom N Harris <tnharris@whoopdedo.org> 453 */ 454 public function deletePage($page) { 455 if (!$this->lock()) 456 return "locked"; 457 458 $result = $this->deletePageNoLock($page); 459 460 $this->unlock(); 461 462 return $result; 463 } 464 465 /** 466 * Remove a page from the index without locking the index, only use this function if the index is already locked 467 * 468 * Erases entries in all known indexes. 469 * 470 * @param string $page a page name 471 * @return boolean the function completed successfully 472 * @author Tom N Harris <tnharris@whoopdedo.org> 473 */ 474 protected function deletePageNoLock($page) { 475 // load known documents 476 $pid = $this->getPIDNoLock($page); 477 if ($pid === false) { 478 return false; 479 } 480 481 // Remove obsolete index entries 482 $pageword_idx = $this->getIndexKey('pageword', '', $pid); 483 if ($pageword_idx !== '') { 484 $delwords = explode(':',$pageword_idx); 485 $upwords = array(); 486 foreach ($delwords as $word) { 487 if ($word != '') { 488 list($wlen,$wid) = explode('*', $word); 489 $wid = (int)$wid; 490 $upwords[$wlen][] = $wid; 491 } 492 } 493 foreach ($upwords as $wlen => $widx) { 494 $index = $this->getIndex('i', $wlen); 495 foreach ($widx as $wid) { 496 $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 497 } 498 $this->saveIndex('i', $wlen, $index); 499 } 500 } 501 // Save the reverse index 502 if (!$this->saveIndexKey('pageword', '', $pid, "")) { 503 return false; 504 } 505 506 $this->saveIndexKey('title', '', $pid, ""); 507 $keyidx = $this->getIndex('metadata', ''); 508 foreach ($keyidx as $metaname) { 509 $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid)); 510 $meta_idx = $this->getIndex($metaname.'_i', ''); 511 foreach ($val_idx as $id) { 512 if ($id === '') continue; 513 $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0); 514 } 515 $this->saveIndex($metaname.'_i', '', $meta_idx); 516 $this->saveIndexKey($metaname.'_p', '', $pid, ''); 517 } 518 519 return true; 520 } 521 522 /** 523 * Clear the whole index 524 * 525 * @return bool If the index has been cleared successfully 526 */ 527 public function clear() { 528 global $conf; 529 530 if (!$this->lock()) return false; 531 532 @unlink($conf['indexdir'].'/page.idx'); 533 @unlink($conf['indexdir'].'/title.idx'); 534 @unlink($conf['indexdir'].'/pageword.idx'); 535 @unlink($conf['indexdir'].'/metadata.idx'); 536 $dir = @opendir($conf['indexdir']); 537 if($dir!==false){ 538 while(($f = readdir($dir)) !== false){ 539 if(substr($f,-4)=='.idx' && 540 (substr($f,0,1)=='i' || substr($f,0,1)=='w' 541 || substr($f,-6)=='_w.idx' || substr($f,-6)=='_i.idx' || substr($f,-6)=='_p.idx')) 542 @unlink($conf['indexdir']."/$f"); 543 } 544 } 545 @unlink($conf['indexdir'].'/lengths.idx'); 546 547 // clear the pid cache 548 $this->pidCache = array(); 549 550 $this->unlock(); 551 return true; 552 } 553 554 /** 555 * Split the text into words for fulltext search 556 * 557 * TODO: does this also need &$stopwords ? 558 * 559 * @triggers INDEXER_TEXT_PREPARE 560 * This event allows plugins to modify the text before it gets tokenized. 561 * Plugins intercepting this event should also intercept INDEX_VERSION_GET 562 * 563 * @param string $text plain text 564 * @param boolean $wc are wildcards allowed? 565 * @return array list of words in the text 566 * @author Tom N Harris <tnharris@whoopdedo.org> 567 * @author Andreas Gohr <andi@splitbrain.org> 568 */ 569 public function tokenizer($text, $wc=false) { 570 $wc = ($wc) ? '' : '\*'; 571 $stopwords =& idx_get_stopwords(); 572 573 // prepare the text to be tokenized 574 $evt = new Doku_Event('INDEXER_TEXT_PREPARE', $text); 575 if ($evt->advise_before(true)) { 576 if (preg_match('/[^0-9A-Za-z ]/u', $text)) { 577 // handle asian chars as single words (may fail on older PHP version) 578 $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text); 579 if (!is_null($asia)) $text = $asia; // recover from regexp falure 580 } 581 } 582 $evt->advise_after(); 583 unset($evt); 584 585 $text = strtr($text, 586 array( 587 "\r" => ' ', 588 "\n" => ' ', 589 "\t" => ' ', 590 "\xC2\xAD" => '', //soft-hyphen 591 ) 592 ); 593 if (preg_match('/[^0-9A-Za-z ]/u', $text)) 594 $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc); 595 596 $wordlist = explode(' ', $text); 597 foreach ($wordlist as $i => $word) { 598 $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ? 599 utf8_strtolower($word) : strtolower($word); 600 } 601 602 foreach ($wordlist as $i => $word) { 603 if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) 604 || array_search($word, $stopwords, true) !== false) 605 unset($wordlist[$i]); 606 } 607 return array_values($wordlist); 608 } 609 610 /** 611 * Get the numeric PID of a page 612 * 613 * @param string $page The page to get the PID for 614 * @return bool|int The page id on success, false on error 615 */ 616 public function getPID($page) { 617 // return PID without locking when it is in the cache 618 if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 619 620 if (!$this->lock()) 621 return false; 622 623 // load known documents 624 $pid = $this->getPIDNoLock($page); 625 if ($pid === false) { 626 $this->unlock(); 627 return false; 628 } 629 630 $this->unlock(); 631 return $pid; 632 } 633 634 /** 635 * Get the numeric PID of a page without locking the index. 636 * Only use this function when the index is already locked. 637 * 638 * @param string $page The page to get the PID for 639 * @return bool|int The page id on success, false on error 640 */ 641 protected function getPIDNoLock($page) { 642 // avoid expensive addIndexKey operation for the most recently requested pages by using a cache 643 if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 644 $pid = $this->addIndexKey('page', '', $page); 645 // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently 646 // added item will be requested again 647 if (count($this->pidCache) > 10) array_shift($this->pidCache); 648 $this->pidCache[$page] = $pid; 649 return $pid; 650 } 651 652 /** 653 * Get the page id of a numeric PID 654 * 655 * @param int $pid The PID to get the page id for 656 * @return string The page id 657 */ 658 public function getPageFromPID($pid) { 659 return $this->getIndexKey('page', '', $pid); 660 } 661 662 /** 663 * Find pages in the fulltext index containing the words, 664 * 665 * The search words must be pre-tokenized, meaning only letters and 666 * numbers with an optional wildcard 667 * 668 * The returned array will have the original tokens as key. The values 669 * in the returned list is an array with the page names as keys and the 670 * number of times that token appears on the page as value. 671 * 672 * @param array $tokens list of words to search for 673 * @return array list of page names with usage counts 674 * @author Tom N Harris <tnharris@whoopdedo.org> 675 * @author Andreas Gohr <andi@splitbrain.org> 676 */ 677 public function lookup(&$tokens) { 678 $result = array(); 679 $wids = $this->getIndexWords($tokens, $result); 680 if (empty($wids)) return array(); 681 // load known words and documents 682 $page_idx = $this->getIndex('page', ''); 683 $docs = array(); 684 foreach (array_keys($wids) as $wlen) { 685 $wids[$wlen] = array_unique($wids[$wlen]); 686 $index = $this->getIndex('i', $wlen); 687 foreach($wids[$wlen] as $ixid) { 688 if ($ixid < count($index)) 689 $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]); 690 } 691 } 692 // merge found pages into final result array 693 $final = array(); 694 foreach ($result as $word => $res) { 695 $final[$word] = array(); 696 foreach ($res as $wid) { 697 // handle the case when ($ixid < count($index)) has been false 698 // and thus $docs[$wid] hasn't been set. 699 if (!isset($docs[$wid])) continue; 700 $hits = &$docs[$wid]; 701 foreach ($hits as $hitkey => $hitcnt) { 702 // make sure the document still exists 703 if (!page_exists($hitkey, '', false)) continue; 704 if (!isset($final[$word][$hitkey])) 705 $final[$word][$hitkey] = $hitcnt; 706 else 707 $final[$word][$hitkey] += $hitcnt; 708 } 709 } 710 } 711 return $final; 712 } 713 714 /** 715 * Find pages containing a metadata key. 716 * 717 * The metadata values are compared as case-sensitive strings. Pass a 718 * callback function that returns true or false to use a different 719 * comparison function. The function will be called with the $value being 720 * searched for as the first argument, and the word in the index as the 721 * second argument. The function preg_match can be used directly if the 722 * values are regexes. 723 * 724 * @param string $key name of the metadata key to look for 725 * @param string $value search term to look for, must be a string or array of strings 726 * @param callback $func comparison function 727 * @return array lists with page names, keys are query values if $value is array 728 * @author Tom N Harris <tnharris@whoopdedo.org> 729 * @author Michael Hamann <michael@content-space.de> 730 */ 731 public function lookupKey($key, &$value, $func=null) { 732 if (!is_array($value)) 733 $value_array = array($value); 734 else 735 $value_array =& $value; 736 737 // the matching ids for the provided value(s) 738 $value_ids = array(); 739 740 $metaname = idx_cleanName($key); 741 742 // get all words in order to search the matching ids 743 if ($key == 'title') { 744 $words = $this->getIndex('title', ''); 745 } else { 746 $words = $this->getIndex($metaname.'_w', ''); 747 } 748 749 if (!is_null($func)) { 750 foreach ($value_array as $val) { 751 foreach ($words as $i => $word) { 752 if (call_user_func_array($func, array($val, $word))) 753 $value_ids[$i][] = $val; 754 } 755 } 756 } else { 757 foreach ($value_array as $val) { 758 $xval = $val; 759 $caret = '^'; 760 $dollar = '$'; 761 // check for wildcards 762 if (substr($xval, 0, 1) == '*') { 763 $xval = substr($xval, 1); 764 $caret = ''; 765 } 766 if (substr($xval, -1, 1) == '*') { 767 $xval = substr($xval, 0, -1); 768 $dollar = ''; 769 } 770 if (!$caret || !$dollar) { 771 $re = $caret.preg_quote($xval, '/').$dollar; 772 foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i) 773 $value_ids[$i][] = $val; 774 } else { 775 if (($i = array_search($val, $words, true)) !== false) 776 $value_ids[$i][] = $val; 777 } 778 } 779 } 780 781 unset($words); // free the used memory 782 783 // initialize the result so it won't be null 784 $result = array(); 785 foreach ($value_array as $val) { 786 $result[$val] = array(); 787 } 788 789 $page_idx = $this->getIndex('page', ''); 790 791 // Special handling for titles 792 if ($key == 'title') { 793 foreach ($value_ids as $pid => $val_list) { 794 $page = $page_idx[$pid]; 795 foreach ($val_list as $val) { 796 $result[$val][] = $page; 797 } 798 } 799 } else { 800 // load all lines and pages so the used lines can be taken and matched with the pages 801 $lines = $this->getIndex($metaname.'_i', ''); 802 803 foreach ($value_ids as $value_id => $val_list) { 804 // parse the tuples of the form page_id*1:page2_id*1 and so on, return value 805 // is an array with page_id => 1, page2_id => 1 etc. so take the keys only 806 $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id])); 807 foreach ($val_list as $val) { 808 $result[$val] = array_merge($result[$val], $pages); 809 } 810 } 811 } 812 if (!is_array($value)) $result = $result[$value]; 813 return $result; 814 } 815 816 /** 817 * Find the index ID of each search term. 818 * 819 * The query terms should only contain valid characters, with a '*' at 820 * either the beginning or end of the word (or both). 821 * The $result parameter can be used to merge the index locations with 822 * the appropriate query term. 823 * 824 * @param array $words The query terms. 825 * @param array $result Set to word => array("length*id" ...) 826 * @return array Set to length => array(id ...) 827 * @author Tom N Harris <tnharris@whoopdedo.org> 828 */ 829 protected function getIndexWords(&$words, &$result) { 830 $tokens = array(); 831 $tokenlength = array(); 832 $tokenwild = array(); 833 foreach ($words as $word) { 834 $result[$word] = array(); 835 $caret = '^'; 836 $dollar = '$'; 837 $xword = $word; 838 $wlen = wordlen($word); 839 840 // check for wildcards 841 if (substr($xword, 0, 1) == '*') { 842 $xword = substr($xword, 1); 843 $caret = ''; 844 $wlen -= 1; 845 } 846 if (substr($xword, -1, 1) == '*') { 847 $xword = substr($xword, 0, -1); 848 $dollar = ''; 849 $wlen -= 1; 850 } 851 if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword)) 852 continue; 853 if (!isset($tokens[$xword])) 854 $tokenlength[$wlen][] = $xword; 855 if (!$caret || !$dollar) { 856 $re = $caret.preg_quote($xword, '/').$dollar; 857 $tokens[$xword][] = array($word, '/'.$re.'/'); 858 if (!isset($tokenwild[$xword])) 859 $tokenwild[$xword] = $wlen; 860 } else { 861 $tokens[$xword][] = array($word, null); 862 } 863 } 864 asort($tokenwild); 865 // $tokens = array( base word => array( [ query term , regexp ] ... ) ... ) 866 // $tokenlength = array( base word length => base word ... ) 867 // $tokenwild = array( base word => base word length ... ) 868 $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength)); 869 $indexes_known = $this->indexLengths($length_filter); 870 if (!empty($tokenwild)) sort($indexes_known); 871 // get word IDs 872 $wids = array(); 873 foreach ($indexes_known as $ixlen) { 874 $word_idx = $this->getIndex('w', $ixlen); 875 // handle exact search 876 if (isset($tokenlength[$ixlen])) { 877 foreach ($tokenlength[$ixlen] as $xword) { 878 $wid = array_search($xword, $word_idx, true); 879 if ($wid !== false) { 880 $wids[$ixlen][] = $wid; 881 foreach ($tokens[$xword] as $w) 882 $result[$w[0]][] = "$ixlen*$wid"; 883 } 884 } 885 } 886 // handle wildcard search 887 foreach ($tokenwild as $xword => $wlen) { 888 if ($wlen >= $ixlen) break; 889 foreach ($tokens[$xword] as $w) { 890 if (is_null($w[1])) continue; 891 foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) { 892 $wids[$ixlen][] = $wid; 893 $result[$w[0]][] = "$ixlen*$wid"; 894 } 895 } 896 } 897 } 898 return $wids; 899 } 900 901 /** 902 * Return a list of all pages 903 * Warning: pages may not exist! 904 * 905 * @param string $key list only pages containing the metadata key (optional) 906 * @return array list of page names 907 * @author Tom N Harris <tnharris@whoopdedo.org> 908 */ 909 public function getPages($key=null) { 910 $page_idx = $this->getIndex('page', ''); 911 if (is_null($key)) return $page_idx; 912 913 $metaname = idx_cleanName($key); 914 915 // Special handling for titles 916 if ($key == 'title') { 917 $title_idx = $this->getIndex('title', ''); 918 array_splice($page_idx, count($title_idx)); 919 foreach ($title_idx as $i => $title) 920 if ($title === "") unset($page_idx[$i]); 921 return array_values($page_idx); 922 } 923 924 $pages = array(); 925 $lines = $this->getIndex($metaname.'_i', ''); 926 foreach ($lines as $line) { 927 $pages = array_merge($pages, $this->parseTuples($page_idx, $line)); 928 } 929 return array_keys($pages); 930 } 931 932 /** 933 * Return a list of words sorted by number of times used 934 * 935 * @param int $min bottom frequency threshold 936 * @param int $max upper frequency limit. No limit if $max<$min 937 * @param int $minlen minimum length of words to count 938 * @param string $key metadata key to list. Uses the fulltext index if not given 939 * @return array list of words as the keys and frequency as values 940 * @author Tom N Harris <tnharris@whoopdedo.org> 941 */ 942 public function histogram($min=1, $max=0, $minlen=3, $key=null) { 943 if ($min < 1) 944 $min = 1; 945 if ($max < $min) 946 $max = 0; 947 948 $result = array(); 949 950 if ($key == 'title') { 951 $index = $this->getIndex('title', ''); 952 $index = array_count_values($index); 953 foreach ($index as $val => $cnt) { 954 if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen) 955 $result[$val] = $cnt; 956 } 957 } 958 elseif (!is_null($key)) { 959 $metaname = idx_cleanName($key); 960 $index = $this->getIndex($metaname.'_i', ''); 961 $val_idx = array(); 962 foreach ($index as $wid => $line) { 963 $freq = $this->countTuples($line); 964 if ($freq >= $min && (!$max || $freq <= $max)) 965 $val_idx[$wid] = $freq; 966 } 967 if (!empty($val_idx)) { 968 $words = $this->getIndex($metaname.'_w', ''); 969 foreach ($val_idx as $wid => $freq) { 970 if (strlen($words[$wid]) >= $minlen) 971 $result[$words[$wid]] = $freq; 972 } 973 } 974 } 975 else { 976 $lengths = idx_listIndexLengths(); 977 foreach ($lengths as $length) { 978 if ($length < $minlen) continue; 979 $index = $this->getIndex('i', $length); 980 $words = null; 981 foreach ($index as $wid => $line) { 982 $freq = $this->countTuples($line); 983 if ($freq >= $min && (!$max || $freq <= $max)) { 984 if ($words === null) 985 $words = $this->getIndex('w', $length); 986 $result[$words[$wid]] = $freq; 987 } 988 } 989 } 990 } 991 992 arsort($result); 993 return $result; 994 } 995 996 /** 997 * Lock the indexer. 998 * 999 * @author Tom N Harris <tnharris@whoopdedo.org> 1000 */ 1001 protected function lock() { 1002 global $conf; 1003 $status = true; 1004 $run = 0; 1005 $lock = $conf['lockdir'].'/_indexer.lock'; 1006 while (!@mkdir($lock, $conf['dmode'])) { 1007 usleep(50); 1008 if(is_dir($lock) && time()-@filemtime($lock) > 60*5){ 1009 // looks like a stale lock - remove it 1010 if (!@rmdir($lock)) { 1011 $status = "removing the stale lock failed"; 1012 return false; 1013 } else { 1014 $status = "stale lock removed"; 1015 } 1016 }elseif($run++ == 1000){ 1017 // we waited 5 seconds for that lock 1018 return false; 1019 } 1020 } 1021 if (!empty($conf['dperm'])) { 1022 chmod($lock, $conf['dperm']); 1023 } 1024 return $status; 1025 } 1026 1027 /** 1028 * Release the indexer lock. 1029 * 1030 * @author Tom N Harris <tnharris@whoopdedo.org> 1031 */ 1032 protected function unlock() { 1033 global $conf; 1034 @rmdir($conf['lockdir'].'/_indexer.lock'); 1035 return true; 1036 } 1037 1038 /** 1039 * Retrieve the entire index. 1040 * 1041 * The $suffix argument is for an index that is split into 1042 * multiple parts. Different index files should use different 1043 * base names. 1044 * 1045 * @param string $idx name of the index 1046 * @param string $suffix subpart identifier 1047 * @return array list of lines without CR or LF 1048 * @author Tom N Harris <tnharris@whoopdedo.org> 1049 */ 1050 protected function getIndex($idx, $suffix) { 1051 global $conf; 1052 $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 1053 if (!@file_exists($fn)) return array(); 1054 return file($fn, FILE_IGNORE_NEW_LINES); 1055 } 1056 1057 /** 1058 * Replace the contents of the index with an array. 1059 * 1060 * @param string $idx name of the index 1061 * @param string $suffix subpart identifier 1062 * @param array $lines list of lines without LF 1063 * @return bool If saving succeeded 1064 * @author Tom N Harris <tnharris@whoopdedo.org> 1065 */ 1066 protected function saveIndex($idx, $suffix, &$lines) { 1067 global $conf; 1068 $fn = $conf['indexdir'].'/'.$idx.$suffix; 1069 $fh = @fopen($fn.'.tmp', 'w'); 1070 if (!$fh) return false; 1071 fwrite($fh, join("\n", $lines)); 1072 if (!empty($lines)) 1073 fwrite($fh, "\n"); 1074 fclose($fh); 1075 if (isset($conf['fperm'])) 1076 chmod($fn.'.tmp', $conf['fperm']); 1077 io_rename($fn.'.tmp', $fn.'.idx'); 1078 return true; 1079 } 1080 1081 /** 1082 * Retrieve a line from the index. 1083 * 1084 * @param string $idx name of the index 1085 * @param string $suffix subpart identifier 1086 * @param int $id the line number 1087 * @return string a line with trailing whitespace removed 1088 * @author Tom N Harris <tnharris@whoopdedo.org> 1089 */ 1090 protected function getIndexKey($idx, $suffix, $id) { 1091 global $conf; 1092 $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 1093 if (!@file_exists($fn)) return ''; 1094 $fh = @fopen($fn, 'r'); 1095 if (!$fh) return ''; 1096 $ln = -1; 1097 while (($line = fgets($fh)) !== false) { 1098 if (++$ln == $id) break; 1099 } 1100 fclose($fh); 1101 return rtrim((string)$line); 1102 } 1103 1104 /** 1105 * Write a line into the index. 1106 * 1107 * @param string $idx name of the index 1108 * @param string $suffix subpart identifier 1109 * @param int $id the line number 1110 * @param string $line line to write 1111 * @return bool If saving succeeded 1112 * @author Tom N Harris <tnharris@whoopdedo.org> 1113 */ 1114 protected function saveIndexKey($idx, $suffix, $id, $line) { 1115 global $conf; 1116 if (substr($line, -1) != "\n") 1117 $line .= "\n"; 1118 $fn = $conf['indexdir'].'/'.$idx.$suffix; 1119 $fh = @fopen($fn.'.tmp', 'w'); 1120 if (!$fh) return false; 1121 $ih = @fopen($fn.'.idx', 'r'); 1122 if ($ih) { 1123 $ln = -1; 1124 while (($curline = fgets($ih)) !== false) { 1125 fwrite($fh, (++$ln == $id) ? $line : $curline); 1126 } 1127 if ($id > $ln) { 1128 while ($id > ++$ln) 1129 fwrite($fh, "\n"); 1130 fwrite($fh, $line); 1131 } 1132 fclose($ih); 1133 } else { 1134 $ln = -1; 1135 while ($id > ++$ln) 1136 fwrite($fh, "\n"); 1137 fwrite($fh, $line); 1138 } 1139 fclose($fh); 1140 if (isset($conf['fperm'])) 1141 chmod($fn.'.tmp', $conf['fperm']); 1142 io_rename($fn.'.tmp', $fn.'.idx'); 1143 return true; 1144 } 1145 1146 /** 1147 * Retrieve or insert a value in the index. 1148 * 1149 * @param string $idx name of the index 1150 * @param string $suffix subpart identifier 1151 * @param string $value line to find in the index 1152 * @return int|bool line number of the value in the index or false if writing the index failed 1153 * @author Tom N Harris <tnharris@whoopdedo.org> 1154 */ 1155 protected function addIndexKey($idx, $suffix, $value) { 1156 $index = $this->getIndex($idx, $suffix); 1157 $id = array_search($value, $index, true); 1158 if ($id === false) { 1159 $id = count($index); 1160 $index[$id] = $value; 1161 if (!$this->saveIndex($idx, $suffix, $index)) { 1162 trigger_error("Failed to write $idx index", E_USER_ERROR); 1163 return false; 1164 } 1165 } 1166 return $id; 1167 } 1168 1169 /** 1170 * Get the list of lengths indexed in the wiki. 1171 * 1172 * Read the index directory or a cache file and returns 1173 * a sorted array of lengths of the words used in the wiki. 1174 * 1175 * @author YoBoY <yoboy.leguesh@gmail.com> 1176 */ 1177 protected function listIndexLengths() { 1178 return idx_listIndexLengths(); 1179 } 1180 1181 /** 1182 * Get the word lengths that have been indexed. 1183 * 1184 * Reads the index directory and returns an array of lengths 1185 * that there are indices for. 1186 * 1187 * @author YoBoY <yoboy.leguesh@gmail.com> 1188 */ 1189 protected function indexLengths($filter) { 1190 global $conf; 1191 $idx = array(); 1192 if (is_array($filter)) { 1193 // testing if index files exist only 1194 $path = $conf['indexdir']."/i"; 1195 foreach ($filter as $key => $value) { 1196 if (@file_exists($path.$key.'.idx')) 1197 $idx[] = $key; 1198 } 1199 } else { 1200 $lengths = idx_listIndexLengths(); 1201 foreach ($lengths as $key => $length) { 1202 // keep all the values equal or superior 1203 if ((int)$length >= (int)$filter) 1204 $idx[] = $length; 1205 } 1206 } 1207 return $idx; 1208 } 1209 1210 /** 1211 * Insert or replace a tuple in a line. 1212 * 1213 * @author Tom N Harris <tnharris@whoopdedo.org> 1214 */ 1215 protected function updateTuple($line, $id, $count) { 1216 $newLine = $line; 1217 if ($newLine !== '') 1218 $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine); 1219 $newLine = trim($newLine, ':'); 1220 if ($count) { 1221 if (strlen($newLine) > 0) 1222 return "$id*$count:".$newLine; 1223 else 1224 return "$id*$count".$newLine; 1225 } 1226 return $newLine; 1227 } 1228 1229 /** 1230 * Split a line into an array of tuples. 1231 * 1232 * @author Tom N Harris <tnharris@whoopdedo.org> 1233 * @author Andreas Gohr <andi@splitbrain.org> 1234 */ 1235 protected function parseTuples(&$keys, $line) { 1236 $result = array(); 1237 if ($line == '') return $result; 1238 $parts = explode(':', $line); 1239 foreach ($parts as $tuple) { 1240 if ($tuple === '') continue; 1241 list($key, $cnt) = explode('*', $tuple); 1242 if (!$cnt) continue; 1243 $key = $keys[$key]; 1244 if (!$key) continue; 1245 $result[$key] = $cnt; 1246 } 1247 return $result; 1248 } 1249 1250 /** 1251 * Sum the counts in a list of tuples. 1252 * 1253 * @author Tom N Harris <tnharris@whoopdedo.org> 1254 */ 1255 protected function countTuples($line) { 1256 $freq = 0; 1257 $parts = explode(':', $line); 1258 foreach ($parts as $tuple) { 1259 if ($tuple === '') continue; 1260 list($pid, $cnt) = explode('*', $tuple); 1261 $freq += (int)$cnt; 1262 } 1263 return $freq; 1264 } 1265} 1266 1267/** 1268 * Create an instance of the indexer. 1269 * 1270 * @return Doku_Indexer a Doku_Indexer 1271 * @author Tom N Harris <tnharris@whoopdedo.org> 1272 */ 1273function idx_get_indexer() { 1274 static $Indexer; 1275 if (!isset($Indexer)) { 1276 $Indexer = new Doku_Indexer(); 1277 } 1278 return $Indexer; 1279} 1280 1281/** 1282 * Returns words that will be ignored. 1283 * 1284 * @return array list of stop words 1285 * @author Tom N Harris <tnharris@whoopdedo.org> 1286 */ 1287function & idx_get_stopwords() { 1288 static $stopwords = null; 1289 if (is_null($stopwords)) { 1290 global $conf; 1291 $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 1292 if(@file_exists($swfile)){ 1293 $stopwords = file($swfile, FILE_IGNORE_NEW_LINES); 1294 }else{ 1295 $stopwords = array(); 1296 } 1297 } 1298 return $stopwords; 1299} 1300 1301/** 1302 * Adds/updates the search index for the given page 1303 * 1304 * Locking is handled internally. 1305 * 1306 * @param string $page name of the page to index 1307 * @param boolean $verbose print status messages 1308 * @param boolean $force force reindexing even when the index is up to date 1309 * @return boolean the function completed successfully 1310 * @author Tom N Harris <tnharris@whoopdedo.org> 1311 */ 1312function idx_addPage($page, $verbose=false, $force=false) { 1313 $idxtag = metaFN($page,'.indexed'); 1314 // check if page was deleted but is still in the index 1315 if (!page_exists($page)) { 1316 if (!@file_exists($idxtag)) { 1317 if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF); 1318 return false; 1319 } 1320 $Indexer = idx_get_indexer(); 1321 $result = $Indexer->deletePage($page); 1322 if ($result === "locked") { 1323 if ($verbose) print("Indexer: locked".DOKU_LF); 1324 return false; 1325 } 1326 @unlink($idxtag); 1327 return $result; 1328 } 1329 1330 // check if indexing needed 1331 if(!$force && @file_exists($idxtag)){ 1332 if(trim(io_readFile($idxtag)) == idx_get_version()){ 1333 $last = @filemtime($idxtag); 1334 if($last > @filemtime(wikiFN($page))){ 1335 if ($verbose) print("Indexer: index for $page up to date".DOKU_LF); 1336 return false; 1337 } 1338 } 1339 } 1340 1341 $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED); 1342 if ($indexenabled === false) { 1343 $result = false; 1344 if (@file_exists($idxtag)) { 1345 $Indexer = idx_get_indexer(); 1346 $result = $Indexer->deletePage($page); 1347 if ($result === "locked") { 1348 if ($verbose) print("Indexer: locked".DOKU_LF); 1349 return false; 1350 } 1351 @unlink($idxtag); 1352 } 1353 if ($verbose) print("Indexer: index disabled for $page".DOKU_LF); 1354 return $result; 1355 } 1356 1357 $Indexer = idx_get_indexer(); 1358 $pid = $Indexer->getPID($page); 1359 if ($pid === false) { 1360 if ($verbose) print("Indexer: getting the PID failed for $page".DOKU_LF); 1361 return false; 1362 } 1363 $body = ''; 1364 $metadata = array(); 1365 $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED); 1366 if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null) 1367 $metadata['relation_references'] = array_keys($references); 1368 else 1369 $metadata['relation_references'] = array(); 1370 1371 if (($media = p_get_metadata($page, 'relation media', METADATA_RENDER_UNLIMITED)) !== null) 1372 $metadata['relation_media'] = array_keys($media); 1373 else 1374 $metadata['relation_media'] = array(); 1375 1376 $data = compact('page', 'body', 'metadata', 'pid'); 1377 $evt = new Doku_Event('INDEXER_PAGE_ADD', $data); 1378 if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page); 1379 $evt->advise_after(); 1380 unset($evt); 1381 extract($data); 1382 1383 $result = $Indexer->addPageWords($page, $body); 1384 if ($result === "locked") { 1385 if ($verbose) print("Indexer: locked".DOKU_LF); 1386 return false; 1387 } 1388 1389 if ($result) { 1390 $result = $Indexer->addMetaKeys($page, $metadata); 1391 if ($result === "locked") { 1392 if ($verbose) print("Indexer: locked".DOKU_LF); 1393 return false; 1394 } 1395 } 1396 1397 if ($result) 1398 io_saveFile(metaFN($page,'.indexed'), idx_get_version()); 1399 if ($verbose) { 1400 print("Indexer: finished".DOKU_LF); 1401 return true; 1402 } 1403 return $result; 1404} 1405 1406/** 1407 * Find tokens in the fulltext index 1408 * 1409 * Takes an array of words and will return a list of matching 1410 * pages for each one. 1411 * 1412 * Important: No ACL checking is done here! All results are 1413 * returned, regardless of permissions 1414 * 1415 * @param array $words list of words to search for 1416 * @return array list of pages found, associated with the search terms 1417 */ 1418function idx_lookup(&$words) { 1419 $Indexer = idx_get_indexer(); 1420 return $Indexer->lookup($words); 1421} 1422 1423/** 1424 * Split a string into tokens 1425 * 1426 */ 1427function idx_tokenizer($string, $wc=false) { 1428 $Indexer = idx_get_indexer(); 1429 return $Indexer->tokenizer($string, $wc); 1430} 1431 1432/* For compatibility */ 1433 1434/** 1435 * Read the list of words in an index (if it exists). 1436 * 1437 * @author Tom N Harris <tnharris@whoopdedo.org> 1438 */ 1439function idx_getIndex($idx, $suffix) { 1440 global $conf; 1441 $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 1442 if (!@file_exists($fn)) return array(); 1443 return file($fn); 1444} 1445 1446/** 1447 * Get the list of lengths indexed in the wiki. 1448 * 1449 * Read the index directory or a cache file and returns 1450 * a sorted array of lengths of the words used in the wiki. 1451 * 1452 * @author YoBoY <yoboy.leguesh@gmail.com> 1453 */ 1454function idx_listIndexLengths() { 1455 global $conf; 1456 // testing what we have to do, create a cache file or not. 1457 if ($conf['readdircache'] == 0) { 1458 $docache = false; 1459 } else { 1460 clearstatcache(); 1461 if (@file_exists($conf['indexdir'].'/lengths.idx') 1462 && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) { 1463 if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) { 1464 $idx = array(); 1465 foreach ($lengths as $length) { 1466 $idx[] = (int)$length; 1467 } 1468 return $idx; 1469 } 1470 } 1471 $docache = true; 1472 } 1473 1474 if ($conf['readdircache'] == 0 || $docache) { 1475 $dir = @opendir($conf['indexdir']); 1476 if ($dir === false) 1477 return array(); 1478 $idx = array(); 1479 while (($f = readdir($dir)) !== false) { 1480 if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') { 1481 $i = substr($f, 1, -4); 1482 if (is_numeric($i)) 1483 $idx[] = (int)$i; 1484 } 1485 } 1486 closedir($dir); 1487 sort($idx); 1488 // save this in a file 1489 if ($docache) { 1490 $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w'); 1491 @fwrite($handle, implode("\n", $idx)); 1492 @fclose($handle); 1493 } 1494 return $idx; 1495 } 1496 1497 return array(); 1498} 1499 1500/** 1501 * Get the word lengths that have been indexed. 1502 * 1503 * Reads the index directory and returns an array of lengths 1504 * that there are indices for. 1505 * 1506 * @author YoBoY <yoboy.leguesh@gmail.com> 1507 */ 1508function idx_indexLengths($filter) { 1509 global $conf; 1510 $idx = array(); 1511 if (is_array($filter)) { 1512 // testing if index files exist only 1513 $path = $conf['indexdir']."/i"; 1514 foreach ($filter as $key => $value) { 1515 if (@file_exists($path.$key.'.idx')) 1516 $idx[] = $key; 1517 } 1518 } else { 1519 $lengths = idx_listIndexLengths(); 1520 foreach ($lengths as $key => $length) { 1521 // keep all the values equal or superior 1522 if ((int)$length >= (int)$filter) 1523 $idx[] = $length; 1524 } 1525 } 1526 return $idx; 1527} 1528 1529/** 1530 * Clean a name of a key for use as a file name. 1531 * 1532 * Romanizes non-latin characters, then strips away anything that's 1533 * not a letter, number, or underscore. 1534 * 1535 * @author Tom N Harris <tnharris@whoopdedo.org> 1536 */ 1537function idx_cleanName($name) { 1538 $name = utf8_romanize(trim((string)$name)); 1539 $name = preg_replace('#[ \./\\:-]+#', '_', $name); 1540 $name = preg_replace('/[^A-Za-z0-9_]/', '', $name); 1541 return strtolower($name); 1542} 1543 1544//Setup VIM: ex: et ts=4 : 1545