PageRenderTime 63ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/inc/fulltext.php

http://github.com/splitbrain/dokuwiki
PHP | 933 lines | 546 code | 89 blank | 298 comment | 118 complexity | 450a81ab11a0aa7cf847b7f6b09575d1 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, GPL-2.0
  1. <?php
  2. /**
  3. * DokuWiki fulltextsearch functions using the index
  4. *
  5. * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
  6. * @author Andreas Gohr <andi@splitbrain.org>
  7. */
  8. use dokuwiki\Extension\Event;
  9. /**
  10. * create snippets for the first few results only
  11. */
  12. if(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15);
  13. /**
  14. * The fulltext search
  15. *
  16. * Returns a list of matching documents for the given query
  17. *
  18. * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
  19. *
  20. * @param string $query
  21. * @param array $highlight
  22. * @param string $sort
  23. * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments
  24. * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments
  25. *
  26. * @return array
  27. */
  28. function ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){
  29. if ($sort === null) {
  30. $sort = 'hits';
  31. }
  32. $data = [
  33. 'query' => $query,
  34. 'sort' => $sort,
  35. 'after' => $after,
  36. 'before' => $before
  37. ];
  38. $data['highlight'] =& $highlight;
  39. return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
  40. }
  41. /**
  42. * Returns a list of matching documents for the given query
  43. *
  44. * @author Andreas Gohr <andi@splitbrain.org>
  45. * @author Kazutaka Miyasaka <kazmiya@gmail.com>
  46. *
  47. * @param array $data event data
  48. * @return array matching documents
  49. */
  50. function _ft_pageSearch(&$data) {
  51. $Indexer = idx_get_indexer();
  52. // parse the given query
  53. $q = ft_queryParser($Indexer, $data['query']);
  54. $data['highlight'] = $q['highlight'];
  55. if (empty($q['parsed_ary'])) return array();
  56. // lookup all words found in the query
  57. $lookup = $Indexer->lookup($q['words']);
  58. // get all pages in this dokuwiki site (!: includes nonexistent pages)
  59. $pages_all = array();
  60. foreach ($Indexer->getPages() as $id) {
  61. $pages_all[$id] = 0; // base: 0 hit
  62. }
  63. // process the query
  64. $stack = array();
  65. foreach ($q['parsed_ary'] as $token) {
  66. switch (substr($token, 0, 3)) {
  67. case 'W+:':
  68. case 'W-:':
  69. case 'W_:': // word
  70. $word = substr($token, 3);
  71. $stack[] = (array) $lookup[$word];
  72. break;
  73. case 'P+:':
  74. case 'P-:': // phrase
  75. $phrase = substr($token, 3);
  76. // since phrases are always parsed as ((W1)(W2)...(P)),
  77. // the end($stack) always points the pages that contain
  78. // all words in this phrase
  79. $pages = end($stack);
  80. $pages_matched = array();
  81. foreach(array_keys($pages) as $id){
  82. $evdata = array(
  83. 'id' => $id,
  84. 'phrase' => $phrase,
  85. 'text' => rawWiki($id)
  86. );
  87. $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata);
  88. if ($evt->advise_before() && $evt->result !== true) {
  89. $text = \dokuwiki\Utf8\PhpString::strtolower($evdata['text']);
  90. if (strpos($text, $phrase) !== false) {
  91. $evt->result = true;
  92. }
  93. }
  94. $evt->advise_after();
  95. if ($evt->result === true) {
  96. $pages_matched[$id] = 0; // phrase: always 0 hit
  97. }
  98. }
  99. $stack[] = $pages_matched;
  100. break;
  101. case 'N+:':
  102. case 'N-:': // namespace
  103. $ns = cleanID(substr($token, 3)) . ':';
  104. $pages_matched = array();
  105. foreach (array_keys($pages_all) as $id) {
  106. if (strpos($id, $ns) === 0) {
  107. $pages_matched[$id] = 0; // namespace: always 0 hit
  108. }
  109. }
  110. $stack[] = $pages_matched;
  111. break;
  112. case 'AND': // and operation
  113. list($pages1, $pages2) = array_splice($stack, -2);
  114. $stack[] = ft_resultCombine(array($pages1, $pages2));
  115. break;
  116. case 'OR': // or operation
  117. list($pages1, $pages2) = array_splice($stack, -2);
  118. $stack[] = ft_resultUnite(array($pages1, $pages2));
  119. break;
  120. case 'NOT': // not operation (unary)
  121. $pages = array_pop($stack);
  122. $stack[] = ft_resultComplement(array($pages_all, $pages));
  123. break;
  124. }
  125. }
  126. $docs = array_pop($stack);
  127. if (empty($docs)) return array();
  128. // check: settings, acls, existence
  129. foreach (array_keys($docs) as $id) {
  130. if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
  131. unset($docs[$id]);
  132. }
  133. }
  134. $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']);
  135. if ($data['sort'] === 'mtime') {
  136. uksort($docs, 'ft_pagemtimesorter');
  137. } else {
  138. // sort docs by count
  139. arsort($docs);
  140. }
  141. return $docs;
  142. }
  143. /**
  144. * Returns the backlinks for a given page
  145. *
  146. * Uses the metadata index.
  147. *
  148. * @param string $id The id for which links shall be returned
  149. * @param bool $ignore_perms Ignore the fact that pages are hidden or read-protected
  150. * @return array The pages that contain links to the given page
  151. */
  152. function ft_backlinks($id, $ignore_perms = false){
  153. $result = idx_get_indexer()->lookupKey('relation_references', $id);
  154. if(!count($result)) return $result;
  155. // check ACL permissions
  156. foreach(array_keys($result) as $idx){
  157. if(($ignore_perms !== true && (
  158. isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
  159. )) || !page_exists($result[$idx], '', false)){
  160. unset($result[$idx]);
  161. }
  162. }
  163. sort($result);
  164. return $result;
  165. }
  166. /**
  167. * Returns the pages that use a given media file
  168. *
  169. * Uses the relation media metadata property and the metadata index.
  170. *
  171. * Note that before 2013-07-31 the second parameter was the maximum number of results and
  172. * permissions were ignored. That's why the parameter is now checked to be explicitely set
  173. * to true (with type bool) in order to be compatible with older uses of the function.
  174. *
  175. * @param string $id The media id to look for
  176. * @param bool $ignore_perms Ignore hidden pages and acls (optional, default: false)
  177. * @return array A list of pages that use the given media file
  178. */
  179. function ft_mediause($id, $ignore_perms = false){
  180. $result = idx_get_indexer()->lookupKey('relation_media', $id);
  181. if(!count($result)) return $result;
  182. // check ACL permissions
  183. foreach(array_keys($result) as $idx){
  184. if(($ignore_perms !== true && (
  185. isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
  186. )) || !page_exists($result[$idx], '', false)){
  187. unset($result[$idx]);
  188. }
  189. }
  190. sort($result);
  191. return $result;
  192. }
  193. /**
  194. * Quicksearch for pagenames
  195. *
  196. * By default it only matches the pagename and ignores the
  197. * namespace. This can be changed with the second parameter.
  198. * The third parameter allows to search in titles as well.
  199. *
  200. * The function always returns titles as well
  201. *
  202. * @triggers SEARCH_QUERY_PAGELOOKUP
  203. * @author Andreas Gohr <andi@splitbrain.org>
  204. * @author Adrian Lang <lang@cosmocode.de>
  205. *
  206. * @param string $id page id
  207. * @param bool $in_ns match against namespace as well?
  208. * @param bool $in_title search in title?
  209. * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments
  210. * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments
  211. *
  212. * @return string[]
  213. */
  214. function ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){
  215. $data = [
  216. 'id' => $id,
  217. 'in_ns' => $in_ns,
  218. 'in_title' => $in_title,
  219. 'after' => $after,
  220. 'before' => $before
  221. ];
  222. $data['has_titles'] = true; // for plugin backward compatibility check
  223. return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup');
  224. }
  225. /**
  226. * Returns list of pages as array(pageid => First Heading)
  227. *
  228. * @param array &$data event data
  229. * @return string[]
  230. */
  231. function _ft_pageLookup(&$data){
  232. // split out original parameters
  233. $id = $data['id'];
  234. $Indexer = idx_get_indexer();
  235. $parsedQuery = ft_queryParser($Indexer, $id);
  236. if (count($parsedQuery['ns']) > 0) {
  237. $ns = cleanID($parsedQuery['ns'][0]) . ':';
  238. $id = implode(' ', $parsedQuery['highlight']);
  239. }
  240. $in_ns = $data['in_ns'];
  241. $in_title = $data['in_title'];
  242. $cleaned = cleanID($id);
  243. $Indexer = idx_get_indexer();
  244. $page_idx = $Indexer->getPages();
  245. $pages = array();
  246. if ($id !== '' && $cleaned !== '') {
  247. foreach ($page_idx as $p_id) {
  248. if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) {
  249. if (!isset($pages[$p_id]))
  250. $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
  251. }
  252. }
  253. if ($in_title) {
  254. foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) {
  255. if (!isset($pages[$p_id]))
  256. $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
  257. }
  258. }
  259. }
  260. if (isset($ns)) {
  261. foreach (array_keys($pages) as $p_id) {
  262. if (strpos($p_id, $ns) !== 0) {
  263. unset($pages[$p_id]);
  264. }
  265. }
  266. }
  267. // discard hidden pages
  268. // discard nonexistent pages
  269. // check ACL permissions
  270. foreach(array_keys($pages) as $idx){
  271. if(!isVisiblePage($idx) || !page_exists($idx) ||
  272. auth_quickaclcheck($idx) < AUTH_READ) {
  273. unset($pages[$idx]);
  274. }
  275. }
  276. $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']);
  277. uksort($pages,'ft_pagesorter');
  278. return $pages;
  279. }
  280. /**
  281. * @param array $results search results in the form pageid => value
  282. * @param int|string $after only returns results with mtime after this date, accepts timestap or strtotime arguments
  283. * @param int|string $before only returns results with mtime after this date, accepts timestap or strtotime arguments
  284. *
  285. * @return array
  286. */
  287. function _ft_filterResultsByTime(array $results, $after, $before) {
  288. if ($after || $before) {
  289. $after = is_int($after) ? $after : strtotime($after);
  290. $before = is_int($before) ? $before : strtotime($before);
  291. foreach ($results as $id => $value) {
  292. $mTime = filemtime(wikiFN($id));
  293. if ($after && $after > $mTime) {
  294. unset($results[$id]);
  295. continue;
  296. }
  297. if ($before && $before < $mTime) {
  298. unset($results[$id]);
  299. }
  300. }
  301. }
  302. return $results;
  303. }
  304. /**
  305. * Tiny helper function for comparing the searched title with the title
  306. * from the search index. This function is a wrapper around stripos with
  307. * adapted argument order and return value.
  308. *
  309. * @param string $search searched title
  310. * @param string $title title from index
  311. * @return bool
  312. */
  313. function _ft_pageLookupTitleCompare($search, $title) {
  314. return stripos($title, $search) !== false;
  315. }
  316. /**
  317. * Sort pages based on their namespace level first, then on their string
  318. * values. This makes higher hierarchy pages rank higher than lower hierarchy
  319. * pages.
  320. *
  321. * @param string $a
  322. * @param string $b
  323. * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal.
  324. */
  325. function ft_pagesorter($a, $b){
  326. $ac = count(explode(':',$a));
  327. $bc = count(explode(':',$b));
  328. if($ac < $bc){
  329. return -1;
  330. }elseif($ac > $bc){
  331. return 1;
  332. }
  333. return strcmp ($a,$b);
  334. }
  335. /**
  336. * Sort pages by their mtime, from newest to oldest
  337. *
  338. * @param string $a
  339. * @param string $b
  340. *
  341. * @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
  342. */
  343. function ft_pagemtimesorter($a, $b) {
  344. $mtimeA = filemtime(wikiFN($a));
  345. $mtimeB = filemtime(wikiFN($b));
  346. return $mtimeB - $mtimeA;
  347. }
  348. /**
  349. * Creates a snippet extract
  350. *
  351. * @author Andreas Gohr <andi@splitbrain.org>
  352. * @triggers FULLTEXT_SNIPPET_CREATE
  353. *
  354. * @param string $id page id
  355. * @param array $highlight
  356. * @return mixed
  357. */
  358. function ft_snippet($id,$highlight){
  359. $text = rawWiki($id);
  360. $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens
  361. $evdata = array(
  362. 'id' => $id,
  363. 'text' => &$text,
  364. 'highlight' => &$highlight,
  365. 'snippet' => '',
  366. );
  367. $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata);
  368. if ($evt->advise_before()) {
  369. $match = array();
  370. $snippets = array();
  371. $utf8_offset = $offset = $end = 0;
  372. $len = \dokuwiki\Utf8\PhpString::strlen($text);
  373. // build a regexp from the phrases to highlight
  374. $re1 = '(' .
  375. join(
  376. '|',
  377. array_map(
  378. 'ft_snippet_re_preprocess',
  379. array_map(
  380. 'preg_quote_cb',
  381. array_filter((array) $highlight)
  382. )
  383. )
  384. ) .
  385. ')';
  386. $re2 = "$re1.{0,75}(?!\\1)$re1";
  387. $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
  388. for ($cnt=4; $cnt--;) {
  389. if (0) {
  390. } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
  391. } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
  392. } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
  393. } else {
  394. break;
  395. }
  396. list($str,$idx) = $match[0];
  397. // convert $idx (a byte offset) into a utf8 character offset
  398. $utf8_idx = \dokuwiki\Utf8\PhpString::strlen(substr($text,0,$idx));
  399. $utf8_len = \dokuwiki\Utf8\PhpString::strlen($str);
  400. // establish context, 100 bytes surrounding the match string
  401. // first look to see if we can go 100 either side,
  402. // then drop to 50 adding any excess if the other side can't go to 50,
  403. $pre = min($utf8_idx-$utf8_offset,100);
  404. $post = min($len-$utf8_idx-$utf8_len,100);
  405. if ($pre>50 && $post>50) {
  406. $pre = $post = 50;
  407. } else if ($pre>50) {
  408. $pre = min($pre,100-$post);
  409. } else if ($post>50) {
  410. $post = min($post, 100-$pre);
  411. } else if ($offset == 0) {
  412. // both are less than 50, means the context is the whole string
  413. // make it so and break out of this loop - there is no need for the
  414. // complex snippet calculations
  415. $snippets = array($text);
  416. break;
  417. }
  418. // establish context start and end points, try to append to previous
  419. // context if possible
  420. $start = $utf8_idx - $pre;
  421. $append = ($start < $end) ? $end : false; // still the end of the previous context snippet
  422. $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context
  423. if ($append) {
  424. $snippets[count($snippets)-1] .= \dokuwiki\Utf8\PhpString::substr($text,$append,$end-$append);
  425. } else {
  426. $snippets[] = \dokuwiki\Utf8\PhpString::substr($text,$start,$end-$start);
  427. }
  428. // set $offset for next match attempt
  429. // continue matching after the current match
  430. // if the current match is not the longest possible match starting at the current offset
  431. // this prevents further matching of this snippet but for possible matches of length
  432. // smaller than match length + context (at least 50 characters) this match is part of the context
  433. $utf8_offset = $utf8_idx + $utf8_len;
  434. $offset = $idx + strlen(\dokuwiki\Utf8\PhpString::substr($text,$utf8_idx,$utf8_len));
  435. $offset = \dokuwiki\Utf8\Clean::correctIdx($text,$offset);
  436. }
  437. $m = "\1";
  438. $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
  439. $snippet = preg_replace(
  440. '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
  441. '<strong class="search_hit">$1</strong>',
  442. hsc(join('... ', $snippets))
  443. );
  444. $evdata['snippet'] = $snippet;
  445. }
  446. $evt->advise_after();
  447. unset($evt);
  448. return $evdata['snippet'];
  449. }
  450. /**
  451. * Wraps a search term in regex boundary checks.
  452. *
  453. * @param string $term
  454. * @return string
  455. */
  456. function ft_snippet_re_preprocess($term) {
  457. // do not process asian terms where word boundaries are not explicit
  458. if(\dokuwiki\Utf8\Asian::isAsianWords($term)) return $term;
  459. if (UTF8_PROPERTYSUPPORT) {
  460. // unicode word boundaries
  461. // see http://stackoverflow.com/a/2449017/172068
  462. $BL = '(?<!\pL)';
  463. $BR = '(?!\pL)';
  464. } else {
  465. // not as correct as above, but at least won't break
  466. $BL = '\b';
  467. $BR = '\b';
  468. }
  469. if(substr($term,0,2) == '\\*'){
  470. $term = substr($term,2);
  471. }else{
  472. $term = $BL.$term;
  473. }
  474. if(substr($term,-2,2) == '\\*'){
  475. $term = substr($term,0,-2);
  476. }else{
  477. $term = $term.$BR;
  478. }
  479. if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
  480. return $term;
  481. }
  482. /**
  483. * Combine found documents and sum up their scores
  484. *
  485. * This function is used to combine searched words with a logical
  486. * AND. Only documents available in all arrays are returned.
  487. *
  488. * based upon PEAR's PHP_Compat function for array_intersect_key()
  489. *
  490. * @param array $args An array of page arrays
  491. * @return array
  492. */
  493. function ft_resultCombine($args){
  494. $array_count = count($args);
  495. if($array_count == 1){
  496. return $args[0];
  497. }
  498. $result = array();
  499. if ($array_count > 1) {
  500. foreach ($args[0] as $key => $value) {
  501. $result[$key] = $value;
  502. for ($i = 1; $i !== $array_count; $i++) {
  503. if (!isset($args[$i][$key])) {
  504. unset($result[$key]);
  505. break;
  506. }
  507. $result[$key] += $args[$i][$key];
  508. }
  509. }
  510. }
  511. return $result;
  512. }
  513. /**
  514. * Unites found documents and sum up their scores
  515. *
  516. * based upon ft_resultCombine() function
  517. *
  518. * @param array $args An array of page arrays
  519. * @return array
  520. *
  521. * @author Kazutaka Miyasaka <kazmiya@gmail.com>
  522. */
  523. function ft_resultUnite($args) {
  524. $array_count = count($args);
  525. if ($array_count === 1) {
  526. return $args[0];
  527. }
  528. $result = $args[0];
  529. for ($i = 1; $i !== $array_count; $i++) {
  530. foreach (array_keys($args[$i]) as $id) {
  531. $result[$id] += $args[$i][$id];
  532. }
  533. }
  534. return $result;
  535. }
  536. /**
  537. * Computes the difference of documents using page id for comparison
  538. *
  539. * nearly identical to PHP5's array_diff_key()
  540. *
  541. * @param array $args An array of page arrays
  542. * @return array
  543. *
  544. * @author Kazutaka Miyasaka <kazmiya@gmail.com>
  545. */
  546. function ft_resultComplement($args) {
  547. $array_count = count($args);
  548. if ($array_count === 1) {
  549. return $args[0];
  550. }
  551. $result = $args[0];
  552. foreach (array_keys($result) as $id) {
  553. for ($i = 1; $i !== $array_count; $i++) {
  554. if (isset($args[$i][$id])) unset($result[$id]);
  555. }
  556. }
  557. return $result;
  558. }
  559. /**
  560. * Parses a search query and builds an array of search formulas
  561. *
  562. * @author Andreas Gohr <andi@splitbrain.org>
  563. * @author Kazutaka Miyasaka <kazmiya@gmail.com>
  564. *
  565. * @param dokuwiki\Search\Indexer $Indexer
  566. * @param string $query search query
  567. * @return array of search formulas
  568. */
  569. function ft_queryParser($Indexer, $query){
  570. /**
  571. * parse a search query and transform it into intermediate representation
  572. *
  573. * in a search query, you can use the following expressions:
  574. *
  575. * words:
  576. * include
  577. * -exclude
  578. * phrases:
  579. * "phrase to be included"
  580. * -"phrase you want to exclude"
  581. * namespaces:
  582. * @include:namespace (or ns:include:namespace)
  583. * ^exclude:namespace (or -ns:exclude:namespace)
  584. * groups:
  585. * ()
  586. * -()
  587. * operators:
  588. * and ('and' is the default operator: you can always omit this)
  589. * or (or pipe symbol '|', lower precedence than 'and')
  590. *
  591. * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
  592. * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
  593. * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
  594. * as long as you don't mind hit counts.
  595. *
  596. * intermediate representation consists of the following parts:
  597. *
  598. * ( ) - group
  599. * AND - logical and
  600. * OR - logical or
  601. * NOT - logical not
  602. * W+:, W-:, W_: - word (underscore: no need to highlight)
  603. * P+:, P-: - phrase (minus sign: logically in NOT group)
  604. * N+:, N-: - namespace
  605. */
  606. $parsed_query = '';
  607. $parens_level = 0;
  608. $terms = preg_split('/(-?".*?")/u', \dokuwiki\Utf8\PhpString::strtolower($query),
  609. -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  610. foreach ($terms as $term) {
  611. $parsed = '';
  612. if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
  613. // phrase-include and phrase-exclude
  614. $not = $matches[1] ? 'NOT' : '';
  615. $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
  616. } else {
  617. // fix incomplete phrase
  618. $term = str_replace('"', ' ', $term);
  619. // fix parentheses
  620. $term = str_replace(')' , ' ) ', $term);
  621. $term = str_replace('(' , ' ( ', $term);
  622. $term = str_replace('- (', ' -(', $term);
  623. // treat pipe symbols as 'OR' operators
  624. $term = str_replace('|', ' or ', $term);
  625. // treat ideographic spaces (U+3000) as search term separators
  626. // FIXME: some more separators?
  627. $term = preg_replace('/[ \x{3000}]+/u', ' ', $term);
  628. $term = trim($term);
  629. if ($term === '') continue;
  630. $tokens = explode(' ', $term);
  631. foreach ($tokens as $token) {
  632. if ($token === '(') {
  633. // parenthesis-include-open
  634. $parsed .= '(';
  635. ++$parens_level;
  636. } elseif ($token === '-(') {
  637. // parenthesis-exclude-open
  638. $parsed .= 'NOT(';
  639. ++$parens_level;
  640. } elseif ($token === ')') {
  641. // parenthesis-any-close
  642. if ($parens_level === 0) continue;
  643. $parsed .= ')';
  644. $parens_level--;
  645. } elseif ($token === 'and') {
  646. // logical-and (do nothing)
  647. } elseif ($token === 'or') {
  648. // logical-or
  649. $parsed .= 'OR';
  650. } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
  651. // namespace-exclude
  652. $parsed .= 'NOT(N+:'.$matches[1].')';
  653. } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
  654. // namespace-include
  655. $parsed .= '(N+:'.$matches[1].')';
  656. } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
  657. // word-exclude
  658. $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
  659. } else {
  660. // word-include
  661. $parsed .= ft_termParser($Indexer, $token);
  662. }
  663. }
  664. }
  665. $parsed_query .= $parsed;
  666. }
  667. // cleanup (very sensitive)
  668. $parsed_query .= str_repeat(')', $parens_level);
  669. do {
  670. $parsed_query_old = $parsed_query;
  671. $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
  672. } while ($parsed_query !== $parsed_query_old);
  673. $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query);
  674. $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query);
  675. $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query);
  676. $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query);
  677. $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
  678. // adjustment: make highlightings right
  679. $parens_level = 0;
  680. $notgrp_levels = array();
  681. $parsed_query_new = '';
  682. $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  683. foreach ($tokens as $token) {
  684. if ($token === 'NOT(') {
  685. $notgrp_levels[] = ++$parens_level;
  686. } elseif ($token === '(') {
  687. ++$parens_level;
  688. } elseif ($token === ')') {
  689. if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
  690. } elseif (count($notgrp_levels) % 2 === 1) {
  691. // turn highlight-flag off if terms are logically in "NOT" group
  692. $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
  693. }
  694. $parsed_query_new .= $token;
  695. }
  696. $parsed_query = $parsed_query_new;
  697. /**
  698. * convert infix notation string into postfix (Reverse Polish notation) array
  699. * by Shunting-yard algorithm
  700. *
  701. * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
  702. * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
  703. */
  704. $parsed_ary = array();
  705. $ope_stack = array();
  706. $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
  707. $ope_regex = '/([()]|OR|AND|NOT)/u';
  708. $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  709. foreach ($tokens as $token) {
  710. if (preg_match($ope_regex, $token)) {
  711. // operator
  712. $last_ope = end($ope_stack);
  713. while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
  714. $parsed_ary[] = array_pop($ope_stack);
  715. $last_ope = end($ope_stack);
  716. }
  717. if ($token == ')') {
  718. array_pop($ope_stack); // this array_pop always deletes '('
  719. } else {
  720. $ope_stack[] = $token;
  721. }
  722. } else {
  723. // operand
  724. $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
  725. $parsed_ary[] = $token_decoded;
  726. }
  727. }
  728. $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
  729. // cleanup: each double "NOT" in RPN array actually does nothing
  730. $parsed_ary_count = count($parsed_ary);
  731. for ($i = 1; $i < $parsed_ary_count; ++$i) {
  732. if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
  733. unset($parsed_ary[$i], $parsed_ary[$i - 1]);
  734. }
  735. }
  736. $parsed_ary = array_values($parsed_ary);
  737. // build return value
  738. $q = array();
  739. $q['query'] = $query;
  740. $q['parsed_str'] = $parsed_query;
  741. $q['parsed_ary'] = $parsed_ary;
  742. foreach ($q['parsed_ary'] as $token) {
  743. if ($token[2] !== ':') continue;
  744. $body = substr($token, 3);
  745. switch (substr($token, 0, 3)) {
  746. case 'N+:':
  747. $q['ns'][] = $body; // for backward compatibility
  748. break;
  749. case 'N-:':
  750. $q['notns'][] = $body; // for backward compatibility
  751. break;
  752. case 'W_:':
  753. $q['words'][] = $body;
  754. break;
  755. case 'W-:':
  756. $q['words'][] = $body;
  757. $q['not'][] = $body; // for backward compatibility
  758. break;
  759. case 'W+:':
  760. $q['words'][] = $body;
  761. $q['highlight'][] = $body;
  762. $q['and'][] = $body; // for backward compatibility
  763. break;
  764. case 'P-:':
  765. $q['phrases'][] = $body;
  766. break;
  767. case 'P+:':
  768. $q['phrases'][] = $body;
  769. $q['highlight'][] = $body;
  770. break;
  771. }
  772. }
  773. foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) {
  774. $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
  775. }
  776. return $q;
  777. }
  778. /**
  779. * Transforms given search term into intermediate representation
  780. *
  781. * This function is used in ft_queryParser() and not for general purpose use.
  782. *
  783. * @author Kazutaka Miyasaka <kazmiya@gmail.com>
  784. *
  785. * @param dokuwiki\Search\Indexer $Indexer
  786. * @param string $term
  787. * @param bool $consider_asian
  788. * @param bool $phrase_mode
  789. * @return string
  790. */
  791. function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) {
  792. $parsed = '';
  793. if ($consider_asian) {
  794. // successive asian characters need to be searched as a phrase
  795. $words = \dokuwiki\Utf8\Asian::splitAsianWords($term);
  796. foreach ($words as $word) {
  797. $phrase_mode = $phrase_mode ? true : \dokuwiki\Utf8\Asian::isAsianWords($word);
  798. $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
  799. }
  800. } else {
  801. $term_noparen = str_replace(array('(', ')'), ' ', $term);
  802. $words = $Indexer->tokenizer($term_noparen, true);
  803. // W_: no need to highlight
  804. if (empty($words)) {
  805. $parsed = '()'; // important: do not remove
  806. } elseif ($words[0] === $term) {
  807. $parsed = '(W+:'.$words[0].')';
  808. } elseif ($phrase_mode) {
  809. $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
  810. $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
  811. } else {
  812. $parsed = '((W+:'.implode(')(W+:', $words).'))';
  813. }
  814. }
  815. return $parsed;
  816. }
  817. /**
  818. * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
  819. *
  820. * @param array $and
  821. * @param array $not
  822. * @param array $phrases
  823. * @param array $ns
  824. * @param array $notns
  825. *
  826. * @return string
  827. */
  828. function ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) {
  829. $query = implode(' ', $and);
  830. if (!empty($not)) {
  831. $query .= ' -' . implode(' -', $not);
  832. }
  833. if (!empty($phrases)) {
  834. $query .= ' "' . implode('" "', $phrases) . '"';
  835. }
  836. if (!empty($ns)) {
  837. $query .= ' @' . implode(' @', $ns);
  838. }
  839. if (!empty($notns)) {
  840. $query .= ' ^' . implode(' ^', $notns);
  841. }
  842. return $query;
  843. }
  844. //Setup VIM: ex: et ts=4 :