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