xref: /dokuwiki/inc/indexer.php (revision 5eb9e8678ddc58a01929a9f340a01048836b47d3)
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    /**
342*5eb9e867SMichael Hamann     * Rename a page in the search index without changing the indexed content
343*5eb9e867SMichael Hamann     *
344*5eb9e867SMichael Hamann     * @param string $oldpage The old page name
345*5eb9e867SMichael Hamann     * @param string $newpage The new page name
346*5eb9e867SMichael Hamann     * @return string|bool If the page was successfully renamed, can be a message in the case of an error
347*5eb9e867SMichael Hamann     */
348*5eb9e867SMichael Hamann    public function renamePage($oldpage, $newpage) {
349*5eb9e867SMichael Hamann        if (!$this->lock()) return 'locked';
350*5eb9e867SMichael Hamann
351*5eb9e867SMichael Hamann        $pages = $this->getPages();
352*5eb9e867SMichael Hamann
353*5eb9e867SMichael Hamann        $id = array_search($oldpage, $pages);
354*5eb9e867SMichael Hamann        if ($id === false) {
355*5eb9e867SMichael Hamann            $this->unlock();
356*5eb9e867SMichael Hamann            return 'page is not in index';
357*5eb9e867SMichael Hamann        }
358*5eb9e867SMichael Hamann
359*5eb9e867SMichael Hamann        $new_id = array_search($newpage, $pages);
360*5eb9e867SMichael Hamann        if ($new_id !== false) {
361*5eb9e867SMichael Hamann            $this->unlock();
362*5eb9e867SMichael Hamann            // make sure the page is not in the index anymore
363*5eb9e867SMichael Hamann            $this->deletePage($newpage);
364*5eb9e867SMichael Hamann            if (!$this->lock()) return 'locked';
365*5eb9e867SMichael Hamann
366*5eb9e867SMichael Hamann            $pages[$new_id] = 'deleted:'.time().rand(0, 9999);
367*5eb9e867SMichael Hamann        }
368*5eb9e867SMichael Hamann
369*5eb9e867SMichael Hamann        $pages[$id] = $newpage;
370*5eb9e867SMichael Hamann
371*5eb9e867SMichael Hamann        // update index
372*5eb9e867SMichael Hamann        if (!$this->saveIndex('page', '', $pages)) {
373*5eb9e867SMichael Hamann            $this->unlock();
374*5eb9e867SMichael Hamann            return false;
375*5eb9e867SMichael Hamann        }
376*5eb9e867SMichael Hamann
377*5eb9e867SMichael Hamann        // reset the pid cache
378*5eb9e867SMichael Hamann        $this->pidCache = array();
379*5eb9e867SMichael Hamann
380*5eb9e867SMichael Hamann        $this->unlock();
381*5eb9e867SMichael Hamann        return true;
382*5eb9e867SMichael Hamann    }
383*5eb9e867SMichael Hamann
384*5eb9e867SMichael Hamann    /**
385*5eb9e867SMichael Hamann     * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages
386*5eb9e867SMichael Hamann     * will be updated.
387*5eb9e867SMichael Hamann     *
388*5eb9e867SMichael Hamann     * @param string $key       The metadata key of which a value shall be changed
389*5eb9e867SMichael Hamann     * @param string $oldvalue  The old value that shall be renamed
390*5eb9e867SMichael Hamann     * @param string $newvalue  The new value to which the old value shall be renamed, can exist (then values will be merged)
391*5eb9e867SMichael Hamann     * @return bool|string      If renaming the value has been successful, false or error message on error.
392*5eb9e867SMichael Hamann     */
393*5eb9e867SMichael Hamann    public function renameMetaValue($key, $oldvalue, $newvalue) {
394*5eb9e867SMichael Hamann        if (!$this->lock()) return 'locked';
395*5eb9e867SMichael Hamann
396*5eb9e867SMichael Hamann        // change the relation references index
397*5eb9e867SMichael Hamann        $metavalues = $this->getIndex($key, '_w');
398*5eb9e867SMichael Hamann        $oldid = array_search($oldvalue, $metavalues);
399*5eb9e867SMichael Hamann        if ($oldid !== false) {
400*5eb9e867SMichael Hamann            $newid = array_search($newvalue, $metavalues);
401*5eb9e867SMichael Hamann            if ($newid !== false) {
402*5eb9e867SMichael Hamann                // free memory
403*5eb9e867SMichael Hamann                unset ($metavalues);
404*5eb9e867SMichael Hamann
405*5eb9e867SMichael Hamann                // okay, now we have two entries for the same value. we need to merge them.
406*5eb9e867SMichael Hamann                $indexline = $this->getIndexKey($key, '_i', $oldid);
407*5eb9e867SMichael Hamann                if ($indexline != '') {
408*5eb9e867SMichael Hamann                    $newindexline = $this->getIndexKey($key, '_i', $newid);
409*5eb9e867SMichael Hamann                    $pagekeys     = $this->getIndex($key, '_p');
410*5eb9e867SMichael Hamann                    $parts = explode(':', $indexline);
411*5eb9e867SMichael Hamann                    foreach ($parts as $part) {
412*5eb9e867SMichael Hamann                        list($id, $count) = explode('*', $part);
413*5eb9e867SMichael Hamann                        $newindexline =  $this->updateTuple($newindexline, $id, $count);
414*5eb9e867SMichael Hamann
415*5eb9e867SMichael Hamann                        $keyline = explode(':', $pagekeys[$id]);
416*5eb9e867SMichael Hamann                        // remove old meta value
417*5eb9e867SMichael Hamann                        $keyline = array_diff($keyline, array($oldid));
418*5eb9e867SMichael Hamann                        // add new meta value when not already present
419*5eb9e867SMichael Hamann                        if (!in_array($newid, $keyline)) {
420*5eb9e867SMichael Hamann                            array_push($keyline, $newid);
421*5eb9e867SMichael Hamann                        }
422*5eb9e867SMichael Hamann                        $pagekeys[$id] = implode(':', $keyline);
423*5eb9e867SMichael Hamann                    }
424*5eb9e867SMichael Hamann                    $this->saveIndex($key, '_p', $pagekeys);
425*5eb9e867SMichael Hamann                    unset($pagekeys);
426*5eb9e867SMichael Hamann                    $this->saveIndexKey($key, '_i', $oldid, '');
427*5eb9e867SMichael Hamann                    $this->saveIndexKey($key, '_i', $newid, $newindexline);
428*5eb9e867SMichael Hamann                }
429*5eb9e867SMichael Hamann            } else {
430*5eb9e867SMichael Hamann                $metavalues[$oldid] = $newvalue;
431*5eb9e867SMichael Hamann                if (!$this->saveIndex($key, '_w', $metavalues)) {
432*5eb9e867SMichael Hamann                    $this->unlock();
433*5eb9e867SMichael Hamann                    return false;
434*5eb9e867SMichael Hamann                }
435*5eb9e867SMichael Hamann            }
436*5eb9e867SMichael Hamann        }
437*5eb9e867SMichael Hamann
438*5eb9e867SMichael Hamann        $this->unlock();
439*5eb9e867SMichael Hamann        return true;
440*5eb9e867SMichael Hamann    }
441*5eb9e867SMichael Hamann    /**
44200803e56STom N Harris     * Remove a page from the index
44344ca0adfSAndreas Gohr     *
44400803e56STom N Harris     * Erases entries in all known indexes.
44544ca0adfSAndreas Gohr     *
44600803e56STom N Harris     * @param string    $page   a page name
44700803e56STom N Harris     * @return boolean          the function completed successfully
44800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
44944ca0adfSAndreas Gohr     */
45000803e56STom N Harris    public function deletePage($page) {
45180fb93f6STom N Harris        if (!$this->lock())
452bbc85ee4STom N Harris            return "locked";
453bbc85ee4STom N Harris
454bbc85ee4STom N Harris        // load known documents
45503aafe1cSMichael Hamann        $pid = $this->getPIDNoLock($page);
4565981eb09STom N Harris        if ($pid === false) {
45780fb93f6STom N Harris            $this->unlock();
458bbc85ee4STom N Harris            return false;
459bbc85ee4STom N Harris        }
460bbc85ee4STom N Harris
461bbc85ee4STom N Harris        // Remove obsolete index entries
46280fb93f6STom N Harris        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
463bbc85ee4STom N Harris        if ($pageword_idx !== '') {
464bbc85ee4STom N Harris            $delwords = explode(':',$pageword_idx);
465bbc85ee4STom N Harris            $upwords = array();
466bbc85ee4STom N Harris            foreach ($delwords as $word) {
467bbc85ee4STom N Harris                if ($word != '') {
468bbc85ee4STom N Harris                    list($wlen,$wid) = explode('*', $word);
469bbc85ee4STom N Harris                    $wid = (int)$wid;
470bbc85ee4STom N Harris                    $upwords[$wlen][] = $wid;
471bbc85ee4STom N Harris                }
472bbc85ee4STom N Harris            }
473bbc85ee4STom N Harris            foreach ($upwords as $wlen => $widx) {
47480fb93f6STom N Harris                $index = $this->getIndex('i', $wlen);
475bbc85ee4STom N Harris                foreach ($widx as $wid) {
47680fb93f6STom N Harris                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
477bbc85ee4STom N Harris                }
47880fb93f6STom N Harris                $this->saveIndex('i', $wlen, $index);
479bbc85ee4STom N Harris            }
480bbc85ee4STom N Harris        }
481bbc85ee4STom N Harris        // Save the reverse index
48280fb93f6STom N Harris        if (!$this->saveIndexKey('pageword', '', $pid, "")) {
48380fb93f6STom N Harris            $this->unlock();
484bbc85ee4STom N Harris            return false;
485bbc85ee4STom N Harris        }
486bbc85ee4STom N Harris
48780fb93f6STom N Harris        $this->saveIndexKey('title', '', $pid, "");
48880fb93f6STom N Harris        $keyidx = $this->getIndex('metadata', '');
4890604da34STom N Harris        foreach ($keyidx as $metaname) {
49080fb93f6STom N Harris            $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid));
49180fb93f6STom N Harris            $meta_idx = $this->getIndex($metaname.'_i', '');
4920604da34STom N Harris            foreach ($val_idx as $id) {
493c55c59e3SMichael Hamann                if ($id === '') continue;
49480fb93f6STom N Harris                $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0);
4950604da34STom N Harris            }
49680fb93f6STom N Harris            $this->saveIndex($metaname.'_i', '', $meta_idx);
49780fb93f6STom N Harris            $this->saveIndexKey($metaname.'_p', '', $pid, '');
4980604da34STom N Harris        }
499bbc85ee4STom N Harris
50080fb93f6STom N Harris        $this->unlock();
501bbc85ee4STom N Harris        return true;
502d5b23302STom N Harris    }
50344ca0adfSAndreas Gohr
504d5b23302STom N Harris    /**
5053cf3c7d6SMichael Hamann     * Clear the whole index
5063cf3c7d6SMichael Hamann     *
5073cf3c7d6SMichael Hamann     * @return bool If the index has been cleared successfully
5083cf3c7d6SMichael Hamann     */
5093cf3c7d6SMichael Hamann    public function clear() {
5103cf3c7d6SMichael Hamann        global $conf;
5113cf3c7d6SMichael Hamann
5123cf3c7d6SMichael Hamann        if (!$this->lock()) return false;
5133cf3c7d6SMichael Hamann
5143cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/page.idx');
5153cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/title.idx');
5163cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/pageword.idx');
5173cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/metadata.idx');
5183cf3c7d6SMichael Hamann        $dir = @opendir($conf['indexdir']);
5193cf3c7d6SMichael Hamann        if($dir!==false){
5203cf3c7d6SMichael Hamann            while(($f = readdir($dir)) !== false){
5213cf3c7d6SMichael Hamann                if(substr($f,-4)=='.idx' &&
5223cf3c7d6SMichael Hamann                    (substr($f,0,1)=='i' || substr($f,0,1)=='w'
5233cf3c7d6SMichael Hamann                        || substr($f,-6)=='_w.idx' || substr($f,-6)=='_i.idx' || substr($f,-6)=='_p.idx'))
5243cf3c7d6SMichael Hamann                    @unlink($conf['indexdir']."/$f");
5253cf3c7d6SMichael Hamann            }
5263cf3c7d6SMichael Hamann        }
5273cf3c7d6SMichael Hamann        @unlink($conf['indexdir'].'/lengths.idx');
5283cf3c7d6SMichael Hamann
5293cf3c7d6SMichael Hamann        // clear the pid cache
5303cf3c7d6SMichael Hamann        $this->pidCache = array();
5313cf3c7d6SMichael Hamann
5323cf3c7d6SMichael Hamann        $this->unlock();
5333cf3c7d6SMichael Hamann        return true;
5343cf3c7d6SMichael Hamann    }
5353cf3c7d6SMichael Hamann
5363cf3c7d6SMichael Hamann    /**
53700803e56STom N Harris     * Split the text into words for fulltext search
538d5b23302STom N Harris     *
53900803e56STom N Harris     * TODO: does this also need &$stopwords ?
540d5b23302STom N Harris     *
5418cd4c12fSAndreas Gohr     * @triggers INDEXER_TEXT_PREPARE
5428cd4c12fSAndreas Gohr     * This event allows plugins to modify the text before it gets tokenized.
5438cd4c12fSAndreas Gohr     * Plugins intercepting this event should also intercept INDEX_VERSION_GET
5448cd4c12fSAndreas Gohr     *
54500803e56STom N Harris     * @param string    $text   plain text
54600803e56STom N Harris     * @param boolean   $wc     are wildcards allowed?
54700803e56STom N Harris     * @return array            list of words in the text
548d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
549d5b23302STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
550d5b23302STom N Harris     */
55100803e56STom N Harris    public function tokenizer($text, $wc=false) {
55200803e56STom N Harris        $wc = ($wc) ? '' : '\*';
55300803e56STom N Harris        $stopwords =& idx_get_stopwords();
55400803e56STom N Harris
5558cd4c12fSAndreas Gohr        // prepare the text to be tokenized
5568cd4c12fSAndreas Gohr        $evt = new Doku_Event('INDEXER_TEXT_PREPARE', $text);
5578cd4c12fSAndreas Gohr        if ($evt->advise_before(true)) {
55800803e56STom N Harris            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
55900803e56STom N Harris                // handle asian chars as single words (may fail on older PHP version)
56000803e56STom N Harris                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
56100803e56STom N Harris                if (!is_null($asia)) $text = $asia; // recover from regexp falure
56222952965SYoBoY            }
56322952965SYoBoY        }
5648cd4c12fSAndreas Gohr        $evt->advise_after();
5658cd4c12fSAndreas Gohr        unset($evt);
5668cd4c12fSAndreas Gohr
567f77fc90dSMichael Hamann        $text = strtr($text,
5684f0030ddSAndreas Gohr                       array(
5694f0030ddSAndreas Gohr                           "\r" => ' ',
5704f0030ddSAndreas Gohr                           "\n" => ' ',
5714f0030ddSAndreas Gohr                           "\t" => ' ',
5724f0030ddSAndreas Gohr                           "\xC2\xAD" => '', //soft-hyphen
5734f0030ddSAndreas Gohr                       )
5744f0030ddSAndreas Gohr                     );
57500803e56STom N Harris        if (preg_match('/[^0-9A-Za-z ]/u', $text))
57600803e56STom N Harris            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
57722952965SYoBoY
57800803e56STom N Harris        $wordlist = explode(' ', $text);
5795f27cb0eSMichael Hamann        foreach ($wordlist as $i => $word) {
5805f27cb0eSMichael Hamann            $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
58100803e56STom N Harris                utf8_strtolower($word) : strtolower($word);
5825f27cb0eSMichael Hamann        }
5835f27cb0eSMichael Hamann
5845f27cb0eSMichael Hamann        foreach ($wordlist as $i => $word) {
585675bf41fSTom N Harris            if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH)
586675bf41fSTom N Harris              || array_search($word, $stopwords) !== false)
587675bf41fSTom N Harris                unset($wordlist[$i]);
58822952965SYoBoY        }
589675bf41fSTom N Harris        return array_values($wordlist);
59022952965SYoBoY    }
59122952965SYoBoY
59222952965SYoBoY    /**
59303aafe1cSMichael Hamann     * Get the numeric PID of a page
59403aafe1cSMichael Hamann     *
59503aafe1cSMichael Hamann     * @param string $page The page to get the PID for
59603aafe1cSMichael Hamann     * @return bool|int The page id on success, false on error
59703aafe1cSMichael Hamann     */
59803aafe1cSMichael Hamann    public function getPID($page) {
5993d2ce006SMichael Hamann        // return PID without locking when it is in the cache
6003d2ce006SMichael Hamann        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
6013d2ce006SMichael Hamann
60203aafe1cSMichael Hamann        if (!$this->lock())
60303aafe1cSMichael Hamann            return false;
60403aafe1cSMichael Hamann
60503aafe1cSMichael Hamann        // load known documents
60603aafe1cSMichael Hamann        $pid = $this->getPIDNoLock($page);
60703aafe1cSMichael Hamann        if ($pid === false) {
60803aafe1cSMichael Hamann            $this->unlock();
60903aafe1cSMichael Hamann            return false;
61003aafe1cSMichael Hamann        }
61103aafe1cSMichael Hamann
61203aafe1cSMichael Hamann        $this->unlock();
61303aafe1cSMichael Hamann        return $pid;
61403aafe1cSMichael Hamann    }
61503aafe1cSMichael Hamann
61603aafe1cSMichael Hamann    /**
61703aafe1cSMichael Hamann     * Get the numeric PID of a page without locking the index.
61803aafe1cSMichael Hamann     * Only use this function when the index is already locked.
61903aafe1cSMichael Hamann     *
62003aafe1cSMichael Hamann     * @param string $page The page to get the PID for
62103aafe1cSMichael Hamann     * @return bool|int The page id on success, false on error
62203aafe1cSMichael Hamann     */
62303aafe1cSMichael Hamann    protected function getPIDNoLock($page) {
6243d2ce006SMichael Hamann        // avoid expensive addIndexKey operation for the most recently requested pages by using a cache
6253d2ce006SMichael Hamann        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
6263d2ce006SMichael Hamann        $pid = $this->addIndexKey('page', '', $page);
6273d2ce006SMichael Hamann        // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently
6283d2ce006SMichael Hamann        // added item will be requested again
6293d2ce006SMichael Hamann        if (count($this->pidCache) > 10) array_shift($this->pidCache);
6303d2ce006SMichael Hamann        $this->pidCache[$page] = $pid;
6313d2ce006SMichael Hamann        return $pid;
63203aafe1cSMichael Hamann    }
63303aafe1cSMichael Hamann
63403aafe1cSMichael Hamann    /**
63503aafe1cSMichael Hamann     * Get the page id of a numeric PID
63603aafe1cSMichael Hamann     *
63703aafe1cSMichael Hamann     * @param int $pid The PID to get the page id for
63803aafe1cSMichael Hamann     * @return string The page id
63903aafe1cSMichael Hamann     */
64003aafe1cSMichael Hamann    public function getPageFromPID($pid) {
64103aafe1cSMichael Hamann        return $this->getIndexKey('page', '', $pid);
64203aafe1cSMichael Hamann    }
64303aafe1cSMichael Hamann
64403aafe1cSMichael Hamann    /**
64500803e56STom N Harris     * Find pages in the fulltext index containing the words,
646579b0f7eSTNHarris     *
64700803e56STom N Harris     * The search words must be pre-tokenized, meaning only letters and
64800803e56STom N Harris     * numbers with an optional wildcard
649579b0f7eSTNHarris     *
65000803e56STom N Harris     * The returned array will have the original tokens as key. The values
65100803e56STom N Harris     * in the returned list is an array with the page names as keys and the
652b00bd361STom N Harris     * number of times that token appears on the page as value.
65300803e56STom N Harris     *
654e3ab6fc5SMichael Hamann     * @param array  $tokens list of words to search for
65500803e56STom N Harris     * @return array         list of page names with usage counts
65600803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
65700803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
658579b0f7eSTNHarris     */
6599b41be24STom N Harris    public function lookup(&$tokens) {
66000803e56STom N Harris        $result = array();
66180fb93f6STom N Harris        $wids = $this->getIndexWords($tokens, $result);
66200803e56STom N Harris        if (empty($wids)) return array();
66300803e56STom N Harris        // load known words and documents
66480fb93f6STom N Harris        $page_idx = $this->getIndex('page', '');
66500803e56STom N Harris        $docs = array();
66600803e56STom N Harris        foreach (array_keys($wids) as $wlen) {
66700803e56STom N Harris            $wids[$wlen] = array_unique($wids[$wlen]);
66880fb93f6STom N Harris            $index = $this->getIndex('i', $wlen);
66900803e56STom N Harris            foreach($wids[$wlen] as $ixid) {
67000803e56STom N Harris                if ($ixid < count($index))
67180fb93f6STom N Harris                    $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]);
672d5b23302STom N Harris            }
673d5b23302STom N Harris        }
67400803e56STom N Harris        // merge found pages into final result array
67500803e56STom N Harris        $final = array();
67600803e56STom N Harris        foreach ($result as $word => $res) {
67700803e56STom N Harris            $final[$word] = array();
67800803e56STom N Harris            foreach ($res as $wid) {
679952ab260SMichael Hamann                // handle the case when ($ixid < count($index)) has been false
680952ab260SMichael Hamann                // and thus $docs[$wid] hasn't been set.
681952ab260SMichael Hamann                if (!isset($docs[$wid])) continue;
68200803e56STom N Harris                $hits = &$docs[$wid];
68300803e56STom N Harris                foreach ($hits as $hitkey => $hitcnt) {
68400803e56STom N Harris                    // make sure the document still exists
68500803e56STom N Harris                    if (!page_exists($hitkey, '', false)) continue;
68600803e56STom N Harris                    if (!isset($final[$word][$hitkey]))
68700803e56STom N Harris                        $final[$word][$hitkey] = $hitcnt;
68800803e56STom N Harris                    else
68900803e56STom N Harris                        $final[$word][$hitkey] += $hitcnt;
690d5b23302STom N Harris                }
691579b0f7eSTNHarris            }
692579b0f7eSTNHarris        }
69300803e56STom N Harris        return $final;
694579b0f7eSTNHarris    }
695579b0f7eSTNHarris
696579b0f7eSTNHarris    /**
69700803e56STom N Harris     * Find pages containing a metadata key.
698d5b23302STom N Harris     *
69900803e56STom N Harris     * The metadata values are compared as case-sensitive strings. Pass a
70000803e56STom N Harris     * callback function that returns true or false to use a different
701b00bd361STom N Harris     * comparison function. The function will be called with the $value being
702b00bd361STom N Harris     * searched for as the first argument, and the word in the index as the
7031538718dSTom N Harris     * second argument. The function preg_match can be used directly if the
7041538718dSTom N Harris     * values are regexes.
705d5b23302STom N Harris     *
70600803e56STom N Harris     * @param string    $key    name of the metadata key to look for
7071538718dSTom N Harris     * @param string    $value  search term to look for, must be a string or array of strings
70800803e56STom N Harris     * @param callback  $func   comparison function
709b00bd361STom N Harris     * @return array            lists with page names, keys are query values if $value is array
71000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
711cd763a5bSMichael Hamann     * @author Michael Hamann <michael@content-space.de>
71200803e56STom N Harris     */
713b00bd361STom N Harris    public function lookupKey($key, &$value, $func=null) {
714f078bb00STom N Harris        if (!is_array($value))
715f078bb00STom N Harris            $value_array = array($value);
716f078bb00STom N Harris        else
717f078bb00STom N Harris            $value_array =& $value;
718cd763a5bSMichael Hamann
719c1209673STom N Harris        // the matching ids for the provided value(s)
720c1209673STom N Harris        $value_ids = array();
721c1209673STom N Harris
722c1209673STom N Harris        $metaname = idx_cleanName($key);
723c1209673STom N Harris
724c1209673STom N Harris        // get all words in order to search the matching ids
725c1209673STom N Harris        if ($key == 'title') {
72680fb93f6STom N Harris            $words = $this->getIndex('title', '');
727c1209673STom N Harris        } else {
728b9d8cc1eSTom N Harris            $words = $this->getIndex($metaname.'_w', '');
729c1209673STom N Harris        }
730c1209673STom N Harris
731f078bb00STom N Harris        if (!is_null($func)) {
7321538718dSTom N Harris            foreach ($value_array as $val) {
733f078bb00STom N Harris                foreach ($words as $i => $word) {
7341538718dSTom N Harris                    if (call_user_func_array($func, array($val, $word)))
735c1209673STom N Harris                        $value_ids[$i][] = $val;
736f078bb00STom N Harris                }
737f078bb00STom N Harris            }
738f078bb00STom N Harris        } else {
739f078bb00STom N Harris            foreach ($value_array as $val) {
740f078bb00STom N Harris                $xval = $val;
741b6d540bdSTom N Harris                $caret = '^';
742b6d540bdSTom N Harris                $dollar = '$';
743f078bb00STom N Harris                // check for wildcards
744f078bb00STom N Harris                if (substr($xval, 0, 1) == '*') {
745f078bb00STom N Harris                    $xval = substr($xval, 1);
746b6d540bdSTom N Harris                    $caret = '';
747f078bb00STom N Harris                }
748f078bb00STom N Harris                if (substr($xval, -1, 1) == '*') {
749f078bb00STom N Harris                    $xval = substr($xval, 0, -1);
750b6d540bdSTom N Harris                    $dollar = '';
751f078bb00STom N Harris                }
752b6d540bdSTom N Harris                if (!$caret || !$dollar) {
753f078bb00STom N Harris                    $re = $caret.preg_quote($xval, '/').$dollar;
754f078bb00STom N Harris                    foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
755c1209673STom N Harris                        $value_ids[$i][] = $val;
756cd763a5bSMichael Hamann                } else {
757f078bb00STom N Harris                    if (($i = array_search($val, $words)) !== false)
758c1209673STom N Harris                        $value_ids[$i][] = $val;
759cd763a5bSMichael Hamann                }
760cd763a5bSMichael Hamann            }
761cd763a5bSMichael Hamann        }
762cd763a5bSMichael Hamann
763cd763a5bSMichael Hamann        unset($words); // free the used memory
764cd763a5bSMichael Hamann
7657233c152SMichael Hamann        // initialize the result so it won't be null
766c1209673STom N Harris        $result = array();
7677233c152SMichael Hamann        foreach ($value_array as $val) {
7687233c152SMichael Hamann            $result[$val] = array();
7697233c152SMichael Hamann        }
7707233c152SMichael Hamann
77180fb93f6STom N Harris        $page_idx = $this->getIndex('page', '');
772cd763a5bSMichael Hamann
773c1209673STom N Harris        // Special handling for titles
774c1209673STom N Harris        if ($key == 'title') {
775c1209673STom N Harris            foreach ($value_ids as $pid => $val_list) {
776c1209673STom N Harris                $page = $page_idx[$pid];
777c1209673STom N Harris                foreach ($val_list as $val) {
778c1209673STom N Harris                    $result[$val][] = $page;
779c1209673STom N Harris                }
780c1209673STom N Harris            }
781c1209673STom N Harris        } else {
782c1209673STom N Harris            // load all lines and pages so the used lines can be taken and matched with the pages
783b9d8cc1eSTom N Harris            $lines = $this->getIndex($metaname.'_i', '');
784c1209673STom N Harris
785c1209673STom N Harris            foreach ($value_ids as $value_id => $val_list) {
786cd763a5bSMichael Hamann                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
787cd763a5bSMichael Hamann                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
78880fb93f6STom N Harris                $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id]));
789c1209673STom N Harris                foreach ($val_list as $val) {
790c1209673STom N Harris                    $result[$val] = array_merge($result[$val], $pages);
791c1209673STom N Harris                }
792c1209673STom N Harris            }
793cd763a5bSMichael Hamann        }
794f078bb00STom N Harris        if (!is_array($value)) $result = $result[$value];
795cd763a5bSMichael Hamann        return $result;
79600803e56STom N Harris    }
79700803e56STom N Harris
79800803e56STom N Harris    /**
79900803e56STom N Harris     * Find the index ID of each search term.
80000803e56STom N Harris     *
80100803e56STom N Harris     * The query terms should only contain valid characters, with a '*' at
80200803e56STom N Harris     * either the beginning or end of the word (or both).
80300803e56STom N Harris     * The $result parameter can be used to merge the index locations with
80400803e56STom N Harris     * the appropriate query term.
80500803e56STom N Harris     *
806e3ab6fc5SMichael Hamann     * @param array  $words  The query terms.
807e3ab6fc5SMichael Hamann     * @param array  $result Set to word => array("length*id" ...)
808d5b23302STom N Harris     * @return array         Set to length => array(id ...)
809d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
810d5b23302STom N Harris     */
81180fb93f6STom N Harris    protected function getIndexWords(&$words, &$result) {
812d5b23302STom N Harris        $tokens = array();
813d5b23302STom N Harris        $tokenlength = array();
814d5b23302STom N Harris        $tokenwild = array();
815d5b23302STom N Harris        foreach ($words as $word) {
816d5b23302STom N Harris            $result[$word] = array();
817b6d540bdSTom N Harris            $caret = '^';
818b6d540bdSTom N Harris            $dollar = '$';
819d5b23302STom N Harris            $xword = $word;
820d5b23302STom N Harris            $wlen = wordlen($word);
821d5b23302STom N Harris
822d5b23302STom N Harris            // check for wildcards
823d5b23302STom N Harris            if (substr($xword, 0, 1) == '*') {
824d5b23302STom N Harris                $xword = substr($xword, 1);
825b6d540bdSTom N Harris                $caret = '';
826d5b23302STom N Harris                $wlen -= 1;
827d5b23302STom N Harris            }
828d5b23302STom N Harris            if (substr($xword, -1, 1) == '*') {
829d5b23302STom N Harris                $xword = substr($xword, 0, -1);
830b6d540bdSTom N Harris                $dollar = '';
831d5b23302STom N Harris                $wlen -= 1;
832d5b23302STom N Harris            }
833b6d540bdSTom N Harris            if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
83400803e56STom N Harris                continue;
83500803e56STom N Harris            if (!isset($tokens[$xword]))
836d5b23302STom N Harris                $tokenlength[$wlen][] = $xword;
837b6d540bdSTom N Harris            if (!$caret || !$dollar) {
838f078bb00STom N Harris                $re = $caret.preg_quote($xword, '/').$dollar;
83900803e56STom N Harris                $tokens[$xword][] = array($word, '/'.$re.'/');
84000803e56STom N Harris                if (!isset($tokenwild[$xword]))
84100803e56STom N Harris                    $tokenwild[$xword] = $wlen;
84200803e56STom N Harris            } else {
843d5b23302STom N Harris                $tokens[$xword][] = array($word, null);
844d5b23302STom N Harris            }
84500803e56STom N Harris        }
846d5b23302STom N Harris        asort($tokenwild);
84700803e56STom N Harris        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
848d5b23302STom N Harris        // $tokenlength = array( base word length => base word ... )
849d5b23302STom N Harris        // $tokenwild = array( base word => base word length ... )
850d5b23302STom N Harris        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
85180fb93f6STom N Harris        $indexes_known = $this->indexLengths($length_filter);
852d5b23302STom N Harris        if (!empty($tokenwild)) sort($indexes_known);
853d5b23302STom N Harris        // get word IDs
854d5b23302STom N Harris        $wids = array();
855d5b23302STom N Harris        foreach ($indexes_known as $ixlen) {
85680fb93f6STom N Harris            $word_idx = $this->getIndex('w', $ixlen);
857d5b23302STom N Harris            // handle exact search
858d5b23302STom N Harris            if (isset($tokenlength[$ixlen])) {
859d5b23302STom N Harris                foreach ($tokenlength[$ixlen] as $xword) {
86000803e56STom N Harris                    $wid = array_search($xword, $word_idx);
86100803e56STom N Harris                    if ($wid !== false) {
862d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
863d5b23302STom N Harris                        foreach ($tokens[$xword] as $w)
864d5b23302STom N Harris                            $result[$w[0]][] = "$ixlen*$wid";
865d5b23302STom N Harris                    }
866d5b23302STom N Harris                }
867d5b23302STom N Harris            }
868d5b23302STom N Harris            // handle wildcard search
869d5b23302STom N Harris            foreach ($tokenwild as $xword => $wlen) {
870d5b23302STom N Harris                if ($wlen >= $ixlen) break;
871d5b23302STom N Harris                foreach ($tokens[$xword] as $w) {
872d5b23302STom N Harris                    if (is_null($w[1])) continue;
873d5b23302STom N Harris                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
874d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
875d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
876d5b23302STom N Harris                    }
877d5b23302STom N Harris                }
878d5b23302STom N Harris            }
879d5b23302STom N Harris        }
880d5b23302STom N Harris        return $wids;
881d5b23302STom N Harris    }
882d5b23302STom N Harris
883d5b23302STom N Harris    /**
88400803e56STom N Harris     * Return a list of all pages
885c1209673STom N Harris     * Warning: pages may not exist!
886488dd6ceSAndreas Gohr     *
88700803e56STom N Harris     * @param string    $key    list only pages containing the metadata key (optional)
88800803e56STom N Harris     * @return array            list of page names
88900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
89000803e56STom N Harris     */
89100803e56STom N Harris    public function getPages($key=null) {
89280fb93f6STom N Harris        $page_idx = $this->getIndex('page', '');
89300803e56STom N Harris        if (is_null($key)) return $page_idx;
894c1209673STom N Harris
895c1209673STom N Harris        $metaname = idx_cleanName($key);
896c1209673STom N Harris
897c1209673STom N Harris        // Special handling for titles
898c1209673STom N Harris        if ($key == 'title') {
89980fb93f6STom N Harris            $title_idx = $this->getIndex('title', '');
900c1209673STom N Harris            array_splice($page_idx, count($title_idx));
901c1209673STom N Harris            foreach ($title_idx as $i => $title)
902c1209673STom N Harris                if ($title === "") unset($page_idx[$i]);
903675bf41fSTom N Harris            return array_values($page_idx);
904c1209673STom N Harris        }
905c1209673STom N Harris
906c1209673STom N Harris        $pages = array();
907b9d8cc1eSTom N Harris        $lines = $this->getIndex($metaname.'_i', '');
908c1209673STom N Harris        foreach ($lines as $line) {
90980fb93f6STom N Harris            $pages = array_merge($pages, $this->parseTuples($page_idx, $line));
910c1209673STom N Harris        }
911c1209673STom N Harris        return array_keys($pages);
91200803e56STom N Harris    }
91300803e56STom N Harris
91400803e56STom N Harris    /**
91500803e56STom N Harris     * Return a list of words sorted by number of times used
91600803e56STom N Harris     *
91700803e56STom N Harris     * @param int       $min    bottom frequency threshold
91800803e56STom N Harris     * @param int       $max    upper frequency limit. No limit if $max<$min
919e3ab6fc5SMichael Hamann     * @param int       $minlen minimum length of words to count
92000803e56STom N Harris     * @param string    $key    metadata key to list. Uses the fulltext index if not given
92100803e56STom N Harris     * @return array            list of words as the keys and frequency as values
92200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
92300803e56STom N Harris     */
924b8c040dbSTom N Harris    public function histogram($min=1, $max=0, $minlen=3, $key=null) {
925175193d2STom N Harris        if ($min < 1)
926175193d2STom N Harris            $min = 1;
927175193d2STom N Harris        if ($max < $min)
928175193d2STom N Harris            $max = 0;
929175193d2STom N Harris
930175193d2STom N Harris        $result = array();
931175193d2STom N Harris
932175193d2STom N Harris        if ($key == 'title') {
93380fb93f6STom N Harris            $index = $this->getIndex('title', '');
934175193d2STom N Harris            $index = array_count_values($index);
935175193d2STom N Harris            foreach ($index as $val => $cnt) {
936b8c040dbSTom N Harris                if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
937175193d2STom N Harris                    $result[$val] = $cnt;
938175193d2STom N Harris            }
939175193d2STom N Harris        }
940175193d2STom N Harris        elseif (!is_null($key)) {
941175193d2STom N Harris            $metaname = idx_cleanName($key);
94280fb93f6STom N Harris            $index = $this->getIndex($metaname.'_i', '');
943175193d2STom N Harris            $val_idx = array();
944175193d2STom N Harris            foreach ($index as $wid => $line) {
94580fb93f6STom N Harris                $freq = $this->countTuples($line);
9469a9b579aSMichael Hamann                if ($freq >= $min && (!$max || $freq <= $max))
947175193d2STom N Harris                    $val_idx[$wid] = $freq;
948175193d2STom N Harris            }
949175193d2STom N Harris            if (!empty($val_idx)) {
95080fb93f6STom N Harris                $words = $this->getIndex($metaname.'_w', '');
9519a9b579aSMichael Hamann                foreach ($val_idx as $wid => $freq) {
9529a9b579aSMichael Hamann                    if (strlen($words[$wid]) >= $minlen)
953175193d2STom N Harris                        $result[$words[$wid]] = $freq;
954175193d2STom N Harris                }
955175193d2STom N Harris            }
9569a9b579aSMichael Hamann        }
957175193d2STom N Harris        else {
958175193d2STom N Harris            $lengths = idx_listIndexLengths();
959175193d2STom N Harris            foreach ($lengths as $length) {
960b8c040dbSTom N Harris                if ($length < $minlen) continue;
96180fb93f6STom N Harris                $index = $this->getIndex('i', $length);
962175193d2STom N Harris                $words = null;
963175193d2STom N Harris                foreach ($index as $wid => $line) {
96480fb93f6STom N Harris                    $freq = $this->countTuples($line);
965175193d2STom N Harris                    if ($freq >= $min && (!$max || $freq <= $max)) {
966175193d2STom N Harris                        if ($words === null)
96780fb93f6STom N Harris                            $words = $this->getIndex('w', $length);
968175193d2STom N Harris                        $result[$words[$wid]] = $freq;
969175193d2STom N Harris                    }
970175193d2STom N Harris                }
971175193d2STom N Harris            }
972175193d2STom N Harris        }
973175193d2STom N Harris
974175193d2STom N Harris        arsort($result);
975175193d2STom N Harris        return $result;
97600803e56STom N Harris    }
97700803e56STom N Harris
97800803e56STom N Harris    /**
97900803e56STom N Harris     * Lock the indexer.
98000803e56STom N Harris     *
98100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
98200803e56STom N Harris     */
98380fb93f6STom N Harris    protected function lock() {
98400803e56STom N Harris        global $conf;
98500803e56STom N Harris        $status = true;
986f77fc90dSMichael Hamann        $run = 0;
98700803e56STom N Harris        $lock = $conf['lockdir'].'/_indexer.lock';
98800803e56STom N Harris        while (!@mkdir($lock, $conf['dmode'])) {
98900803e56STom N Harris            usleep(50);
990f77fc90dSMichael Hamann            if(is_dir($lock) && time()-@filemtime($lock) > 60*5){
991f77fc90dSMichael Hamann                // looks like a stale lock - remove it
992f77fc90dSMichael Hamann                if (!@rmdir($lock)) {
993f77fc90dSMichael Hamann                    $status = "removing the stale lock failed";
994f77fc90dSMichael Hamann                    return false;
99500803e56STom N Harris                } else {
996f77fc90dSMichael Hamann                    $status = "stale lock removed";
997f77fc90dSMichael Hamann                }
998f77fc90dSMichael Hamann            }elseif($run++ == 1000){
999f77fc90dSMichael Hamann                // we waited 5 seconds for that lock
100000803e56STom N Harris                return false;
100100803e56STom N Harris            }
100200803e56STom N Harris        }
100300803e56STom N Harris        if ($conf['dperm'])
100400803e56STom N Harris            chmod($lock, $conf['dperm']);
100500803e56STom N Harris        return $status;
100600803e56STom N Harris    }
100700803e56STom N Harris
100800803e56STom N Harris    /**
100900803e56STom N Harris     * Release the indexer lock.
101000803e56STom N Harris     *
101100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
101200803e56STom N Harris     */
101380fb93f6STom N Harris    protected function unlock() {
101400803e56STom N Harris        global $conf;
101500803e56STom N Harris        @rmdir($conf['lockdir'].'/_indexer.lock');
101600803e56STom N Harris        return true;
101700803e56STom N Harris    }
101800803e56STom N Harris
101900803e56STom N Harris    /**
102000803e56STom N Harris     * Retrieve the entire index.
102100803e56STom N Harris     *
1022b9d8cc1eSTom N Harris     * The $suffix argument is for an index that is split into
1023b9d8cc1eSTom N Harris     * multiple parts. Different index files should use different
1024b9d8cc1eSTom N Harris     * base names.
1025b9d8cc1eSTom N Harris     *
1026b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
1027b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
1028b9d8cc1eSTom N Harris     * @return array            list of lines without CR or LF
102900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
103000803e56STom N Harris     */
103180fb93f6STom N Harris    protected function getIndex($idx, $suffix) {
103200803e56STom N Harris        global $conf;
103300803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1034d64516f5SMichael Hamann        if (!@file_exists($fn)) return array();
1035d64516f5SMichael Hamann        return file($fn, FILE_IGNORE_NEW_LINES);
103600803e56STom N Harris    }
103700803e56STom N Harris
103800803e56STom N Harris    /**
103900803e56STom N Harris     * Replace the contents of the index with an array.
104000803e56STom N Harris     *
1041b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
1042b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
1043e3ab6fc5SMichael Hamann     * @param array     $lines  list of lines without LF
1044e3ab6fc5SMichael Hamann     * @return bool             If saving succeeded
104500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
104600803e56STom N Harris     */
104780fb93f6STom N Harris    protected function saveIndex($idx, $suffix, &$lines) {
104800803e56STom N Harris        global $conf;
104900803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
105000803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
105100803e56STom N Harris        if (!$fh) return false;
105200803e56STom N Harris        fwrite($fh, join("\n", $lines));
10532e1018bcSMichael Hamann        if (!empty($lines))
10542e1018bcSMichael Hamann            fwrite($fh, "\n");
105500803e56STom N Harris        fclose($fh);
105600803e56STom N Harris        if (isset($conf['fperm']))
105700803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
105800803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
105900803e56STom N Harris        if ($suffix !== '')
106080fb93f6STom N Harris            $this->cacheIndexDir($idx, $suffix, empty($lines));
106100803e56STom N Harris        return true;
106200803e56STom N Harris    }
106300803e56STom N Harris
106400803e56STom N Harris    /**
106500803e56STom N Harris     * Retrieve a line from the index.
106600803e56STom N Harris     *
1067b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
1068b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
1069b9d8cc1eSTom N Harris     * @param int       $id     the line number
1070b9d8cc1eSTom N Harris     * @return string           a line with trailing whitespace removed
107100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
107200803e56STom N Harris     */
107380fb93f6STom N Harris    protected function getIndexKey($idx, $suffix, $id) {
107400803e56STom N Harris        global $conf;
107500803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
107600803e56STom N Harris        if (!@file_exists($fn)) return '';
107700803e56STom N Harris        $fh = @fopen($fn, 'r');
107800803e56STom N Harris        if (!$fh) return '';
107900803e56STom N Harris        $ln = -1;
108000803e56STom N Harris        while (($line = fgets($fh)) !== false) {
108100803e56STom N Harris            if (++$ln == $id) break;
108200803e56STom N Harris        }
108300803e56STom N Harris        fclose($fh);
108400803e56STom N Harris        return rtrim((string)$line);
108500803e56STom N Harris    }
108600803e56STom N Harris
108700803e56STom N Harris    /**
108800803e56STom N Harris     * Write a line into the index.
108900803e56STom N Harris     *
1090b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
1091b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
1092b9d8cc1eSTom N Harris     * @param int       $id     the line number
1093b9d8cc1eSTom N Harris     * @param string    $line   line to write
1094e3ab6fc5SMichael Hamann     * @return bool             If saving succeeded
109500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
109600803e56STom N Harris     */
109780fb93f6STom N Harris    protected function saveIndexKey($idx, $suffix, $id, $line) {
109800803e56STom N Harris        global $conf;
109900803e56STom N Harris        if (substr($line, -1) != "\n")
110000803e56STom N Harris            $line .= "\n";
110100803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
110200803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
1103dbb771bbSAdrian Lang        if (!$fh) return false;
110400803e56STom N Harris        $ih = @fopen($fn.'.idx', 'r');
110500803e56STom N Harris        if ($ih) {
110600803e56STom N Harris            $ln = -1;
110700803e56STom N Harris            while (($curline = fgets($ih)) !== false) {
110800803e56STom N Harris                fwrite($fh, (++$ln == $id) ? $line : $curline);
110900803e56STom N Harris            }
11104373c7b5SMichael Hamann            if ($id > $ln) {
11114373c7b5SMichael Hamann                while ($id > ++$ln)
11124373c7b5SMichael Hamann                    fwrite($fh, "\n");
111300803e56STom N Harris                fwrite($fh, $line);
11144373c7b5SMichael Hamann            }
111500803e56STom N Harris            fclose($ih);
111600803e56STom N Harris        } else {
11174373c7b5SMichael Hamann            $ln = -1;
11184373c7b5SMichael Hamann            while ($id > ++$ln)
11194373c7b5SMichael Hamann                fwrite($fh, "\n");
112000803e56STom N Harris            fwrite($fh, $line);
112100803e56STom N Harris        }
112200803e56STom N Harris        fclose($fh);
112300803e56STom N Harris        if (isset($conf['fperm']))
112400803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
112500803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
112600803e56STom N Harris        if ($suffix !== '')
112780fb93f6STom N Harris            $this->cacheIndexDir($idx, $suffix);
112800803e56STom N Harris        return true;
112900803e56STom N Harris    }
113000803e56STom N Harris
113100803e56STom N Harris    /**
113200803e56STom N Harris     * Retrieve or insert a value in the index.
113300803e56STom N Harris     *
1134b9d8cc1eSTom N Harris     * @param string    $idx    name of the index
1135b9d8cc1eSTom N Harris     * @param string    $suffix subpart identifier
1136b9d8cc1eSTom N Harris     * @param string    $value  line to find in the index
113703aafe1cSMichael Hamann     * @return int|bool          line number of the value in the index or false if writing the index failed
113800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
113900803e56STom N Harris     */
114080fb93f6STom N Harris    protected function addIndexKey($idx, $suffix, $value) {
114180fb93f6STom N Harris        $index = $this->getIndex($idx, $suffix);
114200803e56STom N Harris        $id = array_search($value, $index);
114300803e56STom N Harris        if ($id === false) {
114400803e56STom N Harris            $id = count($index);
114500803e56STom N Harris            $index[$id] = $value;
114680fb93f6STom N Harris            if (!$this->saveIndex($idx, $suffix, $index)) {
114700803e56STom N Harris                trigger_error("Failed to write $idx index", E_USER_ERROR);
114800803e56STom N Harris                return false;
114900803e56STom N Harris            }
115000803e56STom N Harris        }
115100803e56STom N Harris        return $id;
115200803e56STom N Harris    }
115300803e56STom N Harris
1154e3ab6fc5SMichael Hamann    /**
1155e3ab6fc5SMichael Hamann     * @param string $idx    The index file which should be added to the key.
1156e3ab6fc5SMichael Hamann     * @param string $suffix The suffix of the file
1157e3ab6fc5SMichael Hamann     * @param bool   $delete Unused
1158e3ab6fc5SMichael Hamann     */
115980fb93f6STom N Harris    protected function cacheIndexDir($idx, $suffix, $delete=false) {
116000803e56STom N Harris        global $conf;
116100803e56STom N Harris        if ($idx == 'i')
116200803e56STom N Harris            $cachename = $conf['indexdir'].'/lengths';
116300803e56STom N Harris        else
116400803e56STom N Harris            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
116500803e56STom N Harris        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
116600803e56STom N Harris        if ($lengths === false) $lengths = array();
116700803e56STom N Harris        $old = array_search((string)$suffix, $lengths);
116800803e56STom N Harris        if (empty($lines)) {
116900803e56STom N Harris            if ($old === false) return;
117000803e56STom N Harris            unset($lengths[$old]);
117100803e56STom N Harris        } else {
117200803e56STom N Harris            if ($old !== false) return;
117300803e56STom N Harris            $lengths[] = $suffix;
117400803e56STom N Harris            sort($lengths);
117500803e56STom N Harris        }
117600803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
117700803e56STom N Harris        if (!$fh) {
117800803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
117900803e56STom N Harris            return;
118000803e56STom N Harris        }
118100803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
118200803e56STom N Harris        @fclose($fh);
118300803e56STom N Harris        if (isset($conf['fperm']))
118400803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
118500803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
118600803e56STom N Harris    }
118700803e56STom N Harris
118800803e56STom N Harris    /**
118900803e56STom N Harris     * Get the list of lengths indexed in the wiki.
119000803e56STom N Harris     *
119100803e56STom N Harris     * Read the index directory or a cache file and returns
119200803e56STom N Harris     * a sorted array of lengths of the words used in the wiki.
119300803e56STom N Harris     *
119400803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
119500803e56STom N Harris     */
119680fb93f6STom N Harris    protected function listIndexLengths() {
119700803e56STom N Harris        global $conf;
119800803e56STom N Harris        $cachename = $conf['indexdir'].'/lengths';
119900803e56STom N Harris        clearstatcache();
120000803e56STom N Harris        if (@file_exists($cachename.'.idx')) {
120100803e56STom N Harris            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
120200803e56STom N Harris            if ($lengths !== false) {
120300803e56STom N Harris                $idx = array();
120400803e56STom N Harris                foreach ($lengths as $length)
120500803e56STom N Harris                    $idx[] = (int)$length;
120600803e56STom N Harris                return $idx;
120700803e56STom N Harris            }
120800803e56STom N Harris        }
120900803e56STom N Harris
121000803e56STom N Harris        $dir = @opendir($conf['indexdir']);
121100803e56STom N Harris        if ($dir === false)
121200803e56STom N Harris            return array();
121300803e56STom N Harris        $lengths[] = array();
121400803e56STom N Harris        while (($f = readdir($dir)) !== false) {
121500803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
121600803e56STom N Harris                $i = substr($f, 1, -4);
121700803e56STom N Harris                if (is_numeric($i))
121800803e56STom N Harris                    $lengths[] = (int)$i;
121900803e56STom N Harris            }
122000803e56STom N Harris        }
122100803e56STom N Harris        closedir($dir);
122200803e56STom N Harris        sort($lengths);
122300803e56STom N Harris        // save this in a file
122400803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
122500803e56STom N Harris        if (!$fh) {
122600803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
12273e8e3ae6SMichael Hamann            return $lengths;
122800803e56STom N Harris        }
122900803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
123000803e56STom N Harris        @fclose($fh);
123100803e56STom N Harris        if (isset($conf['fperm']))
123200803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
123300803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
123400803e56STom N Harris
123500803e56STom N Harris        return $lengths;
123600803e56STom N Harris    }
123700803e56STom N Harris
123800803e56STom N Harris    /**
123900803e56STom N Harris     * Get the word lengths that have been indexed.
124000803e56STom N Harris     *
124100803e56STom N Harris     * Reads the index directory and returns an array of lengths
124200803e56STom N Harris     * that there are indices for.
124300803e56STom N Harris     *
124400803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
124500803e56STom N Harris     */
124680fb93f6STom N Harris    protected function indexLengths($filter) {
124700803e56STom N Harris        global $conf;
124800803e56STom N Harris        $idx = array();
124900803e56STom N Harris        if (is_array($filter)) {
125000803e56STom N Harris            // testing if index files exist only
125100803e56STom N Harris            $path = $conf['indexdir']."/i";
125200803e56STom N Harris            foreach ($filter as $key => $value) {
125300803e56STom N Harris                if (@file_exists($path.$key.'.idx'))
125400803e56STom N Harris                    $idx[] = $key;
125500803e56STom N Harris            }
125600803e56STom N Harris        } else {
125700803e56STom N Harris            $lengths = idx_listIndexLengths();
125800803e56STom N Harris            foreach ($lengths as $key => $length) {
125900803e56STom N Harris                // keep all the values equal or superior
126000803e56STom N Harris                if ((int)$length >= (int)$filter)
126100803e56STom N Harris                    $idx[] = $length;
126200803e56STom N Harris            }
126300803e56STom N Harris        }
126400803e56STom N Harris        return $idx;
126500803e56STom N Harris    }
126600803e56STom N Harris
126700803e56STom N Harris    /**
126800803e56STom N Harris     * Insert or replace a tuple in a line.
126900803e56STom N Harris     *
127000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
127100803e56STom N Harris     */
127280fb93f6STom N Harris    protected function updateTuple($line, $id, $count) {
127300803e56STom N Harris        $newLine = $line;
127400803e56STom N Harris        if ($newLine !== '')
127500803e56STom N Harris            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
127600803e56STom N Harris        $newLine = trim($newLine, ':');
127700803e56STom N Harris        if ($count) {
1278d64516f5SMichael Hamann            if (strlen($newLine) > 0)
127900803e56STom N Harris                return "$id*$count:".$newLine;
128000803e56STom N Harris            else
128100803e56STom N Harris                return "$id*$count".$newLine;
128200803e56STom N Harris        }
128300803e56STom N Harris        return $newLine;
128400803e56STom N Harris    }
128500803e56STom N Harris
128600803e56STom N Harris    /**
128700803e56STom N Harris     * Split a line into an array of tuples.
128800803e56STom N Harris     *
128900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
129000803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
129100803e56STom N Harris     */
129280fb93f6STom N Harris    protected function parseTuples(&$keys, $line) {
129300803e56STom N Harris        $result = array();
129400803e56STom N Harris        if ($line == '') return $result;
129500803e56STom N Harris        $parts = explode(':', $line);
129600803e56STom N Harris        foreach ($parts as $tuple) {
1297675bf41fSTom N Harris            if ($tuple === '') continue;
129800803e56STom N Harris            list($key, $cnt) = explode('*', $tuple);
1299d64516f5SMichael Hamann            if (!$cnt) continue;
130000803e56STom N Harris            $key = $keys[$key];
130100803e56STom N Harris            if (!$key) continue;
130200803e56STom N Harris            $result[$key] = $cnt;
130300803e56STom N Harris        }
130400803e56STom N Harris        return $result;
130500803e56STom N Harris    }
1306175193d2STom N Harris
1307175193d2STom N Harris    /**
1308175193d2STom N Harris     * Sum the counts in a list of tuples.
1309175193d2STom N Harris     *
1310175193d2STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
1311175193d2STom N Harris     */
131280fb93f6STom N Harris    protected function countTuples($line) {
1313175193d2STom N Harris        $freq = 0;
1314175193d2STom N Harris        $parts = explode(':', $line);
1315175193d2STom N Harris        foreach ($parts as $tuple) {
1316675bf41fSTom N Harris            if ($tuple === '') continue;
1317175193d2STom N Harris            list($pid, $cnt) = explode('*', $tuple);
1318175193d2STom N Harris            $freq += (int)$cnt;
1319175193d2STom N Harris        }
1320175193d2STom N Harris        return $freq;
1321175193d2STom N Harris    }
132200803e56STom N Harris}
132300803e56STom N Harris
132400803e56STom N Harris/**
132500803e56STom N Harris * Create an instance of the indexer.
132600803e56STom N Harris *
1327b3d1090eSMichael Hamann * @return Doku_Indexer               a Doku_Indexer
132800803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
132900803e56STom N Harris */
13309b41be24STom N Harrisfunction idx_get_indexer() {
13314f708321SMichael Hamann    static $Indexer;
13321421e548SMichael Hamann    if (!isset($Indexer)) {
133300803e56STom N Harris        $Indexer = new Doku_Indexer();
133400803e56STom N Harris    }
133500803e56STom N Harris    return $Indexer;
133600803e56STom N Harris}
133700803e56STom N Harris
133800803e56STom N Harris/**
133900803e56STom N Harris * Returns words that will be ignored.
134000803e56STom N Harris *
134100803e56STom N Harris * @return array                list of stop words
134200803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
134300803e56STom N Harris */
134400803e56STom N Harrisfunction & idx_get_stopwords() {
134500803e56STom N Harris    static $stopwords = null;
134600803e56STom N Harris    if (is_null($stopwords)) {
134700803e56STom N Harris        global $conf;
134800803e56STom N Harris        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
134900803e56STom N Harris        if(@file_exists($swfile)){
135000803e56STom N Harris            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
135100803e56STom N Harris        }else{
135200803e56STom N Harris            $stopwords = array();
135300803e56STom N Harris        }
135400803e56STom N Harris    }
135500803e56STom N Harris    return $stopwords;
135600803e56STom N Harris}
135700803e56STom N Harris
135800803e56STom N Harris/**
135900803e56STom N Harris * Adds/updates the search index for the given page
136000803e56STom N Harris *
136100803e56STom N Harris * Locking is handled internally.
136200803e56STom N Harris *
136300803e56STom N Harris * @param string        $page   name of the page to index
13649b41be24STom N Harris * @param boolean       $verbose    print status messages
1365d041f8dbSMichael Hamann * @param boolean       $force  force reindexing even when the index is up to date
136600803e56STom N Harris * @return boolean              the function completed successfully
136700803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
136800803e56STom N Harris */
1369d041f8dbSMichael Hamannfunction idx_addPage($page, $verbose=false, $force=false) {
13709b41be24STom N Harris    $idxtag = metaFN($page,'.indexed');
1371a23ac4d7SMichael Hamann    // check if page was deleted but is still in the index
1372bbc85ee4STom N Harris    if (!page_exists($page)) {
1373bbc85ee4STom N Harris        if (!@file_exists($idxtag)) {
1374bbc85ee4STom N Harris            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
1375bbc85ee4STom N Harris            return false;
1376bbc85ee4STom N Harris        }
1377bbc85ee4STom N Harris        $Indexer = idx_get_indexer();
1378bbc85ee4STom N Harris        $result = $Indexer->deletePage($page);
1379bbc85ee4STom N Harris        if ($result === "locked") {
1380bbc85ee4STom N Harris            if ($verbose) print("Indexer: locked".DOKU_LF);
1381bbc85ee4STom N Harris            return false;
1382bbc85ee4STom N Harris        }
1383bbc85ee4STom N Harris        @unlink($idxtag);
1384bbc85ee4STom N Harris        return $result;
1385bbc85ee4STom N Harris    }
1386a23ac4d7SMichael Hamann
1387a23ac4d7SMichael Hamann    // check if indexing needed
1388a23ac4d7SMichael Hamann    if(!$force && @file_exists($idxtag)){
1389a23ac4d7SMichael Hamann        if(trim(io_readFile($idxtag)) == idx_get_version()){
1390a23ac4d7SMichael Hamann            $last = @filemtime($idxtag);
1391a23ac4d7SMichael Hamann            if($last > @filemtime(wikiFN($page))){
1392a23ac4d7SMichael Hamann                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
1393a23ac4d7SMichael Hamann                return false;
1394a23ac4d7SMichael Hamann            }
1395a23ac4d7SMichael Hamann        }
1396a23ac4d7SMichael Hamann    }
1397a23ac4d7SMichael Hamann
139865aa8490SMichael Hamann    $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED);
1399bbc85ee4STom N Harris    if ($indexenabled === false) {
1400bbc85ee4STom N Harris        $result = false;
1401bbc85ee4STom N Harris        if (@file_exists($idxtag)) {
1402bbc85ee4STom N Harris            $Indexer = idx_get_indexer();
1403bbc85ee4STom N Harris            $result = $Indexer->deletePage($page);
1404bbc85ee4STom N Harris            if ($result === "locked") {
1405bbc85ee4STom N Harris                if ($verbose) print("Indexer: locked".DOKU_LF);
1406bbc85ee4STom N Harris                return false;
1407bbc85ee4STom N Harris            }
1408bbc85ee4STom N Harris            @unlink($idxtag);
1409bbc85ee4STom N Harris        }
1410bbc85ee4STom N Harris        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
1411bbc85ee4STom N Harris        return $result;
1412bbc85ee4STom N Harris    }
1413bbc85ee4STom N Harris
141403aafe1cSMichael Hamann    $Indexer = idx_get_indexer();
141503aafe1cSMichael Hamann    $pid = $Indexer->getPID($page);
141603aafe1cSMichael Hamann    if ($pid === false) {
141703aafe1cSMichael Hamann        if ($verbose) print("Indexer: getting the PID failed for $page".DOKU_LF);
141803aafe1cSMichael Hamann        return false;
141903aafe1cSMichael Hamann    }
142000803e56STom N Harris    $body = '';
142139d6fd30SMichael Hamann    $metadata = array();
142265aa8490SMichael Hamann    $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED);
142365aa8490SMichael Hamann    if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null)
142439d6fd30SMichael Hamann        $metadata['relation_references'] = array_keys($references);
1425a424180eSMichael Hamann    else
1426a424180eSMichael Hamann        $metadata['relation_references'] = array();
142703aafe1cSMichael Hamann    $data = compact('page', 'body', 'metadata', 'pid');
142800803e56STom N Harris    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
142939d6fd30SMichael Hamann    if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page);
143000803e56STom N Harris    $evt->advise_after();
143100803e56STom N Harris    unset($evt);
143239d6fd30SMichael Hamann    extract($data);
143300803e56STom N Harris
14349b41be24STom N Harris    $result = $Indexer->addPageWords($page, $body);
1435e1e1a7e0SMichael Hamann    if ($result === "locked") {
14369b41be24STom N Harris        if ($verbose) print("Indexer: locked".DOKU_LF);
14379b41be24STom N Harris        return false;
14389b41be24STom N Harris    }
1439320f489aSMichael Hamann
1440320f489aSMichael Hamann    if ($result) {
144139d6fd30SMichael Hamann        $result = $Indexer->addMetaKeys($page, $metadata);
1442320f489aSMichael Hamann        if ($result === "locked") {
1443320f489aSMichael Hamann            if ($verbose) print("Indexer: locked".DOKU_LF);
1444320f489aSMichael Hamann            return false;
1445320f489aSMichael Hamann        }
1446320f489aSMichael Hamann    }
1447320f489aSMichael Hamann
14489b41be24STom N Harris    if ($result)
14499b41be24STom N Harris        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
14509b41be24STom N Harris    if ($verbose) {
14519b41be24STom N Harris        print("Indexer: finished".DOKU_LF);
14529b41be24STom N Harris        return true;
14539b41be24STom N Harris    }
14549b41be24STom N Harris    return $result;
145500803e56STom N Harris}
145600803e56STom N Harris
145700803e56STom N Harris/**
145800803e56STom N Harris * Find tokens in the fulltext index
145900803e56STom N Harris *
146000803e56STom N Harris * Takes an array of words and will return a list of matching
146100803e56STom N Harris * pages for each one.
1462488dd6ceSAndreas Gohr *
146363773904SAndreas Gohr * Important: No ACL checking is done here! All results are
146463773904SAndreas Gohr *            returned, regardless of permissions
146563773904SAndreas Gohr *
1466e3ab6fc5SMichael Hamann * @param array      $words  list of words to search for
146700803e56STom N Harris * @return array             list of pages found, associated with the search terms
1468488dd6ceSAndreas Gohr */
14699b41be24STom N Harrisfunction idx_lookup(&$words) {
14709b41be24STom N Harris    $Indexer = idx_get_indexer();
147100803e56STom N Harris    return $Indexer->lookup($words);
1472488dd6ceSAndreas Gohr}
1473488dd6ceSAndreas Gohr
1474488dd6ceSAndreas Gohr/**
147500803e56STom N Harris * Split a string into tokens
1476488dd6ceSAndreas Gohr *
1477488dd6ceSAndreas Gohr */
147800803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) {
14799b41be24STom N Harris    $Indexer = idx_get_indexer();
148000803e56STom N Harris    return $Indexer->tokenizer($string, $wc);
1481488dd6ceSAndreas Gohr}
148200803e56STom N Harris
148300803e56STom N Harris/* For compatibility */
1484488dd6ceSAndreas Gohr
1485f5eb7cf0SAndreas Gohr/**
148600803e56STom N Harris * Read the list of words in an index (if it exists).
1487f5eb7cf0SAndreas Gohr *
14884e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
1489f5eb7cf0SAndreas Gohr */
149000803e56STom N Harrisfunction idx_getIndex($idx, $suffix) {
14911c07b9e6STom N Harris    global $conf;
149200803e56STom N Harris    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
149300803e56STom N Harris    if (!@file_exists($fn)) return array();
149400803e56STom N Harris    return file($fn);
149500803e56STom N Harris}
1496f5eb7cf0SAndreas Gohr
149700803e56STom N Harris/**
149800803e56STom N Harris * Get the list of lengths indexed in the wiki.
149900803e56STom N Harris *
150000803e56STom N Harris * Read the index directory or a cache file and returns
150100803e56STom N Harris * a sorted array of lengths of the words used in the wiki.
150200803e56STom N Harris *
150300803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
150400803e56STom N Harris */
150500803e56STom N Harrisfunction idx_listIndexLengths() {
150600803e56STom N Harris    global $conf;
150700803e56STom N Harris    // testing what we have to do, create a cache file or not.
150800803e56STom N Harris    if ($conf['readdircache'] == 0) {
150900803e56STom N Harris        $docache = false;
15101c07b9e6STom N Harris    } else {
151100803e56STom N Harris        clearstatcache();
151200803e56STom N Harris        if (@file_exists($conf['indexdir'].'/lengths.idx')
151300803e56STom N Harris        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
151400803e56STom N Harris            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
151500803e56STom N Harris                $idx = array();
151600803e56STom N Harris                foreach ($lengths as $length) {
151700803e56STom N Harris                    $idx[] = (int)$length;
151800803e56STom N Harris                }
151900803e56STom N Harris                return $idx;
1520f5eb7cf0SAndreas Gohr            }
15211c07b9e6STom N Harris        }
152200803e56STom N Harris        $docache = true;
152300803e56STom N Harris    }
15244e1bf408STom N Harris
152500803e56STom N Harris    if ($conf['readdircache'] == 0 || $docache) {
152600803e56STom N Harris        $dir = @opendir($conf['indexdir']);
152700803e56STom N Harris        if ($dir === false)
152800803e56STom N Harris            return array();
152926f7dbf5SMichael Hamann        $idx = array();
153000803e56STom N Harris        while (($f = readdir($dir)) !== false) {
153100803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
153200803e56STom N Harris                $i = substr($f, 1, -4);
153300803e56STom N Harris                if (is_numeric($i))
153400803e56STom N Harris                    $idx[] = (int)$i;
153500803e56STom N Harris            }
153600803e56STom N Harris        }
153700803e56STom N Harris        closedir($dir);
153800803e56STom N Harris        sort($idx);
153900803e56STom N Harris        // save this in a file
154000803e56STom N Harris        if ($docache) {
154100803e56STom N Harris            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
154200803e56STom N Harris            @fwrite($handle, implode("\n", $idx));
154300803e56STom N Harris            @fclose($handle);
154400803e56STom N Harris        }
154500803e56STom N Harris        return $idx;
154600803e56STom N Harris    }
154700803e56STom N Harris
154800803e56STom N Harris    return array();
154900803e56STom N Harris}
155000803e56STom N Harris
155100803e56STom N Harris/**
155200803e56STom N Harris * Get the word lengths that have been indexed.
155300803e56STom N Harris *
155400803e56STom N Harris * Reads the index directory and returns an array of lengths
155500803e56STom N Harris * that there are indices for.
155600803e56STom N Harris *
155700803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
155800803e56STom N Harris */
155900803e56STom N Harrisfunction idx_indexLengths($filter) {
156000803e56STom N Harris    global $conf;
156100803e56STom N Harris    $idx = array();
156200803e56STom N Harris    if (is_array($filter)) {
156300803e56STom N Harris        // testing if index files exist only
156400803e56STom N Harris        $path = $conf['indexdir']."/i";
156500803e56STom N Harris        foreach ($filter as $key => $value) {
156600803e56STom N Harris            if (@file_exists($path.$key.'.idx'))
156700803e56STom N Harris                $idx[] = $key;
156800803e56STom N Harris        }
1569f5eb7cf0SAndreas Gohr    } else {
157000803e56STom N Harris        $lengths = idx_listIndexLengths();
157100803e56STom N Harris        foreach ($lengths as $key => $length) {
157200803e56STom N Harris            // keep all the values equal or superior
157300803e56STom N Harris            if ((int)$length >= (int)$filter)
157400803e56STom N Harris                $idx[] = $length;
1575f5eb7cf0SAndreas Gohr        }
157600803e56STom N Harris    }
157700803e56STom N Harris    return $idx;
1578f5eb7cf0SAndreas Gohr}
1579f5eb7cf0SAndreas Gohr
158000803e56STom N Harris/**
158100803e56STom N Harris * Clean a name of a key for use as a file name.
158200803e56STom N Harris *
158300803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's
158400803e56STom N Harris * not a letter, number, or underscore.
158500803e56STom N Harris *
158600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
158700803e56STom N Harris */
158800803e56STom N Harrisfunction idx_cleanName($name) {
158900803e56STom N Harris    $name = utf8_romanize(trim((string)$name));
159000803e56STom N Harris    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
159100803e56STom N Harris    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
159200803e56STom N Harris    return strtolower($name);
1593f5eb7cf0SAndreas Gohr}
1594f5eb7cf0SAndreas Gohr
159500803e56STom N Harris//Setup VIM: ex: et ts=4 :
1596