1f5eb7cf0SAndreas Gohr<?php 2d4f83172SAndreas Gohr 3f5eb7cf0SAndreas Gohr/** 4f5eb7cf0SAndreas Gohr * DokuWiki fulltextsearch functions using the index 5f5eb7cf0SAndreas Gohr * 6f5eb7cf0SAndreas Gohr * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 7f5eb7cf0SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 827f63a23SAndreas Gohr */ 9d4f83172SAndreas Gohr 1024870174SAndreas Gohruse dokuwiki\Utf8\Asian; 1124870174SAndreas Gohruse dokuwiki\Search\Indexer; 1227f63a23SAndreas Gohruse dokuwiki\Extension\Event; 137fb26b8eSAndreas Gohruse dokuwiki\Utf8\Clean; 147fb26b8eSAndreas Gohruse dokuwiki\Utf8\PhpString; 152d85e841SAndreas Gohruse dokuwiki\Utf8\Sort; 16f5eb7cf0SAndreas Gohr 17bd0293e7SAndreas Gohr/** 18bd0293e7SAndreas Gohr * create snippets for the first few results only 19bd0293e7SAndreas Gohr */ 20bd0293e7SAndreas Gohrif (!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER', 15); 21f5eb7cf0SAndreas Gohr 22f5eb7cf0SAndreas Gohr/** 23f5eb7cf0SAndreas Gohr * The fulltext search 24f5eb7cf0SAndreas Gohr * 25f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query 26506fa893SAndreas Gohr * 276840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event() 286840140fSChris Smith * 2942ea7f44SGerrit Uitslag * @param string $query 3042ea7f44SGerrit Uitslag * @param array $highlight 313850270cSMichael Große * @param string $sort 3264159a61SAndreas Gohr * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 3364159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 343850270cSMichael Große * 3542ea7f44SGerrit Uitslag * @return array 36f5eb7cf0SAndreas Gohr */ 37d868eb89SAndreas Gohrfunction ft_pageSearch($query, &$highlight, $sort = null, $after = null, $before = null) 38d868eb89SAndreas Gohr{ 396840140fSChris Smith 403850270cSMichael Große if ($sort === null) { 413850270cSMichael Große $sort = 'hits'; 423850270cSMichael Große } 433850270cSMichael Große $data = [ 443850270cSMichael Große 'query' => $query, 453850270cSMichael Große 'sort' => $sort, 463850270cSMichael Große 'after' => $after, 473850270cSMichael Große 'before' => $before 483850270cSMichael Große ]; 496840140fSChris Smith $data['highlight'] =& $highlight; 506840140fSChris Smith 51cbb44eabSAndreas Gohr return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch'); 526840140fSChris Smith} 53865c2687SKazutaka Miyasaka 54865c2687SKazutaka Miyasaka/** 55865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query 56865c2687SKazutaka Miyasaka * 57865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 58865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 5942ea7f44SGerrit Uitslag * 6042ea7f44SGerrit Uitslag * @param array $data event data 6142ea7f44SGerrit Uitslag * @return array matching documents 62865c2687SKazutaka Miyasaka */ 63d868eb89SAndreas Gohrfunction _ft_pageSearch(&$data) 64d868eb89SAndreas Gohr{ 659b41be24STom N Harris $Indexer = idx_get_indexer(); 669b41be24STom N Harris 67865c2687SKazutaka Miyasaka // parse the given query 689b41be24STom N Harris $q = ft_queryParser($Indexer, $data['query']); 69865c2687SKazutaka Miyasaka $data['highlight'] = $q['highlight']; 706840140fSChris Smith 7124870174SAndreas Gohr if (empty($q['parsed_ary'])) return []; 72506fa893SAndreas Gohr 73f5eb7cf0SAndreas Gohr // lookup all words found in the query 749b41be24STom N Harris $lookup = $Indexer->lookup($q['words']); 75f5eb7cf0SAndreas Gohr 76865c2687SKazutaka Miyasaka // get all pages in this dokuwiki site (!: includes nonexistent pages) 7724870174SAndreas Gohr $pages_all = []; 789b41be24STom N Harris foreach ($Indexer->getPages() as $id) { 799b41be24STom N Harris $pages_all[$id] = 0; // base: 0 hit 80f5eb7cf0SAndreas Gohr } 81f5eb7cf0SAndreas Gohr 82865c2687SKazutaka Miyasaka // process the query 8324870174SAndreas Gohr $stack = []; 84865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 85865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 86865c2687SKazutaka Miyasaka case 'W+:': 872f502d70SKazutaka Miyasaka case 'W-:': 882f502d70SKazutaka Miyasaka case 'W_:': // word 89865c2687SKazutaka Miyasaka $word = substr($token, 3); 905afd9580SAndreas Gohr if (isset($lookup[$word])) { 91865c2687SKazutaka Miyasaka $stack[] = (array)$lookup[$word]; 925afd9580SAndreas Gohr } 93865c2687SKazutaka Miyasaka break; 942f502d70SKazutaka Miyasaka case 'P+:': 952f502d70SKazutaka Miyasaka case 'P-:': // phrase 96865c2687SKazutaka Miyasaka $phrase = substr($token, 3); 97865c2687SKazutaka Miyasaka // since phrases are always parsed as ((W1)(W2)...(P)), 98865c2687SKazutaka Miyasaka // the end($stack) always points the pages that contain 99865c2687SKazutaka Miyasaka // all words in this phrase 100865c2687SKazutaka Miyasaka $pages = end($stack); 10124870174SAndreas Gohr $pages_matched = []; 102865c2687SKazutaka Miyasaka foreach (array_keys($pages) as $id) { 10324870174SAndreas Gohr $evdata = [ 104a7e8b43eSMichael Hamann 'id' => $id, 105a7e8b43eSMichael Hamann 'phrase' => $phrase, 106a7e8b43eSMichael Hamann 'text' => rawWiki($id) 10724870174SAndreas Gohr ]; 108e1d9dcc8SAndreas Gohr $evt = new Event('FULLTEXT_PHRASE_MATCH', $evdata); 109a7e8b43eSMichael Hamann if ($evt->advise_before() && $evt->result !== true) { 1107fb26b8eSAndreas Gohr $text = PhpString::strtolower($evdata['text']); 111865c2687SKazutaka Miyasaka if (strpos($text, $phrase) !== false) { 112a7e8b43eSMichael Hamann $evt->result = true; 113a7e8b43eSMichael Hamann } 114a7e8b43eSMichael Hamann } 115a7e8b43eSMichael Hamann $evt->advise_after(); 116a7e8b43eSMichael Hamann if ($evt->result === true) { 117865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // phrase: always 0 hit 118865c2687SKazutaka Miyasaka } 119865c2687SKazutaka Miyasaka } 120865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 121865c2687SKazutaka Miyasaka break; 1222f502d70SKazutaka Miyasaka case 'N+:': 1232f502d70SKazutaka Miyasaka case 'N-:': // namespace 124de3383c6SMichael Große $ns = cleanID(substr($token, 3)) . ':'; 12524870174SAndreas Gohr $pages_matched = []; 126865c2687SKazutaka Miyasaka foreach (array_keys($pages_all) as $id) { 127865c2687SKazutaka Miyasaka if (strpos($id, $ns) === 0) { 128865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // namespace: always 0 hit 129865c2687SKazutaka Miyasaka } 130865c2687SKazutaka Miyasaka } 131865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 132865c2687SKazutaka Miyasaka break; 133865c2687SKazutaka Miyasaka case 'AND': // and operation 13424870174SAndreas Gohr [$pages1, $pages2] = array_splice($stack, -2); 13524870174SAndreas Gohr $stack[] = ft_resultCombine([$pages1, $pages2]); 136865c2687SKazutaka Miyasaka break; 137865c2687SKazutaka Miyasaka case 'OR': // or operation 13824870174SAndreas Gohr [$pages1, $pages2] = array_splice($stack, -2); 13924870174SAndreas Gohr $stack[] = ft_resultUnite([$pages1, $pages2]); 140865c2687SKazutaka Miyasaka break; 141865c2687SKazutaka Miyasaka case 'NOT': // not operation (unary) 142865c2687SKazutaka Miyasaka $pages = array_pop($stack); 14324870174SAndreas Gohr $stack[] = ft_resultComplement([$pages_all, $pages]); 144a21136cdSAndreas Gohr break; 145a21136cdSAndreas Gohr } 146f5eb7cf0SAndreas Gohr } 147865c2687SKazutaka Miyasaka $docs = array_pop($stack); 148865c2687SKazutaka Miyasaka 14924870174SAndreas Gohr if (empty($docs)) return []; 150865c2687SKazutaka Miyasaka 151865c2687SKazutaka Miyasaka // check: settings, acls, existence 152865c2687SKazutaka Miyasaka foreach (array_keys($docs) as $id) { 153865c2687SKazutaka Miyasaka if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) { 154865c2687SKazutaka Miyasaka unset($docs[$id]); 155f5eb7cf0SAndreas Gohr } 156f5eb7cf0SAndreas Gohr } 157f5eb7cf0SAndreas Gohr 1583850270cSMichael Große $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']); 1598d0e286aSMichael Große 1608d0e286aSMichael Große if ($data['sort'] === 'mtime') { 1618d0e286aSMichael Große uksort($docs, 'ft_pagemtimesorter'); 1628d0e286aSMichael Große } else { 163865c2687SKazutaka Miyasaka // sort docs by count 16406281c9cSMoisés Braga Ribeiro uksort($docs, 'ft_pagesorter'); 165f5eb7cf0SAndreas Gohr arsort($docs); 1668d0e286aSMichael Große } 167f5eb7cf0SAndreas Gohr 168f5eb7cf0SAndreas Gohr return $docs; 169f5eb7cf0SAndreas Gohr} 170f5eb7cf0SAndreas Gohr 171f5eb7cf0SAndreas Gohr/** 17254f4c056SAndreas Gohr * Returns the backlinks for a given page 17354f4c056SAndreas Gohr * 174320f489aSMichael Hamann * Uses the metadata index. 17507ff0babSMichael Hamann * 17607ff0babSMichael Hamann * @param string $id The id for which links shall be returned 17707ff0babSMichael Hamann * @param bool $ignore_perms Ignore the fact that pages are hidden or read-protected 17807ff0babSMichael Hamann * @return array The pages that contain links to the given page 17954f4c056SAndreas Gohr */ 180d868eb89SAndreas Gohrfunction ft_backlinks($id, $ignore_perms = false) 181d868eb89SAndreas Gohr{ 182320f489aSMichael Hamann $result = idx_get_indexer()->lookupKey('relation_references', $id); 18354f4c056SAndreas Gohr 18424870174SAndreas Gohr if ($result === []) return $result; 18563773904SAndreas Gohr 18663773904SAndreas Gohr // check ACL permissions 18763773904SAndreas Gohr foreach (array_keys($result) as $idx) { 1887d34963bSAndreas Gohr if ( 1897d34963bSAndreas Gohr (!$ignore_perms && ( 19007ff0babSMichael Hamann isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 1917d34963bSAndreas Gohr )) || !page_exists($result[$idx], '', false) 1927d34963bSAndreas Gohr ) { 19363773904SAndreas Gohr unset($result[$idx]); 19463773904SAndreas Gohr } 19563773904SAndreas Gohr } 19663773904SAndreas Gohr 1972d85e841SAndreas Gohr Sort::sort($result); 19854f4c056SAndreas Gohr return $result; 19954f4c056SAndreas Gohr} 20054f4c056SAndreas Gohr 20154f4c056SAndreas Gohr/** 202a05e297aSAndreas Gohr * Returns the pages that use a given media file 203a05e297aSAndreas Gohr * 204ffec1009SMichael Hamann * Uses the relation media metadata property and the metadata index. 205a05e297aSAndreas Gohr * 206ffec1009SMichael Hamann * Note that before 2013-07-31 the second parameter was the maximum number of results and 207ffec1009SMichael Hamann * permissions were ignored. That's why the parameter is now checked to be explicitely set 208ffec1009SMichael Hamann * to true (with type bool) in order to be compatible with older uses of the function. 209ffec1009SMichael Hamann * 210ffec1009SMichael Hamann * @param string $id The media id to look for 211ffec1009SMichael Hamann * @param bool $ignore_perms Ignore hidden pages and acls (optional, default: false) 212ffec1009SMichael Hamann * @return array A list of pages that use the given media file 213a05e297aSAndreas Gohr */ 214d868eb89SAndreas Gohrfunction ft_mediause($id, $ignore_perms = false) 215d868eb89SAndreas Gohr{ 216ffec1009SMichael Hamann $result = idx_get_indexer()->lookupKey('relation_media', $id); 217a05e297aSAndreas Gohr 21824870174SAndreas Gohr if ($result === []) return $result; 219a05e297aSAndreas Gohr 220ffec1009SMichael Hamann // check ACL permissions 221ffec1009SMichael Hamann foreach (array_keys($result) as $idx) { 2227d34963bSAndreas Gohr if ( 2237d34963bSAndreas Gohr (!$ignore_perms && ( 224ffec1009SMichael Hamann isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 2257d34963bSAndreas Gohr )) || !page_exists($result[$idx], '', false) 2267d34963bSAndreas Gohr ) { 227ffec1009SMichael Hamann unset($result[$idx]); 228a05e297aSAndreas Gohr } 229a05e297aSAndreas Gohr } 230a05e297aSAndreas Gohr 2312d85e841SAndreas Gohr Sort::sort($result); 232a05e297aSAndreas Gohr return $result; 233a05e297aSAndreas Gohr} 234a05e297aSAndreas Gohr 235a05e297aSAndreas Gohr 236a05e297aSAndreas Gohr/** 237506fa893SAndreas Gohr * Quicksearch for pagenames 238506fa893SAndreas Gohr * 239506fa893SAndreas Gohr * By default it only matches the pagename and ignores the 24080423ab6SAdrian Lang * namespace. This can be changed with the second parameter. 24180423ab6SAdrian Lang * The third parameter allows to search in titles as well. 242506fa893SAndreas Gohr * 2438d22f1e9SAndreas Gohr * The function always returns titles as well 2446840140fSChris Smith * 2458d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP 246506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 2478d22f1e9SAndreas Gohr * @author Adrian Lang <lang@cosmocode.de> 24842ea7f44SGerrit Uitslag * 24942ea7f44SGerrit Uitslag * @param string $id page id 25042ea7f44SGerrit Uitslag * @param bool $in_ns match against namespace as well? 25142ea7f44SGerrit Uitslag * @param bool $in_title search in title? 25264159a61SAndreas Gohr * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 25364159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 2543850270cSMichael Große * 25542ea7f44SGerrit Uitslag * @return string[] 256506fa893SAndreas Gohr */ 257d868eb89SAndreas Gohrfunction ft_pageLookup($id, $in_ns = false, $in_title = false, $after = null, $before = null) 258d868eb89SAndreas Gohr{ 2593850270cSMichael Große $data = [ 2603850270cSMichael Große 'id' => $id, 2613850270cSMichael Große 'in_ns' => $in_ns, 2623850270cSMichael Große 'in_title' => $in_title, 2633850270cSMichael Große 'after' => $after, 2643850270cSMichael Große 'before' => $before 2653850270cSMichael Große ]; 2668d22f1e9SAndreas Gohr $data['has_titles'] = true; // for plugin backward compatibility check 267cbb44eabSAndreas Gohr return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup'); 2686840140fSChris Smith} 2696840140fSChris Smith 27042ea7f44SGerrit Uitslag/** 27142ea7f44SGerrit Uitslag * Returns list of pages as array(pageid => First Heading) 27242ea7f44SGerrit Uitslag * 27342ea7f44SGerrit Uitslag * @param array &$data event data 27442ea7f44SGerrit Uitslag * @return string[] 27542ea7f44SGerrit Uitslag */ 276d868eb89SAndreas Gohrfunction _ft_pageLookup(&$data) 277d868eb89SAndreas Gohr{ 27880423ab6SAdrian Lang // split out original parameters 2796840140fSChris Smith $id = $data['id']; 280940f24fcSMichael Große $Indexer = idx_get_indexer(); 281940f24fcSMichael Große $parsedQuery = ft_queryParser($Indexer, $id); 282940f24fcSMichael Große if (count($parsedQuery['ns']) > 0) { 283940f24fcSMichael Große $ns = cleanID($parsedQuery['ns'][0]) . ':'; 284940f24fcSMichael Große $id = implode(' ', $parsedQuery['highlight']); 285b0f6db0cSAdrian Lang } 286248d652bSGerrit Uitslag if (count($parsedQuery['notns']) > 0) { 287248d652bSGerrit Uitslag $notns = cleanID($parsedQuery['notns'][0]) . ':'; 288248d652bSGerrit Uitslag $id = implode(' ', $parsedQuery['highlight']); 289248d652bSGerrit Uitslag } 290b0f6db0cSAdrian Lang 2918d22f1e9SAndreas Gohr $in_ns = $data['in_ns']; 2928d22f1e9SAndreas Gohr $in_title = $data['in_title']; 29380423ab6SAdrian Lang $cleaned = cleanID($id); 2949b41be24STom N Harris 2959b41be24STom N Harris $Indexer = idx_get_indexer(); 2969b41be24STom N Harris $page_idx = $Indexer->getPages(); 2979b41be24STom N Harris 29824870174SAndreas Gohr $pages = []; 2995479a8c3SAndreas Gohr if ($id !== '' && $cleaned !== '') { 3009b41be24STom N Harris foreach ($page_idx as $p_id) { 3019b41be24STom N Harris if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) { 3029b41be24STom N Harris if (!isset($pages[$p_id])) 30367c15eceSMichael Hamann $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 304506fa893SAndreas Gohr } 305506fa893SAndreas Gohr } 306f078bb00STom N Harris if ($in_title) { 307c66f16a3SMichael Hamann foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) { 308f078bb00STom N Harris if (!isset($pages[$p_id])) 30967c15eceSMichael Hamann $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 310f078bb00STom N Harris } 311f078bb00STom N Harris } 312d0bdf765SAdrian Lang } 3130c074a52SMichael Hamann 314d0bdf765SAdrian Lang if (isset($ns)) { 3150c074a52SMichael Hamann foreach (array_keys($pages) as $p_id) { 3160c074a52SMichael Hamann if (strpos($p_id, $ns) !== 0) { 3170c074a52SMichael Hamann unset($pages[$p_id]); 318d0bdf765SAdrian Lang } 319d0bdf765SAdrian Lang } 320506fa893SAndreas Gohr } 321248d652bSGerrit Uitslag if (isset($notns)) { 322248d652bSGerrit Uitslag foreach (array_keys($pages) as $p_id) { 323248d652bSGerrit Uitslag if (strpos($p_id, $notns) === 0) { 324248d652bSGerrit Uitslag unset($pages[$p_id]); 325248d652bSGerrit Uitslag } 326248d652bSGerrit Uitslag } 327248d652bSGerrit Uitslag } 32863773904SAndreas Gohr 32980423ab6SAdrian Lang // discard hidden pages 33080423ab6SAdrian Lang // discard nonexistent pages 33163773904SAndreas Gohr // check ACL permissions 33263773904SAndreas Gohr foreach (array_keys($pages) as $idx) { 3337d34963bSAndreas Gohr if ( 3347d34963bSAndreas Gohr !isVisiblePage($idx) || !page_exists($idx) || 3357d34963bSAndreas Gohr auth_quickaclcheck($idx) < AUTH_READ 3367d34963bSAndreas Gohr ) { 33763773904SAndreas Gohr unset($pages[$idx]); 33863773904SAndreas Gohr } 33963773904SAndreas Gohr } 34063773904SAndreas Gohr 3413850270cSMichael Große $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']); 3421b48999cSMichael Große 3433d2017d9SAdrian Lang uksort($pages, 'ft_pagesorter'); 3448d22f1e9SAndreas Gohr return $pages; 345506fa893SAndreas Gohr} 346506fa893SAndreas Gohr 3471b48999cSMichael Große 3481b48999cSMichael Große/** 3491b48999cSMichael Große * @param array $results search results in the form pageid => value 35064159a61SAndreas Gohr * @param int|string $after only returns results with mtime after this date, accepts timestap or strtotime arguments 35164159a61SAndreas Gohr * @param int|string $before only returns results with mtime after this date, accepts timestap or strtotime arguments 3521b48999cSMichael Große * 3531b48999cSMichael Große * @return array 3541b48999cSMichael Große */ 355d868eb89SAndreas Gohrfunction _ft_filterResultsByTime(array $results, $after, $before) 356d868eb89SAndreas Gohr{ 3573850270cSMichael Große if ($after || $before) { 3581b48999cSMichael Große $after = is_int($after) ? $after : strtotime($after); 3591b48999cSMichael Große $before = is_int($before) ? $before : strtotime($before); 3601b48999cSMichael Große 36124870174SAndreas Gohr foreach (array_keys($results) as $id) { 3621b48999cSMichael Große $mTime = filemtime(wikiFN($id)); 3631b48999cSMichael Große if ($after && $after > $mTime) { 3641b48999cSMichael Große unset($results[$id]); 3651b48999cSMichael Große continue; 3661b48999cSMichael Große } 3671b48999cSMichael Große if ($before && $before < $mTime) { 3681b48999cSMichael Große unset($results[$id]); 3691b48999cSMichael Große } 3701b48999cSMichael Große } 3711b48999cSMichael Große } 3721b48999cSMichael Große 3731b48999cSMichael Große return $results; 3741b48999cSMichael Große} 3751b48999cSMichael Große 376506fa893SAndreas Gohr/** 377c66f16a3SMichael Hamann * Tiny helper function for comparing the searched title with the title 378c66f16a3SMichael Hamann * from the search index. This function is a wrapper around stripos with 379c66f16a3SMichael Hamann * adapted argument order and return value. 38042ea7f44SGerrit Uitslag * 38142ea7f44SGerrit Uitslag * @param string $search searched title 38242ea7f44SGerrit Uitslag * @param string $title title from index 38342ea7f44SGerrit Uitslag * @return bool 384c66f16a3SMichael Hamann */ 385d868eb89SAndreas Gohrfunction _ft_pageLookupTitleCompare($search, $title) 386d868eb89SAndreas Gohr{ 3877fb26b8eSAndreas Gohr if (Clean::isASCII($search)) { 3887fb26b8eSAndreas Gohr $pos = stripos($title, $search); 3897fb26b8eSAndreas Gohr } else { 3907fb26b8eSAndreas Gohr $pos = PhpString::strpos( 3917fb26b8eSAndreas Gohr PhpString::strtolower($title), 3927fb26b8eSAndreas Gohr PhpString::strtolower($search) 3937fb26b8eSAndreas Gohr ); 3947fb26b8eSAndreas Gohr } 3957fb26b8eSAndreas Gohr 3967fb26b8eSAndreas Gohr return $pos !== false; 397c66f16a3SMichael Hamann} 398c66f16a3SMichael Hamann 399c66f16a3SMichael Hamann/** 400f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string 401f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy 402f31eb72bSAndreas Gohr * pages. 40342ea7f44SGerrit Uitslag * 40442ea7f44SGerrit Uitslag * @param string $a 40542ea7f44SGerrit Uitslag * @param string $b 40642ea7f44SGerrit Uitslag * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal. 407f31eb72bSAndreas Gohr */ 408d868eb89SAndreas Gohrfunction ft_pagesorter($a, $b) 409d868eb89SAndreas Gohr{ 410f31eb72bSAndreas Gohr $ac = count(explode(':', $a)); 411f31eb72bSAndreas Gohr $bc = count(explode(':', $b)); 412f31eb72bSAndreas Gohr if ($ac < $bc) { 413f31eb72bSAndreas Gohr return -1; 414f31eb72bSAndreas Gohr } elseif ($ac > $bc) { 415f31eb72bSAndreas Gohr return 1; 416f31eb72bSAndreas Gohr } 4172d85e841SAndreas Gohr return Sort::strcmp($a, $b); 418f31eb72bSAndreas Gohr} 419f31eb72bSAndreas Gohr 420f31eb72bSAndreas Gohr/** 4218d0e286aSMichael Große * Sort pages by their mtime, from newest to oldest 4228d0e286aSMichael Große * 4238d0e286aSMichael Große * @param string $a 4248d0e286aSMichael Große * @param string $b 4258d0e286aSMichael Große * 4268d0e286aSMichael 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 4278d0e286aSMichael Große */ 428d868eb89SAndreas Gohrfunction ft_pagemtimesorter($a, $b) 429d868eb89SAndreas Gohr{ 4308d0e286aSMichael Große $mtimeA = filemtime(wikiFN($a)); 4318d0e286aSMichael Große $mtimeB = filemtime(wikiFN($b)); 4328d0e286aSMichael Große return $mtimeB - $mtimeA; 4338d0e286aSMichael Große} 4348d0e286aSMichael Große 4358d0e286aSMichael Große/** 436506fa893SAndreas Gohr * Creates a snippet extract 437506fa893SAndreas Gohr * 438506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 43960e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE 44042ea7f44SGerrit Uitslag * 44142ea7f44SGerrit Uitslag * @param string $id page id 44242ea7f44SGerrit Uitslag * @param array $highlight 44342ea7f44SGerrit Uitslag * @return mixed 444506fa893SAndreas Gohr */ 445d868eb89SAndreas Gohrfunction ft_snippet($id, $highlight) 446d868eb89SAndreas Gohr{ 447506fa893SAndreas Gohr $text = rawWiki($id); 44824870174SAndreas Gohr $text = str_replace("\xC2\xAD", '', $text); 44924870174SAndreas Gohr // remove soft-hyphens 45024870174SAndreas Gohr $evdata = [ 45160e91a17SAndreas Gohr 'id' => $id, 45260e91a17SAndreas Gohr 'text' => &$text, 45360e91a17SAndreas Gohr 'highlight' => &$highlight, 45424870174SAndreas Gohr 'snippet' => '' 45524870174SAndreas Gohr ]; 45660e91a17SAndreas Gohr 457e1d9dcc8SAndreas Gohr $evt = new Event('FULLTEXT_SNIPPET_CREATE', $evdata); 45860e91a17SAndreas Gohr if ($evt->advise_before()) { 45924870174SAndreas Gohr $match = []; 46024870174SAndreas Gohr $snippets = []; 46124870174SAndreas Gohr $utf8_offset = 0; 46224870174SAndreas Gohr $offset = 0; 46324870174SAndreas Gohr $end = 0; 4647fb26b8eSAndreas Gohr $len = PhpString::strlen($text); 4659ee93076Schris 466546d3a99SAndreas Gohr // build a regexp from the phrases to highlight 46764159a61SAndreas Gohr $re1 = '(' . 46824870174SAndreas Gohr implode( 46964159a61SAndreas Gohr '|', 47064159a61SAndreas Gohr array_map( 47164159a61SAndreas Gohr 'ft_snippet_re_preprocess', 47264159a61SAndreas Gohr array_map( 47364159a61SAndreas Gohr 'preg_quote_cb', 47464159a61SAndreas Gohr array_filter((array) $highlight) 47564159a61SAndreas Gohr ) 47664159a61SAndreas Gohr ) 47764159a61SAndreas Gohr ) . 47864159a61SAndreas Gohr ')'; 479b571ff2dSChuck Kollars $re2 = "$re1.{0,75}(?!\\1)$re1"; 480b571ff2dSChuck Kollars $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; 481546d3a99SAndreas Gohr 482b571ff2dSChuck Kollars for ($cnt = 4; $cnt--;) { 483b571ff2dSChuck Kollars if (0) { 484b571ff2dSChuck Kollars } elseif (preg_match('/' . $re3 . '/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) { 485b571ff2dSChuck Kollars } elseif (preg_match('/' . $re2 . '/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) { 486b571ff2dSChuck Kollars } elseif (preg_match('/' . $re1 . '/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) { 487b571ff2dSChuck Kollars } else { 488b571ff2dSChuck Kollars break; 489b571ff2dSChuck Kollars } 490ced0762eSchris 49124870174SAndreas Gohr [$str, $idx] = $match[0]; 492ced0762eSchris 493ced0762eSchris // convert $idx (a byte offset) into a utf8 character offset 4947fb26b8eSAndreas Gohr $utf8_idx = PhpString::strlen(substr($text, 0, $idx)); 4957fb26b8eSAndreas Gohr $utf8_len = PhpString::strlen($str); 496ced0762eSchris 497ced0762eSchris // establish context, 100 bytes surrounding the match string 498ced0762eSchris // first look to see if we can go 100 either side, 499ced0762eSchris // then drop to 50 adding any excess if the other side can't go to 50, 500ced0762eSchris $pre = min($utf8_idx - $utf8_offset, 100); 501ced0762eSchris $post = min($len - $utf8_idx - $utf8_len, 100); 502ced0762eSchris 503ced0762eSchris if ($pre > 50 && $post > 50) { 50424870174SAndreas Gohr $pre = 50; 50524870174SAndreas Gohr $post = 50; 506ced0762eSchris } elseif ($pre > 50) { 507ced0762eSchris $pre = min($pre, 100 - $post); 508ced0762eSchris } elseif ($post > 50) { 509ced0762eSchris $post = min($post, 100 - $pre); 510ef3e3cddSMichael Hamann } elseif ($offset == 0) { 511ced0762eSchris // both are less than 50, means the context is the whole string 51210ffc9ddSAndreas Gohr // make it so and break out of this loop - there is no need for the 51310ffc9ddSAndreas Gohr // complex snippet calculations 51424870174SAndreas Gohr $snippets = [$text]; 515ced0762eSchris break; 516ced0762eSchris } 517ced0762eSchris 51810ffc9ddSAndreas Gohr // establish context start and end points, try to append to previous 51910ffc9ddSAndreas Gohr // context if possible 5209ee93076Schris $start = $utf8_idx - $pre; 521ced0762eSchris $append = ($start < $end) ? $end : false; // still the end of the previous context snippet 5229ee93076Schris $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context 523ced0762eSchris 524ced0762eSchris if ($append) { 5257fb26b8eSAndreas Gohr $snippets[count($snippets) - 1] .= PhpString::substr($text, $append, $end - $append); 526ced0762eSchris } else { 5277fb26b8eSAndreas Gohr $snippets[] = PhpString::substr($text, $start, $end - $start); 528ced0762eSchris } 529ced0762eSchris 530ced0762eSchris // set $offset for next match attempt 53143d58b76SMichael Hamann // continue matching after the current match 53243d58b76SMichael Hamann // if the current match is not the longest possible match starting at the current offset 53343d58b76SMichael Hamann // this prevents further matching of this snippet but for possible matches of length 53443d58b76SMichael Hamann // smaller than match length + context (at least 50 characters) this match is part of the context 53543d58b76SMichael Hamann $utf8_offset = $utf8_idx + $utf8_len; 5367fb26b8eSAndreas Gohr $offset = $idx + strlen(PhpString::substr($text, $utf8_idx, $utf8_len)); 5377fb26b8eSAndreas Gohr $offset = Clean::correctIdx($text, $offset); 5389ee93076Schris } 5399ee93076Schris 540ced0762eSchris $m = "\1"; 541b571ff2dSChuck Kollars $snippets = preg_replace('/' . $re1 . '/iu', $m . '$1' . $m, $snippets); 54264159a61SAndreas Gohr $snippet = preg_replace( 54364159a61SAndreas Gohr '/' . $m . '([^' . $m . ']*?)' . $m . '/iu', 54464159a61SAndreas Gohr '<strong class="search_hit">$1</strong>', 54524870174SAndreas Gohr hsc(implode('... ', $snippets)) 54664159a61SAndreas Gohr ); 547bd2cb6fcSchris 54860e91a17SAndreas Gohr $evdata['snippet'] = $snippet; 54960e91a17SAndreas Gohr } 55060e91a17SAndreas Gohr $evt->advise_after(); 55160e91a17SAndreas Gohr unset($evt); 55260e91a17SAndreas Gohr 55360e91a17SAndreas Gohr return $evdata['snippet']; 554506fa893SAndreas Gohr} 555506fa893SAndreas Gohr 556506fa893SAndreas Gohr/** 55726eb848cSGina Haeussge * Wraps a search term in regex boundary checks. 55842ea7f44SGerrit Uitslag * 55942ea7f44SGerrit Uitslag * @param string $term 56042ea7f44SGerrit Uitslag * @return string 56126eb848cSGina Haeussge */ 562d868eb89SAndreas Gohrfunction ft_snippet_re_preprocess($term) 563d868eb89SAndreas Gohr{ 56435594613SKazutaka Miyasaka // do not process asian terms where word boundaries are not explicit 56524870174SAndreas Gohr if (Asian::isAsianWords($term)) return $term; 56635594613SKazutaka Miyasaka 5673161005dSAndreas Gohr if (UTF8_PROPERTYSUPPORT) { 56884e581a6SAndreas Gohr // unicode word boundaries 56984e581a6SAndreas Gohr // see http://stackoverflow.com/a/2449017/172068 57084e581a6SAndreas Gohr $BL = '(?<!\pL)'; 57184e581a6SAndreas Gohr $BR = '(?!\pL)'; 5723161005dSAndreas Gohr } else { 5733161005dSAndreas Gohr // not as correct as above, but at least won't break 5743161005dSAndreas Gohr $BL = '\b'; 5753161005dSAndreas Gohr $BR = '\b'; 5763161005dSAndreas Gohr } 5773161005dSAndreas Gohr 578*6c16a3a9Sfiwswe if (str_starts_with($term, '\\*')) { 5792237b4faSAndreas Gohr $term = substr($term, 2); 5802237b4faSAndreas Gohr } else { 58184e581a6SAndreas Gohr $term = $BL . $term; 5822237b4faSAndreas Gohr } 5832237b4faSAndreas Gohr 584*6c16a3a9Sfiwswe if (str_ends_with($term, '\\*')) { 5852237b4faSAndreas Gohr $term = substr($term, 0, -2); 5862237b4faSAndreas Gohr } else { 58724870174SAndreas Gohr $term .= $BR; 5882237b4faSAndreas Gohr } 5898a803caeSAndreas Gohr 59084e581a6SAndreas Gohr if ($term == $BL || $term == $BR || $term == $BL . $BR) $term = ''; 5912237b4faSAndreas Gohr return $term; 59226eb848cSGina Haeussge} 59326eb848cSGina Haeussge 59426eb848cSGina Haeussge/** 595f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores 596f5eb7cf0SAndreas Gohr * 597f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical 598f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned. 599f5eb7cf0SAndreas Gohr * 600f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key() 601f5eb7cf0SAndreas Gohr * 602f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays 60342ea7f44SGerrit Uitslag * @return array 604f5eb7cf0SAndreas Gohr */ 605d868eb89SAndreas Gohrfunction ft_resultCombine($args) 606d868eb89SAndreas Gohr{ 607f5eb7cf0SAndreas Gohr $array_count = count($args); 608134f4ab2SAndreas Gohr if ($array_count == 1) { 609134f4ab2SAndreas Gohr return $args[0]; 610134f4ab2SAndreas Gohr } 611134f4ab2SAndreas Gohr 61224870174SAndreas Gohr $result = []; 61309c27a6dSGuy Brand if ($array_count > 1) { 614a21136cdSAndreas Gohr foreach ($args[0] as $key => $value) { 615a21136cdSAndreas Gohr $result[$key] = $value; 616f5eb7cf0SAndreas Gohr for ($i = 1; $i !== $array_count; $i++) { 617a21136cdSAndreas Gohr if (!isset($args[$i][$key])) { 618a21136cdSAndreas Gohr unset($result[$key]); 619a21136cdSAndreas Gohr break; 620f5eb7cf0SAndreas Gohr } 621a21136cdSAndreas Gohr $result[$key] += $args[$i][$key]; 622f5eb7cf0SAndreas Gohr } 623f5eb7cf0SAndreas Gohr } 62409c27a6dSGuy Brand } 625f5eb7cf0SAndreas Gohr return $result; 626f5eb7cf0SAndreas Gohr} 627f5eb7cf0SAndreas Gohr 628f5eb7cf0SAndreas Gohr/** 629865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores 630f5eb7cf0SAndreas Gohr * 631865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function 632865c2687SKazutaka Miyasaka * 633865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 63442ea7f44SGerrit Uitslag * @return array 63542ea7f44SGerrit Uitslag * 636865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 637865c2687SKazutaka Miyasaka */ 638d868eb89SAndreas Gohrfunction ft_resultUnite($args) 639d868eb89SAndreas Gohr{ 640865c2687SKazutaka Miyasaka $array_count = count($args); 641865c2687SKazutaka Miyasaka if ($array_count === 1) { 642865c2687SKazutaka Miyasaka return $args[0]; 643865c2687SKazutaka Miyasaka } 644865c2687SKazutaka Miyasaka 645865c2687SKazutaka Miyasaka $result = $args[0]; 646865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 647865c2687SKazutaka Miyasaka foreach (array_keys($args[$i]) as $id) { 648865c2687SKazutaka Miyasaka $result[$id] += $args[$i][$id]; 649865c2687SKazutaka Miyasaka } 650865c2687SKazutaka Miyasaka } 651865c2687SKazutaka Miyasaka return $result; 652865c2687SKazutaka Miyasaka} 653865c2687SKazutaka Miyasaka 654865c2687SKazutaka Miyasaka/** 655865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison 656865c2687SKazutaka Miyasaka * 657865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key() 658865c2687SKazutaka Miyasaka * 659865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 66042ea7f44SGerrit Uitslag * @return array 66142ea7f44SGerrit Uitslag * 662865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 663865c2687SKazutaka Miyasaka */ 664d868eb89SAndreas Gohrfunction ft_resultComplement($args) 665d868eb89SAndreas Gohr{ 666865c2687SKazutaka Miyasaka $array_count = count($args); 667865c2687SKazutaka Miyasaka if ($array_count === 1) { 668865c2687SKazutaka Miyasaka return $args[0]; 669865c2687SKazutaka Miyasaka } 670865c2687SKazutaka Miyasaka 671865c2687SKazutaka Miyasaka $result = $args[0]; 672865c2687SKazutaka Miyasaka foreach (array_keys($result) as $id) { 673865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 674865c2687SKazutaka Miyasaka if (isset($args[$i][$id])) unset($result[$id]); 675865c2687SKazutaka Miyasaka } 676865c2687SKazutaka Miyasaka } 677865c2687SKazutaka Miyasaka return $result; 678865c2687SKazutaka Miyasaka} 679865c2687SKazutaka Miyasaka 680865c2687SKazutaka Miyasaka/** 681865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas 682865c2687SKazutaka Miyasaka * 683865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 684865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 68542ea7f44SGerrit Uitslag * 68624870174SAndreas Gohr * @param Indexer $Indexer 68742ea7f44SGerrit Uitslag * @param string $query search query 68842ea7f44SGerrit Uitslag * @return array of search formulas 689f5eb7cf0SAndreas Gohr */ 690d868eb89SAndreas Gohrfunction ft_queryParser($Indexer, $query) 691d868eb89SAndreas Gohr{ 692865c2687SKazutaka Miyasaka /** 693865c2687SKazutaka Miyasaka * parse a search query and transform it into intermediate representation 694865c2687SKazutaka Miyasaka * 695865c2687SKazutaka Miyasaka * in a search query, you can use the following expressions: 696865c2687SKazutaka Miyasaka * 697865c2687SKazutaka Miyasaka * words: 698865c2687SKazutaka Miyasaka * include 699865c2687SKazutaka Miyasaka * -exclude 700865c2687SKazutaka Miyasaka * phrases: 701865c2687SKazutaka Miyasaka * "phrase to be included" 702865c2687SKazutaka Miyasaka * -"phrase you want to exclude" 703865c2687SKazutaka Miyasaka * namespaces: 704865c2687SKazutaka Miyasaka * @include:namespace (or ns:include:namespace) 705865c2687SKazutaka Miyasaka * ^exclude:namespace (or -ns:exclude:namespace) 706865c2687SKazutaka Miyasaka * groups: 707865c2687SKazutaka Miyasaka * () 708865c2687SKazutaka Miyasaka * -() 709865c2687SKazutaka Miyasaka * operators: 710865c2687SKazutaka Miyasaka * and ('and' is the default operator: you can always omit this) 7117871d415SKazutaka Miyasaka * or (or pipe symbol '|', lower precedence than 'and') 712865c2687SKazutaka Miyasaka * 713865c2687SKazutaka Miyasaka * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain 714865c2687SKazutaka Miyasaka * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". 715865c2687SKazutaka Miyasaka * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] 716865c2687SKazutaka Miyasaka * as long as you don't mind hit counts. 717865c2687SKazutaka Miyasaka * 718865c2687SKazutaka Miyasaka * intermediate representation consists of the following parts: 719865c2687SKazutaka Miyasaka * 720865c2687SKazutaka Miyasaka * ( ) - group 721865c2687SKazutaka Miyasaka * AND - logical and 722865c2687SKazutaka Miyasaka * OR - logical or 723865c2687SKazutaka Miyasaka * NOT - logical not 7242f502d70SKazutaka Miyasaka * W+:, W-:, W_: - word (underscore: no need to highlight) 7252f502d70SKazutaka Miyasaka * P+:, P-: - phrase (minus sign: logically in NOT group) 7262f502d70SKazutaka Miyasaka * N+:, N-: - namespace 727865c2687SKazutaka Miyasaka */ 728865c2687SKazutaka Miyasaka $parsed_query = ''; 729865c2687SKazutaka Miyasaka $parens_level = 0; 730dccd6b2bSAndreas Gohr $terms = preg_split( 731dccd6b2bSAndreas Gohr '/(-?".*?")/u', 732dccd6b2bSAndreas Gohr PhpString::strtolower($query), 733dccd6b2bSAndreas Gohr -1, 734dccd6b2bSAndreas Gohr PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY 735dccd6b2bSAndreas Gohr ); 736865c2687SKazutaka Miyasaka 737865c2687SKazutaka Miyasaka foreach ($terms as $term) { 738865c2687SKazutaka Miyasaka $parsed = ''; 739865c2687SKazutaka Miyasaka if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { 740865c2687SKazutaka Miyasaka // phrase-include and phrase-exclude 741865c2687SKazutaka Miyasaka $not = $matches[1] ? 'NOT' : ''; 7429b41be24STom N Harris $parsed = $not . ft_termParser($Indexer, $matches[2], false, true); 743f5eb7cf0SAndreas Gohr } else { 744865c2687SKazutaka Miyasaka // fix incomplete phrase 745865c2687SKazutaka Miyasaka $term = str_replace('"', ' ', $term); 746865c2687SKazutaka Miyasaka 747865c2687SKazutaka Miyasaka // fix parentheses 748865c2687SKazutaka Miyasaka $term = str_replace(')', ' ) ', $term); 749865c2687SKazutaka Miyasaka $term = str_replace('(', ' ( ', $term); 750865c2687SKazutaka Miyasaka $term = str_replace('- (', ' -(', $term); 751865c2687SKazutaka Miyasaka 7527871d415SKazutaka Miyasaka // treat pipe symbols as 'OR' operators 7537871d415SKazutaka Miyasaka $term = str_replace('|', ' or ', $term); 7547871d415SKazutaka Miyasaka 755865c2687SKazutaka Miyasaka // treat ideographic spaces (U+3000) as search term separators 756865c2687SKazutaka Miyasaka // FIXME: some more separators? 757865c2687SKazutaka Miyasaka $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); 758865c2687SKazutaka Miyasaka $term = trim($term); 759865c2687SKazutaka Miyasaka if ($term === '') continue; 760865c2687SKazutaka Miyasaka 761865c2687SKazutaka Miyasaka $tokens = explode(' ', $term); 762865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 763865c2687SKazutaka Miyasaka if ($token === '(') { 764865c2687SKazutaka Miyasaka // parenthesis-include-open 765865c2687SKazutaka Miyasaka $parsed .= '('; 766865c2687SKazutaka Miyasaka ++$parens_level; 767865c2687SKazutaka Miyasaka } elseif ($token === '-(') { 768865c2687SKazutaka Miyasaka // parenthesis-exclude-open 769865c2687SKazutaka Miyasaka $parsed .= 'NOT('; 770865c2687SKazutaka Miyasaka ++$parens_level; 771865c2687SKazutaka Miyasaka } elseif ($token === ')') { 772865c2687SKazutaka Miyasaka // parenthesis-any-close 773865c2687SKazutaka Miyasaka if ($parens_level === 0) continue; 774865c2687SKazutaka Miyasaka $parsed .= ')'; 775865c2687SKazutaka Miyasaka $parens_level--; 776865c2687SKazutaka Miyasaka } elseif ($token === 'and') { 777865c2687SKazutaka Miyasaka // logical-and (do nothing) 778865c2687SKazutaka Miyasaka } elseif ($token === 'or') { 779865c2687SKazutaka Miyasaka // logical-or 780865c2687SKazutaka Miyasaka $parsed .= 'OR'; 781865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { 782865c2687SKazutaka Miyasaka // namespace-exclude 7832f502d70SKazutaka Miyasaka $parsed .= 'NOT(N+:' . $matches[1] . ')'; 784865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { 785865c2687SKazutaka Miyasaka // namespace-include 7862f502d70SKazutaka Miyasaka $parsed .= '(N+:' . $matches[1] . ')'; 787865c2687SKazutaka Miyasaka } elseif (preg_match('/^-(.+)$/', $token, $matches)) { 788865c2687SKazutaka Miyasaka // word-exclude 7899b41be24STom N Harris $parsed .= 'NOT(' . ft_termParser($Indexer, $matches[1]) . ')'; 790865c2687SKazutaka Miyasaka } else { 791865c2687SKazutaka Miyasaka // word-include 7929b41be24STom N Harris $parsed .= ft_termParser($Indexer, $token); 793865c2687SKazutaka Miyasaka } 794865c2687SKazutaka Miyasaka } 795865c2687SKazutaka Miyasaka } 796865c2687SKazutaka Miyasaka $parsed_query .= $parsed; 797f5eb7cf0SAndreas Gohr } 798f5eb7cf0SAndreas Gohr 799865c2687SKazutaka Miyasaka // cleanup (very sensitive) 800865c2687SKazutaka Miyasaka $parsed_query .= str_repeat(')', $parens_level); 801865c2687SKazutaka Miyasaka do { 802865c2687SKazutaka Miyasaka $parsed_query_old = $parsed_query; 803865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); 804865c2687SKazutaka Miyasaka } while ($parsed_query !== $parsed_query_old); 805865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')', $parsed_query); 806865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(OR)+/u', 'OR', $parsed_query); 807865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\(OR/u', '(', $parsed_query); 808865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/^OR|OR$/u', '', $parsed_query); 809865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\)(NOT)?\(/u', ')AND$1(', $parsed_query); 810865c2687SKazutaka Miyasaka 8112f502d70SKazutaka Miyasaka // adjustment: make highlightings right 8122f502d70SKazutaka Miyasaka $parens_level = 0; 81324870174SAndreas Gohr $notgrp_levels = []; 8142f502d70SKazutaka Miyasaka $parsed_query_new = ''; 8152f502d70SKazutaka Miyasaka $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 8162f502d70SKazutaka Miyasaka foreach ($tokens as $token) { 8172f502d70SKazutaka Miyasaka if ($token === 'NOT(') { 8182f502d70SKazutaka Miyasaka $notgrp_levels[] = ++$parens_level; 8192f502d70SKazutaka Miyasaka } elseif ($token === '(') { 8202f502d70SKazutaka Miyasaka ++$parens_level; 8212f502d70SKazutaka Miyasaka } elseif ($token === ')') { 8222f502d70SKazutaka Miyasaka if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels); 8232f502d70SKazutaka Miyasaka } elseif (count($notgrp_levels) % 2 === 1) { 8242f502d70SKazutaka Miyasaka // turn highlight-flag off if terms are logically in "NOT" group 8252f502d70SKazutaka Miyasaka $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token); 8262f502d70SKazutaka Miyasaka } 8272f502d70SKazutaka Miyasaka $parsed_query_new .= $token; 8282f502d70SKazutaka Miyasaka } 8292f502d70SKazutaka Miyasaka $parsed_query = $parsed_query_new; 8302f502d70SKazutaka Miyasaka 831865c2687SKazutaka Miyasaka /** 832865c2687SKazutaka Miyasaka * convert infix notation string into postfix (Reverse Polish notation) array 833865c2687SKazutaka Miyasaka * by Shunting-yard algorithm 834865c2687SKazutaka Miyasaka * 835865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation 836865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm 837865c2687SKazutaka Miyasaka */ 83824870174SAndreas Gohr $parsed_ary = []; 83924870174SAndreas Gohr $ope_stack = []; 84024870174SAndreas Gohr $ope_precedence = [')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5]; 841865c2687SKazutaka Miyasaka $ope_regex = '/([()]|OR|AND|NOT)/u'; 842865c2687SKazutaka Miyasaka 843865c2687SKazutaka Miyasaka $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 844865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 845865c2687SKazutaka Miyasaka if (preg_match($ope_regex, $token)) { 846865c2687SKazutaka Miyasaka // operator 847865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 84867d812e0SMarius van Witzenburg while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { 849865c2687SKazutaka Miyasaka $parsed_ary[] = array_pop($ope_stack); 850865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 851865c2687SKazutaka Miyasaka } 852865c2687SKazutaka Miyasaka if ($token == ')') { 853865c2687SKazutaka Miyasaka array_pop($ope_stack); // this array_pop always deletes '(' 854865c2687SKazutaka Miyasaka } else { 855865c2687SKazutaka Miyasaka $ope_stack[] = $token; 856865c2687SKazutaka Miyasaka } 857865c2687SKazutaka Miyasaka } else { 858865c2687SKazutaka Miyasaka // operand 85924870174SAndreas Gohr $token_decoded = str_replace(['OP', 'CP'], ['(', ')'], $token); 860865c2687SKazutaka Miyasaka $parsed_ary[] = $token_decoded; 861865c2687SKazutaka Miyasaka } 862865c2687SKazutaka Miyasaka } 86324870174SAndreas Gohr $parsed_ary = array_values([...$parsed_ary, ...array_reverse($ope_stack)]); 864865c2687SKazutaka Miyasaka 865865c2687SKazutaka Miyasaka // cleanup: each double "NOT" in RPN array actually does nothing 866865c2687SKazutaka Miyasaka $parsed_ary_count = count($parsed_ary); 867865c2687SKazutaka Miyasaka for ($i = 1; $i < $parsed_ary_count; ++$i) { 868865c2687SKazutaka Miyasaka if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { 869865c2687SKazutaka Miyasaka unset($parsed_ary[$i], $parsed_ary[$i - 1]); 870865c2687SKazutaka Miyasaka } 871865c2687SKazutaka Miyasaka } 872865c2687SKazutaka Miyasaka $parsed_ary = array_values($parsed_ary); 873865c2687SKazutaka Miyasaka 874865c2687SKazutaka Miyasaka // build return value 87524870174SAndreas Gohr $q = []; 876f5eb7cf0SAndreas Gohr $q['query'] = $query; 877865c2687SKazutaka Miyasaka $q['parsed_str'] = $parsed_query; 878865c2687SKazutaka Miyasaka $q['parsed_ary'] = $parsed_ary; 879f5eb7cf0SAndreas Gohr 880865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 88140f2b82eSAndreas Gohr if (strlen($token) < 3 || $token[2] !== ':') continue; 882865c2687SKazutaka Miyasaka $body = substr($token, 3); 883865c2687SKazutaka Miyasaka 884865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 8852f502d70SKazutaka Miyasaka case 'N+:': 886865c2687SKazutaka Miyasaka $q['ns'][] = $body; // for backward compatibility 887865c2687SKazutaka Miyasaka break; 8882f502d70SKazutaka Miyasaka case 'N-:': 8892f502d70SKazutaka Miyasaka $q['notns'][] = $body; // for backward compatibility 8902f502d70SKazutaka Miyasaka break; 8912f502d70SKazutaka Miyasaka case 'W_:': 8922f502d70SKazutaka Miyasaka $q['words'][] = $body; 8932f502d70SKazutaka Miyasaka break; 894865c2687SKazutaka Miyasaka case 'W-:': 895865c2687SKazutaka Miyasaka $q['words'][] = $body; 8962f502d70SKazutaka Miyasaka $q['not'][] = $body; // for backward compatibility 897865c2687SKazutaka Miyasaka break; 898865c2687SKazutaka Miyasaka case 'W+:': 899865c2687SKazutaka Miyasaka $q['words'][] = $body; 9002237b4faSAndreas Gohr $q['highlight'][] = $body; 9012f502d70SKazutaka Miyasaka $q['and'][] = $body; // for backward compatibility 902865c2687SKazutaka Miyasaka break; 9032f502d70SKazutaka Miyasaka case 'P-:': 9042f502d70SKazutaka Miyasaka $q['phrases'][] = $body; 9052f502d70SKazutaka Miyasaka break; 9062f502d70SKazutaka Miyasaka case 'P+:': 907865c2687SKazutaka Miyasaka $q['phrases'][] = $body; 9082237b4faSAndreas Gohr $q['highlight'][] = $body; 909865c2687SKazutaka Miyasaka break; 910865c2687SKazutaka Miyasaka } 911865c2687SKazutaka Miyasaka } 91224870174SAndreas Gohr foreach (['words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not'] as $key) { 91324870174SAndreas Gohr $q[$key] = empty($q[$key]) ? [] : array_values(array_unique($q[$key])); 914f5eb7cf0SAndreas Gohr } 915f5eb7cf0SAndreas Gohr 916f5eb7cf0SAndreas Gohr return $q; 917f5eb7cf0SAndreas Gohr} 918f5eb7cf0SAndreas Gohr 919865c2687SKazutaka Miyasaka/** 920865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation 921865c2687SKazutaka Miyasaka * 922865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use. 923865c2687SKazutaka Miyasaka * 924865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 92542ea7f44SGerrit Uitslag * 92624870174SAndreas Gohr * @param Indexer $Indexer 92742ea7f44SGerrit Uitslag * @param string $term 92842ea7f44SGerrit Uitslag * @param bool $consider_asian 92942ea7f44SGerrit Uitslag * @param bool $phrase_mode 93042ea7f44SGerrit Uitslag * @return string 931865c2687SKazutaka Miyasaka */ 932d868eb89SAndreas Gohrfunction ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) 933d868eb89SAndreas Gohr{ 934865c2687SKazutaka Miyasaka $parsed = ''; 935865c2687SKazutaka Miyasaka if ($consider_asian) { 936865c2687SKazutaka Miyasaka // successive asian characters need to be searched as a phrase 93724870174SAndreas Gohr $words = Asian::splitAsianWords($term); 938865c2687SKazutaka Miyasaka foreach ($words as $word) { 93924870174SAndreas Gohr $phrase_mode = $phrase_mode ? true : Asian::isAsianWords($word); 9409b41be24STom N Harris $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode); 941865c2687SKazutaka Miyasaka } 942865c2687SKazutaka Miyasaka } else { 94324870174SAndreas Gohr $term_noparen = str_replace(['(', ')'], ' ', $term); 9449b41be24STom N Harris $words = $Indexer->tokenizer($term_noparen, true); 945865c2687SKazutaka Miyasaka 9462f502d70SKazutaka Miyasaka // W_: no need to highlight 947865c2687SKazutaka Miyasaka if (empty($words)) { 948865c2687SKazutaka Miyasaka $parsed = '()'; // important: do not remove 949865c2687SKazutaka Miyasaka } elseif ($words[0] === $term) { 950865c2687SKazutaka Miyasaka $parsed = '(W+:' . $words[0] . ')'; 951865c2687SKazutaka Miyasaka } elseif ($phrase_mode) { 95224870174SAndreas Gohr $term_encoded = str_replace(['(', ')'], ['OP', 'CP'], $term); 9532f502d70SKazutaka Miyasaka $parsed = '((W_:' . implode(')(W_:', $words) . ')(P+:' . $term_encoded . '))'; 954865c2687SKazutaka Miyasaka } else { 955865c2687SKazutaka Miyasaka $parsed = '((W+:' . implode(')(W+:', $words) . '))'; 956865c2687SKazutaka Miyasaka } 957865c2687SKazutaka Miyasaka } 958865c2687SKazutaka Miyasaka return $parsed; 959865c2687SKazutaka Miyasaka} 960865c2687SKazutaka Miyasaka 96144156e11SMichael Große/** 96244156e11SMichael Große * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches 96344156e11SMichael Große * 96444156e11SMichael Große * @param array $and 96544156e11SMichael Große * @param array $not 96644156e11SMichael Große * @param array $phrases 96744156e11SMichael Große * @param array $ns 96844156e11SMichael Große * @param array $notns 96944156e11SMichael Große * 97044156e11SMichael Große * @return string 97144156e11SMichael Große */ 972d868eb89SAndreas Gohrfunction ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) 973d868eb89SAndreas Gohr{ 97444156e11SMichael Große $query = implode(' ', $and); 97524870174SAndreas Gohr if ($not !== []) { 97644156e11SMichael Große $query .= ' -' . implode(' -', $not); 97744156e11SMichael Große } 97844156e11SMichael Große 97924870174SAndreas Gohr if ($phrases !== []) { 98044156e11SMichael Große $query .= ' "' . implode('" "', $phrases) . '"'; 98144156e11SMichael Große } 98244156e11SMichael Große 98324870174SAndreas Gohr if ($ns !== []) { 98444156e11SMichael Große $query .= ' @' . implode(' @', $ns); 98544156e11SMichael Große } 98644156e11SMichael Große 98724870174SAndreas Gohr if ($notns !== []) { 98844156e11SMichael Große $query .= ' ^' . implode(' ^', $notns); 98944156e11SMichael Große } 99044156e11SMichael Große 99144156e11SMichael Große return $query; 99244156e11SMichael Große} 99344156e11SMichael Große 994e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 : 995