xref: /dokuwiki/inc/fulltext.php (revision 248d652bb4d2187f7ac3bfe82a4a5951e1975db0)
1f5eb7cf0SAndreas Gohr<?php
2f5eb7cf0SAndreas Gohr/**
3f5eb7cf0SAndreas Gohr * DokuWiki fulltextsearch functions using the index
4f5eb7cf0SAndreas Gohr *
5f5eb7cf0SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6f5eb7cf0SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
727f63a23SAndreas Gohr */
827f63a23SAndreas Gohr
927f63a23SAndreas Gohruse dokuwiki\Extension\Event;
102d85e841SAndreas Gohruse dokuwiki\Utf8\Sort;
11f5eb7cf0SAndreas Gohr
12bd0293e7SAndreas Gohr/**
13bd0293e7SAndreas Gohr * create snippets for the first few results only
14bd0293e7SAndreas Gohr */
15bd0293e7SAndreas Gohrif(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15);
16f5eb7cf0SAndreas Gohr
17f5eb7cf0SAndreas Gohr/**
18f5eb7cf0SAndreas Gohr * The fulltext search
19f5eb7cf0SAndreas Gohr *
20f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query
21506fa893SAndreas Gohr *
226840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
236840140fSChris Smith *
2442ea7f44SGerrit Uitslag * @param string     $query
2542ea7f44SGerrit Uitslag * @param array      $highlight
263850270cSMichael Große * @param string     $sort
2764159a61SAndreas Gohr * @param int|string $after  only show results with mtime after this date, accepts timestap or strtotime arguments
2864159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments
293850270cSMichael Große *
3042ea7f44SGerrit Uitslag * @return array
31f5eb7cf0SAndreas Gohr */
323850270cSMichael Großefunction ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){
336840140fSChris Smith
343850270cSMichael Große    if ($sort === null) {
353850270cSMichael Große        $sort = 'hits';
363850270cSMichael Große    }
373850270cSMichael Große    $data = [
383850270cSMichael Große        'query' => $query,
393850270cSMichael Große        'sort' => $sort,
403850270cSMichael Große        'after' => $after,
413850270cSMichael Große        'before' => $before
423850270cSMichael Große    ];
436840140fSChris Smith    $data['highlight'] =& $highlight;
446840140fSChris Smith
45cbb44eabSAndreas Gohr    return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
466840140fSChris Smith}
47865c2687SKazutaka Miyasaka
48865c2687SKazutaka Miyasaka/**
49865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query
50865c2687SKazutaka Miyasaka *
51865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
52865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
5342ea7f44SGerrit Uitslag *
5442ea7f44SGerrit Uitslag * @param array $data event data
5542ea7f44SGerrit Uitslag * @return array matching documents
56865c2687SKazutaka Miyasaka */
576840140fSChris Smithfunction _ft_pageSearch(&$data) {
589b41be24STom N Harris    $Indexer = idx_get_indexer();
599b41be24STom N Harris
60865c2687SKazutaka Miyasaka    // parse the given query
619b41be24STom N Harris    $q = ft_queryParser($Indexer, $data['query']);
62865c2687SKazutaka Miyasaka    $data['highlight'] = $q['highlight'];
636840140fSChris Smith
64865c2687SKazutaka Miyasaka    if (empty($q['parsed_ary'])) return array();
65506fa893SAndreas Gohr
66f5eb7cf0SAndreas Gohr    // lookup all words found in the query
679b41be24STom N Harris    $lookup = $Indexer->lookup($q['words']);
68f5eb7cf0SAndreas Gohr
69865c2687SKazutaka Miyasaka    // get all pages in this dokuwiki site (!: includes nonexistent pages)
70865c2687SKazutaka Miyasaka    $pages_all = array();
719b41be24STom N Harris    foreach ($Indexer->getPages() as $id) {
729b41be24STom N Harris        $pages_all[$id] = 0; // base: 0 hit
73f5eb7cf0SAndreas Gohr    }
74f5eb7cf0SAndreas Gohr
75865c2687SKazutaka Miyasaka    // process the query
76865c2687SKazutaka Miyasaka    $stack = array();
77865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
78865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
79865c2687SKazutaka Miyasaka            case 'W+:':
802f502d70SKazutaka Miyasaka            case 'W-:':
812f502d70SKazutaka Miyasaka            case 'W_:': // word
82865c2687SKazutaka Miyasaka                $word    = substr($token, 3);
835afd9580SAndreas Gohr                if(isset($lookup[$word])) {
84865c2687SKazutaka Miyasaka                    $stack[] = (array)$lookup[$word];
855afd9580SAndreas Gohr                }
86865c2687SKazutaka Miyasaka                break;
872f502d70SKazutaka Miyasaka            case 'P+:':
882f502d70SKazutaka Miyasaka            case 'P-:': // phrase
89865c2687SKazutaka Miyasaka                $phrase = substr($token, 3);
90865c2687SKazutaka Miyasaka                // since phrases are always parsed as ((W1)(W2)...(P)),
91865c2687SKazutaka Miyasaka                // the end($stack) always points the pages that contain
92865c2687SKazutaka Miyasaka                // all words in this phrase
93865c2687SKazutaka Miyasaka                $pages  = end($stack);
94865c2687SKazutaka Miyasaka                $pages_matched = array();
95865c2687SKazutaka Miyasaka                foreach(array_keys($pages) as $id){
96a7e8b43eSMichael Hamann                    $evdata = array(
97a7e8b43eSMichael Hamann                        'id' => $id,
98a7e8b43eSMichael Hamann                        'phrase' => $phrase,
99a7e8b43eSMichael Hamann                        'text' => rawWiki($id)
100a7e8b43eSMichael Hamann                    );
101e1d9dcc8SAndreas Gohr                    $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata);
102a7e8b43eSMichael Hamann                    if ($evt->advise_before() && $evt->result !== true) {
1038cbc5ee8SAndreas Gohr                        $text = \dokuwiki\Utf8\PhpString::strtolower($evdata['text']);
104865c2687SKazutaka Miyasaka                        if (strpos($text, $phrase) !== false) {
105a7e8b43eSMichael Hamann                            $evt->result = true;
106a7e8b43eSMichael Hamann                        }
107a7e8b43eSMichael Hamann                    }
108a7e8b43eSMichael Hamann                    $evt->advise_after();
109a7e8b43eSMichael Hamann                    if ($evt->result === true) {
110865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // phrase: always 0 hit
111865c2687SKazutaka Miyasaka                    }
112865c2687SKazutaka Miyasaka                }
113865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
114865c2687SKazutaka Miyasaka                break;
1152f502d70SKazutaka Miyasaka            case 'N+:':
1162f502d70SKazutaka Miyasaka            case 'N-:': // namespace
117de3383c6SMichael Große                $ns = cleanID(substr($token, 3)) . ':';
118865c2687SKazutaka Miyasaka                $pages_matched = array();
119865c2687SKazutaka Miyasaka                foreach (array_keys($pages_all) as $id) {
120865c2687SKazutaka Miyasaka                    if (strpos($id, $ns) === 0) {
121865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // namespace: always 0 hit
122865c2687SKazutaka Miyasaka                    }
123865c2687SKazutaka Miyasaka                }
124865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
125865c2687SKazutaka Miyasaka                break;
126865c2687SKazutaka Miyasaka            case 'AND': // and operation
127865c2687SKazutaka Miyasaka                list($pages1, $pages2) = array_splice($stack, -2);
128865c2687SKazutaka Miyasaka                $stack[] = ft_resultCombine(array($pages1, $pages2));
129865c2687SKazutaka Miyasaka                break;
130865c2687SKazutaka Miyasaka            case 'OR':  // or operation
131865c2687SKazutaka Miyasaka                list($pages1, $pages2) = array_splice($stack, -2);
132865c2687SKazutaka Miyasaka                $stack[] = ft_resultUnite(array($pages1, $pages2));
133865c2687SKazutaka Miyasaka                break;
134865c2687SKazutaka Miyasaka            case 'NOT': // not operation (unary)
135865c2687SKazutaka Miyasaka                $pages   = array_pop($stack);
136865c2687SKazutaka Miyasaka                $stack[] = ft_resultComplement(array($pages_all, $pages));
137a21136cdSAndreas Gohr                break;
138a21136cdSAndreas Gohr        }
139f5eb7cf0SAndreas Gohr    }
140865c2687SKazutaka Miyasaka    $docs = array_pop($stack);
141865c2687SKazutaka Miyasaka
142865c2687SKazutaka Miyasaka    if (empty($docs)) return array();
143865c2687SKazutaka Miyasaka
144865c2687SKazutaka Miyasaka    // check: settings, acls, existence
145865c2687SKazutaka Miyasaka    foreach (array_keys($docs) as $id) {
146865c2687SKazutaka Miyasaka        if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
147865c2687SKazutaka Miyasaka            unset($docs[$id]);
148f5eb7cf0SAndreas Gohr        }
149f5eb7cf0SAndreas Gohr    }
150f5eb7cf0SAndreas Gohr
1513850270cSMichael Große    $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']);
1528d0e286aSMichael Große
1538d0e286aSMichael Große    if ($data['sort'] === 'mtime') {
1548d0e286aSMichael Große        uksort($docs, 'ft_pagemtimesorter');
1558d0e286aSMichael Große    } else {
156865c2687SKazutaka Miyasaka        // sort docs by count
15706281c9cSMoisés Braga Ribeiro        uksort($docs, 'ft_pagesorter');
158f5eb7cf0SAndreas Gohr        arsort($docs);
1598d0e286aSMichael Große    }
160f5eb7cf0SAndreas Gohr
161f5eb7cf0SAndreas Gohr    return $docs;
162f5eb7cf0SAndreas Gohr}
163f5eb7cf0SAndreas Gohr
164f5eb7cf0SAndreas Gohr/**
16554f4c056SAndreas Gohr * Returns the backlinks for a given page
16654f4c056SAndreas Gohr *
167320f489aSMichael Hamann * Uses the metadata index.
16807ff0babSMichael Hamann *
16907ff0babSMichael Hamann * @param string $id           The id for which links shall be returned
17007ff0babSMichael Hamann * @param bool   $ignore_perms Ignore the fact that pages are hidden or read-protected
17107ff0babSMichael Hamann * @return array The pages that contain links to the given page
17254f4c056SAndreas Gohr */
17307ff0babSMichael Hamannfunction ft_backlinks($id, $ignore_perms = false){
174320f489aSMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_references', $id);
17554f4c056SAndreas Gohr
17663773904SAndreas Gohr    if(!count($result)) return $result;
17763773904SAndreas Gohr
17863773904SAndreas Gohr    // check ACL permissions
17963773904SAndreas Gohr    foreach(array_keys($result) as $idx){
18007ff0babSMichael Hamann        if(($ignore_perms !== true && (
18107ff0babSMichael Hamann                isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
18207ff0babSMichael Hamann            )) || !page_exists($result[$idx], '', false)){
18363773904SAndreas Gohr            unset($result[$idx]);
18463773904SAndreas Gohr        }
18563773904SAndreas Gohr    }
18663773904SAndreas Gohr
1872d85e841SAndreas Gohr    Sort::sort($result);
18854f4c056SAndreas Gohr    return $result;
18954f4c056SAndreas Gohr}
19054f4c056SAndreas Gohr
19154f4c056SAndreas Gohr/**
192a05e297aSAndreas Gohr * Returns the pages that use a given media file
193a05e297aSAndreas Gohr *
194ffec1009SMichael Hamann * Uses the relation media metadata property and the metadata index.
195a05e297aSAndreas Gohr *
196ffec1009SMichael Hamann * Note that before 2013-07-31 the second parameter was the maximum number of results and
197ffec1009SMichael Hamann * permissions were ignored. That's why the parameter is now checked to be explicitely set
198ffec1009SMichael Hamann * to true (with type bool) in order to be compatible with older uses of the function.
199ffec1009SMichael Hamann *
200ffec1009SMichael Hamann * @param string $id           The media id to look for
201ffec1009SMichael Hamann * @param bool   $ignore_perms Ignore hidden pages and acls (optional, default: false)
202ffec1009SMichael Hamann * @return array A list of pages that use the given media file
203a05e297aSAndreas Gohr */
204ffec1009SMichael Hamannfunction ft_mediause($id, $ignore_perms = false){
205ffec1009SMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_media', $id);
206a05e297aSAndreas Gohr
207ffec1009SMichael Hamann    if(!count($result)) return $result;
208a05e297aSAndreas Gohr
209ffec1009SMichael Hamann    // check ACL permissions
210ffec1009SMichael Hamann    foreach(array_keys($result) as $idx){
211ffec1009SMichael Hamann        if(($ignore_perms !== true && (
212ffec1009SMichael Hamann                    isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
213ffec1009SMichael Hamann                )) || !page_exists($result[$idx], '', false)){
214ffec1009SMichael Hamann            unset($result[$idx]);
215a05e297aSAndreas Gohr        }
216a05e297aSAndreas Gohr    }
217a05e297aSAndreas Gohr
2182d85e841SAndreas Gohr    Sort::sort($result);
219a05e297aSAndreas Gohr    return $result;
220a05e297aSAndreas Gohr}
221a05e297aSAndreas Gohr
222a05e297aSAndreas Gohr
223a05e297aSAndreas Gohr/**
224506fa893SAndreas Gohr * Quicksearch for pagenames
225506fa893SAndreas Gohr *
226506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
22780423ab6SAdrian Lang * namespace. This can be changed with the second parameter.
22880423ab6SAdrian Lang * The third parameter allows to search in titles as well.
229506fa893SAndreas Gohr *
2308d22f1e9SAndreas Gohr * The function always returns titles as well
2316840140fSChris Smith *
2328d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP
233506fa893SAndreas Gohr * @author   Andreas Gohr <andi@splitbrain.org>
2348d22f1e9SAndreas Gohr * @author   Adrian Lang <lang@cosmocode.de>
23542ea7f44SGerrit Uitslag *
23642ea7f44SGerrit Uitslag * @param string     $id       page id
23742ea7f44SGerrit Uitslag * @param bool       $in_ns    match against namespace as well?
23842ea7f44SGerrit Uitslag * @param bool       $in_title search in title?
23964159a61SAndreas Gohr * @param int|string $after    only show results with mtime after this date, accepts timestap or strtotime arguments
24064159a61SAndreas Gohr * @param int|string $before   only show results with mtime before this date, accepts timestap or strtotime arguments
2413850270cSMichael Große *
24242ea7f44SGerrit Uitslag * @return string[]
243506fa893SAndreas Gohr */
2443850270cSMichael Großefunction ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){
2453850270cSMichael Große    $data = [
2463850270cSMichael Große        'id' => $id,
2473850270cSMichael Große        'in_ns' => $in_ns,
2483850270cSMichael Große        'in_title' => $in_title,
2493850270cSMichael Große        'after' => $after,
2503850270cSMichael Große        'before' => $before
2513850270cSMichael Große    ];
2528d22f1e9SAndreas Gohr    $data['has_titles'] = true; // for plugin backward compatibility check
253cbb44eabSAndreas Gohr    return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup');
2546840140fSChris Smith}
2556840140fSChris Smith
25642ea7f44SGerrit Uitslag/**
25742ea7f44SGerrit Uitslag * Returns list of pages as array(pageid => First Heading)
25842ea7f44SGerrit Uitslag *
25942ea7f44SGerrit Uitslag * @param array &$data event data
26042ea7f44SGerrit Uitslag * @return string[]
26142ea7f44SGerrit Uitslag */
2626840140fSChris Smithfunction _ft_pageLookup(&$data){
26380423ab6SAdrian Lang    // split out original parameters
2646840140fSChris Smith    $id = $data['id'];
265940f24fcSMichael Große    $Indexer = idx_get_indexer();
266940f24fcSMichael Große    $parsedQuery = ft_queryParser($Indexer, $id);
267940f24fcSMichael Große    if (count($parsedQuery['ns']) > 0) {
268940f24fcSMichael Große        $ns = cleanID($parsedQuery['ns'][0]) . ':';
269940f24fcSMichael Große        $id = implode(' ', $parsedQuery['highlight']);
270b0f6db0cSAdrian Lang    }
271*248d652bSGerrit Uitslag    if (count($parsedQuery['notns']) > 0) {
272*248d652bSGerrit Uitslag        $notns = cleanID($parsedQuery['notns'][0]) . ':';
273*248d652bSGerrit Uitslag        $id = implode(' ', $parsedQuery['highlight']);
274*248d652bSGerrit Uitslag    }
275b0f6db0cSAdrian Lang
2768d22f1e9SAndreas Gohr    $in_ns    = $data['in_ns'];
2778d22f1e9SAndreas Gohr    $in_title = $data['in_title'];
27880423ab6SAdrian Lang    $cleaned = cleanID($id);
2799b41be24STom N Harris
2809b41be24STom N Harris    $Indexer = idx_get_indexer();
2819b41be24STom N Harris    $page_idx = $Indexer->getPages();
2829b41be24STom N Harris
2839b41be24STom N Harris    $pages = array();
2845479a8c3SAndreas Gohr    if ($id !== '' && $cleaned !== '') {
2859b41be24STom N Harris        foreach ($page_idx as $p_id) {
2869b41be24STom N Harris            if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) {
2879b41be24STom N Harris                if (!isset($pages[$p_id]))
28867c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
289506fa893SAndreas Gohr            }
290506fa893SAndreas Gohr        }
291f078bb00STom N Harris        if ($in_title) {
292c66f16a3SMichael Hamann            foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) {
293f078bb00STom N Harris                if (!isset($pages[$p_id]))
29467c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
295f078bb00STom N Harris            }
296f078bb00STom N Harris        }
297d0bdf765SAdrian Lang    }
2980c074a52SMichael Hamann
299d0bdf765SAdrian Lang    if (isset($ns)) {
3000c074a52SMichael Hamann        foreach (array_keys($pages) as $p_id) {
3010c074a52SMichael Hamann            if (strpos($p_id, $ns) !== 0) {
3020c074a52SMichael Hamann                unset($pages[$p_id]);
303d0bdf765SAdrian Lang            }
304d0bdf765SAdrian Lang        }
305506fa893SAndreas Gohr    }
306*248d652bSGerrit Uitslag    if (isset($notns)) {
307*248d652bSGerrit Uitslag        foreach (array_keys($pages) as $p_id) {
308*248d652bSGerrit Uitslag            if (strpos($p_id, $notns) === 0) {
309*248d652bSGerrit Uitslag                unset($pages[$p_id]);
310*248d652bSGerrit Uitslag            }
311*248d652bSGerrit Uitslag        }
312*248d652bSGerrit Uitslag    }
31363773904SAndreas Gohr
31480423ab6SAdrian Lang    // discard hidden pages
31580423ab6SAdrian Lang    // discard nonexistent pages
31663773904SAndreas Gohr    // check ACL permissions
31763773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
31880423ab6SAdrian Lang        if(!isVisiblePage($idx) || !page_exists($idx) ||
31980423ab6SAdrian Lang           auth_quickaclcheck($idx) < AUTH_READ) {
32063773904SAndreas Gohr            unset($pages[$idx]);
32163773904SAndreas Gohr        }
32263773904SAndreas Gohr    }
32363773904SAndreas Gohr
3243850270cSMichael Große    $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']);
3251b48999cSMichael Große
3263d2017d9SAdrian Lang    uksort($pages,'ft_pagesorter');
3278d22f1e9SAndreas Gohr    return $pages;
328506fa893SAndreas Gohr}
329506fa893SAndreas Gohr
3301b48999cSMichael Große
3311b48999cSMichael Große/**
3321b48999cSMichael Große * @param array      $results search results in the form pageid => value
33364159a61SAndreas Gohr * @param int|string $after   only returns results with mtime after this date, accepts timestap or strtotime arguments
33464159a61SAndreas Gohr * @param int|string $before  only returns results with mtime after this date, accepts timestap or strtotime arguments
3351b48999cSMichael Große *
3361b48999cSMichael Große * @return array
3371b48999cSMichael Große */
3383850270cSMichael Großefunction _ft_filterResultsByTime(array $results, $after, $before) {
3393850270cSMichael Große    if ($after || $before) {
3401b48999cSMichael Große        $after = is_int($after) ? $after : strtotime($after);
3411b48999cSMichael Große        $before = is_int($before) ? $before : strtotime($before);
3421b48999cSMichael Große
3431b48999cSMichael Große        foreach ($results as $id => $value) {
3441b48999cSMichael Große            $mTime = filemtime(wikiFN($id));
3451b48999cSMichael Große            if ($after && $after > $mTime) {
3461b48999cSMichael Große                unset($results[$id]);
3471b48999cSMichael Große                continue;
3481b48999cSMichael Große            }
3491b48999cSMichael Große            if ($before && $before < $mTime) {
3501b48999cSMichael Große                unset($results[$id]);
3511b48999cSMichael Große            }
3521b48999cSMichael Große        }
3531b48999cSMichael Große    }
3541b48999cSMichael Große
3551b48999cSMichael Große    return $results;
3561b48999cSMichael Große}
3571b48999cSMichael Große
358506fa893SAndreas Gohr/**
359c66f16a3SMichael Hamann * Tiny helper function for comparing the searched title with the title
360c66f16a3SMichael Hamann * from the search index. This function is a wrapper around stripos with
361c66f16a3SMichael Hamann * adapted argument order and return value.
36242ea7f44SGerrit Uitslag *
36342ea7f44SGerrit Uitslag * @param string $search searched title
36442ea7f44SGerrit Uitslag * @param string $title  title from index
36542ea7f44SGerrit Uitslag * @return bool
366c66f16a3SMichael Hamann */
367c66f16a3SMichael Hamannfunction _ft_pageLookupTitleCompare($search, $title) {
368c66f16a3SMichael Hamann    return stripos($title, $search) !== false;
369c66f16a3SMichael Hamann}
370c66f16a3SMichael Hamann
371c66f16a3SMichael Hamann/**
372f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string
373f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy
374f31eb72bSAndreas Gohr * pages.
37542ea7f44SGerrit Uitslag *
37642ea7f44SGerrit Uitslag * @param string $a
37742ea7f44SGerrit Uitslag * @param string $b
37842ea7f44SGerrit Uitslag * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal.
379f31eb72bSAndreas Gohr */
380f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){
381f31eb72bSAndreas Gohr    $ac = count(explode(':',$a));
382f31eb72bSAndreas Gohr    $bc = count(explode(':',$b));
383f31eb72bSAndreas Gohr    if($ac < $bc){
384f31eb72bSAndreas Gohr        return -1;
385f31eb72bSAndreas Gohr    }elseif($ac > $bc){
386f31eb72bSAndreas Gohr        return 1;
387f31eb72bSAndreas Gohr    }
3882d85e841SAndreas Gohr    return Sort::strcmp($a,$b);
389f31eb72bSAndreas Gohr}
390f31eb72bSAndreas Gohr
391f31eb72bSAndreas Gohr/**
3928d0e286aSMichael Große * Sort pages by their mtime, from newest to oldest
3938d0e286aSMichael Große *
3948d0e286aSMichael Große * @param string $a
3958d0e286aSMichael Große * @param string $b
3968d0e286aSMichael Große *
3978d0e286aSMichael 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
3988d0e286aSMichael Große */
3998d0e286aSMichael Großefunction ft_pagemtimesorter($a, $b) {
4008d0e286aSMichael Große    $mtimeA = filemtime(wikiFN($a));
4018d0e286aSMichael Große    $mtimeB = filemtime(wikiFN($b));
4028d0e286aSMichael Große    return $mtimeB - $mtimeA;
4038d0e286aSMichael Große}
4048d0e286aSMichael Große
4058d0e286aSMichael Große/**
406506fa893SAndreas Gohr * Creates a snippet extract
407506fa893SAndreas Gohr *
408506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
40960e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE
41042ea7f44SGerrit Uitslag *
41142ea7f44SGerrit Uitslag * @param string $id page id
41242ea7f44SGerrit Uitslag * @param array $highlight
41342ea7f44SGerrit Uitslag * @return mixed
414506fa893SAndreas Gohr */
415546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){
416506fa893SAndreas Gohr    $text = rawWiki($id);
4174f0030ddSAndreas Gohr    $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens
41860e91a17SAndreas Gohr    $evdata = array(
41960e91a17SAndreas Gohr            'id'        => $id,
42060e91a17SAndreas Gohr            'text'      => &$text,
42160e91a17SAndreas Gohr            'highlight' => &$highlight,
42260e91a17SAndreas Gohr            'snippet'   => '',
42360e91a17SAndreas Gohr            );
42460e91a17SAndreas Gohr
425e1d9dcc8SAndreas Gohr    $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata);
42660e91a17SAndreas Gohr    if ($evt->advise_before()) {
427ced0762eSchris        $match = array();
428ced0762eSchris        $snippets = array();
4299ee93076Schris        $utf8_offset = $offset = $end = 0;
4308cbc5ee8SAndreas Gohr        $len = \dokuwiki\Utf8\PhpString::strlen($text);
4319ee93076Schris
432546d3a99SAndreas Gohr        // build a regexp from the phrases to highlight
43364159a61SAndreas Gohr        $re1 = '(' .
43464159a61SAndreas Gohr            join(
43564159a61SAndreas Gohr                '|',
43664159a61SAndreas Gohr                array_map(
43764159a61SAndreas Gohr                    'ft_snippet_re_preprocess',
43864159a61SAndreas Gohr                    array_map(
43964159a61SAndreas Gohr                        'preg_quote_cb',
44064159a61SAndreas Gohr                        array_filter((array) $highlight)
44164159a61SAndreas Gohr                    )
44264159a61SAndreas Gohr                )
44364159a61SAndreas Gohr            ) .
44464159a61SAndreas Gohr            ')';
445b571ff2dSChuck Kollars        $re2 = "$re1.{0,75}(?!\\1)$re1";
446b571ff2dSChuck Kollars        $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
447546d3a99SAndreas Gohr
448b571ff2dSChuck Kollars        for ($cnt=4; $cnt--;) {
449b571ff2dSChuck Kollars            if (0) {
450b571ff2dSChuck Kollars            } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
451b571ff2dSChuck Kollars            } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
452b571ff2dSChuck Kollars            } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
453b571ff2dSChuck Kollars            } else {
454b571ff2dSChuck Kollars                break;
455b571ff2dSChuck Kollars            }
456ced0762eSchris
457ced0762eSchris            list($str,$idx) = $match[0];
458ced0762eSchris
459ced0762eSchris            // convert $idx (a byte offset) into a utf8 character offset
4608cbc5ee8SAndreas Gohr            $utf8_idx = \dokuwiki\Utf8\PhpString::strlen(substr($text,0,$idx));
4618cbc5ee8SAndreas Gohr            $utf8_len = \dokuwiki\Utf8\PhpString::strlen($str);
462ced0762eSchris
463ced0762eSchris            // establish context, 100 bytes surrounding the match string
464ced0762eSchris            // first look to see if we can go 100 either side,
465ced0762eSchris            // then drop to 50 adding any excess if the other side can't go to 50,
466ced0762eSchris            $pre = min($utf8_idx-$utf8_offset,100);
467ced0762eSchris            $post = min($len-$utf8_idx-$utf8_len,100);
468ced0762eSchris
469ced0762eSchris            if ($pre>50 && $post>50) {
470ced0762eSchris                $pre = $post = 50;
471ced0762eSchris            } else if ($pre>50) {
472ced0762eSchris                $pre = min($pre,100-$post);
473ced0762eSchris            } else if ($post>50) {
474ced0762eSchris                $post = min($post, 100-$pre);
475ef3e3cddSMichael Hamann            } else if ($offset == 0) {
476ced0762eSchris                // both are less than 50, means the context is the whole string
47710ffc9ddSAndreas Gohr                // make it so and break out of this loop - there is no need for the
47810ffc9ddSAndreas Gohr                // complex snippet calculations
479ced0762eSchris                $snippets = array($text);
480ced0762eSchris                break;
481ced0762eSchris            }
482ced0762eSchris
48310ffc9ddSAndreas Gohr            // establish context start and end points, try to append to previous
48410ffc9ddSAndreas Gohr            // context if possible
4859ee93076Schris            $start = $utf8_idx - $pre;
486ced0762eSchris            $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
4879ee93076Schris            $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
488ced0762eSchris
489ced0762eSchris            if ($append) {
4908cbc5ee8SAndreas Gohr                $snippets[count($snippets)-1] .= \dokuwiki\Utf8\PhpString::substr($text,$append,$end-$append);
491ced0762eSchris            } else {
4928cbc5ee8SAndreas Gohr                $snippets[] = \dokuwiki\Utf8\PhpString::substr($text,$start,$end-$start);
493ced0762eSchris            }
494ced0762eSchris
495ced0762eSchris            // set $offset for next match attempt
49643d58b76SMichael Hamann            // continue matching after the current match
49743d58b76SMichael Hamann            // if the current match is not the longest possible match starting at the current offset
49843d58b76SMichael Hamann            // this prevents further matching of this snippet but for possible matches of length
49943d58b76SMichael Hamann            // smaller than match length + context (at least 50 characters) this match is part of the context
50043d58b76SMichael Hamann            $utf8_offset = $utf8_idx + $utf8_len;
5018cbc5ee8SAndreas Gohr            $offset = $idx + strlen(\dokuwiki\Utf8\PhpString::substr($text,$utf8_idx,$utf8_len));
5028cbc5ee8SAndreas Gohr            $offset = \dokuwiki\Utf8\Clean::correctIdx($text,$offset);
5039ee93076Schris        }
5049ee93076Schris
505ced0762eSchris        $m = "\1";
506b571ff2dSChuck Kollars        $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
50764159a61SAndreas Gohr        $snippet = preg_replace(
50864159a61SAndreas Gohr            '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
50964159a61SAndreas Gohr            '<strong class="search_hit">$1</strong>',
51064159a61SAndreas Gohr            hsc(join('... ', $snippets))
51164159a61SAndreas Gohr        );
512bd2cb6fcSchris
51360e91a17SAndreas Gohr        $evdata['snippet'] = $snippet;
51460e91a17SAndreas Gohr    }
51560e91a17SAndreas Gohr    $evt->advise_after();
51660e91a17SAndreas Gohr    unset($evt);
51760e91a17SAndreas Gohr
51860e91a17SAndreas Gohr    return $evdata['snippet'];
519506fa893SAndreas Gohr}
520506fa893SAndreas Gohr
521506fa893SAndreas Gohr/**
52226eb848cSGina Haeussge * Wraps a search term in regex boundary checks.
52342ea7f44SGerrit Uitslag *
52442ea7f44SGerrit Uitslag * @param string $term
52542ea7f44SGerrit Uitslag * @return string
52626eb848cSGina Haeussge */
5272237b4faSAndreas Gohrfunction ft_snippet_re_preprocess($term) {
52835594613SKazutaka Miyasaka    // do not process asian terms where word boundaries are not explicit
529dbc189b2SAndreas Gohr    if(\dokuwiki\Utf8\Asian::isAsianWords($term)) return $term;
53035594613SKazutaka Miyasaka
5313161005dSAndreas Gohr    if (UTF8_PROPERTYSUPPORT) {
53284e581a6SAndreas Gohr        // unicode word boundaries
53384e581a6SAndreas Gohr        // see http://stackoverflow.com/a/2449017/172068
53484e581a6SAndreas Gohr        $BL = '(?<!\pL)';
53584e581a6SAndreas Gohr        $BR = '(?!\pL)';
5363161005dSAndreas Gohr    } else {
5373161005dSAndreas Gohr        // not as correct as above, but at least won't break
5383161005dSAndreas Gohr        $BL = '\b';
5393161005dSAndreas Gohr        $BR = '\b';
5403161005dSAndreas Gohr    }
5413161005dSAndreas Gohr
5422237b4faSAndreas Gohr    if(substr($term,0,2) == '\\*'){
5432237b4faSAndreas Gohr        $term = substr($term,2);
5442237b4faSAndreas Gohr    }else{
54584e581a6SAndreas Gohr        $term = $BL.$term;
5462237b4faSAndreas Gohr    }
5472237b4faSAndreas Gohr
5482237b4faSAndreas Gohr    if(substr($term,-2,2) == '\\*'){
5492237b4faSAndreas Gohr        $term = substr($term,0,-2);
5502237b4faSAndreas Gohr    }else{
55184e581a6SAndreas Gohr        $term = $term.$BR;
5522237b4faSAndreas Gohr    }
5538a803caeSAndreas Gohr
55484e581a6SAndreas Gohr    if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
5552237b4faSAndreas Gohr    return $term;
55626eb848cSGina Haeussge}
55726eb848cSGina Haeussge
55826eb848cSGina Haeussge/**
559f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
560f5eb7cf0SAndreas Gohr *
561f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
562f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
563f5eb7cf0SAndreas Gohr *
564f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
565f5eb7cf0SAndreas Gohr *
566f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
56742ea7f44SGerrit Uitslag * @return array
568f5eb7cf0SAndreas Gohr */
569f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){
570f5eb7cf0SAndreas Gohr    $array_count = count($args);
571134f4ab2SAndreas Gohr    if($array_count == 1){
572134f4ab2SAndreas Gohr        return $args[0];
573134f4ab2SAndreas Gohr    }
574134f4ab2SAndreas Gohr
575f5eb7cf0SAndreas Gohr    $result = array();
57609c27a6dSGuy Brand    if ($array_count > 1) {
577a21136cdSAndreas Gohr        foreach ($args[0] as $key => $value) {
578a21136cdSAndreas Gohr            $result[$key] = $value;
579f5eb7cf0SAndreas Gohr            for ($i = 1; $i !== $array_count; $i++) {
580a21136cdSAndreas Gohr                if (!isset($args[$i][$key])) {
581a21136cdSAndreas Gohr                    unset($result[$key]);
582a21136cdSAndreas Gohr                    break;
583f5eb7cf0SAndreas Gohr                }
584a21136cdSAndreas Gohr                $result[$key] += $args[$i][$key];
585f5eb7cf0SAndreas Gohr            }
586f5eb7cf0SAndreas Gohr        }
58709c27a6dSGuy Brand    }
588f5eb7cf0SAndreas Gohr    return $result;
589f5eb7cf0SAndreas Gohr}
590f5eb7cf0SAndreas Gohr
591f5eb7cf0SAndreas Gohr/**
592865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores
593f5eb7cf0SAndreas Gohr *
594865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function
595865c2687SKazutaka Miyasaka *
596865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
59742ea7f44SGerrit Uitslag * @return array
59842ea7f44SGerrit Uitslag *
599865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
600865c2687SKazutaka Miyasaka */
601865c2687SKazutaka Miyasakafunction ft_resultUnite($args) {
602865c2687SKazutaka Miyasaka    $array_count = count($args);
603865c2687SKazutaka Miyasaka    if ($array_count === 1) {
604865c2687SKazutaka Miyasaka        return $args[0];
605865c2687SKazutaka Miyasaka    }
606865c2687SKazutaka Miyasaka
607865c2687SKazutaka Miyasaka    $result = $args[0];
608865c2687SKazutaka Miyasaka    for ($i = 1; $i !== $array_count; $i++) {
609865c2687SKazutaka Miyasaka        foreach (array_keys($args[$i]) as $id) {
610865c2687SKazutaka Miyasaka            $result[$id] += $args[$i][$id];
611865c2687SKazutaka Miyasaka        }
612865c2687SKazutaka Miyasaka    }
613865c2687SKazutaka Miyasaka    return $result;
614865c2687SKazutaka Miyasaka}
615865c2687SKazutaka Miyasaka
616865c2687SKazutaka Miyasaka/**
617865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison
618865c2687SKazutaka Miyasaka *
619865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key()
620865c2687SKazutaka Miyasaka *
621865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
62242ea7f44SGerrit Uitslag * @return array
62342ea7f44SGerrit Uitslag *
624865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
625865c2687SKazutaka Miyasaka */
626865c2687SKazutaka Miyasakafunction ft_resultComplement($args) {
627865c2687SKazutaka Miyasaka    $array_count = count($args);
628865c2687SKazutaka Miyasaka    if ($array_count === 1) {
629865c2687SKazutaka Miyasaka        return $args[0];
630865c2687SKazutaka Miyasaka    }
631865c2687SKazutaka Miyasaka
632865c2687SKazutaka Miyasaka    $result = $args[0];
633865c2687SKazutaka Miyasaka    foreach (array_keys($result) as $id) {
634865c2687SKazutaka Miyasaka        for ($i = 1; $i !== $array_count; $i++) {
635865c2687SKazutaka Miyasaka            if (isset($args[$i][$id])) unset($result[$id]);
636865c2687SKazutaka Miyasaka        }
637865c2687SKazutaka Miyasaka    }
638865c2687SKazutaka Miyasaka    return $result;
639865c2687SKazutaka Miyasaka}
640865c2687SKazutaka Miyasaka
641865c2687SKazutaka Miyasaka/**
642865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas
643865c2687SKazutaka Miyasaka *
644865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
645865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
64642ea7f44SGerrit Uitslag *
6476225b270SMichael Große * @param dokuwiki\Search\Indexer $Indexer
64842ea7f44SGerrit Uitslag * @param string                  $query search query
64942ea7f44SGerrit Uitslag * @return array of search formulas
650f5eb7cf0SAndreas Gohr */
6519b41be24STom N Harrisfunction ft_queryParser($Indexer, $query){
652865c2687SKazutaka Miyasaka    /**
653865c2687SKazutaka Miyasaka     * parse a search query and transform it into intermediate representation
654865c2687SKazutaka Miyasaka     *
655865c2687SKazutaka Miyasaka     * in a search query, you can use the following expressions:
656865c2687SKazutaka Miyasaka     *
657865c2687SKazutaka Miyasaka     *   words:
658865c2687SKazutaka Miyasaka     *     include
659865c2687SKazutaka Miyasaka     *     -exclude
660865c2687SKazutaka Miyasaka     *   phrases:
661865c2687SKazutaka Miyasaka     *     "phrase to be included"
662865c2687SKazutaka Miyasaka     *     -"phrase you want to exclude"
663865c2687SKazutaka Miyasaka     *   namespaces:
664865c2687SKazutaka Miyasaka     *     @include:namespace (or ns:include:namespace)
665865c2687SKazutaka Miyasaka     *     ^exclude:namespace (or -ns:exclude:namespace)
666865c2687SKazutaka Miyasaka     *   groups:
667865c2687SKazutaka Miyasaka     *     ()
668865c2687SKazutaka Miyasaka     *     -()
669865c2687SKazutaka Miyasaka     *   operators:
670865c2687SKazutaka Miyasaka     *     and ('and' is the default operator: you can always omit this)
6717871d415SKazutaka Miyasaka     *     or  (or pipe symbol '|', lower precedence than 'and')
672865c2687SKazutaka Miyasaka     *
673865c2687SKazutaka Miyasaka     * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
674865c2687SKazutaka Miyasaka     *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
675865c2687SKazutaka Miyasaka     *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
676865c2687SKazutaka Miyasaka     *      as long as you don't mind hit counts.
677865c2687SKazutaka Miyasaka     *
678865c2687SKazutaka Miyasaka     * intermediate representation consists of the following parts:
679865c2687SKazutaka Miyasaka     *
680865c2687SKazutaka Miyasaka     *   ( )           - group
681865c2687SKazutaka Miyasaka     *   AND           - logical and
682865c2687SKazutaka Miyasaka     *   OR            - logical or
683865c2687SKazutaka Miyasaka     *   NOT           - logical not
6842f502d70SKazutaka Miyasaka     *   W+:, W-:, W_: - word      (underscore: no need to highlight)
6852f502d70SKazutaka Miyasaka     *   P+:, P-:      - phrase    (minus sign: logically in NOT group)
6862f502d70SKazutaka Miyasaka     *   N+:, N-:      - namespace
687865c2687SKazutaka Miyasaka     */
688865c2687SKazutaka Miyasaka    $parsed_query = '';
689865c2687SKazutaka Miyasaka    $parens_level = 0;
6906ce3e5f8SAndreas Gohr    $terms = preg_split('/(-?".*?")/u', \dokuwiki\Utf8\PhpString::strtolower($query),
6916ce3e5f8SAndreas Gohr        -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
692865c2687SKazutaka Miyasaka
693865c2687SKazutaka Miyasaka    foreach ($terms as $term) {
694865c2687SKazutaka Miyasaka        $parsed = '';
695865c2687SKazutaka Miyasaka        if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
696865c2687SKazutaka Miyasaka            // phrase-include and phrase-exclude
697865c2687SKazutaka Miyasaka            $not = $matches[1] ? 'NOT' : '';
6989b41be24STom N Harris            $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
699f5eb7cf0SAndreas Gohr        } else {
700865c2687SKazutaka Miyasaka            // fix incomplete phrase
701865c2687SKazutaka Miyasaka            $term = str_replace('"', ' ', $term);
702865c2687SKazutaka Miyasaka
703865c2687SKazutaka Miyasaka            // fix parentheses
704865c2687SKazutaka Miyasaka            $term = str_replace(')'  , ' ) ', $term);
705865c2687SKazutaka Miyasaka            $term = str_replace('('  , ' ( ', $term);
706865c2687SKazutaka Miyasaka            $term = str_replace('- (', ' -(', $term);
707865c2687SKazutaka Miyasaka
7087871d415SKazutaka Miyasaka            // treat pipe symbols as 'OR' operators
7097871d415SKazutaka Miyasaka            $term = str_replace('|', ' or ', $term);
7107871d415SKazutaka Miyasaka
711865c2687SKazutaka Miyasaka            // treat ideographic spaces (U+3000) as search term separators
712865c2687SKazutaka Miyasaka            // FIXME: some more separators?
713865c2687SKazutaka Miyasaka            $term = preg_replace('/[ \x{3000}]+/u', ' ',  $term);
714865c2687SKazutaka Miyasaka            $term = trim($term);
715865c2687SKazutaka Miyasaka            if ($term === '') continue;
716865c2687SKazutaka Miyasaka
717865c2687SKazutaka Miyasaka            $tokens = explode(' ', $term);
718865c2687SKazutaka Miyasaka            foreach ($tokens as $token) {
719865c2687SKazutaka Miyasaka                if ($token === '(') {
720865c2687SKazutaka Miyasaka                    // parenthesis-include-open
721865c2687SKazutaka Miyasaka                    $parsed .= '(';
722865c2687SKazutaka Miyasaka                    ++$parens_level;
723865c2687SKazutaka Miyasaka                } elseif ($token === '-(') {
724865c2687SKazutaka Miyasaka                    // parenthesis-exclude-open
725865c2687SKazutaka Miyasaka                    $parsed .= 'NOT(';
726865c2687SKazutaka Miyasaka                    ++$parens_level;
727865c2687SKazutaka Miyasaka                } elseif ($token === ')') {
728865c2687SKazutaka Miyasaka                    // parenthesis-any-close
729865c2687SKazutaka Miyasaka                    if ($parens_level === 0) continue;
730865c2687SKazutaka Miyasaka                    $parsed .= ')';
731865c2687SKazutaka Miyasaka                    $parens_level--;
732865c2687SKazutaka Miyasaka                } elseif ($token === 'and') {
733865c2687SKazutaka Miyasaka                    // logical-and (do nothing)
734865c2687SKazutaka Miyasaka                } elseif ($token === 'or') {
735865c2687SKazutaka Miyasaka                    // logical-or
736865c2687SKazutaka Miyasaka                    $parsed .= 'OR';
737865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
738865c2687SKazutaka Miyasaka                    // namespace-exclude
7392f502d70SKazutaka Miyasaka                    $parsed .= 'NOT(N+:'.$matches[1].')';
740865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
741865c2687SKazutaka Miyasaka                    // namespace-include
7422f502d70SKazutaka Miyasaka                    $parsed .= '(N+:'.$matches[1].')';
743865c2687SKazutaka Miyasaka                } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
744865c2687SKazutaka Miyasaka                    // word-exclude
7459b41be24STom N Harris                    $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
746865c2687SKazutaka Miyasaka                } else {
747865c2687SKazutaka Miyasaka                    // word-include
7489b41be24STom N Harris                    $parsed .= ft_termParser($Indexer, $token);
749865c2687SKazutaka Miyasaka                }
750865c2687SKazutaka Miyasaka            }
751865c2687SKazutaka Miyasaka        }
752865c2687SKazutaka Miyasaka        $parsed_query .= $parsed;
753f5eb7cf0SAndreas Gohr    }
754f5eb7cf0SAndreas Gohr
755865c2687SKazutaka Miyasaka    // cleanup (very sensitive)
756865c2687SKazutaka Miyasaka    $parsed_query .= str_repeat(')', $parens_level);
757865c2687SKazutaka Miyasaka    do {
758865c2687SKazutaka Miyasaka        $parsed_query_old = $parsed_query;
759865c2687SKazutaka Miyasaka        $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
760865c2687SKazutaka Miyasaka    } while ($parsed_query !== $parsed_query_old);
761865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')'      , $parsed_query);
762865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(OR)+/u'      , 'OR'     , $parsed_query);
763865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\(OR/u'       , '('      , $parsed_query);
764865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/^OR|OR$/u'    , ''       , $parsed_query);
765865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
766865c2687SKazutaka Miyasaka
7672f502d70SKazutaka Miyasaka    // adjustment: make highlightings right
7682f502d70SKazutaka Miyasaka    $parens_level     = 0;
7692f502d70SKazutaka Miyasaka    $notgrp_levels    = array();
7702f502d70SKazutaka Miyasaka    $parsed_query_new = '';
7712f502d70SKazutaka Miyasaka    $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
7722f502d70SKazutaka Miyasaka    foreach ($tokens as $token) {
7732f502d70SKazutaka Miyasaka        if ($token === 'NOT(') {
7742f502d70SKazutaka Miyasaka            $notgrp_levels[] = ++$parens_level;
7752f502d70SKazutaka Miyasaka        } elseif ($token === '(') {
7762f502d70SKazutaka Miyasaka            ++$parens_level;
7772f502d70SKazutaka Miyasaka        } elseif ($token === ')') {
7782f502d70SKazutaka Miyasaka            if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
7792f502d70SKazutaka Miyasaka        } elseif (count($notgrp_levels) % 2 === 1) {
7802f502d70SKazutaka Miyasaka            // turn highlight-flag off if terms are logically in "NOT" group
7812f502d70SKazutaka Miyasaka            $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
7822f502d70SKazutaka Miyasaka        }
7832f502d70SKazutaka Miyasaka        $parsed_query_new .= $token;
7842f502d70SKazutaka Miyasaka    }
7852f502d70SKazutaka Miyasaka    $parsed_query = $parsed_query_new;
7862f502d70SKazutaka Miyasaka
787865c2687SKazutaka Miyasaka    /**
788865c2687SKazutaka Miyasaka     * convert infix notation string into postfix (Reverse Polish notation) array
789865c2687SKazutaka Miyasaka     * by Shunting-yard algorithm
790865c2687SKazutaka Miyasaka     *
791865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
792865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
793865c2687SKazutaka Miyasaka     */
794865c2687SKazutaka Miyasaka    $parsed_ary     = array();
795865c2687SKazutaka Miyasaka    $ope_stack      = array();
796865c2687SKazutaka Miyasaka    $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
797865c2687SKazutaka Miyasaka    $ope_regex      = '/([()]|OR|AND|NOT)/u';
798865c2687SKazutaka Miyasaka
799865c2687SKazutaka Miyasaka    $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
800865c2687SKazutaka Miyasaka    foreach ($tokens as $token) {
801865c2687SKazutaka Miyasaka        if (preg_match($ope_regex, $token)) {
802865c2687SKazutaka Miyasaka            // operator
803865c2687SKazutaka Miyasaka            $last_ope = end($ope_stack);
80467d812e0SMarius van Witzenburg            while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
805865c2687SKazutaka Miyasaka                $parsed_ary[] = array_pop($ope_stack);
806865c2687SKazutaka Miyasaka                $last_ope = end($ope_stack);
807865c2687SKazutaka Miyasaka            }
808865c2687SKazutaka Miyasaka            if ($token == ')') {
809865c2687SKazutaka Miyasaka                array_pop($ope_stack); // this array_pop always deletes '('
810865c2687SKazutaka Miyasaka            } else {
811865c2687SKazutaka Miyasaka                $ope_stack[] = $token;
812865c2687SKazutaka Miyasaka            }
813865c2687SKazutaka Miyasaka        } else {
814865c2687SKazutaka Miyasaka            // operand
815865c2687SKazutaka Miyasaka            $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
816865c2687SKazutaka Miyasaka            $parsed_ary[] = $token_decoded;
817865c2687SKazutaka Miyasaka        }
818865c2687SKazutaka Miyasaka    }
819865c2687SKazutaka Miyasaka    $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
820865c2687SKazutaka Miyasaka
821865c2687SKazutaka Miyasaka    // cleanup: each double "NOT" in RPN array actually does nothing
822865c2687SKazutaka Miyasaka    $parsed_ary_count = count($parsed_ary);
823865c2687SKazutaka Miyasaka    for ($i = 1; $i < $parsed_ary_count; ++$i) {
824865c2687SKazutaka Miyasaka        if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
825865c2687SKazutaka Miyasaka            unset($parsed_ary[$i], $parsed_ary[$i - 1]);
826865c2687SKazutaka Miyasaka        }
827865c2687SKazutaka Miyasaka    }
828865c2687SKazutaka Miyasaka    $parsed_ary = array_values($parsed_ary);
829865c2687SKazutaka Miyasaka
830865c2687SKazutaka Miyasaka    // build return value
831f5eb7cf0SAndreas Gohr    $q = array();
832f5eb7cf0SAndreas Gohr    $q['query']      = $query;
833865c2687SKazutaka Miyasaka    $q['parsed_str'] = $parsed_query;
834865c2687SKazutaka Miyasaka    $q['parsed_ary'] = $parsed_ary;
835f5eb7cf0SAndreas Gohr
836865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
837865c2687SKazutaka Miyasaka        if ($token[2] !== ':') continue;
838865c2687SKazutaka Miyasaka        $body = substr($token, 3);
839865c2687SKazutaka Miyasaka
840865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
8412f502d70SKazutaka Miyasaka            case 'N+:':
842865c2687SKazutaka Miyasaka                     $q['ns'][]        = $body; // for backward compatibility
843865c2687SKazutaka Miyasaka                     break;
8442f502d70SKazutaka Miyasaka            case 'N-:':
8452f502d70SKazutaka Miyasaka                     $q['notns'][]     = $body; // for backward compatibility
8462f502d70SKazutaka Miyasaka                     break;
8472f502d70SKazutaka Miyasaka            case 'W_:':
8482f502d70SKazutaka Miyasaka                     $q['words'][]     = $body;
8492f502d70SKazutaka Miyasaka                     break;
850865c2687SKazutaka Miyasaka            case 'W-:':
851865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
8522f502d70SKazutaka Miyasaka                     $q['not'][]       = $body; // for backward compatibility
853865c2687SKazutaka Miyasaka                     break;
854865c2687SKazutaka Miyasaka            case 'W+:':
855865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
8562237b4faSAndreas Gohr                     $q['highlight'][] = $body;
8572f502d70SKazutaka Miyasaka                     $q['and'][]       = $body; // for backward compatibility
858865c2687SKazutaka Miyasaka                     break;
8592f502d70SKazutaka Miyasaka            case 'P-:':
8602f502d70SKazutaka Miyasaka                     $q['phrases'][]   = $body;
8612f502d70SKazutaka Miyasaka                     break;
8622f502d70SKazutaka Miyasaka            case 'P+:':
863865c2687SKazutaka Miyasaka                     $q['phrases'][]   = $body;
8642237b4faSAndreas Gohr                     $q['highlight'][] = $body;
865865c2687SKazutaka Miyasaka                     break;
866865c2687SKazutaka Miyasaka        }
867865c2687SKazutaka Miyasaka    }
8682f502d70SKazutaka Miyasaka    foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) {
869865c2687SKazutaka Miyasaka        $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
870f5eb7cf0SAndreas Gohr    }
871f5eb7cf0SAndreas Gohr
872f5eb7cf0SAndreas Gohr    return $q;
873f5eb7cf0SAndreas Gohr}
874f5eb7cf0SAndreas Gohr
875865c2687SKazutaka Miyasaka/**
876865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation
877865c2687SKazutaka Miyasaka *
878865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use.
879865c2687SKazutaka Miyasaka *
880865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
88142ea7f44SGerrit Uitslag *
8826225b270SMichael Große * @param dokuwiki\Search\Indexer $Indexer
88342ea7f44SGerrit Uitslag * @param string                  $term
88442ea7f44SGerrit Uitslag * @param bool                    $consider_asian
88542ea7f44SGerrit Uitslag * @param bool                    $phrase_mode
88642ea7f44SGerrit Uitslag * @return string
887865c2687SKazutaka Miyasaka */
8889b41be24STom N Harrisfunction ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) {
889865c2687SKazutaka Miyasaka    $parsed = '';
890865c2687SKazutaka Miyasaka    if ($consider_asian) {
891865c2687SKazutaka Miyasaka        // successive asian characters need to be searched as a phrase
892dbc189b2SAndreas Gohr        $words = \dokuwiki\Utf8\Asian::splitAsianWords($term);
893865c2687SKazutaka Miyasaka        foreach ($words as $word) {
894dbc189b2SAndreas Gohr            $phrase_mode = $phrase_mode ? true : \dokuwiki\Utf8\Asian::isAsianWords($word);
8959b41be24STom N Harris            $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
896865c2687SKazutaka Miyasaka        }
897865c2687SKazutaka Miyasaka    } else {
898865c2687SKazutaka Miyasaka        $term_noparen = str_replace(array('(', ')'), ' ', $term);
8999b41be24STom N Harris        $words = $Indexer->tokenizer($term_noparen, true);
900865c2687SKazutaka Miyasaka
9012f502d70SKazutaka Miyasaka        // W_: no need to highlight
902865c2687SKazutaka Miyasaka        if (empty($words)) {
903865c2687SKazutaka Miyasaka            $parsed = '()'; // important: do not remove
904865c2687SKazutaka Miyasaka        } elseif ($words[0] === $term) {
905865c2687SKazutaka Miyasaka            $parsed = '(W+:'.$words[0].')';
906865c2687SKazutaka Miyasaka        } elseif ($phrase_mode) {
907865c2687SKazutaka Miyasaka            $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
9082f502d70SKazutaka Miyasaka            $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
909865c2687SKazutaka Miyasaka        } else {
910865c2687SKazutaka Miyasaka            $parsed = '((W+:'.implode(')(W+:', $words).'))';
911865c2687SKazutaka Miyasaka        }
912865c2687SKazutaka Miyasaka    }
913865c2687SKazutaka Miyasaka    return $parsed;
914865c2687SKazutaka Miyasaka}
915865c2687SKazutaka Miyasaka
91644156e11SMichael Große/**
91744156e11SMichael Große * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
91844156e11SMichael Große *
91944156e11SMichael Große * @param array $and
92044156e11SMichael Große * @param array $not
92144156e11SMichael Große * @param array $phrases
92244156e11SMichael Große * @param array $ns
92344156e11SMichael Große * @param array $notns
92444156e11SMichael Große *
92544156e11SMichael Große * @return string
92644156e11SMichael Große */
92744156e11SMichael Großefunction ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) {
92844156e11SMichael Große    $query = implode(' ', $and);
92944156e11SMichael Große    if (!empty($not)) {
93044156e11SMichael Große        $query .= ' -' . implode(' -', $not);
93144156e11SMichael Große    }
93244156e11SMichael Große
93344156e11SMichael Große    if (!empty($phrases)) {
93444156e11SMichael Große        $query .= ' "' . implode('" "', $phrases) . '"';
93544156e11SMichael Große    }
93644156e11SMichael Große
93744156e11SMichael Große    if (!empty($ns)) {
93844156e11SMichael Große        $query .= ' @' . implode(' @', $ns);
93944156e11SMichael Große    }
94044156e11SMichael Große
94144156e11SMichael Große    if (!empty($notns)) {
94244156e11SMichael Große        $query .= ' ^' . implode(' ^', $notns);
94344156e11SMichael Große    }
94444156e11SMichael Große
94544156e11SMichael Große    return $query;
94644156e11SMichael Große}
94744156e11SMichael Große
948e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 :
949