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 107c2ef4e8STom N Harris// Version tag used to force rebuild on upgrade 11*e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;define('INDEXER_VERSION', 8); 127c2ef4e8STom N Harris 1333815ce2SChris Smith// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens) 14d3fb3219SAndreas Gohrif (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2); 1533815ce2SChris Smith 1693a60ad2SAndreas Gohr// Asian characters are handled as words. The following regexp defines the 1793a60ad2SAndreas Gohr// Unicode-Ranges for Asian characters 1893a60ad2SAndreas Gohr// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block 1993a60ad2SAndreas Gohr// I'm no language expert. If you think some ranges are wrongly chosen or 2093a60ad2SAndreas Gohr// a range is missing, please contact me 21d5b23302STom N Harrisdefine('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai 22d5b23302STom N Harrisdefine('IDX_ASIAN2','['. 23d5b23302STom N Harris '\x{2E80}-\x{3040}'. // CJK -> Hangul 24d5b23302STom N Harris '\x{309D}-\x{30A0}'. 25a0c5c349STom N Harris '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'. 2693a60ad2SAndreas Gohr '\x{F900}-\x{FAFF}'. // CJK Compatibility Ideographs 2793a60ad2SAndreas Gohr '\x{FE30}-\x{FE4F}'. // CJK Compatibility Forms 28ae6c4ec0SDanny Lin "\xF0\xA0\x80\x80-\xF0\xAA\x9B\x9F". // CJK Extension B 29ae6c4ec0SDanny Lin "\xF0\xAA\x9C\x80-\xF0\xAB\x9C\xBF". // CJK Extension C 30ae6c4ec0SDanny Lin "\xF0\xAB\x9D\x80-\xF0\xAB\xA0\x9F". // CJK Extension D 31ae6c4ec0SDanny Lin "\xF0\xAF\xA0\x80-\xF0\xAF\xAB\xBF". // CJK Compatibility Supplement 3293a60ad2SAndreas Gohr ']'); 33d5b23302STom N Harrisdefine('IDX_ASIAN3','['. // Hiragana/Katakana (can be two characters) 34d5b23302STom N Harris '\x{3042}\x{3044}\x{3046}\x{3048}'. 35d5b23302STom N Harris '\x{304A}-\x{3062}\x{3064}-\x{3082}'. 36d5b23302STom N Harris '\x{3084}\x{3086}\x{3088}-\x{308D}'. 37d5b23302STom N Harris '\x{308F}-\x{3094}'. 38d5b23302STom N Harris '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'. 39d5b23302STom N Harris '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'. 40d5b23302STom N Harris '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'. 41d5b23302STom N Harris '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'. 42d5b23302STom N Harris ']['. 43d5b23302STom N Harris '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'. 44d5b23302STom N Harris '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'. 45d5b23302STom N Harris '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'. 46d5b23302STom N Harris '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'. 47d5b23302STom N Harris '\x{31F0}-\x{31FF}'. 48d5b23302STom N Harris ']?'); 49699b8a0bSAndreas Gohrdefine('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')'); 5093a60ad2SAndreas Gohr 51b4ce25e9SAndreas Gohr/** 527c2ef4e8STom N Harris * Version of the indexer taking into consideration the external tokenizer. 537c2ef4e8STom N Harris * The indexer is only compatible with data written by the same version. 547c2ef4e8STom N Harris * 558cd4c12fSAndreas Gohr * @triggers INDEXER_VERSION_GET 56d0d6fe1bSTom N Harris * Plugins that modify what gets indexed should hook this event and 57d0d6fe1bSTom N Harris * add their version info to the event data like so: 58d0d6fe1bSTom N Harris * $data[$plugin_name] = $plugin_version; 59d0d6fe1bSTom N Harris * 607c2ef4e8STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 618605afb1SMichael Hamann * @author Michael Hamann <michael@content-space.de> 6242ea7f44SGerrit Uitslag * 6342ea7f44SGerrit Uitslag * @return int|string 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> 8742ea7f44SGerrit Uitslag * 8842ea7f44SGerrit Uitslag * @param string $w 8942ea7f44SGerrit Uitslag * @return int 90d5b23302STom N Harris */ 91d5b23302STom N Harrisfunction wordlen($w){ 92d5b23302STom N Harris $l = strlen($w); 93d5b23302STom N Harris // If left alone, all chinese "words" will get put into w3.idx 94d5b23302STom N Harris // So the "length" of a "word" is faked 954b9792c6STom N Harris if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) { 964b9792c6STom N Harris foreach($leadbytes[0] as $b) 974b9792c6STom N Harris $l += ord($b) - 0xE1; 984b9792c6STom N Harris } 99d5b23302STom N Harris return $l; 100d5b23302STom N Harris} 101d5b23302STom N Harris 102d5b23302STom N Harris/** 10300803e56STom N Harris * Class that encapsulates operations on the indexer database. 104579b0f7eSTNHarris * 105579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org> 106579b0f7eSTNHarris */ 10700803e56STom N Harrisclass Doku_Indexer { 1083d2ce006SMichael Hamann /** 1093d2ce006SMichael Hamann * @var array $pidCache Cache for getPID() 1103d2ce006SMichael Hamann */ 1113d2ce006SMichael Hamann protected $pidCache = array(); 112579b0f7eSTNHarris 113579b0f7eSTNHarris /** 11400803e56STom N Harris * Adds the contents of a page to the fulltext index 115dd35e9c9SAndreas Gohr * 11600803e56STom N Harris * The added text replaces previous words for the same page. 11700803e56STom N Harris * An empty value erases the page. 11800803e56STom N Harris * 11900803e56STom N Harris * @param string $page a page name 12000803e56STom N Harris * @param string $text the body of the page 12142ea7f44SGerrit Uitslag * @return string|boolean the function completed successfully 12242ea7f44SGerrit Uitslag * 12300803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 124dd35e9c9SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 125dd35e9c9SAndreas Gohr */ 12600803e56STom N Harris public function addPageWords($page, $text) { 12780fb93f6STom N Harris if (!$this->lock()) 1289b41be24STom N Harris return "locked"; 12900803e56STom N Harris 13000803e56STom N Harris // load known documents 13103aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 1325981eb09STom N Harris if ($pid === false) { 13380fb93f6STom N Harris $this->unlock(); 13400803e56STom N Harris return false; 13500803e56STom N Harris } 13600803e56STom N Harris 13700803e56STom N Harris $pagewords = array(); 13800803e56STom N Harris // get word usage in page 13980fb93f6STom N Harris $words = $this->getPageWords($text); 14000803e56STom N Harris if ($words === false) { 14180fb93f6STom N Harris $this->unlock(); 14200803e56STom N Harris return false; 14300803e56STom N Harris } 14400803e56STom N Harris 14500803e56STom N Harris if (!empty($words)) { 14600803e56STom N Harris foreach (array_keys($words) as $wlen) { 14780fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 14800803e56STom N Harris foreach ($words[$wlen] as $wid => $freq) { 14900803e56STom N Harris $idx = ($wid<count($index)) ? $index[$wid] : ''; 15080fb93f6STom N Harris $index[$wid] = $this->updateTuple($idx, $pid, $freq); 15100803e56STom N Harris $pagewords[] = "$wlen*$wid"; 15200803e56STom N Harris } 15380fb93f6STom N Harris if (!$this->saveIndex('i', $wlen, $index)) { 15480fb93f6STom N Harris $this->unlock(); 15500803e56STom N Harris return false; 15600803e56STom N Harris } 15700803e56STom N Harris } 15800803e56STom N Harris } 15900803e56STom N Harris 16000803e56STom N Harris // Remove obsolete index entries 16180fb93f6STom N Harris $pageword_idx = $this->getIndexKey('pageword', '', $pid); 16200803e56STom N Harris if ($pageword_idx !== '') { 16300803e56STom N Harris $oldwords = explode(':',$pageword_idx); 16400803e56STom N Harris $delwords = array_diff($oldwords, $pagewords); 16500803e56STom N Harris $upwords = array(); 16600803e56STom N Harris foreach ($delwords as $word) { 16700803e56STom N Harris if ($word != '') { 16800803e56STom N Harris list($wlen,$wid) = explode('*', $word); 16900803e56STom N Harris $wid = (int)$wid; 17000803e56STom N Harris $upwords[$wlen][] = $wid; 17100803e56STom N Harris } 17200803e56STom N Harris } 17300803e56STom N Harris foreach ($upwords as $wlen => $widx) { 17480fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 17500803e56STom N Harris foreach ($widx as $wid) { 17680fb93f6STom N Harris $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 17700803e56STom N Harris } 17880fb93f6STom N Harris $this->saveIndex('i', $wlen, $index); 17900803e56STom N Harris } 18000803e56STom N Harris } 18100803e56STom N Harris // Save the reverse index 18200803e56STom N Harris $pageword_idx = join(':', $pagewords); 18380fb93f6STom N Harris if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) { 18480fb93f6STom N Harris $this->unlock(); 18500803e56STom N Harris return false; 18600803e56STom N Harris } 18700803e56STom N Harris 18880fb93f6STom N Harris $this->unlock(); 189dd35e9c9SAndreas Gohr return true; 190dd35e9c9SAndreas Gohr } 191dd35e9c9SAndreas Gohr 192dd35e9c9SAndreas Gohr /** 19300803e56STom N Harris * Split the words in a page and add them to the index. 19444ca0adfSAndreas Gohr * 195b9d8cc1eSTom N Harris * @param string $text content of the page 196b9d8cc1eSTom N Harris * @return array list of word IDs and number of times used 19742ea7f44SGerrit Uitslag * 19844ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 19917f42b01SChris Smith * @author Christopher Smith <chris@jalakai.co.uk> 20000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 201b4ce25e9SAndreas Gohr */ 20280fb93f6STom N Harris protected function getPageWords($text) { 20344ca0adfSAndreas Gohr 20400803e56STom N Harris $tokens = $this->tokenizer($text); 20517f42b01SChris Smith $tokens = array_count_values($tokens); // count the frequency of each token 20617f42b01SChris Smith 20717f42b01SChris Smith $words = array(); 2084e1bf408STom N Harris foreach ($tokens as $w=>$c) { 209d5b23302STom N Harris $l = wordlen($w); 210579b0f7eSTNHarris if (isset($words[$l])){ 2114e1bf408STom N Harris $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0); 21217f42b01SChris Smith }else{ 2134e1bf408STom N Harris $words[$l] = array($w => $c); 21417f42b01SChris Smith } 21517f42b01SChris Smith } 21617f42b01SChris Smith 217579b0f7eSTNHarris // arrive here with $words = array(wordlen => array(word => frequency)) 218e5e50383SMichael Hamann $word_idx_modified = false; 219b4ce25e9SAndreas Gohr $index = array(); //resulting index 220579b0f7eSTNHarris foreach (array_keys($words) as $wlen) { 22180fb93f6STom N Harris $word_idx = $this->getIndex('w', $wlen); 222579b0f7eSTNHarris foreach ($words[$wlen] as $word => $freq) { 2235a1d0548SMichael Hamann $word = (string)$word; 224a8dba452SMichael Hamann $wid = array_search($word, $word_idx, true); 22500803e56STom N Harris if ($wid === false) { 226d5b23302STom N Harris $wid = count($word_idx); 22700803e56STom N Harris $word_idx[] = $word; 228e5e50383SMichael Hamann $word_idx_modified = true; 229b4ce25e9SAndreas Gohr } 230579b0f7eSTNHarris if (!isset($index[$wlen])) 231579b0f7eSTNHarris $index[$wlen] = array(); 232579b0f7eSTNHarris $index[$wlen][$wid] = $freq; 23344ca0adfSAndreas Gohr } 23400803e56STom N Harris // save back the word index 23580fb93f6STom N Harris if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx)) 23644ca0adfSAndreas Gohr return false; 23744ca0adfSAndreas Gohr } 238b4ce25e9SAndreas Gohr 239b4ce25e9SAndreas Gohr return $index; 240b4ce25e9SAndreas Gohr } 241b4ce25e9SAndreas Gohr 24244ca0adfSAndreas Gohr /** 243e1e1a7e0SMichael Hamann * Add/update keys to/of the metadata index. 24444ca0adfSAndreas Gohr * 24500803e56STom N Harris * Adding new keys does not remove other keys for the page. 24600803e56STom N Harris * An empty value will erase the key. 24700803e56STom N Harris * The $key parameter can be an array to add multiple keys. $value will 24800803e56STom N Harris * not be used if $key is an array. 24944ca0adfSAndreas Gohr * 25000803e56STom N Harris * @param string $page a page name 25100803e56STom N Harris * @param mixed $key a key string or array of key=>value pairs 25200803e56STom N Harris * @param mixed $value the value or list of values 25342ea7f44SGerrit Uitslag * @return boolean|string the function completed successfully 25442ea7f44SGerrit Uitslag * 25500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 256e1e1a7e0SMichael Hamann * @author Michael Hamann <michael@content-space.de> 25744ca0adfSAndreas Gohr */ 25800803e56STom N Harris public function addMetaKeys($page, $key, $value=null) { 25900803e56STom N Harris if (!is_array($key)) { 26000803e56STom N Harris $key = array($key => $value); 26100803e56STom N Harris } elseif (!is_null($value)) { 26200803e56STom N Harris // $key is array, but $value is not null 26300803e56STom N Harris trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING); 26400803e56STom N Harris } 26500803e56STom N Harris 26680fb93f6STom N Harris if (!$this->lock()) 267e1e1a7e0SMichael Hamann return "locked"; 268b4ce25e9SAndreas Gohr 269488dd6ceSAndreas Gohr // load known documents 27003aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 27100803e56STom N Harris if ($pid === false) { 27280fb93f6STom N Harris $this->unlock(); 273579b0f7eSTNHarris return false; 27444ca0adfSAndreas Gohr } 27500803e56STom N Harris 276c1209673STom N Harris // Special handling for titles so the index file is simpler 277c1209673STom N Harris if (array_key_exists('title', $key)) { 278c1209673STom N Harris $value = $key['title']; 279e1ecd6fdSChristopher Smith if (is_array($value)) { 280c1209673STom N Harris $value = $value[0]; 281e1ecd6fdSChristopher Smith } 28280fb93f6STom N Harris $this->saveIndexKey('title', '', $pid, $value); 283c1209673STom N Harris unset($key['title']); 284c1209673STom N Harris } 285c1209673STom N Harris 28600803e56STom N Harris foreach ($key as $name => $values) { 28700803e56STom N Harris $metaname = idx_cleanName($name); 28880fb93f6STom N Harris $this->addIndexKey('metadata', '', $metaname); 289b9d8cc1eSTom N Harris $metaidx = $this->getIndex($metaname.'_i', ''); 290b9d8cc1eSTom N Harris $metawords = $this->getIndex($metaname.'_w', ''); 29100803e56STom N Harris $addwords = false; 292e1e1a7e0SMichael Hamann 293e1e1a7e0SMichael Hamann if (!is_array($values)) $values = array($values); 294e1e1a7e0SMichael Hamann 295b9d8cc1eSTom N Harris $val_idx = $this->getIndexKey($metaname.'_p', '', $pid); 2965e0da3ceSPhy if ($val_idx !== '') { 297e1e1a7e0SMichael Hamann $val_idx = explode(':', $val_idx); 298e1e1a7e0SMichael Hamann // -1 means remove, 0 keep, 1 add 299e1e1a7e0SMichael Hamann $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1)); 300e1e1a7e0SMichael Hamann } else { 301e1e1a7e0SMichael Hamann $val_idx = array(); 302e1e1a7e0SMichael Hamann } 303e1e1a7e0SMichael Hamann 30400803e56STom N Harris foreach ($values as $val) { 30500803e56STom N Harris $val = (string)$val; 30600803e56STom N Harris if ($val !== "") { 307a8dba452SMichael Hamann $id = array_search($val, $metawords, true); 30800803e56STom N Harris if ($id === false) { 309e1ecd6fdSChristopher Smith // didn't find $val, so we'll add it to the end of metawords and create a placeholder in metaidx 31000803e56STom N Harris $id = count($metawords); 31100803e56STom N Harris $metawords[$id] = $val; 312e1ecd6fdSChristopher Smith $metaidx[$id] = ''; 31300803e56STom N Harris $addwords = true; 314d5b23302STom N Harris } 315e1e1a7e0SMichael Hamann // test if value is already in the index 31639134585SChristopher Smith if (isset($val_idx[$id]) && $val_idx[$id] <= 0){ 317e1e1a7e0SMichael Hamann $val_idx[$id] = 0; 31839134585SChristopher Smith } else { // else add it 319e1e1a7e0SMichael Hamann $val_idx[$id] = 1; 32044ca0adfSAndreas Gohr } 321579b0f7eSTNHarris } 32239134585SChristopher Smith } 323e1e1a7e0SMichael Hamann 32439134585SChristopher Smith if ($addwords) { 32580fb93f6STom N Harris $this->saveIndex($metaname.'_w', '', $metawords); 32639134585SChristopher Smith } 327e1e1a7e0SMichael Hamann $vals_changed = false; 328e1e1a7e0SMichael Hamann foreach ($val_idx as $id => $action) { 329e1e1a7e0SMichael Hamann if ($action == -1) { 33080fb93f6STom N Harris $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0); 331e1e1a7e0SMichael Hamann $vals_changed = true; 332e1e1a7e0SMichael Hamann unset($val_idx[$id]); 333e1e1a7e0SMichael Hamann } elseif ($action == 1) { 33480fb93f6STom N Harris $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1); 335e1e1a7e0SMichael Hamann $vals_changed = true; 336e1e1a7e0SMichael Hamann } 337e1e1a7e0SMichael Hamann } 338e1e1a7e0SMichael Hamann 339e1e1a7e0SMichael Hamann if ($vals_changed) { 34080fb93f6STom N Harris $this->saveIndex($metaname.'_i', '', $metaidx); 341e1e1a7e0SMichael Hamann $val_idx = implode(':', array_keys($val_idx)); 34280fb93f6STom N Harris $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx); 343b6344591STom N Harris } 344e1e1a7e0SMichael Hamann 34500803e56STom N Harris unset($metaidx); 34600803e56STom N Harris unset($metawords); 347a0c5c349STom N Harris } 348e1e1a7e0SMichael Hamann 34980fb93f6STom N Harris $this->unlock(); 350579b0f7eSTNHarris return true; 35144ca0adfSAndreas Gohr } 35244ca0adfSAndreas Gohr 35344ca0adfSAndreas Gohr /** 354af73bba6SMichael Hamann * Rename a page in the search index without changing the indexed content. This function doesn't check if the 355af73bba6SMichael 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 356af73bba6SMichael Hamann * indexer and it deletes all previously indexed content of the new page. 3575eb9e867SMichael Hamann * 3585eb9e867SMichael Hamann * @param string $oldpage The old page name 3595eb9e867SMichael Hamann * @param string $newpage The new page name 3605eb9e867SMichael Hamann * @return string|bool If the page was successfully renamed, can be a message in the case of an error 3615eb9e867SMichael Hamann */ 3625eb9e867SMichael Hamann public function renamePage($oldpage, $newpage) { 3635eb9e867SMichael Hamann if (!$this->lock()) return 'locked'; 3645eb9e867SMichael Hamann 3655eb9e867SMichael Hamann $pages = $this->getPages(); 3665eb9e867SMichael Hamann 367a8dba452SMichael Hamann $id = array_search($oldpage, $pages, true); 3685eb9e867SMichael Hamann if ($id === false) { 3695eb9e867SMichael Hamann $this->unlock(); 3705eb9e867SMichael Hamann return 'page is not in index'; 3715eb9e867SMichael Hamann } 3725eb9e867SMichael Hamann 373a8dba452SMichael Hamann $new_id = array_search($newpage, $pages, true); 3745eb9e867SMichael Hamann if ($new_id !== false) { 3755eb9e867SMichael Hamann // make sure the page is not in the index anymore 376bc27f3e2SMichael Hamann if ($this->deletePageNoLock($newpage) !== true) { 377bc27f3e2SMichael Hamann return false; 378bc27f3e2SMichael Hamann } 3795eb9e867SMichael Hamann 3805eb9e867SMichael Hamann $pages[$new_id] = 'deleted:'.time().rand(0, 9999); 3815eb9e867SMichael Hamann } 3825eb9e867SMichael Hamann 3835eb9e867SMichael Hamann $pages[$id] = $newpage; 3845eb9e867SMichael Hamann 3855eb9e867SMichael Hamann // update index 3865eb9e867SMichael Hamann if (!$this->saveIndex('page', '', $pages)) { 3875eb9e867SMichael Hamann $this->unlock(); 3885eb9e867SMichael Hamann return false; 3895eb9e867SMichael Hamann } 3905eb9e867SMichael Hamann 3915eb9e867SMichael Hamann // reset the pid cache 3925eb9e867SMichael Hamann $this->pidCache = array(); 3935eb9e867SMichael Hamann 3945eb9e867SMichael Hamann $this->unlock(); 3955eb9e867SMichael Hamann return true; 3965eb9e867SMichael Hamann } 3975eb9e867SMichael Hamann 3985eb9e867SMichael Hamann /** 3995eb9e867SMichael Hamann * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages 4005eb9e867SMichael Hamann * will be updated. 4015eb9e867SMichael Hamann * 4025eb9e867SMichael Hamann * @param string $key The metadata key of which a value shall be changed 4035eb9e867SMichael Hamann * @param string $oldvalue The old value that shall be renamed 40464159a61SAndreas Gohr * @param string $newvalue The new value to which the old value shall be renamed, if exists values will be merged 4055eb9e867SMichael Hamann * @return bool|string If renaming the value has been successful, false or error message on error. 4065eb9e867SMichael Hamann */ 4075eb9e867SMichael Hamann public function renameMetaValue($key, $oldvalue, $newvalue) { 4085eb9e867SMichael Hamann if (!$this->lock()) return 'locked'; 4095eb9e867SMichael Hamann 4105eb9e867SMichael Hamann // change the relation references index 4115eb9e867SMichael Hamann $metavalues = $this->getIndex($key, '_w'); 412a8dba452SMichael Hamann $oldid = array_search($oldvalue, $metavalues, true); 4135eb9e867SMichael Hamann if ($oldid !== false) { 414a8dba452SMichael Hamann $newid = array_search($newvalue, $metavalues, true); 4155eb9e867SMichael Hamann if ($newid !== false) { 4165eb9e867SMichael Hamann // free memory 4175eb9e867SMichael Hamann unset ($metavalues); 4185eb9e867SMichael Hamann 4195eb9e867SMichael Hamann // okay, now we have two entries for the same value. we need to merge them. 4209e64ca0dSMichael Hamann $indexline = $this->getIndexKey($key.'_i', '', $oldid); 4215eb9e867SMichael Hamann if ($indexline != '') { 4229e64ca0dSMichael Hamann $newindexline = $this->getIndexKey($key.'_i', '', $newid); 4239e64ca0dSMichael Hamann $pagekeys = $this->getIndex($key.'_p', ''); 4245eb9e867SMichael Hamann $parts = explode(':', $indexline); 4255eb9e867SMichael Hamann foreach ($parts as $part) { 4265eb9e867SMichael Hamann list($id, $count) = explode('*', $part); 4275eb9e867SMichael Hamann $newindexline = $this->updateTuple($newindexline, $id, $count); 4285eb9e867SMichael Hamann 4295eb9e867SMichael Hamann $keyline = explode(':', $pagekeys[$id]); 4305eb9e867SMichael Hamann // remove old meta value 4315eb9e867SMichael Hamann $keyline = array_diff($keyline, array($oldid)); 4325eb9e867SMichael Hamann // add new meta value when not already present 4335eb9e867SMichael Hamann if (!in_array($newid, $keyline)) { 4345eb9e867SMichael Hamann array_push($keyline, $newid); 4355eb9e867SMichael Hamann } 4365eb9e867SMichael Hamann $pagekeys[$id] = implode(':', $keyline); 4375eb9e867SMichael Hamann } 4389e64ca0dSMichael Hamann $this->saveIndex($key.'_p', '', $pagekeys); 4395eb9e867SMichael Hamann unset($pagekeys); 4409e64ca0dSMichael Hamann $this->saveIndexKey($key.'_i', '', $oldid, ''); 4419e64ca0dSMichael Hamann $this->saveIndexKey($key.'_i', '', $newid, $newindexline); 4425eb9e867SMichael Hamann } 4435eb9e867SMichael Hamann } else { 4445eb9e867SMichael Hamann $metavalues[$oldid] = $newvalue; 4459e64ca0dSMichael Hamann if (!$this->saveIndex($key.'_w', '', $metavalues)) { 4465eb9e867SMichael Hamann $this->unlock(); 4475eb9e867SMichael Hamann return false; 4485eb9e867SMichael Hamann } 4495eb9e867SMichael Hamann } 4505eb9e867SMichael Hamann } 4515eb9e867SMichael Hamann 4525eb9e867SMichael Hamann $this->unlock(); 4535eb9e867SMichael Hamann return true; 4545eb9e867SMichael Hamann } 45525adeb91SMichael Hamann 4565eb9e867SMichael Hamann /** 45700803e56STom N Harris * Remove a page from the index 45844ca0adfSAndreas Gohr * 45900803e56STom N Harris * Erases entries in all known indexes. 46044ca0adfSAndreas Gohr * 46100803e56STom N Harris * @param string $page a page name 46242ea7f44SGerrit Uitslag * @return string|boolean the function completed successfully 46342ea7f44SGerrit Uitslag * 46400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 46544ca0adfSAndreas Gohr */ 46600803e56STom N Harris public function deletePage($page) { 46780fb93f6STom N Harris if (!$this->lock()) 468bbc85ee4STom N Harris return "locked"; 469bbc85ee4STom N Harris 47025adeb91SMichael Hamann $result = $this->deletePageNoLock($page); 47125adeb91SMichael Hamann 47225adeb91SMichael Hamann $this->unlock(); 47325adeb91SMichael Hamann 47425adeb91SMichael Hamann return $result; 47525adeb91SMichael Hamann } 47625adeb91SMichael Hamann 47725adeb91SMichael Hamann /** 47825adeb91SMichael Hamann * Remove a page from the index without locking the index, only use this function if the index is already locked 47925adeb91SMichael Hamann * 48025adeb91SMichael Hamann * Erases entries in all known indexes. 48125adeb91SMichael Hamann * 48225adeb91SMichael Hamann * @param string $page a page name 48325adeb91SMichael Hamann * @return boolean the function completed successfully 48442ea7f44SGerrit Uitslag * 48525adeb91SMichael Hamann * @author Tom N Harris <tnharris@whoopdedo.org> 48625adeb91SMichael Hamann */ 48725adeb91SMichael Hamann protected function deletePageNoLock($page) { 488bbc85ee4STom N Harris // load known documents 48903aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 4905981eb09STom N Harris if ($pid === false) { 491bbc85ee4STom N Harris return false; 492bbc85ee4STom N Harris } 493bbc85ee4STom N Harris 494bbc85ee4STom N Harris // Remove obsolete index entries 49580fb93f6STom N Harris $pageword_idx = $this->getIndexKey('pageword', '', $pid); 496bbc85ee4STom N Harris if ($pageword_idx !== '') { 497bbc85ee4STom N Harris $delwords = explode(':',$pageword_idx); 498bbc85ee4STom N Harris $upwords = array(); 499bbc85ee4STom N Harris foreach ($delwords as $word) { 500bbc85ee4STom N Harris if ($word != '') { 501bbc85ee4STom N Harris list($wlen,$wid) = explode('*', $word); 502bbc85ee4STom N Harris $wid = (int)$wid; 503bbc85ee4STom N Harris $upwords[$wlen][] = $wid; 504bbc85ee4STom N Harris } 505bbc85ee4STom N Harris } 506bbc85ee4STom N Harris foreach ($upwords as $wlen => $widx) { 50780fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 508bbc85ee4STom N Harris foreach ($widx as $wid) { 50980fb93f6STom N Harris $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 510bbc85ee4STom N Harris } 51180fb93f6STom N Harris $this->saveIndex('i', $wlen, $index); 512bbc85ee4STom N Harris } 513bbc85ee4STom N Harris } 514bbc85ee4STom N Harris // Save the reverse index 51580fb93f6STom N Harris if (!$this->saveIndexKey('pageword', '', $pid, "")) { 516bbc85ee4STom N Harris return false; 517bbc85ee4STom N Harris } 518bbc85ee4STom N Harris 51980fb93f6STom N Harris $this->saveIndexKey('title', '', $pid, ""); 52080fb93f6STom N Harris $keyidx = $this->getIndex('metadata', ''); 5210604da34STom N Harris foreach ($keyidx as $metaname) { 52280fb93f6STom N Harris $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid)); 52380fb93f6STom N Harris $meta_idx = $this->getIndex($metaname.'_i', ''); 5240604da34STom N Harris foreach ($val_idx as $id) { 525c55c59e3SMichael Hamann if ($id === '') continue; 52680fb93f6STom N Harris $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0); 5270604da34STom N Harris } 52880fb93f6STom N Harris $this->saveIndex($metaname.'_i', '', $meta_idx); 52980fb93f6STom N Harris $this->saveIndexKey($metaname.'_p', '', $pid, ''); 5300604da34STom N Harris } 531bbc85ee4STom N Harris 532bbc85ee4STom N Harris return true; 533d5b23302STom N Harris } 53444ca0adfSAndreas Gohr 535d5b23302STom N Harris /** 5363cf3c7d6SMichael Hamann * Clear the whole index 5373cf3c7d6SMichael Hamann * 5383cf3c7d6SMichael Hamann * @return bool If the index has been cleared successfully 5393cf3c7d6SMichael Hamann */ 5403cf3c7d6SMichael Hamann public function clear() { 5413cf3c7d6SMichael Hamann global $conf; 5423cf3c7d6SMichael Hamann 5433cf3c7d6SMichael Hamann if (!$this->lock()) return false; 5443cf3c7d6SMichael Hamann 5453cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/page.idx'); 5463cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/title.idx'); 5473cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/pageword.idx'); 5483cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/metadata.idx'); 5493cf3c7d6SMichael Hamann $dir = @opendir($conf['indexdir']); 5503cf3c7d6SMichael Hamann if($dir!==false){ 5513cf3c7d6SMichael Hamann while(($f = readdir($dir)) !== false){ 5523cf3c7d6SMichael Hamann if(substr($f,-4)=='.idx' && 5533cf3c7d6SMichael Hamann (substr($f,0,1)=='i' || substr($f,0,1)=='w' 5543cf3c7d6SMichael Hamann || substr($f,-6)=='_w.idx' || substr($f,-6)=='_i.idx' || substr($f,-6)=='_p.idx')) 5553cf3c7d6SMichael Hamann @unlink($conf['indexdir']."/$f"); 5563cf3c7d6SMichael Hamann } 5573cf3c7d6SMichael Hamann } 5583cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/lengths.idx'); 5593cf3c7d6SMichael Hamann 5603cf3c7d6SMichael Hamann // clear the pid cache 5613cf3c7d6SMichael Hamann $this->pidCache = array(); 5623cf3c7d6SMichael Hamann 5633cf3c7d6SMichael Hamann $this->unlock(); 5643cf3c7d6SMichael Hamann return true; 5653cf3c7d6SMichael Hamann } 5663cf3c7d6SMichael Hamann 5673cf3c7d6SMichael Hamann /** 56800803e56STom N Harris * Split the text into words for fulltext search 569d5b23302STom N Harris * 57000803e56STom N Harris * TODO: does this also need &$stopwords ? 571d5b23302STom N Harris * 5728cd4c12fSAndreas Gohr * @triggers INDEXER_TEXT_PREPARE 5738cd4c12fSAndreas Gohr * This event allows plugins to modify the text before it gets tokenized. 5748cd4c12fSAndreas Gohr * Plugins intercepting this event should also intercept INDEX_VERSION_GET 5758cd4c12fSAndreas Gohr * 57600803e56STom N Harris * @param string $text plain text 57700803e56STom N Harris * @param boolean $wc are wildcards allowed? 57800803e56STom N Harris * @return array list of words in the text 57942ea7f44SGerrit Uitslag * 580d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 581d5b23302STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 582d5b23302STom N Harris */ 58300803e56STom N Harris public function tokenizer($text, $wc=false) { 58400803e56STom N Harris $wc = ($wc) ? '' : '\*'; 58500803e56STom N Harris $stopwords =& idx_get_stopwords(); 58600803e56STom N Harris 5878cd4c12fSAndreas Gohr // prepare the text to be tokenized 588*e1d9dcc8SAndreas Gohr $evt = new Event('INDEXER_TEXT_PREPARE', $text); 5898cd4c12fSAndreas Gohr if ($evt->advise_before(true)) { 59000803e56STom N Harris if (preg_match('/[^0-9A-Za-z ]/u', $text)) { 59100803e56STom N Harris // handle asian chars as single words (may fail on older PHP version) 59200803e56STom N Harris $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text); 59300803e56STom N Harris if (!is_null($asia)) $text = $asia; // recover from regexp falure 59422952965SYoBoY } 59522952965SYoBoY } 5968cd4c12fSAndreas Gohr $evt->advise_after(); 5978cd4c12fSAndreas Gohr unset($evt); 5988cd4c12fSAndreas Gohr 599f77fc90dSMichael Hamann $text = strtr($text, 6004f0030ddSAndreas Gohr array( 6014f0030ddSAndreas Gohr "\r" => ' ', 6024f0030ddSAndreas Gohr "\n" => ' ', 6034f0030ddSAndreas Gohr "\t" => ' ', 6044f0030ddSAndreas Gohr "\xC2\xAD" => '', //soft-hyphen 6054f0030ddSAndreas Gohr ) 6064f0030ddSAndreas Gohr ); 60700803e56STom N Harris if (preg_match('/[^0-9A-Za-z ]/u', $text)) 60800803e56STom N Harris $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc); 60922952965SYoBoY 61000803e56STom N Harris $wordlist = explode(' ', $text); 6115f27cb0eSMichael Hamann foreach ($wordlist as $i => $word) { 6125f27cb0eSMichael Hamann $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ? 61300803e56STom N Harris utf8_strtolower($word) : strtolower($word); 6145f27cb0eSMichael Hamann } 6155f27cb0eSMichael Hamann 6165f27cb0eSMichael Hamann foreach ($wordlist as $i => $word) { 617675bf41fSTom N Harris if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) 618a8dba452SMichael Hamann || array_search($word, $stopwords, true) !== false) 619675bf41fSTom N Harris unset($wordlist[$i]); 62022952965SYoBoY } 621675bf41fSTom N Harris return array_values($wordlist); 62222952965SYoBoY } 62322952965SYoBoY 62422952965SYoBoY /** 62503aafe1cSMichael Hamann * Get the numeric PID of a page 62603aafe1cSMichael Hamann * 62703aafe1cSMichael Hamann * @param string $page The page to get the PID for 62803aafe1cSMichael Hamann * @return bool|int The page id on success, false on error 62903aafe1cSMichael Hamann */ 63003aafe1cSMichael Hamann public function getPID($page) { 6313d2ce006SMichael Hamann // return PID without locking when it is in the cache 6323d2ce006SMichael Hamann if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 6333d2ce006SMichael Hamann 63403aafe1cSMichael Hamann if (!$this->lock()) 63503aafe1cSMichael Hamann return false; 63603aafe1cSMichael Hamann 63703aafe1cSMichael Hamann // load known documents 63803aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 63903aafe1cSMichael Hamann if ($pid === false) { 64003aafe1cSMichael Hamann $this->unlock(); 64103aafe1cSMichael Hamann return false; 64203aafe1cSMichael Hamann } 64303aafe1cSMichael Hamann 64403aafe1cSMichael Hamann $this->unlock(); 64503aafe1cSMichael Hamann return $pid; 64603aafe1cSMichael Hamann } 64703aafe1cSMichael Hamann 64803aafe1cSMichael Hamann /** 64903aafe1cSMichael Hamann * Get the numeric PID of a page without locking the index. 65003aafe1cSMichael Hamann * Only use this function when the index is already locked. 65103aafe1cSMichael Hamann * 65203aafe1cSMichael Hamann * @param string $page The page to get the PID for 65303aafe1cSMichael Hamann * @return bool|int The page id on success, false on error 65403aafe1cSMichael Hamann */ 65503aafe1cSMichael Hamann protected function getPIDNoLock($page) { 6563d2ce006SMichael Hamann // avoid expensive addIndexKey operation for the most recently requested pages by using a cache 6573d2ce006SMichael Hamann if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 6583d2ce006SMichael Hamann $pid = $this->addIndexKey('page', '', $page); 6593d2ce006SMichael Hamann // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently 6603d2ce006SMichael Hamann // added item will be requested again 6613d2ce006SMichael Hamann if (count($this->pidCache) > 10) array_shift($this->pidCache); 6623d2ce006SMichael Hamann $this->pidCache[$page] = $pid; 6633d2ce006SMichael Hamann return $pid; 66403aafe1cSMichael Hamann } 66503aafe1cSMichael Hamann 66603aafe1cSMichael Hamann /** 66703aafe1cSMichael Hamann * Get the page id of a numeric PID 66803aafe1cSMichael Hamann * 66903aafe1cSMichael Hamann * @param int $pid The PID to get the page id for 67003aafe1cSMichael Hamann * @return string The page id 67103aafe1cSMichael Hamann */ 67203aafe1cSMichael Hamann public function getPageFromPID($pid) { 67303aafe1cSMichael Hamann return $this->getIndexKey('page', '', $pid); 67403aafe1cSMichael Hamann } 67503aafe1cSMichael Hamann 67603aafe1cSMichael Hamann /** 67700803e56STom N Harris * Find pages in the fulltext index containing the words, 678579b0f7eSTNHarris * 67900803e56STom N Harris * The search words must be pre-tokenized, meaning only letters and 68000803e56STom N Harris * numbers with an optional wildcard 681579b0f7eSTNHarris * 68200803e56STom N Harris * The returned array will have the original tokens as key. The values 68300803e56STom N Harris * in the returned list is an array with the page names as keys and the 684b00bd361STom N Harris * number of times that token appears on the page as value. 68500803e56STom N Harris * 686e3ab6fc5SMichael Hamann * @param array $tokens list of words to search for 68700803e56STom N Harris * @return array list of page names with usage counts 68842ea7f44SGerrit Uitslag * 68900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 69000803e56STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 691579b0f7eSTNHarris */ 6929b41be24STom N Harris public function lookup(&$tokens) { 69300803e56STom N Harris $result = array(); 69480fb93f6STom N Harris $wids = $this->getIndexWords($tokens, $result); 69500803e56STom N Harris if (empty($wids)) return array(); 69600803e56STom N Harris // load known words and documents 69780fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 69800803e56STom N Harris $docs = array(); 69900803e56STom N Harris foreach (array_keys($wids) as $wlen) { 70000803e56STom N Harris $wids[$wlen] = array_unique($wids[$wlen]); 70180fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 70200803e56STom N Harris foreach($wids[$wlen] as $ixid) { 70300803e56STom N Harris if ($ixid < count($index)) 70480fb93f6STom N Harris $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]); 705d5b23302STom N Harris } 706d5b23302STom N Harris } 70700803e56STom N Harris // merge found pages into final result array 70800803e56STom N Harris $final = array(); 70900803e56STom N Harris foreach ($result as $word => $res) { 71000803e56STom N Harris $final[$word] = array(); 71100803e56STom N Harris foreach ($res as $wid) { 712952ab260SMichael Hamann // handle the case when ($ixid < count($index)) has been false 713952ab260SMichael Hamann // and thus $docs[$wid] hasn't been set. 714952ab260SMichael Hamann if (!isset($docs[$wid])) continue; 71500803e56STom N Harris $hits = &$docs[$wid]; 71600803e56STom N Harris foreach ($hits as $hitkey => $hitcnt) { 71700803e56STom N Harris // make sure the document still exists 71800803e56STom N Harris if (!page_exists($hitkey, '', false)) continue; 71900803e56STom N Harris if (!isset($final[$word][$hitkey])) 72000803e56STom N Harris $final[$word][$hitkey] = $hitcnt; 72100803e56STom N Harris else 72200803e56STom N Harris $final[$word][$hitkey] += $hitcnt; 723d5b23302STom N Harris } 724579b0f7eSTNHarris } 725579b0f7eSTNHarris } 72600803e56STom N Harris return $final; 727579b0f7eSTNHarris } 728579b0f7eSTNHarris 729579b0f7eSTNHarris /** 73000803e56STom N Harris * Find pages containing a metadata key. 731d5b23302STom N Harris * 73200803e56STom N Harris * The metadata values are compared as case-sensitive strings. Pass a 73300803e56STom N Harris * callback function that returns true or false to use a different 734b00bd361STom N Harris * comparison function. The function will be called with the $value being 735b00bd361STom N Harris * searched for as the first argument, and the word in the index as the 7361538718dSTom N Harris * second argument. The function preg_match can be used directly if the 7371538718dSTom N Harris * values are regexes. 738d5b23302STom N Harris * 73900803e56STom N Harris * @param string $key name of the metadata key to look for 7401538718dSTom N Harris * @param string $value search term to look for, must be a string or array of strings 74100803e56STom N Harris * @param callback $func comparison function 742b00bd361STom N Harris * @return array lists with page names, keys are query values if $value is array 74342ea7f44SGerrit Uitslag * 74400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 745cd763a5bSMichael Hamann * @author Michael Hamann <michael@content-space.de> 74600803e56STom N Harris */ 747b00bd361STom N Harris public function lookupKey($key, &$value, $func=null) { 748f078bb00STom N Harris if (!is_array($value)) 749f078bb00STom N Harris $value_array = array($value); 750f078bb00STom N Harris else 751f078bb00STom N Harris $value_array =& $value; 752cd763a5bSMichael Hamann 753c1209673STom N Harris // the matching ids for the provided value(s) 754c1209673STom N Harris $value_ids = array(); 755c1209673STom N Harris 756c1209673STom N Harris $metaname = idx_cleanName($key); 757c1209673STom N Harris 758c1209673STom N Harris // get all words in order to search the matching ids 759c1209673STom N Harris if ($key == 'title') { 76080fb93f6STom N Harris $words = $this->getIndex('title', ''); 761c1209673STom N Harris } else { 762b9d8cc1eSTom N Harris $words = $this->getIndex($metaname.'_w', ''); 763c1209673STom N Harris } 764c1209673STom N Harris 765f078bb00STom N Harris if (!is_null($func)) { 7661538718dSTom N Harris foreach ($value_array as $val) { 767f078bb00STom N Harris foreach ($words as $i => $word) { 7681538718dSTom N Harris if (call_user_func_array($func, array($val, $word))) 769c1209673STom N Harris $value_ids[$i][] = $val; 770f078bb00STom N Harris } 771f078bb00STom N Harris } 772f078bb00STom N Harris } else { 773f078bb00STom N Harris foreach ($value_array as $val) { 774f078bb00STom N Harris $xval = $val; 775b6d540bdSTom N Harris $caret = '^'; 776b6d540bdSTom N Harris $dollar = '$'; 777f078bb00STom N Harris // check for wildcards 778f078bb00STom N Harris if (substr($xval, 0, 1) == '*') { 779f078bb00STom N Harris $xval = substr($xval, 1); 780b6d540bdSTom N Harris $caret = ''; 781f078bb00STom N Harris } 782f078bb00STom N Harris if (substr($xval, -1, 1) == '*') { 783f078bb00STom N Harris $xval = substr($xval, 0, -1); 784b6d540bdSTom N Harris $dollar = ''; 785f078bb00STom N Harris } 786b6d540bdSTom N Harris if (!$caret || !$dollar) { 787f078bb00STom N Harris $re = $caret.preg_quote($xval, '/').$dollar; 788f078bb00STom N Harris foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i) 789c1209673STom N Harris $value_ids[$i][] = $val; 790cd763a5bSMichael Hamann } else { 791a8dba452SMichael Hamann if (($i = array_search($val, $words, true)) !== false) 792c1209673STom N Harris $value_ids[$i][] = $val; 793cd763a5bSMichael Hamann } 794cd763a5bSMichael Hamann } 795cd763a5bSMichael Hamann } 796cd763a5bSMichael Hamann 797cd763a5bSMichael Hamann unset($words); // free the used memory 798cd763a5bSMichael Hamann 7997233c152SMichael Hamann // initialize the result so it won't be null 800c1209673STom N Harris $result = array(); 8017233c152SMichael Hamann foreach ($value_array as $val) { 8027233c152SMichael Hamann $result[$val] = array(); 8037233c152SMichael Hamann } 8047233c152SMichael Hamann 80580fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 806cd763a5bSMichael Hamann 807c1209673STom N Harris // Special handling for titles 808c1209673STom N Harris if ($key == 'title') { 809c1209673STom N Harris foreach ($value_ids as $pid => $val_list) { 810c1209673STom N Harris $page = $page_idx[$pid]; 811c1209673STom N Harris foreach ($val_list as $val) { 812c1209673STom N Harris $result[$val][] = $page; 813c1209673STom N Harris } 814c1209673STom N Harris } 815c1209673STom N Harris } else { 816c1209673STom N Harris // load all lines and pages so the used lines can be taken and matched with the pages 817b9d8cc1eSTom N Harris $lines = $this->getIndex($metaname.'_i', ''); 818c1209673STom N Harris 819c1209673STom N Harris foreach ($value_ids as $value_id => $val_list) { 820cd763a5bSMichael Hamann // parse the tuples of the form page_id*1:page2_id*1 and so on, return value 821cd763a5bSMichael Hamann // is an array with page_id => 1, page2_id => 1 etc. so take the keys only 82280fb93f6STom N Harris $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id])); 823c1209673STom N Harris foreach ($val_list as $val) { 824c1209673STom N Harris $result[$val] = array_merge($result[$val], $pages); 825c1209673STom N Harris } 826c1209673STom N Harris } 827cd763a5bSMichael Hamann } 828f078bb00STom N Harris if (!is_array($value)) $result = $result[$value]; 829cd763a5bSMichael Hamann return $result; 83000803e56STom N Harris } 83100803e56STom N Harris 83200803e56STom N Harris /** 83300803e56STom N Harris * Find the index ID of each search term. 83400803e56STom N Harris * 83500803e56STom N Harris * The query terms should only contain valid characters, with a '*' at 83600803e56STom N Harris * either the beginning or end of the word (or both). 83700803e56STom N Harris * The $result parameter can be used to merge the index locations with 83800803e56STom N Harris * the appropriate query term. 83900803e56STom N Harris * 840e3ab6fc5SMichael Hamann * @param array $words The query terms. 841e3ab6fc5SMichael Hamann * @param array $result Set to word => array("length*id" ...) 842d5b23302STom N Harris * @return array Set to length => array(id ...) 84342ea7f44SGerrit Uitslag * 844d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 845d5b23302STom N Harris */ 84680fb93f6STom N Harris protected function getIndexWords(&$words, &$result) { 847d5b23302STom N Harris $tokens = array(); 848d5b23302STom N Harris $tokenlength = array(); 849d5b23302STom N Harris $tokenwild = array(); 850d5b23302STom N Harris foreach ($words as $word) { 851d5b23302STom N Harris $result[$word] = array(); 852b6d540bdSTom N Harris $caret = '^'; 853b6d540bdSTom N Harris $dollar = '$'; 854d5b23302STom N Harris $xword = $word; 855d5b23302STom N Harris $wlen = wordlen($word); 856d5b23302STom N Harris 857d5b23302STom N Harris // check for wildcards 858d5b23302STom N Harris if (substr($xword, 0, 1) == '*') { 859d5b23302STom N Harris $xword = substr($xword, 1); 860b6d540bdSTom N Harris $caret = ''; 861d5b23302STom N Harris $wlen -= 1; 862d5b23302STom N Harris } 863d5b23302STom N Harris if (substr($xword, -1, 1) == '*') { 864d5b23302STom N Harris $xword = substr($xword, 0, -1); 865b6d540bdSTom N Harris $dollar = ''; 866d5b23302STom N Harris $wlen -= 1; 867d5b23302STom N Harris } 868b6d540bdSTom N Harris if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword)) 86900803e56STom N Harris continue; 87000803e56STom N Harris if (!isset($tokens[$xword])) 871d5b23302STom N Harris $tokenlength[$wlen][] = $xword; 872b6d540bdSTom N Harris if (!$caret || !$dollar) { 873f078bb00STom N Harris $re = $caret.preg_quote($xword, '/').$dollar; 87400803e56STom N Harris $tokens[$xword][] = array($word, '/'.$re.'/'); 87500803e56STom N Harris if (!isset($tokenwild[$xword])) 87600803e56STom N Harris $tokenwild[$xword] = $wlen; 87700803e56STom N Harris } else { 878d5b23302STom N Harris $tokens[$xword][] = array($word, null); 879d5b23302STom N Harris } 88000803e56STom N Harris } 881d5b23302STom N Harris asort($tokenwild); 88200803e56STom N Harris // $tokens = array( base word => array( [ query term , regexp ] ... ) ... ) 883d5b23302STom N Harris // $tokenlength = array( base word length => base word ... ) 884d5b23302STom N Harris // $tokenwild = array( base word => base word length ... ) 885d5b23302STom N Harris $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength)); 88680fb93f6STom N Harris $indexes_known = $this->indexLengths($length_filter); 887d5b23302STom N Harris if (!empty($tokenwild)) sort($indexes_known); 888d5b23302STom N Harris // get word IDs 889d5b23302STom N Harris $wids = array(); 890d5b23302STom N Harris foreach ($indexes_known as $ixlen) { 89180fb93f6STom N Harris $word_idx = $this->getIndex('w', $ixlen); 892d5b23302STom N Harris // handle exact search 893d5b23302STom N Harris if (isset($tokenlength[$ixlen])) { 894d5b23302STom N Harris foreach ($tokenlength[$ixlen] as $xword) { 895a8dba452SMichael Hamann $wid = array_search($xword, $word_idx, true); 89600803e56STom N Harris if ($wid !== false) { 897d5b23302STom N Harris $wids[$ixlen][] = $wid; 898d5b23302STom N Harris foreach ($tokens[$xword] as $w) 899d5b23302STom N Harris $result[$w[0]][] = "$ixlen*$wid"; 900d5b23302STom N Harris } 901d5b23302STom N Harris } 902d5b23302STom N Harris } 903d5b23302STom N Harris // handle wildcard search 904d5b23302STom N Harris foreach ($tokenwild as $xword => $wlen) { 905d5b23302STom N Harris if ($wlen >= $ixlen) break; 906d5b23302STom N Harris foreach ($tokens[$xword] as $w) { 907d5b23302STom N Harris if (is_null($w[1])) continue; 908d5b23302STom N Harris foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) { 909d5b23302STom N Harris $wids[$ixlen][] = $wid; 910d5b23302STom N Harris $result[$w[0]][] = "$ixlen*$wid"; 911d5b23302STom N Harris } 912d5b23302STom N Harris } 913d5b23302STom N Harris } 914d5b23302STom N Harris } 915d5b23302STom N Harris return $wids; 916d5b23302STom N Harris } 917d5b23302STom N Harris 918d5b23302STom N Harris /** 91900803e56STom N Harris * Return a list of all pages 920c1209673STom N Harris * Warning: pages may not exist! 921488dd6ceSAndreas Gohr * 92200803e56STom N Harris * @param string $key list only pages containing the metadata key (optional) 92300803e56STom N Harris * @return array list of page names 92442ea7f44SGerrit Uitslag * 92500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 92600803e56STom N Harris */ 92700803e56STom N Harris public function getPages($key=null) { 92880fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 92900803e56STom N Harris if (is_null($key)) return $page_idx; 930c1209673STom N Harris 931c1209673STom N Harris $metaname = idx_cleanName($key); 932c1209673STom N Harris 933c1209673STom N Harris // Special handling for titles 934c1209673STom N Harris if ($key == 'title') { 93580fb93f6STom N Harris $title_idx = $this->getIndex('title', ''); 936c1209673STom N Harris array_splice($page_idx, count($title_idx)); 937c1209673STom N Harris foreach ($title_idx as $i => $title) 938c1209673STom N Harris if ($title === "") unset($page_idx[$i]); 939675bf41fSTom N Harris return array_values($page_idx); 940c1209673STom N Harris } 941c1209673STom N Harris 942c1209673STom N Harris $pages = array(); 943b9d8cc1eSTom N Harris $lines = $this->getIndex($metaname.'_i', ''); 944c1209673STom N Harris foreach ($lines as $line) { 94580fb93f6STom N Harris $pages = array_merge($pages, $this->parseTuples($page_idx, $line)); 946c1209673STom N Harris } 947c1209673STom N Harris return array_keys($pages); 94800803e56STom N Harris } 94900803e56STom N Harris 95000803e56STom N Harris /** 95100803e56STom N Harris * Return a list of words sorted by number of times used 95200803e56STom N Harris * 95300803e56STom N Harris * @param int $min bottom frequency threshold 95400803e56STom N Harris * @param int $max upper frequency limit. No limit if $max<$min 955e3ab6fc5SMichael Hamann * @param int $minlen minimum length of words to count 95600803e56STom N Harris * @param string $key metadata key to list. Uses the fulltext index if not given 95700803e56STom N Harris * @return array list of words as the keys and frequency as values 95842ea7f44SGerrit Uitslag * 95900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 96000803e56STom N Harris */ 961b8c040dbSTom N Harris public function histogram($min=1, $max=0, $minlen=3, $key=null) { 962175193d2STom N Harris if ($min < 1) 963175193d2STom N Harris $min = 1; 964175193d2STom N Harris if ($max < $min) 965175193d2STom N Harris $max = 0; 966175193d2STom N Harris 967175193d2STom N Harris $result = array(); 968175193d2STom N Harris 969175193d2STom N Harris if ($key == 'title') { 97080fb93f6STom N Harris $index = $this->getIndex('title', ''); 971175193d2STom N Harris $index = array_count_values($index); 972175193d2STom N Harris foreach ($index as $val => $cnt) { 973b8c040dbSTom N Harris if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen) 974175193d2STom N Harris $result[$val] = $cnt; 975175193d2STom N Harris } 976175193d2STom N Harris } 977175193d2STom N Harris elseif (!is_null($key)) { 978175193d2STom N Harris $metaname = idx_cleanName($key); 97980fb93f6STom N Harris $index = $this->getIndex($metaname.'_i', ''); 980175193d2STom N Harris $val_idx = array(); 981175193d2STom N Harris foreach ($index as $wid => $line) { 98280fb93f6STom N Harris $freq = $this->countTuples($line); 9839a9b579aSMichael Hamann if ($freq >= $min && (!$max || $freq <= $max)) 984175193d2STom N Harris $val_idx[$wid] = $freq; 985175193d2STom N Harris } 986175193d2STom N Harris if (!empty($val_idx)) { 98780fb93f6STom N Harris $words = $this->getIndex($metaname.'_w', ''); 9889a9b579aSMichael Hamann foreach ($val_idx as $wid => $freq) { 9899a9b579aSMichael Hamann if (strlen($words[$wid]) >= $minlen) 990175193d2STom N Harris $result[$words[$wid]] = $freq; 991175193d2STom N Harris } 992175193d2STom N Harris } 9939a9b579aSMichael Hamann } 994175193d2STom N Harris else { 995175193d2STom N Harris $lengths = idx_listIndexLengths(); 996175193d2STom N Harris foreach ($lengths as $length) { 997b8c040dbSTom N Harris if ($length < $minlen) continue; 99880fb93f6STom N Harris $index = $this->getIndex('i', $length); 999175193d2STom N Harris $words = null; 1000175193d2STom N Harris foreach ($index as $wid => $line) { 100180fb93f6STom N Harris $freq = $this->countTuples($line); 1002175193d2STom N Harris if ($freq >= $min && (!$max || $freq <= $max)) { 1003175193d2STom N Harris if ($words === null) 100480fb93f6STom N Harris $words = $this->getIndex('w', $length); 1005175193d2STom N Harris $result[$words[$wid]] = $freq; 1006175193d2STom N Harris } 1007175193d2STom N Harris } 1008175193d2STom N Harris } 1009175193d2STom N Harris } 1010175193d2STom N Harris 1011175193d2STom N Harris arsort($result); 1012175193d2STom N Harris return $result; 101300803e56STom N Harris } 101400803e56STom N Harris 101500803e56STom N Harris /** 101600803e56STom N Harris * Lock the indexer. 101700803e56STom N Harris * 101800803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 101942ea7f44SGerrit Uitslag * 102042ea7f44SGerrit Uitslag * @return bool|string 102100803e56STom N Harris */ 102280fb93f6STom N Harris protected function lock() { 102300803e56STom N Harris global $conf; 102400803e56STom N Harris $status = true; 1025f77fc90dSMichael Hamann $run = 0; 102600803e56STom N Harris $lock = $conf['lockdir'].'/_indexer.lock'; 102700803e56STom N Harris while (!@mkdir($lock, $conf['dmode'])) { 102800803e56STom N Harris usleep(50); 1029f77fc90dSMichael Hamann if(is_dir($lock) && time()-@filemtime($lock) > 60*5){ 1030f77fc90dSMichael Hamann // looks like a stale lock - remove it 1031f77fc90dSMichael Hamann if (!@rmdir($lock)) { 1032f77fc90dSMichael Hamann $status = "removing the stale lock failed"; 1033f77fc90dSMichael Hamann return false; 103400803e56STom N Harris } else { 1035f77fc90dSMichael Hamann $status = "stale lock removed"; 1036f77fc90dSMichael Hamann } 1037f77fc90dSMichael Hamann }elseif($run++ == 1000){ 1038f77fc90dSMichael Hamann // we waited 5 seconds for that lock 103900803e56STom N Harris return false; 104000803e56STom N Harris } 104100803e56STom N Harris } 1042443e135dSChristopher Smith if (!empty($conf['dperm'])) { 104300803e56STom N Harris chmod($lock, $conf['dperm']); 1044443e135dSChristopher Smith } 104500803e56STom N Harris return $status; 104600803e56STom N Harris } 104700803e56STom N Harris 104800803e56STom N Harris /** 104900803e56STom N Harris * Release the indexer lock. 105000803e56STom N Harris * 105100803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 105242ea7f44SGerrit Uitslag * 105342ea7f44SGerrit Uitslag * @return bool 105400803e56STom N Harris */ 105580fb93f6STom N Harris protected function unlock() { 105600803e56STom N Harris global $conf; 105700803e56STom N Harris @rmdir($conf['lockdir'].'/_indexer.lock'); 105800803e56STom N Harris return true; 105900803e56STom N Harris } 106000803e56STom N Harris 106100803e56STom N Harris /** 106200803e56STom N Harris * Retrieve the entire index. 106300803e56STom N Harris * 1064b9d8cc1eSTom N Harris * The $suffix argument is for an index that is split into 1065b9d8cc1eSTom N Harris * multiple parts. Different index files should use different 1066b9d8cc1eSTom N Harris * base names. 1067b9d8cc1eSTom N Harris * 1068b9d8cc1eSTom N Harris * @param string $idx name of the index 1069b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1070b9d8cc1eSTom N Harris * @return array list of lines without CR or LF 107142ea7f44SGerrit Uitslag * 107200803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 107300803e56STom N Harris */ 107480fb93f6STom N Harris protected function getIndex($idx, $suffix) { 107500803e56STom N Harris global $conf; 107600803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 107779e79377SAndreas Gohr if (!file_exists($fn)) return array(); 1078d64516f5SMichael Hamann return file($fn, FILE_IGNORE_NEW_LINES); 107900803e56STom N Harris } 108000803e56STom N Harris 108100803e56STom N Harris /** 108200803e56STom N Harris * Replace the contents of the index with an array. 108300803e56STom N Harris * 1084b9d8cc1eSTom N Harris * @param string $idx name of the index 1085b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1086e3ab6fc5SMichael Hamann * @param array $lines list of lines without LF 1087e3ab6fc5SMichael Hamann * @return bool If saving succeeded 108842ea7f44SGerrit Uitslag * 108900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 109000803e56STom N Harris */ 109180fb93f6STom N Harris protected function saveIndex($idx, $suffix, &$lines) { 109200803e56STom N Harris global $conf; 109300803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix; 109400803e56STom N Harris $fh = @fopen($fn.'.tmp', 'w'); 109500803e56STom N Harris if (!$fh) return false; 109600803e56STom N Harris fwrite($fh, join("\n", $lines)); 10972e1018bcSMichael Hamann if (!empty($lines)) 10982e1018bcSMichael Hamann fwrite($fh, "\n"); 109900803e56STom N Harris fclose($fh); 110000803e56STom N Harris if (isset($conf['fperm'])) 110100803e56STom N Harris chmod($fn.'.tmp', $conf['fperm']); 110200803e56STom N Harris io_rename($fn.'.tmp', $fn.'.idx'); 110300803e56STom N Harris return true; 110400803e56STom N Harris } 110500803e56STom N Harris 110600803e56STom N Harris /** 110700803e56STom N Harris * Retrieve a line from 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 * @return string a line with trailing whitespace removed 111342ea7f44SGerrit Uitslag * 111400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 111500803e56STom N Harris */ 111680fb93f6STom N Harris protected function getIndexKey($idx, $suffix, $id) { 111700803e56STom N Harris global $conf; 111800803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 111979e79377SAndreas Gohr if (!file_exists($fn)) return ''; 112000803e56STom N Harris $fh = @fopen($fn, 'r'); 112100803e56STom N Harris if (!$fh) return ''; 112200803e56STom N Harris $ln = -1; 112300803e56STom N Harris while (($line = fgets($fh)) !== false) { 112400803e56STom N Harris if (++$ln == $id) break; 112500803e56STom N Harris } 112600803e56STom N Harris fclose($fh); 112700803e56STom N Harris return rtrim((string)$line); 112800803e56STom N Harris } 112900803e56STom N Harris 113000803e56STom N Harris /** 113100803e56STom N Harris * Write a line into the index. 113200803e56STom N Harris * 1133b9d8cc1eSTom N Harris * @param string $idx name of the index 1134b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1135b9d8cc1eSTom N Harris * @param int $id the line number 1136b9d8cc1eSTom N Harris * @param string $line line to write 1137e3ab6fc5SMichael Hamann * @return bool If saving succeeded 113842ea7f44SGerrit Uitslag * 113900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 114000803e56STom N Harris */ 114180fb93f6STom N Harris protected function saveIndexKey($idx, $suffix, $id, $line) { 114200803e56STom N Harris global $conf; 114300803e56STom N Harris if (substr($line, -1) != "\n") 114400803e56STom N Harris $line .= "\n"; 114500803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix; 114600803e56STom N Harris $fh = @fopen($fn.'.tmp', 'w'); 1147dbb771bbSAdrian Lang if (!$fh) return false; 114800803e56STom N Harris $ih = @fopen($fn.'.idx', 'r'); 114900803e56STom N Harris if ($ih) { 115000803e56STom N Harris $ln = -1; 115100803e56STom N Harris while (($curline = fgets($ih)) !== false) { 115200803e56STom N Harris fwrite($fh, (++$ln == $id) ? $line : $curline); 115300803e56STom N Harris } 11544373c7b5SMichael Hamann if ($id > $ln) { 11554373c7b5SMichael Hamann while ($id > ++$ln) 11564373c7b5SMichael Hamann fwrite($fh, "\n"); 115700803e56STom N Harris fwrite($fh, $line); 11584373c7b5SMichael Hamann } 115900803e56STom N Harris fclose($ih); 116000803e56STom N Harris } else { 11614373c7b5SMichael Hamann $ln = -1; 11624373c7b5SMichael Hamann while ($id > ++$ln) 11634373c7b5SMichael Hamann fwrite($fh, "\n"); 116400803e56STom N Harris fwrite($fh, $line); 116500803e56STom N Harris } 116600803e56STom N Harris fclose($fh); 116700803e56STom N Harris if (isset($conf['fperm'])) 116800803e56STom N Harris chmod($fn.'.tmp', $conf['fperm']); 116900803e56STom N Harris io_rename($fn.'.tmp', $fn.'.idx'); 117000803e56STom N Harris return true; 117100803e56STom N Harris } 117200803e56STom N Harris 117300803e56STom N Harris /** 117400803e56STom N Harris * Retrieve or insert a value in the index. 117500803e56STom N Harris * 1176b9d8cc1eSTom N Harris * @param string $idx name of the index 1177b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1178b9d8cc1eSTom N Harris * @param string $value line to find in the index 117903aafe1cSMichael Hamann * @return int|bool line number of the value in the index or false if writing the index failed 118042ea7f44SGerrit Uitslag * 118100803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 118200803e56STom N Harris */ 118380fb93f6STom N Harris protected function addIndexKey($idx, $suffix, $value) { 118480fb93f6STom N Harris $index = $this->getIndex($idx, $suffix); 1185a8dba452SMichael Hamann $id = array_search($value, $index, true); 118600803e56STom N Harris if ($id === false) { 118700803e56STom N Harris $id = count($index); 118800803e56STom N Harris $index[$id] = $value; 118980fb93f6STom N Harris if (!$this->saveIndex($idx, $suffix, $index)) { 119000803e56STom N Harris trigger_error("Failed to write $idx index", E_USER_ERROR); 119100803e56STom N Harris return false; 119200803e56STom N Harris } 119300803e56STom N Harris } 119400803e56STom N Harris return $id; 119500803e56STom N Harris } 119600803e56STom N Harris 1197e3ab6fc5SMichael Hamann /** 119800803e56STom N Harris * Get the list of lengths indexed in the wiki. 119900803e56STom N Harris * 120000803e56STom N Harris * Read the index directory or a cache file and returns 120100803e56STom N Harris * a sorted array of lengths of the words used in the wiki. 120200803e56STom N Harris * 120300803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 120442ea7f44SGerrit Uitslag * 120542ea7f44SGerrit Uitslag * @return array 120600803e56STom N Harris */ 120780fb93f6STom N Harris protected function listIndexLengths() { 1208b1720e5cSMichael Hamann return idx_listIndexLengths(); 120900803e56STom N Harris } 121000803e56STom N Harris 121100803e56STom N Harris /** 121200803e56STom N Harris * Get the word lengths that have been indexed. 121300803e56STom N Harris * 121400803e56STom N Harris * Reads the index directory and returns an array of lengths 121500803e56STom N Harris * that there are indices for. 121600803e56STom N Harris * 121700803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 121842ea7f44SGerrit Uitslag * 121942ea7f44SGerrit Uitslag * @param array|int $filter 122042ea7f44SGerrit Uitslag * @return array 122100803e56STom N Harris */ 122280fb93f6STom N Harris protected function indexLengths($filter) { 122300803e56STom N Harris global $conf; 122400803e56STom N Harris $idx = array(); 122500803e56STom N Harris if (is_array($filter)) { 122600803e56STom N Harris // testing if index files exist only 122700803e56STom N Harris $path = $conf['indexdir']."/i"; 122800803e56STom N Harris foreach ($filter as $key => $value) { 122979e79377SAndreas Gohr if (file_exists($path.$key.'.idx')) 123000803e56STom N Harris $idx[] = $key; 123100803e56STom N Harris } 123200803e56STom N Harris } else { 123300803e56STom N Harris $lengths = idx_listIndexLengths(); 123400803e56STom N Harris foreach ($lengths as $key => $length) { 123500803e56STom N Harris // keep all the values equal or superior 123600803e56STom N Harris if ((int)$length >= (int)$filter) 123700803e56STom N Harris $idx[] = $length; 123800803e56STom N Harris } 123900803e56STom N Harris } 124000803e56STom N Harris return $idx; 124100803e56STom N Harris } 124200803e56STom N Harris 124300803e56STom N Harris /** 124400803e56STom N Harris * Insert or replace a tuple in a line. 124500803e56STom N Harris * 124600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 124742ea7f44SGerrit Uitslag * 124842ea7f44SGerrit Uitslag * @param string $line 1249e3710957SGerrit Uitslag * @param string|int $id 125042ea7f44SGerrit Uitslag * @param int $count 125142ea7f44SGerrit Uitslag * @return string 125200803e56STom N Harris */ 125380fb93f6STom N Harris protected function updateTuple($line, $id, $count) { 1254c6568d42SChristopher Smith if ($line != ''){ 1255c6568d42SChristopher Smith $line = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $line); 125639134585SChristopher Smith } 1257c6568d42SChristopher Smith $line = trim($line, ':'); 125800803e56STom N Harris if ($count) { 1259c6568d42SChristopher Smith if ($line) { 1260c6568d42SChristopher Smith return "$id*$count:".$line; 126139134585SChristopher Smith } else { 1262c6568d42SChristopher Smith return "$id*$count"; 126300803e56STom N Harris } 126439134585SChristopher Smith } 1265c6568d42SChristopher Smith return $line; 126600803e56STom N Harris } 126700803e56STom N Harris 126800803e56STom N Harris /** 126900803e56STom N Harris * Split a line into an array of tuples. 127000803e56STom N Harris * 127100803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 127200803e56STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 127342ea7f44SGerrit Uitslag * 127442ea7f44SGerrit Uitslag * @param array $keys 127542ea7f44SGerrit Uitslag * @param string $line 127642ea7f44SGerrit Uitslag * @return array 127700803e56STom N Harris */ 127880fb93f6STom N Harris protected function parseTuples(&$keys, $line) { 127900803e56STom N Harris $result = array(); 128000803e56STom N Harris if ($line == '') return $result; 128100803e56STom N Harris $parts = explode(':', $line); 128200803e56STom N Harris foreach ($parts as $tuple) { 1283675bf41fSTom N Harris if ($tuple === '') continue; 128400803e56STom N Harris list($key, $cnt) = explode('*', $tuple); 1285d64516f5SMichael Hamann if (!$cnt) continue; 128600803e56STom N Harris $key = $keys[$key]; 12875e0da3ceSPhy if ($key === false || is_null($key)) continue; 128800803e56STom N Harris $result[$key] = $cnt; 128900803e56STom N Harris } 129000803e56STom N Harris return $result; 129100803e56STom N Harris } 1292175193d2STom N Harris 1293175193d2STom N Harris /** 1294175193d2STom N Harris * Sum the counts in a list of tuples. 1295175193d2STom N Harris * 1296175193d2STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 129742ea7f44SGerrit Uitslag * 129842ea7f44SGerrit Uitslag * @param string $line 129942ea7f44SGerrit Uitslag * @return int 1300175193d2STom N Harris */ 130180fb93f6STom N Harris protected function countTuples($line) { 1302175193d2STom N Harris $freq = 0; 1303175193d2STom N Harris $parts = explode(':', $line); 1304175193d2STom N Harris foreach ($parts as $tuple) { 1305675bf41fSTom N Harris if ($tuple === '') continue; 130642ea7f44SGerrit Uitslag list(/* $pid */, $cnt) = explode('*', $tuple); 1307175193d2STom N Harris $freq += (int)$cnt; 1308175193d2STom N Harris } 1309175193d2STom N Harris return $freq; 1310175193d2STom N Harris } 131100803e56STom N Harris} 131200803e56STom N Harris 131300803e56STom N Harris/** 131400803e56STom N Harris * Create an instance of the indexer. 131500803e56STom N Harris * 1316b3d1090eSMichael Hamann * @return Doku_Indexer a Doku_Indexer 131742ea7f44SGerrit Uitslag * 131800803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 131900803e56STom N Harris */ 13209b41be24STom N Harrisfunction idx_get_indexer() { 13214f708321SMichael Hamann static $Indexer; 13221421e548SMichael Hamann if (!isset($Indexer)) { 132300803e56STom N Harris $Indexer = new Doku_Indexer(); 132400803e56STom N Harris } 132500803e56STom N Harris return $Indexer; 132600803e56STom N Harris} 132700803e56STom N Harris 132800803e56STom N Harris/** 132900803e56STom N Harris * Returns words that will be ignored. 133000803e56STom N Harris * 133100803e56STom N Harris * @return array list of stop words 133242ea7f44SGerrit Uitslag * 133300803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 133400803e56STom N Harris */ 133500803e56STom N Harrisfunction & idx_get_stopwords() { 133600803e56STom N Harris static $stopwords = null; 133700803e56STom N Harris if (is_null($stopwords)) { 133800803e56STom N Harris global $conf; 133900803e56STom N Harris $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 134079e79377SAndreas Gohr if(file_exists($swfile)){ 134100803e56STom N Harris $stopwords = file($swfile, FILE_IGNORE_NEW_LINES); 134200803e56STom N Harris }else{ 134300803e56STom N Harris $stopwords = array(); 134400803e56STom N Harris } 134500803e56STom N Harris } 134600803e56STom N Harris return $stopwords; 134700803e56STom N Harris} 134800803e56STom N Harris 134900803e56STom N Harris/** 135000803e56STom N Harris * Adds/updates the search index for the given page 135100803e56STom N Harris * 135200803e56STom N Harris * Locking is handled internally. 135300803e56STom N Harris * 135400803e56STom N Harris * @param string $page name of the page to index 13559b41be24STom N Harris * @param boolean $verbose print status messages 1356d041f8dbSMichael Hamann * @param boolean $force force reindexing even when the index is up to date 135742ea7f44SGerrit Uitslag * @return string|boolean the function completed successfully 135842ea7f44SGerrit Uitslag * 135900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 136000803e56STom N Harris */ 1361d041f8dbSMichael Hamannfunction idx_addPage($page, $verbose=false, $force=false) { 13629b41be24STom N Harris $idxtag = metaFN($page,'.indexed'); 1363a23ac4d7SMichael Hamann // check if page was deleted but is still in the index 1364bbc85ee4STom N Harris if (!page_exists($page)) { 136579e79377SAndreas Gohr if (!file_exists($idxtag)) { 1366bbc85ee4STom N Harris if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF); 1367bbc85ee4STom N Harris return false; 1368bbc85ee4STom N Harris } 1369bbc85ee4STom N Harris $Indexer = idx_get_indexer(); 1370bbc85ee4STom N Harris $result = $Indexer->deletePage($page); 1371bbc85ee4STom N Harris if ($result === "locked") { 1372bbc85ee4STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 1373bbc85ee4STom N Harris return false; 1374bbc85ee4STom N Harris } 1375bbc85ee4STom N Harris @unlink($idxtag); 1376bbc85ee4STom N Harris return $result; 1377bbc85ee4STom N Harris } 1378a23ac4d7SMichael Hamann 1379a23ac4d7SMichael Hamann // check if indexing needed 138079e79377SAndreas Gohr if(!$force && file_exists($idxtag)){ 1381a23ac4d7SMichael Hamann if(trim(io_readFile($idxtag)) == idx_get_version()){ 1382a23ac4d7SMichael Hamann $last = @filemtime($idxtag); 1383a23ac4d7SMichael Hamann if($last > @filemtime(wikiFN($page))){ 1384a23ac4d7SMichael Hamann if ($verbose) print("Indexer: index for $page up to date".DOKU_LF); 1385a23ac4d7SMichael Hamann return false; 1386a23ac4d7SMichael Hamann } 1387a23ac4d7SMichael Hamann } 1388a23ac4d7SMichael Hamann } 1389a23ac4d7SMichael Hamann 139065aa8490SMichael Hamann $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED); 1391bbc85ee4STom N Harris if ($indexenabled === false) { 1392bbc85ee4STom N Harris $result = false; 139379e79377SAndreas Gohr if (file_exists($idxtag)) { 1394bbc85ee4STom N Harris $Indexer = idx_get_indexer(); 1395bbc85ee4STom N Harris $result = $Indexer->deletePage($page); 1396bbc85ee4STom N Harris if ($result === "locked") { 1397bbc85ee4STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 1398bbc85ee4STom N Harris return false; 1399bbc85ee4STom N Harris } 1400bbc85ee4STom N Harris @unlink($idxtag); 1401bbc85ee4STom N Harris } 1402bbc85ee4STom N Harris if ($verbose) print("Indexer: index disabled for $page".DOKU_LF); 1403bbc85ee4STom N Harris return $result; 1404bbc85ee4STom N Harris } 1405bbc85ee4STom N Harris 140603aafe1cSMichael Hamann $Indexer = idx_get_indexer(); 140703aafe1cSMichael Hamann $pid = $Indexer->getPID($page); 140803aafe1cSMichael Hamann if ($pid === false) { 140903aafe1cSMichael Hamann if ($verbose) print("Indexer: getting the PID failed for $page".DOKU_LF); 141003aafe1cSMichael Hamann return false; 141103aafe1cSMichael Hamann } 141200803e56STom N Harris $body = ''; 141339d6fd30SMichael Hamann $metadata = array(); 141465aa8490SMichael Hamann $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED); 141565aa8490SMichael Hamann if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null) 141639d6fd30SMichael Hamann $metadata['relation_references'] = array_keys($references); 1417a424180eSMichael Hamann else 1418a424180eSMichael Hamann $metadata['relation_references'] = array(); 1419ffec1009SMichael Hamann 1420ffec1009SMichael Hamann if (($media = p_get_metadata($page, 'relation media', METADATA_RENDER_UNLIMITED)) !== null) 1421ffec1009SMichael Hamann $metadata['relation_media'] = array_keys($media); 1422ffec1009SMichael Hamann else 1423ffec1009SMichael Hamann $metadata['relation_media'] = array(); 1424ffec1009SMichael Hamann 142503aafe1cSMichael Hamann $data = compact('page', 'body', 'metadata', 'pid'); 1426*e1d9dcc8SAndreas Gohr $evt = new Event('INDEXER_PAGE_ADD', $data); 142739d6fd30SMichael Hamann if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page); 142800803e56STom N Harris $evt->advise_after(); 142900803e56STom N Harris unset($evt); 143039d6fd30SMichael Hamann extract($data); 143100803e56STom N Harris 14329b41be24STom N Harris $result = $Indexer->addPageWords($page, $body); 1433e1e1a7e0SMichael Hamann if ($result === "locked") { 14349b41be24STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 14359b41be24STom N Harris return false; 14369b41be24STom N Harris } 1437320f489aSMichael Hamann 1438320f489aSMichael Hamann if ($result) { 143939d6fd30SMichael Hamann $result = $Indexer->addMetaKeys($page, $metadata); 1440320f489aSMichael Hamann if ($result === "locked") { 1441320f489aSMichael Hamann if ($verbose) print("Indexer: locked".DOKU_LF); 1442320f489aSMichael Hamann return false; 1443320f489aSMichael Hamann } 1444320f489aSMichael Hamann } 1445320f489aSMichael Hamann 14469b41be24STom N Harris if ($result) 14479b41be24STom N Harris io_saveFile(metaFN($page,'.indexed'), idx_get_version()); 14489b41be24STom N Harris if ($verbose) { 14499b41be24STom N Harris print("Indexer: finished".DOKU_LF); 14509b41be24STom N Harris return true; 14519b41be24STom N Harris } 14529b41be24STom N Harris return $result; 145300803e56STom N Harris} 145400803e56STom N Harris 145500803e56STom N Harris/** 145600803e56STom N Harris * Find tokens in the fulltext index 145700803e56STom N Harris * 145800803e56STom N Harris * Takes an array of words and will return a list of matching 145900803e56STom N Harris * pages for each one. 1460488dd6ceSAndreas Gohr * 146163773904SAndreas Gohr * Important: No ACL checking is done here! All results are 146263773904SAndreas Gohr * returned, regardless of permissions 146363773904SAndreas Gohr * 1464e3ab6fc5SMichael Hamann * @param array $words list of words to search for 146500803e56STom N Harris * @return array list of pages found, associated with the search terms 1466488dd6ceSAndreas Gohr */ 14679b41be24STom N Harrisfunction idx_lookup(&$words) { 14689b41be24STom N Harris $Indexer = idx_get_indexer(); 146900803e56STom N Harris return $Indexer->lookup($words); 1470488dd6ceSAndreas Gohr} 1471488dd6ceSAndreas Gohr 1472488dd6ceSAndreas Gohr/** 147300803e56STom N Harris * Split a string into tokens 1474488dd6ceSAndreas Gohr * 1475f50a239bSTakamura * @param string $string 1476f50a239bSTakamura * @param bool $wc 1477f50a239bSTakamura * 1478f50a239bSTakamura * @return array 1479488dd6ceSAndreas Gohr */ 148000803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) { 14819b41be24STom N Harris $Indexer = idx_get_indexer(); 148200803e56STom N Harris return $Indexer->tokenizer($string, $wc); 1483488dd6ceSAndreas Gohr} 148400803e56STom N Harris 148500803e56STom N Harris/* For compatibility */ 1486488dd6ceSAndreas Gohr 1487f5eb7cf0SAndreas Gohr/** 148800803e56STom N Harris * Read the list of words in an index (if it exists). 1489f5eb7cf0SAndreas Gohr * 14904e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 149142ea7f44SGerrit Uitslag * 149242ea7f44SGerrit Uitslag * @param string $idx 149342ea7f44SGerrit Uitslag * @param string $suffix 149442ea7f44SGerrit Uitslag * @return array 1495f5eb7cf0SAndreas Gohr */ 149600803e56STom N Harrisfunction idx_getIndex($idx, $suffix) { 14971c07b9e6STom N Harris global $conf; 149800803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 149979e79377SAndreas Gohr if (!file_exists($fn)) return array(); 150000803e56STom N Harris return file($fn); 150100803e56STom N Harris} 1502f5eb7cf0SAndreas Gohr 150300803e56STom N Harris/** 150400803e56STom N Harris * Get the list of lengths indexed in the wiki. 150500803e56STom N Harris * 150600803e56STom N Harris * Read the index directory or a cache file and returns 150700803e56STom N Harris * a sorted array of lengths of the words used in the wiki. 150800803e56STom N Harris * 150900803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 151042ea7f44SGerrit Uitslag * 151142ea7f44SGerrit Uitslag * @return array 151200803e56STom N Harris */ 151300803e56STom N Harrisfunction idx_listIndexLengths() { 151400803e56STom N Harris global $conf; 151500803e56STom N Harris // testing what we have to do, create a cache file or not. 151600803e56STom N Harris if ($conf['readdircache'] == 0) { 151700803e56STom N Harris $docache = false; 15181c07b9e6STom N Harris } else { 151900803e56STom N Harris clearstatcache(); 152079e79377SAndreas Gohr if (file_exists($conf['indexdir'].'/lengths.idx') 152100803e56STom N Harris && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) { 152264159a61SAndreas Gohr if ( 152364159a61SAndreas Gohr ($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) 152464159a61SAndreas Gohr !== false 152564159a61SAndreas Gohr ) { 152600803e56STom N Harris $idx = array(); 152700803e56STom N Harris foreach ($lengths as $length) { 152800803e56STom N Harris $idx[] = (int)$length; 152900803e56STom N Harris } 153000803e56STom N Harris return $idx; 1531f5eb7cf0SAndreas Gohr } 15321c07b9e6STom N Harris } 153300803e56STom N Harris $docache = true; 153400803e56STom N Harris } 15354e1bf408STom N Harris 153600803e56STom N Harris if ($conf['readdircache'] == 0 || $docache) { 153700803e56STom N Harris $dir = @opendir($conf['indexdir']); 153800803e56STom N Harris if ($dir === false) 153900803e56STom N Harris return array(); 154026f7dbf5SMichael Hamann $idx = array(); 154100803e56STom N Harris while (($f = readdir($dir)) !== false) { 154200803e56STom N Harris if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') { 154300803e56STom N Harris $i = substr($f, 1, -4); 154400803e56STom N Harris if (is_numeric($i)) 154500803e56STom N Harris $idx[] = (int)$i; 154600803e56STom N Harris } 154700803e56STom N Harris } 154800803e56STom N Harris closedir($dir); 154900803e56STom N Harris sort($idx); 155000803e56STom N Harris // save this in a file 155100803e56STom N Harris if ($docache) { 155200803e56STom N Harris $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w'); 155300803e56STom N Harris @fwrite($handle, implode("\n", $idx)); 155400803e56STom N Harris @fclose($handle); 155500803e56STom N Harris } 155600803e56STom N Harris return $idx; 155700803e56STom N Harris } 155800803e56STom N Harris 155900803e56STom N Harris return array(); 156000803e56STom N Harris} 156100803e56STom N Harris 156200803e56STom N Harris/** 156300803e56STom N Harris * Get the word lengths that have been indexed. 156400803e56STom N Harris * 156500803e56STom N Harris * Reads the index directory and returns an array of lengths 156600803e56STom N Harris * that there are indices for. 156700803e56STom N Harris * 156800803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 156942ea7f44SGerrit Uitslag * 157042ea7f44SGerrit Uitslag * @param array|int $filter 157142ea7f44SGerrit Uitslag * @return array 157200803e56STom N Harris */ 157300803e56STom N Harrisfunction idx_indexLengths($filter) { 157400803e56STom N Harris global $conf; 157500803e56STom N Harris $idx = array(); 157600803e56STom N Harris if (is_array($filter)) { 157700803e56STom N Harris // testing if index files exist only 157800803e56STom N Harris $path = $conf['indexdir']."/i"; 157900803e56STom N Harris foreach ($filter as $key => $value) { 158079e79377SAndreas Gohr if (file_exists($path.$key.'.idx')) 158100803e56STom N Harris $idx[] = $key; 158200803e56STom N Harris } 1583f5eb7cf0SAndreas Gohr } else { 158400803e56STom N Harris $lengths = idx_listIndexLengths(); 158500803e56STom N Harris foreach ($lengths as $key => $length) { 158600803e56STom N Harris // keep all the values equal or superior 158700803e56STom N Harris if ((int)$length >= (int)$filter) 158800803e56STom N Harris $idx[] = $length; 1589f5eb7cf0SAndreas Gohr } 159000803e56STom N Harris } 159100803e56STom N Harris return $idx; 1592f5eb7cf0SAndreas Gohr} 1593f5eb7cf0SAndreas Gohr 159400803e56STom N Harris/** 159500803e56STom N Harris * Clean a name of a key for use as a file name. 159600803e56STom N Harris * 159700803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's 159800803e56STom N Harris * not a letter, number, or underscore. 159900803e56STom N Harris * 160000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 160142ea7f44SGerrit Uitslag * 160242ea7f44SGerrit Uitslag * @param string $name 160342ea7f44SGerrit Uitslag * @return string 160400803e56STom N Harris */ 160500803e56STom N Harrisfunction idx_cleanName($name) { 160600803e56STom N Harris $name = utf8_romanize(trim((string)$name)); 160700803e56STom N Harris $name = preg_replace('#[ \./\\:-]+#', '_', $name); 160800803e56STom N Harris $name = preg_replace('/[^A-Za-z0-9_]/', '', $name); 160900803e56STom N Harris return strtolower($name); 1610f5eb7cf0SAndreas Gohr} 1611f5eb7cf0SAndreas Gohr 161200803e56STom N Harris//Setup VIM: ex: et ts=4 : 1613