xref: /dokuwiki/inc/fulltext.php (revision 5afd9580edc06cca1314f98041cb1a26b42e7bb5)
1f5eb7cf0SAndreas Gohr<?php
2f5eb7cf0SAndreas Gohr/**
3f5eb7cf0SAndreas Gohr * DokuWiki fulltextsearch functions using the index
4f5eb7cf0SAndreas Gohr *
5f5eb7cf0SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6f5eb7cf0SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
727f63a23SAndreas Gohr */
827f63a23SAndreas Gohr
927f63a23SAndreas Gohruse dokuwiki\Extension\Event;
102d85e841SAndreas Gohruse dokuwiki\Utf8\Sort;
11f5eb7cf0SAndreas Gohr
12bd0293e7SAndreas Gohr/**
13bd0293e7SAndreas Gohr * create snippets for the first few results only
14bd0293e7SAndreas Gohr */
15bd0293e7SAndreas Gohrif(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15);
16f5eb7cf0SAndreas Gohr
17f5eb7cf0SAndreas Gohr/**
18f5eb7cf0SAndreas Gohr * The fulltext search
19f5eb7cf0SAndreas Gohr *
20f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query
21506fa893SAndreas Gohr *
226840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
236840140fSChris Smith *
2442ea7f44SGerrit Uitslag * @param string     $query
2542ea7f44SGerrit Uitslag * @param array      $highlight
263850270cSMichael Große * @param string     $sort
2764159a61SAndreas Gohr * @param int|string $after  only show results with mtime after this date, accepts timestap or strtotime arguments
2864159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments
293850270cSMichael Große *
3042ea7f44SGerrit Uitslag * @return array
31f5eb7cf0SAndreas Gohr */
323850270cSMichael Großefunction ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){
336840140fSChris Smith
343850270cSMichael Große    if ($sort === null) {
353850270cSMichael Große        $sort = 'hits';
363850270cSMichael Große    }
373850270cSMichael Große    $data = [
383850270cSMichael Große        'query' => $query,
393850270cSMichael Große        'sort' => $sort,
403850270cSMichael Große        'after' => $after,
413850270cSMichael Große        'before' => $before
423850270cSMichael Große    ];
436840140fSChris Smith    $data['highlight'] =& $highlight;
446840140fSChris Smith
45cbb44eabSAndreas Gohr    return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
466840140fSChris Smith}
47865c2687SKazutaka Miyasaka
48865c2687SKazutaka Miyasaka/**
49865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query
50865c2687SKazutaka Miyasaka *
51865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
52865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
5342ea7f44SGerrit Uitslag *
5442ea7f44SGerrit Uitslag * @param array $data event data
5542ea7f44SGerrit Uitslag * @return array matching documents
56865c2687SKazutaka Miyasaka */
576840140fSChris Smithfunction _ft_pageSearch(&$data) {
589b41be24STom N Harris    $Indexer = idx_get_indexer();
599b41be24STom N Harris
60865c2687SKazutaka Miyasaka    // parse the given query
619b41be24STom N Harris    $q = ft_queryParser($Indexer, $data['query']);
62865c2687SKazutaka Miyasaka    $data['highlight'] = $q['highlight'];
636840140fSChris Smith
64865c2687SKazutaka Miyasaka    if (empty($q['parsed_ary'])) return array();
65506fa893SAndreas Gohr
66f5eb7cf0SAndreas Gohr    // lookup all words found in the query
679b41be24STom N Harris    $lookup = $Indexer->lookup($q['words']);
68f5eb7cf0SAndreas Gohr
69865c2687SKazutaka Miyasaka    // get all pages in this dokuwiki site (!: includes nonexistent pages)
70865c2687SKazutaka Miyasaka    $pages_all = array();
719b41be24STom N Harris    foreach ($Indexer->getPages() as $id) {
729b41be24STom N Harris        $pages_all[$id] = 0; // base: 0 hit
73f5eb7cf0SAndreas Gohr    }
74f5eb7cf0SAndreas Gohr
75865c2687SKazutaka Miyasaka    // process the query
76865c2687SKazutaka Miyasaka    $stack = array();
77865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
78865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
79865c2687SKazutaka Miyasaka            case 'W+:':
802f502d70SKazutaka Miyasaka            case 'W-:':
812f502d70SKazutaka Miyasaka            case 'W_:': // word
82865c2687SKazutaka Miyasaka                $word    = substr($token, 3);
83*5afd9580SAndreas Gohr                if(isset($lookup[$word])) {
84865c2687SKazutaka Miyasaka                    $stack[] = (array)$lookup[$word];
85*5afd9580SAndreas Gohr                }
86865c2687SKazutaka Miyasaka                break;
872f502d70SKazutaka Miyasaka            case 'P+:':
882f502d70SKazutaka Miyasaka            case 'P-:': // phrase
89865c2687SKazutaka Miyasaka                $phrase = substr($token, 3);
90865c2687SKazutaka Miyasaka                // since phrases are always parsed as ((W1)(W2)...(P)),
91865c2687SKazutaka Miyasaka                // the end($stack) always points the pages that contain
92865c2687SKazutaka Miyasaka                // all words in this phrase
93865c2687SKazutaka Miyasaka                $pages  = end($stack);
94865c2687SKazutaka Miyasaka                $pages_matched = array();
95865c2687SKazutaka Miyasaka                foreach(array_keys($pages) as $id){
96a7e8b43eSMichael Hamann                    $evdata = array(
97a7e8b43eSMichael Hamann                        'id' => $id,
98a7e8b43eSMichael Hamann                        'phrase' => $phrase,
99a7e8b43eSMichael Hamann                        'text' => rawWiki($id)
100a7e8b43eSMichael Hamann                    );
101e1d9dcc8SAndreas Gohr                    $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata);
102a7e8b43eSMichael Hamann                    if ($evt->advise_before() && $evt->result !== true) {
1038cbc5ee8SAndreas Gohr                        $text = \dokuwiki\Utf8\PhpString::strtolower($evdata['text']);
104865c2687SKazutaka Miyasaka                        if (strpos($text, $phrase) !== false) {
105a7e8b43eSMichael Hamann                            $evt->result = true;
106a7e8b43eSMichael Hamann                        }
107a7e8b43eSMichael Hamann                    }
108a7e8b43eSMichael Hamann                    $evt->advise_after();
109a7e8b43eSMichael Hamann                    if ($evt->result === true) {
110865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // phrase: always 0 hit
111865c2687SKazutaka Miyasaka                    }
112865c2687SKazutaka Miyasaka                }
113865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
114865c2687SKazutaka Miyasaka                break;
1152f502d70SKazutaka Miyasaka            case 'N+:':
1162f502d70SKazutaka Miyasaka            case 'N-:': // namespace
117de3383c6SMichael Große                $ns = cleanID(substr($token, 3)) . ':';
118865c2687SKazutaka Miyasaka                $pages_matched = array();
119865c2687SKazutaka Miyasaka                foreach (array_keys($pages_all) as $id) {
120865c2687SKazutaka Miyasaka                    if (strpos($id, $ns) === 0) {
121865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // namespace: always 0 hit
122865c2687SKazutaka Miyasaka                    }
123865c2687SKazutaka Miyasaka                }
124865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
125865c2687SKazutaka Miyasaka                break;
126865c2687SKazutaka Miyasaka            case 'AND': // and operation
127865c2687SKazutaka Miyasaka                list($pages1, $pages2) = array_splice($stack, -2);
128865c2687SKazutaka Miyasaka                $stack[] = ft_resultCombine(array($pages1, $pages2));
129865c2687SKazutaka Miyasaka                break;
130865c2687SKazutaka Miyasaka            case 'OR':  // or operation
131865c2687SKazutaka Miyasaka                list($pages1, $pages2) = array_splice($stack, -2);
132865c2687SKazutaka Miyasaka                $stack[] = ft_resultUnite(array($pages1, $pages2));
133865c2687SKazutaka Miyasaka                break;
134865c2687SKazutaka Miyasaka            case 'NOT': // not operation (unary)
135865c2687SKazutaka Miyasaka                $pages   = array_pop($stack);
136865c2687SKazutaka Miyasaka                $stack[] = ft_resultComplement(array($pages_all, $pages));
137a21136cdSAndreas Gohr                break;
138a21136cdSAndreas Gohr        }
139f5eb7cf0SAndreas Gohr    }
140865c2687SKazutaka Miyasaka    $docs = array_pop($stack);
141865c2687SKazutaka Miyasaka
142865c2687SKazutaka Miyasaka    if (empty($docs)) return array();
143865c2687SKazutaka Miyasaka
144865c2687SKazutaka Miyasaka    // check: settings, acls, existence
145865c2687SKazutaka Miyasaka    foreach (array_keys($docs) as $id) {
146865c2687SKazutaka Miyasaka        if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
147865c2687SKazutaka Miyasaka            unset($docs[$id]);
148f5eb7cf0SAndreas Gohr        }
149f5eb7cf0SAndreas Gohr    }
150f5eb7cf0SAndreas Gohr
1513850270cSMichael Große    $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']);
1528d0e286aSMichael Große
1538d0e286aSMichael Große    if ($data['sort'] === 'mtime') {
1548d0e286aSMichael Große        uksort($docs, 'ft_pagemtimesorter');
1558d0e286aSMichael Große    } else {
156865c2687SKazutaka Miyasaka        // sort docs by count
15706281c9cSMoisés Braga Ribeiro        uksort($docs, 'ft_pagesorter');
158f5eb7cf0SAndreas Gohr        arsort($docs);
1598d0e286aSMichael Große    }
160f5eb7cf0SAndreas Gohr
161f5eb7cf0SAndreas Gohr    return $docs;
162f5eb7cf0SAndreas Gohr}
163f5eb7cf0SAndreas Gohr
164f5eb7cf0SAndreas Gohr/**
16554f4c056SAndreas Gohr * Returns the backlinks for a given page
16654f4c056SAndreas Gohr *
167320f489aSMichael Hamann * Uses the metadata index.
16807ff0babSMichael Hamann *
16907ff0babSMichael Hamann * @param string $id           The id for which links shall be returned
17007ff0babSMichael Hamann * @param bool   $ignore_perms Ignore the fact that pages are hidden or read-protected
17107ff0babSMichael Hamann * @return array The pages that contain links to the given page
17254f4c056SAndreas Gohr */
17307ff0babSMichael Hamannfunction ft_backlinks($id, $ignore_perms = false){
174320f489aSMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_references', $id);
17554f4c056SAndreas Gohr
17663773904SAndreas Gohr    if(!count($result)) return $result;
17763773904SAndreas Gohr
17863773904SAndreas Gohr    // check ACL permissions
17963773904SAndreas Gohr    foreach(array_keys($result) as $idx){
18007ff0babSMichael Hamann        if(($ignore_perms !== true && (
18107ff0babSMichael Hamann                isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
18207ff0babSMichael Hamann            )) || !page_exists($result[$idx], '', false)){
18363773904SAndreas Gohr            unset($result[$idx]);
18463773904SAndreas Gohr        }
18563773904SAndreas Gohr    }
18663773904SAndreas Gohr
1872d85e841SAndreas Gohr    Sort::sort($result);
18854f4c056SAndreas Gohr    return $result;
18954f4c056SAndreas Gohr}
19054f4c056SAndreas Gohr
19154f4c056SAndreas Gohr/**
192a05e297aSAndreas Gohr * Returns the pages that use a given media file
193a05e297aSAndreas Gohr *
194ffec1009SMichael Hamann * Uses the relation media metadata property and the metadata index.
195a05e297aSAndreas Gohr *
196ffec1009SMichael Hamann * Note that before 2013-07-31 the second parameter was the maximum number of results and
197ffec1009SMichael Hamann * permissions were ignored. That's why the parameter is now checked to be explicitely set
198ffec1009SMichael Hamann * to true (with type bool) in order to be compatible with older uses of the function.
199ffec1009SMichael Hamann *
200ffec1009SMichael Hamann * @param string $id           The media id to look for
201ffec1009SMichael Hamann * @param bool   $ignore_perms Ignore hidden pages and acls (optional, default: false)
202ffec1009SMichael Hamann * @return array A list of pages that use the given media file
203a05e297aSAndreas Gohr */
204ffec1009SMichael Hamannfunction ft_mediause($id, $ignore_perms = false){
205ffec1009SMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_media', $id);
206a05e297aSAndreas Gohr
207ffec1009SMichael Hamann    if(!count($result)) return $result;
208a05e297aSAndreas Gohr
209ffec1009SMichael Hamann    // check ACL permissions
210ffec1009SMichael Hamann    foreach(array_keys($result) as $idx){
211ffec1009SMichael Hamann        if(($ignore_perms !== true && (
212ffec1009SMichael Hamann                    isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
213ffec1009SMichael Hamann                )) || !page_exists($result[$idx], '', false)){
214ffec1009SMichael Hamann            unset($result[$idx]);
215a05e297aSAndreas Gohr        }
216a05e297aSAndreas Gohr    }
217a05e297aSAndreas Gohr
2182d85e841SAndreas Gohr    Sort::sort($result);
219a05e297aSAndreas Gohr    return $result;
220a05e297aSAndreas Gohr}
221a05e297aSAndreas Gohr
222a05e297aSAndreas Gohr
223a05e297aSAndreas Gohr/**
224506fa893SAndreas Gohr * Quicksearch for pagenames
225506fa893SAndreas Gohr *
226506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
22780423ab6SAdrian Lang * namespace. This can be changed with the second parameter.
22880423ab6SAdrian Lang * The third parameter allows to search in titles as well.
229506fa893SAndreas Gohr *
2308d22f1e9SAndreas Gohr * The function always returns titles as well
2316840140fSChris Smith *
2328d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP
233506fa893SAndreas Gohr * @author   Andreas Gohr <andi@splitbrain.org>
2348d22f1e9SAndreas Gohr * @author   Adrian Lang <lang@cosmocode.de>
23542ea7f44SGerrit Uitslag *
23642ea7f44SGerrit Uitslag * @param string     $id       page id
23742ea7f44SGerrit Uitslag * @param bool       $in_ns    match against namespace as well?
23842ea7f44SGerrit Uitslag * @param bool       $in_title search in title?
23964159a61SAndreas Gohr * @param int|string $after    only show results with mtime after this date, accepts timestap or strtotime arguments
24064159a61SAndreas Gohr * @param int|string $before   only show results with mtime before this date, accepts timestap or strtotime arguments
2413850270cSMichael Große *
24242ea7f44SGerrit Uitslag * @return string[]
243506fa893SAndreas Gohr */
2443850270cSMichael Großefunction ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){
2453850270cSMichael Große    $data = [
2463850270cSMichael Große        'id' => $id,
2473850270cSMichael Große        'in_ns' => $in_ns,
2483850270cSMichael Große        'in_title' => $in_title,
2493850270cSMichael Große        'after' => $after,
2503850270cSMichael Große        'before' => $before
2513850270cSMichael Große    ];
2528d22f1e9SAndreas Gohr    $data['has_titles'] = true; // for plugin backward compatibility check
253cbb44eabSAndreas Gohr    return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup');
2546840140fSChris Smith}
2556840140fSChris Smith
25642ea7f44SGerrit Uitslag/**
25742ea7f44SGerrit Uitslag * Returns list of pages as array(pageid => First Heading)
25842ea7f44SGerrit Uitslag *
25942ea7f44SGerrit Uitslag * @param array &$data event data
26042ea7f44SGerrit Uitslag * @return string[]
26142ea7f44SGerrit Uitslag */
2626840140fSChris Smithfunction _ft_pageLookup(&$data){
26380423ab6SAdrian Lang    // split out original parameters
2646840140fSChris Smith    $id = $data['id'];
265940f24fcSMichael Große    $Indexer = idx_get_indexer();
266940f24fcSMichael Große    $parsedQuery = ft_queryParser($Indexer, $id);
267940f24fcSMichael Große    if (count($parsedQuery['ns']) > 0) {
268940f24fcSMichael Große        $ns = cleanID($parsedQuery['ns'][0]) . ':';
269940f24fcSMichael Große        $id = implode(' ', $parsedQuery['highlight']);
270b0f6db0cSAdrian Lang    }
271b0f6db0cSAdrian Lang
2728d22f1e9SAndreas Gohr    $in_ns    = $data['in_ns'];
2738d22f1e9SAndreas Gohr    $in_title = $data['in_title'];
27480423ab6SAdrian Lang    $cleaned = cleanID($id);
2759b41be24STom N Harris
2769b41be24STom N Harris    $Indexer = idx_get_indexer();
2779b41be24STom N Harris    $page_idx = $Indexer->getPages();
2789b41be24STom N Harris
2799b41be24STom N Harris    $pages = array();
2805479a8c3SAndreas Gohr    if ($id !== '' && $cleaned !== '') {
2819b41be24STom N Harris        foreach ($page_idx as $p_id) {
2829b41be24STom N Harris            if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) {
2839b41be24STom N Harris                if (!isset($pages[$p_id]))
28467c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
285506fa893SAndreas Gohr            }
286506fa893SAndreas Gohr        }
287f078bb00STom N Harris        if ($in_title) {
288c66f16a3SMichael Hamann            foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) {
289f078bb00STom N Harris                if (!isset($pages[$p_id]))
29067c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
291f078bb00STom N Harris            }
292f078bb00STom N Harris        }
293d0bdf765SAdrian Lang    }
2940c074a52SMichael Hamann
295d0bdf765SAdrian Lang    if (isset($ns)) {
2960c074a52SMichael Hamann        foreach (array_keys($pages) as $p_id) {
2970c074a52SMichael Hamann            if (strpos($p_id, $ns) !== 0) {
2980c074a52SMichael Hamann                unset($pages[$p_id]);
299d0bdf765SAdrian Lang            }
300d0bdf765SAdrian Lang        }
301506fa893SAndreas Gohr    }
30263773904SAndreas Gohr
30380423ab6SAdrian Lang    // discard hidden pages
30480423ab6SAdrian Lang    // discard nonexistent pages
30563773904SAndreas Gohr    // check ACL permissions
30663773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
30780423ab6SAdrian Lang        if(!isVisiblePage($idx) || !page_exists($idx) ||
30880423ab6SAdrian Lang           auth_quickaclcheck($idx) < AUTH_READ) {
30963773904SAndreas Gohr            unset($pages[$idx]);
31063773904SAndreas Gohr        }
31163773904SAndreas Gohr    }
31263773904SAndreas Gohr
3133850270cSMichael Große    $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']);
3141b48999cSMichael Große
3153d2017d9SAdrian Lang    uksort($pages,'ft_pagesorter');
3168d22f1e9SAndreas Gohr    return $pages;
317506fa893SAndreas Gohr}
318506fa893SAndreas Gohr
3191b48999cSMichael Große
3201b48999cSMichael Große/**
3211b48999cSMichael Große * @param array      $results search results in the form pageid => value
32264159a61SAndreas Gohr * @param int|string $after   only returns results with mtime after this date, accepts timestap or strtotime arguments
32364159a61SAndreas Gohr * @param int|string $before  only returns results with mtime after this date, accepts timestap or strtotime arguments
3241b48999cSMichael Große *
3251b48999cSMichael Große * @return array
3261b48999cSMichael Große */
3273850270cSMichael Großefunction _ft_filterResultsByTime(array $results, $after, $before) {
3283850270cSMichael Große    if ($after || $before) {
3291b48999cSMichael Große        $after = is_int($after) ? $after : strtotime($after);
3301b48999cSMichael Große        $before = is_int($before) ? $before : strtotime($before);
3311b48999cSMichael Große
3321b48999cSMichael Große        foreach ($results as $id => $value) {
3331b48999cSMichael Große            $mTime = filemtime(wikiFN($id));
3341b48999cSMichael Große            if ($after && $after > $mTime) {
3351b48999cSMichael Große                unset($results[$id]);
3361b48999cSMichael Große                continue;
3371b48999cSMichael Große            }
3381b48999cSMichael Große            if ($before && $before < $mTime) {
3391b48999cSMichael Große                unset($results[$id]);
3401b48999cSMichael Große            }
3411b48999cSMichael Große        }
3421b48999cSMichael Große    }
3431b48999cSMichael Große
3441b48999cSMichael Große    return $results;
3451b48999cSMichael Große}
3461b48999cSMichael Große
347506fa893SAndreas Gohr/**
348c66f16a3SMichael Hamann * Tiny helper function for comparing the searched title with the title
349c66f16a3SMichael Hamann * from the search index. This function is a wrapper around stripos with
350c66f16a3SMichael Hamann * adapted argument order and return value.
35142ea7f44SGerrit Uitslag *
35242ea7f44SGerrit Uitslag * @param string $search searched title
35342ea7f44SGerrit Uitslag * @param string $title  title from index
35442ea7f44SGerrit Uitslag * @return bool
355c66f16a3SMichael Hamann */
356c66f16a3SMichael Hamannfunction _ft_pageLookupTitleCompare($search, $title) {
357c66f16a3SMichael Hamann    return stripos($title, $search) !== false;
358c66f16a3SMichael Hamann}
359c66f16a3SMichael Hamann
360c66f16a3SMichael Hamann/**
361f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string
362f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy
363f31eb72bSAndreas Gohr * pages.
36442ea7f44SGerrit Uitslag *
36542ea7f44SGerrit Uitslag * @param string $a
36642ea7f44SGerrit Uitslag * @param string $b
36742ea7f44SGerrit Uitslag * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal.
368f31eb72bSAndreas Gohr */
369f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){
370f31eb72bSAndreas Gohr    $ac = count(explode(':',$a));
371f31eb72bSAndreas Gohr    $bc = count(explode(':',$b));
372f31eb72bSAndreas Gohr    if($ac < $bc){
373f31eb72bSAndreas Gohr        return -1;
374f31eb72bSAndreas Gohr    }elseif($ac > $bc){
375f31eb72bSAndreas Gohr        return 1;
376f31eb72bSAndreas Gohr    }
3772d85e841SAndreas Gohr    return Sort::strcmp($a,$b);
378f31eb72bSAndreas Gohr}
379f31eb72bSAndreas Gohr
380f31eb72bSAndreas Gohr/**
3818d0e286aSMichael Große * Sort pages by their mtime, from newest to oldest
3828d0e286aSMichael Große *
3838d0e286aSMichael Große * @param string $a
3848d0e286aSMichael Große * @param string $b
3858d0e286aSMichael Große *
3868d0e286aSMichael Große * @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
3878d0e286aSMichael Große */
3888d0e286aSMichael Großefunction ft_pagemtimesorter($a, $b) {
3898d0e286aSMichael Große    $mtimeA = filemtime(wikiFN($a));
3908d0e286aSMichael Große    $mtimeB = filemtime(wikiFN($b));
3918d0e286aSMichael Große    return $mtimeB - $mtimeA;
3928d0e286aSMichael Große}
3938d0e286aSMichael Große
3948d0e286aSMichael Große/**
395506fa893SAndreas Gohr * Creates a snippet extract
396506fa893SAndreas Gohr *
397506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
39860e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE
39942ea7f44SGerrit Uitslag *
40042ea7f44SGerrit Uitslag * @param string $id page id
40142ea7f44SGerrit Uitslag * @param array $highlight
40242ea7f44SGerrit Uitslag * @return mixed
403506fa893SAndreas Gohr */
404546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){
405506fa893SAndreas Gohr    $text = rawWiki($id);
4064f0030ddSAndreas Gohr    $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens
40760e91a17SAndreas Gohr    $evdata = array(
40860e91a17SAndreas Gohr            'id'        => $id,
40960e91a17SAndreas Gohr            'text'      => &$text,
41060e91a17SAndreas Gohr            'highlight' => &$highlight,
41160e91a17SAndreas Gohr            'snippet'   => '',
41260e91a17SAndreas Gohr            );
41360e91a17SAndreas Gohr
414e1d9dcc8SAndreas Gohr    $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata);
41560e91a17SAndreas Gohr    if ($evt->advise_before()) {
416ced0762eSchris        $match = array();
417ced0762eSchris        $snippets = array();
4189ee93076Schris        $utf8_offset = $offset = $end = 0;
4198cbc5ee8SAndreas Gohr        $len = \dokuwiki\Utf8\PhpString::strlen($text);
4209ee93076Schris
421546d3a99SAndreas Gohr        // build a regexp from the phrases to highlight
42264159a61SAndreas Gohr        $re1 = '(' .
42364159a61SAndreas Gohr            join(
42464159a61SAndreas Gohr                '|',
42564159a61SAndreas Gohr                array_map(
42664159a61SAndreas Gohr                    'ft_snippet_re_preprocess',
42764159a61SAndreas Gohr                    array_map(
42864159a61SAndreas Gohr                        'preg_quote_cb',
42964159a61SAndreas Gohr                        array_filter((array) $highlight)
43064159a61SAndreas Gohr                    )
43164159a61SAndreas Gohr                )
43264159a61SAndreas Gohr            ) .
43364159a61SAndreas Gohr            ')';
434b571ff2dSChuck Kollars        $re2 = "$re1.{0,75}(?!\\1)$re1";
435b571ff2dSChuck Kollars        $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
436546d3a99SAndreas Gohr
437b571ff2dSChuck Kollars        for ($cnt=4; $cnt--;) {
438b571ff2dSChuck Kollars            if (0) {
439b571ff2dSChuck Kollars            } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
440b571ff2dSChuck Kollars            } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
441b571ff2dSChuck Kollars            } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
442b571ff2dSChuck Kollars            } else {
443b571ff2dSChuck Kollars                break;
444b571ff2dSChuck Kollars            }
445ced0762eSchris
446ced0762eSchris            list($str,$idx) = $match[0];
447ced0762eSchris
448ced0762eSchris            // convert $idx (a byte offset) into a utf8 character offset
4498cbc5ee8SAndreas Gohr            $utf8_idx = \dokuwiki\Utf8\PhpString::strlen(substr($text,0,$idx));
4508cbc5ee8SAndreas Gohr            $utf8_len = \dokuwiki\Utf8\PhpString::strlen($str);
451ced0762eSchris
452ced0762eSchris            // establish context, 100 bytes surrounding the match string
453ced0762eSchris            // first look to see if we can go 100 either side,
454ced0762eSchris            // then drop to 50 adding any excess if the other side can't go to 50,
455ced0762eSchris            $pre = min($utf8_idx-$utf8_offset,100);
456ced0762eSchris            $post = min($len-$utf8_idx-$utf8_len,100);
457ced0762eSchris
458ced0762eSchris            if ($pre>50 && $post>50) {
459ced0762eSchris                $pre = $post = 50;
460ced0762eSchris            } else if ($pre>50) {
461ced0762eSchris                $pre = min($pre,100-$post);
462ced0762eSchris            } else if ($post>50) {
463ced0762eSchris                $post = min($post, 100-$pre);
464ef3e3cddSMichael Hamann            } else if ($offset == 0) {
465ced0762eSchris                // both are less than 50, means the context is the whole string
46610ffc9ddSAndreas Gohr                // make it so and break out of this loop - there is no need for the
46710ffc9ddSAndreas Gohr                // complex snippet calculations
468ced0762eSchris                $snippets = array($text);
469ced0762eSchris                break;
470ced0762eSchris            }
471ced0762eSchris
47210ffc9ddSAndreas Gohr            // establish context start and end points, try to append to previous
47310ffc9ddSAndreas Gohr            // context if possible
4749ee93076Schris            $start = $utf8_idx - $pre;
475ced0762eSchris            $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
4769ee93076Schris            $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
477ced0762eSchris
478ced0762eSchris            if ($append) {
4798cbc5ee8SAndreas Gohr                $snippets[count($snippets)-1] .= \dokuwiki\Utf8\PhpString::substr($text,$append,$end-$append);
480ced0762eSchris            } else {
4818cbc5ee8SAndreas Gohr                $snippets[] = \dokuwiki\Utf8\PhpString::substr($text,$start,$end-$start);
482ced0762eSchris            }
483ced0762eSchris
484ced0762eSchris            // set $offset for next match attempt
48543d58b76SMichael Hamann            // continue matching after the current match
48643d58b76SMichael Hamann            // if the current match is not the longest possible match starting at the current offset
48743d58b76SMichael Hamann            // this prevents further matching of this snippet but for possible matches of length
48843d58b76SMichael Hamann            // smaller than match length + context (at least 50 characters) this match is part of the context
48943d58b76SMichael Hamann            $utf8_offset = $utf8_idx + $utf8_len;
4908cbc5ee8SAndreas Gohr            $offset = $idx + strlen(\dokuwiki\Utf8\PhpString::substr($text,$utf8_idx,$utf8_len));
4918cbc5ee8SAndreas Gohr            $offset = \dokuwiki\Utf8\Clean::correctIdx($text,$offset);
4929ee93076Schris        }
4939ee93076Schris
494ced0762eSchris        $m = "\1";
495b571ff2dSChuck Kollars        $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
49664159a61SAndreas Gohr        $snippet = preg_replace(
49764159a61SAndreas Gohr            '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
49864159a61SAndreas Gohr            '<strong class="search_hit">$1</strong>',
49964159a61SAndreas Gohr            hsc(join('... ', $snippets))
50064159a61SAndreas Gohr        );
501bd2cb6fcSchris
50260e91a17SAndreas Gohr        $evdata['snippet'] = $snippet;
50360e91a17SAndreas Gohr    }
50460e91a17SAndreas Gohr    $evt->advise_after();
50560e91a17SAndreas Gohr    unset($evt);
50660e91a17SAndreas Gohr
50760e91a17SAndreas Gohr    return $evdata['snippet'];
508506fa893SAndreas Gohr}
509506fa893SAndreas Gohr
510506fa893SAndreas Gohr/**
51126eb848cSGina Haeussge * Wraps a search term in regex boundary checks.
51242ea7f44SGerrit Uitslag *
51342ea7f44SGerrit Uitslag * @param string $term
51442ea7f44SGerrit Uitslag * @return string
51526eb848cSGina Haeussge */
5162237b4faSAndreas Gohrfunction ft_snippet_re_preprocess($term) {
51735594613SKazutaka Miyasaka    // do not process asian terms where word boundaries are not explicit
518dbc189b2SAndreas Gohr    if(\dokuwiki\Utf8\Asian::isAsianWords($term)) return $term;
51935594613SKazutaka Miyasaka
5203161005dSAndreas Gohr    if (UTF8_PROPERTYSUPPORT) {
52184e581a6SAndreas Gohr        // unicode word boundaries
52284e581a6SAndreas Gohr        // see http://stackoverflow.com/a/2449017/172068
52384e581a6SAndreas Gohr        $BL = '(?<!\pL)';
52484e581a6SAndreas Gohr        $BR = '(?!\pL)';
5253161005dSAndreas Gohr    } else {
5263161005dSAndreas Gohr        // not as correct as above, but at least won't break
5273161005dSAndreas Gohr        $BL = '\b';
5283161005dSAndreas Gohr        $BR = '\b';
5293161005dSAndreas Gohr    }
5303161005dSAndreas Gohr
5312237b4faSAndreas Gohr    if(substr($term,0,2) == '\\*'){
5322237b4faSAndreas Gohr        $term = substr($term,2);
5332237b4faSAndreas Gohr    }else{
53484e581a6SAndreas Gohr        $term = $BL.$term;
5352237b4faSAndreas Gohr    }
5362237b4faSAndreas Gohr
5372237b4faSAndreas Gohr    if(substr($term,-2,2) == '\\*'){
5382237b4faSAndreas Gohr        $term = substr($term,0,-2);
5392237b4faSAndreas Gohr    }else{
54084e581a6SAndreas Gohr        $term = $term.$BR;
5412237b4faSAndreas Gohr    }
5428a803caeSAndreas Gohr
54384e581a6SAndreas Gohr    if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
5442237b4faSAndreas Gohr    return $term;
54526eb848cSGina Haeussge}
54626eb848cSGina Haeussge
54726eb848cSGina Haeussge/**
548f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
549f5eb7cf0SAndreas Gohr *
550f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
551f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
552f5eb7cf0SAndreas Gohr *
553f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
554f5eb7cf0SAndreas Gohr *
555f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
55642ea7f44SGerrit Uitslag * @return array
557f5eb7cf0SAndreas Gohr */
558f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){
559f5eb7cf0SAndreas Gohr    $array_count = count($args);
560134f4ab2SAndreas Gohr    if($array_count == 1){
561134f4ab2SAndreas Gohr        return $args[0];
562134f4ab2SAndreas Gohr    }
563134f4ab2SAndreas Gohr
564f5eb7cf0SAndreas Gohr    $result = array();
56509c27a6dSGuy Brand    if ($array_count > 1) {
566a21136cdSAndreas Gohr        foreach ($args[0] as $key => $value) {
567a21136cdSAndreas Gohr            $result[$key] = $value;
568f5eb7cf0SAndreas Gohr            for ($i = 1; $i !== $array_count; $i++) {
569a21136cdSAndreas Gohr                if (!isset($args[$i][$key])) {
570a21136cdSAndreas Gohr                    unset($result[$key]);
571a21136cdSAndreas Gohr                    break;
572f5eb7cf0SAndreas Gohr                }
573a21136cdSAndreas Gohr                $result[$key] += $args[$i][$key];
574f5eb7cf0SAndreas Gohr            }
575f5eb7cf0SAndreas Gohr        }
57609c27a6dSGuy Brand    }
577f5eb7cf0SAndreas Gohr    return $result;
578f5eb7cf0SAndreas Gohr}
579f5eb7cf0SAndreas Gohr
580f5eb7cf0SAndreas Gohr/**
581865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores
582f5eb7cf0SAndreas Gohr *
583865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function
584865c2687SKazutaka Miyasaka *
585865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
58642ea7f44SGerrit Uitslag * @return array
58742ea7f44SGerrit Uitslag *
588865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
589865c2687SKazutaka Miyasaka */
590865c2687SKazutaka Miyasakafunction ft_resultUnite($args) {
591865c2687SKazutaka Miyasaka    $array_count = count($args);
592865c2687SKazutaka Miyasaka    if ($array_count === 1) {
593865c2687SKazutaka Miyasaka        return $args[0];
594865c2687SKazutaka Miyasaka    }
595865c2687SKazutaka Miyasaka
596865c2687SKazutaka Miyasaka    $result = $args[0];
597865c2687SKazutaka Miyasaka    for ($i = 1; $i !== $array_count; $i++) {
598865c2687SKazutaka Miyasaka        foreach (array_keys($args[$i]) as $id) {
599865c2687SKazutaka Miyasaka            $result[$id] += $args[$i][$id];
600865c2687SKazutaka Miyasaka        }
601865c2687SKazutaka Miyasaka    }
602865c2687SKazutaka Miyasaka    return $result;
603865c2687SKazutaka Miyasaka}
604865c2687SKazutaka Miyasaka
605865c2687SKazutaka Miyasaka/**
606865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison
607865c2687SKazutaka Miyasaka *
608865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key()
609865c2687SKazutaka Miyasaka *
610865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
61142ea7f44SGerrit Uitslag * @return array
61242ea7f44SGerrit Uitslag *
613865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
614865c2687SKazutaka Miyasaka */
615865c2687SKazutaka Miyasakafunction ft_resultComplement($args) {
616865c2687SKazutaka Miyasaka    $array_count = count($args);
617865c2687SKazutaka Miyasaka    if ($array_count === 1) {
618865c2687SKazutaka Miyasaka        return $args[0];
619865c2687SKazutaka Miyasaka    }
620865c2687SKazutaka Miyasaka
621865c2687SKazutaka Miyasaka    $result = $args[0];
622865c2687SKazutaka Miyasaka    foreach (array_keys($result) as $id) {
623865c2687SKazutaka Miyasaka        for ($i = 1; $i !== $array_count; $i++) {
624865c2687SKazutaka Miyasaka            if (isset($args[$i][$id])) unset($result[$id]);
625865c2687SKazutaka Miyasaka        }
626865c2687SKazutaka Miyasaka    }
627865c2687SKazutaka Miyasaka    return $result;
628865c2687SKazutaka Miyasaka}
629865c2687SKazutaka Miyasaka
630865c2687SKazutaka Miyasaka/**
631865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas
632865c2687SKazutaka Miyasaka *
633865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
634865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
63542ea7f44SGerrit Uitslag *
6366225b270SMichael Große * @param dokuwiki\Search\Indexer $Indexer
63742ea7f44SGerrit Uitslag * @param string                  $query search query
63842ea7f44SGerrit Uitslag * @return array of search formulas
639f5eb7cf0SAndreas Gohr */
6409b41be24STom N Harrisfunction ft_queryParser($Indexer, $query){
641865c2687SKazutaka Miyasaka    /**
642865c2687SKazutaka Miyasaka     * parse a search query and transform it into intermediate representation
643865c2687SKazutaka Miyasaka     *
644865c2687SKazutaka Miyasaka     * in a search query, you can use the following expressions:
645865c2687SKazutaka Miyasaka     *
646865c2687SKazutaka Miyasaka     *   words:
647865c2687SKazutaka Miyasaka     *     include
648865c2687SKazutaka Miyasaka     *     -exclude
649865c2687SKazutaka Miyasaka     *   phrases:
650865c2687SKazutaka Miyasaka     *     "phrase to be included"
651865c2687SKazutaka Miyasaka     *     -"phrase you want to exclude"
652865c2687SKazutaka Miyasaka     *   namespaces:
653865c2687SKazutaka Miyasaka     *     @include:namespace (or ns:include:namespace)
654865c2687SKazutaka Miyasaka     *     ^exclude:namespace (or -ns:exclude:namespace)
655865c2687SKazutaka Miyasaka     *   groups:
656865c2687SKazutaka Miyasaka     *     ()
657865c2687SKazutaka Miyasaka     *     -()
658865c2687SKazutaka Miyasaka     *   operators:
659865c2687SKazutaka Miyasaka     *     and ('and' is the default operator: you can always omit this)
6607871d415SKazutaka Miyasaka     *     or  (or pipe symbol '|', lower precedence than 'and')
661865c2687SKazutaka Miyasaka     *
662865c2687SKazutaka Miyasaka     * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
663865c2687SKazutaka Miyasaka     *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
664865c2687SKazutaka Miyasaka     *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
665865c2687SKazutaka Miyasaka     *      as long as you don't mind hit counts.
666865c2687SKazutaka Miyasaka     *
667865c2687SKazutaka Miyasaka     * intermediate representation consists of the following parts:
668865c2687SKazutaka Miyasaka     *
669865c2687SKazutaka Miyasaka     *   ( )           - group
670865c2687SKazutaka Miyasaka     *   AND           - logical and
671865c2687SKazutaka Miyasaka     *   OR            - logical or
672865c2687SKazutaka Miyasaka     *   NOT           - logical not
6732f502d70SKazutaka Miyasaka     *   W+:, W-:, W_: - word      (underscore: no need to highlight)
6742f502d70SKazutaka Miyasaka     *   P+:, P-:      - phrase    (minus sign: logically in NOT group)
6752f502d70SKazutaka Miyasaka     *   N+:, N-:      - namespace
676865c2687SKazutaka Miyasaka     */
677865c2687SKazutaka Miyasaka    $parsed_query = '';
678865c2687SKazutaka Miyasaka    $parens_level = 0;
6796ce3e5f8SAndreas Gohr    $terms = preg_split('/(-?".*?")/u', \dokuwiki\Utf8\PhpString::strtolower($query),
6806ce3e5f8SAndreas Gohr        -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
681865c2687SKazutaka Miyasaka
682865c2687SKazutaka Miyasaka    foreach ($terms as $term) {
683865c2687SKazutaka Miyasaka        $parsed = '';
684865c2687SKazutaka Miyasaka        if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
685865c2687SKazutaka Miyasaka            // phrase-include and phrase-exclude
686865c2687SKazutaka Miyasaka            $not = $matches[1] ? 'NOT' : '';
6879b41be24STom N Harris            $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
688f5eb7cf0SAndreas Gohr        } else {
689865c2687SKazutaka Miyasaka            // fix incomplete phrase
690865c2687SKazutaka Miyasaka            $term = str_replace('"', ' ', $term);
691865c2687SKazutaka Miyasaka
692865c2687SKazutaka Miyasaka            // fix parentheses
693865c2687SKazutaka Miyasaka            $term = str_replace(')'  , ' ) ', $term);
694865c2687SKazutaka Miyasaka            $term = str_replace('('  , ' ( ', $term);
695865c2687SKazutaka Miyasaka            $term = str_replace('- (', ' -(', $term);
696865c2687SKazutaka Miyasaka
6977871d415SKazutaka Miyasaka            // treat pipe symbols as 'OR' operators
6987871d415SKazutaka Miyasaka            $term = str_replace('|', ' or ', $term);
6997871d415SKazutaka Miyasaka
700865c2687SKazutaka Miyasaka            // treat ideographic spaces (U+3000) as search term separators
701865c2687SKazutaka Miyasaka            // FIXME: some more separators?
702865c2687SKazutaka Miyasaka            $term = preg_replace('/[ \x{3000}]+/u', ' ',  $term);
703865c2687SKazutaka Miyasaka            $term = trim($term);
704865c2687SKazutaka Miyasaka            if ($term === '') continue;
705865c2687SKazutaka Miyasaka
706865c2687SKazutaka Miyasaka            $tokens = explode(' ', $term);
707865c2687SKazutaka Miyasaka            foreach ($tokens as $token) {
708865c2687SKazutaka Miyasaka                if ($token === '(') {
709865c2687SKazutaka Miyasaka                    // parenthesis-include-open
710865c2687SKazutaka Miyasaka                    $parsed .= '(';
711865c2687SKazutaka Miyasaka                    ++$parens_level;
712865c2687SKazutaka Miyasaka                } elseif ($token === '-(') {
713865c2687SKazutaka Miyasaka                    // parenthesis-exclude-open
714865c2687SKazutaka Miyasaka                    $parsed .= 'NOT(';
715865c2687SKazutaka Miyasaka                    ++$parens_level;
716865c2687SKazutaka Miyasaka                } elseif ($token === ')') {
717865c2687SKazutaka Miyasaka                    // parenthesis-any-close
718865c2687SKazutaka Miyasaka                    if ($parens_level === 0) continue;
719865c2687SKazutaka Miyasaka                    $parsed .= ')';
720865c2687SKazutaka Miyasaka                    $parens_level--;
721865c2687SKazutaka Miyasaka                } elseif ($token === 'and') {
722865c2687SKazutaka Miyasaka                    // logical-and (do nothing)
723865c2687SKazutaka Miyasaka                } elseif ($token === 'or') {
724865c2687SKazutaka Miyasaka                    // logical-or
725865c2687SKazutaka Miyasaka                    $parsed .= 'OR';
726865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
727865c2687SKazutaka Miyasaka                    // namespace-exclude
7282f502d70SKazutaka Miyasaka                    $parsed .= 'NOT(N+:'.$matches[1].')';
729865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
730865c2687SKazutaka Miyasaka                    // namespace-include
7312f502d70SKazutaka Miyasaka                    $parsed .= '(N+:'.$matches[1].')';
732865c2687SKazutaka Miyasaka                } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
733865c2687SKazutaka Miyasaka                    // word-exclude
7349b41be24STom N Harris                    $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
735865c2687SKazutaka Miyasaka                } else {
736865c2687SKazutaka Miyasaka                    // word-include
7379b41be24STom N Harris                    $parsed .= ft_termParser($Indexer, $token);
738865c2687SKazutaka Miyasaka                }
739865c2687SKazutaka Miyasaka            }
740865c2687SKazutaka Miyasaka        }
741865c2687SKazutaka Miyasaka        $parsed_query .= $parsed;
742f5eb7cf0SAndreas Gohr    }
743f5eb7cf0SAndreas Gohr
744865c2687SKazutaka Miyasaka    // cleanup (very sensitive)
745865c2687SKazutaka Miyasaka    $parsed_query .= str_repeat(')', $parens_level);
746865c2687SKazutaka Miyasaka    do {
747865c2687SKazutaka Miyasaka        $parsed_query_old = $parsed_query;
748865c2687SKazutaka Miyasaka        $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
749865c2687SKazutaka Miyasaka    } while ($parsed_query !== $parsed_query_old);
750865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')'      , $parsed_query);
751865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(OR)+/u'      , 'OR'     , $parsed_query);
752865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\(OR/u'       , '('      , $parsed_query);
753865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/^OR|OR$/u'    , ''       , $parsed_query);
754865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
755865c2687SKazutaka Miyasaka
7562f502d70SKazutaka Miyasaka    // adjustment: make highlightings right
7572f502d70SKazutaka Miyasaka    $parens_level     = 0;
7582f502d70SKazutaka Miyasaka    $notgrp_levels    = array();
7592f502d70SKazutaka Miyasaka    $parsed_query_new = '';
7602f502d70SKazutaka Miyasaka    $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
7612f502d70SKazutaka Miyasaka    foreach ($tokens as $token) {
7622f502d70SKazutaka Miyasaka        if ($token === 'NOT(') {
7632f502d70SKazutaka Miyasaka            $notgrp_levels[] = ++$parens_level;
7642f502d70SKazutaka Miyasaka        } elseif ($token === '(') {
7652f502d70SKazutaka Miyasaka            ++$parens_level;
7662f502d70SKazutaka Miyasaka        } elseif ($token === ')') {
7672f502d70SKazutaka Miyasaka            if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
7682f502d70SKazutaka Miyasaka        } elseif (count($notgrp_levels) % 2 === 1) {
7692f502d70SKazutaka Miyasaka            // turn highlight-flag off if terms are logically in "NOT" group
7702f502d70SKazutaka Miyasaka            $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
7712f502d70SKazutaka Miyasaka        }
7722f502d70SKazutaka Miyasaka        $parsed_query_new .= $token;
7732f502d70SKazutaka Miyasaka    }
7742f502d70SKazutaka Miyasaka    $parsed_query = $parsed_query_new;
7752f502d70SKazutaka Miyasaka
776865c2687SKazutaka Miyasaka    /**
777865c2687SKazutaka Miyasaka     * convert infix notation string into postfix (Reverse Polish notation) array
778865c2687SKazutaka Miyasaka     * by Shunting-yard algorithm
779865c2687SKazutaka Miyasaka     *
780865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
781865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
782865c2687SKazutaka Miyasaka     */
783865c2687SKazutaka Miyasaka    $parsed_ary     = array();
784865c2687SKazutaka Miyasaka    $ope_stack      = array();
785865c2687SKazutaka Miyasaka    $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
786865c2687SKazutaka Miyasaka    $ope_regex      = '/([()]|OR|AND|NOT)/u';
787865c2687SKazutaka Miyasaka
788865c2687SKazutaka Miyasaka    $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
789865c2687SKazutaka Miyasaka    foreach ($tokens as $token) {
790865c2687SKazutaka Miyasaka        if (preg_match($ope_regex, $token)) {
791865c2687SKazutaka Miyasaka            // operator
792865c2687SKazutaka Miyasaka            $last_ope = end($ope_stack);
79367d812e0SMarius van Witzenburg            while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
794865c2687SKazutaka Miyasaka                $parsed_ary[] = array_pop($ope_stack);
795865c2687SKazutaka Miyasaka                $last_ope = end($ope_stack);
796865c2687SKazutaka Miyasaka            }
797865c2687SKazutaka Miyasaka            if ($token == ')') {
798865c2687SKazutaka Miyasaka                array_pop($ope_stack); // this array_pop always deletes '('
799865c2687SKazutaka Miyasaka            } else {
800865c2687SKazutaka Miyasaka                $ope_stack[] = $token;
801865c2687SKazutaka Miyasaka            }
802865c2687SKazutaka Miyasaka        } else {
803865c2687SKazutaka Miyasaka            // operand
804865c2687SKazutaka Miyasaka            $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
805865c2687SKazutaka Miyasaka            $parsed_ary[] = $token_decoded;
806865c2687SKazutaka Miyasaka        }
807865c2687SKazutaka Miyasaka    }
808865c2687SKazutaka Miyasaka    $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
809865c2687SKazutaka Miyasaka
810865c2687SKazutaka Miyasaka    // cleanup: each double "NOT" in RPN array actually does nothing
811865c2687SKazutaka Miyasaka    $parsed_ary_count = count($parsed_ary);
812865c2687SKazutaka Miyasaka    for ($i = 1; $i < $parsed_ary_count; ++$i) {
813865c2687SKazutaka Miyasaka        if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
814865c2687SKazutaka Miyasaka            unset($parsed_ary[$i], $parsed_ary[$i - 1]);
815865c2687SKazutaka Miyasaka        }
816865c2687SKazutaka Miyasaka    }
817865c2687SKazutaka Miyasaka    $parsed_ary = array_values($parsed_ary);
818865c2687SKazutaka Miyasaka
819865c2687SKazutaka Miyasaka    // build return value
820f5eb7cf0SAndreas Gohr    $q = array();
821f5eb7cf0SAndreas Gohr    $q['query']      = $query;
822865c2687SKazutaka Miyasaka    $q['parsed_str'] = $parsed_query;
823865c2687SKazutaka Miyasaka    $q['parsed_ary'] = $parsed_ary;
824f5eb7cf0SAndreas Gohr
825865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
826865c2687SKazutaka Miyasaka        if ($token[2] !== ':') continue;
827865c2687SKazutaka Miyasaka        $body = substr($token, 3);
828865c2687SKazutaka Miyasaka
829865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
8302f502d70SKazutaka Miyasaka            case 'N+:':
831865c2687SKazutaka Miyasaka                     $q['ns'][]        = $body; // for backward compatibility
832865c2687SKazutaka Miyasaka                     break;
8332f502d70SKazutaka Miyasaka            case 'N-:':
8342f502d70SKazutaka Miyasaka                     $q['notns'][]     = $body; // for backward compatibility
8352f502d70SKazutaka Miyasaka                     break;
8362f502d70SKazutaka Miyasaka            case 'W_:':
8372f502d70SKazutaka Miyasaka                     $q['words'][]     = $body;
8382f502d70SKazutaka Miyasaka                     break;
839865c2687SKazutaka Miyasaka            case 'W-:':
840865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
8412f502d70SKazutaka Miyasaka                     $q['not'][]       = $body; // for backward compatibility
842865c2687SKazutaka Miyasaka                     break;
843865c2687SKazutaka Miyasaka            case 'W+:':
844865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
8452237b4faSAndreas Gohr                     $q['highlight'][] = $body;
8462f502d70SKazutaka Miyasaka                     $q['and'][]       = $body; // for backward compatibility
847865c2687SKazutaka Miyasaka                     break;
8482f502d70SKazutaka Miyasaka            case 'P-:':
8492f502d70SKazutaka Miyasaka                     $q['phrases'][]   = $body;
8502f502d70SKazutaka Miyasaka                     break;
8512f502d70SKazutaka Miyasaka            case 'P+:':
852865c2687SKazutaka Miyasaka                     $q['phrases'][]   = $body;
8532237b4faSAndreas Gohr                     $q['highlight'][] = $body;
854865c2687SKazutaka Miyasaka                     break;
855865c2687SKazutaka Miyasaka        }
856865c2687SKazutaka Miyasaka    }
8572f502d70SKazutaka Miyasaka    foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) {
858865c2687SKazutaka Miyasaka        $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
859f5eb7cf0SAndreas Gohr    }
860f5eb7cf0SAndreas Gohr
861f5eb7cf0SAndreas Gohr    return $q;
862f5eb7cf0SAndreas Gohr}
863f5eb7cf0SAndreas Gohr
864865c2687SKazutaka Miyasaka/**
865865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation
866865c2687SKazutaka Miyasaka *
867865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use.
868865c2687SKazutaka Miyasaka *
869865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
87042ea7f44SGerrit Uitslag *
8716225b270SMichael Große * @param dokuwiki\Search\Indexer $Indexer
87242ea7f44SGerrit Uitslag * @param string                  $term
87342ea7f44SGerrit Uitslag * @param bool                    $consider_asian
87442ea7f44SGerrit Uitslag * @param bool                    $phrase_mode
87542ea7f44SGerrit Uitslag * @return string
876865c2687SKazutaka Miyasaka */
8779b41be24STom N Harrisfunction ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) {
878865c2687SKazutaka Miyasaka    $parsed = '';
879865c2687SKazutaka Miyasaka    if ($consider_asian) {
880865c2687SKazutaka Miyasaka        // successive asian characters need to be searched as a phrase
881dbc189b2SAndreas Gohr        $words = \dokuwiki\Utf8\Asian::splitAsianWords($term);
882865c2687SKazutaka Miyasaka        foreach ($words as $word) {
883dbc189b2SAndreas Gohr            $phrase_mode = $phrase_mode ? true : \dokuwiki\Utf8\Asian::isAsianWords($word);
8849b41be24STom N Harris            $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
885865c2687SKazutaka Miyasaka        }
886865c2687SKazutaka Miyasaka    } else {
887865c2687SKazutaka Miyasaka        $term_noparen = str_replace(array('(', ')'), ' ', $term);
8889b41be24STom N Harris        $words = $Indexer->tokenizer($term_noparen, true);
889865c2687SKazutaka Miyasaka
8902f502d70SKazutaka Miyasaka        // W_: no need to highlight
891865c2687SKazutaka Miyasaka        if (empty($words)) {
892865c2687SKazutaka Miyasaka            $parsed = '()'; // important: do not remove
893865c2687SKazutaka Miyasaka        } elseif ($words[0] === $term) {
894865c2687SKazutaka Miyasaka            $parsed = '(W+:'.$words[0].')';
895865c2687SKazutaka Miyasaka        } elseif ($phrase_mode) {
896865c2687SKazutaka Miyasaka            $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
8972f502d70SKazutaka Miyasaka            $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
898865c2687SKazutaka Miyasaka        } else {
899865c2687SKazutaka Miyasaka            $parsed = '((W+:'.implode(')(W+:', $words).'))';
900865c2687SKazutaka Miyasaka        }
901865c2687SKazutaka Miyasaka    }
902865c2687SKazutaka Miyasaka    return $parsed;
903865c2687SKazutaka Miyasaka}
904865c2687SKazutaka Miyasaka
90544156e11SMichael Große/**
90644156e11SMichael Große * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
90744156e11SMichael Große *
90844156e11SMichael Große * @param array $and
90944156e11SMichael Große * @param array $not
91044156e11SMichael Große * @param array $phrases
91144156e11SMichael Große * @param array $ns
91244156e11SMichael Große * @param array $notns
91344156e11SMichael Große *
91444156e11SMichael Große * @return string
91544156e11SMichael Große */
91644156e11SMichael Großefunction ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) {
91744156e11SMichael Große    $query = implode(' ', $and);
91844156e11SMichael Große    if (!empty($not)) {
91944156e11SMichael Große        $query .= ' -' . implode(' -', $not);
92044156e11SMichael Große    }
92144156e11SMichael Große
92244156e11SMichael Große    if (!empty($phrases)) {
92344156e11SMichael Große        $query .= ' "' . implode('" "', $phrases) . '"';
92444156e11SMichael Große    }
92544156e11SMichael Große
92644156e11SMichael Große    if (!empty($ns)) {
92744156e11SMichael Große        $query .= ' @' . implode(' @', $ns);
92844156e11SMichael Große    }
92944156e11SMichael Große
93044156e11SMichael Große    if (!empty($notns)) {
93144156e11SMichael Große        $query .= ' ^' . implode(' ^', $notns);
93244156e11SMichael Große    }
93344156e11SMichael Große
93444156e11SMichael Große    return $query;
93544156e11SMichael Große}
93644156e11SMichael Große
937e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 :
938