]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/SearchPostgres.php
MediaWiki 1.15.4-scripts
[autoinstalls/mediawiki.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  * @file
22  * @ingroup Search
23  */
24
25 /**
26  * Search engine hook base class for Postgres
27  * @ingroup Search
28  */
29 class SearchPostgres extends SearchEngine {
30
31         function __construct( $db ) {
32                 $this->db = $db;
33         }
34
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)
39          *
40          * @param string $term - Raw search term
41          * @return PostgresSearchResultSet
42          * @access public
43          */
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();
52                 }
53                 return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
54         }
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();
62                 }
63                 return new PostgresSearchResultSet( $resultSet, $this->searchTerms );
64         }
65
66
67         /*
68          * Transform the user's search string into a better form for tsearch2
69          * Returns an SQL fragment consisting of quoted text to search for.
70         */
71         function parseQuery( $term ) {
72
73                 wfDebug( "parseQuery received: $term \n" );
74
75                 ## No backslashes allowed
76                 $term = preg_replace('/\\\/', '', $term);
77
78                 ## Collapse parens into nearby words:
79                 $term = preg_replace('/\s*\(\s*/', ' (', $term);
80                 $term = preg_replace('/\s*\)\s*/', ') ', $term);
81
82                 ## Treat colons as word separators:
83                 $term = preg_replace('/:/', ' ', $term);
84
85                 $searchstring = '';
86                 $m = array();
87                 if( preg_match_all('/([-!]?)(\S+)\s*/', $term, $m, PREG_SET_ORDER ) ) {
88                         foreach( $m as $terms ) {
89                                 if (strlen($terms[1])) {
90                                         $searchstring .= ' & !';
91                                 }
92                                 if (strtolower($terms[2]) === 'and') {
93                                         $searchstring .= ' & ';
94                                 }
95                                 else if (strtolower($terms[2]) === 'or' or $terms[2] === '|') {
96                                         $searchstring .= ' | ';
97                                 }
98                                 else if (strtolower($terms[2]) === 'not') {
99                                         $searchstring .= ' & !';
100                                 }
101                                 else {
102                                         $searchstring .= " & $terms[2]";
103                                 }
104                         }
105                 }
106
107                 ## Strip out leading junk
108                 $searchstring = preg_replace('/^[\s\&\|]+/', '', $searchstring);
109
110                 ## Remove any doubled-up operators
111                 $searchstring = preg_replace('/([\!\&\|]) +(?:[\&\|] +)+/', "$1 ", $searchstring);
112
113                 ## Remove any non-spaced operators (e.g. "Zounds!")
114                 $searchstring = preg_replace('/([^ ])[\!\&\|]/', "$1", $searchstring);
115
116                 ## Remove any trailing whitespace or operators
117                 $searchstring = preg_replace('/[\s\!\&\|]+$/', '', $searchstring);
118
119                 ## Remove unnecessary quotes around everything
120                 $searchstring = preg_replace('/^[\'"](.*)[\'"]$/', "$1", $searchstring);
121
122                 ## Quote the whole thing
123                 $searchstring = $this->db->addQuotes($searchstring);
124
125                 wfDebug( "parseQuery returned: $searchstring \n" );
126
127                 return $searchstring;
128
129         }
130
131         /**
132          * Construct the full SQL query to do the search.
133          * @param string $filteredTerm
134          * @param string $fulltext
135          * @private
136          */
137         function searchQuery( $term, $fulltext, $colname ) {
138                 global $wgDBversion;
139
140                 if ( !isset( $wgDBversion ) ) {
141                         $this->db->getServerVersion();
142                         $wgDBversion = $this->db->numeric_version;
143                 }
144                 $prefix = $wgDBversion < 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 = $wgDBversion > 8.2 ? 5 : 1;
172                         $rank = $wgDBversion < 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 SearchResultSet {
236         function __construct( $resultSet, $terms ) {
237                 $this->mResultSet = $resultSet;
238                 $this->mTerms = $terms;
239         }
240
241         function termMatches() {
242                 return $this->mTerms;
243         }
244
245         function numRows() {
246                 return $this->mResultSet->numRows();
247         }
248
249         function next() {
250                 $row = $this->mResultSet->fetchObject();
251                 if( $row === false ) {
252                         return false;
253                 } else {
254                         return new PostgresSearchResult( $row );
255                 }
256         }
257 }