PageRenderTime 55ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/phpBB/phpbb/search/fulltext_postgres.php

https://github.com/Jipem/phpbb
PHP | 957 lines | 606 code | 126 blank | 225 comment | 100 complexity | c596bbd6bcdb35afe70de7d9785220c6 MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /**
  3. *
  4. * This file is part of the phpBB Forum Software package.
  5. *
  6. * @copyright (c) phpBB Limited <https://www.phpbb.com>
  7. * @license GNU General Public License, version 2 (GPL-2.0)
  8. *
  9. * For full copyright and license information, please see
  10. * the docs/CREDITS.txt file.
  11. *
  12. */
  13. namespace phpbb\search;
  14. /**
  15. * Fulltext search for PostgreSQL
  16. */
  17. class fulltext_postgres extends \phpbb\search\base
  18. {
  19. /**
  20. * Associative array holding index stats
  21. * @var array
  22. */
  23. protected $stats = array();
  24. /**
  25. * Holds the words entered by user, obtained by splitting the entered query on whitespace
  26. * @var array
  27. */
  28. protected $split_words = array();
  29. /**
  30. * True if PostgreSQL version supports tsearch
  31. * @var boolean
  32. */
  33. protected $tsearch_usable = false;
  34. /**
  35. * Stores the PostgreSQL version
  36. * @var string
  37. */
  38. protected $version;
  39. /**
  40. * Stores the tsearch query
  41. * @var string
  42. */
  43. protected $tsearch_query;
  44. /**
  45. * True if phrase search is supported.
  46. * PostgreSQL fulltext currently doesn't support it
  47. * @var boolean
  48. */
  49. protected $phrase_search = false;
  50. /**
  51. * Config object
  52. * @var \phpbb\config\config
  53. */
  54. protected $config;
  55. /**
  56. * Database connection
  57. * @var \phpbb\db\driver\driver_interface
  58. */
  59. protected $db;
  60. /**
  61. * User object
  62. * @var \phpbb\user
  63. */
  64. protected $user;
  65. /**
  66. * Contains tidied search query.
  67. * Operators are prefixed in search query and common words excluded
  68. * @var string
  69. */
  70. protected $search_query;
  71. /**
  72. * Contains common words.
  73. * Common words are words with length less/more than min/max length
  74. * @var array
  75. */
  76. protected $common_words = array();
  77. /**
  78. * Associative array stores the min and max word length to be searched
  79. * @var array
  80. */
  81. protected $word_length = array();
  82. /**
  83. * Constructor
  84. * Creates a new \phpbb\search\fulltext_postgres, which is used as a search backend
  85. *
  86. * @param string|bool $error Any error that occurs is passed on through this reference variable otherwise false
  87. */
  88. public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user)
  89. {
  90. $this->config = $config;
  91. $this->db = $db;
  92. $this->user = $user;
  93. $this->word_length = array('min' => $this->config['fulltext_postgres_min_word_len'], 'max' => $this->config['fulltext_postgres_max_word_len']);
  94. if ($this->db->sql_layer == 'postgres')
  95. {
  96. $pgsql_version = explode(',', substr($this->db->sql_server_info(), 10));
  97. $this->version = trim($pgsql_version[0]);
  98. if (version_compare($this->version, '8.3', '>='))
  99. {
  100. $this->tsearch_usable = true;
  101. }
  102. }
  103. /**
  104. * Load the UTF tools
  105. */
  106. if (!function_exists('utf8_strlen'))
  107. {
  108. include($phpbb_root_path . 'includes/utf/utf_tools.' . $phpEx);
  109. }
  110. $error = false;
  111. }
  112. /**
  113. * Returns the name of this search backend to be displayed to administrators
  114. *
  115. * @return string Name
  116. */
  117. public function get_name()
  118. {
  119. return 'PostgreSQL Fulltext';
  120. }
  121. /**
  122. * Returns the search_query
  123. *
  124. * @return string search query
  125. */
  126. public function get_search_query()
  127. {
  128. return $this->search_query;
  129. }
  130. /**
  131. * Returns the common_words array
  132. *
  133. * @return array common words that are ignored by search backend
  134. */
  135. public function get_common_words()
  136. {
  137. return $this->common_words;
  138. }
  139. /**
  140. * Returns the word_length array
  141. *
  142. * @return array min and max word length for searching
  143. */
  144. public function get_word_length()
  145. {
  146. return $this->word_length;
  147. }
  148. /**
  149. * Returns if phrase search is supported or not
  150. *
  151. * @return bool
  152. */
  153. public function supports_phrase_search()
  154. {
  155. return $this->phrase_search;
  156. }
  157. /**
  158. * Checks for correct PostgreSQL version and stores min/max word length in the config
  159. *
  160. * @return string|bool Language key of the error/incompatiblity occurred
  161. */
  162. public function init()
  163. {
  164. if ($this->db->sql_layer != 'postgres')
  165. {
  166. return $this->user->lang['FULLTEXT_POSTGRES_INCOMPATIBLE_DATABASE'];
  167. }
  168. if (!$this->tsearch_usable)
  169. {
  170. return $this->user->lang['FULLTEXT_POSTGRES_TS_NOT_USABLE'];
  171. }
  172. return false;
  173. }
  174. /**
  175. * Splits keywords entered by a user into an array of words stored in $this->split_words
  176. * Stores the tidied search query in $this->search_query
  177. *
  178. * @param string &$keywords Contains the keyword as entered by the user
  179. * @param string $terms is either 'all' or 'any'
  180. * @return bool false if no valid keywords were found and otherwise true
  181. */
  182. public function split_keywords(&$keywords, $terms)
  183. {
  184. if ($terms == 'all')
  185. {
  186. $match = array('#\sand\s#iu', '#\sor\s#iu', '#\snot\s#iu', '#(^|\s)\+#', '#(^|\s)-#', '#(^|\s)\|#');
  187. $replace = array(' +', ' |', ' -', ' +', ' -', ' |');
  188. $keywords = preg_replace($match, $replace, $keywords);
  189. }
  190. // Filter out as above
  191. $split_keywords = preg_replace("#[\"\n\r\t]+#", ' ', trim(htmlspecialchars_decode($keywords)));
  192. // Split words
  193. $split_keywords = preg_replace('#([^\p{L}\p{N}\'*"()])#u', '$1$1', str_replace('\'\'', '\' \'', trim($split_keywords)));
  194. $matches = array();
  195. preg_match_all('#(?:[^\p{L}\p{N}*"()]|^)([+\-|]?(?:[\p{L}\p{N}*"()]+\'?)*[\p{L}\p{N}*"()])(?:[^\p{L}\p{N}*"()]|$)#u', $split_keywords, $matches);
  196. $this->split_words = $matches[1];
  197. foreach ($this->split_words as $i => $word)
  198. {
  199. $clean_word = preg_replace('#^[+\-|"]#', '', $word);
  200. // check word length
  201. $clean_len = utf8_strlen(str_replace('*', '', $clean_word));
  202. if (($clean_len < $this->config['fulltext_postgres_min_word_len']) || ($clean_len > $this->config['fulltext_postgres_max_word_len']))
  203. {
  204. $this->common_words[] = $word;
  205. unset($this->split_words[$i]);
  206. }
  207. }
  208. if ($terms == 'any')
  209. {
  210. $this->search_query = '';
  211. $this->tsearch_query = '';
  212. foreach ($this->split_words as $word)
  213. {
  214. if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0) || (strpos($word, '|') === 0))
  215. {
  216. $word = substr($word, 1);
  217. }
  218. $this->search_query .= $word . ' ';
  219. $this->tsearch_query .= '|' . $word . ' ';
  220. }
  221. }
  222. else
  223. {
  224. $this->search_query = '';
  225. $this->tsearch_query = '';
  226. foreach ($this->split_words as $word)
  227. {
  228. if (strpos($word, '+') === 0)
  229. {
  230. $this->search_query .= $word . ' ';
  231. $this->tsearch_query .= '&' . substr($word, 1) . ' ';
  232. }
  233. else if (strpos($word, '-') === 0)
  234. {
  235. $this->search_query .= $word . ' ';
  236. $this->tsearch_query .= '&!' . substr($word, 1) . ' ';
  237. }
  238. else if (strpos($word, '|') === 0)
  239. {
  240. $this->search_query .= $word . ' ';
  241. $this->tsearch_query .= '|' . substr($word, 1) . ' ';
  242. }
  243. else
  244. {
  245. $this->search_query .= '+' . $word . ' ';
  246. $this->tsearch_query .= '&' . $word . ' ';
  247. }
  248. }
  249. }
  250. $this->tsearch_query = substr($this->tsearch_query, 1);
  251. $this->search_query = utf8_htmlspecialchars($this->search_query);
  252. if ($this->search_query)
  253. {
  254. $this->split_words = array_values($this->split_words);
  255. sort($this->split_words);
  256. return true;
  257. }
  258. return false;
  259. }
  260. /**
  261. * Turns text into an array of words
  262. * @param string $text contains post text/subject
  263. */
  264. public function split_message($text)
  265. {
  266. // Split words
  267. $text = preg_replace('#([^\p{L}\p{N}\'*])#u', '$1$1', str_replace('\'\'', '\' \'', trim($text)));
  268. $matches = array();
  269. preg_match_all('#(?:[^\p{L}\p{N}*]|^)([+\-|]?(?:[\p{L}\p{N}*]+\'?)*[\p{L}\p{N}*])(?:[^\p{L}\p{N}*]|$)#u', $text, $matches);
  270. $text = $matches[1];
  271. // remove too short or too long words
  272. $text = array_values($text);
  273. for ($i = 0, $n = sizeof($text); $i < $n; $i++)
  274. {
  275. $text[$i] = trim($text[$i]);
  276. if (utf8_strlen($text[$i]) < $this->config['fulltext_postgres_min_word_len'] || utf8_strlen($text[$i]) > $this->config['fulltext_postgres_max_word_len'])
  277. {
  278. unset($text[$i]);
  279. }
  280. }
  281. return array_values($text);
  282. }
  283. /**
  284. * Performs a search on keywords depending on display specific params. You have to run split_keywords() first
  285. *
  286. * @param string $type contains either posts or topics depending on what should be searched for
  287. * @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)
  288. * @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)
  289. * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query
  290. * @param string $sort_key is the key of $sort_by_sql for the selected sorting
  291. * @param string $sort_dir is either a or d representing ASC and DESC
  292. * @param string $sort_days specifies the maximum amount of days a post may be old
  293. * @param array $ex_fid_ary specifies an array of forum ids which should not be searched
  294. * @param string $post_visibility specifies which types of posts the user can view in which forums
  295. * @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
  296. * @param array $author_ary an array of author ids if the author should be ignored during the search the array is empty
  297. * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match
  298. * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
  299. * @param int $start indicates the first index of the page
  300. * @param int $per_page number of ids each page is supposed to contain
  301. * @return boolean|int total number of results
  302. */
  303. public function keyword_search($type, $fields, $terms, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page)
  304. {
  305. // No keywords? No posts
  306. if (!$this->search_query)
  307. {
  308. return false;
  309. }
  310. // When search query contains queries like -foo
  311. if (strpos($this->search_query, '+') === false)
  312. {
  313. return false;
  314. }
  315. // generate a search_key from all the options to identify the results
  316. $search_key = md5(implode('#', array(
  317. implode(', ', $this->split_words),
  318. $type,
  319. $fields,
  320. $terms,
  321. $sort_days,
  322. $sort_key,
  323. $topic_id,
  324. implode(',', $ex_fid_ary),
  325. $post_visibility,
  326. implode(',', $author_ary)
  327. )));
  328. if ($start < 0)
  329. {
  330. $start = 0;
  331. }
  332. // try reading the results from cache
  333. $result_count = 0;
  334. if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
  335. {
  336. return $result_count;
  337. }
  338. $id_ary = array();
  339. $join_topic = ($type == 'posts') ? false : true;
  340. // Build sql strings for sorting
  341. $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
  342. $sql_sort_table = $sql_sort_join = '';
  343. switch ($sql_sort[0])
  344. {
  345. case 'u':
  346. $sql_sort_table = USERS_TABLE . ' u, ';
  347. $sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
  348. break;
  349. case 't':
  350. $join_topic = true;
  351. break;
  352. case 'f':
  353. $sql_sort_table = FORUMS_TABLE . ' f, ';
  354. $sql_sort_join = ' AND f.forum_id = p.forum_id ';
  355. break;
  356. }
  357. // Build some display specific sql strings
  358. switch ($fields)
  359. {
  360. case 'titleonly':
  361. $sql_match = 'p.post_subject';
  362. $sql_match_where = ' AND p.post_id = t.topic_first_post_id';
  363. $join_topic = true;
  364. break;
  365. case 'msgonly':
  366. $sql_match = 'p.post_text';
  367. $sql_match_where = '';
  368. break;
  369. case 'firstpost':
  370. $sql_match = 'p.post_subject, p.post_text';
  371. $sql_match_where = ' AND p.post_id = t.topic_first_post_id';
  372. $join_topic = true;
  373. break;
  374. default:
  375. $sql_match = 'p.post_subject, p.post_text';
  376. $sql_match_where = '';
  377. break;
  378. }
  379. $sql_select = ($type == 'posts') ? 'p.post_id' : 'DISTINCT t.topic_id';
  380. $sql_from = ($join_topic) ? TOPICS_TABLE . ' t, ' : '';
  381. $field = ($type == 'posts') ? 'post_id' : 'topic_id';
  382. $sql_author = (sizeof($author_ary) == 1) ? ' = ' . $author_ary[0] : 'IN (' . implode(', ', $author_ary) . ')';
  383. if (sizeof($author_ary) && $author_name)
  384. {
  385. // first one matches post of registered users, second one guests and deleted users
  386. $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
  387. }
  388. else if (sizeof($author_ary))
  389. {
  390. $sql_author = ' AND ' . $this->db->sql_in_set('p.poster_id', $author_ary);
  391. }
  392. else
  393. {
  394. $sql_author = '';
  395. }
  396. $sql_where_options = $sql_sort_join;
  397. $sql_where_options .= ($topic_id) ? ' AND p.topic_id = ' . $topic_id : '';
  398. $sql_where_options .= ($join_topic) ? ' AND t.topic_id = p.topic_id' : '';
  399. $sql_where_options .= (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
  400. $sql_where_options .= ' AND ' . $post_visibility;
  401. $sql_where_options .= $sql_author;
  402. $sql_where_options .= ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
  403. $sql_where_options .= $sql_match_where;
  404. $tmp_sql_match = array();
  405. $sql_match = str_replace(',', " || ' ' ||", $sql_match);
  406. $tmp_sql_match = "to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', " . $sql_match . ") @@ to_tsquery ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', '" . $this->db->sql_escape($this->tsearch_query) . "')";
  407. $this->db->sql_transaction('begin');
  408. $sql_from = "FROM $sql_from$sql_sort_table" . POSTS_TABLE . " p";
  409. $sql_where = "WHERE (" . $tmp_sql_match . ")
  410. $sql_where_options";
  411. $sql = "SELECT $sql_select
  412. $sql_from
  413. $sql_where
  414. ORDER BY $sql_sort";
  415. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  416. while ($row = $this->db->sql_fetchrow($result))
  417. {
  418. $id_ary[] = $row[$field];
  419. }
  420. $this->db->sql_freeresult($result);
  421. $id_ary = array_unique($id_ary);
  422. // if the total result count is not cached yet, retrieve it from the db
  423. if (!$result_count)
  424. {
  425. $sql_count = "SELECT COUNT(*) as result_count
  426. $sql_from
  427. $sql_where";
  428. $result = $this->db->sql_query($sql_count);
  429. $result_count = (int) $this->db->sql_fetchfield('result_count');
  430. $this->db->sql_freeresult($result);
  431. if (!$result_count)
  432. {
  433. return false;
  434. }
  435. }
  436. $this->db->sql_transaction('commit');
  437. if ($start >= $result_count)
  438. {
  439. $start = floor(($result_count - 1) / $per_page) * $per_page;
  440. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  441. while ($row = $this->db->sql_fetchrow($result))
  442. {
  443. $id_ary[] = $row[$field];
  444. }
  445. $this->db->sql_freeresult($result);
  446. $id_ary = array_unique($id_ary);
  447. }
  448. // store the ids, from start on then delete anything that isn't on the current page because we only need ids for one page
  449. $this->save_ids($search_key, implode(' ', $this->split_words), $author_ary, $result_count, $id_ary, $start, $sort_dir);
  450. $id_ary = array_slice($id_ary, 0, (int) $per_page);
  451. return $result_count;
  452. }
  453. /**
  454. * Performs a search on an author's posts without caring about message contents. Depends on display specific params
  455. *
  456. * @param string $type contains either posts or topics depending on what should be searched for
  457. * @param boolean $firstpost_only if true, only topic starting posts will be considered
  458. * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query
  459. * @param string $sort_key is the key of $sort_by_sql for the selected sorting
  460. * @param string $sort_dir is either a or d representing ASC and DESC
  461. * @param string $sort_days specifies the maximum amount of days a post may be old
  462. * @param array $ex_fid_ary specifies an array of forum ids which should not be searched
  463. * @param string $post_visibility specifies which types of posts the user can view in which forums
  464. * @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
  465. * @param array $author_ary an array of author ids
  466. * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match
  467. * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
  468. * @param int $start indicates the first index of the page
  469. * @param int $per_page number of ids each page is supposed to contain
  470. * @return boolean|int total number of results
  471. */
  472. public function author_search($type, $firstpost_only, $sort_by_sql, $sort_key, $sort_dir, $sort_days, $ex_fid_ary, $post_visibility, $topic_id, $author_ary, $author_name, &$id_ary, &$start, $per_page)
  473. {
  474. // No author? No posts
  475. if (!sizeof($author_ary))
  476. {
  477. return 0;
  478. }
  479. // generate a search_key from all the options to identify the results
  480. $search_key = md5(implode('#', array(
  481. '',
  482. $type,
  483. ($firstpost_only) ? 'firstpost' : '',
  484. '',
  485. '',
  486. $sort_days,
  487. $sort_key,
  488. $topic_id,
  489. implode(',', $ex_fid_ary),
  490. $post_visibility,
  491. implode(',', $author_ary),
  492. $author_name,
  493. )));
  494. if ($start < 0)
  495. {
  496. $start = 0;
  497. }
  498. // try reading the results from cache
  499. $result_count = 0;
  500. if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
  501. {
  502. return $result_count;
  503. }
  504. $id_ary = array();
  505. // Create some display specific sql strings
  506. if ($author_name)
  507. {
  508. // first one matches post of registered users, second one guests and deleted users
  509. $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
  510. }
  511. else
  512. {
  513. $sql_author = $this->db->sql_in_set('p.poster_id', $author_ary);
  514. }
  515. $sql_fora = (sizeof($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
  516. $sql_topic_id = ($topic_id) ? ' AND p.topic_id = ' . (int) $topic_id : '';
  517. $sql_time = ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
  518. $sql_firstpost = ($firstpost_only) ? ' AND p.post_id = t.topic_first_post_id' : '';
  519. // Build sql strings for sorting
  520. $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
  521. $sql_sort_table = $sql_sort_join = '';
  522. switch ($sql_sort[0])
  523. {
  524. case 'u':
  525. $sql_sort_table = USERS_TABLE . ' u, ';
  526. $sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
  527. break;
  528. case 't':
  529. $sql_sort_table = ($type == 'posts' && !$firstpost_only) ? TOPICS_TABLE . ' t, ' : '';
  530. $sql_sort_join = ($type == 'posts' && !$firstpost_only) ? ' AND t.topic_id = p.topic_id ' : '';
  531. break;
  532. case 'f':
  533. $sql_sort_table = FORUMS_TABLE . ' f, ';
  534. $sql_sort_join = ' AND f.forum_id = p.forum_id ';
  535. break;
  536. }
  537. $m_approve_fid_sql = ' AND ' . $post_visibility;
  538. // Build the query for really selecting the post_ids
  539. if ($type == 'posts')
  540. {
  541. $sql = "SELECT p.post_id
  542. FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . "
  543. WHERE $sql_author
  544. $sql_topic_id
  545. $sql_firstpost
  546. $m_approve_fid_sql
  547. $sql_fora
  548. $sql_sort_join
  549. $sql_time
  550. ORDER BY $sql_sort";
  551. $field = 'post_id';
  552. }
  553. else
  554. {
  555. $sql = "SELECT t.topic_id
  556. FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  557. WHERE $sql_author
  558. $sql_topic_id
  559. $sql_firstpost
  560. $m_approve_fid_sql
  561. $sql_fora
  562. AND t.topic_id = p.topic_id
  563. $sql_sort_join
  564. $sql_time
  565. GROUP BY t.topic_id, $sort_by_sql[$sort_key]
  566. ORDER BY $sql_sort";
  567. $field = 'topic_id';
  568. }
  569. $this->db->sql_transaction('begin');
  570. // Only read one block of posts from the db and then cache it
  571. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  572. while ($row = $this->db->sql_fetchrow($result))
  573. {
  574. $id_ary[] = $row[$field];
  575. }
  576. $this->db->sql_freeresult($result);
  577. // retrieve the total result count if needed
  578. if (!$result_count)
  579. {
  580. if ($type == 'posts')
  581. {
  582. $sql_count = "SELECT COUNT(*) as result_count
  583. FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . "
  584. WHERE $sql_author
  585. $sql_topic_id
  586. $sql_firstpost
  587. $m_approve_fid_sql
  588. $sql_fora
  589. $sql_sort_join
  590. $sql_time";
  591. }
  592. else
  593. {
  594. $sql_count = "SELECT COUNT(*) as result_count
  595. FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  596. WHERE $sql_author
  597. $sql_topic_id
  598. $sql_firstpost
  599. $m_approve_fid_sql
  600. $sql_fora
  601. AND t.topic_id = p.topic_id
  602. $sql_sort_join
  603. $sql_time
  604. GROUP BY t.topic_id, $sort_by_sql[$sort_key]";
  605. }
  606. $result = $this->db->sql_query($sql_count);
  607. $result_count = (int) $this->db->sql_fetchfield('result_count');
  608. if (!$result_count)
  609. {
  610. return false;
  611. }
  612. }
  613. $this->db->sql_transaction('commit');
  614. if ($start >= $result_count)
  615. {
  616. $start = floor(($result_count - 1) / $per_page) * $per_page;
  617. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  618. while ($row = $this->db->sql_fetchrow($result))
  619. {
  620. $id_ary[] = (int) $row[$field];
  621. }
  622. $this->db->sql_freeresult($result);
  623. $id_ary = array_unique($id_ary);
  624. }
  625. if (sizeof($id_ary))
  626. {
  627. $this->save_ids($search_key, '', $author_ary, $result_count, $id_ary, $start, $sort_dir);
  628. $id_ary = array_slice($id_ary, 0, $per_page);
  629. return $result_count;
  630. }
  631. return false;
  632. }
  633. /**
  634. * Destroys cached search results, that contained one of the new words in a post so the results won't be outdated
  635. *
  636. * @param string $mode contains the post mode: edit, post, reply, quote ...
  637. * @param int $post_id contains the post id of the post to index
  638. * @param string $message contains the post text of the post
  639. * @param string $subject contains the subject of the post to index
  640. * @param int $poster_id contains the user id of the poster
  641. * @param int $forum_id contains the forum id of parent forum of the post
  642. */
  643. public function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id)
  644. {
  645. // Split old and new post/subject to obtain array of words
  646. $split_text = $this->split_message($message);
  647. $split_title = ($subject) ? $this->split_message($subject) : array();
  648. $words = array_unique(array_merge($split_text, $split_title));
  649. unset($split_text);
  650. unset($split_title);
  651. // destroy cached search results containing any of the words removed or added
  652. $this->destroy_cache($words, array($poster_id));
  653. unset($words);
  654. }
  655. /**
  656. * Destroy cached results, that might be outdated after deleting a post
  657. */
  658. public function index_remove($post_ids, $author_ids, $forum_ids)
  659. {
  660. $this->destroy_cache(array(), $author_ids);
  661. }
  662. /**
  663. * Destroy old cache entries
  664. */
  665. public function tidy()
  666. {
  667. // destroy too old cached search results
  668. $this->destroy_cache(array());
  669. set_config('search_last_gc', time(), true);
  670. }
  671. /**
  672. * Create fulltext index
  673. *
  674. * @return string|bool error string is returned incase of errors otherwise false
  675. */
  676. public function create_index($acp_module, $u_action)
  677. {
  678. // Make sure we can actually use PostgreSQL with fulltext indexes
  679. if ($error = $this->init())
  680. {
  681. return $error;
  682. }
  683. if (empty($this->stats))
  684. {
  685. $this->get_stats();
  686. }
  687. if (!isset($this->stats['post_subject']))
  688. {
  689. $this->db->sql_query("CREATE INDEX " . POSTS_TABLE . "_" . $this->config['fulltext_postgres_ts_name'] . "_post_subject ON " . POSTS_TABLE . " USING gin (to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', post_subject))");
  690. }
  691. if (!isset($this->stats['post_content']))
  692. {
  693. $this->db->sql_query("CREATE INDEX " . POSTS_TABLE . "_" . $this->config['fulltext_postgres_ts_name'] . "_post_content ON " . POSTS_TABLE . " USING gin (to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', post_text || ' ' || post_subject))");
  694. }
  695. $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
  696. return false;
  697. }
  698. /**
  699. * Drop fulltext index
  700. *
  701. * @return string|bool error string is returned incase of errors otherwise false
  702. */
  703. public function delete_index($acp_module, $u_action)
  704. {
  705. // Make sure we can actually use PostgreSQL with fulltext indexes
  706. if ($error = $this->init())
  707. {
  708. return $error;
  709. }
  710. if (empty($this->stats))
  711. {
  712. $this->get_stats();
  713. }
  714. if (isset($this->stats['post_subject']))
  715. {
  716. $this->db->sql_query('DROP INDEX ' . $this->stats['post_subject']['relname']);
  717. }
  718. if (isset($this->stats['post_content']))
  719. {
  720. $this->db->sql_query('DROP INDEX ' . $this->stats['post_content']['relname']);
  721. }
  722. $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
  723. return false;
  724. }
  725. /**
  726. * Returns true if both FULLTEXT indexes exist
  727. */
  728. public function index_created()
  729. {
  730. if (empty($this->stats))
  731. {
  732. $this->get_stats();
  733. }
  734. return (isset($this->stats['post_subject']) && isset($this->stats['post_content'])) ? true : false;
  735. }
  736. /**
  737. * Returns an associative array containing information about the indexes
  738. */
  739. public function index_stats()
  740. {
  741. if (empty($this->stats))
  742. {
  743. $this->get_stats();
  744. }
  745. return array(
  746. $this->user->lang['FULLTEXT_POSTGRES_TOTAL_POSTS'] => ($this->index_created()) ? $this->stats['total_posts'] : 0,
  747. );
  748. }
  749. /**
  750. * Computes the stats and store them in the $this->stats associative array
  751. */
  752. protected function get_stats()
  753. {
  754. if ($this->db->sql_layer != 'postgres')
  755. {
  756. $this->stats = array();
  757. return;
  758. }
  759. $sql = "SELECT c2.relname, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS indexdef
  760. FROM pg_catalog.pg_class c1, pg_catalog.pg_index i, pg_catalog.pg_class c2
  761. WHERE c1.relname = '" . POSTS_TABLE . "'
  762. AND pg_catalog.pg_table_is_visible(c1.oid)
  763. AND c1.oid = i.indrelid
  764. AND i.indexrelid = c2.oid";
  765. $result = $this->db->sql_query($sql);
  766. while ($row = $this->db->sql_fetchrow($result))
  767. {
  768. // deal with older PostgreSQL versions which didn't use Index_type
  769. if (strpos($row['indexdef'], 'to_tsvector') !== false)
  770. {
  771. if ($row['relname'] == POSTS_TABLE . '_' . $this->config['fulltext_postgres_ts_name'] . '_post_subject' || $row['relname'] == POSTS_TABLE . '_post_subject')
  772. {
  773. $this->stats['post_subject'] = $row;
  774. }
  775. else if ($row['relname'] == POSTS_TABLE . '_' . $this->config['fulltext_postgres_ts_name'] . '_post_content' || $row['relname'] == POSTS_TABLE . '_post_content')
  776. {
  777. $this->stats['post_content'] = $row;
  778. }
  779. }
  780. }
  781. $this->db->sql_freeresult($result);
  782. $this->stats['total_posts'] = $this->config['num_posts'];
  783. }
  784. /**
  785. * Display various options that can be configured for the backend from the acp
  786. *
  787. * @return associative array containing template and config variables
  788. */
  789. public function acp()
  790. {
  791. $tpl = '
  792. <dl>
  793. <dt><label>' . $this->user->lang['FULLTEXT_POSTGRES_VERSION_CHECK'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_VERSION_CHECK_EXPLAIN'] . '</span></dt>
  794. <dd>' . (($this->tsearch_usable) ? $this->user->lang['YES'] : $this->user->lang['NO']) . ' (PostgreSQL ' . $this->version . ')</dd>
  795. </dl>
  796. <dl>
  797. <dt><label>' . $this->user->lang['FULLTEXT_POSTGRES_TS_NAME'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_TS_NAME_EXPLAIN'] . '</span></dt>
  798. <dd><select name="config[fulltext_postgres_ts_name]">';
  799. if ($this->db->sql_layer == 'postgres' && $this->tsearch_usable)
  800. {
  801. $sql = 'SELECT cfgname AS ts_name
  802. FROM pg_ts_config';
  803. $result = $this->db->sql_query($sql);
  804. while ($row = $this->db->sql_fetchrow($result))
  805. {
  806. $tpl .= '<option value="' . $row['ts_name'] . '"' . ($row['ts_name'] === $this->config['fulltext_postgres_ts_name'] ? ' selected="selected"' : '') . '>' . $row['ts_name'] . '</option>';
  807. }
  808. $this->db->sql_freeresult($result);
  809. }
  810. else
  811. {
  812. $tpl .= '<option value="' . $this->config['fulltext_postgres_ts_name'] . '" selected="selected">' . $this->config['fulltext_postgres_ts_name'] . '</option>';
  813. }
  814. $tpl .= '</select></dd>
  815. </dl>
  816. <dl>
  817. <dt><label for="fulltext_postgres_min_word_len">' . $this->user->lang['FULLTEXT_POSTGRES_MIN_WORD_LEN'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_MIN_WORD_LEN_EXPLAIN'] . '</span></dt>
  818. <dd><input id="fulltext_postgres_min_word_len" type="number" size="3" maxlength="3" min="0" max="255" name="config[fulltext_postgres_min_word_len]" value="' . (int) $this->config['fulltext_postgres_min_word_len'] . '" /></dd>
  819. </dl>
  820. <dl>
  821. <dt><label for="fulltext_postgres_max_word_len">' . $this->user->lang['FULLTEXT_POSTGRES_MAX_WORD_LEN'] . $this->user->lang['COLON'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_MAX_WORD_LEN_EXPLAIN'] . '</span></dt>
  822. <dd><input id="fulltext_postgres_max_word_len" type="number" size="3" maxlength="3" min="0" max="255" name="config[fulltext_postgres_max_word_len]" value="' . (int) $this->config['fulltext_postgres_max_word_len'] . '" /></dd>
  823. </dl>
  824. ';
  825. // These are fields required in the config table
  826. return array(
  827. 'tpl' => $tpl,
  828. 'config' => array('fulltext_postgres_ts_name' => 'string', 'fulltext_postgres_min_word_len' => 'integer:0:255', 'fulltext_postgres_max_word_len' => 'integer:0:255')
  829. );
  830. }
  831. }