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