xref: /dokuwiki/inc/indexer.php (revision f77fc90de1e477b721442757cd7413f91cccc044)
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 $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) continue;
446            if (array_search($word, $stopwords) !== false) continue;
447            $words[] = $word;
448        }
449        return $words;
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.
509     *
510     * @param string    $key    name of the metadata key to look for
511     * @param string    $value  search term to look for
512     * @param callback  $func   comparison function
513     * @return array            lists with page names, keys are query values if $value is array
514     * @author Tom N Harris <tnharris@whoopdedo.org>
515     * @author Michael Hamann <michael@content-space.de>
516     */
517    public function lookupKey($key, &$value, $func=null) {
518        if (!is_array($value))
519            $value_array = array($value);
520        else
521            $value_array =& $value;
522
523        // the matching ids for the provided value(s)
524        $value_ids = array();
525
526        $metaname = idx_cleanName($key);
527
528        // get all words in order to search the matching ids
529        if ($key == 'title') {
530            $words = $this->_getIndex('title', '');
531        } else {
532            $words = $this->_getIndex($metaname, '_w');
533        }
534
535        if (!is_null($func)) {
536            foreach ($value_array as &$val) {
537                foreach ($words as $i => $word) {
538                    if (call_user_func_array($func, array(&$val, $word)))
539                        $value_ids[$i][] = $val;
540                }
541            }
542        } else {
543            foreach ($value_array as $val) {
544                $xval = $val;
545                $caret = false;
546                $dollar = false;
547                // check for wildcards
548                if (substr($xval, 0, 1) == '*') {
549                    $xval = substr($xval, 1);
550                    $caret = '^';
551                }
552                if (substr($xval, -1, 1) == '*') {
553                    $xval = substr($xval, 0, -1);
554                    $dollar = '$';
555                }
556                if ($caret || $dollar) {
557                    $re = $caret.preg_quote($xval, '/').$dollar;
558                    foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
559                        $value_ids[$i][] = $val;
560                } else {
561                    if (($i = array_search($val, $words)) !== false)
562                        $value_ids[$i][] = $val;
563                }
564            }
565        }
566
567        unset($words); // free the used memory
568
569        $result = array();
570        $page_idx = $this->_getIndex('page', '');
571
572        // Special handling for titles
573        if ($key == 'title') {
574            foreach ($value_ids as $pid => $val_list) {
575                $page = $page_idx[$pid];
576                foreach ($val_list as $val) {
577                    $result[$val][] = $page;
578                }
579            }
580        } else {
581            // load all lines and pages so the used lines can be taken and matched with the pages
582            $lines = $this->_getIndex($metaname, '_i');
583
584            foreach ($value_ids as $value_id => $val_list) {
585                // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
586                // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
587                $pages = array_keys($this->_parseTuples($page_idx, $lines[$value_id]));
588                foreach ($val_list as $val) {
589                    if (!isset($result[$val]))
590                        $result[$val] = $pages;
591                    else
592                        $result[$val] = array_merge($result[$val], $pages);
593                }
594            }
595        }
596        if (!is_array($value)) $result = $result[$value];
597        return $result;
598    }
599
600    /**
601     * Find the index ID of each search term.
602     *
603     * The query terms should only contain valid characters, with a '*' at
604     * either the beginning or end of the word (or both).
605     * The $result parameter can be used to merge the index locations with
606     * the appropriate query term.
607     *
608     * @param arrayref  $words  The query terms.
609     * @param arrayref  $result Set to word => array("length*id" ...)
610     * @return array            Set to length => array(id ...)
611     * @author Tom N Harris <tnharris@whoopdedo.org>
612     */
613    private function _getIndexWords(&$words, &$result) {
614        $tokens = array();
615        $tokenlength = array();
616        $tokenwild = array();
617        foreach ($words as $word) {
618            $result[$word] = array();
619            $caret = false;
620            $dollar = false;
621            $xword = $word;
622            $wlen = wordlen($word);
623
624            // check for wildcards
625            if (substr($xword, 0, 1) == '*') {
626                $xword = substr($xword, 1);
627                $caret = '^';
628                $wlen -= 1;
629            }
630            if (substr($xword, -1, 1) == '*') {
631                $xword = substr($xword, 0, -1);
632                $dollar = '$';
633                $wlen -= 1;
634            }
635            if ($wlen < IDX_MINWORDLENGTH && !$caret && !$dollar && !is_numeric($xword))
636                continue;
637            if (!isset($tokens[$xword]))
638                $tokenlength[$wlen][] = $xword;
639            if ($caret || $dollar) {
640                $re = $caret.preg_quote($xword, '/').$dollar;
641                $tokens[$xword][] = array($word, '/'.$re.'/');
642                if (!isset($tokenwild[$xword]))
643                    $tokenwild[$xword] = $wlen;
644            } else {
645                $tokens[$xword][] = array($word, null);
646            }
647        }
648        asort($tokenwild);
649        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
650        // $tokenlength = array( base word length => base word ... )
651        // $tokenwild = array( base word => base word length ... )
652        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
653        $indexes_known = $this->_indexLengths($length_filter);
654        if (!empty($tokenwild)) sort($indexes_known);
655        // get word IDs
656        $wids = array();
657        foreach ($indexes_known as $ixlen) {
658            $word_idx = $this->_getIndex('w', $ixlen);
659            // handle exact search
660            if (isset($tokenlength[$ixlen])) {
661                foreach ($tokenlength[$ixlen] as $xword) {
662                    $wid = array_search($xword, $word_idx);
663                    if ($wid !== false) {
664                        $wids[$ixlen][] = $wid;
665                        foreach ($tokens[$xword] as $w)
666                            $result[$w[0]][] = "$ixlen*$wid";
667                    }
668                }
669            }
670            // handle wildcard search
671            foreach ($tokenwild as $xword => $wlen) {
672                if ($wlen >= $ixlen) break;
673                foreach ($tokens[$xword] as $w) {
674                    if (is_null($w[1])) continue;
675                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
676                        $wids[$ixlen][] = $wid;
677                        $result[$w[0]][] = "$ixlen*$wid";
678                    }
679                }
680            }
681        }
682        return $wids;
683    }
684
685    /**
686     * Return a list of all pages
687     * Warning: pages may not exist!
688     *
689     * @param string    $key    list only pages containing the metadata key (optional)
690     * @return array            list of page names
691     * @author Tom N Harris <tnharris@whoopdedo.org>
692     */
693    public function getPages($key=null) {
694        $page_idx = $this->_getIndex('page', '');
695        if (is_null($key)) return $page_idx;
696
697        $metaname = idx_cleanName($key);
698
699        // Special handling for titles
700        if ($key == 'title') {
701            $title_idx = $this->_getIndex('title', '');
702            array_splice($page_idx, count($title_idx));
703            foreach ($title_idx as $i => $title)
704                if ($title === "") unset($page_idx[$i]);
705            return $page_idx;
706        }
707
708        $pages = array();
709        $lines = $this->_getIndex($metaname, '_i');
710        foreach ($lines as $line) {
711            $pages = array_merge($pages, $this->_parseTuples($page_idx, $line));
712        }
713        return array_keys($pages);
714    }
715
716    /**
717     * Return a list of words sorted by number of times used
718     *
719     * @param int       $min    bottom frequency threshold
720     * @param int       $max    upper frequency limit. No limit if $max<$min
721     * @param int       $length minimum length of words to count
722     * @param string    $key    metadata key to list. Uses the fulltext index if not given
723     * @return array            list of words as the keys and frequency as values
724     * @author Tom N Harris <tnharris@whoopdedo.org>
725     */
726    public function histogram($min=1, $max=0, $minlen=3, $key=null) {
727        if ($min < 1)
728            $min = 1;
729        if ($max < $min)
730            $max = 0;
731
732        $result = array();
733
734        if ($key == 'title') {
735            $index = $this->_getIndex('title', '');
736            $index = array_count_values($index);
737            foreach ($index as $val => $cnt) {
738                if ($cnt >= $min && (!$max || $cnt <= $max) && strlen($val) >= $minlen)
739                    $result[$val] = $cnt;
740            }
741        }
742        elseif (!is_null($key)) {
743            $metaname = idx_cleanName($key);
744            $index = $this->_getIndex($metaname.'_i', '');
745            $val_idx = array();
746            foreach ($index as $wid => $line) {
747                $freq = $this->_countTuples($line);
748                if ($freq >= $min && (!$max || $freq <= $max) && strlen($val) >= $minlen)
749                    $val_idx[$wid] = $freq;
750            }
751            if (!empty($val_idx)) {
752                $words = $this->_getIndex($metaname.'_w', '');
753                foreach ($val_idx as $wid => $freq)
754                    $result[$words[$wid]] = $freq;
755            }
756        }
757        else {
758            $lengths = idx_listIndexLengths();
759            foreach ($lengths as $length) {
760                if ($length < $minlen) continue;
761                $index = $this->_getIndex('i', $length);
762                $words = null;
763                foreach ($index as $wid => $line) {
764                    $freq = $this->_countTuples($line);
765                    if ($freq >= $min && (!$max || $freq <= $max)) {
766                        if ($words === null)
767                            $words = $this->_getIndex('w', $length);
768                        $result[$words[$wid]] = $freq;
769                    }
770                }
771            }
772        }
773
774        arsort($result);
775        return $result;
776    }
777
778    /**
779     * Lock the indexer.
780     *
781     * @author Tom N Harris <tnharris@whoopdedo.org>
782     */
783    private function _lock() {
784        global $conf;
785        $status = true;
786        $run = 0;
787        $lock = $conf['lockdir'].'/_indexer.lock';
788        while (!@mkdir($lock, $conf['dmode'])) {
789            usleep(50);
790            if(is_dir($lock) && time()-@filemtime($lock) > 60*5){
791                // looks like a stale lock - remove it
792                if (!@rmdir($lock)) {
793                    $status = "removing the stale lock failed";
794                    return false;
795                } else {
796                    $status = "stale lock removed";
797                }
798            }elseif($run++ == 1000){
799                // we waited 5 seconds for that lock
800                return false;
801            }
802        }
803        if ($conf['dperm'])
804            chmod($lock, $conf['dperm']);
805        return $status;
806    }
807
808    /**
809     * Release the indexer lock.
810     *
811     * @author Tom N Harris <tnharris@whoopdedo.org>
812     */
813    private function _unlock() {
814        global $conf;
815        @rmdir($conf['lockdir'].'/_indexer.lock');
816        return true;
817    }
818
819    /**
820     * Retrieve the entire index.
821     *
822     * @author Tom N Harris <tnharris@whoopdedo.org>
823     */
824    private function _getIndex($idx, $suffix) {
825        global $conf;
826        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
827        if (!@file_exists($fn)) return array();
828        return file($fn, FILE_IGNORE_NEW_LINES);
829    }
830
831    /**
832     * Replace the contents of the index with an array.
833     *
834     * @author Tom N Harris <tnharris@whoopdedo.org>
835     */
836    private function _saveIndex($idx, $suffix, &$lines) {
837        global $conf;
838        $fn = $conf['indexdir'].'/'.$idx.$suffix;
839        $fh = @fopen($fn.'.tmp', 'w');
840        if (!$fh) return false;
841        fwrite($fh, join("\n", $lines));
842        fclose($fh);
843        if (isset($conf['fperm']))
844            chmod($fn.'.tmp', $conf['fperm']);
845        io_rename($fn.'.tmp', $fn.'.idx');
846        if ($suffix !== '')
847            $this->_cacheIndexDir($idx, $suffix, empty($lines));
848        return true;
849    }
850
851    /**
852     * Retrieve a line from the index.
853     *
854     * @author Tom N Harris <tnharris@whoopdedo.org>
855     */
856    private function _getIndexKey($idx, $suffix, $id) {
857        global $conf;
858        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
859        if (!@file_exists($fn)) return '';
860        $fh = @fopen($fn, 'r');
861        if (!$fh) return '';
862        $ln = -1;
863        while (($line = fgets($fh)) !== false) {
864            if (++$ln == $id) break;
865        }
866        fclose($fh);
867        return rtrim((string)$line);
868    }
869
870    /**
871     * Write a line into the index.
872     *
873     * @author Tom N Harris <tnharris@whoopdedo.org>
874     */
875    private function _saveIndexKey($idx, $suffix, $id, $line) {
876        global $conf;
877        if (substr($line, -1) != "\n")
878            $line .= "\n";
879        $fn = $conf['indexdir'].'/'.$idx.$suffix;
880        $fh = @fopen($fn.'.tmp', 'w');
881        if (!fh) return false;
882        $ih = @fopen($fn.'.idx', 'r');
883        if ($ih) {
884            $ln = -1;
885            while (($curline = fgets($ih)) !== false) {
886                fwrite($fh, (++$ln == $id) ? $line : $curline);
887            }
888            if ($id > $ln) {
889                while ($id > ++$ln)
890                    fwrite($fh, "\n");
891                fwrite($fh, $line);
892            }
893            fclose($ih);
894        } else {
895            $ln = -1;
896            while ($id > ++$ln)
897                fwrite($fh, "\n");
898            fwrite($fh, $line);
899        }
900        fclose($fh);
901        if (isset($conf['fperm']))
902            chmod($fn.'.tmp', $conf['fperm']);
903        io_rename($fn.'.tmp', $fn.'.idx');
904        if ($suffix !== '')
905            $this->_cacheIndexDir($idx, $suffix);
906        return true;
907    }
908
909    /**
910     * Retrieve or insert a value in the index.
911     *
912     * @author Tom N Harris <tnharris@whoopdedo.org>
913     */
914    private function _addIndexKey($idx, $suffix, $value) {
915        $index = $this->_getIndex($idx, $suffix);
916        $id = array_search($value, $index);
917        if ($id === false) {
918            $id = count($index);
919            $index[$id] = $value;
920            if (!$this->_saveIndex($idx, $suffix, $index)) {
921                trigger_error("Failed to write $idx index", E_USER_ERROR);
922                return false;
923            }
924        }
925        return $id;
926    }
927
928    private function _cacheIndexDir($idx, $suffix, $delete=false) {
929        global $conf;
930        if ($idx == 'i')
931            $cachename = $conf['indexdir'].'/lengths';
932        else
933            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
934        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
935        if ($lengths === false) $lengths = array();
936        $old = array_search((string)$suffix, $lengths);
937        if (empty($lines)) {
938            if ($old === false) return;
939            unset($lengths[$old]);
940        } else {
941            if ($old !== false) return;
942            $lengths[] = $suffix;
943            sort($lengths);
944        }
945        $fh = @fopen($cachename.'.tmp', 'w');
946        if (!$fh) {
947            trigger_error("Failed to write index cache", E_USER_ERROR);
948            return;
949        }
950        @fwrite($fh, implode("\n", $lengths));
951        @fclose($fh);
952        if (isset($conf['fperm']))
953            chmod($cachename.'.tmp', $conf['fperm']);
954        io_rename($cachename.'.tmp', $cachename.'.idx');
955    }
956
957    /**
958     * Get the list of lengths indexed in the wiki.
959     *
960     * Read the index directory or a cache file and returns
961     * a sorted array of lengths of the words used in the wiki.
962     *
963     * @author YoBoY <yoboy.leguesh@gmail.com>
964     */
965    private function _listIndexLengths() {
966        global $conf;
967        $cachename = $conf['indexdir'].'/lengths';
968        clearstatcache();
969        if (@file_exists($cachename.'.idx')) {
970            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
971            if ($lengths !== false) {
972                $idx = array();
973                foreach ($lengths as $length)
974                    $idx[] = (int)$length;
975                return $idx;
976            }
977        }
978
979        $dir = @opendir($conf['indexdir']);
980        if ($dir === false)
981            return array();
982        $lengths[] = array();
983        while (($f = readdir($dir)) !== false) {
984            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
985                $i = substr($f, 1, -4);
986                if (is_numeric($i))
987                    $lengths[] = (int)$i;
988            }
989        }
990        closedir($dir);
991        sort($lengths);
992        // save this in a file
993        $fh = @fopen($cachename.'.tmp', 'w');
994        if (!$fh) {
995            trigger_error("Failed to write index cache", E_USER_ERROR);
996            return;
997        }
998        @fwrite($fh, implode("\n", $lengths));
999        @fclose($fh);
1000        if (isset($conf['fperm']))
1001            chmod($cachename.'.tmp', $conf['fperm']);
1002        io_rename($cachename.'.tmp', $cachename.'.idx');
1003
1004        return $lengths;
1005    }
1006
1007    /**
1008     * Get the word lengths that have been indexed.
1009     *
1010     * Reads the index directory and returns an array of lengths
1011     * that there are indices for.
1012     *
1013     * @author YoBoY <yoboy.leguesh@gmail.com>
1014     */
1015    private function _indexLengths($filter) {
1016        global $conf;
1017        $idx = array();
1018        if (is_array($filter)) {
1019            // testing if index files exist only
1020            $path = $conf['indexdir']."/i";
1021            foreach ($filter as $key => $value) {
1022                if (@file_exists($path.$key.'.idx'))
1023                    $idx[] = $key;
1024            }
1025        } else {
1026            $lengths = idx_listIndexLengths();
1027            foreach ($lengths as $key => $length) {
1028                // keep all the values equal or superior
1029                if ((int)$length >= (int)$filter)
1030                    $idx[] = $length;
1031            }
1032        }
1033        return $idx;
1034    }
1035
1036    /**
1037     * Insert or replace a tuple in a line.
1038     *
1039     * @author Tom N Harris <tnharris@whoopdedo.org>
1040     */
1041    private function _updateTuple($line, $id, $count) {
1042        $newLine = $line;
1043        if ($newLine !== '')
1044            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
1045        $newLine = trim($newLine, ':');
1046        if ($count) {
1047            if (strlen($newLine) > 0)
1048                return "$id*$count:".$newLine;
1049            else
1050                return "$id*$count".$newLine;
1051        }
1052        return $newLine;
1053    }
1054
1055    /**
1056     * Split a line into an array of tuples.
1057     *
1058     * @author Tom N Harris <tnharris@whoopdedo.org>
1059     * @author Andreas Gohr <andi@splitbrain.org>
1060     */
1061    private function _parseTuples(&$keys, $line) {
1062        $result = array();
1063        if ($line == '') return $result;
1064        $parts = explode(':', $line);
1065        foreach ($parts as $tuple) {
1066            if ($tuple == '') continue;
1067            list($key, $cnt) = explode('*', $tuple);
1068            if (!$cnt) continue;
1069            $key = $keys[$key];
1070            if (!$key) continue;
1071            $result[$key] = $cnt;
1072        }
1073        return $result;
1074    }
1075
1076    /**
1077     * Sum the counts in a list of tuples.
1078     *
1079     * @author Tom N Harris <tnharris@whoopdedo.org>
1080     */
1081    private function _countTuples($line) {
1082        $freq = 0;
1083        $parts = explode(':', $line);
1084        foreach ($parts as $tuple) {
1085            if ($tuple == '') continue;
1086            list($pid, $cnt) = explode('*', $tuple);
1087            $freq += (int)$cnt;
1088        }
1089        return $freq;
1090    }
1091}
1092
1093/**
1094 * Create an instance of the indexer.
1095 *
1096 * @return object               a Doku_Indexer
1097 * @author Tom N Harris <tnharris@whoopdedo.org>
1098 */
1099function idx_get_indexer() {
1100    static $Indexer = null;
1101    if (is_null($Indexer)) {
1102        $Indexer = new Doku_Indexer();
1103    }
1104    return $Indexer;
1105}
1106
1107/**
1108 * Returns words that will be ignored.
1109 *
1110 * @return array                list of stop words
1111 * @author Tom N Harris <tnharris@whoopdedo.org>
1112 */
1113function & idx_get_stopwords() {
1114    static $stopwords = null;
1115    if (is_null($stopwords)) {
1116        global $conf;
1117        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1118        if(@file_exists($swfile)){
1119            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
1120        }else{
1121            $stopwords = array();
1122        }
1123    }
1124    return $stopwords;
1125}
1126
1127/**
1128 * Adds/updates the search index for the given page
1129 *
1130 * Locking is handled internally.
1131 *
1132 * @param string        $page   name of the page to index
1133 * @param boolean       $verbose    print status messages
1134 * @return boolean              the function completed successfully
1135 * @author Tom N Harris <tnharris@whoopdedo.org>
1136 */
1137function idx_addPage($page, $verbose=false) {
1138    // check if indexing needed
1139    $idxtag = metaFN($page,'.indexed');
1140    if(@file_exists($idxtag)){
1141        if(trim(io_readFile($idxtag)) == idx_get_version()){
1142            $last = @filemtime($idxtag);
1143            if($last > @filemtime(wikiFN($ID))){
1144                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
1145                return false;
1146            }
1147        }
1148    }
1149
1150    if (!page_exists($page)) {
1151        if (!@file_exists($idxtag)) {
1152            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
1153            return false;
1154        }
1155        $Indexer = idx_get_indexer();
1156        $result = $Indexer->deletePage($page);
1157        if ($result === "locked") {
1158            if ($verbose) print("Indexer: locked".DOKU_LF);
1159            return false;
1160        }
1161        @unlink($idxtag);
1162        return $result;
1163    }
1164    $indexenabled = p_get_metadata($page, 'internal index', false);
1165    if ($indexenabled === false) {
1166        $result = false;
1167        if (@file_exists($idxtag)) {
1168            $Indexer = idx_get_indexer();
1169            $result = $Indexer->deletePage($page);
1170            if ($result === "locked") {
1171                if ($verbose) print("Indexer: locked".DOKU_LF);
1172                return false;
1173            }
1174            @unlink($idxtag);
1175        }
1176        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
1177        return $result;
1178    }
1179
1180    $body = '';
1181    $data = array($page, $body);
1182    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
1183    if ($evt->advise_before()) $data[1] = $data[1] . " " . rawWiki($page);
1184    $evt->advise_after();
1185    unset($evt);
1186    list($page,$body) = $data;
1187
1188    $Indexer = idx_get_indexer();
1189    $result = $Indexer->addPageWords($page, $body);
1190    if ($result === "locked") {
1191        if ($verbose) print("Indexer: locked".DOKU_LF);
1192        return false;
1193    }
1194
1195    if ($result) {
1196        $data = array('page' => $page, 'metadata' => array());
1197
1198        $data['metadata']['title'] = p_get_metadata($page, 'title', false);
1199        if (($references = p_get_metadata($page, 'relation references', false)) !== null)
1200            $data['metadata']['relation_references'] = array_keys($references);
1201
1202        $evt = new Doku_Event('INDEXER_METADATA_INDEX', $data);
1203        if ($evt->advise_before()) {
1204            $result = $Indexer->addMetaKeys($page, $data['metadata']);
1205            if ($result === "locked") {
1206                if ($verbose) print("Indexer: locked".DOKU_LF);
1207                return false;
1208            }
1209        }
1210        $evt->advise_after();
1211        unset($evt);
1212    }
1213
1214    if ($result)
1215        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
1216    if ($verbose) {
1217        print("Indexer: finished".DOKU_LF);
1218        return true;
1219    }
1220    return $result;
1221}
1222
1223/**
1224 * Find tokens in the fulltext index
1225 *
1226 * Takes an array of words and will return a list of matching
1227 * pages for each one.
1228 *
1229 * Important: No ACL checking is done here! All results are
1230 *            returned, regardless of permissions
1231 *
1232 * @param arrayref      $words  list of words to search for
1233 * @return array                list of pages found, associated with the search terms
1234 */
1235function idx_lookup(&$words) {
1236    $Indexer = idx_get_indexer();
1237    return $Indexer->lookup($words);
1238}
1239
1240/**
1241 * Split a string into tokens
1242 *
1243 */
1244function idx_tokenizer($string, $wc=false) {
1245    $Indexer = idx_get_indexer();
1246    return $Indexer->tokenizer($string, $wc);
1247}
1248
1249/* For compatibility */
1250
1251/**
1252 * Read the list of words in an index (if it exists).
1253 *
1254 * @author Tom N Harris <tnharris@whoopdedo.org>
1255 */
1256function idx_getIndex($idx, $suffix) {
1257    global $conf;
1258    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1259    if (!@file_exists($fn)) return array();
1260    return file($fn);
1261}
1262
1263/**
1264 * Get the list of lengths indexed in the wiki.
1265 *
1266 * Read the index directory or a cache file and returns
1267 * a sorted array of lengths of the words used in the wiki.
1268 *
1269 * @author YoBoY <yoboy.leguesh@gmail.com>
1270 */
1271function idx_listIndexLengths() {
1272    global $conf;
1273    // testing what we have to do, create a cache file or not.
1274    if ($conf['readdircache'] == 0) {
1275        $docache = false;
1276    } else {
1277        clearstatcache();
1278        if (@file_exists($conf['indexdir'].'/lengths.idx')
1279        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
1280            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
1281                $idx = array();
1282                foreach ($lengths as $length) {
1283                    $idx[] = (int)$length;
1284                }
1285                return $idx;
1286            }
1287        }
1288        $docache = true;
1289    }
1290
1291    if ($conf['readdircache'] == 0 || $docache) {
1292        $dir = @opendir($conf['indexdir']);
1293        if ($dir === false)
1294            return array();
1295        $idx[] = array();
1296        while (($f = readdir($dir)) !== false) {
1297            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
1298                $i = substr($f, 1, -4);
1299                if (is_numeric($i))
1300                    $idx[] = (int)$i;
1301            }
1302        }
1303        closedir($dir);
1304        sort($idx);
1305        // save this in a file
1306        if ($docache) {
1307            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
1308            @fwrite($handle, implode("\n", $idx));
1309            @fclose($handle);
1310        }
1311        return $idx;
1312    }
1313
1314    return array();
1315}
1316
1317/**
1318 * Get the word lengths that have been indexed.
1319 *
1320 * Reads the index directory and returns an array of lengths
1321 * that there are indices for.
1322 *
1323 * @author YoBoY <yoboy.leguesh@gmail.com>
1324 */
1325function idx_indexLengths($filter) {
1326    global $conf;
1327    $idx = array();
1328    if (is_array($filter)) {
1329        // testing if index files exist only
1330        $path = $conf['indexdir']."/i";
1331        foreach ($filter as $key => $value) {
1332            if (@file_exists($path.$key.'.idx'))
1333                $idx[] = $key;
1334        }
1335    } else {
1336        $lengths = idx_listIndexLengths();
1337        foreach ($lengths as $key => $length) {
1338            // keep all the values equal or superior
1339            if ((int)$length >= (int)$filter)
1340                $idx[] = $length;
1341        }
1342    }
1343    return $idx;
1344}
1345
1346/**
1347 * Clean a name of a key for use as a file name.
1348 *
1349 * Romanizes non-latin characters, then strips away anything that's
1350 * not a letter, number, or underscore.
1351 *
1352 * @author Tom N Harris <tnharris@whoopdedo.org>
1353 */
1354function idx_cleanName($name) {
1355    $name = utf8_romanize(trim((string)$name));
1356    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
1357    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
1358    return strtolower($name);
1359}
1360
1361//Setup VIM: ex: et ts=4 :
1362