xref: /dokuwiki/inc/indexer.php (revision 175193d28ead34dd3a45395407813c080f1b2f25)
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
1300803e56STom N Harrisdefine('INDEXER_VERSION', 3);
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
3093a60ad2SAndreas Gohr                   ']');
31d5b23302STom N Harrisdefine('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
32d5b23302STom N Harris                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
33d5b23302STom N Harris                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
34d5b23302STom N Harris                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
35d5b23302STom N Harris                   '\x{308F}-\x{3094}'.
36d5b23302STom N Harris                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
37d5b23302STom N Harris                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
38d5b23302STom N Harris                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
39d5b23302STom N Harris                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
40d5b23302STom N Harris                   ']['.
41d5b23302STom N Harris                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
42d5b23302STom N Harris                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
43d5b23302STom N Harris                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
44d5b23302STom N Harris                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
45d5b23302STom N Harris                   '\x{31F0}-\x{31FF}'.
46d5b23302STom N Harris                   ']?');
47699b8a0bSAndreas Gohrdefine('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
4893a60ad2SAndreas Gohr
49b4ce25e9SAndreas Gohr/**
507c2ef4e8STom N Harris * Version of the indexer taking into consideration the external tokenizer.
517c2ef4e8STom N Harris * The indexer is only compatible with data written by the same version.
527c2ef4e8STom N Harris *
53d0d6fe1bSTom N Harris * Triggers INDEXER_VERSION_GET
54d0d6fe1bSTom N Harris * Plugins that modify what gets indexed should hook this event and
55d0d6fe1bSTom N Harris * add their version info to the event data like so:
56d0d6fe1bSTom N Harris *     $data[$plugin_name] = $plugin_version;
57d0d6fe1bSTom N Harris *
587c2ef4e8STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
598605afb1SMichael Hamann * @author Michael Hamann <michael@content-space.de>
607c2ef4e8STom N Harris */
617c2ef4e8STom N Harrisfunction idx_get_version(){
62d0d6fe1bSTom N Harris    static $indexer_version = null;
63d0d6fe1bSTom N Harris    if ($indexer_version == null) {
647c2ef4e8STom N Harris        global $conf;
657c2ef4e8STom N Harris        if($conf['external_tokenizer'])
668605afb1SMichael Hamann            $version = INDEXER_VERSION . '+' . trim($conf['tokenizer_cmd']);
677c2ef4e8STom N Harris        else
688605afb1SMichael Hamann            $version = INDEXER_VERSION;
698605afb1SMichael Hamann
70d0d6fe1bSTom N Harris        // DokuWiki version is included for the convenience of plugins
71d0d6fe1bSTom N Harris        $data = array('dokuwiki'=>$version);
728605afb1SMichael Hamann        trigger_event('INDEXER_VERSION_GET', $data, null, false);
73d0d6fe1bSTom N Harris        unset($data['dokuwiki']); // this needs to be first
74d0d6fe1bSTom N Harris        ksort($data);
75d0d6fe1bSTom N Harris        foreach ($data as $plugin=>$vers)
76d0d6fe1bSTom N Harris            $version .= '+'.$plugin.'='.$vers;
77d0d6fe1bSTom N Harris        $indexer_version = $version;
78d0d6fe1bSTom N Harris    }
79d0d6fe1bSTom N Harris    return $indexer_version;
807c2ef4e8STom N Harris}
817c2ef4e8STom N Harris
827c2ef4e8STom N Harris/**
83d5b23302STom N Harris * Measure the length of a string.
84d5b23302STom N Harris * Differs from strlen in handling of asian characters.
85d5b23302STom N Harris *
86d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
87d5b23302STom N Harris */
88d5b23302STom N Harrisfunction wordlen($w){
89d5b23302STom N Harris    $l = strlen($w);
90d5b23302STom N Harris    // If left alone, all chinese "words" will get put into w3.idx
91d5b23302STom N Harris    // So the "length" of a "word" is faked
924b9792c6STom N Harris    if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) {
934b9792c6STom N Harris        foreach($leadbytes[0] as $b)
944b9792c6STom N Harris            $l += ord($b) - 0xE1;
954b9792c6STom N Harris    }
96d5b23302STom N Harris    return $l;
97d5b23302STom N Harris}
98d5b23302STom N Harris
99d5b23302STom N Harris/**
10000803e56STom N Harris * Class that encapsulates operations on the indexer database.
101579b0f7eSTNHarris *
102579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
103579b0f7eSTNHarris */
10400803e56STom N Harrisclass Doku_Indexer {
105579b0f7eSTNHarris
106579b0f7eSTNHarris    /**
10700803e56STom N Harris     * Adds the contents of a page to the fulltext index
108dd35e9c9SAndreas Gohr     *
10900803e56STom N Harris     * The added text replaces previous words for the same page.
11000803e56STom N Harris     * An empty value erases the page.
11100803e56STom N Harris     *
11200803e56STom N Harris     * @param string    $page   a page name
11300803e56STom N Harris     * @param string    $text   the body of the page
11400803e56STom N Harris     * @return boolean          the function completed successfully
11500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
116dd35e9c9SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
117dd35e9c9SAndreas Gohr     */
11800803e56STom N Harris    public function addPageWords($page, $text) {
1199b41be24STom N Harris        if (!$this->_lock())
1209b41be24STom N Harris            return "locked";
12100803e56STom N Harris
12200803e56STom N Harris        // load known documents
12300803e56STom N Harris        $page_idx = $this->_addIndexKey('page', '', $page);
12400803e56STom N Harris        if ($page_idx === false) {
12500803e56STom N Harris            $this->_unlock();
12600803e56STom N Harris            return false;
12700803e56STom N Harris        }
12800803e56STom N Harris
12900803e56STom N Harris        $pagewords = array();
13000803e56STom N Harris        // get word usage in page
13100803e56STom N Harris        $words = $this->_getPageWords($text);
13200803e56STom N Harris        if ($words === false) {
13300803e56STom N Harris            $this->_unlock();
13400803e56STom N Harris            return false;
13500803e56STom N Harris        }
13600803e56STom N Harris
13700803e56STom N Harris        if (!empty($words)) {
13800803e56STom N Harris            foreach (array_keys($words) as $wlen) {
13900803e56STom N Harris                $index = $this->_getIndex('i', $wlen);
14000803e56STom N Harris                foreach ($words[$wlen] as $wid => $freq) {
14100803e56STom N Harris                    $idx = ($wid<count($index)) ? $index[$wid] : '';
14200803e56STom N Harris                    $index[$wid] = $this->_updateTuple($idx, $pid, $freq);
14300803e56STom N Harris                    $pagewords[] = "$wlen*$wid";
14400803e56STom N Harris                }
14500803e56STom N Harris                if (!$this->_saveIndex('i', $wlen, $index)) {
14600803e56STom N Harris                    $this->_unlock();
14700803e56STom N Harris                    return false;
14800803e56STom N Harris                }
14900803e56STom N Harris            }
15000803e56STom N Harris        }
15100803e56STom N Harris
15200803e56STom N Harris        // Remove obsolete index entries
15300803e56STom N Harris        $pageword_idx = $this->_getIndexKey('pageword', '', $pid);
15400803e56STom N Harris        if ($pageword_idx !== '') {
15500803e56STom N Harris            $oldwords = explode(':',$pageword_idx);
15600803e56STom N Harris            $delwords = array_diff($oldwords, $pagewords);
15700803e56STom N Harris            $upwords = array();
15800803e56STom N Harris            foreach ($delwords as $word) {
15900803e56STom N Harris                if ($word != '') {
16000803e56STom N Harris                    list($wlen,$wid) = explode('*', $word);
16100803e56STom N Harris                    $wid = (int)$wid;
16200803e56STom N Harris                    $upwords[$wlen][] = $wid;
16300803e56STom N Harris                }
16400803e56STom N Harris            }
16500803e56STom N Harris            foreach ($upwords as $wlen => $widx) {
16600803e56STom N Harris                $index = $this->_getIndex('i', $wlen);
16700803e56STom N Harris                foreach ($widx as $wid) {
16800803e56STom N Harris                    $index[$wid] = $this->_updateTuple($index[$wid], $pid, 0);
16900803e56STom N Harris                }
17000803e56STom N Harris                $this->_saveIndex('i', $wlen, $index);
17100803e56STom N Harris            }
17200803e56STom N Harris        }
17300803e56STom N Harris        // Save the reverse index
17400803e56STom N Harris        $pageword_idx = join(':', $pagewords);
17500803e56STom N Harris        if (!$this->_saveIndexKey('pageword', '', $pid, $pageword_idx)) {
17600803e56STom N Harris            $this->_unlock();
17700803e56STom N Harris            return false;
17800803e56STom N Harris        }
17900803e56STom N Harris
18000803e56STom N Harris        $this->_unlock();
181dd35e9c9SAndreas Gohr        return true;
182dd35e9c9SAndreas Gohr    }
183dd35e9c9SAndreas Gohr
184dd35e9c9SAndreas Gohr    /**
18500803e56STom N Harris     * Split the words in a page and add them to the index.
18644ca0adfSAndreas Gohr     *
18744ca0adfSAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
18817f42b01SChris Smith     * @author Christopher Smith <chris@jalakai.co.uk>
18900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
190b4ce25e9SAndreas Gohr     */
19100803e56STom N Harris    private function _getPageWords($text) {
19244ca0adfSAndreas Gohr        global $conf;
19344ca0adfSAndreas Gohr
19400803e56STom N Harris        $tokens = $this->tokenizer($text);
19517f42b01SChris Smith        $tokens = array_count_values($tokens);  // count the frequency of each token
19617f42b01SChris Smith
19717f42b01SChris Smith        $words = array();
1984e1bf408STom N Harris        foreach ($tokens as $w=>$c) {
199d5b23302STom N Harris            $l = wordlen($w);
200579b0f7eSTNHarris            if (isset($words[$l])){
2014e1bf408STom N Harris                $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
20217f42b01SChris Smith            }else{
2034e1bf408STom N Harris                $words[$l] = array($w => $c);
20417f42b01SChris Smith            }
20517f42b01SChris Smith        }
20617f42b01SChris Smith
207579b0f7eSTNHarris        // arrive here with $words = array(wordlen => array(word => frequency))
208e5e50383SMichael Hamann        $word_idx_modified = false;
209b4ce25e9SAndreas Gohr        $index = array();   //resulting index
210579b0f7eSTNHarris        foreach (array_keys($words) as $wlen) {
21100803e56STom N Harris            $word_idx = $this->_getIndex('w', $wlen);
212579b0f7eSTNHarris            foreach ($words[$wlen] as $word => $freq) {
21300803e56STom N Harris                $wid = array_search($word, $word_idx);
21400803e56STom N Harris                if ($wid === false) {
215d5b23302STom N Harris                    $wid = count($word_idx);
21600803e56STom N Harris                    $word_idx[] = $word;
217e5e50383SMichael Hamann                    $word_idx_modified = true;
218b4ce25e9SAndreas Gohr                }
219579b0f7eSTNHarris                if (!isset($index[$wlen]))
220579b0f7eSTNHarris                    $index[$wlen] = array();
221579b0f7eSTNHarris                $index[$wlen][$wid] = $freq;
22244ca0adfSAndreas Gohr            }
22300803e56STom N Harris            // save back the word index
22400803e56STom N Harris            if ($word_idx_modified && !$this->_saveIndex('w', $wlen, $word_idx))
22544ca0adfSAndreas Gohr                return false;
22644ca0adfSAndreas Gohr        }
227b4ce25e9SAndreas Gohr
228b4ce25e9SAndreas Gohr        return $index;
229b4ce25e9SAndreas Gohr    }
230b4ce25e9SAndreas Gohr
23144ca0adfSAndreas Gohr    /**
232e1e1a7e0SMichael Hamann     * Add/update keys to/of the metadata index.
23344ca0adfSAndreas Gohr     *
23400803e56STom N Harris     * Adding new keys does not remove other keys for the page.
23500803e56STom N Harris     * An empty value will erase the key.
23600803e56STom N Harris     * The $key parameter can be an array to add multiple keys. $value will
23700803e56STom N Harris     * not be used if $key is an array.
23844ca0adfSAndreas Gohr     *
23900803e56STom N Harris     * @param string    $page   a page name
24000803e56STom N Harris     * @param mixed     $key    a key string or array of key=>value pairs
24100803e56STom N Harris     * @param mixed     $value  the value or list of values
24200803e56STom N Harris     * @return boolean          the function completed successfully
24300803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
244e1e1a7e0SMichael Hamann     * @author Michael Hamann <michael@content-space.de>
24544ca0adfSAndreas Gohr     */
24600803e56STom N Harris    public function addMetaKeys($page, $key, $value=null) {
24700803e56STom N Harris        if (!is_array($key)) {
24800803e56STom N Harris            $key = array($key => $value);
24900803e56STom N Harris        } elseif (!is_null($value)) {
25000803e56STom N Harris            // $key is array, but $value is not null
25100803e56STom N Harris            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
25200803e56STom N Harris        }
25300803e56STom N Harris
254e1e1a7e0SMichael Hamann        if (!$this->_lock())
255e1e1a7e0SMichael Hamann            return "locked";
256b4ce25e9SAndreas Gohr
257488dd6ceSAndreas Gohr        // load known documents
25800803e56STom N Harris        $pid = $this->_addIndexKey('page', '', $page);
25900803e56STom N Harris        if ($pid === false) {
26000803e56STom N Harris            $this->_unlock();
261579b0f7eSTNHarris            return false;
26244ca0adfSAndreas Gohr        }
26300803e56STom N Harris
264c1209673STom N Harris        // Special handling for titles so the index file is simpler
265c1209673STom N Harris        if (array_key_exists('title', $key)) {
266c1209673STom N Harris            $value = $key['title'];
267c1209673STom N Harris            if (is_array($value))
268c1209673STom N Harris                $value = $value[0];
269c1209673STom N Harris            $this->_saveIndexKey('title', '', $pid, $value);
270c1209673STom N Harris            unset($key['title']);
271c1209673STom N Harris        }
272c1209673STom N Harris
27300803e56STom N Harris        foreach ($key as $name => $values) {
27400803e56STom N Harris            $metaname = idx_cleanName($name);
2750604da34STom N Harris            $this->_addIndexKey('metadata', '', $metaname);
27600803e56STom N Harris            $metaidx = $this->_getIndex($metaname, '_i');
27700803e56STom N Harris            $metawords = $this->_getIndex($metaname, '_w');
27800803e56STom N Harris            $addwords = false;
279e1e1a7e0SMichael Hamann
280e1e1a7e0SMichael Hamann            if (!is_array($values)) $values = array($values);
281e1e1a7e0SMichael Hamann
282e1e1a7e0SMichael Hamann            $val_idx = $this->_getIndexKey($metaname, '_p', $pid);
283e1e1a7e0SMichael Hamann            if ($val_idx != '') {
284e1e1a7e0SMichael Hamann                $val_idx = explode(':', $val_idx);
285e1e1a7e0SMichael Hamann                // -1 means remove, 0 keep, 1 add
286e1e1a7e0SMichael Hamann                $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
287e1e1a7e0SMichael Hamann            } else {
288e1e1a7e0SMichael Hamann                $val_idx = array();
289e1e1a7e0SMichael Hamann            }
290e1e1a7e0SMichael Hamann
291e1e1a7e0SMichael Hamann
29200803e56STom N Harris            foreach ($values as $val) {
29300803e56STom N Harris                $val = (string)$val;
29400803e56STom N Harris                if ($val !== "") {
29500803e56STom N Harris                    $id = array_search($val, $metawords);
29600803e56STom N Harris                    if ($id === false) {
29700803e56STom N Harris                        $id = count($metawords);
29800803e56STom N Harris                        $metawords[$id] = $val;
29900803e56STom N Harris                        $addwords = true;
300d5b23302STom N Harris                    }
301e1e1a7e0SMichael Hamann                    // test if value is already in the index
302e1e1a7e0SMichael Hamann                    if (isset($val_idx[$id]) && $val_idx[$id] <= 0)
303e1e1a7e0SMichael Hamann                        $val_idx[$id] = 0;
304e1e1a7e0SMichael Hamann                    else // else add it
305e1e1a7e0SMichael Hamann                        $val_idx[$id] = 1;
30644ca0adfSAndreas Gohr                }
307579b0f7eSTNHarris            }
308e1e1a7e0SMichael Hamann
30900803e56STom N Harris            if ($addwords)
31000803e56STom N Harris                $this->_saveIndex($metaname.'_w', '', $metawords);
311e1e1a7e0SMichael Hamann            $vals_changed = false;
312e1e1a7e0SMichael Hamann            foreach ($val_idx as $id => $action) {
313e1e1a7e0SMichael Hamann                if ($action == -1) {
314e1e1a7e0SMichael Hamann                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 0);
315e1e1a7e0SMichael Hamann                    $vals_changed = true;
316e1e1a7e0SMichael Hamann                    unset($val_idx[$id]);
317e1e1a7e0SMichael Hamann                } elseif ($action == 1) {
318e1e1a7e0SMichael Hamann                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 1);
319e1e1a7e0SMichael Hamann                    $vals_changed = true;
320e1e1a7e0SMichael Hamann                }
321e1e1a7e0SMichael Hamann            }
322e1e1a7e0SMichael Hamann
323e1e1a7e0SMichael Hamann            if ($vals_changed) {
32400803e56STom N Harris                $this->_saveIndex($metaname.'_i', '', $metaidx);
325e1e1a7e0SMichael Hamann                $val_idx = implode(':', array_keys($val_idx));
326e1e1a7e0SMichael Hamann                $this->_saveIndexKey($metaname.'_p', '', $pid, $val_idx);
327b6344591STom N Harris            }
328e1e1a7e0SMichael Hamann
32900803e56STom N Harris            unset($metaidx);
33000803e56STom N Harris            unset($metawords);
331a0c5c349STom N Harris        }
332e1e1a7e0SMichael Hamann
333e1e1a7e0SMichael Hamann        $this->_unlock();
334579b0f7eSTNHarris        return true;
33544ca0adfSAndreas Gohr    }
33644ca0adfSAndreas Gohr
33744ca0adfSAndreas Gohr    /**
33800803e56STom N Harris     * Remove a page from the index
33944ca0adfSAndreas Gohr     *
34000803e56STom N Harris     * Erases entries in all known indexes.
34144ca0adfSAndreas Gohr     *
34200803e56STom N Harris     * @param string    $page   a page name
34300803e56STom N Harris     * @return boolean          the function completed successfully
34400803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
34544ca0adfSAndreas Gohr     */
34600803e56STom N Harris    public function deletePage($page) {
347bbc85ee4STom N Harris        if (!$this->_lock())
348bbc85ee4STom N Harris            return "locked";
349bbc85ee4STom N Harris
350bbc85ee4STom N Harris        // load known documents
351bbc85ee4STom N Harris        $page_idx = $this->_getIndexKey('page', '', $page);
352bbc85ee4STom N Harris        if ($page_idx === false) {
353bbc85ee4STom N Harris            $this->_unlock();
354bbc85ee4STom N Harris            return false;
355bbc85ee4STom N Harris        }
356bbc85ee4STom N Harris
357bbc85ee4STom N Harris        // Remove obsolete index entries
358bbc85ee4STom N Harris        $pageword_idx = $this->_getIndexKey('pageword', '', $pid);
359bbc85ee4STom N Harris        if ($pageword_idx !== '') {
360bbc85ee4STom N Harris            $delwords = explode(':',$pageword_idx);
361bbc85ee4STom N Harris            $upwords = array();
362bbc85ee4STom N Harris            foreach ($delwords as $word) {
363bbc85ee4STom N Harris                if ($word != '') {
364bbc85ee4STom N Harris                    list($wlen,$wid) = explode('*', $word);
365bbc85ee4STom N Harris                    $wid = (int)$wid;
366bbc85ee4STom N Harris                    $upwords[$wlen][] = $wid;
367bbc85ee4STom N Harris                }
368bbc85ee4STom N Harris            }
369bbc85ee4STom N Harris            foreach ($upwords as $wlen => $widx) {
370bbc85ee4STom N Harris                $index = $this->_getIndex('i', $wlen);
371bbc85ee4STom N Harris                foreach ($widx as $wid) {
372bbc85ee4STom N Harris                    $index[$wid] = $this->_updateTuple($index[$wid], $pid, 0);
373bbc85ee4STom N Harris                }
374bbc85ee4STom N Harris                $this->_saveIndex('i', $wlen, $index);
375bbc85ee4STom N Harris            }
376bbc85ee4STom N Harris        }
377bbc85ee4STom N Harris        // Save the reverse index
378bbc85ee4STom N Harris        if (!$this->_saveIndexKey('pageword', '', $pid, "")) {
379bbc85ee4STom N Harris            $this->_unlock();
380bbc85ee4STom N Harris            return false;
381bbc85ee4STom N Harris        }
382bbc85ee4STom N Harris
383c1209673STom N Harris        $this->_saveIndexKey('title', '', $pid, "");
3840604da34STom N Harris        $keyidx = $this->_getIndex('metadata', '');
3850604da34STom N Harris        foreach ($keyidx as $metaname) {
3860604da34STom N Harris            $val_idx = explode(':', $this->_getIndexKey($metaname.'_p', '', $pid));
3870604da34STom N Harris            $meta_idx = $this->_getIndex($metaname.'_i', '');
3880604da34STom N Harris            foreach ($val_idx as $id) {
3890604da34STom N Harris                $meta_idx[$id] = $this->_updateTuple($meta_idx[$id], $pid, 0);
3900604da34STom N Harris            }
3910604da34STom N Harris            $this->_saveIndex($metaname.'_i', '', $meta_idx);
3920604da34STom N Harris            $this->_saveIndexKey($metaname.'_p', '', $pid, '');
3930604da34STom N Harris        }
394bbc85ee4STom N Harris
395bbc85ee4STom N Harris        $this->_unlock();
396bbc85ee4STom N Harris        return true;
397d5b23302STom N Harris    }
39844ca0adfSAndreas Gohr
399d5b23302STom N Harris    /**
40000803e56STom N Harris     * Split the text into words for fulltext search
401d5b23302STom N Harris     *
40200803e56STom N Harris     * TODO: does this also need &$stopwords ?
403d5b23302STom N Harris     *
40400803e56STom N Harris     * @param string    $text   plain text
40500803e56STom N Harris     * @param boolean   $wc     are wildcards allowed?
40600803e56STom N Harris     * @return array            list of words in the text
407d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
408d5b23302STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
409d5b23302STom N Harris     */
41000803e56STom N Harris    public function tokenizer($text, $wc=false) {
41122952965SYoBoY        global $conf;
41200803e56STom N Harris        $words = array();
41300803e56STom N Harris        $wc = ($wc) ? '' : '\*';
41400803e56STom N Harris        $stopwords =& idx_get_stopwords();
41500803e56STom N Harris
41600803e56STom N Harris        if ($conf['external_tokenizer'] && $conf['tokenizer_cmd'] != '') {
41700803e56STom N Harris            if (0 == io_exec($conf['tokenizer_cmd'], $text, $output))
41800803e56STom N Harris                $text = $output;
41922952965SYoBoY        } else {
42000803e56STom N Harris            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
42100803e56STom N Harris                // handle asian chars as single words (may fail on older PHP version)
42200803e56STom N Harris                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
42300803e56STom N Harris                if (!is_null($asia)) $text = $asia; // recover from regexp falure
42422952965SYoBoY            }
42522952965SYoBoY        }
42600803e56STom N Harris        $text = strtr($text, "\r\n\t", '   ');
42700803e56STom N Harris        if (preg_match('/[^0-9A-Za-z ]/u', $text))
42800803e56STom N Harris            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
42922952965SYoBoY
43000803e56STom N Harris        $wordlist = explode(' ', $text);
43100803e56STom N Harris        foreach ($wordlist as $word) {
43200803e56STom N Harris            $word = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
43300803e56STom N Harris                utf8_strtolower($word) : strtolower($word);
43400803e56STom N Harris            if (!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) continue;
43500803e56STom N Harris            if (array_search($word, $stopwords) !== false) continue;
43600803e56STom N Harris            $words[] = $word;
43722952965SYoBoY        }
43800803e56STom N Harris        return $words;
43922952965SYoBoY    }
44022952965SYoBoY
44122952965SYoBoY    /**
44200803e56STom N Harris     * Find pages in the fulltext index containing the words,
443579b0f7eSTNHarris     *
44400803e56STom N Harris     * The search words must be pre-tokenized, meaning only letters and
44500803e56STom N Harris     * numbers with an optional wildcard
446579b0f7eSTNHarris     *
44700803e56STom N Harris     * The returned array will have the original tokens as key. The values
44800803e56STom N Harris     * in the returned list is an array with the page names as keys and the
449b00bd361STom N Harris     * number of times that token appears on the page as value.
45000803e56STom N Harris     *
4519b41be24STom N Harris     * @param arrayref  $tokens list of words to search for
45200803e56STom N Harris     * @return array            list of page names with usage counts
45300803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
45400803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
455579b0f7eSTNHarris     */
4569b41be24STom N Harris    public function lookup(&$tokens) {
45700803e56STom N Harris        $result = array();
45800803e56STom N Harris        $wids = $this->_getIndexWords($tokens, $result);
45900803e56STom N Harris        if (empty($wids)) return array();
46000803e56STom N Harris        // load known words and documents
46100803e56STom N Harris        $page_idx = $this->_getIndex('page', '');
46200803e56STom N Harris        $docs = array();
46300803e56STom N Harris        foreach (array_keys($wids) as $wlen) {
46400803e56STom N Harris            $wids[$wlen] = array_unique($wids[$wlen]);
46500803e56STom N Harris            $index = $this->_getIndex('i', $wlen);
46600803e56STom N Harris            foreach($wids[$wlen] as $ixid) {
46700803e56STom N Harris                if ($ixid < count($index))
46800803e56STom N Harris                    $docs["$wlen*$ixid"] = $this->_parseTuples($page_idx, $index[$ixid]);
469d5b23302STom N Harris            }
470d5b23302STom N Harris        }
47100803e56STom N Harris        // merge found pages into final result array
47200803e56STom N Harris        $final = array();
47300803e56STom N Harris        foreach ($result as $word => $res) {
47400803e56STom N Harris            $final[$word] = array();
47500803e56STom N Harris            foreach ($res as $wid) {
47600803e56STom N Harris                $hits = &$docs[$wid];
47700803e56STom N Harris                foreach ($hits as $hitkey => $hitcnt) {
47800803e56STom N Harris                    // make sure the document still exists
47900803e56STom N Harris                    if (!page_exists($hitkey, '', false)) continue;
48000803e56STom N Harris                    if (!isset($final[$word][$hitkey]))
48100803e56STom N Harris                        $final[$word][$hitkey] = $hitcnt;
48200803e56STom N Harris                    else
48300803e56STom N Harris                        $final[$word][$hitkey] += $hitcnt;
484d5b23302STom N Harris                }
485579b0f7eSTNHarris            }
486579b0f7eSTNHarris        }
48700803e56STom N Harris        return $final;
488579b0f7eSTNHarris    }
489579b0f7eSTNHarris
490579b0f7eSTNHarris    /**
49100803e56STom N Harris     * Find pages containing a metadata key.
492d5b23302STom N Harris     *
49300803e56STom N Harris     * The metadata values are compared as case-sensitive strings. Pass a
49400803e56STom N Harris     * callback function that returns true or false to use a different
495b00bd361STom N Harris     * comparison function. The function will be called with the $value being
496b00bd361STom N Harris     * searched for as the first argument, and the word in the index as the
497b00bd361STom N Harris     * second argument.
498d5b23302STom N Harris     *
49900803e56STom N Harris     * @param string    $key    name of the metadata key to look for
50000803e56STom N Harris     * @param string    $value  search term to look for
50100803e56STom N Harris     * @param callback  $func   comparison function
502b00bd361STom N Harris     * @return array            lists with page names, keys are query values if $value is array
50300803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
504cd763a5bSMichael Hamann     * @author Michael Hamann <michael@content-space.de>
50500803e56STom N Harris     */
506b00bd361STom N Harris    public function lookupKey($key, &$value, $func=null) {
507f078bb00STom N Harris        if (!is_array($value))
508f078bb00STom N Harris            $value_array = array($value);
509f078bb00STom N Harris        else
510f078bb00STom N Harris            $value_array =& $value;
511cd763a5bSMichael Hamann
512c1209673STom N Harris        // the matching ids for the provided value(s)
513c1209673STom N Harris        $value_ids = array();
514c1209673STom N Harris
515c1209673STom N Harris        $metaname = idx_cleanName($key);
516c1209673STom N Harris
517c1209673STom N Harris        // get all words in order to search the matching ids
518c1209673STom N Harris        if ($key == 'title') {
519c1209673STom N Harris            $words = $this->_getIndex('title', '');
520c1209673STom N Harris        } else {
521c1209673STom N Harris            $words = $this->_getIndex($metaname, '_w');
522c1209673STom N Harris        }
523c1209673STom N Harris
524f078bb00STom N Harris        if (!is_null($func)) {
525b00bd361STom N Harris            foreach ($value_array as &$val) {
526f078bb00STom N Harris                foreach ($words as $i => $word) {
527b00bd361STom N Harris                    if (call_user_func_array($func, array(&$val, $word)))
528c1209673STom N Harris                        $value_ids[$i][] = $val;
529f078bb00STom N Harris                }
530f078bb00STom N Harris            }
531f078bb00STom N Harris        } else {
532f078bb00STom N Harris            foreach ($value_array as $val) {
533f078bb00STom N Harris                $xval = $val;
534f078bb00STom N Harris                $caret = false;
535f078bb00STom N Harris                $dollar = false;
536f078bb00STom N Harris                // check for wildcards
537f078bb00STom N Harris                if (substr($xval, 0, 1) == '*') {
538f078bb00STom N Harris                    $xval = substr($xval, 1);
539f078bb00STom N Harris                    $caret = '^';
540f078bb00STom N Harris                }
541f078bb00STom N Harris                if (substr($xval, -1, 1) == '*') {
542f078bb00STom N Harris                    $xval = substr($xval, 0, -1);
543f078bb00STom N Harris                    $dollar = '$';
544f078bb00STom N Harris                }
545f078bb00STom N Harris                if ($caret || $dollar) {
546f078bb00STom N Harris                    $re = $caret.preg_quote($xval, '/').$dollar;
547f078bb00STom N Harris                    foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
548c1209673STom N Harris                        $value_ids[$i][] = $val;
549cd763a5bSMichael Hamann                } else {
550f078bb00STom N Harris                    if (($i = array_search($val, $words)) !== false)
551c1209673STom N Harris                        $value_ids[$i][] = $val;
552cd763a5bSMichael Hamann                }
553cd763a5bSMichael Hamann            }
554cd763a5bSMichael Hamann        }
555cd763a5bSMichael Hamann
556cd763a5bSMichael Hamann        unset($words); // free the used memory
557cd763a5bSMichael Hamann
558c1209673STom N Harris        $result = array();
559cd763a5bSMichael Hamann        $page_idx = $this->_getIndex('page', '');
560cd763a5bSMichael Hamann
561c1209673STom N Harris        // Special handling for titles
562c1209673STom N Harris        if ($key == 'title') {
563c1209673STom N Harris            foreach ($value_ids as $pid => $val_list) {
564c1209673STom N Harris                $page = $page_idx[$pid];
565c1209673STom N Harris                foreach ($val_list as $val) {
566c1209673STom N Harris                    $result[$val][] = $page;
567c1209673STom N Harris                }
568c1209673STom N Harris            }
569c1209673STom N Harris        } else {
570c1209673STom N Harris            // load all lines and pages so the used lines can be taken and matched with the pages
571c1209673STom N Harris            $lines = $this->_getIndex($metaname, '_i');
572c1209673STom N Harris
573c1209673STom N Harris            foreach ($value_ids as $value_id => $val_list) {
574cd763a5bSMichael Hamann                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
575cd763a5bSMichael Hamann                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
576c1209673STom N Harris                $pages = array_keys($this->_parseTuples($page_idx, $lines[$value_id]));
577c1209673STom N Harris                foreach ($val_list as $val) {
578c1209673STom N Harris                    if (!isset($result[$val]))
579c1209673STom N Harris                        $result[$val] = $pages;
580c1209673STom N Harris                    else
581c1209673STom N Harris                        $result[$val] = array_merge($result[$val], $pages);
582c1209673STom N Harris                }
583c1209673STom N Harris            }
584cd763a5bSMichael Hamann        }
585f078bb00STom N Harris        if (!is_array($value)) $result = $result[$value];
586cd763a5bSMichael Hamann        return $result;
58700803e56STom N Harris    }
58800803e56STom N Harris
58900803e56STom N Harris    /**
59000803e56STom N Harris     * Find the index ID of each search term.
59100803e56STom N Harris     *
59200803e56STom N Harris     * The query terms should only contain valid characters, with a '*' at
59300803e56STom N Harris     * either the beginning or end of the word (or both).
59400803e56STom N Harris     * The $result parameter can be used to merge the index locations with
59500803e56STom N Harris     * the appropriate query term.
59600803e56STom N Harris     *
5979b41be24STom N Harris     * @param arrayref  $words  The query terms.
59800803e56STom N Harris     * @param arrayref  $result Set to word => array("length*id" ...)
599d5b23302STom N Harris     * @return array            Set to length => array(id ...)
600d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
601d5b23302STom N Harris     */
6029b41be24STom N Harris    private function _getIndexWords(&$words, &$result) {
603d5b23302STom N Harris        $tokens = array();
604d5b23302STom N Harris        $tokenlength = array();
605d5b23302STom N Harris        $tokenwild = array();
606d5b23302STom N Harris        foreach ($words as $word) {
607d5b23302STom N Harris            $result[$word] = array();
60800803e56STom N Harris            $caret = false;
60900803e56STom N Harris            $dollar = false;
610d5b23302STom N Harris            $xword = $word;
611d5b23302STom N Harris            $wlen = wordlen($word);
612d5b23302STom N Harris
613d5b23302STom N Harris            // check for wildcards
614d5b23302STom N Harris            if (substr($xword, 0, 1) == '*') {
615d5b23302STom N Harris                $xword = substr($xword, 1);
616f078bb00STom N Harris                $caret = '^';
617d5b23302STom N Harris                $wlen -= 1;
618d5b23302STom N Harris            }
619d5b23302STom N Harris            if (substr($xword, -1, 1) == '*') {
620d5b23302STom N Harris                $xword = substr($xword, 0, -1);
621f078bb00STom N Harris                $dollar = '$';
622d5b23302STom N Harris                $wlen -= 1;
623d5b23302STom N Harris            }
62400803e56STom N Harris            if ($wlen < IDX_MINWORDLENGTH && !$caret && !$dollar && !is_numeric($xword))
62500803e56STom N Harris                continue;
62600803e56STom N Harris            if (!isset($tokens[$xword]))
627d5b23302STom N Harris                $tokenlength[$wlen][] = $xword;
62800803e56STom N Harris            if ($caret || $dollar) {
629f078bb00STom N Harris                $re = $caret.preg_quote($xword, '/').$dollar;
63000803e56STom N Harris                $tokens[$xword][] = array($word, '/'.$re.'/');
63100803e56STom N Harris                if (!isset($tokenwild[$xword]))
63200803e56STom N Harris                    $tokenwild[$xword] = $wlen;
63300803e56STom N Harris            } else {
634d5b23302STom N Harris                $tokens[$xword][] = array($word, null);
635d5b23302STom N Harris            }
63600803e56STom N Harris        }
637d5b23302STom N Harris        asort($tokenwild);
63800803e56STom N Harris        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
639d5b23302STom N Harris        // $tokenlength = array( base word length => base word ... )
640d5b23302STom N Harris        // $tokenwild = array( base word => base word length ... )
641d5b23302STom N Harris        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
64200803e56STom N Harris        $indexes_known = $this->_indexLengths($length_filter);
643d5b23302STom N Harris        if (!empty($tokenwild)) sort($indexes_known);
644d5b23302STom N Harris        // get word IDs
645d5b23302STom N Harris        $wids = array();
646d5b23302STom N Harris        foreach ($indexes_known as $ixlen) {
64700803e56STom N Harris            $word_idx = $this->_getIndex('w', $ixlen);
648d5b23302STom N Harris            // handle exact search
649d5b23302STom N Harris            if (isset($tokenlength[$ixlen])) {
650d5b23302STom N Harris                foreach ($tokenlength[$ixlen] as $xword) {
65100803e56STom N Harris                    $wid = array_search($xword, $word_idx);
65200803e56STom N Harris                    if ($wid !== false) {
653d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
654d5b23302STom N Harris                        foreach ($tokens[$xword] as $w)
655d5b23302STom N Harris                            $result[$w[0]][] = "$ixlen*$wid";
656d5b23302STom N Harris                    }
657d5b23302STom N Harris                }
658d5b23302STom N Harris            }
659d5b23302STom N Harris            // handle wildcard search
660d5b23302STom N Harris            foreach ($tokenwild as $xword => $wlen) {
661d5b23302STom N Harris                if ($wlen >= $ixlen) break;
662d5b23302STom N Harris                foreach ($tokens[$xword] as $w) {
663d5b23302STom N Harris                    if (is_null($w[1])) continue;
664d5b23302STom N Harris                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
665d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
666d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
667d5b23302STom N Harris                    }
668d5b23302STom N Harris                }
669d5b23302STom N Harris            }
670d5b23302STom N Harris        }
671d5b23302STom N Harris        return $wids;
672d5b23302STom N Harris    }
673d5b23302STom N Harris
674d5b23302STom N Harris    /**
67500803e56STom N Harris     * Return a list of all pages
676c1209673STom N Harris     * Warning: pages may not exist!
677488dd6ceSAndreas Gohr     *
67800803e56STom N Harris     * @param string    $key    list only pages containing the metadata key (optional)
67900803e56STom N Harris     * @return array            list of page names
68000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
68100803e56STom N Harris     */
68200803e56STom N Harris    public function getPages($key=null) {
68300803e56STom N Harris        $page_idx = $this->_getIndex('page', '');
68400803e56STom N Harris        if (is_null($key)) return $page_idx;
685c1209673STom N Harris
686c1209673STom N Harris        $metaname = idx_cleanName($key);
687c1209673STom N Harris
688c1209673STom N Harris        // Special handling for titles
689c1209673STom N Harris        if ($key == 'title') {
690c1209673STom N Harris            $title_idx = $this->_getIndex('title', '');
691c1209673STom N Harris            array_splice($page_idx, count($title_idx));
692c1209673STom N Harris            foreach ($title_idx as $i => $title)
693c1209673STom N Harris                if ($title === "") unset($page_idx[$i]);
694c1209673STom N Harris            return $page_idx;
695c1209673STom N Harris        }
696c1209673STom N Harris
697c1209673STom N Harris        $pages = array();
698c1209673STom N Harris        $lines = $this->_getIndex($metaname, '_i');
699c1209673STom N Harris        foreach ($lines as $line) {
700c1209673STom N Harris            $pages = array_merge($pages, $this->_parseTuples($page_idx, $line));
701c1209673STom N Harris        }
702c1209673STom N Harris        return array_keys($pages);
70300803e56STom N Harris    }
70400803e56STom N Harris
70500803e56STom N Harris    /**
70600803e56STom N Harris     * Return a list of words sorted by number of times used
70700803e56STom N Harris     *
70800803e56STom N Harris     * @param int       $min    bottom frequency threshold
70900803e56STom N Harris     * @param int       $max    upper frequency limit. No limit if $max<$min
71000803e56STom N Harris     * @param string    $key    metadata key to list. Uses the fulltext index if not given
71100803e56STom N Harris     * @return array            list of words as the keys and frequency as values
71200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
71300803e56STom N Harris     */
71400803e56STom N Harris    public function histogram($min=1, $max=0, $key=null) {
715*175193d2STom N Harris        if ($min < 1)
716*175193d2STom N Harris            $min = 1;
717*175193d2STom N Harris        if ($max < $min)
718*175193d2STom N Harris            $max = 0;
719*175193d2STom N Harris
720*175193d2STom N Harris        $result = array();
721*175193d2STom N Harris
722*175193d2STom N Harris        if ($key == 'title') {
723*175193d2STom N Harris            $index = $this->_getIndex('title', '');
724*175193d2STom N Harris            $index = array_count_values($index);
725*175193d2STom N Harris            foreach ($index as $val => $cnt) {
726*175193d2STom N Harris                if ($cnt >= $min && (!$max || $cnt <= $max))
727*175193d2STom N Harris                    $result[$val] = $cnt;
728*175193d2STom N Harris            }
729*175193d2STom N Harris        }
730*175193d2STom N Harris        elseif (!is_null($key)) {
731*175193d2STom N Harris            $metaname = idx_cleanName($key);
732*175193d2STom N Harris            $index = $this->_getIndex($metaname.'_i', '');
733*175193d2STom N Harris            $val_idx = array();
734*175193d2STom N Harris            foreach ($index as $wid => $line) {
735*175193d2STom N Harris                $freq = $this->_countTuples($line);
736*175193d2STom N Harris                if ($freq >= $min && (!$max || $freq <= $max))
737*175193d2STom N Harris                    $val_idx[$wid] = $freq;
738*175193d2STom N Harris            }
739*175193d2STom N Harris            if (!empty($val_idx)) {
740*175193d2STom N Harris                $words = $this->_getIndex($metaname.'_w', '');
741*175193d2STom N Harris                foreach ($val_idx as $wid => $freq)
742*175193d2STom N Harris                    $result[$words[$wid]] = $freq;
743*175193d2STom N Harris            }
744*175193d2STom N Harris        }
745*175193d2STom N Harris        else {
746*175193d2STom N Harris            $lengths = idx_listIndexLengths();
747*175193d2STom N Harris            foreach ($lengths as $length) {
748*175193d2STom N Harris                $index = $this->_getIndex('i', $length);
749*175193d2STom N Harris                $words = null;
750*175193d2STom N Harris                foreach ($index as $wid => $line) {
751*175193d2STom N Harris                    $freq = $this->_countTuples($line);
752*175193d2STom N Harris                    if ($freq >= $min && (!$max || $freq <= $max)) {
753*175193d2STom N Harris                        if ($words === null)
754*175193d2STom N Harris                            $words = $this->_getIndex('w', $length);
755*175193d2STom N Harris                        $result[$words[$wid]] = $freq;
756*175193d2STom N Harris                    }
757*175193d2STom N Harris                }
758*175193d2STom N Harris            }
759*175193d2STom N Harris        }
760*175193d2STom N Harris
761*175193d2STom N Harris        arsort($result);
762*175193d2STom N Harris        return $result;
76300803e56STom N Harris    }
76400803e56STom N Harris
76500803e56STom N Harris    /**
76600803e56STom N Harris     * Lock the indexer.
76700803e56STom N Harris     *
76800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
76900803e56STom N Harris     */
77000803e56STom N Harris    private function _lock() {
77100803e56STom N Harris        global $conf;
77200803e56STom N Harris        $status = true;
77300803e56STom N Harris        $lock = $conf['lockdir'].'/_indexer.lock';
77400803e56STom N Harris        while (!@mkdir($lock, $conf['dmode'])) {
77500803e56STom N Harris            usleep(50);
77600803e56STom N Harris            if (time() - @filemtime($lock) > 60*5) {
77700803e56STom N Harris                // looks like a stale lock, remove it
77800803e56STom N Harris                @rmdir($lock);
77900803e56STom N Harris                $status = "stale lock removed";
78000803e56STom N Harris            } else {
78100803e56STom N Harris                return false;
78200803e56STom N Harris            }
78300803e56STom N Harris        }
78400803e56STom N Harris        if ($conf['dperm'])
78500803e56STom N Harris            chmod($lock, $conf['dperm']);
78600803e56STom N Harris        return $status;
78700803e56STom N Harris    }
78800803e56STom N Harris
78900803e56STom N Harris    /**
79000803e56STom N Harris     * Release the indexer lock.
79100803e56STom N Harris     *
79200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
79300803e56STom N Harris     */
79400803e56STom N Harris    private function _unlock() {
79500803e56STom N Harris        global $conf;
79600803e56STom N Harris        @rmdir($conf['lockdir'].'/_indexer.lock');
79700803e56STom N Harris        return true;
79800803e56STom N Harris    }
79900803e56STom N Harris
80000803e56STom N Harris    /**
80100803e56STom N Harris     * Retrieve the entire index.
80200803e56STom N Harris     *
80300803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
80400803e56STom N Harris     */
80500803e56STom N Harris    private function _getIndex($idx, $suffix) {
80600803e56STom N Harris        global $conf;
80700803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
808d64516f5SMichael Hamann        if (!@file_exists($fn)) return array();
809d64516f5SMichael Hamann        return file($fn, FILE_IGNORE_NEW_LINES);
81000803e56STom N Harris    }
81100803e56STom N Harris
81200803e56STom N Harris    /**
81300803e56STom N Harris     * Replace the contents of the index with an array.
81400803e56STom N Harris     *
81500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
81600803e56STom N Harris     */
81700803e56STom N Harris    private function _saveIndex($idx, $suffix, &$lines) {
81800803e56STom N Harris        global $conf;
81900803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
82000803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
82100803e56STom N Harris        if (!$fh) return false;
82200803e56STom N Harris        fwrite($fh, join("\n", $lines));
82300803e56STom N Harris        fclose($fh);
82400803e56STom N Harris        if (isset($conf['fperm']))
82500803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
82600803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
82700803e56STom N Harris        if ($suffix !== '')
82800803e56STom N Harris            $this->_cacheIndexDir($idx, $suffix, empty($lines));
82900803e56STom N Harris        return true;
83000803e56STom N Harris    }
83100803e56STom N Harris
83200803e56STom N Harris    /**
83300803e56STom N Harris     * Retrieve a line from the index.
83400803e56STom N Harris     *
83500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
83600803e56STom N Harris     */
83700803e56STom N Harris    private function _getIndexKey($idx, $suffix, $id) {
83800803e56STom N Harris        global $conf;
83900803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
84000803e56STom N Harris        if (!@file_exists($fn)) return '';
84100803e56STom N Harris        $fh = @fopen($fn, 'r');
84200803e56STom N Harris        if (!$fh) return '';
84300803e56STom N Harris        $ln = -1;
84400803e56STom N Harris        while (($line = fgets($fh)) !== false) {
84500803e56STom N Harris            if (++$ln == $id) break;
84600803e56STom N Harris        }
84700803e56STom N Harris        fclose($fh);
84800803e56STom N Harris        return rtrim((string)$line);
84900803e56STom N Harris    }
85000803e56STom N Harris
85100803e56STom N Harris    /**
85200803e56STom N Harris     * Write a line into the index.
85300803e56STom N Harris     *
85400803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
85500803e56STom N Harris     */
85600803e56STom N Harris    private function _saveIndexKey($idx, $suffix, $id, $line) {
85700803e56STom N Harris        global $conf;
85800803e56STom N Harris        if (substr($line, -1) != "\n")
85900803e56STom N Harris            $line .= "\n";
86000803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
86100803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
86200803e56STom N Harris        if (!fh) return false;
86300803e56STom N Harris        $ih = @fopen($fn.'.idx', 'r');
86400803e56STom N Harris        if ($ih) {
86500803e56STom N Harris            $ln = -1;
86600803e56STom N Harris            while (($curline = fgets($ih)) !== false) {
86700803e56STom N Harris                fwrite($fh, (++$ln == $id) ? $line : $curline);
86800803e56STom N Harris            }
8694373c7b5SMichael Hamann            if ($id > $ln) {
8704373c7b5SMichael Hamann                while ($id > ++$ln)
8714373c7b5SMichael Hamann                    fwrite($fh, "\n");
87200803e56STom N Harris                fwrite($fh, $line);
8734373c7b5SMichael Hamann            }
87400803e56STom N Harris            fclose($ih);
87500803e56STom N Harris        } else {
8764373c7b5SMichael Hamann            $ln = -1;
8774373c7b5SMichael Hamann            while ($id > ++$ln)
8784373c7b5SMichael Hamann                fwrite($fh, "\n");
87900803e56STom N Harris            fwrite($fh, $line);
88000803e56STom N Harris        }
88100803e56STom N Harris        fclose($fh);
88200803e56STom N Harris        if (isset($conf['fperm']))
88300803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
88400803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
88500803e56STom N Harris        if ($suffix !== '')
88600803e56STom N Harris            $this->_cacheIndexDir($idx, $suffix);
88700803e56STom N Harris        return true;
88800803e56STom N Harris    }
88900803e56STom N Harris
89000803e56STom N Harris    /**
89100803e56STom N Harris     * Retrieve or insert a value in the index.
89200803e56STom N Harris     *
89300803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
89400803e56STom N Harris     */
89500803e56STom N Harris    private function _addIndexKey($idx, $suffix, $value) {
89600803e56STom N Harris        $index = $this->_getIndex($idx, $suffix);
89700803e56STom N Harris        $id = array_search($value, $index);
89800803e56STom N Harris        if ($id === false) {
89900803e56STom N Harris            $id = count($index);
90000803e56STom N Harris            $index[$id] = $value;
90100803e56STom N Harris            if (!$this->_saveIndex($idx, $suffix, $index)) {
90200803e56STom N Harris                trigger_error("Failed to write $idx index", E_USER_ERROR);
90300803e56STom N Harris                return false;
90400803e56STom N Harris            }
90500803e56STom N Harris        }
90600803e56STom N Harris        return $id;
90700803e56STom N Harris    }
90800803e56STom N Harris
90900803e56STom N Harris    private function _cacheIndexDir($idx, $suffix, $delete=false) {
91000803e56STom N Harris        global $conf;
91100803e56STom N Harris        if ($idx == 'i')
91200803e56STom N Harris            $cachename = $conf['indexdir'].'/lengths';
91300803e56STom N Harris        else
91400803e56STom N Harris            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
91500803e56STom N Harris        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
91600803e56STom N Harris        if ($lengths === false) $lengths = array();
91700803e56STom N Harris        $old = array_search((string)$suffix, $lengths);
91800803e56STom N Harris        if (empty($lines)) {
91900803e56STom N Harris            if ($old === false) return;
92000803e56STom N Harris            unset($lengths[$old]);
92100803e56STom N Harris        } else {
92200803e56STom N Harris            if ($old !== false) return;
92300803e56STom N Harris            $lengths[] = $suffix;
92400803e56STom N Harris            sort($lengths);
92500803e56STom N Harris        }
92600803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
92700803e56STom N Harris        if (!$fh) {
92800803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
92900803e56STom N Harris            return;
93000803e56STom N Harris        }
93100803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
93200803e56STom N Harris        @fclose($fh);
93300803e56STom N Harris        if (isset($conf['fperm']))
93400803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
93500803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
93600803e56STom N Harris    }
93700803e56STom N Harris
93800803e56STom N Harris    /**
93900803e56STom N Harris     * Get the list of lengths indexed in the wiki.
94000803e56STom N Harris     *
94100803e56STom N Harris     * Read the index directory or a cache file and returns
94200803e56STom N Harris     * a sorted array of lengths of the words used in the wiki.
94300803e56STom N Harris     *
94400803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
94500803e56STom N Harris     */
94600803e56STom N Harris    private function _listIndexLengths() {
94700803e56STom N Harris        global $conf;
94800803e56STom N Harris        $cachename = $conf['indexdir'].'/lengths';
94900803e56STom N Harris        clearstatcache();
95000803e56STom N Harris        if (@file_exists($cachename.'.idx')) {
95100803e56STom N Harris            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
95200803e56STom N Harris            if ($lengths !== false) {
95300803e56STom N Harris                $idx = array();
95400803e56STom N Harris                foreach ($lengths as $length)
95500803e56STom N Harris                    $idx[] = (int)$length;
95600803e56STom N Harris                return $idx;
95700803e56STom N Harris            }
95800803e56STom N Harris        }
95900803e56STom N Harris
96000803e56STom N Harris        $dir = @opendir($conf['indexdir']);
96100803e56STom N Harris        if ($dir === false)
96200803e56STom N Harris            return array();
96300803e56STom N Harris        $lengths[] = array();
96400803e56STom N Harris        while (($f = readdir($dir)) !== false) {
96500803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
96600803e56STom N Harris                $i = substr($f, 1, -4);
96700803e56STom N Harris                if (is_numeric($i))
96800803e56STom N Harris                    $lengths[] = (int)$i;
96900803e56STom N Harris            }
97000803e56STom N Harris        }
97100803e56STom N Harris        closedir($dir);
97200803e56STom N Harris        sort($lengths);
97300803e56STom N Harris        // save this in a file
97400803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
97500803e56STom N Harris        if (!$fh) {
97600803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
97700803e56STom N Harris            return;
97800803e56STom N Harris        }
97900803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
98000803e56STom N Harris        @fclose($fh);
98100803e56STom N Harris        if (isset($conf['fperm']))
98200803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
98300803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
98400803e56STom N Harris
98500803e56STom N Harris        return $lengths;
98600803e56STom N Harris    }
98700803e56STom N Harris
98800803e56STom N Harris    /**
98900803e56STom N Harris     * Get the word lengths that have been indexed.
99000803e56STom N Harris     *
99100803e56STom N Harris     * Reads the index directory and returns an array of lengths
99200803e56STom N Harris     * that there are indices for.
99300803e56STom N Harris     *
99400803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
99500803e56STom N Harris     */
99600803e56STom N Harris    private function _indexLengths($filter) {
99700803e56STom N Harris        global $conf;
99800803e56STom N Harris        $idx = array();
99900803e56STom N Harris        if (is_array($filter)) {
100000803e56STom N Harris            // testing if index files exist only
100100803e56STom N Harris            $path = $conf['indexdir']."/i";
100200803e56STom N Harris            foreach ($filter as $key => $value) {
100300803e56STom N Harris                if (@file_exists($path.$key.'.idx'))
100400803e56STom N Harris                    $idx[] = $key;
100500803e56STom N Harris            }
100600803e56STom N Harris        } else {
100700803e56STom N Harris            $lengths = idx_listIndexLengths();
100800803e56STom N Harris            foreach ($lengths as $key => $length) {
100900803e56STom N Harris                // keep all the values equal or superior
101000803e56STom N Harris                if ((int)$length >= (int)$filter)
101100803e56STom N Harris                    $idx[] = $length;
101200803e56STom N Harris            }
101300803e56STom N Harris        }
101400803e56STom N Harris        return $idx;
101500803e56STom N Harris    }
101600803e56STom N Harris
101700803e56STom N Harris    /**
101800803e56STom N Harris     * Insert or replace a tuple in a line.
101900803e56STom N Harris     *
102000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
102100803e56STom N Harris     */
102200803e56STom N Harris    private function _updateTuple($line, $id, $count) {
102300803e56STom N Harris        $newLine = $line;
102400803e56STom N Harris        if ($newLine !== '')
102500803e56STom N Harris            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
102600803e56STom N Harris        $newLine = trim($newLine, ':');
102700803e56STom N Harris        if ($count) {
1028d64516f5SMichael Hamann            if (strlen($newLine) > 0)
102900803e56STom N Harris                return "$id*$count:".$newLine;
103000803e56STom N Harris            else
103100803e56STom N Harris                return "$id*$count".$newLine;
103200803e56STom N Harris        }
103300803e56STom N Harris        return $newLine;
103400803e56STom N Harris    }
103500803e56STom N Harris
103600803e56STom N Harris    /**
103700803e56STom N Harris     * Split a line into an array of tuples.
103800803e56STom N Harris     *
103900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
104000803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
104100803e56STom N Harris     */
104200803e56STom N Harris    private function _parseTuples(&$keys, $line) {
104300803e56STom N Harris        $result = array();
104400803e56STom N Harris        if ($line == '') return $result;
104500803e56STom N Harris        $parts = explode(':', $line);
104600803e56STom N Harris        foreach ($parts as $tuple) {
104700803e56STom N Harris            if ($tuple == '') continue;
104800803e56STom N Harris            list($key, $cnt) = explode('*', $tuple);
1049d64516f5SMichael Hamann            if (!$cnt) continue;
105000803e56STom N Harris            $key = $keys[$key];
105100803e56STom N Harris            if (!$key) continue;
105200803e56STom N Harris            $result[$key] = $cnt;
105300803e56STom N Harris        }
105400803e56STom N Harris        return $result;
105500803e56STom N Harris    }
1056*175193d2STom N Harris
1057*175193d2STom N Harris    /**
1058*175193d2STom N Harris     * Sum the counts in a list of tuples.
1059*175193d2STom N Harris     *
1060*175193d2STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
1061*175193d2STom N Harris     */
1062*175193d2STom N Harris    private function _countTuples($line) {
1063*175193d2STom N Harris        $freq = 0;
1064*175193d2STom N Harris        $parts = explode(':', $line);
1065*175193d2STom N Harris        foreach ($parts as $tuple) {
1066*175193d2STom N Harris            if ($tuple == '') continue;
1067*175193d2STom N Harris            list($pid, $cnt) = explode('*', $tuple);
1068*175193d2STom N Harris            $freq += (int)$cnt;
1069*175193d2STom N Harris        }
1070*175193d2STom N Harris        return $freq;
1071*175193d2STom N Harris    }
107200803e56STom N Harris}
107300803e56STom N Harris
107400803e56STom N Harris/**
107500803e56STom N Harris * Create an instance of the indexer.
107600803e56STom N Harris *
107700803e56STom N Harris * @return object               a Doku_Indexer
107800803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
107900803e56STom N Harris */
10809b41be24STom N Harrisfunction idx_get_indexer() {
108100803e56STom N Harris    static $Indexer = null;
108200803e56STom N Harris    if (is_null($Indexer)) {
108300803e56STom N Harris        $Indexer = new Doku_Indexer();
108400803e56STom N Harris    }
108500803e56STom N Harris    return $Indexer;
108600803e56STom N Harris}
108700803e56STom N Harris
108800803e56STom N Harris/**
108900803e56STom N Harris * Returns words that will be ignored.
109000803e56STom N Harris *
109100803e56STom N Harris * @return array                list of stop words
109200803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
109300803e56STom N Harris */
109400803e56STom N Harrisfunction & idx_get_stopwords() {
109500803e56STom N Harris    static $stopwords = null;
109600803e56STom N Harris    if (is_null($stopwords)) {
109700803e56STom N Harris        global $conf;
109800803e56STom N Harris        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
109900803e56STom N Harris        if(@file_exists($swfile)){
110000803e56STom N Harris            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
110100803e56STom N Harris        }else{
110200803e56STom N Harris            $stopwords = array();
110300803e56STom N Harris        }
110400803e56STom N Harris    }
110500803e56STom N Harris    return $stopwords;
110600803e56STom N Harris}
110700803e56STom N Harris
110800803e56STom N Harris/**
110900803e56STom N Harris * Adds/updates the search index for the given page
111000803e56STom N Harris *
111100803e56STom N Harris * Locking is handled internally.
111200803e56STom N Harris *
111300803e56STom N Harris * @param string        $page   name of the page to index
11149b41be24STom N Harris * @param boolean       $verbose    print status messages
111500803e56STom N Harris * @return boolean              the function completed successfully
111600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
111700803e56STom N Harris */
11189b41be24STom N Harrisfunction idx_addPage($page, $verbose=false) {
11199b41be24STom N Harris    // check if indexing needed
11209b41be24STom N Harris    $idxtag = metaFN($page,'.indexed');
11219b41be24STom N Harris    if(@file_exists($idxtag)){
11229b41be24STom N Harris        if(trim(io_readFile($idxtag)) == idx_get_version()){
11239b41be24STom N Harris            $last = @filemtime($idxtag);
11249b41be24STom N Harris            if($last > @filemtime(wikiFN($ID))){
11259b41be24STom N Harris                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
11269b41be24STom N Harris                return false;
11279b41be24STom N Harris            }
11289b41be24STom N Harris        }
11299b41be24STom N Harris    }
11309b41be24STom N Harris
1131bbc85ee4STom N Harris    if (!page_exists($page)) {
1132bbc85ee4STom N Harris        if (!@file_exists($idxtag)) {
1133bbc85ee4STom N Harris            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
1134bbc85ee4STom N Harris            return false;
1135bbc85ee4STom N Harris        }
1136bbc85ee4STom N Harris        $Indexer = idx_get_indexer();
1137bbc85ee4STom N Harris        $result = $Indexer->deletePage($page);
1138bbc85ee4STom N Harris        if ($result === "locked") {
1139bbc85ee4STom N Harris            if ($verbose) print("Indexer: locked".DOKU_LF);
1140bbc85ee4STom N Harris            return false;
1141bbc85ee4STom N Harris        }
1142bbc85ee4STom N Harris        @unlink($idxtag);
1143bbc85ee4STom N Harris        return $result;
1144bbc85ee4STom N Harris    }
1145bbc85ee4STom N Harris    $indexenabled = p_get_metadata($page, 'internal index', false);
1146bbc85ee4STom N Harris    if ($indexenabled === false) {
1147bbc85ee4STom N Harris        $result = false;
1148bbc85ee4STom N Harris        if (@file_exists($idxtag)) {
1149bbc85ee4STom N Harris            $Indexer = idx_get_indexer();
1150bbc85ee4STom N Harris            $result = $Indexer->deletePage($page);
1151bbc85ee4STom N Harris            if ($result === "locked") {
1152bbc85ee4STom N Harris                if ($verbose) print("Indexer: locked".DOKU_LF);
1153bbc85ee4STom N Harris                return false;
1154bbc85ee4STom N Harris            }
1155bbc85ee4STom N Harris            @unlink($idxtag);
1156bbc85ee4STom N Harris        }
1157bbc85ee4STom N Harris        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
1158bbc85ee4STom N Harris        return $result;
1159bbc85ee4STom N Harris    }
1160bbc85ee4STom N Harris
116100803e56STom N Harris    $body = '';
116200803e56STom N Harris    $data = array($page, $body);
116300803e56STom N Harris    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
116400803e56STom N Harris    if ($evt->advise_before()) $data[1] = $data[1] . " " . rawWiki($page);
116500803e56STom N Harris    $evt->advise_after();
116600803e56STom N Harris    unset($evt);
116700803e56STom N Harris    list($page,$body) = $data;
116800803e56STom N Harris
11699b41be24STom N Harris    $Indexer = idx_get_indexer();
11709b41be24STom N Harris    $result = $Indexer->addPageWords($page, $body);
1171e1e1a7e0SMichael Hamann    if ($result === "locked") {
11729b41be24STom N Harris        if ($verbose) print("Indexer: locked".DOKU_LF);
11739b41be24STom N Harris        return false;
11749b41be24STom N Harris    }
1175320f489aSMichael Hamann
1176320f489aSMichael Hamann    if ($result) {
1177320f489aSMichael Hamann        $data = array('page' => $page, 'metadata' => array());
1178320f489aSMichael Hamann
1179bbc85ee4STom N Harris        $data['metadata']['title'] = p_get_metadata($page, 'title', false);
1180bbc85ee4STom N Harris        if (($references = p_get_metadata($page, 'relation references', false)) !== null)
1181320f489aSMichael Hamann            $data['metadata']['relation_references'] = array_keys($references);
1182320f489aSMichael Hamann
1183320f489aSMichael Hamann        $evt = new Doku_Event('INDEXER_METADATA_INDEX', $data);
1184320f489aSMichael Hamann        if ($evt->advise_before()) {
1185320f489aSMichael Hamann            $result = $Indexer->addMetaKeys($page, $data['metadata']);
1186320f489aSMichael Hamann            if ($result === "locked") {
1187320f489aSMichael Hamann                if ($verbose) print("Indexer: locked".DOKU_LF);
1188320f489aSMichael Hamann                return false;
1189320f489aSMichael Hamann            }
1190320f489aSMichael Hamann        }
1191320f489aSMichael Hamann        $evt->advise_after();
1192320f489aSMichael Hamann        unset($evt);
1193320f489aSMichael Hamann    }
1194320f489aSMichael Hamann
11959b41be24STom N Harris    if ($result)
11969b41be24STom N Harris        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
11979b41be24STom N Harris    if ($verbose) {
11989b41be24STom N Harris        print("Indexer: finished".DOKU_LF);
11999b41be24STom N Harris        return true;
12009b41be24STom N Harris    }
12019b41be24STom N Harris    return $result;
120200803e56STom N Harris}
120300803e56STom N Harris
120400803e56STom N Harris/**
120500803e56STom N Harris * Find tokens in the fulltext index
120600803e56STom N Harris *
120700803e56STom N Harris * Takes an array of words and will return a list of matching
120800803e56STom N Harris * pages for each one.
1209488dd6ceSAndreas Gohr *
121063773904SAndreas Gohr * Important: No ACL checking is done here! All results are
121163773904SAndreas Gohr *            returned, regardless of permissions
121263773904SAndreas Gohr *
12139b41be24STom N Harris * @param arrayref      $words  list of words to search for
121400803e56STom N Harris * @return array                list of pages found, associated with the search terms
1215488dd6ceSAndreas Gohr */
12169b41be24STom N Harrisfunction idx_lookup(&$words) {
12179b41be24STom N Harris    $Indexer = idx_get_indexer();
121800803e56STom N Harris    return $Indexer->lookup($words);
1219488dd6ceSAndreas Gohr}
1220488dd6ceSAndreas Gohr
1221488dd6ceSAndreas Gohr/**
122200803e56STom N Harris * Split a string into tokens
1223488dd6ceSAndreas Gohr *
1224488dd6ceSAndreas Gohr */
122500803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) {
12269b41be24STom N Harris    $Indexer = idx_get_indexer();
122700803e56STom N Harris    return $Indexer->tokenizer($string, $wc);
1228488dd6ceSAndreas Gohr}
122900803e56STom N Harris
123000803e56STom N Harris/* For compatibility */
1231488dd6ceSAndreas Gohr
1232f5eb7cf0SAndreas Gohr/**
123300803e56STom N Harris * Read the list of words in an index (if it exists).
1234f5eb7cf0SAndreas Gohr *
12354e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
1236f5eb7cf0SAndreas Gohr */
123700803e56STom N Harrisfunction idx_getIndex($idx, $suffix) {
12381c07b9e6STom N Harris    global $conf;
123900803e56STom N Harris    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
124000803e56STom N Harris    if (!@file_exists($fn)) return array();
124100803e56STom N Harris    return file($fn);
124200803e56STom N Harris}
1243f5eb7cf0SAndreas Gohr
124400803e56STom N Harris/**
124500803e56STom N Harris * Get the list of lengths indexed in the wiki.
124600803e56STom N Harris *
124700803e56STom N Harris * Read the index directory or a cache file and returns
124800803e56STom N Harris * a sorted array of lengths of the words used in the wiki.
124900803e56STom N Harris *
125000803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
125100803e56STom N Harris */
125200803e56STom N Harrisfunction idx_listIndexLengths() {
125300803e56STom N Harris    global $conf;
125400803e56STom N Harris    // testing what we have to do, create a cache file or not.
125500803e56STom N Harris    if ($conf['readdircache'] == 0) {
125600803e56STom N Harris        $docache = false;
12571c07b9e6STom N Harris    } else {
125800803e56STom N Harris        clearstatcache();
125900803e56STom N Harris        if (@file_exists($conf['indexdir'].'/lengths.idx')
126000803e56STom N Harris        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
126100803e56STom N Harris            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
126200803e56STom N Harris                $idx = array();
126300803e56STom N Harris                foreach ($lengths as $length) {
126400803e56STom N Harris                    $idx[] = (int)$length;
126500803e56STom N Harris                }
126600803e56STom N Harris                return $idx;
1267f5eb7cf0SAndreas Gohr            }
12681c07b9e6STom N Harris        }
126900803e56STom N Harris        $docache = true;
127000803e56STom N Harris    }
12714e1bf408STom N Harris
127200803e56STom N Harris    if ($conf['readdircache'] == 0 || $docache) {
127300803e56STom N Harris        $dir = @opendir($conf['indexdir']);
127400803e56STom N Harris        if ($dir === false)
127500803e56STom N Harris            return array();
127600803e56STom N Harris        $idx[] = array();
127700803e56STom N Harris        while (($f = readdir($dir)) !== false) {
127800803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
127900803e56STom N Harris                $i = substr($f, 1, -4);
128000803e56STom N Harris                if (is_numeric($i))
128100803e56STom N Harris                    $idx[] = (int)$i;
128200803e56STom N Harris            }
128300803e56STom N Harris        }
128400803e56STom N Harris        closedir($dir);
128500803e56STom N Harris        sort($idx);
128600803e56STom N Harris        // save this in a file
128700803e56STom N Harris        if ($docache) {
128800803e56STom N Harris            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
128900803e56STom N Harris            @fwrite($handle, implode("\n", $idx));
129000803e56STom N Harris            @fclose($handle);
129100803e56STom N Harris        }
129200803e56STom N Harris        return $idx;
129300803e56STom N Harris    }
129400803e56STom N Harris
129500803e56STom N Harris    return array();
129600803e56STom N Harris}
129700803e56STom N Harris
129800803e56STom N Harris/**
129900803e56STom N Harris * Get the word lengths that have been indexed.
130000803e56STom N Harris *
130100803e56STom N Harris * Reads the index directory and returns an array of lengths
130200803e56STom N Harris * that there are indices for.
130300803e56STom N Harris *
130400803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
130500803e56STom N Harris */
130600803e56STom N Harrisfunction idx_indexLengths($filter) {
130700803e56STom N Harris    global $conf;
130800803e56STom N Harris    $idx = array();
130900803e56STom N Harris    if (is_array($filter)) {
131000803e56STom N Harris        // testing if index files exist only
131100803e56STom N Harris        $path = $conf['indexdir']."/i";
131200803e56STom N Harris        foreach ($filter as $key => $value) {
131300803e56STom N Harris            if (@file_exists($path.$key.'.idx'))
131400803e56STom N Harris                $idx[] = $key;
131500803e56STom N Harris        }
1316f5eb7cf0SAndreas Gohr    } else {
131700803e56STom N Harris        $lengths = idx_listIndexLengths();
131800803e56STom N Harris        foreach ($lengths as $key => $length) {
131900803e56STom N Harris            // keep all the values equal or superior
132000803e56STom N Harris            if ((int)$length >= (int)$filter)
132100803e56STom N Harris                $idx[] = $length;
1322f5eb7cf0SAndreas Gohr        }
132300803e56STom N Harris    }
132400803e56STom N Harris    return $idx;
1325f5eb7cf0SAndreas Gohr}
1326f5eb7cf0SAndreas Gohr
132700803e56STom N Harris/**
132800803e56STom N Harris * Clean a name of a key for use as a file name.
132900803e56STom N Harris *
133000803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's
133100803e56STom N Harris * not a letter, number, or underscore.
133200803e56STom N Harris *
133300803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
133400803e56STom N Harris */
133500803e56STom N Harrisfunction idx_cleanName($name) {
133600803e56STom N Harris    $name = utf8_romanize(trim((string)$name));
133700803e56STom N Harris    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
133800803e56STom N Harris    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
133900803e56STom N Harris    return strtolower($name);
1340f5eb7cf0SAndreas Gohr}
1341f5eb7cf0SAndreas Gohr
134200803e56STom N Harris//Setup VIM: ex: et ts=4 :
1343