PageRenderTime 81ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/search/fulltext_native.php

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