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