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