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