PageRenderTime 30ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/forum/includes/search/fulltext_native.php

https://bitbucket.org/itoxable/chiron-gaming
PHP | 1758 lines | 1305 code | 199 blank | 254 comment | 174 complexity | 35b59757a92310934ebe63b75fd7147e MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0

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

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

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