xref: /dokuwiki/inc/fulltext.php (revision 865296af7db64bdb24a3e9a25c17f6c4621d4ae6)
1<?php
2/**
3 * DokuWiki fulltextsearch functions using the index
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9if(!defined('DOKU_INC')) die('meh.');
10require_once(DOKU_INC.'inc/indexer.php');
11
12
13/**
14 * The fulltext search
15 *
16 * Returns a list of matching documents for the given query
17 *
18 * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
19 *
20 */
21function ft_pageSearch($query,&$highlight){
22
23  $data['query'] = $query;
24  $data['highlight'] =& $highlight;
25
26  return trigger_event('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
27}
28
29/**
30 * Returns a list of matching documents for the given query
31 *
32 * @author Andreas Gohr <andi@splitbrain.org>
33 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
34 */
35function _ft_pageSearch(&$data) {
36    // parse the given query
37    $q = ft_queryParser($data['query']);
38    $data['highlight'] = $q['highlight'];
39
40    if (empty($q['parsed_ary'])) return array();
41
42    // lookup all words found in the query
43    $lookup = idx_lookup($q['words']);
44
45    // get all pages in this dokuwiki site (!: includes nonexistent pages)
46    $pages_all = array();
47    foreach (idx_getIndex('page', '') as $id) {
48        $pages_all[trim($id)] = 0; // base: 0 hit
49    }
50
51    // process the query
52    $stack = array();
53    foreach ($q['parsed_ary'] as $token) {
54        switch (substr($token, 0, 3)) {
55            case 'W+:':
56            case 'W-:': // word
57                $word    = substr($token, 3);
58                $stack[] = (array) $lookup[$word];
59                break;
60            case 'P_:': // phrase
61                $phrase = substr($token, 3);
62                // since phrases are always parsed as ((W1)(W2)...(P)),
63                // the end($stack) always points the pages that contain
64                // all words in this phrase
65                $pages  = end($stack);
66                $pages_matched = array();
67                foreach(array_keys($pages) as $id){
68                    $text = utf8_strtolower(rawWiki($id));
69                    if (strpos($text, $phrase) !== false) {
70                        $pages_matched[$id] = 0; // phrase: always 0 hit
71                    }
72                }
73                $stack[] = $pages_matched;
74                break;
75            case 'N_:': // namespace
76                $ns = substr($token, 3);
77                $pages_matched = array();
78                foreach (array_keys($pages_all) as $id) {
79                    if (strpos($id, $ns) === 0) {
80                        $pages_matched[$id] = 0; // namespace: always 0 hit
81                    }
82                }
83                $stack[] = $pages_matched;
84                break;
85            case 'AND': // and operation
86                list($pages1, $pages2) = array_splice($stack, -2);
87                $stack[] = ft_resultCombine(array($pages1, $pages2));
88                break;
89            case 'OR':  // or operation
90                list($pages1, $pages2) = array_splice($stack, -2);
91                $stack[] = ft_resultUnite(array($pages1, $pages2));
92                break;
93            case 'NOT': // not operation (unary)
94                $pages   = array_pop($stack);
95                $stack[] = ft_resultComplement(array($pages_all, $pages));
96                break;
97        }
98    }
99    $docs = array_pop($stack);
100
101    if (empty($docs)) return array();
102
103    // check: settings, acls, existence
104    foreach (array_keys($docs) as $id) {
105        if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
106            unset($docs[$id]);
107        }
108    }
109
110    // sort docs by count
111    arsort($docs);
112
113    return $docs;
114}
115
116/**
117 * Returns the backlinks for a given page
118 *
119 * Does a quick lookup with the fulltext index, then
120 * evaluates the instructions of the found pages
121 */
122function ft_backlinks($id){
123    global $conf;
124    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
125    $stopwords = @file_exists($swfile) ? file($swfile) : array();
126
127    $result = array();
128
129    // quick lookup of the pagename
130    $page    = noNS($id);
131    $matches = idx_lookup(idx_tokenizer($page,$stopwords));  // pagename may contain specials (_ or .)
132    $docs    = array_keys(ft_resultCombine(array_values($matches)));
133    $docs    = array_filter($docs,'isVisiblePage'); // discard hidden pages
134    if(!count($docs)) return $result;
135    require_once(DOKU_INC.'inc/parserutils.php');
136
137    // check metadata for matching links
138    foreach($docs as $match){
139        // metadata relation reference links are already resolved
140        $links = p_get_metadata($match,'relation references');
141        if (isset($links[$id])) $result[] = $match;
142    }
143
144    if(!count($result)) return $result;
145
146    // check ACL permissions
147    foreach(array_keys($result) as $idx){
148        if(auth_quickaclcheck($result[$idx]) < AUTH_READ){
149            unset($result[$idx]);
150        }
151    }
152
153    sort($result);
154    return $result;
155}
156
157/**
158 * Returns the pages that use a given media file
159 *
160 * Does a quick lookup with the fulltext index, then
161 * evaluates the instructions of the found pages
162 *
163 * Aborts after $max found results
164 */
165function ft_mediause($id,$max){
166    global $conf;
167    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
168    $stopwords = @file_exists($swfile) ? file($swfile) : array();
169
170    if(!$max) $max = 1; // need to find at least one
171
172    $result = array();
173
174    // quick lookup of the mediafile
175    $media   = noNS($id);
176    $matches = idx_lookup(idx_tokenizer($media,$stopwords));
177    $docs    = array_keys(ft_resultCombine(array_values($matches)));
178    if(!count($docs)) return $result;
179
180    // go through all found pages
181    $found = 0;
182    $pcre  = preg_quote($media,'/');
183    foreach($docs as $doc){
184        $ns = getNS($doc);
185        preg_match_all('/\{\{([^|}]*'.$pcre.'[^|}]*)(|[^}]+)?\}\}/i',rawWiki($doc),$matches);
186        foreach($matches[1] as $img){
187            $img = trim($img);
188            if(preg_match('/^https?:\/\//i',$img)) continue; // skip external images
189            list($img) = explode('?',$img);                  // remove any parameters
190            resolve_mediaid($ns,$img,$exists);               // resolve the possibly relative img
191
192            if($img == $id){                                 // we have a match
193                $result[] = $doc;
194                $found++;
195                break;
196            }
197        }
198        if($found >= $max) break;
199    }
200
201    sort($result);
202    return $result;
203}
204
205
206
207/**
208 * Quicksearch for pagenames
209 *
210 * By default it only matches the pagename and ignores the
211 * namespace. This can be changed with the second parameter
212 *
213 * refactored into ft_pageLookup(), _ft_pageLookup() and trigger_event()
214 *
215 * @author Andreas Gohr <andi@splitbrain.org>
216 */
217function ft_pageLookup($id,$pageonly=true){
218    $data = array('id' => $id, 'pageonly' => $pageonly);
219    return trigger_event('SEARCH_QUERY_PAGELOOKUP',$data,'_ft_pageLookup');
220}
221
222function _ft_pageLookup(&$data){
223    // split out original parameterrs
224    $id = $data['id'];
225    $pageonly = $data['pageonly'];
226
227    global $conf;
228    $id    = preg_quote($id,'/');
229    $pages = file($conf['indexdir'].'/page.idx');
230    if($id) $pages = array_values(preg_grep('/'.$id.'/',$pages));
231
232    $cnt = count($pages);
233    for($i=0; $i<$cnt; $i++){
234        if($pageonly){
235            if(!preg_match('/'.$id.'/',noNS($pages[$i]))){
236                unset($pages[$i]);
237                continue;
238            }
239        }
240        if(!page_exists($pages[$i])){
241            unset($pages[$i]);
242            continue;
243        }
244    }
245
246    $pages = array_filter($pages,'isVisiblePage'); // discard hidden pages
247    if(!count($pages)) return array();
248
249    // check ACL permissions
250    foreach(array_keys($pages) as $idx){
251        if(auth_quickaclcheck(trim($pages[$idx])) < AUTH_READ){
252            unset($pages[$idx]);
253        }
254    }
255
256    $pages = array_map('trim',$pages);
257    usort($pages,'ft_pagesorter');
258    return $pages;
259}
260
261/**
262 * Sort pages based on their namespace level first, then on their string
263 * values. This makes higher hierarchy pages rank higher than lower hierarchy
264 * pages.
265 */
266function ft_pagesorter($a, $b){
267    $ac = count(explode(':',$a));
268    $bc = count(explode(':',$b));
269    if($ac < $bc){
270        return -1;
271    }elseif($ac > $bc){
272        return 1;
273    }
274    return strcmp ($a,$b);
275}
276
277/**
278 * Creates a snippet extract
279 *
280 * @author Andreas Gohr <andi@splitbrain.org>
281 */
282function ft_snippet($id,$highlight){
283    $text     = rawWiki($id);
284    $match = array();
285    $snippets = array();
286    $utf8_offset = $offset = $end = 0;
287    $len = utf8_strlen($text);
288
289    // build a regexp from the phrases to highlight
290    $re1 = '('.join('|',array_map('preg_quote_cb',array_filter((array) $highlight))).')';
291    $re2 = "$re1.{0,75}(?!\\1)$re1";
292    $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
293
294    for ($cnt=4; $cnt--;) {
295      if (0) {
296      } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
297      } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
298      } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
299      } else {
300        break;
301      }
302
303      list($str,$idx) = $match[0];
304
305      // convert $idx (a byte offset) into a utf8 character offset
306      $utf8_idx = utf8_strlen(substr($text,0,$idx));
307      $utf8_len = utf8_strlen($str);
308
309      // establish context, 100 bytes surrounding the match string
310      // first look to see if we can go 100 either side,
311      // then drop to 50 adding any excess if the other side can't go to 50,
312      $pre = min($utf8_idx-$utf8_offset,100);
313      $post = min($len-$utf8_idx-$utf8_len,100);
314
315      if ($pre>50 && $post>50) {
316        $pre = $post = 50;
317      } else if ($pre>50) {
318        $pre = min($pre,100-$post);
319      } else if ($post>50) {
320        $post = min($post, 100-$pre);
321      } else {
322        // both are less than 50, means the context is the whole string
323        // make it so and break out of this loop - there is no need for the
324        // complex snippet calculations
325        $snippets = array($text);
326        break;
327      }
328
329      // establish context start and end points, try to append to previous
330      // context if possible
331      $start = $utf8_idx - $pre;
332      $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
333      $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
334
335      if ($append) {
336        $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append);
337      } else {
338        $snippets[] = utf8_substr($text,$start,$end-$start);
339      }
340
341      // set $offset for next match attempt
342      //   substract strlen to avoid splitting a potential search success,
343      //   this is an approximation as the search pattern may match strings
344      //   of varying length and it will fail if the context snippet
345      //   boundary breaks a matching string longer than the current match
346      $utf8_offset = $utf8_idx + $post;
347      $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$post));
348      $offset = utf8_correctIdx($text,$offset);
349    }
350
351    $m = "\1";
352    $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
353    $snippet = preg_replace('/'.$m.'([^'.$m.']*?)'.$m.'/iu','<strong class="search_hit">$1</strong>',hsc(join('... ',$snippets)));
354
355    return $snippet;
356}
357
358/**
359 * Combine found documents and sum up their scores
360 *
361 * This function is used to combine searched words with a logical
362 * AND. Only documents available in all arrays are returned.
363 *
364 * based upon PEAR's PHP_Compat function for array_intersect_key()
365 *
366 * @param array $args An array of page arrays
367 */
368function ft_resultCombine($args){
369    $array_count = count($args);
370    if($array_count == 1){
371        return $args[0];
372    }
373
374    $result = array();
375    if ($array_count > 1) {
376      foreach ($args[0] as $key => $value) {
377        $result[$key] = $value;
378        for ($i = 1; $i !== $array_count; $i++) {
379            if (!isset($args[$i][$key])) {
380                unset($result[$key]);
381                break;
382            }
383            $result[$key] += $args[$i][$key];
384        }
385      }
386    }
387    return $result;
388}
389
390/**
391 * Unites found documents and sum up their scores
392 *
393 * based upon ft_resultCombine() function
394 *
395 * @param array $args An array of page arrays
396 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
397 */
398function ft_resultUnite($args) {
399    $array_count = count($args);
400    if ($array_count === 1) {
401        return $args[0];
402    }
403
404    $result = $args[0];
405    for ($i = 1; $i !== $array_count; $i++) {
406        foreach (array_keys($args[$i]) as $id) {
407            $result[$id] += $args[$i][$id];
408        }
409    }
410    return $result;
411}
412
413/**
414 * Computes the difference of documents using page id for comparison
415 *
416 * nearly identical to PHP5's array_diff_key()
417 *
418 * @param array $args An array of page arrays
419 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
420 */
421function ft_resultComplement($args) {
422    $array_count = count($args);
423    if ($array_count === 1) {
424        return $args[0];
425    }
426
427    $result = $args[0];
428    foreach (array_keys($result) as $id) {
429        for ($i = 1; $i !== $array_count; $i++) {
430            if (isset($args[$i][$id])) unset($result[$id]);
431        }
432    }
433    return $result;
434}
435
436/**
437 * Parses a search query and builds an array of search formulas
438 *
439 * @author Andreas Gohr <andi@splitbrain.org>
440 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
441 */
442function ft_queryParser($query){
443    global $conf;
444    $swfile    = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
445    $stopwords = @file_exists($swfile) ? file($swfile) : array();
446
447    /**
448     * parse a search query and transform it into intermediate representation
449     *
450     * in a search query, you can use the following expressions:
451     *
452     *   words:
453     *     include
454     *     -exclude
455     *   phrases:
456     *     "phrase to be included"
457     *     -"phrase you want to exclude"
458     *   namespaces:
459     *     @include:namespace (or ns:include:namespace)
460     *     ^exclude:namespace (or -ns:exclude:namespace)
461     *   groups:
462     *     ()
463     *     -()
464     *   operators:
465     *     and ('and' is the default operator: you can always omit this)
466     *     or  (or pipe symbol '|', lower precedence than 'and')
467     *
468     * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
469     *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
470     *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
471     *      as long as you don't mind hit counts.
472     *
473     * intermediate representation consists of the following parts:
474     *
475     *   ( ) - group
476     *   AND - logical and
477     *   OR  - logical or
478     *   NOT - logical not
479     *   W+: - word (needs to be highlighted)
480     *   W-: - word (no need to highlight)
481     *   P_: - phrase
482     *   N_: - namespace
483     */
484    $parsed_query = '';
485    $parens_level = 0;
486    $terms = preg_split('/(-?".*?")/u', utf8_strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
487
488    foreach ($terms as $term) {
489        $parsed = '';
490        if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
491            // phrase-include and phrase-exclude
492            $not = $matches[1] ? 'NOT' : '';
493            $parsed = $not.ft_termParser($matches[2], $stopwords, false, true);
494        } else {
495            // fix incomplete phrase
496            $term = str_replace('"', ' ', $term);
497
498            // fix parentheses
499            $term = str_replace(')'  , ' ) ', $term);
500            $term = str_replace('('  , ' ( ', $term);
501            $term = str_replace('- (', ' -(', $term);
502
503            // treat pipe symbols as 'OR' operators
504            $term = str_replace('|', ' or ', $term);
505
506            // treat ideographic spaces (U+3000) as search term separators
507            // FIXME: some more separators?
508            $term = preg_replace('/[ \x{3000}]+/u', ' ',  $term);
509            $term = trim($term);
510            if ($term === '') continue;
511
512            $tokens = explode(' ', $term);
513            foreach ($tokens as $token) {
514                if ($token === '(') {
515                    // parenthesis-include-open
516                    $parsed .= '(';
517                    ++$parens_level;
518                } elseif ($token === '-(') {
519                    // parenthesis-exclude-open
520                    $parsed .= 'NOT(';
521                    ++$parens_level;
522                } elseif ($token === ')') {
523                    // parenthesis-any-close
524                    if ($parens_level === 0) continue;
525                    $parsed .= ')';
526                    $parens_level--;
527                } elseif ($token === 'and') {
528                    // logical-and (do nothing)
529                } elseif ($token === 'or') {
530                    // logical-or
531                    $parsed .= 'OR';
532                } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
533                    // namespace-exclude
534                    $parsed .= 'NOT(N_:'.$matches[1].')';
535                } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
536                    // namespace-include
537                    $parsed .= '(N_:'.$matches[1].')';
538                } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
539                    // word-exclude
540                    $parsed .= 'NOT('.ft_termParser($matches[1], $stopwords).')';
541                } else {
542                    // word-include
543                    $parsed .= ft_termParser($token, $stopwords);
544                }
545            }
546        }
547        $parsed_query .= $parsed;
548    }
549
550    // cleanup (very sensitive)
551    $parsed_query .= str_repeat(')', $parens_level);
552    do {
553        $parsed_query_old = $parsed_query;
554        $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
555    } while ($parsed_query !== $parsed_query_old);
556    $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')'      , $parsed_query);
557    $parsed_query = preg_replace('/(OR)+/u'      , 'OR'     , $parsed_query);
558    $parsed_query = preg_replace('/\(OR/u'       , '('      , $parsed_query);
559    $parsed_query = preg_replace('/^OR|OR$/u'    , ''       , $parsed_query);
560    $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
561
562    /**
563     * convert infix notation string into postfix (Reverse Polish notation) array
564     * by Shunting-yard algorithm
565     *
566     * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
567     * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
568     */
569    $parsed_ary     = array();
570    $ope_stack      = array();
571    $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
572    $ope_regex      = '/([()]|OR|AND|NOT)/u';
573
574    $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
575    foreach ($tokens as $token) {
576        if (preg_match($ope_regex, $token)) {
577            // operator
578            $last_ope = end($ope_stack);
579            while ($ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
580                $parsed_ary[] = array_pop($ope_stack);
581                $last_ope = end($ope_stack);
582            }
583            if ($token == ')') {
584                array_pop($ope_stack); // this array_pop always deletes '('
585            } else {
586                $ope_stack[] = $token;
587            }
588        } else {
589            // operand
590            $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
591            $parsed_ary[] = $token_decoded;
592        }
593    }
594    $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
595
596    // cleanup: each double "NOT" in RPN array actually does nothing
597    $parsed_ary_count = count($parsed_ary);
598    for ($i = 1; $i < $parsed_ary_count; ++$i) {
599        if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
600            unset($parsed_ary[$i], $parsed_ary[$i - 1]);
601        }
602    }
603    $parsed_ary = array_values($parsed_ary);
604
605    // build return value
606    $q = array();
607    $q['query']      = $query;
608    $q['parsed_str'] = $parsed_query;
609    $q['parsed_ary'] = $parsed_ary;
610
611    foreach ($q['parsed_ary'] as $token) {
612        if ($token[2] !== ':') continue;
613        $body = substr($token, 3);
614
615        switch (substr($token, 0, 3)) {
616            case 'N_:':
617                $q['ns'][]        = $body; // for backward compatibility
618                break;
619            case 'W-:':
620                $q['words'][]     = $body;
621                break;
622            case 'W+:':
623                $q['words'][]     = $body;
624                $q['highlight'][] = str_replace('*', '', $body);
625                break;
626            case 'P_:':
627                $q['phrases'][]   = $body;
628                $q['highlight'][] = str_replace('*', '', $body);
629                break;
630        }
631    }
632    foreach (array('words', 'phrases', 'highlight', 'ns') as $key) {
633        $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
634    }
635
636    // keep backward compatibility (to some extent)
637    // this part can be deleted if no plugins use ft_queryParser() directly
638    $q['and']   = $q['words'];
639    $q['not']   = array(); // difficult to set: imagine [ aaa -(bbb -ccc) ]
640    $q['notns'] = array(); // same as above
641
642    return $q;
643}
644
645/**
646 * Transforms given search term into intermediate representation
647 *
648 * This function is used in ft_queryParser() and not for general purpose use.
649 *
650 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
651 */
652function ft_termParser($term, &$stopwords, $consider_asian = true, $phrase_mode = false) {
653    $parsed = '';
654    if ($consider_asian) {
655        // successive asian characters need to be searched as a phrase
656        $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
657        foreach ($words as $word) {
658            if (preg_match('/'.IDX_ASIAN.'/u', $word)) $phrase_mode = true;
659            $parsed .= ft_termParser($word, $stopwords, false, $phrase_mode);
660        }
661    } else {
662        $term_noparen = str_replace(array('(', ')'), ' ', $term);
663        $words = idx_tokenizer($term_noparen, $stopwords, true);
664
665        // W+: needs to be highlighted, W-: no need to highlight
666        if (empty($words)) {
667            $parsed = '()'; // important: do not remove
668        } elseif ($words[0] === $term) {
669            $parsed = '(W+:'.$words[0].')';
670        } elseif ($phrase_mode) {
671            $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
672            $parsed = '((W-:'.implode(')(W-:', $words).')(P_:'.$term_encoded.'))';
673        } else {
674            $parsed = '((W+:'.implode(')(W+:', $words).'))';
675        }
676    }
677    return $parsed;
678}
679
680//Setup VIM: ex: et ts=4 enc=utf-8 :
681