1<?php 2 3namespace dokuwiki\Search; 4 5use dokuwiki\Utf8\Asian; 6use dokuwiki\Utf8\Clean; 7use dokuwiki\Utf8\PhpString; 8use dokuwiki\Extension\Event; 9 10/** 11 * Class that encapsulates operations on the indexer database. 12 * 13 * @author Tom N Harris <tnharris@whoopdedo.org> 14 */ 15class Indexer 16{ 17 /** 18 * @var array $pidCache Cache for getPID() 19 */ 20 protected $pidCache = []; 21 22 /** 23 * Adds the contents of a page to the fulltext index 24 * 25 * The added text replaces previous words for the same page. 26 * An empty value erases the page. 27 * 28 * @param string $page a page name 29 * @param string $text the body of the page 30 * @return string|boolean the function completed successfully 31 * 32 * @author Tom N Harris <tnharris@whoopdedo.org> 33 * @author Andreas Gohr <andi@splitbrain.org> 34 */ 35 public function addPageWords($page, $text) 36 { 37 if (!$this->lock()) 38 return "locked"; 39 40 // load known documents 41 $pid = $this->getPIDNoLock($page); 42 if ($pid === false) { 43 $this->unlock(); 44 return false; 45 } 46 47 $pagewords = []; 48 // get word usage in page 49 $words = $this->getPageWords($text); 50 if ($words === false) { 51 $this->unlock(); 52 return false; 53 } 54 55 if (!empty($words)) { 56 foreach (array_keys($words) as $wlen) { 57 $index = $this->getIndex('i', $wlen); 58 foreach ($words[$wlen] as $wid => $freq) { 59 $idx = ($wid<count($index)) ? $index[$wid] : ''; 60 $index[$wid] = $this->updateTuple($idx, $pid, $freq); 61 $pagewords[] = "$wlen*$wid"; 62 } 63 if (!$this->saveIndex('i', $wlen, $index)) { 64 $this->unlock(); 65 return false; 66 } 67 } 68 } 69 70 // Remove obsolete index entries 71 $pageword_idx = $this->getIndexKey('pageword', '', $pid); 72 if ($pageword_idx !== '') { 73 $oldwords = explode(':', $pageword_idx); 74 $delwords = array_diff($oldwords, $pagewords); 75 $upwords = []; 76 foreach ($delwords as $word) { 77 if ($word != '') { 78 [$wlen, $wid] = explode('*', $word); 79 $wid = (int)$wid; 80 $upwords[$wlen][] = $wid; 81 } 82 } 83 foreach ($upwords as $wlen => $widx) { 84 $index = $this->getIndex('i', $wlen); 85 foreach ($widx as $wid) { 86 $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 87 } 88 $this->saveIndex('i', $wlen, $index); 89 } 90 } 91 // Save the reverse index 92 $pageword_idx = implode(':', $pagewords); 93 if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) { 94 $this->unlock(); 95 return false; 96 } 97 98 $this->unlock(); 99 return true; 100 } 101 102 /** 103 * Split the words in a page and add them to the index. 104 * 105 * @param string $text content of the page 106 * @return array list of word IDs and number of times used 107 * 108 * @author Andreas Gohr <andi@splitbrain.org> 109 * @author Christopher Smith <chris@jalakai.co.uk> 110 * @author Tom N Harris <tnharris@whoopdedo.org> 111 */ 112 protected function getPageWords($text) 113 { 114 115 $tokens = $this->tokenizer($text); 116 $tokens = array_count_values($tokens); // count the frequency of each token 117 118 $words = []; 119 foreach ($tokens as $w => $c) { 120 $l = wordlen($w); 121 if (isset($words[$l])){ 122 $words[$l][$w] = $c + ($words[$l][$w] ?? 0); 123 }else{ 124 $words[$l] = [$w => $c]; 125 } 126 } 127 128 // arrive here with $words = array(wordlen => array(word => frequency)) 129 $index = []; //resulting index 130 foreach (array_keys($words) as $wlen) { 131 $word_idx = $this->getIndex('w', $wlen); 132 $word_idx_modified = false; 133 foreach ($words[$wlen] as $word => $freq) { 134 $word = (string)$word; 135 $wid = array_search($word, $word_idx, true); 136 if ($wid === false) { 137 $wid = count($word_idx); 138 $word_idx[] = $word; 139 $word_idx_modified = true; 140 } 141 if (!isset($index[$wlen])) 142 $index[$wlen] = []; 143 $index[$wlen][$wid] = $freq; 144 } 145 // save back the word index 146 if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx)) 147 return false; 148 } 149 150 return $index; 151 } 152 153 /** 154 * Add/update keys to/of the metadata index. 155 * 156 * Adding new keys does not remove other keys for the page. 157 * An empty value will erase the key. 158 * The $key parameter can be an array to add multiple keys. $value will 159 * not be used if $key is an array. 160 * 161 * @param string $page a page name 162 * @param mixed $key a key string or array of key=>value pairs 163 * @param mixed $value the value or list of values 164 * @return boolean|string the function completed successfully 165 * 166 * @author Tom N Harris <tnharris@whoopdedo.org> 167 * @author Michael Hamann <michael@content-space.de> 168 */ 169 public function addMetaKeys($page, $key, $value = null) 170 { 171 if (!is_array($key)) { 172 $key = [$key => $value]; 173 } elseif (!is_null($value)) { 174 // $key is array, but $value is not null 175 trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING); 176 } 177 178 if (!$this->lock()) 179 return "locked"; 180 181 // load known documents 182 $pid = $this->getPIDNoLock($page); 183 if ($pid === false) { 184 $this->unlock(); 185 return false; 186 } 187 188 // Special handling for titles so the index file is simpler 189 if (isset($key['title'])) { 190 $value = $key['title']; 191 if (is_array($value)) { 192 $value = $value[0]; 193 } 194 $this->saveIndexKey('title', '', $pid, $value); 195 unset($key['title']); 196 } 197 198 foreach ($key as $name => $values) { 199 $metaname = idx_cleanName($name); 200 $this->addIndexKey('metadata', '', $metaname); 201 $metaidx = $this->getIndex($metaname.'_i', ''); 202 $metawords = $this->getIndex($metaname.'_w', ''); 203 $addwords = false; 204 205 if (!is_array($values)) $values = [$values]; 206 207 $val_idx = $this->getIndexKey($metaname.'_p', '', $pid); 208 if ($val_idx !== '') { 209 $val_idx = explode(':', $val_idx); 210 // -1 means remove, 0 keep, 1 add 211 $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1)); 212 } else { 213 $val_idx = []; 214 } 215 216 foreach ($values as $val) { 217 $val = (string)$val; 218 if ($val !== "") { 219 $id = array_search($val, $metawords, true); 220 if ($id === false) { 221 // didn't find $val, so we'll add it to the end of metawords and create a placeholder in metaidx 222 $id = count($metawords); 223 $metawords[$id] = $val; 224 $metaidx[$id] = ''; 225 $addwords = true; 226 } 227 // test if value is already in the index 228 if (isset($val_idx[$id]) && $val_idx[$id] <= 0){ 229 $val_idx[$id] = 0; 230 } else { // else add it 231 $val_idx[$id] = 1; 232 } 233 } 234 } 235 236 if ($addwords) { 237 $this->saveIndex($metaname.'_w', '', $metawords); 238 } 239 $vals_changed = false; 240 foreach ($val_idx as $id => $action) { 241 if ($action == -1) { 242 $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0); 243 $vals_changed = true; 244 unset($val_idx[$id]); 245 } elseif ($action == 1) { 246 $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1); 247 $vals_changed = true; 248 } 249 } 250 251 if ($vals_changed) { 252 $this->saveIndex($metaname.'_i', '', $metaidx); 253 $val_idx = implode(':', array_keys($val_idx)); 254 $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx); 255 } 256 257 unset($metaidx); 258 unset($metawords); 259 } 260 261 $this->unlock(); 262 return true; 263 } 264 265 /** 266 * Rename a page in the search index without changing the indexed content. This function doesn't check if the 267 * old or new name exists in the filesystem. It returns an error if the old page isn't in the page list of the 268 * indexer and it deletes all previously indexed content of the new page. 269 * 270 * @param string $oldpage The old page name 271 * @param string $newpage The new page name 272 * @return string|bool If the page was successfully renamed, can be a message in the case of an error 273 */ 274 public function renamePage($oldpage, $newpage) 275 { 276 if (!$this->lock()) return 'locked'; 277 278 $pages = $this->getPages(); 279 280 $id = array_search($oldpage, $pages, true); 281 if ($id === false) { 282 $this->unlock(); 283 return 'page is not in index'; 284 } 285 286 $new_id = array_search($newpage, $pages, true); 287 if ($new_id !== false) { 288 // make sure the page is not in the index anymore 289 if (!$this->deletePageNoLock($newpage)) { 290 return false; 291 } 292 293 $pages[$new_id] = 'deleted:'.time().random_int(0, 9999); 294 } 295 296 $pages[$id] = $newpage; 297 298 // update index 299 if (!$this->saveIndex('page', '', $pages)) { 300 $this->unlock(); 301 return false; 302 } 303 304 // reset the pid cache 305 $this->pidCache = []; 306 307 $this->unlock(); 308 return true; 309 } 310 311 /** 312 * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages 313 * will be updated. 314 * 315 * @param string $key The metadata key of which a value shall be changed 316 * @param string $oldvalue The old value that shall be renamed 317 * @param string $newvalue The new value to which the old value shall be renamed, if exists values will be merged 318 * @return bool|string If renaming the value has been successful, false or error message on error. 319 */ 320 public function renameMetaValue($key, $oldvalue, $newvalue) 321 { 322 if (!$this->lock()) return 'locked'; 323 324 // change the relation references index 325 $metavalues = $this->getIndex($key, '_w'); 326 $oldid = array_search($oldvalue, $metavalues, true); 327 if ($oldid !== false) { 328 $newid = array_search($newvalue, $metavalues, true); 329 if ($newid !== false) { 330 // free memory 331 unset($metavalues); 332 333 // okay, now we have two entries for the same value. we need to merge them. 334 $indexline = $this->getIndexKey($key.'_i', '', $oldid); 335 if ($indexline != '') { 336 $newindexline = $this->getIndexKey($key.'_i', '', $newid); 337 $pagekeys = $this->getIndex($key.'_p', ''); 338 $parts = explode(':', $indexline); 339 foreach ($parts as $part) { 340 [$id, $count] = explode('*', $part); 341 $newindexline = $this->updateTuple($newindexline, $id, $count); 342 343 $keyline = explode(':', $pagekeys[$id]); 344 // remove old meta value 345 $keyline = array_diff($keyline, [$oldid]); 346 // add new meta value when not already present 347 if (!in_array($newid, $keyline)) { 348 $keyline[] = $newid; 349 } 350 $pagekeys[$id] = implode(':', $keyline); 351 } 352 $this->saveIndex($key.'_p', '', $pagekeys); 353 unset($pagekeys); 354 $this->saveIndexKey($key.'_i', '', $oldid, ''); 355 $this->saveIndexKey($key.'_i', '', $newid, $newindexline); 356 } 357 } else { 358 $metavalues[$oldid] = $newvalue; 359 if (!$this->saveIndex($key.'_w', '', $metavalues)) { 360 $this->unlock(); 361 return false; 362 } 363 } 364 } 365 366 $this->unlock(); 367 return true; 368 } 369 370 /** 371 * Remove a page from the index 372 * 373 * Erases entries in all known indexes. 374 * 375 * @param string $page a page name 376 * @return string|boolean the function completed successfully 377 * 378 * @author Tom N Harris <tnharris@whoopdedo.org> 379 */ 380 public function deletePage($page) 381 { 382 if (!$this->lock()) 383 return "locked"; 384 385 $result = $this->deletePageNoLock($page); 386 387 $this->unlock(); 388 389 return $result; 390 } 391 392 /** 393 * Remove a page from the index without locking the index, only use this function if the index is already locked 394 * 395 * Erases entries in all known indexes. 396 * 397 * @param string $page a page name 398 * @return boolean the function completed successfully 399 * 400 * @author Tom N Harris <tnharris@whoopdedo.org> 401 */ 402 protected function deletePageNoLock($page) 403 { 404 // load known documents 405 $pid = $this->getPIDNoLock($page); 406 if ($pid === false) { 407 return false; 408 } 409 410 // Remove obsolete index entries 411 $pageword_idx = $this->getIndexKey('pageword', '', $pid); 412 if ($pageword_idx !== '') { 413 $delwords = explode(':', $pageword_idx); 414 $upwords = []; 415 foreach ($delwords as $word) { 416 if ($word != '') { 417 [$wlen, $wid] = explode('*', $word); 418 $wid = (int)$wid; 419 $upwords[$wlen][] = $wid; 420 } 421 } 422 foreach ($upwords as $wlen => $widx) { 423 $index = $this->getIndex('i', $wlen); 424 foreach ($widx as $wid) { 425 $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 426 } 427 $this->saveIndex('i', $wlen, $index); 428 } 429 } 430 // Save the reverse index 431 if (!$this->saveIndexKey('pageword', '', $pid, "")) { 432 return false; 433 } 434 435 $this->saveIndexKey('title', '', $pid, ""); 436 $keyidx = $this->getIndex('metadata', ''); 437 foreach ($keyidx as $metaname) { 438 $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid)); 439 $meta_idx = $this->getIndex($metaname.'_i', ''); 440 foreach ($val_idx as $id) { 441 if ($id === '') continue; 442 $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0); 443 } 444 $this->saveIndex($metaname.'_i', '', $meta_idx); 445 $this->saveIndexKey($metaname.'_p', '', $pid, ''); 446 } 447 448 return true; 449 } 450 451 /** 452 * Clear the whole index 453 * 454 * @return bool If the index has been cleared successfully 455 */ 456 public function clear() 457 { 458 global $conf; 459 460 if (!$this->lock()) return false; 461 462 @unlink($conf['indexdir'].'/page.idx'); 463 @unlink($conf['indexdir'].'/title.idx'); 464 @unlink($conf['indexdir'].'/pageword.idx'); 465 @unlink($conf['indexdir'].'/metadata.idx'); 466 $dir = @opendir($conf['indexdir']); 467 if($dir!==false){ 468 while(($f = readdir($dir)) !== false){ 469 if(substr($f, -4)=='.idx' && 470 (substr($f, 0, 1)=='i' || substr($f, 0, 1)=='w' 471 || substr($f, -6)=='_w.idx' || substr($f, -6)=='_i.idx' || substr($f, -6)=='_p.idx')) 472 @unlink($conf['indexdir']."/$f"); 473 } 474 } 475 @unlink($conf['indexdir'].'/lengths.idx'); 476 477 // clear the pid cache 478 $this->pidCache = []; 479 480 $this->unlock(); 481 return true; 482 } 483 484 /** 485 * Split the text into words for fulltext search 486 * 487 * TODO: does this also need &$stopwords ? 488 * 489 * @triggers INDEXER_TEXT_PREPARE 490 * This event allows plugins to modify the text before it gets tokenized. 491 * Plugins intercepting this event should also intercept INDEX_VERSION_GET 492 * 493 * @param string $text plain text 494 * @param boolean $wc are wildcards allowed? 495 * @return array list of words in the text 496 * 497 * @author Tom N Harris <tnharris@whoopdedo.org> 498 * @author Andreas Gohr <andi@splitbrain.org> 499 */ 500 public function tokenizer($text, $wc = false) 501 { 502 $wc = ($wc) ? '' : '\*'; 503 $stopwords =& idx_get_stopwords(); 504 505 // prepare the text to be tokenized 506 $evt = new Event('INDEXER_TEXT_PREPARE', $text); 507 if ($evt->advise_before(true)) { 508 if (preg_match('/[^0-9A-Za-z ]/u', $text)) { 509 $text = Asian::separateAsianWords($text); 510 } 511 } 512 $evt->advise_after(); 513 unset($evt); 514 515 $text = strtr( 516 $text, 517 ["\r" => ' ', "\n" => ' ', "\t" => ' ', "\xC2\xAD" => ''] 518 ); 519 if (preg_match('/[^0-9A-Za-z ]/u', $text)) 520 $text = Clean::stripspecials($text, ' ', '\._\-:'.$wc); 521 522 $wordlist = explode(' ', $text); 523 foreach ($wordlist as $i => $word) { 524 $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ? 525 PhpString::strtolower($word) : strtolower($word); 526 } 527 528 foreach ($wordlist as $i => $word) { 529 if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) 530 || in_array($word, $stopwords, true)) 531 unset($wordlist[$i]); 532 } 533 return array_values($wordlist); 534 } 535 536 /** 537 * Get the numeric PID of a page 538 * 539 * @param string $page The page to get the PID for 540 * @return bool|int The page id on success, false on error 541 */ 542 public function getPID($page) 543 { 544 // return PID without locking when it is in the cache 545 if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 546 547 if (!$this->lock()) 548 return false; 549 550 // load known documents 551 $pid = $this->getPIDNoLock($page); 552 if ($pid === false) { 553 $this->unlock(); 554 return false; 555 } 556 557 $this->unlock(); 558 return $pid; 559 } 560 561 /** 562 * Get the numeric PID of a page without locking the index. 563 * Only use this function when the index is already locked. 564 * 565 * @param string $page The page to get the PID for 566 * @return bool|int The page id on success, false on error 567 */ 568 protected function getPIDNoLock($page) 569 { 570 // avoid expensive addIndexKey operation for the most recently requested pages by using a cache 571 if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 572 $pid = $this->addIndexKey('page', '', $page); 573 // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently 574 // added item will be requested again 575 if (count($this->pidCache) > 10) array_shift($this->pidCache); 576 $this->pidCache[$page] = $pid; 577 return $pid; 578 } 579 580 /** 581 * Get the page id of a numeric PID 582 * 583 * @param int $pid The PID to get the page id for 584 * @return string The page id 585 */ 586 public function getPageFromPID($pid) 587 { 588 return $this->getIndexKey('page', '', $pid); 589 } 590 591 /** 592 * Find pages in the fulltext index containing the words, 593 * 594 * The search words must be pre-tokenized, meaning only letters and 595 * numbers with an optional wildcard 596 * 597 * The returned array will have the original tokens as key. The values 598 * in the returned list is an array with the page names as keys and the 599 * number of times that token appears on the page as value. 600 * 601 * @param array $tokens list of words to search for 602 * @return array list of page names with usage counts 603 * 604 * @author Tom N Harris <tnharris@whoopdedo.org> 605 * @author Andreas Gohr <andi@splitbrain.org> 606 */ 607 public function lookup(&$tokens) 608 { 609 $result = []; 610 $wids = $this->getIndexWords($tokens, $result); 611 if (empty($wids)) return []; 612 // load known words and documents 613 $page_idx = $this->getIndex('page', ''); 614 $docs = []; 615 foreach (array_keys($wids) as $wlen) { 616 $wids[$wlen] = array_unique($wids[$wlen]); 617 $index = $this->getIndex('i', $wlen); 618 foreach($wids[$wlen] as $ixid) { 619 if ($ixid < count($index)) 620 $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]); 621 } 622 } 623 // merge found pages into final result array 624 $final = []; 625 foreach ($result as $word => $res) { 626 $final[$word] = []; 627 foreach ($res as $wid) { 628 // handle the case when ($ixid < count($index)) has been false 629 // and thus $docs[$wid] hasn't been set. 630 if (!isset($docs[$wid])) continue; 631 $hits = &$docs[$wid]; 632 foreach ($hits as $hitkey => $hitcnt) { 633 // make sure the document still exists 634 if (!page_exists($hitkey, '', false)) continue; 635 if (!isset($final[$word][$hitkey])) 636 $final[$word][$hitkey] = $hitcnt; 637 else 638 $final[$word][$hitkey] += $hitcnt; 639 } 640 } 641 } 642 return $final; 643 } 644 645 /** 646 * Find pages containing a metadata key. 647 * 648 * The metadata values are compared as case-sensitive strings. Pass a 649 * callback function that returns true or false to use a different 650 * comparison function. The function will be called with the $value being 651 * searched for as the first argument, and the word in the index as the 652 * second argument. The function preg_match can be used directly if the 653 * values are regexes. 654 * 655 * @param string $key name of the metadata key to look for 656 * @param string $value search term to look for, must be a string or array of strings 657 * @param callback $func comparison function 658 * @return array lists with page names, keys are query values if $value is array 659 * 660 * @author Tom N Harris <tnharris@whoopdedo.org> 661 * @author Michael Hamann <michael@content-space.de> 662 */ 663 public function lookupKey($key, &$value, $func = null) 664 { 665 if (!is_array($value)) 666 $value_array = [$value]; 667 else 668 $value_array =& $value; 669 670 // the matching ids for the provided value(s) 671 $value_ids = []; 672 673 $metaname = idx_cleanName($key); 674 675 // get all words in order to search the matching ids 676 if ($key == 'title') { 677 $words = $this->getIndex('title', ''); 678 } else { 679 $words = $this->getIndex($metaname.'_w', ''); 680 } 681 682 if (!is_null($func)) { 683 foreach ($value_array as $val) { 684 foreach ($words as $i => $word) { 685 if (call_user_func_array($func, [$val, $word])) 686 $value_ids[$i][] = $val; 687 } 688 } 689 } else { 690 foreach ($value_array as $val) { 691 $xval = $val; 692 $caret = '^'; 693 $dollar = '$'; 694 // check for wildcards 695 if (substr($xval, 0, 1) == '*') { 696 $xval = substr($xval, 1); 697 $caret = ''; 698 } 699 if (substr($xval, -1, 1) == '*') { 700 $xval = substr($xval, 0, -1); 701 $dollar = ''; 702 } 703 if (!$caret || !$dollar) { 704 $re = $caret.preg_quote($xval, '/').$dollar; 705 foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i) 706 $value_ids[$i][] = $val; 707 } elseif (($i = array_search($val, $words, true)) !== false) { 708 $value_ids[$i][] = $val; 709 } 710 } 711 } 712 713 unset($words); // free the used memory 714 715 // initialize the result so it won't be null 716 $result = []; 717 foreach ($value_array as $val) { 718 $result[$val] = []; 719 } 720 721 $page_idx = $this->getIndex('page', ''); 722 723 // Special handling for titles 724 if ($key == 'title') { 725 foreach ($value_ids as $pid => $val_list) { 726 $page = $page_idx[$pid]; 727 foreach ($val_list as $val) { 728 $result[$val][] = $page; 729 } 730 } 731 } else { 732 // load all lines and pages so the used lines can be taken and matched with the pages 733 $lines = $this->getIndex($metaname.'_i', ''); 734 735 foreach ($value_ids as $value_id => $val_list) { 736 // parse the tuples of the form page_id*1:page2_id*1 and so on, return value 737 // is an array with page_id => 1, page2_id => 1 etc. so take the keys only 738 $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id])); 739 foreach ($val_list as $val) { 740 $result[$val] = [...$result[$val], ...$pages]; 741 } 742 } 743 } 744 if (!is_array($value)) $result = $result[$value]; 745 return $result; 746 } 747 748 /** 749 * Find the index ID of each search term. 750 * 751 * The query terms should only contain valid characters, with a '*' at 752 * either the beginning or end of the word (or both). 753 * The $result parameter can be used to merge the index locations with 754 * the appropriate query term. 755 * 756 * @param array $words The query terms. 757 * @param array $result Set to word => array("length*id" ...) 758 * @return array Set to length => array(id ...) 759 * 760 * @author Tom N Harris <tnharris@whoopdedo.org> 761 */ 762 protected function getIndexWords(&$words, &$result) 763 { 764 $tokens = []; 765 $tokenlength = []; 766 $tokenwild = []; 767 foreach ($words as $word) { 768 $result[$word] = []; 769 $caret = '^'; 770 $dollar = '$'; 771 $xword = $word; 772 $wlen = wordlen($word); 773 774 // check for wildcards 775 if (substr($xword, 0, 1) == '*') { 776 $xword = substr($xword, 1); 777 $caret = ''; 778 --$wlen; 779 } 780 if (substr($xword, -1, 1) == '*') { 781 $xword = substr($xword, 0, -1); 782 $dollar = ''; 783 --$wlen; 784 } 785 if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword)) 786 continue; 787 if (!isset($tokens[$xword])) 788 $tokenlength[$wlen][] = $xword; 789 if (!$caret || !$dollar) { 790 $re = $caret.preg_quote($xword, '/').$dollar; 791 $tokens[$xword][] = [$word, '/'.$re.'/']; 792 if (!isset($tokenwild[$xword])) 793 $tokenwild[$xword] = $wlen; 794 } else { 795 $tokens[$xword][] = [$word, null]; 796 } 797 } 798 asort($tokenwild); 799 // $tokens = array( base word => array( [ query term , regexp ] ... ) ... ) 800 // $tokenlength = array( base word length => base word ... ) 801 // $tokenwild = array( base word => base word length ... ) 802 $length_filter = $tokenwild === [] ? $tokenlength : min(array_keys($tokenlength)); 803 $indexes_known = $this->indexLengths($length_filter); 804 if ($tokenwild !== []) sort($indexes_known); 805 // get word IDs 806 $wids = []; 807 foreach ($indexes_known as $ixlen) { 808 $word_idx = $this->getIndex('w', $ixlen); 809 // handle exact search 810 if (isset($tokenlength[$ixlen])) { 811 foreach ($tokenlength[$ixlen] as $xword) { 812 $wid = array_search($xword, $word_idx, true); 813 if ($wid !== false) { 814 $wids[$ixlen][] = $wid; 815 foreach ($tokens[$xword] as $w) 816 $result[$w[0]][] = "$ixlen*$wid"; 817 } 818 } 819 } 820 // handle wildcard search 821 foreach ($tokenwild as $xword => $wlen) { 822 if ($wlen >= $ixlen) break; 823 foreach ($tokens[$xword] as $w) { 824 if (is_null($w[1])) continue; 825 foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) { 826 $wids[$ixlen][] = $wid; 827 $result[$w[0]][] = "$ixlen*$wid"; 828 } 829 } 830 } 831 } 832 return $wids; 833 } 834 835 /** 836 * Return a list of all pages 837 * Warning: pages may not exist! 838 * 839 * @param string $key list only pages containing the metadata key (optional) 840 * @return array list of page names 841 * 842 * @author Tom N Harris <tnharris@whoopdedo.org> 843 */ 844 public function getPages($key = null) 845 { 846 $page_idx = $this->getIndex('page', ''); 847 if (is_null($key)) return $page_idx; 848 849 $metaname = idx_cleanName($key); 850 851 // Special handling for titles 852 if ($key == 'title') { 853 $title_idx = $this->getIndex('title', ''); 854 array_splice($page_idx, count($title_idx)); 855 foreach ($title_idx as $i => $title) 856 if ($title === "") unset($page_idx[$i]); 857 return array_values($page_idx); 858 } 859 860 $pages = []; 861 $lines = $this->getIndex($metaname.'_i', ''); 862 foreach ($lines as $line) { 863 $pages = array_merge($pages, $this->parseTuples($page_idx, $line)); 864 } 865 return array_keys($pages); 866 } 867 868 /** 869 * Return a list of words sorted by number of times used 870 * 871 * @param int $min bottom frequency threshold 872 * @param int $max upper frequency limit. No limit if $max<$min 873 * @param int $minlen minimum length of words to count 874 * @param string $key metadata key to list. Uses the fulltext index if not given 875 * @return array list of words as the keys and frequency as values 876 * 877 * @author Tom N Harris <tnharris@whoopdedo.org> 878 */ 879 public function histogram($min = 1, $max = 0, $minlen = 3, $key = null) 880 { 881 if ($min < 1) 882 $min = 1; 883 if ($max < $min) 884 $max = 0; 885 886 $result = []; 887 888 if ($key == 'title') { 889 $index = $this->getIndex('title', ''); 890 $index = array_count_values($index); 891 foreach ($index as $val => $cnt) { 892 if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen) 893 $result[$val] = $cnt; 894 } 895 } 896 elseif (!is_null($key)) { 897 $metaname = idx_cleanName($key); 898 $index = $this->getIndex($metaname.'_i', ''); 899 $val_idx = []; 900 foreach ($index as $wid => $line) { 901 $freq = $this->countTuples($line); 902 if ($freq >= $min && (!$max || $freq <= $max)) 903 $val_idx[$wid] = $freq; 904 } 905 if (!empty($val_idx)) { 906 $words = $this->getIndex($metaname.'_w', ''); 907 foreach ($val_idx as $wid => $freq) { 908 if (strlen($words[$wid]) >= $minlen) 909 $result[$words[$wid]] = $freq; 910 } 911 } 912 } 913 else { 914 $lengths = idx_listIndexLengths(); 915 foreach ($lengths as $length) { 916 if ($length < $minlen) continue; 917 $index = $this->getIndex('i', $length); 918 $words = null; 919 foreach ($index as $wid => $line) { 920 $freq = $this->countTuples($line); 921 if ($freq >= $min && (!$max || $freq <= $max)) { 922 if ($words === null) 923 $words = $this->getIndex('w', $length); 924 $result[$words[$wid]] = $freq; 925 } 926 } 927 } 928 } 929 930 arsort($result); 931 return $result; 932 } 933 934 /** 935 * Lock the indexer. 936 * 937 * @author Tom N Harris <tnharris@whoopdedo.org> 938 * 939 * @return bool|string 940 */ 941 protected function lock() 942 { 943 global $conf; 944 $status = true; 945 $run = 0; 946 $lock = $conf['lockdir'].'/_indexer.lock'; 947 while (!@mkdir($lock)) { 948 usleep(50); 949 if(is_dir($lock) && time()-@filemtime($lock) > 60*5){ 950 // looks like a stale lock - remove it 951 if (!@rmdir($lock)) { 952 $status = "removing the stale lock failed"; 953 return false; 954 } else { 955 $status = "stale lock removed"; 956 } 957 }elseif($run++ == 1000){ 958 // we waited 5 seconds for that lock 959 return false; 960 } 961 } 962 if ($conf['dperm']) { 963 chmod($lock, $conf['dperm']); 964 } 965 return $status; 966 } 967 968 /** 969 * Release the indexer lock. 970 * 971 * @author Tom N Harris <tnharris@whoopdedo.org> 972 * 973 * @return bool 974 */ 975 protected function unlock() 976 { 977 global $conf; 978 @rmdir($conf['lockdir'].'/_indexer.lock'); 979 return true; 980 } 981 982 /** 983 * Retrieve the entire index. 984 * 985 * The $suffix argument is for an index that is split into 986 * multiple parts. Different index files should use different 987 * base names. 988 * 989 * @param string $idx name of the index 990 * @param string $suffix subpart identifier 991 * @return array list of lines without CR or LF 992 * 993 * @author Tom N Harris <tnharris@whoopdedo.org> 994 */ 995 protected function getIndex($idx, $suffix) 996 { 997 global $conf; 998 $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 999 if (!file_exists($fn)) return []; 1000 return file($fn, FILE_IGNORE_NEW_LINES); 1001 } 1002 1003 /** 1004 * Replace the contents of the index with an array. 1005 * 1006 * @param string $idx name of the index 1007 * @param string $suffix subpart identifier 1008 * @param array $lines list of lines without LF 1009 * @return bool If saving succeeded 1010 * 1011 * @author Tom N Harris <tnharris@whoopdedo.org> 1012 */ 1013 protected function saveIndex($idx, $suffix, &$lines) 1014 { 1015 global $conf; 1016 $fn = $conf['indexdir'].'/'.$idx.$suffix; 1017 $fh = @fopen($fn.'.tmp', 'w'); 1018 if (!$fh) return false; 1019 fwrite($fh, implode("\n", $lines)); 1020 if (!empty($lines)) 1021 fwrite($fh, "\n"); 1022 fclose($fh); 1023 if ($conf['fperm']) 1024 chmod($fn.'.tmp', $conf['fperm']); 1025 io_rename($fn.'.tmp', $fn.'.idx'); 1026 return true; 1027 } 1028 1029 /** 1030 * Retrieve a line from the index. 1031 * 1032 * @param string $idx name of the index 1033 * @param string $suffix subpart identifier 1034 * @param int $id the line number 1035 * @return string a line with trailing whitespace removed 1036 * 1037 * @author Tom N Harris <tnharris@whoopdedo.org> 1038 */ 1039 protected function getIndexKey($idx, $suffix, $id) 1040 { 1041 global $conf; 1042 $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 1043 if (!file_exists($fn)) return ''; 1044 $fh = @fopen($fn, 'r'); 1045 if (!$fh) return ''; 1046 $ln = -1; 1047 while (($line = fgets($fh)) !== false) { 1048 if (++$ln == $id) break; 1049 } 1050 fclose($fh); 1051 return rtrim((string)$line); 1052 } 1053 1054 /** 1055 * Write a line into the index. 1056 * 1057 * @param string $idx name of the index 1058 * @param string $suffix subpart identifier 1059 * @param int $id the line number 1060 * @param string $line line to write 1061 * @return bool If saving succeeded 1062 * 1063 * @author Tom N Harris <tnharris@whoopdedo.org> 1064 */ 1065 protected function saveIndexKey($idx, $suffix, $id, $line) 1066 { 1067 global $conf; 1068 if (substr($line, -1) != "\n") 1069 $line .= "\n"; 1070 $fn = $conf['indexdir'].'/'.$idx.$suffix; 1071 $fh = @fopen($fn.'.tmp', 'w'); 1072 if (!$fh) return false; 1073 $ih = @fopen($fn.'.idx', 'r'); 1074 if ($ih) { 1075 $ln = -1; 1076 while (($curline = fgets($ih)) !== false) { 1077 fwrite($fh, (++$ln == $id) ? $line : $curline); 1078 } 1079 if ($id > $ln) { 1080 while ($id > ++$ln) 1081 fwrite($fh, "\n"); 1082 fwrite($fh, $line); 1083 } 1084 fclose($ih); 1085 } else { 1086 $ln = -1; 1087 while ($id > ++$ln) 1088 fwrite($fh, "\n"); 1089 fwrite($fh, $line); 1090 } 1091 fclose($fh); 1092 if ($conf['fperm']) 1093 chmod($fn.'.tmp', $conf['fperm']); 1094 io_rename($fn.'.tmp', $fn.'.idx'); 1095 return true; 1096 } 1097 1098 /** 1099 * Retrieve or insert a value in the index. 1100 * 1101 * @param string $idx name of the index 1102 * @param string $suffix subpart identifier 1103 * @param string $value line to find in the index 1104 * @return int|bool line number of the value in the index or false if writing the index failed 1105 * 1106 * @author Tom N Harris <tnharris@whoopdedo.org> 1107 */ 1108 protected function addIndexKey($idx, $suffix, $value) 1109 { 1110 $index = $this->getIndex($idx, $suffix); 1111 $id = array_search($value, $index, true); 1112 if ($id === false) { 1113 $id = count($index); 1114 $index[$id] = $value; 1115 if (!$this->saveIndex($idx, $suffix, $index)) { 1116 trigger_error("Failed to write $idx index", E_USER_ERROR); 1117 return false; 1118 } 1119 } 1120 return $id; 1121 } 1122 1123 /** 1124 * Get the list of lengths indexed in the wiki. 1125 * 1126 * Read the index directory or a cache file and returns 1127 * a sorted array of lengths of the words used in the wiki. 1128 * 1129 * @author YoBoY <yoboy.leguesh@gmail.com> 1130 * 1131 * @return array 1132 */ 1133 protected function listIndexLengths() 1134 { 1135 return idx_listIndexLengths(); 1136 } 1137 1138 /** 1139 * Get the word lengths that have been indexed. 1140 * 1141 * Reads the index directory and returns an array of lengths 1142 * that there are indices for. 1143 * 1144 * @author YoBoY <yoboy.leguesh@gmail.com> 1145 * 1146 * @param array|int $filter 1147 * @return array 1148 */ 1149 protected function indexLengths($filter) 1150 { 1151 global $conf; 1152 $idx = []; 1153 if (is_array($filter)) { 1154 // testing if index files exist only 1155 $path = $conf['indexdir']."/i"; 1156 foreach (array_keys($filter) as $key) { 1157 if (file_exists($path.$key.'.idx')) 1158 $idx[] = $key; 1159 } 1160 } else { 1161 $lengths = idx_listIndexLengths(); 1162 foreach ($lengths as $length) { 1163 // keep all the values equal or superior 1164 if ((int)$length >= (int)$filter) 1165 $idx[] = $length; 1166 } 1167 } 1168 return $idx; 1169 } 1170 1171 /** 1172 * Insert or replace a tuple in a line. 1173 * 1174 * @author Tom N Harris <tnharris@whoopdedo.org> 1175 * 1176 * @param string $line 1177 * @param string|int $id 1178 * @param int $count 1179 * @return string 1180 */ 1181 protected function updateTuple($line, $id, $count) 1182 { 1183 if ($line != ''){ 1184 $line = preg_replace('/(^|:)'.preg_quote($id, '/').'\*\d*/', '', $line); 1185 } 1186 $line = trim($line, ':'); 1187 if ($count) { 1188 if ($line) { 1189 return "$id*$count:".$line; 1190 } else { 1191 return "$id*$count"; 1192 } 1193 } 1194 return $line; 1195 } 1196 1197 /** 1198 * Split a line into an array of tuples. 1199 * 1200 * @author Tom N Harris <tnharris@whoopdedo.org> 1201 * @author Andreas Gohr <andi@splitbrain.org> 1202 * 1203 * @param array $keys 1204 * @param string $line 1205 * @return array 1206 */ 1207 protected function parseTuples(&$keys, $line) 1208 { 1209 $result = []; 1210 if ($line == '') return $result; 1211 $parts = explode(':', $line); 1212 foreach ($parts as $tuple) { 1213 if ($tuple === '') continue; 1214 [$key, $cnt] = explode('*', $tuple); 1215 if (!$cnt) continue; 1216 if (isset($keys[$key])) { 1217 $key = $keys[$key]; 1218 if ($key === false || is_null($key)) continue; 1219 } 1220 $result[$key] = $cnt; 1221 } 1222 return $result; 1223 } 1224 1225 /** 1226 * Sum the counts in a list of tuples. 1227 * 1228 * @author Tom N Harris <tnharris@whoopdedo.org> 1229 * 1230 * @param string $line 1231 * @return int 1232 */ 1233 protected function countTuples($line) 1234 { 1235 $freq = 0; 1236 $parts = explode(':', $line); 1237 foreach ($parts as $tuple) { 1238 if ($tuple === '') continue; 1239 [, $cnt] = explode('*', $tuple); 1240 $freq += (int)$cnt; 1241 } 1242 return $freq; 1243 } 1244} 1245