PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/phpBB/phpbb/search/fulltext_native.php

https://github.com/Jipem/phpbb
PHP | 1811 lines | 1296 code | 207 blank | 308 comment | 171 complexity | fe010358b93143afa44d99d9c2cc522f MD5 | raw file
Possible License(s): AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. *
  4. * This file is part of the phpBB Forum Software package.
  5. *
  6. * @copyright (c) phpBB Limited <https://www.phpbb.com>
  7. * @license GNU General Public License, version 2 (GPL-2.0)
  8. *
  9. * For full copyright and license information, please see
  10. * the docs/CREDITS.txt file.
  11. *
  12. */
  13. namespace phpbb\search;
  14. /**
  15. * phpBB's own db driven fulltext search, version 2
  16. */
  17. class fulltext_native extends \phpbb\search\base
  18. {
  19. /**
  20. * Associative array holding index stats
  21. * @var array
  22. */
  23. protected $stats = array();
  24. /**
  25. * Associative array stores the min and max word length to be searched
  26. * @var array
  27. */
  28. protected $word_length = array();
  29. /**
  30. * Contains tidied search query.
  31. * Operators are prefixed in search query and common words excluded
  32. * @var string
  33. */
  34. protected $search_query;
  35. /**
  36. * Contains common words.
  37. * Common words are words with length less/more than min/max length
  38. * @var array
  39. */
  40. protected $common_words = array();
  41. /**
  42. * Post ids of posts containing words that are to be included
  43. * @var array
  44. */
  45. protected $must_contain_ids = array();
  46. /**
  47. * Post ids of posts containing words that should not be included
  48. * @var array
  49. */
  50. protected $must_not_contain_ids = array();
  51. /**
  52. * Post ids of posts containing atleast one word that needs to be excluded
  53. * @var array
  54. */
  55. protected $must_exclude_one_ids = array();
  56. /**
  57. * Relative path to board root
  58. * @var string
  59. */
  60. protected $phpbb_root_path;
  61. /**
  62. * PHP Extension
  63. * @var string
  64. */
  65. protected $php_ext;
  66. /**
  67. * Config object
  68. * @var \phpbb\config\config
  69. */
  70. protected $config;
  71. /**
  72. * Database connection
  73. * @var \phpbb\db\driver\driver_interface
  74. */
  75. protected $db;
  76. /**
  77. * User object
  78. * @var \phpbb\user
  79. */
  80. protected $user;
  81. /**
  82. * Initialises the fulltext_native search backend with min/max word length and makes sure the UTF-8 normalizer is loaded
  83. *
  84. * @param boolean|string &$error is passed by reference and should either be set to false on success or an error message on failure
  85. */
  86. public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user)
  87. {
  88. $this->phpbb_root_path = $phpbb_root_path;
  89. $this->php_ext = $phpEx;
  90. $this->config = $config;
  91. $this->db = $db;
  92. $this->user = $user;
  93. $this->word_length = array('min' => $this->config['fulltext_native_min_chars'], 'max' => $this->config['fulltext_native_max_chars']);
  94. /**
  95. * Load the UTF tools
  96. */
  97. if (!class_exists('utf_normalizer'))
  98. {
  99. include($this->phpbb_root_path . 'includes/utf/utf_normalizer.' . $this->php_ext);
  100. }
  101. if (!function_exists('utf8_decode_ncr'))
  102. {
  103. include($this->phpbb_root_path . 'includes/utf/utf_tools.' . $this->php_ext);
  104. }
  105. $error = false;
  106. }
  107. /**
  108. * Returns the name of this search backend to be displayed to administrators
  109. *
  110. * @return string Name
  111. */
  112. public function get_name()
  113. {
  114. return 'phpBB Native Fulltext';
  115. }
  116. /**
  117. * Returns the search_query
  118. *
  119. * @return string search query
  120. */
  121. public function get_search_query()
  122. {
  123. return $this->search_query;
  124. }
  125. /**
  126. * Returns the common_words array
  127. *
  128. * @return array common words that are ignored by search backend
  129. */
  130. public function get_common_words()
  131. {
  132. return $this->common_words;
  133. }
  134. /**
  135. * Returns the word_length array
  136. *
  137. * @return array min and max word length for searching
  138. */
  139. public function get_word_length()
  140. {
  141. return $this->word_length;
  142. }
  143. /**
  144. * This function fills $this->search_query with the cleaned user search query
  145. *
  146. * If $terms is 'any' then the words will be extracted from the search query
  147. * and combined with | inside brackets. They will afterwards be treated like
  148. * an standard search query.
  149. *
  150. * Then it analyses the query and fills the internal arrays $must_not_contain_ids,
  151. * $must_contain_ids and $must_exclude_one_ids which are later used by keyword_search()
  152. *
  153. * @param string $keywords contains the search query string as entered by the user
  154. * @param string $terms is either 'all' (use search query as entered, default words to 'must be contained in post')
  155. * or 'any' (find all posts containing at least one of the given words)
  156. * @return boolean false if no valid keywords were found and otherwise true
  157. */
  158. public function split_keywords($keywords, $terms)
  159. {
  160. $tokens = '+-|()*';
  161. $keywords = trim($this->cleanup($keywords, $tokens));
  162. // allow word|word|word without brackets
  163. if ((strpos($keywords, ' ') === false) && (strpos($keywords, '|') !== false) && (strpos($keywords, '(') === false))
  164. {
  165. $keywords = '(' . $keywords . ')';
  166. }
  167. $open_bracket = $space = false;
  168. for ($i = 0, $n = strlen($keywords); $i < $n; $i++)
  169. {
  170. if ($open_bracket !== false)
  171. {
  172. switch ($keywords[$i])
  173. {
  174. case ')':
  175. if ($open_bracket + 1 == $i)
  176. {
  177. $keywords[$i - 1] = '|';
  178. $keywords[$i] = '|';
  179. }
  180. $open_bracket = false;
  181. break;
  182. case '(':
  183. $keywords[$i] = '|';
  184. break;
  185. case '+':
  186. case '-':
  187. case ' ':
  188. $keywords[$i] = '|';
  189. break;
  190. case '*':
  191. if ($i === 0 || ($keywords[$i - 1] !== '*' && strcspn($keywords[$i - 1], $tokens) === 0))
  192. {
  193. if ($i === $n - 1 || ($keywords[$i + 1] !== '*' && strcspn($keywords[$i + 1], $tokens) === 0))
  194. {
  195. $keywords = substr($keywords, 0, $i) . substr($keywords, $i + 1);
  196. }
  197. }
  198. break;
  199. }
  200. }
  201. else
  202. {
  203. switch ($keywords[$i])
  204. {
  205. case ')':
  206. $keywords[$i] = ' ';
  207. break;
  208. case '(':
  209. $open_bracket = $i;
  210. $space = false;
  211. break;
  212. case '|':
  213. $keywords[$i] = ' ';
  214. break;
  215. case '-':
  216. case '+':
  217. $space = $keywords[$i];
  218. break;
  219. case ' ':
  220. if ($space !== false)
  221. {
  222. $keywords[$i] = $space;
  223. }
  224. break;
  225. default:
  226. $space = false;
  227. }
  228. }
  229. }
  230. if ($open_bracket)
  231. {
  232. $keywords .= ')';
  233. }
  234. $match = array(
  235. '# +#',
  236. '#\|\|+#',
  237. '#(\+|\-)(?:\+|\-)+#',
  238. '#\(\|#',
  239. '#\|\)#',
  240. );
  241. $replace = array(
  242. ' ',
  243. '|',
  244. '$1',
  245. '(',
  246. ')',
  247. );
  248. $keywords = preg_replace($match, $replace, $keywords);
  249. $num_keywords = sizeof(explode(' ', $keywords));
  250. // We limit the number of allowed keywords to minimize load on the database
  251. if ($this->config['max_num_search_keywords'] && $num_keywords > $this->config['max_num_search_keywords'])
  252. {
  253. trigger_error($this->user->lang('MAX_NUM_SEARCH_KEYWORDS_REFINE', (int) $this->config['max_num_search_keywords'], $num_keywords));
  254. }
  255. // $keywords input format: each word separated by a space, words in a bracket are not separated
  256. // the user wants to search for any word, convert the search query
  257. if ($terms == 'any')
  258. {
  259. $words = array();
  260. preg_match_all('#([^\\s+\\-|()]+)(?:$|[\\s+\\-|()])#u', $keywords, $words);
  261. if (sizeof($words[1]))
  262. {
  263. $keywords = '(' . implode('|', $words[1]) . ')';
  264. }
  265. }
  266. // set the search_query which is shown to the user
  267. $this->search_query = $keywords;
  268. $exact_words = array();
  269. preg_match_all('#([^\\s+\\-|*()]+)(?:$|[\\s+\\-|()])#u', $keywords, $exact_words);
  270. $exact_words = $exact_words[1];
  271. $common_ids = $words = array();
  272. if (sizeof($exact_words))
  273. {
  274. $sql = 'SELECT word_id, word_text, word_common
  275. FROM ' . SEARCH_WORDLIST_TABLE . '
  276. WHERE ' . $this->db->sql_in_set('word_text', $exact_words) . '
  277. ORDER BY word_count ASC';
  278. $result = $this->db->sql_query($sql);
  279. // store an array of words and ids, remove common words
  280. while ($row = $this->db->sql_fetchrow($result))
  281. {
  282. if ($row['word_common'])
  283. {
  284. $this->common_words[] = $row['word_text'];
  285. $common_ids[$row['word_text']] = (int) $row['word_id'];
  286. continue;
  287. }
  288. $words[$row['word_text']] = (int) $row['word_id'];
  289. }
  290. $this->db->sql_freeresult($result);
  291. }
  292. // Handle +, - without preceeding whitespace character
  293. $match = array('#(\S)\+#', '#(\S)-#');
  294. $replace = array('$1 +', '$1 +');
  295. $keywords = preg_replace($match, $replace, $keywords);
  296. // now analyse the search query, first split it using the spaces
  297. $query = explode(' ', $keywords);
  298. $this->must_contain_ids = array();
  299. $this->must_not_contain_ids = array();
  300. $this->must_exclude_one_ids = array();
  301. $mode = '';
  302. $ignore_no_id = true;
  303. foreach ($query as $word)
  304. {
  305. if (empty($word))
  306. {
  307. continue;
  308. }
  309. // words which should not be included
  310. if ($word[0] == '-')
  311. {
  312. $word = substr($word, 1);
  313. // a group of which at least one may not be in the resulting posts
  314. if ($word[0] == '(')
  315. {
  316. $word = array_unique(explode('|', substr($word, 1, -1)));
  317. $mode = 'must_exclude_one';
  318. }
  319. // one word which should not be in the resulting posts
  320. else
  321. {
  322. $mode = 'must_not_contain';
  323. }
  324. $ignore_no_id = true;
  325. }
  326. // words which have to be included
  327. else
  328. {
  329. // no prefix is the same as a +prefix
  330. if ($word[0] == '+')
  331. {
  332. $word = substr($word, 1);
  333. }
  334. // a group of words of which at least one word should be in every resulting post
  335. if ($word[0] == '(')
  336. {
  337. $word = array_unique(explode('|', substr($word, 1, -1)));
  338. }
  339. $ignore_no_id = false;
  340. $mode = 'must_contain';
  341. }
  342. if (empty($word))
  343. {
  344. continue;
  345. }
  346. // if this is an array of words then retrieve an id for each
  347. if (is_array($word))
  348. {
  349. $non_common_words = array();
  350. $id_words = array();
  351. foreach ($word as $i => $word_part)
  352. {
  353. if (strpos($word_part, '*') !== false)
  354. {
  355. $id_words[] = '\'' . $this->db->sql_escape(str_replace('*', '%', $word_part)) . '\'';
  356. $non_common_words[] = $word_part;
  357. }
  358. else if (isset($words[$word_part]))
  359. {
  360. $id_words[] = $words[$word_part];
  361. $non_common_words[] = $word_part;
  362. }
  363. else
  364. {
  365. $len = utf8_strlen($word_part);
  366. if ($len < $this->word_length['min'] || $len > $this->word_length['max'])
  367. {
  368. $this->common_words[] = $word_part;
  369. }
  370. }
  371. }
  372. if (sizeof($id_words))
  373. {
  374. sort($id_words);
  375. if (sizeof($id_words) > 1)
  376. {
  377. $this->{$mode . '_ids'}[] = $id_words;
  378. }
  379. else
  380. {
  381. $mode = ($mode == 'must_exclude_one') ? 'must_not_contain' : $mode;
  382. $this->{$mode . '_ids'}[] = $id_words[0];
  383. }
  384. }
  385. // throw an error if we shall not ignore unexistant words
  386. else if (!$ignore_no_id && sizeof($non_common_words))
  387. {
  388. trigger_error(sprintf($user->lang['WORDS_IN_NO_POST'], implode($user->lang['COMMA_SEPARATOR'], $non_common_words)));
  389. }
  390. unset($non_common_words);
  391. }
  392. // else we only need one id
  393. else if (($wildcard = strpos($word, '*') !== false) || isset($words[$word]))
  394. {
  395. if ($wildcard)
  396. {
  397. $len = utf8_strlen(str_replace('*', '', $word));
  398. if ($len >= $this->word_length['min'] && $len <= $this->word_length['max'])
  399. {
  400. $this->{$mode . '_ids'}[] = '\'' . $this->db->sql_escape(str_replace('*', '%', $word)) . '\'';
  401. }
  402. else
  403. {
  404. $this->common_words[] = $word;
  405. }
  406. }
  407. else
  408. {
  409. $this->{$mode . '_ids'}[] = $words[$word];
  410. }
  411. }
  412. else
  413. {
  414. if (!isset($common_ids[$word]))
  415. {
  416. $len = utf8_strlen($word);
  417. if ($len < $this->word_length['min'] || $len > $this->word_length['max'])
  418. {
  419. $this->common_words[] = $word;
  420. }
  421. }
  422. }
  423. }
  424. // Return true if all words are not common words
  425. if (sizeof($exact_words) - sizeof($this->common_words) > 0)
  426. {
  427. return true;
  428. }
  429. return false;
  430. }
  431. /**
  432. * Performs a search on keywords depending on display specific params. You have to run split_keywords() first
  433. *
  434. * @param string $type contains either posts or topics depending on what should be searched for
  435. * @param string $fields contains either titleonly (topic titles should be searched), msgonly (only message bodies should be searched), firstpost (only subject and body of the first post should be searched) or all (all post bodies and subjects should be searched)
  436. * @param string $terms is either 'all' (use query as entered, words without prefix should default to "have to be in field") or 'any' (ignore search query parts and just return all posts that contain any of the specified words)
  437. * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query
  438. * @param string $sort_key is the key of $sort_by_sql for the selected sorting
  439. * @param string $sort_dir is either a or d representing ASC and DESC
  440. * @param string $sort_days specifies the maximum amount of days a post may be old
  441. * @param array $ex_fid_ary specifies an array of forum ids which should not be searched
  442. * @param string $post_visibility specifies which types of posts the user can view in which forums
  443. * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched
  444. * @param array $author_ary an array of author ids if the author should be ignored during the search the array is empty
  445. * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match
  446. * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
  447. * @param int $start indicates the first index of the page
  448. * @param int $per_page number of ids each page is supposed to contain
  449. * @return boolean|int total number of results
  450. */
  451. public function keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page)
  452. {
  453. // No keywords? No posts.
  454. if (empty($this->search_query))
  455. {
  456. return false;
  457. }
  458. // we can't search for negatives only
  459. if (empty($this->must_contain_ids))
  460. {
  461. return false;
  462. }
  463. $must_contain_ids = $this->must_contain_ids;
  464. $must_not_contain_ids = $this->must_not_contain_ids;
  465. $must_exclude_one_ids = $this->must_exclude_one_ids;
  466. sort($must_contain_ids);
  467. sort($must_not_contain_ids);
  468. sort($must_exclude_one_ids);
  469. // generate a search_key from all the options to identify the results
  470. $search_key = md5(implode('#', array(
  471. serialize($must_contain_ids),
  472. serialize($must_not_contain_ids),
  473. serialize($must_exclude_one_ids),
  474. $type,
  475. $fields,
  476. $terms,
  477. $sort_days,
  478. $sort_key,
  479. $topic_id,
  480. implode(',', $ex_fid_ary),
  481. $post_visibility,
  482. implode(',', $author_ary),
  483. $author_name,
  484. )));
  485. // try reading the results from cache
  486. $total_results = 0;
  487. if ($this->obtain_ids($search_key, $total_results, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
  488. {
  489. return $total_results;
  490. }
  491. $id_ary = array();
  492. $sql_where = array();
  493. $group_by = false;
  494. $m_num = 0;
  495. $w_num = 0;
  496. $sql_array = array(
  497. 'SELECT' => ($type == 'posts') ? 'p.post_id' : 'p.topic_id',
  498. 'FROM' => array(
  499. SEARCH_WORDMATCH_TABLE => array(),
  500. SEARCH_WORDLIST_TABLE => array(),
  501. ),
  502. 'LEFT_JOIN' => array(array(
  503. 'FROM' => array(POSTS_TABLE => 'p'),
  504. 'ON' => 'm0.post_id = p.post_id',
  505. )),
  506. );
  507. $title_match = '';
  508. $left_join_topics = false;
  509. $group_by = true;
  510. // Build some display specific sql strings
  511. switch ($fields)
  512. {
  513. case 'titleonly':
  514. $title_match = 'title_match = 1';
  515. $group_by = false;
  516. // no break
  517. case 'firstpost':
  518. $left_join_topics = true;
  519. $sql_where[] = 'p.post_id = t.topic_first_post_id';
  520. break;
  521. case 'msgonly':
  522. $title_match = 'title_match = 0';
  523. $group_by = false;
  524. break;
  525. }
  526. if ($type == 'topics')
  527. {
  528. $left_join_topics = true;
  529. $group_by = true;
  530. }
  531. /**
  532. * @todo Add a query optimizer (handle stuff like "+(4|3) +4")
  533. */
  534. foreach ($this->must_contain_ids as $subquery)
  535. {
  536. if (is_array($subquery))
  537. {
  538. $group_by = true;
  539. $word_id_sql = array();
  540. $word_ids = array();
  541. foreach ($subquery as $id)
  542. {
  543. if (is_string($id))
  544. {
  545. $sql_array['LEFT_JOIN'][] = array(
  546. 'FROM' => array(SEARCH_WORDLIST_TABLE => 'w' . $w_num),
  547. 'ON' => "w$w_num.word_text LIKE $id"
  548. );
  549. $word_ids[] = "w$w_num.word_id";
  550. $w_num++;
  551. }
  552. else
  553. {
  554. $word_ids[] = $id;
  555. }
  556. }
  557. $sql_where[] = $this->db->sql_in_set("m$m_num.word_id", $word_ids);
  558. unset($word_id_sql);
  559. unset($word_ids);
  560. }
  561. else if (is_string($subquery))
  562. {
  563. $sql_array['FROM'][SEARCH_WORDLIST_TABLE][] = 'w' . $w_num;
  564. $sql_where[] = "w$w_num.word_text LIKE $subquery";
  565. $sql_where[] = "m$m_num.word_id = w$w_num.word_id";
  566. $group_by = true;
  567. $w_num++;
  568. }
  569. else
  570. {
  571. $sql_where[] = "m$m_num.word_id = $subquery";
  572. }
  573. $sql_array['FROM'][SEARCH_WORDMATCH_TABLE][] = 'm' . $m_num;
  574. if ($title_match)
  575. {
  576. $sql_where[] = "m$m_num.$title_match";
  577. }
  578. if ($m_num != 0)
  579. {
  580. $sql_where[] = "m$m_num.post_id = m0.post_id";
  581. }
  582. $m_num++;
  583. }
  584. foreach ($this->must_not_contain_ids as $key => $subquery)
  585. {
  586. if (is_string($subquery))
  587. {
  588. $sql_array['LEFT_JOIN'][] = array(
  589. 'FROM' => array(SEARCH_WORDLIST_TABLE => 'w' . $w_num),
  590. 'ON' => "w$w_num.word_text LIKE $subquery"
  591. );
  592. $this->must_not_contain_ids[$key] = "w$w_num.word_id";
  593. $group_by = true;
  594. $w_num++;
  595. }
  596. }
  597. if (sizeof($this->must_not_contain_ids))
  598. {
  599. $sql_array['LEFT_JOIN'][] = array(
  600. 'FROM' => array(SEARCH_WORDMATCH_TABLE => 'm' . $m_num),
  601. 'ON' => $this->db->sql_in_set("m$m_num.word_id", $this->must_not_contain_ids) . (($title_match) ? " AND m$m_num.$title_match" : '') . " AND m$m_num.post_id = m0.post_id"
  602. );
  603. $sql_where[] = "m$m_num.word_id IS NULL";
  604. $m_num++;
  605. }
  606. foreach ($this->must_exclude_one_ids as $ids)
  607. {
  608. $is_null_joins = array();
  609. foreach ($ids as $id)
  610. {
  611. if (is_string($id))
  612. {
  613. $sql_array['LEFT_JOIN'][] = array(
  614. 'FROM' => array(SEARCH_WORDLIST_TABLE => 'w' . $w_num),
  615. 'ON' => "w$w_num.word_text LIKE $id"
  616. );
  617. $id = "w$w_num.word_id";
  618. $group_by = true;
  619. $w_num++;
  620. }
  621. $sql_array['LEFT_JOIN'][] = array(
  622. 'FROM' => array(SEARCH_WORDMATCH_TABLE => 'm' . $m_num),
  623. 'ON' => "m$m_num.word_id = $id AND m$m_num.post_id = m0.post_id" . (($title_match) ? " AND m$m_num.$title_match" : '')
  624. );
  625. $is_null_joins[] = "m$m_num.word_id IS NULL";
  626. $m_num++;
  627. }
  628. $sql_where[] = '(' . implode(' OR ', $is_null_joins) . ')';
  629. }
  630. $sql_where[] = $post_visibility;
  631. if ($topic_id)
  632. {
  633. $sql_where[] = 'p.topic_id = ' . $topic_id;
  634. }
  635. if (sizeof($author_ary))
  636. {
  637. if ($author_name)
  638. {
  639. // first one matches post of registered users, second one guests and deleted users
  640. $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
  641. }
  642. else
  643. {
  644. $sql_author = $this->db->sql_in_set('p.poster_id', $author_ary);
  645. }
  646. $sql_where[] = $sql_author;
  647. }
  648. if (sizeof($ex_fid_ary))
  649. {
  650. $sql_where[] = $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true);
  651. }
  652. if ($sort_days)
  653. {
  654. $sql_where[] = 'p.post_time >= ' . (time() - ($sort_days * 86400));
  655. }
  656. $sql_array['WHERE'] = implode(' AND ', $sql_where);
  657. $is_mysql = false;
  658. // if the total result count is not cached yet, retrieve it from the db
  659. if (!$total_results)
  660. {
  661. $sql = '';
  662. $sql_array_count = $sql_array;
  663. if ($left_join_topics)
  664. {
  665. $sql_array_count['LEFT_JOIN'][] = array(
  666. 'FROM' => array(TOPICS_TABLE => 't'),
  667. 'ON' => 'p.topic_id = t.topic_id'
  668. );
  669. }
  670. switch ($this->db->sql_layer)
  671. {
  672. case 'mysql4':
  673. case 'mysqli':
  674. // 3.x does not support SQL_CALC_FOUND_ROWS
  675. // $sql_array['SELECT'] = 'SQL_CALC_FOUND_ROWS ' . $sql_array['SELECT'];
  676. $is_mysql = true;
  677. break;
  678. case 'sqlite':
  679. case 'sqlite3':
  680. $sql_array_count['SELECT'] = ($type == 'posts') ? 'DISTINCT p.post_id' : 'DISTINCT p.topic_id';
  681. $sql = 'SELECT COUNT(' . (($type == 'posts') ? 'post_id' : 'topic_id') . ') as total_results
  682. FROM (' . $this->db->sql_build_query('SELECT', $sql_array_count) . ')';
  683. // no break
  684. default:
  685. $sql_array_count['SELECT'] = ($type == 'posts') ? 'COUNT(DISTINCT p.post_id) AS total_results' : 'COUNT(DISTINCT p.topic_id) AS total_results';
  686. $sql = (!$sql) ? $this->db->sql_build_query('SELECT', $sql_array_count) : $sql;
  687. $result = $this->db->sql_query($sql);
  688. $total_results = (int) $this->db->sql_fetchfield('total_results');
  689. $this->db->sql_freeresult($result);
  690. if (!$total_results)
  691. {
  692. return false;
  693. }
  694. break;
  695. }
  696. unset($sql_array_count, $sql);
  697. }
  698. // Build sql strings for sorting
  699. $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
  700. switch ($sql_sort[0])
  701. {
  702. case 'u':
  703. $sql_array['FROM'][USERS_TABLE] = 'u';
  704. $sql_where[] = 'u.user_id = p.poster_id ';
  705. break;
  706. case 't':
  707. $left_join_topics = true;
  708. break;
  709. case 'f':
  710. $sql_array['FROM'][FORUMS_TABLE] = 'f';
  711. $sql_where[] = 'f.forum_id = p.forum_id';
  712. break;
  713. }
  714. if ($left_join_topics)
  715. {
  716. $sql_array['LEFT_JOIN'][] = array(
  717. 'FROM' => array(TOPICS_TABLE => 't'),
  718. 'ON' => 'p.topic_id = t.topic_id'
  719. );
  720. }
  721. $sql_array['WHERE'] = implode(' AND ', $sql_where);
  722. $sql_array['GROUP_BY'] = ($group_by) ? (($type == 'posts') ? 'p.post_id' : 'p.topic_id') . ', ' . $sort_by_sql[$sort_key] : '';
  723. $sql_array['ORDER_BY'] = $sql_sort;
  724. unset($sql_where, $sql_sort, $group_by);
  725. $sql = $this->db->sql_build_query('SELECT', $sql_array);
  726. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  727. while ($row = $this->db->sql_fetchrow($result))
  728. {
  729. $id_ary[] = (int) $row[(($type == 'posts') ? 'post_id' : 'topic_id')];
  730. }
  731. $this->db->sql_freeresult($result);
  732. // if we use mysql and the total result count is not cached yet, retrieve it from the db
  733. if (!$total_results && $is_mysql)
  734. {
  735. // Count rows for the executed queries. Replace $select within $sql with SQL_CALC_FOUND_ROWS, and run it
  736. $sql_array_copy = $sql_array;
  737. $sql_array_copy['SELECT'] = 'SQL_CALC_FOUND_ROWS p.post_id ';
  738. $sql_calc = $this->db->sql_build_query('SELECT', $sql_array_copy);
  739. unset($sql_array_copy);
  740. $this->db->sql_query($sql_calc);
  741. $this->db->sql_freeresult($result);
  742. $sql_count = 'SELECT FOUND_ROWS() as total_results';
  743. $result = $this->db->sql_query($sql_count);
  744. $total_results = (int) $this->db->sql_fetchfield('total_results');
  745. $this->db->sql_freeresult($result);
  746. if (!$total_results)
  747. {
  748. return false;
  749. }
  750. }
  751. if ($start >= $total_results)
  752. {
  753. $start = floor(($total_results - 1) / $per_page) * $per_page;
  754. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  755. while ($row = $this->db->sql_fetchrow($result))
  756. {
  757. $id_ary[] = (int) $row[(($type == 'posts') ? 'post_id' : 'topic_id')];
  758. }
  759. $this->db->sql_freeresult($result);
  760. }
  761. // store the ids, from start on then delete anything that isn't on the current page because we only need ids for one page
  762. $this->save_ids($search_key, $this->search_query, $author_ary, $total_results, $id_ary, $start, $sort_dir);
  763. $id_ary = array_slice($id_ary, 0, (int) $per_page);
  764. return $total_results;
  765. }
  766. /**
  767. * Performs a search on an author's posts without caring about message contents. Depends on display specific params
  768. *
  769. * @param string $type contains either posts or topics depending on what should be searched for
  770. * @param boolean $firstpost_only if true, only topic starting posts will be considered
  771. * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query
  772. * @param string $sort_key is the key of $sort_by_sql for the selected sorting
  773. * @param string $sort_dir is either a or d representing ASC and DESC
  774. * @param string $sort_days specifies the maximum amount of days a post may be old
  775. * @param array $ex_fid_ary specifies an array of forum ids which should not be searched
  776. * @param string $post_visibility specifies which types of posts the user can view in which forums
  777. * @param int $topic_id is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched
  778. * @param array $author_ary an array of author ids
  779. * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match
  780. * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
  781. * @param int $start indicates the first index of the page
  782. * @param int $per_page number of ids each page is supposed to contain
  783. * @return boolean|int total number of results
  784. */
  785. public function author_search($type, $firstpost_only, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page)
  786. {
  787. // No author? No posts
  788. if (!sizeof($author_ary))
  789. {
  790. return 0;
  791. }
  792. // generate a search_key from all the options to identify the results
  793. $search_key = md5(implode('#', array(
  794. '',
  795. $type,
  796. ($firstpost_only) ? 'firstpost' : '',
  797. '',
  798. '',
  799. $sort_days,
  800. $sort_key,
  801. $topic_id,
  802. implode(',', $ex_fid_ary),
  803. $post_visibility,
  804. implode(',', $author_ary),
  805. $author_name,
  806. )));
  807. // try reading the results from cache
  808. $total_results = 0;
  809. if ($this->obtain_ids($search_key, $total_results, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
  810. {
  811. return $total_results;
  812. }
  813. $id_ary = array();
  814. // Create some display specific sql strings
  815. if ($author_name)
  816. {
  817. // first one matches post of registered users, second one guests and deleted users
  818. $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
  819. }
  820. else
  821. {
  822. $sql_author = $this->db->sql_in_set('p.poster_id', $author_ary);
  823. }
  824. $sql_fora = (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
  825. $sql_time = ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
  826. $sql_topic_id = ($topic_id) ? ' AND p.topic_id = ' . (int) $topic_id : '';
  827. $sql_firstpost = ($firstpost_only) ? ' AND p.post_id = t.topic_first_post_id' : '';
  828. $post_visibility = ($post_visibility) ? ' AND ' . $post_visibility : '';
  829. // Build sql strings for sorting
  830. $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
  831. $sql_sort_table = $sql_sort_join = '';
  832. switch ($sql_sort[0])
  833. {
  834. case 'u':
  835. $sql_sort_table = USERS_TABLE . ' u, ';
  836. $sql_sort_join = ' AND u.user_id = p.poster_id ';
  837. break;
  838. case 't':
  839. $sql_sort_table = ($type == 'posts' && !$firstpost_only) ? TOPICS_TABLE . ' t, ' : '';
  840. $sql_sort_join = ($type == 'posts' && !$firstpost_only) ? ' AND t.topic_id = p.topic_id ' : '';
  841. break;
  842. case 'f':
  843. $sql_sort_table = FORUMS_TABLE . ' f, ';
  844. $sql_sort_join = ' AND f.forum_id = p.forum_id ';
  845. break;
  846. }
  847. $select = ($type == 'posts') ? 'p.post_id' : 't.topic_id';
  848. $is_mysql = false;
  849. // If the cache was completely empty count the results
  850. if (!$total_results)
  851. {
  852. switch ($this->db->sql_layer)
  853. {
  854. case 'mysql4':
  855. case 'mysqli':
  856. // $select = 'SQL_CALC_FOUND_ROWS ' . $select;
  857. $is_mysql = true;
  858. break;
  859. default:
  860. if ($type == 'posts')
  861. {
  862. $sql = 'SELECT COUNT(p.post_id) as total_results
  863. FROM ' . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . "
  864. WHERE $sql_author
  865. $sql_topic_id
  866. $sql_firstpost
  867. $post_visibility
  868. $sql_fora
  869. $sql_time";
  870. }
  871. else
  872. {
  873. if ($this->db->sql_layer == 'sqlite' || $this->db->sql_layer == 'sqlite3')
  874. {
  875. $sql = 'SELECT COUNT(topic_id) as total_results
  876. FROM (SELECT DISTINCT t.topic_id';
  877. }
  878. else
  879. {
  880. $sql = 'SELECT COUNT(DISTINCT t.topic_id) as total_results';
  881. }
  882. $sql .= ' FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  883. WHERE $sql_author
  884. $sql_topic_id
  885. $sql_firstpost
  886. $post_visibility
  887. $sql_fora
  888. AND t.topic_id = p.topic_id
  889. $sql_time" . (($this->db->sql_layer == 'sqlite' || $this->db->sql_layer == 'sqlite3') ? ')' : '');
  890. }
  891. $result = $this->db->sql_query($sql);
  892. $total_results = (int) $this->db->sql_fetchfield('total_results');
  893. $this->db->sql_freeresult($result);
  894. if (!$total_results)
  895. {
  896. return false;
  897. }
  898. break;
  899. }
  900. }
  901. // Build the query for really selecting the post_ids
  902. if ($type == 'posts')
  903. {
  904. $sql = "SELECT $select
  905. FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t' : '') . "
  906. WHERE $sql_author
  907. $sql_topic_id
  908. $sql_firstpost
  909. $post_visibility
  910. $sql_fora
  911. $sql_sort_join
  912. $sql_time
  913. ORDER BY $sql_sort";
  914. $field = 'post_id';
  915. }
  916. else
  917. {
  918. $sql = "SELECT $select
  919. FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  920. WHERE $sql_author
  921. $sql_topic_id
  922. $sql_firstpost
  923. $post_visibility
  924. $sql_fora
  925. AND t.topic_id = p.topic_id
  926. $sql_sort_join
  927. $sql_time
  928. GROUP BY t.topic_id, " . $sort_by_sql[$sort_key] . '
  929. ORDER BY ' . $sql_sort;
  930. $field = 'topic_id';
  931. }
  932. // Only read one block of posts from the db and then cache it
  933. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  934. while ($row = $this->db->sql_fetchrow($result))
  935. {
  936. $id_ary[] = (int) $row[$field];
  937. }
  938. $this->db->sql_freeresult($result);
  939. if (!$total_results && $is_mysql)
  940. {
  941. // Count rows for the executed queries. Replace $select within $sql with SQL_CALC_FOUND_ROWS, and run it.
  942. $sql_calc = str_replace('SELECT ' . $select, 'SELECT DISTINCT SQL_CALC_FOUND_ROWS p.post_id', $sql);
  943. $this->db->sql_query($sql_calc);
  944. $this->db->sql_freeresult($result);
  945. $sql_count = 'SELECT FOUND_ROWS() as total_results';
  946. $result = $this->db->sql_query($sql_count);
  947. $total_results = (int) $this->db->sql_fetchfield('total_results');
  948. $this->db->sql_freeresult($result);
  949. if (!$total_results)
  950. {
  951. return false;
  952. }
  953. }
  954. if ($start >= $total_results)
  955. {
  956. $start = floor(($total_results - 1) / $per_page) * $per_page;
  957. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  958. while ($row = $this->db->sql_fetchrow($result))
  959. {
  960. $id_ary[] = (int) $row[$field];
  961. }
  962. $this->db->sql_freeresult($result);
  963. }
  964. if (sizeof($id_ary))
  965. {
  966. $this->save_ids($search_key, '', $author_ary, $total_results, $id_ary, $start, $sort_dir);
  967. $id_ary = array_slice($id_ary, 0, $per_page);
  968. return $total_results;
  969. }
  970. return false;
  971. }
  972. /**
  973. * Split a text into words of a given length
  974. *
  975. * The text is converted to UTF-8, cleaned up, and split. Then, words that
  976. * conform to the defined length range are returned in an array.
  977. *
  978. * NOTE: duplicates are NOT removed from the return array
  979. *
  980. * @param string $text Text to split, encoded in UTF-8
  981. * @return array Array of UTF-8 words
  982. */
  983. public function split_message($text)
  984. {
  985. $match = $words = array();
  986. /**
  987. * Taken from the original code
  988. */
  989. // Do not index code
  990. $match[] = '#\[code(?:=.*?)?(\:?[0-9a-z]{5,})\].*?\[\/code(\:?[0-9a-z]{5,})\]#is';
  991. // BBcode
  992. $match[] = '#\[\/?[a-z0-9\*\+\-]+(?:=.*?)?(?::[a-z])?(\:?[0-9a-z]{5,})\]#';
  993. $min = $this->word_length['min'];
  994. $max = $this->word_length['max'];
  995. $isset_min = $min - 1;
  996. /**
  997. * Clean up the string, remove HTML tags, remove BBCodes
  998. */
  999. $word = strtok($this->cleanup(preg_replace($match, ' ', strip_tags($text)), -1), ' ');
  1000. while (strlen($word))
  1001. {
  1002. if (strlen($word) > 255 || strlen($word) <= $isset_min)
  1003. {
  1004. /**
  1005. * Words longer than 255 bytes are ignored. This will have to be
  1006. * changed whenever we change the length of search_wordlist.word_text
  1007. *
  1008. * Words shorter than $isset_min bytes are ignored, too
  1009. */
  1010. $word = strtok(' ');
  1011. continue;
  1012. }
  1013. $len = utf8_strlen($word);
  1014. /**
  1015. * Test whether the word is too short to be indexed.
  1016. *
  1017. * Note that this limit does NOT apply to CJK and Hangul
  1018. */
  1019. if ($len < $min)
  1020. {
  1021. /**
  1022. * Note: this could be optimized. If the codepoint is lower than Hangul's range
  1023. * we know that it will also be lower than CJK ranges
  1024. */
  1025. if ((strncmp($word, UTF8_HANGUL_FIRST, 3) < 0 || strncmp($word, UTF8_HANGUL_LAST, 3) > 0)
  1026. && (strncmp($word, UTF8_CJK_FIRST, 3) < 0 || strncmp($word, UTF8_CJK_LAST, 3) > 0)
  1027. && (strncmp($word, UTF8_CJK_B_FIRST, 4) < 0 || strncmp($word, UTF8_CJK_B_LAST, 4) > 0))
  1028. {
  1029. $word = strtok(' ');
  1030. continue;
  1031. }
  1032. }
  1033. $words[] = $word;
  1034. $word = strtok(' ');
  1035. }
  1036. return $words;
  1037. }
  1038. /**
  1039. * Updates wordlist and wordmatch tables when a message is posted or changed
  1040. *
  1041. * @param string $mode Contains the post mode: edit, post, reply, quote
  1042. * @param int $post_id The id of the post which is modified/created
  1043. * @param string &$message New or updated post content
  1044. * @param string &$subject New or updated post subject
  1045. * @param int $poster_id Post author's user id
  1046. * @param int $forum_id The id of the forum in which the post is located
  1047. */
  1048. public function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id)
  1049. {
  1050. if (!$this->config['fulltext_native_load_upd'])
  1051. {
  1052. /**
  1053. * The search indexer is disabled, return
  1054. */
  1055. return;
  1056. }
  1057. // Split old and new post/subject to obtain array of 'words'
  1058. $split_text = $this->split_message($message);
  1059. $split_title = $this->split_message($subject);
  1060. $cur_words = array('post' => array(), 'title' => array());
  1061. $words = array();
  1062. if ($mode == 'edit')
  1063. {
  1064. $words['add']['post'] = array();
  1065. $words['add']['title'] = array();
  1066. $words['del']['post'] = array();
  1067. $words['del']['title'] = array();
  1068. $sql = 'SELECT w.word_id, w.word_text, m.title_match
  1069. FROM ' . SEARCH_WORDLIST_TABLE . ' w, ' . SEARCH_WORDMATCH_TABLE . " m
  1070. WHERE m.post_id = $post_id
  1071. AND w.word_id = m.word_id";
  1072. $result = $this->db->sql_query($sql);
  1073. while ($row = $this->db->sql_fetchrow($result))
  1074. {
  1075. $which = ($row['title_match']) ? 'title' : 'post';
  1076. $cur_words[$which][$row['word_text']] = $row['word_id'];
  1077. }
  1078. $this->db->sql_freeresult($result);
  1079. $words['add']['post'] = array_diff($split_text, array_keys($cur_words['post']));
  1080. $words['add']['title'] = array_diff($split_title, array_keys($cur_words['title']));
  1081. $words['del']['post'] = array_diff(array_keys($cur_words['post']), $split_text);
  1082. $words['del']['title'] = array_diff(array_keys($cur_words['title']), $split_title);
  1083. }
  1084. else
  1085. {
  1086. $words['add']['post'] = $split_text;
  1087. $words['add']['title'] = $split_title;
  1088. $words['del']['post'] = array();
  1089. $words['del']['title'] = array();
  1090. }
  1091. unset($split_text);
  1092. unset($split_title);
  1093. // Get unique words from the above arrays
  1094. $unique_add_words = array_unique(array_merge($words['add']['post'], $words['add']['title']));
  1095. // We now have unique arrays of all words to be added and removed and
  1096. // individual arrays of added and removed words for text and title. What
  1097. // we need to do now is add the new words (if they don't already exist)
  1098. // and then add (or remove) matches between the words and this post
  1099. if (sizeof($unique_add_words))
  1100. {
  1101. $sql = 'SELECT word_id, word_text
  1102. FROM ' . SEARCH_WORDLIST_TABLE . '
  1103. WHERE ' . $this->db->sql_in_set('word_text', $unique_add_words);
  1104. $result = $this->db->sql_query($sql);
  1105. $word_ids = array();
  1106. while ($row = $this->db->sql_fetchrow($result))
  1107. {
  1108. $word_ids[$row['word_text']] = $row['word_id'];
  1109. }
  1110. $this->db->sql_freeresult($result);
  1111. $new_words = array_diff($unique_add_words, array_keys($word_ids));
  1112. $this->db->sql_transaction('begin');
  1113. if (sizeof($new_words))
  1114. {
  1115. $sql_ary = array();
  1116. foreach ($new_words as $word)
  1117. {
  1118. $sql_ary[] = array('word_text' => (string) $word, 'word_count' => 0);
  1119. }
  1120. $this->db->sql_return_on_error(true);
  1121. $this->db->sql_multi_insert(SEARCH_WORDLIST_TABLE, $sql_ary);
  1122. $this->db->sql_return_on_error(false);
  1123. }
  1124. unset($new_words, $sql_ary);
  1125. }
  1126. else
  1127. {
  1128. $this->db->sql_transaction('begin');
  1129. }
  1130. // now update the search match table, remove links to removed words and add links to new words
  1131. foreach ($words['del'] as $word_in => $word_ary)
  1132. {
  1133. $title_match = ($word_in == 'title') ? 1 : 0;
  1134. if (sizeof($word_ary))
  1135. {
  1136. $sql_in = array();
  1137. foreach ($word_ary as $word)
  1138. {
  1139. $sql_in[] = $cur_words[$word_in][$word];
  1140. }
  1141. $sql = 'DELETE FROM ' . SEARCH_WORDMATCH_TABLE . '
  1142. WHERE ' . $this->db->sql_in_set('word_id', $sql_in) . '
  1143. AND post_id = ' . intval($post_id) . "
  1144. AND title_match = $title_match";
  1145. $this->db->sql_query($sql);
  1146. $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . '
  1147. SET word_count = word_count - 1
  1148. WHERE ' . $this->db->sql_in_set('word_id', $sql_in) . '
  1149. AND word_count > 0';
  1150. $this->db->sql_query($sql);
  1151. unset($sql_in);
  1152. }
  1153. }
  1154. $this->db->sql_return_on_error(true);
  1155. foreach ($words['add'] as $word_in => $word_ary)
  1156. {
  1157. $title_match = ($word_in == 'title') ? 1 : 0;
  1158. if (sizeof($word_ary))
  1159. {
  1160. $sql = 'INSERT INTO ' . SEARCH_WORDMATCH_TABLE . ' (post_id, word_id, title_match)
  1161. SELECT ' . (int) $post_id . ', word_id, ' . (int) $title_match . '
  1162. FROM ' . SEARCH_WORDLIST_TABLE . '
  1163. WHERE ' . $this->db->sql_in_set('word_text', $word_ary);
  1164. $this->db->sql_query($sql);
  1165. $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . '
  1166. SET word_count = word_count + 1
  1167. WHERE ' . $this->db->sql_in_set('word_text', $word_ary);
  1168. $this->db->sql_query($sql);
  1169. }
  1170. }
  1171. $this->db->sql_return_on_error(false);
  1172. $this->db->sql_transaction('commit');
  1173. // destroy cached search results containing any of the words removed or added
  1174. $this->destroy_cache(array_unique(array_merge($words['add']['post'], $words['add']['title'], $words['del']['post'], $words['del']['title'])), array($poster_id));
  1175. unset($unique_add_words);
  1176. unset($words);
  1177. unset($cur_words);
  1178. }
  1179. /**
  1180. * Removes entries from the wordmatch table for the specified post_ids
  1181. */
  1182. public function index_remove($post_ids, $author_ids, $forum_ids)
  1183. {
  1184. if (sizeof($post_ids))
  1185. {
  1186. $sql = 'SELECT w.word_id, w.word_text, m.title_match
  1187. FROM ' . SEARCH_WORDMATCH_TABLE . ' m, ' . SEARCH_WORDLIST_TABLE . ' w
  1188. WHERE ' . $this->db->sql_in_set('m.post_id', $post_ids) . '
  1189. AND w.word_id = m.word_id';
  1190. $result = $this->db->sql_query($sql);
  1191. $message_word_ids = $title_word_ids = $word_texts = array();
  1192. while ($row = $this->db->sql_fetchrow($result))
  1193. {
  1194. if ($row['title_match'])
  1195. {
  1196. $title_word_ids[] = $row['word_id'];
  1197. }
  1198. else
  1199. {
  1200. $message_word_ids[] = $row['word_id'];
  1201. }
  1202. $word_texts[] = $row['word_text'];
  1203. }
  1204. $this->db->sql_freeresult($result);
  1205. if (sizeof($title_word_ids))
  1206. {
  1207. $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . '
  1208. SET word_count = word_count - 1
  1209. WHERE ' . $this->db->sql_in_set('word_id', $title_word_ids) . '
  1210. AND word_count > 0';
  1211. $this->db->sql_query($sql);
  1212. }
  1213. if (sizeof($message_word_ids))
  1214. {
  1215. $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . '
  1216. SET word_count = word_count - 1
  1217. WHERE ' . $this->db->sql_in_set('word_id', $message_word_ids) . '
  1218. AND word_count > 0';
  1219. $this->db->sql_query($sql);
  1220. }
  1221. unset($title_word_ids);
  1222. unset($message_word_ids);
  1223. $sql = 'DELETE FROM ' . SEARCH_WORDMATCH_TABLE . '
  1224. WHERE ' . $this->db->sql_in_set('post_id', $post_ids);
  1225. $this->db->sql_query($sql);
  1226. }
  1227. $this->destroy_cache(array_unique($word_texts), array_unique($author_ids));
  1228. }
  1229. /**
  1230. * Tidy up indexes: Tag 'common words' and remove
  1231. * words no longer referenced in the match table
  1232. */
  1233. public function tidy()
  1234. {
  1235. // Is the fulltext indexer disabled? If yes then we need not
  1236. // carry on ... it's okay ... I know when I'm not wanted boo hoo
  1237. if (!$this->config['fulltext_native_load_upd'])
  1238. {
  1239. set_config('search_last_gc', time(), true);
  1240. return;
  1241. }
  1242. $destroy_cache_words = array();
  1243. // Remove common words
  1244. if ($this->config['num_posts'] >= 100 && $this->config['fulltext_native_common_thres'])
  1245. {
  1246. $common_threshold = ((double) $this->config['fulltext_native_common_thres']) / 100.0;
  1247. // First, get the IDs of common words
  1248. $sql = 'SELECT word_id, word_text
  1249. FROM ' . SEARCH_WORDLIST_TABLE . '
  1250. WHERE word_count > ' . floor($this->config['num_posts'] * $common_threshold) . '
  1251. OR word_common = 1';
  1252. $result = $this->db->sql_query($sql);
  1253. $sql_in = array();
  1254. while ($row = $this->db->sql_fetchrow($result))
  1255. {
  1256. $sql_in[] = $row['word_id'];
  1257. $destroy_cache_words[] = $row['word_text'];
  1258. }
  1259. $this->db->sql_freeresult($result);
  1260. if (sizeof($sql_in))
  1261. {
  1262. // Flag the words
  1263. $sql = 'UPDATE ' . SEARCH_WORDLIST_TABLE . '
  1264. SET word_common = 1
  1265. WHERE ' . $this->db->sql_in_set('word_id', $sql_in);
  1266. $this->db->sql_query($sql);
  1267. // by setting search_last_gc to the new time here we make sure that if a user reloads because the
  1268. // following query takes too long, he won't run into it again
  1269. set_config('search_last_gc', time(), true);
  1270. // Delete the matches
  1271. $sql = 'DELETE FROM ' . SEARCH_WORDMATCH_TABLE . '
  1272. WHERE ' . $this->db->sql_in_set('word_id', $sql_in);
  1273. $this->db->sql_query($sql);
  1274. }
  1275. unset($sql_in);
  1276. }
  1277. if (sizeof($destroy_cache_words))
  1278. {
  1279. // destroy cached search results containing any of the words that are now common or were removed
  1280. $this->destroy_cache(array_unique($destroy_cache_words));
  1281. }
  1282. set_config('search_last_gc', time(), true);
  1283. }
  1284. /**
  1285. * Deletes all words from the index
  1286. */
  1287. public function delete_index($acp_module, $u_action)
  1288. {
  1289. switch ($this->db->sql_layer)
  1290. {
  1291. case 'sqlite':
  1292. case 'sqlite3':
  1293. case 'firebird':
  1294. $this->db->sql_query('DELETE FROM ' . SEARCH_WORDLIST_TABLE);
  1295. $this->db->sql_query('DELETE FROM ' . SEARCH_WORDMATCH_TABLE);
  1296. $this->db->sql_query('DELETE FROM ' . SEARCH_RESULTS_TABLE);
  1297. break;
  1298. default:
  1299. $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_WORDLIST_TABLE);
  1300. $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_WORDMATCH_TABLE);
  1301. $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
  1302. break;
  1303. }
  1304. }
  1305. /**
  1306. * Returns true if both FULLTEXT indexes exist
  1307. */
  1308. public function index_created()
  1309. {
  1310. if (!sizeof($this->stats))
  1311. {
  1312. $this->get_stats();
  1313. }
  1314. return ($this->stats['total_words'] && $this->stats['total_matches']) ? true : false;
  1315. }
  1316. /**
  1317. * Returns an associative array containing information about the indexes
  1318. */
  1319. public function index_stats()
  1320. {
  1321. if (!sizeof($this->stats))
  1322. {
  1323. $this->get_stats();
  1324. }
  1325. return array(
  1326. $this->user->lang['TOTAL_WORDS'] => $this->stats['total_words'],
  1327. $this->user->lang['TOTAL_MATCHES'] => $this->stats['total_matches']);
  1328. }
  1329. protected function get_stats()
  1330. {
  1331. $this->stats['total_words'] = $this->db->get_estimated_row_count(SEARCH_WORDLIST_TABLE);
  1332. $this->stats['total_matches'] = $this->db->get_estimated_row_count(SEARCH_WORDMATCH_TABLE);
  1333. }
  1334. /**
  1335. * Clean up a text to remove non-alphanumeric characters
  1336. *
  1337. * This method receives a UTF-8 string, normalizes and validates it, replaces all
  1338. * non-alphanumeric characters with strings then returns the result.
  1339. *
  1340. * Any number of "allowed chars" can be passed as a UTF-8 string in NFC.
  1341. *
  1342. * @param string $text Text to split, in UTF-8 (not normalized or sanitized)
  1343. * @param string $allowed_chars String of special chars to allow
  1344. * @param string $encoding Text encoding
  1345. * @return string Cleaned up text, only alphanumeric chars are left
  1346. *
  1347. * @todo \normalizer::cleanup being able to be used?
  1348. */
  1349. protected function cleanup($text, $allowed_chars = null, $encoding = 'utf-8')
  1350. {
  1351. static $conv = array(), $conv_loaded = array();
  1352. $words = $allow = array();
  1353. // Convert the text to UTF-8
  1354. $encoding = strtolower($encoding);
  1355. if ($encoding != 'utf-8')
  1356. {
  1357. $text = utf8_recode($text, $encoding);
  1358. }
  1359. $utf_len_mask = array(
  1360. "\xC0" => 2,
  1361. "\xD0" => 2,
  1362. "\xE0" => 3,
  1363. "\xF0" => 4
  1364. );
  1365. /**
  1366. * Replace HTML entities and NCRs
  1367. */
  1368. $text = htmlspecialchars_decode(utf8_decode_ncr($text), ENT_QUOTES);
  1369. /**
  1370. * Load the UTF-8 normalizer
  1371. *
  1372. * If we use it more widely, an instance of that class should be held in a
  1373. * a global variable instead
  1374. */
  1375. \utf_normalizer::nfc($text);
  1376. /**
  1377. * The first thing we do is:
  1378. *
  1379. * - convert ASCII-7 letters to lowercase
  1380. * - remove the ASCII-7 non-alpha characters
  1381. * - remove the bytes that should not appear in a valid UTF-8 string: 0xC0,
  1382. * 0xC1 and 0xF5-0xFF
  1383. *
  1384. * @todo in theory, the third one is already taken care of during normalization and those chars should have been replaced by Unicode replacement chars
  1385. */
  1386. $sb_match = "ISTCPAMELRDOJBNHFGVWUQKYXZ\r\n\t!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\xC0\xC1\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF";
  1387. $sb_replace = 'istcpamelrdojbnhfgvwuqkyxz ';
  1388. /**
  1389. * This is the list of legal ASCII chars, it is automatically extended
  1390. * with ASCII chars from $allowed_chars
  1391. */
  1392. $legal_ascii = ' eaisntroludcpmghbfvq10xy2j9kw354867z';
  1393. /**
  1394. * Prepare an array containing the extra chars to allow
  1395. */
  1396. if (isset($allowed_chars[0]))
  1397. {
  1398. $pos = 0;
  1399. $len = strlen($allowed_chars);
  1400. do
  1401. {
  1402. $c = $allowed_chars[$pos];
  1403. if ($c < "\x80")
  1404. {
  1405. /**
  1406. * ASCII char
  1407. */
  1408. $sb_pos = strpos($sb_match, $c);
  1409. if (is_int($sb_pos))
  1410. {
  1411. /**
  1412. * Remove the char from $sb_match and its corresponding
  1413. * replacement in $sb_replace
  1414. */
  1415. $sb_match = substr($sb_match, 0, $sb_pos) . substr($sb_match, $sb_pos + 1);
  1416. $sb_replace = substr($sb_replace, 0, $sb_pos) . substr($sb_replace, $sb_pos + 1);
  1417. $legal_ascii .= $c;
  1418. }
  1419. ++$pos;
  1420. }
  1421. else
  1422. {
  1423. /**
  1424. * UTF-8 char
  1425. */
  1426. $utf_len = $utf_len_mask[$c & "\xF0"];
  1427. $allow[substr($allowed_chars, $pos, $utf_len)] = 1;
  1428. $pos += $utf_len;
  1429. }
  1430. }
  1431. while ($pos < $len);
  1432. }
  1433. $text = strtr($text, $sb_match, $sb_replace);
  1434. $ret = '';
  1435. $pos = 0;
  1436. $len = strlen($text);
  1437. do
  1438. {
  1439. /**
  1440. * Do all consecutive ASCII chars at once
  1441. */
  1442. if ($spn = strspn($text, $legal_ascii, $pos))
  1443. {
  1444. $ret .= substr($text, $pos, $spn);
  1445. $pos += $spn;
  1446. }
  1447. if ($pos >= $len)
  1448. {
  1449. return $ret;
  1450. }
  1451. /**
  1452. * Capture the UTF char
  1453. */
  1454. $utf_len = $utf_len_mask[$text[$pos] & "\xF0"];
  1455. $utf_char = substr($text, $pos, $utf_len);
  1456. $pos += $utf_len;
  1457. if (($utf_char >= UTF8_HANGUL_FIRST && $utf_char <= UTF8_HANGUL_LAST)
  1458. || ($utf_char >= UTF8_CJK_FIRST && $utf_char <= UTF8_CJK_LAST)
  1459. || ($utf_char >= UTF8_CJK_B_FIRST && $utf_char <= UTF8_CJK_B_LAST))
  1460. {
  1461. /**
  1462. * All characters within these ranges are valid
  1463. *
  1464. * We separate them with a space in order to index each character
  1465. * individually
  1466. */
  1467. $ret .= ' ' . $utf_char . ' ';
  1468. continue;
  1469. }
  1470. if (isset($allow[$utf_char]))
  1471. {
  1472. /**
  1473. * The char is explicitly allowed
  1474. */
  1475. $ret .= $utf_char;
  1476. continue;
  1477. }
  1478. if (isset($conv[$utf_char]))
  1479. {
  1480. /**
  1481. * The char is mapped to something, maybe to itself actually
  1482. */
  1483. $ret .= $conv[$utf_char];
  1484. continue;
  1485. }
  1486. /**
  1487. * The char isn't mapped, but did we load its conversion table?
  1488. *
  1489. * The search indexer table is split into blocks. The block number of
  1490. * each char is equal to its codepoint right-shifted for 11 bits. It
  1491. * means that out of the 11, 16 or 21 meaningful bits of a 2-, 3- or
  1492. * 4- byte sequence we only keep the leftmost 0, 5 or 10 bits. Thus,
  1493. * all UTF chars encoded in 2 bytes are in the same first block.
  1494. */
  1495. if (isset($utf_char[2]))
  1496. {
  1497. if (isset($utf_char[3]))
  1498. {
  1499. /**
  1500. * 1111 0nnn 10nn nnnn 10nx xxxx 10xx xxxx
  1501. * 0000 0111 0011 1111 0010 0000
  1502. */
  1503. $idx = ((ord($utf_char[0]) & 0x07) << 7) | ((ord($utf_char[1]) & 0x3F) << 1) | ((ord($utf_char[2]) & 0x20) >> 5);
  1504. }
  1505. else
  1506. {
  1507. /**
  1508. * 1110 nnnn 10nx xxxx 10xx xxxx
  1509. * 0000 0111 0010 0000
  1510. */
  1511. $idx = ((ord($utf_char[0]) & 0x07) << 1) | ((ord($utf_char[1]) & 0x20) >> 5);
  1512. }
  1513. }
  1514. else
  1515. {
  1516. /**
  1517. * 110x xxxx 10xx xxxx
  1518. * 0000 0000 0000 0000
  1519. */
  1520. $idx = 0;
  1521. }
  1522. /**
  1523. * Check if the required conv table has been loaded already
  1524. */
  1525. if (!isset($conv_loaded[$idx]))
  1526. {
  1527. $conv_loaded[$idx] = 1;
  1528. $file = $this->phpbb_root_path . 'includes/utf/data/search_indexer_' . $idx . '.' . $this->php_ext;
  1529. if (file_exists($file))
  1530. {
  1531. $conv += include($file);
  1532. }
  1533. }
  1534. if (isset($conv[$utf_char]))
  1535. {
  1536. $ret .= $conv[$utf_char];
  1537. }
  1538. else
  1539. {
  1540. /**
  1541. * We add an entry to the conversion table so that we
  1542. * don't have to convert to codepoint and perform the checks
  1543. * that are above this block
  1544. */
  1545. $conv[$utf_char] = ' ';
  1546. $ret .= ' ';
  1547. }
  1548. }
  1549. while (1);
  1550. return $ret;
  1551. }
  1552. /**
  1553. * Returns a list of options for the ACP to display
  1554. */
  1555. public function acp()
  1556. {
  1557. /**
  1558. * if we need any options, copied from fulltext_native for now, will have to be adjusted or removed
  1559. */
  1560. $tpl = '
  1561. <dl>
  1562. <dt><label for="fulltext_native_load_upd">' . $this->user->lang['YES_SEARCH_UPDATE'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['YES_SEARCH_UPDATE_EXPLAIN'] . '</span></dt>
  1563. <dd><label><input type="radio" id="fulltext_native_load_upd" name="config[fulltext_native_load_upd]" value="1"' . (($this->config['fulltext_native_load_upd']) ? ' checked="checked"' : '') . ' class="radio" /> ' . $this->user->lang['YES'] . '</label><label><input type="radio" name="config[f…

Large files files are truncated, but you can click here to view the full file