xref: /dokuwiki/inc/fulltext.php (revision 24870174d2ee45460ba6bcfe5f5a0ae94715efd7)
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 */
8*24870174SAndreas Gohruse dokuwiki\Utf8\Asian;
9*24870174SAndreas Gohruse dokuwiki\Search\Indexer;
1027f63a23SAndreas Gohruse dokuwiki\Extension\Event;
117fb26b8eSAndreas Gohruse dokuwiki\Utf8\Clean;
127fb26b8eSAndreas Gohruse dokuwiki\Utf8\PhpString;
132d85e841SAndreas Gohruse dokuwiki\Utf8\Sort;
14f5eb7cf0SAndreas Gohr
15bd0293e7SAndreas Gohr/**
16bd0293e7SAndreas Gohr * create snippets for the first few results only
17bd0293e7SAndreas Gohr */
18bd0293e7SAndreas Gohrif(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15);
19f5eb7cf0SAndreas Gohr
20f5eb7cf0SAndreas Gohr/**
21f5eb7cf0SAndreas Gohr * The fulltext search
22f5eb7cf0SAndreas Gohr *
23f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query
24506fa893SAndreas Gohr *
256840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
266840140fSChris Smith *
2742ea7f44SGerrit Uitslag * @param string     $query
2842ea7f44SGerrit Uitslag * @param array      $highlight
293850270cSMichael Große * @param string     $sort
3064159a61SAndreas Gohr * @param int|string $after  only show results with mtime after this date, accepts timestap or strtotime arguments
3164159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments
323850270cSMichael Große *
3342ea7f44SGerrit Uitslag * @return array
34f5eb7cf0SAndreas Gohr */
353850270cSMichael Großefunction ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){
366840140fSChris Smith
373850270cSMichael Große    if ($sort === null) {
383850270cSMichael Große        $sort = 'hits';
393850270cSMichael Große    }
403850270cSMichael Große    $data = [
413850270cSMichael Große        'query' => $query,
423850270cSMichael Große        'sort' => $sort,
433850270cSMichael Große        'after' => $after,
443850270cSMichael Große        'before' => $before
453850270cSMichael Große    ];
466840140fSChris Smith    $data['highlight'] =& $highlight;
476840140fSChris Smith
48cbb44eabSAndreas Gohr    return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
496840140fSChris Smith}
50865c2687SKazutaka Miyasaka
51865c2687SKazutaka Miyasaka/**
52865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query
53865c2687SKazutaka Miyasaka *
54865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
55865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
5642ea7f44SGerrit Uitslag *
5742ea7f44SGerrit Uitslag * @param array $data event data
5842ea7f44SGerrit Uitslag * @return array matching documents
59865c2687SKazutaka Miyasaka */
606840140fSChris Smithfunction _ft_pageSearch(&$data) {
619b41be24STom N Harris    $Indexer = idx_get_indexer();
629b41be24STom N Harris
63865c2687SKazutaka Miyasaka    // parse the given query
649b41be24STom N Harris    $q = ft_queryParser($Indexer, $data['query']);
65865c2687SKazutaka Miyasaka    $data['highlight'] = $q['highlight'];
666840140fSChris Smith
67*24870174SAndreas Gohr    if (empty($q['parsed_ary'])) return [];
68506fa893SAndreas Gohr
69f5eb7cf0SAndreas Gohr    // lookup all words found in the query
709b41be24STom N Harris    $lookup = $Indexer->lookup($q['words']);
71f5eb7cf0SAndreas Gohr
72865c2687SKazutaka Miyasaka    // get all pages in this dokuwiki site (!: includes nonexistent pages)
73*24870174SAndreas Gohr    $pages_all = [];
749b41be24STom N Harris    foreach ($Indexer->getPages() as $id) {
759b41be24STom N Harris        $pages_all[$id] = 0; // base: 0 hit
76f5eb7cf0SAndreas Gohr    }
77f5eb7cf0SAndreas Gohr
78865c2687SKazutaka Miyasaka    // process the query
79*24870174SAndreas Gohr    $stack = [];
80865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
81865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
82865c2687SKazutaka Miyasaka            case 'W+:':
832f502d70SKazutaka Miyasaka            case 'W-:':
842f502d70SKazutaka Miyasaka            case 'W_:': // word
85865c2687SKazutaka Miyasaka                $word    = substr($token, 3);
865afd9580SAndreas Gohr                if(isset($lookup[$word])) {
87865c2687SKazutaka Miyasaka                    $stack[] = (array)$lookup[$word];
885afd9580SAndreas Gohr                }
89865c2687SKazutaka Miyasaka                break;
902f502d70SKazutaka Miyasaka            case 'P+:':
912f502d70SKazutaka Miyasaka            case 'P-:': // phrase
92865c2687SKazutaka Miyasaka                $phrase = substr($token, 3);
93865c2687SKazutaka Miyasaka                // since phrases are always parsed as ((W1)(W2)...(P)),
94865c2687SKazutaka Miyasaka                // the end($stack) always points the pages that contain
95865c2687SKazutaka Miyasaka                // all words in this phrase
96865c2687SKazutaka Miyasaka                $pages  = end($stack);
97*24870174SAndreas Gohr                $pages_matched = [];
98865c2687SKazutaka Miyasaka                foreach(array_keys($pages) as $id){
99*24870174SAndreas Gohr                    $evdata = [
100a7e8b43eSMichael Hamann                        'id' => $id,
101a7e8b43eSMichael Hamann                        'phrase' => $phrase,
102a7e8b43eSMichael Hamann                        'text' => rawWiki($id)
103*24870174SAndreas Gohr                    ];
104e1d9dcc8SAndreas Gohr                    $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata);
105a7e8b43eSMichael Hamann                    if ($evt->advise_before() && $evt->result !== true) {
1067fb26b8eSAndreas Gohr                        $text = PhpString::strtolower($evdata['text']);
107865c2687SKazutaka Miyasaka                        if (strpos($text, $phrase) !== false) {
108a7e8b43eSMichael Hamann                            $evt->result = true;
109a7e8b43eSMichael Hamann                        }
110a7e8b43eSMichael Hamann                    }
111a7e8b43eSMichael Hamann                    $evt->advise_after();
112a7e8b43eSMichael Hamann                    if ($evt->result === true) {
113865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // phrase: always 0 hit
114865c2687SKazutaka Miyasaka                    }
115865c2687SKazutaka Miyasaka                }
116865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
117865c2687SKazutaka Miyasaka                break;
1182f502d70SKazutaka Miyasaka            case 'N+:':
1192f502d70SKazutaka Miyasaka            case 'N-:': // namespace
120de3383c6SMichael Große                $ns = cleanID(substr($token, 3)) . ':';
121*24870174SAndreas Gohr                $pages_matched = [];
122865c2687SKazutaka Miyasaka                foreach (array_keys($pages_all) as $id) {
123865c2687SKazutaka Miyasaka                    if (strpos($id, $ns) === 0) {
124865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // namespace: always 0 hit
125865c2687SKazutaka Miyasaka                    }
126865c2687SKazutaka Miyasaka                }
127865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
128865c2687SKazutaka Miyasaka                break;
129865c2687SKazutaka Miyasaka            case 'AND': // and operation
130*24870174SAndreas Gohr                [$pages1, $pages2] = array_splice($stack, -2);
131*24870174SAndreas Gohr                $stack[] = ft_resultCombine([$pages1, $pages2]);
132865c2687SKazutaka Miyasaka                break;
133865c2687SKazutaka Miyasaka            case 'OR':  // or operation
134*24870174SAndreas Gohr                [$pages1, $pages2] = array_splice($stack, -2);
135*24870174SAndreas Gohr                $stack[] = ft_resultUnite([$pages1, $pages2]);
136865c2687SKazutaka Miyasaka                break;
137865c2687SKazutaka Miyasaka            case 'NOT': // not operation (unary)
138865c2687SKazutaka Miyasaka                $pages   = array_pop($stack);
139*24870174SAndreas Gohr                $stack[] = ft_resultComplement([$pages_all, $pages]);
140a21136cdSAndreas Gohr                break;
141a21136cdSAndreas Gohr        }
142f5eb7cf0SAndreas Gohr    }
143865c2687SKazutaka Miyasaka    $docs = array_pop($stack);
144865c2687SKazutaka Miyasaka
145*24870174SAndreas Gohr    if (empty($docs)) return [];
146865c2687SKazutaka Miyasaka
147865c2687SKazutaka Miyasaka    // check: settings, acls, existence
148865c2687SKazutaka Miyasaka    foreach (array_keys($docs) as $id) {
149865c2687SKazutaka Miyasaka        if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
150865c2687SKazutaka Miyasaka            unset($docs[$id]);
151f5eb7cf0SAndreas Gohr        }
152f5eb7cf0SAndreas Gohr    }
153f5eb7cf0SAndreas Gohr
1543850270cSMichael Große    $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']);
1558d0e286aSMichael Große
1568d0e286aSMichael Große    if ($data['sort'] === 'mtime') {
1578d0e286aSMichael Große        uksort($docs, 'ft_pagemtimesorter');
1588d0e286aSMichael Große    } else {
159865c2687SKazutaka Miyasaka        // sort docs by count
16006281c9cSMoisés Braga Ribeiro        uksort($docs, 'ft_pagesorter');
161f5eb7cf0SAndreas Gohr        arsort($docs);
1628d0e286aSMichael Große    }
163f5eb7cf0SAndreas Gohr
164f5eb7cf0SAndreas Gohr    return $docs;
165f5eb7cf0SAndreas Gohr}
166f5eb7cf0SAndreas Gohr
167f5eb7cf0SAndreas Gohr/**
16854f4c056SAndreas Gohr * Returns the backlinks for a given page
16954f4c056SAndreas Gohr *
170320f489aSMichael Hamann * Uses the metadata index.
17107ff0babSMichael Hamann *
17207ff0babSMichael Hamann * @param string $id           The id for which links shall be returned
17307ff0babSMichael Hamann * @param bool   $ignore_perms Ignore the fact that pages are hidden or read-protected
17407ff0babSMichael Hamann * @return array The pages that contain links to the given page
17554f4c056SAndreas Gohr */
17607ff0babSMichael Hamannfunction ft_backlinks($id, $ignore_perms = false){
177320f489aSMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_references', $id);
17854f4c056SAndreas Gohr
179*24870174SAndreas Gohr    if($result === []) return $result;
18063773904SAndreas Gohr
18163773904SAndreas Gohr    // check ACL permissions
18263773904SAndreas Gohr    foreach(array_keys($result) as $idx){
183*24870174SAndreas Gohr        if((!$ignore_perms && (
18407ff0babSMichael Hamann                isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
18507ff0babSMichael Hamann            )) || !page_exists($result[$idx], '', false)){
18663773904SAndreas Gohr            unset($result[$idx]);
18763773904SAndreas Gohr        }
18863773904SAndreas Gohr    }
18963773904SAndreas Gohr
1902d85e841SAndreas Gohr    Sort::sort($result);
19154f4c056SAndreas Gohr    return $result;
19254f4c056SAndreas Gohr}
19354f4c056SAndreas Gohr
19454f4c056SAndreas Gohr/**
195a05e297aSAndreas Gohr * Returns the pages that use a given media file
196a05e297aSAndreas Gohr *
197ffec1009SMichael Hamann * Uses the relation media metadata property and the metadata index.
198a05e297aSAndreas Gohr *
199ffec1009SMichael Hamann * Note that before 2013-07-31 the second parameter was the maximum number of results and
200ffec1009SMichael Hamann * permissions were ignored. That's why the parameter is now checked to be explicitely set
201ffec1009SMichael Hamann * to true (with type bool) in order to be compatible with older uses of the function.
202ffec1009SMichael Hamann *
203ffec1009SMichael Hamann * @param string $id           The media id to look for
204ffec1009SMichael Hamann * @param bool   $ignore_perms Ignore hidden pages and acls (optional, default: false)
205ffec1009SMichael Hamann * @return array A list of pages that use the given media file
206a05e297aSAndreas Gohr */
207ffec1009SMichael Hamannfunction ft_mediause($id, $ignore_perms = false){
208ffec1009SMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_media', $id);
209a05e297aSAndreas Gohr
210*24870174SAndreas Gohr    if($result === []) return $result;
211a05e297aSAndreas Gohr
212ffec1009SMichael Hamann    // check ACL permissions
213ffec1009SMichael Hamann    foreach(array_keys($result) as $idx){
214*24870174SAndreas Gohr        if((!$ignore_perms && (
215ffec1009SMichael Hamann                    isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
216ffec1009SMichael Hamann                )) || !page_exists($result[$idx], '', false)){
217ffec1009SMichael Hamann            unset($result[$idx]);
218a05e297aSAndreas Gohr        }
219a05e297aSAndreas Gohr    }
220a05e297aSAndreas Gohr
2212d85e841SAndreas Gohr    Sort::sort($result);
222a05e297aSAndreas Gohr    return $result;
223a05e297aSAndreas Gohr}
224a05e297aSAndreas Gohr
225a05e297aSAndreas Gohr
226a05e297aSAndreas Gohr/**
227506fa893SAndreas Gohr * Quicksearch for pagenames
228506fa893SAndreas Gohr *
229506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
23080423ab6SAdrian Lang * namespace. This can be changed with the second parameter.
23180423ab6SAdrian Lang * The third parameter allows to search in titles as well.
232506fa893SAndreas Gohr *
2338d22f1e9SAndreas Gohr * The function always returns titles as well
2346840140fSChris Smith *
2358d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP
236506fa893SAndreas Gohr * @author   Andreas Gohr <andi@splitbrain.org>
2378d22f1e9SAndreas Gohr * @author   Adrian Lang <lang@cosmocode.de>
23842ea7f44SGerrit Uitslag *
23942ea7f44SGerrit Uitslag * @param string     $id       page id
24042ea7f44SGerrit Uitslag * @param bool       $in_ns    match against namespace as well?
24142ea7f44SGerrit Uitslag * @param bool       $in_title search in title?
24264159a61SAndreas Gohr * @param int|string $after    only show results with mtime after this date, accepts timestap or strtotime arguments
24364159a61SAndreas Gohr * @param int|string $before   only show results with mtime before this date, accepts timestap or strtotime arguments
2443850270cSMichael Große *
24542ea7f44SGerrit Uitslag * @return string[]
246506fa893SAndreas Gohr */
2473850270cSMichael Großefunction ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){
2483850270cSMichael Große    $data = [
2493850270cSMichael Große        'id' => $id,
2503850270cSMichael Große        'in_ns' => $in_ns,
2513850270cSMichael Große        'in_title' => $in_title,
2523850270cSMichael Große        'after' => $after,
2533850270cSMichael Große        'before' => $before
2543850270cSMichael Große    ];
2558d22f1e9SAndreas Gohr    $data['has_titles'] = true; // for plugin backward compatibility check
256cbb44eabSAndreas Gohr    return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup');
2576840140fSChris Smith}
2586840140fSChris Smith
25942ea7f44SGerrit Uitslag/**
26042ea7f44SGerrit Uitslag * Returns list of pages as array(pageid => First Heading)
26142ea7f44SGerrit Uitslag *
26242ea7f44SGerrit Uitslag * @param array &$data event data
26342ea7f44SGerrit Uitslag * @return string[]
26442ea7f44SGerrit Uitslag */
2656840140fSChris Smithfunction _ft_pageLookup(&$data){
26680423ab6SAdrian Lang    // split out original parameters
2676840140fSChris Smith    $id = $data['id'];
268940f24fcSMichael Große    $Indexer = idx_get_indexer();
269940f24fcSMichael Große    $parsedQuery = ft_queryParser($Indexer, $id);
270940f24fcSMichael Große    if (count($parsedQuery['ns']) > 0) {
271940f24fcSMichael Große        $ns = cleanID($parsedQuery['ns'][0]) . ':';
272940f24fcSMichael Große        $id = implode(' ', $parsedQuery['highlight']);
273b0f6db0cSAdrian Lang    }
274248d652bSGerrit Uitslag    if (count($parsedQuery['notns']) > 0) {
275248d652bSGerrit Uitslag        $notns = cleanID($parsedQuery['notns'][0]) . ':';
276248d652bSGerrit Uitslag        $id = implode(' ', $parsedQuery['highlight']);
277248d652bSGerrit Uitslag    }
278b0f6db0cSAdrian Lang
2798d22f1e9SAndreas Gohr    $in_ns    = $data['in_ns'];
2808d22f1e9SAndreas Gohr    $in_title = $data['in_title'];
28180423ab6SAdrian Lang    $cleaned = cleanID($id);
2829b41be24STom N Harris
2839b41be24STom N Harris    $Indexer = idx_get_indexer();
2849b41be24STom N Harris    $page_idx = $Indexer->getPages();
2859b41be24STom N Harris
286*24870174SAndreas Gohr    $pages = [];
2875479a8c3SAndreas Gohr    if ($id !== '' && $cleaned !== '') {
2889b41be24STom N Harris        foreach ($page_idx as $p_id) {
2899b41be24STom N Harris            if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) {
2909b41be24STom N Harris                if (!isset($pages[$p_id]))
29167c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
292506fa893SAndreas Gohr            }
293506fa893SAndreas Gohr        }
294f078bb00STom N Harris        if ($in_title) {
295c66f16a3SMichael Hamann            foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) {
296f078bb00STom N Harris                if (!isset($pages[$p_id]))
29767c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
298f078bb00STom N Harris            }
299f078bb00STom N Harris        }
300d0bdf765SAdrian Lang    }
3010c074a52SMichael Hamann
302d0bdf765SAdrian Lang    if (isset($ns)) {
3030c074a52SMichael Hamann        foreach (array_keys($pages) as $p_id) {
3040c074a52SMichael Hamann            if (strpos($p_id, $ns) !== 0) {
3050c074a52SMichael Hamann                unset($pages[$p_id]);
306d0bdf765SAdrian Lang            }
307d0bdf765SAdrian Lang        }
308506fa893SAndreas Gohr    }
309248d652bSGerrit Uitslag    if (isset($notns)) {
310248d652bSGerrit Uitslag        foreach (array_keys($pages) as $p_id) {
311248d652bSGerrit Uitslag            if (strpos($p_id, $notns) === 0) {
312248d652bSGerrit Uitslag                unset($pages[$p_id]);
313248d652bSGerrit Uitslag            }
314248d652bSGerrit Uitslag        }
315248d652bSGerrit Uitslag    }
31663773904SAndreas Gohr
31780423ab6SAdrian Lang    // discard hidden pages
31880423ab6SAdrian Lang    // discard nonexistent pages
31963773904SAndreas Gohr    // check ACL permissions
32063773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
32180423ab6SAdrian Lang        if(!isVisiblePage($idx) || !page_exists($idx) ||
32280423ab6SAdrian Lang           auth_quickaclcheck($idx) < AUTH_READ) {
32363773904SAndreas Gohr            unset($pages[$idx]);
32463773904SAndreas Gohr        }
32563773904SAndreas Gohr    }
32663773904SAndreas Gohr
3273850270cSMichael Große    $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']);
3281b48999cSMichael Große
3293d2017d9SAdrian Lang    uksort($pages,'ft_pagesorter');
3308d22f1e9SAndreas Gohr    return $pages;
331506fa893SAndreas Gohr}
332506fa893SAndreas Gohr
3331b48999cSMichael Große
3341b48999cSMichael Große/**
3351b48999cSMichael Große * @param array      $results search results in the form pageid => value
33664159a61SAndreas Gohr * @param int|string $after   only returns results with mtime after this date, accepts timestap or strtotime arguments
33764159a61SAndreas Gohr * @param int|string $before  only returns results with mtime after this date, accepts timestap or strtotime arguments
3381b48999cSMichael Große *
3391b48999cSMichael Große * @return array
3401b48999cSMichael Große */
3413850270cSMichael Großefunction _ft_filterResultsByTime(array $results, $after, $before) {
3423850270cSMichael Große    if ($after || $before) {
3431b48999cSMichael Große        $after = is_int($after) ? $after : strtotime($after);
3441b48999cSMichael Große        $before = is_int($before) ? $before : strtotime($before);
3451b48999cSMichael Große
346*24870174SAndreas Gohr        foreach (array_keys($results) as $id) {
3471b48999cSMichael Große            $mTime = filemtime(wikiFN($id));
3481b48999cSMichael Große            if ($after && $after > $mTime) {
3491b48999cSMichael Große                unset($results[$id]);
3501b48999cSMichael Große                continue;
3511b48999cSMichael Große            }
3521b48999cSMichael Große            if ($before && $before < $mTime) {
3531b48999cSMichael Große                unset($results[$id]);
3541b48999cSMichael Große            }
3551b48999cSMichael Große        }
3561b48999cSMichael Große    }
3571b48999cSMichael Große
3581b48999cSMichael Große    return $results;
3591b48999cSMichael Große}
3601b48999cSMichael Große
361506fa893SAndreas Gohr/**
362c66f16a3SMichael Hamann * Tiny helper function for comparing the searched title with the title
363c66f16a3SMichael Hamann * from the search index. This function is a wrapper around stripos with
364c66f16a3SMichael Hamann * adapted argument order and return value.
36542ea7f44SGerrit Uitslag *
36642ea7f44SGerrit Uitslag * @param string $search searched title
36742ea7f44SGerrit Uitslag * @param string $title  title from index
36842ea7f44SGerrit Uitslag * @return bool
369c66f16a3SMichael Hamann */
370c66f16a3SMichael Hamannfunction _ft_pageLookupTitleCompare($search, $title) {
3717fb26b8eSAndreas Gohr    if (Clean::isASCII($search)) {
3727fb26b8eSAndreas Gohr        $pos = stripos($title, $search);
3737fb26b8eSAndreas Gohr    } else {
3747fb26b8eSAndreas Gohr        $pos = PhpString::strpos(
3757fb26b8eSAndreas Gohr            PhpString::strtolower($title),
3767fb26b8eSAndreas Gohr            PhpString::strtolower($search)
3777fb26b8eSAndreas Gohr        );
3787fb26b8eSAndreas Gohr    }
3797fb26b8eSAndreas Gohr
3807fb26b8eSAndreas Gohr    return $pos !== false;
381c66f16a3SMichael Hamann}
382c66f16a3SMichael Hamann
383c66f16a3SMichael Hamann/**
384f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string
385f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy
386f31eb72bSAndreas Gohr * pages.
38742ea7f44SGerrit Uitslag *
38842ea7f44SGerrit Uitslag * @param string $a
38942ea7f44SGerrit Uitslag * @param string $b
39042ea7f44SGerrit Uitslag * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal.
391f31eb72bSAndreas Gohr */
392f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){
393f31eb72bSAndreas Gohr    $ac = count(explode(':',$a));
394f31eb72bSAndreas Gohr    $bc = count(explode(':',$b));
395f31eb72bSAndreas Gohr    if($ac < $bc){
396f31eb72bSAndreas Gohr        return -1;
397f31eb72bSAndreas Gohr    }elseif($ac > $bc){
398f31eb72bSAndreas Gohr        return 1;
399f31eb72bSAndreas Gohr    }
4002d85e841SAndreas Gohr    return Sort::strcmp($a,$b);
401f31eb72bSAndreas Gohr}
402f31eb72bSAndreas Gohr
403f31eb72bSAndreas Gohr/**
4048d0e286aSMichael Große * Sort pages by their mtime, from newest to oldest
4058d0e286aSMichael Große *
4068d0e286aSMichael Große * @param string $a
4078d0e286aSMichael Große * @param string $b
4088d0e286aSMichael Große *
4098d0e286aSMichael 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
4108d0e286aSMichael Große */
4118d0e286aSMichael Großefunction ft_pagemtimesorter($a, $b) {
4128d0e286aSMichael Große    $mtimeA = filemtime(wikiFN($a));
4138d0e286aSMichael Große    $mtimeB = filemtime(wikiFN($b));
4148d0e286aSMichael Große    return $mtimeB - $mtimeA;
4158d0e286aSMichael Große}
4168d0e286aSMichael Große
4178d0e286aSMichael Große/**
418506fa893SAndreas Gohr * Creates a snippet extract
419506fa893SAndreas Gohr *
420506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
42160e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE
42242ea7f44SGerrit Uitslag *
42342ea7f44SGerrit Uitslag * @param string $id page id
42442ea7f44SGerrit Uitslag * @param array $highlight
42542ea7f44SGerrit Uitslag * @return mixed
426506fa893SAndreas Gohr */
427546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){
428506fa893SAndreas Gohr    $text = rawWiki($id);
429*24870174SAndreas Gohr    $text = str_replace("\xC2\xAD",'',$text);
430*24870174SAndreas Gohr     // remove soft-hyphens
431*24870174SAndreas Gohr    $evdata = [
43260e91a17SAndreas Gohr        'id'        => $id,
43360e91a17SAndreas Gohr        'text'      => &$text,
43460e91a17SAndreas Gohr        'highlight' => &$highlight,
435*24870174SAndreas Gohr        'snippet'   => ''
436*24870174SAndreas Gohr    ];
43760e91a17SAndreas Gohr
438e1d9dcc8SAndreas Gohr    $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata);
43960e91a17SAndreas Gohr    if ($evt->advise_before()) {
440*24870174SAndreas Gohr        $match = [];
441*24870174SAndreas Gohr        $snippets = [];
442*24870174SAndreas Gohr        $utf8_offset = 0;
443*24870174SAndreas Gohr        $offset = 0;
444*24870174SAndreas Gohr        $end = 0;
4457fb26b8eSAndreas Gohr        $len = PhpString::strlen($text);
4469ee93076Schris
447546d3a99SAndreas Gohr        // build a regexp from the phrases to highlight
44864159a61SAndreas Gohr        $re1 = '(' .
449*24870174SAndreas Gohr            implode(
45064159a61SAndreas Gohr                '|',
45164159a61SAndreas Gohr                array_map(
45264159a61SAndreas Gohr                    'ft_snippet_re_preprocess',
45364159a61SAndreas Gohr                    array_map(
45464159a61SAndreas Gohr                        'preg_quote_cb',
45564159a61SAndreas Gohr                        array_filter((array) $highlight)
45664159a61SAndreas Gohr                    )
45764159a61SAndreas Gohr                )
45864159a61SAndreas Gohr            ) .
45964159a61SAndreas Gohr            ')';
460b571ff2dSChuck Kollars        $re2 = "$re1.{0,75}(?!\\1)$re1";
461b571ff2dSChuck Kollars        $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
462546d3a99SAndreas Gohr
463b571ff2dSChuck Kollars        for ($cnt=4; $cnt--;) {
464b571ff2dSChuck Kollars            if (0) {
465b571ff2dSChuck Kollars            } elseif (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
466*24870174SAndreas Gohr
467b571ff2dSChuck Kollars            } elseif (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
468*24870174SAndreas Gohr
469b571ff2dSChuck Kollars            } elseif (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
470*24870174SAndreas Gohr
471b571ff2dSChuck Kollars            } else {
472b571ff2dSChuck Kollars                break;
473b571ff2dSChuck Kollars            }
474ced0762eSchris
475*24870174SAndreas Gohr            [$str, $idx] = $match[0];
476ced0762eSchris
477ced0762eSchris            // convert $idx (a byte offset) into a utf8 character offset
4787fb26b8eSAndreas Gohr            $utf8_idx = PhpString::strlen(substr($text,0,$idx));
4797fb26b8eSAndreas Gohr            $utf8_len = PhpString::strlen($str);
480ced0762eSchris
481ced0762eSchris            // establish context, 100 bytes surrounding the match string
482ced0762eSchris            // first look to see if we can go 100 either side,
483ced0762eSchris            // then drop to 50 adding any excess if the other side can't go to 50,
484ced0762eSchris            $pre = min($utf8_idx-$utf8_offset,100);
485ced0762eSchris            $post = min($len-$utf8_idx-$utf8_len,100);
486ced0762eSchris
487ced0762eSchris            if ($pre>50 && $post>50) {
488*24870174SAndreas Gohr                $pre = 50;
489*24870174SAndreas Gohr                $post = 50;
490ced0762eSchris            } elseif ($pre>50) {
491ced0762eSchris                $pre = min($pre,100-$post);
492ced0762eSchris            } elseif ($post>50) {
493ced0762eSchris                $post = min($post, 100-$pre);
494ef3e3cddSMichael Hamann            } elseif ($offset == 0) {
495ced0762eSchris                // both are less than 50, means the context is the whole string
49610ffc9ddSAndreas Gohr                // make it so and break out of this loop - there is no need for the
49710ffc9ddSAndreas Gohr                // complex snippet calculations
498*24870174SAndreas Gohr                $snippets = [$text];
499ced0762eSchris                break;
500ced0762eSchris            }
501ced0762eSchris
50210ffc9ddSAndreas Gohr            // establish context start and end points, try to append to previous
50310ffc9ddSAndreas Gohr            // context if possible
5049ee93076Schris            $start = $utf8_idx - $pre;
505ced0762eSchris            $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
5069ee93076Schris            $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
507ced0762eSchris
508ced0762eSchris            if ($append) {
5097fb26b8eSAndreas Gohr                $snippets[count($snippets)-1] .= PhpString::substr($text,$append,$end-$append);
510ced0762eSchris            } else {
5117fb26b8eSAndreas Gohr                $snippets[] = PhpString::substr($text,$start,$end-$start);
512ced0762eSchris            }
513ced0762eSchris
514ced0762eSchris            // set $offset for next match attempt
51543d58b76SMichael Hamann            // continue matching after the current match
51643d58b76SMichael Hamann            // if the current match is not the longest possible match starting at the current offset
51743d58b76SMichael Hamann            // this prevents further matching of this snippet but for possible matches of length
51843d58b76SMichael Hamann            // smaller than match length + context (at least 50 characters) this match is part of the context
51943d58b76SMichael Hamann            $utf8_offset = $utf8_idx + $utf8_len;
5207fb26b8eSAndreas Gohr            $offset = $idx + strlen(PhpString::substr($text,$utf8_idx,$utf8_len));
5217fb26b8eSAndreas Gohr            $offset = Clean::correctIdx($text,$offset);
5229ee93076Schris        }
5239ee93076Schris
524ced0762eSchris        $m = "\1";
525b571ff2dSChuck Kollars        $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
52664159a61SAndreas Gohr        $snippet = preg_replace(
52764159a61SAndreas Gohr            '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
52864159a61SAndreas Gohr            '<strong class="search_hit">$1</strong>',
529*24870174SAndreas Gohr            hsc(implode('... ', $snippets))
53064159a61SAndreas Gohr        );
531bd2cb6fcSchris
53260e91a17SAndreas Gohr        $evdata['snippet'] = $snippet;
53360e91a17SAndreas Gohr    }
53460e91a17SAndreas Gohr    $evt->advise_after();
53560e91a17SAndreas Gohr    unset($evt);
53660e91a17SAndreas Gohr
53760e91a17SAndreas Gohr    return $evdata['snippet'];
538506fa893SAndreas Gohr}
539506fa893SAndreas Gohr
540506fa893SAndreas Gohr/**
54126eb848cSGina Haeussge * Wraps a search term in regex boundary checks.
54242ea7f44SGerrit Uitslag *
54342ea7f44SGerrit Uitslag * @param string $term
54442ea7f44SGerrit Uitslag * @return string
54526eb848cSGina Haeussge */
5462237b4faSAndreas Gohrfunction ft_snippet_re_preprocess($term) {
54735594613SKazutaka Miyasaka    // do not process asian terms where word boundaries are not explicit
548*24870174SAndreas Gohr    if(Asian::isAsianWords($term)) return $term;
54935594613SKazutaka Miyasaka
5503161005dSAndreas Gohr    if (UTF8_PROPERTYSUPPORT) {
55184e581a6SAndreas Gohr        // unicode word boundaries
55284e581a6SAndreas Gohr        // see http://stackoverflow.com/a/2449017/172068
55384e581a6SAndreas Gohr        $BL = '(?<!\pL)';
55484e581a6SAndreas Gohr        $BR = '(?!\pL)';
5553161005dSAndreas Gohr    } else {
5563161005dSAndreas Gohr        // not as correct as above, but at least won't break
5573161005dSAndreas Gohr        $BL = '\b';
5583161005dSAndreas Gohr        $BR = '\b';
5593161005dSAndreas Gohr    }
5603161005dSAndreas Gohr
5612237b4faSAndreas Gohr    if(substr($term,0,2) == '\\*'){
5622237b4faSAndreas Gohr        $term = substr($term,2);
5632237b4faSAndreas Gohr    }else{
56484e581a6SAndreas Gohr        $term = $BL.$term;
5652237b4faSAndreas Gohr    }
5662237b4faSAndreas Gohr
5672237b4faSAndreas Gohr    if(substr($term,-2,2) == '\\*'){
5682237b4faSAndreas Gohr        $term = substr($term,0,-2);
5692237b4faSAndreas Gohr    }else{
570*24870174SAndreas Gohr        $term .= $BR;
5712237b4faSAndreas Gohr    }
5728a803caeSAndreas Gohr
57384e581a6SAndreas Gohr    if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
5742237b4faSAndreas Gohr    return $term;
57526eb848cSGina Haeussge}
57626eb848cSGina Haeussge
57726eb848cSGina Haeussge/**
578f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
579f5eb7cf0SAndreas Gohr *
580f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
581f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
582f5eb7cf0SAndreas Gohr *
583f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
584f5eb7cf0SAndreas Gohr *
585f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
58642ea7f44SGerrit Uitslag * @return array
587f5eb7cf0SAndreas Gohr */
588f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){
589f5eb7cf0SAndreas Gohr    $array_count = count($args);
590134f4ab2SAndreas Gohr    if($array_count == 1){
591134f4ab2SAndreas Gohr        return $args[0];
592134f4ab2SAndreas Gohr    }
593134f4ab2SAndreas Gohr
594*24870174SAndreas Gohr    $result = [];
59509c27a6dSGuy Brand    if ($array_count > 1) {
596a21136cdSAndreas Gohr        foreach ($args[0] as $key => $value) {
597a21136cdSAndreas Gohr            $result[$key] = $value;
598f5eb7cf0SAndreas Gohr            for ($i = 1; $i !== $array_count; $i++) {
599a21136cdSAndreas Gohr                if (!isset($args[$i][$key])) {
600a21136cdSAndreas Gohr                    unset($result[$key]);
601a21136cdSAndreas Gohr                    break;
602f5eb7cf0SAndreas Gohr                }
603a21136cdSAndreas Gohr                $result[$key] += $args[$i][$key];
604f5eb7cf0SAndreas Gohr            }
605f5eb7cf0SAndreas Gohr        }
60609c27a6dSGuy Brand    }
607f5eb7cf0SAndreas Gohr    return $result;
608f5eb7cf0SAndreas Gohr}
609f5eb7cf0SAndreas Gohr
610f5eb7cf0SAndreas Gohr/**
611865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores
612f5eb7cf0SAndreas Gohr *
613865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function
614865c2687SKazutaka Miyasaka *
615865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
61642ea7f44SGerrit Uitslag * @return array
61742ea7f44SGerrit Uitslag *
618865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
619865c2687SKazutaka Miyasaka */
620865c2687SKazutaka Miyasakafunction ft_resultUnite($args) {
621865c2687SKazutaka Miyasaka    $array_count = count($args);
622865c2687SKazutaka Miyasaka    if ($array_count === 1) {
623865c2687SKazutaka Miyasaka        return $args[0];
624865c2687SKazutaka Miyasaka    }
625865c2687SKazutaka Miyasaka
626865c2687SKazutaka Miyasaka    $result = $args[0];
627865c2687SKazutaka Miyasaka    for ($i = 1; $i !== $array_count; $i++) {
628865c2687SKazutaka Miyasaka        foreach (array_keys($args[$i]) as $id) {
629865c2687SKazutaka Miyasaka            $result[$id] += $args[$i][$id];
630865c2687SKazutaka Miyasaka        }
631865c2687SKazutaka Miyasaka    }
632865c2687SKazutaka Miyasaka    return $result;
633865c2687SKazutaka Miyasaka}
634865c2687SKazutaka Miyasaka
635865c2687SKazutaka Miyasaka/**
636865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison
637865c2687SKazutaka Miyasaka *
638865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key()
639865c2687SKazutaka Miyasaka *
640865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
64142ea7f44SGerrit Uitslag * @return array
64242ea7f44SGerrit Uitslag *
643865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
644865c2687SKazutaka Miyasaka */
645865c2687SKazutaka Miyasakafunction ft_resultComplement($args) {
646865c2687SKazutaka Miyasaka    $array_count = count($args);
647865c2687SKazutaka Miyasaka    if ($array_count === 1) {
648865c2687SKazutaka Miyasaka        return $args[0];
649865c2687SKazutaka Miyasaka    }
650865c2687SKazutaka Miyasaka
651865c2687SKazutaka Miyasaka    $result = $args[0];
652865c2687SKazutaka Miyasaka    foreach (array_keys($result) as $id) {
653865c2687SKazutaka Miyasaka        for ($i = 1; $i !== $array_count; $i++) {
654865c2687SKazutaka Miyasaka            if (isset($args[$i][$id])) unset($result[$id]);
655865c2687SKazutaka Miyasaka        }
656865c2687SKazutaka Miyasaka    }
657865c2687SKazutaka Miyasaka    return $result;
658865c2687SKazutaka Miyasaka}
659865c2687SKazutaka Miyasaka
660865c2687SKazutaka Miyasaka/**
661865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas
662865c2687SKazutaka Miyasaka *
663865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
664865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
66542ea7f44SGerrit Uitslag *
666*24870174SAndreas Gohr * @param Indexer $Indexer
66742ea7f44SGerrit Uitslag * @param string                  $query search query
66842ea7f44SGerrit Uitslag * @return array of search formulas
669f5eb7cf0SAndreas Gohr */
6709b41be24STom N Harrisfunction ft_queryParser($Indexer, $query){
671865c2687SKazutaka Miyasaka    /**
672865c2687SKazutaka Miyasaka     * parse a search query and transform it into intermediate representation
673865c2687SKazutaka Miyasaka     *
674865c2687SKazutaka Miyasaka     * in a search query, you can use the following expressions:
675865c2687SKazutaka Miyasaka     *
676865c2687SKazutaka Miyasaka     *   words:
677865c2687SKazutaka Miyasaka     *     include
678865c2687SKazutaka Miyasaka     *     -exclude
679865c2687SKazutaka Miyasaka     *   phrases:
680865c2687SKazutaka Miyasaka     *     "phrase to be included"
681865c2687SKazutaka Miyasaka     *     -"phrase you want to exclude"
682865c2687SKazutaka Miyasaka     *   namespaces:
683865c2687SKazutaka Miyasaka     *     @include:namespace (or ns:include:namespace)
684865c2687SKazutaka Miyasaka     *     ^exclude:namespace (or -ns:exclude:namespace)
685865c2687SKazutaka Miyasaka     *   groups:
686865c2687SKazutaka Miyasaka     *     ()
687865c2687SKazutaka Miyasaka     *     -()
688865c2687SKazutaka Miyasaka     *   operators:
689865c2687SKazutaka Miyasaka     *     and ('and' is the default operator: you can always omit this)
6907871d415SKazutaka Miyasaka     *     or  (or pipe symbol '|', lower precedence than 'and')
691865c2687SKazutaka Miyasaka     *
692865c2687SKazutaka Miyasaka     * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
693865c2687SKazutaka Miyasaka     *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
694865c2687SKazutaka Miyasaka     *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
695865c2687SKazutaka Miyasaka     *      as long as you don't mind hit counts.
696865c2687SKazutaka Miyasaka     *
697865c2687SKazutaka Miyasaka     * intermediate representation consists of the following parts:
698865c2687SKazutaka Miyasaka     *
699865c2687SKazutaka Miyasaka     *   ( )           - group
700865c2687SKazutaka Miyasaka     *   AND           - logical and
701865c2687SKazutaka Miyasaka     *   OR            - logical or
702865c2687SKazutaka Miyasaka     *   NOT           - logical not
7032f502d70SKazutaka Miyasaka     *   W+:, W-:, W_: - word      (underscore: no need to highlight)
7042f502d70SKazutaka Miyasaka     *   P+:, P-:      - phrase    (minus sign: logically in NOT group)
7052f502d70SKazutaka Miyasaka     *   N+:, N-:      - namespace
706865c2687SKazutaka Miyasaka     */
707865c2687SKazutaka Miyasaka    $parsed_query = '';
708865c2687SKazutaka Miyasaka    $parens_level = 0;
7097fb26b8eSAndreas Gohr    $terms = preg_split('/(-?".*?")/u', PhpString::strtolower($query),
7106ce3e5f8SAndreas Gohr        -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
711865c2687SKazutaka Miyasaka
712865c2687SKazutaka Miyasaka    foreach ($terms as $term) {
713865c2687SKazutaka Miyasaka        $parsed = '';
714865c2687SKazutaka Miyasaka        if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
715865c2687SKazutaka Miyasaka            // phrase-include and phrase-exclude
716865c2687SKazutaka Miyasaka            $not = $matches[1] ? 'NOT' : '';
7179b41be24STom N Harris            $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
718f5eb7cf0SAndreas Gohr        } else {
719865c2687SKazutaka Miyasaka            // fix incomplete phrase
720865c2687SKazutaka Miyasaka            $term = str_replace('"', ' ', $term);
721865c2687SKazutaka Miyasaka
722865c2687SKazutaka Miyasaka            // fix parentheses
723865c2687SKazutaka Miyasaka            $term = str_replace(')'  , ' ) ', $term);
724865c2687SKazutaka Miyasaka            $term = str_replace('('  , ' ( ', $term);
725865c2687SKazutaka Miyasaka            $term = str_replace('- (', ' -(', $term);
726865c2687SKazutaka Miyasaka
7277871d415SKazutaka Miyasaka            // treat pipe symbols as 'OR' operators
7287871d415SKazutaka Miyasaka            $term = str_replace('|', ' or ', $term);
7297871d415SKazutaka Miyasaka
730865c2687SKazutaka Miyasaka            // treat ideographic spaces (U+3000) as search term separators
731865c2687SKazutaka Miyasaka            // FIXME: some more separators?
732865c2687SKazutaka Miyasaka            $term = preg_replace('/[ \x{3000}]+/u', ' ',  $term);
733865c2687SKazutaka Miyasaka            $term = trim($term);
734865c2687SKazutaka Miyasaka            if ($term === '') continue;
735865c2687SKazutaka Miyasaka
736865c2687SKazutaka Miyasaka            $tokens = explode(' ', $term);
737865c2687SKazutaka Miyasaka            foreach ($tokens as $token) {
738865c2687SKazutaka Miyasaka                if ($token === '(') {
739865c2687SKazutaka Miyasaka                    // parenthesis-include-open
740865c2687SKazutaka Miyasaka                    $parsed .= '(';
741865c2687SKazutaka Miyasaka                    ++$parens_level;
742865c2687SKazutaka Miyasaka                } elseif ($token === '-(') {
743865c2687SKazutaka Miyasaka                    // parenthesis-exclude-open
744865c2687SKazutaka Miyasaka                    $parsed .= 'NOT(';
745865c2687SKazutaka Miyasaka                    ++$parens_level;
746865c2687SKazutaka Miyasaka                } elseif ($token === ')') {
747865c2687SKazutaka Miyasaka                    // parenthesis-any-close
748865c2687SKazutaka Miyasaka                    if ($parens_level === 0) continue;
749865c2687SKazutaka Miyasaka                    $parsed .= ')';
750865c2687SKazutaka Miyasaka                    $parens_level--;
751865c2687SKazutaka Miyasaka                } elseif ($token === 'and') {
752865c2687SKazutaka Miyasaka                    // logical-and (do nothing)
753865c2687SKazutaka Miyasaka                } elseif ($token === 'or') {
754865c2687SKazutaka Miyasaka                    // logical-or
755865c2687SKazutaka Miyasaka                    $parsed .= 'OR';
756865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
757865c2687SKazutaka Miyasaka                    // namespace-exclude
7582f502d70SKazutaka Miyasaka                    $parsed .= 'NOT(N+:'.$matches[1].')';
759865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
760865c2687SKazutaka Miyasaka                    // namespace-include
7612f502d70SKazutaka Miyasaka                    $parsed .= '(N+:'.$matches[1].')';
762865c2687SKazutaka Miyasaka                } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
763865c2687SKazutaka Miyasaka                    // word-exclude
7649b41be24STom N Harris                    $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
765865c2687SKazutaka Miyasaka                } else {
766865c2687SKazutaka Miyasaka                    // word-include
7679b41be24STom N Harris                    $parsed .= ft_termParser($Indexer, $token);
768865c2687SKazutaka Miyasaka                }
769865c2687SKazutaka Miyasaka            }
770865c2687SKazutaka Miyasaka        }
771865c2687SKazutaka Miyasaka        $parsed_query .= $parsed;
772f5eb7cf0SAndreas Gohr    }
773f5eb7cf0SAndreas Gohr
774865c2687SKazutaka Miyasaka    // cleanup (very sensitive)
775865c2687SKazutaka Miyasaka    $parsed_query .= str_repeat(')', $parens_level);
776865c2687SKazutaka Miyasaka    do {
777865c2687SKazutaka Miyasaka        $parsed_query_old = $parsed_query;
778865c2687SKazutaka Miyasaka        $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
779865c2687SKazutaka Miyasaka    } while ($parsed_query !== $parsed_query_old);
780865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')'      , $parsed_query);
781865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(OR)+/u'      , 'OR'     , $parsed_query);
782865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\(OR/u'       , '('      , $parsed_query);
783865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/^OR|OR$/u'    , ''       , $parsed_query);
784865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
785865c2687SKazutaka Miyasaka
7862f502d70SKazutaka Miyasaka    // adjustment: make highlightings right
7872f502d70SKazutaka Miyasaka    $parens_level     = 0;
788*24870174SAndreas Gohr    $notgrp_levels    = [];
7892f502d70SKazutaka Miyasaka    $parsed_query_new = '';
7902f502d70SKazutaka Miyasaka    $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
7912f502d70SKazutaka Miyasaka    foreach ($tokens as $token) {
7922f502d70SKazutaka Miyasaka        if ($token === 'NOT(') {
7932f502d70SKazutaka Miyasaka            $notgrp_levels[] = ++$parens_level;
7942f502d70SKazutaka Miyasaka        } elseif ($token === '(') {
7952f502d70SKazutaka Miyasaka            ++$parens_level;
7962f502d70SKazutaka Miyasaka        } elseif ($token === ')') {
7972f502d70SKazutaka Miyasaka            if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
7982f502d70SKazutaka Miyasaka        } elseif (count($notgrp_levels) % 2 === 1) {
7992f502d70SKazutaka Miyasaka            // turn highlight-flag off if terms are logically in "NOT" group
8002f502d70SKazutaka Miyasaka            $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
8012f502d70SKazutaka Miyasaka        }
8022f502d70SKazutaka Miyasaka        $parsed_query_new .= $token;
8032f502d70SKazutaka Miyasaka    }
8042f502d70SKazutaka Miyasaka    $parsed_query = $parsed_query_new;
8052f502d70SKazutaka Miyasaka
806865c2687SKazutaka Miyasaka    /**
807865c2687SKazutaka Miyasaka     * convert infix notation string into postfix (Reverse Polish notation) array
808865c2687SKazutaka Miyasaka     * by Shunting-yard algorithm
809865c2687SKazutaka Miyasaka     *
810865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
811865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
812865c2687SKazutaka Miyasaka     */
813*24870174SAndreas Gohr    $parsed_ary     = [];
814*24870174SAndreas Gohr    $ope_stack      = [];
815*24870174SAndreas Gohr    $ope_precedence = [')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5];
816865c2687SKazutaka Miyasaka    $ope_regex      = '/([()]|OR|AND|NOT)/u';
817865c2687SKazutaka Miyasaka
818865c2687SKazutaka Miyasaka    $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
819865c2687SKazutaka Miyasaka    foreach ($tokens as $token) {
820865c2687SKazutaka Miyasaka        if (preg_match($ope_regex, $token)) {
821865c2687SKazutaka Miyasaka            // operator
822865c2687SKazutaka Miyasaka            $last_ope = end($ope_stack);
82367d812e0SMarius van Witzenburg            while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
824865c2687SKazutaka Miyasaka                $parsed_ary[] = array_pop($ope_stack);
825865c2687SKazutaka Miyasaka                $last_ope = end($ope_stack);
826865c2687SKazutaka Miyasaka            }
827865c2687SKazutaka Miyasaka            if ($token == ')') {
828865c2687SKazutaka Miyasaka                array_pop($ope_stack); // this array_pop always deletes '('
829865c2687SKazutaka Miyasaka            } else {
830865c2687SKazutaka Miyasaka                $ope_stack[] = $token;
831865c2687SKazutaka Miyasaka            }
832865c2687SKazutaka Miyasaka        } else {
833865c2687SKazutaka Miyasaka            // operand
834*24870174SAndreas Gohr            $token_decoded = str_replace(['OP', 'CP'], ['(', ')'], $token);
835865c2687SKazutaka Miyasaka            $parsed_ary[] = $token_decoded;
836865c2687SKazutaka Miyasaka        }
837865c2687SKazutaka Miyasaka    }
838*24870174SAndreas Gohr    $parsed_ary = array_values([...$parsed_ary, ...array_reverse($ope_stack)]);
839865c2687SKazutaka Miyasaka
840865c2687SKazutaka Miyasaka    // cleanup: each double "NOT" in RPN array actually does nothing
841865c2687SKazutaka Miyasaka    $parsed_ary_count = count($parsed_ary);
842865c2687SKazutaka Miyasaka    for ($i = 1; $i < $parsed_ary_count; ++$i) {
843865c2687SKazutaka Miyasaka        if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
844865c2687SKazutaka Miyasaka            unset($parsed_ary[$i], $parsed_ary[$i - 1]);
845865c2687SKazutaka Miyasaka        }
846865c2687SKazutaka Miyasaka    }
847865c2687SKazutaka Miyasaka    $parsed_ary = array_values($parsed_ary);
848865c2687SKazutaka Miyasaka
849865c2687SKazutaka Miyasaka    // build return value
850*24870174SAndreas Gohr    $q = [];
851f5eb7cf0SAndreas Gohr    $q['query']      = $query;
852865c2687SKazutaka Miyasaka    $q['parsed_str'] = $parsed_query;
853865c2687SKazutaka Miyasaka    $q['parsed_ary'] = $parsed_ary;
854f5eb7cf0SAndreas Gohr
855865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
85640f2b82eSAndreas Gohr        if (strlen($token) < 3 || $token[2] !== ':') continue;
857865c2687SKazutaka Miyasaka        $body = substr($token, 3);
858865c2687SKazutaka Miyasaka
859865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
8602f502d70SKazutaka Miyasaka            case 'N+:':
861865c2687SKazutaka Miyasaka                     $q['ns'][]        = $body; // for backward compatibility
862865c2687SKazutaka Miyasaka                     break;
8632f502d70SKazutaka Miyasaka            case 'N-:':
8642f502d70SKazutaka Miyasaka                     $q['notns'][]     = $body; // for backward compatibility
8652f502d70SKazutaka Miyasaka                     break;
8662f502d70SKazutaka Miyasaka            case 'W_:':
8672f502d70SKazutaka Miyasaka                     $q['words'][]     = $body;
8682f502d70SKazutaka Miyasaka                     break;
869865c2687SKazutaka Miyasaka            case 'W-:':
870865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
8712f502d70SKazutaka Miyasaka                     $q['not'][]       = $body; // for backward compatibility
872865c2687SKazutaka Miyasaka                     break;
873865c2687SKazutaka Miyasaka            case 'W+:':
874865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
8752237b4faSAndreas Gohr                     $q['highlight'][] = $body;
8762f502d70SKazutaka Miyasaka                     $q['and'][]       = $body; // for backward compatibility
877865c2687SKazutaka Miyasaka                     break;
8782f502d70SKazutaka Miyasaka            case 'P-:':
8792f502d70SKazutaka Miyasaka                     $q['phrases'][]   = $body;
8802f502d70SKazutaka Miyasaka                     break;
8812f502d70SKazutaka Miyasaka            case 'P+:':
882865c2687SKazutaka Miyasaka                     $q['phrases'][]   = $body;
8832237b4faSAndreas Gohr                     $q['highlight'][] = $body;
884865c2687SKazutaka Miyasaka                     break;
885865c2687SKazutaka Miyasaka        }
886865c2687SKazutaka Miyasaka    }
887*24870174SAndreas Gohr    foreach (['words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not'] as $key) {
888*24870174SAndreas Gohr        $q[$key] = empty($q[$key]) ? [] : array_values(array_unique($q[$key]));
889f5eb7cf0SAndreas Gohr    }
890f5eb7cf0SAndreas Gohr
891f5eb7cf0SAndreas Gohr    return $q;
892f5eb7cf0SAndreas Gohr}
893f5eb7cf0SAndreas Gohr
894865c2687SKazutaka Miyasaka/**
895865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation
896865c2687SKazutaka Miyasaka *
897865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use.
898865c2687SKazutaka Miyasaka *
899865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
90042ea7f44SGerrit Uitslag *
901*24870174SAndreas Gohr * @param Indexer $Indexer
90242ea7f44SGerrit Uitslag * @param string                  $term
90342ea7f44SGerrit Uitslag * @param bool                    $consider_asian
90442ea7f44SGerrit Uitslag * @param bool                    $phrase_mode
90542ea7f44SGerrit Uitslag * @return string
906865c2687SKazutaka Miyasaka */
9079b41be24STom N Harrisfunction ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) {
908865c2687SKazutaka Miyasaka    $parsed = '';
909865c2687SKazutaka Miyasaka    if ($consider_asian) {
910865c2687SKazutaka Miyasaka        // successive asian characters need to be searched as a phrase
911*24870174SAndreas Gohr        $words = Asian::splitAsianWords($term);
912865c2687SKazutaka Miyasaka        foreach ($words as $word) {
913*24870174SAndreas Gohr            $phrase_mode = $phrase_mode ? true : Asian::isAsianWords($word);
9149b41be24STom N Harris            $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
915865c2687SKazutaka Miyasaka        }
916865c2687SKazutaka Miyasaka    } else {
917*24870174SAndreas Gohr        $term_noparen = str_replace(['(', ')'], ' ', $term);
9189b41be24STom N Harris        $words = $Indexer->tokenizer($term_noparen, true);
919865c2687SKazutaka Miyasaka
9202f502d70SKazutaka Miyasaka        // W_: no need to highlight
921865c2687SKazutaka Miyasaka        if (empty($words)) {
922865c2687SKazutaka Miyasaka            $parsed = '()'; // important: do not remove
923865c2687SKazutaka Miyasaka        } elseif ($words[0] === $term) {
924865c2687SKazutaka Miyasaka            $parsed = '(W+:'.$words[0].')';
925865c2687SKazutaka Miyasaka        } elseif ($phrase_mode) {
926*24870174SAndreas Gohr            $term_encoded = str_replace(['(', ')'], ['OP', 'CP'], $term);
9272f502d70SKazutaka Miyasaka            $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
928865c2687SKazutaka Miyasaka        } else {
929865c2687SKazutaka Miyasaka            $parsed = '((W+:'.implode(')(W+:', $words).'))';
930865c2687SKazutaka Miyasaka        }
931865c2687SKazutaka Miyasaka    }
932865c2687SKazutaka Miyasaka    return $parsed;
933865c2687SKazutaka Miyasaka}
934865c2687SKazutaka Miyasaka
93544156e11SMichael Große/**
93644156e11SMichael Große * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
93744156e11SMichael Große *
93844156e11SMichael Große * @param array $and
93944156e11SMichael Große * @param array $not
94044156e11SMichael Große * @param array $phrases
94144156e11SMichael Große * @param array $ns
94244156e11SMichael Große * @param array $notns
94344156e11SMichael Große *
94444156e11SMichael Große * @return string
94544156e11SMichael Große */
94644156e11SMichael Großefunction ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) {
94744156e11SMichael Große    $query = implode(' ', $and);
948*24870174SAndreas Gohr    if ($not !== []) {
94944156e11SMichael Große        $query .= ' -' . implode(' -', $not);
95044156e11SMichael Große    }
95144156e11SMichael Große
952*24870174SAndreas Gohr    if ($phrases !== []) {
95344156e11SMichael Große        $query .= ' "' . implode('" "', $phrases) . '"';
95444156e11SMichael Große    }
95544156e11SMichael Große
956*24870174SAndreas Gohr    if ($ns !== []) {
95744156e11SMichael Große        $query .= ' @' . implode(' @', $ns);
95844156e11SMichael Große    }
95944156e11SMichael Große
960*24870174SAndreas Gohr    if ($notns !== []) {
96144156e11SMichael Große        $query .= ' ^' . implode(' ^', $notns);
96244156e11SMichael Große    }
96344156e11SMichael Große
96444156e11SMichael Große    return $query;
96544156e11SMichael Große}
96644156e11SMichael Große
967e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 :
968