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', 5); 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 $wid = array_search($word, $word_idx); 219 if ($wid === false) { 220 $wid = count($word_idx); 221 $word_idx[] = $word; 222 $word_idx_modified = true; 223 } 224 if (!isset($index[$wlen])) 225 $index[$wlen] = array(); 226 $index[$wlen][$wid] = $freq; 227 } 228 // save back the word index 229 if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx)) 230 return false; 231 } 232 233 return $index; 234 } 235 236 /** 237 * Add/update keys to/of the metadata index. 238 * 239 * Adding new keys does not remove other keys for the page. 240 * An empty value will erase the key. 241 * The $key parameter can be an array to add multiple keys. $value will 242 * not be used if $key is an array. 243 * 244 * @param string $page a page name 245 * @param mixed $key a key string or array of key=>value pairs 246 * @param mixed $value the value or list of values 247 * @return boolean the function completed successfully 248 * @author Tom N Harris <tnharris@whoopdedo.org> 249 * @author Michael Hamann <michael@content-space.de> 250 */ 251 public function addMetaKeys($page, $key, $value=null) { 252 if (!is_array($key)) { 253 $key = array($key => $value); 254 } elseif (!is_null($value)) { 255 // $key is array, but $value is not null 256 trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING); 257 } 258 259 if (!$this->lock()) 260 return "locked"; 261 262 // load known documents 263 $pid = $this->getPIDNoLock($page); 264 if ($pid === false) { 265 $this->unlock(); 266 return false; 267 } 268 269 // Special handling for titles so the index file is simpler 270 if (array_key_exists('title', $key)) { 271 $value = $key['title']; 272 if (is_array($value)) 273 $value = $value[0]; 274 $this->saveIndexKey('title', '', $pid, $value); 275 unset($key['title']); 276 } 277 278 foreach ($key as $name => $values) { 279 $metaname = idx_cleanName($name); 280 $this->addIndexKey('metadata', '', $metaname); 281 $metaidx = $this->getIndex($metaname.'_i', ''); 282 $metawords = $this->getIndex($metaname.'_w', ''); 283 $addwords = false; 284 285 if (!is_array($values)) $values = array($values); 286 287 $val_idx = $this->getIndexKey($metaname.'_p', '', $pid); 288 if ($val_idx != '') { 289 $val_idx = explode(':', $val_idx); 290 // -1 means remove, 0 keep, 1 add 291 $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1)); 292 } else { 293 $val_idx = array(); 294 } 295 296 foreach ($values as $val) { 297 $val = (string)$val; 298 if ($val !== "") { 299 $id = array_search($val, $metawords); 300 if ($id === false) { 301 $id = count($metawords); 302 $metawords[$id] = $val; 303 $addwords = true; 304 } 305 // test if value is already in the index 306 if (isset($val_idx[$id]) && $val_idx[$id] <= 0) 307 $val_idx[$id] = 0; 308 else // else add it 309 $val_idx[$id] = 1; 310 } 311 } 312 313 if ($addwords) 314 $this->saveIndex($metaname.'_w', '', $metawords); 315 $vals_changed = false; 316 foreach ($val_idx as $id => $action) { 317 if ($action == -1) { 318 $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0); 319 $vals_changed = true; 320 unset($val_idx[$id]); 321 } elseif ($action == 1) { 322 $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1); 323 $vals_changed = true; 324 } 325 } 326 327 if ($vals_changed) { 328 $this->saveIndex($metaname.'_i', '', $metaidx); 329 $val_idx = implode(':', array_keys($val_idx)); 330 $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx); 331 } 332 333 unset($metaidx); 334 unset($metawords); 335 } 336 337 $this->unlock(); 338 return true; 339 } 340 341 /** 342 * Remove a page from the index 343 * 344 * Erases entries in all known indexes. 345 * 346 * @param string $page a page name 347 * @return boolean the function completed successfully 348 * @author Tom N Harris <tnharris@whoopdedo.org> 349 */ 350 public function deletePage($page) { 351 if (!$this->lock()) 352 return "locked"; 353 354 // load known documents 355 $pid = $this->getPIDNoLock($page); 356 if ($pid === false) { 357 $this->unlock(); 358 return false; 359 } 360 361 // Remove obsolete index entries 362 $pageword_idx = $this->getIndexKey('pageword', '', $pid); 363 if ($pageword_idx !== '') { 364 $delwords = explode(':',$pageword_idx); 365 $upwords = array(); 366 foreach ($delwords as $word) { 367 if ($word != '') { 368 list($wlen,$wid) = explode('*', $word); 369 $wid = (int)$wid; 370 $upwords[$wlen][] = $wid; 371 } 372 } 373 foreach ($upwords as $wlen => $widx) { 374 $index = $this->getIndex('i', $wlen); 375 foreach ($widx as $wid) { 376 $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 377 } 378 $this->saveIndex('i', $wlen, $index); 379 } 380 } 381 // Save the reverse index 382 if (!$this->saveIndexKey('pageword', '', $pid, "")) { 383 $this->unlock(); 384 return false; 385 } 386 387 $this->saveIndexKey('title', '', $pid, ""); 388 $keyidx = $this->getIndex('metadata', ''); 389 foreach ($keyidx as $metaname) { 390 $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid)); 391 $meta_idx = $this->getIndex($metaname.'_i', ''); 392 foreach ($val_idx as $id) { 393 if ($id === '') continue; 394 $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0); 395 } 396 $this->saveIndex($metaname.'_i', '', $meta_idx); 397 $this->saveIndexKey($metaname.'_p', '', $pid, ''); 398 } 399 400 $this->unlock(); 401 return true; 402 } 403 404 /** 405 * Split the text into words for fulltext search 406 * 407 * TODO: does this also need &$stopwords ? 408 * 409 * @triggers INDEXER_TEXT_PREPARE 410 * This event allows plugins to modify the text before it gets tokenized. 411 * Plugins intercepting this event should also intercept INDEX_VERSION_GET 412 * 413 * @param string $text plain text 414 * @param boolean $wc are wildcards allowed? 415 * @return array list of words in the text 416 * @author Tom N Harris <tnharris@whoopdedo.org> 417 * @author Andreas Gohr <andi@splitbrain.org> 418 */ 419 public function tokenizer($text, $wc=false) { 420 $wc = ($wc) ? '' : '\*'; 421 $stopwords =& idx_get_stopwords(); 422 423 // prepare the text to be tokenized 424 $evt = new Doku_Event('INDEXER_TEXT_PREPARE', $text); 425 if ($evt->advise_before(true)) { 426 if (preg_match('/[^0-9A-Za-z ]/u', $text)) { 427 // handle asian chars as single words (may fail on older PHP version) 428 $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text); 429 if (!is_null($asia)) $text = $asia; // recover from regexp falure 430 } 431 } 432 $evt->advise_after(); 433 unset($evt); 434 435 $text = strtr($text, 436 array( 437 "\r" => ' ', 438 "\n" => ' ', 439 "\t" => ' ', 440 "\xC2\xAD" => '', //soft-hyphen 441 ) 442 ); 443 if (preg_match('/[^0-9A-Za-z ]/u', $text)) 444 $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc); 445 446 $wordlist = explode(' ', $text); 447 foreach ($wordlist as $i => $word) { 448 $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ? 449 utf8_strtolower($word) : strtolower($word); 450 } 451 452 foreach ($wordlist as $i => $word) { 453 if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) 454 || array_search($word, $stopwords) !== false) 455 unset($wordlist[$i]); 456 } 457 return array_values($wordlist); 458 } 459 460 /** 461 * Get the numeric PID of a page 462 * 463 * @param string $page The page to get the PID for 464 * @return bool|int The page id on success, false on error 465 */ 466 public function getPID($page) { 467 // return PID without locking when it is in the cache 468 if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 469 470 if (!$this->lock()) 471 return false; 472 473 // load known documents 474 $pid = $this->getPIDNoLock($page); 475 if ($pid === false) { 476 $this->unlock(); 477 return false; 478 } 479 480 $this->unlock(); 481 return $pid; 482 } 483 484 /** 485 * Get the numeric PID of a page without locking the index. 486 * Only use this function when the index is already locked. 487 * 488 * @param string $page The page to get the PID for 489 * @return bool|int The page id on success, false on error 490 */ 491 protected function getPIDNoLock($page) { 492 // avoid expensive addIndexKey operation for the most recently requested pages by using a cache 493 if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 494 $pid = $this->addIndexKey('page', '', $page); 495 // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently 496 // added item will be requested again 497 if (count($this->pidCache) > 10) array_shift($this->pidCache); 498 $this->pidCache[$page] = $pid; 499 return $pid; 500 } 501 502 /** 503 * Get the page id of a numeric PID 504 * 505 * @param int $pid The PID to get the page id for 506 * @return string The page id 507 */ 508 public function getPageFromPID($pid) { 509 return $this->getIndexKey('page', '', $pid); 510 } 511 512 /** 513 * Find pages in the fulltext index containing the words, 514 * 515 * The search words must be pre-tokenized, meaning only letters and 516 * numbers with an optional wildcard 517 * 518 * The returned array will have the original tokens as key. The values 519 * in the returned list is an array with the page names as keys and the 520 * number of times that token appears on the page as value. 521 * 522 * @param array $tokens list of words to search for 523 * @return array list of page names with usage counts 524 * @author Tom N Harris <tnharris@whoopdedo.org> 525 * @author Andreas Gohr <andi@splitbrain.org> 526 */ 527 public function lookup(&$tokens) { 528 $result = array(); 529 $wids = $this->getIndexWords($tokens, $result); 530 if (empty($wids)) return array(); 531 // load known words and documents 532 $page_idx = $this->getIndex('page', ''); 533 $docs = array(); 534 foreach (array_keys($wids) as $wlen) { 535 $wids[$wlen] = array_unique($wids[$wlen]); 536 $index = $this->getIndex('i', $wlen); 537 foreach($wids[$wlen] as $ixid) { 538 if ($ixid < count($index)) 539 $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]); 540 } 541 } 542 // merge found pages into final result array 543 $final = array(); 544 foreach ($result as $word => $res) { 545 $final[$word] = array(); 546 foreach ($res as $wid) { 547 // handle the case when ($ixid < count($index)) has been false 548 // and thus $docs[$wid] hasn't been set. 549 if (!isset($docs[$wid])) continue; 550 $hits = &$docs[$wid]; 551 foreach ($hits as $hitkey => $hitcnt) { 552 // make sure the document still exists 553 if (!page_exists($hitkey, '', false)) continue; 554 if (!isset($final[$word][$hitkey])) 555 $final[$word][$hitkey] = $hitcnt; 556 else 557 $final[$word][$hitkey] += $hitcnt; 558 } 559 } 560 } 561 return $final; 562 } 563 564 /** 565 * Find pages containing a metadata key. 566 * 567 * The metadata values are compared as case-sensitive strings. Pass a 568 * callback function that returns true or false to use a different 569 * comparison function. The function will be called with the $value being 570 * searched for as the first argument, and the word in the index as the 571 * second argument. The function preg_match can be used directly if the 572 * values are regexes. 573 * 574 * @param string $key name of the metadata key to look for 575 * @param string $value search term to look for, must be a string or array of strings 576 * @param callback $func comparison function 577 * @return array lists with page names, keys are query values if $value is array 578 * @author Tom N Harris <tnharris@whoopdedo.org> 579 * @author Michael Hamann <michael@content-space.de> 580 */ 581 public function lookupKey($key, &$value, $func=null) { 582 if (!is_array($value)) 583 $value_array = array($value); 584 else 585 $value_array =& $value; 586 587 // the matching ids for the provided value(s) 588 $value_ids = array(); 589 590 $metaname = idx_cleanName($key); 591 592 // get all words in order to search the matching ids 593 if ($key == 'title') { 594 $words = $this->getIndex('title', ''); 595 } else { 596 $words = $this->getIndex($metaname.'_w', ''); 597 } 598 599 if (!is_null($func)) { 600 foreach ($value_array as $val) { 601 foreach ($words as $i => $word) { 602 if (call_user_func_array($func, array($val, $word))) 603 $value_ids[$i][] = $val; 604 } 605 } 606 } else { 607 foreach ($value_array as $val) { 608 $xval = $val; 609 $caret = '^'; 610 $dollar = '$'; 611 // check for wildcards 612 if (substr($xval, 0, 1) == '*') { 613 $xval = substr($xval, 1); 614 $caret = ''; 615 } 616 if (substr($xval, -1, 1) == '*') { 617 $xval = substr($xval, 0, -1); 618 $dollar = ''; 619 } 620 if (!$caret || !$dollar) { 621 $re = $caret.preg_quote($xval, '/').$dollar; 622 foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i) 623 $value_ids[$i][] = $val; 624 } else { 625 if (($i = array_search($val, $words)) !== false) 626 $value_ids[$i][] = $val; 627 } 628 } 629 } 630 631 unset($words); // free the used memory 632 633 // initialize the result so it won't be null 634 $result = array(); 635 foreach ($value_array as $val) { 636 $result[$val] = array(); 637 } 638 639 $page_idx = $this->getIndex('page', ''); 640 641 // Special handling for titles 642 if ($key == 'title') { 643 foreach ($value_ids as $pid => $val_list) { 644 $page = $page_idx[$pid]; 645 foreach ($val_list as $val) { 646 $result[$val][] = $page; 647 } 648 } 649 } else { 650 // load all lines and pages so the used lines can be taken and matched with the pages 651 $lines = $this->getIndex($metaname.'_i', ''); 652 653 foreach ($value_ids as $value_id => $val_list) { 654 // parse the tuples of the form page_id*1:page2_id*1 and so on, return value 655 // is an array with page_id => 1, page2_id => 1 etc. so take the keys only 656 $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id])); 657 foreach ($val_list as $val) { 658 $result[$val] = array_merge($result[$val], $pages); 659 } 660 } 661 } 662 if (!is_array($value)) $result = $result[$value]; 663 return $result; 664 } 665 666 /** 667 * Find the index ID of each search term. 668 * 669 * The query terms should only contain valid characters, with a '*' at 670 * either the beginning or end of the word (or both). 671 * The $result parameter can be used to merge the index locations with 672 * the appropriate query term. 673 * 674 * @param array $words The query terms. 675 * @param array $result Set to word => array("length*id" ...) 676 * @return array Set to length => array(id ...) 677 * @author Tom N Harris <tnharris@whoopdedo.org> 678 */ 679 protected function getIndexWords(&$words, &$result) { 680 $tokens = array(); 681 $tokenlength = array(); 682 $tokenwild = array(); 683 foreach ($words as $word) { 684 $result[$word] = array(); 685 $caret = '^'; 686 $dollar = '$'; 687 $xword = $word; 688 $wlen = wordlen($word); 689 690 // check for wildcards 691 if (substr($xword, 0, 1) == '*') { 692 $xword = substr($xword, 1); 693 $caret = ''; 694 $wlen -= 1; 695 } 696 if (substr($xword, -1, 1) == '*') { 697 $xword = substr($xword, 0, -1); 698 $dollar = ''; 699 $wlen -= 1; 700 } 701 if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword)) 702 continue; 703 if (!isset($tokens[$xword])) 704 $tokenlength[$wlen][] = $xword; 705 if (!$caret || !$dollar) { 706 $re = $caret.preg_quote($xword, '/').$dollar; 707 $tokens[$xword][] = array($word, '/'.$re.'/'); 708 if (!isset($tokenwild[$xword])) 709 $tokenwild[$xword] = $wlen; 710 } else { 711 $tokens[$xword][] = array($word, null); 712 } 713 } 714 asort($tokenwild); 715 // $tokens = array( base word => array( [ query term , regexp ] ... ) ... ) 716 // $tokenlength = array( base word length => base word ... ) 717 // $tokenwild = array( base word => base word length ... ) 718 $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength)); 719 $indexes_known = $this->indexLengths($length_filter); 720 if (!empty($tokenwild)) sort($indexes_known); 721 // get word IDs 722 $wids = array(); 723 foreach ($indexes_known as $ixlen) { 724 $word_idx = $this->getIndex('w', $ixlen); 725 // handle exact search 726 if (isset($tokenlength[$ixlen])) { 727 foreach ($tokenlength[$ixlen] as $xword) { 728 $wid = array_search($xword, $word_idx); 729 if ($wid !== false) { 730 $wids[$ixlen][] = $wid; 731 foreach ($tokens[$xword] as $w) 732 $result[$w[0]][] = "$ixlen*$wid"; 733 } 734 } 735 } 736 // handle wildcard search 737 foreach ($tokenwild as $xword => $wlen) { 738 if ($wlen >= $ixlen) break; 739 foreach ($tokens[$xword] as $w) { 740 if (is_null($w[1])) continue; 741 foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) { 742 $wids[$ixlen][] = $wid; 743 $result[$w[0]][] = "$ixlen*$wid"; 744 } 745 } 746 } 747 } 748 return $wids; 749 } 750 751 /** 752 * Return a list of all pages 753 * Warning: pages may not exist! 754 * 755 * @param string $key list only pages containing the metadata key (optional) 756 * @return array list of page names 757 * @author Tom N Harris <tnharris@whoopdedo.org> 758 */ 759 public function getPages($key=null) { 760 $page_idx = $this->getIndex('page', ''); 761 if (is_null($key)) return $page_idx; 762 763 $metaname = idx_cleanName($key); 764 765 // Special handling for titles 766 if ($key == 'title') { 767 $title_idx = $this->getIndex('title', ''); 768 array_splice($page_idx, count($title_idx)); 769 foreach ($title_idx as $i => $title) 770 if ($title === "") unset($page_idx[$i]); 771 return array_values($page_idx); 772 } 773 774 $pages = array(); 775 $lines = $this->getIndex($metaname.'_i', ''); 776 foreach ($lines as $line) { 777 $pages = array_merge($pages, $this->parseTuples($page_idx, $line)); 778 } 779 return array_keys($pages); 780 } 781 782 /** 783 * Return a list of words sorted by number of times used 784 * 785 * @param int $min bottom frequency threshold 786 * @param int $max upper frequency limit. No limit if $max<$min 787 * @param int $minlen minimum length of words to count 788 * @param string $key metadata key to list. Uses the fulltext index if not given 789 * @return array list of words as the keys and frequency as values 790 * @author Tom N Harris <tnharris@whoopdedo.org> 791 */ 792 public function histogram($min=1, $max=0, $minlen=3, $key=null) { 793 if ($min < 1) 794 $min = 1; 795 if ($max < $min) 796 $max = 0; 797 798 $result = array(); 799 800 if ($key == 'title') { 801 $index = $this->getIndex('title', ''); 802 $index = array_count_values($index); 803 foreach ($index as $val => $cnt) { 804 if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen) 805 $result[$val] = $cnt; 806 } 807 } 808 elseif (!is_null($key)) { 809 $metaname = idx_cleanName($key); 810 $index = $this->getIndex($metaname.'_i', ''); 811 $val_idx = array(); 812 foreach ($index as $wid => $line) { 813 $freq = $this->countTuples($line); 814 if ($freq >= $min && (!$max || $freq <= $max)) 815 $val_idx[$wid] = $freq; 816 } 817 if (!empty($val_idx)) { 818 $words = $this->getIndex($metaname.'_w', ''); 819 foreach ($val_idx as $wid => $freq) { 820 if (strlen($words[$wid]) >= $minlen) 821 $result[$words[$wid]] = $freq; 822 } 823 } 824 } 825 else { 826 $lengths = idx_listIndexLengths(); 827 foreach ($lengths as $length) { 828 if ($length < $minlen) continue; 829 $index = $this->getIndex('i', $length); 830 $words = null; 831 foreach ($index as $wid => $line) { 832 $freq = $this->countTuples($line); 833 if ($freq >= $min && (!$max || $freq <= $max)) { 834 if ($words === null) 835 $words = $this->getIndex('w', $length); 836 $result[$words[$wid]] = $freq; 837 } 838 } 839 } 840 } 841 842 arsort($result); 843 return $result; 844 } 845 846 /** 847 * Lock the indexer. 848 * 849 * @author Tom N Harris <tnharris@whoopdedo.org> 850 */ 851 protected function lock() { 852 global $conf; 853 $status = true; 854 $run = 0; 855 $lock = $conf['lockdir'].'/_indexer.lock'; 856 while (!@mkdir($lock, $conf['dmode'])) { 857 usleep(50); 858 if(is_dir($lock) && time()-@filemtime($lock) > 60*5){ 859 // looks like a stale lock - remove it 860 if (!@rmdir($lock)) { 861 $status = "removing the stale lock failed"; 862 return false; 863 } else { 864 $status = "stale lock removed"; 865 } 866 }elseif($run++ == 1000){ 867 // we waited 5 seconds for that lock 868 return false; 869 } 870 } 871 if ($conf['dperm']) 872 chmod($lock, $conf['dperm']); 873 return $status; 874 } 875 876 /** 877 * Release the indexer lock. 878 * 879 * @author Tom N Harris <tnharris@whoopdedo.org> 880 */ 881 protected function unlock() { 882 global $conf; 883 @rmdir($conf['lockdir'].'/_indexer.lock'); 884 return true; 885 } 886 887 /** 888 * Retrieve the entire index. 889 * 890 * The $suffix argument is for an index that is split into 891 * multiple parts. Different index files should use different 892 * base names. 893 * 894 * @param string $idx name of the index 895 * @param string $suffix subpart identifier 896 * @return array list of lines without CR or LF 897 * @author Tom N Harris <tnharris@whoopdedo.org> 898 */ 899 protected function getIndex($idx, $suffix) { 900 global $conf; 901 $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 902 if (!@file_exists($fn)) return array(); 903 return file($fn, FILE_IGNORE_NEW_LINES); 904 } 905 906 /** 907 * Replace the contents of the index with an array. 908 * 909 * @param string $idx name of the index 910 * @param string $suffix subpart identifier 911 * @param array $lines list of lines without LF 912 * @return bool If saving succeeded 913 * @author Tom N Harris <tnharris@whoopdedo.org> 914 */ 915 protected function saveIndex($idx, $suffix, &$lines) { 916 global $conf; 917 $fn = $conf['indexdir'].'/'.$idx.$suffix; 918 $fh = @fopen($fn.'.tmp', 'w'); 919 if (!$fh) return false; 920 fwrite($fh, join("\n", $lines)); 921 if (!empty($lines)) 922 fwrite($fh, "\n"); 923 fclose($fh); 924 if (isset($conf['fperm'])) 925 chmod($fn.'.tmp', $conf['fperm']); 926 io_rename($fn.'.tmp', $fn.'.idx'); 927 if ($suffix !== '') 928 $this->cacheIndexDir($idx, $suffix, empty($lines)); 929 return true; 930 } 931 932 /** 933 * Retrieve a line from the index. 934 * 935 * @param string $idx name of the index 936 * @param string $suffix subpart identifier 937 * @param int $id the line number 938 * @return string a line with trailing whitespace removed 939 * @author Tom N Harris <tnharris@whoopdedo.org> 940 */ 941 protected function getIndexKey($idx, $suffix, $id) { 942 global $conf; 943 $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 944 if (!@file_exists($fn)) return ''; 945 $fh = @fopen($fn, 'r'); 946 if (!$fh) return ''; 947 $ln = -1; 948 while (($line = fgets($fh)) !== false) { 949 if (++$ln == $id) break; 950 } 951 fclose($fh); 952 return rtrim((string)$line); 953 } 954 955 /** 956 * Write a line into the index. 957 * 958 * @param string $idx name of the index 959 * @param string $suffix subpart identifier 960 * @param int $id the line number 961 * @param string $line line to write 962 * @return bool If saving succeeded 963 * @author Tom N Harris <tnharris@whoopdedo.org> 964 */ 965 protected function saveIndexKey($idx, $suffix, $id, $line) { 966 global $conf; 967 if (substr($line, -1) != "\n") 968 $line .= "\n"; 969 $fn = $conf['indexdir'].'/'.$idx.$suffix; 970 $fh = @fopen($fn.'.tmp', 'w'); 971 if (!$fh) return false; 972 $ih = @fopen($fn.'.idx', 'r'); 973 if ($ih) { 974 $ln = -1; 975 while (($curline = fgets($ih)) !== false) { 976 fwrite($fh, (++$ln == $id) ? $line : $curline); 977 } 978 if ($id > $ln) { 979 while ($id > ++$ln) 980 fwrite($fh, "\n"); 981 fwrite($fh, $line); 982 } 983 fclose($ih); 984 } else { 985 $ln = -1; 986 while ($id > ++$ln) 987 fwrite($fh, "\n"); 988 fwrite($fh, $line); 989 } 990 fclose($fh); 991 if (isset($conf['fperm'])) 992 chmod($fn.'.tmp', $conf['fperm']); 993 io_rename($fn.'.tmp', $fn.'.idx'); 994 if ($suffix !== '') 995 $this->cacheIndexDir($idx, $suffix); 996 return true; 997 } 998 999 /** 1000 * Retrieve or insert a value in the index. 1001 * 1002 * @param string $idx name of the index 1003 * @param string $suffix subpart identifier 1004 * @param string $value line to find in the index 1005 * @return int|bool line number of the value in the index or false if writing the index failed 1006 * @author Tom N Harris <tnharris@whoopdedo.org> 1007 */ 1008 protected function addIndexKey($idx, $suffix, $value) { 1009 $index = $this->getIndex($idx, $suffix); 1010 $id = array_search($value, $index); 1011 if ($id === false) { 1012 $id = count($index); 1013 $index[$id] = $value; 1014 if (!$this->saveIndex($idx, $suffix, $index)) { 1015 trigger_error("Failed to write $idx index", E_USER_ERROR); 1016 return false; 1017 } 1018 } 1019 return $id; 1020 } 1021 1022 /** 1023 * @param string $idx The index file which should be added to the key. 1024 * @param string $suffix The suffix of the file 1025 * @param bool $delete Unused 1026 */ 1027 protected function cacheIndexDir($idx, $suffix, $delete=false) { 1028 global $conf; 1029 if ($idx == 'i') 1030 $cachename = $conf['indexdir'].'/lengths'; 1031 else 1032 $cachename = $conf['indexdir'].'/'.$idx.'lengths'; 1033 $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 1034 if ($lengths === false) $lengths = array(); 1035 $old = array_search((string)$suffix, $lengths); 1036 if (empty($lines)) { 1037 if ($old === false) return; 1038 unset($lengths[$old]); 1039 } else { 1040 if ($old !== false) return; 1041 $lengths[] = $suffix; 1042 sort($lengths); 1043 } 1044 $fh = @fopen($cachename.'.tmp', 'w'); 1045 if (!$fh) { 1046 trigger_error("Failed to write index cache", E_USER_ERROR); 1047 return; 1048 } 1049 @fwrite($fh, implode("\n", $lengths)); 1050 @fclose($fh); 1051 if (isset($conf['fperm'])) 1052 chmod($cachename.'.tmp', $conf['fperm']); 1053 io_rename($cachename.'.tmp', $cachename.'.idx'); 1054 } 1055 1056 /** 1057 * Get the list of lengths indexed in the wiki. 1058 * 1059 * Read the index directory or a cache file and returns 1060 * a sorted array of lengths of the words used in the wiki. 1061 * 1062 * @author YoBoY <yoboy.leguesh@gmail.com> 1063 */ 1064 protected function listIndexLengths() { 1065 global $conf; 1066 $cachename = $conf['indexdir'].'/lengths'; 1067 clearstatcache(); 1068 if (@file_exists($cachename.'.idx')) { 1069 $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 1070 if ($lengths !== false) { 1071 $idx = array(); 1072 foreach ($lengths as $length) 1073 $idx[] = (int)$length; 1074 return $idx; 1075 } 1076 } 1077 1078 $dir = @opendir($conf['indexdir']); 1079 if ($dir === false) 1080 return array(); 1081 $lengths[] = array(); 1082 while (($f = readdir($dir)) !== false) { 1083 if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') { 1084 $i = substr($f, 1, -4); 1085 if (is_numeric($i)) 1086 $lengths[] = (int)$i; 1087 } 1088 } 1089 closedir($dir); 1090 sort($lengths); 1091 // save this in a file 1092 $fh = @fopen($cachename.'.tmp', 'w'); 1093 if (!$fh) { 1094 trigger_error("Failed to write index cache", E_USER_ERROR); 1095 return $lengths; 1096 } 1097 @fwrite($fh, implode("\n", $lengths)); 1098 @fclose($fh); 1099 if (isset($conf['fperm'])) 1100 chmod($cachename.'.tmp', $conf['fperm']); 1101 io_rename($cachename.'.tmp', $cachename.'.idx'); 1102 1103 return $lengths; 1104 } 1105 1106 /** 1107 * Get the word lengths that have been indexed. 1108 * 1109 * Reads the index directory and returns an array of lengths 1110 * that there are indices for. 1111 * 1112 * @author YoBoY <yoboy.leguesh@gmail.com> 1113 */ 1114 protected function indexLengths($filter) { 1115 global $conf; 1116 $idx = array(); 1117 if (is_array($filter)) { 1118 // testing if index files exist only 1119 $path = $conf['indexdir']."/i"; 1120 foreach ($filter as $key => $value) { 1121 if (@file_exists($path.$key.'.idx')) 1122 $idx[] = $key; 1123 } 1124 } else { 1125 $lengths = idx_listIndexLengths(); 1126 foreach ($lengths as $key => $length) { 1127 // keep all the values equal or superior 1128 if ((int)$length >= (int)$filter) 1129 $idx[] = $length; 1130 } 1131 } 1132 return $idx; 1133 } 1134 1135 /** 1136 * Insert or replace a tuple in a line. 1137 * 1138 * @author Tom N Harris <tnharris@whoopdedo.org> 1139 */ 1140 protected function updateTuple($line, $id, $count) { 1141 $newLine = $line; 1142 if ($newLine !== '') 1143 $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine); 1144 $newLine = trim($newLine, ':'); 1145 if ($count) { 1146 if (strlen($newLine) > 0) 1147 return "$id*$count:".$newLine; 1148 else 1149 return "$id*$count".$newLine; 1150 } 1151 return $newLine; 1152 } 1153 1154 /** 1155 * Split a line into an array of tuples. 1156 * 1157 * @author Tom N Harris <tnharris@whoopdedo.org> 1158 * @author Andreas Gohr <andi@splitbrain.org> 1159 */ 1160 protected function parseTuples(&$keys, $line) { 1161 $result = array(); 1162 if ($line == '') return $result; 1163 $parts = explode(':', $line); 1164 foreach ($parts as $tuple) { 1165 if ($tuple === '') continue; 1166 list($key, $cnt) = explode('*', $tuple); 1167 if (!$cnt) continue; 1168 $key = $keys[$key]; 1169 if (!$key) continue; 1170 $result[$key] = $cnt; 1171 } 1172 return $result; 1173 } 1174 1175 /** 1176 * Sum the counts in a list of tuples. 1177 * 1178 * @author Tom N Harris <tnharris@whoopdedo.org> 1179 */ 1180 protected function countTuples($line) { 1181 $freq = 0; 1182 $parts = explode(':', $line); 1183 foreach ($parts as $tuple) { 1184 if ($tuple === '') continue; 1185 list($pid, $cnt) = explode('*', $tuple); 1186 $freq += (int)$cnt; 1187 } 1188 return $freq; 1189 } 1190} 1191 1192/** 1193 * Create an instance of the indexer. 1194 * 1195 * @return Doku_Indexer a Doku_Indexer 1196 * @author Tom N Harris <tnharris@whoopdedo.org> 1197 */ 1198function idx_get_indexer() { 1199 global $Indexer; 1200 if (!isset($Indexer)) { 1201 $Indexer = new Doku_Indexer(); 1202 } 1203 return $Indexer; 1204} 1205 1206/** 1207 * Returns words that will be ignored. 1208 * 1209 * @return array list of stop words 1210 * @author Tom N Harris <tnharris@whoopdedo.org> 1211 */ 1212function & idx_get_stopwords() { 1213 static $stopwords = null; 1214 if (is_null($stopwords)) { 1215 global $conf; 1216 $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 1217 if(@file_exists($swfile)){ 1218 $stopwords = file($swfile, FILE_IGNORE_NEW_LINES); 1219 }else{ 1220 $stopwords = array(); 1221 } 1222 } 1223 return $stopwords; 1224} 1225 1226/** 1227 * Adds/updates the search index for the given page 1228 * 1229 * Locking is handled internally. 1230 * 1231 * @param string $page name of the page to index 1232 * @param boolean $verbose print status messages 1233 * @param boolean $force force reindexing even when the index is up to date 1234 * @return boolean the function completed successfully 1235 * @author Tom N Harris <tnharris@whoopdedo.org> 1236 */ 1237function idx_addPage($page, $verbose=false, $force=false) { 1238 $idxtag = metaFN($page,'.indexed'); 1239 // check if page was deleted but is still in the index 1240 if (!page_exists($page)) { 1241 if (!@file_exists($idxtag)) { 1242 if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF); 1243 return false; 1244 } 1245 $Indexer = idx_get_indexer(); 1246 $result = $Indexer->deletePage($page); 1247 if ($result === "locked") { 1248 if ($verbose) print("Indexer: locked".DOKU_LF); 1249 return false; 1250 } 1251 @unlink($idxtag); 1252 return $result; 1253 } 1254 1255 // check if indexing needed 1256 if(!$force && @file_exists($idxtag)){ 1257 if(trim(io_readFile($idxtag)) == idx_get_version()){ 1258 $last = @filemtime($idxtag); 1259 if($last > @filemtime(wikiFN($page))){ 1260 if ($verbose) print("Indexer: index for $page up to date".DOKU_LF); 1261 return false; 1262 } 1263 } 1264 } 1265 1266 $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED); 1267 if ($indexenabled === false) { 1268 $result = false; 1269 if (@file_exists($idxtag)) { 1270 $Indexer = idx_get_indexer(); 1271 $result = $Indexer->deletePage($page); 1272 if ($result === "locked") { 1273 if ($verbose) print("Indexer: locked".DOKU_LF); 1274 return false; 1275 } 1276 @unlink($idxtag); 1277 } 1278 if ($verbose) print("Indexer: index disabled for $page".DOKU_LF); 1279 return $result; 1280 } 1281 1282 $Indexer = idx_get_indexer(); 1283 $pid = $Indexer->getPID($page); 1284 if ($pid === false) { 1285 if ($verbose) print("Indexer: getting the PID failed for $page".DOKU_LF); 1286 return false; 1287 } 1288 $body = ''; 1289 $metadata = array(); 1290 $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED); 1291 if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null) 1292 $metadata['relation_references'] = array_keys($references); 1293 else 1294 $metadata['relation_references'] = array(); 1295 $data = compact('page', 'body', 'metadata', 'pid'); 1296 $evt = new Doku_Event('INDEXER_PAGE_ADD', $data); 1297 if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page); 1298 $evt->advise_after(); 1299 unset($evt); 1300 extract($data); 1301 1302 $result = $Indexer->addPageWords($page, $body); 1303 if ($result === "locked") { 1304 if ($verbose) print("Indexer: locked".DOKU_LF); 1305 return false; 1306 } 1307 1308 if ($result) { 1309 $result = $Indexer->addMetaKeys($page, $metadata); 1310 if ($result === "locked") { 1311 if ($verbose) print("Indexer: locked".DOKU_LF); 1312 return false; 1313 } 1314 } 1315 1316 if ($result) 1317 io_saveFile(metaFN($page,'.indexed'), idx_get_version()); 1318 if ($verbose) { 1319 print("Indexer: finished".DOKU_LF); 1320 return true; 1321 } 1322 return $result; 1323} 1324 1325/** 1326 * Find tokens in the fulltext index 1327 * 1328 * Takes an array of words and will return a list of matching 1329 * pages for each one. 1330 * 1331 * Important: No ACL checking is done here! All results are 1332 * returned, regardless of permissions 1333 * 1334 * @param array $words list of words to search for 1335 * @return array list of pages found, associated with the search terms 1336 */ 1337function idx_lookup(&$words) { 1338 $Indexer = idx_get_indexer(); 1339 return $Indexer->lookup($words); 1340} 1341 1342/** 1343 * Split a string into tokens 1344 * 1345 */ 1346function idx_tokenizer($string, $wc=false) { 1347 $Indexer = idx_get_indexer(); 1348 return $Indexer->tokenizer($string, $wc); 1349} 1350 1351/* For compatibility */ 1352 1353/** 1354 * Read the list of words in an index (if it exists). 1355 * 1356 * @author Tom N Harris <tnharris@whoopdedo.org> 1357 */ 1358function idx_getIndex($idx, $suffix) { 1359 global $conf; 1360 $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 1361 if (!@file_exists($fn)) return array(); 1362 return file($fn); 1363} 1364 1365/** 1366 * Get the list of lengths indexed in the wiki. 1367 * 1368 * Read the index directory or a cache file and returns 1369 * a sorted array of lengths of the words used in the wiki. 1370 * 1371 * @author YoBoY <yoboy.leguesh@gmail.com> 1372 */ 1373function idx_listIndexLengths() { 1374 global $conf; 1375 // testing what we have to do, create a cache file or not. 1376 if ($conf['readdircache'] == 0) { 1377 $docache = false; 1378 } else { 1379 clearstatcache(); 1380 if (@file_exists($conf['indexdir'].'/lengths.idx') 1381 && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) { 1382 if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) { 1383 $idx = array(); 1384 foreach ($lengths as $length) { 1385 $idx[] = (int)$length; 1386 } 1387 return $idx; 1388 } 1389 } 1390 $docache = true; 1391 } 1392 1393 if ($conf['readdircache'] == 0 || $docache) { 1394 $dir = @opendir($conf['indexdir']); 1395 if ($dir === false) 1396 return array(); 1397 $idx = array(); 1398 while (($f = readdir($dir)) !== false) { 1399 if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') { 1400 $i = substr($f, 1, -4); 1401 if (is_numeric($i)) 1402 $idx[] = (int)$i; 1403 } 1404 } 1405 closedir($dir); 1406 sort($idx); 1407 // save this in a file 1408 if ($docache) { 1409 $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w'); 1410 @fwrite($handle, implode("\n", $idx)); 1411 @fclose($handle); 1412 } 1413 return $idx; 1414 } 1415 1416 return array(); 1417} 1418 1419/** 1420 * Get the word lengths that have been indexed. 1421 * 1422 * Reads the index directory and returns an array of lengths 1423 * that there are indices for. 1424 * 1425 * @author YoBoY <yoboy.leguesh@gmail.com> 1426 */ 1427function idx_indexLengths($filter) { 1428 global $conf; 1429 $idx = array(); 1430 if (is_array($filter)) { 1431 // testing if index files exist only 1432 $path = $conf['indexdir']."/i"; 1433 foreach ($filter as $key => $value) { 1434 if (@file_exists($path.$key.'.idx')) 1435 $idx[] = $key; 1436 } 1437 } else { 1438 $lengths = idx_listIndexLengths(); 1439 foreach ($lengths as $key => $length) { 1440 // keep all the values equal or superior 1441 if ((int)$length >= (int)$filter) 1442 $idx[] = $length; 1443 } 1444 } 1445 return $idx; 1446} 1447 1448/** 1449 * Clean a name of a key for use as a file name. 1450 * 1451 * Romanizes non-latin characters, then strips away anything that's 1452 * not a letter, number, or underscore. 1453 * 1454 * @author Tom N Harris <tnharris@whoopdedo.org> 1455 */ 1456function idx_cleanName($name) { 1457 $name = utf8_romanize(trim((string)$name)); 1458 $name = preg_replace('#[ \./\\:-]+#', '_', $name); 1459 $name = preg_replace('/[^A-Za-z0-9_]/', '', $name); 1460 return strtolower($name); 1461} 1462 1463//Setup VIM: ex: et ts=4 : 1464