xref: /dokuwiki/inc/indexer.php (revision 0604da3403f907227d3dfe13e6e58d2e78d0c855)
1b4ce25e9SAndreas Gohr<?php
2b4ce25e9SAndreas Gohr/**
3fcd3bb7cSAndreas Gohr * Functions to create the fulltext search index
4b4ce25e9SAndreas Gohr *
5b4ce25e9SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6b4ce25e9SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
700803e56STom N Harris * @author     Tom N Harris <tnharris@whoopdedo.org>
8b4ce25e9SAndreas Gohr */
9b4ce25e9SAndreas Gohr
10fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
11b4ce25e9SAndreas Gohr
127c2ef4e8STom N Harris// Version tag used to force rebuild on upgrade
1300803e56STom N Harrisdefine('INDEXER_VERSION', 3);
147c2ef4e8STom N Harris
1533815ce2SChris Smith// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens)
16d3fb3219SAndreas Gohrif (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2);
1733815ce2SChris Smith
1893a60ad2SAndreas Gohr// Asian characters are handled as words. The following regexp defines the
1993a60ad2SAndreas Gohr// Unicode-Ranges for Asian characters
2093a60ad2SAndreas Gohr// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
2193a60ad2SAndreas Gohr// I'm no language expert. If you think some ranges are wrongly chosen or
2293a60ad2SAndreas Gohr// a range is missing, please contact me
23d5b23302STom N Harrisdefine('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
24d5b23302STom N Harrisdefine('IDX_ASIAN2','['.
25d5b23302STom N Harris                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
26d5b23302STom N Harris                   '\x{309D}-\x{30A0}'.
27a0c5c349STom N Harris                   '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'.
2893a60ad2SAndreas Gohr                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
2993a60ad2SAndreas Gohr                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
3093a60ad2SAndreas Gohr                   ']');
31d5b23302STom N Harrisdefine('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
32d5b23302STom N Harris                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
33d5b23302STom N Harris                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
34d5b23302STom N Harris                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
35d5b23302STom N Harris                   '\x{308F}-\x{3094}'.
36d5b23302STom N Harris                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
37d5b23302STom N Harris                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
38d5b23302STom N Harris                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
39d5b23302STom N Harris                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
40d5b23302STom N Harris                   ']['.
41d5b23302STom N Harris                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
42d5b23302STom N Harris                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
43d5b23302STom N Harris                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
44d5b23302STom N Harris                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
45d5b23302STom N Harris                   '\x{31F0}-\x{31FF}'.
46d5b23302STom N Harris                   ']?');
47699b8a0bSAndreas Gohrdefine('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
4893a60ad2SAndreas Gohr
49b4ce25e9SAndreas Gohr/**
507c2ef4e8STom N Harris * Version of the indexer taking into consideration the external tokenizer.
517c2ef4e8STom N Harris * The indexer is only compatible with data written by the same version.
527c2ef4e8STom N Harris *
537c2ef4e8STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
548605afb1SMichael Hamann * @author Michael Hamann <michael@content-space.de>
557c2ef4e8STom N Harris */
567c2ef4e8STom N Harrisfunction idx_get_version(){
577c2ef4e8STom N Harris    global $conf;
587c2ef4e8STom N Harris    if($conf['external_tokenizer'])
598605afb1SMichael Hamann        $version = INDEXER_VERSION . '+' . trim($conf['tokenizer_cmd']);
607c2ef4e8STom N Harris    else
618605afb1SMichael Hamann        $version = INDEXER_VERSION;
628605afb1SMichael Hamann
638605afb1SMichael Hamann    $data = array($version);
648605afb1SMichael Hamann    trigger_event('INDEXER_VERSION_GET', $data, null, false);
658605afb1SMichael Hamann    return implode('+', $data);
667c2ef4e8STom N Harris}
677c2ef4e8STom N Harris
687c2ef4e8STom N Harris/**
69d5b23302STom N Harris * Measure the length of a string.
70d5b23302STom N Harris * Differs from strlen in handling of asian characters.
71d5b23302STom N Harris *
72d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
73d5b23302STom N Harris */
74d5b23302STom N Harrisfunction wordlen($w){
75d5b23302STom N Harris    $l = strlen($w);
76d5b23302STom N Harris    // If left alone, all chinese "words" will get put into w3.idx
77d5b23302STom N Harris    // So the "length" of a "word" is faked
784b9792c6STom N Harris    if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) {
794b9792c6STom N Harris        foreach($leadbytes[0] as $b)
804b9792c6STom N Harris            $l += ord($b) - 0xE1;
814b9792c6STom N Harris    }
82d5b23302STom N Harris    return $l;
83d5b23302STom N Harris}
84d5b23302STom N Harris
85d5b23302STom N Harris/**
8600803e56STom N Harris * Class that encapsulates operations on the indexer database.
87579b0f7eSTNHarris *
88579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
89579b0f7eSTNHarris */
9000803e56STom N Harrisclass Doku_Indexer {
91579b0f7eSTNHarris
92579b0f7eSTNHarris    /**
9300803e56STom N Harris     * Adds the contents of a page to the fulltext index
94dd35e9c9SAndreas Gohr     *
9500803e56STom N Harris     * The added text replaces previous words for the same page.
9600803e56STom N Harris     * An empty value erases the page.
9700803e56STom N Harris     *
9800803e56STom N Harris     * @param string    $page   a page name
9900803e56STom N Harris     * @param string    $text   the body of the page
10000803e56STom N Harris     * @return boolean          the function completed successfully
10100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
102dd35e9c9SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
103dd35e9c9SAndreas Gohr     */
10400803e56STom N Harris    public function addPageWords($page, $text) {
1059b41be24STom N Harris        if (!$this->_lock())
1069b41be24STom N Harris            return "locked";
10700803e56STom N Harris
10800803e56STom N Harris        // load known documents
10900803e56STom N Harris        $page_idx = $this->_addIndexKey('page', '', $page);
11000803e56STom N Harris        if ($page_idx === false) {
11100803e56STom N Harris            $this->_unlock();
11200803e56STom N Harris            return false;
11300803e56STom N Harris        }
11400803e56STom N Harris
11500803e56STom N Harris        $pagewords = array();
11600803e56STom N Harris        // get word usage in page
11700803e56STom N Harris        $words = $this->_getPageWords($text);
11800803e56STom N Harris        if ($words === false) {
11900803e56STom N Harris            $this->_unlock();
12000803e56STom N Harris            return false;
12100803e56STom N Harris        }
12200803e56STom N Harris
12300803e56STom N Harris        if (!empty($words)) {
12400803e56STom N Harris            foreach (array_keys($words) as $wlen) {
12500803e56STom N Harris                $index = $this->_getIndex('i', $wlen);
12600803e56STom N Harris                foreach ($words[$wlen] as $wid => $freq) {
12700803e56STom N Harris                    $idx = ($wid<count($index)) ? $index[$wid] : '';
12800803e56STom N Harris                    $index[$wid] = $this->_updateTuple($idx, $pid, $freq);
12900803e56STom N Harris                    $pagewords[] = "$wlen*$wid";
13000803e56STom N Harris                }
13100803e56STom N Harris                if (!$this->_saveIndex('i', $wlen, $index)) {
13200803e56STom N Harris                    $this->_unlock();
13300803e56STom N Harris                    return false;
13400803e56STom N Harris                }
13500803e56STom N Harris            }
13600803e56STom N Harris        }
13700803e56STom N Harris
13800803e56STom N Harris        // Remove obsolete index entries
13900803e56STom N Harris        $pageword_idx = $this->_getIndexKey('pageword', '', $pid);
14000803e56STom N Harris        if ($pageword_idx !== '') {
14100803e56STom N Harris            $oldwords = explode(':',$pageword_idx);
14200803e56STom N Harris            $delwords = array_diff($oldwords, $pagewords);
14300803e56STom N Harris            $upwords = array();
14400803e56STom N Harris            foreach ($delwords as $word) {
14500803e56STom N Harris                if ($word != '') {
14600803e56STom N Harris                    list($wlen,$wid) = explode('*', $word);
14700803e56STom N Harris                    $wid = (int)$wid;
14800803e56STom N Harris                    $upwords[$wlen][] = $wid;
14900803e56STom N Harris                }
15000803e56STom N Harris            }
15100803e56STom N Harris            foreach ($upwords as $wlen => $widx) {
15200803e56STom N Harris                $index = $this->_getIndex('i', $wlen);
15300803e56STom N Harris                foreach ($widx as $wid) {
15400803e56STom N Harris                    $index[$wid] = $this->_updateTuple($index[$wid], $pid, 0);
15500803e56STom N Harris                }
15600803e56STom N Harris                $this->_saveIndex('i', $wlen, $index);
15700803e56STom N Harris            }
15800803e56STom N Harris        }
15900803e56STom N Harris        // Save the reverse index
16000803e56STom N Harris        $pageword_idx = join(':', $pagewords);
16100803e56STom N Harris        if (!$this->_saveIndexKey('pageword', '', $pid, $pageword_idx)) {
16200803e56STom N Harris            $this->_unlock();
16300803e56STom N Harris            return false;
16400803e56STom N Harris        }
16500803e56STom N Harris
16600803e56STom N Harris        $this->_unlock();
167dd35e9c9SAndreas Gohr        return true;
168dd35e9c9SAndreas Gohr    }
169dd35e9c9SAndreas Gohr
170dd35e9c9SAndreas Gohr    /**
17100803e56STom N Harris     * Split the words in a page and add them to the index.
17244ca0adfSAndreas Gohr     *
17344ca0adfSAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
17417f42b01SChris Smith     * @author Christopher Smith <chris@jalakai.co.uk>
17500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
176b4ce25e9SAndreas Gohr     */
17700803e56STom N Harris    private function _getPageWords($text) {
17844ca0adfSAndreas Gohr        global $conf;
17944ca0adfSAndreas Gohr
18000803e56STom N Harris        $tokens = $this->tokenizer($text);
18117f42b01SChris Smith        $tokens = array_count_values($tokens);  // count the frequency of each token
18217f42b01SChris Smith
18317f42b01SChris Smith        $words = array();
1844e1bf408STom N Harris        foreach ($tokens as $w=>$c) {
185d5b23302STom N Harris            $l = wordlen($w);
186579b0f7eSTNHarris            if (isset($words[$l])){
1874e1bf408STom N Harris                $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
18817f42b01SChris Smith            }else{
1894e1bf408STom N Harris                $words[$l] = array($w => $c);
19017f42b01SChris Smith            }
19117f42b01SChris Smith        }
19217f42b01SChris Smith
193579b0f7eSTNHarris        // arrive here with $words = array(wordlen => array(word => frequency))
194e5e50383SMichael Hamann        $word_idx_modified = false;
195b4ce25e9SAndreas Gohr        $index = array();   //resulting index
196579b0f7eSTNHarris        foreach (array_keys($words) as $wlen) {
19700803e56STom N Harris            $word_idx = $this->_getIndex('w', $wlen);
198579b0f7eSTNHarris            foreach ($words[$wlen] as $word => $freq) {
19900803e56STom N Harris                $wid = array_search($word, $word_idx);
20000803e56STom N Harris                if ($wid === false) {
201d5b23302STom N Harris                    $wid = count($word_idx);
20200803e56STom N Harris                    $word_idx[] = $word;
203e5e50383SMichael Hamann                    $word_idx_modified = true;
204b4ce25e9SAndreas Gohr                }
205579b0f7eSTNHarris                if (!isset($index[$wlen]))
206579b0f7eSTNHarris                    $index[$wlen] = array();
207579b0f7eSTNHarris                $index[$wlen][$wid] = $freq;
20844ca0adfSAndreas Gohr            }
20900803e56STom N Harris            // save back the word index
21000803e56STom N Harris            if ($word_idx_modified && !$this->_saveIndex('w', $wlen, $word_idx))
21144ca0adfSAndreas Gohr                return false;
21244ca0adfSAndreas Gohr        }
213b4ce25e9SAndreas Gohr
214b4ce25e9SAndreas Gohr        return $index;
215b4ce25e9SAndreas Gohr    }
216b4ce25e9SAndreas Gohr
21744ca0adfSAndreas Gohr    /**
218e1e1a7e0SMichael Hamann     * Add/update keys to/of the metadata index.
21944ca0adfSAndreas Gohr     *
22000803e56STom N Harris     * Adding new keys does not remove other keys for the page.
22100803e56STom N Harris     * An empty value will erase the key.
22200803e56STom N Harris     * The $key parameter can be an array to add multiple keys. $value will
22300803e56STom N Harris     * not be used if $key is an array.
22444ca0adfSAndreas Gohr     *
22500803e56STom N Harris     * @param string    $page   a page name
22600803e56STom N Harris     * @param mixed     $key    a key string or array of key=>value pairs
22700803e56STom N Harris     * @param mixed     $value  the value or list of values
22800803e56STom N Harris     * @return boolean          the function completed successfully
22900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
230e1e1a7e0SMichael Hamann     * @author Michael Hamann <michael@content-space.de>
23144ca0adfSAndreas Gohr     */
23200803e56STom N Harris    public function addMetaKeys($page, $key, $value=null) {
23300803e56STom N Harris        if (!is_array($key)) {
23400803e56STom N Harris            $key = array($key => $value);
23500803e56STom N Harris        } elseif (!is_null($value)) {
23600803e56STom N Harris            // $key is array, but $value is not null
23700803e56STom N Harris            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
23800803e56STom N Harris        }
23900803e56STom N Harris
240e1e1a7e0SMichael Hamann        if (!$this->_lock())
241e1e1a7e0SMichael Hamann            return "locked";
242b4ce25e9SAndreas Gohr
243488dd6ceSAndreas Gohr        // load known documents
24400803e56STom N Harris        $pid = $this->_addIndexKey('page', '', $page);
24500803e56STom N Harris        if ($pid === false) {
24600803e56STom N Harris            $this->_unlock();
247579b0f7eSTNHarris            return false;
24844ca0adfSAndreas Gohr        }
24900803e56STom N Harris
250c1209673STom N Harris        // Special handling for titles so the index file is simpler
251c1209673STom N Harris        if (array_key_exists('title', $key)) {
252c1209673STom N Harris            $value = $key['title'];
253c1209673STom N Harris            if (is_array($value))
254c1209673STom N Harris                $value = $value[0];
255c1209673STom N Harris            $this->_saveIndexKey('title', '', $pid, $value);
256c1209673STom N Harris            unset($key['title']);
257c1209673STom N Harris        }
258c1209673STom N Harris
25900803e56STom N Harris        foreach ($key as $name => $values) {
26000803e56STom N Harris            $metaname = idx_cleanName($name);
261*0604da34STom N Harris            $this->_addIndexKey('metadata', '', $metaname);
26200803e56STom N Harris            $metaidx = $this->_getIndex($metaname, '_i');
26300803e56STom N Harris            $metawords = $this->_getIndex($metaname, '_w');
26400803e56STom N Harris            $addwords = false;
265e1e1a7e0SMichael Hamann
266e1e1a7e0SMichael Hamann            if (!is_array($values)) $values = array($values);
267e1e1a7e0SMichael Hamann
268e1e1a7e0SMichael Hamann            $val_idx = $this->_getIndexKey($metaname, '_p', $pid);
269e1e1a7e0SMichael Hamann            if ($val_idx != '') {
270e1e1a7e0SMichael Hamann                $val_idx = explode(':', $val_idx);
271e1e1a7e0SMichael Hamann                // -1 means remove, 0 keep, 1 add
272e1e1a7e0SMichael Hamann                $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
273e1e1a7e0SMichael Hamann            } else {
274e1e1a7e0SMichael Hamann                $val_idx = array();
275e1e1a7e0SMichael Hamann            }
276e1e1a7e0SMichael Hamann
277e1e1a7e0SMichael Hamann
27800803e56STom N Harris            foreach ($values as $val) {
27900803e56STom N Harris                $val = (string)$val;
28000803e56STom N Harris                if ($val !== "") {
28100803e56STom N Harris                    $id = array_search($val, $metawords);
28200803e56STom N Harris                    if ($id === false) {
28300803e56STom N Harris                        $id = count($metawords);
28400803e56STom N Harris                        $metawords[$id] = $val;
28500803e56STom N Harris                        $addwords = true;
286d5b23302STom N Harris                    }
287e1e1a7e0SMichael Hamann                    // test if value is already in the index
288e1e1a7e0SMichael Hamann                    if (isset($val_idx[$id]) && $val_idx[$id] <= 0)
289e1e1a7e0SMichael Hamann                        $val_idx[$id] = 0;
290e1e1a7e0SMichael Hamann                    else // else add it
291e1e1a7e0SMichael Hamann                        $val_idx[$id] = 1;
29244ca0adfSAndreas Gohr                }
293579b0f7eSTNHarris            }
294e1e1a7e0SMichael Hamann
29500803e56STom N Harris            if ($addwords)
29600803e56STom N Harris                $this->_saveIndex($metaname.'_w', '', $metawords);
297e1e1a7e0SMichael Hamann            $vals_changed = false;
298e1e1a7e0SMichael Hamann            foreach ($val_idx as $id => $action) {
299e1e1a7e0SMichael Hamann                if ($action == -1) {
300e1e1a7e0SMichael Hamann                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 0);
301e1e1a7e0SMichael Hamann                    $vals_changed = true;
302e1e1a7e0SMichael Hamann                    unset($val_idx[$id]);
303e1e1a7e0SMichael Hamann                } elseif ($action == 1) {
304e1e1a7e0SMichael Hamann                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 1);
305e1e1a7e0SMichael Hamann                    $vals_changed = true;
306e1e1a7e0SMichael Hamann                }
307e1e1a7e0SMichael Hamann            }
308e1e1a7e0SMichael Hamann
309e1e1a7e0SMichael Hamann            if ($vals_changed) {
31000803e56STom N Harris                $this->_saveIndex($metaname.'_i', '', $metaidx);
311e1e1a7e0SMichael Hamann                $val_idx = implode(':', array_keys($val_idx));
312e1e1a7e0SMichael Hamann                $this->_saveIndexKey($metaname.'_p', '', $pid, $val_idx);
313b6344591STom N Harris            }
314e1e1a7e0SMichael Hamann
31500803e56STom N Harris            unset($metaidx);
31600803e56STom N Harris            unset($metawords);
317a0c5c349STom N Harris        }
318e1e1a7e0SMichael Hamann
319e1e1a7e0SMichael Hamann        $this->_unlock();
320579b0f7eSTNHarris        return true;
32144ca0adfSAndreas Gohr    }
32244ca0adfSAndreas Gohr
32344ca0adfSAndreas Gohr    /**
32400803e56STom N Harris     * Remove a page from the index
32544ca0adfSAndreas Gohr     *
32600803e56STom N Harris     * Erases entries in all known indexes.
32744ca0adfSAndreas Gohr     *
32800803e56STom N Harris     * @param string    $page   a page name
32900803e56STom N Harris     * @return boolean          the function completed successfully
33000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
33144ca0adfSAndreas Gohr     */
33200803e56STom N Harris    public function deletePage($page) {
333bbc85ee4STom N Harris        if (!$this->_lock())
334bbc85ee4STom N Harris            return "locked";
335bbc85ee4STom N Harris
336bbc85ee4STom N Harris        // load known documents
337bbc85ee4STom N Harris        $page_idx = $this->_getIndexKey('page', '', $page);
338bbc85ee4STom N Harris        if ($page_idx === false) {
339bbc85ee4STom N Harris            $this->_unlock();
340bbc85ee4STom N Harris            return false;
341bbc85ee4STom N Harris        }
342bbc85ee4STom N Harris
343bbc85ee4STom N Harris        // Remove obsolete index entries
344bbc85ee4STom N Harris        $pageword_idx = $this->_getIndexKey('pageword', '', $pid);
345bbc85ee4STom N Harris        if ($pageword_idx !== '') {
346bbc85ee4STom N Harris            $delwords = explode(':',$pageword_idx);
347bbc85ee4STom N Harris            $upwords = array();
348bbc85ee4STom N Harris            foreach ($delwords as $word) {
349bbc85ee4STom N Harris                if ($word != '') {
350bbc85ee4STom N Harris                    list($wlen,$wid) = explode('*', $word);
351bbc85ee4STom N Harris                    $wid = (int)$wid;
352bbc85ee4STom N Harris                    $upwords[$wlen][] = $wid;
353bbc85ee4STom N Harris                }
354bbc85ee4STom N Harris            }
355bbc85ee4STom N Harris            foreach ($upwords as $wlen => $widx) {
356bbc85ee4STom N Harris                $index = $this->_getIndex('i', $wlen);
357bbc85ee4STom N Harris                foreach ($widx as $wid) {
358bbc85ee4STom N Harris                    $index[$wid] = $this->_updateTuple($index[$wid], $pid, 0);
359bbc85ee4STom N Harris                }
360bbc85ee4STom N Harris                $this->_saveIndex('i', $wlen, $index);
361bbc85ee4STom N Harris            }
362bbc85ee4STom N Harris        }
363bbc85ee4STom N Harris        // Save the reverse index
364bbc85ee4STom N Harris        if (!$this->_saveIndexKey('pageword', '', $pid, "")) {
365bbc85ee4STom N Harris            $this->_unlock();
366bbc85ee4STom N Harris            return false;
367bbc85ee4STom N Harris        }
368bbc85ee4STom N Harris
369c1209673STom N Harris        $this->_saveIndexKey('title', '', $pid, "");
370*0604da34STom N Harris        $keyidx = $this->_getIndex('metadata', '');
371*0604da34STom N Harris        foreach ($keyidx as $metaname) {
372*0604da34STom N Harris            $val_idx = explode(':', $this->_getIndexKey($metaname.'_p', '', $pid));
373*0604da34STom N Harris            $meta_idx = $this->_getIndex($metaname.'_i', '');
374*0604da34STom N Harris            foreach ($val_idx as $id) {
375*0604da34STom N Harris                $meta_idx[$id] = $this->_updateTuple($meta_idx[$id], $pid, 0);
376*0604da34STom N Harris            }
377*0604da34STom N Harris            $this->_saveIndex($metaname.'_i', '', $meta_idx);
378*0604da34STom N Harris            $this->_saveIndexKey($metaname.'_p', '', $pid, '');
379*0604da34STom N Harris        }
380bbc85ee4STom N Harris
381bbc85ee4STom N Harris        $this->_unlock();
382bbc85ee4STom N Harris        return true;
383d5b23302STom N Harris    }
38444ca0adfSAndreas Gohr
385d5b23302STom N Harris    /**
38600803e56STom N Harris     * Split the text into words for fulltext search
387d5b23302STom N Harris     *
38800803e56STom N Harris     * TODO: does this also need &$stopwords ?
389d5b23302STom N Harris     *
39000803e56STom N Harris     * @param string    $text   plain text
39100803e56STom N Harris     * @param boolean   $wc     are wildcards allowed?
39200803e56STom N Harris     * @return array            list of words in the text
393d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
394d5b23302STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
395d5b23302STom N Harris     */
39600803e56STom N Harris    public function tokenizer($text, $wc=false) {
39722952965SYoBoY        global $conf;
39800803e56STom N Harris        $words = array();
39900803e56STom N Harris        $wc = ($wc) ? '' : '\*';
40000803e56STom N Harris        $stopwords =& idx_get_stopwords();
40100803e56STom N Harris
40200803e56STom N Harris        if ($conf['external_tokenizer'] && $conf['tokenizer_cmd'] != '') {
40300803e56STom N Harris            if (0 == io_exec($conf['tokenizer_cmd'], $text, $output))
40400803e56STom N Harris                $text = $output;
40522952965SYoBoY        } else {
40600803e56STom N Harris            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
40700803e56STom N Harris                // handle asian chars as single words (may fail on older PHP version)
40800803e56STom N Harris                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
40900803e56STom N Harris                if (!is_null($asia)) $text = $asia; // recover from regexp falure
41022952965SYoBoY            }
41122952965SYoBoY        }
41200803e56STom N Harris        $text = strtr($text, "\r\n\t", '   ');
41300803e56STom N Harris        if (preg_match('/[^0-9A-Za-z ]/u', $text))
41400803e56STom N Harris            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
41522952965SYoBoY
41600803e56STom N Harris        $wordlist = explode(' ', $text);
41700803e56STom N Harris        foreach ($wordlist as $word) {
41800803e56STom N Harris            $word = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
41900803e56STom N Harris                utf8_strtolower($word) : strtolower($word);
42000803e56STom N Harris            if (!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) continue;
42100803e56STom N Harris            if (array_search($word, $stopwords) !== false) continue;
42200803e56STom N Harris            $words[] = $word;
42322952965SYoBoY        }
42400803e56STom N Harris        return $words;
42522952965SYoBoY    }
42622952965SYoBoY
42722952965SYoBoY    /**
42800803e56STom N Harris     * Find pages in the fulltext index containing the words,
429579b0f7eSTNHarris     *
43000803e56STom N Harris     * The search words must be pre-tokenized, meaning only letters and
43100803e56STom N Harris     * numbers with an optional wildcard
432579b0f7eSTNHarris     *
43300803e56STom N Harris     * The returned array will have the original tokens as key. The values
43400803e56STom N Harris     * in the returned list is an array with the page names as keys and the
435b00bd361STom N Harris     * number of times that token appears on the page as value.
43600803e56STom N Harris     *
4379b41be24STom N Harris     * @param arrayref  $tokens list of words to search for
43800803e56STom N Harris     * @return array            list of page names with usage counts
43900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
44000803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
441579b0f7eSTNHarris     */
4429b41be24STom N Harris    public function lookup(&$tokens) {
44300803e56STom N Harris        $result = array();
44400803e56STom N Harris        $wids = $this->_getIndexWords($tokens, $result);
44500803e56STom N Harris        if (empty($wids)) return array();
44600803e56STom N Harris        // load known words and documents
44700803e56STom N Harris        $page_idx = $this->_getIndex('page', '');
44800803e56STom N Harris        $docs = array();
44900803e56STom N Harris        foreach (array_keys($wids) as $wlen) {
45000803e56STom N Harris            $wids[$wlen] = array_unique($wids[$wlen]);
45100803e56STom N Harris            $index = $this->_getIndex('i', $wlen);
45200803e56STom N Harris            foreach($wids[$wlen] as $ixid) {
45300803e56STom N Harris                if ($ixid < count($index))
45400803e56STom N Harris                    $docs["$wlen*$ixid"] = $this->_parseTuples($page_idx, $index[$ixid]);
455d5b23302STom N Harris            }
456d5b23302STom N Harris        }
45700803e56STom N Harris        // merge found pages into final result array
45800803e56STom N Harris        $final = array();
45900803e56STom N Harris        foreach ($result as $word => $res) {
46000803e56STom N Harris            $final[$word] = array();
46100803e56STom N Harris            foreach ($res as $wid) {
46200803e56STom N Harris                $hits = &$docs[$wid];
46300803e56STom N Harris                foreach ($hits as $hitkey => $hitcnt) {
46400803e56STom N Harris                    // make sure the document still exists
46500803e56STom N Harris                    if (!page_exists($hitkey, '', false)) continue;
46600803e56STom N Harris                    if (!isset($final[$word][$hitkey]))
46700803e56STom N Harris                        $final[$word][$hitkey] = $hitcnt;
46800803e56STom N Harris                    else
46900803e56STom N Harris                        $final[$word][$hitkey] += $hitcnt;
470d5b23302STom N Harris                }
471579b0f7eSTNHarris            }
472579b0f7eSTNHarris        }
47300803e56STom N Harris        return $final;
474579b0f7eSTNHarris    }
475579b0f7eSTNHarris
476579b0f7eSTNHarris    /**
47700803e56STom N Harris     * Find pages containing a metadata key.
478d5b23302STom N Harris     *
47900803e56STom N Harris     * The metadata values are compared as case-sensitive strings. Pass a
48000803e56STom N Harris     * callback function that returns true or false to use a different
481b00bd361STom N Harris     * comparison function. The function will be called with the $value being
482b00bd361STom N Harris     * searched for as the first argument, and the word in the index as the
483b00bd361STom N Harris     * second argument.
484d5b23302STom N Harris     *
48500803e56STom N Harris     * @param string    $key    name of the metadata key to look for
48600803e56STom N Harris     * @param string    $value  search term to look for
48700803e56STom N Harris     * @param callback  $func   comparison function
488b00bd361STom N Harris     * @return array            lists with page names, keys are query values if $value is array
48900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
490cd763a5bSMichael Hamann     * @author Michael Hamann <michael@content-space.de>
49100803e56STom N Harris     */
492b00bd361STom N Harris    public function lookupKey($key, &$value, $func=null) {
493f078bb00STom N Harris        if (!is_array($value))
494f078bb00STom N Harris            $value_array = array($value);
495f078bb00STom N Harris        else
496f078bb00STom N Harris            $value_array =& $value;
497cd763a5bSMichael Hamann
498c1209673STom N Harris        // the matching ids for the provided value(s)
499c1209673STom N Harris        $value_ids = array();
500c1209673STom N Harris
501c1209673STom N Harris        $metaname = idx_cleanName($key);
502c1209673STom N Harris
503c1209673STom N Harris        // get all words in order to search the matching ids
504c1209673STom N Harris        if ($key == 'title') {
505c1209673STom N Harris            $words = $this->_getIndex('title', '');
506c1209673STom N Harris        } else {
507c1209673STom N Harris            $words = $this->_getIndex($metaname, '_w');
508c1209673STom N Harris        }
509c1209673STom N Harris
510f078bb00STom N Harris        if (!is_null($func)) {
511b00bd361STom N Harris            foreach ($value_array as &$val) {
512f078bb00STom N Harris                foreach ($words as $i => $word) {
513b00bd361STom N Harris                    if (call_user_func_array($func, array(&$val, $word)))
514c1209673STom N Harris                        $value_ids[$i][] = $val;
515f078bb00STom N Harris                }
516f078bb00STom N Harris            }
517f078bb00STom N Harris        } else {
518f078bb00STom N Harris            foreach ($value_array as $val) {
519f078bb00STom N Harris                $xval = $val;
520f078bb00STom N Harris                $caret = false;
521f078bb00STom N Harris                $dollar = false;
522f078bb00STom N Harris                // check for wildcards
523f078bb00STom N Harris                if (substr($xval, 0, 1) == '*') {
524f078bb00STom N Harris                    $xval = substr($xval, 1);
525f078bb00STom N Harris                    $caret = '^';
526f078bb00STom N Harris                }
527f078bb00STom N Harris                if (substr($xval, -1, 1) == '*') {
528f078bb00STom N Harris                    $xval = substr($xval, 0, -1);
529f078bb00STom N Harris                    $dollar = '$';
530f078bb00STom N Harris                }
531f078bb00STom N Harris                if ($caret || $dollar) {
532f078bb00STom N Harris                    $re = $caret.preg_quote($xval, '/').$dollar;
533f078bb00STom N Harris                    foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
534c1209673STom N Harris                        $value_ids[$i][] = $val;
535cd763a5bSMichael Hamann                } else {
536f078bb00STom N Harris                    if (($i = array_search($val, $words)) !== false)
537c1209673STom N Harris                        $value_ids[$i][] = $val;
538cd763a5bSMichael Hamann                }
539cd763a5bSMichael Hamann            }
540cd763a5bSMichael Hamann        }
541cd763a5bSMichael Hamann
542cd763a5bSMichael Hamann        unset($words); // free the used memory
543cd763a5bSMichael Hamann
544c1209673STom N Harris        $result = array();
545cd763a5bSMichael Hamann        $page_idx = $this->_getIndex('page', '');
546cd763a5bSMichael Hamann
547c1209673STom N Harris        // Special handling for titles
548c1209673STom N Harris        if ($key == 'title') {
549c1209673STom N Harris            foreach ($value_ids as $pid => $val_list) {
550c1209673STom N Harris                $page = $page_idx[$pid];
551c1209673STom N Harris                foreach ($val_list as $val) {
552c1209673STom N Harris                    $result[$val][] = $page;
553c1209673STom N Harris                }
554c1209673STom N Harris            }
555c1209673STom N Harris        } else {
556c1209673STom N Harris            // load all lines and pages so the used lines can be taken and matched with the pages
557c1209673STom N Harris            $lines = $this->_getIndex($metaname, '_i');
558c1209673STom N Harris
559c1209673STom N Harris            foreach ($value_ids as $value_id => $val_list) {
560cd763a5bSMichael Hamann                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
561cd763a5bSMichael Hamann                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
562c1209673STom N Harris                $pages = array_keys($this->_parseTuples($page_idx, $lines[$value_id]));
563c1209673STom N Harris                foreach ($val_list as $val) {
564c1209673STom N Harris                    if (!isset($result[$val]))
565c1209673STom N Harris                        $result[$val] = $pages;
566c1209673STom N Harris                    else
567c1209673STom N Harris                        $result[$val] = array_merge($result[$val], $pages);
568c1209673STom N Harris                }
569c1209673STom N Harris            }
570cd763a5bSMichael Hamann        }
571f078bb00STom N Harris        if (!is_array($value)) $result = $result[$value];
572cd763a5bSMichael Hamann        return $result;
57300803e56STom N Harris    }
57400803e56STom N Harris
57500803e56STom N Harris    /**
57600803e56STom N Harris     * Find the index ID of each search term.
57700803e56STom N Harris     *
57800803e56STom N Harris     * The query terms should only contain valid characters, with a '*' at
57900803e56STom N Harris     * either the beginning or end of the word (or both).
58000803e56STom N Harris     * The $result parameter can be used to merge the index locations with
58100803e56STom N Harris     * the appropriate query term.
58200803e56STom N Harris     *
5839b41be24STom N Harris     * @param arrayref  $words  The query terms.
58400803e56STom N Harris     * @param arrayref  $result Set to word => array("length*id" ...)
585d5b23302STom N Harris     * @return array            Set to length => array(id ...)
586d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
587d5b23302STom N Harris     */
5889b41be24STom N Harris    private function _getIndexWords(&$words, &$result) {
589d5b23302STom N Harris        $tokens = array();
590d5b23302STom N Harris        $tokenlength = array();
591d5b23302STom N Harris        $tokenwild = array();
592d5b23302STom N Harris        foreach ($words as $word) {
593d5b23302STom N Harris            $result[$word] = array();
59400803e56STom N Harris            $caret = false;
59500803e56STom N Harris            $dollar = false;
596d5b23302STom N Harris            $xword = $word;
597d5b23302STom N Harris            $wlen = wordlen($word);
598d5b23302STom N Harris
599d5b23302STom N Harris            // check for wildcards
600d5b23302STom N Harris            if (substr($xword, 0, 1) == '*') {
601d5b23302STom N Harris                $xword = substr($xword, 1);
602f078bb00STom N Harris                $caret = '^';
603d5b23302STom N Harris                $wlen -= 1;
604d5b23302STom N Harris            }
605d5b23302STom N Harris            if (substr($xword, -1, 1) == '*') {
606d5b23302STom N Harris                $xword = substr($xword, 0, -1);
607f078bb00STom N Harris                $dollar = '$';
608d5b23302STom N Harris                $wlen -= 1;
609d5b23302STom N Harris            }
61000803e56STom N Harris            if ($wlen < IDX_MINWORDLENGTH && !$caret && !$dollar && !is_numeric($xword))
61100803e56STom N Harris                continue;
61200803e56STom N Harris            if (!isset($tokens[$xword]))
613d5b23302STom N Harris                $tokenlength[$wlen][] = $xword;
61400803e56STom N Harris            if ($caret || $dollar) {
615f078bb00STom N Harris                $re = $caret.preg_quote($xword, '/').$dollar;
61600803e56STom N Harris                $tokens[$xword][] = array($word, '/'.$re.'/');
61700803e56STom N Harris                if (!isset($tokenwild[$xword]))
61800803e56STom N Harris                    $tokenwild[$xword] = $wlen;
61900803e56STom N Harris            } else {
620d5b23302STom N Harris                $tokens[$xword][] = array($word, null);
621d5b23302STom N Harris            }
62200803e56STom N Harris        }
623d5b23302STom N Harris        asort($tokenwild);
62400803e56STom N Harris        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
625d5b23302STom N Harris        // $tokenlength = array( base word length => base word ... )
626d5b23302STom N Harris        // $tokenwild = array( base word => base word length ... )
627d5b23302STom N Harris        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
62800803e56STom N Harris        $indexes_known = $this->_indexLengths($length_filter);
629d5b23302STom N Harris        if (!empty($tokenwild)) sort($indexes_known);
630d5b23302STom N Harris        // get word IDs
631d5b23302STom N Harris        $wids = array();
632d5b23302STom N Harris        foreach ($indexes_known as $ixlen) {
63300803e56STom N Harris            $word_idx = $this->_getIndex('w', $ixlen);
634d5b23302STom N Harris            // handle exact search
635d5b23302STom N Harris            if (isset($tokenlength[$ixlen])) {
636d5b23302STom N Harris                foreach ($tokenlength[$ixlen] as $xword) {
63700803e56STom N Harris                    $wid = array_search($xword, $word_idx);
63800803e56STom N Harris                    if ($wid !== false) {
639d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
640d5b23302STom N Harris                        foreach ($tokens[$xword] as $w)
641d5b23302STom N Harris                            $result[$w[0]][] = "$ixlen*$wid";
642d5b23302STom N Harris                    }
643d5b23302STom N Harris                }
644d5b23302STom N Harris            }
645d5b23302STom N Harris            // handle wildcard search
646d5b23302STom N Harris            foreach ($tokenwild as $xword => $wlen) {
647d5b23302STom N Harris                if ($wlen >= $ixlen) break;
648d5b23302STom N Harris                foreach ($tokens[$xword] as $w) {
649d5b23302STom N Harris                    if (is_null($w[1])) continue;
650d5b23302STom N Harris                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
651d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
652d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
653d5b23302STom N Harris                    }
654d5b23302STom N Harris                }
655d5b23302STom N Harris            }
656d5b23302STom N Harris        }
657d5b23302STom N Harris        return $wids;
658d5b23302STom N Harris    }
659d5b23302STom N Harris
660d5b23302STom N Harris    /**
66100803e56STom N Harris     * Return a list of all pages
662c1209673STom N Harris     * Warning: pages may not exist!
663488dd6ceSAndreas Gohr     *
66400803e56STom N Harris     * @param string    $key    list only pages containing the metadata key (optional)
66500803e56STom N Harris     * @return array            list of page names
66600803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
66700803e56STom N Harris     */
66800803e56STom N Harris    public function getPages($key=null) {
66900803e56STom N Harris        $page_idx = $this->_getIndex('page', '');
67000803e56STom N Harris        if (is_null($key)) return $page_idx;
671c1209673STom N Harris
672c1209673STom N Harris        $metaname = idx_cleanName($key);
673c1209673STom N Harris
674c1209673STom N Harris        // Special handling for titles
675c1209673STom N Harris        if ($key == 'title') {
676c1209673STom N Harris            $title_idx = $this->_getIndex('title', '');
677c1209673STom N Harris            array_splice($page_idx, count($title_idx));
678c1209673STom N Harris            foreach ($title_idx as $i => $title)
679c1209673STom N Harris                if ($title === "") unset($page_idx[$i]);
680c1209673STom N Harris            return $page_idx;
681c1209673STom N Harris        }
682c1209673STom N Harris
683c1209673STom N Harris        $pages = array();
684c1209673STom N Harris        $lines = $this->_getIndex($metaname, '_i');
685c1209673STom N Harris        foreach ($lines as $line) {
686c1209673STom N Harris            $pages = array_merge($pages, $this->_parseTuples($page_idx, $line));
687c1209673STom N Harris        }
688c1209673STom N Harris        return array_keys($pages);
68900803e56STom N Harris    }
69000803e56STom N Harris
69100803e56STom N Harris    /**
69200803e56STom N Harris     * Return a list of words sorted by number of times used
69300803e56STom N Harris     *
69400803e56STom N Harris     * @param int       $min    bottom frequency threshold
69500803e56STom N Harris     * @param int       $max    upper frequency limit. No limit if $max<$min
69600803e56STom N Harris     * @param string    $key    metadata key to list. Uses the fulltext index if not given
69700803e56STom N Harris     * @return array            list of words as the keys and frequency as values
69800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
69900803e56STom N Harris     */
70000803e56STom N Harris    public function histogram($min=1, $max=0, $key=null) {
70100803e56STom N Harris    }
70200803e56STom N Harris
70300803e56STom N Harris    /**
70400803e56STom N Harris     * Lock the indexer.
70500803e56STom N Harris     *
70600803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
70700803e56STom N Harris     */
70800803e56STom N Harris    private function _lock() {
70900803e56STom N Harris        global $conf;
71000803e56STom N Harris        $status = true;
71100803e56STom N Harris        $lock = $conf['lockdir'].'/_indexer.lock';
71200803e56STom N Harris        while (!@mkdir($lock, $conf['dmode'])) {
71300803e56STom N Harris            usleep(50);
71400803e56STom N Harris            if (time() - @filemtime($lock) > 60*5) {
71500803e56STom N Harris                // looks like a stale lock, remove it
71600803e56STom N Harris                @rmdir($lock);
71700803e56STom N Harris                $status = "stale lock removed";
71800803e56STom N Harris            } else {
71900803e56STom N Harris                return false;
72000803e56STom N Harris            }
72100803e56STom N Harris        }
72200803e56STom N Harris        if ($conf['dperm'])
72300803e56STom N Harris            chmod($lock, $conf['dperm']);
72400803e56STom N Harris        return $status;
72500803e56STom N Harris    }
72600803e56STom N Harris
72700803e56STom N Harris    /**
72800803e56STom N Harris     * Release the indexer lock.
72900803e56STom N Harris     *
73000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
73100803e56STom N Harris     */
73200803e56STom N Harris    private function _unlock() {
73300803e56STom N Harris        global $conf;
73400803e56STom N Harris        @rmdir($conf['lockdir'].'/_indexer.lock');
73500803e56STom N Harris        return true;
73600803e56STom N Harris    }
73700803e56STom N Harris
73800803e56STom N Harris    /**
73900803e56STom N Harris     * Retrieve the entire index.
74000803e56STom N Harris     *
74100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
74200803e56STom N Harris     */
74300803e56STom N Harris    private function _getIndex($idx, $suffix) {
74400803e56STom N Harris        global $conf;
74500803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
746d64516f5SMichael Hamann        if (!@file_exists($fn)) return array();
747d64516f5SMichael Hamann        return file($fn, FILE_IGNORE_NEW_LINES);
74800803e56STom N Harris    }
74900803e56STom N Harris
75000803e56STom N Harris    /**
75100803e56STom N Harris     * Replace the contents of the index with an array.
75200803e56STom N Harris     *
75300803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
75400803e56STom N Harris     */
75500803e56STom N Harris    private function _saveIndex($idx, $suffix, &$lines) {
75600803e56STom N Harris        global $conf;
75700803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
75800803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
75900803e56STom N Harris        if (!$fh) return false;
76000803e56STom N Harris        fwrite($fh, join("\n", $lines));
76100803e56STom N Harris        fclose($fh);
76200803e56STom N Harris        if (isset($conf['fperm']))
76300803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
76400803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
76500803e56STom N Harris        if ($suffix !== '')
76600803e56STom N Harris            $this->_cacheIndexDir($idx, $suffix, empty($lines));
76700803e56STom N Harris        return true;
76800803e56STom N Harris    }
76900803e56STom N Harris
77000803e56STom N Harris    /**
77100803e56STom N Harris     * Retrieve a line from the index.
77200803e56STom N Harris     *
77300803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
77400803e56STom N Harris     */
77500803e56STom N Harris    private function _getIndexKey($idx, $suffix, $id) {
77600803e56STom N Harris        global $conf;
77700803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
77800803e56STom N Harris        if (!@file_exists($fn)) return '';
77900803e56STom N Harris        $fh = @fopen($fn, 'r');
78000803e56STom N Harris        if (!$fh) return '';
78100803e56STom N Harris        $ln = -1;
78200803e56STom N Harris        while (($line = fgets($fh)) !== false) {
78300803e56STom N Harris            if (++$ln == $id) break;
78400803e56STom N Harris        }
78500803e56STom N Harris        fclose($fh);
78600803e56STom N Harris        return rtrim((string)$line);
78700803e56STom N Harris    }
78800803e56STom N Harris
78900803e56STom N Harris    /**
79000803e56STom N Harris     * Write a line into the index.
79100803e56STom N Harris     *
79200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
79300803e56STom N Harris     */
79400803e56STom N Harris    private function _saveIndexKey($idx, $suffix, $id, $line) {
79500803e56STom N Harris        global $conf;
79600803e56STom N Harris        if (substr($line, -1) != "\n")
79700803e56STom N Harris            $line .= "\n";
79800803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
79900803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
80000803e56STom N Harris        if (!fh) return false;
80100803e56STom N Harris        $ih = @fopen($fn.'.idx', 'r');
80200803e56STom N Harris        if ($ih) {
80300803e56STom N Harris            $ln = -1;
80400803e56STom N Harris            while (($curline = fgets($ih)) !== false) {
80500803e56STom N Harris                fwrite($fh, (++$ln == $id) ? $line : $curline);
80600803e56STom N Harris            }
8074373c7b5SMichael Hamann            if ($id > $ln) {
8084373c7b5SMichael Hamann                while ($id > ++$ln)
8094373c7b5SMichael Hamann                    fwrite($fh, "\n");
81000803e56STom N Harris                fwrite($fh, $line);
8114373c7b5SMichael Hamann            }
81200803e56STom N Harris            fclose($ih);
81300803e56STom N Harris        } else {
8144373c7b5SMichael Hamann            $ln = -1;
8154373c7b5SMichael Hamann            while ($id > ++$ln)
8164373c7b5SMichael Hamann                fwrite($fh, "\n");
81700803e56STom N Harris            fwrite($fh, $line);
81800803e56STom N Harris        }
81900803e56STom N Harris        fclose($fh);
82000803e56STom N Harris        if (isset($conf['fperm']))
82100803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
82200803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
82300803e56STom N Harris        if ($suffix !== '')
82400803e56STom N Harris            $this->_cacheIndexDir($idx, $suffix);
82500803e56STom N Harris        return true;
82600803e56STom N Harris    }
82700803e56STom N Harris
82800803e56STom N Harris    /**
82900803e56STom N Harris     * Retrieve or insert a value in the index.
83000803e56STom N Harris     *
83100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
83200803e56STom N Harris     */
83300803e56STom N Harris    private function _addIndexKey($idx, $suffix, $value) {
83400803e56STom N Harris        $index = $this->_getIndex($idx, $suffix);
83500803e56STom N Harris        $id = array_search($value, $index);
83600803e56STom N Harris        if ($id === false) {
83700803e56STom N Harris            $id = count($index);
83800803e56STom N Harris            $index[$id] = $value;
83900803e56STom N Harris            if (!$this->_saveIndex($idx, $suffix, $index)) {
84000803e56STom N Harris                trigger_error("Failed to write $idx index", E_USER_ERROR);
84100803e56STom N Harris                return false;
84200803e56STom N Harris            }
84300803e56STom N Harris        }
84400803e56STom N Harris        return $id;
84500803e56STom N Harris    }
84600803e56STom N Harris
84700803e56STom N Harris    private function _cacheIndexDir($idx, $suffix, $delete=false) {
84800803e56STom N Harris        global $conf;
84900803e56STom N Harris        if ($idx == 'i')
85000803e56STom N Harris            $cachename = $conf['indexdir'].'/lengths';
85100803e56STom N Harris        else
85200803e56STom N Harris            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
85300803e56STom N Harris        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
85400803e56STom N Harris        if ($lengths === false) $lengths = array();
85500803e56STom N Harris        $old = array_search((string)$suffix, $lengths);
85600803e56STom N Harris        if (empty($lines)) {
85700803e56STom N Harris            if ($old === false) return;
85800803e56STom N Harris            unset($lengths[$old]);
85900803e56STom N Harris        } else {
86000803e56STom N Harris            if ($old !== false) return;
86100803e56STom N Harris            $lengths[] = $suffix;
86200803e56STom N Harris            sort($lengths);
86300803e56STom N Harris        }
86400803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
86500803e56STom N Harris        if (!$fh) {
86600803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
86700803e56STom N Harris            return;
86800803e56STom N Harris        }
86900803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
87000803e56STom N Harris        @fclose($fh);
87100803e56STom N Harris        if (isset($conf['fperm']))
87200803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
87300803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
87400803e56STom N Harris    }
87500803e56STom N Harris
87600803e56STom N Harris    /**
87700803e56STom N Harris     * Get the list of lengths indexed in the wiki.
87800803e56STom N Harris     *
87900803e56STom N Harris     * Read the index directory or a cache file and returns
88000803e56STom N Harris     * a sorted array of lengths of the words used in the wiki.
88100803e56STom N Harris     *
88200803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
88300803e56STom N Harris     */
88400803e56STom N Harris    private function _listIndexLengths() {
88500803e56STom N Harris        global $conf;
88600803e56STom N Harris        $cachename = $conf['indexdir'].'/lengths';
88700803e56STom N Harris        clearstatcache();
88800803e56STom N Harris        if (@file_exists($cachename.'.idx')) {
88900803e56STom N Harris            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
89000803e56STom N Harris            if ($lengths !== false) {
89100803e56STom N Harris                $idx = array();
89200803e56STom N Harris                foreach ($lengths as $length)
89300803e56STom N Harris                    $idx[] = (int)$length;
89400803e56STom N Harris                return $idx;
89500803e56STom N Harris            }
89600803e56STom N Harris        }
89700803e56STom N Harris
89800803e56STom N Harris        $dir = @opendir($conf['indexdir']);
89900803e56STom N Harris        if ($dir === false)
90000803e56STom N Harris            return array();
90100803e56STom N Harris        $lengths[] = array();
90200803e56STom N Harris        while (($f = readdir($dir)) !== false) {
90300803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
90400803e56STom N Harris                $i = substr($f, 1, -4);
90500803e56STom N Harris                if (is_numeric($i))
90600803e56STom N Harris                    $lengths[] = (int)$i;
90700803e56STom N Harris            }
90800803e56STom N Harris        }
90900803e56STom N Harris        closedir($dir);
91000803e56STom N Harris        sort($lengths);
91100803e56STom N Harris        // save this in a file
91200803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
91300803e56STom N Harris        if (!$fh) {
91400803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
91500803e56STom N Harris            return;
91600803e56STom N Harris        }
91700803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
91800803e56STom N Harris        @fclose($fh);
91900803e56STom N Harris        if (isset($conf['fperm']))
92000803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
92100803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
92200803e56STom N Harris
92300803e56STom N Harris        return $lengths;
92400803e56STom N Harris    }
92500803e56STom N Harris
92600803e56STom N Harris    /**
92700803e56STom N Harris     * Get the word lengths that have been indexed.
92800803e56STom N Harris     *
92900803e56STom N Harris     * Reads the index directory and returns an array of lengths
93000803e56STom N Harris     * that there are indices for.
93100803e56STom N Harris     *
93200803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
93300803e56STom N Harris     */
93400803e56STom N Harris    private function _indexLengths($filter) {
93500803e56STom N Harris        global $conf;
93600803e56STom N Harris        $idx = array();
93700803e56STom N Harris        if (is_array($filter)) {
93800803e56STom N Harris            // testing if index files exist only
93900803e56STom N Harris            $path = $conf['indexdir']."/i";
94000803e56STom N Harris            foreach ($filter as $key => $value) {
94100803e56STom N Harris                if (@file_exists($path.$key.'.idx'))
94200803e56STom N Harris                    $idx[] = $key;
94300803e56STom N Harris            }
94400803e56STom N Harris        } else {
94500803e56STom N Harris            $lengths = idx_listIndexLengths();
94600803e56STom N Harris            foreach ($lengths as $key => $length) {
94700803e56STom N Harris                // keep all the values equal or superior
94800803e56STom N Harris                if ((int)$length >= (int)$filter)
94900803e56STom N Harris                    $idx[] = $length;
95000803e56STom N Harris            }
95100803e56STom N Harris        }
95200803e56STom N Harris        return $idx;
95300803e56STom N Harris    }
95400803e56STom N Harris
95500803e56STom N Harris    /**
95600803e56STom N Harris     * Insert or replace a tuple in a line.
95700803e56STom N Harris     *
95800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
95900803e56STom N Harris     */
96000803e56STom N Harris    private function _updateTuple($line, $id, $count) {
96100803e56STom N Harris        $newLine = $line;
96200803e56STom N Harris        if ($newLine !== '')
96300803e56STom N Harris            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
96400803e56STom N Harris        $newLine = trim($newLine, ':');
96500803e56STom N Harris        if ($count) {
966d64516f5SMichael Hamann            if (strlen($newLine) > 0)
96700803e56STom N Harris                return "$id*$count:".$newLine;
96800803e56STom N Harris            else
96900803e56STom N Harris                return "$id*$count".$newLine;
97000803e56STom N Harris        }
97100803e56STom N Harris        return $newLine;
97200803e56STom N Harris    }
97300803e56STom N Harris
97400803e56STom N Harris    /**
97500803e56STom N Harris     * Split a line into an array of tuples.
97600803e56STom N Harris     *
97700803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
97800803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
97900803e56STom N Harris     */
98000803e56STom N Harris    private function _parseTuples(&$keys, $line) {
98100803e56STom N Harris        $result = array();
98200803e56STom N Harris        if ($line == '') return $result;
98300803e56STom N Harris        $parts = explode(':', $line);
98400803e56STom N Harris        foreach ($parts as $tuple) {
98500803e56STom N Harris            if ($tuple == '') continue;
98600803e56STom N Harris            list($key, $cnt) = explode('*', $tuple);
987d64516f5SMichael Hamann            if (!$cnt) continue;
98800803e56STom N Harris            $key = $keys[$key];
98900803e56STom N Harris            if (!$key) continue;
99000803e56STom N Harris            $result[$key] = $cnt;
99100803e56STom N Harris        }
99200803e56STom N Harris        return $result;
99300803e56STom N Harris    }
99400803e56STom N Harris}
99500803e56STom N Harris
99600803e56STom N Harris/**
99700803e56STom N Harris * Create an instance of the indexer.
99800803e56STom N Harris *
99900803e56STom N Harris * @return object               a Doku_Indexer
100000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
100100803e56STom N Harris */
10029b41be24STom N Harrisfunction idx_get_indexer() {
100300803e56STom N Harris    static $Indexer = null;
100400803e56STom N Harris    if (is_null($Indexer)) {
100500803e56STom N Harris        $Indexer = new Doku_Indexer();
100600803e56STom N Harris    }
100700803e56STom N Harris    return $Indexer;
100800803e56STom N Harris}
100900803e56STom N Harris
101000803e56STom N Harris/**
101100803e56STom N Harris * Returns words that will be ignored.
101200803e56STom N Harris *
101300803e56STom N Harris * @return array                list of stop words
101400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
101500803e56STom N Harris */
101600803e56STom N Harrisfunction & idx_get_stopwords() {
101700803e56STom N Harris    static $stopwords = null;
101800803e56STom N Harris    if (is_null($stopwords)) {
101900803e56STom N Harris        global $conf;
102000803e56STom N Harris        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
102100803e56STom N Harris        if(@file_exists($swfile)){
102200803e56STom N Harris            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
102300803e56STom N Harris        }else{
102400803e56STom N Harris            $stopwords = array();
102500803e56STom N Harris        }
102600803e56STom N Harris    }
102700803e56STom N Harris    return $stopwords;
102800803e56STom N Harris}
102900803e56STom N Harris
103000803e56STom N Harris/**
103100803e56STom N Harris * Adds/updates the search index for the given page
103200803e56STom N Harris *
103300803e56STom N Harris * Locking is handled internally.
103400803e56STom N Harris *
103500803e56STom N Harris * @param string        $page   name of the page to index
10369b41be24STom N Harris * @param boolean       $verbose    print status messages
103700803e56STom N Harris * @return boolean              the function completed successfully
103800803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
103900803e56STom N Harris */
10409b41be24STom N Harrisfunction idx_addPage($page, $verbose=false) {
10419b41be24STom N Harris    // check if indexing needed
10429b41be24STom N Harris    $idxtag = metaFN($page,'.indexed');
10439b41be24STom N Harris    if(@file_exists($idxtag)){
10449b41be24STom N Harris        if(trim(io_readFile($idxtag)) == idx_get_version()){
10459b41be24STom N Harris            $last = @filemtime($idxtag);
10469b41be24STom N Harris            if($last > @filemtime(wikiFN($ID))){
10479b41be24STom N Harris                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
10489b41be24STom N Harris                return false;
10499b41be24STom N Harris            }
10509b41be24STom N Harris        }
10519b41be24STom N Harris    }
10529b41be24STom N Harris
1053bbc85ee4STom N Harris    if (!page_exists($page)) {
1054bbc85ee4STom N Harris        if (!@file_exists($idxtag)) {
1055bbc85ee4STom N Harris            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
1056bbc85ee4STom N Harris            return false;
1057bbc85ee4STom N Harris        }
1058bbc85ee4STom N Harris        $Indexer = idx_get_indexer();
1059bbc85ee4STom N Harris        $result = $Indexer->deletePage($page);
1060bbc85ee4STom N Harris        if ($result === "locked") {
1061bbc85ee4STom N Harris            if ($verbose) print("Indexer: locked".DOKU_LF);
1062bbc85ee4STom N Harris            return false;
1063bbc85ee4STom N Harris        }
1064bbc85ee4STom N Harris        @unlink($idxtag);
1065bbc85ee4STom N Harris        return $result;
1066bbc85ee4STom N Harris    }
1067bbc85ee4STom N Harris    $indexenabled = p_get_metadata($page, 'internal index', false);
1068bbc85ee4STom N Harris    if ($indexenabled === false) {
1069bbc85ee4STom N Harris        $result = false;
1070bbc85ee4STom N Harris        if (@file_exists($idxtag)) {
1071bbc85ee4STom N Harris            $Indexer = idx_get_indexer();
1072bbc85ee4STom N Harris            $result = $Indexer->deletePage($page);
1073bbc85ee4STom N Harris            if ($result === "locked") {
1074bbc85ee4STom N Harris                if ($verbose) print("Indexer: locked".DOKU_LF);
1075bbc85ee4STom N Harris                return false;
1076bbc85ee4STom N Harris            }
1077bbc85ee4STom N Harris            @unlink($idxtag);
1078bbc85ee4STom N Harris        }
1079bbc85ee4STom N Harris        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
1080bbc85ee4STom N Harris        return $result;
1081bbc85ee4STom N Harris    }
1082bbc85ee4STom N Harris
108300803e56STom N Harris    $body = '';
108400803e56STom N Harris    $data = array($page, $body);
108500803e56STom N Harris    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
108600803e56STom N Harris    if ($evt->advise_before()) $data[1] = $data[1] . " " . rawWiki($page);
108700803e56STom N Harris    $evt->advise_after();
108800803e56STom N Harris    unset($evt);
108900803e56STom N Harris    list($page,$body) = $data;
109000803e56STom N Harris
10919b41be24STom N Harris    $Indexer = idx_get_indexer();
10929b41be24STom N Harris    $result = $Indexer->addPageWords($page, $body);
1093e1e1a7e0SMichael Hamann    if ($result === "locked") {
10949b41be24STom N Harris        if ($verbose) print("Indexer: locked".DOKU_LF);
10959b41be24STom N Harris        return false;
10969b41be24STom N Harris    }
1097320f489aSMichael Hamann
1098320f489aSMichael Hamann    if ($result) {
1099320f489aSMichael Hamann        $data = array('page' => $page, 'metadata' => array());
1100320f489aSMichael Hamann
1101bbc85ee4STom N Harris        $data['metadata']['title'] = p_get_metadata($page, 'title', false);
1102bbc85ee4STom N Harris        if (($references = p_get_metadata($page, 'relation references', false)) !== null)
1103320f489aSMichael Hamann            $data['metadata']['relation_references'] = array_keys($references);
1104320f489aSMichael Hamann
1105320f489aSMichael Hamann        $evt = new Doku_Event('INDEXER_METADATA_INDEX', $data);
1106320f489aSMichael Hamann        if ($evt->advise_before()) {
1107320f489aSMichael Hamann            $result = $Indexer->addMetaKeys($page, $data['metadata']);
1108320f489aSMichael Hamann            if ($result === "locked") {
1109320f489aSMichael Hamann                if ($verbose) print("Indexer: locked".DOKU_LF);
1110320f489aSMichael Hamann                return false;
1111320f489aSMichael Hamann            }
1112320f489aSMichael Hamann        }
1113320f489aSMichael Hamann        $evt->advise_after();
1114320f489aSMichael Hamann        unset($evt);
1115320f489aSMichael Hamann    }
1116320f489aSMichael Hamann
11179b41be24STom N Harris    if ($result)
11189b41be24STom N Harris        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
11199b41be24STom N Harris    if ($verbose) {
11209b41be24STom N Harris        print("Indexer: finished".DOKU_LF);
11219b41be24STom N Harris        return true;
11229b41be24STom N Harris    }
11239b41be24STom N Harris    return $result;
112400803e56STom N Harris}
112500803e56STom N Harris
112600803e56STom N Harris/**
112700803e56STom N Harris * Find tokens in the fulltext index
112800803e56STom N Harris *
112900803e56STom N Harris * Takes an array of words and will return a list of matching
113000803e56STom N Harris * pages for each one.
1131488dd6ceSAndreas Gohr *
113263773904SAndreas Gohr * Important: No ACL checking is done here! All results are
113363773904SAndreas Gohr *            returned, regardless of permissions
113463773904SAndreas Gohr *
11359b41be24STom N Harris * @param arrayref      $words  list of words to search for
113600803e56STom N Harris * @return array                list of pages found, associated with the search terms
1137488dd6ceSAndreas Gohr */
11389b41be24STom N Harrisfunction idx_lookup(&$words) {
11399b41be24STom N Harris    $Indexer = idx_get_indexer();
114000803e56STom N Harris    return $Indexer->lookup($words);
1141488dd6ceSAndreas Gohr}
1142488dd6ceSAndreas Gohr
1143488dd6ceSAndreas Gohr/**
114400803e56STom N Harris * Split a string into tokens
1145488dd6ceSAndreas Gohr *
1146488dd6ceSAndreas Gohr */
114700803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) {
11489b41be24STom N Harris    $Indexer = idx_get_indexer();
114900803e56STom N Harris    return $Indexer->tokenizer($string, $wc);
1150488dd6ceSAndreas Gohr}
115100803e56STom N Harris
115200803e56STom N Harris/* For compatibility */
1153488dd6ceSAndreas Gohr
1154f5eb7cf0SAndreas Gohr/**
115500803e56STom N Harris * Read the list of words in an index (if it exists).
1156f5eb7cf0SAndreas Gohr *
11574e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
1158f5eb7cf0SAndreas Gohr */
115900803e56STom N Harrisfunction idx_getIndex($idx, $suffix) {
11601c07b9e6STom N Harris    global $conf;
116100803e56STom N Harris    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
116200803e56STom N Harris    if (!@file_exists($fn)) return array();
116300803e56STom N Harris    return file($fn);
116400803e56STom N Harris}
1165f5eb7cf0SAndreas Gohr
116600803e56STom N Harris/**
116700803e56STom N Harris * Get the list of lengths indexed in the wiki.
116800803e56STom N Harris *
116900803e56STom N Harris * Read the index directory or a cache file and returns
117000803e56STom N Harris * a sorted array of lengths of the words used in the wiki.
117100803e56STom N Harris *
117200803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
117300803e56STom N Harris */
117400803e56STom N Harrisfunction idx_listIndexLengths() {
117500803e56STom N Harris    global $conf;
117600803e56STom N Harris    // testing what we have to do, create a cache file or not.
117700803e56STom N Harris    if ($conf['readdircache'] == 0) {
117800803e56STom N Harris        $docache = false;
11791c07b9e6STom N Harris    } else {
118000803e56STom N Harris        clearstatcache();
118100803e56STom N Harris        if (@file_exists($conf['indexdir'].'/lengths.idx')
118200803e56STom N Harris        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
118300803e56STom N Harris            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
118400803e56STom N Harris                $idx = array();
118500803e56STom N Harris                foreach ($lengths as $length) {
118600803e56STom N Harris                    $idx[] = (int)$length;
118700803e56STom N Harris                }
118800803e56STom N Harris                return $idx;
1189f5eb7cf0SAndreas Gohr            }
11901c07b9e6STom N Harris        }
119100803e56STom N Harris        $docache = true;
119200803e56STom N Harris    }
11934e1bf408STom N Harris
119400803e56STom N Harris    if ($conf['readdircache'] == 0 || $docache) {
119500803e56STom N Harris        $dir = @opendir($conf['indexdir']);
119600803e56STom N Harris        if ($dir === false)
119700803e56STom N Harris            return array();
119800803e56STom N Harris        $idx[] = array();
119900803e56STom N Harris        while (($f = readdir($dir)) !== false) {
120000803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
120100803e56STom N Harris                $i = substr($f, 1, -4);
120200803e56STom N Harris                if (is_numeric($i))
120300803e56STom N Harris                    $idx[] = (int)$i;
120400803e56STom N Harris            }
120500803e56STom N Harris        }
120600803e56STom N Harris        closedir($dir);
120700803e56STom N Harris        sort($idx);
120800803e56STom N Harris        // save this in a file
120900803e56STom N Harris        if ($docache) {
121000803e56STom N Harris            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
121100803e56STom N Harris            @fwrite($handle, implode("\n", $idx));
121200803e56STom N Harris            @fclose($handle);
121300803e56STom N Harris        }
121400803e56STom N Harris        return $idx;
121500803e56STom N Harris    }
121600803e56STom N Harris
121700803e56STom N Harris    return array();
121800803e56STom N Harris}
121900803e56STom N Harris
122000803e56STom N Harris/**
122100803e56STom N Harris * Get the word lengths that have been indexed.
122200803e56STom N Harris *
122300803e56STom N Harris * Reads the index directory and returns an array of lengths
122400803e56STom N Harris * that there are indices for.
122500803e56STom N Harris *
122600803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
122700803e56STom N Harris */
122800803e56STom N Harrisfunction idx_indexLengths($filter) {
122900803e56STom N Harris    global $conf;
123000803e56STom N Harris    $idx = array();
123100803e56STom N Harris    if (is_array($filter)) {
123200803e56STom N Harris        // testing if index files exist only
123300803e56STom N Harris        $path = $conf['indexdir']."/i";
123400803e56STom N Harris        foreach ($filter as $key => $value) {
123500803e56STom N Harris            if (@file_exists($path.$key.'.idx'))
123600803e56STom N Harris                $idx[] = $key;
123700803e56STom N Harris        }
1238f5eb7cf0SAndreas Gohr    } else {
123900803e56STom N Harris        $lengths = idx_listIndexLengths();
124000803e56STom N Harris        foreach ($lengths as $key => $length) {
124100803e56STom N Harris            // keep all the values equal or superior
124200803e56STom N Harris            if ((int)$length >= (int)$filter)
124300803e56STom N Harris                $idx[] = $length;
1244f5eb7cf0SAndreas Gohr        }
124500803e56STom N Harris    }
124600803e56STom N Harris    return $idx;
1247f5eb7cf0SAndreas Gohr}
1248f5eb7cf0SAndreas Gohr
124900803e56STom N Harris/**
125000803e56STom N Harris * Clean a name of a key for use as a file name.
125100803e56STom N Harris *
125200803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's
125300803e56STom N Harris * not a letter, number, or underscore.
125400803e56STom N Harris *
125500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
125600803e56STom N Harris */
125700803e56STom N Harrisfunction idx_cleanName($name) {
125800803e56STom N Harris    $name = utf8_romanize(trim((string)$name));
125900803e56STom N Harris    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
126000803e56STom N Harris    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
126100803e56STom N Harris    return strtolower($name);
1262f5eb7cf0SAndreas Gohr}
1263f5eb7cf0SAndreas Gohr
126400803e56STom N Harris//Setup VIM: ex: et ts=4 :
1265