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

/phpBB3/includes/search/fulltext_native.php

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