Defer populating searchTerms until later on - allows for better highlighting.
[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 if( preg_match_all('/([-!]?)(\S+)\s*/', $term, $m, PREG_SET_ORDER ) ) {
68 foreach( $m as $terms ) {
69 if (strlen($terms[1])) {
70 $searchstring .= ' & !';
71 }
72 if (strtolower($terms[2]) === 'and') {
73 $searchstring .= ' & ';
74 }
75 else if (strtolower($terms[2]) === 'or' or $terms[2] === '|') {
76 $searchstring .= ' | ';
77 }
78 else if (strtolower($terms[2]) === 'not') {
79 $searchstring .= ' & !';
80 }
81 else {
82 $searchstring .= " & $terms[2]";
83 }
84 }
85 }
86
87 ## Strip out leading junk
88 $searchstring = preg_replace('/^[\s\&\|]+/', '', $searchstring);
89
90 ## Remove any doubled-up operators
91 $searchstring = preg_replace('/([\!\&\|]) +(?:[\&\|] +)+/', "$1 ", $searchstring);
92
93 ## Remove any non-spaced operators (e.g. "Zounds!")
94 $searchstring = preg_replace('/([^ ])[\!\&\|]/', "$1", $searchstring);
95
96 ## Remove any trailing whitespace or operators
97 $searchstring = preg_replace('/[\s\!\&\|]+$/', '', $searchstring);
98
99 ## Remove unnecessary quotes around everything
100 $searchstring = preg_replace('/^[\'"](.*)[\'"]$/', "$1", $searchstring);
101
102 ## Quote the whole thing
103 $searchstring = $this->db->addQuotes($searchstring);
104
105 wfDebug( "parseQuery returned: $searchstring" );
106
107 return $searchstring;
108
109 }
110
111 /**
112 * Construct the full SQL query to do the search.
113 * @param string $filteredTerm
114 * @param string $fulltext
115 * @private
116 */
117 function searchQuery( $term, $fulltext, $colname ) {
118
119 $searchstring = $this->parseQuery( $term );
120
121 ## We need a separate query here so gin does not complain about empty searches
122 $SQL = "SELECT to_tsquery('default',$searchstring)";
123 $res = $this->db->doQuery($SQL);
124 if (!$res) {
125 ## TODO: Better output (example to catch: one 'two)
126 die ("Sorry, that was not a valid search string. Please go back and try again");
127 }
128 $top = pg_fetch_result($res,0,0);
129
130 if ($top === "") { ## e.g. if only stopwords are used XXX return something better
131 $query = "SELECT page_id, page_namespace, page_title, 0 AS score ".
132 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
133 "AND r.rev_text_id = c.old_id AND 1=0";
134 }
135 else {
136 $m = array();
137 if( preg_match_all("/'([^']+)'/", $top, $m, PREG_SET_ORDER ) ) {
138 foreach( $m as $terms ) {
139 $this->searchTerms[$terms[1]] = $terms[1];
140 }
141 }
142
143 $query = "SELECT page_id, page_namespace, page_title, ".
144 "rank($fulltext, to_tsquery('default',$searchstring),5) AS score ".
145 "FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
146 "AND r.rev_text_id = c.old_id AND $fulltext @@ to_tsquery('default',$searchstring)";
147 }
148
149 ## Redirects
150 if (! $this->showRedirects)
151 $query .= ' AND page_is_redirect = 0'; ## IS FALSE
152
153 ## Namespaces - defaults to 0
154 if ( count($this->namespaces) < 1)
155 $query .= ' AND page_namespace = 0';
156 else {
157 $namespaces = implode( ',', $this->namespaces );
158 $query .= " AND page_namespace IN ($namespaces)";
159 }
160
161 $query .= " ORDER BY score DESC, page_id DESC";
162
163 $query .= $this->db->limitResult( '', $this->limit, $this->offset );
164
165 wfDebug( "searchQuery returned: $query" );
166
167 return $query;
168 }
169
170 ## Most of the work of these two functions are done automatically via triggers
171
172 function update( $pageid, $title, $text ) {
173 ## We don't want to index older revisions
174 $SQL = "UPDATE pagecontent SET textvector = NULL WHERE old_id = ".
175 "(SELECT rev_text_id FROM revision WHERE rev_page = $pageid ".
176 "ORDER BY rev_text_id DESC LIMIT 1 OFFSET 1)";
177 $this->db->doQuery($SQL);
178 return true;
179 }
180
181 function updateTitle( $id, $title ) {
182 return true;
183 }
184
185 } ## end of the SearchPostgres class
186
187 /**
188 * @addtogroup Search
189 */
190 class PostgresSearchResult extends SearchResult {
191 function PostgresSearchResult( $row ) {
192 $this->mTitle = Title::makeTitle( $row->page_namespace, $row->page_title );
193 $this->score = $row->score;
194 }
195 function getScore() {
196 return $this->score;
197 }
198 }
199
200 /**
201 * @addtogroup Search
202 */
203 class PostgresSearchResultSet extends SearchResultSet {
204 function PostgresSearchResultSet( $resultSet, $terms ) {
205 $this->mResultSet = $resultSet;
206 $this->mTerms = $terms;
207 }
208
209 function termMatches() {
210 return $this->mTerms;
211 }
212
213 function numRows() {
214 return $this->mResultSet->numRows();
215 }
216
217 function next() {
218 $row = $this->mResultSet->fetchObject();
219 if( $row === false ) {
220 return false;
221 } else {
222 return new PostgresSearchResult( $row );
223 }
224 }
225 }
226
227
228 ?>