Define $wgRateLimitsExcludedGroups to an empty array to avoid some PHP warnings,...
[mediawiki.git] / includes / SearchPostgres.php
blob02638bb5c8752c3278f2ecd6429c5cbbb1ce0d45
1 <?php
2 # Copyright (C) 2006-2007 Greg Sabino Mullane <greg@turnstep.com>
3 # http://www.mediawiki.org/
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.
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.
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
20 /**
21 * @file
22 * @ingroup Search
25 /**
26 * Search engine hook base class for Postgres
27 * @ingroup Search
29 class SearchPostgres extends SearchEngine {
31 function SearchPostgres( $db ) {
32 $this->db = $db;
35 /**
36 * Perform a full text search query via tsearch2 and return a result set.
37 * Currently searches a page's current title (page.page_title) and
38 * latest revision article text (pagecontent.old_text)
40 * @param string $term - Raw search term
41 * @return PostgresSearchResultSet
42 * @access public
44 function searchTitle( $term ) {
45 $q = $this->searchQuery( $term , 'titlevector', 'page_title' );
46 $olderror = error_reporting(E_ERROR);
47 $resultSet = $this->db->resultObject( $this->db->query( $q, 'SearchPostgres', true ) );
48 error_reporting($olderror);
49 if (!$resultSet) {
50 // Needed for "Query requires full scan, GIN doesn't support it"
51 return new SearchResultTooMany();
53 return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
55 function searchText( $term ) {
56 $q = $this->searchQuery( $term, 'textvector', 'old_text' );
57 $olderror = error_reporting(E_ERROR);
58 $resultSet = $this->db->resultObject( $this->db->query( $q, 'SearchPostgres', true ) );
59 error_reporting($olderror);
60 if (!$resultSet) {
61 return new SearchResultTooMany();
63 return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
68 * Transform the user's search string into a better form for tsearch2
70 function parseQuery( $term ) {
72 wfDebug( "parseQuery received: $term" );
74 ## No backslashes allowed
75 $term = preg_replace('/\\\/', '', $term);
77 ## Collapse parens into nearby words:
78 $term = preg_replace('/\s*\(\s*/', ' (', $term);
79 $term = preg_replace('/\s*\)\s*/', ') ', $term);
81 ## Treat colons as word separators:
82 $term = preg_replace('/:/', ' ', $term);
84 $searchstring = '';
85 $m = array();
86 if( preg_match_all('/([-!]?)(\S+)\s*/', $term, $m, PREG_SET_ORDER ) ) {
87 foreach( $m as $terms ) {
88 if (strlen($terms[1])) {
89 $searchstring .= ' & !';
91 if (strtolower($terms[2]) === 'and') {
92 $searchstring .= ' & ';
94 else if (strtolower($terms[2]) === 'or' or $terms[2] === '|') {
95 $searchstring .= ' | ';
97 else if (strtolower($terms[2]) === 'not') {
98 $searchstring .= ' & !';
100 else {
101 $searchstring .= " & $terms[2]";
106 ## Strip out leading junk
107 $searchstring = preg_replace('/^[\s\&\|]+/', '', $searchstring);
109 ## Remove any doubled-up operators
110 $searchstring = preg_replace('/([\!\&\|]) +(?:[\&\|] +)+/', "$1 ", $searchstring);
112 ## Remove any non-spaced operators (e.g. "Zounds!")
113 $searchstring = preg_replace('/([^ ])[\!\&\|]/', "$1", $searchstring);
115 ## Remove any trailing whitespace or operators
116 $searchstring = preg_replace('/[\s\!\&\|]+$/', '', $searchstring);
118 ## Remove unnecessary quotes around everything
119 $searchstring = preg_replace('/^[\'"](.*)[\'"]$/', "$1", $searchstring);
121 ## Quote the whole thing
122 $searchstring = $this->db->addQuotes($searchstring);
124 wfDebug( "parseQuery returned: $searchstring" );
126 return $searchstring;
131 * Construct the full SQL query to do the search.
132 * @param string $filteredTerm
133 * @param string $fulltext
134 * @private
136 function searchQuery( $term, $fulltext, $colname ) {
137 global $wgDBversion;
139 if ( !isset( $wgDBversion ) ) {
140 $this->db->getServerVersion();
141 $wgDBversion = $this->db->numeric_version;
143 $prefix = $wgDBversion < 8.3 ? "'default'," : '';
145 $searchstring = $this->parseQuery( $term );
147 ## We need a separate query here so gin does not complain about empty searches
148 $SQL = "SELECT to_tsquery($prefix $searchstring)";
149 $res = $this->db->doQuery($SQL);
150 if (!$res) {
151 ## TODO: Better output (example to catch: one 'two)
152 die ("Sorry, that was not a valid search string. Please go back and try again");
154 $top = pg_fetch_result($res,0,0);
156 if ($top === "") { ## e.g. if only stopwords are used XXX return something better
157 $query = "SELECT page_id, page_namespace, page_title, 0 AS score ".
158 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
159 "AND r.rev_text_id = c.old_id AND 1=0";
161 else {
162 $m = array();
163 if( preg_match_all("/'([^']+)'/", $top, $m, PREG_SET_ORDER ) ) {
164 foreach( $m as $terms ) {
165 $this->searchTerms[$terms[1]] = $terms[1];
169 $rankscore = $wgDBversion > 8.2 ? 5 : 1;
170 $rank = $wgDBversion < 8.3 ? 'rank' : 'ts_rank';
171 $query = "SELECT page_id, page_namespace, page_title, ".
172 "$rank($fulltext, to_tsquery($prefix $searchstring), $rankscore) AS score ".
173 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
174 "AND r.rev_text_id = c.old_id AND $fulltext @@ to_tsquery($prefix $searchstring)";
177 ## Redirects
178 if (! $this->showRedirects)
179 $query .= ' AND page_is_redirect = 0';
181 ## Namespaces - defaults to 0
182 if( !is_null($this->namespaces) ){ // null -> search all
183 if ( count($this->namespaces) < 1)
184 $query .= ' AND page_namespace = 0';
185 else {
186 $namespaces = implode( ',', $this->namespaces );
187 $query .= " AND page_namespace IN ($namespaces)";
191 $query .= " ORDER BY score DESC, page_id DESC";
193 $query .= $this->db->limitResult( '', $this->limit, $this->offset );
195 wfDebug( "searchQuery returned: $query" );
197 return $query;
200 ## Most of the work of these two functions are done automatically via triggers
202 function update( $pageid, $title, $text ) {
203 ## We don't want to index older revisions
204 $SQL = "UPDATE pagecontent SET textvector = NULL WHERE old_id = ".
205 "(SELECT rev_text_id FROM revision WHERE rev_page = $pageid ".
206 "ORDER BY rev_text_id DESC LIMIT 1 OFFSET 1)";
207 $this->db->doQuery($SQL);
208 return true;
211 function updateTitle( $id, $title ) {
212 return true;
215 } ## end of the SearchPostgres class
218 * @ingroup Search
220 class PostgresSearchResult extends SearchResult {
221 function PostgresSearchResult( $row ) {
222 $this->mTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
223 $this->score = $row->score;
225 function getScore() {
226 return $this->score;
231 * @ingroup Search
233 class PostgresSearchResultSet extends SearchResultSet {
234 function PostgresSearchResultSet( $resultSet, $terms ) {
235 $this->mResultSet = $resultSet;
236 $this->mTerms = $terms;
239 function termMatches() {
240 return $this->mTerms;
243 function numRows() {
244 return $this->mResultSet->numRows();
247 function next() {
248 $row = $this->mResultSet->fetchObject();
249 if( $row === false ) {
250 return false;
251 } else {
252 return new PostgresSearchResult( $row );