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