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> 7e1d9dcc8SAndreas Gohr */use dokuwiki\Extension\Event; 8f5eb7cf0SAndreas Gohr 9bd0293e7SAndreas Gohr/** 10bd0293e7SAndreas Gohr * create snippets for the first few results only 11bd0293e7SAndreas Gohr */ 12bd0293e7SAndreas Gohrif(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15); 13f5eb7cf0SAndreas Gohr 14f5eb7cf0SAndreas Gohr/** 15f5eb7cf0SAndreas Gohr * The fulltext search 16f5eb7cf0SAndreas Gohr * 17f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query 18506fa893SAndreas Gohr * 196840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event() 206840140fSChris Smith * 2142ea7f44SGerrit Uitslag * @param string $query 2242ea7f44SGerrit Uitslag * @param array $highlight 233850270cSMichael Große * @param string $sort 2464159a61SAndreas Gohr * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 2564159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 263850270cSMichael Große * 2742ea7f44SGerrit Uitslag * @return array 28f5eb7cf0SAndreas Gohr */ 293850270cSMichael Großefunction ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){ 306840140fSChris Smith 313850270cSMichael Große if ($sort === null) { 323850270cSMichael Große $sort = 'hits'; 333850270cSMichael Große } 343850270cSMichael Große $data = [ 353850270cSMichael Große 'query' => $query, 363850270cSMichael Große 'sort' => $sort, 373850270cSMichael Große 'after' => $after, 383850270cSMichael Große 'before' => $before 393850270cSMichael Große ]; 406840140fSChris Smith $data['highlight'] =& $highlight; 416840140fSChris Smith 42cbb44eabSAndreas Gohr return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch'); 436840140fSChris Smith} 44865c2687SKazutaka Miyasaka 45865c2687SKazutaka Miyasaka/** 46865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query 47865c2687SKazutaka Miyasaka * 48865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 49865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 5042ea7f44SGerrit Uitslag * 5142ea7f44SGerrit Uitslag * @param array $data event data 5242ea7f44SGerrit Uitslag * @return array matching documents 53865c2687SKazutaka Miyasaka */ 546840140fSChris Smithfunction _ft_pageSearch(&$data) { 559b41be24STom N Harris $Indexer = idx_get_indexer(); 569b41be24STom N Harris 57865c2687SKazutaka Miyasaka // parse the given query 589b41be24STom N Harris $q = ft_queryParser($Indexer, $data['query']); 59865c2687SKazutaka Miyasaka $data['highlight'] = $q['highlight']; 606840140fSChris Smith 61865c2687SKazutaka Miyasaka if (empty($q['parsed_ary'])) return array(); 62506fa893SAndreas Gohr 63f5eb7cf0SAndreas Gohr // lookup all words found in the query 649b41be24STom N Harris $lookup = $Indexer->lookup($q['words']); 65f5eb7cf0SAndreas Gohr 66865c2687SKazutaka Miyasaka // get all pages in this dokuwiki site (!: includes nonexistent pages) 67865c2687SKazutaka Miyasaka $pages_all = array(); 689b41be24STom N Harris foreach ($Indexer->getPages() as $id) { 699b41be24STom N Harris $pages_all[$id] = 0; // base: 0 hit 70f5eb7cf0SAndreas Gohr } 71f5eb7cf0SAndreas Gohr 72865c2687SKazutaka Miyasaka // process the query 73865c2687SKazutaka Miyasaka $stack = array(); 74865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 75865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 76865c2687SKazutaka Miyasaka case 'W+:': 772f502d70SKazutaka Miyasaka case 'W-:': 782f502d70SKazutaka Miyasaka case 'W_:': // word 79865c2687SKazutaka Miyasaka $word = substr($token, 3); 80865c2687SKazutaka Miyasaka $stack[] = (array) $lookup[$word]; 81865c2687SKazutaka Miyasaka break; 822f502d70SKazutaka Miyasaka case 'P+:': 832f502d70SKazutaka Miyasaka case 'P-:': // phrase 84865c2687SKazutaka Miyasaka $phrase = substr($token, 3); 85865c2687SKazutaka Miyasaka // since phrases are always parsed as ((W1)(W2)...(P)), 86865c2687SKazutaka Miyasaka // the end($stack) always points the pages that contain 87865c2687SKazutaka Miyasaka // all words in this phrase 88865c2687SKazutaka Miyasaka $pages = end($stack); 89865c2687SKazutaka Miyasaka $pages_matched = array(); 90865c2687SKazutaka Miyasaka foreach(array_keys($pages) as $id){ 91a7e8b43eSMichael Hamann $evdata = array( 92a7e8b43eSMichael Hamann 'id' => $id, 93a7e8b43eSMichael Hamann 'phrase' => $phrase, 94a7e8b43eSMichael Hamann 'text' => rawWiki($id) 95a7e8b43eSMichael Hamann ); 96e1d9dcc8SAndreas Gohr $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata); 97a7e8b43eSMichael Hamann if ($evt->advise_before() && $evt->result !== true) { 98*8cbc5ee8SAndreas Gohr $text = \dokuwiki\Utf8\PhpString::strtolower($evdata['text']); 99865c2687SKazutaka Miyasaka if (strpos($text, $phrase) !== false) { 100a7e8b43eSMichael Hamann $evt->result = true; 101a7e8b43eSMichael Hamann } 102a7e8b43eSMichael Hamann } 103a7e8b43eSMichael Hamann $evt->advise_after(); 104a7e8b43eSMichael Hamann if ($evt->result === true) { 105865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // phrase: always 0 hit 106865c2687SKazutaka Miyasaka } 107865c2687SKazutaka Miyasaka } 108865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 109865c2687SKazutaka Miyasaka break; 1102f502d70SKazutaka Miyasaka case 'N+:': 1112f502d70SKazutaka Miyasaka case 'N-:': // namespace 112de3383c6SMichael Große $ns = cleanID(substr($token, 3)) . ':'; 113865c2687SKazutaka Miyasaka $pages_matched = array(); 114865c2687SKazutaka Miyasaka foreach (array_keys($pages_all) as $id) { 115865c2687SKazutaka Miyasaka if (strpos($id, $ns) === 0) { 116865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // namespace: always 0 hit 117865c2687SKazutaka Miyasaka } 118865c2687SKazutaka Miyasaka } 119865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 120865c2687SKazutaka Miyasaka break; 121865c2687SKazutaka Miyasaka case 'AND': // and operation 122865c2687SKazutaka Miyasaka list($pages1, $pages2) = array_splice($stack, -2); 123865c2687SKazutaka Miyasaka $stack[] = ft_resultCombine(array($pages1, $pages2)); 124865c2687SKazutaka Miyasaka break; 125865c2687SKazutaka Miyasaka case 'OR': // or operation 126865c2687SKazutaka Miyasaka list($pages1, $pages2) = array_splice($stack, -2); 127865c2687SKazutaka Miyasaka $stack[] = ft_resultUnite(array($pages1, $pages2)); 128865c2687SKazutaka Miyasaka break; 129865c2687SKazutaka Miyasaka case 'NOT': // not operation (unary) 130865c2687SKazutaka Miyasaka $pages = array_pop($stack); 131865c2687SKazutaka Miyasaka $stack[] = ft_resultComplement(array($pages_all, $pages)); 132a21136cdSAndreas Gohr break; 133a21136cdSAndreas Gohr } 134f5eb7cf0SAndreas Gohr } 135865c2687SKazutaka Miyasaka $docs = array_pop($stack); 136865c2687SKazutaka Miyasaka 137865c2687SKazutaka Miyasaka if (empty($docs)) return array(); 138865c2687SKazutaka Miyasaka 139865c2687SKazutaka Miyasaka // check: settings, acls, existence 140865c2687SKazutaka Miyasaka foreach (array_keys($docs) as $id) { 141865c2687SKazutaka Miyasaka if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) { 142865c2687SKazutaka Miyasaka unset($docs[$id]); 143f5eb7cf0SAndreas Gohr } 144f5eb7cf0SAndreas Gohr } 145f5eb7cf0SAndreas Gohr 1463850270cSMichael Große $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']); 1478d0e286aSMichael Große 1488d0e286aSMichael Große if ($data['sort'] === 'mtime') { 1498d0e286aSMichael Große uksort($docs, 'ft_pagemtimesorter'); 1508d0e286aSMichael Große } else { 151865c2687SKazutaka Miyasaka // sort docs by count 152f5eb7cf0SAndreas Gohr arsort($docs); 1538d0e286aSMichael Große } 154f5eb7cf0SAndreas Gohr 155f5eb7cf0SAndreas Gohr return $docs; 156f5eb7cf0SAndreas Gohr} 157f5eb7cf0SAndreas Gohr 158f5eb7cf0SAndreas Gohr/** 15954f4c056SAndreas Gohr * Returns the backlinks for a given page 16054f4c056SAndreas Gohr * 161320f489aSMichael Hamann * Uses the metadata index. 16207ff0babSMichael Hamann * 16307ff0babSMichael Hamann * @param string $id The id for which links shall be returned 16407ff0babSMichael Hamann * @param bool $ignore_perms Ignore the fact that pages are hidden or read-protected 16507ff0babSMichael Hamann * @return array The pages that contain links to the given page 16654f4c056SAndreas Gohr */ 16707ff0babSMichael Hamannfunction ft_backlinks($id, $ignore_perms = false){ 168320f489aSMichael Hamann $result = idx_get_indexer()->lookupKey('relation_references', $id); 16954f4c056SAndreas Gohr 17063773904SAndreas Gohr if(!count($result)) return $result; 17163773904SAndreas Gohr 17263773904SAndreas Gohr // check ACL permissions 17363773904SAndreas Gohr foreach(array_keys($result) as $idx){ 17407ff0babSMichael Hamann if(($ignore_perms !== true && ( 17507ff0babSMichael Hamann isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 17607ff0babSMichael Hamann )) || !page_exists($result[$idx], '', false)){ 17763773904SAndreas Gohr unset($result[$idx]); 17863773904SAndreas Gohr } 17963773904SAndreas Gohr } 18063773904SAndreas Gohr 18154f4c056SAndreas Gohr sort($result); 18254f4c056SAndreas Gohr return $result; 18354f4c056SAndreas Gohr} 18454f4c056SAndreas Gohr 18554f4c056SAndreas Gohr/** 186a05e297aSAndreas Gohr * Returns the pages that use a given media file 187a05e297aSAndreas Gohr * 188ffec1009SMichael Hamann * Uses the relation media metadata property and the metadata index. 189a05e297aSAndreas Gohr * 190ffec1009SMichael Hamann * Note that before 2013-07-31 the second parameter was the maximum number of results and 191ffec1009SMichael Hamann * permissions were ignored. That's why the parameter is now checked to be explicitely set 192ffec1009SMichael Hamann * to true (with type bool) in order to be compatible with older uses of the function. 193ffec1009SMichael Hamann * 194ffec1009SMichael Hamann * @param string $id The media id to look for 195ffec1009SMichael Hamann * @param bool $ignore_perms Ignore hidden pages and acls (optional, default: false) 196ffec1009SMichael Hamann * @return array A list of pages that use the given media file 197a05e297aSAndreas Gohr */ 198ffec1009SMichael Hamannfunction ft_mediause($id, $ignore_perms = false){ 199ffec1009SMichael Hamann $result = idx_get_indexer()->lookupKey('relation_media', $id); 200a05e297aSAndreas Gohr 201ffec1009SMichael Hamann if(!count($result)) return $result; 202a05e297aSAndreas Gohr 203ffec1009SMichael Hamann // check ACL permissions 204ffec1009SMichael Hamann foreach(array_keys($result) as $idx){ 205ffec1009SMichael Hamann if(($ignore_perms !== true && ( 206ffec1009SMichael Hamann isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 207ffec1009SMichael Hamann )) || !page_exists($result[$idx], '', false)){ 208ffec1009SMichael Hamann unset($result[$idx]); 209a05e297aSAndreas Gohr } 210a05e297aSAndreas Gohr } 211a05e297aSAndreas Gohr 212a05e297aSAndreas Gohr sort($result); 213a05e297aSAndreas Gohr return $result; 214a05e297aSAndreas Gohr} 215a05e297aSAndreas Gohr 216a05e297aSAndreas Gohr 217a05e297aSAndreas Gohr/** 218506fa893SAndreas Gohr * Quicksearch for pagenames 219506fa893SAndreas Gohr * 220506fa893SAndreas Gohr * By default it only matches the pagename and ignores the 22180423ab6SAdrian Lang * namespace. This can be changed with the second parameter. 22280423ab6SAdrian Lang * The third parameter allows to search in titles as well. 223506fa893SAndreas Gohr * 2248d22f1e9SAndreas Gohr * The function always returns titles as well 2256840140fSChris Smith * 2268d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP 227506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 2288d22f1e9SAndreas Gohr * @author Adrian Lang <lang@cosmocode.de> 22942ea7f44SGerrit Uitslag * 23042ea7f44SGerrit Uitslag * @param string $id page id 23142ea7f44SGerrit Uitslag * @param bool $in_ns match against namespace as well? 23242ea7f44SGerrit Uitslag * @param bool $in_title search in title? 23364159a61SAndreas Gohr * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 23464159a61SAndreas Gohr * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 2353850270cSMichael Große * 23642ea7f44SGerrit Uitslag * @return string[] 237506fa893SAndreas Gohr */ 2383850270cSMichael Großefunction ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){ 2393850270cSMichael Große $data = [ 2403850270cSMichael Große 'id' => $id, 2413850270cSMichael Große 'in_ns' => $in_ns, 2423850270cSMichael Große 'in_title' => $in_title, 2433850270cSMichael Große 'after' => $after, 2443850270cSMichael Große 'before' => $before 2453850270cSMichael Große ]; 2468d22f1e9SAndreas Gohr $data['has_titles'] = true; // for plugin backward compatibility check 247cbb44eabSAndreas Gohr return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup'); 2486840140fSChris Smith} 2496840140fSChris Smith 25042ea7f44SGerrit Uitslag/** 25142ea7f44SGerrit Uitslag * Returns list of pages as array(pageid => First Heading) 25242ea7f44SGerrit Uitslag * 25342ea7f44SGerrit Uitslag * @param array &$data event data 25442ea7f44SGerrit Uitslag * @return string[] 25542ea7f44SGerrit Uitslag */ 2566840140fSChris Smithfunction _ft_pageLookup(&$data){ 25780423ab6SAdrian Lang // split out original parameters 2586840140fSChris Smith $id = $data['id']; 259940f24fcSMichael Große $Indexer = idx_get_indexer(); 260940f24fcSMichael Große $parsedQuery = ft_queryParser($Indexer, $id); 261940f24fcSMichael Große if (count($parsedQuery['ns']) > 0) { 262940f24fcSMichael Große $ns = cleanID($parsedQuery['ns'][0]) . ':'; 263940f24fcSMichael Große $id = implode(' ', $parsedQuery['highlight']); 264b0f6db0cSAdrian Lang } 265b0f6db0cSAdrian Lang 2668d22f1e9SAndreas Gohr $in_ns = $data['in_ns']; 2678d22f1e9SAndreas Gohr $in_title = $data['in_title']; 26880423ab6SAdrian Lang $cleaned = cleanID($id); 2699b41be24STom N Harris 2709b41be24STom N Harris $Indexer = idx_get_indexer(); 2719b41be24STom N Harris $page_idx = $Indexer->getPages(); 2729b41be24STom N Harris 2739b41be24STom N Harris $pages = array(); 2745479a8c3SAndreas Gohr if ($id !== '' && $cleaned !== '') { 2759b41be24STom N Harris foreach ($page_idx as $p_id) { 2769b41be24STom N Harris if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) { 2779b41be24STom N Harris if (!isset($pages[$p_id])) 27867c15eceSMichael Hamann $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 279506fa893SAndreas Gohr } 280506fa893SAndreas Gohr } 281f078bb00STom N Harris if ($in_title) { 282c66f16a3SMichael Hamann foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) { 283f078bb00STom N Harris if (!isset($pages[$p_id])) 28467c15eceSMichael Hamann $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 285f078bb00STom N Harris } 286f078bb00STom N Harris } 287d0bdf765SAdrian Lang } 2880c074a52SMichael Hamann 289d0bdf765SAdrian Lang if (isset($ns)) { 2900c074a52SMichael Hamann foreach (array_keys($pages) as $p_id) { 2910c074a52SMichael Hamann if (strpos($p_id, $ns) !== 0) { 2920c074a52SMichael Hamann unset($pages[$p_id]); 293d0bdf765SAdrian Lang } 294d0bdf765SAdrian Lang } 295506fa893SAndreas Gohr } 29663773904SAndreas Gohr 29780423ab6SAdrian Lang // discard hidden pages 29880423ab6SAdrian Lang // discard nonexistent pages 29963773904SAndreas Gohr // check ACL permissions 30063773904SAndreas Gohr foreach(array_keys($pages) as $idx){ 30180423ab6SAdrian Lang if(!isVisiblePage($idx) || !page_exists($idx) || 30280423ab6SAdrian Lang auth_quickaclcheck($idx) < AUTH_READ) { 30363773904SAndreas Gohr unset($pages[$idx]); 30463773904SAndreas Gohr } 30563773904SAndreas Gohr } 30663773904SAndreas Gohr 3073850270cSMichael Große $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']); 3081b48999cSMichael Große 3093d2017d9SAdrian Lang uksort($pages,'ft_pagesorter'); 3108d22f1e9SAndreas Gohr return $pages; 311506fa893SAndreas Gohr} 312506fa893SAndreas Gohr 3131b48999cSMichael Große 3141b48999cSMichael Große/** 3151b48999cSMichael Große * @param array $results search results in the form pageid => value 31664159a61SAndreas Gohr * @param int|string $after only returns results with mtime after this date, accepts timestap or strtotime arguments 31764159a61SAndreas Gohr * @param int|string $before only returns results with mtime after this date, accepts timestap or strtotime arguments 3181b48999cSMichael Große * 3191b48999cSMichael Große * @return array 3201b48999cSMichael Große */ 3213850270cSMichael Großefunction _ft_filterResultsByTime(array $results, $after, $before) { 3223850270cSMichael Große if ($after || $before) { 3231b48999cSMichael Große $after = is_int($after) ? $after : strtotime($after); 3241b48999cSMichael Große $before = is_int($before) ? $before : strtotime($before); 3251b48999cSMichael Große 3261b48999cSMichael Große foreach ($results as $id => $value) { 3271b48999cSMichael Große $mTime = filemtime(wikiFN($id)); 3281b48999cSMichael Große if ($after && $after > $mTime) { 3291b48999cSMichael Große unset($results[$id]); 3301b48999cSMichael Große continue; 3311b48999cSMichael Große } 3321b48999cSMichael Große if ($before && $before < $mTime) { 3331b48999cSMichael Große unset($results[$id]); 3341b48999cSMichael Große } 3351b48999cSMichael Große } 3361b48999cSMichael Große } 3371b48999cSMichael Große 3381b48999cSMichael Große return $results; 3391b48999cSMichael Große} 3401b48999cSMichael Große 341506fa893SAndreas Gohr/** 342c66f16a3SMichael Hamann * Tiny helper function for comparing the searched title with the title 343c66f16a3SMichael Hamann * from the search index. This function is a wrapper around stripos with 344c66f16a3SMichael Hamann * adapted argument order and return value. 34542ea7f44SGerrit Uitslag * 34642ea7f44SGerrit Uitslag * @param string $search searched title 34742ea7f44SGerrit Uitslag * @param string $title title from index 34842ea7f44SGerrit Uitslag * @return bool 349c66f16a3SMichael Hamann */ 350c66f16a3SMichael Hamannfunction _ft_pageLookupTitleCompare($search, $title) { 351c66f16a3SMichael Hamann return stripos($title, $search) !== false; 352c66f16a3SMichael Hamann} 353c66f16a3SMichael Hamann 354c66f16a3SMichael Hamann/** 355f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string 356f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy 357f31eb72bSAndreas Gohr * pages. 35842ea7f44SGerrit Uitslag * 35942ea7f44SGerrit Uitslag * @param string $a 36042ea7f44SGerrit Uitslag * @param string $b 36142ea7f44SGerrit Uitslag * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal. 362f31eb72bSAndreas Gohr */ 363f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){ 364f31eb72bSAndreas Gohr $ac = count(explode(':',$a)); 365f31eb72bSAndreas Gohr $bc = count(explode(':',$b)); 366f31eb72bSAndreas Gohr if($ac < $bc){ 367f31eb72bSAndreas Gohr return -1; 368f31eb72bSAndreas Gohr }elseif($ac > $bc){ 369f31eb72bSAndreas Gohr return 1; 370f31eb72bSAndreas Gohr } 371f31eb72bSAndreas Gohr return strcmp ($a,$b); 372f31eb72bSAndreas Gohr} 373f31eb72bSAndreas Gohr 374f31eb72bSAndreas Gohr/** 3758d0e286aSMichael Große * Sort pages by their mtime, from newest to oldest 3768d0e286aSMichael Große * 3778d0e286aSMichael Große * @param string $a 3788d0e286aSMichael Große * @param string $b 3798d0e286aSMichael Große * 3808d0e286aSMichael 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 3818d0e286aSMichael Große */ 3828d0e286aSMichael Großefunction ft_pagemtimesorter($a, $b) { 3838d0e286aSMichael Große $mtimeA = filemtime(wikiFN($a)); 3848d0e286aSMichael Große $mtimeB = filemtime(wikiFN($b)); 3858d0e286aSMichael Große return $mtimeB - $mtimeA; 3868d0e286aSMichael Große} 3878d0e286aSMichael Große 3888d0e286aSMichael Große/** 389506fa893SAndreas Gohr * Creates a snippet extract 390506fa893SAndreas Gohr * 391506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 39260e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE 39342ea7f44SGerrit Uitslag * 39442ea7f44SGerrit Uitslag * @param string $id page id 39542ea7f44SGerrit Uitslag * @param array $highlight 39642ea7f44SGerrit Uitslag * @return mixed 397506fa893SAndreas Gohr */ 398546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){ 399506fa893SAndreas Gohr $text = rawWiki($id); 4004f0030ddSAndreas Gohr $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens 40160e91a17SAndreas Gohr $evdata = array( 40260e91a17SAndreas Gohr 'id' => $id, 40360e91a17SAndreas Gohr 'text' => &$text, 40460e91a17SAndreas Gohr 'highlight' => &$highlight, 40560e91a17SAndreas Gohr 'snippet' => '', 40660e91a17SAndreas Gohr ); 40760e91a17SAndreas Gohr 408e1d9dcc8SAndreas Gohr $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata); 40960e91a17SAndreas Gohr if ($evt->advise_before()) { 410ced0762eSchris $match = array(); 411ced0762eSchris $snippets = array(); 4129ee93076Schris $utf8_offset = $offset = $end = 0; 413*8cbc5ee8SAndreas Gohr $len = \dokuwiki\Utf8\PhpString::strlen($text); 4149ee93076Schris 415546d3a99SAndreas Gohr // build a regexp from the phrases to highlight 41664159a61SAndreas Gohr $re1 = '(' . 41764159a61SAndreas Gohr join( 41864159a61SAndreas Gohr '|', 41964159a61SAndreas Gohr array_map( 42064159a61SAndreas Gohr 'ft_snippet_re_preprocess', 42164159a61SAndreas Gohr array_map( 42264159a61SAndreas Gohr 'preg_quote_cb', 42364159a61SAndreas Gohr array_filter((array) $highlight) 42464159a61SAndreas Gohr ) 42564159a61SAndreas Gohr ) 42664159a61SAndreas Gohr ) . 42764159a61SAndreas Gohr ')'; 428b571ff2dSChuck Kollars $re2 = "$re1.{0,75}(?!\\1)$re1"; 429b571ff2dSChuck Kollars $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; 430546d3a99SAndreas Gohr 431b571ff2dSChuck Kollars for ($cnt=4; $cnt--;) { 432b571ff2dSChuck Kollars if (0) { 433b571ff2dSChuck Kollars } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 434b571ff2dSChuck Kollars } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 435b571ff2dSChuck Kollars } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 436b571ff2dSChuck Kollars } else { 437b571ff2dSChuck Kollars break; 438b571ff2dSChuck Kollars } 439ced0762eSchris 440ced0762eSchris list($str,$idx) = $match[0]; 441ced0762eSchris 442ced0762eSchris // convert $idx (a byte offset) into a utf8 character offset 443*8cbc5ee8SAndreas Gohr $utf8_idx = \dokuwiki\Utf8\PhpString::strlen(substr($text,0,$idx)); 444*8cbc5ee8SAndreas Gohr $utf8_len = \dokuwiki\Utf8\PhpString::strlen($str); 445ced0762eSchris 446ced0762eSchris // establish context, 100 bytes surrounding the match string 447ced0762eSchris // first look to see if we can go 100 either side, 448ced0762eSchris // then drop to 50 adding any excess if the other side can't go to 50, 449ced0762eSchris $pre = min($utf8_idx-$utf8_offset,100); 450ced0762eSchris $post = min($len-$utf8_idx-$utf8_len,100); 451ced0762eSchris 452ced0762eSchris if ($pre>50 && $post>50) { 453ced0762eSchris $pre = $post = 50; 454ced0762eSchris } else if ($pre>50) { 455ced0762eSchris $pre = min($pre,100-$post); 456ced0762eSchris } else if ($post>50) { 457ced0762eSchris $post = min($post, 100-$pre); 458ef3e3cddSMichael Hamann } else if ($offset == 0) { 459ced0762eSchris // both are less than 50, means the context is the whole string 46010ffc9ddSAndreas Gohr // make it so and break out of this loop - there is no need for the 46110ffc9ddSAndreas Gohr // complex snippet calculations 462ced0762eSchris $snippets = array($text); 463ced0762eSchris break; 464ced0762eSchris } 465ced0762eSchris 46610ffc9ddSAndreas Gohr // establish context start and end points, try to append to previous 46710ffc9ddSAndreas Gohr // context if possible 4689ee93076Schris $start = $utf8_idx - $pre; 469ced0762eSchris $append = ($start < $end) ? $end : false; // still the end of the previous context snippet 4709ee93076Schris $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context 471ced0762eSchris 472ced0762eSchris if ($append) { 473*8cbc5ee8SAndreas Gohr $snippets[count($snippets)-1] .= \dokuwiki\Utf8\PhpString::substr($text,$append,$end-$append); 474ced0762eSchris } else { 475*8cbc5ee8SAndreas Gohr $snippets[] = \dokuwiki\Utf8\PhpString::substr($text,$start,$end-$start); 476ced0762eSchris } 477ced0762eSchris 478ced0762eSchris // set $offset for next match attempt 47943d58b76SMichael Hamann // continue matching after the current match 48043d58b76SMichael Hamann // if the current match is not the longest possible match starting at the current offset 48143d58b76SMichael Hamann // this prevents further matching of this snippet but for possible matches of length 48243d58b76SMichael Hamann // smaller than match length + context (at least 50 characters) this match is part of the context 48343d58b76SMichael Hamann $utf8_offset = $utf8_idx + $utf8_len; 484*8cbc5ee8SAndreas Gohr $offset = $idx + strlen(\dokuwiki\Utf8\PhpString::substr($text,$utf8_idx,$utf8_len)); 485*8cbc5ee8SAndreas Gohr $offset = \dokuwiki\Utf8\Clean::correctIdx($text,$offset); 4869ee93076Schris } 4879ee93076Schris 488ced0762eSchris $m = "\1"; 489b571ff2dSChuck Kollars $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets); 49064159a61SAndreas Gohr $snippet = preg_replace( 49164159a61SAndreas Gohr '/' . $m . '([^' . $m . ']*?)' . $m . '/iu', 49264159a61SAndreas Gohr '<strong class="search_hit">$1</strong>', 49364159a61SAndreas Gohr hsc(join('... ', $snippets)) 49464159a61SAndreas Gohr ); 495bd2cb6fcSchris 49660e91a17SAndreas Gohr $evdata['snippet'] = $snippet; 49760e91a17SAndreas Gohr } 49860e91a17SAndreas Gohr $evt->advise_after(); 49960e91a17SAndreas Gohr unset($evt); 50060e91a17SAndreas Gohr 50160e91a17SAndreas Gohr return $evdata['snippet']; 502506fa893SAndreas Gohr} 503506fa893SAndreas Gohr 504506fa893SAndreas Gohr/** 50526eb848cSGina Haeussge * Wraps a search term in regex boundary checks. 50642ea7f44SGerrit Uitslag * 50742ea7f44SGerrit Uitslag * @param string $term 50842ea7f44SGerrit Uitslag * @return string 50926eb848cSGina Haeussge */ 5102237b4faSAndreas Gohrfunction ft_snippet_re_preprocess($term) { 51135594613SKazutaka Miyasaka // do not process asian terms where word boundaries are not explicit 51235594613SKazutaka Miyasaka if(preg_match('/'.IDX_ASIAN.'/u',$term)){ 51335594613SKazutaka Miyasaka return $term; 51435594613SKazutaka Miyasaka } 51535594613SKazutaka Miyasaka 5163161005dSAndreas Gohr if (UTF8_PROPERTYSUPPORT) { 51784e581a6SAndreas Gohr // unicode word boundaries 51884e581a6SAndreas Gohr // see http://stackoverflow.com/a/2449017/172068 51984e581a6SAndreas Gohr $BL = '(?<!\pL)'; 52084e581a6SAndreas Gohr $BR = '(?!\pL)'; 5213161005dSAndreas Gohr } else { 5223161005dSAndreas Gohr // not as correct as above, but at least won't break 5233161005dSAndreas Gohr $BL = '\b'; 5243161005dSAndreas Gohr $BR = '\b'; 5253161005dSAndreas Gohr } 5263161005dSAndreas Gohr 5272237b4faSAndreas Gohr if(substr($term,0,2) == '\\*'){ 5282237b4faSAndreas Gohr $term = substr($term,2); 5292237b4faSAndreas Gohr }else{ 53084e581a6SAndreas Gohr $term = $BL.$term; 5312237b4faSAndreas Gohr } 5322237b4faSAndreas Gohr 5332237b4faSAndreas Gohr if(substr($term,-2,2) == '\\*'){ 5342237b4faSAndreas Gohr $term = substr($term,0,-2); 5352237b4faSAndreas Gohr }else{ 53684e581a6SAndreas Gohr $term = $term.$BR; 5372237b4faSAndreas Gohr } 5388a803caeSAndreas Gohr 53984e581a6SAndreas Gohr if($term == $BL || $term == $BR || $term == $BL.$BR) $term = ''; 5402237b4faSAndreas Gohr return $term; 54126eb848cSGina Haeussge} 54226eb848cSGina Haeussge 54326eb848cSGina Haeussge/** 544f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores 545f5eb7cf0SAndreas Gohr * 546f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical 547f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned. 548f5eb7cf0SAndreas Gohr * 549f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key() 550f5eb7cf0SAndreas Gohr * 551f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays 55242ea7f44SGerrit Uitslag * @return array 553f5eb7cf0SAndreas Gohr */ 554f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){ 555f5eb7cf0SAndreas Gohr $array_count = count($args); 556134f4ab2SAndreas Gohr if($array_count == 1){ 557134f4ab2SAndreas Gohr return $args[0]; 558134f4ab2SAndreas Gohr } 559134f4ab2SAndreas Gohr 560f5eb7cf0SAndreas Gohr $result = array(); 56109c27a6dSGuy Brand if ($array_count > 1) { 562a21136cdSAndreas Gohr foreach ($args[0] as $key => $value) { 563a21136cdSAndreas Gohr $result[$key] = $value; 564f5eb7cf0SAndreas Gohr for ($i = 1; $i !== $array_count; $i++) { 565a21136cdSAndreas Gohr if (!isset($args[$i][$key])) { 566a21136cdSAndreas Gohr unset($result[$key]); 567a21136cdSAndreas Gohr break; 568f5eb7cf0SAndreas Gohr } 569a21136cdSAndreas Gohr $result[$key] += $args[$i][$key]; 570f5eb7cf0SAndreas Gohr } 571f5eb7cf0SAndreas Gohr } 57209c27a6dSGuy Brand } 573f5eb7cf0SAndreas Gohr return $result; 574f5eb7cf0SAndreas Gohr} 575f5eb7cf0SAndreas Gohr 576f5eb7cf0SAndreas Gohr/** 577865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores 578f5eb7cf0SAndreas Gohr * 579865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function 580865c2687SKazutaka Miyasaka * 581865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 58242ea7f44SGerrit Uitslag * @return array 58342ea7f44SGerrit Uitslag * 584865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 585865c2687SKazutaka Miyasaka */ 586865c2687SKazutaka Miyasakafunction ft_resultUnite($args) { 587865c2687SKazutaka Miyasaka $array_count = count($args); 588865c2687SKazutaka Miyasaka if ($array_count === 1) { 589865c2687SKazutaka Miyasaka return $args[0]; 590865c2687SKazutaka Miyasaka } 591865c2687SKazutaka Miyasaka 592865c2687SKazutaka Miyasaka $result = $args[0]; 593865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 594865c2687SKazutaka Miyasaka foreach (array_keys($args[$i]) as $id) { 595865c2687SKazutaka Miyasaka $result[$id] += $args[$i][$id]; 596865c2687SKazutaka Miyasaka } 597865c2687SKazutaka Miyasaka } 598865c2687SKazutaka Miyasaka return $result; 599865c2687SKazutaka Miyasaka} 600865c2687SKazutaka Miyasaka 601865c2687SKazutaka Miyasaka/** 602865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison 603865c2687SKazutaka Miyasaka * 604865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key() 605865c2687SKazutaka Miyasaka * 606865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 60742ea7f44SGerrit Uitslag * @return array 60842ea7f44SGerrit Uitslag * 609865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 610865c2687SKazutaka Miyasaka */ 611865c2687SKazutaka Miyasakafunction ft_resultComplement($args) { 612865c2687SKazutaka Miyasaka $array_count = count($args); 613865c2687SKazutaka Miyasaka if ($array_count === 1) { 614865c2687SKazutaka Miyasaka return $args[0]; 615865c2687SKazutaka Miyasaka } 616865c2687SKazutaka Miyasaka 617865c2687SKazutaka Miyasaka $result = $args[0]; 618865c2687SKazutaka Miyasaka foreach (array_keys($result) as $id) { 619865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 620865c2687SKazutaka Miyasaka if (isset($args[$i][$id])) unset($result[$id]); 621865c2687SKazutaka Miyasaka } 622865c2687SKazutaka Miyasaka } 623865c2687SKazutaka Miyasaka return $result; 624865c2687SKazutaka Miyasaka} 625865c2687SKazutaka Miyasaka 626865c2687SKazutaka Miyasaka/** 627865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas 628865c2687SKazutaka Miyasaka * 629865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 630865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 63142ea7f44SGerrit Uitslag * 63242ea7f44SGerrit Uitslag * @param Doku_Indexer $Indexer 63342ea7f44SGerrit Uitslag * @param string $query search query 63442ea7f44SGerrit Uitslag * @return array of search formulas 635f5eb7cf0SAndreas Gohr */ 6369b41be24STom N Harrisfunction ft_queryParser($Indexer, $query){ 637865c2687SKazutaka Miyasaka /** 638865c2687SKazutaka Miyasaka * parse a search query and transform it into intermediate representation 639865c2687SKazutaka Miyasaka * 640865c2687SKazutaka Miyasaka * in a search query, you can use the following expressions: 641865c2687SKazutaka Miyasaka * 642865c2687SKazutaka Miyasaka * words: 643865c2687SKazutaka Miyasaka * include 644865c2687SKazutaka Miyasaka * -exclude 645865c2687SKazutaka Miyasaka * phrases: 646865c2687SKazutaka Miyasaka * "phrase to be included" 647865c2687SKazutaka Miyasaka * -"phrase you want to exclude" 648865c2687SKazutaka Miyasaka * namespaces: 649865c2687SKazutaka Miyasaka * @include:namespace (or ns:include:namespace) 650865c2687SKazutaka Miyasaka * ^exclude:namespace (or -ns:exclude:namespace) 651865c2687SKazutaka Miyasaka * groups: 652865c2687SKazutaka Miyasaka * () 653865c2687SKazutaka Miyasaka * -() 654865c2687SKazutaka Miyasaka * operators: 655865c2687SKazutaka Miyasaka * and ('and' is the default operator: you can always omit this) 6567871d415SKazutaka Miyasaka * or (or pipe symbol '|', lower precedence than 'and') 657865c2687SKazutaka Miyasaka * 658865c2687SKazutaka Miyasaka * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain 659865c2687SKazutaka Miyasaka * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". 660865c2687SKazutaka Miyasaka * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] 661865c2687SKazutaka Miyasaka * as long as you don't mind hit counts. 662865c2687SKazutaka Miyasaka * 663865c2687SKazutaka Miyasaka * intermediate representation consists of the following parts: 664865c2687SKazutaka Miyasaka * 665865c2687SKazutaka Miyasaka * ( ) - group 666865c2687SKazutaka Miyasaka * AND - logical and 667865c2687SKazutaka Miyasaka * OR - logical or 668865c2687SKazutaka Miyasaka * NOT - logical not 6692f502d70SKazutaka Miyasaka * W+:, W-:, W_: - word (underscore: no need to highlight) 6702f502d70SKazutaka Miyasaka * P+:, P-: - phrase (minus sign: logically in NOT group) 6712f502d70SKazutaka Miyasaka * N+:, N-: - namespace 672865c2687SKazutaka Miyasaka */ 673865c2687SKazutaka Miyasaka $parsed_query = ''; 674865c2687SKazutaka Miyasaka $parens_level = 0; 675*8cbc5ee8SAndreas Gohr $terms = preg_split('/(-?".*?")/u', \dokuwiki\Utf8\PhpString::strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 676865c2687SKazutaka Miyasaka 677865c2687SKazutaka Miyasaka foreach ($terms as $term) { 678865c2687SKazutaka Miyasaka $parsed = ''; 679865c2687SKazutaka Miyasaka if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { 680865c2687SKazutaka Miyasaka // phrase-include and phrase-exclude 681865c2687SKazutaka Miyasaka $not = $matches[1] ? 'NOT' : ''; 6829b41be24STom N Harris $parsed = $not.ft_termParser($Indexer, $matches[2], false, true); 683f5eb7cf0SAndreas Gohr } else { 684865c2687SKazutaka Miyasaka // fix incomplete phrase 685865c2687SKazutaka Miyasaka $term = str_replace('"', ' ', $term); 686865c2687SKazutaka Miyasaka 687865c2687SKazutaka Miyasaka // fix parentheses 688865c2687SKazutaka Miyasaka $term = str_replace(')' , ' ) ', $term); 689865c2687SKazutaka Miyasaka $term = str_replace('(' , ' ( ', $term); 690865c2687SKazutaka Miyasaka $term = str_replace('- (', ' -(', $term); 691865c2687SKazutaka Miyasaka 6927871d415SKazutaka Miyasaka // treat pipe symbols as 'OR' operators 6937871d415SKazutaka Miyasaka $term = str_replace('|', ' or ', $term); 6947871d415SKazutaka Miyasaka 695865c2687SKazutaka Miyasaka // treat ideographic spaces (U+3000) as search term separators 696865c2687SKazutaka Miyasaka // FIXME: some more separators? 697865c2687SKazutaka Miyasaka $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); 698865c2687SKazutaka Miyasaka $term = trim($term); 699865c2687SKazutaka Miyasaka if ($term === '') continue; 700865c2687SKazutaka Miyasaka 701865c2687SKazutaka Miyasaka $tokens = explode(' ', $term); 702865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 703865c2687SKazutaka Miyasaka if ($token === '(') { 704865c2687SKazutaka Miyasaka // parenthesis-include-open 705865c2687SKazutaka Miyasaka $parsed .= '('; 706865c2687SKazutaka Miyasaka ++$parens_level; 707865c2687SKazutaka Miyasaka } elseif ($token === '-(') { 708865c2687SKazutaka Miyasaka // parenthesis-exclude-open 709865c2687SKazutaka Miyasaka $parsed .= 'NOT('; 710865c2687SKazutaka Miyasaka ++$parens_level; 711865c2687SKazutaka Miyasaka } elseif ($token === ')') { 712865c2687SKazutaka Miyasaka // parenthesis-any-close 713865c2687SKazutaka Miyasaka if ($parens_level === 0) continue; 714865c2687SKazutaka Miyasaka $parsed .= ')'; 715865c2687SKazutaka Miyasaka $parens_level--; 716865c2687SKazutaka Miyasaka } elseif ($token === 'and') { 717865c2687SKazutaka Miyasaka // logical-and (do nothing) 718865c2687SKazutaka Miyasaka } elseif ($token === 'or') { 719865c2687SKazutaka Miyasaka // logical-or 720865c2687SKazutaka Miyasaka $parsed .= 'OR'; 721865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { 722865c2687SKazutaka Miyasaka // namespace-exclude 7232f502d70SKazutaka Miyasaka $parsed .= 'NOT(N+:'.$matches[1].')'; 724865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { 725865c2687SKazutaka Miyasaka // namespace-include 7262f502d70SKazutaka Miyasaka $parsed .= '(N+:'.$matches[1].')'; 727865c2687SKazutaka Miyasaka } elseif (preg_match('/^-(.+)$/', $token, $matches)) { 728865c2687SKazutaka Miyasaka // word-exclude 7299b41be24STom N Harris $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')'; 730865c2687SKazutaka Miyasaka } else { 731865c2687SKazutaka Miyasaka // word-include 7329b41be24STom N Harris $parsed .= ft_termParser($Indexer, $token); 733865c2687SKazutaka Miyasaka } 734865c2687SKazutaka Miyasaka } 735865c2687SKazutaka Miyasaka } 736865c2687SKazutaka Miyasaka $parsed_query .= $parsed; 737f5eb7cf0SAndreas Gohr } 738f5eb7cf0SAndreas Gohr 739865c2687SKazutaka Miyasaka // cleanup (very sensitive) 740865c2687SKazutaka Miyasaka $parsed_query .= str_repeat(')', $parens_level); 741865c2687SKazutaka Miyasaka do { 742865c2687SKazutaka Miyasaka $parsed_query_old = $parsed_query; 743865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); 744865c2687SKazutaka Miyasaka } while ($parsed_query !== $parsed_query_old); 745865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query); 746865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query); 747865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query); 748865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query); 749865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query); 750865c2687SKazutaka Miyasaka 7512f502d70SKazutaka Miyasaka // adjustment: make highlightings right 7522f502d70SKazutaka Miyasaka $parens_level = 0; 7532f502d70SKazutaka Miyasaka $notgrp_levels = array(); 7542f502d70SKazutaka Miyasaka $parsed_query_new = ''; 7552f502d70SKazutaka Miyasaka $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 7562f502d70SKazutaka Miyasaka foreach ($tokens as $token) { 7572f502d70SKazutaka Miyasaka if ($token === 'NOT(') { 7582f502d70SKazutaka Miyasaka $notgrp_levels[] = ++$parens_level; 7592f502d70SKazutaka Miyasaka } elseif ($token === '(') { 7602f502d70SKazutaka Miyasaka ++$parens_level; 7612f502d70SKazutaka Miyasaka } elseif ($token === ')') { 7622f502d70SKazutaka Miyasaka if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels); 7632f502d70SKazutaka Miyasaka } elseif (count($notgrp_levels) % 2 === 1) { 7642f502d70SKazutaka Miyasaka // turn highlight-flag off if terms are logically in "NOT" group 7652f502d70SKazutaka Miyasaka $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token); 7662f502d70SKazutaka Miyasaka } 7672f502d70SKazutaka Miyasaka $parsed_query_new .= $token; 7682f502d70SKazutaka Miyasaka } 7692f502d70SKazutaka Miyasaka $parsed_query = $parsed_query_new; 7702f502d70SKazutaka Miyasaka 771865c2687SKazutaka Miyasaka /** 772865c2687SKazutaka Miyasaka * convert infix notation string into postfix (Reverse Polish notation) array 773865c2687SKazutaka Miyasaka * by Shunting-yard algorithm 774865c2687SKazutaka Miyasaka * 775865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation 776865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm 777865c2687SKazutaka Miyasaka */ 778865c2687SKazutaka Miyasaka $parsed_ary = array(); 779865c2687SKazutaka Miyasaka $ope_stack = array(); 780865c2687SKazutaka Miyasaka $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5); 781865c2687SKazutaka Miyasaka $ope_regex = '/([()]|OR|AND|NOT)/u'; 782865c2687SKazutaka Miyasaka 783865c2687SKazutaka Miyasaka $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 784865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 785865c2687SKazutaka Miyasaka if (preg_match($ope_regex, $token)) { 786865c2687SKazutaka Miyasaka // operator 787865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 78867d812e0SMarius van Witzenburg while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { 789865c2687SKazutaka Miyasaka $parsed_ary[] = array_pop($ope_stack); 790865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 791865c2687SKazutaka Miyasaka } 792865c2687SKazutaka Miyasaka if ($token == ')') { 793865c2687SKazutaka Miyasaka array_pop($ope_stack); // this array_pop always deletes '(' 794865c2687SKazutaka Miyasaka } else { 795865c2687SKazutaka Miyasaka $ope_stack[] = $token; 796865c2687SKazutaka Miyasaka } 797865c2687SKazutaka Miyasaka } else { 798865c2687SKazutaka Miyasaka // operand 799865c2687SKazutaka Miyasaka $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token); 800865c2687SKazutaka Miyasaka $parsed_ary[] = $token_decoded; 801865c2687SKazutaka Miyasaka } 802865c2687SKazutaka Miyasaka } 803865c2687SKazutaka Miyasaka $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack))); 804865c2687SKazutaka Miyasaka 805865c2687SKazutaka Miyasaka // cleanup: each double "NOT" in RPN array actually does nothing 806865c2687SKazutaka Miyasaka $parsed_ary_count = count($parsed_ary); 807865c2687SKazutaka Miyasaka for ($i = 1; $i < $parsed_ary_count; ++$i) { 808865c2687SKazutaka Miyasaka if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { 809865c2687SKazutaka Miyasaka unset($parsed_ary[$i], $parsed_ary[$i - 1]); 810865c2687SKazutaka Miyasaka } 811865c2687SKazutaka Miyasaka } 812865c2687SKazutaka Miyasaka $parsed_ary = array_values($parsed_ary); 813865c2687SKazutaka Miyasaka 814865c2687SKazutaka Miyasaka // build return value 815f5eb7cf0SAndreas Gohr $q = array(); 816f5eb7cf0SAndreas Gohr $q['query'] = $query; 817865c2687SKazutaka Miyasaka $q['parsed_str'] = $parsed_query; 818865c2687SKazutaka Miyasaka $q['parsed_ary'] = $parsed_ary; 819f5eb7cf0SAndreas Gohr 820865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 821865c2687SKazutaka Miyasaka if ($token[2] !== ':') continue; 822865c2687SKazutaka Miyasaka $body = substr($token, 3); 823865c2687SKazutaka Miyasaka 824865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 8252f502d70SKazutaka Miyasaka case 'N+:': 826865c2687SKazutaka Miyasaka $q['ns'][] = $body; // for backward compatibility 827865c2687SKazutaka Miyasaka break; 8282f502d70SKazutaka Miyasaka case 'N-:': 8292f502d70SKazutaka Miyasaka $q['notns'][] = $body; // for backward compatibility 8302f502d70SKazutaka Miyasaka break; 8312f502d70SKazutaka Miyasaka case 'W_:': 8322f502d70SKazutaka Miyasaka $q['words'][] = $body; 8332f502d70SKazutaka Miyasaka break; 834865c2687SKazutaka Miyasaka case 'W-:': 835865c2687SKazutaka Miyasaka $q['words'][] = $body; 8362f502d70SKazutaka Miyasaka $q['not'][] = $body; // for backward compatibility 837865c2687SKazutaka Miyasaka break; 838865c2687SKazutaka Miyasaka case 'W+:': 839865c2687SKazutaka Miyasaka $q['words'][] = $body; 8402237b4faSAndreas Gohr $q['highlight'][] = $body; 8412f502d70SKazutaka Miyasaka $q['and'][] = $body; // for backward compatibility 842865c2687SKazutaka Miyasaka break; 8432f502d70SKazutaka Miyasaka case 'P-:': 8442f502d70SKazutaka Miyasaka $q['phrases'][] = $body; 8452f502d70SKazutaka Miyasaka break; 8462f502d70SKazutaka Miyasaka case 'P+:': 847865c2687SKazutaka Miyasaka $q['phrases'][] = $body; 8482237b4faSAndreas Gohr $q['highlight'][] = $body; 849865c2687SKazutaka Miyasaka break; 850865c2687SKazutaka Miyasaka } 851865c2687SKazutaka Miyasaka } 8522f502d70SKazutaka Miyasaka foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) { 853865c2687SKazutaka Miyasaka $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key])); 854f5eb7cf0SAndreas Gohr } 855f5eb7cf0SAndreas Gohr 856f5eb7cf0SAndreas Gohr return $q; 857f5eb7cf0SAndreas Gohr} 858f5eb7cf0SAndreas Gohr 859865c2687SKazutaka Miyasaka/** 860865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation 861865c2687SKazutaka Miyasaka * 862865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use. 863865c2687SKazutaka Miyasaka * 864865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 86542ea7f44SGerrit Uitslag * 86642ea7f44SGerrit Uitslag * @param Doku_Indexer $Indexer 86742ea7f44SGerrit Uitslag * @param string $term 86842ea7f44SGerrit Uitslag * @param bool $consider_asian 86942ea7f44SGerrit Uitslag * @param bool $phrase_mode 87042ea7f44SGerrit Uitslag * @return string 871865c2687SKazutaka Miyasaka */ 8729b41be24STom N Harrisfunction ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) { 873865c2687SKazutaka Miyasaka $parsed = ''; 874865c2687SKazutaka Miyasaka if ($consider_asian) { 875865c2687SKazutaka Miyasaka // successive asian characters need to be searched as a phrase 876865c2687SKazutaka Miyasaka $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 877865c2687SKazutaka Miyasaka foreach ($words as $word) { 8786ac2077aSKazutaka Miyasaka $phrase_mode = $phrase_mode ? true : preg_match('/'.IDX_ASIAN.'/u', $word); 8799b41be24STom N Harris $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode); 880865c2687SKazutaka Miyasaka } 881865c2687SKazutaka Miyasaka } else { 882865c2687SKazutaka Miyasaka $term_noparen = str_replace(array('(', ')'), ' ', $term); 8839b41be24STom N Harris $words = $Indexer->tokenizer($term_noparen, true); 884865c2687SKazutaka Miyasaka 8852f502d70SKazutaka Miyasaka // W_: no need to highlight 886865c2687SKazutaka Miyasaka if (empty($words)) { 887865c2687SKazutaka Miyasaka $parsed = '()'; // important: do not remove 888865c2687SKazutaka Miyasaka } elseif ($words[0] === $term) { 889865c2687SKazutaka Miyasaka $parsed = '(W+:'.$words[0].')'; 890865c2687SKazutaka Miyasaka } elseif ($phrase_mode) { 891865c2687SKazutaka Miyasaka $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term); 8922f502d70SKazutaka Miyasaka $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))'; 893865c2687SKazutaka Miyasaka } else { 894865c2687SKazutaka Miyasaka $parsed = '((W+:'.implode(')(W+:', $words).'))'; 895865c2687SKazutaka Miyasaka } 896865c2687SKazutaka Miyasaka } 897865c2687SKazutaka Miyasaka return $parsed; 898865c2687SKazutaka Miyasaka} 899865c2687SKazutaka Miyasaka 90044156e11SMichael Große/** 90144156e11SMichael Große * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches 90244156e11SMichael Große * 90344156e11SMichael Große * @param array $and 90444156e11SMichael Große * @param array $not 90544156e11SMichael Große * @param array $phrases 90644156e11SMichael Große * @param array $ns 90744156e11SMichael Große * @param array $notns 90844156e11SMichael Große * 90944156e11SMichael Große * @return string 91044156e11SMichael Große */ 91144156e11SMichael Großefunction ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) { 91244156e11SMichael Große $query = implode(' ', $and); 91344156e11SMichael Große if (!empty($not)) { 91444156e11SMichael Große $query .= ' -' . implode(' -', $not); 91544156e11SMichael Große } 91644156e11SMichael Große 91744156e11SMichael Große if (!empty($phrases)) { 91844156e11SMichael Große $query .= ' "' . implode('" "', $phrases) . '"'; 91944156e11SMichael Große } 92044156e11SMichael Große 92144156e11SMichael Große if (!empty($ns)) { 92244156e11SMichael Große $query .= ' @' . implode(' @', $ns); 92344156e11SMichael Große } 92444156e11SMichael Große 92544156e11SMichael Große if (!empty($notns)) { 92644156e11SMichael Große $query .= ' ^' . implode(' ^', $notns); 92744156e11SMichael Große } 92844156e11SMichael Große 92944156e11SMichael Große return $query; 93044156e11SMichael Große} 93144156e11SMichael Große 932e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 : 933