xref: /dokuwiki/inc/indexer.php (revision c01cdb709fd0bf8c91333c5134743e33bf587833)
1<?php
2/**
3 * Functions to create the fulltext search index
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 * @author     Tom N Harris <tnharris@whoopdedo.org>
8 */
9
10if(!defined('DOKU_INC')) die('meh.');
11
12// Version tag used to force rebuild on upgrade
13define('INDEXER_VERSION', 8);
14
15// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens)
16if (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2);
17
18// Asian characters are handled as words. The following regexp defines the
19// Unicode-Ranges for Asian characters
20// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
21// I'm no language expert. If you think some ranges are wrongly chosen or
22// a range is missing, please contact me
23define('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
24define('IDX_ASIAN2','['.
25                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
26                   '\x{309D}-\x{30A0}'.
27                   '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'.
28                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
29                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
30                   "\xF0\xA0\x80\x80-\xF0\xAA\x9B\x9F". // CJK Extension B
31                   "\xF0\xAA\x9C\x80-\xF0\xAB\x9C\xBF". // CJK Extension C
32                   "\xF0\xAB\x9D\x80-\xF0\xAB\xA0\x9F". // CJK Extension D
33                   "\xF0\xAF\xA0\x80-\xF0\xAF\xAB\xBF". // CJK Compatibility Supplement
34                   ']');
35define('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
36                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
37                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
38                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
39                   '\x{308F}-\x{3094}'.
40                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
41                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
42                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
43                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
44                   ']['.
45                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
46                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
47                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
48                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
49                   '\x{31F0}-\x{31FF}'.
50                   ']?');
51define('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
52
53/**
54 * Version of the indexer taking into consideration the external tokenizer.
55 * The indexer is only compatible with data written by the same version.
56 *
57 * @triggers INDEXER_VERSION_GET
58 * Plugins that modify what gets indexed should hook this event and
59 * add their version info to the event data like so:
60 *     $data[$plugin_name] = $plugin_version;
61 *
62 * @author Tom N Harris <tnharris@whoopdedo.org>
63 * @author Michael Hamann <michael@content-space.de>
64 */
65function idx_get_version(){
66    static $indexer_version = null;
67    if ($indexer_version == null) {
68        $version = INDEXER_VERSION;
69
70        // DokuWiki version is included for the convenience of plugins
71        $data = array('dokuwiki'=>$version);
72        trigger_event('INDEXER_VERSION_GET', $data, null, false);
73        unset($data['dokuwiki']); // this needs to be first
74        ksort($data);
75        foreach ($data as $plugin=>$vers)
76            $version .= '+'.$plugin.'='.$vers;
77        $indexer_version = $version;
78    }
79    return $indexer_version;
80}
81
82/**
83 * Measure the length of a string.
84 * Differs from strlen in handling of asian characters.
85 *
86 * @author Tom N Harris <tnharris@whoopdedo.org>
87 */
88function wordlen($w){
89    $l = strlen($w);
90    // If left alone, all chinese "words" will get put into w3.idx
91    // So the "length" of a "word" is faked
92    if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) {
93        foreach($leadbytes[0] as $b)
94            $l += ord($b) - 0xE1;
95    }
96    return $l;
97}
98
99/**
100 * Class that encapsulates operations on the indexer database.
101 *
102 * @author Tom N Harris <tnharris@whoopdedo.org>
103 */
104class Doku_Indexer {
105    /**
106     * @var array $pidCache Cache for getPID()
107     */
108    protected $pidCache = array();
109
110    /**
111     * Adds the contents of a page to the fulltext index
112     *
113     * The added text replaces previous words for the same page.
114     * An empty value erases the page.
115     *
116     * @param string    $page   a page name
117     * @param string    $text   the body of the page
118     * @return boolean          the function completed successfully
119     * @author Tom N Harris <tnharris@whoopdedo.org>
120     * @author Andreas Gohr <andi@splitbrain.org>
121     */
122    public function addPageWords($page, $text) {
123        if (!$this->lock())
124            return "locked";
125
126        // load known documents
127        $pid = $this->getPIDNoLock($page);
128        if ($pid === false) {
129            $this->unlock();
130            return false;
131        }
132
133        $pagewords = array();
134        // get word usage in page
135        $words = $this->getPageWords($text);
136        if ($words === false) {
137            $this->unlock();
138            return false;
139        }
140
141        if (!empty($words)) {
142            foreach (array_keys($words) as $wlen) {
143                $index = $this->getIndex('i', $wlen);
144                foreach ($words[$wlen] as $wid => $freq) {
145                    $idx = ($wid<count($index)) ? $index[$wid] : '';
146                    $index[$wid] = $this->updateTuple($idx, $pid, $freq);
147                    $pagewords[] = "$wlen*$wid";
148                }
149                if (!$this->saveIndex('i', $wlen, $index)) {
150                    $this->unlock();
151                    return false;
152                }
153            }
154        }
155
156        // Remove obsolete index entries
157        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
158        if ($pageword_idx !== '') {
159            $oldwords = explode(':',$pageword_idx);
160            $delwords = array_diff($oldwords, $pagewords);
161            $upwords = array();
162            foreach ($delwords as $word) {
163                if ($word != '') {
164                    list($wlen,$wid) = explode('*', $word);
165                    $wid = (int)$wid;
166                    $upwords[$wlen][] = $wid;
167                }
168            }
169            foreach ($upwords as $wlen => $widx) {
170                $index = $this->getIndex('i', $wlen);
171                foreach ($widx as $wid) {
172                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
173                }
174                $this->saveIndex('i', $wlen, $index);
175            }
176        }
177        // Save the reverse index
178        $pageword_idx = join(':', $pagewords);
179        if (!$this->saveIndexKey('pageword', '', $pid, $pageword_idx)) {
180            $this->unlock();
181            return false;
182        }
183
184        $this->unlock();
185        return true;
186    }
187
188    /**
189     * Split the words in a page and add them to the index.
190     *
191     * @param string    $text   content of the page
192     * @return array            list of word IDs and number of times used
193     * @author Andreas Gohr <andi@splitbrain.org>
194     * @author Christopher Smith <chris@jalakai.co.uk>
195     * @author Tom N Harris <tnharris@whoopdedo.org>
196     */
197    protected function getPageWords($text) {
198
199        $tokens = $this->tokenizer($text);
200        $tokens = array_count_values($tokens);  // count the frequency of each token
201
202        $words = array();
203        foreach ($tokens as $w=>$c) {
204            $l = wordlen($w);
205            if (isset($words[$l])){
206                $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
207            }else{
208                $words[$l] = array($w => $c);
209            }
210        }
211
212        // arrive here with $words = array(wordlen => array(word => frequency))
213        $word_idx_modified = false;
214        $index = array();   //resulting index
215        foreach (array_keys($words) as $wlen) {
216            $word_idx = $this->getIndex('w', $wlen);
217            foreach ($words[$wlen] as $word => $freq) {
218                $word = (string)$word;
219                $wid = array_search($word, $word_idx, true);
220                if ($wid === false) {
221                    $wid = count($word_idx);
222                    $word_idx[] = $word;
223                    $word_idx_modified = true;
224                }
225                if (!isset($index[$wlen]))
226                    $index[$wlen] = array();
227                $index[$wlen][$wid] = $freq;
228            }
229            // save back the word index
230            if ($word_idx_modified && !$this->saveIndex('w', $wlen, $word_idx))
231                return false;
232        }
233
234        return $index;
235    }
236
237    /**
238     * Add/update keys to/of the metadata index.
239     *
240     * Adding new keys does not remove other keys for the page.
241     * An empty value will erase the key.
242     * The $key parameter can be an array to add multiple keys. $value will
243     * not be used if $key is an array.
244     *
245     * @param string    $page   a page name
246     * @param mixed     $key    a key string or array of key=>value pairs
247     * @param mixed     $value  the value or list of values
248     * @return boolean          the function completed successfully
249     * @author Tom N Harris <tnharris@whoopdedo.org>
250     * @author Michael Hamann <michael@content-space.de>
251     */
252    public function addMetaKeys($page, $key, $value=null) {
253        if (!is_array($key)) {
254            $key = array($key => $value);
255        } elseif (!is_null($value)) {
256            // $key is array, but $value is not null
257            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
258        }
259
260        if (!$this->lock())
261            return "locked";
262
263        // load known documents
264        $pid = $this->getPIDNoLock($page);
265        if ($pid === false) {
266            $this->unlock();
267            return false;
268        }
269
270        // Special handling for titles so the index file is simpler
271        if (array_key_exists('title', $key)) {
272            $value = $key['title'];
273            if (is_array($value))
274                $value = $value[0];
275            $this->saveIndexKey('title', '', $pid, $value);
276            unset($key['title']);
277        }
278
279        foreach ($key as $name => $values) {
280            $metaname = idx_cleanName($name);
281            $this->addIndexKey('metadata', '', $metaname);
282            $metaidx = $this->getIndex($metaname.'_i', '');
283            $metawords = $this->getIndex($metaname.'_w', '');
284            $addwords = false;
285
286            if (!is_array($values)) $values = array($values);
287
288            $val_idx = $this->getIndexKey($metaname.'_p', '', $pid);
289            if ($val_idx != '') {
290                $val_idx = explode(':', $val_idx);
291                // -1 means remove, 0 keep, 1 add
292                $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
293            } else {
294                $val_idx = array();
295            }
296
297            foreach ($values as $val) {
298                $val = (string)$val;
299                if ($val !== "") {
300                    $id = array_search($val, $metawords, true);
301                    if ($id === false) {
302                        $id = count($metawords);
303                        $metawords[$id] = $val;
304                        $addwords = true;
305                    }
306                    // test if value is already in the index
307                    if (isset($val_idx[$id]) && $val_idx[$id] <= 0){
308                        $val_idx[$id] = 0;
309                    } else { // else add it
310                        $val_idx[$id] = 1;
311                    }
312                }
313            }
314
315            if ($addwords) {
316                $this->saveIndex($metaname.'_w', '', $metawords);
317            }
318            $vals_changed = false;
319            foreach ($val_idx as $id => $action) {
320                if ($action == -1) {
321                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 0);
322                    $vals_changed = true;
323                    unset($val_idx[$id]);
324                } elseif ($action == 1) {
325                    $metaidx[$id] = $this->updateTuple($metaidx[$id], $pid, 1);
326                    $vals_changed = true;
327                }
328            }
329
330            if ($vals_changed) {
331                $this->saveIndex($metaname.'_i', '', $metaidx);
332                $val_idx = implode(':', array_keys($val_idx));
333                $this->saveIndexKey($metaname.'_p', '', $pid, $val_idx);
334            }
335
336            unset($metaidx);
337            unset($metawords);
338        }
339
340        $this->unlock();
341        return true;
342    }
343
344    /**
345     * Rename a page in the search index without changing the indexed content. This function doesn't check if the
346     * old or new name exists in the filesystem. It returns an error if the old page isn't in the page list of the
347     * indexer and it deletes all previously indexed content of the new page.
348     *
349     * @param string $oldpage The old page name
350     * @param string $newpage The new page name
351     * @return string|bool If the page was successfully renamed, can be a message in the case of an error
352     */
353    public function renamePage($oldpage, $newpage) {
354        if (!$this->lock()) return 'locked';
355
356        $pages = $this->getPages();
357
358        $id = array_search($oldpage, $pages, true);
359        if ($id === false) {
360            $this->unlock();
361            return 'page is not in index';
362        }
363
364        $new_id = array_search($newpage, $pages, true);
365        if ($new_id !== false) {
366            // make sure the page is not in the index anymore
367            if ($this->deletePageNoLock($newpage) !== true) {
368                return false;
369            }
370
371            $pages[$new_id] = 'deleted:'.time().rand(0, 9999);
372        }
373
374        $pages[$id] = $newpage;
375
376        // update index
377        if (!$this->saveIndex('page', '', $pages)) {
378            $this->unlock();
379            return false;
380        }
381
382        // reset the pid cache
383        $this->pidCache = array();
384
385        $this->unlock();
386        return true;
387    }
388
389    /**
390     * Renames a meta value in the index. This doesn't change the meta value in the pages, it assumes that all pages
391     * will be updated.
392     *
393     * @param string $key       The metadata key of which a value shall be changed
394     * @param string $oldvalue  The old value that shall be renamed
395     * @param string $newvalue  The new value to which the old value shall be renamed, can exist (then values will be merged)
396     * @return bool|string      If renaming the value has been successful, false or error message on error.
397     */
398    public function renameMetaValue($key, $oldvalue, $newvalue) {
399        if (!$this->lock()) return 'locked';
400
401        // change the relation references index
402        $metavalues = $this->getIndex($key, '_w');
403        $oldid = array_search($oldvalue, $metavalues, true);
404        if ($oldid !== false) {
405            $newid = array_search($newvalue, $metavalues, true);
406            if ($newid !== false) {
407                // free memory
408                unset ($metavalues);
409
410                // okay, now we have two entries for the same value. we need to merge them.
411                $indexline = $this->getIndexKey($key.'_i', '', $oldid);
412                if ($indexline != '') {
413                    $newindexline = $this->getIndexKey($key.'_i', '', $newid);
414                    $pagekeys     = $this->getIndex($key.'_p', '');
415                    $parts = explode(':', $indexline);
416                    foreach ($parts as $part) {
417                        list($id, $count) = explode('*', $part);
418                        $newindexline =  $this->updateTuple($newindexline, $id, $count);
419
420                        $keyline = explode(':', $pagekeys[$id]);
421                        // remove old meta value
422                        $keyline = array_diff($keyline, array($oldid));
423                        // add new meta value when not already present
424                        if (!in_array($newid, $keyline)) {
425                            array_push($keyline, $newid);
426                        }
427                        $pagekeys[$id] = implode(':', $keyline);
428                    }
429                    $this->saveIndex($key.'_p', '', $pagekeys);
430                    unset($pagekeys);
431                    $this->saveIndexKey($key.'_i', '', $oldid, '');
432                    $this->saveIndexKey($key.'_i', '', $newid, $newindexline);
433                }
434            } else {
435                $metavalues[$oldid] = $newvalue;
436                if (!$this->saveIndex($key.'_w', '', $metavalues)) {
437                    $this->unlock();
438                    return false;
439                }
440            }
441        }
442
443        $this->unlock();
444        return true;
445    }
446
447    /**
448     * Remove a page from the index
449     *
450     * Erases entries in all known indexes.
451     *
452     * @param string    $page   a page name
453     * @return boolean          the function completed successfully
454     * @author Tom N Harris <tnharris@whoopdedo.org>
455     */
456    public function deletePage($page) {
457        if (!$this->lock())
458            return "locked";
459
460        $result = $this->deletePageNoLock($page);
461
462        $this->unlock();
463
464        return $result;
465    }
466
467    /**
468     * Remove a page from the index without locking the index, only use this function if the index is already locked
469     *
470     * Erases entries in all known indexes.
471     *
472     * @param string    $page   a page name
473     * @return boolean          the function completed successfully
474     * @author Tom N Harris <tnharris@whoopdedo.org>
475     */
476    protected function deletePageNoLock($page) {
477        // load known documents
478        $pid = $this->getPIDNoLock($page);
479        if ($pid === false) {
480            return false;
481        }
482
483        // Remove obsolete index entries
484        $pageword_idx = $this->getIndexKey('pageword', '', $pid);
485        if ($pageword_idx !== '') {
486            $delwords = explode(':',$pageword_idx);
487            $upwords = array();
488            foreach ($delwords as $word) {
489                if ($word != '') {
490                    list($wlen,$wid) = explode('*', $word);
491                    $wid = (int)$wid;
492                    $upwords[$wlen][] = $wid;
493                }
494            }
495            foreach ($upwords as $wlen => $widx) {
496                $index = $this->getIndex('i', $wlen);
497                foreach ($widx as $wid) {
498                    $index[$wid] = $this->updateTuple($index[$wid], $pid, 0);
499                }
500                $this->saveIndex('i', $wlen, $index);
501            }
502        }
503        // Save the reverse index
504        if (!$this->saveIndexKey('pageword', '', $pid, "")) {
505            return false;
506        }
507
508        $this->saveIndexKey('title', '', $pid, "");
509        $keyidx = $this->getIndex('metadata', '');
510        foreach ($keyidx as $metaname) {
511            $val_idx = explode(':', $this->getIndexKey($metaname.'_p', '', $pid));
512            $meta_idx = $this->getIndex($metaname.'_i', '');
513            foreach ($val_idx as $id) {
514                if ($id === '') continue;
515                $meta_idx[$id] = $this->updateTuple($meta_idx[$id], $pid, 0);
516            }
517            $this->saveIndex($metaname.'_i', '', $meta_idx);
518            $this->saveIndexKey($metaname.'_p', '', $pid, '');
519        }
520
521        return true;
522    }
523
524    /**
525     * Clear the whole index
526     *
527     * @return bool If the index has been cleared successfully
528     */
529    public function clear() {
530        global $conf;
531
532        if (!$this->lock()) return false;
533
534        @unlink($conf['indexdir'].'/page.idx');
535        @unlink($conf['indexdir'].'/title.idx');
536        @unlink($conf['indexdir'].'/pageword.idx');
537        @unlink($conf['indexdir'].'/metadata.idx');
538        $dir = @opendir($conf['indexdir']);
539        if($dir!==false){
540            while(($f = readdir($dir)) !== false){
541                if(substr($f,-4)=='.idx' &&
542                    (substr($f,0,1)=='i' || substr($f,0,1)=='w'
543                        || substr($f,-6)=='_w.idx' || substr($f,-6)=='_i.idx' || substr($f,-6)=='_p.idx'))
544                    @unlink($conf['indexdir']."/$f");
545            }
546        }
547        @unlink($conf['indexdir'].'/lengths.idx');
548
549        // clear the pid cache
550        $this->pidCache = array();
551
552        $this->unlock();
553        return true;
554    }
555
556    /**
557     * Split the text into words for fulltext search
558     *
559     * TODO: does this also need &$stopwords ?
560     *
561     * @triggers INDEXER_TEXT_PREPARE
562     * This event allows plugins to modify the text before it gets tokenized.
563     * Plugins intercepting this event should also intercept INDEX_VERSION_GET
564     *
565     * @param string    $text   plain text
566     * @param boolean   $wc     are wildcards allowed?
567     * @return array            list of words in the text
568     * @author Tom N Harris <tnharris@whoopdedo.org>
569     * @author Andreas Gohr <andi@splitbrain.org>
570     */
571    public function tokenizer($text, $wc=false) {
572        $wc = ($wc) ? '' : '\*';
573        $stopwords =& idx_get_stopwords();
574
575        // prepare the text to be tokenized
576        $evt = new Doku_Event('INDEXER_TEXT_PREPARE', $text);
577        if ($evt->advise_before(true)) {
578            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
579                // handle asian chars as single words (may fail on older PHP version)
580                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
581                if (!is_null($asia)) $text = $asia; // recover from regexp falure
582            }
583        }
584        $evt->advise_after();
585        unset($evt);
586
587        $text = strtr($text,
588                       array(
589                           "\r" => ' ',
590                           "\n" => ' ',
591                           "\t" => ' ',
592                           "\xC2\xAD" => '', //soft-hyphen
593                       )
594                     );
595        if (preg_match('/[^0-9A-Za-z ]/u', $text))
596            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
597
598        $wordlist = explode(' ', $text);
599        foreach ($wordlist as $i => $word) {
600            $wordlist[$i] = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
601                utf8_strtolower($word) : strtolower($word);
602        }
603
604        foreach ($wordlist as $i => $word) {
605            if ((!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH)
606              || array_search($word, $stopwords, true) !== false)
607                unset($wordlist[$i]);
608        }
609        return array_values($wordlist);
610    }
611
612    /**
613     * Get the numeric PID of a page
614     *
615     * @param string $page The page to get the PID for
616     * @return bool|int The page id on success, false on error
617     */
618    public function getPID($page) {
619        // return PID without locking when it is in the cache
620        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
621
622        if (!$this->lock())
623            return false;
624
625        // load known documents
626        $pid = $this->getPIDNoLock($page);
627        if ($pid === false) {
628            $this->unlock();
629            return false;
630        }
631
632        $this->unlock();
633        return $pid;
634    }
635
636    /**
637     * Get the numeric PID of a page without locking the index.
638     * Only use this function when the index is already locked.
639     *
640     * @param string $page The page to get the PID for
641     * @return bool|int The page id on success, false on error
642     */
643    protected function getPIDNoLock($page) {
644        // avoid expensive addIndexKey operation for the most recently requested pages by using a cache
645        if (isset($this->pidCache[$page])) return $this->pidCache[$page];
646        $pid = $this->addIndexKey('page', '', $page);
647        // limit cache to 10 entries by discarding the oldest element as in DokuWiki usually only the most recently
648        // added item will be requested again
649        if (count($this->pidCache) > 10) array_shift($this->pidCache);
650        $this->pidCache[$page] = $pid;
651        return $pid;
652    }
653
654    /**
655     * Get the page id of a numeric PID
656     *
657     * @param int $pid The PID to get the page id for
658     * @return string The page id
659     */
660    public function getPageFromPID($pid) {
661        return $this->getIndexKey('page', '', $pid);
662    }
663
664    /**
665     * Find pages in the fulltext index containing the words,
666     *
667     * The search words must be pre-tokenized, meaning only letters and
668     * numbers with an optional wildcard
669     *
670     * The returned array will have the original tokens as key. The values
671     * in the returned list is an array with the page names as keys and the
672     * number of times that token appears on the page as value.
673     *
674     * @param array  $tokens list of words to search for
675     * @return array         list of page names with usage counts
676     * @author Tom N Harris <tnharris@whoopdedo.org>
677     * @author Andreas Gohr <andi@splitbrain.org>
678     */
679    public function lookup(&$tokens) {
680        $result = array();
681        $wids = $this->getIndexWords($tokens, $result);
682        if (empty($wids)) return array();
683        // load known words and documents
684        $page_idx = $this->getIndex('page', '');
685        $docs = array();
686        foreach (array_keys($wids) as $wlen) {
687            $wids[$wlen] = array_unique($wids[$wlen]);
688            $index = $this->getIndex('i', $wlen);
689            foreach($wids[$wlen] as $ixid) {
690                if ($ixid < count($index))
691                    $docs["$wlen*$ixid"] = $this->parseTuples($page_idx, $index[$ixid]);
692            }
693        }
694        // merge found pages into final result array
695        $final = array();
696        foreach ($result as $word => $res) {
697            $final[$word] = array();
698            foreach ($res as $wid) {
699                // handle the case when ($ixid < count($index)) has been false
700                // and thus $docs[$wid] hasn't been set.
701                if (!isset($docs[$wid])) continue;
702                $hits = &$docs[$wid];
703                foreach ($hits as $hitkey => $hitcnt) {
704                    // make sure the document still exists
705                    if (!page_exists($hitkey, '', false)) continue;
706                    if (!isset($final[$word][$hitkey]))
707                        $final[$word][$hitkey] = $hitcnt;
708                    else
709                        $final[$word][$hitkey] += $hitcnt;
710                }
711            }
712        }
713        return $final;
714    }
715
716    /**
717     * Find pages containing a metadata key.
718     *
719     * The metadata values are compared as case-sensitive strings. Pass a
720     * callback function that returns true or false to use a different
721     * comparison function. The function will be called with the $value being
722     * searched for as the first argument, and the word in the index as the
723     * second argument. The function preg_match can be used directly if the
724     * values are regexes.
725     *
726     * @param string    $key    name of the metadata key to look for
727     * @param string    $value  search term to look for, must be a string or array of strings
728     * @param callback  $func   comparison function
729     * @return array            lists with page names, keys are query values if $value is array
730     * @author Tom N Harris <tnharris@whoopdedo.org>
731     * @author Michael Hamann <michael@content-space.de>
732     */
733    public function lookupKey($key, &$value, $func=null) {
734        if (!is_array($value))
735            $value_array = array($value);
736        else
737            $value_array =& $value;
738
739        // the matching ids for the provided value(s)
740        $value_ids = array();
741
742        $metaname = idx_cleanName($key);
743
744        // get all words in order to search the matching ids
745        if ($key == 'title') {
746            $words = $this->getIndex('title', '');
747        } else {
748            $words = $this->getIndex($metaname.'_w', '');
749        }
750
751        if (!is_null($func)) {
752            foreach ($value_array as $val) {
753                foreach ($words as $i => $word) {
754                    if (call_user_func_array($func, array($val, $word)))
755                        $value_ids[$i][] = $val;
756                }
757            }
758        } else {
759            foreach ($value_array as $val) {
760                $xval = $val;
761                $caret = '^';
762                $dollar = '$';
763                // check for wildcards
764                if (substr($xval, 0, 1) == '*') {
765                    $xval = substr($xval, 1);
766                    $caret = '';
767                }
768                if (substr($xval, -1, 1) == '*') {
769                    $xval = substr($xval, 0, -1);
770                    $dollar = '';
771                }
772                if (!$caret || !$dollar) {
773                    $re = $caret.preg_quote($xval, '/').$dollar;
774                    foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
775                        $value_ids[$i][] = $val;
776                } else {
777                    if (($i = array_search($val, $words, true)) !== false)
778                        $value_ids[$i][] = $val;
779                }
780            }
781        }
782
783        unset($words); // free the used memory
784
785        // initialize the result so it won't be null
786        $result = array();
787        foreach ($value_array as $val) {
788            $result[$val] = array();
789        }
790
791        $page_idx = $this->getIndex('page', '');
792
793        // Special handling for titles
794        if ($key == 'title') {
795            foreach ($value_ids as $pid => $val_list) {
796                $page = $page_idx[$pid];
797                foreach ($val_list as $val) {
798                    $result[$val][] = $page;
799                }
800            }
801        } else {
802            // load all lines and pages so the used lines can be taken and matched with the pages
803            $lines = $this->getIndex($metaname.'_i', '');
804
805            foreach ($value_ids as $value_id => $val_list) {
806                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
807                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
808                $pages = array_keys($this->parseTuples($page_idx, $lines[$value_id]));
809                foreach ($val_list as $val) {
810                    $result[$val] = array_merge($result[$val], $pages);
811                }
812            }
813        }
814        if (!is_array($value)) $result = $result[$value];
815        return $result;
816    }
817
818    /**
819     * Find the index ID of each search term.
820     *
821     * The query terms should only contain valid characters, with a '*' at
822     * either the beginning or end of the word (or both).
823     * The $result parameter can be used to merge the index locations with
824     * the appropriate query term.
825     *
826     * @param array  $words  The query terms.
827     * @param array  $result Set to word => array("length*id" ...)
828     * @return array         Set to length => array(id ...)
829     * @author Tom N Harris <tnharris@whoopdedo.org>
830     */
831    protected function getIndexWords(&$words, &$result) {
832        $tokens = array();
833        $tokenlength = array();
834        $tokenwild = array();
835        foreach ($words as $word) {
836            $result[$word] = array();
837            $caret = '^';
838            $dollar = '$';
839            $xword = $word;
840            $wlen = wordlen($word);
841
842            // check for wildcards
843            if (substr($xword, 0, 1) == '*') {
844                $xword = substr($xword, 1);
845                $caret = '';
846                $wlen -= 1;
847            }
848            if (substr($xword, -1, 1) == '*') {
849                $xword = substr($xword, 0, -1);
850                $dollar = '';
851                $wlen -= 1;
852            }
853            if ($wlen < IDX_MINWORDLENGTH && $caret && $dollar && !is_numeric($xword))
854                continue;
855            if (!isset($tokens[$xword]))
856                $tokenlength[$wlen][] = $xword;
857            if (!$caret || !$dollar) {
858                $re = $caret.preg_quote($xword, '/').$dollar;
859                $tokens[$xword][] = array($word, '/'.$re.'/');
860                if (!isset($tokenwild[$xword]))
861                    $tokenwild[$xword] = $wlen;
862            } else {
863                $tokens[$xword][] = array($word, null);
864            }
865        }
866        asort($tokenwild);
867        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
868        // $tokenlength = array( base word length => base word ... )
869        // $tokenwild = array( base word => base word length ... )
870        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
871        $indexes_known = $this->indexLengths($length_filter);
872        if (!empty($tokenwild)) sort($indexes_known);
873        // get word IDs
874        $wids = array();
875        foreach ($indexes_known as $ixlen) {
876            $word_idx = $this->getIndex('w', $ixlen);
877            // handle exact search
878            if (isset($tokenlength[$ixlen])) {
879                foreach ($tokenlength[$ixlen] as $xword) {
880                    $wid = array_search($xword, $word_idx, true);
881                    if ($wid !== false) {
882                        $wids[$ixlen][] = $wid;
883                        foreach ($tokens[$xword] as $w)
884                            $result[$w[0]][] = "$ixlen*$wid";
885                    }
886                }
887            }
888            // handle wildcard search
889            foreach ($tokenwild as $xword => $wlen) {
890                if ($wlen >= $ixlen) break;
891                foreach ($tokens[$xword] as $w) {
892                    if (is_null($w[1])) continue;
893                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
894                        $wids[$ixlen][] = $wid;
895                        $result[$w[0]][] = "$ixlen*$wid";
896                    }
897                }
898            }
899        }
900        return $wids;
901    }
902
903    /**
904     * Return a list of all pages
905     * Warning: pages may not exist!
906     *
907     * @param string    $key    list only pages containing the metadata key (optional)
908     * @return array            list of page names
909     * @author Tom N Harris <tnharris@whoopdedo.org>
910     */
911    public function getPages($key=null) {
912        $page_idx = $this->getIndex('page', '');
913        if (is_null($key)) return $page_idx;
914
915        $metaname = idx_cleanName($key);
916
917        // Special handling for titles
918        if ($key == 'title') {
919            $title_idx = $this->getIndex('title', '');
920            array_splice($page_idx, count($title_idx));
921            foreach ($title_idx as $i => $title)
922                if ($title === "") unset($page_idx[$i]);
923            return array_values($page_idx);
924        }
925
926        $pages = array();
927        $lines = $this->getIndex($metaname.'_i', '');
928        foreach ($lines as $line) {
929            $pages = array_merge($pages, $this->parseTuples($page_idx, $line));
930        }
931        return array_keys($pages);
932    }
933
934    /**
935     * Return a list of words sorted by number of times used
936     *
937     * @param int       $min    bottom frequency threshold
938     * @param int       $max    upper frequency limit. No limit if $max<$min
939     * @param int       $minlen minimum length of words to count
940     * @param string    $key    metadata key to list. Uses the fulltext index if not given
941     * @return array            list of words as the keys and frequency as values
942     * @author Tom N Harris <tnharris@whoopdedo.org>
943     */
944    public function histogram($min=1, $max=0, $minlen=3, $key=null) {
945        if ($min < 1)
946            $min = 1;
947        if ($max < $min)
948            $max = 0;
949
950        $result = array();
951
952        if ($key == 'title') {
953            $index = $this->getIndex('title', '');
954            $index = array_count_values($index);
955            foreach ($index as $val => $cnt) {
956                if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
957                    $result[$val] = $cnt;
958            }
959        }
960        elseif (!is_null($key)) {
961            $metaname = idx_cleanName($key);
962            $index = $this->getIndex($metaname.'_i', '');
963            $val_idx = array();
964            foreach ($index as $wid => $line) {
965                $freq = $this->countTuples($line);
966                if ($freq >= $min && (!$max || $freq <= $max))
967                    $val_idx[$wid] = $freq;
968            }
969            if (!empty($val_idx)) {
970                $words = $this->getIndex($metaname.'_w', '');
971                foreach ($val_idx as $wid => $freq) {
972                    if (strlen($words[$wid]) >= $minlen)
973                        $result[$words[$wid]] = $freq;
974                }
975            }
976        }
977        else {
978            $lengths = idx_listIndexLengths();
979            foreach ($lengths as $length) {
980                if ($length < $minlen) continue;
981                $index = $this->getIndex('i', $length);
982                $words = null;
983                foreach ($index as $wid => $line) {
984                    $freq = $this->countTuples($line);
985                    if ($freq >= $min && (!$max || $freq <= $max)) {
986                        if ($words === null)
987                            $words = $this->getIndex('w', $length);
988                        $result[$words[$wid]] = $freq;
989                    }
990                }
991            }
992        }
993
994        arsort($result);
995        return $result;
996    }
997
998    /**
999     * Lock the indexer.
1000     *
1001     * @author Tom N Harris <tnharris@whoopdedo.org>
1002     */
1003    protected function lock() {
1004        global $conf;
1005        $status = true;
1006        $run = 0;
1007        $lock = $conf['lockdir'].'/_indexer.lock';
1008        while (!@mkdir($lock, $conf['dmode'])) {
1009            usleep(50);
1010            if(is_dir($lock) && time()-@filemtime($lock) > 60*5){
1011                // looks like a stale lock - remove it
1012                if (!@rmdir($lock)) {
1013                    $status = "removing the stale lock failed";
1014                    return false;
1015                } else {
1016                    $status = "stale lock removed";
1017                }
1018            }elseif($run++ == 1000){
1019                // we waited 5 seconds for that lock
1020                return false;
1021            }
1022        }
1023        if (!empty($conf['dperm'])) {
1024            chmod($lock, $conf['dperm']);
1025        }
1026        return $status;
1027    }
1028
1029    /**
1030     * Release the indexer lock.
1031     *
1032     * @author Tom N Harris <tnharris@whoopdedo.org>
1033     */
1034    protected function unlock() {
1035        global $conf;
1036        @rmdir($conf['lockdir'].'/_indexer.lock');
1037        return true;
1038    }
1039
1040    /**
1041     * Retrieve the entire index.
1042     *
1043     * The $suffix argument is for an index that is split into
1044     * multiple parts. Different index files should use different
1045     * base names.
1046     *
1047     * @param string    $idx    name of the index
1048     * @param string    $suffix subpart identifier
1049     * @return array            list of lines without CR or LF
1050     * @author Tom N Harris <tnharris@whoopdedo.org>
1051     */
1052    protected function getIndex($idx, $suffix) {
1053        global $conf;
1054        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1055        if (!@file_exists($fn)) return array();
1056        return file($fn, FILE_IGNORE_NEW_LINES);
1057    }
1058
1059    /**
1060     * Replace the contents of the index with an array.
1061     *
1062     * @param string    $idx    name of the index
1063     * @param string    $suffix subpart identifier
1064     * @param array     $lines  list of lines without LF
1065     * @return bool             If saving succeeded
1066     * @author Tom N Harris <tnharris@whoopdedo.org>
1067     */
1068    protected function saveIndex($idx, $suffix, &$lines) {
1069        global $conf;
1070        $fn = $conf['indexdir'].'/'.$idx.$suffix;
1071        $fh = @fopen($fn.'.tmp', 'w');
1072        if (!$fh) return false;
1073        fwrite($fh, join("\n", $lines));
1074        if (!empty($lines))
1075            fwrite($fh, "\n");
1076        fclose($fh);
1077        if (isset($conf['fperm']))
1078            chmod($fn.'.tmp', $conf['fperm']);
1079        io_rename($fn.'.tmp', $fn.'.idx');
1080        return true;
1081    }
1082
1083    /**
1084     * Retrieve a line from the index.
1085     *
1086     * @param string    $idx    name of the index
1087     * @param string    $suffix subpart identifier
1088     * @param int       $id     the line number
1089     * @return string           a line with trailing whitespace removed
1090     * @author Tom N Harris <tnharris@whoopdedo.org>
1091     */
1092    protected function getIndexKey($idx, $suffix, $id) {
1093        global $conf;
1094        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1095        if (!@file_exists($fn)) return '';
1096        $fh = @fopen($fn, 'r');
1097        if (!$fh) return '';
1098        $ln = -1;
1099        while (($line = fgets($fh)) !== false) {
1100            if (++$ln == $id) break;
1101        }
1102        fclose($fh);
1103        return rtrim((string)$line);
1104    }
1105
1106    /**
1107     * Write a line into the index.
1108     *
1109     * @param string    $idx    name of the index
1110     * @param string    $suffix subpart identifier
1111     * @param int       $id     the line number
1112     * @param string    $line   line to write
1113     * @return bool             If saving succeeded
1114     * @author Tom N Harris <tnharris@whoopdedo.org>
1115     */
1116    protected function saveIndexKey($idx, $suffix, $id, $line) {
1117        global $conf;
1118        if (substr($line, -1) != "\n")
1119            $line .= "\n";
1120        $fn = $conf['indexdir'].'/'.$idx.$suffix;
1121        $fh = @fopen($fn.'.tmp', 'w');
1122        if (!$fh) return false;
1123        $ih = @fopen($fn.'.idx', 'r');
1124        if ($ih) {
1125            $ln = -1;
1126            while (($curline = fgets($ih)) !== false) {
1127                fwrite($fh, (++$ln == $id) ? $line : $curline);
1128            }
1129            if ($id > $ln) {
1130                while ($id > ++$ln)
1131                    fwrite($fh, "\n");
1132                fwrite($fh, $line);
1133            }
1134            fclose($ih);
1135        } else {
1136            $ln = -1;
1137            while ($id > ++$ln)
1138                fwrite($fh, "\n");
1139            fwrite($fh, $line);
1140        }
1141        fclose($fh);
1142        if (isset($conf['fperm']))
1143            chmod($fn.'.tmp', $conf['fperm']);
1144        io_rename($fn.'.tmp', $fn.'.idx');
1145        return true;
1146    }
1147
1148    /**
1149     * Retrieve or insert a value in the index.
1150     *
1151     * @param string    $idx    name of the index
1152     * @param string    $suffix subpart identifier
1153     * @param string    $value  line to find in the index
1154     * @return int|bool          line number of the value in the index or false if writing the index failed
1155     * @author Tom N Harris <tnharris@whoopdedo.org>
1156     */
1157    protected function addIndexKey($idx, $suffix, $value) {
1158        $index = $this->getIndex($idx, $suffix);
1159        $id = array_search($value, $index, true);
1160        if ($id === false) {
1161            $id = count($index);
1162            $index[$id] = $value;
1163            if (!$this->saveIndex($idx, $suffix, $index)) {
1164                trigger_error("Failed to write $idx index", E_USER_ERROR);
1165                return false;
1166            }
1167        }
1168        return $id;
1169    }
1170
1171    /**
1172     * Get the list of lengths indexed in the wiki.
1173     *
1174     * Read the index directory or a cache file and returns
1175     * a sorted array of lengths of the words used in the wiki.
1176     *
1177     * @author YoBoY <yoboy.leguesh@gmail.com>
1178     */
1179    protected function listIndexLengths() {
1180        return idx_listIndexLengths();
1181    }
1182
1183    /**
1184     * Get the word lengths that have been indexed.
1185     *
1186     * Reads the index directory and returns an array of lengths
1187     * that there are indices for.
1188     *
1189     * @author YoBoY <yoboy.leguesh@gmail.com>
1190     */
1191    protected function indexLengths($filter) {
1192        global $conf;
1193        $idx = array();
1194        if (is_array($filter)) {
1195            // testing if index files exist only
1196            $path = $conf['indexdir']."/i";
1197            foreach ($filter as $key => $value) {
1198                if (@file_exists($path.$key.'.idx'))
1199                    $idx[] = $key;
1200            }
1201        } else {
1202            $lengths = idx_listIndexLengths();
1203            foreach ($lengths as $key => $length) {
1204                // keep all the values equal or superior
1205                if ((int)$length >= (int)$filter)
1206                    $idx[] = $length;
1207            }
1208        }
1209        return $idx;
1210    }
1211
1212    /**
1213     * Insert or replace a tuple in a line.
1214     *
1215     * @author Tom N Harris <tnharris@whoopdedo.org>
1216     */
1217    protected function updateTuple($line, $id, $count) {
1218        $newLine = $line;
1219        if ($newLine !== ''){
1220            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
1221        }
1222        $newLine = trim($newLine, ':');
1223        if ($count) {
1224            if (strlen($newLine) > 0) {
1225                return "$id*$count:".$newLine;
1226            } else {
1227                return "$id*$count".$newLine;
1228            }
1229        }
1230        return $newLine;
1231    }
1232
1233    /**
1234     * Split a line into an array of tuples.
1235     *
1236     * @author Tom N Harris <tnharris@whoopdedo.org>
1237     * @author Andreas Gohr <andi@splitbrain.org>
1238     */
1239    protected function parseTuples(&$keys, $line) {
1240        $result = array();
1241        if ($line == '') return $result;
1242        $parts = explode(':', $line);
1243        foreach ($parts as $tuple) {
1244            if ($tuple === '') continue;
1245            list($key, $cnt) = explode('*', $tuple);
1246            if (!$cnt) continue;
1247            $key = $keys[$key];
1248            if (!$key) continue;
1249            $result[$key] = $cnt;
1250        }
1251        return $result;
1252    }
1253
1254    /**
1255     * Sum the counts in a list of tuples.
1256     *
1257     * @author Tom N Harris <tnharris@whoopdedo.org>
1258     */
1259    protected function countTuples($line) {
1260        $freq = 0;
1261        $parts = explode(':', $line);
1262        foreach ($parts as $tuple) {
1263            if ($tuple === '') continue;
1264            list($pid, $cnt) = explode('*', $tuple);
1265            $freq += (int)$cnt;
1266        }
1267        return $freq;
1268    }
1269}
1270
1271/**
1272 * Create an instance of the indexer.
1273 *
1274 * @return Doku_Indexer               a Doku_Indexer
1275 * @author Tom N Harris <tnharris@whoopdedo.org>
1276 */
1277function idx_get_indexer() {
1278    static $Indexer;
1279    if (!isset($Indexer)) {
1280        $Indexer = new Doku_Indexer();
1281    }
1282    return $Indexer;
1283}
1284
1285/**
1286 * Returns words that will be ignored.
1287 *
1288 * @return array                list of stop words
1289 * @author Tom N Harris <tnharris@whoopdedo.org>
1290 */
1291function & idx_get_stopwords() {
1292    static $stopwords = null;
1293    if (is_null($stopwords)) {
1294        global $conf;
1295        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1296        if(@file_exists($swfile)){
1297            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
1298        }else{
1299            $stopwords = array();
1300        }
1301    }
1302    return $stopwords;
1303}
1304
1305/**
1306 * Adds/updates the search index for the given page
1307 *
1308 * Locking is handled internally.
1309 *
1310 * @param string        $page   name of the page to index
1311 * @param boolean       $verbose    print status messages
1312 * @param boolean       $force  force reindexing even when the index is up to date
1313 * @return boolean              the function completed successfully
1314 * @author Tom N Harris <tnharris@whoopdedo.org>
1315 */
1316function idx_addPage($page, $verbose=false, $force=false) {
1317    $idxtag = metaFN($page,'.indexed');
1318    // check if page was deleted but is still in the index
1319    if (!page_exists($page)) {
1320        if (!@file_exists($idxtag)) {
1321            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
1322            return false;
1323        }
1324        $Indexer = idx_get_indexer();
1325        $result = $Indexer->deletePage($page);
1326        if ($result === "locked") {
1327            if ($verbose) print("Indexer: locked".DOKU_LF);
1328            return false;
1329        }
1330        @unlink($idxtag);
1331        return $result;
1332    }
1333
1334    // check if indexing needed
1335    if(!$force && @file_exists($idxtag)){
1336        if(trim(io_readFile($idxtag)) == idx_get_version()){
1337            $last = @filemtime($idxtag);
1338            if($last > @filemtime(wikiFN($page))){
1339                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
1340                return false;
1341            }
1342        }
1343    }
1344
1345    $indexenabled = p_get_metadata($page, 'internal index', METADATA_RENDER_UNLIMITED);
1346    if ($indexenabled === false) {
1347        $result = false;
1348        if (@file_exists($idxtag)) {
1349            $Indexer = idx_get_indexer();
1350            $result = $Indexer->deletePage($page);
1351            if ($result === "locked") {
1352                if ($verbose) print("Indexer: locked".DOKU_LF);
1353                return false;
1354            }
1355            @unlink($idxtag);
1356        }
1357        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
1358        return $result;
1359    }
1360
1361    $Indexer = idx_get_indexer();
1362    $pid = $Indexer->getPID($page);
1363    if ($pid === false) {
1364        if ($verbose) print("Indexer: getting the PID failed for $page".DOKU_LF);
1365        return false;
1366    }
1367    $body = '';
1368    $metadata = array();
1369    $metadata['title'] = p_get_metadata($page, 'title', METADATA_RENDER_UNLIMITED);
1370    if (($references = p_get_metadata($page, 'relation references', METADATA_RENDER_UNLIMITED)) !== null)
1371        $metadata['relation_references'] = array_keys($references);
1372    else
1373        $metadata['relation_references'] = array();
1374
1375    if (($media = p_get_metadata($page, 'relation media', METADATA_RENDER_UNLIMITED)) !== null)
1376        $metadata['relation_media'] = array_keys($media);
1377    else
1378        $metadata['relation_media'] = array();
1379
1380    $data = compact('page', 'body', 'metadata', 'pid');
1381    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
1382    if ($evt->advise_before()) $data['body'] = $data['body'] . " " . rawWiki($page);
1383    $evt->advise_after();
1384    unset($evt);
1385    extract($data);
1386
1387    $result = $Indexer->addPageWords($page, $body);
1388    if ($result === "locked") {
1389        if ($verbose) print("Indexer: locked".DOKU_LF);
1390        return false;
1391    }
1392
1393    if ($result) {
1394        $result = $Indexer->addMetaKeys($page, $metadata);
1395        if ($result === "locked") {
1396            if ($verbose) print("Indexer: locked".DOKU_LF);
1397            return false;
1398        }
1399    }
1400
1401    if ($result)
1402        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
1403    if ($verbose) {
1404        print("Indexer: finished".DOKU_LF);
1405        return true;
1406    }
1407    return $result;
1408}
1409
1410/**
1411 * Find tokens in the fulltext index
1412 *
1413 * Takes an array of words and will return a list of matching
1414 * pages for each one.
1415 *
1416 * Important: No ACL checking is done here! All results are
1417 *            returned, regardless of permissions
1418 *
1419 * @param array      $words  list of words to search for
1420 * @return array             list of pages found, associated with the search terms
1421 */
1422function idx_lookup(&$words) {
1423    $Indexer = idx_get_indexer();
1424    return $Indexer->lookup($words);
1425}
1426
1427/**
1428 * Split a string into tokens
1429 *
1430 */
1431function idx_tokenizer($string, $wc=false) {
1432    $Indexer = idx_get_indexer();
1433    return $Indexer->tokenizer($string, $wc);
1434}
1435
1436/* For compatibility */
1437
1438/**
1439 * Read the list of words in an index (if it exists).
1440 *
1441 * @author Tom N Harris <tnharris@whoopdedo.org>
1442 */
1443function idx_getIndex($idx, $suffix) {
1444    global $conf;
1445    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1446    if (!@file_exists($fn)) return array();
1447    return file($fn);
1448}
1449
1450/**
1451 * Get the list of lengths indexed in the wiki.
1452 *
1453 * Read the index directory or a cache file and returns
1454 * a sorted array of lengths of the words used in the wiki.
1455 *
1456 * @author YoBoY <yoboy.leguesh@gmail.com>
1457 */
1458function idx_listIndexLengths() {
1459    global $conf;
1460    // testing what we have to do, create a cache file or not.
1461    if ($conf['readdircache'] == 0) {
1462        $docache = false;
1463    } else {
1464        clearstatcache();
1465        if (@file_exists($conf['indexdir'].'/lengths.idx')
1466        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
1467            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
1468                $idx = array();
1469                foreach ($lengths as $length) {
1470                    $idx[] = (int)$length;
1471                }
1472                return $idx;
1473            }
1474        }
1475        $docache = true;
1476    }
1477
1478    if ($conf['readdircache'] == 0 || $docache) {
1479        $dir = @opendir($conf['indexdir']);
1480        if ($dir === false)
1481            return array();
1482        $idx = array();
1483        while (($f = readdir($dir)) !== false) {
1484            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
1485                $i = substr($f, 1, -4);
1486                if (is_numeric($i))
1487                    $idx[] = (int)$i;
1488            }
1489        }
1490        closedir($dir);
1491        sort($idx);
1492        // save this in a file
1493        if ($docache) {
1494            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
1495            @fwrite($handle, implode("\n", $idx));
1496            @fclose($handle);
1497        }
1498        return $idx;
1499    }
1500
1501    return array();
1502}
1503
1504/**
1505 * Get the word lengths that have been indexed.
1506 *
1507 * Reads the index directory and returns an array of lengths
1508 * that there are indices for.
1509 *
1510 * @author YoBoY <yoboy.leguesh@gmail.com>
1511 */
1512function idx_indexLengths($filter) {
1513    global $conf;
1514    $idx = array();
1515    if (is_array($filter)) {
1516        // testing if index files exist only
1517        $path = $conf['indexdir']."/i";
1518        foreach ($filter as $key => $value) {
1519            if (@file_exists($path.$key.'.idx'))
1520                $idx[] = $key;
1521        }
1522    } else {
1523        $lengths = idx_listIndexLengths();
1524        foreach ($lengths as $key => $length) {
1525            // keep all the values equal or superior
1526            if ((int)$length >= (int)$filter)
1527                $idx[] = $length;
1528        }
1529    }
1530    return $idx;
1531}
1532
1533/**
1534 * Clean a name of a key for use as a file name.
1535 *
1536 * Romanizes non-latin characters, then strips away anything that's
1537 * not a letter, number, or underscore.
1538 *
1539 * @author Tom N Harris <tnharris@whoopdedo.org>
1540 */
1541function idx_cleanName($name) {
1542    $name = utf8_romanize(trim((string)$name));
1543    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
1544    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
1545    return strtolower($name);
1546}
1547
1548//Setup VIM: ex: et ts=4 :
1549