1b4ce25e9SAndreas Gohr<?php 2b4ce25e9SAndreas Gohr/** 3fcd3bb7cSAndreas Gohr * Functions to create the fulltext search index 4b4ce25e9SAndreas Gohr * 5b4ce25e9SAndreas Gohr * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 6b4ce25e9SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 700803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 8b4ce25e9SAndreas Gohr */ 9b4ce25e9SAndreas Gohr 10fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.'); 11b4ce25e9SAndreas Gohr 127c2ef4e8STom N Harris// Version tag used to force rebuild on upgrade 137d939e4eSMichael Hamanndefine('INDEXER_VERSION', 5); 147c2ef4e8STom N Harris 1533815ce2SChris Smith// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens) 16d3fb3219SAndreas Gohrif (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2); 1733815ce2SChris Smith 1893a60ad2SAndreas Gohr// Asian characters are handled as words. The following regexp defines the 1993a60ad2SAndreas Gohr// Unicode-Ranges for Asian characters 2093a60ad2SAndreas Gohr// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block 2193a60ad2SAndreas Gohr// I'm no language expert. If you think some ranges are wrongly chosen or 2293a60ad2SAndreas Gohr// a range is missing, please contact me 23d5b23302STom N Harrisdefine('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai 24d5b23302STom N Harrisdefine('IDX_ASIAN2','['. 25d5b23302STom N Harris '\x{2E80}-\x{3040}'. // CJK -> Hangul 26d5b23302STom N Harris '\x{309D}-\x{30A0}'. 27a0c5c349STom N Harris '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'. 2893a60ad2SAndreas Gohr '\x{F900}-\x{FAFF}'. // CJK Compatibility Ideographs 2993a60ad2SAndreas Gohr '\x{FE30}-\x{FE4F}'. // CJK Compatibility Forms 30ae6c4ec0SDanny Lin "\xF0\xA0\x80\x80-\xF0\xAA\x9B\x9F". // CJK Extension B 31ae6c4ec0SDanny Lin "\xF0\xAA\x9C\x80-\xF0\xAB\x9C\xBF". // CJK Extension C 32ae6c4ec0SDanny Lin "\xF0\xAB\x9D\x80-\xF0\xAB\xA0\x9F". // CJK Extension D 33ae6c4ec0SDanny Lin "\xF0\xAF\xA0\x80-\xF0\xAF\xAB\xBF". // CJK Compatibility Supplement 3493a60ad2SAndreas Gohr ']'); 35d5b23302STom N Harrisdefine('IDX_ASIAN3','['. // Hiragana/Katakana (can be two characters) 36d5b23302STom N Harris '\x{3042}\x{3044}\x{3046}\x{3048}'. 37d5b23302STom N Harris '\x{304A}-\x{3062}\x{3064}-\x{3082}'. 38d5b23302STom N Harris '\x{3084}\x{3086}\x{3088}-\x{308D}'. 39d5b23302STom N Harris '\x{308F}-\x{3094}'. 40d5b23302STom N Harris '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'. 41d5b23302STom N Harris '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'. 42d5b23302STom N Harris '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'. 43d5b23302STom N Harris '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'. 44d5b23302STom N Harris ']['. 45d5b23302STom N Harris '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'. 46d5b23302STom N Harris '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'. 47d5b23302STom N Harris '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'. 48d5b23302STom N Harris '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'. 49d5b23302STom N Harris '\x{31F0}-\x{31FF}'. 50d5b23302STom N Harris ']?'); 51699b8a0bSAndreas Gohrdefine('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')'); 5293a60ad2SAndreas Gohr 53b4ce25e9SAndreas Gohr/** 547c2ef4e8STom N Harris * Version of the indexer taking into consideration the external tokenizer. 557c2ef4e8STom N Harris * The indexer is only compatible with data written by the same version. 567c2ef4e8STom N Harris * 578cd4c12fSAndreas Gohr * @triggers INDEXER_VERSION_GET 58d0d6fe1bSTom N Harris * Plugins that modify what gets indexed should hook this event and 59d0d6fe1bSTom N Harris * add their version info to the event data like so: 60d0d6fe1bSTom N Harris * $data[$plugin_name] = $plugin_version; 61d0d6fe1bSTom N Harris * 627c2ef4e8STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 638605afb1SMichael Hamann * @author Michael Hamann <michael@content-space.de> 647c2ef4e8STom N Harris */ 657c2ef4e8STom N Harrisfunction idx_get_version(){ 66d0d6fe1bSTom N Harris static $indexer_version = null; 67d0d6fe1bSTom N Harris if ($indexer_version == null) { 688605afb1SMichael Hamann $version = INDEXER_VERSION; 698605afb1SMichael Hamann 70d0d6fe1bSTom N Harris // DokuWiki version is included for the convenience of plugins 71d0d6fe1bSTom N Harris $data = array('dokuwiki'=>$version); 728605afb1SMichael Hamann trigger_event('INDEXER_VERSION_GET', $data, null, false); 73d0d6fe1bSTom N Harris unset($data['dokuwiki']); // this needs to be first 74d0d6fe1bSTom N Harris ksort($data); 75d0d6fe1bSTom N Harris foreach ($data as $plugin=>$vers) 76d0d6fe1bSTom N Harris $version .= '+'.$plugin.'='.$vers; 77d0d6fe1bSTom N Harris $indexer_version = $version; 78d0d6fe1bSTom N Harris } 79d0d6fe1bSTom N Harris return $indexer_version; 807c2ef4e8STom N Harris} 817c2ef4e8STom N Harris 827c2ef4e8STom N Harris/** 83d5b23302STom N Harris * Measure the length of a string. 84d5b23302STom N Harris * Differs from strlen in handling of asian characters. 85d5b23302STom N Harris * 86d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 87d5b23302STom N Harris */ 88d5b23302STom N Harrisfunction wordlen($w){ 89d5b23302STom N Harris $l = strlen($w); 90d5b23302STom N Harris // If left alone, all chinese "words" will get put into w3.idx 91d5b23302STom N Harris // So the "length" of a "word" is faked 924b9792c6STom N Harris if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) { 934b9792c6STom N Harris foreach($leadbytes[0] as $b) 944b9792c6STom N Harris $l += ord($b) - 0xE1; 954b9792c6STom N Harris } 96d5b23302STom N Harris return $l; 97d5b23302STom N Harris} 98d5b23302STom N Harris 99d5b23302STom N Harris/** 10000803e56STom N Harris * Class that encapsulates operations on the indexer database. 101579b0f7eSTNHarris * 102579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org> 103579b0f7eSTNHarris */ 10400803e56STom N Harrisclass Doku_Indexer { 105579b0f7eSTNHarris 106579b0f7eSTNHarris /** 10700803e56STom N Harris * Adds the contents of a page to the fulltext index 108dd35e9c9SAndreas Gohr * 10900803e56STom N Harris * The added text replaces previous words for the same page. 11000803e56STom N Harris * An empty value erases the page. 11100803e56STom N Harris * 11200803e56STom N Harris * @param string $page a page name 11300803e56STom N Harris * @param string $text the body of the page 11400803e56STom N Harris * @return boolean the function completed successfully 11500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 116dd35e9c9SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 117dd35e9c9SAndreas Gohr */ 11800803e56STom N Harris public function addPageWords($page, $text) { 11980fb93f6STom N Harris if (!$this->lock()) 1209b41be24STom N Harris return "locked"; 12100803e56STom N Harris 12200803e56STom N Harris // load known documents 123*03aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 1245981eb09STom N Harris if ($pid === false) { 12580fb93f6STom N Harris $this->unlock(); 12600803e56STom N Harris return false; 12700803e56STom N Harris } 12800803e56STom N Harris 12900803e56STom N Harris $pagewords = array(); 13000803e56STom N Harris // get word usage in page 13180fb93f6STom N Harris $words = $this->getPageWords($text); 13200803e56STom N Harris if ($words === false) { 13380fb93f6STom N Harris $this->unlock(); 13400803e56STom N Harris return false; 13500803e56STom N Harris } 13600803e56STom N Harris 13700803e56STom N Harris if (!empty($words)) { 13800803e56STom N Harris foreach (array_keys($words) as $wlen) { 13980fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 14000803e56STom N Harris foreach ($words[$wlen] as $wid => $freq) { 14100803e56STom N Harris $idx = ($wid<count($index)) ? $index[$wid] : ''; 14280fb93f6STom N Harris $index[$wid] = $this->updateTuple($idx, $pid, $freq); 14300803e56STom N Harris $pagewords[] = "$wlen*$wid"; 14400803e56STom N Harris } 14580fb93f6STom N Harris if (!$this->saveIndex('i', $wlen, $index)) { 14680fb93f6STom N Harris $this->unlock(); 14700803e56STom N Harris return false; 14800803e56STom N Harris } 14900803e56STom N Harris } 15000803e56STom N Harris } 15100803e56STom N Harris 15200803e56STom N Harris // Remove obsolete index entries 15380fb93f6STom N Harris $pageword_idx = $this->getIndexKey('pageword', '', $pid); 15400803e56STom N Harris if ($pageword_idx !== '') { 15500803e56STom N Harris $oldwords = explode(':',$pageword_idx); 15600803e56STom N Harris $delwords = array_diff($oldwords, $pagewords); 15700803e56STom N Harris $upwords = array(); 15800803e56STom N Harris foreach ($delwords as $word) { 15900803e56STom N Harris if ($word != '') { 16000803e56STom N Harris list($wlen,$wid) = explode('*', $word); 16100803e56STom N Harris $wid = (int)$wid; 16200803e56STom N Harris $upwords[$wlen][] = $wid; 16300803e56STom N Harris } 16400803e56STom N Harris } 16500803e56STom N Harris foreach ($upwords as $wlen => $widx) { 16680fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 16700803e56STom N Harris foreach ($widx as $wid) { 16880fb93f6STom N Harris $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 16900803e56STom N Harris } 17080fb93f6STom N Harris $this->saveIndex('i', $wlen, $index); 17100803e56STom N Harris } 17200803e56STom N Harris } 17300803e56STom N Harris // Save the reverse index 17400803e56STom N Harris $pageword_idx = join(':', $pagewords); 17580fb93f6STom N Harris if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) { 17680fb93f6STom N Harris $this->unlock(); 17700803e56STom N Harris return false; 17800803e56STom N Harris } 17900803e56STom N Harris 18080fb93f6STom N Harris $this->unlock(); 181dd35e9c9SAndreas Gohr return true; 182dd35e9c9SAndreas Gohr } 183dd35e9c9SAndreas Gohr 184dd35e9c9SAndreas Gohr /** 18500803e56STom N Harris * Split the words in a page and add them to the index. 18644ca0adfSAndreas Gohr * 187b9d8cc1eSTom N Harris * @param string $text content of the page 188b9d8cc1eSTom N Harris * @return array list of word IDs and number of times used 18944ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 19017f42b01SChris Smith * @author Christopher Smith <chris@jalakai.co.uk> 19100803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 192b4ce25e9SAndreas Gohr */ 19380fb93f6STom N Harris protected function getPageWords($text) { 19444ca0adfSAndreas Gohr 19500803e56STom N Harris $tokens = $this->tokenizer($text); 19617f42b01SChris Smith $tokens = array_count_values($tokens); // count the frequency of each token 19717f42b01SChris Smith 19817f42b01SChris Smith $words = array(); 1994e1bf408STom N Harris foreach ($tokens as $w=>$c) { 200d5b23302STom N Harris $l = wordlen($w); 201579b0f7eSTNHarris if (isset($words[$l])){ 2024e1bf408STom N Harris $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0); 20317f42b01SChris Smith }else{ 2044e1bf408STom N Harris $words[$l] = array($w => $c); 20517f42b01SChris Smith } 20617f42b01SChris Smith } 20717f42b01SChris Smith 208579b0f7eSTNHarris // arrive here with $words = array(wordlen => array(word => frequency)) 209e5e50383SMichael Hamann $word_idx_modified = false; 210b4ce25e9SAndreas Gohr $index = array(); //resulting index 211579b0f7eSTNHarris foreach (array_keys($words) as $wlen) { 21280fb93f6STom N Harris $word_idx = $this->getIndex('w', $wlen); 213579b0f7eSTNHarris foreach ($words[$wlen] as $word => $freq) { 21400803e56STom N Harris $wid = array_search($word, $word_idx); 21500803e56STom N Harris if ($wid === false) { 216d5b23302STom N Harris $wid = count($word_idx); 21700803e56STom N Harris $word_idx[] = $word; 218e5e50383SMichael Hamann $word_idx_modified = true; 219b4ce25e9SAndreas Gohr } 220579b0f7eSTNHarris if (!isset($index[$wlen])) 221579b0f7eSTNHarris $index[$wlen] = array(); 222579b0f7eSTNHarris $index[$wlen][$wid] = $freq; 22344ca0adfSAndreas Gohr } 22400803e56STom N Harris // save back the word index 22580fb93f6STom N Harris if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx)) 22644ca0adfSAndreas Gohr return false; 22744ca0adfSAndreas Gohr } 228b4ce25e9SAndreas Gohr 229b4ce25e9SAndreas Gohr return $index; 230b4ce25e9SAndreas Gohr } 231b4ce25e9SAndreas Gohr 23244ca0adfSAndreas Gohr /** 233e1e1a7e0SMichael Hamann * Add/update keys to/of the metadata index. 23444ca0adfSAndreas Gohr * 23500803e56STom N Harris * Adding new keys does not remove other keys for the page. 23600803e56STom N Harris * An empty value will erase the key. 23700803e56STom N Harris * The $key parameter can be an array to add multiple keys. $value will 23800803e56STom N Harris * not be used if $key is an array. 23944ca0adfSAndreas Gohr * 24000803e56STom N Harris * @param string $page a page name 24100803e56STom N Harris * @param mixed $key a key string or array of key=>value pairs 24200803e56STom N Harris * @param mixed $value the value or list of values 24300803e56STom N Harris * @return boolean the function completed successfully 24400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 245e1e1a7e0SMichael Hamann * @author Michael Hamann <michael@content-space.de> 24644ca0adfSAndreas Gohr */ 24700803e56STom N Harris public function addMetaKeys($page, $key, $value=null) { 24800803e56STom N Harris if (!is_array($key)) { 24900803e56STom N Harris $key = array($key => $value); 25000803e56STom N Harris } elseif (!is_null($value)) { 25100803e56STom N Harris // $key is array, but $value is not null 25200803e56STom N Harris trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING); 25300803e56STom N Harris } 25400803e56STom N Harris 25580fb93f6STom N Harris if (!$this->lock()) 256e1e1a7e0SMichael Hamann return "locked"; 257b4ce25e9SAndreas Gohr 258488dd6ceSAndreas Gohr // load known documents 259*03aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 26000803e56STom N Harris if ($pid === false) { 26180fb93f6STom N Harris $this->unlock(); 262579b0f7eSTNHarris return false; 26344ca0adfSAndreas Gohr } 26400803e56STom N Harris 265c1209673STom N Harris // Special handling for titles so the index file is simpler 266c1209673STom N Harris if (array_key_exists('title', $key)) { 267c1209673STom N Harris $value = $key['title']; 268c1209673STom N Harris if (is_array($value)) 269c1209673STom N Harris $value = $value[0]; 27080fb93f6STom N Harris $this->saveIndexKey('title', '', $pid, $value); 271c1209673STom N Harris unset($key['title']); 272c1209673STom N Harris } 273c1209673STom N Harris 27400803e56STom N Harris foreach ($key as $name => $values) { 27500803e56STom N Harris $metaname = idx_cleanName($name); 27680fb93f6STom N Harris $this->addIndexKey('metadata', '', $metaname); 277b9d8cc1eSTom N Harris $metaidx = $this->getIndex($metaname.'_i', ''); 278b9d8cc1eSTom N Harris $metawords = $this->getIndex($metaname.'_w', ''); 27900803e56STom N Harris $addwords = false; 280e1e1a7e0SMichael Hamann 281e1e1a7e0SMichael Hamann if (!is_array($values)) $values = array($values); 282e1e1a7e0SMichael Hamann 283b9d8cc1eSTom N Harris $val_idx = $this->getIndexKey($metaname.'_p', '', $pid); 284e1e1a7e0SMichael Hamann if ($val_idx != '') { 285e1e1a7e0SMichael Hamann $val_idx = explode(':', $val_idx); 286e1e1a7e0SMichael Hamann // -1 means remove, 0 keep, 1 add 287e1e1a7e0SMichael Hamann $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1)); 288e1e1a7e0SMichael Hamann } else { 289e1e1a7e0SMichael Hamann $val_idx = array(); 290e1e1a7e0SMichael Hamann } 291e1e1a7e0SMichael Hamann 29200803e56STom N Harris foreach ($values as $val) { 29300803e56STom N Harris $val = (string)$val; 29400803e56STom N Harris if ($val !== "") { 29500803e56STom N Harris $id = array_search($val, $metawords); 29600803e56STom N Harris if ($id === false) { 29700803e56STom N Harris $id = count($metawords); 29800803e56STom N Harris $metawords[$id] = $val; 29900803e56STom N Harris $addwords = true; 300d5b23302STom N Harris } 301e1e1a7e0SMichael Hamann // test if value is already in the index 302e1e1a7e0SMichael Hamann if (isset($val_idx[$id]) && $val_idx[$id] <= 0) 303e1e1a7e0SMichael Hamann $val_idx[$id] = 0; 304e1e1a7e0SMichael Hamann else // else add it 305e1e1a7e0SMichael Hamann $val_idx[$id] = 1; 30644ca0adfSAndreas Gohr } 307579b0f7eSTNHarris } 308e1e1a7e0SMichael Hamann 30900803e56STom N Harris if ($addwords) 31080fb93f6STom N Harris $this->saveIndex($metaname.'_w', '', $metawords); 311e1e1a7e0SMichael Hamann $vals_changed = false; 312e1e1a7e0SMichael Hamann foreach ($val_idx as $id => $action) { 313e1e1a7e0SMichael Hamann if ($action == -1) { 31480fb93f6STom N Harris $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0); 315e1e1a7e0SMichael Hamann $vals_changed = true; 316e1e1a7e0SMichael Hamann unset($val_idx[$id]); 317e1e1a7e0SMichael Hamann } elseif ($action == 1) { 31880fb93f6STom N Harris $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1); 319e1e1a7e0SMichael Hamann $vals_changed = true; 320e1e1a7e0SMichael Hamann } 321e1e1a7e0SMichael Hamann } 322e1e1a7e0SMichael Hamann 323e1e1a7e0SMichael Hamann if ($vals_changed) { 32480fb93f6STom N Harris $this->saveIndex($metaname.'_i', '', $metaidx); 325e1e1a7e0SMichael Hamann $val_idx = implode(':', array_keys($val_idx)); 32680fb93f6STom N Harris $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx); 327b6344591STom N Harris } 328e1e1a7e0SMichael Hamann 32900803e56STom N Harris unset($metaidx); 33000803e56STom N Harris unset($metawords); 331a0c5c349STom N Harris } 332e1e1a7e0SMichael Hamann 33380fb93f6STom N Harris $this->unlock(); 334579b0f7eSTNHarris return true; 33544ca0adfSAndreas Gohr } 33644ca0adfSAndreas Gohr 33744ca0adfSAndreas Gohr /** 33800803e56STom N Harris * Remove a page from the index 33944ca0adfSAndreas Gohr * 34000803e56STom N Harris * Erases entries in all known indexes. 34144ca0adfSAndreas Gohr * 34200803e56STom N Harris * @param string $page a page name 34300803e56STom N Harris * @return boolean the function completed successfully 34400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 34544ca0adfSAndreas Gohr */ 34600803e56STom N Harris public function deletePage($page) { 34780fb93f6STom N Harris if (!$this->lock()) 348bbc85ee4STom N Harris return "locked"; 349bbc85ee4STom N Harris 350bbc85ee4STom N Harris // load known documents 351*03aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 3525981eb09STom N Harris if ($pid === false) { 35380fb93f6STom N Harris $this->unlock(); 354bbc85ee4STom N Harris return false; 355bbc85ee4STom N Harris } 356bbc85ee4STom N Harris 357bbc85ee4STom N Harris // Remove obsolete index entries 35880fb93f6STom N Harris $pageword_idx = $this->getIndexKey('pageword', '', $pid); 359bbc85ee4STom N Harris if ($pageword_idx !== '') { 360bbc85ee4STom N Harris $delwords = explode(':',$pageword_idx); 361bbc85ee4STom N Harris $upwords = array(); 362bbc85ee4STom N Harris foreach ($delwords as $word) { 363bbc85ee4STom N Harris if ($word != '') { 364bbc85ee4STom N Harris list($wlen,$wid) = explode('*', $word); 365bbc85ee4STom N Harris $wid = (int)$wid; 366bbc85ee4STom N Harris $upwords[$wlen][] = $wid; 367bbc85ee4STom N Harris } 368bbc85ee4STom N Harris } 369bbc85ee4STom N Harris foreach ($upwords as $wlen => $widx) { 37080fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 371bbc85ee4STom N Harris foreach ($widx as $wid) { 37280fb93f6STom N Harris $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 373bbc85ee4STom N Harris } 37480fb93f6STom N Harris $this->saveIndex('i', $wlen, $index); 375bbc85ee4STom N Harris } 376bbc85ee4STom N Harris } 377bbc85ee4STom N Harris // Save the reverse index 37880fb93f6STom N Harris if (!$this->saveIndexKey('pageword', '', $pid, "")) { 37980fb93f6STom N Harris $this->unlock(); 380bbc85ee4STom N Harris return false; 381bbc85ee4STom N Harris } 382bbc85ee4STom N Harris 38380fb93f6STom N Harris $this->saveIndexKey('title', '', $pid, ""); 38480fb93f6STom N Harris $keyidx = $this->getIndex('metadata', ''); 3850604da34STom N Harris foreach ($keyidx as $metaname) { 38680fb93f6STom N Harris $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid)); 38780fb93f6STom N Harris $meta_idx = $this->getIndex($metaname.'_i', ''); 3880604da34STom N Harris foreach ($val_idx as $id) { 389c55c59e3SMichael Hamann if ($id === '') continue; 39080fb93f6STom N Harris $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0); 3910604da34STom N Harris } 39280fb93f6STom N Harris $this->saveIndex($metaname.'_i', '', $meta_idx); 39380fb93f6STom N Harris $this->saveIndexKey($metaname.'_p', '', $pid, ''); 3940604da34STom N Harris } 395bbc85ee4STom N Harris 39680fb93f6STom N Harris $this->unlock(); 397bbc85ee4STom N Harris return true; 398d5b23302STom N Harris } 39944ca0adfSAndreas Gohr 400d5b23302STom N Harris /** 40100803e56STom N Harris * Split the text into words for fulltext search 402d5b23302STom N Harris * 40300803e56STom N Harris * TODO: does this also need &$stopwords ? 404d5b23302STom N Harris * 4058cd4c12fSAndreas Gohr * @triggers INDEXER_TEXT_PREPARE 4068cd4c12fSAndreas Gohr * This event allows plugins to modify the text before it gets tokenized. 4078cd4c12fSAndreas Gohr * Plugins intercepting this event should also intercept INDEX_VERSION_GET 4088cd4c12fSAndreas Gohr * 40900803e56STom N Harris * @param string $text plain text 41000803e56STom N Harris * @param boolean $wc are wildcards allowed? 41100803e56STom N Harris * @return array list of words in the text 412d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 413d5b23302STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 414d5b23302STom N Harris */ 41500803e56STom N Harris public function tokenizer($text, $wc=false) { 41600803e56STom N Harris $wc = ($wc) ? '' : '\*'; 41700803e56STom N Harris $stopwords =& idx_get_stopwords(); 41800803e56STom N Harris 4198cd4c12fSAndreas Gohr // prepare the text to be tokenized 4208cd4c12fSAndreas Gohr $evt = new Doku_Event('INDEXER_TEXT_PREPARE', $text); 4218cd4c12fSAndreas Gohr if ($evt->advise_before(true)) { 42200803e56STom N Harris if (preg_match('/[^0-9A-Za-z ]/u', $text)) { 42300803e56STom N Harris // handle asian chars as single words (may fail on older PHP version) 42400803e56STom N Harris $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text); 42500803e56STom N Harris if (!is_null($asia)) $text = $asia; // recover from regexp falure 42622952965SYoBoY } 42722952965SYoBoY } 4288cd4c12fSAndreas Gohr $evt->advise_after(); 4298cd4c12fSAndreas Gohr unset($evt); 4308cd4c12fSAndreas Gohr 431f77fc90dSMichael Hamann $text = strtr($text, 4324f0030ddSAndreas Gohr array( 4334f0030ddSAndreas Gohr "\r" => ' ', 4344f0030ddSAndreas Gohr "\n" => ' ', 4354f0030ddSAndreas Gohr "\t" => ' ', 4364f0030ddSAndreas Gohr "\xC2\xAD" => '', //soft-hyphen 4374f0030ddSAndreas Gohr ) 4384f0030ddSAndreas Gohr ); 43900803e56STom N Harris if (preg_match('/[^0-9A-Za-z ]/u', $text)) 44000803e56STom N Harris $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc); 44122952965SYoBoY 44200803e56STom N Harris $wordlist = explode(' ', $text); 4435f27cb0eSMichael Hamann foreach ($wordlist as $i => $word) { 4445f27cb0eSMichael Hamann $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ? 44500803e56STom N Harris utf8_strtolower($word) : strtolower($word); 4465f27cb0eSMichael Hamann } 4475f27cb0eSMichael Hamann 4485f27cb0eSMichael Hamann foreach ($wordlist as $i => $word) { 449675bf41fSTom N Harris if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) 450675bf41fSTom N Harris || array_search($word, $stopwords) !== false) 451675bf41fSTom N Harris unset($wordlist[$i]); 45222952965SYoBoY } 453675bf41fSTom N Harris return array_values($wordlist); 45422952965SYoBoY } 45522952965SYoBoY 45622952965SYoBoY /** 457*03aafe1cSMichael Hamann * Get the numeric PID of a page 458*03aafe1cSMichael Hamann * 459*03aafe1cSMichael Hamann * @param string $page The page to get the PID for 460*03aafe1cSMichael Hamann * @return bool|int The page id on success, false on error 461*03aafe1cSMichael Hamann */ 462*03aafe1cSMichael Hamann public function getPID($page) { 463*03aafe1cSMichael Hamann if (!$this->lock()) 464*03aafe1cSMichael Hamann return false; 465*03aafe1cSMichael Hamann 466*03aafe1cSMichael Hamann // load known documents 467*03aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 468*03aafe1cSMichael Hamann if ($pid === false) { 469*03aafe1cSMichael Hamann $this->unlock(); 470*03aafe1cSMichael Hamann return false; 471*03aafe1cSMichael Hamann } 472*03aafe1cSMichael Hamann 473*03aafe1cSMichael Hamann $this->unlock(); 474*03aafe1cSMichael Hamann return $pid; 475*03aafe1cSMichael Hamann } 476*03aafe1cSMichael Hamann 477*03aafe1cSMichael Hamann /** 478*03aafe1cSMichael Hamann * Get the numeric PID of a page without locking the index. 479*03aafe1cSMichael Hamann * Only use this function when the index is already locked. 480*03aafe1cSMichael Hamann * 481*03aafe1cSMichael Hamann * @param string $page The page to get the PID for 482*03aafe1cSMichael Hamann * @return bool|int The page id on success, false on error 483*03aafe1cSMichael Hamann */ 484*03aafe1cSMichael Hamann protected function getPIDNoLock($page) { 485*03aafe1cSMichael Hamann return $this->addIndexKey('page', '', $page); 486*03aafe1cSMichael Hamann } 487*03aafe1cSMichael Hamann 488*03aafe1cSMichael Hamann /** 489*03aafe1cSMichael Hamann * Get the page id of a numeric PID 490*03aafe1cSMichael Hamann * 491*03aafe1cSMichael Hamann * @param int $pid The PID to get the page id for 492*03aafe1cSMichael Hamann * @return string The page id 493*03aafe1cSMichael Hamann */ 494*03aafe1cSMichael Hamann public function getPageFromPID($pid) { 495*03aafe1cSMichael Hamann return $this->getIndexKey('page', '', $pid); 496*03aafe1cSMichael Hamann } 497*03aafe1cSMichael Hamann 498*03aafe1cSMichael Hamann /** 49900803e56STom N Harris * Find pages in the fulltext index containing the words, 500579b0f7eSTNHarris * 50100803e56STom N Harris * The search words must be pre-tokenized, meaning only letters and 50200803e56STom N Harris * numbers with an optional wildcard 503579b0f7eSTNHarris * 50400803e56STom N Harris * The returned array will have the original tokens as key. The values 50500803e56STom N Harris * in the returned list is an array with the page names as keys and the 506b00bd361STom N Harris * number of times that token appears on the page as value. 50700803e56STom N Harris * 508e3ab6fc5SMichael Hamann * @param array $tokens list of words to search for 50900803e56STom N Harris * @return array list of page names with usage counts 51000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 51100803e56STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 512579b0f7eSTNHarris */ 5139b41be24STom N Harris public function lookup(&$tokens) { 51400803e56STom N Harris $result = array(); 51580fb93f6STom N Harris $wids = $this->getIndexWords($tokens, $result); 51600803e56STom N Harris if (empty($wids)) return array(); 51700803e56STom N Harris // load known words and documents 51880fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 51900803e56STom N Harris $docs = array(); 52000803e56STom N Harris foreach (array_keys($wids) as $wlen) { 52100803e56STom N Harris $wids[$wlen] = array_unique($wids[$wlen]); 52280fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 52300803e56STom N Harris foreach($wids[$wlen] as $ixid) { 52400803e56STom N Harris if ($ixid < count($index)) 52580fb93f6STom N Harris $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]); 526d5b23302STom N Harris } 527d5b23302STom N Harris } 52800803e56STom N Harris // merge found pages into final result array 52900803e56STom N Harris $final = array(); 53000803e56STom N Harris foreach ($result as $word => $res) { 53100803e56STom N Harris $final[$word] = array(); 53200803e56STom N Harris foreach ($res as $wid) { 533952ab260SMichael Hamann // handle the case when ($ixid < count($index)) has been false 534952ab260SMichael Hamann // and thus $docs[$wid] hasn't been set. 535952ab260SMichael Hamann if (!isset($docs[$wid])) continue; 53600803e56STom N Harris $hits = &$docs[$wid]; 53700803e56STom N Harris foreach ($hits as $hitkey => $hitcnt) { 53800803e56STom N Harris // make sure the document still exists 53900803e56STom N Harris if (!page_exists($hitkey, '', false)) continue; 54000803e56STom N Harris if (!isset($final[$word][$hitkey])) 54100803e56STom N Harris $final[$word][$hitkey] = $hitcnt; 54200803e56STom N Harris else 54300803e56STom N Harris $final[$word][$hitkey] += $hitcnt; 544d5b23302STom N Harris } 545579b0f7eSTNHarris } 546579b0f7eSTNHarris } 54700803e56STom N Harris return $final; 548579b0f7eSTNHarris } 549579b0f7eSTNHarris 550579b0f7eSTNHarris /** 55100803e56STom N Harris * Find pages containing a metadata key. 552d5b23302STom N Harris * 55300803e56STom N Harris * The metadata values are compared as case-sensitive strings. Pass a 55400803e56STom N Harris * callback function that returns true or false to use a different 555b00bd361STom N Harris * comparison function. The function will be called with the $value being 556b00bd361STom N Harris * searched for as the first argument, and the word in the index as the 5571538718dSTom N Harris * second argument. The function preg_match can be used directly if the 5581538718dSTom N Harris * values are regexes. 559d5b23302STom N Harris * 56000803e56STom N Harris * @param string $key name of the metadata key to look for 5611538718dSTom N Harris * @param string $value search term to look for, must be a string or array of strings 56200803e56STom N Harris * @param callback $func comparison function 563b00bd361STom N Harris * @return array lists with page names, keys are query values if $value is array 56400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 565cd763a5bSMichael Hamann * @author Michael Hamann <michael@content-space.de> 56600803e56STom N Harris */ 567b00bd361STom N Harris public function lookupKey($key, &$value, $func=null) { 568f078bb00STom N Harris if (!is_array($value)) 569f078bb00STom N Harris $value_array = array($value); 570f078bb00STom N Harris else 571f078bb00STom N Harris $value_array =& $value; 572cd763a5bSMichael Hamann 573c1209673STom N Harris // the matching ids for the provided value(s) 574c1209673STom N Harris $value_ids = array(); 575c1209673STom N Harris 576c1209673STom N Harris $metaname = idx_cleanName($key); 577c1209673STom N Harris 578c1209673STom N Harris // get all words in order to search the matching ids 579c1209673STom N Harris if ($key == 'title') { 58080fb93f6STom N Harris $words = $this->getIndex('title', ''); 581c1209673STom N Harris } else { 582b9d8cc1eSTom N Harris $words = $this->getIndex($metaname.'_w', ''); 583c1209673STom N Harris } 584c1209673STom N Harris 585f078bb00STom N Harris if (!is_null($func)) { 5861538718dSTom N Harris foreach ($value_array as $val) { 587f078bb00STom N Harris foreach ($words as $i => $word) { 5881538718dSTom N Harris if (call_user_func_array($func, array($val, $word))) 589c1209673STom N Harris $value_ids[$i][] = $val; 590f078bb00STom N Harris } 591f078bb00STom N Harris } 592f078bb00STom N Harris } else { 593f078bb00STom N Harris foreach ($value_array as $val) { 594f078bb00STom N Harris $xval = $val; 595b6d540bdSTom N Harris $caret = '^'; 596b6d540bdSTom N Harris $dollar = '$'; 597f078bb00STom N Harris // check for wildcards 598f078bb00STom N Harris if (substr($xval, 0, 1) == '*') { 599f078bb00STom N Harris $xval = substr($xval, 1); 600b6d540bdSTom N Harris $caret = ''; 601f078bb00STom N Harris } 602f078bb00STom N Harris if (substr($xval, -1, 1) == '*') { 603f078bb00STom N Harris $xval = substr($xval, 0, -1); 604b6d540bdSTom N Harris $dollar = ''; 605f078bb00STom N Harris } 606b6d540bdSTom N Harris if (!$caret || !$dollar) { 607f078bb00STom N Harris $re = $caret.preg_quote($xval, '/').$dollar; 608f078bb00STom N Harris foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i) 609c1209673STom N Harris $value_ids[$i][] = $val; 610cd763a5bSMichael Hamann } else { 611f078bb00STom N Harris if (($i = array_search($val, $words)) !== false) 612c1209673STom N Harris $value_ids[$i][] = $val; 613cd763a5bSMichael Hamann } 614cd763a5bSMichael Hamann } 615cd763a5bSMichael Hamann } 616cd763a5bSMichael Hamann 617cd763a5bSMichael Hamann unset($words); // free the used memory 618cd763a5bSMichael Hamann 6197233c152SMichael Hamann // initialize the result so it won't be null 620c1209673STom N Harris $result = array(); 6217233c152SMichael Hamann foreach ($value_array as $val) { 6227233c152SMichael Hamann $result[$val] = array(); 6237233c152SMichael Hamann } 6247233c152SMichael Hamann 62580fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 626cd763a5bSMichael Hamann 627c1209673STom N Harris // Special handling for titles 628c1209673STom N Harris if ($key == 'title') { 629c1209673STom N Harris foreach ($value_ids as $pid => $val_list) { 630c1209673STom N Harris $page = $page_idx[$pid]; 631c1209673STom N Harris foreach ($val_list as $val) { 632c1209673STom N Harris $result[$val][] = $page; 633c1209673STom N Harris } 634c1209673STom N Harris } 635c1209673STom N Harris } else { 636c1209673STom N Harris // load all lines and pages so the used lines can be taken and matched with the pages 637b9d8cc1eSTom N Harris $lines = $this->getIndex($metaname.'_i', ''); 638c1209673STom N Harris 639c1209673STom N Harris foreach ($value_ids as $value_id => $val_list) { 640cd763a5bSMichael Hamann // parse the tuples of the form page_id*1:page2_id*1 and so on, return value 641cd763a5bSMichael Hamann // is an array with page_id => 1, page2_id => 1 etc. so take the keys only 64280fb93f6STom N Harris $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id])); 643c1209673STom N Harris foreach ($val_list as $val) { 644c1209673STom N Harris $result[$val] = array_merge($result[$val], $pages); 645c1209673STom N Harris } 646c1209673STom N Harris } 647cd763a5bSMichael Hamann } 648f078bb00STom N Harris if (!is_array($value)) $result = $result[$value]; 649cd763a5bSMichael Hamann return $result; 65000803e56STom N Harris } 65100803e56STom N Harris 65200803e56STom N Harris /** 65300803e56STom N Harris * Find the index ID of each search term. 65400803e56STom N Harris * 65500803e56STom N Harris * The query terms should only contain valid characters, with a '*' at 65600803e56STom N Harris * either the beginning or end of the word (or both). 65700803e56STom N Harris * The $result parameter can be used to merge the index locations with 65800803e56STom N Harris * the appropriate query term. 65900803e56STom N Harris * 660e3ab6fc5SMichael Hamann * @param array $words The query terms. 661e3ab6fc5SMichael Hamann * @param array $result Set to word => array("length*id" ...) 662d5b23302STom N Harris * @return array Set to length => array(id ...) 663d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 664d5b23302STom N Harris */ 66580fb93f6STom N Harris protected function getIndexWords(&$words, &$result) { 666d5b23302STom N Harris $tokens = array(); 667d5b23302STom N Harris $tokenlength = array(); 668d5b23302STom N Harris $tokenwild = array(); 669d5b23302STom N Harris foreach ($words as $word) { 670d5b23302STom N Harris $result[$word] = array(); 671b6d540bdSTom N Harris $caret = '^'; 672b6d540bdSTom N Harris $dollar = '$'; 673d5b23302STom N Harris $xword = $word; 674d5b23302STom N Harris $wlen = wordlen($word); 675d5b23302STom N Harris 676d5b23302STom N Harris // check for wildcards 677d5b23302STom N Harris if (substr($xword, 0, 1) == '*') { 678d5b23302STom N Harris $xword = substr($xword, 1); 679b6d540bdSTom N Harris $caret = ''; 680d5b23302STom N Harris $wlen -= 1; 681d5b23302STom N Harris } 682d5b23302STom N Harris if (substr($xword, -1, 1) == '*') { 683d5b23302STom N Harris $xword = substr($xword, 0, -1); 684b6d540bdSTom N Harris $dollar = ''; 685d5b23302STom N Harris $wlen -= 1; 686d5b23302STom N Harris } 687b6d540bdSTom N Harris if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword)) 68800803e56STom N Harris continue; 68900803e56STom N Harris if (!isset($tokens[$xword])) 690d5b23302STom N Harris $tokenlength[$wlen][] = $xword; 691b6d540bdSTom N Harris if (!$caret || !$dollar) { 692f078bb00STom N Harris $re = $caret.preg_quote($xword, '/').$dollar; 69300803e56STom N Harris $tokens[$xword][] = array($word, '/'.$re.'/'); 69400803e56STom N Harris if (!isset($tokenwild[$xword])) 69500803e56STom N Harris $tokenwild[$xword] = $wlen; 69600803e56STom N Harris } else { 697d5b23302STom N Harris $tokens[$xword][] = array($word, null); 698d5b23302STom N Harris } 69900803e56STom N Harris } 700d5b23302STom N Harris asort($tokenwild); 70100803e56STom N Harris // $tokens = array( base word => array( [ query term , regexp ] ... ) ... ) 702d5b23302STom N Harris // $tokenlength = array( base word length => base word ... ) 703d5b23302STom N Harris // $tokenwild = array( base word => base word length ... ) 704d5b23302STom N Harris $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength)); 70580fb93f6STom N Harris $indexes_known = $this->indexLengths($length_filter); 706d5b23302STom N Harris if (!empty($tokenwild)) sort($indexes_known); 707d5b23302STom N Harris // get word IDs 708d5b23302STom N Harris $wids = array(); 709d5b23302STom N Harris foreach ($indexes_known as $ixlen) { 71080fb93f6STom N Harris $word_idx = $this->getIndex('w', $ixlen); 711d5b23302STom N Harris // handle exact search 712d5b23302STom N Harris if (isset($tokenlength[$ixlen])) { 713d5b23302STom N Harris foreach ($tokenlength[$ixlen] as $xword) { 71400803e56STom N Harris $wid = array_search($xword, $word_idx); 71500803e56STom N Harris if ($wid !== false) { 716d5b23302STom N Harris $wids[$ixlen][] = $wid; 717d5b23302STom N Harris foreach ($tokens[$xword] as $w) 718d5b23302STom N Harris $result[$w[0]][] = "$ixlen*$wid"; 719d5b23302STom N Harris } 720d5b23302STom N Harris } 721d5b23302STom N Harris } 722d5b23302STom N Harris // handle wildcard search 723d5b23302STom N Harris foreach ($tokenwild as $xword => $wlen) { 724d5b23302STom N Harris if ($wlen >= $ixlen) break; 725d5b23302STom N Harris foreach ($tokens[$xword] as $w) { 726d5b23302STom N Harris if (is_null($w[1])) continue; 727d5b23302STom N Harris foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) { 728d5b23302STom N Harris $wids[$ixlen][] = $wid; 729d5b23302STom N Harris $result[$w[0]][] = "$ixlen*$wid"; 730d5b23302STom N Harris } 731d5b23302STom N Harris } 732d5b23302STom N Harris } 733d5b23302STom N Harris } 734d5b23302STom N Harris return $wids; 735d5b23302STom N Harris } 736d5b23302STom N Harris 737d5b23302STom N Harris /** 73800803e56STom N Harris * Return a list of all pages 739c1209673STom N Harris * Warning: pages may not exist! 740488dd6ceSAndreas Gohr * 74100803e56STom N Harris * @param string $key list only pages containing the metadata key (optional) 74200803e56STom N Harris * @return array list of page names 74300803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 74400803e56STom N Harris */ 74500803e56STom N Harris public function getPages($key=null) { 74680fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 74700803e56STom N Harris if (is_null($key)) return $page_idx; 748c1209673STom N Harris 749c1209673STom N Harris $metaname = idx_cleanName($key); 750c1209673STom N Harris 751c1209673STom N Harris // Special handling for titles 752c1209673STom N Harris if ($key == 'title') { 75380fb93f6STom N Harris $title_idx = $this->getIndex('title', ''); 754c1209673STom N Harris array_splice($page_idx, count($title_idx)); 755c1209673STom N Harris foreach ($title_idx as $i => $title) 756c1209673STom N Harris if ($title === "") unset($page_idx[$i]); 757675bf41fSTom N Harris return array_values($page_idx); 758c1209673STom N Harris } 759c1209673STom N Harris 760c1209673STom N Harris $pages = array(); 761b9d8cc1eSTom N Harris $lines = $this->getIndex($metaname.'_i', ''); 762c1209673STom N Harris foreach ($lines as $line) { 76380fb93f6STom N Harris $pages = array_merge($pages, $this->parseTuples($page_idx, $line)); 764c1209673STom N Harris } 765c1209673STom N Harris return array_keys($pages); 76600803e56STom N Harris } 76700803e56STom N Harris 76800803e56STom N Harris /** 76900803e56STom N Harris * Return a list of words sorted by number of times used 77000803e56STom N Harris * 77100803e56STom N Harris * @param int $min bottom frequency threshold 77200803e56STom N Harris * @param int $max upper frequency limit. No limit if $max<$min 773e3ab6fc5SMichael Hamann * @param int $minlen minimum length of words to count 77400803e56STom N Harris * @param string $key metadata key to list. Uses the fulltext index if not given 77500803e56STom N Harris * @return array list of words as the keys and frequency as values 77600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 77700803e56STom N Harris */ 778b8c040dbSTom N Harris public function histogram($min=1, $max=0, $minlen=3, $key=null) { 779175193d2STom N Harris if ($min < 1) 780175193d2STom N Harris $min = 1; 781175193d2STom N Harris if ($max < $min) 782175193d2STom N Harris $max = 0; 783175193d2STom N Harris 784175193d2STom N Harris $result = array(); 785175193d2STom N Harris 786175193d2STom N Harris if ($key == 'title') { 78780fb93f6STom N Harris $index = $this->getIndex('title', ''); 788175193d2STom N Harris $index = array_count_values($index); 789175193d2STom N Harris foreach ($index as $val => $cnt) { 790b8c040dbSTom N Harris if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen) 791175193d2STom N Harris $result[$val] = $cnt; 792175193d2STom N Harris } 793175193d2STom N Harris } 794175193d2STom N Harris elseif (!is_null($key)) { 795175193d2STom N Harris $metaname = idx_cleanName($key); 79680fb93f6STom N Harris $index = $this->getIndex($metaname.'_i', ''); 797175193d2STom N Harris $val_idx = array(); 798175193d2STom N Harris foreach ($index as $wid => $line) { 79980fb93f6STom N Harris $freq = $this->countTuples($line); 8009a9b579aSMichael Hamann if ($freq >= $min && (!$max || $freq <= $max)) 801175193d2STom N Harris $val_idx[$wid] = $freq; 802175193d2STom N Harris } 803175193d2STom N Harris if (!empty($val_idx)) { 80480fb93f6STom N Harris $words = $this->getIndex($metaname.'_w', ''); 8059a9b579aSMichael Hamann foreach ($val_idx as $wid => $freq) { 8069a9b579aSMichael Hamann if (strlen($words[$wid]) >= $minlen) 807175193d2STom N Harris $result[$words[$wid]] = $freq; 808175193d2STom N Harris } 809175193d2STom N Harris } 8109a9b579aSMichael Hamann } 811175193d2STom N Harris else { 812175193d2STom N Harris $lengths = idx_listIndexLengths(); 813175193d2STom N Harris foreach ($lengths as $length) { 814b8c040dbSTom N Harris if ($length < $minlen) continue; 81580fb93f6STom N Harris $index = $this->getIndex('i', $length); 816175193d2STom N Harris $words = null; 817175193d2STom N Harris foreach ($index as $wid => $line) { 81880fb93f6STom N Harris $freq = $this->countTuples($line); 819175193d2STom N Harris if ($freq >= $min && (!$max || $freq <= $max)) { 820175193d2STom N Harris if ($words === null) 82180fb93f6STom N Harris $words = $this->getIndex('w', $length); 822175193d2STom N Harris $result[$words[$wid]] = $freq; 823175193d2STom N Harris } 824175193d2STom N Harris } 825175193d2STom N Harris } 826175193d2STom N Harris } 827175193d2STom N Harris 828175193d2STom N Harris arsort($result); 829175193d2STom N Harris return $result; 83000803e56STom N Harris } 83100803e56STom N Harris 83200803e56STom N Harris /** 83300803e56STom N Harris * Lock the indexer. 83400803e56STom N Harris * 83500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 83600803e56STom N Harris */ 83780fb93f6STom N Harris protected function lock() { 83800803e56STom N Harris global $conf; 83900803e56STom N Harris $status = true; 840f77fc90dSMichael Hamann $run = 0; 84100803e56STom N Harris $lock = $conf['lockdir'].'/_indexer.lock'; 84200803e56STom N Harris while (!@mkdir($lock, $conf['dmode'])) { 84300803e56STom N Harris usleep(50); 844f77fc90dSMichael Hamann if(is_dir($lock) && time()-@filemtime($lock) > 60*5){ 845f77fc90dSMichael Hamann // looks like a stale lock - remove it 846f77fc90dSMichael Hamann if (!@rmdir($lock)) { 847f77fc90dSMichael Hamann $status = "removing the stale lock failed"; 848f77fc90dSMichael Hamann return false; 84900803e56STom N Harris } else { 850f77fc90dSMichael Hamann $status = "stale lock removed"; 851f77fc90dSMichael Hamann } 852f77fc90dSMichael Hamann }elseif($run++ == 1000){ 853f77fc90dSMichael Hamann // we waited 5 seconds for that lock 85400803e56STom N Harris return false; 85500803e56STom N Harris } 85600803e56STom N Harris } 85700803e56STom N Harris if ($conf['dperm']) 85800803e56STom N Harris chmod($lock, $conf['dperm']); 85900803e56STom N Harris return $status; 86000803e56STom N Harris } 86100803e56STom N Harris 86200803e56STom N Harris /** 86300803e56STom N Harris * Release the indexer lock. 86400803e56STom N Harris * 86500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 86600803e56STom N Harris */ 86780fb93f6STom N Harris protected function unlock() { 86800803e56STom N Harris global $conf; 86900803e56STom N Harris @rmdir($conf['lockdir'].'/_indexer.lock'); 87000803e56STom N Harris return true; 87100803e56STom N Harris } 87200803e56STom N Harris 87300803e56STom N Harris /** 87400803e56STom N Harris * Retrieve the entire index. 87500803e56STom N Harris * 876b9d8cc1eSTom N Harris * The $suffix argument is for an index that is split into 877b9d8cc1eSTom N Harris * multiple parts. Different index files should use different 878b9d8cc1eSTom N Harris * base names. 879b9d8cc1eSTom N Harris * 880b9d8cc1eSTom N Harris * @param string $idx name of the index 881b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 882b9d8cc1eSTom N Harris * @return array list of lines without CR or LF 88300803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 88400803e56STom N Harris */ 88580fb93f6STom N Harris protected function getIndex($idx, $suffix) { 88600803e56STom N Harris global $conf; 88700803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 888d64516f5SMichael Hamann if (!@file_exists($fn)) return array(); 889d64516f5SMichael Hamann return file($fn, FILE_IGNORE_NEW_LINES); 89000803e56STom N Harris } 89100803e56STom N Harris 89200803e56STom N Harris /** 89300803e56STom N Harris * Replace the contents of the index with an array. 89400803e56STom N Harris * 895b9d8cc1eSTom N Harris * @param string $idx name of the index 896b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 897e3ab6fc5SMichael Hamann * @param array $lines list of lines without LF 898e3ab6fc5SMichael Hamann * @return bool If saving succeeded 89900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 90000803e56STom N Harris */ 90180fb93f6STom N Harris protected function saveIndex($idx, $suffix, &$lines) { 90200803e56STom N Harris global $conf; 90300803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix; 90400803e56STom N Harris $fh = @fopen($fn.'.tmp', 'w'); 90500803e56STom N Harris if (!$fh) return false; 90600803e56STom N Harris fwrite($fh, join("\n", $lines)); 9072e1018bcSMichael Hamann if (!empty($lines)) 9082e1018bcSMichael Hamann fwrite($fh, "\n"); 90900803e56STom N Harris fclose($fh); 91000803e56STom N Harris if (isset($conf['fperm'])) 91100803e56STom N Harris chmod($fn.'.tmp', $conf['fperm']); 91200803e56STom N Harris io_rename($fn.'.tmp', $fn.'.idx'); 91300803e56STom N Harris if ($suffix !== '') 91480fb93f6STom N Harris $this->cacheIndexDir($idx, $suffix, empty($lines)); 91500803e56STom N Harris return true; 91600803e56STom N Harris } 91700803e56STom N Harris 91800803e56STom N Harris /** 91900803e56STom N Harris * Retrieve a line from the index. 92000803e56STom N Harris * 921b9d8cc1eSTom N Harris * @param string $idx name of the index 922b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 923b9d8cc1eSTom N Harris * @param int $id the line number 924b9d8cc1eSTom N Harris * @return string a line with trailing whitespace removed 92500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 92600803e56STom N Harris */ 92780fb93f6STom N Harris protected function getIndexKey($idx, $suffix, $id) { 92800803e56STom N Harris global $conf; 92900803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 93000803e56STom N Harris if (!@file_exists($fn)) return ''; 93100803e56STom N Harris $fh = @fopen($fn, 'r'); 93200803e56STom N Harris if (!$fh) return ''; 93300803e56STom N Harris $ln = -1; 93400803e56STom N Harris while (($line = fgets($fh)) !== false) { 93500803e56STom N Harris if (++$ln == $id) break; 93600803e56STom N Harris } 93700803e56STom N Harris fclose($fh); 93800803e56STom N Harris return rtrim((string)$line); 93900803e56STom N Harris } 94000803e56STom N Harris 94100803e56STom N Harris /** 94200803e56STom N Harris * Write a line into the index. 94300803e56STom N Harris * 944b9d8cc1eSTom N Harris * @param string $idx name of the index 945b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 946b9d8cc1eSTom N Harris * @param int $id the line number 947b9d8cc1eSTom N Harris * @param string $line line to write 948e3ab6fc5SMichael Hamann * @return bool If saving succeeded 94900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 95000803e56STom N Harris */ 95180fb93f6STom N Harris protected function saveIndexKey($idx, $suffix, $id, $line) { 95200803e56STom N Harris global $conf; 95300803e56STom N Harris if (substr($line, -1) != "\n") 95400803e56STom N Harris $line .= "\n"; 95500803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix; 95600803e56STom N Harris $fh = @fopen($fn.'.tmp', 'w'); 957dbb771bbSAdrian Lang if (!$fh) return false; 95800803e56STom N Harris $ih = @fopen($fn.'.idx', 'r'); 95900803e56STom N Harris if ($ih) { 96000803e56STom N Harris $ln = -1; 96100803e56STom N Harris while (($curline = fgets($ih)) !== false) { 96200803e56STom N Harris fwrite($fh, (++$ln == $id) ? $line : $curline); 96300803e56STom N Harris } 9644373c7b5SMichael Hamann if ($id > $ln) { 9654373c7b5SMichael Hamann while ($id > ++$ln) 9664373c7b5SMichael Hamann fwrite($fh, "\n"); 96700803e56STom N Harris fwrite($fh, $line); 9684373c7b5SMichael Hamann } 96900803e56STom N Harris fclose($ih); 97000803e56STom N Harris } else { 9714373c7b5SMichael Hamann $ln = -1; 9724373c7b5SMichael Hamann while ($id > ++$ln) 9734373c7b5SMichael Hamann fwrite($fh, "\n"); 97400803e56STom N Harris fwrite($fh, $line); 97500803e56STom N Harris } 97600803e56STom N Harris fclose($fh); 97700803e56STom N Harris if (isset($conf['fperm'])) 97800803e56STom N Harris chmod($fn.'.tmp', $conf['fperm']); 97900803e56STom N Harris io_rename($fn.'.tmp', $fn.'.idx'); 98000803e56STom N Harris if ($suffix !== '') 98180fb93f6STom N Harris $this->cacheIndexDir($idx, $suffix); 98200803e56STom N Harris return true; 98300803e56STom N Harris } 98400803e56STom N Harris 98500803e56STom N Harris /** 98600803e56STom N Harris * Retrieve or insert a value in the index. 98700803e56STom N Harris * 988b9d8cc1eSTom N Harris * @param string $idx name of the index 989b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 990b9d8cc1eSTom N Harris * @param string $value line to find in the index 991*03aafe1cSMichael Hamann * @return int|bool line number of the value in the index or false if writing the index failed 99200803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 99300803e56STom N Harris */ 99480fb93f6STom N Harris protected function addIndexKey($idx, $suffix, $value) { 99580fb93f6STom N Harris $index = $this->getIndex($idx, $suffix); 99600803e56STom N Harris $id = array_search($value, $index); 99700803e56STom N Harris if ($id === false) { 99800803e56STom N Harris $id = count($index); 99900803e56STom N Harris $index[$id] = $value; 100080fb93f6STom N Harris if (!$this->saveIndex($idx, $suffix, $index)) { 100100803e56STom N Harris trigger_error("Failed to write $idx index", E_USER_ERROR); 100200803e56STom N Harris return false; 100300803e56STom N Harris } 100400803e56STom N Harris } 100500803e56STom N Harris return $id; 100600803e56STom N Harris } 100700803e56STom N Harris 1008e3ab6fc5SMichael Hamann /** 1009e3ab6fc5SMichael Hamann * @param string $idx The index file which should be added to the key. 1010e3ab6fc5SMichael Hamann * @param string $suffix The suffix of the file 1011e3ab6fc5SMichael Hamann * @param bool $delete Unused 1012e3ab6fc5SMichael Hamann */ 101380fb93f6STom N Harris protected function cacheIndexDir($idx, $suffix, $delete=false) { 101400803e56STom N Harris global $conf; 101500803e56STom N Harris if ($idx == 'i') 101600803e56STom N Harris $cachename = $conf['indexdir'].'/lengths'; 101700803e56STom N Harris else 101800803e56STom N Harris $cachename = $conf['indexdir'].'/'.$idx.'lengths'; 101900803e56STom N Harris $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 102000803e56STom N Harris if ($lengths === false) $lengths = array(); 102100803e56STom N Harris $old = array_search((string)$suffix, $lengths); 102200803e56STom N Harris if (empty($lines)) { 102300803e56STom N Harris if ($old === false) return; 102400803e56STom N Harris unset($lengths[$old]); 102500803e56STom N Harris } else { 102600803e56STom N Harris if ($old !== false) return; 102700803e56STom N Harris $lengths[] = $suffix; 102800803e56STom N Harris sort($lengths); 102900803e56STom N Harris } 103000803e56STom N Harris $fh = @fopen($cachename.'.tmp', 'w'); 103100803e56STom N Harris if (!$fh) { 103200803e56STom N Harris trigger_error("Failed to write index cache", E_USER_ERROR); 103300803e56STom N Harris return; 103400803e56STom N Harris } 103500803e56STom N Harris @fwrite($fh, implode("\n", $lengths)); 103600803e56STom N Harris @fclose($fh); 103700803e56STom N Harris if (isset($conf['fperm'])) 103800803e56STom N Harris chmod($cachename.'.tmp', $conf['fperm']); 103900803e56STom N Harris io_rename($cachename.'.tmp', $cachename.'.idx'); 104000803e56STom N Harris } 104100803e56STom N Harris 104200803e56STom N Harris /** 104300803e56STom N Harris * Get the list of lengths indexed in the wiki. 104400803e56STom N Harris * 104500803e56STom N Harris * Read the index directory or a cache file and returns 104600803e56STom N Harris * a sorted array of lengths of the words used in the wiki. 104700803e56STom N Harris * 104800803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 104900803e56STom N Harris */ 105080fb93f6STom N Harris protected function listIndexLengths() { 105100803e56STom N Harris global $conf; 105200803e56STom N Harris $cachename = $conf['indexdir'].'/lengths'; 105300803e56STom N Harris clearstatcache(); 105400803e56STom N Harris if (@file_exists($cachename.'.idx')) { 105500803e56STom N Harris $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 105600803e56STom N Harris if ($lengths !== false) { 105700803e56STom N Harris $idx = array(); 105800803e56STom N Harris foreach ($lengths as $length) 105900803e56STom N Harris $idx[] = (int)$length; 106000803e56STom N Harris return $idx; 106100803e56STom N Harris } 106200803e56STom N Harris } 106300803e56STom N Harris 106400803e56STom N Harris $dir = @opendir($conf['indexdir']); 106500803e56STom N Harris if ($dir === false) 106600803e56STom N Harris return array(); 106700803e56STom N Harris $lengths[] = array(); 106800803e56STom N Harris while (($f = readdir($dir)) !== false) { 106900803e56STom N Harris if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') { 107000803e56STom N Harris $i = substr($f, 1, -4); 107100803e56STom N Harris if (is_numeric($i)) 107200803e56STom N Harris $lengths[] = (int)$i; 107300803e56STom N Harris } 107400803e56STom N Harris } 107500803e56STom N Harris closedir($dir); 107600803e56STom N Harris sort($lengths); 107700803e56STom N Harris // save this in a file 107800803e56STom N Harris $fh = @fopen($cachename.'.tmp', 'w'); 107900803e56STom N Harris if (!$fh) { 108000803e56STom N Harris trigger_error("Failed to write index cache", E_USER_ERROR); 10813e8e3ae6SMichael Hamann return $lengths; 108200803e56STom N Harris } 108300803e56STom N Harris @fwrite($fh, implode("\n", $lengths)); 108400803e56STom N Harris @fclose($fh); 108500803e56STom N Harris if (isset($conf['fperm'])) 108600803e56STom N Harris chmod($cachename.'.tmp', $conf['fperm']); 108700803e56STom N Harris io_rename($cachename.'.tmp', $cachename.'.idx'); 108800803e56STom N Harris 108900803e56STom N Harris return $lengths; 109000803e56STom N Harris } 109100803e56STom N Harris 109200803e56STom N Harris /** 109300803e56STom N Harris * Get the word lengths that have been indexed. 109400803e56STom N Harris * 109500803e56STom N Harris * Reads the index directory and returns an array of lengths 109600803e56STom N Harris * that there are indices for. 109700803e56STom N Harris * 109800803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 109900803e56STom N Harris */ 110080fb93f6STom N Harris protected function indexLengths($filter) { 110100803e56STom N Harris global $conf; 110200803e56STom N Harris $idx = array(); 110300803e56STom N Harris if (is_array($filter)) { 110400803e56STom N Harris // testing if index files exist only 110500803e56STom N Harris $path = $conf['indexdir']."/i"; 110600803e56STom N Harris foreach ($filter as $key => $value) { 110700803e56STom N Harris if (@file_exists($path.$key.'.idx')) 110800803e56STom N Harris $idx[] = $key; 110900803e56STom N Harris } 111000803e56STom N Harris } else { 111100803e56STom N Harris $lengths = idx_listIndexLengths(); 111200803e56STom N Harris foreach ($lengths as $key => $length) { 111300803e56STom N Harris // keep all the values equal or superior 111400803e56STom N Harris if ((int)$length >= (int)$filter) 111500803e56STom N Harris $idx[] = $length; 111600803e56STom N Harris } 111700803e56STom N Harris } 111800803e56STom N Harris return $idx; 111900803e56STom N Harris } 112000803e56STom N Harris 112100803e56STom N Harris /** 112200803e56STom N Harris * Insert or replace a tuple in a line. 112300803e56STom N Harris * 112400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 112500803e56STom N Harris */ 112680fb93f6STom N Harris protected function updateTuple($line, $id, $count) { 112700803e56STom N Harris $newLine = $line; 112800803e56STom N Harris if ($newLine !== '') 112900803e56STom N Harris $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine); 113000803e56STom N Harris $newLine = trim($newLine, ':'); 113100803e56STom N Harris if ($count) { 1132d64516f5SMichael Hamann if (strlen($newLine) > 0) 113300803e56STom N Harris return "$id*$count:".$newLine; 113400803e56STom N Harris else 113500803e56STom N Harris return "$id*$count".$newLine; 113600803e56STom N Harris } 113700803e56STom N Harris return $newLine; 113800803e56STom N Harris } 113900803e56STom N Harris 114000803e56STom N Harris /** 114100803e56STom N Harris * Split a line into an array of tuples. 114200803e56STom N Harris * 114300803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 114400803e56STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 114500803e56STom N Harris */ 114680fb93f6STom N Harris protected function parseTuples(&$keys, $line) { 114700803e56STom N Harris $result = array(); 114800803e56STom N Harris if ($line == '') return $result; 114900803e56STom N Harris $parts = explode(':', $line); 115000803e56STom N Harris foreach ($parts as $tuple) { 1151675bf41fSTom N Harris if ($tuple === '') continue; 115200803e56STom N Harris list($key, $cnt) = explode('*', $tuple); 1153d64516f5SMichael Hamann if (!$cnt) continue; 115400803e56STom N Harris $key = $keys[$key]; 115500803e56STom N Harris if (!$key) continue; 115600803e56STom N Harris $result[$key] = $cnt; 115700803e56STom N Harris } 115800803e56STom N Harris return $result; 115900803e56STom N Harris } 1160175193d2STom N Harris 1161175193d2STom N Harris /** 1162175193d2STom N Harris * Sum the counts in a list of tuples. 1163175193d2STom N Harris * 1164175193d2STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 1165175193d2STom N Harris */ 116680fb93f6STom N Harris protected function countTuples($line) { 1167175193d2STom N Harris $freq = 0; 1168175193d2STom N Harris $parts = explode(':', $line); 1169175193d2STom N Harris foreach ($parts as $tuple) { 1170675bf41fSTom N Harris if ($tuple === '') continue; 1171175193d2STom N Harris list($pid, $cnt) = explode('*', $tuple); 1172175193d2STom N Harris $freq += (int)$cnt; 1173175193d2STom N Harris } 1174175193d2STom N Harris return $freq; 1175175193d2STom N Harris } 117600803e56STom N Harris} 117700803e56STom N Harris 117800803e56STom N Harris/** 117900803e56STom N Harris * Create an instance of the indexer. 118000803e56STom N Harris * 1181b3d1090eSMichael Hamann * @return Doku_Indexer a Doku_Indexer 118200803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 118300803e56STom N Harris */ 11849b41be24STom N Harrisfunction idx_get_indexer() { 118500803e56STom N Harris static $Indexer = null; 118600803e56STom N Harris if (is_null($Indexer)) { 118700803e56STom N Harris $Indexer = new Doku_Indexer(); 118800803e56STom N Harris } 118900803e56STom N Harris return $Indexer; 119000803e56STom N Harris} 119100803e56STom N Harris 119200803e56STom N Harris/** 119300803e56STom N Harris * Returns words that will be ignored. 119400803e56STom N Harris * 119500803e56STom N Harris * @return array list of stop words 119600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 119700803e56STom N Harris */ 119800803e56STom N Harrisfunction & idx_get_stopwords() { 119900803e56STom N Harris static $stopwords = null; 120000803e56STom N Harris if (is_null($stopwords)) { 120100803e56STom N Harris global $conf; 120200803e56STom N Harris $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 120300803e56STom N Harris if(@file_exists($swfile)){ 120400803e56STom N Harris $stopwords = file($swfile, FILE_IGNORE_NEW_LINES); 120500803e56STom N Harris }else{ 120600803e56STom N Harris $stopwords = array(); 120700803e56STom N Harris } 120800803e56STom N Harris } 120900803e56STom N Harris return $stopwords; 121000803e56STom N Harris} 121100803e56STom N Harris 121200803e56STom N Harris/** 121300803e56STom N Harris * Adds/updates the search index for the given page 121400803e56STom N Harris * 121500803e56STom N Harris * Locking is handled internally. 121600803e56STom N Harris * 121700803e56STom N Harris * @param string $page name of the page to index 12189b41be24STom N Harris * @param boolean $verbose print status messages 1219d041f8dbSMichael Hamann * @param boolean $force force reindexing even when the index is up to date 122000803e56STom N Harris * @return boolean the function completed successfully 122100803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 122200803e56STom N Harris */ 1223d041f8dbSMichael Hamannfunction idx_addPage($page, $verbose=false, $force=false) { 12249b41be24STom N Harris $idxtag = metaFN($page,'.indexed'); 1225a23ac4d7SMichael Hamann // check if page was deleted but is still in the index 1226bbc85ee4STom N Harris if (!page_exists($page)) { 1227bbc85ee4STom N Harris if (!@file_exists($idxtag)) { 1228bbc85ee4STom N Harris if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF); 1229bbc85ee4STom N Harris return false; 1230bbc85ee4STom N Harris } 1231bbc85ee4STom N Harris $Indexer = idx_get_indexer(); 1232bbc85ee4STom N Harris $result = $Indexer->deletePage($page); 1233bbc85ee4STom N Harris if ($result === "locked") { 1234bbc85ee4STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 1235bbc85ee4STom N Harris return false; 1236bbc85ee4STom N Harris } 1237bbc85ee4STom N Harris @unlink($idxtag); 1238bbc85ee4STom N Harris return $result; 1239bbc85ee4STom N Harris } 1240a23ac4d7SMichael Hamann 1241a23ac4d7SMichael Hamann // check if indexing needed 1242a23ac4d7SMichael Hamann if(!$force && @file_exists($idxtag)){ 1243a23ac4d7SMichael Hamann if(trim(io_readFile($idxtag)) == idx_get_version()){ 1244a23ac4d7SMichael Hamann $last = @filemtime($idxtag); 1245a23ac4d7SMichael Hamann if($last > @filemtime(wikiFN($page))){ 1246a23ac4d7SMichael Hamann if ($verbose) print("Indexer: index for $page up to date".DOKU_LF); 1247a23ac4d7SMichael Hamann return false; 1248a23ac4d7SMichael Hamann } 1249a23ac4d7SMichael Hamann } 1250a23ac4d7SMichael Hamann } 1251a23ac4d7SMichael Hamann 125265aa8490SMichael Hamann $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED); 1253bbc85ee4STom N Harris if ($indexenabled === false) { 1254bbc85ee4STom N Harris $result = false; 1255bbc85ee4STom N Harris if (@file_exists($idxtag)) { 1256bbc85ee4STom N Harris $Indexer = idx_get_indexer(); 1257bbc85ee4STom N Harris $result = $Indexer->deletePage($page); 1258bbc85ee4STom N Harris if ($result === "locked") { 1259bbc85ee4STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 1260bbc85ee4STom N Harris return false; 1261bbc85ee4STom N Harris } 1262bbc85ee4STom N Harris @unlink($idxtag); 1263bbc85ee4STom N Harris } 1264bbc85ee4STom N Harris if ($verbose) print("Indexer: index disabled for $page".DOKU_LF); 1265bbc85ee4STom N Harris return $result; 1266bbc85ee4STom N Harris } 1267bbc85ee4STom N Harris 1268*03aafe1cSMichael Hamann $Indexer = idx_get_indexer(); 1269*03aafe1cSMichael Hamann $pid = $Indexer->getPID($page); 1270*03aafe1cSMichael Hamann if ($pid === false) { 1271*03aafe1cSMichael Hamann if ($verbose) print("Indexer: getting the PID failed for $page".DOKU_LF); 1272*03aafe1cSMichael Hamann return false; 1273*03aafe1cSMichael Hamann } 127400803e56STom N Harris $body = ''; 127539d6fd30SMichael Hamann $metadata = array(); 127665aa8490SMichael Hamann $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED); 127765aa8490SMichael Hamann if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null) 127839d6fd30SMichael Hamann $metadata['relation_references'] = array_keys($references); 1279a424180eSMichael Hamann else 1280a424180eSMichael Hamann $metadata['relation_references'] = array(); 1281*03aafe1cSMichael Hamann $data = compact('page', 'body', 'metadata', 'pid'); 128200803e56STom N Harris $evt = new Doku_Event('INDEXER_PAGE_ADD', $data); 128339d6fd30SMichael Hamann if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page); 128400803e56STom N Harris $evt->advise_after(); 128500803e56STom N Harris unset($evt); 128639d6fd30SMichael Hamann extract($data); 128700803e56STom N Harris 12889b41be24STom N Harris $result = $Indexer->addPageWords($page, $body); 1289e1e1a7e0SMichael Hamann if ($result === "locked") { 12909b41be24STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 12919b41be24STom N Harris return false; 12929b41be24STom N Harris } 1293320f489aSMichael Hamann 1294320f489aSMichael Hamann if ($result) { 129539d6fd30SMichael Hamann $result = $Indexer->addMetaKeys($page, $metadata); 1296320f489aSMichael Hamann if ($result === "locked") { 1297320f489aSMichael Hamann if ($verbose) print("Indexer: locked".DOKU_LF); 1298320f489aSMichael Hamann return false; 1299320f489aSMichael Hamann } 1300320f489aSMichael Hamann } 1301320f489aSMichael Hamann 13029b41be24STom N Harris if ($result) 13039b41be24STom N Harris io_saveFile(metaFN($page,'.indexed'), idx_get_version()); 13049b41be24STom N Harris if ($verbose) { 13059b41be24STom N Harris print("Indexer: finished".DOKU_LF); 13069b41be24STom N Harris return true; 13079b41be24STom N Harris } 13089b41be24STom N Harris return $result; 130900803e56STom N Harris} 131000803e56STom N Harris 131100803e56STom N Harris/** 131200803e56STom N Harris * Find tokens in the fulltext index 131300803e56STom N Harris * 131400803e56STom N Harris * Takes an array of words and will return a list of matching 131500803e56STom N Harris * pages for each one. 1316488dd6ceSAndreas Gohr * 131763773904SAndreas Gohr * Important: No ACL checking is done here! All results are 131863773904SAndreas Gohr * returned, regardless of permissions 131963773904SAndreas Gohr * 1320e3ab6fc5SMichael Hamann * @param array $words list of words to search for 132100803e56STom N Harris * @return array list of pages found, associated with the search terms 1322488dd6ceSAndreas Gohr */ 13239b41be24STom N Harrisfunction idx_lookup(&$words) { 13249b41be24STom N Harris $Indexer = idx_get_indexer(); 132500803e56STom N Harris return $Indexer->lookup($words); 1326488dd6ceSAndreas Gohr} 1327488dd6ceSAndreas Gohr 1328488dd6ceSAndreas Gohr/** 132900803e56STom N Harris * Split a string into tokens 1330488dd6ceSAndreas Gohr * 1331488dd6ceSAndreas Gohr */ 133200803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) { 13339b41be24STom N Harris $Indexer = idx_get_indexer(); 133400803e56STom N Harris return $Indexer->tokenizer($string, $wc); 1335488dd6ceSAndreas Gohr} 133600803e56STom N Harris 133700803e56STom N Harris/* For compatibility */ 1338488dd6ceSAndreas Gohr 1339f5eb7cf0SAndreas Gohr/** 134000803e56STom N Harris * Read the list of words in an index (if it exists). 1341f5eb7cf0SAndreas Gohr * 13424e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 1343f5eb7cf0SAndreas Gohr */ 134400803e56STom N Harrisfunction idx_getIndex($idx, $suffix) { 13451c07b9e6STom N Harris global $conf; 134600803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 134700803e56STom N Harris if (!@file_exists($fn)) return array(); 134800803e56STom N Harris return file($fn); 134900803e56STom N Harris} 1350f5eb7cf0SAndreas Gohr 135100803e56STom N Harris/** 135200803e56STom N Harris * Get the list of lengths indexed in the wiki. 135300803e56STom N Harris * 135400803e56STom N Harris * Read the index directory or a cache file and returns 135500803e56STom N Harris * a sorted array of lengths of the words used in the wiki. 135600803e56STom N Harris * 135700803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 135800803e56STom N Harris */ 135900803e56STom N Harrisfunction idx_listIndexLengths() { 136000803e56STom N Harris global $conf; 136100803e56STom N Harris // testing what we have to do, create a cache file or not. 136200803e56STom N Harris if ($conf['readdircache'] == 0) { 136300803e56STom N Harris $docache = false; 13641c07b9e6STom N Harris } else { 136500803e56STom N Harris clearstatcache(); 136600803e56STom N Harris if (@file_exists($conf['indexdir'].'/lengths.idx') 136700803e56STom N Harris && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) { 136800803e56STom N Harris if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) { 136900803e56STom N Harris $idx = array(); 137000803e56STom N Harris foreach ($lengths as $length) { 137100803e56STom N Harris $idx[] = (int)$length; 137200803e56STom N Harris } 137300803e56STom N Harris return $idx; 1374f5eb7cf0SAndreas Gohr } 13751c07b9e6STom N Harris } 137600803e56STom N Harris $docache = true; 137700803e56STom N Harris } 13784e1bf408STom N Harris 137900803e56STom N Harris if ($conf['readdircache'] == 0 || $docache) { 138000803e56STom N Harris $dir = @opendir($conf['indexdir']); 138100803e56STom N Harris if ($dir === false) 138200803e56STom N Harris return array(); 138326f7dbf5SMichael Hamann $idx = array(); 138400803e56STom N Harris while (($f = readdir($dir)) !== false) { 138500803e56STom N Harris if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') { 138600803e56STom N Harris $i = substr($f, 1, -4); 138700803e56STom N Harris if (is_numeric($i)) 138800803e56STom N Harris $idx[] = (int)$i; 138900803e56STom N Harris } 139000803e56STom N Harris } 139100803e56STom N Harris closedir($dir); 139200803e56STom N Harris sort($idx); 139300803e56STom N Harris // save this in a file 139400803e56STom N Harris if ($docache) { 139500803e56STom N Harris $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w'); 139600803e56STom N Harris @fwrite($handle, implode("\n", $idx)); 139700803e56STom N Harris @fclose($handle); 139800803e56STom N Harris } 139900803e56STom N Harris return $idx; 140000803e56STom N Harris } 140100803e56STom N Harris 140200803e56STom N Harris return array(); 140300803e56STom N Harris} 140400803e56STom N Harris 140500803e56STom N Harris/** 140600803e56STom N Harris * Get the word lengths that have been indexed. 140700803e56STom N Harris * 140800803e56STom N Harris * Reads the index directory and returns an array of lengths 140900803e56STom N Harris * that there are indices for. 141000803e56STom N Harris * 141100803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 141200803e56STom N Harris */ 141300803e56STom N Harrisfunction idx_indexLengths($filter) { 141400803e56STom N Harris global $conf; 141500803e56STom N Harris $idx = array(); 141600803e56STom N Harris if (is_array($filter)) { 141700803e56STom N Harris // testing if index files exist only 141800803e56STom N Harris $path = $conf['indexdir']."/i"; 141900803e56STom N Harris foreach ($filter as $key => $value) { 142000803e56STom N Harris if (@file_exists($path.$key.'.idx')) 142100803e56STom N Harris $idx[] = $key; 142200803e56STom N Harris } 1423f5eb7cf0SAndreas Gohr } else { 142400803e56STom N Harris $lengths = idx_listIndexLengths(); 142500803e56STom N Harris foreach ($lengths as $key => $length) { 142600803e56STom N Harris // keep all the values equal or superior 142700803e56STom N Harris if ((int)$length >= (int)$filter) 142800803e56STom N Harris $idx[] = $length; 1429f5eb7cf0SAndreas Gohr } 143000803e56STom N Harris } 143100803e56STom N Harris return $idx; 1432f5eb7cf0SAndreas Gohr} 1433f5eb7cf0SAndreas Gohr 143400803e56STom N Harris/** 143500803e56STom N Harris * Clean a name of a key for use as a file name. 143600803e56STom N Harris * 143700803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's 143800803e56STom N Harris * not a letter, number, or underscore. 143900803e56STom N Harris * 144000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 144100803e56STom N Harris */ 144200803e56STom N Harrisfunction idx_cleanName($name) { 144300803e56STom N Harris $name = utf8_romanize(trim((string)$name)); 144400803e56STom N Harris $name = preg_replace('#[ \./\\:-]+#', '_', $name); 144500803e56STom N Harris $name = preg_replace('/[^A-Za-z0-9_]/', '', $name); 144600803e56STom N Harris return strtolower($name); 1447f5eb7cf0SAndreas Gohr} 1448f5eb7cf0SAndreas Gohr 144900803e56STom N Harris//Setup VIM: ex: et ts=4 : 1450