PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/phpBB/phpbb/search/fulltext_postgres.php

http://github.com/phpbb/phpbb
PHP | 1192 lines | 708 code | 141 blank | 343 comment | 102 complexity | 9092f60a282459007a93cc5f876676a9 MD5 | raw file
Possible License(s): GPL-3.0, 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. * Stores the tsearch query
  31. * @var string
  32. */
  33. protected $tsearch_query;
  34. /**
  35. * True if phrase search is supported.
  36. * PostgreSQL fulltext currently doesn't support it
  37. * @var boolean
  38. */
  39. protected $phrase_search = false;
  40. /**
  41. * Config object
  42. * @var \phpbb\config\config
  43. */
  44. protected $config;
  45. /**
  46. * Database connection
  47. * @var \phpbb\db\driver\driver_interface
  48. */
  49. protected $db;
  50. /**
  51. * phpBB event dispatcher object
  52. * @var \phpbb\event\dispatcher_interface
  53. */
  54. protected $phpbb_dispatcher;
  55. /**
  56. * User object
  57. * @var \phpbb\user
  58. */
  59. protected $user;
  60. /**
  61. * Contains tidied search query.
  62. * Operators are prefixed in search query and common words excluded
  63. * @var string
  64. */
  65. protected $search_query;
  66. /**
  67. * Contains common words.
  68. * Common words are words with length less/more than min/max length
  69. * @var array
  70. */
  71. protected $common_words = array();
  72. /**
  73. * Associative array stores the min and max word length to be searched
  74. * @var array
  75. */
  76. protected $word_length = array();
  77. /**
  78. * Constructor
  79. * Creates a new \phpbb\search\fulltext_postgres, which is used as a search backend
  80. *
  81. * @param string|bool $error Any error that occurs is passed on through this reference variable otherwise false
  82. * @param string $phpbb_root_path Relative path to phpBB root
  83. * @param string $phpEx PHP file extension
  84. * @param \phpbb\auth\auth $auth Auth object
  85. * @param \phpbb\config\config $config Config object
  86. * @param \phpbb\db\driver\driver_interface Database object
  87. * @param \phpbb\user $user User object
  88. * @param \phpbb\event\dispatcher_interface $phpbb_dispatcher Event dispatcher object
  89. */
  90. public function __construct(&$error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user, $phpbb_dispatcher)
  91. {
  92. $this->config = $config;
  93. $this->db = $db;
  94. $this->phpbb_dispatcher = $phpbb_dispatcher;
  95. $this->user = $user;
  96. $this->word_length = array('min' => $this->config['fulltext_postgres_min_word_len'], 'max' => $this->config['fulltext_postgres_max_word_len']);
  97. /**
  98. * Load the UTF tools
  99. */
  100. if (!function_exists('utf8_strlen'))
  101. {
  102. include($phpbb_root_path . 'includes/utf/utf_tools.' . $phpEx);
  103. }
  104. $error = false;
  105. }
  106. /**
  107. * Returns the name of this search backend to be displayed to administrators
  108. *
  109. * @return string Name
  110. */
  111. public function get_name()
  112. {
  113. return 'PostgreSQL Fulltext';
  114. }
  115. /**
  116. * Returns the search_query
  117. *
  118. * @return string search query
  119. */
  120. public function get_search_query()
  121. {
  122. return $this->search_query;
  123. }
  124. /**
  125. * Returns the common_words array
  126. *
  127. * @return array common words that are ignored by search backend
  128. */
  129. public function get_common_words()
  130. {
  131. return $this->common_words;
  132. }
  133. /**
  134. * Returns the word_length array
  135. *
  136. * @return array min and max word length for searching
  137. */
  138. public function get_word_length()
  139. {
  140. return $this->word_length;
  141. }
  142. /**
  143. * Returns if phrase search is supported or not
  144. *
  145. * @return bool
  146. */
  147. public function supports_phrase_search()
  148. {
  149. return $this->phrase_search;
  150. }
  151. /**
  152. * Checks for correct PostgreSQL version and stores min/max word length in the config
  153. *
  154. * @return string|bool Language key of the error/incompatibility occurred
  155. */
  156. public function init()
  157. {
  158. if ($this->db->get_sql_layer() != 'postgres')
  159. {
  160. return $this->user->lang['FULLTEXT_POSTGRES_INCOMPATIBLE_DATABASE'];
  161. }
  162. return false;
  163. }
  164. /**
  165. * Splits keywords entered by a user into an array of words stored in $this->split_words
  166. * Stores the tidied search query in $this->search_query
  167. *
  168. * @param string &$keywords Contains the keyword as entered by the user
  169. * @param string $terms is either 'all' or 'any'
  170. * @return bool false if no valid keywords were found and otherwise true
  171. */
  172. public function split_keywords(&$keywords, $terms)
  173. {
  174. if ($terms == 'all')
  175. {
  176. $match = array('#\sand\s#iu', '#\sor\s#iu', '#\snot\s#iu', '#(^|\s)\+#', '#(^|\s)-#', '#(^|\s)\|#');
  177. $replace = array(' +', ' |', ' -', ' +', ' -', ' |');
  178. $keywords = preg_replace($match, $replace, $keywords);
  179. }
  180. // Filter out as above
  181. $split_keywords = preg_replace("#[\"\n\r\t]+#", ' ', trim(htmlspecialchars_decode($keywords)));
  182. // Split words
  183. $split_keywords = preg_replace('#([^\p{L}\p{N}\'*"()])#u', '$1$1', str_replace('\'\'', '\' \'', trim($split_keywords)));
  184. $matches = array();
  185. preg_match_all('#(?:[^\p{L}\p{N}*"()]|^)([+\-|]?(?:[\p{L}\p{N}*"()]+\'?)*[\p{L}\p{N}*"()])(?:[^\p{L}\p{N}*"()]|$)#u', $split_keywords, $matches);
  186. $this->split_words = $matches[1];
  187. foreach ($this->split_words as $i => $word)
  188. {
  189. $clean_word = preg_replace('#^[+\-|"]#', '', $word);
  190. // check word length
  191. $clean_len = utf8_strlen(str_replace('*', '', $clean_word));
  192. if (($clean_len < $this->config['fulltext_postgres_min_word_len']) || ($clean_len > $this->config['fulltext_postgres_max_word_len']))
  193. {
  194. $this->common_words[] = $word;
  195. unset($this->split_words[$i]);
  196. }
  197. }
  198. if ($terms == 'any')
  199. {
  200. $this->search_query = '';
  201. $this->tsearch_query = '';
  202. foreach ($this->split_words as $word)
  203. {
  204. if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0) || (strpos($word, '|') === 0))
  205. {
  206. $word = substr($word, 1);
  207. }
  208. $this->search_query .= $word . ' ';
  209. $this->tsearch_query .= '|' . $word . ' ';
  210. }
  211. }
  212. else
  213. {
  214. $this->search_query = '';
  215. $this->tsearch_query = '';
  216. foreach ($this->split_words as $word)
  217. {
  218. if (strpos($word, '+') === 0)
  219. {
  220. $this->search_query .= $word . ' ';
  221. $this->tsearch_query .= '&' . substr($word, 1) . ' ';
  222. }
  223. else if (strpos($word, '-') === 0)
  224. {
  225. $this->search_query .= $word . ' ';
  226. $this->tsearch_query .= '&!' . substr($word, 1) . ' ';
  227. }
  228. else if (strpos($word, '|') === 0)
  229. {
  230. $this->search_query .= $word . ' ';
  231. $this->tsearch_query .= '|' . substr($word, 1) . ' ';
  232. }
  233. else
  234. {
  235. $this->search_query .= '+' . $word . ' ';
  236. $this->tsearch_query .= '&' . $word . ' ';
  237. }
  238. }
  239. }
  240. $this->tsearch_query = substr($this->tsearch_query, 1);
  241. $this->search_query = utf8_htmlspecialchars($this->search_query);
  242. if ($this->search_query)
  243. {
  244. $this->split_words = array_values($this->split_words);
  245. sort($this->split_words);
  246. return true;
  247. }
  248. return false;
  249. }
  250. /**
  251. * Turns text into an array of words
  252. * @param string $text contains post text/subject
  253. */
  254. public function split_message($text)
  255. {
  256. // Split words
  257. $text = preg_replace('#([^\p{L}\p{N}\'*])#u', '$1$1', str_replace('\'\'', '\' \'', trim($text)));
  258. $matches = array();
  259. preg_match_all('#(?:[^\p{L}\p{N}*]|^)([+\-|]?(?:[\p{L}\p{N}*]+\'?)*[\p{L}\p{N}*])(?:[^\p{L}\p{N}*]|$)#u', $text, $matches);
  260. $text = $matches[1];
  261. // remove too short or too long words
  262. $text = array_values($text);
  263. for ($i = 0, $n = count($text); $i < $n; $i++)
  264. {
  265. $text[$i] = trim($text[$i]);
  266. if (utf8_strlen($text[$i]) < $this->config['fulltext_postgres_min_word_len'] || utf8_strlen($text[$i]) > $this->config['fulltext_postgres_max_word_len'])
  267. {
  268. unset($text[$i]);
  269. }
  270. }
  271. return array_values($text);
  272. }
  273. /**
  274. * Performs a search on keywords depending on display specific params. You have to run split_keywords() first
  275. *
  276. * @param string $type contains either posts or topics depending on what should be searched for
  277. * @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)
  278. * @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)
  279. * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query
  280. * @param string $sort_key is the key of $sort_by_sql for the selected sorting
  281. * @param string $sort_dir is either a or d representing ASC and DESC
  282. * @param string $sort_days specifies the maximum amount of days a post may be old
  283. * @param array $ex_fid_ary specifies an array of forum ids which should not be searched
  284. * @param string $post_visibility specifies which types of posts the user can view in which forums
  285. * @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
  286. * @param array $author_ary an array of author ids if the author should be ignored during the search the array is empty
  287. * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match
  288. * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
  289. * @param int $start indicates the first index of the page
  290. * @param int $per_page number of ids each page is supposed to contain
  291. * @return boolean|int total number of results
  292. */
  293. 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)
  294. {
  295. // No keywords? No posts
  296. if (!$this->search_query)
  297. {
  298. return false;
  299. }
  300. // When search query contains queries like -foo
  301. if (strpos($this->search_query, '+') === false)
  302. {
  303. return false;
  304. }
  305. // generate a search_key from all the options to identify the results
  306. $search_key_array = array(
  307. implode(', ', $this->split_words),
  308. $type,
  309. $fields,
  310. $terms,
  311. $sort_days,
  312. $sort_key,
  313. $topic_id,
  314. implode(',', $ex_fid_ary),
  315. $post_visibility,
  316. implode(',', $author_ary)
  317. );
  318. /**
  319. * Allow changing the search_key for cached results
  320. *
  321. * @event core.search_postgres_by_keyword_modify_search_key
  322. * @var array search_key_array Array with search parameters to generate the search_key
  323. * @var string type Searching type ('posts', 'topics')
  324. * @var string fields Searching fields ('titleonly', 'msgonly', 'firstpost', 'all')
  325. * @var string terms Searching terms ('all', 'any')
  326. * @var int sort_days Time, in days, of the oldest possible post to list
  327. * @var string sort_key The sort type used from the possible sort types
  328. * @var int topic_id Limit the search to this topic_id only
  329. * @var array ex_fid_ary Which forums not to search on
  330. * @var string post_visibility Post visibility data
  331. * @var array author_ary Array of user_id containing the users to filter the results to
  332. * @since 3.1.7-RC1
  333. */
  334. $vars = array(
  335. 'search_key_array',
  336. 'type',
  337. 'fields',
  338. 'terms',
  339. 'sort_days',
  340. 'sort_key',
  341. 'topic_id',
  342. 'ex_fid_ary',
  343. 'post_visibility',
  344. 'author_ary',
  345. );
  346. extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_by_keyword_modify_search_key', compact($vars)));
  347. $search_key = md5(implode('#', $search_key_array));
  348. if ($start < 0)
  349. {
  350. $start = 0;
  351. }
  352. // try reading the results from cache
  353. $result_count = 0;
  354. if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
  355. {
  356. return $result_count;
  357. }
  358. $id_ary = array();
  359. $join_topic = ($type == 'posts') ? false : true;
  360. // Build sql strings for sorting
  361. $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
  362. $sql_sort_table = $sql_sort_join = '';
  363. switch ($sql_sort[0])
  364. {
  365. case 'u':
  366. $sql_sort_table = USERS_TABLE . ' u, ';
  367. $sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
  368. break;
  369. case 't':
  370. $join_topic = true;
  371. break;
  372. case 'f':
  373. $sql_sort_table = FORUMS_TABLE . ' f, ';
  374. $sql_sort_join = ' AND f.forum_id = p.forum_id ';
  375. break;
  376. }
  377. // Build some display specific sql strings
  378. switch ($fields)
  379. {
  380. case 'titleonly':
  381. $sql_match = 'p.post_subject';
  382. $sql_match_where = ' AND p.post_id = t.topic_first_post_id';
  383. $join_topic = true;
  384. break;
  385. case 'msgonly':
  386. $sql_match = 'p.post_text';
  387. $sql_match_where = '';
  388. break;
  389. case 'firstpost':
  390. $sql_match = 'p.post_subject, p.post_text';
  391. $sql_match_where = ' AND p.post_id = t.topic_first_post_id';
  392. $join_topic = true;
  393. break;
  394. default:
  395. $sql_match = 'p.post_subject, p.post_text';
  396. $sql_match_where = '';
  397. break;
  398. }
  399. $tsearch_query = $this->tsearch_query;
  400. /**
  401. * Allow changing the query used to search for posts using fulltext_postgres
  402. *
  403. * @event core.search_postgres_keywords_main_query_before
  404. * @var string tsearch_query The parsed keywords used for this search
  405. * @var int result_count The previous result count for the format of the query.
  406. * Set to 0 to force a re-count
  407. * @var bool join_topic Weather or not TOPICS_TABLE should be CROSS JOIN'ED
  408. * @var array author_ary Array of user_id containing the users to filter the results to
  409. * @var string author_name An extra username to search on (!empty(author_ary) must be true, to be relevant)
  410. * @var array ex_fid_ary Which forums not to search on
  411. * @var int topic_id Limit the search to this topic_id only
  412. * @var string sql_sort_table Extra tables to include in the SQL query.
  413. * Used in conjunction with sql_sort_join
  414. * @var string sql_sort_join SQL conditions to join all the tables used together.
  415. * Used in conjunction with sql_sort_table
  416. * @var int sort_days Time, in days, of the oldest possible post to list
  417. * @var string sql_match Which columns to do the search on.
  418. * @var string sql_match_where Extra conditions to use to properly filter the matching process
  419. * @var string sort_by_sql The possible predefined sort types
  420. * @var string sort_key The sort type used from the possible sort types
  421. * @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used
  422. * @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir
  423. * @var int start How many posts to skip in the search results (used for pagination)
  424. * @since 3.1.5-RC1
  425. */
  426. $vars = array(
  427. 'tsearch_query',
  428. 'result_count',
  429. 'join_topic',
  430. 'author_ary',
  431. 'author_name',
  432. 'ex_fid_ary',
  433. 'topic_id',
  434. 'sql_sort_table',
  435. 'sql_sort_join',
  436. 'sort_days',
  437. 'sql_match',
  438. 'sql_match_where',
  439. 'sort_by_sql',
  440. 'sort_key',
  441. 'sort_dir',
  442. 'sql_sort',
  443. 'start',
  444. );
  445. extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_keywords_main_query_before', compact($vars)));
  446. $sql_select = ($type == 'posts') ? 'p.post_id' : 'DISTINCT t.topic_id, ' . $sort_by_sql[$sort_key];
  447. $sql_from = ($join_topic) ? TOPICS_TABLE . ' t, ' : '';
  448. $field = ($type == 'posts') ? 'post_id' : 'topic_id';
  449. if (count($author_ary) && $author_name)
  450. {
  451. // first one matches post of registered users, second one guests and deleted users
  452. $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
  453. }
  454. else if (count($author_ary))
  455. {
  456. $sql_author = ' AND ' . $this->db->sql_in_set('p.poster_id', $author_ary);
  457. }
  458. else
  459. {
  460. $sql_author = '';
  461. }
  462. $sql_where_options = $sql_sort_join;
  463. $sql_where_options .= ($topic_id) ? ' AND p.topic_id = ' . $topic_id : '';
  464. $sql_where_options .= ($join_topic) ? ' AND t.topic_id = p.topic_id' : '';
  465. $sql_where_options .= (count($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
  466. $sql_where_options .= ' AND ' . $post_visibility;
  467. $sql_where_options .= $sql_author;
  468. $sql_where_options .= ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
  469. $sql_where_options .= $sql_match_where;
  470. $sql_match = str_replace(',', " || ' ' ||", $sql_match);
  471. $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) . "')";
  472. $this->db->sql_transaction('begin');
  473. $sql_from = "FROM $sql_from$sql_sort_table" . POSTS_TABLE . " p";
  474. $sql_where = "WHERE (" . $tmp_sql_match . ")
  475. $sql_where_options";
  476. $sql = "SELECT $sql_select
  477. $sql_from
  478. $sql_where
  479. ORDER BY $sql_sort";
  480. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  481. while ($row = $this->db->sql_fetchrow($result))
  482. {
  483. $id_ary[] = $row[$field];
  484. }
  485. $this->db->sql_freeresult($result);
  486. $id_ary = array_unique($id_ary);
  487. // if the total result count is not cached yet, retrieve it from the db
  488. if (!$result_count)
  489. {
  490. $sql_count = "SELECT COUNT(*) as result_count
  491. $sql_from
  492. $sql_where";
  493. $result = $this->db->sql_query($sql_count);
  494. $result_count = (int) $this->db->sql_fetchfield('result_count');
  495. $this->db->sql_freeresult($result);
  496. if (!$result_count)
  497. {
  498. return false;
  499. }
  500. }
  501. $this->db->sql_transaction('commit');
  502. if ($start >= $result_count)
  503. {
  504. $start = floor(($result_count - 1) / $per_page) * $per_page;
  505. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  506. while ($row = $this->db->sql_fetchrow($result))
  507. {
  508. $id_ary[] = $row[$field];
  509. }
  510. $this->db->sql_freeresult($result);
  511. $id_ary = array_unique($id_ary);
  512. }
  513. // store the ids, from start on then delete anything that isn't on the current page because we only need ids for one page
  514. $this->save_ids($search_key, implode(' ', $this->split_words), $author_ary, $result_count, $id_ary, $start, $sort_dir);
  515. $id_ary = array_slice($id_ary, 0, (int) $per_page);
  516. return $result_count;
  517. }
  518. /**
  519. * Performs a search on an author's posts without caring about message contents. Depends on display specific params
  520. *
  521. * @param string $type contains either posts or topics depending on what should be searched for
  522. * @param boolean $firstpost_only if true, only topic starting posts will be considered
  523. * @param array $sort_by_sql contains SQL code for the ORDER BY part of a query
  524. * @param string $sort_key is the key of $sort_by_sql for the selected sorting
  525. * @param string $sort_dir is either a or d representing ASC and DESC
  526. * @param string $sort_days specifies the maximum amount of days a post may be old
  527. * @param array $ex_fid_ary specifies an array of forum ids which should not be searched
  528. * @param string $post_visibility specifies which types of posts the user can view in which forums
  529. * @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
  530. * @param array $author_ary an array of author ids
  531. * @param string $author_name specifies the author match, when ANONYMOUS is also a search-match
  532. * @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
  533. * @param int $start indicates the first index of the page
  534. * @param int $per_page number of ids each page is supposed to contain
  535. * @return boolean|int total number of results
  536. */
  537. 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)
  538. {
  539. // No author? No posts
  540. if (!count($author_ary))
  541. {
  542. return 0;
  543. }
  544. // generate a search_key from all the options to identify the results
  545. $search_key_array = array(
  546. '',
  547. $type,
  548. ($firstpost_only) ? 'firstpost' : '',
  549. '',
  550. '',
  551. $sort_days,
  552. $sort_key,
  553. $topic_id,
  554. implode(',', $ex_fid_ary),
  555. $post_visibility,
  556. implode(',', $author_ary),
  557. $author_name,
  558. );
  559. /**
  560. * Allow changing the search_key for cached results
  561. *
  562. * @event core.search_postgres_by_author_modify_search_key
  563. * @var array search_key_array Array with search parameters to generate the search_key
  564. * @var string type Searching type ('posts', 'topics')
  565. * @var boolean firstpost_only Flag indicating if only topic starting posts are considered
  566. * @var int sort_days Time, in days, of the oldest possible post to list
  567. * @var string sort_key The sort type used from the possible sort types
  568. * @var int topic_id Limit the search to this topic_id only
  569. * @var array ex_fid_ary Which forums not to search on
  570. * @var string post_visibility Post visibility data
  571. * @var array author_ary Array of user_id containing the users to filter the results to
  572. * @var string author_name The username to search on
  573. * @since 3.1.7-RC1
  574. */
  575. $vars = array(
  576. 'search_key_array',
  577. 'type',
  578. 'firstpost_only',
  579. 'sort_days',
  580. 'sort_key',
  581. 'topic_id',
  582. 'ex_fid_ary',
  583. 'post_visibility',
  584. 'author_ary',
  585. 'author_name',
  586. );
  587. extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_by_author_modify_search_key', compact($vars)));
  588. $search_key = md5(implode('#', $search_key_array));
  589. if ($start < 0)
  590. {
  591. $start = 0;
  592. }
  593. // try reading the results from cache
  594. $result_count = 0;
  595. if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
  596. {
  597. return $result_count;
  598. }
  599. $id_ary = array();
  600. // Create some display specific sql strings
  601. if ($author_name)
  602. {
  603. // first one matches post of registered users, second one guests and deleted users
  604. $sql_author = '(' . $this->db->sql_in_set('p.poster_id', array_diff($author_ary, array(ANONYMOUS)), false, true) . ' OR p.post_username ' . $author_name . ')';
  605. }
  606. else
  607. {
  608. $sql_author = $this->db->sql_in_set('p.poster_id', $author_ary);
  609. }
  610. $sql_fora = (count($ex_fid_ary)) ? ' AND ' . $this->db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
  611. $sql_topic_id = ($topic_id) ? ' AND p.topic_id = ' . (int) $topic_id : '';
  612. $sql_time = ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
  613. $sql_firstpost = ($firstpost_only) ? ' AND p.post_id = t.topic_first_post_id' : '';
  614. // Build sql strings for sorting
  615. $sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
  616. $sql_sort_table = $sql_sort_join = '';
  617. switch ($sql_sort[0])
  618. {
  619. case 'u':
  620. $sql_sort_table = USERS_TABLE . ' u, ';
  621. $sql_sort_join = ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
  622. break;
  623. case 't':
  624. $sql_sort_table = ($type == 'posts' && !$firstpost_only) ? TOPICS_TABLE . ' t, ' : '';
  625. $sql_sort_join = ($type == 'posts' && !$firstpost_only) ? ' AND t.topic_id = p.topic_id ' : '';
  626. break;
  627. case 'f':
  628. $sql_sort_table = FORUMS_TABLE . ' f, ';
  629. $sql_sort_join = ' AND f.forum_id = p.forum_id ';
  630. break;
  631. }
  632. $m_approve_fid_sql = ' AND ' . $post_visibility;
  633. /**
  634. * Allow changing the query used to search for posts by author in fulltext_postgres
  635. *
  636. * @event core.search_postgres_author_count_query_before
  637. * @var int result_count The previous result count for the format of the query.
  638. * Set to 0 to force a re-count
  639. * @var string sql_sort_table CROSS JOIN'ed table to allow doing the sort chosen
  640. * @var string sql_sort_join Condition to define how to join the CROSS JOIN'ed table specifyed in sql_sort_table
  641. * @var array author_ary Array of user_id containing the users to filter the results to
  642. * @var string author_name An extra username to search on
  643. * @var string sql_author SQL WHERE condition for the post author ids
  644. * @var int topic_id Limit the search to this topic_id only
  645. * @var string sql_topic_id SQL of topic_id
  646. * @var string sort_by_sql The possible predefined sort types
  647. * @var string sort_key The sort type used from the possible sort types
  648. * @var string sort_dir "a" for ASC or "d" dor DESC for the sort order used
  649. * @var string sql_sort The result SQL when processing sort_by_sql + sort_key + sort_dir
  650. * @var string sort_days Time, in days, that the oldest post showing can have
  651. * @var string sql_time The SQL to search on the time specifyed by sort_days
  652. * @var bool firstpost_only Wether or not to search only on the first post of the topics
  653. * @var array ex_fid_ary Forum ids that must not be searched on
  654. * @var array sql_fora SQL query for ex_fid_ary
  655. * @var string m_approve_fid_sql WHERE clause condition on post_visibility restrictions
  656. * @var int start How many posts to skip in the search results (used for pagination)
  657. * @since 3.1.5-RC1
  658. */
  659. $vars = array(
  660. 'result_count',
  661. 'sql_sort_table',
  662. 'sql_sort_join',
  663. 'author_ary',
  664. 'author_name',
  665. 'sql_author',
  666. 'topic_id',
  667. 'sql_topic_id',
  668. 'sort_by_sql',
  669. 'sort_key',
  670. 'sort_dir',
  671. 'sql_sort',
  672. 'sort_days',
  673. 'sql_time',
  674. 'firstpost_only',
  675. 'ex_fid_ary',
  676. 'sql_fora',
  677. 'm_approve_fid_sql',
  678. 'start',
  679. );
  680. extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_author_count_query_before', compact($vars)));
  681. // Build the query for really selecting the post_ids
  682. if ($type == 'posts')
  683. {
  684. $sql = "SELECT p.post_id
  685. FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . "
  686. WHERE $sql_author
  687. $sql_topic_id
  688. $sql_firstpost
  689. $m_approve_fid_sql
  690. $sql_fora
  691. $sql_sort_join
  692. $sql_time
  693. ORDER BY $sql_sort";
  694. $field = 'post_id';
  695. }
  696. else
  697. {
  698. $sql = "SELECT t.topic_id
  699. FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  700. WHERE $sql_author
  701. $sql_topic_id
  702. $sql_firstpost
  703. $m_approve_fid_sql
  704. $sql_fora
  705. AND t.topic_id = p.topic_id
  706. $sql_sort_join
  707. $sql_time
  708. GROUP BY t.topic_id, $sort_by_sql[$sort_key]
  709. ORDER BY $sql_sort";
  710. $field = 'topic_id';
  711. }
  712. $this->db->sql_transaction('begin');
  713. // Only read one block of posts from the db and then cache it
  714. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  715. while ($row = $this->db->sql_fetchrow($result))
  716. {
  717. $id_ary[] = $row[$field];
  718. }
  719. $this->db->sql_freeresult($result);
  720. // retrieve the total result count if needed
  721. if (!$result_count)
  722. {
  723. if ($type == 'posts')
  724. {
  725. $sql_count = "SELECT COUNT(*) as result_count
  726. FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . "
  727. WHERE $sql_author
  728. $sql_topic_id
  729. $sql_firstpost
  730. $m_approve_fid_sql
  731. $sql_fora
  732. $sql_sort_join
  733. $sql_time";
  734. }
  735. else
  736. {
  737. $sql_count = "SELECT COUNT(*) as result_count
  738. FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
  739. WHERE $sql_author
  740. $sql_topic_id
  741. $sql_firstpost
  742. $m_approve_fid_sql
  743. $sql_fora
  744. AND t.topic_id = p.topic_id
  745. $sql_sort_join
  746. $sql_time
  747. GROUP BY t.topic_id, $sort_by_sql[$sort_key]";
  748. }
  749. $this->db->sql_query($sql_count);
  750. $result_count = (int) $this->db->sql_fetchfield('result_count');
  751. if (!$result_count)
  752. {
  753. return false;
  754. }
  755. }
  756. $this->db->sql_transaction('commit');
  757. if ($start >= $result_count)
  758. {
  759. $start = floor(($result_count - 1) / $per_page) * $per_page;
  760. $result = $this->db->sql_query_limit($sql, $this->config['search_block_size'], $start);
  761. while ($row = $this->db->sql_fetchrow($result))
  762. {
  763. $id_ary[] = (int) $row[$field];
  764. }
  765. $this->db->sql_freeresult($result);
  766. $id_ary = array_unique($id_ary);
  767. }
  768. if (count($id_ary))
  769. {
  770. $this->save_ids($search_key, '', $author_ary, $result_count, $id_ary, $start, $sort_dir);
  771. $id_ary = array_slice($id_ary, 0, $per_page);
  772. return $result_count;
  773. }
  774. return false;
  775. }
  776. /**
  777. * Destroys cached search results, that contained one of the new words in a post so the results won't be outdated
  778. *
  779. * @param string $mode contains the post mode: edit, post, reply, quote ...
  780. * @param int $post_id contains the post id of the post to index
  781. * @param string $message contains the post text of the post
  782. * @param string $subject contains the subject of the post to index
  783. * @param int $poster_id contains the user id of the poster
  784. * @param int $forum_id contains the forum id of parent forum of the post
  785. */
  786. public function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id)
  787. {
  788. // Split old and new post/subject to obtain array of words
  789. $split_text = $this->split_message($message);
  790. $split_title = ($subject) ? $this->split_message($subject) : array();
  791. $words = array_unique(array_merge($split_text, $split_title));
  792. /**
  793. * Event to modify method arguments and words before the PostgreSQL search index is updated
  794. *
  795. * @event core.search_postgres_index_before
  796. * @var string mode Contains the post mode: edit, post, reply, quote
  797. * @var int post_id The id of the post which is modified/created
  798. * @var string message New or updated post content
  799. * @var string subject New or updated post subject
  800. * @var int poster_id Post author's user id
  801. * @var int forum_id The id of the forum in which the post is located
  802. * @var array words Array of words added to the index
  803. * @var array split_text Array of words from the message
  804. * @var array split_title Array of words from the title
  805. * @since 3.2.3-RC1
  806. */
  807. $vars = array(
  808. 'mode',
  809. 'post_id',
  810. 'message',
  811. 'subject',
  812. 'poster_id',
  813. 'forum_id',
  814. 'words',
  815. 'split_text',
  816. 'split_title',
  817. );
  818. extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_index_before', compact($vars)));
  819. unset($split_text);
  820. unset($split_title);
  821. // destroy cached search results containing any of the words removed or added
  822. $this->destroy_cache($words, array($poster_id));
  823. unset($words);
  824. }
  825. /**
  826. * Destroy cached results, that might be outdated after deleting a post
  827. */
  828. public function index_remove($post_ids, $author_ids, $forum_ids)
  829. {
  830. $this->destroy_cache(array(), $author_ids);
  831. }
  832. /**
  833. * Destroy old cache entries
  834. */
  835. public function tidy()
  836. {
  837. // destroy too old cached search results
  838. $this->destroy_cache(array());
  839. $this->config->set('search_last_gc', time(), false);
  840. }
  841. /**
  842. * Create fulltext index
  843. *
  844. * @return string|bool error string is returned incase of errors otherwise false
  845. */
  846. public function create_index($acp_module, $u_action)
  847. {
  848. // Make sure we can actually use PostgreSQL with fulltext indexes
  849. if ($error = $this->init())
  850. {
  851. return $error;
  852. }
  853. if (empty($this->stats))
  854. {
  855. $this->get_stats();
  856. }
  857. $sql_queries = [];
  858. if (!isset($this->stats['post_subject']))
  859. {
  860. $sql_queries[] = "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))";
  861. }
  862. if (!isset($this->stats['post_content']))
  863. {
  864. $sql_queries[] = "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))";
  865. }
  866. if (!isset($this->stats['post_subject_content']))
  867. {
  868. $sql_queries[] = "CREATE INDEX " . POSTS_TABLE . "_" . $this->config['fulltext_postgres_ts_name'] . "_post_subject_content ON " . POSTS_TABLE . " USING gin (to_tsvector ('" . $this->db->sql_escape($this->config['fulltext_postgres_ts_name']) . "', post_subject || ' ' || post_text))";
  869. }
  870. $stats = $this->stats;
  871. /**
  872. * Event to modify SQL queries before the Postgres search index is created
  873. *
  874. * @event core.search_postgres_create_index_before
  875. * @var array sql_queries Array with queries for creating the search index
  876. * @var array stats Array with statistics of the current index (read only)
  877. * @since 3.2.3-RC1
  878. */
  879. $vars = array(
  880. 'sql_queries',
  881. 'stats',
  882. );
  883. extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_create_index_before', compact($vars)));
  884. foreach ($sql_queries as $sql_query)
  885. {
  886. $this->db->sql_query($sql_query);
  887. }
  888. $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
  889. return false;
  890. }
  891. /**
  892. * Drop fulltext index
  893. *
  894. * @return string|bool error string is returned incase of errors otherwise false
  895. */
  896. public function delete_index($acp_module, $u_action)
  897. {
  898. // Make sure we can actually use PostgreSQL with fulltext indexes
  899. if ($error = $this->init())
  900. {
  901. return $error;
  902. }
  903. if (empty($this->stats))
  904. {
  905. $this->get_stats();
  906. }
  907. $sql_queries = [];
  908. if (isset($this->stats['post_subject']))
  909. {
  910. $sql_queries[] = 'DROP INDEX ' . $this->stats['post_subject']['relname'];
  911. }
  912. if (isset($this->stats['post_content']))
  913. {
  914. $sql_queries[] = 'DROP INDEX ' . $this->stats['post_content']['relname'];
  915. }
  916. if (isset($this->stats['post_subject_content']))
  917. {
  918. $sql_queries[] = 'DROP INDEX ' . $this->stats['post_subject_content']['relname'];
  919. }
  920. $stats = $this->stats;
  921. /**
  922. * Event to modify SQL queries before the Postgres search index is created
  923. *
  924. * @event core.search_postgres_delete_index_before
  925. * @var array sql_queries Array with queries for deleting the search index
  926. * @var array stats Array with statistics of the current index (read only)
  927. * @since 3.2.3-RC1
  928. */
  929. $vars = array(
  930. 'sql_queries',
  931. 'stats',
  932. );
  933. extract($this->phpbb_dispatcher->trigger_event('core.search_postgres_delete_index_before', compact($vars)));
  934. foreach ($sql_queries as $sql_query)
  935. {
  936. $this->db->sql_query($sql_query);
  937. }
  938. $this->db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
  939. return false;
  940. }
  941. /**
  942. * Returns true if both FULLTEXT indexes exist
  943. */
  944. public function index_created()
  945. {
  946. if (empty($this->stats))
  947. {
  948. $this->get_stats();
  949. }
  950. return (isset($this->stats['post_subject']) && isset($this->stats['post_content'])) ? true : false;
  951. }
  952. /**
  953. * Returns an associative array containing information about the indexes
  954. */
  955. public function index_stats()
  956. {
  957. if (empty($this->stats))
  958. {
  959. $this->get_stats();
  960. }
  961. return array(
  962. $this->user->lang['FULLTEXT_POSTGRES_TOTAL_POSTS'] => ($this->index_created()) ? $this->stats['total_posts'] : 0,
  963. );
  964. }
  965. /**
  966. * Computes the stats and store them in the $this->stats associative array
  967. */
  968. protected function get_stats()
  969. {
  970. if ($this->db->get_sql_layer() != 'postgres')
  971. {
  972. $this->stats = array();
  973. return;
  974. }
  975. $sql = "SELECT c2.relname, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS indexdef
  976. FROM pg_catalog.pg_class c1, pg_catalog.pg_index i, pg_catalog.pg_class c2
  977. WHERE c1.relname = '" . POSTS_TABLE . "'
  978. AND pg_catalog.pg_table_is_visible(c1.oid)
  979. AND c1.oid = i.indrelid
  980. AND i.indexrelid = c2.oid";
  981. $result = $this->db->sql_query($sql);
  982. while ($row = $this->db->sql_fetchrow($result))
  983. {
  984. // deal with older PostgreSQL versions which didn't use Index_type
  985. if (strpos($row['indexdef'], 'to_tsvector') !== false)
  986. {
  987. if ($row['relname'] == POSTS_TABLE . '_' . $this->config['fulltext_postgres_ts_name'] . '_post_subject' || $row['relname'] == POSTS_TABLE . '_post_subject')
  988. {
  989. $this->stats['post_subject'] = $row;
  990. }
  991. else if ($row['relname'] == POSTS_TABLE . '_' . $this->config['fulltext_postgres_ts_name'] . '_post_content' || $row['relname'] == POSTS_TABLE . '_post_content')
  992. {
  993. $this->stats['post_content'] = $row;
  994. }
  995. else if ($row['relname'] == POSTS_TABLE . '_' . $this->config['fulltext_postgres_ts_name'] . '_post_subject_content' || $row['relname'] == POSTS_TABLE . '_post_subject_content')
  996. {
  997. $this->stats['post_subject_content'] = $row;
  998. }
  999. }
  1000. }
  1001. $this->db->sql_freeresult($result);
  1002. $this->stats['total_posts'] = $this->config['num_posts'];
  1003. }
  1004. /**
  1005. * Display various options that can be configured for the backend from the acp
  1006. *
  1007. * @return associative array containing template and config variables
  1008. */
  1009. public function acp()
  1010. {
  1011. $tpl = '
  1012. <dl>
  1013. <dt><label>' . $this->user->lang['FULLTEXT_POSTGRES_VERSION_CHECK'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_VERSION_CHECK_EXPLAIN'] . '</span></dt>
  1014. <dd>' . (($this->db->get_sql_layer() == 'postgres') ? $this->user->lang['YES'] : $this->user->lang['NO']) . '</dd>
  1015. </dl>
  1016. <dl>
  1017. <dt><label>' . $this->user->lang['FULLTEXT_POSTGRES_TS_NAME'] . '</label><br /><span>' . $this->user->lang['FULLTEXT_POSTGRES_TS_NAME_EXPLAIN'] . '</span></dt>
  1018. <dd><select name="config[fulltext_postgres_ts_name]">';
  1019. if ($this->db->get_sql_layer() == 'postgres')
  1020. {
  1021. $sql = 'SELECT cfgname AS ts_name
  1022. FROM pg_ts_config';
  1023. $result = $this->db->sql_query($sql);
  1024. while ($row = $this->db->sql_fetchrow($result))
  1025. {
  1026. $tpl .= '<option value="' . $row['ts_name'] . '"' . ($row['ts_name'] === $this->config['fulltext_postgres_ts_name'] ? ' selected="selected"' : '') . '>' . $row['ts_name'] . '</option>';
  1027. }
  1028. $this->db->sql_freeresult($result);
  1029. }
  1030. else
  1031. {
  1032. $tpl .= '<option value="' . $this->config['fulltext_postgres_ts_name'] . '" selected="selected">' . $this->config['fulltext_postgres_ts_name'] . '</option>';
  1033. }
  1034. $tpl .= '</select></dd>
  1035. </dl>
  1036. <dl>
  1037. <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>
  1038. <dd><input id="fulltext_postgres_min_word_len" type="number" min="0" max="255" name="config[fulltext_postgres_min_word_len]" value="' . (int) $this->config['fulltext_postgres_min_word_len'] . '" /></dd>
  1039. </dl>
  1040. <dl>
  1041. <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>
  1042. <dd><input id="fulltext_postgres_max_word_len" type="number" min="0" max="255" name="config[fulltext_postgres_max_word_len]" value="' . (int) $this->config['fulltext_postgres_max_word_len'] . '" /></dd>
  1043. </dl>
  1044. ';
  1045. // These are fields required in the config table
  1046. return array(
  1047. 'tpl' => $tpl,
  1048. 'config' => array('fulltext_postgres_ts_name' => 'string', 'fulltext_postgres_min_word_len' => 'integer:0:255', 'fulltext_postgres_max_word_len' => 'integer:0:255')
  1049. );
  1050. }
  1051. }