Make Postgres 8.3 compatible.
[lhc/web/wiklou.git] / includes / SearchPostgres.php
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 /**
21 * Search engine hook base class for Postgres
22 * @addtogroup Search
23 */
24 class SearchPostgres extends SearchEngine {
25
26 function SearchPostgres( $db ) {
27 $this->db = $db;
28 }
29
30 /**
31 * Perform a full text search query via tsearch2 and return a result set.
32 * Currently searches a page's current title (page.page_title) and
33 * latest revision article text (pagecontent.old_text)
34 *
35 * @param string $term - Raw search term
36 * @return PostgresSearchResultSet
37 * @access public
38 */
39 function searchTitle( $term ) {
40 $resultSet = $this->db->resultObject( $this->db->query( $this->searchQuery( $term , 'titlevector', 'page_title' )));
41 return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
42 }
43 function searchText( $term ) {
44 $resultSet = $this->db->resultObject( $this->db->query( $this->searchQuery( $term, 'textvector', 'old_text' )));
45 return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
46 }
47
48
49 /*
50 * Transform the user's search string into a better form for tsearch2
51 */
52 function parseQuery( $term ) {
53
54 wfDebug( "parseQuery received: $term" );
55
56 ## No backslashes allowed
57 $term = preg_replace('/\\\/', '', $term);
58
59 ## Collapse parens into nearby words:
60 $term = preg_replace('/\s*\(\s*/', ' (', $term);
61 $term = preg_replace('/\s*\)\s*/', ') ', $term);
62
63 ## Treat colons as word separators:
64 $term = preg_replace('/:/', ' ', $term);
65
66 $searchstring = '';
67 $m = array();
68 if( preg_match_all('/([-!]?)(\S+)\s*/', $term, $m, PREG_SET_ORDER ) ) {
69 foreach( $m as $terms ) {
70 if (strlen($terms[1])) {
71 $searchstring .= ' & !';
72 }
73 if (strtolower($terms[2]) === 'and') {
74 $searchstring .= ' & ';
75 }
76 else if (strtolower($terms[2]) === 'or' or $terms[2] === '|') {
77 $searchstring .= ' | ';
78 }
79 else if (strtolower($terms[2]) === 'not') {
80 $searchstring .= ' & !';
81 }
82 else {
83 $searchstring .= " & $terms[2]";
84 }
85 }
86 }
87
88 ## Strip out leading junk
89 $searchstring = preg_replace('/^[\s\&\|]+/', '', $searchstring);
90
91 ## Remove any doubled-up operators
92 $searchstring = preg_replace('/([\!\&\|]) +(?:[\&\|] +)+/', "$1 ", $searchstring);
93
94 ## Remove any non-spaced operators (e.g. "Zounds!")
95 $searchstring = preg_replace('/([^ ])[\!\&\|]/', "$1", $searchstring);
96
97 ## Remove any trailing whitespace or operators
98 $searchstring = preg_replace('/[\s\!\&\|]+$/', '', $searchstring);
99
100 ## Remove unnecessary quotes around everything
101 $searchstring = preg_replace('/^[\'"](.*)[\'"]$/', "$1", $searchstring);
102
103 ## Quote the whole thing
104 $searchstring = $this->db->addQuotes($searchstring);
105
106 wfDebug( "parseQuery returned: $searchstring" );
107
108 return $searchstring;
109
110 }
111
112 /**
113 * Construct the full SQL query to do the search.
114 * @param string $filteredTerm
115 * @param string $fulltext
116 * @private
117 */
118 function searchQuery( $term, $fulltext, $colname ) {
119 global $wgDBversion;
120
121 if ( !isset( $wgDBversion ) ) {
122 $this->db->getServerVersion();
123 $wgDBversion = $this->db->numeric_version;
124 }
125 $prefix = $wgDBversion < 8.3 ? "'default'," : '';
126
127 $searchstring = $this->parseQuery( $term );
128
129 ## We need a separate query here so gin does not complain about empty searches
130 $SQL = "SELECT to_tsquery($prefix $searchstring)";
131 $res = $this->db->doQuery($SQL);
132 if (!$res) {
133 ## TODO: Better output (example to catch: one 'two)
134 die ("Sorry, that was not a valid search string. Please go back and try again");
135 }
136 $top = pg_fetch_result($res,0,0);
137
138 if ($top === "") { ## e.g. if only stopwords are used XXX return something better
139 $query = "SELECT page_id, page_namespace, page_title, 0 AS score ".
140 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
141 "AND r.rev_text_id = c.old_id AND 1=0";
142 }
143 else {
144 $m = array();
145 if( preg_match_all("/'([^']+)'/", $top, $m, PREG_SET_ORDER ) ) {
146 foreach( $m as $terms ) {
147 $this->searchTerms[$terms[1]] = $terms[1];
148 }
149 }
150
151 $rankscore = $wgDBversion > 8.2 ? 5 : 1;
152 $rank = $wgDBversion < 8.3 ? 'rank' : 'ts_rank';
153 $query = "SELECT page_id, page_namespace, page_title, ".
154 "$rank($fulltext, to_tsquery($prefix $searchstring), $rankscore) AS score ".
155 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
156 "AND r.rev_text_id = c.old_id AND $fulltext @@ to_tsquery($prefix $searchstring)";
157 }
158
159 ## Redirects
160 if (! $this->showRedirects)
161 $query .= ' AND page_is_redirect = 0::char'; ## IS FALSE
162
163 ## Namespaces - defaults to 0
164 if ( count($this->namespaces) < 1)
165 $query .= ' AND page_namespace = 0';
166 else {
167 $namespaces = implode( ',', $this->namespaces );
168 $query .= " AND page_namespace IN ($namespaces)";
169 }
170
171 $query .= " ORDER BY score DESC, page_id DESC";
172
173 $query .= $this->db->limitResult( '', $this->limit, $this->offset );
174
175 wfDebug( "searchQuery returned: $query" );
176
177 return $query;
178 }
179
180 ## Most of the work of these two functions are done automatically via triggers
181
182 function update( $pageid, $title, $text ) {
183 ## We don't want to index older revisions
184 $SQL = "UPDATE pagecontent SET textvector = NULL WHERE old_id = ".
185 "(SELECT rev_text_id FROM revision WHERE rev_page = $pageid ".
186 "ORDER BY rev_text_id DESC LIMIT 1 OFFSET 1)";
187 $this->db->doQuery($SQL);
188 return true;
189 }
190
191 function updateTitle( $id, $title ) {
192 return true;
193 }
194
195 } ## end of the SearchPostgres class
196
197 /**
198 * @addtogroup Search
199 */
200 class PostgresSearchResult extends SearchResult {
201 function PostgresSearchResult( $row ) {
202 $this->mTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
203 $this->score = $row->score;
204 }
205 function getScore() {
206 return $this->score;
207 }
208 }
209
210 /**
211 * @addtogroup Search
212 */
213 class PostgresSearchResultSet extends SearchResultSet {
214 function PostgresSearchResultSet( $resultSet, $terms ) {
215 $this->mResultSet = $resultSet;
216 $this->mTerms = $terms;
217 }
218
219 function termMatches() {
220 return $this->mTerms;
221 }
222
223 function numRows() {
224 return $this->mResultSet->numRows();
225 }
226
227 function next() {
228 $row = $this->mResultSet->fetchObject();
229 if( $row === false ) {
230 return false;
231 } else {
232 return new PostgresSearchResult( $row );
233 }
234 }
235 }
236
237
238