Merge pull request #2911 from dokuwiki-translate/lang_update_1395_1573893897
[dokuwiki.git] / inc / fulltext.php
blob48fe28da2f6c36d4f39adffe6101bd05807e0a3b
1 <?php
2 /**
3 * DokuWiki fulltextsearch functions using the index
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
7 */
9 use dokuwiki\Extension\Event;
11 /**
12 * create snippets for the first few results only
14 if(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15);
16 /**
17 * The fulltext search
19 * Returns a list of matching documents for the given query
21 * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
23 * @param string $query
24 * @param array $highlight
25 * @param string $sort
26 * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments
27 * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments
29 * @return array
31 function ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){
33 if ($sort === null) {
34 $sort = 'hits';
36 $data = [
37 'query' => $query,
38 'sort' => $sort,
39 'after' => $after,
40 'before' => $before
42 $data['highlight'] =& $highlight;
44 return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
47 /**
48 * Returns a list of matching documents for the given query
50 * @author Andreas Gohr <andi@splitbrain.org>
51 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
53 * @param array $data event data
54 * @return array matching documents
56 function _ft_pageSearch(&$data) {
57 $Indexer = idx_get_indexer();
59 // parse the given query
60 $q = ft_queryParser($Indexer, $data['query']);
61 $data['highlight'] = $q['highlight'];
63 if (empty($q['parsed_ary'])) return array();
65 // lookup all words found in the query
66 $lookup = $Indexer->lookup($q['words']);
68 // get all pages in this dokuwiki site (!: includes nonexistent pages)
69 $pages_all = array();
70 foreach ($Indexer->getPages() as $id) {
71 $pages_all[$id] = 0; // base: 0 hit
74 // process the query
75 $stack = array();
76 foreach ($q['parsed_ary'] as $token) {
77 switch (substr($token, 0, 3)) {
78 case 'W+:':
79 case 'W-:':
80 case 'W_:': // word
81 $word = substr($token, 3);
82 $stack[] = (array) $lookup[$word];
83 break;
84 case 'P+:':
85 case 'P-:': // phrase
86 $phrase = substr($token, 3);
87 // since phrases are always parsed as ((W1)(W2)...(P)),
88 // the end($stack) always points the pages that contain
89 // all words in this phrase
90 $pages = end($stack);
91 $pages_matched = array();
92 foreach(array_keys($pages) as $id){
93 $evdata = array(
94 'id' => $id,
95 'phrase' => $phrase,
96 'text' => rawWiki($id)
98 $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata);
99 if ($evt->advise_before() && $evt->result !== true) {
100 $text = \dokuwiki\Utf8\PhpString::strtolower($evdata['text']);
101 if (strpos($text, $phrase) !== false) {
102 $evt->result = true;
105 $evt->advise_after();
106 if ($evt->result === true) {
107 $pages_matched[$id] = 0; // phrase: always 0 hit
110 $stack[] = $pages_matched;
111 break;
112 case 'N+:':
113 case 'N-:': // namespace
114 $ns = cleanID(substr($token, 3)) . ':';
115 $pages_matched = array();
116 foreach (array_keys($pages_all) as $id) {
117 if (strpos($id, $ns) === 0) {
118 $pages_matched[$id] = 0; // namespace: always 0 hit
121 $stack[] = $pages_matched;
122 break;
123 case 'AND': // and operation
124 list($pages1, $pages2) = array_splice($stack, -2);
125 $stack[] = ft_resultCombine(array($pages1, $pages2));
126 break;
127 case 'OR': // or operation
128 list($pages1, $pages2) = array_splice($stack, -2);
129 $stack[] = ft_resultUnite(array($pages1, $pages2));
130 break;
131 case 'NOT': // not operation (unary)
132 $pages = array_pop($stack);
133 $stack[] = ft_resultComplement(array($pages_all, $pages));
134 break;
137 $docs = array_pop($stack);
139 if (empty($docs)) return array();
141 // check: settings, acls, existence
142 foreach (array_keys($docs) as $id) {
143 if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
144 unset($docs[$id]);
148 $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']);
150 if ($data['sort'] === 'mtime') {
151 uksort($docs, 'ft_pagemtimesorter');
152 } else {
153 // sort docs by count
154 arsort($docs);
157 return $docs;
161 * Returns the backlinks for a given page
163 * Uses the metadata index.
165 * @param string $id The id for which links shall be returned
166 * @param bool $ignore_perms Ignore the fact that pages are hidden or read-protected
167 * @return array The pages that contain links to the given page
169 function ft_backlinks($id, $ignore_perms = false){
170 $result = idx_get_indexer()->lookupKey('relation_references', $id);
172 if(!count($result)) return $result;
174 // check ACL permissions
175 foreach(array_keys($result) as $idx){
176 if(($ignore_perms !== true && (
177 isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
178 )) || !page_exists($result[$idx], '', false)){
179 unset($result[$idx]);
183 sort($result);
184 return $result;
188 * Returns the pages that use a given media file
190 * Uses the relation media metadata property and the metadata index.
192 * Note that before 2013-07-31 the second parameter was the maximum number of results and
193 * permissions were ignored. That's why the parameter is now checked to be explicitely set
194 * to true (with type bool) in order to be compatible with older uses of the function.
196 * @param string $id The media id to look for
197 * @param bool $ignore_perms Ignore hidden pages and acls (optional, default: false)
198 * @return array A list of pages that use the given media file
200 function ft_mediause($id, $ignore_perms = false){
201 $result = idx_get_indexer()->lookupKey('relation_media', $id);
203 if(!count($result)) return $result;
205 // check ACL permissions
206 foreach(array_keys($result) as $idx){
207 if(($ignore_perms !== true && (
208 isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
209 )) || !page_exists($result[$idx], '', false)){
210 unset($result[$idx]);
214 sort($result);
215 return $result;
220 * Quicksearch for pagenames
222 * By default it only matches the pagename and ignores the
223 * namespace. This can be changed with the second parameter.
224 * The third parameter allows to search in titles as well.
226 * The function always returns titles as well
228 * @triggers SEARCH_QUERY_PAGELOOKUP
229 * @author Andreas Gohr <andi@splitbrain.org>
230 * @author Adrian Lang <lang@cosmocode.de>
232 * @param string $id page id
233 * @param bool $in_ns match against namespace as well?
234 * @param bool $in_title search in title?
235 * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments
236 * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments
238 * @return string[]
240 function ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){
241 $data = [
242 'id' => $id,
243 'in_ns' => $in_ns,
244 'in_title' => $in_title,
245 'after' => $after,
246 'before' => $before
248 $data['has_titles'] = true; // for plugin backward compatibility check
249 return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup');
253 * Returns list of pages as array(pageid => First Heading)
255 * @param array &$data event data
256 * @return string[]
258 function _ft_pageLookup(&$data){
259 // split out original parameters
260 $id = $data['id'];
261 $Indexer = idx_get_indexer();
262 $parsedQuery = ft_queryParser($Indexer, $id);
263 if (count($parsedQuery['ns']) > 0) {
264 $ns = cleanID($parsedQuery['ns'][0]) . ':';
265 $id = implode(' ', $parsedQuery['highlight']);
268 $in_ns = $data['in_ns'];
269 $in_title = $data['in_title'];
270 $cleaned = cleanID($id);
272 $Indexer = idx_get_indexer();
273 $page_idx = $Indexer->getPages();
275 $pages = array();
276 if ($id !== '' && $cleaned !== '') {
277 foreach ($page_idx as $p_id) {
278 if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) {
279 if (!isset($pages[$p_id]))
280 $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
283 if ($in_title) {
284 foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) {
285 if (!isset($pages[$p_id]))
286 $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
291 if (isset($ns)) {
292 foreach (array_keys($pages) as $p_id) {
293 if (strpos($p_id, $ns) !== 0) {
294 unset($pages[$p_id]);
299 // discard hidden pages
300 // discard nonexistent pages
301 // check ACL permissions
302 foreach(array_keys($pages) as $idx){
303 if(!isVisiblePage($idx) || !page_exists($idx) ||
304 auth_quickaclcheck($idx) < AUTH_READ) {
305 unset($pages[$idx]);
309 $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']);
311 uksort($pages,'ft_pagesorter');
312 return $pages;
317 * @param array $results search results in the form pageid => value
318 * @param int|string $after only returns results with mtime after this date, accepts timestap or strtotime arguments
319 * @param int|string $before only returns results with mtime after this date, accepts timestap or strtotime arguments
321 * @return array
323 function _ft_filterResultsByTime(array $results, $after, $before) {
324 if ($after || $before) {
325 $after = is_int($after) ? $after : strtotime($after);
326 $before = is_int($before) ? $before : strtotime($before);
328 foreach ($results as $id => $value) {
329 $mTime = filemtime(wikiFN($id));
330 if ($after && $after > $mTime) {
331 unset($results[$id]);
332 continue;
334 if ($before && $before < $mTime) {
335 unset($results[$id]);
340 return $results;
344 * Tiny helper function for comparing the searched title with the title
345 * from the search index. This function is a wrapper around stripos with
346 * adapted argument order and return value.
348 * @param string $search searched title
349 * @param string $title title from index
350 * @return bool
352 function _ft_pageLookupTitleCompare($search, $title) {
353 return stripos($title, $search) !== false;
357 * Sort pages based on their namespace level first, then on their string
358 * values. This makes higher hierarchy pages rank higher than lower hierarchy
359 * pages.
361 * @param string $a
362 * @param string $b
363 * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal.
365 function ft_pagesorter($a, $b){
366 $ac = count(explode(':',$a));
367 $bc = count(explode(':',$b));
368 if($ac < $bc){
369 return -1;
370 }elseif($ac > $bc){
371 return 1;
373 return strcmp ($a,$b);
377 * Sort pages by their mtime, from newest to oldest
379 * @param string $a
380 * @param string $b
382 * @return int Returns < 0 if $a is newer than $b, > 0 if $b is newer than $a and 0 if they are of the same age
384 function ft_pagemtimesorter($a, $b) {
385 $mtimeA = filemtime(wikiFN($a));
386 $mtimeB = filemtime(wikiFN($b));
387 return $mtimeB - $mtimeA;
391 * Creates a snippet extract
393 * @author Andreas Gohr <andi@splitbrain.org>
394 * @triggers FULLTEXT_SNIPPET_CREATE
396 * @param string $id page id
397 * @param array $highlight
398 * @return mixed
400 function ft_snippet($id,$highlight){
401 $text = rawWiki($id);
402 $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens
403 $evdata = array(
404 'id' => $id,
405 'text' => &$text,
406 'highlight' => &$highlight,
407 'snippet' => '',
410 $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata);
411 if ($evt->advise_before()) {
412 $match = array();
413 $snippets = array();
414 $utf8_offset = $offset = $end = 0;
415 $len = \dokuwiki\Utf8\PhpString::strlen($text);
417 // build a regexp from the phrases to highlight
418 $re1 = '(' .
419 join(
420 '|',
421 array_map(
422 'ft_snippet_re_preprocess',
423 array_map(
424 'preg_quote_cb',
425 array_filter((array) $highlight)
429 ')';
430 $re2 = "$re1.{0,75}(?!\\1)$re1";
431 $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
433 for ($cnt=4; $cnt--;) {
434 if (0) {
435 } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
436 } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
437 } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
438 } else {
439 break;
442 list($str,$idx) = $match[0];
444 // convert $idx (a byte offset) into a utf8 character offset
445 $utf8_idx = \dokuwiki\Utf8\PhpString::strlen(substr($text,0,$idx));
446 $utf8_len = \dokuwiki\Utf8\PhpString::strlen($str);
448 // establish context, 100 bytes surrounding the match string
449 // first look to see if we can go 100 either side,
450 // then drop to 50 adding any excess if the other side can't go to 50,
451 $pre = min($utf8_idx-$utf8_offset,100);
452 $post = min($len-$utf8_idx-$utf8_len,100);
454 if ($pre>50 && $post>50) {
455 $pre = $post = 50;
456 } else if ($pre>50) {
457 $pre = min($pre,100-$post);
458 } else if ($post>50) {
459 $post = min($post, 100-$pre);
460 } else if ($offset == 0) {
461 // both are less than 50, means the context is the whole string
462 // make it so and break out of this loop - there is no need for the
463 // complex snippet calculations
464 $snippets = array($text);
465 break;
468 // establish context start and end points, try to append to previous
469 // context if possible
470 $start = $utf8_idx - $pre;
471 $append = ($start < $end) ? $end : false; // still the end of the previous context snippet
472 $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context
474 if ($append) {
475 $snippets[count($snippets)-1] .= \dokuwiki\Utf8\PhpString::substr($text,$append,$end-$append);
476 } else {
477 $snippets[] = \dokuwiki\Utf8\PhpString::substr($text,$start,$end-$start);
480 // set $offset for next match attempt
481 // continue matching after the current match
482 // if the current match is not the longest possible match starting at the current offset
483 // this prevents further matching of this snippet but for possible matches of length
484 // smaller than match length + context (at least 50 characters) this match is part of the context
485 $utf8_offset = $utf8_idx + $utf8_len;
486 $offset = $idx + strlen(\dokuwiki\Utf8\PhpString::substr($text,$utf8_idx,$utf8_len));
487 $offset = \dokuwiki\Utf8\Clean::correctIdx($text,$offset);
490 $m = "\1";
491 $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
492 $snippet = preg_replace(
493 '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
494 '<strong class="search_hit">$1</strong>',
495 hsc(join('... ', $snippets))
498 $evdata['snippet'] = $snippet;
500 $evt->advise_after();
501 unset($evt);
503 return $evdata['snippet'];
507 * Wraps a search term in regex boundary checks.
509 * @param string $term
510 * @return string
512 function ft_snippet_re_preprocess($term) {
513 // do not process asian terms where word boundaries are not explicit
514 if(\dokuwiki\Utf8\Asian::isAsianWords($term)) return $term;
516 if (UTF8_PROPERTYSUPPORT) {
517 // unicode word boundaries
518 // see http://stackoverflow.com/a/2449017/172068
519 $BL = '(?<!\pL)';
520 $BR = '(?!\pL)';
521 } else {
522 // not as correct as above, but at least won't break
523 $BL = '\b';
524 $BR = '\b';
527 if(substr($term,0,2) == '\\*'){
528 $term = substr($term,2);
529 }else{
530 $term = $BL.$term;
533 if(substr($term,-2,2) == '\\*'){
534 $term = substr($term,0,-2);
535 }else{
536 $term = $term.$BR;
539 if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
540 return $term;
544 * Combine found documents and sum up their scores
546 * This function is used to combine searched words with a logical
547 * AND. Only documents available in all arrays are returned.
549 * based upon PEAR's PHP_Compat function for array_intersect_key()
551 * @param array $args An array of page arrays
552 * @return array
554 function ft_resultCombine($args){
555 $array_count = count($args);
556 if($array_count == 1){
557 return $args[0];
560 $result = array();
561 if ($array_count > 1) {
562 foreach ($args[0] as $key => $value) {
563 $result[$key] = $value;
564 for ($i = 1; $i !== $array_count; $i++) {
565 if (!isset($args[$i][$key])) {
566 unset($result[$key]);
567 break;
569 $result[$key] += $args[$i][$key];
573 return $result;
577 * Unites found documents and sum up their scores
579 * based upon ft_resultCombine() function
581 * @param array $args An array of page arrays
582 * @return array
584 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
586 function ft_resultUnite($args) {
587 $array_count = count($args);
588 if ($array_count === 1) {
589 return $args[0];
592 $result = $args[0];
593 for ($i = 1; $i !== $array_count; $i++) {
594 foreach (array_keys($args[$i]) as $id) {
595 $result[$id] += $args[$i][$id];
598 return $result;
602 * Computes the difference of documents using page id for comparison
604 * nearly identical to PHP5's array_diff_key()
606 * @param array $args An array of page arrays
607 * @return array
609 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
611 function ft_resultComplement($args) {
612 $array_count = count($args);
613 if ($array_count === 1) {
614 return $args[0];
617 $result = $args[0];
618 foreach (array_keys($result) as $id) {
619 for ($i = 1; $i !== $array_count; $i++) {
620 if (isset($args[$i][$id])) unset($result[$id]);
623 return $result;
627 * Parses a search query and builds an array of search formulas
629 * @author Andreas Gohr <andi@splitbrain.org>
630 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
632 * @param Doku_Indexer $Indexer
633 * @param string $query search query
634 * @return array of search formulas
636 function ft_queryParser($Indexer, $query){
638 * parse a search query and transform it into intermediate representation
640 * in a search query, you can use the following expressions:
642 * words:
643 * include
644 * -exclude
645 * phrases:
646 * "phrase to be included"
647 * -"phrase you want to exclude"
648 * namespaces:
649 * @include:namespace (or ns:include:namespace)
650 * ^exclude:namespace (or -ns:exclude:namespace)
651 * groups:
652 * ()
653 * -()
654 * operators:
655 * and ('and' is the default operator: you can always omit this)
656 * or (or pipe symbol '|', lower precedence than 'and')
658 * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
659 * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
660 * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
661 * as long as you don't mind hit counts.
663 * intermediate representation consists of the following parts:
665 * ( ) - group
666 * AND - logical and
667 * OR - logical or
668 * NOT - logical not
669 * W+:, W-:, W_: - word (underscore: no need to highlight)
670 * P+:, P-: - phrase (minus sign: logically in NOT group)
671 * N+:, N-: - namespace
673 $parsed_query = '';
674 $parens_level = 0;
675 $terms = preg_split('/(-?".*?")/u', \dokuwiki\Utf8\PhpString::strtolower($query),
676 -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
678 foreach ($terms as $term) {
679 $parsed = '';
680 if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
681 // phrase-include and phrase-exclude
682 $not = $matches[1] ? 'NOT' : '';
683 $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
684 } else {
685 // fix incomplete phrase
686 $term = str_replace('"', ' ', $term);
688 // fix parentheses
689 $term = str_replace(')' , ' ) ', $term);
690 $term = str_replace('(' , ' ( ', $term);
691 $term = str_replace('- (', ' -(', $term);
693 // treat pipe symbols as 'OR' operators
694 $term = str_replace('|', ' or ', $term);
696 // treat ideographic spaces (U+3000) as search term separators
697 // FIXME: some more separators?
698 $term = preg_replace('/[ \x{3000}]+/u', ' ', $term);
699 $term = trim($term);
700 if ($term === '') continue;
702 $tokens = explode(' ', $term);
703 foreach ($tokens as $token) {
704 if ($token === '(') {
705 // parenthesis-include-open
706 $parsed .= '(';
707 ++$parens_level;
708 } elseif ($token === '-(') {
709 // parenthesis-exclude-open
710 $parsed .= 'NOT(';
711 ++$parens_level;
712 } elseif ($token === ')') {
713 // parenthesis-any-close
714 if ($parens_level === 0) continue;
715 $parsed .= ')';
716 $parens_level--;
717 } elseif ($token === 'and') {
718 // logical-and (do nothing)
719 } elseif ($token === 'or') {
720 // logical-or
721 $parsed .= 'OR';
722 } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
723 // namespace-exclude
724 $parsed .= 'NOT(N+:'.$matches[1].')';
725 } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
726 // namespace-include
727 $parsed .= '(N+:'.$matches[1].')';
728 } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
729 // word-exclude
730 $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
731 } else {
732 // word-include
733 $parsed .= ft_termParser($Indexer, $token);
737 $parsed_query .= $parsed;
740 // cleanup (very sensitive)
741 $parsed_query .= str_repeat(')', $parens_level);
742 do {
743 $parsed_query_old = $parsed_query;
744 $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
745 } while ($parsed_query !== $parsed_query_old);
746 $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query);
747 $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query);
748 $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query);
749 $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query);
750 $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
752 // adjustment: make highlightings right
753 $parens_level = 0;
754 $notgrp_levels = array();
755 $parsed_query_new = '';
756 $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
757 foreach ($tokens as $token) {
758 if ($token === 'NOT(') {
759 $notgrp_levels[] = ++$parens_level;
760 } elseif ($token === '(') {
761 ++$parens_level;
762 } elseif ($token === ')') {
763 if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
764 } elseif (count($notgrp_levels) % 2 === 1) {
765 // turn highlight-flag off if terms are logically in "NOT" group
766 $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
768 $parsed_query_new .= $token;
770 $parsed_query = $parsed_query_new;
773 * convert infix notation string into postfix (Reverse Polish notation) array
774 * by Shunting-yard algorithm
776 * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
777 * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
779 $parsed_ary = array();
780 $ope_stack = array();
781 $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
782 $ope_regex = '/([()]|OR|AND|NOT)/u';
784 $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
785 foreach ($tokens as $token) {
786 if (preg_match($ope_regex, $token)) {
787 // operator
788 $last_ope = end($ope_stack);
789 while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
790 $parsed_ary[] = array_pop($ope_stack);
791 $last_ope = end($ope_stack);
793 if ($token == ')') {
794 array_pop($ope_stack); // this array_pop always deletes '('
795 } else {
796 $ope_stack[] = $token;
798 } else {
799 // operand
800 $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
801 $parsed_ary[] = $token_decoded;
804 $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
806 // cleanup: each double "NOT" in RPN array actually does nothing
807 $parsed_ary_count = count($parsed_ary);
808 for ($i = 1; $i < $parsed_ary_count; ++$i) {
809 if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
810 unset($parsed_ary[$i], $parsed_ary[$i - 1]);
813 $parsed_ary = array_values($parsed_ary);
815 // build return value
816 $q = array();
817 $q['query'] = $query;
818 $q['parsed_str'] = $parsed_query;
819 $q['parsed_ary'] = $parsed_ary;
821 foreach ($q['parsed_ary'] as $token) {
822 if ($token[2] !== ':') continue;
823 $body = substr($token, 3);
825 switch (substr($token, 0, 3)) {
826 case 'N+:':
827 $q['ns'][] = $body; // for backward compatibility
828 break;
829 case 'N-:':
830 $q['notns'][] = $body; // for backward compatibility
831 break;
832 case 'W_:':
833 $q['words'][] = $body;
834 break;
835 case 'W-:':
836 $q['words'][] = $body;
837 $q['not'][] = $body; // for backward compatibility
838 break;
839 case 'W+:':
840 $q['words'][] = $body;
841 $q['highlight'][] = $body;
842 $q['and'][] = $body; // for backward compatibility
843 break;
844 case 'P-:':
845 $q['phrases'][] = $body;
846 break;
847 case 'P+:':
848 $q['phrases'][] = $body;
849 $q['highlight'][] = $body;
850 break;
853 foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) {
854 $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
857 return $q;
861 * Transforms given search term into intermediate representation
863 * This function is used in ft_queryParser() and not for general purpose use.
865 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
867 * @param Doku_Indexer $Indexer
868 * @param string $term
869 * @param bool $consider_asian
870 * @param bool $phrase_mode
871 * @return string
873 function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) {
874 $parsed = '';
875 if ($consider_asian) {
876 // successive asian characters need to be searched as a phrase
877 $words = \dokuwiki\Utf8\Asian::splitAsianWords($term);
878 foreach ($words as $word) {
879 $phrase_mode = $phrase_mode ? true : \dokuwiki\Utf8\Asian::isAsianWords($word);
880 $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
882 } else {
883 $term_noparen = str_replace(array('(', ')'), ' ', $term);
884 $words = $Indexer->tokenizer($term_noparen, true);
886 // W_: no need to highlight
887 if (empty($words)) {
888 $parsed = '()'; // important: do not remove
889 } elseif ($words[0] === $term) {
890 $parsed = '(W+:'.$words[0].')';
891 } elseif ($phrase_mode) {
892 $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
893 $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
894 } else {
895 $parsed = '((W+:'.implode(')(W+:', $words).'))';
898 return $parsed;
902 * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
904 * @param array $and
905 * @param array $not
906 * @param array $phrases
907 * @param array $ns
908 * @param array $notns
910 * @return string
912 function ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) {
913 $query = implode(' ', $and);
914 if (!empty($not)) {
915 $query .= ' -' . implode(' -', $not);
918 if (!empty($phrases)) {
919 $query .= ' "' . implode('" "', $phrases) . '"';
922 if (!empty($ns)) {
923 $query .= ' @' . implode(' @', $ns);
926 if (!empty($notns)) {
927 $query .= ' ^' . implode(' ^', $notns);
930 return $query;
933 //Setup VIM: ex: et ts=4 :