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; 10f5eb7cf0SAndreas Gohr 11bd0293e7SAndreas Gohr/** 12bd0293e7SAndreas Gohr * create snippets for the first few results only 13bd0293e7SAndreas Gohr */ 14bd0293e7SAndreas Gohrif(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15); 15f5eb7cf0SAndreas Gohr 16f5eb7cf0SAndreas Gohr/** 17f5eb7cf0SAndreas Gohr * The fulltext search 18f5eb7cf0SAndreas Gohr * 19f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query 20506fa893SAndreas Gohr * 216840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event() 226840140fSChris Smith * 2342ea7f44SGerrit Uitslag * @param string $query 2442ea7f44SGerrit Uitslag * @param array $highlight 253850270cSMichael Große * @param string $sort 2664159a61SAndreas Gohr * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 2764159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 283850270cSMichael Große * 2942ea7f44SGerrit Uitslag * @return array 30f5eb7cf0SAndreas Gohr */ 313850270cSMichael Großefunction ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){ 326840140fSChris Smith 333850270cSMichael Große if ($sort === null) { 343850270cSMichael Große $sort = 'hits'; 353850270cSMichael Große } 363850270cSMichael Große $data = [ 373850270cSMichael Große 'query' => $query, 383850270cSMichael Große 'sort' => $sort, 393850270cSMichael Große 'after' => $after, 403850270cSMichael Große 'before' => $before 413850270cSMichael Große ]; 426840140fSChris Smith $data['highlight'] =& $highlight; 436840140fSChris Smith 44cbb44eabSAndreas Gohr return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch'); 456840140fSChris Smith} 46865c2687SKazutaka Miyasaka 47865c2687SKazutaka Miyasaka/** 48865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query 49865c2687SKazutaka Miyasaka * 50865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 51865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 5242ea7f44SGerrit Uitslag * 5342ea7f44SGerrit Uitslag * @param array $data event data 5442ea7f44SGerrit Uitslag * @return array matching documents 55865c2687SKazutaka Miyasaka */ 566840140fSChris Smithfunction _ft_pageSearch(&$data) { 579b41be24STom N Harris $Indexer = idx_get_indexer(); 589b41be24STom N Harris 59865c2687SKazutaka Miyasaka // parse the given query 609b41be24STom N Harris $q = ft_queryParser($Indexer, $data['query']); 61865c2687SKazutaka Miyasaka $data['highlight'] = $q['highlight']; 626840140fSChris Smith 63865c2687SKazutaka Miyasaka if (empty($q['parsed_ary'])) return array(); 64506fa893SAndreas Gohr 65f5eb7cf0SAndreas Gohr // lookup all words found in the query 669b41be24STom N Harris $lookup = $Indexer->lookup($q['words']); 67f5eb7cf0SAndreas Gohr 68865c2687SKazutaka Miyasaka // get all pages in this dokuwiki site (!: includes nonexistent pages) 69865c2687SKazutaka Miyasaka $pages_all = array(); 709b41be24STom N Harris foreach ($Indexer->getPages() as $id) { 719b41be24STom N Harris $pages_all[$id] = 0; // base: 0 hit 72f5eb7cf0SAndreas Gohr } 73f5eb7cf0SAndreas Gohr 74865c2687SKazutaka Miyasaka // process the query 75865c2687SKazutaka Miyasaka $stack = array(); 76865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 77865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 78865c2687SKazutaka Miyasaka case 'W+:': 792f502d70SKazutaka Miyasaka case 'W-:': 802f502d70SKazutaka Miyasaka case 'W_:': // word 81865c2687SKazutaka Miyasaka $word = substr($token, 3); 82865c2687SKazutaka Miyasaka $stack[] = (array) $lookup[$word]; 83865c2687SKazutaka Miyasaka break; 842f502d70SKazutaka Miyasaka case 'P+:': 852f502d70SKazutaka Miyasaka case 'P-:': // phrase 86865c2687SKazutaka Miyasaka $phrase = substr($token, 3); 87865c2687SKazutaka Miyasaka // since phrases are always parsed as ((W1)(W2)...(P)), 88865c2687SKazutaka Miyasaka // the end($stack) always points the pages that contain 89865c2687SKazutaka Miyasaka // all words in this phrase 90865c2687SKazutaka Miyasaka $pages = end($stack); 91865c2687SKazutaka Miyasaka $pages_matched = array(); 92865c2687SKazutaka Miyasaka foreach(array_keys($pages) as $id){ 93a7e8b43eSMichael Hamann $evdata = array( 94a7e8b43eSMichael Hamann 'id' => $id, 95a7e8b43eSMichael Hamann 'phrase' => $phrase, 96a7e8b43eSMichael Hamann 'text' => rawWiki($id) 97a7e8b43eSMichael Hamann ); 98e1d9dcc8SAndreas Gohr $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata); 99a7e8b43eSMichael Hamann if ($evt->advise_before() && $evt->result !== true) { 1008cbc5ee8SAndreas Gohr $text = \dokuwiki\Utf8\PhpString::strtolower($evdata['text']); 101865c2687SKazutaka Miyasaka if (strpos($text, $phrase) !== false) { 102a7e8b43eSMichael Hamann $evt->result = true; 103a7e8b43eSMichael Hamann } 104a7e8b43eSMichael Hamann } 105a7e8b43eSMichael Hamann $evt->advise_after(); 106a7e8b43eSMichael Hamann if ($evt->result === true) { 107865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // phrase: always 0 hit 108865c2687SKazutaka Miyasaka } 109865c2687SKazutaka Miyasaka } 110865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 111865c2687SKazutaka Miyasaka break; 1122f502d70SKazutaka Miyasaka case 'N+:': 1132f502d70SKazutaka Miyasaka case 'N-:': // namespace 114de3383c6SMichael Große $ns = cleanID(substr($token, 3)) . ':'; 115865c2687SKazutaka Miyasaka $pages_matched = array(); 116865c2687SKazutaka Miyasaka foreach (array_keys($pages_all) as $id) { 117865c2687SKazutaka Miyasaka if (strpos($id, $ns) === 0) { 118865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // namespace: always 0 hit 119865c2687SKazutaka Miyasaka } 120865c2687SKazutaka Miyasaka } 121865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 122865c2687SKazutaka Miyasaka break; 123865c2687SKazutaka Miyasaka case 'AND': // and operation 124865c2687SKazutaka Miyasaka list($pages1, $pages2) = array_splice($stack, -2); 125865c2687SKazutaka Miyasaka $stack[] = ft_resultCombine(array($pages1, $pages2)); 126865c2687SKazutaka Miyasaka break; 127865c2687SKazutaka Miyasaka case 'OR': // or operation 128865c2687SKazutaka Miyasaka list($pages1, $pages2) = array_splice($stack, -2); 129865c2687SKazutaka Miyasaka $stack[] = ft_resultUnite(array($pages1, $pages2)); 130865c2687SKazutaka Miyasaka break; 131865c2687SKazutaka Miyasaka case 'NOT': // not operation (unary) 132865c2687SKazutaka Miyasaka $pages = array_pop($stack); 133865c2687SKazutaka Miyasaka $stack[] = ft_resultComplement(array($pages_all, $pages)); 134a21136cdSAndreas Gohr break; 135a21136cdSAndreas Gohr } 136f5eb7cf0SAndreas Gohr } 137865c2687SKazutaka Miyasaka $docs = array_pop($stack); 138865c2687SKazutaka Miyasaka 139865c2687SKazutaka Miyasaka if (empty($docs)) return array(); 140865c2687SKazutaka Miyasaka 141865c2687SKazutaka Miyasaka // check: settings, acls, existence 142865c2687SKazutaka Miyasaka foreach (array_keys($docs) as $id) { 143865c2687SKazutaka Miyasaka if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) { 144865c2687SKazutaka Miyasaka unset($docs[$id]); 145f5eb7cf0SAndreas Gohr } 146f5eb7cf0SAndreas Gohr } 147f5eb7cf0SAndreas Gohr 1483850270cSMichael Große $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']); 1498d0e286aSMichael Große 1508d0e286aSMichael Große if ($data['sort'] === 'mtime') { 1518d0e286aSMichael Große uksort($docs, 'ft_pagemtimesorter'); 1528d0e286aSMichael Große } else { 153865c2687SKazutaka Miyasaka // sort docs by count 154f5eb7cf0SAndreas Gohr arsort($docs); 1558d0e286aSMichael Große } 156f5eb7cf0SAndreas Gohr 157f5eb7cf0SAndreas Gohr return $docs; 158f5eb7cf0SAndreas Gohr} 159f5eb7cf0SAndreas Gohr 160f5eb7cf0SAndreas Gohr/** 16154f4c056SAndreas Gohr * Returns the backlinks for a given page 16254f4c056SAndreas Gohr * 163320f489aSMichael Hamann * Uses the metadata index. 16407ff0babSMichael Hamann * 16507ff0babSMichael Hamann * @param string $id The id for which links shall be returned 16607ff0babSMichael Hamann * @param bool $ignore_perms Ignore the fact that pages are hidden or read-protected 16707ff0babSMichael Hamann * @return array The pages that contain links to the given page 16854f4c056SAndreas Gohr */ 16907ff0babSMichael Hamannfunction ft_backlinks($id, $ignore_perms = false){ 170320f489aSMichael Hamann $result = idx_get_indexer()->lookupKey('relation_references', $id); 17154f4c056SAndreas Gohr 17263773904SAndreas Gohr if(!count($result)) return $result; 17363773904SAndreas Gohr 17463773904SAndreas Gohr // check ACL permissions 17563773904SAndreas Gohr foreach(array_keys($result) as $idx){ 17607ff0babSMichael Hamann if(($ignore_perms !== true && ( 17707ff0babSMichael Hamann isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 17807ff0babSMichael Hamann )) || !page_exists($result[$idx], '', false)){ 17963773904SAndreas Gohr unset($result[$idx]); 18063773904SAndreas Gohr } 18163773904SAndreas Gohr } 18263773904SAndreas Gohr 18354f4c056SAndreas Gohr sort($result); 18454f4c056SAndreas Gohr return $result; 18554f4c056SAndreas Gohr} 18654f4c056SAndreas Gohr 18754f4c056SAndreas Gohr/** 188a05e297aSAndreas Gohr * Returns the pages that use a given media file 189a05e297aSAndreas Gohr * 190ffec1009SMichael Hamann * Uses the relation media metadata property and the metadata index. 191a05e297aSAndreas Gohr * 192ffec1009SMichael Hamann * Note that before 2013-07-31 the second parameter was the maximum number of results and 193ffec1009SMichael Hamann * permissions were ignored. That's why the parameter is now checked to be explicitely set 194ffec1009SMichael Hamann * to true (with type bool) in order to be compatible with older uses of the function. 195ffec1009SMichael Hamann * 196ffec1009SMichael Hamann * @param string $id The media id to look for 197ffec1009SMichael Hamann * @param bool $ignore_perms Ignore hidden pages and acls (optional, default: false) 198ffec1009SMichael Hamann * @return array A list of pages that use the given media file 199a05e297aSAndreas Gohr */ 200ffec1009SMichael Hamannfunction ft_mediause($id, $ignore_perms = false){ 201ffec1009SMichael Hamann $result = idx_get_indexer()->lookupKey('relation_media', $id); 202a05e297aSAndreas Gohr 203ffec1009SMichael Hamann if(!count($result)) return $result; 204a05e297aSAndreas Gohr 205ffec1009SMichael Hamann // check ACL permissions 206ffec1009SMichael Hamann foreach(array_keys($result) as $idx){ 207ffec1009SMichael Hamann if(($ignore_perms !== true && ( 208ffec1009SMichael Hamann isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 209ffec1009SMichael Hamann )) || !page_exists($result[$idx], '', false)){ 210ffec1009SMichael Hamann unset($result[$idx]); 211a05e297aSAndreas Gohr } 212a05e297aSAndreas Gohr } 213a05e297aSAndreas Gohr 214a05e297aSAndreas Gohr sort($result); 215a05e297aSAndreas Gohr return $result; 216a05e297aSAndreas Gohr} 217a05e297aSAndreas Gohr 218a05e297aSAndreas Gohr 219a05e297aSAndreas Gohr/** 220506fa893SAndreas Gohr * Quicksearch for pagenames 221506fa893SAndreas Gohr * 222506fa893SAndreas Gohr * By default it only matches the pagename and ignores the 22380423ab6SAdrian Lang * namespace. This can be changed with the second parameter. 22480423ab6SAdrian Lang * The third parameter allows to search in titles as well. 225506fa893SAndreas Gohr * 2268d22f1e9SAndreas Gohr * The function always returns titles as well 2276840140fSChris Smith * 2288d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP 229506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 2308d22f1e9SAndreas Gohr * @author Adrian Lang <lang@cosmocode.de> 23142ea7f44SGerrit Uitslag * 23242ea7f44SGerrit Uitslag * @param string $id page id 23342ea7f44SGerrit Uitslag * @param bool $in_ns match against namespace as well? 23442ea7f44SGerrit Uitslag * @param bool $in_title search in title? 23564159a61SAndreas Gohr * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 23664159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 2373850270cSMichael Große * 23842ea7f44SGerrit Uitslag * @return string[] 239506fa893SAndreas Gohr */ 2403850270cSMichael Großefunction ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){ 2413850270cSMichael Große $data = [ 2423850270cSMichael Große 'id' => $id, 2433850270cSMichael Große 'in_ns' => $in_ns, 2443850270cSMichael Große 'in_title' => $in_title, 2453850270cSMichael Große 'after' => $after, 2463850270cSMichael Große 'before' => $before 2473850270cSMichael Große ]; 2488d22f1e9SAndreas Gohr $data['has_titles'] = true; // for plugin backward compatibility check 249cbb44eabSAndreas Gohr return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup'); 2506840140fSChris Smith} 2516840140fSChris Smith 25242ea7f44SGerrit Uitslag/** 25342ea7f44SGerrit Uitslag * Returns list of pages as array(pageid => First Heading) 25442ea7f44SGerrit Uitslag * 25542ea7f44SGerrit Uitslag * @param array &$data event data 25642ea7f44SGerrit Uitslag * @return string[] 25742ea7f44SGerrit Uitslag */ 2586840140fSChris Smithfunction _ft_pageLookup(&$data){ 25980423ab6SAdrian Lang // split out original parameters 2606840140fSChris Smith $id = $data['id']; 261940f24fcSMichael Große $Indexer = idx_get_indexer(); 262940f24fcSMichael Große $parsedQuery = ft_queryParser($Indexer, $id); 263940f24fcSMichael Große if (count($parsedQuery['ns']) > 0) { 264940f24fcSMichael Große $ns = cleanID($parsedQuery['ns'][0]) . ':'; 265940f24fcSMichael Große $id = implode(' ', $parsedQuery['highlight']); 266b0f6db0cSAdrian Lang } 267b0f6db0cSAdrian Lang 2688d22f1e9SAndreas Gohr $in_ns = $data['in_ns']; 2698d22f1e9SAndreas Gohr $in_title = $data['in_title']; 27080423ab6SAdrian Lang $cleaned = cleanID($id); 2719b41be24STom N Harris 2729b41be24STom N Harris $Indexer = idx_get_indexer(); 2739b41be24STom N Harris $page_idx = $Indexer->getPages(); 2749b41be24STom N Harris 2759b41be24STom N Harris $pages = array(); 2765479a8c3SAndreas Gohr if ($id !== '' && $cleaned !== '') { 2779b41be24STom N Harris foreach ($page_idx as $p_id) { 2789b41be24STom N Harris if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) { 2799b41be24STom N Harris if (!isset($pages[$p_id])) 28067c15eceSMichael Hamann $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 281506fa893SAndreas Gohr } 282506fa893SAndreas Gohr } 283f078bb00STom N Harris if ($in_title) { 284c66f16a3SMichael Hamann foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) { 285f078bb00STom N Harris if (!isset($pages[$p_id])) 28667c15eceSMichael Hamann $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 287f078bb00STom N Harris } 288f078bb00STom N Harris } 289d0bdf765SAdrian Lang } 2900c074a52SMichael Hamann 291d0bdf765SAdrian Lang if (isset($ns)) { 2920c074a52SMichael Hamann foreach (array_keys($pages) as $p_id) { 2930c074a52SMichael Hamann if (strpos($p_id, $ns) !== 0) { 2940c074a52SMichael Hamann unset($pages[$p_id]); 295d0bdf765SAdrian Lang } 296d0bdf765SAdrian Lang } 297506fa893SAndreas Gohr } 29863773904SAndreas Gohr 29980423ab6SAdrian Lang // discard hidden pages 30080423ab6SAdrian Lang // discard nonexistent pages 30163773904SAndreas Gohr // check ACL permissions 30263773904SAndreas Gohr foreach(array_keys($pages) as $idx){ 30380423ab6SAdrian Lang if(!isVisiblePage($idx) || !page_exists($idx) || 30480423ab6SAdrian Lang auth_quickaclcheck($idx) < AUTH_READ) { 30563773904SAndreas Gohr unset($pages[$idx]); 30663773904SAndreas Gohr } 30763773904SAndreas Gohr } 30863773904SAndreas Gohr 3093850270cSMichael Große $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']); 3101b48999cSMichael Große 3113d2017d9SAdrian Lang uksort($pages,'ft_pagesorter'); 3128d22f1e9SAndreas Gohr return $pages; 313506fa893SAndreas Gohr} 314506fa893SAndreas Gohr 3151b48999cSMichael Große 3161b48999cSMichael Große/** 3171b48999cSMichael Große * @param array $results search results in the form pageid => value 31864159a61SAndreas Gohr * @param int|string $after only returns results with mtime after this date, accepts timestap or strtotime arguments 31964159a61SAndreas Gohr * @param int|string $before only returns results with mtime after this date, accepts timestap or strtotime arguments 3201b48999cSMichael Große * 3211b48999cSMichael Große * @return array 3221b48999cSMichael Große */ 3233850270cSMichael Großefunction _ft_filterResultsByTime(array $results, $after, $before) { 3243850270cSMichael Große if ($after || $before) { 3251b48999cSMichael Große $after = is_int($after) ? $after : strtotime($after); 3261b48999cSMichael Große $before = is_int($before) ? $before : strtotime($before); 3271b48999cSMichael Große 3281b48999cSMichael Große foreach ($results as $id => $value) { 3291b48999cSMichael Große $mTime = filemtime(wikiFN($id)); 3301b48999cSMichael Große if ($after && $after > $mTime) { 3311b48999cSMichael Große unset($results[$id]); 3321b48999cSMichael Große continue; 3331b48999cSMichael Große } 3341b48999cSMichael Große if ($before && $before < $mTime) { 3351b48999cSMichael Große unset($results[$id]); 3361b48999cSMichael Große } 3371b48999cSMichael Große } 3381b48999cSMichael Große } 3391b48999cSMichael Große 3401b48999cSMichael Große return $results; 3411b48999cSMichael Große} 3421b48999cSMichael Große 343506fa893SAndreas Gohr/** 344c66f16a3SMichael Hamann * Tiny helper function for comparing the searched title with the title 345c66f16a3SMichael Hamann * from the search index. This function is a wrapper around stripos with 346c66f16a3SMichael Hamann * adapted argument order and return value. 34742ea7f44SGerrit Uitslag * 34842ea7f44SGerrit Uitslag * @param string $search searched title 34942ea7f44SGerrit Uitslag * @param string $title title from index 35042ea7f44SGerrit Uitslag * @return bool 351c66f16a3SMichael Hamann */ 352c66f16a3SMichael Hamannfunction _ft_pageLookupTitleCompare($search, $title) { 353c66f16a3SMichael Hamann return stripos($title, $search) !== false; 354c66f16a3SMichael Hamann} 355c66f16a3SMichael Hamann 356c66f16a3SMichael Hamann/** 357f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string 358f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy 359f31eb72bSAndreas Gohr * pages. 36042ea7f44SGerrit Uitslag * 36142ea7f44SGerrit Uitslag * @param string $a 36242ea7f44SGerrit Uitslag * @param string $b 36342ea7f44SGerrit Uitslag * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal. 364f31eb72bSAndreas Gohr */ 365f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){ 366f31eb72bSAndreas Gohr $ac = count(explode(':',$a)); 367f31eb72bSAndreas Gohr $bc = count(explode(':',$b)); 368f31eb72bSAndreas Gohr if($ac < $bc){ 369f31eb72bSAndreas Gohr return -1; 370f31eb72bSAndreas Gohr }elseif($ac > $bc){ 371f31eb72bSAndreas Gohr return 1; 372f31eb72bSAndreas Gohr } 373f31eb72bSAndreas Gohr return strcmp ($a,$b); 374f31eb72bSAndreas Gohr} 375f31eb72bSAndreas Gohr 376f31eb72bSAndreas Gohr/** 3778d0e286aSMichael Große * Sort pages by their mtime, from newest to oldest 3788d0e286aSMichael Große * 3798d0e286aSMichael Große * @param string $a 3808d0e286aSMichael Große * @param string $b 3818d0e286aSMichael Große * 3828d0e286aSMichael 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 3838d0e286aSMichael Große */ 3848d0e286aSMichael Großefunction ft_pagemtimesorter($a, $b) { 3858d0e286aSMichael Große $mtimeA = filemtime(wikiFN($a)); 3868d0e286aSMichael Große $mtimeB = filemtime(wikiFN($b)); 3878d0e286aSMichael Große return $mtimeB - $mtimeA; 3888d0e286aSMichael Große} 3898d0e286aSMichael Große 3908d0e286aSMichael Große/** 391506fa893SAndreas Gohr * Creates a snippet extract 392506fa893SAndreas Gohr * 393506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 39460e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE 39542ea7f44SGerrit Uitslag * 39642ea7f44SGerrit Uitslag * @param string $id page id 39742ea7f44SGerrit Uitslag * @param array $highlight 39842ea7f44SGerrit Uitslag * @return mixed 399506fa893SAndreas Gohr */ 400546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){ 401506fa893SAndreas Gohr $text = rawWiki($id); 4024f0030ddSAndreas Gohr $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens 40360e91a17SAndreas Gohr $evdata = array( 40460e91a17SAndreas Gohr 'id' => $id, 40560e91a17SAndreas Gohr 'text' => &$text, 40660e91a17SAndreas Gohr 'highlight' => &$highlight, 40760e91a17SAndreas Gohr 'snippet' => '', 40860e91a17SAndreas Gohr ); 40960e91a17SAndreas Gohr 410e1d9dcc8SAndreas Gohr $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata); 41160e91a17SAndreas Gohr if ($evt->advise_before()) { 412ced0762eSchris $match = array(); 413ced0762eSchris $snippets = array(); 4149ee93076Schris $utf8_offset = $offset = $end = 0; 4158cbc5ee8SAndreas Gohr $len = \dokuwiki\Utf8\PhpString::strlen($text); 4169ee93076Schris 417546d3a99SAndreas Gohr // build a regexp from the phrases to highlight 41864159a61SAndreas Gohr $re1 = '(' . 41964159a61SAndreas Gohr join( 42064159a61SAndreas Gohr '|', 42164159a61SAndreas Gohr array_map( 42264159a61SAndreas Gohr 'ft_snippet_re_preprocess', 42364159a61SAndreas Gohr array_map( 42464159a61SAndreas Gohr 'preg_quote_cb', 42564159a61SAndreas Gohr array_filter((array) $highlight) 42664159a61SAndreas Gohr ) 42764159a61SAndreas Gohr ) 42864159a61SAndreas Gohr ) . 42964159a61SAndreas Gohr ')'; 430b571ff2dSChuck Kollars $re2 = "$re1.{0,75}(?!\\1)$re1"; 431b571ff2dSChuck Kollars $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; 432546d3a99SAndreas Gohr 433b571ff2dSChuck Kollars for ($cnt=4; $cnt--;) { 434b571ff2dSChuck Kollars if (0) { 435b571ff2dSChuck Kollars } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 436b571ff2dSChuck Kollars } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 437b571ff2dSChuck Kollars } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 438b571ff2dSChuck Kollars } else { 439b571ff2dSChuck Kollars break; 440b571ff2dSChuck Kollars } 441ced0762eSchris 442ced0762eSchris list($str,$idx) = $match[0]; 443ced0762eSchris 444ced0762eSchris // convert $idx (a byte offset) into a utf8 character offset 4458cbc5ee8SAndreas Gohr $utf8_idx = \dokuwiki\Utf8\PhpString::strlen(substr($text,0,$idx)); 4468cbc5ee8SAndreas Gohr $utf8_len = \dokuwiki\Utf8\PhpString::strlen($str); 447ced0762eSchris 448ced0762eSchris // establish context, 100 bytes surrounding the match string 449ced0762eSchris // first look to see if we can go 100 either side, 450ced0762eSchris // then drop to 50 adding any excess if the other side can't go to 50, 451ced0762eSchris $pre = min($utf8_idx-$utf8_offset,100); 452ced0762eSchris $post = min($len-$utf8_idx-$utf8_len,100); 453ced0762eSchris 454ced0762eSchris if ($pre>50 && $post>50) { 455ced0762eSchris $pre = $post = 50; 456ced0762eSchris } else if ($pre>50) { 457ced0762eSchris $pre = min($pre,100-$post); 458ced0762eSchris } else if ($post>50) { 459ced0762eSchris $post = min($post, 100-$pre); 460ef3e3cddSMichael Hamann } else if ($offset == 0) { 461ced0762eSchris // both are less than 50, means the context is the whole string 46210ffc9ddSAndreas Gohr // make it so and break out of this loop - there is no need for the 46310ffc9ddSAndreas Gohr // complex snippet calculations 464ced0762eSchris $snippets = array($text); 465ced0762eSchris break; 466ced0762eSchris } 467ced0762eSchris 46810ffc9ddSAndreas Gohr // establish context start and end points, try to append to previous 46910ffc9ddSAndreas Gohr // context if possible 4709ee93076Schris $start = $utf8_idx - $pre; 471ced0762eSchris $append = ($start < $end) ? $end : false; // still the end of the previous context snippet 4729ee93076Schris $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context 473ced0762eSchris 474ced0762eSchris if ($append) { 4758cbc5ee8SAndreas Gohr $snippets[count($snippets)-1] .= \dokuwiki\Utf8\PhpString::substr($text,$append,$end-$append); 476ced0762eSchris } else { 4778cbc5ee8SAndreas Gohr $snippets[] = \dokuwiki\Utf8\PhpString::substr($text,$start,$end-$start); 478ced0762eSchris } 479ced0762eSchris 480ced0762eSchris // set $offset for next match attempt 48143d58b76SMichael Hamann // continue matching after the current match 48243d58b76SMichael Hamann // if the current match is not the longest possible match starting at the current offset 48343d58b76SMichael Hamann // this prevents further matching of this snippet but for possible matches of length 48443d58b76SMichael Hamann // smaller than match length + context (at least 50 characters) this match is part of the context 48543d58b76SMichael Hamann $utf8_offset = $utf8_idx + $utf8_len; 4868cbc5ee8SAndreas Gohr $offset = $idx + strlen(\dokuwiki\Utf8\PhpString::substr($text,$utf8_idx,$utf8_len)); 4878cbc5ee8SAndreas Gohr $offset = \dokuwiki\Utf8\Clean::correctIdx($text,$offset); 4889ee93076Schris } 4899ee93076Schris 490ced0762eSchris $m = "\1"; 491b571ff2dSChuck Kollars $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets); 49264159a61SAndreas Gohr $snippet = preg_replace( 49364159a61SAndreas Gohr '/' . $m . '([^' . $m . ']*?)' . $m . '/iu', 49464159a61SAndreas Gohr '<strong class="search_hit">$1</strong>', 49564159a61SAndreas Gohr hsc(join('... ', $snippets)) 49664159a61SAndreas Gohr ); 497bd2cb6fcSchris 49860e91a17SAndreas Gohr $evdata['snippet'] = $snippet; 49960e91a17SAndreas Gohr } 50060e91a17SAndreas Gohr $evt->advise_after(); 50160e91a17SAndreas Gohr unset($evt); 50260e91a17SAndreas Gohr 50360e91a17SAndreas Gohr return $evdata['snippet']; 504506fa893SAndreas Gohr} 505506fa893SAndreas Gohr 506506fa893SAndreas Gohr/** 50726eb848cSGina Haeussge * Wraps a search term in regex boundary checks. 50842ea7f44SGerrit Uitslag * 50942ea7f44SGerrit Uitslag * @param string $term 51042ea7f44SGerrit Uitslag * @return string 51126eb848cSGina Haeussge */ 5122237b4faSAndreas Gohrfunction ft_snippet_re_preprocess($term) { 51335594613SKazutaka Miyasaka // do not process asian terms where word boundaries are not explicit 51435594613SKazutaka Miyasaka if(preg_match('/'.IDX_ASIAN.'/u',$term)){ 51535594613SKazutaka Miyasaka return $term; 51635594613SKazutaka Miyasaka } 51735594613SKazutaka Miyasaka 5183161005dSAndreas Gohr if (UTF8_PROPERTYSUPPORT) { 51984e581a6SAndreas Gohr // unicode word boundaries 52084e581a6SAndreas Gohr // see http://stackoverflow.com/a/2449017/172068 52184e581a6SAndreas Gohr $BL = '(?<!\pL)'; 52284e581a6SAndreas Gohr $BR = '(?!\pL)'; 5233161005dSAndreas Gohr } else { 5243161005dSAndreas Gohr // not as correct as above, but at least won't break 5253161005dSAndreas Gohr $BL = '\b'; 5263161005dSAndreas Gohr $BR = '\b'; 5273161005dSAndreas Gohr } 5283161005dSAndreas Gohr 5292237b4faSAndreas Gohr if(substr($term,0,2) == '\\*'){ 5302237b4faSAndreas Gohr $term = substr($term,2); 5312237b4faSAndreas Gohr }else{ 53284e581a6SAndreas Gohr $term = $BL.$term; 5332237b4faSAndreas Gohr } 5342237b4faSAndreas Gohr 5352237b4faSAndreas Gohr if(substr($term,-2,2) == '\\*'){ 5362237b4faSAndreas Gohr $term = substr($term,0,-2); 5372237b4faSAndreas Gohr }else{ 53884e581a6SAndreas Gohr $term = $term.$BR; 5392237b4faSAndreas Gohr } 5408a803caeSAndreas Gohr 54184e581a6SAndreas Gohr if($term == $BL || $term == $BR || $term == $BL.$BR) $term = ''; 5422237b4faSAndreas Gohr return $term; 54326eb848cSGina Haeussge} 54426eb848cSGina Haeussge 54526eb848cSGina Haeussge/** 546f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores 547f5eb7cf0SAndreas Gohr * 548f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical 549f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned. 550f5eb7cf0SAndreas Gohr * 551f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key() 552f5eb7cf0SAndreas Gohr * 553f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays 55442ea7f44SGerrit Uitslag * @return array 555f5eb7cf0SAndreas Gohr */ 556f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){ 557f5eb7cf0SAndreas Gohr $array_count = count($args); 558134f4ab2SAndreas Gohr if($array_count == 1){ 559134f4ab2SAndreas Gohr return $args[0]; 560134f4ab2SAndreas Gohr } 561134f4ab2SAndreas Gohr 562f5eb7cf0SAndreas Gohr $result = array(); 56309c27a6dSGuy Brand if ($array_count > 1) { 564a21136cdSAndreas Gohr foreach ($args[0] as $key => $value) { 565a21136cdSAndreas Gohr $result[$key] = $value; 566f5eb7cf0SAndreas Gohr for ($i = 1; $i !== $array_count; $i++) { 567a21136cdSAndreas Gohr if (!isset($args[$i][$key])) { 568a21136cdSAndreas Gohr unset($result[$key]); 569a21136cdSAndreas Gohr break; 570f5eb7cf0SAndreas Gohr } 571a21136cdSAndreas Gohr $result[$key] += $args[$i][$key]; 572f5eb7cf0SAndreas Gohr } 573f5eb7cf0SAndreas Gohr } 57409c27a6dSGuy Brand } 575f5eb7cf0SAndreas Gohr return $result; 576f5eb7cf0SAndreas Gohr} 577f5eb7cf0SAndreas Gohr 578f5eb7cf0SAndreas Gohr/** 579865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores 580f5eb7cf0SAndreas Gohr * 581865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function 582865c2687SKazutaka Miyasaka * 583865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 58442ea7f44SGerrit Uitslag * @return array 58542ea7f44SGerrit Uitslag * 586865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 587865c2687SKazutaka Miyasaka */ 588865c2687SKazutaka Miyasakafunction ft_resultUnite($args) { 589865c2687SKazutaka Miyasaka $array_count = count($args); 590865c2687SKazutaka Miyasaka if ($array_count === 1) { 591865c2687SKazutaka Miyasaka return $args[0]; 592865c2687SKazutaka Miyasaka } 593865c2687SKazutaka Miyasaka 594865c2687SKazutaka Miyasaka $result = $args[0]; 595865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 596865c2687SKazutaka Miyasaka foreach (array_keys($args[$i]) as $id) { 597865c2687SKazutaka Miyasaka $result[$id] += $args[$i][$id]; 598865c2687SKazutaka Miyasaka } 599865c2687SKazutaka Miyasaka } 600865c2687SKazutaka Miyasaka return $result; 601865c2687SKazutaka Miyasaka} 602865c2687SKazutaka Miyasaka 603865c2687SKazutaka Miyasaka/** 604865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison 605865c2687SKazutaka Miyasaka * 606865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key() 607865c2687SKazutaka Miyasaka * 608865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 60942ea7f44SGerrit Uitslag * @return array 61042ea7f44SGerrit Uitslag * 611865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 612865c2687SKazutaka Miyasaka */ 613865c2687SKazutaka Miyasakafunction ft_resultComplement($args) { 614865c2687SKazutaka Miyasaka $array_count = count($args); 615865c2687SKazutaka Miyasaka if ($array_count === 1) { 616865c2687SKazutaka Miyasaka return $args[0]; 617865c2687SKazutaka Miyasaka } 618865c2687SKazutaka Miyasaka 619865c2687SKazutaka Miyasaka $result = $args[0]; 620865c2687SKazutaka Miyasaka foreach (array_keys($result) as $id) { 621865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 622865c2687SKazutaka Miyasaka if (isset($args[$i][$id])) unset($result[$id]); 623865c2687SKazutaka Miyasaka } 624865c2687SKazutaka Miyasaka } 625865c2687SKazutaka Miyasaka return $result; 626865c2687SKazutaka Miyasaka} 627865c2687SKazutaka Miyasaka 628865c2687SKazutaka Miyasaka/** 629865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas 630865c2687SKazutaka Miyasaka * 631865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 632865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 63342ea7f44SGerrit Uitslag * 63442ea7f44SGerrit Uitslag * @param Doku_Indexer $Indexer 63542ea7f44SGerrit Uitslag * @param string $query search query 63642ea7f44SGerrit Uitslag * @return array of search formulas 637f5eb7cf0SAndreas Gohr */ 6389b41be24STom N Harrisfunction ft_queryParser($Indexer, $query){ 639865c2687SKazutaka Miyasaka /** 640865c2687SKazutaka Miyasaka * parse a search query and transform it into intermediate representation 641865c2687SKazutaka Miyasaka * 642865c2687SKazutaka Miyasaka * in a search query, you can use the following expressions: 643865c2687SKazutaka Miyasaka * 644865c2687SKazutaka Miyasaka * words: 645865c2687SKazutaka Miyasaka * include 646865c2687SKazutaka Miyasaka * -exclude 647865c2687SKazutaka Miyasaka * phrases: 648865c2687SKazutaka Miyasaka * "phrase to be included" 649865c2687SKazutaka Miyasaka * -"phrase you want to exclude" 650865c2687SKazutaka Miyasaka * namespaces: 651865c2687SKazutaka Miyasaka * @include:namespace (or ns:include:namespace) 652865c2687SKazutaka Miyasaka * ^exclude:namespace (or -ns:exclude:namespace) 653865c2687SKazutaka Miyasaka * groups: 654865c2687SKazutaka Miyasaka * () 655865c2687SKazutaka Miyasaka * -() 656865c2687SKazutaka Miyasaka * operators: 657865c2687SKazutaka Miyasaka * and ('and' is the default operator: you can always omit this) 6587871d415SKazutaka Miyasaka * or (or pipe symbol '|', lower precedence than 'and') 659865c2687SKazutaka Miyasaka * 660865c2687SKazutaka Miyasaka * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain 661865c2687SKazutaka Miyasaka * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". 662865c2687SKazutaka Miyasaka * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] 663865c2687SKazutaka Miyasaka * as long as you don't mind hit counts. 664865c2687SKazutaka Miyasaka * 665865c2687SKazutaka Miyasaka * intermediate representation consists of the following parts: 666865c2687SKazutaka Miyasaka * 667865c2687SKazutaka Miyasaka * ( ) - group 668865c2687SKazutaka Miyasaka * AND - logical and 669865c2687SKazutaka Miyasaka * OR - logical or 670865c2687SKazutaka Miyasaka * NOT - logical not 6712f502d70SKazutaka Miyasaka * W+:, W-:, W_: - word (underscore: no need to highlight) 6722f502d70SKazutaka Miyasaka * P+:, P-: - phrase (minus sign: logically in NOT group) 6732f502d70SKazutaka Miyasaka * N+:, N-: - namespace 674865c2687SKazutaka Miyasaka */ 675865c2687SKazutaka Miyasaka $parsed_query = ''; 676865c2687SKazutaka Miyasaka $parens_level = 0; 677*6ce3e5f8SAndreas Gohr $terms = preg_split('/(-?".*?")/u', \dokuwiki\Utf8\PhpString::strtolower($query), 678*6ce3e5f8SAndreas Gohr -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 679865c2687SKazutaka Miyasaka 680865c2687SKazutaka Miyasaka foreach ($terms as $term) { 681865c2687SKazutaka Miyasaka $parsed = ''; 682865c2687SKazutaka Miyasaka if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { 683865c2687SKazutaka Miyasaka // phrase-include and phrase-exclude 684865c2687SKazutaka Miyasaka $not = $matches[1] ? 'NOT' : ''; 6859b41be24STom N Harris $parsed = $not.ft_termParser($Indexer, $matches[2], false, true); 686f5eb7cf0SAndreas Gohr } else { 687865c2687SKazutaka Miyasaka // fix incomplete phrase 688865c2687SKazutaka Miyasaka $term = str_replace('"', ' ', $term); 689865c2687SKazutaka Miyasaka 690865c2687SKazutaka Miyasaka // fix parentheses 691865c2687SKazutaka Miyasaka $term = str_replace(')' , ' ) ', $term); 692865c2687SKazutaka Miyasaka $term = str_replace('(' , ' ( ', $term); 693865c2687SKazutaka Miyasaka $term = str_replace('- (', ' -(', $term); 694865c2687SKazutaka Miyasaka 6957871d415SKazutaka Miyasaka // treat pipe symbols as 'OR' operators 6967871d415SKazutaka Miyasaka $term = str_replace('|', ' or ', $term); 6977871d415SKazutaka Miyasaka 698865c2687SKazutaka Miyasaka // treat ideographic spaces (U+3000) as search term separators 699865c2687SKazutaka Miyasaka // FIXME: some more separators? 700865c2687SKazutaka Miyasaka $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); 701865c2687SKazutaka Miyasaka $term = trim($term); 702865c2687SKazutaka Miyasaka if ($term === '') continue; 703865c2687SKazutaka Miyasaka 704865c2687SKazutaka Miyasaka $tokens = explode(' ', $term); 705865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 706865c2687SKazutaka Miyasaka if ($token === '(') { 707865c2687SKazutaka Miyasaka // parenthesis-include-open 708865c2687SKazutaka Miyasaka $parsed .= '('; 709865c2687SKazutaka Miyasaka ++$parens_level; 710865c2687SKazutaka Miyasaka } elseif ($token === '-(') { 711865c2687SKazutaka Miyasaka // parenthesis-exclude-open 712865c2687SKazutaka Miyasaka $parsed .= 'NOT('; 713865c2687SKazutaka Miyasaka ++$parens_level; 714865c2687SKazutaka Miyasaka } elseif ($token === ')') { 715865c2687SKazutaka Miyasaka // parenthesis-any-close 716865c2687SKazutaka Miyasaka if ($parens_level === 0) continue; 717865c2687SKazutaka Miyasaka $parsed .= ')'; 718865c2687SKazutaka Miyasaka $parens_level--; 719865c2687SKazutaka Miyasaka } elseif ($token === 'and') { 720865c2687SKazutaka Miyasaka // logical-and (do nothing) 721865c2687SKazutaka Miyasaka } elseif ($token === 'or') { 722865c2687SKazutaka Miyasaka // logical-or 723865c2687SKazutaka Miyasaka $parsed .= 'OR'; 724865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { 725865c2687SKazutaka Miyasaka // namespace-exclude 7262f502d70SKazutaka Miyasaka $parsed .= 'NOT(N+:'.$matches[1].')'; 727865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { 728865c2687SKazutaka Miyasaka // namespace-include 7292f502d70SKazutaka Miyasaka $parsed .= '(N+:'.$matches[1].')'; 730865c2687SKazutaka Miyasaka } elseif (preg_match('/^-(.+)$/', $token, $matches)) { 731865c2687SKazutaka Miyasaka // word-exclude 7329b41be24STom N Harris $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')'; 733865c2687SKazutaka Miyasaka } else { 734865c2687SKazutaka Miyasaka // word-include 7359b41be24STom N Harris $parsed .= ft_termParser($Indexer, $token); 736865c2687SKazutaka Miyasaka } 737865c2687SKazutaka Miyasaka } 738865c2687SKazutaka Miyasaka } 739865c2687SKazutaka Miyasaka $parsed_query .= $parsed; 740f5eb7cf0SAndreas Gohr } 741f5eb7cf0SAndreas Gohr 742865c2687SKazutaka Miyasaka // cleanup (very sensitive) 743865c2687SKazutaka Miyasaka $parsed_query .= str_repeat(')', $parens_level); 744865c2687SKazutaka Miyasaka do { 745865c2687SKazutaka Miyasaka $parsed_query_old = $parsed_query; 746865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); 747865c2687SKazutaka Miyasaka } while ($parsed_query !== $parsed_query_old); 748865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query); 749865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query); 750865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query); 751865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query); 752865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query); 753865c2687SKazutaka Miyasaka 7542f502d70SKazutaka Miyasaka // adjustment: make highlightings right 7552f502d70SKazutaka Miyasaka $parens_level = 0; 7562f502d70SKazutaka Miyasaka $notgrp_levels = array(); 7572f502d70SKazutaka Miyasaka $parsed_query_new = ''; 7582f502d70SKazutaka Miyasaka $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 7592f502d70SKazutaka Miyasaka foreach ($tokens as $token) { 7602f502d70SKazutaka Miyasaka if ($token === 'NOT(') { 7612f502d70SKazutaka Miyasaka $notgrp_levels[] = ++$parens_level; 7622f502d70SKazutaka Miyasaka } elseif ($token === '(') { 7632f502d70SKazutaka Miyasaka ++$parens_level; 7642f502d70SKazutaka Miyasaka } elseif ($token === ')') { 7652f502d70SKazutaka Miyasaka if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels); 7662f502d70SKazutaka Miyasaka } elseif (count($notgrp_levels) % 2 === 1) { 7672f502d70SKazutaka Miyasaka // turn highlight-flag off if terms are logically in "NOT" group 7682f502d70SKazutaka Miyasaka $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token); 7692f502d70SKazutaka Miyasaka } 7702f502d70SKazutaka Miyasaka $parsed_query_new .= $token; 7712f502d70SKazutaka Miyasaka } 7722f502d70SKazutaka Miyasaka $parsed_query = $parsed_query_new; 7732f502d70SKazutaka Miyasaka 774865c2687SKazutaka Miyasaka /** 775865c2687SKazutaka Miyasaka * convert infix notation string into postfix (Reverse Polish notation) array 776865c2687SKazutaka Miyasaka * by Shunting-yard algorithm 777865c2687SKazutaka Miyasaka * 778865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation 779865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm 780865c2687SKazutaka Miyasaka */ 781865c2687SKazutaka Miyasaka $parsed_ary = array(); 782865c2687SKazutaka Miyasaka $ope_stack = array(); 783865c2687SKazutaka Miyasaka $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5); 784865c2687SKazutaka Miyasaka $ope_regex = '/([()]|OR|AND|NOT)/u'; 785865c2687SKazutaka Miyasaka 786865c2687SKazutaka Miyasaka $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 787865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 788865c2687SKazutaka Miyasaka if (preg_match($ope_regex, $token)) { 789865c2687SKazutaka Miyasaka // operator 790865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 79167d812e0SMarius van Witzenburg while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { 792865c2687SKazutaka Miyasaka $parsed_ary[] = array_pop($ope_stack); 793865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 794865c2687SKazutaka Miyasaka } 795865c2687SKazutaka Miyasaka if ($token == ')') { 796865c2687SKazutaka Miyasaka array_pop($ope_stack); // this array_pop always deletes '(' 797865c2687SKazutaka Miyasaka } else { 798865c2687SKazutaka Miyasaka $ope_stack[] = $token; 799865c2687SKazutaka Miyasaka } 800865c2687SKazutaka Miyasaka } else { 801865c2687SKazutaka Miyasaka // operand 802865c2687SKazutaka Miyasaka $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token); 803865c2687SKazutaka Miyasaka $parsed_ary[] = $token_decoded; 804865c2687SKazutaka Miyasaka } 805865c2687SKazutaka Miyasaka } 806865c2687SKazutaka Miyasaka $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack))); 807865c2687SKazutaka Miyasaka 808865c2687SKazutaka Miyasaka // cleanup: each double "NOT" in RPN array actually does nothing 809865c2687SKazutaka Miyasaka $parsed_ary_count = count($parsed_ary); 810865c2687SKazutaka Miyasaka for ($i = 1; $i < $parsed_ary_count; ++$i) { 811865c2687SKazutaka Miyasaka if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { 812865c2687SKazutaka Miyasaka unset($parsed_ary[$i], $parsed_ary[$i - 1]); 813865c2687SKazutaka Miyasaka } 814865c2687SKazutaka Miyasaka } 815865c2687SKazutaka Miyasaka $parsed_ary = array_values($parsed_ary); 816865c2687SKazutaka Miyasaka 817865c2687SKazutaka Miyasaka // build return value 818f5eb7cf0SAndreas Gohr $q = array(); 819f5eb7cf0SAndreas Gohr $q['query'] = $query; 820865c2687SKazutaka Miyasaka $q['parsed_str'] = $parsed_query; 821865c2687SKazutaka Miyasaka $q['parsed_ary'] = $parsed_ary; 822f5eb7cf0SAndreas Gohr 823865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 824865c2687SKazutaka Miyasaka if ($token[2] !== ':') continue; 825865c2687SKazutaka Miyasaka $body = substr($token, 3); 826865c2687SKazutaka Miyasaka 827865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 8282f502d70SKazutaka Miyasaka case 'N+:': 829865c2687SKazutaka Miyasaka $q['ns'][] = $body; // for backward compatibility 830865c2687SKazutaka Miyasaka break; 8312f502d70SKazutaka Miyasaka case 'N-:': 8322f502d70SKazutaka Miyasaka $q['notns'][] = $body; // for backward compatibility 8332f502d70SKazutaka Miyasaka break; 8342f502d70SKazutaka Miyasaka case 'W_:': 8352f502d70SKazutaka Miyasaka $q['words'][] = $body; 8362f502d70SKazutaka Miyasaka break; 837865c2687SKazutaka Miyasaka case 'W-:': 838865c2687SKazutaka Miyasaka $q['words'][] = $body; 8392f502d70SKazutaka Miyasaka $q['not'][] = $body; // for backward compatibility 840865c2687SKazutaka Miyasaka break; 841865c2687SKazutaka Miyasaka case 'W+:': 842865c2687SKazutaka Miyasaka $q['words'][] = $body; 8432237b4faSAndreas Gohr $q['highlight'][] = $body; 8442f502d70SKazutaka Miyasaka $q['and'][] = $body; // for backward compatibility 845865c2687SKazutaka Miyasaka break; 8462f502d70SKazutaka Miyasaka case 'P-:': 8472f502d70SKazutaka Miyasaka $q['phrases'][] = $body; 8482f502d70SKazutaka Miyasaka break; 8492f502d70SKazutaka Miyasaka case 'P+:': 850865c2687SKazutaka Miyasaka $q['phrases'][] = $body; 8512237b4faSAndreas Gohr $q['highlight'][] = $body; 852865c2687SKazutaka Miyasaka break; 853865c2687SKazutaka Miyasaka } 854865c2687SKazutaka Miyasaka } 8552f502d70SKazutaka Miyasaka foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) { 856865c2687SKazutaka Miyasaka $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key])); 857f5eb7cf0SAndreas Gohr } 858f5eb7cf0SAndreas Gohr 859f5eb7cf0SAndreas Gohr return $q; 860f5eb7cf0SAndreas Gohr} 861f5eb7cf0SAndreas Gohr 862865c2687SKazutaka Miyasaka/** 863865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation 864865c2687SKazutaka Miyasaka * 865865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use. 866865c2687SKazutaka Miyasaka * 867865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 86842ea7f44SGerrit Uitslag * 86942ea7f44SGerrit Uitslag * @param Doku_Indexer $Indexer 87042ea7f44SGerrit Uitslag * @param string $term 87142ea7f44SGerrit Uitslag * @param bool $consider_asian 87242ea7f44SGerrit Uitslag * @param bool $phrase_mode 87342ea7f44SGerrit Uitslag * @return string 874865c2687SKazutaka Miyasaka */ 8759b41be24STom N Harrisfunction ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) { 876865c2687SKazutaka Miyasaka $parsed = ''; 877865c2687SKazutaka Miyasaka if ($consider_asian) { 878865c2687SKazutaka Miyasaka // successive asian characters need to be searched as a phrase 879865c2687SKazutaka Miyasaka $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 880865c2687SKazutaka Miyasaka foreach ($words as $word) { 8816ac2077aSKazutaka Miyasaka $phrase_mode = $phrase_mode ? true : preg_match('/'.IDX_ASIAN.'/u', $word); 8829b41be24STom N Harris $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode); 883865c2687SKazutaka Miyasaka } 884865c2687SKazutaka Miyasaka } else { 885865c2687SKazutaka Miyasaka $term_noparen = str_replace(array('(', ')'), ' ', $term); 8869b41be24STom N Harris $words = $Indexer->tokenizer($term_noparen, true); 887865c2687SKazutaka Miyasaka 8882f502d70SKazutaka Miyasaka // W_: no need to highlight 889865c2687SKazutaka Miyasaka if (empty($words)) { 890865c2687SKazutaka Miyasaka $parsed = '()'; // important: do not remove 891865c2687SKazutaka Miyasaka } elseif ($words[0] === $term) { 892865c2687SKazutaka Miyasaka $parsed = '(W+:'.$words[0].')'; 893865c2687SKazutaka Miyasaka } elseif ($phrase_mode) { 894865c2687SKazutaka Miyasaka $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term); 8952f502d70SKazutaka Miyasaka $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))'; 896865c2687SKazutaka Miyasaka } else { 897865c2687SKazutaka Miyasaka $parsed = '((W+:'.implode(')(W+:', $words).'))'; 898865c2687SKazutaka Miyasaka } 899865c2687SKazutaka Miyasaka } 900865c2687SKazutaka Miyasaka return $parsed; 901865c2687SKazutaka Miyasaka} 902865c2687SKazutaka Miyasaka 90344156e11SMichael Große/** 90444156e11SMichael Große * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches 90544156e11SMichael Große * 90644156e11SMichael Große * @param array $and 90744156e11SMichael Große * @param array $not 90844156e11SMichael Große * @param array $phrases 90944156e11SMichael Große * @param array $ns 91044156e11SMichael Große * @param array $notns 91144156e11SMichael Große * 91244156e11SMichael Große * @return string 91344156e11SMichael Große */ 91444156e11SMichael Großefunction ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) { 91544156e11SMichael Große $query = implode(' ', $and); 91644156e11SMichael Große if (!empty($not)) { 91744156e11SMichael Große $query .= ' -' . implode(' -', $not); 91844156e11SMichael Große } 91944156e11SMichael Große 92044156e11SMichael Große if (!empty($phrases)) { 92144156e11SMichael Große $query .= ' "' . implode('" "', $phrases) . '"'; 92244156e11SMichael Große } 92344156e11SMichael Große 92444156e11SMichael Große if (!empty($ns)) { 92544156e11SMichael Große $query .= ' @' . implode(' @', $ns); 92644156e11SMichael Große } 92744156e11SMichael Große 92844156e11SMichael Große if (!empty($notns)) { 92944156e11SMichael Große $query .= ' ^' . implode(' ^', $notns); 93044156e11SMichael Große } 93144156e11SMichael Große 93244156e11SMichael Große return $query; 93344156e11SMichael Große} 93444156e11SMichael Große 935e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 : 936