PageRenderTime 69ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/forum/includes/search/fulltext_native.php

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