xref: /dokuwiki/inc/indexer.php (revision 4f7083212993bf72f0b8969e6d57f587faaa5dfc)
1b4ce25e9SAndreas Gohr<?php
2b4ce25e9SAndreas Gohr/**
3fcd3bb7cSAndreas Gohr * Functions to create the fulltext search index
4b4ce25e9SAndreas Gohr *
5b4ce25e9SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6b4ce25e9SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
700803e56STom N Harris * @author     Tom N Harris <tnharris@whoopdedo.org>
8b4ce25e9SAndreas Gohr */
9b4ce25e9SAndreas Gohr
10fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
11b4ce25e9SAndreas Gohr
127c2ef4e8STom N Harris// Version tag used to force rebuild on upgrade
137d939e4eSMichael Hamanndefine('INDEXER_VERSION', 5);
147c2ef4e8STom N Harris
1533815ce2SChris Smith// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens)
16d3fb3219SAndreas Gohrif (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2);
1733815ce2SChris Smith
1893a60ad2SAndreas Gohr// Asian characters are handled as words. The following regexp defines the
1993a60ad2SAndreas Gohr// Unicode-Ranges for Asian characters
2093a60ad2SAndreas Gohr// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
2193a60ad2SAndreas Gohr// I'm no language expert. If you think some ranges are wrongly chosen or
2293a60ad2SAndreas Gohr// a range is missing, please contact me
23d5b23302STom N Harrisdefine('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
24d5b23302STom N Harrisdefine('IDX_ASIAN2','['.
25d5b23302STom N Harris                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
26d5b23302STom N Harris                   '\x{309D}-\x{30A0}'.
27a0c5c349STom N Harris                   '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'.
2893a60ad2SAndreas Gohr                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
2993a60ad2SAndreas Gohr                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
30ae6c4ec0SDanny Lin                   "\xF0\xA0\x80\x80-\xF0\xAA\x9B\x9F". // CJK Extension B
31ae6c4ec0SDanny Lin                   "\xF0\xAA\x9C\x80-\xF0\xAB\x9C\xBF". // CJK Extension C
32ae6c4ec0SDanny Lin                   "\xF0\xAB\x9D\x80-\xF0\xAB\xA0\x9F". // CJK Extension D
33ae6c4ec0SDanny Lin                   "\xF0\xAF\xA0\x80-\xF0\xAF\xAB\xBF". // CJK Compatibility Supplement
3493a60ad2SAndreas Gohr                   ']');
35d5b23302STom N Harrisdefine('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
36d5b23302STom N Harris                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
37d5b23302STom N Harris                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
38d5b23302STom N Harris                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
39d5b23302STom N Harris                   '\x{308F}-\x{3094}'.
40d5b23302STom N Harris                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
41d5b23302STom N Harris                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
42d5b23302STom N Harris                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
43d5b23302STom N Harris                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
44d5b23302STom N Harris                   ']['.
45d5b23302STom N Harris                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
46d5b23302STom N Harris                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
47d5b23302STom N Harris                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
48d5b23302STom N Harris                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
49d5b23302STom N Harris                   '\x{31F0}-\x{31FF}'.
50d5b23302STom N Harris                   ']?');
51699b8a0bSAndreas Gohrdefine('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
5293a60ad2SAndreas Gohr
53b4ce25e9SAndreas Gohr/**
547c2ef4e8STom N Harris * Version of the indexer taking into consideration the external tokenizer.
557c2ef4e8STom N Harris * The indexer is only compatible with data written by the same version.
567c2ef4e8STom N Harris *
578cd4c12fSAndreas Gohr * @triggers INDEXER_VERSION_GET
58d0d6fe1bSTom N Harris * Plugins that modify what gets indexed should hook this event and
59d0d6fe1bSTom N Harris * add their version info to the event data like so:
60d0d6fe1bSTom N Harris *     $data[$plugin_name] = $plugin_version;
61d0d6fe1bSTom N Harris *
627c2ef4e8STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
638605afb1SMichael Hamann * @author Michael Hamann <michael@content-space.de>
647c2ef4e8STom N Harris */
657c2ef4e8STom N Harrisfunction idx_get_version(){
66d0d6fe1bSTom N Harris    static $indexer_version = null;
67d0d6fe1bSTom N Harris    if ($indexer_version == null) {
688605afb1SMichael Hamann        $version = INDEXER_VERSION;
698605afb1SMichael Hamann
70d0d6fe1bSTom N Harris        // DokuWiki version is included for the convenience of plugins
71d0d6fe1bSTom N Harris        $data = array('dokuwiki'=>$version);
728605afb1SMichael Hamann        trigger_event('INDEXER_VERSION_GET', $data, null, false);
73d0d6fe1bSTom N Harris        unset($data['dokuwiki']); // this needs to be first
74d0d6fe1bSTom N Harris        ksort($data);
75d0d6fe1bSTom N Harris        foreach ($data as $plugin=>$vers)
76d0d6fe1bSTom N Harris            $version .= '+'.$plugin.'='.$vers;
77d0d6fe1bSTom N Harris        $indexer_version = $version;
78d0d6fe1bSTom N Harris    }
79d0d6fe1bSTom N Harris    return $indexer_version;
807c2ef4e8STom N Harris}
817c2ef4e8STom N Harris
827c2ef4e8STom N Harris/**
83d5b23302STom N Harris * Measure the length of a string.
84d5b23302STom N Harris * Differs from strlen in handling of asian characters.
85d5b23302STom N Harris *
86d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
87d5b23302STom N Harris */
88d5b23302STom N Harrisfunction wordlen($w){
89d5b23302STom N Harris    $l = strlen($w);
90d5b23302STom N Harris    // If left alone, all chinese "words" will get put into w3.idx
91d5b23302STom N Harris    // So the "length" of a "word" is faked
924b9792c6STom N Harris    if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) {
934b9792c6STom N Harris        foreach($leadbytes[0] as $b)
944b9792c6STom N Harris            $l += ord($b) - 0xE1;
954b9792c6STom N Harris    }
96d5b23302STom N Harris    return $l;
97d5b23302STom N Harris}
98d5b23302STom N Harris
99d5b23302STom N Harris/**
10000803e56STom N Harris * Class that encapsulates operations on the indexer database.
101579b0f7eSTNHarris *
102579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
103579b0f7eSTNHarris */
10400803e56STom N Harrisclass Doku_Indexer {
1053d2ce006SMichael Hamann    /**
1063d2ce006SMichael Hamann     * @var array $pidCache Cache for getPID()
1073d2ce006SMichael Hamann     */
1083d2ce006SMichael Hamann    protected $pidCache = array();
109579b0f7eSTNHarris
110579b0f7eSTNHarris    /**
11100803e56STom N Harris     * Adds the contents of a page to the fulltext index
112dd35e9c9SAndreas Gohr     *
11300803e56STom N Harris     * The added text replaces previous words for the same page.
11400803e56STom N Harris     * An empty value erases the page.
11500803e56STom N Harris     *
11600803e56STom N Harris     * @param string    $page   a page name
11700803e56STom N Harris     * @param string    $text   the body of the page
11800803e56STom N Harris     * @return boolean          the function completed successfully
11900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
120dd35e9c9SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
121dd35e9c9SAndreas Gohr     */
12200803e56STom N Harris    public function addPageWords($page, $text) {
12380fb93f6STom N Harris        if (!$this->lock())
1249b41be24STom N Harris            return "locked";
12500803e56STom N Harris
12600803e56STom N Harris        // load known documents
12703aafe1cSMichael Hamann        $pid = $this->getPIDNoLock($page);
1285981eb09STom N Harris        if ($pid === false) {
12980fb93f6STom N Harris            $this->unlock();
13000803e56STom N Harris            return false;
13100803e56STom N Harris        }
13200803e56STom N Harris
13300803e56STom N Harris        $pagewords = array();
13400803e56STom N Harris        // get word usage in page
13580fb93f6STom N Harris        $words = $this->getPageWords($text);
13600803e56STom N Harris        if ($words === false) {
13780fb93f6STom N Harris            $this->unlock();
13800803e56STom N Harris            return false;
13900803e56STom N Harris        }
14000803e56STom N Harris
14100803e56STom N Harris        if (!empty($words)) {
14200803e56STom N Harris            foreach (array_keys($words) as $wlen) {
14380fb93f6STom N Harris                $index = $this->getIndex('i', $wlen);
14400803e56STom N Harris                foreach ($words[$wlen] as $wid => $freq) {
14500803e56STom N Harris                    $idx = ($wid<count($index)) ? $index[$wid] : '';
14680fb93f6STom N Harris                    $index[$wid] = $this->updateTuple($idx, $pid, $freq);
14700803e56STom N Harris                    $pagewords[] = "$wlen*$wid";
14800803e56STom N Harris                }
14980fb93f6STom N Harris                if (!$this->saveIndex('i', $wlen, $index)) {
15080fb93f6STom N Harris                    $this->unlock();
15100803e56STom N Harris                    return false;
15200803e56STom N Harris                }
15300803e56STom N Harris            }
15400803e56STom N Harris        }
15500803e56STom N Harris
15600803e56STom N Harris        // Remove obsolete index entries
15780fb93f6STom N Harris        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
15800803e56STom N Harris        if ($pageword_idx !== '') {
15900803e56STom N Harris            $oldwords = explode(':',$pageword_idx);
16000803e56STom N Harris            $delwords = array_diff($oldwords, $pagewords);
16100803e56STom N Harris            $upwords = array();
16200803e56STom N Harris            foreach ($delwords as $word) {
16300803e56STom N Harris                if ($word != '') {
16400803e56STom N Harris                    list($wlen,$wid) = explode('*', $word);
16500803e56STom N Harris                    $wid = (int)$wid;
16600803e56STom N Harris                    $upwords[$wlen][] = $wid;
16700803e56STom N Harris                }
16800803e56STom N Harris            }
16900803e56STom N Harris            foreach ($upwords as $wlen => $widx) {
17080fb93f6STom N Harris                $index = $this->getIndex('i', $wlen);
17100803e56STom N Harris                foreach ($widx as $wid) {
17280fb93f6STom N Harris                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
17300803e56STom N Harris                }
17480fb93f6STom N Harris                $this->saveIndex('i', $wlen, $index);
17500803e56STom N Harris            }
17600803e56STom N Harris        }
17700803e56STom N Harris        // Save the reverse index
17800803e56STom N Harris        $pageword_idx = join(':', $pagewords);
17980fb93f6STom N Harris        if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) {
18080fb93f6STom N Harris            $this->unlock();
18100803e56STom N Harris            return false;
18200803e56STom N Harris        }
18300803e56STom N Harris
18480fb93f6STom N Harris        $this->unlock();
185dd35e9c9SAndreas Gohr        return true;
186dd35e9c9SAndreas Gohr    }
187dd35e9c9SAndreas Gohr
188dd35e9c9SAndreas Gohr    /**
18900803e56STom N Harris     * Split the words in a page and add them to the index.
19044ca0adfSAndreas Gohr     *
191b9d8cc1eSTom N Harris     * @param string    $text   content of the page
192b9d8cc1eSTom N Harris     * @return array            list of word IDs and number of times used
19344ca0adfSAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
19417f42b01SChris Smith     * @author Christopher Smith <chris@jalakai.co.uk>
19500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
196b4ce25e9SAndreas Gohr     */
19780fb93f6STom N Harris    protected function getPageWords($text) {
19844ca0adfSAndreas Gohr
19900803e56STom N Harris        $tokens = $this->tokenizer($text);
20017f42b01SChris Smith        $tokens = array_count_values($tokens);  // count the frequency of each token
20117f42b01SChris Smith
20217f42b01SChris Smith        $words = array();
2034e1bf408STom N Harris        foreach ($tokens as $w=>$c) {
204d5b23302STom N Harris            $l = wordlen($w);
205579b0f7eSTNHarris            if (isset($words[$l])){
2064e1bf408STom N Harris                $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
20717f42b01SChris Smith            }else{
2084e1bf408STom N Harris                $words[$l] = array($w => $c);
20917f42b01SChris Smith            }
21017f42b01SChris Smith        }
21117f42b01SChris Smith
212579b0f7eSTNHarris        // arrive here with $words = array(wordlen => array(word => frequency))
213e5e50383SMichael Hamann        $word_idx_modified = false;
214b4ce25e9SAndreas Gohr        $index = array();   //resulting index
215579b0f7eSTNHarris        foreach (array_keys($words) as $wlen) {
21680fb93f6STom N Harris            $word_idx = $this->getIndex('w', $wlen);
217579b0f7eSTNHarris            foreach ($words[$wlen] as $word => $freq) {
21800803e56STom N Harris                $wid = array_search($word, $word_idx);
21900803e56STom N Harris                if ($wid === false) {
220d5b23302STom N Harris                    $wid = count($word_idx);
22100803e56STom N Harris                    $word_idx[] = $word;
222e5e50383SMichael Hamann                    $word_idx_modified = true;
223b4ce25e9SAndreas Gohr                }
224579b0f7eSTNHarris                if (!isset($index[$wlen]))
225579b0f7eSTNHarris                    $index[$wlen] = array();
226579b0f7eSTNHarris                $index[$wlen][$wid] = $freq;
22744ca0adfSAndreas Gohr            }
22800803e56STom N Harris            // save back the word index
22980fb93f6STom N Harris            if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx))
23044ca0adfSAndreas Gohr                return false;
23144ca0adfSAndreas Gohr        }
232b4ce25e9SAndreas Gohr
233b4ce25e9SAndreas Gohr        return $index;
234b4ce25e9SAndreas Gohr    }
235b4ce25e9SAndreas Gohr
23644ca0adfSAndreas Gohr    /**
237e1e1a7e0SMichael Hamann     * Add/update keys to/of the metadata index.
23844ca0adfSAndreas Gohr     *
23900803e56STom N Harris     * Adding new keys does not remove other keys for the page.
24000803e56STom N Harris     * An empty value will erase the key.
24100803e56STom N Harris     * The $key parameter can be an array to add multiple keys. $value will
24200803e56STom N Harris     * not be used if $key is an array.
24344ca0adfSAndreas Gohr     *
24400803e56STom N Harris     * @param string    $page   a page name
24500803e56STom N Harris     * @param mixed     $key    a key string or array of key=>value pairs
24600803e56STom N Harris     * @param mixed     $value  the value or list of values
24700803e56STom N Harris     * @return boolean          the function completed successfully
24800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
249e1e1a7e0SMichael Hamann     * @author Michael Hamann <michael@content-space.de>
25044ca0adfSAndreas Gohr     */
25100803e56STom N Harris    public function addMetaKeys($page, $key, $value=null) {
25200803e56STom N Harris        if (!is_array($key)) {
25300803e56STom N Harris            $key = array($key => $value);
25400803e56STom N Harris        } elseif (!is_null($value)) {
25500803e56STom N Harris            // $key is array, but $value is not null
25600803e56STom N Harris            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
25700803e56STom N Harris        }
25800803e56STom N Harris
25980fb93f6STom N Harris        if (!$this->lock())
260e1e1a7e0SMichael Hamann            return "locked";
261b4ce25e9SAndreas Gohr
262488dd6ceSAndreas Gohr        // load known documents
26303aafe1cSMichael Hamann        $pid = $this->getPIDNoLock($page);
26400803e56STom N Harris        if ($pid === false) {
26580fb93f6STom N Harris            $this->unlock();
266579b0f7eSTNHarris            return false;
26744ca0adfSAndreas Gohr        }
26800803e56STom N Harris
269c1209673STom N Harris        // Special handling for titles so the index file is simpler
270c1209673STom N Harris        if (array_key_exists('title', $key)) {
271c1209673STom N Harris            $value = $key['title'];
272c1209673STom N Harris            if (is_array($value))
273c1209673STom N Harris                $value = $value[0];
27480fb93f6STom N Harris            $this->saveIndexKey('title', '', $pid, $value);
275c1209673STom N Harris            unset($key['title']);
276c1209673STom N Harris        }
277c1209673STom N Harris
27800803e56STom N Harris        foreach ($key as $name => $values) {
27900803e56STom N Harris            $metaname = idx_cleanName($name);
28080fb93f6STom N Harris            $this->addIndexKey('metadata', '', $metaname);
281b9d8cc1eSTom N Harris            $metaidx = $this->getIndex($metaname.'_i', '');
282b9d8cc1eSTom N Harris            $metawords = $this->getIndex($metaname.'_w', '');
28300803e56STom N Harris            $addwords = false;
284e1e1a7e0SMichael Hamann
285e1e1a7e0SMichael Hamann            if (!is_array($values)) $values = array($values);
286e1e1a7e0SMichael Hamann
287b9d8cc1eSTom N Harris            $val_idx = $this->getIndexKey($metaname.'_p', '', $pid);
288e1e1a7e0SMichael Hamann            if ($val_idx != '') {
289e1e1a7e0SMichael Hamann                $val_idx = explode(':', $val_idx);
290e1e1a7e0SMichael Hamann                // -1 means remove, 0 keep, 1 add
291e1e1a7e0SMichael Hamann                $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
292e1e1a7e0SMichael Hamann            } else {
293e1e1a7e0SMichael Hamann                $val_idx = array();
294e1e1a7e0SMichael Hamann            }
295e1e1a7e0SMichael Hamann
29600803e56STom N Harris            foreach ($values as $val) {
29700803e56STom N Harris                $val = (string)$val;
29800803e56STom N Harris                if ($val !== "") {
29900803e56STom N Harris                    $id = array_search($val, $metawords);
30000803e56STom N Harris                    if ($id === false) {
30100803e56STom N Harris                        $id = count($metawords);
30200803e56STom N Harris                        $metawords[$id] = $val;
30300803e56STom N Harris                        $addwords = true;
304d5b23302STom N Harris                    }
305e1e1a7e0SMichael Hamann                    // test if value is already in the index
306e1e1a7e0SMichael Hamann                    if (isset($val_idx[$id]) && $val_idx[$id] <= 0)
307e1e1a7e0SMichael Hamann                        $val_idx[$id] = 0;
308e1e1a7e0SMichael Hamann                    else // else add it
309e1e1a7e0SMichael Hamann                        $val_idx[$id] = 1;
31044ca0adfSAndreas Gohr                }
311579b0f7eSTNHarris            }
312e1e1a7e0SMichael Hamann
31300803e56STom N Harris            if ($addwords)
31480fb93f6STom N Harris                $this->saveIndex($metaname.'_w', '', $metawords);
315e1e1a7e0SMichael Hamann            $vals_changed = false;
316e1e1a7e0SMichael Hamann            foreach ($val_idx as $id => $action) {
317e1e1a7e0SMichael Hamann                if ($action == -1) {
31880fb93f6STom N Harris                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0);
319e1e1a7e0SMichael Hamann                    $vals_changed = true;
320e1e1a7e0SMichael Hamann                    unset($val_idx[$id]);
321e1e1a7e0SMichael Hamann                } elseif ($action == 1) {
32280fb93f6STom N Harris                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1);
323e1e1a7e0SMichael Hamann                    $vals_changed = true;
324e1e1a7e0SMichael Hamann                }
325e1e1a7e0SMichael Hamann            }
326e1e1a7e0SMichael Hamann
327e1e1a7e0SMichael Hamann            if ($vals_changed) {
32880fb93f6STom N Harris                $this->saveIndex($metaname.'_i', '', $metaidx);
329e1e1a7e0SMichael Hamann                $val_idx = implode(':', array_keys($val_idx));
33080fb93f6STom N Harris                $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx);
331b6344591STom N Harris            }
332e1e1a7e0SMichael Hamann
33300803e56STom N Harris            unset($metaidx);
33400803e56STom N Harris            unset($metawords);
335a0c5c349STom N Harris        }
336e1e1a7e0SMichael Hamann
33780fb93f6STom N Harris        $this->unlock();
338579b0f7eSTNHarris        return true;
33944ca0adfSAndreas Gohr    }
34044ca0adfSAndreas Gohr
34144ca0adfSAndreas Gohr    /**
34200803e56STom N Harris     * Remove a page from the index
34344ca0adfSAndreas Gohr     *
34400803e56STom N Harris     * Erases entries in all known indexes.
34544ca0adfSAndreas Gohr     *
34600803e56STom N Harris     * @param string    $page   a page name
34700803e56STom N Harris     * @return boolean          the function completed successfully
34800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
34944ca0adfSAndreas Gohr     */
35000803e56STom N Harris    public function deletePage($page) {
35180fb93f6STom N Harris        if (!$this->lock())
352bbc85ee4STom N Harris            return "locked";
353bbc85ee4STom N Harris
354bbc85ee4STom N Harris        // load known documents
35503aafe1cSMichael Hamann        $pid = $this->getPIDNoLock($page);
3565981eb09STom N Harris        if ($pid === false) {
35780fb93f6STom N Harris            $this->unlock();
358bbc85ee4STom N Harris            return false;
359bbc85ee4STom N Harris        }
360bbc85ee4STom N Harris
361bbc85ee4STom N Harris        // Remove obsolete index entries
36280fb93f6STom N Harris        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
363bbc85ee4STom N Harris        if ($pageword_idx !== '') {
364bbc85ee4STom N Harris            $delwords = explode(':',$pageword_idx);
365bbc85ee4STom N Harris            $upwords = array();
366bbc85ee4STom N Harris            foreach ($delwords as $word) {
367bbc85ee4STom N Harris                if ($word != '') {
368bbc85ee4STom N Harris                    list($wlen,$wid) = explode('*', $word);
369bbc85ee4STom N Harris                    $wid = (int)$wid;
370bbc85ee4STom N Harris                    $upwords[$wlen][] = $wid;
371bbc85ee4STom N Harris                }
372bbc85ee4STom N Harris            }
373bbc85ee4STom N Harris            foreach ($upwords as $wlen => $widx) {
37480fb93f6STom N Harris                $index = $this->getIndex('i', $wlen);
375bbc85ee4STom N Harris                foreach ($widx as $wid) {
37680fb93f6STom N Harris                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
377bbc85ee4STom N Harris                }
37880fb93f6STom N Harris                $this->saveIndex('i', $wlen, $index);
379bbc85ee4STom N Harris            }
380bbc85ee4STom N Harris        }
381bbc85ee4STom N Harris        // Save the reverse index
38280fb93f6STom N Harris        if (!$this->saveIndexKey('pageword', '', $pid, "")) {
38380fb93f6STom N Harris            $this->unlock();
384bbc85ee4STom N Harris            return false;
385bbc85ee4STom N Harris        }
386bbc85ee4STom N Harris
38780fb93f6STom N Harris        $this->saveIndexKey('title', '', $pid, "");
38880fb93f6STom N Harris        $keyidx = $this->getIndex('metadata', '');
3890604da34STom N Harris        foreach ($keyidx as $metaname) {
39080fb93f6STom N Harris            $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid));
39180fb93f6STom N Harris            $meta_idx = $this->getIndex($metaname.'_i', '');
3920604da34STom N Harris            foreach ($val_idx as $id) {
393c55c59e3SMichael Hamann                if ($id === '') continue;
39480fb93f6STom N Harris                $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0);
3950604da34STom N Harris            }
39680fb93f6STom N Harris            $this->saveIndex($metaname.'_i', '', $meta_idx);
39780fb93f6STom N Harris            $this->saveIndexKey($metaname.'_p', '', $pid, '');
3980604da34STom N Harris        }
399bbc85ee4STom N Harris
40080fb93f6STom N Harris        $this->unlock();
401bbc85ee4STom N Harris        return true;
402d5b23302STom N Harris    }
40344ca0adfSAndreas Gohr
404d5b23302STom N Harris    /**
4053cf3c7d6SMichael Hamann     * Clear the whole index
4063cf3c7d6SMichael Hamann     *
4073cf3c7d6SMichael Hamann     * @return bool If the index has been cleared successfully
4083cf3c7d6SMichael Hamann     */
4093cf3c7d6SMichael Hamann    public function clear() {
4103cf3c7d6SMichael Hamann        global $conf;
4113cf3c7d6SMichael Hamann
4123cf3c7d6SMichael Hamann        if (!$this->lock()) return false;
4133cf3c7d6SMichael Hamann
4143cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/page.idx');
4153cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/title.idx');
4163cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/pageword.idx');
4173cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/metadata.idx');
4183cf3c7d6SMichael Hamann        $dir = @opendir($conf['indexdir']);
4193cf3c7d6SMichael Hamann        if($dir!==false){
4203cf3c7d6SMichael Hamann            while(($f = readdir($dir)) !== false){
4213cf3c7d6SMichael Hamann                if(substr($f,-4)=='.idx' &&
4223cf3c7d6SMichael Hamann                    (substr($f,0,1)=='i' || substr($f,0,1)=='w'
4233cf3c7d6SMichael Hamann                        || substr($f,-6)=='_w.idx' || substr($f,-6)=='_i.idx' || substr($f,-6)=='_p.idx'))
4243cf3c7d6SMichael Hamann                    @unlink($conf['indexdir']."/$f");
4253cf3c7d6SMichael Hamann            }
4263cf3c7d6SMichael Hamann        }
4273cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/lengths.idx');
4283cf3c7d6SMichael Hamann
4293cf3c7d6SMichael Hamann        // clear the pid cache
4303cf3c7d6SMichael Hamann        $this->pidCache = array();
4313cf3c7d6SMichael Hamann
4323cf3c7d6SMichael Hamann        $this->unlock();
4333cf3c7d6SMichael Hamann        return true;
4343cf3c7d6SMichael Hamann    }
4353cf3c7d6SMichael Hamann
4363cf3c7d6SMichael Hamann    /**
43700803e56STom N Harris     * Split the text into words for fulltext search
438d5b23302STom N Harris     *
43900803e56STom N Harris     * TODO: does this also need &$stopwords ?
440d5b23302STom N Harris     *
4418cd4c12fSAndreas Gohr     * @triggers INDEXER_TEXT_PREPARE
4428cd4c12fSAndreas Gohr     * This event allows plugins to modify the text before it gets tokenized.
4438cd4c12fSAndreas Gohr     * Plugins intercepting this event should also intercept INDEX_VERSION_GET
4448cd4c12fSAndreas Gohr     *
44500803e56STom N Harris     * @param string    $text   plain text
44600803e56STom N Harris     * @param boolean   $wc     are wildcards allowed?
44700803e56STom N Harris     * @return array            list of words in the text
448d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
449d5b23302STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
450d5b23302STom N Harris     */
45100803e56STom N Harris    public function tokenizer($text, $wc=false) {
45200803e56STom N Harris        $wc = ($wc) ? '' : '\*';
45300803e56STom N Harris        $stopwords =& idx_get_stopwords();
45400803e56STom N Harris
4558cd4c12fSAndreas Gohr        // prepare the text to be tokenized
4568cd4c12fSAndreas Gohr        $evt = new Doku_Event('INDEXER_TEXT_PREPARE', $text);
4578cd4c12fSAndreas Gohr        if ($evt->advise_before(true)) {
45800803e56STom N Harris            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
45900803e56STom N Harris                // handle asian chars as single words (may fail on older PHP version)
46000803e56STom N Harris                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
46100803e56STom N Harris                if (!is_null($asia)) $text = $asia; // recover from regexp falure
46222952965SYoBoY            }
46322952965SYoBoY        }
4648cd4c12fSAndreas Gohr        $evt->advise_after();
4658cd4c12fSAndreas Gohr        unset($evt);
4668cd4c12fSAndreas Gohr
467f77fc90dSMichael Hamann        $text = strtr($text,
4684f0030ddSAndreas Gohr                       array(
4694f0030ddSAndreas Gohr                           "\r" => ' ',
4704f0030ddSAndreas Gohr                           "\n" => ' ',
4714f0030ddSAndreas Gohr                           "\t" => ' ',
4724f0030ddSAndreas Gohr                           "\xC2\xAD" => '', //soft-hyphen
4734f0030ddSAndreas Gohr                       )
4744f0030ddSAndreas Gohr                     );
47500803e56STom N Harris        if (preg_match('/[^0-9A-Za-z ]/u', $text))
47600803e56STom N Harris            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
47722952965SYoBoY
47800803e56STom N Harris        $wordlist = explode(' ', $text);
4795f27cb0eSMichael Hamann        foreach ($wordlist as $i => $word) {
4805f27cb0eSMichael Hamann            $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
48100803e56STom N Harris                utf8_strtolower($word) : strtolower($word);
4825f27cb0eSMichael Hamann        }
4835f27cb0eSMichael Hamann
4845f27cb0eSMichael Hamann        foreach ($wordlist as $i => $word) {
485675bf41fSTom N Harris            if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH)
486675bf41fSTom N Harris              || array_search($word, $stopwords) !== false)
487675bf41fSTom N Harris                unset($wordlist[$i]);
48822952965SYoBoY        }
489675bf41fSTom N Harris        return array_values($wordlist);
49022952965SYoBoY    }
49122952965SYoBoY
49222952965SYoBoY    /**
49303aafe1cSMichael Hamann     * Get the numeric PID of a page
49403aafe1cSMichael Hamann     *
49503aafe1cSMichael Hamann     * @param string $page The page to get the PID for
49603aafe1cSMichael Hamann     * @return bool|int The page id on success, false on error
49703aafe1cSMichael Hamann     */
49803aafe1cSMichael Hamann    public function getPID($page) {
4993d2ce006SMichael Hamann        // return PID without locking when it is in the cache
5003d2ce006SMichael Hamann        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
5013d2ce006SMichael Hamann
50203aafe1cSMichael Hamann        if (!$this->lock())
50303aafe1cSMichael Hamann            return false;
50403aafe1cSMichael Hamann
50503aafe1cSMichael Hamann        // load known documents
50603aafe1cSMichael Hamann        $pid = $this->getPIDNoLock($page);
50703aafe1cSMichael Hamann        if ($pid === false) {
50803aafe1cSMichael Hamann            $this->unlock();
50903aafe1cSMichael Hamann            return false;
51003aafe1cSMichael Hamann        }
51103aafe1cSMichael Hamann
51203aafe1cSMichael Hamann        $this->unlock();
51303aafe1cSMichael Hamann        return $pid;
51403aafe1cSMichael Hamann    }
51503aafe1cSMichael Hamann
51603aafe1cSMichael Hamann    /**
51703aafe1cSMichael Hamann     * Get the numeric PID of a page without locking the index.
51803aafe1cSMichael Hamann     * Only use this function when the index is already locked.
51903aafe1cSMichael Hamann     *
52003aafe1cSMichael Hamann     * @param string $page The page to get the PID for
52103aafe1cSMichael Hamann     * @return bool|int The page id on success, false on error
52203aafe1cSMichael Hamann     */
52303aafe1cSMichael Hamann    protected function getPIDNoLock($page) {
5243d2ce006SMichael Hamann        // avoid expensive addIndexKey operation for the most recently requested pages by using a cache
5253d2ce006SMichael Hamann        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
5263d2ce006SMichael Hamann        $pid = $this->addIndexKey('page', '', $page);
5273d2ce006SMichael Hamann        // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently
5283d2ce006SMichael Hamann        // added item will be requested again
5293d2ce006SMichael Hamann        if (count($this->pidCache) > 10) array_shift($this->pidCache);
5303d2ce006SMichael Hamann        $this->pidCache[$page] = $pid;
5313d2ce006SMichael Hamann        return $pid;
53203aafe1cSMichael Hamann    }
53303aafe1cSMichael Hamann
53403aafe1cSMichael Hamann    /**
53503aafe1cSMichael Hamann     * Get the page id of a numeric PID
53603aafe1cSMichael Hamann     *
53703aafe1cSMichael Hamann     * @param int $pid The PID to get the page id for
53803aafe1cSMichael Hamann     * @return string The page id
53903aafe1cSMichael Hamann     */
54003aafe1cSMichael Hamann    public function getPageFromPID($pid) {
54103aafe1cSMichael Hamann        return $this->getIndexKey('page', '', $pid);
54203aafe1cSMichael Hamann    }
54303aafe1cSMichael Hamann
54403aafe1cSMichael Hamann    /**
54500803e56STom N Harris     * Find pages in the fulltext index containing the words,
546579b0f7eSTNHarris     *
54700803e56STom N Harris     * The search words must be pre-tokenized, meaning only letters and
54800803e56STom N Harris     * numbers with an optional wildcard
549579b0f7eSTNHarris     *
55000803e56STom N Harris     * The returned array will have the original tokens as key. The values
55100803e56STom N Harris     * in the returned list is an array with the page names as keys and the
552b00bd361STom N Harris     * number of times that token appears on the page as value.
55300803e56STom N Harris     *
554e3ab6fc5SMichael Hamann     * @param array  $tokens list of words to search for
55500803e56STom N Harris     * @return array         list of page names with usage counts
55600803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
55700803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
558579b0f7eSTNHarris     */
5599b41be24STom N Harris    public function lookup(&$tokens) {
56000803e56STom N Harris        $result = array();
56180fb93f6STom N Harris        $wids = $this->getIndexWords($tokens, $result);
56200803e56STom N Harris        if (empty($wids)) return array();
56300803e56STom N Harris        // load known words and documents
56480fb93f6STom N Harris        $page_idx = $this->getIndex('page', '');
56500803e56STom N Harris        $docs = array();
56600803e56STom N Harris        foreach (array_keys($wids) as $wlen) {
56700803e56STom N Harris            $wids[$wlen] = array_unique($wids[$wlen]);
56880fb93f6STom N Harris            $index = $this->getIndex('i', $wlen);
56900803e56STom N Harris            foreach($wids[$wlen] as $ixid) {
57000803e56STom N Harris                if ($ixid < count($index))
57180fb93f6STom N Harris                    $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]);
572d5b23302STom N Harris            }
573d5b23302STom N Harris        }
57400803e56STom N Harris        // merge found pages into final result array
57500803e56STom N Harris        $final = array();
57600803e56STom N Harris        foreach ($result as $word => $res) {
57700803e56STom N Harris            $final[$word] = array();
57800803e56STom N Harris            foreach ($res as $wid) {
579952ab260SMichael Hamann                // handle the case when ($ixid < count($index)) has been false
580952ab260SMichael Hamann                // and thus $docs[$wid] hasn't been set.
581952ab260SMichael Hamann                if (!isset($docs[$wid])) continue;
58200803e56STom N Harris                $hits = &$docs[$wid];
58300803e56STom N Harris                foreach ($hits as $hitkey => $hitcnt) {
58400803e56STom N Harris                    // make sure the document still exists
58500803e56STom N Harris                    if (!page_exists($hitkey, '', false)) continue;
58600803e56STom N Harris                    if (!isset($final[$word][$hitkey]))
58700803e56STom N Harris                        $final[$word][$hitkey] = $hitcnt;
58800803e56STom N Harris                    else
58900803e56STom N Harris                        $final[$word][$hitkey] += $hitcnt;
590d5b23302STom N Harris                }
591579b0f7eSTNHarris            }
592579b0f7eSTNHarris        }
59300803e56STom N Harris        return $final;
594579b0f7eSTNHarris    }
595579b0f7eSTNHarris
596579b0f7eSTNHarris    /**
59700803e56STom N Harris     * Find pages containing a metadata key.
598d5b23302STom N Harris     *
59900803e56STom N Harris     * The metadata values are compared as case-sensitive strings. Pass a
60000803e56STom N Harris     * callback function that returns true or false to use a different
601b00bd361STom N Harris     * comparison function. The function will be called with the $value being
602b00bd361STom N Harris     * searched for as the first argument, and the word in the index as the
6031538718dSTom N Harris     * second argument. The function preg_match can be used directly if the
6041538718dSTom N Harris     * values are regexes.
605d5b23302STom N Harris     *
60600803e56STom N Harris     * @param string    $key    name of the metadata key to look for
6071538718dSTom N Harris     * @param string    $value  search term to look for, must be a string or array of strings
60800803e56STom N Harris     * @param callback  $func   comparison function
609b00bd361STom N Harris     * @return array            lists with page names, keys are query values if $value is array
61000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
611cd763a5bSMichael Hamann     * @author Michael Hamann <michael@content-space.de>
61200803e56STom N Harris     */
613b00bd361STom N Harris    public function lookupKey($key, &$value, $func=null) {
614f078bb00STom N Harris        if (!is_array($value))
615f078bb00STom N Harris            $value_array = array($value);
616f078bb00STom N Harris        else
617f078bb00STom N Harris            $value_array =& $value;
618cd763a5bSMichael Hamann
619c1209673STom N Harris        // the matching ids for the provided value(s)
620c1209673STom N Harris        $value_ids = array();
621c1209673STom N Harris
622c1209673STom N Harris        $metaname = idx_cleanName($key);
623c1209673STom N Harris
624c1209673STom N Harris        // get all words in order to search the matching ids
625c1209673STom N Harris        if ($key == 'title') {
62680fb93f6STom N Harris            $words = $this->getIndex('title', '');
627c1209673STom N Harris        } else {
628b9d8cc1eSTom N Harris            $words = $this->getIndex($metaname.'_w', '');
629c1209673STom N Harris        }
630c1209673STom N Harris
631f078bb00STom N Harris        if (!is_null($func)) {
6321538718dSTom N Harris            foreach ($value_array as $val) {
633f078bb00STom N Harris                foreach ($words as $i => $word) {
6341538718dSTom N Harris                    if (call_user_func_array($func, array($val, $word)))
635c1209673STom N Harris                        $value_ids[$i][] = $val;
636f078bb00STom N Harris                }
637f078bb00STom N Harris            }
638f078bb00STom N Harris        } else {
639f078bb00STom N Harris            foreach ($value_array as $val) {
640f078bb00STom N Harris                $xval = $val;
641b6d540bdSTom N Harris                $caret = '^';
642b6d540bdSTom N Harris                $dollar = '$';
643f078bb00STom N Harris                // check for wildcards
644f078bb00STom N Harris                if (substr($xval, 0, 1) == '*') {
645f078bb00STom N Harris                    $xval = substr($xval, 1);
646b6d540bdSTom N Harris                    $caret = '';
647f078bb00STom N Harris                }
648f078bb00STom N Harris                if (substr($xval, -1, 1) == '*') {
649f078bb00STom N Harris                    $xval = substr($xval, 0, -1);
650b6d540bdSTom N Harris                    $dollar = '';
651f078bb00STom N Harris                }
652b6d540bdSTom N Harris                if (!$caret || !$dollar) {
653f078bb00STom N Harris                    $re = $caret.preg_quote($xval, '/').$dollar;
654f078bb00STom N Harris                    foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
655c1209673STom N Harris                        $value_ids[$i][] = $val;
656cd763a5bSMichael Hamann                } else {
657f078bb00STom N Harris                    if (($i = array_search($val, $words)) !== false)
658c1209673STom N Harris                        $value_ids[$i][] = $val;
659cd763a5bSMichael Hamann                }
660cd763a5bSMichael Hamann            }
661cd763a5bSMichael Hamann        }
662cd763a5bSMichael Hamann
663cd763a5bSMichael Hamann        unset($words); // free the used memory
664cd763a5bSMichael Hamann
6657233c152SMichael Hamann        // initialize the result so it won't be null
666c1209673STom N Harris        $result = array();
6677233c152SMichael Hamann        foreach ($value_array as $val) {
6687233c152SMichael Hamann            $result[$val] = array();
6697233c152SMichael Hamann        }
6707233c152SMichael Hamann
67180fb93f6STom N Harris        $page_idx = $this->getIndex('page', '');
672cd763a5bSMichael Hamann
673c1209673STom N Harris        // Special handling for titles
674c1209673STom N Harris        if ($key == 'title') {
675c1209673STom N Harris            foreach ($value_ids as $pid => $val_list) {
676c1209673STom N Harris                $page = $page_idx[$pid];
677c1209673STom N Harris                foreach ($val_list as $val) {
678c1209673STom N Harris                    $result[$val][] = $page;
679c1209673STom N Harris                }
680c1209673STom N Harris            }
681c1209673STom N Harris        } else {
682c1209673STom N Harris            // load all lines and pages so the used lines can be taken and matched with the pages
683b9d8cc1eSTom N Harris            $lines = $this->getIndex($metaname.'_i', '');
684c1209673STom N Harris
685c1209673STom N Harris            foreach ($value_ids as $value_id => $val_list) {
686cd763a5bSMichael Hamann                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
687cd763a5bSMichael Hamann                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
68880fb93f6STom N Harris                $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id]));
689c1209673STom N Harris                foreach ($val_list as $val) {
690c1209673STom N Harris                    $result[$val] = array_merge($result[$val], $pages);
691c1209673STom N Harris                }
692c1209673STom N Harris            }
693cd763a5bSMichael Hamann        }
694f078bb00STom N Harris        if (!is_array($value)) $result = $result[$value];
695cd763a5bSMichael Hamann        return $result;
69600803e56STom N Harris    }
69700803e56STom N Harris
69800803e56STom N Harris    /**
69900803e56STom N Harris     * Find the index ID of each search term.
70000803e56STom N Harris     *
70100803e56STom N Harris     * The query terms should only contain valid characters, with a '*' at
70200803e56STom N Harris     * either the beginning or end of the word (or both).
70300803e56STom N Harris     * The $result parameter can be used to merge the index locations with
70400803e56STom N Harris     * the appropriate query term.
70500803e56STom N Harris     *
706e3ab6fc5SMichael Hamann     * @param array  $words  The query terms.
707e3ab6fc5SMichael Hamann     * @param array  $result Set to word => array("length*id" ...)
708d5b23302STom N Harris     * @return array         Set to length => array(id ...)
709d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
710d5b23302STom N Harris     */
71180fb93f6STom N Harris    protected function getIndexWords(&$words, &$result) {
712d5b23302STom N Harris        $tokens = array();
713d5b23302STom N Harris        $tokenlength = array();
714d5b23302STom N Harris        $tokenwild = array();
715d5b23302STom N Harris        foreach ($words as $word) {
716d5b23302STom N Harris            $result[$word] = array();
717b6d540bdSTom N Harris            $caret = '^';
718b6d540bdSTom N Harris            $dollar = '$';
719d5b23302STom N Harris            $xword = $word;
720d5b23302STom N Harris            $wlen = wordlen($word);
721d5b23302STom N Harris
722d5b23302STom N Harris            // check for wildcards
723d5b23302STom N Harris            if (substr($xword, 0, 1) == '*') {
724d5b23302STom N Harris                $xword = substr($xword, 1);
725b6d540bdSTom N Harris                $caret = '';
726d5b23302STom N Harris                $wlen -= 1;
727d5b23302STom N Harris            }
728d5b23302STom N Harris            if (substr($xword, -1, 1) == '*') {
729d5b23302STom N Harris                $xword = substr($xword, 0, -1);
730b6d540bdSTom N Harris                $dollar = '';
731d5b23302STom N Harris                $wlen -= 1;
732d5b23302STom N Harris            }
733b6d540bdSTom N Harris            if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
73400803e56STom N Harris                continue;
73500803e56STom N Harris            if (!isset($tokens[$xword]))
736d5b23302STom N Harris                $tokenlength[$wlen][] = $xword;
737b6d540bdSTom N Harris            if (!$caret || !$dollar) {
738f078bb00STom N Harris                $re = $caret.preg_quote($xword, '/').$dollar;
73900803e56STom N Harris                $tokens[$xword][] = array($word, '/'.$re.'/');
74000803e56STom N Harris                if (!isset($tokenwild[$xword]))
74100803e56STom N Harris                    $tokenwild[$xword] = $wlen;
74200803e56STom N Harris            } else {
743d5b23302STom N Harris                $tokens[$xword][] = array($word, null);
744d5b23302STom N Harris            }
74500803e56STom N Harris        }
746d5b23302STom N Harris        asort($tokenwild);
74700803e56STom N Harris        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
748d5b23302STom N Harris        // $tokenlength = array( base word length => base word ... )
749d5b23302STom N Harris        // $tokenwild = array( base word => base word length ... )
750d5b23302STom N Harris        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
75180fb93f6STom N Harris        $indexes_known = $this->indexLengths($length_filter);
752d5b23302STom N Harris        if (!empty($tokenwild)) sort($indexes_known);
753d5b23302STom N Harris        // get word IDs
754d5b23302STom N Harris        $wids = array();
755d5b23302STom N Harris        foreach ($indexes_known as $ixlen) {
75680fb93f6STom N Harris            $word_idx = $this->getIndex('w', $ixlen);
757d5b23302STom N Harris            // handle exact search
758d5b23302STom N Harris            if (isset($tokenlength[$ixlen])) {
759d5b23302STom N Harris                foreach ($tokenlength[$ixlen] as $xword) {
76000803e56STom N Harris                    $wid = array_search($xword, $word_idx);
76100803e56STom N Harris                    if ($wid !== false) {
762d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
763d5b23302STom N Harris                        foreach ($tokens[$xword] as $w)
764d5b23302STom N Harris                            $result[$w[0]][] = "$ixlen*$wid";
765d5b23302STom N Harris                    }
766d5b23302STom N Harris                }
767d5b23302STom N Harris            }
768d5b23302STom N Harris            // handle wildcard search
769d5b23302STom N Harris            foreach ($tokenwild as $xword => $wlen) {
770d5b23302STom N Harris                if ($wlen >= $ixlen) break;
771d5b23302STom N Harris                foreach ($tokens[$xword] as $w) {
772d5b23302STom N Harris                    if (is_null($w[1])) continue;
773d5b23302STom N Harris                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
774d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
775d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
776d5b23302STom N Harris                    }
777d5b23302STom N Harris                }
778d5b23302STom N Harris            }
779d5b23302STom N Harris        }
780d5b23302STom N Harris        return $wids;
781d5b23302STom N Harris    }
782d5b23302STom N Harris
783d5b23302STom N Harris    /**
78400803e56STom N Harris     * Return a list of all pages
785c1209673STom N Harris     * Warning: pages may not exist!
786488dd6ceSAndreas Gohr     *
78700803e56STom N Harris     * @param string    $key    list only pages containing the metadata key (optional)
78800803e56STom N Harris     * @return array            list of page names
78900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
79000803e56STom N Harris     */
79100803e56STom N Harris    public function getPages($key=null) {
79280fb93f6STom N Harris        $page_idx = $this->getIndex('page', '');
79300803e56STom N Harris        if (is_null($key)) return $page_idx;
794c1209673STom N Harris
795c1209673STom N Harris        $metaname = idx_cleanName($key);
796c1209673STom N Harris
797c1209673STom N Harris        // Special handling for titles
798c1209673STom N Harris        if ($key == 'title') {
79980fb93f6STom N Harris            $title_idx = $this->getIndex('title', '');
800c1209673STom N Harris            array_splice($page_idx, count($title_idx));
801c1209673STom N Harris            foreach ($title_idx as $i => $title)
802c1209673STom N Harris                if ($title === "") unset($page_idx[$i]);
803675bf41fSTom N Harris            return array_values($page_idx);
804c1209673STom N Harris        }
805c1209673STom N Harris
806c1209673STom N Harris        $pages = array();
807b9d8cc1eSTom N Harris        $lines = $this->getIndex($metaname.'_i', '');
808c1209673STom N Harris        foreach ($lines as $line) {
80980fb93f6STom N Harris            $pages = array_merge($pages, $this->parseTuples($page_idx, $line));
810c1209673STom N Harris        }
811c1209673STom N Harris        return array_keys($pages);
81200803e56STom N Harris    }
81300803e56STom N Harris
81400803e56STom N Harris    /**
81500803e56STom N Harris     * Return a list of words sorted by number of times used
81600803e56STom N Harris     *
81700803e56STom N Harris     * @param int       $min    bottom frequency threshold
81800803e56STom N Harris     * @param int       $max    upper frequency limit. No limit if $max<$min
819e3ab6fc5SMichael Hamann     * @param int       $minlen minimum length of words to count
82000803e56STom N Harris     * @param string    $key    metadata key to list. Uses the fulltext index if not given
82100803e56STom N Harris     * @return array            list of words as the keys and frequency as values
82200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
82300803e56STom N Harris     */
824b8c040dbSTom N Harris    public function histogram($min=1, $max=0, $minlen=3, $key=null) {
825175193d2STom N Harris        if ($min < 1)
826175193d2STom N Harris            $min = 1;
827175193d2STom N Harris        if ($max < $min)
828175193d2STom N Harris            $max = 0;
829175193d2STom N Harris
830175193d2STom N Harris        $result = array();
831175193d2STom N Harris
832175193d2STom N Harris        if ($key == 'title') {
83380fb93f6STom N Harris            $index = $this->getIndex('title', '');
834175193d2STom N Harris            $index = array_count_values($index);
835175193d2STom N Harris            foreach ($index as $val => $cnt) {
836b8c040dbSTom N Harris                if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
837175193d2STom N Harris                    $result[$val] = $cnt;
838175193d2STom N Harris            }
839175193d2STom N Harris        }
840175193d2STom N Harris        elseif (!is_null($key)) {
841175193d2STom N Harris            $metaname = idx_cleanName($key);
84280fb93f6STom N Harris            $index = $this->getIndex($metaname.'_i', '');
843175193d2STom N Harris            $val_idx = array();
844175193d2STom N Harris            foreach ($index as $wid => $line) {
84580fb93f6STom N Harris                $freq = $this->countTuples($line);
8469a9b579aSMichael Hamann                if ($freq >= $min && (!$max || $freq <= $max))
847175193d2STom N Harris                    $val_idx[$wid] = $freq;
848175193d2STom N Harris            }
849175193d2STom N Harris            if (!empty($val_idx)) {
85080fb93f6STom N Harris                $words = $this->getIndex($metaname.'_w', '');
8519a9b579aSMichael Hamann                foreach ($val_idx as $wid => $freq) {
8529a9b579aSMichael Hamann                    if (strlen($words[$wid]) >= $minlen)
853175193d2STom N Harris                        $result[$words[$wid]] = $freq;
854175193d2STom N Harris                }
855175193d2STom N Harris            }
8569a9b579aSMichael Hamann        }
857175193d2STom N Harris        else {
858175193d2STom N Harris            $lengths = idx_listIndexLengths();
859175193d2STom N Harris            foreach ($lengths as $length) {
860b8c040dbSTom N Harris                if ($length < $minlen) continue;
86180fb93f6STom N Harris                $index = $this->getIndex('i', $length);
862175193d2STom N Harris                $words = null;
863175193d2STom N Harris                foreach ($index as $wid => $line) {
86480fb93f6STom N Harris                    $freq = $this->countTuples($line);
865175193d2STom N Harris                    if ($freq >= $min && (!$max || $freq <= $max)) {
866175193d2STom N Harris                        if ($words === null)
86780fb93f6STom N Harris                            $words = $this->getIndex('w', $length);
868175193d2STom N Harris                        $result[$words[$wid]] = $freq;
869175193d2STom N Harris                    }
870175193d2STom N Harris                }
871175193d2STom N Harris            }
872175193d2STom N Harris        }
873175193d2STom N Harris
874175193d2STom N Harris        arsort($result);
875175193d2STom N Harris        return $result;
87600803e56STom N Harris    }
87700803e56STom N Harris
87800803e56STom N Harris    /**
87900803e56STom N Harris     * Lock the indexer.
88000803e56STom N Harris     *
88100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
88200803e56STom N Harris     */
88380fb93f6STom N Harris    protected function lock() {
88400803e56STom N Harris        global $conf;
88500803e56STom N Harris        $status = true;
886f77fc90dSMichael Hamann        $run = 0;
88700803e56STom N Harris        $lock = $conf['lockdir'].'/_indexer.lock';
88800803e56STom N Harris        while (!@mkdir($lock, $conf['dmode'])) {
88900803e56STom N Harris            usleep(50);
890f77fc90dSMichael Hamann            if(is_dir($lock) && time()-@filemtime($lock) > 60*5){
891f77fc90dSMichael Hamann                // looks like a stale lock - remove it
892f77fc90dSMichael Hamann                if (!@rmdir($lock)) {
893f77fc90dSMichael Hamann                    $status = "removing the stale lock failed";
894f77fc90dSMichael Hamann                    return false;
89500803e56STom N Harris                } else {
896f77fc90dSMichael Hamann                    $status = "stale lock removed";
897f77fc90dSMichael Hamann                }
898f77fc90dSMichael Hamann            }elseif($run++ == 1000){
899f77fc90dSMichael Hamann                // we waited 5 seconds for that lock
90000803e56STom N Harris                return false;
90100803e56STom N Harris            }
90200803e56STom N Harris        }
90300803e56STom N Harris        if ($conf['dperm'])
90400803e56STom N Harris            chmod($lock, $conf['dperm']);
90500803e56STom N Harris        return $status;
90600803e56STom N Harris    }
90700803e56STom N Harris
90800803e56STom N Harris    /**
90900803e56STom N Harris     * Release the indexer lock.
91000803e56STom N Harris     *
91100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
91200803e56STom N Harris     */
91380fb93f6STom N Harris    protected function unlock() {
91400803e56STom N Harris        global $conf;
91500803e56STom N Harris        @rmdir($conf['lockdir'].'/_indexer.lock');
91600803e56STom N Harris        return true;
91700803e56STom N Harris    }
91800803e56STom N Harris
91900803e56STom N Harris    /**
92000803e56STom N Harris     * Retrieve the entire index.
92100803e56STom N Harris     *
922b9d8cc1eSTom N Harris     * The $suffix argument is for an index that is split into
923b9d8cc1eSTom N Harris     * multiple parts. Different index files should use different
924b9d8cc1eSTom N Harris     * base names.
925b9d8cc1eSTom N Harris     *
926b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
927b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
928b9d8cc1eSTom N Harris     * @return array            list of lines without CR or LF
92900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
93000803e56STom N Harris     */
93180fb93f6STom N Harris    protected function getIndex($idx, $suffix) {
93200803e56STom N Harris        global $conf;
93300803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
934d64516f5SMichael Hamann        if (!@file_exists($fn)) return array();
935d64516f5SMichael Hamann        return file($fn, FILE_IGNORE_NEW_LINES);
93600803e56STom N Harris    }
93700803e56STom N Harris
93800803e56STom N Harris    /**
93900803e56STom N Harris     * Replace the contents of the index with an array.
94000803e56STom N Harris     *
941b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
942b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
943e3ab6fc5SMichael Hamann     * @param array     $lines  list of lines without LF
944e3ab6fc5SMichael Hamann     * @return bool             If saving succeeded
94500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
94600803e56STom N Harris     */
94780fb93f6STom N Harris    protected function saveIndex($idx, $suffix, &$lines) {
94800803e56STom N Harris        global $conf;
94900803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
95000803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
95100803e56STom N Harris        if (!$fh) return false;
95200803e56STom N Harris        fwrite($fh, join("\n", $lines));
9532e1018bcSMichael Hamann        if (!empty($lines))
9542e1018bcSMichael Hamann            fwrite($fh, "\n");
95500803e56STom N Harris        fclose($fh);
95600803e56STom N Harris        if (isset($conf['fperm']))
95700803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
95800803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
95900803e56STom N Harris        if ($suffix !== '')
96080fb93f6STom N Harris            $this->cacheIndexDir($idx, $suffix, empty($lines));
96100803e56STom N Harris        return true;
96200803e56STom N Harris    }
96300803e56STom N Harris
96400803e56STom N Harris    /**
96500803e56STom N Harris     * Retrieve a line from the index.
96600803e56STom N Harris     *
967b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
968b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
969b9d8cc1eSTom N Harris     * @param int       $id     the line number
970b9d8cc1eSTom N Harris     * @return string           a line with trailing whitespace removed
97100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
97200803e56STom N Harris     */
97380fb93f6STom N Harris    protected function getIndexKey($idx, $suffix, $id) {
97400803e56STom N Harris        global $conf;
97500803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
97600803e56STom N Harris        if (!@file_exists($fn)) return '';
97700803e56STom N Harris        $fh = @fopen($fn, 'r');
97800803e56STom N Harris        if (!$fh) return '';
97900803e56STom N Harris        $ln = -1;
98000803e56STom N Harris        while (($line = fgets($fh)) !== false) {
98100803e56STom N Harris            if (++$ln == $id) break;
98200803e56STom N Harris        }
98300803e56STom N Harris        fclose($fh);
98400803e56STom N Harris        return rtrim((string)$line);
98500803e56STom N Harris    }
98600803e56STom N Harris
98700803e56STom N Harris    /**
98800803e56STom N Harris     * Write a line into the index.
98900803e56STom N Harris     *
990b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
991b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
992b9d8cc1eSTom N Harris     * @param int       $id     the line number
993b9d8cc1eSTom N Harris     * @param string    $line   line to write
994e3ab6fc5SMichael Hamann     * @return bool             If saving succeeded
99500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
99600803e56STom N Harris     */
99780fb93f6STom N Harris    protected function saveIndexKey($idx, $suffix, $id, $line) {
99800803e56STom N Harris        global $conf;
99900803e56STom N Harris        if (substr($line, -1) != "\n")
100000803e56STom N Harris            $line .= "\n";
100100803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
100200803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
1003dbb771bbSAdrian Lang        if (!$fh) return false;
100400803e56STom N Harris        $ih = @fopen($fn.'.idx', 'r');
100500803e56STom N Harris        if ($ih) {
100600803e56STom N Harris            $ln = -1;
100700803e56STom N Harris            while (($curline = fgets($ih)) !== false) {
100800803e56STom N Harris                fwrite($fh, (++$ln == $id) ? $line : $curline);
100900803e56STom N Harris            }
10104373c7b5SMichael Hamann            if ($id > $ln) {
10114373c7b5SMichael Hamann                while ($id > ++$ln)
10124373c7b5SMichael Hamann                    fwrite($fh, "\n");
101300803e56STom N Harris                fwrite($fh, $line);
10144373c7b5SMichael Hamann            }
101500803e56STom N Harris            fclose($ih);
101600803e56STom N Harris        } else {
10174373c7b5SMichael Hamann            $ln = -1;
10184373c7b5SMichael Hamann            while ($id > ++$ln)
10194373c7b5SMichael Hamann                fwrite($fh, "\n");
102000803e56STom N Harris            fwrite($fh, $line);
102100803e56STom N Harris        }
102200803e56STom N Harris        fclose($fh);
102300803e56STom N Harris        if (isset($conf['fperm']))
102400803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
102500803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
102600803e56STom N Harris        if ($suffix !== '')
102780fb93f6STom N Harris            $this->cacheIndexDir($idx, $suffix);
102800803e56STom N Harris        return true;
102900803e56STom N Harris    }
103000803e56STom N Harris
103100803e56STom N Harris    /**
103200803e56STom N Harris     * Retrieve or insert a value in the index.
103300803e56STom N Harris     *
1034b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
1035b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
1036b9d8cc1eSTom N Harris     * @param string    $value  line to find in the index
103703aafe1cSMichael Hamann     * @return int|bool          line number of the value in the index or false if writing the index failed
103800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
103900803e56STom N Harris     */
104080fb93f6STom N Harris    protected function addIndexKey($idx, $suffix, $value) {
104180fb93f6STom N Harris        $index = $this->getIndex($idx, $suffix);
104200803e56STom N Harris        $id = array_search($value, $index);
104300803e56STom N Harris        if ($id === false) {
104400803e56STom N Harris            $id = count($index);
104500803e56STom N Harris            $index[$id] = $value;
104680fb93f6STom N Harris            if (!$this->saveIndex($idx, $suffix, $index)) {
104700803e56STom N Harris                trigger_error("Failed to write $idx index", E_USER_ERROR);
104800803e56STom N Harris                return false;
104900803e56STom N Harris            }
105000803e56STom N Harris        }
105100803e56STom N Harris        return $id;
105200803e56STom N Harris    }
105300803e56STom N Harris
1054e3ab6fc5SMichael Hamann    /**
1055e3ab6fc5SMichael Hamann     * @param string $idx    The index file which should be added to the key.
1056e3ab6fc5SMichael Hamann     * @param string $suffix The suffix of the file
1057e3ab6fc5SMichael Hamann     * @param bool   $delete Unused
1058e3ab6fc5SMichael Hamann     */
105980fb93f6STom N Harris    protected function cacheIndexDir($idx, $suffix, $delete=false) {
106000803e56STom N Harris        global $conf;
106100803e56STom N Harris        if ($idx == 'i')
106200803e56STom N Harris            $cachename = $conf['indexdir'].'/lengths';
106300803e56STom N Harris        else
106400803e56STom N Harris            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
106500803e56STom N Harris        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
106600803e56STom N Harris        if ($lengths === false) $lengths = array();
106700803e56STom N Harris        $old = array_search((string)$suffix, $lengths);
106800803e56STom N Harris        if (empty($lines)) {
106900803e56STom N Harris            if ($old === false) return;
107000803e56STom N Harris            unset($lengths[$old]);
107100803e56STom N Harris        } else {
107200803e56STom N Harris            if ($old !== false) return;
107300803e56STom N Harris            $lengths[] = $suffix;
107400803e56STom N Harris            sort($lengths);
107500803e56STom N Harris        }
107600803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
107700803e56STom N Harris        if (!$fh) {
107800803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
107900803e56STom N Harris            return;
108000803e56STom N Harris        }
108100803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
108200803e56STom N Harris        @fclose($fh);
108300803e56STom N Harris        if (isset($conf['fperm']))
108400803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
108500803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
108600803e56STom N Harris    }
108700803e56STom N Harris
108800803e56STom N Harris    /**
108900803e56STom N Harris     * Get the list of lengths indexed in the wiki.
109000803e56STom N Harris     *
109100803e56STom N Harris     * Read the index directory or a cache file and returns
109200803e56STom N Harris     * a sorted array of lengths of the words used in the wiki.
109300803e56STom N Harris     *
109400803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
109500803e56STom N Harris     */
109680fb93f6STom N Harris    protected function listIndexLengths() {
109700803e56STom N Harris        global $conf;
109800803e56STom N Harris        $cachename = $conf['indexdir'].'/lengths';
109900803e56STom N Harris        clearstatcache();
110000803e56STom N Harris        if (@file_exists($cachename.'.idx')) {
110100803e56STom N Harris            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
110200803e56STom N Harris            if ($lengths !== false) {
110300803e56STom N Harris                $idx = array();
110400803e56STom N Harris                foreach ($lengths as $length)
110500803e56STom N Harris                    $idx[] = (int)$length;
110600803e56STom N Harris                return $idx;
110700803e56STom N Harris            }
110800803e56STom N Harris        }
110900803e56STom N Harris
111000803e56STom N Harris        $dir = @opendir($conf['indexdir']);
111100803e56STom N Harris        if ($dir === false)
111200803e56STom N Harris            return array();
111300803e56STom N Harris        $lengths[] = array();
111400803e56STom N Harris        while (($f = readdir($dir)) !== false) {
111500803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
111600803e56STom N Harris                $i = substr($f, 1, -4);
111700803e56STom N Harris                if (is_numeric($i))
111800803e56STom N Harris                    $lengths[] = (int)$i;
111900803e56STom N Harris            }
112000803e56STom N Harris        }
112100803e56STom N Harris        closedir($dir);
112200803e56STom N Harris        sort($lengths);
112300803e56STom N Harris        // save this in a file
112400803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
112500803e56STom N Harris        if (!$fh) {
112600803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
11273e8e3ae6SMichael Hamann            return $lengths;
112800803e56STom N Harris        }
112900803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
113000803e56STom N Harris        @fclose($fh);
113100803e56STom N Harris        if (isset($conf['fperm']))
113200803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
113300803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
113400803e56STom N Harris
113500803e56STom N Harris        return $lengths;
113600803e56STom N Harris    }
113700803e56STom N Harris
113800803e56STom N Harris    /**
113900803e56STom N Harris     * Get the word lengths that have been indexed.
114000803e56STom N Harris     *
114100803e56STom N Harris     * Reads the index directory and returns an array of lengths
114200803e56STom N Harris     * that there are indices for.
114300803e56STom N Harris     *
114400803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
114500803e56STom N Harris     */
114680fb93f6STom N Harris    protected function indexLengths($filter) {
114700803e56STom N Harris        global $conf;
114800803e56STom N Harris        $idx = array();
114900803e56STom N Harris        if (is_array($filter)) {
115000803e56STom N Harris            // testing if index files exist only
115100803e56STom N Harris            $path = $conf['indexdir']."/i";
115200803e56STom N Harris            foreach ($filter as $key => $value) {
115300803e56STom N Harris                if (@file_exists($path.$key.'.idx'))
115400803e56STom N Harris                    $idx[] = $key;
115500803e56STom N Harris            }
115600803e56STom N Harris        } else {
115700803e56STom N Harris            $lengths = idx_listIndexLengths();
115800803e56STom N Harris            foreach ($lengths as $key => $length) {
115900803e56STom N Harris                // keep all the values equal or superior
116000803e56STom N Harris                if ((int)$length >= (int)$filter)
116100803e56STom N Harris                    $idx[] = $length;
116200803e56STom N Harris            }
116300803e56STom N Harris        }
116400803e56STom N Harris        return $idx;
116500803e56STom N Harris    }
116600803e56STom N Harris
116700803e56STom N Harris    /**
116800803e56STom N Harris     * Insert or replace a tuple in a line.
116900803e56STom N Harris     *
117000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
117100803e56STom N Harris     */
117280fb93f6STom N Harris    protected function updateTuple($line, $id, $count) {
117300803e56STom N Harris        $newLine = $line;
117400803e56STom N Harris        if ($newLine !== '')
117500803e56STom N Harris            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
117600803e56STom N Harris        $newLine = trim($newLine, ':');
117700803e56STom N Harris        if ($count) {
1178d64516f5SMichael Hamann            if (strlen($newLine) > 0)
117900803e56STom N Harris                return "$id*$count:".$newLine;
118000803e56STom N Harris            else
118100803e56STom N Harris                return "$id*$count".$newLine;
118200803e56STom N Harris        }
118300803e56STom N Harris        return $newLine;
118400803e56STom N Harris    }
118500803e56STom N Harris
118600803e56STom N Harris    /**
118700803e56STom N Harris     * Split a line into an array of tuples.
118800803e56STom N Harris     *
118900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
119000803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
119100803e56STom N Harris     */
119280fb93f6STom N Harris    protected function parseTuples(&$keys, $line) {
119300803e56STom N Harris        $result = array();
119400803e56STom N Harris        if ($line == '') return $result;
119500803e56STom N Harris        $parts = explode(':', $line);
119600803e56STom N Harris        foreach ($parts as $tuple) {
1197675bf41fSTom N Harris            if ($tuple === '') continue;
119800803e56STom N Harris            list($key, $cnt) = explode('*', $tuple);
1199d64516f5SMichael Hamann            if (!$cnt) continue;
120000803e56STom N Harris            $key = $keys[$key];
120100803e56STom N Harris            if (!$key) continue;
120200803e56STom N Harris            $result[$key] = $cnt;
120300803e56STom N Harris        }
120400803e56STom N Harris        return $result;
120500803e56STom N Harris    }
1206175193d2STom N Harris
1207175193d2STom N Harris    /**
1208175193d2STom N Harris     * Sum the counts in a list of tuples.
1209175193d2STom N Harris     *
1210175193d2STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
1211175193d2STom N Harris     */
121280fb93f6STom N Harris    protected function countTuples($line) {
1213175193d2STom N Harris        $freq = 0;
1214175193d2STom N Harris        $parts = explode(':', $line);
1215175193d2STom N Harris        foreach ($parts as $tuple) {
1216675bf41fSTom N Harris            if ($tuple === '') continue;
1217175193d2STom N Harris            list($pid, $cnt) = explode('*', $tuple);
1218175193d2STom N Harris            $freq += (int)$cnt;
1219175193d2STom N Harris        }
1220175193d2STom N Harris        return $freq;
1221175193d2STom N Harris    }
122200803e56STom N Harris}
122300803e56STom N Harris
122400803e56STom N Harris/**
122500803e56STom N Harris * Create an instance of the indexer.
122600803e56STom N Harris *
1227b3d1090eSMichael Hamann * @return Doku_Indexer               a Doku_Indexer
122800803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
122900803e56STom N Harris */
12309b41be24STom N Harrisfunction idx_get_indexer() {
1231*4f708321SMichael Hamann    static $Indexer;
12321421e548SMichael Hamann    if (!isset($Indexer)) {
123300803e56STom N Harris        $Indexer = new Doku_Indexer();
123400803e56STom N Harris    }
123500803e56STom N Harris    return $Indexer;
123600803e56STom N Harris}
123700803e56STom N Harris
123800803e56STom N Harris/**
123900803e56STom N Harris * Returns words that will be ignored.
124000803e56STom N Harris *
124100803e56STom N Harris * @return array                list of stop words
124200803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
124300803e56STom N Harris */
124400803e56STom N Harrisfunction & idx_get_stopwords() {
124500803e56STom N Harris    static $stopwords = null;
124600803e56STom N Harris    if (is_null($stopwords)) {
124700803e56STom N Harris        global $conf;
124800803e56STom N Harris        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
124900803e56STom N Harris        if(@file_exists($swfile)){
125000803e56STom N Harris            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
125100803e56STom N Harris        }else{
125200803e56STom N Harris            $stopwords = array();
125300803e56STom N Harris        }
125400803e56STom N Harris    }
125500803e56STom N Harris    return $stopwords;
125600803e56STom N Harris}
125700803e56STom N Harris
125800803e56STom N Harris/**
125900803e56STom N Harris * Adds/updates the search index for the given page
126000803e56STom N Harris *
126100803e56STom N Harris * Locking is handled internally.
126200803e56STom N Harris *
126300803e56STom N Harris * @param string        $page   name of the page to index
12649b41be24STom N Harris * @param boolean       $verbose    print status messages
1265d041f8dbSMichael Hamann * @param boolean       $force  force reindexing even when the index is up to date
126600803e56STom N Harris * @return boolean              the function completed successfully
126700803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
126800803e56STom N Harris */
1269d041f8dbSMichael Hamannfunction idx_addPage($page, $verbose=false, $force=false) {
12709b41be24STom N Harris    $idxtag = metaFN($page,'.indexed');
1271a23ac4d7SMichael Hamann    // check if page was deleted but is still in the index
1272bbc85ee4STom N Harris    if (!page_exists($page)) {
1273bbc85ee4STom N Harris        if (!@file_exists($idxtag)) {
1274bbc85ee4STom N Harris            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
1275bbc85ee4STom N Harris            return false;
1276bbc85ee4STom N Harris        }
1277bbc85ee4STom N Harris        $Indexer = idx_get_indexer();
1278bbc85ee4STom N Harris        $result = $Indexer->deletePage($page);
1279bbc85ee4STom N Harris        if ($result === "locked") {
1280bbc85ee4STom N Harris            if ($verbose) print("Indexer: locked".DOKU_LF);
1281bbc85ee4STom N Harris            return false;
1282bbc85ee4STom N Harris        }
1283bbc85ee4STom N Harris        @unlink($idxtag);
1284bbc85ee4STom N Harris        return $result;
1285bbc85ee4STom N Harris    }
1286a23ac4d7SMichael Hamann
1287a23ac4d7SMichael Hamann    // check if indexing needed
1288a23ac4d7SMichael Hamann    if(!$force && @file_exists($idxtag)){
1289a23ac4d7SMichael Hamann        if(trim(io_readFile($idxtag)) == idx_get_version()){
1290a23ac4d7SMichael Hamann            $last = @filemtime($idxtag);
1291a23ac4d7SMichael Hamann            if($last > @filemtime(wikiFN($page))){
1292a23ac4d7SMichael Hamann                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
1293a23ac4d7SMichael Hamann                return false;
1294a23ac4d7SMichael Hamann            }
1295a23ac4d7SMichael Hamann        }
1296a23ac4d7SMichael Hamann    }
1297a23ac4d7SMichael Hamann
129865aa8490SMichael Hamann    $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED);
1299bbc85ee4STom N Harris    if ($indexenabled === false) {
1300bbc85ee4STom N Harris        $result = false;
1301bbc85ee4STom N Harris        if (@file_exists($idxtag)) {
1302bbc85ee4STom N Harris            $Indexer = idx_get_indexer();
1303bbc85ee4STom N Harris            $result = $Indexer->deletePage($page);
1304bbc85ee4STom N Harris            if ($result === "locked") {
1305bbc85ee4STom N Harris                if ($verbose) print("Indexer: locked".DOKU_LF);
1306bbc85ee4STom N Harris                return false;
1307bbc85ee4STom N Harris            }
1308bbc85ee4STom N Harris            @unlink($idxtag);
1309bbc85ee4STom N Harris        }
1310bbc85ee4STom N Harris        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
1311bbc85ee4STom N Harris        return $result;
1312bbc85ee4STom N Harris    }
1313bbc85ee4STom N Harris
131403aafe1cSMichael Hamann    $Indexer = idx_get_indexer();
131503aafe1cSMichael Hamann    $pid = $Indexer->getPID($page);
131603aafe1cSMichael Hamann    if ($pid === false) {
131703aafe1cSMichael Hamann        if ($verbose) print("Indexer: getting the PID failed for $page".DOKU_LF);
131803aafe1cSMichael Hamann        return false;
131903aafe1cSMichael Hamann    }
132000803e56STom N Harris    $body = '';
132139d6fd30SMichael Hamann    $metadata = array();
132265aa8490SMichael Hamann    $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED);
132365aa8490SMichael Hamann    if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null)
132439d6fd30SMichael Hamann        $metadata['relation_references'] = array_keys($references);
1325a424180eSMichael Hamann    else
1326a424180eSMichael Hamann        $metadata['relation_references'] = array();
132703aafe1cSMichael Hamann    $data = compact('page', 'body', 'metadata', 'pid');
132800803e56STom N Harris    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
132939d6fd30SMichael Hamann    if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page);
133000803e56STom N Harris    $evt->advise_after();
133100803e56STom N Harris    unset($evt);
133239d6fd30SMichael Hamann    extract($data);
133300803e56STom N Harris
13349b41be24STom N Harris    $result = $Indexer->addPageWords($page, $body);
1335e1e1a7e0SMichael Hamann    if ($result === "locked") {
13369b41be24STom N Harris        if ($verbose) print("Indexer: locked".DOKU_LF);
13379b41be24STom N Harris        return false;
13389b41be24STom N Harris    }
1339320f489aSMichael Hamann
1340320f489aSMichael Hamann    if ($result) {
134139d6fd30SMichael Hamann        $result = $Indexer->addMetaKeys($page, $metadata);
1342320f489aSMichael Hamann        if ($result === "locked") {
1343320f489aSMichael Hamann            if ($verbose) print("Indexer: locked".DOKU_LF);
1344320f489aSMichael Hamann            return false;
1345320f489aSMichael Hamann        }
1346320f489aSMichael Hamann    }
1347320f489aSMichael Hamann
13489b41be24STom N Harris    if ($result)
13499b41be24STom N Harris        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
13509b41be24STom N Harris    if ($verbose) {
13519b41be24STom N Harris        print("Indexer: finished".DOKU_LF);
13529b41be24STom N Harris        return true;
13539b41be24STom N Harris    }
13549b41be24STom N Harris    return $result;
135500803e56STom N Harris}
135600803e56STom N Harris
135700803e56STom N Harris/**
135800803e56STom N Harris * Find tokens in the fulltext index
135900803e56STom N Harris *
136000803e56STom N Harris * Takes an array of words and will return a list of matching
136100803e56STom N Harris * pages for each one.
1362488dd6ceSAndreas Gohr *
136363773904SAndreas Gohr * Important: No ACL checking is done here! All results are
136463773904SAndreas Gohr *            returned, regardless of permissions
136563773904SAndreas Gohr *
1366e3ab6fc5SMichael Hamann * @param array      $words  list of words to search for
136700803e56STom N Harris * @return array             list of pages found, associated with the search terms
1368488dd6ceSAndreas Gohr */
13699b41be24STom N Harrisfunction idx_lookup(&$words) {
13709b41be24STom N Harris    $Indexer = idx_get_indexer();
137100803e56STom N Harris    return $Indexer->lookup($words);
1372488dd6ceSAndreas Gohr}
1373488dd6ceSAndreas Gohr
1374488dd6ceSAndreas Gohr/**
137500803e56STom N Harris * Split a string into tokens
1376488dd6ceSAndreas Gohr *
1377488dd6ceSAndreas Gohr */
137800803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) {
13799b41be24STom N Harris    $Indexer = idx_get_indexer();
138000803e56STom N Harris    return $Indexer->tokenizer($string, $wc);
1381488dd6ceSAndreas Gohr}
138200803e56STom N Harris
138300803e56STom N Harris/* For compatibility */
1384488dd6ceSAndreas Gohr
1385f5eb7cf0SAndreas Gohr/**
138600803e56STom N Harris * Read the list of words in an index (if it exists).
1387f5eb7cf0SAndreas Gohr *
13884e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
1389f5eb7cf0SAndreas Gohr */
139000803e56STom N Harrisfunction idx_getIndex($idx, $suffix) {
13911c07b9e6STom N Harris    global $conf;
139200803e56STom N Harris    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
139300803e56STom N Harris    if (!@file_exists($fn)) return array();
139400803e56STom N Harris    return file($fn);
139500803e56STom N Harris}
1396f5eb7cf0SAndreas Gohr
139700803e56STom N Harris/**
139800803e56STom N Harris * Get the list of lengths indexed in the wiki.
139900803e56STom N Harris *
140000803e56STom N Harris * Read the index directory or a cache file and returns
140100803e56STom N Harris * a sorted array of lengths of the words used in the wiki.
140200803e56STom N Harris *
140300803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
140400803e56STom N Harris */
140500803e56STom N Harrisfunction idx_listIndexLengths() {
140600803e56STom N Harris    global $conf;
140700803e56STom N Harris    // testing what we have to do, create a cache file or not.
140800803e56STom N Harris    if ($conf['readdircache'] == 0) {
140900803e56STom N Harris        $docache = false;
14101c07b9e6STom N Harris    } else {
141100803e56STom N Harris        clearstatcache();
141200803e56STom N Harris        if (@file_exists($conf['indexdir'].'/lengths.idx')
141300803e56STom N Harris        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
141400803e56STom N Harris            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
141500803e56STom N Harris                $idx = array();
141600803e56STom N Harris                foreach ($lengths as $length) {
141700803e56STom N Harris                    $idx[] = (int)$length;
141800803e56STom N Harris                }
141900803e56STom N Harris                return $idx;
1420f5eb7cf0SAndreas Gohr            }
14211c07b9e6STom N Harris        }
142200803e56STom N Harris        $docache = true;
142300803e56STom N Harris    }
14244e1bf408STom N Harris
142500803e56STom N Harris    if ($conf['readdircache'] == 0 || $docache) {
142600803e56STom N Harris        $dir = @opendir($conf['indexdir']);
142700803e56STom N Harris        if ($dir === false)
142800803e56STom N Harris            return array();
142926f7dbf5SMichael Hamann        $idx = array();
143000803e56STom N Harris        while (($f = readdir($dir)) !== false) {
143100803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
143200803e56STom N Harris                $i = substr($f, 1, -4);
143300803e56STom N Harris                if (is_numeric($i))
143400803e56STom N Harris                    $idx[] = (int)$i;
143500803e56STom N Harris            }
143600803e56STom N Harris        }
143700803e56STom N Harris        closedir($dir);
143800803e56STom N Harris        sort($idx);
143900803e56STom N Harris        // save this in a file
144000803e56STom N Harris        if ($docache) {
144100803e56STom N Harris            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
144200803e56STom N Harris            @fwrite($handle, implode("\n", $idx));
144300803e56STom N Harris            @fclose($handle);
144400803e56STom N Harris        }
144500803e56STom N Harris        return $idx;
144600803e56STom N Harris    }
144700803e56STom N Harris
144800803e56STom N Harris    return array();
144900803e56STom N Harris}
145000803e56STom N Harris
145100803e56STom N Harris/**
145200803e56STom N Harris * Get the word lengths that have been indexed.
145300803e56STom N Harris *
145400803e56STom N Harris * Reads the index directory and returns an array of lengths
145500803e56STom N Harris * that there are indices for.
145600803e56STom N Harris *
145700803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
145800803e56STom N Harris */
145900803e56STom N Harrisfunction idx_indexLengths($filter) {
146000803e56STom N Harris    global $conf;
146100803e56STom N Harris    $idx = array();
146200803e56STom N Harris    if (is_array($filter)) {
146300803e56STom N Harris        // testing if index files exist only
146400803e56STom N Harris        $path = $conf['indexdir']."/i";
146500803e56STom N Harris        foreach ($filter as $key => $value) {
146600803e56STom N Harris            if (@file_exists($path.$key.'.idx'))
146700803e56STom N Harris                $idx[] = $key;
146800803e56STom N Harris        }
1469f5eb7cf0SAndreas Gohr    } else {
147000803e56STom N Harris        $lengths = idx_listIndexLengths();
147100803e56STom N Harris        foreach ($lengths as $key => $length) {
147200803e56STom N Harris            // keep all the values equal or superior
147300803e56STom N Harris            if ((int)$length >= (int)$filter)
147400803e56STom N Harris                $idx[] = $length;
1475f5eb7cf0SAndreas Gohr        }
147600803e56STom N Harris    }
147700803e56STom N Harris    return $idx;
1478f5eb7cf0SAndreas Gohr}
1479f5eb7cf0SAndreas Gohr
148000803e56STom N Harris/**
148100803e56STom N Harris * Clean a name of a key for use as a file name.
148200803e56STom N Harris *
148300803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's
148400803e56STom N Harris * not a letter, number, or underscore.
148500803e56STom N Harris *
148600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
148700803e56STom N Harris */
148800803e56STom N Harrisfunction idx_cleanName($name) {
148900803e56STom N Harris    $name = utf8_romanize(trim((string)$name));
149000803e56STom N Harris    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
149100803e56STom N Harris    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
149200803e56STom N Harris    return strtolower($name);
1493f5eb7cf0SAndreas Gohr}
1494f5eb7cf0SAndreas Gohr
149500803e56STom N Harris//Setup VIM: ex: et ts=4 :
1496