xref: /dokuwiki/inc/fulltext.php (revision dccd6b2bba7367e4d1d2d7aa84c9f9d15584b593)
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 */
824870174SAndreas Gohruse dokuwiki\Utf8\Asian;
924870174SAndreas 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 */
35d868eb89SAndreas Gohrfunction ft_pageSearch($query, &$highlight, $sort = null, $after = null, $before = null)
36d868eb89SAndreas Gohr{
376840140fSChris Smith
383850270cSMichael Große    if ($sort === null) {
393850270cSMichael Große        $sort = 'hits';
403850270cSMichael Große    }
413850270cSMichael Große    $data = [
423850270cSMichael Große        'query' => $query,
433850270cSMichael Große        'sort' => $sort,
443850270cSMichael Große        'after' => $after,
453850270cSMichael Große        'before' => $before
463850270cSMichael Große    ];
476840140fSChris Smith    $data['highlight'] =& $highlight;
486840140fSChris Smith
49cbb44eabSAndreas Gohr    return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
506840140fSChris Smith}
51865c2687SKazutaka Miyasaka
52865c2687SKazutaka Miyasaka/**
53865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query
54865c2687SKazutaka Miyasaka *
55865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
56865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
5742ea7f44SGerrit Uitslag *
5842ea7f44SGerrit Uitslag * @param array $data event data
5942ea7f44SGerrit Uitslag * @return array matching documents
60865c2687SKazutaka Miyasaka */
61d868eb89SAndreas Gohrfunction _ft_pageSearch(&$data)
62d868eb89SAndreas Gohr{
639b41be24STom N Harris    $Indexer = idx_get_indexer();
649b41be24STom N Harris
65865c2687SKazutaka Miyasaka    // parse the given query
669b41be24STom N Harris    $q = ft_queryParser($Indexer, $data['query']);
67865c2687SKazutaka Miyasaka    $data['highlight'] = $q['highlight'];
686840140fSChris Smith
6924870174SAndreas Gohr    if (empty($q['parsed_ary'])) return [];
70506fa893SAndreas Gohr
71f5eb7cf0SAndreas Gohr    // lookup all words found in the query
729b41be24STom N Harris    $lookup = $Indexer->lookup($q['words']);
73f5eb7cf0SAndreas Gohr
74865c2687SKazutaka Miyasaka    // get all pages in this dokuwiki site (!: includes nonexistent pages)
7524870174SAndreas Gohr    $pages_all = [];
769b41be24STom N Harris    foreach ($Indexer->getPages() as $id) {
779b41be24STom N Harris        $pages_all[$id] = 0; // base: 0 hit
78f5eb7cf0SAndreas Gohr    }
79f5eb7cf0SAndreas Gohr
80865c2687SKazutaka Miyasaka    // process the query
8124870174SAndreas Gohr    $stack = [];
82865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
83865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
84865c2687SKazutaka Miyasaka            case 'W+:':
852f502d70SKazutaka Miyasaka            case 'W-:':
862f502d70SKazutaka Miyasaka            case 'W_:': // word
87865c2687SKazutaka Miyasaka                $word    = substr($token, 3);
885afd9580SAndreas Gohr                if(isset($lookup[$word])) {
89865c2687SKazutaka Miyasaka                    $stack[] = (array)$lookup[$word];
905afd9580SAndreas Gohr                }
91865c2687SKazutaka Miyasaka                break;
922f502d70SKazutaka Miyasaka            case 'P+:':
932f502d70SKazutaka Miyasaka            case 'P-:': // phrase
94865c2687SKazutaka Miyasaka                $phrase = substr($token, 3);
95865c2687SKazutaka Miyasaka                // since phrases are always parsed as ((W1)(W2)...(P)),
96865c2687SKazutaka Miyasaka                // the end($stack) always points the pages that contain
97865c2687SKazutaka Miyasaka                // all words in this phrase
98865c2687SKazutaka Miyasaka                $pages  = end($stack);
9924870174SAndreas Gohr                $pages_matched = [];
100865c2687SKazutaka Miyasaka                foreach(array_keys($pages) as $id){
10124870174SAndreas Gohr                    $evdata = [
102a7e8b43eSMichael Hamann                        'id' => $id,
103a7e8b43eSMichael Hamann                        'phrase' => $phrase,
104a7e8b43eSMichael Hamann                        'text' => rawWiki($id)
10524870174SAndreas Gohr                    ];
106e1d9dcc8SAndreas Gohr                    $evt = new Event('FULLTEXT_PHRASE_MATCH', $evdata);
107a7e8b43eSMichael Hamann                    if ($evt->advise_before() && $evt->result !== true) {
1087fb26b8eSAndreas Gohr                        $text = PhpString::strtolower($evdata['text']);
109865c2687SKazutaka Miyasaka                        if (strpos($text, $phrase) !== false) {
110a7e8b43eSMichael Hamann                            $evt->result = true;
111a7e8b43eSMichael Hamann                        }
112a7e8b43eSMichael Hamann                    }
113a7e8b43eSMichael Hamann                    $evt->advise_after();
114a7e8b43eSMichael Hamann                    if ($evt->result === true) {
115865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // phrase: always 0 hit
116865c2687SKazutaka Miyasaka                    }
117865c2687SKazutaka Miyasaka                }
118865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
119865c2687SKazutaka Miyasaka                break;
1202f502d70SKazutaka Miyasaka            case 'N+:':
1212f502d70SKazutaka Miyasaka            case 'N-:': // namespace
122de3383c6SMichael Große                $ns = cleanID(substr($token, 3)) . ':';
12324870174SAndreas Gohr                $pages_matched = [];
124865c2687SKazutaka Miyasaka                foreach (array_keys($pages_all) as $id) {
125865c2687SKazutaka Miyasaka                    if (strpos($id, $ns) === 0) {
126865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // namespace: always 0 hit
127865c2687SKazutaka Miyasaka                    }
128865c2687SKazutaka Miyasaka                }
129865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
130865c2687SKazutaka Miyasaka                break;
131865c2687SKazutaka Miyasaka            case 'AND': // and operation
13224870174SAndreas Gohr                [$pages1, $pages2] = array_splice($stack, -2);
13324870174SAndreas Gohr                $stack[] = ft_resultCombine([$pages1, $pages2]);
134865c2687SKazutaka Miyasaka                break;
135865c2687SKazutaka Miyasaka            case 'OR':  // or operation
13624870174SAndreas Gohr                [$pages1, $pages2] = array_splice($stack, -2);
13724870174SAndreas Gohr                $stack[] = ft_resultUnite([$pages1, $pages2]);
138865c2687SKazutaka Miyasaka                break;
139865c2687SKazutaka Miyasaka            case 'NOT': // not operation (unary)
140865c2687SKazutaka Miyasaka                $pages   = array_pop($stack);
14124870174SAndreas Gohr                $stack[] = ft_resultComplement([$pages_all, $pages]);
142a21136cdSAndreas Gohr                break;
143a21136cdSAndreas Gohr        }
144f5eb7cf0SAndreas Gohr    }
145865c2687SKazutaka Miyasaka    $docs = array_pop($stack);
146865c2687SKazutaka Miyasaka
14724870174SAndreas Gohr    if (empty($docs)) return [];
148865c2687SKazutaka Miyasaka
149865c2687SKazutaka Miyasaka    // check: settings, acls, existence
150865c2687SKazutaka Miyasaka    foreach (array_keys($docs) as $id) {
151865c2687SKazutaka Miyasaka        if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
152865c2687SKazutaka Miyasaka            unset($docs[$id]);
153f5eb7cf0SAndreas Gohr        }
154f5eb7cf0SAndreas Gohr    }
155f5eb7cf0SAndreas Gohr
1563850270cSMichael Große    $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']);
1578d0e286aSMichael Große
1588d0e286aSMichael Große    if ($data['sort'] === 'mtime') {
1598d0e286aSMichael Große        uksort($docs, 'ft_pagemtimesorter');
1608d0e286aSMichael Große    } else {
161865c2687SKazutaka Miyasaka        // sort docs by count
16206281c9cSMoisés Braga Ribeiro        uksort($docs, 'ft_pagesorter');
163f5eb7cf0SAndreas Gohr        arsort($docs);
1648d0e286aSMichael Große    }
165f5eb7cf0SAndreas Gohr
166f5eb7cf0SAndreas Gohr    return $docs;
167f5eb7cf0SAndreas Gohr}
168f5eb7cf0SAndreas Gohr
169f5eb7cf0SAndreas Gohr/**
17054f4c056SAndreas Gohr * Returns the backlinks for a given page
17154f4c056SAndreas Gohr *
172320f489aSMichael Hamann * Uses the metadata index.
17307ff0babSMichael Hamann *
17407ff0babSMichael Hamann * @param string $id           The id for which links shall be returned
17507ff0babSMichael Hamann * @param bool   $ignore_perms Ignore the fact that pages are hidden or read-protected
17607ff0babSMichael Hamann * @return array The pages that contain links to the given page
17754f4c056SAndreas Gohr */
178d868eb89SAndreas Gohrfunction ft_backlinks($id, $ignore_perms = false)
179d868eb89SAndreas Gohr{
180320f489aSMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_references', $id);
18154f4c056SAndreas Gohr
18224870174SAndreas Gohr    if($result === []) return $result;
18363773904SAndreas Gohr
18463773904SAndreas Gohr    // check ACL permissions
18563773904SAndreas Gohr    foreach(array_keys($result) as $idx){
18624870174SAndreas Gohr        if((!$ignore_perms && (
18707ff0babSMichael Hamann                isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
18807ff0babSMichael Hamann            )) || !page_exists($result[$idx], '', false)){
18963773904SAndreas Gohr            unset($result[$idx]);
19063773904SAndreas Gohr        }
19163773904SAndreas Gohr    }
19263773904SAndreas Gohr
1932d85e841SAndreas Gohr    Sort::sort($result);
19454f4c056SAndreas Gohr    return $result;
19554f4c056SAndreas Gohr}
19654f4c056SAndreas Gohr
19754f4c056SAndreas Gohr/**
198a05e297aSAndreas Gohr * Returns the pages that use a given media file
199a05e297aSAndreas Gohr *
200ffec1009SMichael Hamann * Uses the relation media metadata property and the metadata index.
201a05e297aSAndreas Gohr *
202ffec1009SMichael Hamann * Note that before 2013-07-31 the second parameter was the maximum number of results and
203ffec1009SMichael Hamann * permissions were ignored. That's why the parameter is now checked to be explicitely set
204ffec1009SMichael Hamann * to true (with type bool) in order to be compatible with older uses of the function.
205ffec1009SMichael Hamann *
206ffec1009SMichael Hamann * @param string $id           The media id to look for
207ffec1009SMichael Hamann * @param bool   $ignore_perms Ignore hidden pages and acls (optional, default: false)
208ffec1009SMichael Hamann * @return array A list of pages that use the given media file
209a05e297aSAndreas Gohr */
210d868eb89SAndreas Gohrfunction ft_mediause($id, $ignore_perms = false)
211d868eb89SAndreas Gohr{
212ffec1009SMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_media', $id);
213a05e297aSAndreas Gohr
21424870174SAndreas Gohr    if($result === []) return $result;
215a05e297aSAndreas Gohr
216ffec1009SMichael Hamann    // check ACL permissions
217ffec1009SMichael Hamann    foreach(array_keys($result) as $idx){
21824870174SAndreas Gohr        if((!$ignore_perms && (
219ffec1009SMichael Hamann                    isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
220ffec1009SMichael Hamann                )) || !page_exists($result[$idx], '', false)){
221ffec1009SMichael Hamann            unset($result[$idx]);
222a05e297aSAndreas Gohr        }
223a05e297aSAndreas Gohr    }
224a05e297aSAndreas Gohr
2252d85e841SAndreas Gohr    Sort::sort($result);
226a05e297aSAndreas Gohr    return $result;
227a05e297aSAndreas Gohr}
228a05e297aSAndreas Gohr
229a05e297aSAndreas Gohr
230a05e297aSAndreas Gohr/**
231506fa893SAndreas Gohr * Quicksearch for pagenames
232506fa893SAndreas Gohr *
233506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
23480423ab6SAdrian Lang * namespace. This can be changed with the second parameter.
23580423ab6SAdrian Lang * The third parameter allows to search in titles as well.
236506fa893SAndreas Gohr *
2378d22f1e9SAndreas Gohr * The function always returns titles as well
2386840140fSChris Smith *
2398d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP
240506fa893SAndreas Gohr * @author   Andreas Gohr <andi@splitbrain.org>
2418d22f1e9SAndreas Gohr * @author   Adrian Lang <lang@cosmocode.de>
24242ea7f44SGerrit Uitslag *
24342ea7f44SGerrit Uitslag * @param string     $id       page id
24442ea7f44SGerrit Uitslag * @param bool       $in_ns    match against namespace as well?
24542ea7f44SGerrit Uitslag * @param bool       $in_title search in title?
24664159a61SAndreas Gohr * @param int|string $after    only show results with mtime after this date, accepts timestap or strtotime arguments
24764159a61SAndreas Gohr * @param int|string $before   only show results with mtime before this date, accepts timestap or strtotime arguments
2483850270cSMichael Große *
24942ea7f44SGerrit Uitslag * @return string[]
250506fa893SAndreas Gohr */
251d868eb89SAndreas Gohrfunction ft_pageLookup($id, $in_ns = false, $in_title = false, $after = null, $before = null)
252d868eb89SAndreas Gohr{
2533850270cSMichael Große    $data = [
2543850270cSMichael Große        'id' => $id,
2553850270cSMichael Große        'in_ns' => $in_ns,
2563850270cSMichael Große        'in_title' => $in_title,
2573850270cSMichael Große        'after' => $after,
2583850270cSMichael Große        'before' => $before
2593850270cSMichael Große    ];
2608d22f1e9SAndreas Gohr    $data['has_titles'] = true; // for plugin backward compatibility check
261cbb44eabSAndreas Gohr    return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup');
2626840140fSChris Smith}
2636840140fSChris Smith
26442ea7f44SGerrit Uitslag/**
26542ea7f44SGerrit Uitslag * Returns list of pages as array(pageid => First Heading)
26642ea7f44SGerrit Uitslag *
26742ea7f44SGerrit Uitslag * @param array &$data event data
26842ea7f44SGerrit Uitslag * @return string[]
26942ea7f44SGerrit Uitslag */
270d868eb89SAndreas Gohrfunction _ft_pageLookup(&$data)
271d868eb89SAndreas Gohr{
27280423ab6SAdrian Lang    // split out original parameters
2736840140fSChris Smith    $id = $data['id'];
274940f24fcSMichael Große    $Indexer = idx_get_indexer();
275940f24fcSMichael Große    $parsedQuery = ft_queryParser($Indexer, $id);
276940f24fcSMichael Große    if (count($parsedQuery['ns']) > 0) {
277940f24fcSMichael Große        $ns = cleanID($parsedQuery['ns'][0]) . ':';
278940f24fcSMichael Große        $id = implode(' ', $parsedQuery['highlight']);
279b0f6db0cSAdrian Lang    }
280248d652bSGerrit Uitslag    if (count($parsedQuery['notns']) > 0) {
281248d652bSGerrit Uitslag        $notns = cleanID($parsedQuery['notns'][0]) . ':';
282248d652bSGerrit Uitslag        $id = implode(' ', $parsedQuery['highlight']);
283248d652bSGerrit Uitslag    }
284b0f6db0cSAdrian Lang
2858d22f1e9SAndreas Gohr    $in_ns    = $data['in_ns'];
2868d22f1e9SAndreas Gohr    $in_title = $data['in_title'];
28780423ab6SAdrian Lang    $cleaned = cleanID($id);
2889b41be24STom N Harris
2899b41be24STom N Harris    $Indexer = idx_get_indexer();
2909b41be24STom N Harris    $page_idx = $Indexer->getPages();
2919b41be24STom N Harris
29224870174SAndreas Gohr    $pages = [];
2935479a8c3SAndreas Gohr    if ($id !== '' && $cleaned !== '') {
2949b41be24STom N Harris        foreach ($page_idx as $p_id) {
2959b41be24STom N Harris            if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) {
2969b41be24STom N Harris                if (!isset($pages[$p_id]))
29767c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
298506fa893SAndreas Gohr            }
299506fa893SAndreas Gohr        }
300f078bb00STom N Harris        if ($in_title) {
301c66f16a3SMichael Hamann            foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) {
302f078bb00STom N Harris                if (!isset($pages[$p_id]))
30367c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
304f078bb00STom N Harris            }
305f078bb00STom N Harris        }
306d0bdf765SAdrian Lang    }
3070c074a52SMichael Hamann
308d0bdf765SAdrian Lang    if (isset($ns)) {
3090c074a52SMichael Hamann        foreach (array_keys($pages) as $p_id) {
3100c074a52SMichael Hamann            if (strpos($p_id, $ns) !== 0) {
3110c074a52SMichael Hamann                unset($pages[$p_id]);
312d0bdf765SAdrian Lang            }
313d0bdf765SAdrian Lang        }
314506fa893SAndreas Gohr    }
315248d652bSGerrit Uitslag    if (isset($notns)) {
316248d652bSGerrit Uitslag        foreach (array_keys($pages) as $p_id) {
317248d652bSGerrit Uitslag            if (strpos($p_id, $notns) === 0) {
318248d652bSGerrit Uitslag                unset($pages[$p_id]);
319248d652bSGerrit Uitslag            }
320248d652bSGerrit Uitslag        }
321248d652bSGerrit Uitslag    }
32263773904SAndreas Gohr
32380423ab6SAdrian Lang    // discard hidden pages
32480423ab6SAdrian Lang    // discard nonexistent pages
32563773904SAndreas Gohr    // check ACL permissions
32663773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
32780423ab6SAdrian Lang        if(!isVisiblePage($idx) || !page_exists($idx) ||
32880423ab6SAdrian Lang           auth_quickaclcheck($idx) < AUTH_READ) {
32963773904SAndreas Gohr            unset($pages[$idx]);
33063773904SAndreas Gohr        }
33163773904SAndreas Gohr    }
33263773904SAndreas Gohr
3333850270cSMichael Große    $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']);
3341b48999cSMichael Große
3353d2017d9SAdrian Lang    uksort($pages, 'ft_pagesorter');
3368d22f1e9SAndreas Gohr    return $pages;
337506fa893SAndreas Gohr}
338506fa893SAndreas Gohr
3391b48999cSMichael Große
3401b48999cSMichael Große/**
3411b48999cSMichael Große * @param array      $results search results in the form pageid => value
34264159a61SAndreas Gohr * @param int|string $after   only returns results with mtime after this date, accepts timestap or strtotime arguments
34364159a61SAndreas Gohr * @param int|string $before  only returns results with mtime after this date, accepts timestap or strtotime arguments
3441b48999cSMichael Große *
3451b48999cSMichael Große * @return array
3461b48999cSMichael Große */
347d868eb89SAndreas Gohrfunction _ft_filterResultsByTime(array $results, $after, $before)
348d868eb89SAndreas Gohr{
3493850270cSMichael Große    if ($after || $before) {
3501b48999cSMichael Große        $after = is_int($after) ? $after : strtotime($after);
3511b48999cSMichael Große        $before = is_int($before) ? $before : strtotime($before);
3521b48999cSMichael Große
35324870174SAndreas Gohr        foreach (array_keys($results) as $id) {
3541b48999cSMichael Große            $mTime = filemtime(wikiFN($id));
3551b48999cSMichael Große            if ($after && $after > $mTime) {
3561b48999cSMichael Große                unset($results[$id]);
3571b48999cSMichael Große                continue;
3581b48999cSMichael Große            }
3591b48999cSMichael Große            if ($before && $before < $mTime) {
3601b48999cSMichael Große                unset($results[$id]);
3611b48999cSMichael Große            }
3621b48999cSMichael Große        }
3631b48999cSMichael Große    }
3641b48999cSMichael Große
3651b48999cSMichael Große    return $results;
3661b48999cSMichael Große}
3671b48999cSMichael Große
368506fa893SAndreas Gohr/**
369c66f16a3SMichael Hamann * Tiny helper function for comparing the searched title with the title
370c66f16a3SMichael Hamann * from the search index. This function is a wrapper around stripos with
371c66f16a3SMichael Hamann * adapted argument order and return value.
37242ea7f44SGerrit Uitslag *
37342ea7f44SGerrit Uitslag * @param string $search searched title
37442ea7f44SGerrit Uitslag * @param string $title  title from index
37542ea7f44SGerrit Uitslag * @return bool
376c66f16a3SMichael Hamann */
377d868eb89SAndreas Gohrfunction _ft_pageLookupTitleCompare($search, $title)
378d868eb89SAndreas Gohr{
3797fb26b8eSAndreas Gohr    if (Clean::isASCII($search)) {
3807fb26b8eSAndreas Gohr        $pos = stripos($title, $search);
3817fb26b8eSAndreas Gohr    } else {
3827fb26b8eSAndreas Gohr        $pos = PhpString::strpos(
3837fb26b8eSAndreas Gohr            PhpString::strtolower($title),
3847fb26b8eSAndreas Gohr            PhpString::strtolower($search)
3857fb26b8eSAndreas Gohr        );
3867fb26b8eSAndreas Gohr    }
3877fb26b8eSAndreas Gohr
3887fb26b8eSAndreas Gohr    return $pos !== false;
389c66f16a3SMichael Hamann}
390c66f16a3SMichael Hamann
391c66f16a3SMichael Hamann/**
392f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string
393f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy
394f31eb72bSAndreas Gohr * pages.
39542ea7f44SGerrit Uitslag *
39642ea7f44SGerrit Uitslag * @param string $a
39742ea7f44SGerrit Uitslag * @param string $b
39842ea7f44SGerrit Uitslag * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal.
399f31eb72bSAndreas Gohr */
400d868eb89SAndreas Gohrfunction ft_pagesorter($a, $b)
401d868eb89SAndreas Gohr{
402f31eb72bSAndreas Gohr    $ac = count(explode(':', $a));
403f31eb72bSAndreas Gohr    $bc = count(explode(':', $b));
404f31eb72bSAndreas Gohr    if($ac < $bc){
405f31eb72bSAndreas Gohr        return -1;
406f31eb72bSAndreas Gohr    }elseif($ac > $bc){
407f31eb72bSAndreas Gohr        return 1;
408f31eb72bSAndreas Gohr    }
4092d85e841SAndreas Gohr    return Sort::strcmp($a, $b);
410f31eb72bSAndreas Gohr}
411f31eb72bSAndreas Gohr
412f31eb72bSAndreas Gohr/**
4138d0e286aSMichael Große * Sort pages by their mtime, from newest to oldest
4148d0e286aSMichael Große *
4158d0e286aSMichael Große * @param string $a
4168d0e286aSMichael Große * @param string $b
4178d0e286aSMichael Große *
4188d0e286aSMichael 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
4198d0e286aSMichael Große */
420d868eb89SAndreas Gohrfunction ft_pagemtimesorter($a, $b)
421d868eb89SAndreas Gohr{
4228d0e286aSMichael Große    $mtimeA = filemtime(wikiFN($a));
4238d0e286aSMichael Große    $mtimeB = filemtime(wikiFN($b));
4248d0e286aSMichael Große    return $mtimeB - $mtimeA;
4258d0e286aSMichael Große}
4268d0e286aSMichael Große
4278d0e286aSMichael Große/**
428506fa893SAndreas Gohr * Creates a snippet extract
429506fa893SAndreas Gohr *
430506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
43160e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE
43242ea7f44SGerrit Uitslag *
43342ea7f44SGerrit Uitslag * @param string $id page id
43442ea7f44SGerrit Uitslag * @param array $highlight
43542ea7f44SGerrit Uitslag * @return mixed
436506fa893SAndreas Gohr */
437d868eb89SAndreas Gohrfunction ft_snippet($id, $highlight)
438d868eb89SAndreas Gohr{
439506fa893SAndreas Gohr    $text = rawWiki($id);
44024870174SAndreas Gohr    $text = str_replace("\xC2\xAD", '', $text);
44124870174SAndreas Gohr     // remove soft-hyphens
44224870174SAndreas Gohr    $evdata = [
44360e91a17SAndreas Gohr        'id'        => $id,
44460e91a17SAndreas Gohr        'text'      => &$text,
44560e91a17SAndreas Gohr        'highlight' => &$highlight,
44624870174SAndreas Gohr        'snippet'   => ''
44724870174SAndreas Gohr    ];
44860e91a17SAndreas Gohr
449e1d9dcc8SAndreas Gohr    $evt = new Event('FULLTEXT_SNIPPET_CREATE', $evdata);
45060e91a17SAndreas Gohr    if ($evt->advise_before()) {
45124870174SAndreas Gohr        $match = [];
45224870174SAndreas Gohr        $snippets = [];
45324870174SAndreas Gohr        $utf8_offset = 0;
45424870174SAndreas Gohr        $offset = 0;
45524870174SAndreas Gohr        $end = 0;
4567fb26b8eSAndreas Gohr        $len = PhpString::strlen($text);
4579ee93076Schris
458546d3a99SAndreas Gohr        // build a regexp from the phrases to highlight
45964159a61SAndreas Gohr        $re1 = '(' .
46024870174SAndreas Gohr            implode(
46164159a61SAndreas Gohr                '|',
46264159a61SAndreas Gohr                array_map(
46364159a61SAndreas Gohr                    'ft_snippet_re_preprocess',
46464159a61SAndreas Gohr                    array_map(
46564159a61SAndreas Gohr                        'preg_quote_cb',
46664159a61SAndreas Gohr                        array_filter((array) $highlight)
46764159a61SAndreas Gohr                    )
46864159a61SAndreas Gohr                )
46964159a61SAndreas Gohr            ) .
47064159a61SAndreas Gohr            ')';
471b571ff2dSChuck Kollars        $re2 = "$re1.{0,75}(?!\\1)$re1";
472b571ff2dSChuck Kollars        $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
473546d3a99SAndreas Gohr
474b571ff2dSChuck Kollars        for ($cnt=4; $cnt--;) {
475b571ff2dSChuck Kollars            if (0) {
476b571ff2dSChuck Kollars            } elseif (preg_match('/'.$re3.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
47724870174SAndreas Gohr
478b571ff2dSChuck Kollars            } elseif (preg_match('/'.$re2.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
47924870174SAndreas Gohr
480b571ff2dSChuck Kollars            } elseif (preg_match('/'.$re1.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
48124870174SAndreas Gohr
482b571ff2dSChuck Kollars            } else {
483b571ff2dSChuck Kollars                break;
484b571ff2dSChuck Kollars            }
485ced0762eSchris
48624870174SAndreas Gohr            [$str, $idx] = $match[0];
487ced0762eSchris
488ced0762eSchris            // convert $idx (a byte offset) into a utf8 character offset
4897fb26b8eSAndreas Gohr            $utf8_idx = PhpString::strlen(substr($text, 0, $idx));
4907fb26b8eSAndreas Gohr            $utf8_len = PhpString::strlen($str);
491ced0762eSchris
492ced0762eSchris            // establish context, 100 bytes surrounding the match string
493ced0762eSchris            // first look to see if we can go 100 either side,
494ced0762eSchris            // then drop to 50 adding any excess if the other side can't go to 50,
495ced0762eSchris            $pre = min($utf8_idx-$utf8_offset, 100);
496ced0762eSchris            $post = min($len-$utf8_idx-$utf8_len, 100);
497ced0762eSchris
498ced0762eSchris            if ($pre>50 && $post>50) {
49924870174SAndreas Gohr                $pre = 50;
50024870174SAndreas Gohr                $post = 50;
501ced0762eSchris            } elseif ($pre>50) {
502ced0762eSchris                $pre = min($pre, 100-$post);
503ced0762eSchris            } elseif ($post>50) {
504ced0762eSchris                $post = min($post, 100-$pre);
505ef3e3cddSMichael Hamann            } elseif ($offset == 0) {
506ced0762eSchris                // both are less than 50, means the context is the whole string
50710ffc9ddSAndreas Gohr                // make it so and break out of this loop - there is no need for the
50810ffc9ddSAndreas Gohr                // complex snippet calculations
50924870174SAndreas Gohr                $snippets = [$text];
510ced0762eSchris                break;
511ced0762eSchris            }
512ced0762eSchris
51310ffc9ddSAndreas Gohr            // establish context start and end points, try to append to previous
51410ffc9ddSAndreas Gohr            // context if possible
5159ee93076Schris            $start = $utf8_idx - $pre;
516ced0762eSchris            $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
5179ee93076Schris            $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
518ced0762eSchris
519ced0762eSchris            if ($append) {
5207fb26b8eSAndreas Gohr                $snippets[count($snippets)-1] .= PhpString::substr($text, $append, $end-$append);
521ced0762eSchris            } else {
5227fb26b8eSAndreas Gohr                $snippets[] = PhpString::substr($text, $start, $end-$start);
523ced0762eSchris            }
524ced0762eSchris
525ced0762eSchris            // set $offset for next match attempt
52643d58b76SMichael Hamann            // continue matching after the current match
52743d58b76SMichael Hamann            // if the current match is not the longest possible match starting at the current offset
52843d58b76SMichael Hamann            // this prevents further matching of this snippet but for possible matches of length
52943d58b76SMichael Hamann            // smaller than match length + context (at least 50 characters) this match is part of the context
53043d58b76SMichael Hamann            $utf8_offset = $utf8_idx + $utf8_len;
5317fb26b8eSAndreas Gohr            $offset = $idx + strlen(PhpString::substr($text, $utf8_idx, $utf8_len));
5327fb26b8eSAndreas Gohr            $offset = Clean::correctIdx($text, $offset);
5339ee93076Schris        }
5349ee93076Schris
535ced0762eSchris        $m = "\1";
536b571ff2dSChuck Kollars        $snippets = preg_replace('/'.$re1.'/iu', $m.'$1'.$m, $snippets);
53764159a61SAndreas Gohr        $snippet = preg_replace(
53864159a61SAndreas Gohr            '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
53964159a61SAndreas Gohr            '<strong class="search_hit">$1</strong>',
54024870174SAndreas Gohr            hsc(implode('... ', $snippets))
54164159a61SAndreas Gohr        );
542bd2cb6fcSchris
54360e91a17SAndreas Gohr        $evdata['snippet'] = $snippet;
54460e91a17SAndreas Gohr    }
54560e91a17SAndreas Gohr    $evt->advise_after();
54660e91a17SAndreas Gohr    unset($evt);
54760e91a17SAndreas Gohr
54860e91a17SAndreas Gohr    return $evdata['snippet'];
549506fa893SAndreas Gohr}
550506fa893SAndreas Gohr
551506fa893SAndreas Gohr/**
55226eb848cSGina Haeussge * Wraps a search term in regex boundary checks.
55342ea7f44SGerrit Uitslag *
55442ea7f44SGerrit Uitslag * @param string $term
55542ea7f44SGerrit Uitslag * @return string
55626eb848cSGina Haeussge */
557d868eb89SAndreas Gohrfunction ft_snippet_re_preprocess($term)
558d868eb89SAndreas Gohr{
55935594613SKazutaka Miyasaka    // do not process asian terms where word boundaries are not explicit
56024870174SAndreas Gohr    if(Asian::isAsianWords($term)) return $term;
56135594613SKazutaka Miyasaka
5623161005dSAndreas Gohr    if (UTF8_PROPERTYSUPPORT) {
56384e581a6SAndreas Gohr        // unicode word boundaries
56484e581a6SAndreas Gohr        // see http://stackoverflow.com/a/2449017/172068
56584e581a6SAndreas Gohr        $BL = '(?<!\pL)';
56684e581a6SAndreas Gohr        $BR = '(?!\pL)';
5673161005dSAndreas Gohr    } else {
5683161005dSAndreas Gohr        // not as correct as above, but at least won't break
5693161005dSAndreas Gohr        $BL = '\b';
5703161005dSAndreas Gohr        $BR = '\b';
5713161005dSAndreas Gohr    }
5723161005dSAndreas Gohr
5732237b4faSAndreas Gohr    if(substr($term, 0, 2) == '\\*'){
5742237b4faSAndreas Gohr        $term = substr($term, 2);
5752237b4faSAndreas Gohr    }else{
57684e581a6SAndreas Gohr        $term = $BL.$term;
5772237b4faSAndreas Gohr    }
5782237b4faSAndreas Gohr
5792237b4faSAndreas Gohr    if(substr($term, -2, 2) == '\\*'){
5802237b4faSAndreas Gohr        $term = substr($term, 0, -2);
5812237b4faSAndreas Gohr    }else{
58224870174SAndreas Gohr        $term .= $BR;
5832237b4faSAndreas Gohr    }
5848a803caeSAndreas Gohr
58584e581a6SAndreas Gohr    if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
5862237b4faSAndreas Gohr    return $term;
58726eb848cSGina Haeussge}
58826eb848cSGina Haeussge
58926eb848cSGina Haeussge/**
590f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
591f5eb7cf0SAndreas Gohr *
592f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
593f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
594f5eb7cf0SAndreas Gohr *
595f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
596f5eb7cf0SAndreas Gohr *
597f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
59842ea7f44SGerrit Uitslag * @return array
599f5eb7cf0SAndreas Gohr */
600d868eb89SAndreas Gohrfunction ft_resultCombine($args)
601d868eb89SAndreas Gohr{
602f5eb7cf0SAndreas Gohr    $array_count = count($args);
603134f4ab2SAndreas Gohr    if($array_count == 1){
604134f4ab2SAndreas Gohr        return $args[0];
605134f4ab2SAndreas Gohr    }
606134f4ab2SAndreas Gohr
60724870174SAndreas Gohr    $result = [];
60809c27a6dSGuy Brand    if ($array_count > 1) {
609a21136cdSAndreas Gohr        foreach ($args[0] as $key => $value) {
610a21136cdSAndreas Gohr            $result[$key] = $value;
611f5eb7cf0SAndreas Gohr            for ($i = 1; $i !== $array_count; $i++) {
612a21136cdSAndreas Gohr                if (!isset($args[$i][$key])) {
613a21136cdSAndreas Gohr                    unset($result[$key]);
614a21136cdSAndreas Gohr                    break;
615f5eb7cf0SAndreas Gohr                }
616a21136cdSAndreas Gohr                $result[$key] += $args[$i][$key];
617f5eb7cf0SAndreas Gohr            }
618f5eb7cf0SAndreas Gohr        }
61909c27a6dSGuy Brand    }
620f5eb7cf0SAndreas Gohr    return $result;
621f5eb7cf0SAndreas Gohr}
622f5eb7cf0SAndreas Gohr
623f5eb7cf0SAndreas Gohr/**
624865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores
625f5eb7cf0SAndreas Gohr *
626865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function
627865c2687SKazutaka Miyasaka *
628865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
62942ea7f44SGerrit Uitslag * @return array
63042ea7f44SGerrit Uitslag *
631865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
632865c2687SKazutaka Miyasaka */
633d868eb89SAndreas Gohrfunction ft_resultUnite($args)
634d868eb89SAndreas Gohr{
635865c2687SKazutaka Miyasaka    $array_count = count($args);
636865c2687SKazutaka Miyasaka    if ($array_count === 1) {
637865c2687SKazutaka Miyasaka        return $args[0];
638865c2687SKazutaka Miyasaka    }
639865c2687SKazutaka Miyasaka
640865c2687SKazutaka Miyasaka    $result = $args[0];
641865c2687SKazutaka Miyasaka    for ($i = 1; $i !== $array_count; $i++) {
642865c2687SKazutaka Miyasaka        foreach (array_keys($args[$i]) as $id) {
643865c2687SKazutaka Miyasaka            $result[$id] += $args[$i][$id];
644865c2687SKazutaka Miyasaka        }
645865c2687SKazutaka Miyasaka    }
646865c2687SKazutaka Miyasaka    return $result;
647865c2687SKazutaka Miyasaka}
648865c2687SKazutaka Miyasaka
649865c2687SKazutaka Miyasaka/**
650865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison
651865c2687SKazutaka Miyasaka *
652865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key()
653865c2687SKazutaka Miyasaka *
654865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
65542ea7f44SGerrit Uitslag * @return array
65642ea7f44SGerrit Uitslag *
657865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
658865c2687SKazutaka Miyasaka */
659d868eb89SAndreas Gohrfunction ft_resultComplement($args)
660d868eb89SAndreas Gohr{
661865c2687SKazutaka Miyasaka    $array_count = count($args);
662865c2687SKazutaka Miyasaka    if ($array_count === 1) {
663865c2687SKazutaka Miyasaka        return $args[0];
664865c2687SKazutaka Miyasaka    }
665865c2687SKazutaka Miyasaka
666865c2687SKazutaka Miyasaka    $result = $args[0];
667865c2687SKazutaka Miyasaka    foreach (array_keys($result) as $id) {
668865c2687SKazutaka Miyasaka        for ($i = 1; $i !== $array_count; $i++) {
669865c2687SKazutaka Miyasaka            if (isset($args[$i][$id])) unset($result[$id]);
670865c2687SKazutaka Miyasaka        }
671865c2687SKazutaka Miyasaka    }
672865c2687SKazutaka Miyasaka    return $result;
673865c2687SKazutaka Miyasaka}
674865c2687SKazutaka Miyasaka
675865c2687SKazutaka Miyasaka/**
676865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas
677865c2687SKazutaka Miyasaka *
678865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
679865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
68042ea7f44SGerrit Uitslag *
68124870174SAndreas Gohr * @param Indexer $Indexer
68242ea7f44SGerrit Uitslag * @param string                  $query search query
68342ea7f44SGerrit Uitslag * @return array of search formulas
684f5eb7cf0SAndreas Gohr */
685d868eb89SAndreas Gohrfunction ft_queryParser($Indexer, $query)
686d868eb89SAndreas Gohr{
687865c2687SKazutaka Miyasaka    /**
688865c2687SKazutaka Miyasaka     * parse a search query and transform it into intermediate representation
689865c2687SKazutaka Miyasaka     *
690865c2687SKazutaka Miyasaka     * in a search query, you can use the following expressions:
691865c2687SKazutaka Miyasaka     *
692865c2687SKazutaka Miyasaka     *   words:
693865c2687SKazutaka Miyasaka     *     include
694865c2687SKazutaka Miyasaka     *     -exclude
695865c2687SKazutaka Miyasaka     *   phrases:
696865c2687SKazutaka Miyasaka     *     "phrase to be included"
697865c2687SKazutaka Miyasaka     *     -"phrase you want to exclude"
698865c2687SKazutaka Miyasaka     *   namespaces:
699865c2687SKazutaka Miyasaka     *     @include:namespace (or ns:include:namespace)
700865c2687SKazutaka Miyasaka     *     ^exclude:namespace (or -ns:exclude:namespace)
701865c2687SKazutaka Miyasaka     *   groups:
702865c2687SKazutaka Miyasaka     *     ()
703865c2687SKazutaka Miyasaka     *     -()
704865c2687SKazutaka Miyasaka     *   operators:
705865c2687SKazutaka Miyasaka     *     and ('and' is the default operator: you can always omit this)
7067871d415SKazutaka Miyasaka     *     or  (or pipe symbol '|', lower precedence than 'and')
707865c2687SKazutaka Miyasaka     *
708865c2687SKazutaka Miyasaka     * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
709865c2687SKazutaka Miyasaka     *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
710865c2687SKazutaka Miyasaka     *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
711865c2687SKazutaka Miyasaka     *      as long as you don't mind hit counts.
712865c2687SKazutaka Miyasaka     *
713865c2687SKazutaka Miyasaka     * intermediate representation consists of the following parts:
714865c2687SKazutaka Miyasaka     *
715865c2687SKazutaka Miyasaka     *   ( )           - group
716865c2687SKazutaka Miyasaka     *   AND           - logical and
717865c2687SKazutaka Miyasaka     *   OR            - logical or
718865c2687SKazutaka Miyasaka     *   NOT           - logical not
7192f502d70SKazutaka Miyasaka     *   W+:, W-:, W_: - word      (underscore: no need to highlight)
7202f502d70SKazutaka Miyasaka     *   P+:, P-:      - phrase    (minus sign: logically in NOT group)
7212f502d70SKazutaka Miyasaka     *   N+:, N-:      - namespace
722865c2687SKazutaka Miyasaka     */
723865c2687SKazutaka Miyasaka    $parsed_query = '';
724865c2687SKazutaka Miyasaka    $parens_level = 0;
725*dccd6b2bSAndreas Gohr    $terms = preg_split(
726*dccd6b2bSAndreas Gohr        '/(-?".*?")/u',
727*dccd6b2bSAndreas Gohr        PhpString::strtolower($query),
728*dccd6b2bSAndreas Gohr        -1,
729*dccd6b2bSAndreas Gohr        PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
730*dccd6b2bSAndreas Gohr    );
731865c2687SKazutaka Miyasaka
732865c2687SKazutaka Miyasaka    foreach ($terms as $term) {
733865c2687SKazutaka Miyasaka        $parsed = '';
734865c2687SKazutaka Miyasaka        if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
735865c2687SKazutaka Miyasaka            // phrase-include and phrase-exclude
736865c2687SKazutaka Miyasaka            $not = $matches[1] ? 'NOT' : '';
7379b41be24STom N Harris            $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
738f5eb7cf0SAndreas Gohr        } else {
739865c2687SKazutaka Miyasaka            // fix incomplete phrase
740865c2687SKazutaka Miyasaka            $term = str_replace('"', ' ', $term);
741865c2687SKazutaka Miyasaka
742865c2687SKazutaka Miyasaka            // fix parentheses
743865c2687SKazutaka Miyasaka            $term = str_replace(')', ' ) ', $term);
744865c2687SKazutaka Miyasaka            $term = str_replace('(', ' ( ', $term);
745865c2687SKazutaka Miyasaka            $term = str_replace('- (', ' -(', $term);
746865c2687SKazutaka Miyasaka
7477871d415SKazutaka Miyasaka            // treat pipe symbols as 'OR' operators
7487871d415SKazutaka Miyasaka            $term = str_replace('|', ' or ', $term);
7497871d415SKazutaka Miyasaka
750865c2687SKazutaka Miyasaka            // treat ideographic spaces (U+3000) as search term separators
751865c2687SKazutaka Miyasaka            // FIXME: some more separators?
752865c2687SKazutaka Miyasaka            $term = preg_replace('/[ \x{3000}]+/u', ' ', $term);
753865c2687SKazutaka Miyasaka            $term = trim($term);
754865c2687SKazutaka Miyasaka            if ($term === '') continue;
755865c2687SKazutaka Miyasaka
756865c2687SKazutaka Miyasaka            $tokens = explode(' ', $term);
757865c2687SKazutaka Miyasaka            foreach ($tokens as $token) {
758865c2687SKazutaka Miyasaka                if ($token === '(') {
759865c2687SKazutaka Miyasaka                    // parenthesis-include-open
760865c2687SKazutaka Miyasaka                    $parsed .= '(';
761865c2687SKazutaka Miyasaka                    ++$parens_level;
762865c2687SKazutaka Miyasaka                } elseif ($token === '-(') {
763865c2687SKazutaka Miyasaka                    // parenthesis-exclude-open
764865c2687SKazutaka Miyasaka                    $parsed .= 'NOT(';
765865c2687SKazutaka Miyasaka                    ++$parens_level;
766865c2687SKazutaka Miyasaka                } elseif ($token === ')') {
767865c2687SKazutaka Miyasaka                    // parenthesis-any-close
768865c2687SKazutaka Miyasaka                    if ($parens_level === 0) continue;
769865c2687SKazutaka Miyasaka                    $parsed .= ')';
770865c2687SKazutaka Miyasaka                    $parens_level--;
771865c2687SKazutaka Miyasaka                } elseif ($token === 'and') {
772865c2687SKazutaka Miyasaka                    // logical-and (do nothing)
773865c2687SKazutaka Miyasaka                } elseif ($token === 'or') {
774865c2687SKazutaka Miyasaka                    // logical-or
775865c2687SKazutaka Miyasaka                    $parsed .= 'OR';
776865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
777865c2687SKazutaka Miyasaka                    // namespace-exclude
7782f502d70SKazutaka Miyasaka                    $parsed .= 'NOT(N+:'.$matches[1].')';
779865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
780865c2687SKazutaka Miyasaka                    // namespace-include
7812f502d70SKazutaka Miyasaka                    $parsed .= '(N+:'.$matches[1].')';
782865c2687SKazutaka Miyasaka                } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
783865c2687SKazutaka Miyasaka                    // word-exclude
7849b41be24STom N Harris                    $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
785865c2687SKazutaka Miyasaka                } else {
786865c2687SKazutaka Miyasaka                    // word-include
7879b41be24STom N Harris                    $parsed .= ft_termParser($Indexer, $token);
788865c2687SKazutaka Miyasaka                }
789865c2687SKazutaka Miyasaka            }
790865c2687SKazutaka Miyasaka        }
791865c2687SKazutaka Miyasaka        $parsed_query .= $parsed;
792f5eb7cf0SAndreas Gohr    }
793f5eb7cf0SAndreas Gohr
794865c2687SKazutaka Miyasaka    // cleanup (very sensitive)
795865c2687SKazutaka Miyasaka    $parsed_query .= str_repeat(')', $parens_level);
796865c2687SKazutaka Miyasaka    do {
797865c2687SKazutaka Miyasaka        $parsed_query_old = $parsed_query;
798865c2687SKazutaka Miyasaka        $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
799865c2687SKazutaka Miyasaka    } while ($parsed_query !== $parsed_query_old);
800865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')', $parsed_query);
801865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(OR)+/u', 'OR', $parsed_query);
802865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\(OR/u', '(', $parsed_query);
803865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/^OR|OR$/u', '', $parsed_query);
804865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\)(NOT)?\(/u', ')AND$1(', $parsed_query);
805865c2687SKazutaka Miyasaka
8062f502d70SKazutaka Miyasaka    // adjustment: make highlightings right
8072f502d70SKazutaka Miyasaka    $parens_level     = 0;
80824870174SAndreas Gohr    $notgrp_levels    = [];
8092f502d70SKazutaka Miyasaka    $parsed_query_new = '';
8102f502d70SKazutaka Miyasaka    $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
8112f502d70SKazutaka Miyasaka    foreach ($tokens as $token) {
8122f502d70SKazutaka Miyasaka        if ($token === 'NOT(') {
8132f502d70SKazutaka Miyasaka            $notgrp_levels[] = ++$parens_level;
8142f502d70SKazutaka Miyasaka        } elseif ($token === '(') {
8152f502d70SKazutaka Miyasaka            ++$parens_level;
8162f502d70SKazutaka Miyasaka        } elseif ($token === ')') {
8172f502d70SKazutaka Miyasaka            if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
8182f502d70SKazutaka Miyasaka        } elseif (count($notgrp_levels) % 2 === 1) {
8192f502d70SKazutaka Miyasaka            // turn highlight-flag off if terms are logically in "NOT" group
8202f502d70SKazutaka Miyasaka            $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
8212f502d70SKazutaka Miyasaka        }
8222f502d70SKazutaka Miyasaka        $parsed_query_new .= $token;
8232f502d70SKazutaka Miyasaka    }
8242f502d70SKazutaka Miyasaka    $parsed_query = $parsed_query_new;
8252f502d70SKazutaka Miyasaka
826865c2687SKazutaka Miyasaka    /**
827865c2687SKazutaka Miyasaka     * convert infix notation string into postfix (Reverse Polish notation) array
828865c2687SKazutaka Miyasaka     * by Shunting-yard algorithm
829865c2687SKazutaka Miyasaka     *
830865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
831865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
832865c2687SKazutaka Miyasaka     */
83324870174SAndreas Gohr    $parsed_ary     = [];
83424870174SAndreas Gohr    $ope_stack      = [];
83524870174SAndreas Gohr    $ope_precedence = [')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5];
836865c2687SKazutaka Miyasaka    $ope_regex      = '/([()]|OR|AND|NOT)/u';
837865c2687SKazutaka Miyasaka
838865c2687SKazutaka Miyasaka    $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
839865c2687SKazutaka Miyasaka    foreach ($tokens as $token) {
840865c2687SKazutaka Miyasaka        if (preg_match($ope_regex, $token)) {
841865c2687SKazutaka Miyasaka            // operator
842865c2687SKazutaka Miyasaka            $last_ope = end($ope_stack);
84367d812e0SMarius van Witzenburg            while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
844865c2687SKazutaka Miyasaka                $parsed_ary[] = array_pop($ope_stack);
845865c2687SKazutaka Miyasaka                $last_ope = end($ope_stack);
846865c2687SKazutaka Miyasaka            }
847865c2687SKazutaka Miyasaka            if ($token == ')') {
848865c2687SKazutaka Miyasaka                array_pop($ope_stack); // this array_pop always deletes '('
849865c2687SKazutaka Miyasaka            } else {
850865c2687SKazutaka Miyasaka                $ope_stack[] = $token;
851865c2687SKazutaka Miyasaka            }
852865c2687SKazutaka Miyasaka        } else {
853865c2687SKazutaka Miyasaka            // operand
85424870174SAndreas Gohr            $token_decoded = str_replace(['OP', 'CP'], ['(', ')'], $token);
855865c2687SKazutaka Miyasaka            $parsed_ary[] = $token_decoded;
856865c2687SKazutaka Miyasaka        }
857865c2687SKazutaka Miyasaka    }
85824870174SAndreas Gohr    $parsed_ary = array_values([...$parsed_ary, ...array_reverse($ope_stack)]);
859865c2687SKazutaka Miyasaka
860865c2687SKazutaka Miyasaka    // cleanup: each double "NOT" in RPN array actually does nothing
861865c2687SKazutaka Miyasaka    $parsed_ary_count = count($parsed_ary);
862865c2687SKazutaka Miyasaka    for ($i = 1; $i < $parsed_ary_count; ++$i) {
863865c2687SKazutaka Miyasaka        if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
864865c2687SKazutaka Miyasaka            unset($parsed_ary[$i], $parsed_ary[$i - 1]);
865865c2687SKazutaka Miyasaka        }
866865c2687SKazutaka Miyasaka    }
867865c2687SKazutaka Miyasaka    $parsed_ary = array_values($parsed_ary);
868865c2687SKazutaka Miyasaka
869865c2687SKazutaka Miyasaka    // build return value
87024870174SAndreas Gohr    $q = [];
871f5eb7cf0SAndreas Gohr    $q['query']      = $query;
872865c2687SKazutaka Miyasaka    $q['parsed_str'] = $parsed_query;
873865c2687SKazutaka Miyasaka    $q['parsed_ary'] = $parsed_ary;
874f5eb7cf0SAndreas Gohr
875865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
87640f2b82eSAndreas Gohr        if (strlen($token) < 3 || $token[2] !== ':') continue;
877865c2687SKazutaka Miyasaka        $body = substr($token, 3);
878865c2687SKazutaka Miyasaka
879865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
8802f502d70SKazutaka Miyasaka            case 'N+:':
881865c2687SKazutaka Miyasaka                     $q['ns'][]        = $body; // for backward compatibility
882865c2687SKazutaka Miyasaka                     break;
8832f502d70SKazutaka Miyasaka            case 'N-:':
8842f502d70SKazutaka Miyasaka                     $q['notns'][]     = $body; // for backward compatibility
8852f502d70SKazutaka Miyasaka                     break;
8862f502d70SKazutaka Miyasaka            case 'W_:':
8872f502d70SKazutaka Miyasaka                     $q['words'][]     = $body;
8882f502d70SKazutaka Miyasaka                     break;
889865c2687SKazutaka Miyasaka            case 'W-:':
890865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
8912f502d70SKazutaka Miyasaka                     $q['not'][]       = $body; // for backward compatibility
892865c2687SKazutaka Miyasaka                     break;
893865c2687SKazutaka Miyasaka            case 'W+:':
894865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
8952237b4faSAndreas Gohr                     $q['highlight'][] = $body;
8962f502d70SKazutaka Miyasaka                     $q['and'][]       = $body; // for backward compatibility
897865c2687SKazutaka Miyasaka                     break;
8982f502d70SKazutaka Miyasaka            case 'P-:':
8992f502d70SKazutaka Miyasaka                     $q['phrases'][]   = $body;
9002f502d70SKazutaka Miyasaka                     break;
9012f502d70SKazutaka Miyasaka            case 'P+:':
902865c2687SKazutaka Miyasaka                     $q['phrases'][]   = $body;
9032237b4faSAndreas Gohr                     $q['highlight'][] = $body;
904865c2687SKazutaka Miyasaka                     break;
905865c2687SKazutaka Miyasaka        }
906865c2687SKazutaka Miyasaka    }
90724870174SAndreas Gohr    foreach (['words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not'] as $key) {
90824870174SAndreas Gohr        $q[$key] = empty($q[$key]) ? [] : array_values(array_unique($q[$key]));
909f5eb7cf0SAndreas Gohr    }
910f5eb7cf0SAndreas Gohr
911f5eb7cf0SAndreas Gohr    return $q;
912f5eb7cf0SAndreas Gohr}
913f5eb7cf0SAndreas Gohr
914865c2687SKazutaka Miyasaka/**
915865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation
916865c2687SKazutaka Miyasaka *
917865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use.
918865c2687SKazutaka Miyasaka *
919865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
92042ea7f44SGerrit Uitslag *
92124870174SAndreas Gohr * @param Indexer $Indexer
92242ea7f44SGerrit Uitslag * @param string                  $term
92342ea7f44SGerrit Uitslag * @param bool                    $consider_asian
92442ea7f44SGerrit Uitslag * @param bool                    $phrase_mode
92542ea7f44SGerrit Uitslag * @return string
926865c2687SKazutaka Miyasaka */
927d868eb89SAndreas Gohrfunction ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false)
928d868eb89SAndreas Gohr{
929865c2687SKazutaka Miyasaka    $parsed = '';
930865c2687SKazutaka Miyasaka    if ($consider_asian) {
931865c2687SKazutaka Miyasaka        // successive asian characters need to be searched as a phrase
93224870174SAndreas Gohr        $words = Asian::splitAsianWords($term);
933865c2687SKazutaka Miyasaka        foreach ($words as $word) {
93424870174SAndreas Gohr            $phrase_mode = $phrase_mode ? true : Asian::isAsianWords($word);
9359b41be24STom N Harris            $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
936865c2687SKazutaka Miyasaka        }
937865c2687SKazutaka Miyasaka    } else {
93824870174SAndreas Gohr        $term_noparen = str_replace(['(', ')'], ' ', $term);
9399b41be24STom N Harris        $words = $Indexer->tokenizer($term_noparen, true);
940865c2687SKazutaka Miyasaka
9412f502d70SKazutaka Miyasaka        // W_: no need to highlight
942865c2687SKazutaka Miyasaka        if (empty($words)) {
943865c2687SKazutaka Miyasaka            $parsed = '()'; // important: do not remove
944865c2687SKazutaka Miyasaka        } elseif ($words[0] === $term) {
945865c2687SKazutaka Miyasaka            $parsed = '(W+:'.$words[0].')';
946865c2687SKazutaka Miyasaka        } elseif ($phrase_mode) {
94724870174SAndreas Gohr            $term_encoded = str_replace(['(', ')'], ['OP', 'CP'], $term);
9482f502d70SKazutaka Miyasaka            $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
949865c2687SKazutaka Miyasaka        } else {
950865c2687SKazutaka Miyasaka            $parsed = '((W+:'.implode(')(W+:', $words).'))';
951865c2687SKazutaka Miyasaka        }
952865c2687SKazutaka Miyasaka    }
953865c2687SKazutaka Miyasaka    return $parsed;
954865c2687SKazutaka Miyasaka}
955865c2687SKazutaka Miyasaka
95644156e11SMichael Große/**
95744156e11SMichael Große * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
95844156e11SMichael Große *
95944156e11SMichael Große * @param array $and
96044156e11SMichael Große * @param array $not
96144156e11SMichael Große * @param array $phrases
96244156e11SMichael Große * @param array $ns
96344156e11SMichael Große * @param array $notns
96444156e11SMichael Große *
96544156e11SMichael Große * @return string
96644156e11SMichael Große */
967d868eb89SAndreas Gohrfunction ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns)
968d868eb89SAndreas Gohr{
96944156e11SMichael Große    $query = implode(' ', $and);
97024870174SAndreas Gohr    if ($not !== []) {
97144156e11SMichael Große        $query .= ' -' . implode(' -', $not);
97244156e11SMichael Große    }
97344156e11SMichael Große
97424870174SAndreas Gohr    if ($phrases !== []) {
97544156e11SMichael Große        $query .= ' "' . implode('" "', $phrases) . '"';
97644156e11SMichael Große    }
97744156e11SMichael Große
97824870174SAndreas Gohr    if ($ns !== []) {
97944156e11SMichael Große        $query .= ' @' . implode(' @', $ns);
98044156e11SMichael Große    }
98144156e11SMichael Große
98224870174SAndreas Gohr    if ($notns !== []) {
98344156e11SMichael Große        $query .= ' ^' . implode(' ^', $notns);
98444156e11SMichael Große    }
98544156e11SMichael Große
98644156e11SMichael Große    return $query;
98744156e11SMichael Große}
98844156e11SMichael Große
989e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 :
990