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