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