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 135a1d0548SMichael Hamanndefine('INDEXER_VERSION', 8); 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 { 1053d2ce006SMichael Hamann /** 1063d2ce006SMichael Hamann * @var array $pidCache Cache for getPID() 1073d2ce006SMichael Hamann */ 1083d2ce006SMichael Hamann protected $pidCache = array(); 109579b0f7eSTNHarris 110579b0f7eSTNHarris /** 11100803e56STom N Harris * Adds the contents of a page to the fulltext index 112dd35e9c9SAndreas Gohr * 11300803e56STom N Harris * The added text replaces previous words for the same page. 11400803e56STom N Harris * An empty value erases the page. 11500803e56STom N Harris * 11600803e56STom N Harris * @param string $page a page name 11700803e56STom N Harris * @param string $text the body of the page 11800803e56STom N Harris * @return boolean the function completed successfully 11900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 120dd35e9c9SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 121dd35e9c9SAndreas Gohr */ 12200803e56STom N Harris public function addPageWords($page, $text) { 12380fb93f6STom N Harris if (!$this->lock()) 1249b41be24STom N Harris return "locked"; 12500803e56STom N Harris 12600803e56STom N Harris // load known documents 12703aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 1285981eb09STom N Harris if ($pid === false) { 12980fb93f6STom N Harris $this->unlock(); 13000803e56STom N Harris return false; 13100803e56STom N Harris } 13200803e56STom N Harris 13300803e56STom N Harris $pagewords = array(); 13400803e56STom N Harris // get word usage in page 13580fb93f6STom N Harris $words = $this->getPageWords($text); 13600803e56STom N Harris if ($words === false) { 13780fb93f6STom N Harris $this->unlock(); 13800803e56STom N Harris return false; 13900803e56STom N Harris } 14000803e56STom N Harris 14100803e56STom N Harris if (!empty($words)) { 14200803e56STom N Harris foreach (array_keys($words) as $wlen) { 14380fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 14400803e56STom N Harris foreach ($words[$wlen] as $wid => $freq) { 14500803e56STom N Harris $idx = ($wid<count($index)) ? $index[$wid] : ''; 14680fb93f6STom N Harris $index[$wid] = $this->updateTuple($idx, $pid, $freq); 14700803e56STom N Harris $pagewords[] = "$wlen*$wid"; 14800803e56STom N Harris } 14980fb93f6STom N Harris if (!$this->saveIndex('i', $wlen, $index)) { 15080fb93f6STom N Harris $this->unlock(); 15100803e56STom N Harris return false; 15200803e56STom N Harris } 15300803e56STom N Harris } 15400803e56STom N Harris } 15500803e56STom N Harris 15600803e56STom N Harris // Remove obsolete index entries 15780fb93f6STom N Harris $pageword_idx = $this->getIndexKey('pageword', '', $pid); 15800803e56STom N Harris if ($pageword_idx !== '') { 15900803e56STom N Harris $oldwords = explode(':',$pageword_idx); 16000803e56STom N Harris $delwords = array_diff($oldwords, $pagewords); 16100803e56STom N Harris $upwords = array(); 16200803e56STom N Harris foreach ($delwords as $word) { 16300803e56STom N Harris if ($word != '') { 16400803e56STom N Harris list($wlen,$wid) = explode('*', $word); 16500803e56STom N Harris $wid = (int)$wid; 16600803e56STom N Harris $upwords[$wlen][] = $wid; 16700803e56STom N Harris } 16800803e56STom N Harris } 16900803e56STom N Harris foreach ($upwords as $wlen => $widx) { 17080fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 17100803e56STom N Harris foreach ($widx as $wid) { 17280fb93f6STom N Harris $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 17300803e56STom N Harris } 17480fb93f6STom N Harris $this->saveIndex('i', $wlen, $index); 17500803e56STom N Harris } 17600803e56STom N Harris } 17700803e56STom N Harris // Save the reverse index 17800803e56STom N Harris $pageword_idx = join(':', $pagewords); 17980fb93f6STom N Harris if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) { 18080fb93f6STom N Harris $this->unlock(); 18100803e56STom N Harris return false; 18200803e56STom N Harris } 18300803e56STom N Harris 18480fb93f6STom N Harris $this->unlock(); 185dd35e9c9SAndreas Gohr return true; 186dd35e9c9SAndreas Gohr } 187dd35e9c9SAndreas Gohr 188dd35e9c9SAndreas Gohr /** 18900803e56STom N Harris * Split the words in a page and add them to the index. 19044ca0adfSAndreas Gohr * 191b9d8cc1eSTom N Harris * @param string $text content of the page 192b9d8cc1eSTom N Harris * @return array list of word IDs and number of times used 19344ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 19417f42b01SChris Smith * @author Christopher Smith <chris@jalakai.co.uk> 19500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 196b4ce25e9SAndreas Gohr */ 19780fb93f6STom N Harris protected function getPageWords($text) { 19844ca0adfSAndreas Gohr 19900803e56STom N Harris $tokens = $this->tokenizer($text); 20017f42b01SChris Smith $tokens = array_count_values($tokens); // count the frequency of each token 20117f42b01SChris Smith 20217f42b01SChris Smith $words = array(); 2034e1bf408STom N Harris foreach ($tokens as $w=>$c) { 204d5b23302STom N Harris $l = wordlen($w); 205579b0f7eSTNHarris if (isset($words[$l])){ 2064e1bf408STom N Harris $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0); 20717f42b01SChris Smith }else{ 2084e1bf408STom N Harris $words[$l] = array($w => $c); 20917f42b01SChris Smith } 21017f42b01SChris Smith } 21117f42b01SChris Smith 212579b0f7eSTNHarris // arrive here with $words = array(wordlen => array(word => frequency)) 213e5e50383SMichael Hamann $word_idx_modified = false; 214b4ce25e9SAndreas Gohr $index = array(); //resulting index 215579b0f7eSTNHarris foreach (array_keys($words) as $wlen) { 21680fb93f6STom N Harris $word_idx = $this->getIndex('w', $wlen); 217579b0f7eSTNHarris foreach ($words[$wlen] as $word => $freq) { 2185a1d0548SMichael Hamann $word = (string)$word; 219a8dba452SMichael Hamann $wid = array_search($word, $word_idx, true); 22000803e56STom N Harris if ($wid === false) { 221d5b23302STom N Harris $wid = count($word_idx); 22200803e56STom N Harris $word_idx[] = $word; 223e5e50383SMichael Hamann $word_idx_modified = true; 224b4ce25e9SAndreas Gohr } 225579b0f7eSTNHarris if (!isset($index[$wlen])) 226579b0f7eSTNHarris $index[$wlen] = array(); 227579b0f7eSTNHarris $index[$wlen][$wid] = $freq; 22844ca0adfSAndreas Gohr } 22900803e56STom N Harris // save back the word index 23080fb93f6STom N Harris if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx)) 23144ca0adfSAndreas Gohr return false; 23244ca0adfSAndreas Gohr } 233b4ce25e9SAndreas Gohr 234b4ce25e9SAndreas Gohr return $index; 235b4ce25e9SAndreas Gohr } 236b4ce25e9SAndreas Gohr 23744ca0adfSAndreas Gohr /** 238e1e1a7e0SMichael Hamann * Add/update keys to/of the metadata index. 23944ca0adfSAndreas Gohr * 24000803e56STom N Harris * Adding new keys does not remove other keys for the page. 24100803e56STom N Harris * An empty value will erase the key. 24200803e56STom N Harris * The $key parameter can be an array to add multiple keys. $value will 24300803e56STom N Harris * not be used if $key is an array. 24444ca0adfSAndreas Gohr * 24500803e56STom N Harris * @param string $page a page name 24600803e56STom N Harris * @param mixed $key a key string or array of key=>value pairs 24700803e56STom N Harris * @param mixed $value the value or list of values 24800803e56STom N Harris * @return boolean the function completed successfully 24900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 250e1e1a7e0SMichael Hamann * @author Michael Hamann <michael@content-space.de> 25144ca0adfSAndreas Gohr */ 25200803e56STom N Harris public function addMetaKeys($page, $key, $value=null) { 25300803e56STom N Harris if (!is_array($key)) { 25400803e56STom N Harris $key = array($key => $value); 25500803e56STom N Harris } elseif (!is_null($value)) { 25600803e56STom N Harris // $key is array, but $value is not null 25700803e56STom N Harris trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING); 25800803e56STom N Harris } 25900803e56STom N Harris 26080fb93f6STom N Harris if (!$this->lock()) 261e1e1a7e0SMichael Hamann return "locked"; 262b4ce25e9SAndreas Gohr 263488dd6ceSAndreas Gohr // load known documents 26403aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 26500803e56STom N Harris if ($pid === false) { 26680fb93f6STom N Harris $this->unlock(); 267579b0f7eSTNHarris return false; 26844ca0adfSAndreas Gohr } 26900803e56STom N Harris 270c1209673STom N Harris // Special handling for titles so the index file is simpler 271c1209673STom N Harris if (array_key_exists('title', $key)) { 272c1209673STom N Harris $value = $key['title']; 273c1209673STom N Harris if (is_array($value)) 274c1209673STom N Harris $value = $value[0]; 27580fb93f6STom N Harris $this->saveIndexKey('title', '', $pid, $value); 276c1209673STom N Harris unset($key['title']); 277c1209673STom N Harris } 278c1209673STom N Harris 27900803e56STom N Harris foreach ($key as $name => $values) { 28000803e56STom N Harris $metaname = idx_cleanName($name); 28180fb93f6STom N Harris $this->addIndexKey('metadata', '', $metaname); 282b9d8cc1eSTom N Harris $metaidx = $this->getIndex($metaname.'_i', ''); 283b9d8cc1eSTom N Harris $metawords = $this->getIndex($metaname.'_w', ''); 28400803e56STom N Harris $addwords = false; 285e1e1a7e0SMichael Hamann 286e1e1a7e0SMichael Hamann if (!is_array($values)) $values = array($values); 287e1e1a7e0SMichael Hamann 288b9d8cc1eSTom N Harris $val_idx = $this->getIndexKey($metaname.'_p', '', $pid); 289e1e1a7e0SMichael Hamann if ($val_idx != '') { 290e1e1a7e0SMichael Hamann $val_idx = explode(':', $val_idx); 291e1e1a7e0SMichael Hamann // -1 means remove, 0 keep, 1 add 292e1e1a7e0SMichael Hamann $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1)); 293e1e1a7e0SMichael Hamann } else { 294e1e1a7e0SMichael Hamann $val_idx = array(); 295e1e1a7e0SMichael Hamann } 296e1e1a7e0SMichael Hamann 29700803e56STom N Harris foreach ($values as $val) { 29800803e56STom N Harris $val = (string)$val; 29900803e56STom N Harris if ($val !== "") { 300a8dba452SMichael Hamann $id = array_search($val, $metawords, true); 30100803e56STom N Harris if ($id === false) { 30200803e56STom N Harris $id = count($metawords); 30300803e56STom N Harris $metawords[$id] = $val; 30400803e56STom N Harris $addwords = true; 305d5b23302STom N Harris } 306e1e1a7e0SMichael Hamann // test if value is already in the index 307*39134585SChristopher Smith if (isset($val_idx[$id]) && $val_idx[$id] <= 0){ 308e1e1a7e0SMichael Hamann $val_idx[$id] = 0; 309*39134585SChristopher Smith } else { // else add it 310e1e1a7e0SMichael Hamann $val_idx[$id] = 1; 31144ca0adfSAndreas Gohr } 312579b0f7eSTNHarris } 313*39134585SChristopher Smith } 314e1e1a7e0SMichael Hamann 315*39134585SChristopher Smith if ($addwords) { 31680fb93f6STom N Harris $this->saveIndex($metaname.'_w', '', $metawords); 317*39134585SChristopher Smith } 318e1e1a7e0SMichael Hamann $vals_changed = false; 319e1e1a7e0SMichael Hamann foreach ($val_idx as $id => $action) { 320e1e1a7e0SMichael Hamann if ($action == -1) { 32180fb93f6STom N Harris $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0); 322e1e1a7e0SMichael Hamann $vals_changed = true; 323e1e1a7e0SMichael Hamann unset($val_idx[$id]); 324e1e1a7e0SMichael Hamann } elseif ($action == 1) { 32580fb93f6STom N Harris $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1); 326e1e1a7e0SMichael Hamann $vals_changed = true; 327e1e1a7e0SMichael Hamann } 328e1e1a7e0SMichael Hamann } 329e1e1a7e0SMichael Hamann 330e1e1a7e0SMichael Hamann if ($vals_changed) { 33180fb93f6STom N Harris $this->saveIndex($metaname.'_i', '', $metaidx); 332e1e1a7e0SMichael Hamann $val_idx = implode(':', array_keys($val_idx)); 33380fb93f6STom N Harris $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx); 334b6344591STom N Harris } 335e1e1a7e0SMichael Hamann 33600803e56STom N Harris unset($metaidx); 33700803e56STom N Harris unset($metawords); 338a0c5c349STom N Harris } 339e1e1a7e0SMichael Hamann 34080fb93f6STom N Harris $this->unlock(); 341579b0f7eSTNHarris return true; 34244ca0adfSAndreas Gohr } 34344ca0adfSAndreas Gohr 34444ca0adfSAndreas Gohr /** 345af73bba6SMichael Hamann * Rename a page in the search index without changing the indexed content. This function doesn't check if the 346af73bba6SMichael Hamann * old or new name exists in the filesystem. It returns an error if the old page isn't in the page list of the 347af73bba6SMichael Hamann * indexer and it deletes all previously indexed content of the new page. 3485eb9e867SMichael Hamann * 3495eb9e867SMichael Hamann * @param string $oldpage The old page name 3505eb9e867SMichael Hamann * @param string $newpage The new page name 3515eb9e867SMichael Hamann * @return string|bool If the page was successfully renamed, can be a message in the case of an error 3525eb9e867SMichael Hamann */ 3535eb9e867SMichael Hamann public function renamePage($oldpage, $newpage) { 3545eb9e867SMichael Hamann if (!$this->lock()) return 'locked'; 3555eb9e867SMichael Hamann 3565eb9e867SMichael Hamann $pages = $this->getPages(); 3575eb9e867SMichael Hamann 358a8dba452SMichael Hamann $id = array_search($oldpage, $pages, true); 3595eb9e867SMichael Hamann if ($id === false) { 3605eb9e867SMichael Hamann $this->unlock(); 3615eb9e867SMichael Hamann return 'page is not in index'; 3625eb9e867SMichael Hamann } 3635eb9e867SMichael Hamann 364a8dba452SMichael Hamann $new_id = array_search($newpage, $pages, true); 3655eb9e867SMichael Hamann if ($new_id !== false) { 3665eb9e867SMichael Hamann // make sure the page is not in the index anymore 367bc27f3e2SMichael Hamann if ($this->deletePageNoLock($newpage) !== true) { 368bc27f3e2SMichael Hamann return false; 369bc27f3e2SMichael Hamann } 3705eb9e867SMichael Hamann 3715eb9e867SMichael Hamann $pages[$new_id] = 'deleted:'.time().rand(0, 9999); 3725eb9e867SMichael Hamann } 3735eb9e867SMichael Hamann 3745eb9e867SMichael Hamann $pages[$id] = $newpage; 3755eb9e867SMichael Hamann 3765eb9e867SMichael Hamann // update index 3775eb9e867SMichael Hamann if (!$this->saveIndex('page', '', $pages)) { 3785eb9e867SMichael Hamann $this->unlock(); 3795eb9e867SMichael Hamann return false; 3805eb9e867SMichael Hamann } 3815eb9e867SMichael Hamann 3825eb9e867SMichael Hamann // reset the pid cache 3835eb9e867SMichael Hamann $this->pidCache = array(); 3845eb9e867SMichael Hamann 3855eb9e867SMichael Hamann $this->unlock(); 3865eb9e867SMichael Hamann return true; 3875eb9e867SMichael Hamann } 3885eb9e867SMichael Hamann 3895eb9e867SMichael Hamann /** 3905eb9e867SMichael Hamann * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages 3915eb9e867SMichael Hamann * will be updated. 3925eb9e867SMichael Hamann * 3935eb9e867SMichael Hamann * @param string $key The metadata key of which a value shall be changed 3945eb9e867SMichael Hamann * @param string $oldvalue The old value that shall be renamed 3955eb9e867SMichael Hamann * @param string $newvalue The new value to which the old value shall be renamed, can exist (then values will be merged) 3965eb9e867SMichael Hamann * @return bool|string If renaming the value has been successful, false or error message on error. 3975eb9e867SMichael Hamann */ 3985eb9e867SMichael Hamann public function renameMetaValue($key, $oldvalue, $newvalue) { 3995eb9e867SMichael Hamann if (!$this->lock()) return 'locked'; 4005eb9e867SMichael Hamann 4015eb9e867SMichael Hamann // change the relation references index 4025eb9e867SMichael Hamann $metavalues = $this->getIndex($key, '_w'); 403a8dba452SMichael Hamann $oldid = array_search($oldvalue, $metavalues, true); 4045eb9e867SMichael Hamann if ($oldid !== false) { 405a8dba452SMichael Hamann $newid = array_search($newvalue, $metavalues, true); 4065eb9e867SMichael Hamann if ($newid !== false) { 4075eb9e867SMichael Hamann // free memory 4085eb9e867SMichael Hamann unset ($metavalues); 4095eb9e867SMichael Hamann 4105eb9e867SMichael Hamann // okay, now we have two entries for the same value. we need to merge them. 4119e64ca0dSMichael Hamann $indexline = $this->getIndexKey($key.'_i', '', $oldid); 4125eb9e867SMichael Hamann if ($indexline != '') { 4139e64ca0dSMichael Hamann $newindexline = $this->getIndexKey($key.'_i', '', $newid); 4149e64ca0dSMichael Hamann $pagekeys = $this->getIndex($key.'_p', ''); 4155eb9e867SMichael Hamann $parts = explode(':', $indexline); 4165eb9e867SMichael Hamann foreach ($parts as $part) { 4175eb9e867SMichael Hamann list($id, $count) = explode('*', $part); 4185eb9e867SMichael Hamann $newindexline = $this->updateTuple($newindexline, $id, $count); 4195eb9e867SMichael Hamann 4205eb9e867SMichael Hamann $keyline = explode(':', $pagekeys[$id]); 4215eb9e867SMichael Hamann // remove old meta value 4225eb9e867SMichael Hamann $keyline = array_diff($keyline, array($oldid)); 4235eb9e867SMichael Hamann // add new meta value when not already present 4245eb9e867SMichael Hamann if (!in_array($newid, $keyline)) { 4255eb9e867SMichael Hamann array_push($keyline, $newid); 4265eb9e867SMichael Hamann } 4275eb9e867SMichael Hamann $pagekeys[$id] = implode(':', $keyline); 4285eb9e867SMichael Hamann } 4299e64ca0dSMichael Hamann $this->saveIndex($key.'_p', '', $pagekeys); 4305eb9e867SMichael Hamann unset($pagekeys); 4319e64ca0dSMichael Hamann $this->saveIndexKey($key.'_i', '', $oldid, ''); 4329e64ca0dSMichael Hamann $this->saveIndexKey($key.'_i', '', $newid, $newindexline); 4335eb9e867SMichael Hamann } 4345eb9e867SMichael Hamann } else { 4355eb9e867SMichael Hamann $metavalues[$oldid] = $newvalue; 4369e64ca0dSMichael Hamann if (!$this->saveIndex($key.'_w', '', $metavalues)) { 4375eb9e867SMichael Hamann $this->unlock(); 4385eb9e867SMichael Hamann return false; 4395eb9e867SMichael Hamann } 4405eb9e867SMichael Hamann } 4415eb9e867SMichael Hamann } 4425eb9e867SMichael Hamann 4435eb9e867SMichael Hamann $this->unlock(); 4445eb9e867SMichael Hamann return true; 4455eb9e867SMichael Hamann } 44625adeb91SMichael Hamann 4475eb9e867SMichael Hamann /** 44800803e56STom N Harris * Remove a page from the index 44944ca0adfSAndreas Gohr * 45000803e56STom N Harris * Erases entries in all known indexes. 45144ca0adfSAndreas Gohr * 45200803e56STom N Harris * @param string $page a page name 45300803e56STom N Harris * @return boolean the function completed successfully 45400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 45544ca0adfSAndreas Gohr */ 45600803e56STom N Harris public function deletePage($page) { 45780fb93f6STom N Harris if (!$this->lock()) 458bbc85ee4STom N Harris return "locked"; 459bbc85ee4STom N Harris 46025adeb91SMichael Hamann $result = $this->deletePageNoLock($page); 46125adeb91SMichael Hamann 46225adeb91SMichael Hamann $this->unlock(); 46325adeb91SMichael Hamann 46425adeb91SMichael Hamann return $result; 46525adeb91SMichael Hamann } 46625adeb91SMichael Hamann 46725adeb91SMichael Hamann /** 46825adeb91SMichael Hamann * Remove a page from the index without locking the index, only use this function if the index is already locked 46925adeb91SMichael Hamann * 47025adeb91SMichael Hamann * Erases entries in all known indexes. 47125adeb91SMichael Hamann * 47225adeb91SMichael Hamann * @param string $page a page name 47325adeb91SMichael Hamann * @return boolean the function completed successfully 47425adeb91SMichael Hamann * @author Tom N Harris <tnharris@whoopdedo.org> 47525adeb91SMichael Hamann */ 47625adeb91SMichael Hamann protected function deletePageNoLock($page) { 477bbc85ee4STom N Harris // load known documents 47803aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 4795981eb09STom N Harris if ($pid === false) { 480bbc85ee4STom N Harris return false; 481bbc85ee4STom N Harris } 482bbc85ee4STom N Harris 483bbc85ee4STom N Harris // Remove obsolete index entries 48480fb93f6STom N Harris $pageword_idx = $this->getIndexKey('pageword', '', $pid); 485bbc85ee4STom N Harris if ($pageword_idx !== '') { 486bbc85ee4STom N Harris $delwords = explode(':',$pageword_idx); 487bbc85ee4STom N Harris $upwords = array(); 488bbc85ee4STom N Harris foreach ($delwords as $word) { 489bbc85ee4STom N Harris if ($word != '') { 490bbc85ee4STom N Harris list($wlen,$wid) = explode('*', $word); 491bbc85ee4STom N Harris $wid = (int)$wid; 492bbc85ee4STom N Harris $upwords[$wlen][] = $wid; 493bbc85ee4STom N Harris } 494bbc85ee4STom N Harris } 495bbc85ee4STom N Harris foreach ($upwords as $wlen => $widx) { 49680fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 497bbc85ee4STom N Harris foreach ($widx as $wid) { 49880fb93f6STom N Harris $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 499bbc85ee4STom N Harris } 50080fb93f6STom N Harris $this->saveIndex('i', $wlen, $index); 501bbc85ee4STom N Harris } 502bbc85ee4STom N Harris } 503bbc85ee4STom N Harris // Save the reverse index 50480fb93f6STom N Harris if (!$this->saveIndexKey('pageword', '', $pid, "")) { 505bbc85ee4STom N Harris return false; 506bbc85ee4STom N Harris } 507bbc85ee4STom N Harris 50880fb93f6STom N Harris $this->saveIndexKey('title', '', $pid, ""); 50980fb93f6STom N Harris $keyidx = $this->getIndex('metadata', ''); 5100604da34STom N Harris foreach ($keyidx as $metaname) { 51180fb93f6STom N Harris $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid)); 51280fb93f6STom N Harris $meta_idx = $this->getIndex($metaname.'_i', ''); 5130604da34STom N Harris foreach ($val_idx as $id) { 514c55c59e3SMichael Hamann if ($id === '') continue; 51580fb93f6STom N Harris $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0); 5160604da34STom N Harris } 51780fb93f6STom N Harris $this->saveIndex($metaname.'_i', '', $meta_idx); 51880fb93f6STom N Harris $this->saveIndexKey($metaname.'_p', '', $pid, ''); 5190604da34STom N Harris } 520bbc85ee4STom N Harris 521bbc85ee4STom N Harris return true; 522d5b23302STom N Harris } 52344ca0adfSAndreas Gohr 524d5b23302STom N Harris /** 5253cf3c7d6SMichael Hamann * Clear the whole index 5263cf3c7d6SMichael Hamann * 5273cf3c7d6SMichael Hamann * @return bool If the index has been cleared successfully 5283cf3c7d6SMichael Hamann */ 5293cf3c7d6SMichael Hamann public function clear() { 5303cf3c7d6SMichael Hamann global $conf; 5313cf3c7d6SMichael Hamann 5323cf3c7d6SMichael Hamann if (!$this->lock()) return false; 5333cf3c7d6SMichael Hamann 5343cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/page.idx'); 5353cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/title.idx'); 5363cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/pageword.idx'); 5373cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/metadata.idx'); 5383cf3c7d6SMichael Hamann $dir = @opendir($conf['indexdir']); 5393cf3c7d6SMichael Hamann if($dir!==false){ 5403cf3c7d6SMichael Hamann while(($f = readdir($dir)) !== false){ 5413cf3c7d6SMichael Hamann if(substr($f,-4)=='.idx' && 5423cf3c7d6SMichael Hamann (substr($f,0,1)=='i' || substr($f,0,1)=='w' 5433cf3c7d6SMichael Hamann || substr($f,-6)=='_w.idx' || substr($f,-6)=='_i.idx' || substr($f,-6)=='_p.idx')) 5443cf3c7d6SMichael Hamann @unlink($conf['indexdir']."/$f"); 5453cf3c7d6SMichael Hamann } 5463cf3c7d6SMichael Hamann } 5473cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/lengths.idx'); 5483cf3c7d6SMichael Hamann 5493cf3c7d6SMichael Hamann // clear the pid cache 5503cf3c7d6SMichael Hamann $this->pidCache = array(); 5513cf3c7d6SMichael Hamann 5523cf3c7d6SMichael Hamann $this->unlock(); 5533cf3c7d6SMichael Hamann return true; 5543cf3c7d6SMichael Hamann } 5553cf3c7d6SMichael Hamann 5563cf3c7d6SMichael Hamann /** 55700803e56STom N Harris * Split the text into words for fulltext search 558d5b23302STom N Harris * 55900803e56STom N Harris * TODO: does this also need &$stopwords ? 560d5b23302STom N Harris * 5618cd4c12fSAndreas Gohr * @triggers INDEXER_TEXT_PREPARE 5628cd4c12fSAndreas Gohr * This event allows plugins to modify the text before it gets tokenized. 5638cd4c12fSAndreas Gohr * Plugins intercepting this event should also intercept INDEX_VERSION_GET 5648cd4c12fSAndreas Gohr * 56500803e56STom N Harris * @param string $text plain text 56600803e56STom N Harris * @param boolean $wc are wildcards allowed? 56700803e56STom N Harris * @return array list of words in the text 568d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 569d5b23302STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 570d5b23302STom N Harris */ 57100803e56STom N Harris public function tokenizer($text, $wc=false) { 57200803e56STom N Harris $wc = ($wc) ? '' : '\*'; 57300803e56STom N Harris $stopwords =& idx_get_stopwords(); 57400803e56STom N Harris 5758cd4c12fSAndreas Gohr // prepare the text to be tokenized 5768cd4c12fSAndreas Gohr $evt = new Doku_Event('INDEXER_TEXT_PREPARE', $text); 5778cd4c12fSAndreas Gohr if ($evt->advise_before(true)) { 57800803e56STom N Harris if (preg_match('/[^0-9A-Za-z ]/u', $text)) { 57900803e56STom N Harris // handle asian chars as single words (may fail on older PHP version) 58000803e56STom N Harris $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text); 58100803e56STom N Harris if (!is_null($asia)) $text = $asia; // recover from regexp falure 58222952965SYoBoY } 58322952965SYoBoY } 5848cd4c12fSAndreas Gohr $evt->advise_after(); 5858cd4c12fSAndreas Gohr unset($evt); 5868cd4c12fSAndreas Gohr 587f77fc90dSMichael Hamann $text = strtr($text, 5884f0030ddSAndreas Gohr array( 5894f0030ddSAndreas Gohr "\r" => ' ', 5904f0030ddSAndreas Gohr "\n" => ' ', 5914f0030ddSAndreas Gohr "\t" => ' ', 5924f0030ddSAndreas Gohr "\xC2\xAD" => '', //soft-hyphen 5934f0030ddSAndreas Gohr ) 5944f0030ddSAndreas Gohr ); 59500803e56STom N Harris if (preg_match('/[^0-9A-Za-z ]/u', $text)) 59600803e56STom N Harris $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc); 59722952965SYoBoY 59800803e56STom N Harris $wordlist = explode(' ', $text); 5995f27cb0eSMichael Hamann foreach ($wordlist as $i => $word) { 6005f27cb0eSMichael Hamann $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ? 60100803e56STom N Harris utf8_strtolower($word) : strtolower($word); 6025f27cb0eSMichael Hamann } 6035f27cb0eSMichael Hamann 6045f27cb0eSMichael Hamann foreach ($wordlist as $i => $word) { 605675bf41fSTom N Harris if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) 606a8dba452SMichael Hamann || array_search($word, $stopwords, true) !== false) 607675bf41fSTom N Harris unset($wordlist[$i]); 60822952965SYoBoY } 609675bf41fSTom N Harris return array_values($wordlist); 61022952965SYoBoY } 61122952965SYoBoY 61222952965SYoBoY /** 61303aafe1cSMichael Hamann * Get the numeric PID of a page 61403aafe1cSMichael Hamann * 61503aafe1cSMichael Hamann * @param string $page The page to get the PID for 61603aafe1cSMichael Hamann * @return bool|int The page id on success, false on error 61703aafe1cSMichael Hamann */ 61803aafe1cSMichael Hamann public function getPID($page) { 6193d2ce006SMichael Hamann // return PID without locking when it is in the cache 6203d2ce006SMichael Hamann if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 6213d2ce006SMichael Hamann 62203aafe1cSMichael Hamann if (!$this->lock()) 62303aafe1cSMichael Hamann return false; 62403aafe1cSMichael Hamann 62503aafe1cSMichael Hamann // load known documents 62603aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 62703aafe1cSMichael Hamann if ($pid === false) { 62803aafe1cSMichael Hamann $this->unlock(); 62903aafe1cSMichael Hamann return false; 63003aafe1cSMichael Hamann } 63103aafe1cSMichael Hamann 63203aafe1cSMichael Hamann $this->unlock(); 63303aafe1cSMichael Hamann return $pid; 63403aafe1cSMichael Hamann } 63503aafe1cSMichael Hamann 63603aafe1cSMichael Hamann /** 63703aafe1cSMichael Hamann * Get the numeric PID of a page without locking the index. 63803aafe1cSMichael Hamann * Only use this function when the index is already locked. 63903aafe1cSMichael Hamann * 64003aafe1cSMichael Hamann * @param string $page The page to get the PID for 64103aafe1cSMichael Hamann * @return bool|int The page id on success, false on error 64203aafe1cSMichael Hamann */ 64303aafe1cSMichael Hamann protected function getPIDNoLock($page) { 6443d2ce006SMichael Hamann // avoid expensive addIndexKey operation for the most recently requested pages by using a cache 6453d2ce006SMichael Hamann if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 6463d2ce006SMichael Hamann $pid = $this->addIndexKey('page', '', $page); 6473d2ce006SMichael Hamann // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently 6483d2ce006SMichael Hamann // added item will be requested again 6493d2ce006SMichael Hamann if (count($this->pidCache) > 10) array_shift($this->pidCache); 6503d2ce006SMichael Hamann $this->pidCache[$page] = $pid; 6513d2ce006SMichael Hamann return $pid; 65203aafe1cSMichael Hamann } 65303aafe1cSMichael Hamann 65403aafe1cSMichael Hamann /** 65503aafe1cSMichael Hamann * Get the page id of a numeric PID 65603aafe1cSMichael Hamann * 65703aafe1cSMichael Hamann * @param int $pid The PID to get the page id for 65803aafe1cSMichael Hamann * @return string The page id 65903aafe1cSMichael Hamann */ 66003aafe1cSMichael Hamann public function getPageFromPID($pid) { 66103aafe1cSMichael Hamann return $this->getIndexKey('page', '', $pid); 66203aafe1cSMichael Hamann } 66303aafe1cSMichael Hamann 66403aafe1cSMichael Hamann /** 66500803e56STom N Harris * Find pages in the fulltext index containing the words, 666579b0f7eSTNHarris * 66700803e56STom N Harris * The search words must be pre-tokenized, meaning only letters and 66800803e56STom N Harris * numbers with an optional wildcard 669579b0f7eSTNHarris * 67000803e56STom N Harris * The returned array will have the original tokens as key. The values 67100803e56STom N Harris * in the returned list is an array with the page names as keys and the 672b00bd361STom N Harris * number of times that token appears on the page as value. 67300803e56STom N Harris * 674e3ab6fc5SMichael Hamann * @param array $tokens list of words to search for 67500803e56STom N Harris * @return array list of page names with usage counts 67600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 67700803e56STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 678579b0f7eSTNHarris */ 6799b41be24STom N Harris public function lookup(&$tokens) { 68000803e56STom N Harris $result = array(); 68180fb93f6STom N Harris $wids = $this->getIndexWords($tokens, $result); 68200803e56STom N Harris if (empty($wids)) return array(); 68300803e56STom N Harris // load known words and documents 68480fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 68500803e56STom N Harris $docs = array(); 68600803e56STom N Harris foreach (array_keys($wids) as $wlen) { 68700803e56STom N Harris $wids[$wlen] = array_unique($wids[$wlen]); 68880fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 68900803e56STom N Harris foreach($wids[$wlen] as $ixid) { 69000803e56STom N Harris if ($ixid < count($index)) 69180fb93f6STom N Harris $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]); 692d5b23302STom N Harris } 693d5b23302STom N Harris } 69400803e56STom N Harris // merge found pages into final result array 69500803e56STom N Harris $final = array(); 69600803e56STom N Harris foreach ($result as $word => $res) { 69700803e56STom N Harris $final[$word] = array(); 69800803e56STom N Harris foreach ($res as $wid) { 699952ab260SMichael Hamann // handle the case when ($ixid < count($index)) has been false 700952ab260SMichael Hamann // and thus $docs[$wid] hasn't been set. 701952ab260SMichael Hamann if (!isset($docs[$wid])) continue; 70200803e56STom N Harris $hits = &$docs[$wid]; 70300803e56STom N Harris foreach ($hits as $hitkey => $hitcnt) { 70400803e56STom N Harris // make sure the document still exists 70500803e56STom N Harris if (!page_exists($hitkey, '', false)) continue; 70600803e56STom N Harris if (!isset($final[$word][$hitkey])) 70700803e56STom N Harris $final[$word][$hitkey] = $hitcnt; 70800803e56STom N Harris else 70900803e56STom N Harris $final[$word][$hitkey] += $hitcnt; 710d5b23302STom N Harris } 711579b0f7eSTNHarris } 712579b0f7eSTNHarris } 71300803e56STom N Harris return $final; 714579b0f7eSTNHarris } 715579b0f7eSTNHarris 716579b0f7eSTNHarris /** 71700803e56STom N Harris * Find pages containing a metadata key. 718d5b23302STom N Harris * 71900803e56STom N Harris * The metadata values are compared as case-sensitive strings. Pass a 72000803e56STom N Harris * callback function that returns true or false to use a different 721b00bd361STom N Harris * comparison function. The function will be called with the $value being 722b00bd361STom N Harris * searched for as the first argument, and the word in the index as the 7231538718dSTom N Harris * second argument. The function preg_match can be used directly if the 7241538718dSTom N Harris * values are regexes. 725d5b23302STom N Harris * 72600803e56STom N Harris * @param string $key name of the metadata key to look for 7271538718dSTom N Harris * @param string $value search term to look for, must be a string or array of strings 72800803e56STom N Harris * @param callback $func comparison function 729b00bd361STom N Harris * @return array lists with page names, keys are query values if $value is array 73000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 731cd763a5bSMichael Hamann * @author Michael Hamann <michael@content-space.de> 73200803e56STom N Harris */ 733b00bd361STom N Harris public function lookupKey($key, &$value, $func=null) { 734f078bb00STom N Harris if (!is_array($value)) 735f078bb00STom N Harris $value_array = array($value); 736f078bb00STom N Harris else 737f078bb00STom N Harris $value_array =& $value; 738cd763a5bSMichael Hamann 739c1209673STom N Harris // the matching ids for the provided value(s) 740c1209673STom N Harris $value_ids = array(); 741c1209673STom N Harris 742c1209673STom N Harris $metaname = idx_cleanName($key); 743c1209673STom N Harris 744c1209673STom N Harris // get all words in order to search the matching ids 745c1209673STom N Harris if ($key == 'title') { 74680fb93f6STom N Harris $words = $this->getIndex('title', ''); 747c1209673STom N Harris } else { 748b9d8cc1eSTom N Harris $words = $this->getIndex($metaname.'_w', ''); 749c1209673STom N Harris } 750c1209673STom N Harris 751f078bb00STom N Harris if (!is_null($func)) { 7521538718dSTom N Harris foreach ($value_array as $val) { 753f078bb00STom N Harris foreach ($words as $i => $word) { 7541538718dSTom N Harris if (call_user_func_array($func, array($val, $word))) 755c1209673STom N Harris $value_ids[$i][] = $val; 756f078bb00STom N Harris } 757f078bb00STom N Harris } 758f078bb00STom N Harris } else { 759f078bb00STom N Harris foreach ($value_array as $val) { 760f078bb00STom N Harris $xval = $val; 761b6d540bdSTom N Harris $caret = '^'; 762b6d540bdSTom N Harris $dollar = '$'; 763f078bb00STom N Harris // check for wildcards 764f078bb00STom N Harris if (substr($xval, 0, 1) == '*') { 765f078bb00STom N Harris $xval = substr($xval, 1); 766b6d540bdSTom N Harris $caret = ''; 767f078bb00STom N Harris } 768f078bb00STom N Harris if (substr($xval, -1, 1) == '*') { 769f078bb00STom N Harris $xval = substr($xval, 0, -1); 770b6d540bdSTom N Harris $dollar = ''; 771f078bb00STom N Harris } 772b6d540bdSTom N Harris if (!$caret || !$dollar) { 773f078bb00STom N Harris $re = $caret.preg_quote($xval, '/').$dollar; 774f078bb00STom N Harris foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i) 775c1209673STom N Harris $value_ids[$i][] = $val; 776cd763a5bSMichael Hamann } else { 777a8dba452SMichael Hamann if (($i = array_search($val, $words, true)) !== false) 778c1209673STom N Harris $value_ids[$i][] = $val; 779cd763a5bSMichael Hamann } 780cd763a5bSMichael Hamann } 781cd763a5bSMichael Hamann } 782cd763a5bSMichael Hamann 783cd763a5bSMichael Hamann unset($words); // free the used memory 784cd763a5bSMichael Hamann 7857233c152SMichael Hamann // initialize the result so it won't be null 786c1209673STom N Harris $result = array(); 7877233c152SMichael Hamann foreach ($value_array as $val) { 7887233c152SMichael Hamann $result[$val] = array(); 7897233c152SMichael Hamann } 7907233c152SMichael Hamann 79180fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 792cd763a5bSMichael Hamann 793c1209673STom N Harris // Special handling for titles 794c1209673STom N Harris if ($key == 'title') { 795c1209673STom N Harris foreach ($value_ids as $pid => $val_list) { 796c1209673STom N Harris $page = $page_idx[$pid]; 797c1209673STom N Harris foreach ($val_list as $val) { 798c1209673STom N Harris $result[$val][] = $page; 799c1209673STom N Harris } 800c1209673STom N Harris } 801c1209673STom N Harris } else { 802c1209673STom N Harris // load all lines and pages so the used lines can be taken and matched with the pages 803b9d8cc1eSTom N Harris $lines = $this->getIndex($metaname.'_i', ''); 804c1209673STom N Harris 805c1209673STom N Harris foreach ($value_ids as $value_id => $val_list) { 806cd763a5bSMichael Hamann // parse the tuples of the form page_id*1:page2_id*1 and so on, return value 807cd763a5bSMichael Hamann // is an array with page_id => 1, page2_id => 1 etc. so take the keys only 80880fb93f6STom N Harris $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id])); 809c1209673STom N Harris foreach ($val_list as $val) { 810c1209673STom N Harris $result[$val] = array_merge($result[$val], $pages); 811c1209673STom N Harris } 812c1209673STom N Harris } 813cd763a5bSMichael Hamann } 814f078bb00STom N Harris if (!is_array($value)) $result = $result[$value]; 815cd763a5bSMichael Hamann return $result; 81600803e56STom N Harris } 81700803e56STom N Harris 81800803e56STom N Harris /** 81900803e56STom N Harris * Find the index ID of each search term. 82000803e56STom N Harris * 82100803e56STom N Harris * The query terms should only contain valid characters, with a '*' at 82200803e56STom N Harris * either the beginning or end of the word (or both). 82300803e56STom N Harris * The $result parameter can be used to merge the index locations with 82400803e56STom N Harris * the appropriate query term. 82500803e56STom N Harris * 826e3ab6fc5SMichael Hamann * @param array $words The query terms. 827e3ab6fc5SMichael Hamann * @param array $result Set to word => array("length*id" ...) 828d5b23302STom N Harris * @return array Set to length => array(id ...) 829d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 830d5b23302STom N Harris */ 83180fb93f6STom N Harris protected function getIndexWords(&$words, &$result) { 832d5b23302STom N Harris $tokens = array(); 833d5b23302STom N Harris $tokenlength = array(); 834d5b23302STom N Harris $tokenwild = array(); 835d5b23302STom N Harris foreach ($words as $word) { 836d5b23302STom N Harris $result[$word] = array(); 837b6d540bdSTom N Harris $caret = '^'; 838b6d540bdSTom N Harris $dollar = '$'; 839d5b23302STom N Harris $xword = $word; 840d5b23302STom N Harris $wlen = wordlen($word); 841d5b23302STom N Harris 842d5b23302STom N Harris // check for wildcards 843d5b23302STom N Harris if (substr($xword, 0, 1) == '*') { 844d5b23302STom N Harris $xword = substr($xword, 1); 845b6d540bdSTom N Harris $caret = ''; 846d5b23302STom N Harris $wlen -= 1; 847d5b23302STom N Harris } 848d5b23302STom N Harris if (substr($xword, -1, 1) == '*') { 849d5b23302STom N Harris $xword = substr($xword, 0, -1); 850b6d540bdSTom N Harris $dollar = ''; 851d5b23302STom N Harris $wlen -= 1; 852d5b23302STom N Harris } 853b6d540bdSTom N Harris if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword)) 85400803e56STom N Harris continue; 85500803e56STom N Harris if (!isset($tokens[$xword])) 856d5b23302STom N Harris $tokenlength[$wlen][] = $xword; 857b6d540bdSTom N Harris if (!$caret || !$dollar) { 858f078bb00STom N Harris $re = $caret.preg_quote($xword, '/').$dollar; 85900803e56STom N Harris $tokens[$xword][] = array($word, '/'.$re.'/'); 86000803e56STom N Harris if (!isset($tokenwild[$xword])) 86100803e56STom N Harris $tokenwild[$xword] = $wlen; 86200803e56STom N Harris } else { 863d5b23302STom N Harris $tokens[$xword][] = array($word, null); 864d5b23302STom N Harris } 86500803e56STom N Harris } 866d5b23302STom N Harris asort($tokenwild); 86700803e56STom N Harris // $tokens = array( base word => array( [ query term , regexp ] ... ) ... ) 868d5b23302STom N Harris // $tokenlength = array( base word length => base word ... ) 869d5b23302STom N Harris // $tokenwild = array( base word => base word length ... ) 870d5b23302STom N Harris $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength)); 87180fb93f6STom N Harris $indexes_known = $this->indexLengths($length_filter); 872d5b23302STom N Harris if (!empty($tokenwild)) sort($indexes_known); 873d5b23302STom N Harris // get word IDs 874d5b23302STom N Harris $wids = array(); 875d5b23302STom N Harris foreach ($indexes_known as $ixlen) { 87680fb93f6STom N Harris $word_idx = $this->getIndex('w', $ixlen); 877d5b23302STom N Harris // handle exact search 878d5b23302STom N Harris if (isset($tokenlength[$ixlen])) { 879d5b23302STom N Harris foreach ($tokenlength[$ixlen] as $xword) { 880a8dba452SMichael Hamann $wid = array_search($xword, $word_idx, true); 88100803e56STom N Harris if ($wid !== false) { 882d5b23302STom N Harris $wids[$ixlen][] = $wid; 883d5b23302STom N Harris foreach ($tokens[$xword] as $w) 884d5b23302STom N Harris $result[$w[0]][] = "$ixlen*$wid"; 885d5b23302STom N Harris } 886d5b23302STom N Harris } 887d5b23302STom N Harris } 888d5b23302STom N Harris // handle wildcard search 889d5b23302STom N Harris foreach ($tokenwild as $xword => $wlen) { 890d5b23302STom N Harris if ($wlen >= $ixlen) break; 891d5b23302STom N Harris foreach ($tokens[$xword] as $w) { 892d5b23302STom N Harris if (is_null($w[1])) continue; 893d5b23302STom N Harris foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) { 894d5b23302STom N Harris $wids[$ixlen][] = $wid; 895d5b23302STom N Harris $result[$w[0]][] = "$ixlen*$wid"; 896d5b23302STom N Harris } 897d5b23302STom N Harris } 898d5b23302STom N Harris } 899d5b23302STom N Harris } 900d5b23302STom N Harris return $wids; 901d5b23302STom N Harris } 902d5b23302STom N Harris 903d5b23302STom N Harris /** 90400803e56STom N Harris * Return a list of all pages 905c1209673STom N Harris * Warning: pages may not exist! 906488dd6ceSAndreas Gohr * 90700803e56STom N Harris * @param string $key list only pages containing the metadata key (optional) 90800803e56STom N Harris * @return array list of page names 90900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 91000803e56STom N Harris */ 91100803e56STom N Harris public function getPages($key=null) { 91280fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 91300803e56STom N Harris if (is_null($key)) return $page_idx; 914c1209673STom N Harris 915c1209673STom N Harris $metaname = idx_cleanName($key); 916c1209673STom N Harris 917c1209673STom N Harris // Special handling for titles 918c1209673STom N Harris if ($key == 'title') { 91980fb93f6STom N Harris $title_idx = $this->getIndex('title', ''); 920c1209673STom N Harris array_splice($page_idx, count($title_idx)); 921c1209673STom N Harris foreach ($title_idx as $i => $title) 922c1209673STom N Harris if ($title === "") unset($page_idx[$i]); 923675bf41fSTom N Harris return array_values($page_idx); 924c1209673STom N Harris } 925c1209673STom N Harris 926c1209673STom N Harris $pages = array(); 927b9d8cc1eSTom N Harris $lines = $this->getIndex($metaname.'_i', ''); 928c1209673STom N Harris foreach ($lines as $line) { 92980fb93f6STom N Harris $pages = array_merge($pages, $this->parseTuples($page_idx, $line)); 930c1209673STom N Harris } 931c1209673STom N Harris return array_keys($pages); 93200803e56STom N Harris } 93300803e56STom N Harris 93400803e56STom N Harris /** 93500803e56STom N Harris * Return a list of words sorted by number of times used 93600803e56STom N Harris * 93700803e56STom N Harris * @param int $min bottom frequency threshold 93800803e56STom N Harris * @param int $max upper frequency limit. No limit if $max<$min 939e3ab6fc5SMichael Hamann * @param int $minlen minimum length of words to count 94000803e56STom N Harris * @param string $key metadata key to list. Uses the fulltext index if not given 94100803e56STom N Harris * @return array list of words as the keys and frequency as values 94200803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 94300803e56STom N Harris */ 944b8c040dbSTom N Harris public function histogram($min=1, $max=0, $minlen=3, $key=null) { 945175193d2STom N Harris if ($min < 1) 946175193d2STom N Harris $min = 1; 947175193d2STom N Harris if ($max < $min) 948175193d2STom N Harris $max = 0; 949175193d2STom N Harris 950175193d2STom N Harris $result = array(); 951175193d2STom N Harris 952175193d2STom N Harris if ($key == 'title') { 95380fb93f6STom N Harris $index = $this->getIndex('title', ''); 954175193d2STom N Harris $index = array_count_values($index); 955175193d2STom N Harris foreach ($index as $val => $cnt) { 956b8c040dbSTom N Harris if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen) 957175193d2STom N Harris $result[$val] = $cnt; 958175193d2STom N Harris } 959175193d2STom N Harris } 960175193d2STom N Harris elseif (!is_null($key)) { 961175193d2STom N Harris $metaname = idx_cleanName($key); 96280fb93f6STom N Harris $index = $this->getIndex($metaname.'_i', ''); 963175193d2STom N Harris $val_idx = array(); 964175193d2STom N Harris foreach ($index as $wid => $line) { 96580fb93f6STom N Harris $freq = $this->countTuples($line); 9669a9b579aSMichael Hamann if ($freq >= $min && (!$max || $freq <= $max)) 967175193d2STom N Harris $val_idx[$wid] = $freq; 968175193d2STom N Harris } 969175193d2STom N Harris if (!empty($val_idx)) { 97080fb93f6STom N Harris $words = $this->getIndex($metaname.'_w', ''); 9719a9b579aSMichael Hamann foreach ($val_idx as $wid => $freq) { 9729a9b579aSMichael Hamann if (strlen($words[$wid]) >= $minlen) 973175193d2STom N Harris $result[$words[$wid]] = $freq; 974175193d2STom N Harris } 975175193d2STom N Harris } 9769a9b579aSMichael Hamann } 977175193d2STom N Harris else { 978175193d2STom N Harris $lengths = idx_listIndexLengths(); 979175193d2STom N Harris foreach ($lengths as $length) { 980b8c040dbSTom N Harris if ($length < $minlen) continue; 98180fb93f6STom N Harris $index = $this->getIndex('i', $length); 982175193d2STom N Harris $words = null; 983175193d2STom N Harris foreach ($index as $wid => $line) { 98480fb93f6STom N Harris $freq = $this->countTuples($line); 985175193d2STom N Harris if ($freq >= $min && (!$max || $freq <= $max)) { 986175193d2STom N Harris if ($words === null) 98780fb93f6STom N Harris $words = $this->getIndex('w', $length); 988175193d2STom N Harris $result[$words[$wid]] = $freq; 989175193d2STom N Harris } 990175193d2STom N Harris } 991175193d2STom N Harris } 992175193d2STom N Harris } 993175193d2STom N Harris 994175193d2STom N Harris arsort($result); 995175193d2STom N Harris return $result; 99600803e56STom N Harris } 99700803e56STom N Harris 99800803e56STom N Harris /** 99900803e56STom N Harris * Lock the indexer. 100000803e56STom N Harris * 100100803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 100200803e56STom N Harris */ 100380fb93f6STom N Harris protected function lock() { 100400803e56STom N Harris global $conf; 100500803e56STom N Harris $status = true; 1006f77fc90dSMichael Hamann $run = 0; 100700803e56STom N Harris $lock = $conf['lockdir'].'/_indexer.lock'; 100800803e56STom N Harris while (!@mkdir($lock, $conf['dmode'])) { 100900803e56STom N Harris usleep(50); 1010f77fc90dSMichael Hamann if(is_dir($lock) && time()-@filemtime($lock) > 60*5){ 1011f77fc90dSMichael Hamann // looks like a stale lock - remove it 1012f77fc90dSMichael Hamann if (!@rmdir($lock)) { 1013f77fc90dSMichael Hamann $status = "removing the stale lock failed"; 1014f77fc90dSMichael Hamann return false; 101500803e56STom N Harris } else { 1016f77fc90dSMichael Hamann $status = "stale lock removed"; 1017f77fc90dSMichael Hamann } 1018f77fc90dSMichael Hamann }elseif($run++ == 1000){ 1019f77fc90dSMichael Hamann // we waited 5 seconds for that lock 102000803e56STom N Harris return false; 102100803e56STom N Harris } 102200803e56STom N Harris } 1023443e135dSChristopher Smith if (!empty($conf['dperm'])) { 102400803e56STom N Harris chmod($lock, $conf['dperm']); 1025443e135dSChristopher Smith } 102600803e56STom N Harris return $status; 102700803e56STom N Harris } 102800803e56STom N Harris 102900803e56STom N Harris /** 103000803e56STom N Harris * Release the indexer lock. 103100803e56STom N Harris * 103200803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 103300803e56STom N Harris */ 103480fb93f6STom N Harris protected function unlock() { 103500803e56STom N Harris global $conf; 103600803e56STom N Harris @rmdir($conf['lockdir'].'/_indexer.lock'); 103700803e56STom N Harris return true; 103800803e56STom N Harris } 103900803e56STom N Harris 104000803e56STom N Harris /** 104100803e56STom N Harris * Retrieve the entire index. 104200803e56STom N Harris * 1043b9d8cc1eSTom N Harris * The $suffix argument is for an index that is split into 1044b9d8cc1eSTom N Harris * multiple parts. Different index files should use different 1045b9d8cc1eSTom N Harris * base names. 1046b9d8cc1eSTom N Harris * 1047b9d8cc1eSTom N Harris * @param string $idx name of the index 1048b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1049b9d8cc1eSTom N Harris * @return array list of lines without CR or LF 105000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 105100803e56STom N Harris */ 105280fb93f6STom N Harris protected function getIndex($idx, $suffix) { 105300803e56STom N Harris global $conf; 105400803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 1055d64516f5SMichael Hamann if (!@file_exists($fn)) return array(); 1056d64516f5SMichael Hamann return file($fn, FILE_IGNORE_NEW_LINES); 105700803e56STom N Harris } 105800803e56STom N Harris 105900803e56STom N Harris /** 106000803e56STom N Harris * Replace the contents of the index with an array. 106100803e56STom N Harris * 1062b9d8cc1eSTom N Harris * @param string $idx name of the index 1063b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1064e3ab6fc5SMichael Hamann * @param array $lines list of lines without LF 1065e3ab6fc5SMichael Hamann * @return bool If saving succeeded 106600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 106700803e56STom N Harris */ 106880fb93f6STom N Harris protected function saveIndex($idx, $suffix, &$lines) { 106900803e56STom N Harris global $conf; 107000803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix; 107100803e56STom N Harris $fh = @fopen($fn.'.tmp', 'w'); 107200803e56STom N Harris if (!$fh) return false; 107300803e56STom N Harris fwrite($fh, join("\n", $lines)); 10742e1018bcSMichael Hamann if (!empty($lines)) 10752e1018bcSMichael Hamann fwrite($fh, "\n"); 107600803e56STom N Harris fclose($fh); 107700803e56STom N Harris if (isset($conf['fperm'])) 107800803e56STom N Harris chmod($fn.'.tmp', $conf['fperm']); 107900803e56STom N Harris io_rename($fn.'.tmp', $fn.'.idx'); 108000803e56STom N Harris return true; 108100803e56STom N Harris } 108200803e56STom N Harris 108300803e56STom N Harris /** 108400803e56STom N Harris * Retrieve a line from the index. 108500803e56STom N Harris * 1086b9d8cc1eSTom N Harris * @param string $idx name of the index 1087b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1088b9d8cc1eSTom N Harris * @param int $id the line number 1089b9d8cc1eSTom N Harris * @return string a line with trailing whitespace removed 109000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 109100803e56STom N Harris */ 109280fb93f6STom N Harris protected function getIndexKey($idx, $suffix, $id) { 109300803e56STom N Harris global $conf; 109400803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 109500803e56STom N Harris if (!@file_exists($fn)) return ''; 109600803e56STom N Harris $fh = @fopen($fn, 'r'); 109700803e56STom N Harris if (!$fh) return ''; 109800803e56STom N Harris $ln = -1; 109900803e56STom N Harris while (($line = fgets($fh)) !== false) { 110000803e56STom N Harris if (++$ln == $id) break; 110100803e56STom N Harris } 110200803e56STom N Harris fclose($fh); 110300803e56STom N Harris return rtrim((string)$line); 110400803e56STom N Harris } 110500803e56STom N Harris 110600803e56STom N Harris /** 110700803e56STom N Harris * Write a line into the index. 110800803e56STom N Harris * 1109b9d8cc1eSTom N Harris * @param string $idx name of the index 1110b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1111b9d8cc1eSTom N Harris * @param int $id the line number 1112b9d8cc1eSTom N Harris * @param string $line line to write 1113e3ab6fc5SMichael Hamann * @return bool If saving succeeded 111400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 111500803e56STom N Harris */ 111680fb93f6STom N Harris protected function saveIndexKey($idx, $suffix, $id, $line) { 111700803e56STom N Harris global $conf; 111800803e56STom N Harris if (substr($line, -1) != "\n") 111900803e56STom N Harris $line .= "\n"; 112000803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix; 112100803e56STom N Harris $fh = @fopen($fn.'.tmp', 'w'); 1122dbb771bbSAdrian Lang if (!$fh) return false; 112300803e56STom N Harris $ih = @fopen($fn.'.idx', 'r'); 112400803e56STom N Harris if ($ih) { 112500803e56STom N Harris $ln = -1; 112600803e56STom N Harris while (($curline = fgets($ih)) !== false) { 112700803e56STom N Harris fwrite($fh, (++$ln == $id) ? $line : $curline); 112800803e56STom N Harris } 11294373c7b5SMichael Hamann if ($id > $ln) { 11304373c7b5SMichael Hamann while ($id > ++$ln) 11314373c7b5SMichael Hamann fwrite($fh, "\n"); 113200803e56STom N Harris fwrite($fh, $line); 11334373c7b5SMichael Hamann } 113400803e56STom N Harris fclose($ih); 113500803e56STom N Harris } else { 11364373c7b5SMichael Hamann $ln = -1; 11374373c7b5SMichael Hamann while ($id > ++$ln) 11384373c7b5SMichael Hamann fwrite($fh, "\n"); 113900803e56STom N Harris fwrite($fh, $line); 114000803e56STom N Harris } 114100803e56STom N Harris fclose($fh); 114200803e56STom N Harris if (isset($conf['fperm'])) 114300803e56STom N Harris chmod($fn.'.tmp', $conf['fperm']); 114400803e56STom N Harris io_rename($fn.'.tmp', $fn.'.idx'); 114500803e56STom N Harris return true; 114600803e56STom N Harris } 114700803e56STom N Harris 114800803e56STom N Harris /** 114900803e56STom N Harris * Retrieve or insert a value in the index. 115000803e56STom N Harris * 1151b9d8cc1eSTom N Harris * @param string $idx name of the index 1152b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1153b9d8cc1eSTom N Harris * @param string $value line to find in the index 115403aafe1cSMichael Hamann * @return int|bool line number of the value in the index or false if writing the index failed 115500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 115600803e56STom N Harris */ 115780fb93f6STom N Harris protected function addIndexKey($idx, $suffix, $value) { 115880fb93f6STom N Harris $index = $this->getIndex($idx, $suffix); 1159a8dba452SMichael Hamann $id = array_search($value, $index, true); 116000803e56STom N Harris if ($id === false) { 116100803e56STom N Harris $id = count($index); 116200803e56STom N Harris $index[$id] = $value; 116380fb93f6STom N Harris if (!$this->saveIndex($idx, $suffix, $index)) { 116400803e56STom N Harris trigger_error("Failed to write $idx index", E_USER_ERROR); 116500803e56STom N Harris return false; 116600803e56STom N Harris } 116700803e56STom N Harris } 116800803e56STom N Harris return $id; 116900803e56STom N Harris } 117000803e56STom N Harris 1171e3ab6fc5SMichael Hamann /** 117200803e56STom N Harris * Get the list of lengths indexed in the wiki. 117300803e56STom N Harris * 117400803e56STom N Harris * Read the index directory or a cache file and returns 117500803e56STom N Harris * a sorted array of lengths of the words used in the wiki. 117600803e56STom N Harris * 117700803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 117800803e56STom N Harris */ 117980fb93f6STom N Harris protected function listIndexLengths() { 1180b1720e5cSMichael Hamann return idx_listIndexLengths(); 118100803e56STom N Harris } 118200803e56STom N Harris 118300803e56STom N Harris /** 118400803e56STom N Harris * Get the word lengths that have been indexed. 118500803e56STom N Harris * 118600803e56STom N Harris * Reads the index directory and returns an array of lengths 118700803e56STom N Harris * that there are indices for. 118800803e56STom N Harris * 118900803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 119000803e56STom N Harris */ 119180fb93f6STom N Harris protected function indexLengths($filter) { 119200803e56STom N Harris global $conf; 119300803e56STom N Harris $idx = array(); 119400803e56STom N Harris if (is_array($filter)) { 119500803e56STom N Harris // testing if index files exist only 119600803e56STom N Harris $path = $conf['indexdir']."/i"; 119700803e56STom N Harris foreach ($filter as $key => $value) { 119800803e56STom N Harris if (@file_exists($path.$key.'.idx')) 119900803e56STom N Harris $idx[] = $key; 120000803e56STom N Harris } 120100803e56STom N Harris } else { 120200803e56STom N Harris $lengths = idx_listIndexLengths(); 120300803e56STom N Harris foreach ($lengths as $key => $length) { 120400803e56STom N Harris // keep all the values equal or superior 120500803e56STom N Harris if ((int)$length >= (int)$filter) 120600803e56STom N Harris $idx[] = $length; 120700803e56STom N Harris } 120800803e56STom N Harris } 120900803e56STom N Harris return $idx; 121000803e56STom N Harris } 121100803e56STom N Harris 121200803e56STom N Harris /** 121300803e56STom N Harris * Insert or replace a tuple in a line. 121400803e56STom N Harris * 121500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 121600803e56STom N Harris */ 121780fb93f6STom N Harris protected function updateTuple($line, $id, $count) { 121800803e56STom N Harris $newLine = $line; 1219*39134585SChristopher Smith if ($newLine !== ''){ 122000803e56STom N Harris $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine); 1221*39134585SChristopher Smith } 122200803e56STom N Harris $newLine = trim($newLine, ':'); 122300803e56STom N Harris if ($count) { 1224*39134585SChristopher Smith if (strlen($newLine) > 0) { 122500803e56STom N Harris return "$id*$count:".$newLine; 1226*39134585SChristopher Smith } else { 122700803e56STom N Harris return "$id*$count".$newLine; 122800803e56STom N Harris } 1229*39134585SChristopher Smith } 123000803e56STom N Harris return $newLine; 123100803e56STom N Harris } 123200803e56STom N Harris 123300803e56STom N Harris /** 123400803e56STom N Harris * Split a line into an array of tuples. 123500803e56STom N Harris * 123600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 123700803e56STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 123800803e56STom N Harris */ 123980fb93f6STom N Harris protected function parseTuples(&$keys, $line) { 124000803e56STom N Harris $result = array(); 124100803e56STom N Harris if ($line == '') return $result; 124200803e56STom N Harris $parts = explode(':', $line); 124300803e56STom N Harris foreach ($parts as $tuple) { 1244675bf41fSTom N Harris if ($tuple === '') continue; 124500803e56STom N Harris list($key, $cnt) = explode('*', $tuple); 1246d64516f5SMichael Hamann if (!$cnt) continue; 124700803e56STom N Harris $key = $keys[$key]; 124800803e56STom N Harris if (!$key) continue; 124900803e56STom N Harris $result[$key] = $cnt; 125000803e56STom N Harris } 125100803e56STom N Harris return $result; 125200803e56STom N Harris } 1253175193d2STom N Harris 1254175193d2STom N Harris /** 1255175193d2STom N Harris * Sum the counts in a list of tuples. 1256175193d2STom N Harris * 1257175193d2STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 1258175193d2STom N Harris */ 125980fb93f6STom N Harris protected function countTuples($line) { 1260175193d2STom N Harris $freq = 0; 1261175193d2STom N Harris $parts = explode(':', $line); 1262175193d2STom N Harris foreach ($parts as $tuple) { 1263675bf41fSTom N Harris if ($tuple === '') continue; 1264175193d2STom N Harris list($pid, $cnt) = explode('*', $tuple); 1265175193d2STom N Harris $freq += (int)$cnt; 1266175193d2STom N Harris } 1267175193d2STom N Harris return $freq; 1268175193d2STom N Harris } 126900803e56STom N Harris} 127000803e56STom N Harris 127100803e56STom N Harris/** 127200803e56STom N Harris * Create an instance of the indexer. 127300803e56STom N Harris * 1274b3d1090eSMichael Hamann * @return Doku_Indexer a Doku_Indexer 127500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 127600803e56STom N Harris */ 12779b41be24STom N Harrisfunction idx_get_indexer() { 12784f708321SMichael Hamann static $Indexer; 12791421e548SMichael Hamann if (!isset($Indexer)) { 128000803e56STom N Harris $Indexer = new Doku_Indexer(); 128100803e56STom N Harris } 128200803e56STom N Harris return $Indexer; 128300803e56STom N Harris} 128400803e56STom N Harris 128500803e56STom N Harris/** 128600803e56STom N Harris * Returns words that will be ignored. 128700803e56STom N Harris * 128800803e56STom N Harris * @return array list of stop words 128900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 129000803e56STom N Harris */ 129100803e56STom N Harrisfunction & idx_get_stopwords() { 129200803e56STom N Harris static $stopwords = null; 129300803e56STom N Harris if (is_null($stopwords)) { 129400803e56STom N Harris global $conf; 129500803e56STom N Harris $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 129600803e56STom N Harris if(@file_exists($swfile)){ 129700803e56STom N Harris $stopwords = file($swfile, FILE_IGNORE_NEW_LINES); 129800803e56STom N Harris }else{ 129900803e56STom N Harris $stopwords = array(); 130000803e56STom N Harris } 130100803e56STom N Harris } 130200803e56STom N Harris return $stopwords; 130300803e56STom N Harris} 130400803e56STom N Harris 130500803e56STom N Harris/** 130600803e56STom N Harris * Adds/updates the search index for the given page 130700803e56STom N Harris * 130800803e56STom N Harris * Locking is handled internally. 130900803e56STom N Harris * 131000803e56STom N Harris * @param string $page name of the page to index 13119b41be24STom N Harris * @param boolean $verbose print status messages 1312d041f8dbSMichael Hamann * @param boolean $force force reindexing even when the index is up to date 131300803e56STom N Harris * @return boolean the function completed successfully 131400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 131500803e56STom N Harris */ 1316d041f8dbSMichael Hamannfunction idx_addPage($page, $verbose=false, $force=false) { 13179b41be24STom N Harris $idxtag = metaFN($page,'.indexed'); 1318a23ac4d7SMichael Hamann // check if page was deleted but is still in the index 1319bbc85ee4STom N Harris if (!page_exists($page)) { 1320bbc85ee4STom N Harris if (!@file_exists($idxtag)) { 1321bbc85ee4STom N Harris if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF); 1322bbc85ee4STom N Harris return false; 1323bbc85ee4STom N Harris } 1324bbc85ee4STom N Harris $Indexer = idx_get_indexer(); 1325bbc85ee4STom N Harris $result = $Indexer->deletePage($page); 1326bbc85ee4STom N Harris if ($result === "locked") { 1327bbc85ee4STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 1328bbc85ee4STom N Harris return false; 1329bbc85ee4STom N Harris } 1330bbc85ee4STom N Harris @unlink($idxtag); 1331bbc85ee4STom N Harris return $result; 1332bbc85ee4STom N Harris } 1333a23ac4d7SMichael Hamann 1334a23ac4d7SMichael Hamann // check if indexing needed 1335a23ac4d7SMichael Hamann if(!$force && @file_exists($idxtag)){ 1336a23ac4d7SMichael Hamann if(trim(io_readFile($idxtag)) == idx_get_version()){ 1337a23ac4d7SMichael Hamann $last = @filemtime($idxtag); 1338a23ac4d7SMichael Hamann if($last > @filemtime(wikiFN($page))){ 1339a23ac4d7SMichael Hamann if ($verbose) print("Indexer: index for $page up to date".DOKU_LF); 1340a23ac4d7SMichael Hamann return false; 1341a23ac4d7SMichael Hamann } 1342a23ac4d7SMichael Hamann } 1343a23ac4d7SMichael Hamann } 1344a23ac4d7SMichael Hamann 134565aa8490SMichael Hamann $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED); 1346bbc85ee4STom N Harris if ($indexenabled === false) { 1347bbc85ee4STom N Harris $result = false; 1348bbc85ee4STom N Harris if (@file_exists($idxtag)) { 1349bbc85ee4STom N Harris $Indexer = idx_get_indexer(); 1350bbc85ee4STom N Harris $result = $Indexer->deletePage($page); 1351bbc85ee4STom N Harris if ($result === "locked") { 1352bbc85ee4STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 1353bbc85ee4STom N Harris return false; 1354bbc85ee4STom N Harris } 1355bbc85ee4STom N Harris @unlink($idxtag); 1356bbc85ee4STom N Harris } 1357bbc85ee4STom N Harris if ($verbose) print("Indexer: index disabled for $page".DOKU_LF); 1358bbc85ee4STom N Harris return $result; 1359bbc85ee4STom N Harris } 1360bbc85ee4STom N Harris 136103aafe1cSMichael Hamann $Indexer = idx_get_indexer(); 136203aafe1cSMichael Hamann $pid = $Indexer->getPID($page); 136303aafe1cSMichael Hamann if ($pid === false) { 136403aafe1cSMichael Hamann if ($verbose) print("Indexer: getting the PID failed for $page".DOKU_LF); 136503aafe1cSMichael Hamann return false; 136603aafe1cSMichael Hamann } 136700803e56STom N Harris $body = ''; 136839d6fd30SMichael Hamann $metadata = array(); 136965aa8490SMichael Hamann $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED); 137065aa8490SMichael Hamann if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null) 137139d6fd30SMichael Hamann $metadata['relation_references'] = array_keys($references); 1372a424180eSMichael Hamann else 1373a424180eSMichael Hamann $metadata['relation_references'] = array(); 1374ffec1009SMichael Hamann 1375ffec1009SMichael Hamann if (($media = p_get_metadata($page, 'relation media', METADATA_RENDER_UNLIMITED)) !== null) 1376ffec1009SMichael Hamann $metadata['relation_media'] = array_keys($media); 1377ffec1009SMichael Hamann else 1378ffec1009SMichael Hamann $metadata['relation_media'] = array(); 1379ffec1009SMichael Hamann 138003aafe1cSMichael Hamann $data = compact('page', 'body', 'metadata', 'pid'); 138100803e56STom N Harris $evt = new Doku_Event('INDEXER_PAGE_ADD', $data); 138239d6fd30SMichael Hamann if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page); 138300803e56STom N Harris $evt->advise_after(); 138400803e56STom N Harris unset($evt); 138539d6fd30SMichael Hamann extract($data); 138600803e56STom N Harris 13879b41be24STom N Harris $result = $Indexer->addPageWords($page, $body); 1388e1e1a7e0SMichael Hamann if ($result === "locked") { 13899b41be24STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 13909b41be24STom N Harris return false; 13919b41be24STom N Harris } 1392320f489aSMichael Hamann 1393320f489aSMichael Hamann if ($result) { 139439d6fd30SMichael Hamann $result = $Indexer->addMetaKeys($page, $metadata); 1395320f489aSMichael Hamann if ($result === "locked") { 1396320f489aSMichael Hamann if ($verbose) print("Indexer: locked".DOKU_LF); 1397320f489aSMichael Hamann return false; 1398320f489aSMichael Hamann } 1399320f489aSMichael Hamann } 1400320f489aSMichael Hamann 14019b41be24STom N Harris if ($result) 14029b41be24STom N Harris io_saveFile(metaFN($page,'.indexed'), idx_get_version()); 14039b41be24STom N Harris if ($verbose) { 14049b41be24STom N Harris print("Indexer: finished".DOKU_LF); 14059b41be24STom N Harris return true; 14069b41be24STom N Harris } 14079b41be24STom N Harris return $result; 140800803e56STom N Harris} 140900803e56STom N Harris 141000803e56STom N Harris/** 141100803e56STom N Harris * Find tokens in the fulltext index 141200803e56STom N Harris * 141300803e56STom N Harris * Takes an array of words and will return a list of matching 141400803e56STom N Harris * pages for each one. 1415488dd6ceSAndreas Gohr * 141663773904SAndreas Gohr * Important: No ACL checking is done here! All results are 141763773904SAndreas Gohr * returned, regardless of permissions 141863773904SAndreas Gohr * 1419e3ab6fc5SMichael Hamann * @param array $words list of words to search for 142000803e56STom N Harris * @return array list of pages found, associated with the search terms 1421488dd6ceSAndreas Gohr */ 14229b41be24STom N Harrisfunction idx_lookup(&$words) { 14239b41be24STom N Harris $Indexer = idx_get_indexer(); 142400803e56STom N Harris return $Indexer->lookup($words); 1425488dd6ceSAndreas Gohr} 1426488dd6ceSAndreas Gohr 1427488dd6ceSAndreas Gohr/** 142800803e56STom N Harris * Split a string into tokens 1429488dd6ceSAndreas Gohr * 1430488dd6ceSAndreas Gohr */ 143100803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) { 14329b41be24STom N Harris $Indexer = idx_get_indexer(); 143300803e56STom N Harris return $Indexer->tokenizer($string, $wc); 1434488dd6ceSAndreas Gohr} 143500803e56STom N Harris 143600803e56STom N Harris/* For compatibility */ 1437488dd6ceSAndreas Gohr 1438f5eb7cf0SAndreas Gohr/** 143900803e56STom N Harris * Read the list of words in an index (if it exists). 1440f5eb7cf0SAndreas Gohr * 14414e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 1442f5eb7cf0SAndreas Gohr */ 144300803e56STom N Harrisfunction idx_getIndex($idx, $suffix) { 14441c07b9e6STom N Harris global $conf; 144500803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 144600803e56STom N Harris if (!@file_exists($fn)) return array(); 144700803e56STom N Harris return file($fn); 144800803e56STom N Harris} 1449f5eb7cf0SAndreas Gohr 145000803e56STom N Harris/** 145100803e56STom N Harris * Get the list of lengths indexed in the wiki. 145200803e56STom N Harris * 145300803e56STom N Harris * Read the index directory or a cache file and returns 145400803e56STom N Harris * a sorted array of lengths of the words used in the wiki. 145500803e56STom N Harris * 145600803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 145700803e56STom N Harris */ 145800803e56STom N Harrisfunction idx_listIndexLengths() { 145900803e56STom N Harris global $conf; 146000803e56STom N Harris // testing what we have to do, create a cache file or not. 146100803e56STom N Harris if ($conf['readdircache'] == 0) { 146200803e56STom N Harris $docache = false; 14631c07b9e6STom N Harris } else { 146400803e56STom N Harris clearstatcache(); 146500803e56STom N Harris if (@file_exists($conf['indexdir'].'/lengths.idx') 146600803e56STom N Harris && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) { 146700803e56STom N Harris if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) { 146800803e56STom N Harris $idx = array(); 146900803e56STom N Harris foreach ($lengths as $length) { 147000803e56STom N Harris $idx[] = (int)$length; 147100803e56STom N Harris } 147200803e56STom N Harris return $idx; 1473f5eb7cf0SAndreas Gohr } 14741c07b9e6STom N Harris } 147500803e56STom N Harris $docache = true; 147600803e56STom N Harris } 14774e1bf408STom N Harris 147800803e56STom N Harris if ($conf['readdircache'] == 0 || $docache) { 147900803e56STom N Harris $dir = @opendir($conf['indexdir']); 148000803e56STom N Harris if ($dir === false) 148100803e56STom N Harris return array(); 148226f7dbf5SMichael Hamann $idx = array(); 148300803e56STom N Harris while (($f = readdir($dir)) !== false) { 148400803e56STom N Harris if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') { 148500803e56STom N Harris $i = substr($f, 1, -4); 148600803e56STom N Harris if (is_numeric($i)) 148700803e56STom N Harris $idx[] = (int)$i; 148800803e56STom N Harris } 148900803e56STom N Harris } 149000803e56STom N Harris closedir($dir); 149100803e56STom N Harris sort($idx); 149200803e56STom N Harris // save this in a file 149300803e56STom N Harris if ($docache) { 149400803e56STom N Harris $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w'); 149500803e56STom N Harris @fwrite($handle, implode("\n", $idx)); 149600803e56STom N Harris @fclose($handle); 149700803e56STom N Harris } 149800803e56STom N Harris return $idx; 149900803e56STom N Harris } 150000803e56STom N Harris 150100803e56STom N Harris return array(); 150200803e56STom N Harris} 150300803e56STom N Harris 150400803e56STom N Harris/** 150500803e56STom N Harris * Get the word lengths that have been indexed. 150600803e56STom N Harris * 150700803e56STom N Harris * Reads the index directory and returns an array of lengths 150800803e56STom N Harris * that there are indices for. 150900803e56STom N Harris * 151000803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 151100803e56STom N Harris */ 151200803e56STom N Harrisfunction idx_indexLengths($filter) { 151300803e56STom N Harris global $conf; 151400803e56STom N Harris $idx = array(); 151500803e56STom N Harris if (is_array($filter)) { 151600803e56STom N Harris // testing if index files exist only 151700803e56STom N Harris $path = $conf['indexdir']."/i"; 151800803e56STom N Harris foreach ($filter as $key => $value) { 151900803e56STom N Harris if (@file_exists($path.$key.'.idx')) 152000803e56STom N Harris $idx[] = $key; 152100803e56STom N Harris } 1522f5eb7cf0SAndreas Gohr } else { 152300803e56STom N Harris $lengths = idx_listIndexLengths(); 152400803e56STom N Harris foreach ($lengths as $key => $length) { 152500803e56STom N Harris // keep all the values equal or superior 152600803e56STom N Harris if ((int)$length >= (int)$filter) 152700803e56STom N Harris $idx[] = $length; 1528f5eb7cf0SAndreas Gohr } 152900803e56STom N Harris } 153000803e56STom N Harris return $idx; 1531f5eb7cf0SAndreas Gohr} 1532f5eb7cf0SAndreas Gohr 153300803e56STom N Harris/** 153400803e56STom N Harris * Clean a name of a key for use as a file name. 153500803e56STom N Harris * 153600803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's 153700803e56STom N Harris * not a letter, number, or underscore. 153800803e56STom N Harris * 153900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 154000803e56STom N Harris */ 154100803e56STom N Harrisfunction idx_cleanName($name) { 154200803e56STom N Harris $name = utf8_romanize(trim((string)$name)); 154300803e56STom N Harris $name = preg_replace('#[ \./\\:-]+#', '_', $name); 154400803e56STom N Harris $name = preg_replace('/[^A-Za-z0-9_]/', '', $name); 154500803e56STom N Harris return strtolower($name); 1546f5eb7cf0SAndreas Gohr} 1547f5eb7cf0SAndreas Gohr 154800803e56STom N Harris//Setup VIM: ex: et ts=4 : 1549