PageRenderTime 88ms CodeModel.GetById 43ms RepoModel.GetById 1ms app.codeStats 0ms

/phpBB/includes/search/fulltext_native.php

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