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 10*dbc189b2SAndreas Gohruse dokuwiki\Extension\Event; 11*dbc189b2SAndreas Gohr 127c2ef4e8STom N Harris// Version tag used to force rebuild on upgrade 13*dbc189b2SAndreas Gohrdefine('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 18b4ce25e9SAndreas Gohr/** 197c2ef4e8STom N Harris * Version of the indexer taking into consideration the external tokenizer. 207c2ef4e8STom N Harris * The indexer is only compatible with data written by the same version. 217c2ef4e8STom N Harris * 228cd4c12fSAndreas Gohr * @triggers INDEXER_VERSION_GET 23d0d6fe1bSTom N Harris * Plugins that modify what gets indexed should hook this event and 24d0d6fe1bSTom N Harris * add their version info to the event data like so: 25d0d6fe1bSTom N Harris * $data[$plugin_name] = $plugin_version; 26d0d6fe1bSTom N Harris * 277c2ef4e8STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 288605afb1SMichael Hamann * @author Michael Hamann <michael@content-space.de> 2942ea7f44SGerrit Uitslag * 3042ea7f44SGerrit Uitslag * @return int|string 317c2ef4e8STom N Harris */ 327c2ef4e8STom N Harrisfunction idx_get_version(){ 33d0d6fe1bSTom N Harris static $indexer_version = null; 34d0d6fe1bSTom N Harris if ($indexer_version == null) { 358605afb1SMichael Hamann $version = INDEXER_VERSION; 368605afb1SMichael Hamann 37d0d6fe1bSTom N Harris // DokuWiki version is included for the convenience of plugins 38d0d6fe1bSTom N Harris $data = array('dokuwiki'=>$version); 39cbb44eabSAndreas Gohr Event::createAndTrigger('INDEXER_VERSION_GET', $data, null, false); 40d0d6fe1bSTom N Harris unset($data['dokuwiki']); // this needs to be first 41d0d6fe1bSTom N Harris ksort($data); 42d0d6fe1bSTom N Harris foreach ($data as $plugin=>$vers) 43d0d6fe1bSTom N Harris $version .= '+'.$plugin.'='.$vers; 44d0d6fe1bSTom N Harris $indexer_version = $version; 45d0d6fe1bSTom N Harris } 46d0d6fe1bSTom N Harris return $indexer_version; 477c2ef4e8STom N Harris} 487c2ef4e8STom N Harris 497c2ef4e8STom N Harris/** 50d5b23302STom N Harris * Measure the length of a string. 51d5b23302STom N Harris * Differs from strlen in handling of asian characters. 52d5b23302STom N Harris * 53d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 5442ea7f44SGerrit Uitslag * 5542ea7f44SGerrit Uitslag * @param string $w 5642ea7f44SGerrit Uitslag * @return int 57d5b23302STom N Harris */ 58d5b23302STom N Harrisfunction wordlen($w){ 59d5b23302STom N Harris $l = strlen($w); 60d5b23302STom N Harris // If left alone, all chinese "words" will get put into w3.idx 61d5b23302STom N Harris // So the "length" of a "word" is faked 624b9792c6STom N Harris if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) { 634b9792c6STom N Harris foreach($leadbytes[0] as $b) 644b9792c6STom N Harris $l += ord($b) - 0xE1; 654b9792c6STom N Harris } 66d5b23302STom N Harris return $l; 67d5b23302STom N Harris} 68d5b23302STom N Harris 69d5b23302STom N Harris/** 7000803e56STom N Harris * Class that encapsulates operations on the indexer database. 71579b0f7eSTNHarris * 72579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org> 73579b0f7eSTNHarris */ 7400803e56STom N Harrisclass Doku_Indexer { 753d2ce006SMichael Hamann /** 763d2ce006SMichael Hamann * @var array $pidCache Cache for getPID() 773d2ce006SMichael Hamann */ 783d2ce006SMichael Hamann protected $pidCache = array(); 79579b0f7eSTNHarris 80579b0f7eSTNHarris /** 8100803e56STom N Harris * Adds the contents of a page to the fulltext index 82dd35e9c9SAndreas Gohr * 8300803e56STom N Harris * The added text replaces previous words for the same page. 8400803e56STom N Harris * An empty value erases the page. 8500803e56STom N Harris * 8600803e56STom N Harris * @param string $page a page name 8700803e56STom N Harris * @param string $text the body of the page 8842ea7f44SGerrit Uitslag * @return string|boolean the function completed successfully 8942ea7f44SGerrit Uitslag * 9000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 91dd35e9c9SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 92dd35e9c9SAndreas Gohr */ 9300803e56STom N Harris public function addPageWords($page, $text) { 9480fb93f6STom N Harris if (!$this->lock()) 959b41be24STom N Harris return "locked"; 9600803e56STom N Harris 9700803e56STom N Harris // load known documents 9803aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 995981eb09STom N Harris if ($pid === false) { 10080fb93f6STom N Harris $this->unlock(); 10100803e56STom N Harris return false; 10200803e56STom N Harris } 10300803e56STom N Harris 10400803e56STom N Harris $pagewords = array(); 10500803e56STom N Harris // get word usage in page 10680fb93f6STom N Harris $words = $this->getPageWords($text); 10700803e56STom N Harris if ($words === false) { 10880fb93f6STom N Harris $this->unlock(); 10900803e56STom N Harris return false; 11000803e56STom N Harris } 11100803e56STom N Harris 11200803e56STom N Harris if (!empty($words)) { 11300803e56STom N Harris foreach (array_keys($words) as $wlen) { 11480fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 11500803e56STom N Harris foreach ($words[$wlen] as $wid => $freq) { 11600803e56STom N Harris $idx = ($wid<count($index)) ? $index[$wid] : ''; 11780fb93f6STom N Harris $index[$wid] = $this->updateTuple($idx, $pid, $freq); 11800803e56STom N Harris $pagewords[] = "$wlen*$wid"; 11900803e56STom N Harris } 12080fb93f6STom N Harris if (!$this->saveIndex('i', $wlen, $index)) { 12180fb93f6STom N Harris $this->unlock(); 12200803e56STom N Harris return false; 12300803e56STom N Harris } 12400803e56STom N Harris } 12500803e56STom N Harris } 12600803e56STom N Harris 12700803e56STom N Harris // Remove obsolete index entries 12880fb93f6STom N Harris $pageword_idx = $this->getIndexKey('pageword', '', $pid); 12900803e56STom N Harris if ($pageword_idx !== '') { 13000803e56STom N Harris $oldwords = explode(':',$pageword_idx); 13100803e56STom N Harris $delwords = array_diff($oldwords, $pagewords); 13200803e56STom N Harris $upwords = array(); 13300803e56STom N Harris foreach ($delwords as $word) { 13400803e56STom N Harris if ($word != '') { 13500803e56STom N Harris list($wlen,$wid) = explode('*', $word); 13600803e56STom N Harris $wid = (int)$wid; 13700803e56STom N Harris $upwords[$wlen][] = $wid; 13800803e56STom N Harris } 13900803e56STom N Harris } 14000803e56STom N Harris foreach ($upwords as $wlen => $widx) { 14180fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 14200803e56STom N Harris foreach ($widx as $wid) { 14380fb93f6STom N Harris $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 14400803e56STom N Harris } 14580fb93f6STom N Harris $this->saveIndex('i', $wlen, $index); 14600803e56STom N Harris } 14700803e56STom N Harris } 14800803e56STom N Harris // Save the reverse index 14900803e56STom N Harris $pageword_idx = join(':', $pagewords); 15080fb93f6STom N Harris if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) { 15180fb93f6STom N Harris $this->unlock(); 15200803e56STom N Harris return false; 15300803e56STom N Harris } 15400803e56STom N Harris 15580fb93f6STom N Harris $this->unlock(); 156dd35e9c9SAndreas Gohr return true; 157dd35e9c9SAndreas Gohr } 158dd35e9c9SAndreas Gohr 159dd35e9c9SAndreas Gohr /** 16000803e56STom N Harris * Split the words in a page and add them to the index. 16144ca0adfSAndreas Gohr * 162b9d8cc1eSTom N Harris * @param string $text content of the page 163b9d8cc1eSTom N Harris * @return array list of word IDs and number of times used 16442ea7f44SGerrit Uitslag * 16544ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 16617f42b01SChris Smith * @author Christopher Smith <chris@jalakai.co.uk> 16700803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 168b4ce25e9SAndreas Gohr */ 16980fb93f6STom N Harris protected function getPageWords($text) { 17044ca0adfSAndreas Gohr 17100803e56STom N Harris $tokens = $this->tokenizer($text); 17217f42b01SChris Smith $tokens = array_count_values($tokens); // count the frequency of each token 17317f42b01SChris Smith 17417f42b01SChris Smith $words = array(); 1754e1bf408STom N Harris foreach ($tokens as $w=>$c) { 176d5b23302STom N Harris $l = wordlen($w); 177579b0f7eSTNHarris if (isset($words[$l])){ 1784e1bf408STom N Harris $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0); 17917f42b01SChris Smith }else{ 1804e1bf408STom N Harris $words[$l] = array($w => $c); 18117f42b01SChris Smith } 18217f42b01SChris Smith } 18317f42b01SChris Smith 184579b0f7eSTNHarris // arrive here with $words = array(wordlen => array(word => frequency)) 185e5e50383SMichael Hamann $word_idx_modified = false; 186b4ce25e9SAndreas Gohr $index = array(); //resulting index 187579b0f7eSTNHarris foreach (array_keys($words) as $wlen) { 18880fb93f6STom N Harris $word_idx = $this->getIndex('w', $wlen); 189579b0f7eSTNHarris foreach ($words[$wlen] as $word => $freq) { 1905a1d0548SMichael Hamann $word = (string)$word; 191a8dba452SMichael Hamann $wid = array_search($word, $word_idx, true); 19200803e56STom N Harris if ($wid === false) { 193d5b23302STom N Harris $wid = count($word_idx); 19400803e56STom N Harris $word_idx[] = $word; 195e5e50383SMichael Hamann $word_idx_modified = true; 196b4ce25e9SAndreas Gohr } 197579b0f7eSTNHarris if (!isset($index[$wlen])) 198579b0f7eSTNHarris $index[$wlen] = array(); 199579b0f7eSTNHarris $index[$wlen][$wid] = $freq; 20044ca0adfSAndreas Gohr } 20100803e56STom N Harris // save back the word index 20280fb93f6STom N Harris if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx)) 20344ca0adfSAndreas Gohr return false; 20444ca0adfSAndreas Gohr } 205b4ce25e9SAndreas Gohr 206b4ce25e9SAndreas Gohr return $index; 207b4ce25e9SAndreas Gohr } 208b4ce25e9SAndreas Gohr 20944ca0adfSAndreas Gohr /** 210e1e1a7e0SMichael Hamann * Add/update keys to/of the metadata index. 21144ca0adfSAndreas Gohr * 21200803e56STom N Harris * Adding new keys does not remove other keys for the page. 21300803e56STom N Harris * An empty value will erase the key. 21400803e56STom N Harris * The $key parameter can be an array to add multiple keys. $value will 21500803e56STom N Harris * not be used if $key is an array. 21644ca0adfSAndreas Gohr * 21700803e56STom N Harris * @param string $page a page name 21800803e56STom N Harris * @param mixed $key a key string or array of key=>value pairs 21900803e56STom N Harris * @param mixed $value the value or list of values 22042ea7f44SGerrit Uitslag * @return boolean|string the function completed successfully 22142ea7f44SGerrit Uitslag * 22200803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 223e1e1a7e0SMichael Hamann * @author Michael Hamann <michael@content-space.de> 22444ca0adfSAndreas Gohr */ 22500803e56STom N Harris public function addMetaKeys($page, $key, $value=null) { 22600803e56STom N Harris if (!is_array($key)) { 22700803e56STom N Harris $key = array($key => $value); 22800803e56STom N Harris } elseif (!is_null($value)) { 22900803e56STom N Harris // $key is array, but $value is not null 23000803e56STom N Harris trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING); 23100803e56STom N Harris } 23200803e56STom N Harris 23380fb93f6STom N Harris if (!$this->lock()) 234e1e1a7e0SMichael Hamann return "locked"; 235b4ce25e9SAndreas Gohr 236488dd6ceSAndreas Gohr // load known documents 23703aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 23800803e56STom N Harris if ($pid === false) { 23980fb93f6STom N Harris $this->unlock(); 240579b0f7eSTNHarris return false; 24144ca0adfSAndreas Gohr } 24200803e56STom N Harris 243c1209673STom N Harris // Special handling for titles so the index file is simpler 244c1209673STom N Harris if (array_key_exists('title', $key)) { 245c1209673STom N Harris $value = $key['title']; 246e1ecd6fdSChristopher Smith if (is_array($value)) { 247c1209673STom N Harris $value = $value[0]; 248e1ecd6fdSChristopher Smith } 24980fb93f6STom N Harris $this->saveIndexKey('title', '', $pid, $value); 250c1209673STom N Harris unset($key['title']); 251c1209673STom N Harris } 252c1209673STom N Harris 25300803e56STom N Harris foreach ($key as $name => $values) { 25400803e56STom N Harris $metaname = idx_cleanName($name); 25580fb93f6STom N Harris $this->addIndexKey('metadata', '', $metaname); 256b9d8cc1eSTom N Harris $metaidx = $this->getIndex($metaname.'_i', ''); 257b9d8cc1eSTom N Harris $metawords = $this->getIndex($metaname.'_w', ''); 25800803e56STom N Harris $addwords = false; 259e1e1a7e0SMichael Hamann 260e1e1a7e0SMichael Hamann if (!is_array($values)) $values = array($values); 261e1e1a7e0SMichael Hamann 262b9d8cc1eSTom N Harris $val_idx = $this->getIndexKey($metaname.'_p', '', $pid); 2635e0da3ceSPhy if ($val_idx !== '') { 264e1e1a7e0SMichael Hamann $val_idx = explode(':', $val_idx); 265e1e1a7e0SMichael Hamann // -1 means remove, 0 keep, 1 add 266e1e1a7e0SMichael Hamann $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1)); 267e1e1a7e0SMichael Hamann } else { 268e1e1a7e0SMichael Hamann $val_idx = array(); 269e1e1a7e0SMichael Hamann } 270e1e1a7e0SMichael Hamann 27100803e56STom N Harris foreach ($values as $val) { 27200803e56STom N Harris $val = (string)$val; 27300803e56STom N Harris if ($val !== "") { 274a8dba452SMichael Hamann $id = array_search($val, $metawords, true); 27500803e56STom N Harris if ($id === false) { 276e1ecd6fdSChristopher Smith // didn't find $val, so we'll add it to the end of metawords and create a placeholder in metaidx 27700803e56STom N Harris $id = count($metawords); 27800803e56STom N Harris $metawords[$id] = $val; 279e1ecd6fdSChristopher Smith $metaidx[$id] = ''; 28000803e56STom N Harris $addwords = true; 281d5b23302STom N Harris } 282e1e1a7e0SMichael Hamann // test if value is already in the index 28339134585SChristopher Smith if (isset($val_idx[$id]) && $val_idx[$id] <= 0){ 284e1e1a7e0SMichael Hamann $val_idx[$id] = 0; 28539134585SChristopher Smith } else { // else add it 286e1e1a7e0SMichael Hamann $val_idx[$id] = 1; 28744ca0adfSAndreas Gohr } 288579b0f7eSTNHarris } 28939134585SChristopher Smith } 290e1e1a7e0SMichael Hamann 29139134585SChristopher Smith if ($addwords) { 29280fb93f6STom N Harris $this->saveIndex($metaname.'_w', '', $metawords); 29339134585SChristopher Smith } 294e1e1a7e0SMichael Hamann $vals_changed = false; 295e1e1a7e0SMichael Hamann foreach ($val_idx as $id => $action) { 296e1e1a7e0SMichael Hamann if ($action == -1) { 29780fb93f6STom N Harris $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0); 298e1e1a7e0SMichael Hamann $vals_changed = true; 299e1e1a7e0SMichael Hamann unset($val_idx[$id]); 300e1e1a7e0SMichael Hamann } elseif ($action == 1) { 30180fb93f6STom N Harris $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1); 302e1e1a7e0SMichael Hamann $vals_changed = true; 303e1e1a7e0SMichael Hamann } 304e1e1a7e0SMichael Hamann } 305e1e1a7e0SMichael Hamann 306e1e1a7e0SMichael Hamann if ($vals_changed) { 30780fb93f6STom N Harris $this->saveIndex($metaname.'_i', '', $metaidx); 308e1e1a7e0SMichael Hamann $val_idx = implode(':', array_keys($val_idx)); 30980fb93f6STom N Harris $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx); 310b6344591STom N Harris } 311e1e1a7e0SMichael Hamann 31200803e56STom N Harris unset($metaidx); 31300803e56STom N Harris unset($metawords); 314a0c5c349STom N Harris } 315e1e1a7e0SMichael Hamann 31680fb93f6STom N Harris $this->unlock(); 317579b0f7eSTNHarris return true; 31844ca0adfSAndreas Gohr } 31944ca0adfSAndreas Gohr 32044ca0adfSAndreas Gohr /** 321af73bba6SMichael Hamann * Rename a page in the search index without changing the indexed content. This function doesn't check if the 322af73bba6SMichael 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 323af73bba6SMichael Hamann * indexer and it deletes all previously indexed content of the new page. 3245eb9e867SMichael Hamann * 3255eb9e867SMichael Hamann * @param string $oldpage The old page name 3265eb9e867SMichael Hamann * @param string $newpage The new page name 3275eb9e867SMichael Hamann * @return string|bool If the page was successfully renamed, can be a message in the case of an error 3285eb9e867SMichael Hamann */ 3295eb9e867SMichael Hamann public function renamePage($oldpage, $newpage) { 3305eb9e867SMichael Hamann if (!$this->lock()) return 'locked'; 3315eb9e867SMichael Hamann 3325eb9e867SMichael Hamann $pages = $this->getPages(); 3335eb9e867SMichael Hamann 334a8dba452SMichael Hamann $id = array_search($oldpage, $pages, true); 3355eb9e867SMichael Hamann if ($id === false) { 3365eb9e867SMichael Hamann $this->unlock(); 3375eb9e867SMichael Hamann return 'page is not in index'; 3385eb9e867SMichael Hamann } 3395eb9e867SMichael Hamann 340a8dba452SMichael Hamann $new_id = array_search($newpage, $pages, true); 3415eb9e867SMichael Hamann if ($new_id !== false) { 3425eb9e867SMichael Hamann // make sure the page is not in the index anymore 343bc27f3e2SMichael Hamann if ($this->deletePageNoLock($newpage) !== true) { 344bc27f3e2SMichael Hamann return false; 345bc27f3e2SMichael Hamann } 3465eb9e867SMichael Hamann 3475eb9e867SMichael Hamann $pages[$new_id] = 'deleted:'.time().rand(0, 9999); 3485eb9e867SMichael Hamann } 3495eb9e867SMichael Hamann 3505eb9e867SMichael Hamann $pages[$id] = $newpage; 3515eb9e867SMichael Hamann 3525eb9e867SMichael Hamann // update index 3535eb9e867SMichael Hamann if (!$this->saveIndex('page', '', $pages)) { 3545eb9e867SMichael Hamann $this->unlock(); 3555eb9e867SMichael Hamann return false; 3565eb9e867SMichael Hamann } 3575eb9e867SMichael Hamann 3585eb9e867SMichael Hamann // reset the pid cache 3595eb9e867SMichael Hamann $this->pidCache = array(); 3605eb9e867SMichael Hamann 3615eb9e867SMichael Hamann $this->unlock(); 3625eb9e867SMichael Hamann return true; 3635eb9e867SMichael Hamann } 3645eb9e867SMichael Hamann 3655eb9e867SMichael Hamann /** 3665eb9e867SMichael Hamann * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages 3675eb9e867SMichael Hamann * will be updated. 3685eb9e867SMichael Hamann * 3695eb9e867SMichael Hamann * @param string $key The metadata key of which a value shall be changed 3705eb9e867SMichael Hamann * @param string $oldvalue The old value that shall be renamed 37164159a61SAndreas Gohr * @param string $newvalue The new value to which the old value shall be renamed, if exists values will be merged 3725eb9e867SMichael Hamann * @return bool|string If renaming the value has been successful, false or error message on error. 3735eb9e867SMichael Hamann */ 3745eb9e867SMichael Hamann public function renameMetaValue($key, $oldvalue, $newvalue) { 3755eb9e867SMichael Hamann if (!$this->lock()) return 'locked'; 3765eb9e867SMichael Hamann 3775eb9e867SMichael Hamann // change the relation references index 3785eb9e867SMichael Hamann $metavalues = $this->getIndex($key, '_w'); 379a8dba452SMichael Hamann $oldid = array_search($oldvalue, $metavalues, true); 3805eb9e867SMichael Hamann if ($oldid !== false) { 381a8dba452SMichael Hamann $newid = array_search($newvalue, $metavalues, true); 3825eb9e867SMichael Hamann if ($newid !== false) { 3835eb9e867SMichael Hamann // free memory 3845eb9e867SMichael Hamann unset ($metavalues); 3855eb9e867SMichael Hamann 3865eb9e867SMichael Hamann // okay, now we have two entries for the same value. we need to merge them. 3879e64ca0dSMichael Hamann $indexline = $this->getIndexKey($key.'_i', '', $oldid); 3885eb9e867SMichael Hamann if ($indexline != '') { 3899e64ca0dSMichael Hamann $newindexline = $this->getIndexKey($key.'_i', '', $newid); 3909e64ca0dSMichael Hamann $pagekeys = $this->getIndex($key.'_p', ''); 3915eb9e867SMichael Hamann $parts = explode(':', $indexline); 3925eb9e867SMichael Hamann foreach ($parts as $part) { 3935eb9e867SMichael Hamann list($id, $count) = explode('*', $part); 3945eb9e867SMichael Hamann $newindexline = $this->updateTuple($newindexline, $id, $count); 3955eb9e867SMichael Hamann 3965eb9e867SMichael Hamann $keyline = explode(':', $pagekeys[$id]); 3975eb9e867SMichael Hamann // remove old meta value 3985eb9e867SMichael Hamann $keyline = array_diff($keyline, array($oldid)); 3995eb9e867SMichael Hamann // add new meta value when not already present 4005eb9e867SMichael Hamann if (!in_array($newid, $keyline)) { 4015eb9e867SMichael Hamann array_push($keyline, $newid); 4025eb9e867SMichael Hamann } 4035eb9e867SMichael Hamann $pagekeys[$id] = implode(':', $keyline); 4045eb9e867SMichael Hamann } 4059e64ca0dSMichael Hamann $this->saveIndex($key.'_p', '', $pagekeys); 4065eb9e867SMichael Hamann unset($pagekeys); 4079e64ca0dSMichael Hamann $this->saveIndexKey($key.'_i', '', $oldid, ''); 4089e64ca0dSMichael Hamann $this->saveIndexKey($key.'_i', '', $newid, $newindexline); 4095eb9e867SMichael Hamann } 4105eb9e867SMichael Hamann } else { 4115eb9e867SMichael Hamann $metavalues[$oldid] = $newvalue; 4129e64ca0dSMichael Hamann if (!$this->saveIndex($key.'_w', '', $metavalues)) { 4135eb9e867SMichael Hamann $this->unlock(); 4145eb9e867SMichael Hamann return false; 4155eb9e867SMichael Hamann } 4165eb9e867SMichael Hamann } 4175eb9e867SMichael Hamann } 4185eb9e867SMichael Hamann 4195eb9e867SMichael Hamann $this->unlock(); 4205eb9e867SMichael Hamann return true; 4215eb9e867SMichael Hamann } 42225adeb91SMichael Hamann 4235eb9e867SMichael Hamann /** 42400803e56STom N Harris * Remove a page from the index 42544ca0adfSAndreas Gohr * 42600803e56STom N Harris * Erases entries in all known indexes. 42744ca0adfSAndreas Gohr * 42800803e56STom N Harris * @param string $page a page name 42942ea7f44SGerrit Uitslag * @return string|boolean the function completed successfully 43042ea7f44SGerrit Uitslag * 43100803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 43244ca0adfSAndreas Gohr */ 43300803e56STom N Harris public function deletePage($page) { 43480fb93f6STom N Harris if (!$this->lock()) 435bbc85ee4STom N Harris return "locked"; 436bbc85ee4STom N Harris 43725adeb91SMichael Hamann $result = $this->deletePageNoLock($page); 43825adeb91SMichael Hamann 43925adeb91SMichael Hamann $this->unlock(); 44025adeb91SMichael Hamann 44125adeb91SMichael Hamann return $result; 44225adeb91SMichael Hamann } 44325adeb91SMichael Hamann 44425adeb91SMichael Hamann /** 44525adeb91SMichael Hamann * Remove a page from the index without locking the index, only use this function if the index is already locked 44625adeb91SMichael Hamann * 44725adeb91SMichael Hamann * Erases entries in all known indexes. 44825adeb91SMichael Hamann * 44925adeb91SMichael Hamann * @param string $page a page name 45025adeb91SMichael Hamann * @return boolean the function completed successfully 45142ea7f44SGerrit Uitslag * 45225adeb91SMichael Hamann * @author Tom N Harris <tnharris@whoopdedo.org> 45325adeb91SMichael Hamann */ 45425adeb91SMichael Hamann protected function deletePageNoLock($page) { 455bbc85ee4STom N Harris // load known documents 45603aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 4575981eb09STom N Harris if ($pid === false) { 458bbc85ee4STom N Harris return false; 459bbc85ee4STom N Harris } 460bbc85ee4STom N Harris 461bbc85ee4STom N Harris // Remove obsolete index entries 46280fb93f6STom N Harris $pageword_idx = $this->getIndexKey('pageword', '', $pid); 463bbc85ee4STom N Harris if ($pageword_idx !== '') { 464bbc85ee4STom N Harris $delwords = explode(':',$pageword_idx); 465bbc85ee4STom N Harris $upwords = array(); 466bbc85ee4STom N Harris foreach ($delwords as $word) { 467bbc85ee4STom N Harris if ($word != '') { 468bbc85ee4STom N Harris list($wlen,$wid) = explode('*', $word); 469bbc85ee4STom N Harris $wid = (int)$wid; 470bbc85ee4STom N Harris $upwords[$wlen][] = $wid; 471bbc85ee4STom N Harris } 472bbc85ee4STom N Harris } 473bbc85ee4STom N Harris foreach ($upwords as $wlen => $widx) { 47480fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 475bbc85ee4STom N Harris foreach ($widx as $wid) { 47680fb93f6STom N Harris $index[$wid] = $this->updateTuple($index[$wid], $pid, 0); 477bbc85ee4STom N Harris } 47880fb93f6STom N Harris $this->saveIndex('i', $wlen, $index); 479bbc85ee4STom N Harris } 480bbc85ee4STom N Harris } 481bbc85ee4STom N Harris // Save the reverse index 48280fb93f6STom N Harris if (!$this->saveIndexKey('pageword', '', $pid, "")) { 483bbc85ee4STom N Harris return false; 484bbc85ee4STom N Harris } 485bbc85ee4STom N Harris 48680fb93f6STom N Harris $this->saveIndexKey('title', '', $pid, ""); 48780fb93f6STom N Harris $keyidx = $this->getIndex('metadata', ''); 4880604da34STom N Harris foreach ($keyidx as $metaname) { 48980fb93f6STom N Harris $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid)); 49080fb93f6STom N Harris $meta_idx = $this->getIndex($metaname.'_i', ''); 4910604da34STom N Harris foreach ($val_idx as $id) { 492c55c59e3SMichael Hamann if ($id === '') continue; 49380fb93f6STom N Harris $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0); 4940604da34STom N Harris } 49580fb93f6STom N Harris $this->saveIndex($metaname.'_i', '', $meta_idx); 49680fb93f6STom N Harris $this->saveIndexKey($metaname.'_p', '', $pid, ''); 4970604da34STom N Harris } 498bbc85ee4STom N Harris 499bbc85ee4STom N Harris return true; 500d5b23302STom N Harris } 50144ca0adfSAndreas Gohr 502d5b23302STom N Harris /** 5033cf3c7d6SMichael Hamann * Clear the whole index 5043cf3c7d6SMichael Hamann * 5053cf3c7d6SMichael Hamann * @return bool If the index has been cleared successfully 5063cf3c7d6SMichael Hamann */ 5073cf3c7d6SMichael Hamann public function clear() { 5083cf3c7d6SMichael Hamann global $conf; 5093cf3c7d6SMichael Hamann 5103cf3c7d6SMichael Hamann if (!$this->lock()) return false; 5113cf3c7d6SMichael Hamann 5123cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/page.idx'); 5133cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/title.idx'); 5143cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/pageword.idx'); 5153cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/metadata.idx'); 5163cf3c7d6SMichael Hamann $dir = @opendir($conf['indexdir']); 5173cf3c7d6SMichael Hamann if($dir!==false){ 5183cf3c7d6SMichael Hamann while(($f = readdir($dir)) !== false){ 5193cf3c7d6SMichael Hamann if(substr($f,-4)=='.idx' && 5203cf3c7d6SMichael Hamann (substr($f,0,1)=='i' || substr($f,0,1)=='w' 5213cf3c7d6SMichael Hamann || substr($f,-6)=='_w.idx' || substr($f,-6)=='_i.idx' || substr($f,-6)=='_p.idx')) 5223cf3c7d6SMichael Hamann @unlink($conf['indexdir']."/$f"); 5233cf3c7d6SMichael Hamann } 5243cf3c7d6SMichael Hamann } 5253cf3c7d6SMichael Hamann @unlink($conf['indexdir'].'/lengths.idx'); 5263cf3c7d6SMichael Hamann 5273cf3c7d6SMichael Hamann // clear the pid cache 5283cf3c7d6SMichael Hamann $this->pidCache = array(); 5293cf3c7d6SMichael Hamann 5303cf3c7d6SMichael Hamann $this->unlock(); 5313cf3c7d6SMichael Hamann return true; 5323cf3c7d6SMichael Hamann } 5333cf3c7d6SMichael Hamann 5343cf3c7d6SMichael Hamann /** 53500803e56STom N Harris * Split the text into words for fulltext search 536d5b23302STom N Harris * 53700803e56STom N Harris * TODO: does this also need &$stopwords ? 538d5b23302STom N Harris * 5398cd4c12fSAndreas Gohr * @triggers INDEXER_TEXT_PREPARE 5408cd4c12fSAndreas Gohr * This event allows plugins to modify the text before it gets tokenized. 5418cd4c12fSAndreas Gohr * Plugins intercepting this event should also intercept INDEX_VERSION_GET 5428cd4c12fSAndreas Gohr * 54300803e56STom N Harris * @param string $text plain text 54400803e56STom N Harris * @param boolean $wc are wildcards allowed? 54500803e56STom N Harris * @return array list of words in the text 54642ea7f44SGerrit Uitslag * 547d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 548d5b23302STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 549d5b23302STom N Harris */ 55000803e56STom N Harris public function tokenizer($text, $wc=false) { 55100803e56STom N Harris $wc = ($wc) ? '' : '\*'; 55200803e56STom N Harris $stopwords =& idx_get_stopwords(); 55300803e56STom N Harris 5548cd4c12fSAndreas Gohr // prepare the text to be tokenized 555e1d9dcc8SAndreas Gohr $evt = new Event('INDEXER_TEXT_PREPARE', $text); 5568cd4c12fSAndreas Gohr if ($evt->advise_before(true)) { 55700803e56STom N Harris if (preg_match('/[^0-9A-Za-z ]/u', $text)) { 558*dbc189b2SAndreas Gohr $text = \dokuwiki\Utf8\Asian::separateAsianWords($text); 55922952965SYoBoY } 56022952965SYoBoY } 5618cd4c12fSAndreas Gohr $evt->advise_after(); 5628cd4c12fSAndreas Gohr unset($evt); 5638cd4c12fSAndreas Gohr 564f77fc90dSMichael Hamann $text = strtr($text, 5654f0030ddSAndreas Gohr array( 5664f0030ddSAndreas Gohr "\r" => ' ', 5674f0030ddSAndreas Gohr "\n" => ' ', 5684f0030ddSAndreas Gohr "\t" => ' ', 5694f0030ddSAndreas Gohr "\xC2\xAD" => '', //soft-hyphen 5704f0030ddSAndreas Gohr ) 5714f0030ddSAndreas Gohr ); 57200803e56STom N Harris if (preg_match('/[^0-9A-Za-z ]/u', $text)) 5738cbc5ee8SAndreas Gohr $text = \dokuwiki\Utf8\Clean::stripspecials($text, ' ', '\._\-:'.$wc); 57422952965SYoBoY 57500803e56STom N Harris $wordlist = explode(' ', $text); 5765f27cb0eSMichael Hamann foreach ($wordlist as $i => $word) { 5775f27cb0eSMichael Hamann $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ? 5788cbc5ee8SAndreas Gohr \dokuwiki\Utf8\PhpString::strtolower($word) : strtolower($word); 5795f27cb0eSMichael Hamann } 5805f27cb0eSMichael Hamann 5815f27cb0eSMichael Hamann foreach ($wordlist as $i => $word) { 582675bf41fSTom N Harris if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) 583a8dba452SMichael Hamann || array_search($word, $stopwords, true) !== false) 584675bf41fSTom N Harris unset($wordlist[$i]); 58522952965SYoBoY } 586675bf41fSTom N Harris return array_values($wordlist); 58722952965SYoBoY } 58822952965SYoBoY 58922952965SYoBoY /** 59003aafe1cSMichael Hamann * Get the numeric PID of a page 59103aafe1cSMichael Hamann * 59203aafe1cSMichael Hamann * @param string $page The page to get the PID for 59303aafe1cSMichael Hamann * @return bool|int The page id on success, false on error 59403aafe1cSMichael Hamann */ 59503aafe1cSMichael Hamann public function getPID($page) { 5963d2ce006SMichael Hamann // return PID without locking when it is in the cache 5973d2ce006SMichael Hamann if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 5983d2ce006SMichael Hamann 59903aafe1cSMichael Hamann if (!$this->lock()) 60003aafe1cSMichael Hamann return false; 60103aafe1cSMichael Hamann 60203aafe1cSMichael Hamann // load known documents 60303aafe1cSMichael Hamann $pid = $this->getPIDNoLock($page); 60403aafe1cSMichael Hamann if ($pid === false) { 60503aafe1cSMichael Hamann $this->unlock(); 60603aafe1cSMichael Hamann return false; 60703aafe1cSMichael Hamann } 60803aafe1cSMichael Hamann 60903aafe1cSMichael Hamann $this->unlock(); 61003aafe1cSMichael Hamann return $pid; 61103aafe1cSMichael Hamann } 61203aafe1cSMichael Hamann 61303aafe1cSMichael Hamann /** 61403aafe1cSMichael Hamann * Get the numeric PID of a page without locking the index. 61503aafe1cSMichael Hamann * Only use this function when the index is already locked. 61603aafe1cSMichael Hamann * 61703aafe1cSMichael Hamann * @param string $page The page to get the PID for 61803aafe1cSMichael Hamann * @return bool|int The page id on success, false on error 61903aafe1cSMichael Hamann */ 62003aafe1cSMichael Hamann protected function getPIDNoLock($page) { 6213d2ce006SMichael Hamann // avoid expensive addIndexKey operation for the most recently requested pages by using a cache 6223d2ce006SMichael Hamann if (isset($this->pidCache[$page])) return $this->pidCache[$page]; 6233d2ce006SMichael Hamann $pid = $this->addIndexKey('page', '', $page); 6243d2ce006SMichael Hamann // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently 6253d2ce006SMichael Hamann // added item will be requested again 6263d2ce006SMichael Hamann if (count($this->pidCache) > 10) array_shift($this->pidCache); 6273d2ce006SMichael Hamann $this->pidCache[$page] = $pid; 6283d2ce006SMichael Hamann return $pid; 62903aafe1cSMichael Hamann } 63003aafe1cSMichael Hamann 63103aafe1cSMichael Hamann /** 63203aafe1cSMichael Hamann * Get the page id of a numeric PID 63303aafe1cSMichael Hamann * 63403aafe1cSMichael Hamann * @param int $pid The PID to get the page id for 63503aafe1cSMichael Hamann * @return string The page id 63603aafe1cSMichael Hamann */ 63703aafe1cSMichael Hamann public function getPageFromPID($pid) { 63803aafe1cSMichael Hamann return $this->getIndexKey('page', '', $pid); 63903aafe1cSMichael Hamann } 64003aafe1cSMichael Hamann 64103aafe1cSMichael Hamann /** 64200803e56STom N Harris * Find pages in the fulltext index containing the words, 643579b0f7eSTNHarris * 64400803e56STom N Harris * The search words must be pre-tokenized, meaning only letters and 64500803e56STom N Harris * numbers with an optional wildcard 646579b0f7eSTNHarris * 64700803e56STom N Harris * The returned array will have the original tokens as key. The values 64800803e56STom N Harris * in the returned list is an array with the page names as keys and the 649b00bd361STom N Harris * number of times that token appears on the page as value. 65000803e56STom N Harris * 651e3ab6fc5SMichael Hamann * @param array $tokens list of words to search for 65200803e56STom N Harris * @return array list of page names with usage counts 65342ea7f44SGerrit Uitslag * 65400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 65500803e56STom N Harris * @author Andreas Gohr <andi@splitbrain.org> 656579b0f7eSTNHarris */ 6579b41be24STom N Harris public function lookup(&$tokens) { 65800803e56STom N Harris $result = array(); 65980fb93f6STom N Harris $wids = $this->getIndexWords($tokens, $result); 66000803e56STom N Harris if (empty($wids)) return array(); 66100803e56STom N Harris // load known words and documents 66280fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 66300803e56STom N Harris $docs = array(); 66400803e56STom N Harris foreach (array_keys($wids) as $wlen) { 66500803e56STom N Harris $wids[$wlen] = array_unique($wids[$wlen]); 66680fb93f6STom N Harris $index = $this->getIndex('i', $wlen); 66700803e56STom N Harris foreach($wids[$wlen] as $ixid) { 66800803e56STom N Harris if ($ixid < count($index)) 66980fb93f6STom N Harris $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]); 670d5b23302STom N Harris } 671d5b23302STom N Harris } 67200803e56STom N Harris // merge found pages into final result array 67300803e56STom N Harris $final = array(); 67400803e56STom N Harris foreach ($result as $word => $res) { 67500803e56STom N Harris $final[$word] = array(); 67600803e56STom N Harris foreach ($res as $wid) { 677952ab260SMichael Hamann // handle the case when ($ixid < count($index)) has been false 678952ab260SMichael Hamann // and thus $docs[$wid] hasn't been set. 679952ab260SMichael Hamann if (!isset($docs[$wid])) continue; 68000803e56STom N Harris $hits = &$docs[$wid]; 68100803e56STom N Harris foreach ($hits as $hitkey => $hitcnt) { 68200803e56STom N Harris // make sure the document still exists 68300803e56STom N Harris if (!page_exists($hitkey, '', false)) continue; 68400803e56STom N Harris if (!isset($final[$word][$hitkey])) 68500803e56STom N Harris $final[$word][$hitkey] = $hitcnt; 68600803e56STom N Harris else 68700803e56STom N Harris $final[$word][$hitkey] += $hitcnt; 688d5b23302STom N Harris } 689579b0f7eSTNHarris } 690579b0f7eSTNHarris } 69100803e56STom N Harris return $final; 692579b0f7eSTNHarris } 693579b0f7eSTNHarris 694579b0f7eSTNHarris /** 69500803e56STom N Harris * Find pages containing a metadata key. 696d5b23302STom N Harris * 69700803e56STom N Harris * The metadata values are compared as case-sensitive strings. Pass a 69800803e56STom N Harris * callback function that returns true or false to use a different 699b00bd361STom N Harris * comparison function. The function will be called with the $value being 700b00bd361STom N Harris * searched for as the first argument, and the word in the index as the 7011538718dSTom N Harris * second argument. The function preg_match can be used directly if the 7021538718dSTom N Harris * values are regexes. 703d5b23302STom N Harris * 70400803e56STom N Harris * @param string $key name of the metadata key to look for 7051538718dSTom N Harris * @param string $value search term to look for, must be a string or array of strings 70600803e56STom N Harris * @param callback $func comparison function 707b00bd361STom N Harris * @return array lists with page names, keys are query values if $value is array 70842ea7f44SGerrit Uitslag * 70900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 710cd763a5bSMichael Hamann * @author Michael Hamann <michael@content-space.de> 71100803e56STom N Harris */ 712b00bd361STom N Harris public function lookupKey($key, &$value, $func=null) { 713f078bb00STom N Harris if (!is_array($value)) 714f078bb00STom N Harris $value_array = array($value); 715f078bb00STom N Harris else 716f078bb00STom N Harris $value_array =& $value; 717cd763a5bSMichael Hamann 718c1209673STom N Harris // the matching ids for the provided value(s) 719c1209673STom N Harris $value_ids = array(); 720c1209673STom N Harris 721c1209673STom N Harris $metaname = idx_cleanName($key); 722c1209673STom N Harris 723c1209673STom N Harris // get all words in order to search the matching ids 724c1209673STom N Harris if ($key == 'title') { 72580fb93f6STom N Harris $words = $this->getIndex('title', ''); 726c1209673STom N Harris } else { 727b9d8cc1eSTom N Harris $words = $this->getIndex($metaname.'_w', ''); 728c1209673STom N Harris } 729c1209673STom N Harris 730f078bb00STom N Harris if (!is_null($func)) { 7311538718dSTom N Harris foreach ($value_array as $val) { 732f078bb00STom N Harris foreach ($words as $i => $word) { 7331538718dSTom N Harris if (call_user_func_array($func, array($val, $word))) 734c1209673STom N Harris $value_ids[$i][] = $val; 735f078bb00STom N Harris } 736f078bb00STom N Harris } 737f078bb00STom N Harris } else { 738f078bb00STom N Harris foreach ($value_array as $val) { 739f078bb00STom N Harris $xval = $val; 740b6d540bdSTom N Harris $caret = '^'; 741b6d540bdSTom N Harris $dollar = '$'; 742f078bb00STom N Harris // check for wildcards 743f078bb00STom N Harris if (substr($xval, 0, 1) == '*') { 744f078bb00STom N Harris $xval = substr($xval, 1); 745b6d540bdSTom N Harris $caret = ''; 746f078bb00STom N Harris } 747f078bb00STom N Harris if (substr($xval, -1, 1) == '*') { 748f078bb00STom N Harris $xval = substr($xval, 0, -1); 749b6d540bdSTom N Harris $dollar = ''; 750f078bb00STom N Harris } 751b6d540bdSTom N Harris if (!$caret || !$dollar) { 752f078bb00STom N Harris $re = $caret.preg_quote($xval, '/').$dollar; 753f078bb00STom N Harris foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i) 754c1209673STom N Harris $value_ids[$i][] = $val; 755cd763a5bSMichael Hamann } else { 756a8dba452SMichael Hamann if (($i = array_search($val, $words, true)) !== false) 757c1209673STom N Harris $value_ids[$i][] = $val; 758cd763a5bSMichael Hamann } 759cd763a5bSMichael Hamann } 760cd763a5bSMichael Hamann } 761cd763a5bSMichael Hamann 762cd763a5bSMichael Hamann unset($words); // free the used memory 763cd763a5bSMichael Hamann 7647233c152SMichael Hamann // initialize the result so it won't be null 765c1209673STom N Harris $result = array(); 7667233c152SMichael Hamann foreach ($value_array as $val) { 7677233c152SMichael Hamann $result[$val] = array(); 7687233c152SMichael Hamann } 7697233c152SMichael Hamann 77080fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 771cd763a5bSMichael Hamann 772c1209673STom N Harris // Special handling for titles 773c1209673STom N Harris if ($key == 'title') { 774c1209673STom N Harris foreach ($value_ids as $pid => $val_list) { 775c1209673STom N Harris $page = $page_idx[$pid]; 776c1209673STom N Harris foreach ($val_list as $val) { 777c1209673STom N Harris $result[$val][] = $page; 778c1209673STom N Harris } 779c1209673STom N Harris } 780c1209673STom N Harris } else { 781c1209673STom N Harris // load all lines and pages so the used lines can be taken and matched with the pages 782b9d8cc1eSTom N Harris $lines = $this->getIndex($metaname.'_i', ''); 783c1209673STom N Harris 784c1209673STom N Harris foreach ($value_ids as $value_id => $val_list) { 785cd763a5bSMichael Hamann // parse the tuples of the form page_id*1:page2_id*1 and so on, return value 786cd763a5bSMichael Hamann // is an array with page_id => 1, page2_id => 1 etc. so take the keys only 78780fb93f6STom N Harris $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id])); 788c1209673STom N Harris foreach ($val_list as $val) { 789c1209673STom N Harris $result[$val] = array_merge($result[$val], $pages); 790c1209673STom N Harris } 791c1209673STom N Harris } 792cd763a5bSMichael Hamann } 793f078bb00STom N Harris if (!is_array($value)) $result = $result[$value]; 794cd763a5bSMichael Hamann return $result; 79500803e56STom N Harris } 79600803e56STom N Harris 79700803e56STom N Harris /** 79800803e56STom N Harris * Find the index ID of each search term. 79900803e56STom N Harris * 80000803e56STom N Harris * The query terms should only contain valid characters, with a '*' at 80100803e56STom N Harris * either the beginning or end of the word (or both). 80200803e56STom N Harris * The $result parameter can be used to merge the index locations with 80300803e56STom N Harris * the appropriate query term. 80400803e56STom N Harris * 805e3ab6fc5SMichael Hamann * @param array $words The query terms. 806e3ab6fc5SMichael Hamann * @param array $result Set to word => array("length*id" ...) 807d5b23302STom N Harris * @return array Set to length => array(id ...) 80842ea7f44SGerrit Uitslag * 809d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 810d5b23302STom N Harris */ 81180fb93f6STom N Harris protected function getIndexWords(&$words, &$result) { 812d5b23302STom N Harris $tokens = array(); 813d5b23302STom N Harris $tokenlength = array(); 814d5b23302STom N Harris $tokenwild = array(); 815d5b23302STom N Harris foreach ($words as $word) { 816d5b23302STom N Harris $result[$word] = array(); 817b6d540bdSTom N Harris $caret = '^'; 818b6d540bdSTom N Harris $dollar = '$'; 819d5b23302STom N Harris $xword = $word; 820d5b23302STom N Harris $wlen = wordlen($word); 821d5b23302STom N Harris 822d5b23302STom N Harris // check for wildcards 823d5b23302STom N Harris if (substr($xword, 0, 1) == '*') { 824d5b23302STom N Harris $xword = substr($xword, 1); 825b6d540bdSTom N Harris $caret = ''; 826d5b23302STom N Harris $wlen -= 1; 827d5b23302STom N Harris } 828d5b23302STom N Harris if (substr($xword, -1, 1) == '*') { 829d5b23302STom N Harris $xword = substr($xword, 0, -1); 830b6d540bdSTom N Harris $dollar = ''; 831d5b23302STom N Harris $wlen -= 1; 832d5b23302STom N Harris } 833b6d540bdSTom N Harris if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword)) 83400803e56STom N Harris continue; 83500803e56STom N Harris if (!isset($tokens[$xword])) 836d5b23302STom N Harris $tokenlength[$wlen][] = $xword; 837b6d540bdSTom N Harris if (!$caret || !$dollar) { 838f078bb00STom N Harris $re = $caret.preg_quote($xword, '/').$dollar; 83900803e56STom N Harris $tokens[$xword][] = array($word, '/'.$re.'/'); 84000803e56STom N Harris if (!isset($tokenwild[$xword])) 84100803e56STom N Harris $tokenwild[$xword] = $wlen; 84200803e56STom N Harris } else { 843d5b23302STom N Harris $tokens[$xword][] = array($word, null); 844d5b23302STom N Harris } 84500803e56STom N Harris } 846d5b23302STom N Harris asort($tokenwild); 84700803e56STom N Harris // $tokens = array( base word => array( [ query term , regexp ] ... ) ... ) 848d5b23302STom N Harris // $tokenlength = array( base word length => base word ... ) 849d5b23302STom N Harris // $tokenwild = array( base word => base word length ... ) 850d5b23302STom N Harris $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength)); 85180fb93f6STom N Harris $indexes_known = $this->indexLengths($length_filter); 852d5b23302STom N Harris if (!empty($tokenwild)) sort($indexes_known); 853d5b23302STom N Harris // get word IDs 854d5b23302STom N Harris $wids = array(); 855d5b23302STom N Harris foreach ($indexes_known as $ixlen) { 85680fb93f6STom N Harris $word_idx = $this->getIndex('w', $ixlen); 857d5b23302STom N Harris // handle exact search 858d5b23302STom N Harris if (isset($tokenlength[$ixlen])) { 859d5b23302STom N Harris foreach ($tokenlength[$ixlen] as $xword) { 860a8dba452SMichael Hamann $wid = array_search($xword, $word_idx, true); 86100803e56STom N Harris if ($wid !== false) { 862d5b23302STom N Harris $wids[$ixlen][] = $wid; 863d5b23302STom N Harris foreach ($tokens[$xword] as $w) 864d5b23302STom N Harris $result[$w[0]][] = "$ixlen*$wid"; 865d5b23302STom N Harris } 866d5b23302STom N Harris } 867d5b23302STom N Harris } 868d5b23302STom N Harris // handle wildcard search 869d5b23302STom N Harris foreach ($tokenwild as $xword => $wlen) { 870d5b23302STom N Harris if ($wlen >= $ixlen) break; 871d5b23302STom N Harris foreach ($tokens[$xword] as $w) { 872d5b23302STom N Harris if (is_null($w[1])) continue; 873d5b23302STom N Harris foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) { 874d5b23302STom N Harris $wids[$ixlen][] = $wid; 875d5b23302STom N Harris $result[$w[0]][] = "$ixlen*$wid"; 876d5b23302STom N Harris } 877d5b23302STom N Harris } 878d5b23302STom N Harris } 879d5b23302STom N Harris } 880d5b23302STom N Harris return $wids; 881d5b23302STom N Harris } 882d5b23302STom N Harris 883d5b23302STom N Harris /** 88400803e56STom N Harris * Return a list of all pages 885c1209673STom N Harris * Warning: pages may not exist! 886488dd6ceSAndreas Gohr * 88700803e56STom N Harris * @param string $key list only pages containing the metadata key (optional) 88800803e56STom N Harris * @return array list of page names 88942ea7f44SGerrit Uitslag * 89000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 89100803e56STom N Harris */ 89200803e56STom N Harris public function getPages($key=null) { 89380fb93f6STom N Harris $page_idx = $this->getIndex('page', ''); 89400803e56STom N Harris if (is_null($key)) return $page_idx; 895c1209673STom N Harris 896c1209673STom N Harris $metaname = idx_cleanName($key); 897c1209673STom N Harris 898c1209673STom N Harris // Special handling for titles 899c1209673STom N Harris if ($key == 'title') { 90080fb93f6STom N Harris $title_idx = $this->getIndex('title', ''); 901c1209673STom N Harris array_splice($page_idx, count($title_idx)); 902c1209673STom N Harris foreach ($title_idx as $i => $title) 903c1209673STom N Harris if ($title === "") unset($page_idx[$i]); 904675bf41fSTom N Harris return array_values($page_idx); 905c1209673STom N Harris } 906c1209673STom N Harris 907c1209673STom N Harris $pages = array(); 908b9d8cc1eSTom N Harris $lines = $this->getIndex($metaname.'_i', ''); 909c1209673STom N Harris foreach ($lines as $line) { 91080fb93f6STom N Harris $pages = array_merge($pages, $this->parseTuples($page_idx, $line)); 911c1209673STom N Harris } 912c1209673STom N Harris return array_keys($pages); 91300803e56STom N Harris } 91400803e56STom N Harris 91500803e56STom N Harris /** 91600803e56STom N Harris * Return a list of words sorted by number of times used 91700803e56STom N Harris * 91800803e56STom N Harris * @param int $min bottom frequency threshold 91900803e56STom N Harris * @param int $max upper frequency limit. No limit if $max<$min 920e3ab6fc5SMichael Hamann * @param int $minlen minimum length of words to count 92100803e56STom N Harris * @param string $key metadata key to list. Uses the fulltext index if not given 92200803e56STom N Harris * @return array list of words as the keys and frequency as values 92342ea7f44SGerrit Uitslag * 92400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 92500803e56STom N Harris */ 926b8c040dbSTom N Harris public function histogram($min=1, $max=0, $minlen=3, $key=null) { 927175193d2STom N Harris if ($min < 1) 928175193d2STom N Harris $min = 1; 929175193d2STom N Harris if ($max < $min) 930175193d2STom N Harris $max = 0; 931175193d2STom N Harris 932175193d2STom N Harris $result = array(); 933175193d2STom N Harris 934175193d2STom N Harris if ($key == 'title') { 93580fb93f6STom N Harris $index = $this->getIndex('title', ''); 936175193d2STom N Harris $index = array_count_values($index); 937175193d2STom N Harris foreach ($index as $val => $cnt) { 938b8c040dbSTom N Harris if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen) 939175193d2STom N Harris $result[$val] = $cnt; 940175193d2STom N Harris } 941175193d2STom N Harris } 942175193d2STom N Harris elseif (!is_null($key)) { 943175193d2STom N Harris $metaname = idx_cleanName($key); 94480fb93f6STom N Harris $index = $this->getIndex($metaname.'_i', ''); 945175193d2STom N Harris $val_idx = array(); 946175193d2STom N Harris foreach ($index as $wid => $line) { 94780fb93f6STom N Harris $freq = $this->countTuples($line); 9489a9b579aSMichael Hamann if ($freq >= $min && (!$max || $freq <= $max)) 949175193d2STom N Harris $val_idx[$wid] = $freq; 950175193d2STom N Harris } 951175193d2STom N Harris if (!empty($val_idx)) { 95280fb93f6STom N Harris $words = $this->getIndex($metaname.'_w', ''); 9539a9b579aSMichael Hamann foreach ($val_idx as $wid => $freq) { 9549a9b579aSMichael Hamann if (strlen($words[$wid]) >= $minlen) 955175193d2STom N Harris $result[$words[$wid]] = $freq; 956175193d2STom N Harris } 957175193d2STom N Harris } 9589a9b579aSMichael Hamann } 959175193d2STom N Harris else { 960175193d2STom N Harris $lengths = idx_listIndexLengths(); 961175193d2STom N Harris foreach ($lengths as $length) { 962b8c040dbSTom N Harris if ($length < $minlen) continue; 96380fb93f6STom N Harris $index = $this->getIndex('i', $length); 964175193d2STom N Harris $words = null; 965175193d2STom N Harris foreach ($index as $wid => $line) { 96680fb93f6STom N Harris $freq = $this->countTuples($line); 967175193d2STom N Harris if ($freq >= $min && (!$max || $freq <= $max)) { 968175193d2STom N Harris if ($words === null) 96980fb93f6STom N Harris $words = $this->getIndex('w', $length); 970175193d2STom N Harris $result[$words[$wid]] = $freq; 971175193d2STom N Harris } 972175193d2STom N Harris } 973175193d2STom N Harris } 974175193d2STom N Harris } 975175193d2STom N Harris 976175193d2STom N Harris arsort($result); 977175193d2STom N Harris return $result; 97800803e56STom N Harris } 97900803e56STom N Harris 98000803e56STom N Harris /** 98100803e56STom N Harris * Lock the indexer. 98200803e56STom N Harris * 98300803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 98442ea7f44SGerrit Uitslag * 98542ea7f44SGerrit Uitslag * @return bool|string 98600803e56STom N Harris */ 98780fb93f6STom N Harris protected function lock() { 98800803e56STom N Harris global $conf; 98900803e56STom N Harris $status = true; 990f77fc90dSMichael Hamann $run = 0; 99100803e56STom N Harris $lock = $conf['lockdir'].'/_indexer.lock'; 99200803e56STom N Harris while (!@mkdir($lock, $conf['dmode'])) { 99300803e56STom N Harris usleep(50); 994f77fc90dSMichael Hamann if(is_dir($lock) && time()-@filemtime($lock) > 60*5){ 995f77fc90dSMichael Hamann // looks like a stale lock - remove it 996f77fc90dSMichael Hamann if (!@rmdir($lock)) { 997f77fc90dSMichael Hamann $status = "removing the stale lock failed"; 998f77fc90dSMichael Hamann return false; 99900803e56STom N Harris } else { 1000f77fc90dSMichael Hamann $status = "stale lock removed"; 1001f77fc90dSMichael Hamann } 1002f77fc90dSMichael Hamann }elseif($run++ == 1000){ 1003f77fc90dSMichael Hamann // we waited 5 seconds for that lock 100400803e56STom N Harris return false; 100500803e56STom N Harris } 100600803e56STom N Harris } 1007443e135dSChristopher Smith if (!empty($conf['dperm'])) { 100800803e56STom N Harris chmod($lock, $conf['dperm']); 1009443e135dSChristopher Smith } 101000803e56STom N Harris return $status; 101100803e56STom N Harris } 101200803e56STom N Harris 101300803e56STom N Harris /** 101400803e56STom N Harris * Release the indexer lock. 101500803e56STom N Harris * 101600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 101742ea7f44SGerrit Uitslag * 101842ea7f44SGerrit Uitslag * @return bool 101900803e56STom N Harris */ 102080fb93f6STom N Harris protected function unlock() { 102100803e56STom N Harris global $conf; 102200803e56STom N Harris @rmdir($conf['lockdir'].'/_indexer.lock'); 102300803e56STom N Harris return true; 102400803e56STom N Harris } 102500803e56STom N Harris 102600803e56STom N Harris /** 102700803e56STom N Harris * Retrieve the entire index. 102800803e56STom N Harris * 1029b9d8cc1eSTom N Harris * The $suffix argument is for an index that is split into 1030b9d8cc1eSTom N Harris * multiple parts. Different index files should use different 1031b9d8cc1eSTom N Harris * base names. 1032b9d8cc1eSTom N Harris * 1033b9d8cc1eSTom N Harris * @param string $idx name of the index 1034b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1035b9d8cc1eSTom N Harris * @return array list of lines without CR or LF 103642ea7f44SGerrit Uitslag * 103700803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 103800803e56STom N Harris */ 103980fb93f6STom N Harris protected function getIndex($idx, $suffix) { 104000803e56STom N Harris global $conf; 104100803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 104279e79377SAndreas Gohr if (!file_exists($fn)) return array(); 1043d64516f5SMichael Hamann return file($fn, FILE_IGNORE_NEW_LINES); 104400803e56STom N Harris } 104500803e56STom N Harris 104600803e56STom N Harris /** 104700803e56STom N Harris * Replace the contents of the index with an array. 104800803e56STom N Harris * 1049b9d8cc1eSTom N Harris * @param string $idx name of the index 1050b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1051e3ab6fc5SMichael Hamann * @param array $lines list of lines without LF 1052e3ab6fc5SMichael Hamann * @return bool If saving succeeded 105342ea7f44SGerrit Uitslag * 105400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 105500803e56STom N Harris */ 105680fb93f6STom N Harris protected function saveIndex($idx, $suffix, &$lines) { 105700803e56STom N Harris global $conf; 105800803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix; 105900803e56STom N Harris $fh = @fopen($fn.'.tmp', 'w'); 106000803e56STom N Harris if (!$fh) return false; 106100803e56STom N Harris fwrite($fh, join("\n", $lines)); 10622e1018bcSMichael Hamann if (!empty($lines)) 10632e1018bcSMichael Hamann fwrite($fh, "\n"); 106400803e56STom N Harris fclose($fh); 106500803e56STom N Harris if (isset($conf['fperm'])) 106600803e56STom N Harris chmod($fn.'.tmp', $conf['fperm']); 106700803e56STom N Harris io_rename($fn.'.tmp', $fn.'.idx'); 106800803e56STom N Harris return true; 106900803e56STom N Harris } 107000803e56STom N Harris 107100803e56STom N Harris /** 107200803e56STom N Harris * Retrieve a line from the index. 107300803e56STom N Harris * 1074b9d8cc1eSTom N Harris * @param string $idx name of the index 1075b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1076b9d8cc1eSTom N Harris * @param int $id the line number 1077b9d8cc1eSTom N Harris * @return string a line with trailing whitespace removed 107842ea7f44SGerrit Uitslag * 107900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 108000803e56STom N Harris */ 108180fb93f6STom N Harris protected function getIndexKey($idx, $suffix, $id) { 108200803e56STom N Harris global $conf; 108300803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 108479e79377SAndreas Gohr if (!file_exists($fn)) return ''; 108500803e56STom N Harris $fh = @fopen($fn, 'r'); 108600803e56STom N Harris if (!$fh) return ''; 108700803e56STom N Harris $ln = -1; 108800803e56STom N Harris while (($line = fgets($fh)) !== false) { 108900803e56STom N Harris if (++$ln == $id) break; 109000803e56STom N Harris } 109100803e56STom N Harris fclose($fh); 109200803e56STom N Harris return rtrim((string)$line); 109300803e56STom N Harris } 109400803e56STom N Harris 109500803e56STom N Harris /** 109600803e56STom N Harris * Write a line into the index. 109700803e56STom N Harris * 1098b9d8cc1eSTom N Harris * @param string $idx name of the index 1099b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1100b9d8cc1eSTom N Harris * @param int $id the line number 1101b9d8cc1eSTom N Harris * @param string $line line to write 1102e3ab6fc5SMichael Hamann * @return bool If saving succeeded 110342ea7f44SGerrit Uitslag * 110400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 110500803e56STom N Harris */ 110680fb93f6STom N Harris protected function saveIndexKey($idx, $suffix, $id, $line) { 110700803e56STom N Harris global $conf; 110800803e56STom N Harris if (substr($line, -1) != "\n") 110900803e56STom N Harris $line .= "\n"; 111000803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix; 111100803e56STom N Harris $fh = @fopen($fn.'.tmp', 'w'); 1112dbb771bbSAdrian Lang if (!$fh) return false; 111300803e56STom N Harris $ih = @fopen($fn.'.idx', 'r'); 111400803e56STom N Harris if ($ih) { 111500803e56STom N Harris $ln = -1; 111600803e56STom N Harris while (($curline = fgets($ih)) !== false) { 111700803e56STom N Harris fwrite($fh, (++$ln == $id) ? $line : $curline); 111800803e56STom N Harris } 11194373c7b5SMichael Hamann if ($id > $ln) { 11204373c7b5SMichael Hamann while ($id > ++$ln) 11214373c7b5SMichael Hamann fwrite($fh, "\n"); 112200803e56STom N Harris fwrite($fh, $line); 11234373c7b5SMichael Hamann } 112400803e56STom N Harris fclose($ih); 112500803e56STom N Harris } else { 11264373c7b5SMichael Hamann $ln = -1; 11274373c7b5SMichael Hamann while ($id > ++$ln) 11284373c7b5SMichael Hamann fwrite($fh, "\n"); 112900803e56STom N Harris fwrite($fh, $line); 113000803e56STom N Harris } 113100803e56STom N Harris fclose($fh); 113200803e56STom N Harris if (isset($conf['fperm'])) 113300803e56STom N Harris chmod($fn.'.tmp', $conf['fperm']); 113400803e56STom N Harris io_rename($fn.'.tmp', $fn.'.idx'); 113500803e56STom N Harris return true; 113600803e56STom N Harris } 113700803e56STom N Harris 113800803e56STom N Harris /** 113900803e56STom N Harris * Retrieve or insert a value in the index. 114000803e56STom N Harris * 1141b9d8cc1eSTom N Harris * @param string $idx name of the index 1142b9d8cc1eSTom N Harris * @param string $suffix subpart identifier 1143b9d8cc1eSTom N Harris * @param string $value line to find in the index 114403aafe1cSMichael Hamann * @return int|bool line number of the value in the index or false if writing the index failed 114542ea7f44SGerrit Uitslag * 114600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 114700803e56STom N Harris */ 114880fb93f6STom N Harris protected function addIndexKey($idx, $suffix, $value) { 114980fb93f6STom N Harris $index = $this->getIndex($idx, $suffix); 1150a8dba452SMichael Hamann $id = array_search($value, $index, true); 115100803e56STom N Harris if ($id === false) { 115200803e56STom N Harris $id = count($index); 115300803e56STom N Harris $index[$id] = $value; 115480fb93f6STom N Harris if (!$this->saveIndex($idx, $suffix, $index)) { 115500803e56STom N Harris trigger_error("Failed to write $idx index", E_USER_ERROR); 115600803e56STom N Harris return false; 115700803e56STom N Harris } 115800803e56STom N Harris } 115900803e56STom N Harris return $id; 116000803e56STom N Harris } 116100803e56STom N Harris 1162e3ab6fc5SMichael Hamann /** 116300803e56STom N Harris * Get the list of lengths indexed in the wiki. 116400803e56STom N Harris * 116500803e56STom N Harris * Read the index directory or a cache file and returns 116600803e56STom N Harris * a sorted array of lengths of the words used in the wiki. 116700803e56STom N Harris * 116800803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 116942ea7f44SGerrit Uitslag * 117042ea7f44SGerrit Uitslag * @return array 117100803e56STom N Harris */ 117280fb93f6STom N Harris protected function listIndexLengths() { 1173b1720e5cSMichael Hamann return idx_listIndexLengths(); 117400803e56STom N Harris } 117500803e56STom N Harris 117600803e56STom N Harris /** 117700803e56STom N Harris * Get the word lengths that have been indexed. 117800803e56STom N Harris * 117900803e56STom N Harris * Reads the index directory and returns an array of lengths 118000803e56STom N Harris * that there are indices for. 118100803e56STom N Harris * 118200803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 118342ea7f44SGerrit Uitslag * 118442ea7f44SGerrit Uitslag * @param array|int $filter 118542ea7f44SGerrit Uitslag * @return array 118600803e56STom N Harris */ 118780fb93f6STom N Harris protected function indexLengths($filter) { 118800803e56STom N Harris global $conf; 118900803e56STom N Harris $idx = array(); 119000803e56STom N Harris if (is_array($filter)) { 119100803e56STom N Harris // testing if index files exist only 119200803e56STom N Harris $path = $conf['indexdir']."/i"; 119300803e56STom N Harris foreach ($filter as $key => $value) { 119479e79377SAndreas Gohr if (file_exists($path.$key.'.idx')) 119500803e56STom N Harris $idx[] = $key; 119600803e56STom N Harris } 119700803e56STom N Harris } else { 119800803e56STom N Harris $lengths = idx_listIndexLengths(); 119900803e56STom N Harris foreach ($lengths as $key => $length) { 120000803e56STom N Harris // keep all the values equal or superior 120100803e56STom N Harris if ((int)$length >= (int)$filter) 120200803e56STom N Harris $idx[] = $length; 120300803e56STom N Harris } 120400803e56STom N Harris } 120500803e56STom N Harris return $idx; 120600803e56STom N Harris } 120700803e56STom N Harris 120800803e56STom N Harris /** 120900803e56STom N Harris * Insert or replace a tuple in a line. 121000803e56STom N Harris * 121100803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 121242ea7f44SGerrit Uitslag * 121342ea7f44SGerrit Uitslag * @param string $line 1214e3710957SGerrit Uitslag * @param string|int $id 121542ea7f44SGerrit Uitslag * @param int $count 121642ea7f44SGerrit Uitslag * @return string 121700803e56STom N Harris */ 121880fb93f6STom N Harris protected function updateTuple($line, $id, $count) { 1219c6568d42SChristopher Smith if ($line != ''){ 1220c6568d42SChristopher Smith $line = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $line); 122139134585SChristopher Smith } 1222c6568d42SChristopher Smith $line = trim($line, ':'); 122300803e56STom N Harris if ($count) { 1224c6568d42SChristopher Smith if ($line) { 1225c6568d42SChristopher Smith return "$id*$count:".$line; 122639134585SChristopher Smith } else { 1227c6568d42SChristopher Smith return "$id*$count"; 122800803e56STom N Harris } 122939134585SChristopher Smith } 1230c6568d42SChristopher Smith return $line; 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> 123842ea7f44SGerrit Uitslag * 123942ea7f44SGerrit Uitslag * @param array $keys 124042ea7f44SGerrit Uitslag * @param string $line 124142ea7f44SGerrit Uitslag * @return array 124200803e56STom N Harris */ 124380fb93f6STom N Harris protected function parseTuples(&$keys, $line) { 124400803e56STom N Harris $result = array(); 124500803e56STom N Harris if ($line == '') return $result; 124600803e56STom N Harris $parts = explode(':', $line); 124700803e56STom N Harris foreach ($parts as $tuple) { 1248675bf41fSTom N Harris if ($tuple === '') continue; 124900803e56STom N Harris list($key, $cnt) = explode('*', $tuple); 1250d64516f5SMichael Hamann if (!$cnt) continue; 125100803e56STom N Harris $key = $keys[$key]; 12525e0da3ceSPhy if ($key === false || is_null($key)) continue; 125300803e56STom N Harris $result[$key] = $cnt; 125400803e56STom N Harris } 125500803e56STom N Harris return $result; 125600803e56STom N Harris } 1257175193d2STom N Harris 1258175193d2STom N Harris /** 1259175193d2STom N Harris * Sum the counts in a list of tuples. 1260175193d2STom N Harris * 1261175193d2STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 126242ea7f44SGerrit Uitslag * 126342ea7f44SGerrit Uitslag * @param string $line 126442ea7f44SGerrit Uitslag * @return int 1265175193d2STom N Harris */ 126680fb93f6STom N Harris protected function countTuples($line) { 1267175193d2STom N Harris $freq = 0; 1268175193d2STom N Harris $parts = explode(':', $line); 1269175193d2STom N Harris foreach ($parts as $tuple) { 1270675bf41fSTom N Harris if ($tuple === '') continue; 127142ea7f44SGerrit Uitslag list(/* $pid */, $cnt) = explode('*', $tuple); 1272175193d2STom N Harris $freq += (int)$cnt; 1273175193d2STom N Harris } 1274175193d2STom N Harris return $freq; 1275175193d2STom N Harris } 127600803e56STom N Harris} 127700803e56STom N Harris 127800803e56STom N Harris/** 127900803e56STom N Harris * Create an instance of the indexer. 128000803e56STom N Harris * 1281b3d1090eSMichael Hamann * @return Doku_Indexer a Doku_Indexer 128242ea7f44SGerrit Uitslag * 128300803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 128400803e56STom N Harris */ 12859b41be24STom N Harrisfunction idx_get_indexer() { 12864f708321SMichael Hamann static $Indexer; 12871421e548SMichael Hamann if (!isset($Indexer)) { 128800803e56STom N Harris $Indexer = new Doku_Indexer(); 128900803e56STom N Harris } 129000803e56STom N Harris return $Indexer; 129100803e56STom N Harris} 129200803e56STom N Harris 129300803e56STom N Harris/** 129400803e56STom N Harris * Returns words that will be ignored. 129500803e56STom N Harris * 129600803e56STom N Harris * @return array list of stop words 129742ea7f44SGerrit Uitslag * 129800803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 129900803e56STom N Harris */ 130000803e56STom N Harrisfunction & idx_get_stopwords() { 130100803e56STom N Harris static $stopwords = null; 130200803e56STom N Harris if (is_null($stopwords)) { 130300803e56STom N Harris global $conf; 130400803e56STom N Harris $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 130579e79377SAndreas Gohr if(file_exists($swfile)){ 130600803e56STom N Harris $stopwords = file($swfile, FILE_IGNORE_NEW_LINES); 130700803e56STom N Harris }else{ 130800803e56STom N Harris $stopwords = array(); 130900803e56STom N Harris } 131000803e56STom N Harris } 131100803e56STom N Harris return $stopwords; 131200803e56STom N Harris} 131300803e56STom N Harris 131400803e56STom N Harris/** 131500803e56STom N Harris * Adds/updates the search index for the given page 131600803e56STom N Harris * 131700803e56STom N Harris * Locking is handled internally. 131800803e56STom N Harris * 131900803e56STom N Harris * @param string $page name of the page to index 13209b41be24STom N Harris * @param boolean $verbose print status messages 1321d041f8dbSMichael Hamann * @param boolean $force force reindexing even when the index is up to date 132242ea7f44SGerrit Uitslag * @return string|boolean the function completed successfully 132342ea7f44SGerrit Uitslag * 132400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 132500803e56STom N Harris */ 1326d041f8dbSMichael Hamannfunction idx_addPage($page, $verbose=false, $force=false) { 13279b41be24STom N Harris $idxtag = metaFN($page,'.indexed'); 1328a23ac4d7SMichael Hamann // check if page was deleted but is still in the index 1329bbc85ee4STom N Harris if (!page_exists($page)) { 133079e79377SAndreas Gohr if (!file_exists($idxtag)) { 1331bbc85ee4STom N Harris if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF); 1332bbc85ee4STom N Harris return false; 1333bbc85ee4STom N Harris } 1334bbc85ee4STom N Harris $Indexer = idx_get_indexer(); 1335bbc85ee4STom N Harris $result = $Indexer->deletePage($page); 1336bbc85ee4STom N Harris if ($result === "locked") { 1337bbc85ee4STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 1338bbc85ee4STom N Harris return false; 1339bbc85ee4STom N Harris } 1340bbc85ee4STom N Harris @unlink($idxtag); 1341bbc85ee4STom N Harris return $result; 1342bbc85ee4STom N Harris } 1343a23ac4d7SMichael Hamann 1344a23ac4d7SMichael Hamann // check if indexing needed 134579e79377SAndreas Gohr if(!$force && file_exists($idxtag)){ 1346a23ac4d7SMichael Hamann if(trim(io_readFile($idxtag)) == idx_get_version()){ 1347a23ac4d7SMichael Hamann $last = @filemtime($idxtag); 1348a23ac4d7SMichael Hamann if($last > @filemtime(wikiFN($page))){ 1349a23ac4d7SMichael Hamann if ($verbose) print("Indexer: index for $page up to date".DOKU_LF); 1350a23ac4d7SMichael Hamann return false; 1351a23ac4d7SMichael Hamann } 1352a23ac4d7SMichael Hamann } 1353a23ac4d7SMichael Hamann } 1354a23ac4d7SMichael Hamann 135565aa8490SMichael Hamann $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED); 1356bbc85ee4STom N Harris if ($indexenabled === false) { 1357bbc85ee4STom N Harris $result = false; 135879e79377SAndreas Gohr if (file_exists($idxtag)) { 1359bbc85ee4STom N Harris $Indexer = idx_get_indexer(); 1360bbc85ee4STom N Harris $result = $Indexer->deletePage($page); 1361bbc85ee4STom N Harris if ($result === "locked") { 1362bbc85ee4STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 1363bbc85ee4STom N Harris return false; 1364bbc85ee4STom N Harris } 1365bbc85ee4STom N Harris @unlink($idxtag); 1366bbc85ee4STom N Harris } 1367bbc85ee4STom N Harris if ($verbose) print("Indexer: index disabled for $page".DOKU_LF); 1368bbc85ee4STom N Harris return $result; 1369bbc85ee4STom N Harris } 1370bbc85ee4STom N Harris 137103aafe1cSMichael Hamann $Indexer = idx_get_indexer(); 137203aafe1cSMichael Hamann $pid = $Indexer->getPID($page); 137303aafe1cSMichael Hamann if ($pid === false) { 137403aafe1cSMichael Hamann if ($verbose) print("Indexer: getting the PID failed for $page".DOKU_LF); 137503aafe1cSMichael Hamann return false; 137603aafe1cSMichael Hamann } 137700803e56STom N Harris $body = ''; 137839d6fd30SMichael Hamann $metadata = array(); 137965aa8490SMichael Hamann $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED); 138065aa8490SMichael Hamann if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null) 138139d6fd30SMichael Hamann $metadata['relation_references'] = array_keys($references); 1382a424180eSMichael Hamann else 1383a424180eSMichael Hamann $metadata['relation_references'] = array(); 1384ffec1009SMichael Hamann 1385ffec1009SMichael Hamann if (($media = p_get_metadata($page, 'relation media', METADATA_RENDER_UNLIMITED)) !== null) 1386ffec1009SMichael Hamann $metadata['relation_media'] = array_keys($media); 1387ffec1009SMichael Hamann else 1388ffec1009SMichael Hamann $metadata['relation_media'] = array(); 1389ffec1009SMichael Hamann 139003aafe1cSMichael Hamann $data = compact('page', 'body', 'metadata', 'pid'); 1391e1d9dcc8SAndreas Gohr $evt = new Event('INDEXER_PAGE_ADD', $data); 139239d6fd30SMichael Hamann if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page); 139300803e56STom N Harris $evt->advise_after(); 139400803e56STom N Harris unset($evt); 139539d6fd30SMichael Hamann extract($data); 139600803e56STom N Harris 13979b41be24STom N Harris $result = $Indexer->addPageWords($page, $body); 1398e1e1a7e0SMichael Hamann if ($result === "locked") { 13999b41be24STom N Harris if ($verbose) print("Indexer: locked".DOKU_LF); 14009b41be24STom N Harris return false; 14019b41be24STom N Harris } 1402320f489aSMichael Hamann 1403320f489aSMichael Hamann if ($result) { 140439d6fd30SMichael Hamann $result = $Indexer->addMetaKeys($page, $metadata); 1405320f489aSMichael Hamann if ($result === "locked") { 1406320f489aSMichael Hamann if ($verbose) print("Indexer: locked".DOKU_LF); 1407320f489aSMichael Hamann return false; 1408320f489aSMichael Hamann } 1409320f489aSMichael Hamann } 1410320f489aSMichael Hamann 14119b41be24STom N Harris if ($result) 14129b41be24STom N Harris io_saveFile(metaFN($page,'.indexed'), idx_get_version()); 14139b41be24STom N Harris if ($verbose) { 14149b41be24STom N Harris print("Indexer: finished".DOKU_LF); 14159b41be24STom N Harris return true; 14169b41be24STom N Harris } 14179b41be24STom N Harris return $result; 141800803e56STom N Harris} 141900803e56STom N Harris 142000803e56STom N Harris/** 142100803e56STom N Harris * Find tokens in the fulltext index 142200803e56STom N Harris * 142300803e56STom N Harris * Takes an array of words and will return a list of matching 142400803e56STom N Harris * pages for each one. 1425488dd6ceSAndreas Gohr * 142663773904SAndreas Gohr * Important: No ACL checking is done here! All results are 142763773904SAndreas Gohr * returned, regardless of permissions 142863773904SAndreas Gohr * 1429e3ab6fc5SMichael Hamann * @param array $words list of words to search for 143000803e56STom N Harris * @return array list of pages found, associated with the search terms 1431488dd6ceSAndreas Gohr */ 14329b41be24STom N Harrisfunction idx_lookup(&$words) { 14339b41be24STom N Harris $Indexer = idx_get_indexer(); 143400803e56STom N Harris return $Indexer->lookup($words); 1435488dd6ceSAndreas Gohr} 1436488dd6ceSAndreas Gohr 1437488dd6ceSAndreas Gohr/** 143800803e56STom N Harris * Split a string into tokens 1439488dd6ceSAndreas Gohr * 1440f50a239bSTakamura * @param string $string 1441f50a239bSTakamura * @param bool $wc 1442f50a239bSTakamura * 1443f50a239bSTakamura * @return array 1444488dd6ceSAndreas Gohr */ 144500803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) { 14469b41be24STom N Harris $Indexer = idx_get_indexer(); 144700803e56STom N Harris return $Indexer->tokenizer($string, $wc); 1448488dd6ceSAndreas Gohr} 144900803e56STom N Harris 145000803e56STom N Harris/* For compatibility */ 1451488dd6ceSAndreas Gohr 1452f5eb7cf0SAndreas Gohr/** 145300803e56STom N Harris * Read the list of words in an index (if it exists). 1454f5eb7cf0SAndreas Gohr * 14554e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 145642ea7f44SGerrit Uitslag * 145742ea7f44SGerrit Uitslag * @param string $idx 145842ea7f44SGerrit Uitslag * @param string $suffix 145942ea7f44SGerrit Uitslag * @return array 1460f5eb7cf0SAndreas Gohr */ 146100803e56STom N Harrisfunction idx_getIndex($idx, $suffix) { 14621c07b9e6STom N Harris global $conf; 146300803e56STom N Harris $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx'; 146479e79377SAndreas Gohr if (!file_exists($fn)) return array(); 146500803e56STom N Harris return file($fn); 146600803e56STom N Harris} 1467f5eb7cf0SAndreas Gohr 146800803e56STom N Harris/** 146900803e56STom N Harris * Get the list of lengths indexed in the wiki. 147000803e56STom N Harris * 147100803e56STom N Harris * Read the index directory or a cache file and returns 147200803e56STom N Harris * a sorted array of lengths of the words used in the wiki. 147300803e56STom N Harris * 147400803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 147542ea7f44SGerrit Uitslag * 147642ea7f44SGerrit Uitslag * @return array 147700803e56STom N Harris */ 147800803e56STom N Harrisfunction idx_listIndexLengths() { 147900803e56STom N Harris global $conf; 148000803e56STom N Harris // testing what we have to do, create a cache file or not. 148100803e56STom N Harris if ($conf['readdircache'] == 0) { 148200803e56STom N Harris $docache = false; 14831c07b9e6STom N Harris } else { 148400803e56STom N Harris clearstatcache(); 148579e79377SAndreas Gohr if (file_exists($conf['indexdir'].'/lengths.idx') 148600803e56STom N Harris && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) { 148764159a61SAndreas Gohr if ( 148864159a61SAndreas Gohr ($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) 148964159a61SAndreas Gohr !== false 149064159a61SAndreas Gohr ) { 149100803e56STom N Harris $idx = array(); 149200803e56STom N Harris foreach ($lengths as $length) { 149300803e56STom N Harris $idx[] = (int)$length; 149400803e56STom N Harris } 149500803e56STom N Harris return $idx; 1496f5eb7cf0SAndreas Gohr } 14971c07b9e6STom N Harris } 149800803e56STom N Harris $docache = true; 149900803e56STom N Harris } 15004e1bf408STom N Harris 150100803e56STom N Harris if ($conf['readdircache'] == 0 || $docache) { 150200803e56STom N Harris $dir = @opendir($conf['indexdir']); 150300803e56STom N Harris if ($dir === false) 150400803e56STom N Harris return array(); 150526f7dbf5SMichael Hamann $idx = array(); 150600803e56STom N Harris while (($f = readdir($dir)) !== false) { 150700803e56STom N Harris if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') { 150800803e56STom N Harris $i = substr($f, 1, -4); 150900803e56STom N Harris if (is_numeric($i)) 151000803e56STom N Harris $idx[] = (int)$i; 151100803e56STom N Harris } 151200803e56STom N Harris } 151300803e56STom N Harris closedir($dir); 151400803e56STom N Harris sort($idx); 151500803e56STom N Harris // save this in a file 151600803e56STom N Harris if ($docache) { 151700803e56STom N Harris $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w'); 151800803e56STom N Harris @fwrite($handle, implode("\n", $idx)); 151900803e56STom N Harris @fclose($handle); 152000803e56STom N Harris } 152100803e56STom N Harris return $idx; 152200803e56STom N Harris } 152300803e56STom N Harris 152400803e56STom N Harris return array(); 152500803e56STom N Harris} 152600803e56STom N Harris 152700803e56STom N Harris/** 152800803e56STom N Harris * Get the word lengths that have been indexed. 152900803e56STom N Harris * 153000803e56STom N Harris * Reads the index directory and returns an array of lengths 153100803e56STom N Harris * that there are indices for. 153200803e56STom N Harris * 153300803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com> 153442ea7f44SGerrit Uitslag * 153542ea7f44SGerrit Uitslag * @param array|int $filter 153642ea7f44SGerrit Uitslag * @return array 153700803e56STom N Harris */ 153800803e56STom N Harrisfunction idx_indexLengths($filter) { 153900803e56STom N Harris global $conf; 154000803e56STom N Harris $idx = array(); 154100803e56STom N Harris if (is_array($filter)) { 154200803e56STom N Harris // testing if index files exist only 154300803e56STom N Harris $path = $conf['indexdir']."/i"; 154400803e56STom N Harris foreach ($filter as $key => $value) { 154579e79377SAndreas Gohr if (file_exists($path.$key.'.idx')) 154600803e56STom N Harris $idx[] = $key; 154700803e56STom N Harris } 1548f5eb7cf0SAndreas Gohr } else { 154900803e56STom N Harris $lengths = idx_listIndexLengths(); 155000803e56STom N Harris foreach ($lengths as $key => $length) { 155100803e56STom N Harris // keep all the values equal or superior 155200803e56STom N Harris if ((int)$length >= (int)$filter) 155300803e56STom N Harris $idx[] = $length; 1554f5eb7cf0SAndreas Gohr } 155500803e56STom N Harris } 155600803e56STom N Harris return $idx; 1557f5eb7cf0SAndreas Gohr} 1558f5eb7cf0SAndreas Gohr 155900803e56STom N Harris/** 156000803e56STom N Harris * Clean a name of a key for use as a file name. 156100803e56STom N Harris * 156200803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's 156300803e56STom N Harris * not a letter, number, or underscore. 156400803e56STom N Harris * 156500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org> 156642ea7f44SGerrit Uitslag * 156742ea7f44SGerrit Uitslag * @param string $name 156842ea7f44SGerrit Uitslag * @return string 156900803e56STom N Harris */ 157000803e56STom N Harrisfunction idx_cleanName($name) { 15718cbc5ee8SAndreas Gohr $name = \dokuwiki\Utf8\Clean::romanize(trim((string)$name)); 157200803e56STom N Harris $name = preg_replace('#[ \./\\:-]+#', '_', $name); 157300803e56STom N Harris $name = preg_replace('/[^A-Za-z0-9_]/', '', $name); 157400803e56STom N Harris return strtolower($name); 1575f5eb7cf0SAndreas Gohr} 1576f5eb7cf0SAndreas Gohr 157700803e56STom N Harris//Setup VIM: ex: et ts=4 : 1578