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; 107fb26b8eSAndreas Gohruse dokuwiki\Utf8\Clean; 117fb26b8eSAndreas Gohruse dokuwiki\Utf8\PhpString; 122d85e841SAndreas Gohruse dokuwiki\Utf8\Sort; 13f5eb7cf0SAndreas Gohr 14bd0293e7SAndreas Gohr/** 15bd0293e7SAndreas Gohr * create snippets for the first few results only 16bd0293e7SAndreas Gohr */ 17bd0293e7SAndreas Gohrif(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15); 18f5eb7cf0SAndreas Gohr 19f5eb7cf0SAndreas Gohr/** 20f5eb7cf0SAndreas Gohr * The fulltext search 21f5eb7cf0SAndreas Gohr * 22f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query 23506fa893SAndreas Gohr * 246840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event() 256840140fSChris Smith * 2642ea7f44SGerrit Uitslag * @param string $query 2742ea7f44SGerrit Uitslag * @param array $highlight 283850270cSMichael Große * @param string $sort 2964159a61SAndreas Gohr * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 3064159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 313850270cSMichael Große * 3242ea7f44SGerrit Uitslag * @return array 33f5eb7cf0SAndreas Gohr */ 343850270cSMichael Großefunction ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){ 356840140fSChris Smith 363850270cSMichael Große if ($sort === null) { 373850270cSMichael Große $sort = 'hits'; 383850270cSMichael Große } 393850270cSMichael Große $data = [ 403850270cSMichael Große 'query' => $query, 413850270cSMichael Große 'sort' => $sort, 423850270cSMichael Große 'after' => $after, 433850270cSMichael Große 'before' => $before 443850270cSMichael Große ]; 456840140fSChris Smith $data['highlight'] =& $highlight; 466840140fSChris Smith 47cbb44eabSAndreas Gohr return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch'); 486840140fSChris Smith} 49865c2687SKazutaka Miyasaka 50865c2687SKazutaka Miyasaka/** 51865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query 52865c2687SKazutaka Miyasaka * 53865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 54865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 5542ea7f44SGerrit Uitslag * 5642ea7f44SGerrit Uitslag * @param array $data event data 5742ea7f44SGerrit Uitslag * @return array matching documents 58865c2687SKazutaka Miyasaka */ 596840140fSChris Smithfunction _ft_pageSearch(&$data) { 609b41be24STom N Harris $Indexer = idx_get_indexer(); 619b41be24STom N Harris 62865c2687SKazutaka Miyasaka // parse the given query 639b41be24STom N Harris $q = ft_queryParser($Indexer, $data['query']); 64865c2687SKazutaka Miyasaka $data['highlight'] = $q['highlight']; 656840140fSChris Smith 66865c2687SKazutaka Miyasaka if (empty($q['parsed_ary'])) return array(); 67506fa893SAndreas Gohr 68f5eb7cf0SAndreas Gohr // lookup all words found in the query 699b41be24STom N Harris $lookup = $Indexer->lookup($q['words']); 70f5eb7cf0SAndreas Gohr 71865c2687SKazutaka Miyasaka // get all pages in this dokuwiki site (!: includes nonexistent pages) 72865c2687SKazutaka Miyasaka $pages_all = array(); 739b41be24STom N Harris foreach ($Indexer->getPages() as $id) { 749b41be24STom N Harris $pages_all[$id] = 0; // base: 0 hit 75f5eb7cf0SAndreas Gohr } 76f5eb7cf0SAndreas Gohr 77865c2687SKazutaka Miyasaka // process the query 78865c2687SKazutaka Miyasaka $stack = array(); 79865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 80865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 81865c2687SKazutaka Miyasaka case 'W+:': 822f502d70SKazutaka Miyasaka case 'W-:': 832f502d70SKazutaka Miyasaka case 'W_:': // word 84865c2687SKazutaka Miyasaka $word = substr($token, 3); 855afd9580SAndreas Gohr if(isset($lookup[$word])) { 86865c2687SKazutaka Miyasaka $stack[] = (array)$lookup[$word]; 875afd9580SAndreas Gohr } 88865c2687SKazutaka Miyasaka break; 892f502d70SKazutaka Miyasaka case 'P+:': 902f502d70SKazutaka Miyasaka case 'P-:': // phrase 91865c2687SKazutaka Miyasaka $phrase = substr($token, 3); 92865c2687SKazutaka Miyasaka // since phrases are always parsed as ((W1)(W2)...(P)), 93865c2687SKazutaka Miyasaka // the end($stack) always points the pages that contain 94865c2687SKazutaka Miyasaka // all words in this phrase 95865c2687SKazutaka Miyasaka $pages = end($stack); 96865c2687SKazutaka Miyasaka $pages_matched = array(); 97865c2687SKazutaka Miyasaka foreach(array_keys($pages) as $id){ 98a7e8b43eSMichael Hamann $evdata = array( 99a7e8b43eSMichael Hamann 'id' => $id, 100a7e8b43eSMichael Hamann 'phrase' => $phrase, 101a7e8b43eSMichael Hamann 'text' => rawWiki($id) 102a7e8b43eSMichael Hamann ); 103e1d9dcc8SAndreas Gohr $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata); 104a7e8b43eSMichael Hamann if ($evt->advise_before() && $evt->result !== true) { 1057fb26b8eSAndreas Gohr $text = PhpString::strtolower($evdata['text']); 106865c2687SKazutaka Miyasaka if (strpos($text, $phrase) !== false) { 107a7e8b43eSMichael Hamann $evt->result = true; 108a7e8b43eSMichael Hamann } 109a7e8b43eSMichael Hamann } 110a7e8b43eSMichael Hamann $evt->advise_after(); 111a7e8b43eSMichael Hamann if ($evt->result === true) { 112865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // phrase: always 0 hit 113865c2687SKazutaka Miyasaka } 114865c2687SKazutaka Miyasaka } 115865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 116865c2687SKazutaka Miyasaka break; 1172f502d70SKazutaka Miyasaka case 'N+:': 1182f502d70SKazutaka Miyasaka case 'N-:': // namespace 119de3383c6SMichael Große $ns = cleanID(substr($token, 3)) . ':'; 120865c2687SKazutaka Miyasaka $pages_matched = array(); 121865c2687SKazutaka Miyasaka foreach (array_keys($pages_all) as $id) { 122865c2687SKazutaka Miyasaka if (strpos($id, $ns) === 0) { 123865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // namespace: always 0 hit 124865c2687SKazutaka Miyasaka } 125865c2687SKazutaka Miyasaka } 126865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 127865c2687SKazutaka Miyasaka break; 128865c2687SKazutaka Miyasaka case 'AND': // and operation 129865c2687SKazutaka Miyasaka list($pages1, $pages2) = array_splice($stack, -2); 130865c2687SKazutaka Miyasaka $stack[] = ft_resultCombine(array($pages1, $pages2)); 131865c2687SKazutaka Miyasaka break; 132865c2687SKazutaka Miyasaka case 'OR': // or operation 133865c2687SKazutaka Miyasaka list($pages1, $pages2) = array_splice($stack, -2); 134865c2687SKazutaka Miyasaka $stack[] = ft_resultUnite(array($pages1, $pages2)); 135865c2687SKazutaka Miyasaka break; 136865c2687SKazutaka Miyasaka case 'NOT': // not operation (unary) 137865c2687SKazutaka Miyasaka $pages = array_pop($stack); 138865c2687SKazutaka Miyasaka $stack[] = ft_resultComplement(array($pages_all, $pages)); 139a21136cdSAndreas Gohr break; 140a21136cdSAndreas Gohr } 141f5eb7cf0SAndreas Gohr } 142865c2687SKazutaka Miyasaka $docs = array_pop($stack); 143865c2687SKazutaka Miyasaka 144865c2687SKazutaka Miyasaka if (empty($docs)) return array(); 145865c2687SKazutaka Miyasaka 146865c2687SKazutaka Miyasaka // check: settings, acls, existence 147865c2687SKazutaka Miyasaka foreach (array_keys($docs) as $id) { 148865c2687SKazutaka Miyasaka if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) { 149865c2687SKazutaka Miyasaka unset($docs[$id]); 150f5eb7cf0SAndreas Gohr } 151f5eb7cf0SAndreas Gohr } 152f5eb7cf0SAndreas Gohr 1533850270cSMichael Große $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']); 1548d0e286aSMichael Große 1558d0e286aSMichael Große if ($data['sort'] === 'mtime') { 1568d0e286aSMichael Große uksort($docs, 'ft_pagemtimesorter'); 1578d0e286aSMichael Große } else { 158865c2687SKazutaka Miyasaka // sort docs by count 15906281c9cSMoisés Braga Ribeiro uksort($docs, 'ft_pagesorter'); 160f5eb7cf0SAndreas Gohr arsort($docs); 1618d0e286aSMichael Große } 162f5eb7cf0SAndreas Gohr 163f5eb7cf0SAndreas Gohr return $docs; 164f5eb7cf0SAndreas Gohr} 165f5eb7cf0SAndreas Gohr 166f5eb7cf0SAndreas Gohr/** 16754f4c056SAndreas Gohr * Returns the backlinks for a given page 16854f4c056SAndreas Gohr * 169320f489aSMichael Hamann * Uses the metadata index. 17007ff0babSMichael Hamann * 17107ff0babSMichael Hamann * @param string $id The id for which links shall be returned 17207ff0babSMichael Hamann * @param bool $ignore_perms Ignore the fact that pages are hidden or read-protected 17307ff0babSMichael Hamann * @return array The pages that contain links to the given page 17454f4c056SAndreas Gohr */ 17507ff0babSMichael Hamannfunction ft_backlinks($id, $ignore_perms = false){ 176320f489aSMichael Hamann $result = idx_get_indexer()->lookupKey('relation_references', $id); 17754f4c056SAndreas Gohr 17863773904SAndreas Gohr if(!count($result)) return $result; 17963773904SAndreas Gohr 18063773904SAndreas Gohr // check ACL permissions 18163773904SAndreas Gohr foreach(array_keys($result) as $idx){ 18207ff0babSMichael Hamann if(($ignore_perms !== true && ( 18307ff0babSMichael Hamann isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 18407ff0babSMichael Hamann )) || !page_exists($result[$idx], '', false)){ 18563773904SAndreas Gohr unset($result[$idx]); 18663773904SAndreas Gohr } 18763773904SAndreas Gohr } 18863773904SAndreas Gohr 1892d85e841SAndreas Gohr Sort::sort($result); 19054f4c056SAndreas Gohr return $result; 19154f4c056SAndreas Gohr} 19254f4c056SAndreas Gohr 19354f4c056SAndreas Gohr/** 194a05e297aSAndreas Gohr * Returns the pages that use a given media file 195a05e297aSAndreas Gohr * 196ffec1009SMichael Hamann * Uses the relation media metadata property and the metadata index. 197a05e297aSAndreas Gohr * 198ffec1009SMichael Hamann * Note that before 2013-07-31 the second parameter was the maximum number of results and 199ffec1009SMichael Hamann * permissions were ignored. That's why the parameter is now checked to be explicitely set 200ffec1009SMichael Hamann * to true (with type bool) in order to be compatible with older uses of the function. 201ffec1009SMichael Hamann * 202ffec1009SMichael Hamann * @param string $id The media id to look for 203ffec1009SMichael Hamann * @param bool $ignore_perms Ignore hidden pages and acls (optional, default: false) 204ffec1009SMichael Hamann * @return array A list of pages that use the given media file 205a05e297aSAndreas Gohr */ 206ffec1009SMichael Hamannfunction ft_mediause($id, $ignore_perms = false){ 207ffec1009SMichael Hamann $result = idx_get_indexer()->lookupKey('relation_media', $id); 208a05e297aSAndreas Gohr 209ffec1009SMichael Hamann if(!count($result)) return $result; 210a05e297aSAndreas Gohr 211ffec1009SMichael Hamann // check ACL permissions 212ffec1009SMichael Hamann foreach(array_keys($result) as $idx){ 213ffec1009SMichael Hamann if(($ignore_perms !== true && ( 214ffec1009SMichael Hamann isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 215ffec1009SMichael Hamann )) || !page_exists($result[$idx], '', false)){ 216ffec1009SMichael Hamann unset($result[$idx]); 217a05e297aSAndreas Gohr } 218a05e297aSAndreas Gohr } 219a05e297aSAndreas Gohr 2202d85e841SAndreas Gohr Sort::sort($result); 221a05e297aSAndreas Gohr return $result; 222a05e297aSAndreas Gohr} 223a05e297aSAndreas Gohr 224a05e297aSAndreas Gohr 225a05e297aSAndreas Gohr/** 226506fa893SAndreas Gohr * Quicksearch for pagenames 227506fa893SAndreas Gohr * 228506fa893SAndreas Gohr * By default it only matches the pagename and ignores the 22980423ab6SAdrian Lang * namespace. This can be changed with the second parameter. 23080423ab6SAdrian Lang * The third parameter allows to search in titles as well. 231506fa893SAndreas Gohr * 2328d22f1e9SAndreas Gohr * The function always returns titles as well 2336840140fSChris Smith * 2348d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP 235506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 2368d22f1e9SAndreas Gohr * @author Adrian Lang <lang@cosmocode.de> 23742ea7f44SGerrit Uitslag * 23842ea7f44SGerrit Uitslag * @param string $id page id 23942ea7f44SGerrit Uitslag * @param bool $in_ns match against namespace as well? 24042ea7f44SGerrit Uitslag * @param bool $in_title search in title? 24164159a61SAndreas Gohr * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 24264159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 2433850270cSMichael Große * 24442ea7f44SGerrit Uitslag * @return string[] 245506fa893SAndreas Gohr */ 2463850270cSMichael Großefunction ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){ 2473850270cSMichael Große $data = [ 2483850270cSMichael Große 'id' => $id, 2493850270cSMichael Große 'in_ns' => $in_ns, 2503850270cSMichael Große 'in_title' => $in_title, 2513850270cSMichael Große 'after' => $after, 2523850270cSMichael Große 'before' => $before 2533850270cSMichael Große ]; 2548d22f1e9SAndreas Gohr $data['has_titles'] = true; // for plugin backward compatibility check 255cbb44eabSAndreas Gohr return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup'); 2566840140fSChris Smith} 2576840140fSChris Smith 25842ea7f44SGerrit Uitslag/** 25942ea7f44SGerrit Uitslag * Returns list of pages as array(pageid => First Heading) 26042ea7f44SGerrit Uitslag * 26142ea7f44SGerrit Uitslag * @param array &$data event data 26242ea7f44SGerrit Uitslag * @return string[] 26342ea7f44SGerrit Uitslag */ 2646840140fSChris Smithfunction _ft_pageLookup(&$data){ 26580423ab6SAdrian Lang // split out original parameters 2666840140fSChris Smith $id = $data['id']; 267940f24fcSMichael Große $Indexer = idx_get_indexer(); 268940f24fcSMichael Große $parsedQuery = ft_queryParser($Indexer, $id); 269940f24fcSMichael Große if (count($parsedQuery['ns']) > 0) { 270940f24fcSMichael Große $ns = cleanID($parsedQuery['ns'][0]) . ':'; 271940f24fcSMichael Große $id = implode(' ', $parsedQuery['highlight']); 272b0f6db0cSAdrian Lang } 273248d652bSGerrit Uitslag if (count($parsedQuery['notns']) > 0) { 274248d652bSGerrit Uitslag $notns = cleanID($parsedQuery['notns'][0]) . ':'; 275248d652bSGerrit Uitslag $id = implode(' ', $parsedQuery['highlight']); 276248d652bSGerrit Uitslag } 277b0f6db0cSAdrian Lang 2788d22f1e9SAndreas Gohr $in_ns = $data['in_ns']; 2798d22f1e9SAndreas Gohr $in_title = $data['in_title']; 28080423ab6SAdrian Lang $cleaned = cleanID($id); 2819b41be24STom N Harris 2829b41be24STom N Harris $Indexer = idx_get_indexer(); 2839b41be24STom N Harris $page_idx = $Indexer->getPages(); 2849b41be24STom N Harris 2859b41be24STom N Harris $pages = array(); 2865479a8c3SAndreas Gohr if ($id !== '' && $cleaned !== '') { 2879b41be24STom N Harris foreach ($page_idx as $p_id) { 2889b41be24STom N Harris if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) { 2899b41be24STom N Harris if (!isset($pages[$p_id])) 29067c15eceSMichael Hamann $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 291506fa893SAndreas Gohr } 292506fa893SAndreas Gohr } 293f078bb00STom N Harris if ($in_title) { 294c66f16a3SMichael Hamann foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) { 295f078bb00STom N Harris if (!isset($pages[$p_id])) 29667c15eceSMichael Hamann $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 297f078bb00STom N Harris } 298f078bb00STom N Harris } 299d0bdf765SAdrian Lang } 3000c074a52SMichael Hamann 301d0bdf765SAdrian Lang if (isset($ns)) { 3020c074a52SMichael Hamann foreach (array_keys($pages) as $p_id) { 3030c074a52SMichael Hamann if (strpos($p_id, $ns) !== 0) { 3040c074a52SMichael Hamann unset($pages[$p_id]); 305d0bdf765SAdrian Lang } 306d0bdf765SAdrian Lang } 307506fa893SAndreas Gohr } 308248d652bSGerrit Uitslag if (isset($notns)) { 309248d652bSGerrit Uitslag foreach (array_keys($pages) as $p_id) { 310248d652bSGerrit Uitslag if (strpos($p_id, $notns) === 0) { 311248d652bSGerrit Uitslag unset($pages[$p_id]); 312248d652bSGerrit Uitslag } 313248d652bSGerrit Uitslag } 314248d652bSGerrit Uitslag } 31563773904SAndreas Gohr 31680423ab6SAdrian Lang // discard hidden pages 31780423ab6SAdrian Lang // discard nonexistent pages 31863773904SAndreas Gohr // check ACL permissions 31963773904SAndreas Gohr foreach(array_keys($pages) as $idx){ 32080423ab6SAdrian Lang if(!isVisiblePage($idx) || !page_exists($idx) || 32180423ab6SAdrian Lang auth_quickaclcheck($idx) < AUTH_READ) { 32263773904SAndreas Gohr unset($pages[$idx]); 32363773904SAndreas Gohr } 32463773904SAndreas Gohr } 32563773904SAndreas Gohr 3263850270cSMichael Große $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']); 3271b48999cSMichael Große 3283d2017d9SAdrian Lang uksort($pages,'ft_pagesorter'); 3298d22f1e9SAndreas Gohr return $pages; 330506fa893SAndreas Gohr} 331506fa893SAndreas Gohr 3321b48999cSMichael Große 3331b48999cSMichael Große/** 3341b48999cSMichael Große * @param array $results search results in the form pageid => value 33564159a61SAndreas Gohr * @param int|string $after only returns results with mtime after this date, accepts timestap or strtotime arguments 33664159a61SAndreas Gohr * @param int|string $before only returns results with mtime after this date, accepts timestap or strtotime arguments 3371b48999cSMichael Große * 3381b48999cSMichael Große * @return array 3391b48999cSMichael Große */ 3403850270cSMichael Großefunction _ft_filterResultsByTime(array $results, $after, $before) { 3413850270cSMichael Große if ($after || $before) { 3421b48999cSMichael Große $after = is_int($after) ? $after : strtotime($after); 3431b48999cSMichael Große $before = is_int($before) ? $before : strtotime($before); 3441b48999cSMichael Große 3451b48999cSMichael Große foreach ($results as $id => $value) { 3461b48999cSMichael Große $mTime = filemtime(wikiFN($id)); 3471b48999cSMichael Große if ($after && $after > $mTime) { 3481b48999cSMichael Große unset($results[$id]); 3491b48999cSMichael Große continue; 3501b48999cSMichael Große } 3511b48999cSMichael Große if ($before && $before < $mTime) { 3521b48999cSMichael Große unset($results[$id]); 3531b48999cSMichael Große } 3541b48999cSMichael Große } 3551b48999cSMichael Große } 3561b48999cSMichael Große 3571b48999cSMichael Große return $results; 3581b48999cSMichael Große} 3591b48999cSMichael Große 360506fa893SAndreas Gohr/** 361c66f16a3SMichael Hamann * Tiny helper function for comparing the searched title with the title 362c66f16a3SMichael Hamann * from the search index. This function is a wrapper around stripos with 363c66f16a3SMichael Hamann * adapted argument order and return value. 36442ea7f44SGerrit Uitslag * 36542ea7f44SGerrit Uitslag * @param string $search searched title 36642ea7f44SGerrit Uitslag * @param string $title title from index 36742ea7f44SGerrit Uitslag * @return bool 368c66f16a3SMichael Hamann */ 369c66f16a3SMichael Hamannfunction _ft_pageLookupTitleCompare($search, $title) { 3707fb26b8eSAndreas Gohr if (Clean::isASCII($search)) { 3717fb26b8eSAndreas Gohr $pos = stripos($title, $search); 3727fb26b8eSAndreas Gohr } else { 3737fb26b8eSAndreas Gohr $pos = PhpString::strpos( 3747fb26b8eSAndreas Gohr PhpString::strtolower($title), 3757fb26b8eSAndreas Gohr PhpString::strtolower($search) 3767fb26b8eSAndreas Gohr ); 3777fb26b8eSAndreas Gohr } 3787fb26b8eSAndreas Gohr 3797fb26b8eSAndreas Gohr return $pos !== false; 380c66f16a3SMichael Hamann} 381c66f16a3SMichael Hamann 382c66f16a3SMichael Hamann/** 383f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string 384f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy 385f31eb72bSAndreas Gohr * pages. 38642ea7f44SGerrit Uitslag * 38742ea7f44SGerrit Uitslag * @param string $a 38842ea7f44SGerrit Uitslag * @param string $b 38942ea7f44SGerrit Uitslag * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal. 390f31eb72bSAndreas Gohr */ 391f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){ 392f31eb72bSAndreas Gohr $ac = count(explode(':',$a)); 393f31eb72bSAndreas Gohr $bc = count(explode(':',$b)); 394f31eb72bSAndreas Gohr if($ac < $bc){ 395f31eb72bSAndreas Gohr return -1; 396f31eb72bSAndreas Gohr }elseif($ac > $bc){ 397f31eb72bSAndreas Gohr return 1; 398f31eb72bSAndreas Gohr } 3992d85e841SAndreas Gohr return Sort::strcmp($a,$b); 400f31eb72bSAndreas Gohr} 401f31eb72bSAndreas Gohr 402f31eb72bSAndreas Gohr/** 4038d0e286aSMichael Große * Sort pages by their mtime, from newest to oldest 4048d0e286aSMichael Große * 4058d0e286aSMichael Große * @param string $a 4068d0e286aSMichael Große * @param string $b 4078d0e286aSMichael Große * 4088d0e286aSMichael 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 4098d0e286aSMichael Große */ 4108d0e286aSMichael Großefunction ft_pagemtimesorter($a, $b) { 4118d0e286aSMichael Große $mtimeA = filemtime(wikiFN($a)); 4128d0e286aSMichael Große $mtimeB = filemtime(wikiFN($b)); 4138d0e286aSMichael Große return $mtimeB - $mtimeA; 4148d0e286aSMichael Große} 4158d0e286aSMichael Große 4168d0e286aSMichael Große/** 417506fa893SAndreas Gohr * Creates a snippet extract 418506fa893SAndreas Gohr * 419506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 42060e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE 42142ea7f44SGerrit Uitslag * 42242ea7f44SGerrit Uitslag * @param string $id page id 42342ea7f44SGerrit Uitslag * @param array $highlight 42442ea7f44SGerrit Uitslag * @return mixed 425506fa893SAndreas Gohr */ 426546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){ 427506fa893SAndreas Gohr $text = rawWiki($id); 4284f0030ddSAndreas Gohr $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens 42960e91a17SAndreas Gohr $evdata = array( 43060e91a17SAndreas Gohr 'id' => $id, 43160e91a17SAndreas Gohr 'text' => &$text, 43260e91a17SAndreas Gohr 'highlight' => &$highlight, 43360e91a17SAndreas Gohr 'snippet' => '', 43460e91a17SAndreas Gohr ); 43560e91a17SAndreas Gohr 436e1d9dcc8SAndreas Gohr $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata); 43760e91a17SAndreas Gohr if ($evt->advise_before()) { 438ced0762eSchris $match = array(); 439ced0762eSchris $snippets = array(); 4409ee93076Schris $utf8_offset = $offset = $end = 0; 4417fb26b8eSAndreas Gohr $len = PhpString::strlen($text); 4429ee93076Schris 443546d3a99SAndreas Gohr // build a regexp from the phrases to highlight 44464159a61SAndreas Gohr $re1 = '(' . 44564159a61SAndreas Gohr join( 44664159a61SAndreas Gohr '|', 44764159a61SAndreas Gohr array_map( 44864159a61SAndreas Gohr 'ft_snippet_re_preprocess', 44964159a61SAndreas Gohr array_map( 45064159a61SAndreas Gohr 'preg_quote_cb', 45164159a61SAndreas Gohr array_filter((array) $highlight) 45264159a61SAndreas Gohr ) 45364159a61SAndreas Gohr ) 45464159a61SAndreas Gohr ) . 45564159a61SAndreas Gohr ')'; 456b571ff2dSChuck Kollars $re2 = "$re1.{0,75}(?!\\1)$re1"; 457b571ff2dSChuck Kollars $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; 458546d3a99SAndreas Gohr 459b571ff2dSChuck Kollars for ($cnt=4; $cnt--;) { 460b571ff2dSChuck Kollars if (0) { 461b571ff2dSChuck Kollars } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 462b571ff2dSChuck Kollars } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 463b571ff2dSChuck Kollars } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 464b571ff2dSChuck Kollars } else { 465b571ff2dSChuck Kollars break; 466b571ff2dSChuck Kollars } 467ced0762eSchris 468ced0762eSchris list($str,$idx) = $match[0]; 469ced0762eSchris 470ced0762eSchris // convert $idx (a byte offset) into a utf8 character offset 4717fb26b8eSAndreas Gohr $utf8_idx = PhpString::strlen(substr($text,0,$idx)); 4727fb26b8eSAndreas Gohr $utf8_len = PhpString::strlen($str); 473ced0762eSchris 474ced0762eSchris // establish context, 100 bytes surrounding the match string 475ced0762eSchris // first look to see if we can go 100 either side, 476ced0762eSchris // then drop to 50 adding any excess if the other side can't go to 50, 477ced0762eSchris $pre = min($utf8_idx-$utf8_offset,100); 478ced0762eSchris $post = min($len-$utf8_idx-$utf8_len,100); 479ced0762eSchris 480ced0762eSchris if ($pre>50 && $post>50) { 481ced0762eSchris $pre = $post = 50; 482ced0762eSchris } else if ($pre>50) { 483ced0762eSchris $pre = min($pre,100-$post); 484ced0762eSchris } else if ($post>50) { 485ced0762eSchris $post = min($post, 100-$pre); 486ef3e3cddSMichael Hamann } else if ($offset == 0) { 487ced0762eSchris // both are less than 50, means the context is the whole string 48810ffc9ddSAndreas Gohr // make it so and break out of this loop - there is no need for the 48910ffc9ddSAndreas Gohr // complex snippet calculations 490ced0762eSchris $snippets = array($text); 491ced0762eSchris break; 492ced0762eSchris } 493ced0762eSchris 49410ffc9ddSAndreas Gohr // establish context start and end points, try to append to previous 49510ffc9ddSAndreas Gohr // context if possible 4969ee93076Schris $start = $utf8_idx - $pre; 497ced0762eSchris $append = ($start < $end) ? $end : false; // still the end of the previous context snippet 4989ee93076Schris $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context 499ced0762eSchris 500ced0762eSchris if ($append) { 5017fb26b8eSAndreas Gohr $snippets[count($snippets)-1] .= PhpString::substr($text,$append,$end-$append); 502ced0762eSchris } else { 5037fb26b8eSAndreas Gohr $snippets[] = PhpString::substr($text,$start,$end-$start); 504ced0762eSchris } 505ced0762eSchris 506ced0762eSchris // set $offset for next match attempt 50743d58b76SMichael Hamann // continue matching after the current match 50843d58b76SMichael Hamann // if the current match is not the longest possible match starting at the current offset 50943d58b76SMichael Hamann // this prevents further matching of this snippet but for possible matches of length 51043d58b76SMichael Hamann // smaller than match length + context (at least 50 characters) this match is part of the context 51143d58b76SMichael Hamann $utf8_offset = $utf8_idx + $utf8_len; 5127fb26b8eSAndreas Gohr $offset = $idx + strlen(PhpString::substr($text,$utf8_idx,$utf8_len)); 5137fb26b8eSAndreas Gohr $offset = Clean::correctIdx($text,$offset); 5149ee93076Schris } 5159ee93076Schris 516ced0762eSchris $m = "\1"; 517b571ff2dSChuck Kollars $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets); 51864159a61SAndreas Gohr $snippet = preg_replace( 51964159a61SAndreas Gohr '/' . $m . '([^' . $m . ']*?)' . $m . '/iu', 52064159a61SAndreas Gohr '<strong class="search_hit">$1</strong>', 52164159a61SAndreas Gohr hsc(join('... ', $snippets)) 52264159a61SAndreas Gohr ); 523bd2cb6fcSchris 52460e91a17SAndreas Gohr $evdata['snippet'] = $snippet; 52560e91a17SAndreas Gohr } 52660e91a17SAndreas Gohr $evt->advise_after(); 52760e91a17SAndreas Gohr unset($evt); 52860e91a17SAndreas Gohr 52960e91a17SAndreas Gohr return $evdata['snippet']; 530506fa893SAndreas Gohr} 531506fa893SAndreas Gohr 532506fa893SAndreas Gohr/** 53326eb848cSGina Haeussge * Wraps a search term in regex boundary checks. 53442ea7f44SGerrit Uitslag * 53542ea7f44SGerrit Uitslag * @param string $term 53642ea7f44SGerrit Uitslag * @return string 53726eb848cSGina Haeussge */ 5382237b4faSAndreas Gohrfunction ft_snippet_re_preprocess($term) { 53935594613SKazutaka Miyasaka // do not process asian terms where word boundaries are not explicit 540dbc189b2SAndreas Gohr if(\dokuwiki\Utf8\Asian::isAsianWords($term)) return $term; 54135594613SKazutaka Miyasaka 5423161005dSAndreas Gohr if (UTF8_PROPERTYSUPPORT) { 54384e581a6SAndreas Gohr // unicode word boundaries 54484e581a6SAndreas Gohr // see http://stackoverflow.com/a/2449017/172068 54584e581a6SAndreas Gohr $BL = '(?<!\pL)'; 54684e581a6SAndreas Gohr $BR = '(?!\pL)'; 5473161005dSAndreas Gohr } else { 5483161005dSAndreas Gohr // not as correct as above, but at least won't break 5493161005dSAndreas Gohr $BL = '\b'; 5503161005dSAndreas Gohr $BR = '\b'; 5513161005dSAndreas Gohr } 5523161005dSAndreas Gohr 5532237b4faSAndreas Gohr if(substr($term,0,2) == '\\*'){ 5542237b4faSAndreas Gohr $term = substr($term,2); 5552237b4faSAndreas Gohr }else{ 55684e581a6SAndreas Gohr $term = $BL.$term; 5572237b4faSAndreas Gohr } 5582237b4faSAndreas Gohr 5592237b4faSAndreas Gohr if(substr($term,-2,2) == '\\*'){ 5602237b4faSAndreas Gohr $term = substr($term,0,-2); 5612237b4faSAndreas Gohr }else{ 56284e581a6SAndreas Gohr $term = $term.$BR; 5632237b4faSAndreas Gohr } 5648a803caeSAndreas Gohr 56584e581a6SAndreas Gohr if($term == $BL || $term == $BR || $term == $BL.$BR) $term = ''; 5662237b4faSAndreas Gohr return $term; 56726eb848cSGina Haeussge} 56826eb848cSGina Haeussge 56926eb848cSGina Haeussge/** 570f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores 571f5eb7cf0SAndreas Gohr * 572f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical 573f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned. 574f5eb7cf0SAndreas Gohr * 575f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key() 576f5eb7cf0SAndreas Gohr * 577f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays 57842ea7f44SGerrit Uitslag * @return array 579f5eb7cf0SAndreas Gohr */ 580f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){ 581f5eb7cf0SAndreas Gohr $array_count = count($args); 582134f4ab2SAndreas Gohr if($array_count == 1){ 583134f4ab2SAndreas Gohr return $args[0]; 584134f4ab2SAndreas Gohr } 585134f4ab2SAndreas Gohr 586f5eb7cf0SAndreas Gohr $result = array(); 58709c27a6dSGuy Brand if ($array_count > 1) { 588a21136cdSAndreas Gohr foreach ($args[0] as $key => $value) { 589a21136cdSAndreas Gohr $result[$key] = $value; 590f5eb7cf0SAndreas Gohr for ($i = 1; $i !== $array_count; $i++) { 591a21136cdSAndreas Gohr if (!isset($args[$i][$key])) { 592a21136cdSAndreas Gohr unset($result[$key]); 593a21136cdSAndreas Gohr break; 594f5eb7cf0SAndreas Gohr } 595a21136cdSAndreas Gohr $result[$key] += $args[$i][$key]; 596f5eb7cf0SAndreas Gohr } 597f5eb7cf0SAndreas Gohr } 59809c27a6dSGuy Brand } 599f5eb7cf0SAndreas Gohr return $result; 600f5eb7cf0SAndreas Gohr} 601f5eb7cf0SAndreas Gohr 602f5eb7cf0SAndreas Gohr/** 603865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores 604f5eb7cf0SAndreas Gohr * 605865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function 606865c2687SKazutaka Miyasaka * 607865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 60842ea7f44SGerrit Uitslag * @return array 60942ea7f44SGerrit Uitslag * 610865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 611865c2687SKazutaka Miyasaka */ 612865c2687SKazutaka Miyasakafunction ft_resultUnite($args) { 613865c2687SKazutaka Miyasaka $array_count = count($args); 614865c2687SKazutaka Miyasaka if ($array_count === 1) { 615865c2687SKazutaka Miyasaka return $args[0]; 616865c2687SKazutaka Miyasaka } 617865c2687SKazutaka Miyasaka 618865c2687SKazutaka Miyasaka $result = $args[0]; 619865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 620865c2687SKazutaka Miyasaka foreach (array_keys($args[$i]) as $id) { 621865c2687SKazutaka Miyasaka $result[$id] += $args[$i][$id]; 622865c2687SKazutaka Miyasaka } 623865c2687SKazutaka Miyasaka } 624865c2687SKazutaka Miyasaka return $result; 625865c2687SKazutaka Miyasaka} 626865c2687SKazutaka Miyasaka 627865c2687SKazutaka Miyasaka/** 628865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison 629865c2687SKazutaka Miyasaka * 630865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key() 631865c2687SKazutaka Miyasaka * 632865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 63342ea7f44SGerrit Uitslag * @return array 63442ea7f44SGerrit Uitslag * 635865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 636865c2687SKazutaka Miyasaka */ 637865c2687SKazutaka Miyasakafunction ft_resultComplement($args) { 638865c2687SKazutaka Miyasaka $array_count = count($args); 639865c2687SKazutaka Miyasaka if ($array_count === 1) { 640865c2687SKazutaka Miyasaka return $args[0]; 641865c2687SKazutaka Miyasaka } 642865c2687SKazutaka Miyasaka 643865c2687SKazutaka Miyasaka $result = $args[0]; 644865c2687SKazutaka Miyasaka foreach (array_keys($result) as $id) { 645865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 646865c2687SKazutaka Miyasaka if (isset($args[$i][$id])) unset($result[$id]); 647865c2687SKazutaka Miyasaka } 648865c2687SKazutaka Miyasaka } 649865c2687SKazutaka Miyasaka return $result; 650865c2687SKazutaka Miyasaka} 651865c2687SKazutaka Miyasaka 652865c2687SKazutaka Miyasaka/** 653865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas 654865c2687SKazutaka Miyasaka * 655865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 656865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 65742ea7f44SGerrit Uitslag * 6586225b270SMichael Große * @param dokuwiki\Search\Indexer $Indexer 65942ea7f44SGerrit Uitslag * @param string $query search query 66042ea7f44SGerrit Uitslag * @return array of search formulas 661f5eb7cf0SAndreas Gohr */ 6629b41be24STom N Harrisfunction ft_queryParser($Indexer, $query){ 663865c2687SKazutaka Miyasaka /** 664865c2687SKazutaka Miyasaka * parse a search query and transform it into intermediate representation 665865c2687SKazutaka Miyasaka * 666865c2687SKazutaka Miyasaka * in a search query, you can use the following expressions: 667865c2687SKazutaka Miyasaka * 668865c2687SKazutaka Miyasaka * words: 669865c2687SKazutaka Miyasaka * include 670865c2687SKazutaka Miyasaka * -exclude 671865c2687SKazutaka Miyasaka * phrases: 672865c2687SKazutaka Miyasaka * "phrase to be included" 673865c2687SKazutaka Miyasaka * -"phrase you want to exclude" 674865c2687SKazutaka Miyasaka * namespaces: 675865c2687SKazutaka Miyasaka * @include:namespace (or ns:include:namespace) 676865c2687SKazutaka Miyasaka * ^exclude:namespace (or -ns:exclude:namespace) 677865c2687SKazutaka Miyasaka * groups: 678865c2687SKazutaka Miyasaka * () 679865c2687SKazutaka Miyasaka * -() 680865c2687SKazutaka Miyasaka * operators: 681865c2687SKazutaka Miyasaka * and ('and' is the default operator: you can always omit this) 6827871d415SKazutaka Miyasaka * or (or pipe symbol '|', lower precedence than 'and') 683865c2687SKazutaka Miyasaka * 684865c2687SKazutaka Miyasaka * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain 685865c2687SKazutaka Miyasaka * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". 686865c2687SKazutaka Miyasaka * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] 687865c2687SKazutaka Miyasaka * as long as you don't mind hit counts. 688865c2687SKazutaka Miyasaka * 689865c2687SKazutaka Miyasaka * intermediate representation consists of the following parts: 690865c2687SKazutaka Miyasaka * 691865c2687SKazutaka Miyasaka * ( ) - group 692865c2687SKazutaka Miyasaka * AND - logical and 693865c2687SKazutaka Miyasaka * OR - logical or 694865c2687SKazutaka Miyasaka * NOT - logical not 6952f502d70SKazutaka Miyasaka * W+:, W-:, W_: - word (underscore: no need to highlight) 6962f502d70SKazutaka Miyasaka * P+:, P-: - phrase (minus sign: logically in NOT group) 6972f502d70SKazutaka Miyasaka * N+:, N-: - namespace 698865c2687SKazutaka Miyasaka */ 699865c2687SKazutaka Miyasaka $parsed_query = ''; 700865c2687SKazutaka Miyasaka $parens_level = 0; 7017fb26b8eSAndreas Gohr $terms = preg_split('/(-?".*?")/u', PhpString::strtolower($query), 7026ce3e5f8SAndreas Gohr -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 703865c2687SKazutaka Miyasaka 704865c2687SKazutaka Miyasaka foreach ($terms as $term) { 705865c2687SKazutaka Miyasaka $parsed = ''; 706865c2687SKazutaka Miyasaka if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { 707865c2687SKazutaka Miyasaka // phrase-include and phrase-exclude 708865c2687SKazutaka Miyasaka $not = $matches[1] ? 'NOT' : ''; 7099b41be24STom N Harris $parsed = $not.ft_termParser($Indexer, $matches[2], false, true); 710f5eb7cf0SAndreas Gohr } else { 711865c2687SKazutaka Miyasaka // fix incomplete phrase 712865c2687SKazutaka Miyasaka $term = str_replace('"', ' ', $term); 713865c2687SKazutaka Miyasaka 714865c2687SKazutaka Miyasaka // fix parentheses 715865c2687SKazutaka Miyasaka $term = str_replace(')' , ' ) ', $term); 716865c2687SKazutaka Miyasaka $term = str_replace('(' , ' ( ', $term); 717865c2687SKazutaka Miyasaka $term = str_replace('- (', ' -(', $term); 718865c2687SKazutaka Miyasaka 7197871d415SKazutaka Miyasaka // treat pipe symbols as 'OR' operators 7207871d415SKazutaka Miyasaka $term = str_replace('|', ' or ', $term); 7217871d415SKazutaka Miyasaka 722865c2687SKazutaka Miyasaka // treat ideographic spaces (U+3000) as search term separators 723865c2687SKazutaka Miyasaka // FIXME: some more separators? 724865c2687SKazutaka Miyasaka $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); 725865c2687SKazutaka Miyasaka $term = trim($term); 726865c2687SKazutaka Miyasaka if ($term === '') continue; 727865c2687SKazutaka Miyasaka 728865c2687SKazutaka Miyasaka $tokens = explode(' ', $term); 729865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 730865c2687SKazutaka Miyasaka if ($token === '(') { 731865c2687SKazutaka Miyasaka // parenthesis-include-open 732865c2687SKazutaka Miyasaka $parsed .= '('; 733865c2687SKazutaka Miyasaka ++$parens_level; 734865c2687SKazutaka Miyasaka } elseif ($token === '-(') { 735865c2687SKazutaka Miyasaka // parenthesis-exclude-open 736865c2687SKazutaka Miyasaka $parsed .= 'NOT('; 737865c2687SKazutaka Miyasaka ++$parens_level; 738865c2687SKazutaka Miyasaka } elseif ($token === ')') { 739865c2687SKazutaka Miyasaka // parenthesis-any-close 740865c2687SKazutaka Miyasaka if ($parens_level === 0) continue; 741865c2687SKazutaka Miyasaka $parsed .= ')'; 742865c2687SKazutaka Miyasaka $parens_level--; 743865c2687SKazutaka Miyasaka } elseif ($token === 'and') { 744865c2687SKazutaka Miyasaka // logical-and (do nothing) 745865c2687SKazutaka Miyasaka } elseif ($token === 'or') { 746865c2687SKazutaka Miyasaka // logical-or 747865c2687SKazutaka Miyasaka $parsed .= 'OR'; 748865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { 749865c2687SKazutaka Miyasaka // namespace-exclude 7502f502d70SKazutaka Miyasaka $parsed .= 'NOT(N+:'.$matches[1].')'; 751865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { 752865c2687SKazutaka Miyasaka // namespace-include 7532f502d70SKazutaka Miyasaka $parsed .= '(N+:'.$matches[1].')'; 754865c2687SKazutaka Miyasaka } elseif (preg_match('/^-(.+)$/', $token, $matches)) { 755865c2687SKazutaka Miyasaka // word-exclude 7569b41be24STom N Harris $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')'; 757865c2687SKazutaka Miyasaka } else { 758865c2687SKazutaka Miyasaka // word-include 7599b41be24STom N Harris $parsed .= ft_termParser($Indexer, $token); 760865c2687SKazutaka Miyasaka } 761865c2687SKazutaka Miyasaka } 762865c2687SKazutaka Miyasaka } 763865c2687SKazutaka Miyasaka $parsed_query .= $parsed; 764f5eb7cf0SAndreas Gohr } 765f5eb7cf0SAndreas Gohr 766865c2687SKazutaka Miyasaka // cleanup (very sensitive) 767865c2687SKazutaka Miyasaka $parsed_query .= str_repeat(')', $parens_level); 768865c2687SKazutaka Miyasaka do { 769865c2687SKazutaka Miyasaka $parsed_query_old = $parsed_query; 770865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); 771865c2687SKazutaka Miyasaka } while ($parsed_query !== $parsed_query_old); 772865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query); 773865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query); 774865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query); 775865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query); 776865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query); 777865c2687SKazutaka Miyasaka 7782f502d70SKazutaka Miyasaka // adjustment: make highlightings right 7792f502d70SKazutaka Miyasaka $parens_level = 0; 7802f502d70SKazutaka Miyasaka $notgrp_levels = array(); 7812f502d70SKazutaka Miyasaka $parsed_query_new = ''; 7822f502d70SKazutaka Miyasaka $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 7832f502d70SKazutaka Miyasaka foreach ($tokens as $token) { 7842f502d70SKazutaka Miyasaka if ($token === 'NOT(') { 7852f502d70SKazutaka Miyasaka $notgrp_levels[] = ++$parens_level; 7862f502d70SKazutaka Miyasaka } elseif ($token === '(') { 7872f502d70SKazutaka Miyasaka ++$parens_level; 7882f502d70SKazutaka Miyasaka } elseif ($token === ')') { 7892f502d70SKazutaka Miyasaka if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels); 7902f502d70SKazutaka Miyasaka } elseif (count($notgrp_levels) % 2 === 1) { 7912f502d70SKazutaka Miyasaka // turn highlight-flag off if terms are logically in "NOT" group 7922f502d70SKazutaka Miyasaka $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token); 7932f502d70SKazutaka Miyasaka } 7942f502d70SKazutaka Miyasaka $parsed_query_new .= $token; 7952f502d70SKazutaka Miyasaka } 7962f502d70SKazutaka Miyasaka $parsed_query = $parsed_query_new; 7972f502d70SKazutaka Miyasaka 798865c2687SKazutaka Miyasaka /** 799865c2687SKazutaka Miyasaka * convert infix notation string into postfix (Reverse Polish notation) array 800865c2687SKazutaka Miyasaka * by Shunting-yard algorithm 801865c2687SKazutaka Miyasaka * 802865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation 803865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm 804865c2687SKazutaka Miyasaka */ 805865c2687SKazutaka Miyasaka $parsed_ary = array(); 806865c2687SKazutaka Miyasaka $ope_stack = array(); 807865c2687SKazutaka Miyasaka $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5); 808865c2687SKazutaka Miyasaka $ope_regex = '/([()]|OR|AND|NOT)/u'; 809865c2687SKazutaka Miyasaka 810865c2687SKazutaka Miyasaka $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 811865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 812865c2687SKazutaka Miyasaka if (preg_match($ope_regex, $token)) { 813865c2687SKazutaka Miyasaka // operator 814865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 81567d812e0SMarius van Witzenburg while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { 816865c2687SKazutaka Miyasaka $parsed_ary[] = array_pop($ope_stack); 817865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 818865c2687SKazutaka Miyasaka } 819865c2687SKazutaka Miyasaka if ($token == ')') { 820865c2687SKazutaka Miyasaka array_pop($ope_stack); // this array_pop always deletes '(' 821865c2687SKazutaka Miyasaka } else { 822865c2687SKazutaka Miyasaka $ope_stack[] = $token; 823865c2687SKazutaka Miyasaka } 824865c2687SKazutaka Miyasaka } else { 825865c2687SKazutaka Miyasaka // operand 826865c2687SKazutaka Miyasaka $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token); 827865c2687SKazutaka Miyasaka $parsed_ary[] = $token_decoded; 828865c2687SKazutaka Miyasaka } 829865c2687SKazutaka Miyasaka } 830865c2687SKazutaka Miyasaka $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack))); 831865c2687SKazutaka Miyasaka 832865c2687SKazutaka Miyasaka // cleanup: each double "NOT" in RPN array actually does nothing 833865c2687SKazutaka Miyasaka $parsed_ary_count = count($parsed_ary); 834865c2687SKazutaka Miyasaka for ($i = 1; $i < $parsed_ary_count; ++$i) { 835865c2687SKazutaka Miyasaka if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { 836865c2687SKazutaka Miyasaka unset($parsed_ary[$i], $parsed_ary[$i - 1]); 837865c2687SKazutaka Miyasaka } 838865c2687SKazutaka Miyasaka } 839865c2687SKazutaka Miyasaka $parsed_ary = array_values($parsed_ary); 840865c2687SKazutaka Miyasaka 841865c2687SKazutaka Miyasaka // build return value 842f5eb7cf0SAndreas Gohr $q = array(); 843f5eb7cf0SAndreas Gohr $q['query'] = $query; 844865c2687SKazutaka Miyasaka $q['parsed_str'] = $parsed_query; 845865c2687SKazutaka Miyasaka $q['parsed_ary'] = $parsed_ary; 846f5eb7cf0SAndreas Gohr 847865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 848*40f2b82eSAndreas Gohr if (strlen($token) < 3 || $token[2] !== ':') continue; 849865c2687SKazutaka Miyasaka $body = substr($token, 3); 850865c2687SKazutaka Miyasaka 851865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 8522f502d70SKazutaka Miyasaka case 'N+:': 853865c2687SKazutaka Miyasaka $q['ns'][] = $body; // for backward compatibility 854865c2687SKazutaka Miyasaka break; 8552f502d70SKazutaka Miyasaka case 'N-:': 8562f502d70SKazutaka Miyasaka $q['notns'][] = $body; // for backward compatibility 8572f502d70SKazutaka Miyasaka break; 8582f502d70SKazutaka Miyasaka case 'W_:': 8592f502d70SKazutaka Miyasaka $q['words'][] = $body; 8602f502d70SKazutaka Miyasaka break; 861865c2687SKazutaka Miyasaka case 'W-:': 862865c2687SKazutaka Miyasaka $q['words'][] = $body; 8632f502d70SKazutaka Miyasaka $q['not'][] = $body; // for backward compatibility 864865c2687SKazutaka Miyasaka break; 865865c2687SKazutaka Miyasaka case 'W+:': 866865c2687SKazutaka Miyasaka $q['words'][] = $body; 8672237b4faSAndreas Gohr $q['highlight'][] = $body; 8682f502d70SKazutaka Miyasaka $q['and'][] = $body; // for backward compatibility 869865c2687SKazutaka Miyasaka break; 8702f502d70SKazutaka Miyasaka case 'P-:': 8712f502d70SKazutaka Miyasaka $q['phrases'][] = $body; 8722f502d70SKazutaka Miyasaka break; 8732f502d70SKazutaka Miyasaka case 'P+:': 874865c2687SKazutaka Miyasaka $q['phrases'][] = $body; 8752237b4faSAndreas Gohr $q['highlight'][] = $body; 876865c2687SKazutaka Miyasaka break; 877865c2687SKazutaka Miyasaka } 878865c2687SKazutaka Miyasaka } 8792f502d70SKazutaka Miyasaka foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) { 880865c2687SKazutaka Miyasaka $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key])); 881f5eb7cf0SAndreas Gohr } 882f5eb7cf0SAndreas Gohr 883f5eb7cf0SAndreas Gohr return $q; 884f5eb7cf0SAndreas Gohr} 885f5eb7cf0SAndreas Gohr 886865c2687SKazutaka Miyasaka/** 887865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation 888865c2687SKazutaka Miyasaka * 889865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use. 890865c2687SKazutaka Miyasaka * 891865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 89242ea7f44SGerrit Uitslag * 8936225b270SMichael Große * @param dokuwiki\Search\Indexer $Indexer 89442ea7f44SGerrit Uitslag * @param string $term 89542ea7f44SGerrit Uitslag * @param bool $consider_asian 89642ea7f44SGerrit Uitslag * @param bool $phrase_mode 89742ea7f44SGerrit Uitslag * @return string 898865c2687SKazutaka Miyasaka */ 8999b41be24STom N Harrisfunction ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) { 900865c2687SKazutaka Miyasaka $parsed = ''; 901865c2687SKazutaka Miyasaka if ($consider_asian) { 902865c2687SKazutaka Miyasaka // successive asian characters need to be searched as a phrase 903dbc189b2SAndreas Gohr $words = \dokuwiki\Utf8\Asian::splitAsianWords($term); 904865c2687SKazutaka Miyasaka foreach ($words as $word) { 905dbc189b2SAndreas Gohr $phrase_mode = $phrase_mode ? true : \dokuwiki\Utf8\Asian::isAsianWords($word); 9069b41be24STom N Harris $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode); 907865c2687SKazutaka Miyasaka } 908865c2687SKazutaka Miyasaka } else { 909865c2687SKazutaka Miyasaka $term_noparen = str_replace(array('(', ')'), ' ', $term); 9109b41be24STom N Harris $words = $Indexer->tokenizer($term_noparen, true); 911865c2687SKazutaka Miyasaka 9122f502d70SKazutaka Miyasaka // W_: no need to highlight 913865c2687SKazutaka Miyasaka if (empty($words)) { 914865c2687SKazutaka Miyasaka $parsed = '()'; // important: do not remove 915865c2687SKazutaka Miyasaka } elseif ($words[0] === $term) { 916865c2687SKazutaka Miyasaka $parsed = '(W+:'.$words[0].')'; 917865c2687SKazutaka Miyasaka } elseif ($phrase_mode) { 918865c2687SKazutaka Miyasaka $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term); 9192f502d70SKazutaka Miyasaka $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))'; 920865c2687SKazutaka Miyasaka } else { 921865c2687SKazutaka Miyasaka $parsed = '((W+:'.implode(')(W+:', $words).'))'; 922865c2687SKazutaka Miyasaka } 923865c2687SKazutaka Miyasaka } 924865c2687SKazutaka Miyasaka return $parsed; 925865c2687SKazutaka Miyasaka} 926865c2687SKazutaka Miyasaka 92744156e11SMichael Große/** 92844156e11SMichael Große * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches 92944156e11SMichael Große * 93044156e11SMichael Große * @param array $and 93144156e11SMichael Große * @param array $not 93244156e11SMichael Große * @param array $phrases 93344156e11SMichael Große * @param array $ns 93444156e11SMichael Große * @param array $notns 93544156e11SMichael Große * 93644156e11SMichael Große * @return string 93744156e11SMichael Große */ 93844156e11SMichael Großefunction ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) { 93944156e11SMichael Große $query = implode(' ', $and); 94044156e11SMichael Große if (!empty($not)) { 94144156e11SMichael Große $query .= ' -' . implode(' -', $not); 94244156e11SMichael Große } 94344156e11SMichael Große 94444156e11SMichael Große if (!empty($phrases)) { 94544156e11SMichael Große $query .= ' "' . implode('" "', $phrases) . '"'; 94644156e11SMichael Große } 94744156e11SMichael Große 94844156e11SMichael Große if (!empty($ns)) { 94944156e11SMichael Große $query .= ' @' . implode(' @', $ns); 95044156e11SMichael Große } 95144156e11SMichael Große 95244156e11SMichael Große if (!empty($notns)) { 95344156e11SMichael Große $query .= ' ^' . implode(' ^', $notns); 95444156e11SMichael Große } 95544156e11SMichael Große 95644156e11SMichael Große return $query; 95744156e11SMichael Große} 95844156e11SMichael Große 959e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 : 960