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