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> 7f5eb7cf0SAndreas Gohr */ 8f5eb7cf0SAndreas Gohr 9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.'); 10f5eb7cf0SAndreas Gohrrequire_once(DOKU_INC.'inc/indexer.php'); 11f5eb7cf0SAndreas Gohr 12f5eb7cf0SAndreas Gohr 13f5eb7cf0SAndreas Gohr/** 14f5eb7cf0SAndreas Gohr * The fulltext search 15f5eb7cf0SAndreas Gohr * 16f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query 17506fa893SAndreas Gohr * 186840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event() 196840140fSChris Smith * 20f5eb7cf0SAndreas Gohr */ 21546d3a99SAndreas Gohrfunction ft_pageSearch($query,&$highlight){ 226840140fSChris Smith 236840140fSChris Smith $data['query'] = $query; 246840140fSChris Smith $data['highlight'] =& $highlight; 256840140fSChris Smith 266840140fSChris Smith return trigger_event('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch'); 276840140fSChris Smith} 28865c2687SKazutaka Miyasaka 29865c2687SKazutaka Miyasaka/** 30865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query 31865c2687SKazutaka Miyasaka * 32865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 33865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 34865c2687SKazutaka Miyasaka */ 356840140fSChris Smithfunction _ft_pageSearch(&$data) { 36865c2687SKazutaka Miyasaka // parse the given query 37865c2687SKazutaka Miyasaka $q = ft_queryParser($data['query']); 38865c2687SKazutaka Miyasaka $data['highlight'] = $q['highlight']; 396840140fSChris Smith 40865c2687SKazutaka Miyasaka if (empty($q['parsed_ary'])) return array(); 41506fa893SAndreas Gohr 42f5eb7cf0SAndreas Gohr // lookup all words found in the query 43865c2687SKazutaka Miyasaka $lookup = idx_lookup($q['words']); 44f5eb7cf0SAndreas Gohr 45865c2687SKazutaka Miyasaka // get all pages in this dokuwiki site (!: includes nonexistent pages) 46865c2687SKazutaka Miyasaka $pages_all = array(); 47865c2687SKazutaka Miyasaka foreach (idx_getIndex('page', '') as $id) { 48865c2687SKazutaka Miyasaka $pages_all[trim($id)] = 0; // base: 0 hit 49f5eb7cf0SAndreas Gohr } 50f5eb7cf0SAndreas Gohr 51865c2687SKazutaka Miyasaka // process the query 52865c2687SKazutaka Miyasaka $stack = array(); 53865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 54865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 55865c2687SKazutaka Miyasaka case 'W+:': 56865c2687SKazutaka Miyasaka case 'W-:': // word 57865c2687SKazutaka Miyasaka $word = substr($token, 3); 58865c2687SKazutaka Miyasaka $stack[] = (array) $lookup[$word]; 59865c2687SKazutaka Miyasaka break; 60865c2687SKazutaka Miyasaka case 'P_:': // phrase 61865c2687SKazutaka Miyasaka $phrase = substr($token, 3); 62865c2687SKazutaka Miyasaka // since phrases are always parsed as ((W1)(W2)...(P)), 63865c2687SKazutaka Miyasaka // the end($stack) always points the pages that contain 64865c2687SKazutaka Miyasaka // all words in this phrase 65865c2687SKazutaka Miyasaka $pages = end($stack); 66865c2687SKazutaka Miyasaka $pages_matched = array(); 67865c2687SKazutaka Miyasaka foreach(array_keys($pages) as $id){ 68f5eb7cf0SAndreas Gohr $text = utf8_strtolower(rawWiki($id)); 69865c2687SKazutaka Miyasaka if (strpos($text, $phrase) !== false) { 70865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // phrase: always 0 hit 71865c2687SKazutaka Miyasaka } 72865c2687SKazutaka Miyasaka } 73865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 74865c2687SKazutaka Miyasaka break; 75865c2687SKazutaka Miyasaka case 'N_:': // namespace 76865c2687SKazutaka Miyasaka $ns = substr($token, 3); 77865c2687SKazutaka Miyasaka $pages_matched = array(); 78865c2687SKazutaka Miyasaka foreach (array_keys($pages_all) as $id) { 79865c2687SKazutaka Miyasaka if (strpos($id, $ns) === 0) { 80865c2687SKazutaka Miyasaka $pages_matched[$id] = 0; // namespace: always 0 hit 81865c2687SKazutaka Miyasaka } 82865c2687SKazutaka Miyasaka } 83865c2687SKazutaka Miyasaka $stack[] = $pages_matched; 84865c2687SKazutaka Miyasaka break; 85865c2687SKazutaka Miyasaka case 'AND': // and operation 86865c2687SKazutaka Miyasaka list($pages1, $pages2) = array_splice($stack, -2); 87865c2687SKazutaka Miyasaka $stack[] = ft_resultCombine(array($pages1, $pages2)); 88865c2687SKazutaka Miyasaka break; 89865c2687SKazutaka Miyasaka case 'OR': // or operation 90865c2687SKazutaka Miyasaka list($pages1, $pages2) = array_splice($stack, -2); 91865c2687SKazutaka Miyasaka $stack[] = ft_resultUnite(array($pages1, $pages2)); 92865c2687SKazutaka Miyasaka break; 93865c2687SKazutaka Miyasaka case 'NOT': // not operation (unary) 94865c2687SKazutaka Miyasaka $pages = array_pop($stack); 95865c2687SKazutaka Miyasaka $stack[] = ft_resultComplement(array($pages_all, $pages)); 96a21136cdSAndreas Gohr break; 97a21136cdSAndreas Gohr } 98f5eb7cf0SAndreas Gohr } 99865c2687SKazutaka Miyasaka $docs = array_pop($stack); 100865c2687SKazutaka Miyasaka 101865c2687SKazutaka Miyasaka if (empty($docs)) return array(); 102865c2687SKazutaka Miyasaka 103865c2687SKazutaka Miyasaka // check: settings, acls, existence 104865c2687SKazutaka Miyasaka foreach (array_keys($docs) as $id) { 105865c2687SKazutaka Miyasaka if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) { 106865c2687SKazutaka Miyasaka unset($docs[$id]); 107f5eb7cf0SAndreas Gohr } 108f5eb7cf0SAndreas Gohr } 109f5eb7cf0SAndreas Gohr 110865c2687SKazutaka Miyasaka // sort docs by count 111f5eb7cf0SAndreas Gohr arsort($docs); 112f5eb7cf0SAndreas Gohr 113f5eb7cf0SAndreas Gohr return $docs; 114f5eb7cf0SAndreas Gohr} 115f5eb7cf0SAndreas Gohr 116f5eb7cf0SAndreas Gohr/** 11754f4c056SAndreas Gohr * Returns the backlinks for a given page 11854f4c056SAndreas Gohr * 11954f4c056SAndreas Gohr * Does a quick lookup with the fulltext index, then 12054f4c056SAndreas Gohr * evaluates the instructions of the found pages 12154f4c056SAndreas Gohr */ 12254f4c056SAndreas Gohrfunction ft_backlinks($id){ 12354f4c056SAndreas Gohr global $conf; 1246b06b652Schris $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 1256b06b652Schris $stopwords = @file_exists($swfile) ? file($swfile) : array(); 1266b06b652Schris 12754f4c056SAndreas Gohr $result = array(); 12854f4c056SAndreas Gohr 12954f4c056SAndreas Gohr // quick lookup of the pagename 13054f4c056SAndreas Gohr $page = noNS($id); 1316b06b652Schris $matches = idx_lookup(idx_tokenizer($page,$stopwords)); // pagename may contain specials (_ or .) 1320dc92c6fSAndreas Gohr $docs = array_keys(ft_resultCombine(array_values($matches))); 1330dc92c6fSAndreas Gohr $docs = array_filter($docs,'isVisiblePage'); // discard hidden pages 1343cbaa9a4SAndreas Gohr if(!count($docs)) return $result; 13554f4c056SAndreas Gohr require_once(DOKU_INC.'inc/parserutils.php'); 13654f4c056SAndreas Gohr 13710ffc9ddSAndreas Gohr // check metadata for matching links 1380dc92c6fSAndreas Gohr foreach($docs as $match){ 13910ffc9ddSAndreas Gohr // metadata relation reference links are already resolved 1406b06b652Schris $links = p_get_metadata($match,'relation references'); 1413be6e394Schris if (isset($links[$id])) $result[] = $match; 14254f4c056SAndreas Gohr } 14354f4c056SAndreas Gohr 14463773904SAndreas Gohr if(!count($result)) return $result; 14563773904SAndreas Gohr 14663773904SAndreas Gohr // check ACL permissions 14763773904SAndreas Gohr foreach(array_keys($result) as $idx){ 14863773904SAndreas Gohr if(auth_quickaclcheck($result[$idx]) < AUTH_READ){ 14963773904SAndreas Gohr unset($result[$idx]); 15063773904SAndreas Gohr } 15163773904SAndreas Gohr } 15263773904SAndreas Gohr 15354f4c056SAndreas Gohr sort($result); 15454f4c056SAndreas Gohr return $result; 15554f4c056SAndreas Gohr} 15654f4c056SAndreas Gohr 15754f4c056SAndreas Gohr/** 158a05e297aSAndreas Gohr * Returns the pages that use a given media file 159a05e297aSAndreas Gohr * 160a05e297aSAndreas Gohr * Does a quick lookup with the fulltext index, then 161a05e297aSAndreas Gohr * evaluates the instructions of the found pages 162a05e297aSAndreas Gohr * 163a05e297aSAndreas Gohr * Aborts after $max found results 164a05e297aSAndreas Gohr */ 165a05e297aSAndreas Gohrfunction ft_mediause($id,$max){ 166a05e297aSAndreas Gohr global $conf; 167a05e297aSAndreas Gohr $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 168a05e297aSAndreas Gohr $stopwords = @file_exists($swfile) ? file($swfile) : array(); 169a05e297aSAndreas Gohr 170a05e297aSAndreas Gohr if(!$max) $max = 1; // need to find at least one 171a05e297aSAndreas Gohr 172a05e297aSAndreas Gohr $result = array(); 173a05e297aSAndreas Gohr 174a05e297aSAndreas Gohr // quick lookup of the mediafile 175a05e297aSAndreas Gohr $media = noNS($id); 176a05e297aSAndreas Gohr $matches = idx_lookup(idx_tokenizer($media,$stopwords)); 177a05e297aSAndreas Gohr $docs = array_keys(ft_resultCombine(array_values($matches))); 178a05e297aSAndreas Gohr if(!count($docs)) return $result; 179a05e297aSAndreas Gohr 180a05e297aSAndreas Gohr // go through all found pages 181a05e297aSAndreas Gohr $found = 0; 182a05e297aSAndreas Gohr $pcre = preg_quote($media,'/'); 183a05e297aSAndreas Gohr foreach($docs as $doc){ 184a05e297aSAndreas Gohr $ns = getNS($doc); 185a05e297aSAndreas Gohr preg_match_all('/\{\{([^|}]*'.$pcre.'[^|}]*)(|[^}]+)?\}\}/i',rawWiki($doc),$matches); 186a05e297aSAndreas Gohr foreach($matches[1] as $img){ 187a05e297aSAndreas Gohr $img = trim($img); 188a05e297aSAndreas Gohr if(preg_match('/^https?:\/\//i',$img)) continue; // skip external images 189a05e297aSAndreas Gohr list($img) = explode('?',$img); // remove any parameters 190a05e297aSAndreas Gohr resolve_mediaid($ns,$img,$exists); // resolve the possibly relative img 191a05e297aSAndreas Gohr 192a05e297aSAndreas Gohr if($img == $id){ // we have a match 193a05e297aSAndreas Gohr $result[] = $doc; 194a05e297aSAndreas Gohr $found++; 195a05e297aSAndreas Gohr break; 196a05e297aSAndreas Gohr } 197a05e297aSAndreas Gohr } 198a05e297aSAndreas Gohr if($found >= $max) break; 199a05e297aSAndreas Gohr } 200a05e297aSAndreas Gohr 201a05e297aSAndreas Gohr sort($result); 202a05e297aSAndreas Gohr return $result; 203a05e297aSAndreas Gohr} 204a05e297aSAndreas Gohr 205a05e297aSAndreas Gohr 206a05e297aSAndreas Gohr 207a05e297aSAndreas Gohr/** 208506fa893SAndreas Gohr * Quicksearch for pagenames 209506fa893SAndreas Gohr * 210506fa893SAndreas Gohr * By default it only matches the pagename and ignores the 211506fa893SAndreas Gohr * namespace. This can be changed with the second parameter 212506fa893SAndreas Gohr * 2136840140fSChris Smith * refactored into ft_pageLookup(), _ft_pageLookup() and trigger_event() 2146840140fSChris Smith * 215506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 216506fa893SAndreas Gohr */ 217506fa893SAndreas Gohrfunction ft_pageLookup($id,$pageonly=true){ 2186840140fSChris Smith $data = array('id' => $id, 'pageonly' => $pageonly); 2196840140fSChris Smith return trigger_event('SEARCH_QUERY_PAGELOOKUP',$data,'_ft_pageLookup'); 2206840140fSChris Smith} 2216840140fSChris Smith 2226840140fSChris Smithfunction _ft_pageLookup(&$data){ 2236840140fSChris Smith // split out original parameterrs 2246840140fSChris Smith $id = $data['id']; 2256840140fSChris Smith $pageonly = $data['pageonly']; 2266840140fSChris Smith 227506fa893SAndreas Gohr global $conf; 228506fa893SAndreas Gohr $id = preg_quote($id,'/'); 229579b0f7eSTNHarris $pages = file($conf['indexdir'].'/page.idx'); 2306798a86aSAndreas Gohr if($id) $pages = array_values(preg_grep('/'.$id.'/',$pages)); 231506fa893SAndreas Gohr 232506fa893SAndreas Gohr $cnt = count($pages); 233506fa893SAndreas Gohr for($i=0; $i<$cnt; $i++){ 234506fa893SAndreas Gohr if($pageonly){ 235506fa893SAndreas Gohr if(!preg_match('/'.$id.'/',noNS($pages[$i]))){ 236506fa893SAndreas Gohr unset($pages[$i]); 237506fa893SAndreas Gohr continue; 238506fa893SAndreas Gohr } 239506fa893SAndreas Gohr } 240103c256aSChris Smith if(!page_exists($pages[$i])){ 241506fa893SAndreas Gohr unset($pages[$i]); 242506fa893SAndreas Gohr continue; 243506fa893SAndreas Gohr } 244506fa893SAndreas Gohr } 24563773904SAndreas Gohr 2460dc92c6fSAndreas Gohr $pages = array_filter($pages,'isVisiblePage'); // discard hidden pages 24763773904SAndreas Gohr if(!count($pages)) return array(); 24863773904SAndreas Gohr 24963773904SAndreas Gohr // check ACL permissions 25063773904SAndreas Gohr foreach(array_keys($pages) as $idx){ 25132ee5830SChris Smith if(auth_quickaclcheck(trim($pages[$idx])) < AUTH_READ){ 25263773904SAndreas Gohr unset($pages[$idx]); 25363773904SAndreas Gohr } 25463773904SAndreas Gohr } 25563773904SAndreas Gohr 2566798a86aSAndreas Gohr $pages = array_map('trim',$pages); 257f31eb72bSAndreas Gohr usort($pages,'ft_pagesorter'); 258506fa893SAndreas Gohr return $pages; 259506fa893SAndreas Gohr} 260506fa893SAndreas Gohr 261506fa893SAndreas Gohr/** 262f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string 263f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy 264f31eb72bSAndreas Gohr * pages. 265f31eb72bSAndreas Gohr */ 266f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){ 267f31eb72bSAndreas Gohr $ac = count(explode(':',$a)); 268f31eb72bSAndreas Gohr $bc = count(explode(':',$b)); 269f31eb72bSAndreas Gohr if($ac < $bc){ 270f31eb72bSAndreas Gohr return -1; 271f31eb72bSAndreas Gohr }elseif($ac > $bc){ 272f31eb72bSAndreas Gohr return 1; 273f31eb72bSAndreas Gohr } 274f31eb72bSAndreas Gohr return strcmp ($a,$b); 275f31eb72bSAndreas Gohr} 276f31eb72bSAndreas Gohr 277f31eb72bSAndreas Gohr/** 278506fa893SAndreas Gohr * Creates a snippet extract 279506fa893SAndreas Gohr * 280506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org> 281*60e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE 282506fa893SAndreas Gohr */ 283546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){ 284506fa893SAndreas Gohr $text = rawWiki($id); 285*60e91a17SAndreas Gohr $evdata = array( 286*60e91a17SAndreas Gohr 'id' => $id, 287*60e91a17SAndreas Gohr 'text' => &$text, 288*60e91a17SAndreas Gohr 'highlight' => &$highlight, 289*60e91a17SAndreas Gohr 'snippet' => '', 290*60e91a17SAndreas Gohr ); 291*60e91a17SAndreas Gohr 292*60e91a17SAndreas Gohr $evt = new Doku_Event('FULLTEXT_SNIPPET_CREATE',$evdata); 293*60e91a17SAndreas Gohr if ($evt->advise_before()) { 294ced0762eSchris $match = array(); 295ced0762eSchris $snippets = array(); 2969ee93076Schris $utf8_offset = $offset = $end = 0; 297ced0762eSchris $len = utf8_strlen($text); 2989ee93076Schris 299546d3a99SAndreas Gohr // build a regexp from the phrases to highlight 300b571ff2dSChuck Kollars $re1 = '('.join('|',array_map('preg_quote_cb',array_filter((array) $highlight))).')'; 301b571ff2dSChuck Kollars $re2 = "$re1.{0,75}(?!\\1)$re1"; 302b571ff2dSChuck Kollars $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; 303546d3a99SAndreas Gohr 304b571ff2dSChuck Kollars for ($cnt=4; $cnt--;) { 305b571ff2dSChuck Kollars if (0) { 306b571ff2dSChuck Kollars } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 307b571ff2dSChuck Kollars } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 308b571ff2dSChuck Kollars } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 309b571ff2dSChuck Kollars } else { 310b571ff2dSChuck Kollars break; 311b571ff2dSChuck Kollars } 312ced0762eSchris 313ced0762eSchris list($str,$idx) = $match[0]; 314ced0762eSchris 315ced0762eSchris // convert $idx (a byte offset) into a utf8 character offset 316ced0762eSchris $utf8_idx = utf8_strlen(substr($text,0,$idx)); 317ced0762eSchris $utf8_len = utf8_strlen($str); 318ced0762eSchris 319ced0762eSchris // establish context, 100 bytes surrounding the match string 320ced0762eSchris // first look to see if we can go 100 either side, 321ced0762eSchris // then drop to 50 adding any excess if the other side can't go to 50, 322ced0762eSchris $pre = min($utf8_idx-$utf8_offset,100); 323ced0762eSchris $post = min($len-$utf8_idx-$utf8_len,100); 324ced0762eSchris 325ced0762eSchris if ($pre>50 && $post>50) { 326ced0762eSchris $pre = $post = 50; 327ced0762eSchris } else if ($pre>50) { 328ced0762eSchris $pre = min($pre,100-$post); 329ced0762eSchris } else if ($post>50) { 330ced0762eSchris $post = min($post, 100-$pre); 331ced0762eSchris } else { 332ced0762eSchris // both are less than 50, means the context is the whole string 33310ffc9ddSAndreas Gohr // make it so and break out of this loop - there is no need for the 33410ffc9ddSAndreas Gohr // complex snippet calculations 335ced0762eSchris $snippets = array($text); 336ced0762eSchris break; 337ced0762eSchris } 338ced0762eSchris 33910ffc9ddSAndreas Gohr // establish context start and end points, try to append to previous 34010ffc9ddSAndreas Gohr // context if possible 3419ee93076Schris $start = $utf8_idx - $pre; 342ced0762eSchris $append = ($start < $end) ? $end : false; // still the end of the previous context snippet 3439ee93076Schris $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context 344ced0762eSchris 345ced0762eSchris if ($append) { 346ced0762eSchris $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append); 347ced0762eSchris } else { 348ced0762eSchris $snippets[] = utf8_substr($text,$start,$end-$start); 349ced0762eSchris } 350ced0762eSchris 351ced0762eSchris // set $offset for next match attempt 35210ffc9ddSAndreas Gohr // substract strlen to avoid splitting a potential search success, 35310ffc9ddSAndreas Gohr // this is an approximation as the search pattern may match strings 35410ffc9ddSAndreas Gohr // of varying length and it will fail if the context snippet 355ced0762eSchris // boundary breaks a matching string longer than the current match 3569ee93076Schris $utf8_offset = $utf8_idx + $post; 3579ee93076Schris $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$post)); 3589ee93076Schris $offset = utf8_correctIdx($text,$offset); 3599ee93076Schris } 3609ee93076Schris 361ced0762eSchris $m = "\1"; 362b571ff2dSChuck Kollars $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets); 363b571ff2dSChuck Kollars $snippet = preg_replace('/'.$m.'([^'.$m.']*?)'.$m.'/iu','<strong class="search_hit">$1</strong>',hsc(join('... ',$snippets))); 364bd2cb6fcSchris 365*60e91a17SAndreas Gohr $evdata['snippet'] = $snippet; 366*60e91a17SAndreas Gohr } 367*60e91a17SAndreas Gohr $evt->advise_after(); 368*60e91a17SAndreas Gohr unset($evt); 369*60e91a17SAndreas Gohr 370*60e91a17SAndreas Gohr return $evdata['snippet']; 371506fa893SAndreas Gohr} 372506fa893SAndreas Gohr 373506fa893SAndreas Gohr/** 374f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores 375f5eb7cf0SAndreas Gohr * 376f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical 377f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned. 378f5eb7cf0SAndreas Gohr * 379f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key() 380f5eb7cf0SAndreas Gohr * 381f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays 382f5eb7cf0SAndreas Gohr */ 383f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){ 384f5eb7cf0SAndreas Gohr $array_count = count($args); 385134f4ab2SAndreas Gohr if($array_count == 1){ 386134f4ab2SAndreas Gohr return $args[0]; 387134f4ab2SAndreas Gohr } 388134f4ab2SAndreas Gohr 389f5eb7cf0SAndreas Gohr $result = array(); 39009c27a6dSGuy Brand if ($array_count > 1) { 391a21136cdSAndreas Gohr foreach ($args[0] as $key => $value) { 392a21136cdSAndreas Gohr $result[$key] = $value; 393f5eb7cf0SAndreas Gohr for ($i = 1; $i !== $array_count; $i++) { 394a21136cdSAndreas Gohr if (!isset($args[$i][$key])) { 395a21136cdSAndreas Gohr unset($result[$key]); 396a21136cdSAndreas Gohr break; 397f5eb7cf0SAndreas Gohr } 398a21136cdSAndreas Gohr $result[$key] += $args[$i][$key]; 399f5eb7cf0SAndreas Gohr } 400f5eb7cf0SAndreas Gohr } 40109c27a6dSGuy Brand } 402f5eb7cf0SAndreas Gohr return $result; 403f5eb7cf0SAndreas Gohr} 404f5eb7cf0SAndreas Gohr 405f5eb7cf0SAndreas Gohr/** 406865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores 407f5eb7cf0SAndreas Gohr * 408865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function 409865c2687SKazutaka Miyasaka * 410865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 411865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 412865c2687SKazutaka Miyasaka */ 413865c2687SKazutaka Miyasakafunction ft_resultUnite($args) { 414865c2687SKazutaka Miyasaka $array_count = count($args); 415865c2687SKazutaka Miyasaka if ($array_count === 1) { 416865c2687SKazutaka Miyasaka return $args[0]; 417865c2687SKazutaka Miyasaka } 418865c2687SKazutaka Miyasaka 419865c2687SKazutaka Miyasaka $result = $args[0]; 420865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 421865c2687SKazutaka Miyasaka foreach (array_keys($args[$i]) as $id) { 422865c2687SKazutaka Miyasaka $result[$id] += $args[$i][$id]; 423865c2687SKazutaka Miyasaka } 424865c2687SKazutaka Miyasaka } 425865c2687SKazutaka Miyasaka return $result; 426865c2687SKazutaka Miyasaka} 427865c2687SKazutaka Miyasaka 428865c2687SKazutaka Miyasaka/** 429865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison 430865c2687SKazutaka Miyasaka * 431865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key() 432865c2687SKazutaka Miyasaka * 433865c2687SKazutaka Miyasaka * @param array $args An array of page arrays 434865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 435865c2687SKazutaka Miyasaka */ 436865c2687SKazutaka Miyasakafunction ft_resultComplement($args) { 437865c2687SKazutaka Miyasaka $array_count = count($args); 438865c2687SKazutaka Miyasaka if ($array_count === 1) { 439865c2687SKazutaka Miyasaka return $args[0]; 440865c2687SKazutaka Miyasaka } 441865c2687SKazutaka Miyasaka 442865c2687SKazutaka Miyasaka $result = $args[0]; 443865c2687SKazutaka Miyasaka foreach (array_keys($result) as $id) { 444865c2687SKazutaka Miyasaka for ($i = 1; $i !== $array_count; $i++) { 445865c2687SKazutaka Miyasaka if (isset($args[$i][$id])) unset($result[$id]); 446865c2687SKazutaka Miyasaka } 447865c2687SKazutaka Miyasaka } 448865c2687SKazutaka Miyasaka return $result; 449865c2687SKazutaka Miyasaka} 450865c2687SKazutaka Miyasaka 451865c2687SKazutaka Miyasaka/** 452865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas 453865c2687SKazutaka Miyasaka * 454865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org> 455865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 456f5eb7cf0SAndreas Gohr */ 457f5eb7cf0SAndreas Gohrfunction ft_queryParser($query){ 458f5eb7cf0SAndreas Gohr global $conf; 459f5eb7cf0SAndreas Gohr $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 460865c2687SKazutaka Miyasaka $stopwords = @file_exists($swfile) ? file($swfile) : array(); 461865c2687SKazutaka Miyasaka 462865c2687SKazutaka Miyasaka /** 463865c2687SKazutaka Miyasaka * parse a search query and transform it into intermediate representation 464865c2687SKazutaka Miyasaka * 465865c2687SKazutaka Miyasaka * in a search query, you can use the following expressions: 466865c2687SKazutaka Miyasaka * 467865c2687SKazutaka Miyasaka * words: 468865c2687SKazutaka Miyasaka * include 469865c2687SKazutaka Miyasaka * -exclude 470865c2687SKazutaka Miyasaka * phrases: 471865c2687SKazutaka Miyasaka * "phrase to be included" 472865c2687SKazutaka Miyasaka * -"phrase you want to exclude" 473865c2687SKazutaka Miyasaka * namespaces: 474865c2687SKazutaka Miyasaka * @include:namespace (or ns:include:namespace) 475865c2687SKazutaka Miyasaka * ^exclude:namespace (or -ns:exclude:namespace) 476865c2687SKazutaka Miyasaka * groups: 477865c2687SKazutaka Miyasaka * () 478865c2687SKazutaka Miyasaka * -() 479865c2687SKazutaka Miyasaka * operators: 480865c2687SKazutaka Miyasaka * and ('and' is the default operator: you can always omit this) 4817871d415SKazutaka Miyasaka * or (or pipe symbol '|', lower precedence than 'and') 482865c2687SKazutaka Miyasaka * 483865c2687SKazutaka Miyasaka * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain 484865c2687SKazutaka Miyasaka * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". 485865c2687SKazutaka Miyasaka * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] 486865c2687SKazutaka Miyasaka * as long as you don't mind hit counts. 487865c2687SKazutaka Miyasaka * 488865c2687SKazutaka Miyasaka * intermediate representation consists of the following parts: 489865c2687SKazutaka Miyasaka * 490865c2687SKazutaka Miyasaka * ( ) - group 491865c2687SKazutaka Miyasaka * AND - logical and 492865c2687SKazutaka Miyasaka * OR - logical or 493865c2687SKazutaka Miyasaka * NOT - logical not 494865c2687SKazutaka Miyasaka * W+: - word (needs to be highlighted) 495865c2687SKazutaka Miyasaka * W-: - word (no need to highlight) 496865c2687SKazutaka Miyasaka * P_: - phrase 497865c2687SKazutaka Miyasaka * N_: - namespace 498865c2687SKazutaka Miyasaka */ 499865c2687SKazutaka Miyasaka $parsed_query = ''; 500865c2687SKazutaka Miyasaka $parens_level = 0; 501865c2687SKazutaka Miyasaka $terms = preg_split('/(-?".*?")/u', utf8_strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 502865c2687SKazutaka Miyasaka 503865c2687SKazutaka Miyasaka foreach ($terms as $term) { 504865c2687SKazutaka Miyasaka $parsed = ''; 505865c2687SKazutaka Miyasaka if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { 506865c2687SKazutaka Miyasaka // phrase-include and phrase-exclude 507865c2687SKazutaka Miyasaka $not = $matches[1] ? 'NOT' : ''; 508865c2687SKazutaka Miyasaka $parsed = $not.ft_termParser($matches[2], $stopwords, false, true); 509f5eb7cf0SAndreas Gohr } else { 510865c2687SKazutaka Miyasaka // fix incomplete phrase 511865c2687SKazutaka Miyasaka $term = str_replace('"', ' ', $term); 512865c2687SKazutaka Miyasaka 513865c2687SKazutaka Miyasaka // fix parentheses 514865c2687SKazutaka Miyasaka $term = str_replace(')' , ' ) ', $term); 515865c2687SKazutaka Miyasaka $term = str_replace('(' , ' ( ', $term); 516865c2687SKazutaka Miyasaka $term = str_replace('- (', ' -(', $term); 517865c2687SKazutaka Miyasaka 5187871d415SKazutaka Miyasaka // treat pipe symbols as 'OR' operators 5197871d415SKazutaka Miyasaka $term = str_replace('|', ' or ', $term); 5207871d415SKazutaka Miyasaka 521865c2687SKazutaka Miyasaka // treat ideographic spaces (U+3000) as search term separators 522865c2687SKazutaka Miyasaka // FIXME: some more separators? 523865c2687SKazutaka Miyasaka $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); 524865c2687SKazutaka Miyasaka $term = trim($term); 525865c2687SKazutaka Miyasaka if ($term === '') continue; 526865c2687SKazutaka Miyasaka 527865c2687SKazutaka Miyasaka $tokens = explode(' ', $term); 528865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 529865c2687SKazutaka Miyasaka if ($token === '(') { 530865c2687SKazutaka Miyasaka // parenthesis-include-open 531865c2687SKazutaka Miyasaka $parsed .= '('; 532865c2687SKazutaka Miyasaka ++$parens_level; 533865c2687SKazutaka Miyasaka } elseif ($token === '-(') { 534865c2687SKazutaka Miyasaka // parenthesis-exclude-open 535865c2687SKazutaka Miyasaka $parsed .= 'NOT('; 536865c2687SKazutaka Miyasaka ++$parens_level; 537865c2687SKazutaka Miyasaka } elseif ($token === ')') { 538865c2687SKazutaka Miyasaka // parenthesis-any-close 539865c2687SKazutaka Miyasaka if ($parens_level === 0) continue; 540865c2687SKazutaka Miyasaka $parsed .= ')'; 541865c2687SKazutaka Miyasaka $parens_level--; 542865c2687SKazutaka Miyasaka } elseif ($token === 'and') { 543865c2687SKazutaka Miyasaka // logical-and (do nothing) 544865c2687SKazutaka Miyasaka } elseif ($token === 'or') { 545865c2687SKazutaka Miyasaka // logical-or 546865c2687SKazutaka Miyasaka $parsed .= 'OR'; 547865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { 548865c2687SKazutaka Miyasaka // namespace-exclude 549865c2687SKazutaka Miyasaka $parsed .= 'NOT(N_:'.$matches[1].')'; 550865c2687SKazutaka Miyasaka } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { 551865c2687SKazutaka Miyasaka // namespace-include 552865c2687SKazutaka Miyasaka $parsed .= '(N_:'.$matches[1].')'; 553865c2687SKazutaka Miyasaka } elseif (preg_match('/^-(.+)$/', $token, $matches)) { 554865c2687SKazutaka Miyasaka // word-exclude 555865c2687SKazutaka Miyasaka $parsed .= 'NOT('.ft_termParser($matches[1], $stopwords).')'; 556865c2687SKazutaka Miyasaka } else { 557865c2687SKazutaka Miyasaka // word-include 558865c2687SKazutaka Miyasaka $parsed .= ft_termParser($token, $stopwords); 559865c2687SKazutaka Miyasaka } 560865c2687SKazutaka Miyasaka } 561865c2687SKazutaka Miyasaka } 562865c2687SKazutaka Miyasaka $parsed_query .= $parsed; 563f5eb7cf0SAndreas Gohr } 564f5eb7cf0SAndreas Gohr 565865c2687SKazutaka Miyasaka // cleanup (very sensitive) 566865c2687SKazutaka Miyasaka $parsed_query .= str_repeat(')', $parens_level); 567865c2687SKazutaka Miyasaka do { 568865c2687SKazutaka Miyasaka $parsed_query_old = $parsed_query; 569865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); 570865c2687SKazutaka Miyasaka } while ($parsed_query !== $parsed_query_old); 571865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query); 572865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query); 573865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query); 574865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query); 575865c2687SKazutaka Miyasaka $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query); 576865c2687SKazutaka Miyasaka 577865c2687SKazutaka Miyasaka /** 578865c2687SKazutaka Miyasaka * convert infix notation string into postfix (Reverse Polish notation) array 579865c2687SKazutaka Miyasaka * by Shunting-yard algorithm 580865c2687SKazutaka Miyasaka * 581865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation 582865c2687SKazutaka Miyasaka * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm 583865c2687SKazutaka Miyasaka */ 584865c2687SKazutaka Miyasaka $parsed_ary = array(); 585865c2687SKazutaka Miyasaka $ope_stack = array(); 586865c2687SKazutaka Miyasaka $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5); 587865c2687SKazutaka Miyasaka $ope_regex = '/([()]|OR|AND|NOT)/u'; 588865c2687SKazutaka Miyasaka 589865c2687SKazutaka Miyasaka $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 590865c2687SKazutaka Miyasaka foreach ($tokens as $token) { 591865c2687SKazutaka Miyasaka if (preg_match($ope_regex, $token)) { 592865c2687SKazutaka Miyasaka // operator 593865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 594865c2687SKazutaka Miyasaka while ($ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { 595865c2687SKazutaka Miyasaka $parsed_ary[] = array_pop($ope_stack); 596865c2687SKazutaka Miyasaka $last_ope = end($ope_stack); 597865c2687SKazutaka Miyasaka } 598865c2687SKazutaka Miyasaka if ($token == ')') { 599865c2687SKazutaka Miyasaka array_pop($ope_stack); // this array_pop always deletes '(' 600865c2687SKazutaka Miyasaka } else { 601865c2687SKazutaka Miyasaka $ope_stack[] = $token; 602865c2687SKazutaka Miyasaka } 603865c2687SKazutaka Miyasaka } else { 604865c2687SKazutaka Miyasaka // operand 605865c2687SKazutaka Miyasaka $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token); 606865c2687SKazutaka Miyasaka $parsed_ary[] = $token_decoded; 607865c2687SKazutaka Miyasaka } 608865c2687SKazutaka Miyasaka } 609865c2687SKazutaka Miyasaka $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack))); 610865c2687SKazutaka Miyasaka 611865c2687SKazutaka Miyasaka // cleanup: each double "NOT" in RPN array actually does nothing 612865c2687SKazutaka Miyasaka $parsed_ary_count = count($parsed_ary); 613865c2687SKazutaka Miyasaka for ($i = 1; $i < $parsed_ary_count; ++$i) { 614865c2687SKazutaka Miyasaka if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { 615865c2687SKazutaka Miyasaka unset($parsed_ary[$i], $parsed_ary[$i - 1]); 616865c2687SKazutaka Miyasaka } 617865c2687SKazutaka Miyasaka } 618865c2687SKazutaka Miyasaka $parsed_ary = array_values($parsed_ary); 619865c2687SKazutaka Miyasaka 620865c2687SKazutaka Miyasaka // build return value 621f5eb7cf0SAndreas Gohr $q = array(); 622f5eb7cf0SAndreas Gohr $q['query'] = $query; 623865c2687SKazutaka Miyasaka $q['parsed_str'] = $parsed_query; 624865c2687SKazutaka Miyasaka $q['parsed_ary'] = $parsed_ary; 625f5eb7cf0SAndreas Gohr 626865c2687SKazutaka Miyasaka foreach ($q['parsed_ary'] as $token) { 627865c2687SKazutaka Miyasaka if ($token[2] !== ':') continue; 628865c2687SKazutaka Miyasaka $body = substr($token, 3); 629865c2687SKazutaka Miyasaka 630865c2687SKazutaka Miyasaka switch (substr($token, 0, 3)) { 631865c2687SKazutaka Miyasaka case 'N_:': 632865c2687SKazutaka Miyasaka $q['ns'][] = $body; // for backward compatibility 633865c2687SKazutaka Miyasaka break; 634865c2687SKazutaka Miyasaka case 'W-:': 635865c2687SKazutaka Miyasaka $q['words'][] = $body; 636865c2687SKazutaka Miyasaka break; 637865c2687SKazutaka Miyasaka case 'W+:': 638865c2687SKazutaka Miyasaka $q['words'][] = $body; 639865c2687SKazutaka Miyasaka $q['highlight'][] = str_replace('*', '', $body); 640865c2687SKazutaka Miyasaka break; 641865c2687SKazutaka Miyasaka case 'P_:': 642865c2687SKazutaka Miyasaka $q['phrases'][] = $body; 643865c2687SKazutaka Miyasaka $q['highlight'][] = str_replace('*', '', $body); 644865c2687SKazutaka Miyasaka break; 645865c2687SKazutaka Miyasaka } 646865c2687SKazutaka Miyasaka } 647865c2687SKazutaka Miyasaka foreach (array('words', 'phrases', 'highlight', 'ns') as $key) { 648865c2687SKazutaka Miyasaka $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key])); 649f5eb7cf0SAndreas Gohr } 650f5eb7cf0SAndreas Gohr 651865c2687SKazutaka Miyasaka // keep backward compatibility (to some extent) 652865c2687SKazutaka Miyasaka // this part can be deleted if no plugins use ft_queryParser() directly 653865c2687SKazutaka Miyasaka $q['and'] = $q['words']; 654865c2687SKazutaka Miyasaka $q['not'] = array(); // difficult to set: imagine [ aaa -(bbb -ccc) ] 655865c2687SKazutaka Miyasaka $q['notns'] = array(); // same as above 656f5eb7cf0SAndreas Gohr 657f5eb7cf0SAndreas Gohr return $q; 658f5eb7cf0SAndreas Gohr} 659f5eb7cf0SAndreas Gohr 660865c2687SKazutaka Miyasaka/** 661865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation 662865c2687SKazutaka Miyasaka * 663865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use. 664865c2687SKazutaka Miyasaka * 665865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com> 666865c2687SKazutaka Miyasaka */ 667865c2687SKazutaka Miyasakafunction ft_termParser($term, &$stopwords, $consider_asian = true, $phrase_mode = false) { 668865c2687SKazutaka Miyasaka $parsed = ''; 669865c2687SKazutaka Miyasaka if ($consider_asian) { 670865c2687SKazutaka Miyasaka // successive asian characters need to be searched as a phrase 671865c2687SKazutaka Miyasaka $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 672865c2687SKazutaka Miyasaka foreach ($words as $word) { 673865c2687SKazutaka Miyasaka if (preg_match('/'.IDX_ASIAN.'/u', $word)) $phrase_mode = true; 674865c2687SKazutaka Miyasaka $parsed .= ft_termParser($word, $stopwords, false, $phrase_mode); 675865c2687SKazutaka Miyasaka } 676865c2687SKazutaka Miyasaka } else { 677865c2687SKazutaka Miyasaka $term_noparen = str_replace(array('(', ')'), ' ', $term); 678865c2687SKazutaka Miyasaka $words = idx_tokenizer($term_noparen, $stopwords, true); 679865c2687SKazutaka Miyasaka 680865c2687SKazutaka Miyasaka // W+: needs to be highlighted, W-: no need to highlight 681865c2687SKazutaka Miyasaka if (empty($words)) { 682865c2687SKazutaka Miyasaka $parsed = '()'; // important: do not remove 683865c2687SKazutaka Miyasaka } elseif ($words[0] === $term) { 684865c2687SKazutaka Miyasaka $parsed = '(W+:'.$words[0].')'; 685865c2687SKazutaka Miyasaka } elseif ($phrase_mode) { 686865c2687SKazutaka Miyasaka $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term); 687865c2687SKazutaka Miyasaka $parsed = '((W-:'.implode(')(W-:', $words).')(P_:'.$term_encoded.'))'; 688865c2687SKazutaka Miyasaka } else { 689865c2687SKazutaka Miyasaka $parsed = '((W+:'.implode(')(W+:', $words).'))'; 690865c2687SKazutaka Miyasaka } 691865c2687SKazutaka Miyasaka } 692865c2687SKazutaka Miyasaka return $parsed; 693865c2687SKazutaka Miyasaka} 694865c2687SKazutaka Miyasaka 695506fa893SAndreas Gohr//Setup VIM: ex: et ts=4 enc=utf-8 : 696