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