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