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