replaced deprecated utf8 functions
[dokuwiki.git] / inc / fulltext.php
blob155fcf9f157b452811cf17c0ca315d92ef6a94d3
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 */use dokuwiki\Extension\Event;
9 /**
10 * create snippets for the first few results only
12 if(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15);
14 /**
15 * The fulltext search
17 * Returns a list of matching documents for the given query
19 * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
21 * @param string $query
22 * @param array $highlight
23 * @param string $sort
24 * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments
25 * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments
27 * @return array
29 function ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){
31 if ($sort === null) {
32 $sort = 'hits';
34 $data = [
35 'query' => $query,
36 'sort' => $sort,
37 'after' => $after,
38 'before' => $before
40 $data['highlight'] =& $highlight;
42 return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
45 /**
46 * Returns a list of matching documents for the given query
48 * @author Andreas Gohr <andi@splitbrain.org>
49 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
51 * @param array $data event data
52 * @return array matching documents
54 function _ft_pageSearch(&$data) {
55 $Indexer = idx_get_indexer();
57 // parse the given query
58 $q = ft_queryParser($Indexer, $data['query']);
59 $data['highlight'] = $q['highlight'];
61 if (empty($q['parsed_ary'])) return array();
63 // lookup all words found in the query
64 $lookup = $Indexer->lookup($q['words']);
66 // get all pages in this dokuwiki site (!: includes nonexistent pages)
67 $pages_all = array();
68 foreach ($Indexer->getPages() as $id) {
69 $pages_all[$id] = 0; // base: 0 hit
72 // process the query
73 $stack = array();
74 foreach ($q['parsed_ary'] as $token) {
75 switch (substr($token, 0, 3)) {
76 case 'W+:':
77 case 'W-:':
78 case 'W_:': // word
79 $word = substr($token, 3);
80 $stack[] = (array) $lookup[$word];
81 break;
82 case 'P+:':
83 case 'P-:': // phrase
84 $phrase = substr($token, 3);
85 // since phrases are always parsed as ((W1)(W2)...(P)),
86 // the end($stack) always points the pages that contain
87 // all words in this phrase
88 $pages = end($stack);
89 $pages_matched = array();
90 foreach(array_keys($pages) as $id){
91 $evdata = array(
92 'id' => $id,
93 'phrase' => $phrase,
94 'text' => rawWiki($id)
96 $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata);
97 if ($evt->advise_before() && $evt->result !== true) {
98 $text = \dokuwiki\Utf8\PhpString::strtolower($evdata['text']);
99 if (strpos($text, $phrase) !== false) {
100 $evt->result = true;
103 $evt->advise_after();
104 if ($evt->result === true) {
105 $pages_matched[$id] = 0; // phrase: always 0 hit
108 $stack[] = $pages_matched;
109 break;
110 case 'N+:':
111 case 'N-:': // namespace
112 $ns = cleanID(substr($token, 3)) . ':';
113 $pages_matched = array();
114 foreach (array_keys($pages_all) as $id) {
115 if (strpos($id, $ns) === 0) {
116 $pages_matched[$id] = 0; // namespace: always 0 hit
119 $stack[] = $pages_matched;
120 break;
121 case 'AND': // and operation
122 list($pages1, $pages2) = array_splice($stack, -2);
123 $stack[] = ft_resultCombine(array($pages1, $pages2));
124 break;
125 case 'OR': // or operation
126 list($pages1, $pages2) = array_splice($stack, -2);
127 $stack[] = ft_resultUnite(array($pages1, $pages2));
128 break;
129 case 'NOT': // not operation (unary)
130 $pages = array_pop($stack);
131 $stack[] = ft_resultComplement(array($pages_all, $pages));
132 break;
135 $docs = array_pop($stack);
137 if (empty($docs)) return array();
139 // check: settings, acls, existence
140 foreach (array_keys($docs) as $id) {
141 if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
142 unset($docs[$id]);
146 $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']);
148 if ($data['sort'] === 'mtime') {
149 uksort($docs, 'ft_pagemtimesorter');
150 } else {
151 // sort docs by count
152 arsort($docs);
155 return $docs;
159 * Returns the backlinks for a given page
161 * Uses the metadata index.
163 * @param string $id The id for which links shall be returned
164 * @param bool $ignore_perms Ignore the fact that pages are hidden or read-protected
165 * @return array The pages that contain links to the given page
167 function ft_backlinks($id, $ignore_perms = false){
168 $result = idx_get_indexer()->lookupKey('relation_references', $id);
170 if(!count($result)) return $result;
172 // check ACL permissions
173 foreach(array_keys($result) as $idx){
174 if(($ignore_perms !== true && (
175 isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
176 )) || !page_exists($result[$idx], '', false)){
177 unset($result[$idx]);
181 sort($result);
182 return $result;
186 * Returns the pages that use a given media file
188 * Uses the relation media metadata property and the metadata index.
190 * Note that before 2013-07-31 the second parameter was the maximum number of results and
191 * permissions were ignored. That's why the parameter is now checked to be explicitely set
192 * to true (with type bool) in order to be compatible with older uses of the function.
194 * @param string $id The media id to look for
195 * @param bool $ignore_perms Ignore hidden pages and acls (optional, default: false)
196 * @return array A list of pages that use the given media file
198 function ft_mediause($id, $ignore_perms = false){
199 $result = idx_get_indexer()->lookupKey('relation_media', $id);
201 if(!count($result)) return $result;
203 // check ACL permissions
204 foreach(array_keys($result) as $idx){
205 if(($ignore_perms !== true && (
206 isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
207 )) || !page_exists($result[$idx], '', false)){
208 unset($result[$idx]);
212 sort($result);
213 return $result;
218 * Quicksearch for pagenames
220 * By default it only matches the pagename and ignores the
221 * namespace. This can be changed with the second parameter.
222 * The third parameter allows to search in titles as well.
224 * The function always returns titles as well
226 * @triggers SEARCH_QUERY_PAGELOOKUP
227 * @author Andreas Gohr <andi@splitbrain.org>
228 * @author Adrian Lang <lang@cosmocode.de>
230 * @param string $id page id
231 * @param bool $in_ns match against namespace as well?
232 * @param bool $in_title search in title?
233 * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments
234 * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments
236 * @return string[]
238 function ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){
239 $data = [
240 'id' => $id,
241 'in_ns' => $in_ns,
242 'in_title' => $in_title,
243 'after' => $after,
244 'before' => $before
246 $data['has_titles'] = true; // for plugin backward compatibility check
247 return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup');
251 * Returns list of pages as array(pageid => First Heading)
253 * @param array &$data event data
254 * @return string[]
256 function _ft_pageLookup(&$data){
257 // split out original parameters
258 $id = $data['id'];
259 $Indexer = idx_get_indexer();
260 $parsedQuery = ft_queryParser($Indexer, $id);
261 if (count($parsedQuery['ns']) > 0) {
262 $ns = cleanID($parsedQuery['ns'][0]) . ':';
263 $id = implode(' ', $parsedQuery['highlight']);
266 $in_ns = $data['in_ns'];
267 $in_title = $data['in_title'];
268 $cleaned = cleanID($id);
270 $Indexer = idx_get_indexer();
271 $page_idx = $Indexer->getPages();
273 $pages = array();
274 if ($id !== '' && $cleaned !== '') {
275 foreach ($page_idx as $p_id) {
276 if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) {
277 if (!isset($pages[$p_id]))
278 $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
281 if ($in_title) {
282 foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) {
283 if (!isset($pages[$p_id]))
284 $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
289 if (isset($ns)) {
290 foreach (array_keys($pages) as $p_id) {
291 if (strpos($p_id, $ns) !== 0) {
292 unset($pages[$p_id]);
297 // discard hidden pages
298 // discard nonexistent pages
299 // check ACL permissions
300 foreach(array_keys($pages) as $idx){
301 if(!isVisiblePage($idx) || !page_exists($idx) ||
302 auth_quickaclcheck($idx) < AUTH_READ) {
303 unset($pages[$idx]);
307 $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']);
309 uksort($pages,'ft_pagesorter');
310 return $pages;
315 * @param array $results search results in the form pageid => value
316 * @param int|string $after only returns results with mtime after this date, accepts timestap or strtotime arguments
317 * @param int|string $before only returns results with mtime after this date, accepts timestap or strtotime arguments
319 * @return array
321 function _ft_filterResultsByTime(array $results, $after, $before) {
322 if ($after || $before) {
323 $after = is_int($after) ? $after : strtotime($after);
324 $before = is_int($before) ? $before : strtotime($before);
326 foreach ($results as $id => $value) {
327 $mTime = filemtime(wikiFN($id));
328 if ($after && $after > $mTime) {
329 unset($results[$id]);
330 continue;
332 if ($before && $before < $mTime) {
333 unset($results[$id]);
338 return $results;
342 * Tiny helper function for comparing the searched title with the title
343 * from the search index. This function is a wrapper around stripos with
344 * adapted argument order and return value.
346 * @param string $search searched title
347 * @param string $title title from index
348 * @return bool
350 function _ft_pageLookupTitleCompare($search, $title) {
351 return stripos($title, $search) !== false;
355 * Sort pages based on their namespace level first, then on their string
356 * values. This makes higher hierarchy pages rank higher than lower hierarchy
357 * pages.
359 * @param string $a
360 * @param string $b
361 * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal.
363 function ft_pagesorter($a, $b){
364 $ac = count(explode(':',$a));
365 $bc = count(explode(':',$b));
366 if($ac < $bc){
367 return -1;
368 }elseif($ac > $bc){
369 return 1;
371 return strcmp ($a,$b);
375 * Sort pages by their mtime, from newest to oldest
377 * @param string $a
378 * @param string $b
380 * @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
382 function ft_pagemtimesorter($a, $b) {
383 $mtimeA = filemtime(wikiFN($a));
384 $mtimeB = filemtime(wikiFN($b));
385 return $mtimeB - $mtimeA;
389 * Creates a snippet extract
391 * @author Andreas Gohr <andi@splitbrain.org>
392 * @triggers FULLTEXT_SNIPPET_CREATE
394 * @param string $id page id
395 * @param array $highlight
396 * @return mixed
398 function ft_snippet($id,$highlight){
399 $text = rawWiki($id);
400 $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens
401 $evdata = array(
402 'id' => $id,
403 'text' => &$text,
404 'highlight' => &$highlight,
405 'snippet' => '',
408 $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata);
409 if ($evt->advise_before()) {
410 $match = array();
411 $snippets = array();
412 $utf8_offset = $offset = $end = 0;
413 $len = \dokuwiki\Utf8\PhpString::strlen($text);
415 // build a regexp from the phrases to highlight
416 $re1 = '(' .
417 join(
418 '|',
419 array_map(
420 'ft_snippet_re_preprocess',
421 array_map(
422 'preg_quote_cb',
423 array_filter((array) $highlight)
427 ')';
428 $re2 = "$re1.{0,75}(?!\\1)$re1";
429 $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
431 for ($cnt=4; $cnt--;) {
432 if (0) {
433 } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
434 } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
435 } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
436 } else {
437 break;
440 list($str,$idx) = $match[0];
442 // convert $idx (a byte offset) into a utf8 character offset
443 $utf8_idx = \dokuwiki\Utf8\PhpString::strlen(substr($text,0,$idx));
444 $utf8_len = \dokuwiki\Utf8\PhpString::strlen($str);
446 // establish context, 100 bytes surrounding the match string
447 // first look to see if we can go 100 either side,
448 // then drop to 50 adding any excess if the other side can't go to 50,
449 $pre = min($utf8_idx-$utf8_offset,100);
450 $post = min($len-$utf8_idx-$utf8_len,100);
452 if ($pre>50 && $post>50) {
453 $pre = $post = 50;
454 } else if ($pre>50) {
455 $pre = min($pre,100-$post);
456 } else if ($post>50) {
457 $post = min($post, 100-$pre);
458 } else if ($offset == 0) {
459 // both are less than 50, means the context is the whole string
460 // make it so and break out of this loop - there is no need for the
461 // complex snippet calculations
462 $snippets = array($text);
463 break;
466 // establish context start and end points, try to append to previous
467 // context if possible
468 $start = $utf8_idx - $pre;
469 $append = ($start < $end) ? $end : false; // still the end of the previous context snippet
470 $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context
472 if ($append) {
473 $snippets[count($snippets)-1] .= \dokuwiki\Utf8\PhpString::substr($text,$append,$end-$append);
474 } else {
475 $snippets[] = \dokuwiki\Utf8\PhpString::substr($text,$start,$end-$start);
478 // set $offset for next match attempt
479 // continue matching after the current match
480 // if the current match is not the longest possible match starting at the current offset
481 // this prevents further matching of this snippet but for possible matches of length
482 // smaller than match length + context (at least 50 characters) this match is part of the context
483 $utf8_offset = $utf8_idx + $utf8_len;
484 $offset = $idx + strlen(\dokuwiki\Utf8\PhpString::substr($text,$utf8_idx,$utf8_len));
485 $offset = \dokuwiki\Utf8\Clean::correctIdx($text,$offset);
488 $m = "\1";
489 $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
490 $snippet = preg_replace(
491 '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
492 '<strong class="search_hit">$1</strong>',
493 hsc(join('... ', $snippets))
496 $evdata['snippet'] = $snippet;
498 $evt->advise_after();
499 unset($evt);
501 return $evdata['snippet'];
505 * Wraps a search term in regex boundary checks.
507 * @param string $term
508 * @return string
510 function ft_snippet_re_preprocess($term) {
511 // do not process asian terms where word boundaries are not explicit
512 if(preg_match('/'.IDX_ASIAN.'/u',$term)){
513 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), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
677 foreach ($terms as $term) {
678 $parsed = '';
679 if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
680 // phrase-include and phrase-exclude
681 $not = $matches[1] ? 'NOT' : '';
682 $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
683 } else {
684 // fix incomplete phrase
685 $term = str_replace('"', ' ', $term);
687 // fix parentheses
688 $term = str_replace(')' , ' ) ', $term);
689 $term = str_replace('(' , ' ( ', $term);
690 $term = str_replace('- (', ' -(', $term);
692 // treat pipe symbols as 'OR' operators
693 $term = str_replace('|', ' or ', $term);
695 // treat ideographic spaces (U+3000) as search term separators
696 // FIXME: some more separators?
697 $term = preg_replace('/[ \x{3000}]+/u', ' ', $term);
698 $term = trim($term);
699 if ($term === '') continue;
701 $tokens = explode(' ', $term);
702 foreach ($tokens as $token) {
703 if ($token === '(') {
704 // parenthesis-include-open
705 $parsed .= '(';
706 ++$parens_level;
707 } elseif ($token === '-(') {
708 // parenthesis-exclude-open
709 $parsed .= 'NOT(';
710 ++$parens_level;
711 } elseif ($token === ')') {
712 // parenthesis-any-close
713 if ($parens_level === 0) continue;
714 $parsed .= ')';
715 $parens_level--;
716 } elseif ($token === 'and') {
717 // logical-and (do nothing)
718 } elseif ($token === 'or') {
719 // logical-or
720 $parsed .= 'OR';
721 } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
722 // namespace-exclude
723 $parsed .= 'NOT(N+:'.$matches[1].')';
724 } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
725 // namespace-include
726 $parsed .= '(N+:'.$matches[1].')';
727 } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
728 // word-exclude
729 $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
730 } else {
731 // word-include
732 $parsed .= ft_termParser($Indexer, $token);
736 $parsed_query .= $parsed;
739 // cleanup (very sensitive)
740 $parsed_query .= str_repeat(')', $parens_level);
741 do {
742 $parsed_query_old = $parsed_query;
743 $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
744 } while ($parsed_query !== $parsed_query_old);
745 $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query);
746 $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query);
747 $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query);
748 $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query);
749 $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
751 // adjustment: make highlightings right
752 $parens_level = 0;
753 $notgrp_levels = array();
754 $parsed_query_new = '';
755 $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
756 foreach ($tokens as $token) {
757 if ($token === 'NOT(') {
758 $notgrp_levels[] = ++$parens_level;
759 } elseif ($token === '(') {
760 ++$parens_level;
761 } elseif ($token === ')') {
762 if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
763 } elseif (count($notgrp_levels) % 2 === 1) {
764 // turn highlight-flag off if terms are logically in "NOT" group
765 $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
767 $parsed_query_new .= $token;
769 $parsed_query = $parsed_query_new;
772 * convert infix notation string into postfix (Reverse Polish notation) array
773 * by Shunting-yard algorithm
775 * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
776 * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
778 $parsed_ary = array();
779 $ope_stack = array();
780 $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
781 $ope_regex = '/([()]|OR|AND|NOT)/u';
783 $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
784 foreach ($tokens as $token) {
785 if (preg_match($ope_regex, $token)) {
786 // operator
787 $last_ope = end($ope_stack);
788 while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
789 $parsed_ary[] = array_pop($ope_stack);
790 $last_ope = end($ope_stack);
792 if ($token == ')') {
793 array_pop($ope_stack); // this array_pop always deletes '('
794 } else {
795 $ope_stack[] = $token;
797 } else {
798 // operand
799 $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
800 $parsed_ary[] = $token_decoded;
803 $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
805 // cleanup: each double "NOT" in RPN array actually does nothing
806 $parsed_ary_count = count($parsed_ary);
807 for ($i = 1; $i < $parsed_ary_count; ++$i) {
808 if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
809 unset($parsed_ary[$i], $parsed_ary[$i - 1]);
812 $parsed_ary = array_values($parsed_ary);
814 // build return value
815 $q = array();
816 $q['query'] = $query;
817 $q['parsed_str'] = $parsed_query;
818 $q['parsed_ary'] = $parsed_ary;
820 foreach ($q['parsed_ary'] as $token) {
821 if ($token[2] !== ':') continue;
822 $body = substr($token, 3);
824 switch (substr($token, 0, 3)) {
825 case 'N+:':
826 $q['ns'][] = $body; // for backward compatibility
827 break;
828 case 'N-:':
829 $q['notns'][] = $body; // for backward compatibility
830 break;
831 case 'W_:':
832 $q['words'][] = $body;
833 break;
834 case 'W-:':
835 $q['words'][] = $body;
836 $q['not'][] = $body; // for backward compatibility
837 break;
838 case 'W+:':
839 $q['words'][] = $body;
840 $q['highlight'][] = $body;
841 $q['and'][] = $body; // for backward compatibility
842 break;
843 case 'P-:':
844 $q['phrases'][] = $body;
845 break;
846 case 'P+:':
847 $q['phrases'][] = $body;
848 $q['highlight'][] = $body;
849 break;
852 foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) {
853 $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
856 return $q;
860 * Transforms given search term into intermediate representation
862 * This function is used in ft_queryParser() and not for general purpose use.
864 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
866 * @param Doku_Indexer $Indexer
867 * @param string $term
868 * @param bool $consider_asian
869 * @param bool $phrase_mode
870 * @return string
872 function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) {
873 $parsed = '';
874 if ($consider_asian) {
875 // successive asian characters need to be searched as a phrase
876 $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
877 foreach ($words as $word) {
878 $phrase_mode = $phrase_mode ? true : preg_match('/'.IDX_ASIAN.'/u', $word);
879 $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
881 } else {
882 $term_noparen = str_replace(array('(', ')'), ' ', $term);
883 $words = $Indexer->tokenizer($term_noparen, true);
885 // W_: no need to highlight
886 if (empty($words)) {
887 $parsed = '()'; // important: do not remove
888 } elseif ($words[0] === $term) {
889 $parsed = '(W+:'.$words[0].')';
890 } elseif ($phrase_mode) {
891 $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
892 $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
893 } else {
894 $parsed = '((W+:'.implode(')(W+:', $words).'))';
897 return $parsed;
901 * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
903 * @param array $and
904 * @param array $not
905 * @param array $phrases
906 * @param array $ns
907 * @param array $notns
909 * @return string
911 function ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) {
912 $query = implode(' ', $and);
913 if (!empty($not)) {
914 $query .= ' -' . implode(' -', $not);
917 if (!empty($phrases)) {
918 $query .= ' "' . implode('" "', $phrases) . '"';
921 if (!empty($ns)) {
922 $query .= ' @' . implode(' @', $ns);
925 if (!empty($notns)) {
926 $query .= ' ^' . implode(' ^', $notns);
929 return $query;
932 //Setup VIM: ex: et ts=4 :