SearchPostgres.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. <?php
  2. # Copyright (C) 2006-2007 Greg Sabino Mullane <greg@turnstep.com>
  3. # http://www.mediawiki.org/
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License along
  16. # with this program; if not, write to the Free Software Foundation, Inc.,
  17. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. # http://www.gnu.org/copyleft/gpl.html
  19. /**
  20. * @file
  21. * @ingroup Search
  22. */
  23. /**
  24. * Search engine hook base class for Postgres
  25. * @ingroup Search
  26. */
  27. class SearchPostgres extends SearchEngine {
  28. function __construct( $db ) {
  29. $this->db = $db;
  30. }
  31. /**
  32. * Perform a full text search query via tsearch2 and return a result set.
  33. * Currently searches a page's current title (page.page_title) and
  34. * latest revision article text (pagecontent.old_text)
  35. *
  36. * @param string $term - Raw search term
  37. * @return PostgresSearchResultSet
  38. * @access public
  39. */
  40. function searchTitle( $term ) {
  41. $q = $this->searchQuery( $term , 'titlevector', 'page_title' );
  42. $olderror = error_reporting(E_ERROR);
  43. $resultSet = $this->db->resultObject( $this->db->query( $q, 'SearchPostgres', true ) );
  44. error_reporting($olderror);
  45. if (!$resultSet) {
  46. // Needed for "Query requires full scan, GIN doesn't support it"
  47. return new SearchResultTooMany();
  48. }
  49. return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
  50. }
  51. function searchText( $term ) {
  52. $q = $this->searchQuery( $term, 'textvector', 'old_text' );
  53. $olderror = error_reporting(E_ERROR);
  54. $resultSet = $this->db->resultObject( $this->db->query( $q, 'SearchPostgres', true ) );
  55. error_reporting($olderror);
  56. if (!$resultSet) {
  57. return new SearchResultTooMany();
  58. }
  59. return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
  60. }
  61. /*
  62. * Transform the user's search string into a better form for tsearch2
  63. * Returns an SQL fragment consisting of quoted text to search for.
  64. */
  65. function parseQuery( $term ) {
  66. wfDebug( "parseQuery received: $term \n" );
  67. ## No backslashes allowed
  68. $term = preg_replace('/\\\/', '', $term);
  69. ## Collapse parens into nearby words:
  70. $term = preg_replace('/\s*\(\s*/', ' (', $term);
  71. $term = preg_replace('/\s*\)\s*/', ') ', $term);
  72. ## Treat colons as word separators:
  73. $term = preg_replace('/:/', ' ', $term);
  74. $searchstring = '';
  75. $m = array();
  76. if( preg_match_all('/([-!]?)(\S+)\s*/', $term, $m, PREG_SET_ORDER ) ) {
  77. foreach( $m as $terms ) {
  78. if (strlen($terms[1])) {
  79. $searchstring .= ' & !';
  80. }
  81. if (strtolower($terms[2]) === 'and') {
  82. $searchstring .= ' & ';
  83. }
  84. else if (strtolower($terms[2]) === 'or' or $terms[2] === '|') {
  85. $searchstring .= ' | ';
  86. }
  87. else if (strtolower($terms[2]) === 'not') {
  88. $searchstring .= ' & !';
  89. }
  90. else {
  91. $searchstring .= " & $terms[2]";
  92. }
  93. }
  94. }
  95. ## Strip out leading junk
  96. $searchstring = preg_replace('/^[\s\&\|]+/', '', $searchstring);
  97. ## Remove any doubled-up operators
  98. $searchstring = preg_replace('/([\!\&\|]) +(?:[\&\|] +)+/', "$1 ", $searchstring);
  99. ## Remove any non-spaced operators (e.g. "Zounds!")
  100. $searchstring = preg_replace('/([^ ])[\!\&\|]/', "$1", $searchstring);
  101. ## Remove any trailing whitespace or operators
  102. $searchstring = preg_replace('/[\s\!\&\|]+$/', '', $searchstring);
  103. ## Remove unnecessary quotes around everything
  104. $searchstring = preg_replace('/^[\'"](.*)[\'"]$/', "$1", $searchstring);
  105. ## Quote the whole thing
  106. $searchstring = $this->db->addQuotes($searchstring);
  107. wfDebug( "parseQuery returned: $searchstring \n" );
  108. return $searchstring;
  109. }
  110. /**
  111. * Construct the full SQL query to do the search.
  112. * @param string $filteredTerm
  113. * @param string $fulltext
  114. * @private
  115. */
  116. function searchQuery( $term, $fulltext, $colname ) {
  117. global $wgDBversion;
  118. if ( !isset( $wgDBversion ) ) {
  119. $this->db->getServerVersion();
  120. $wgDBversion = $this->db->numeric_version;
  121. }
  122. $prefix = $wgDBversion < 8.3 ? "'default'," : '';
  123. # Get the SQL fragment for the given term
  124. $searchstring = $this->parseQuery( $term );
  125. ## We need a separate query here so gin does not complain about empty searches
  126. $SQL = "SELECT to_tsquery($prefix $searchstring)";
  127. $res = $this->db->doQuery($SQL);
  128. if (!$res) {
  129. ## TODO: Better output (example to catch: one 'two)
  130. die ("Sorry, that was not a valid search string. Please go back and try again");
  131. }
  132. $top = pg_fetch_result($res,0,0);
  133. if ($top === "") { ## e.g. if only stopwords are used XXX return something better
  134. $query = "SELECT page_id, page_namespace, page_title, 0 AS score ".
  135. "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
  136. "AND r.rev_text_id = c.old_id AND 1=0";
  137. }
  138. else {
  139. $m = array();
  140. if( preg_match_all("/'([^']+)'/", $top, $m, PREG_SET_ORDER ) ) {
  141. foreach( $m as $terms ) {
  142. $this->searchTerms[$terms[1]] = $terms[1];
  143. }
  144. }
  145. $rankscore = $wgDBversion > 8.2 ? 5 : 1;
  146. $rank = $wgDBversion < 8.3 ? 'rank' : 'ts_rank';
  147. $query = "SELECT page_id, page_namespace, page_title, ".
  148. "$rank($fulltext, to_tsquery($prefix $searchstring), $rankscore) AS score ".
  149. "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
  150. "AND r.rev_text_id = c.old_id AND $fulltext @@ to_tsquery($prefix $searchstring)";
  151. }
  152. ## Redirects
  153. if (! $this->showRedirects)
  154. $query .= ' AND page_is_redirect = 0';
  155. ## Namespaces - defaults to 0
  156. if( !is_null($this->namespaces) ){ // null -> search all
  157. if ( count($this->namespaces) < 1)
  158. $query .= ' AND page_namespace = 0';
  159. else {
  160. $namespaces = $this->db->makeList( $this->namespaces );
  161. $query .= " AND page_namespace IN ($namespaces)";
  162. }
  163. }
  164. $query .= " ORDER BY score DESC, page_id DESC";
  165. $query .= $this->db->limitResult( '', $this->limit, $this->offset );
  166. wfDebug( "searchQuery returned: $query \n" );
  167. return $query;
  168. }
  169. ## Most of the work of these two functions are done automatically via triggers
  170. function update( $pageid, $title, $text ) {
  171. ## We don't want to index older revisions
  172. $SQL = "UPDATE pagecontent SET textvector = NULL WHERE old_id IN ".
  173. "(SELECT rev_text_id FROM revision WHERE rev_page = " . intval( $pageid ) .
  174. " ORDER BY rev_text_id DESC OFFSET 1)";
  175. $this->db->doQuery($SQL);
  176. return true;
  177. }
  178. function updateTitle( $id, $title ) {
  179. return true;
  180. }
  181. } ## end of the SearchPostgres class
  182. /**
  183. * @ingroup Search
  184. */
  185. class PostgresSearchResult extends SearchResult {
  186. function __construct( $row ) {
  187. parent::__construct($row);
  188. $this->score = $row->score;
  189. }
  190. function getScore() {
  191. return $this->score;
  192. }
  193. }
  194. /**
  195. * @ingroup Search
  196. */
  197. class PostgresSearchResultSet extends SearchResultSet {
  198. function __construct( $resultSet, $terms ) {
  199. $this->mResultSet = $resultSet;
  200. $this->mTerms = $terms;
  201. }
  202. function termMatches() {
  203. return $this->mTerms;
  204. }
  205. function numRows() {
  206. return $this->mResultSet->numRows();
  207. }
  208. function next() {
  209. $row = $this->mResultSet->fetchObject();
  210. if( $row === false ) {
  211. return false;
  212. } else {
  213. return new PostgresSearchResult( $row );
  214. }
  215. }
  216. }