Merge "Allow for time-limited tokens"
[lhc/web/wiklou.git] / includes / PrefixSearch.php
1 <?php
2 /**
3 * Prefix search of page names.
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 * @file
21 */
22
23 /**
24 * Handles searching prefixes of titles and finding any page
25 * names that match. Used largely by the OpenSearch implementation.
26 *
27 * @ingroup Search
28 */
29 abstract class PrefixSearch {
30 /**
31 * Do a prefix search of titles and return a list of matching page names.
32 * @deprecated Since 1.23, use TitlePrefixSearch or StringPrefixSearch classes
33 *
34 * @param string $search
35 * @param int $limit
36 * @param array $namespaces Used if query is not explicitly prefixed
37 * @return array Array of strings
38 */
39 public static function titleSearch( $search, $limit, $namespaces = array() ) {
40 $prefixSearch = new StringPrefixSearch;
41 return $prefixSearch->search( $search, $limit, $namespaces );
42 }
43
44 /**
45 * Do a prefix search of titles and return a list of matching page names.
46 *
47 * @param string $search
48 * @param int $limit
49 * @param array $namespaces Used if query is not explicitly prefixed
50 * @return array Array of strings or Title objects
51 */
52 public function search( $search, $limit, $namespaces = array() ) {
53 $search = trim( $search );
54 if ( $search == '' ) {
55 return array(); // Return empty result
56 }
57 $namespaces = $this->validateNamespaces( $namespaces );
58
59 // Find a Title which is not an interwiki and is in NS_MAIN
60 $title = Title::newFromText( $search );
61 if ( $title && !$title->isExternal() ) {
62 $ns = array( $title->getNamespace() );
63 if ( $ns[0] == NS_MAIN ) {
64 $ns = $namespaces; // no explicit prefix, use default namespaces
65 }
66 return $this->searchBackend( $ns, $title->getText(), $limit );
67 }
68
69 // Is this a namespace prefix?
70 $title = Title::newFromText( $search . 'Dummy' );
71 if ( $title && $title->getText() == 'Dummy'
72 && $title->getNamespace() != NS_MAIN
73 && !$title->isExternal() )
74 {
75 $namespaces = array( $title->getNamespace() );
76 $search = '';
77 }
78
79 return $this->searchBackend( $namespaces, $search, $limit );
80 }
81
82 /**
83 * Do a prefix search for all possible variants of the prefix
84 * @param string $search
85 * @param int $limit
86 * @param array $namespaces
87 *
88 * @return array
89 */
90 public function searchWithVariants( $search, $limit, array $namespaces ) {
91 wfProfileIn( __METHOD__ );
92 $searches = $this->search( $search, $limit, $namespaces );
93
94 // if the content language has variants, try to retrieve fallback results
95 $fallbackLimit = $limit - count( $searches );
96 if ( $fallbackLimit > 0 ) {
97 global $wgContLang;
98
99 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
100 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), array( $search ) );
101
102 foreach ( $fallbackSearches as $fbs ) {
103 $fallbackSearchResult = $this->search( $fbs, $fallbackLimit, $namespaces );
104 $searches = array_merge( $searches, $fallbackSearchResult );
105 $fallbackLimit -= count( $fallbackSearchResult );
106
107 if ( $fallbackLimit == 0 ) {
108 break;
109 }
110 }
111 }
112 wfProfileOut( __METHOD__ );
113 return $searches;
114 }
115
116 /**
117 * When implemented in a descendant class, receives an array of Title objects and returns
118 * either an unmodified array or an array of strings corresponding to titles passed to it.
119 *
120 * @param array $titles
121 * @return array
122 */
123 abstract protected function titles( array $titles );
124
125 /**
126 * When implemented in a descendant class, receives an array of titles as strings and returns
127 * either an unmodified array or an array of Title objects corresponding to strings received.
128 *
129 * @param array $strings
130 *
131 * @return array
132 */
133 abstract protected function strings( array $strings );
134
135 /**
136 * Do a prefix search of titles and return a list of matching page names.
137 * @param array $namespaces
138 * @param string $search
139 * @param int $limit
140 * @return array Array of strings
141 */
142 protected function searchBackend( $namespaces, $search, $limit ) {
143 if ( count( $namespaces ) == 1 ) {
144 $ns = $namespaces[0];
145 if ( $ns == NS_MEDIA ) {
146 $namespaces = array( NS_FILE );
147 } elseif ( $ns == NS_SPECIAL ) {
148 return $this->titles( $this->specialSearch( $search, $limit ) );
149 }
150 }
151 $srchres = array();
152 if ( wfRunHooks( 'PrefixSearchBackend', array( $namespaces, $search, $limit, &$srchres ) ) ) {
153 return $this->titles( $this->defaultSearchBackend( $namespaces, $search, $limit ) );
154 } else {
155 // Default search backend does proper prefix searching, but custom backends
156 // may sort based on other algorythms that may cause the exact title match
157 // to not be in the results or be lower down the list.
158
159 // Pick namespace (based on PrefixSearch::defaultSearchBackend)
160 $ns = in_array( NS_MAIN, $namespaces ) ? NS_MAIN : $namespaces[0];
161 $t = Title::newFromText( $search, $ns );
162 if ( $t ) {
163 // If text is a valid title and is in the search results
164 $string = $t->getPrefixedText();
165 $key = array_search( $string, $srchres );
166 if ( $key !== false ) {
167 // Move it to the front
168 $cut = array_splice( $srchres, $key, 1 );
169 array_unshift( $srchres, $cut[0] );
170 } elseif ( $t->exists() ) {
171 // Add it in front
172 array_unshift( $srchres, $string );
173
174 if ( count( $srchres ) > $limit ) {
175 array_pop( $srchres );
176 }
177 }
178 }
179 }
180
181 return $this->strings( $srchres );
182 }
183
184 /**
185 * Prefix search special-case for Special: namespace.
186 *
187 * @param string $search Term
188 * @param int $limit Max number of items to return
189 * @return array
190 */
191 protected function specialSearch( $search, $limit ) {
192 global $wgContLang;
193
194 $searchParts = explode( '/', $search, 2 );
195 $searchKey = $searchParts[0];
196 $subpageSearch = isset( $searchParts[1] ) ? $searchParts[1] : null;
197
198 // Handle subpage search separately.
199 if ( $subpageSearch !== null ) {
200 // Try matching the full search string as a page name
201 $specialTitle = Title::makeTitleSafe( NS_SPECIAL, $searchKey );
202 if ( !$specialTitle ) {
203 return array();
204 }
205 $special = SpecialPageFactory::getPage( $specialTitle->getText() );
206 if ( $special ) {
207 $subpages = $special->prefixSearchSubpages( $subpageSearch, $limit );
208 return array_map( function ( $sub ) use ( $specialTitle ) {
209 return $specialTitle->getSubpage( $sub );
210 }, $subpages );
211 } else {
212 return array();
213 }
214 }
215
216 # normalize searchKey, so aliases with spaces can be found - bug 25675
217 $searchKey = str_replace( ' ', '_', $searchKey );
218 $searchKey = $wgContLang->caseFold( $searchKey );
219
220 // Unlike SpecialPage itself, we want the canonical forms of both
221 // canonical and alias title forms...
222 $keys = array();
223 foreach ( SpecialPageFactory::getNames() as $page ) {
224 $keys[$wgContLang->caseFold( $page )] = $page;
225 }
226
227 foreach ( $wgContLang->getSpecialPageAliases() as $page => $aliases ) {
228 if ( !in_array( $page, SpecialPageFactory::getNames() ) ) {# bug 20885
229 continue;
230 }
231
232 foreach ( $aliases as $alias ) {
233 $keys[$wgContLang->caseFold( $alias )] = $alias;
234 }
235 }
236 ksort( $keys );
237
238 $srchres = array();
239 foreach ( $keys as $pageKey => $page ) {
240 if ( $searchKey === '' || strpos( $pageKey, $searchKey ) === 0 ) {
241 // bug 27671: Don't use SpecialPage::getTitleFor() here because it
242 // localizes its input leading to searches for e.g. Special:All
243 // returning Spezial:MediaWiki-Systemnachrichten and returning
244 // Spezial:Alle_Seiten twice when $wgLanguageCode == 'de'
245 $srchres[] = Title::makeTitleSafe( NS_SPECIAL, $page );
246 }
247
248 if ( count( $srchres ) >= $limit ) {
249 break;
250 }
251 }
252
253 return $srchres;
254 }
255
256 /**
257 * Unless overridden by PrefixSearchBackend hook...
258 * This is case-sensitive (First character may
259 * be automatically capitalized by Title::secureAndSpit()
260 * later on depending on $wgCapitalLinks)
261 *
262 * @param array $namespaces Namespaces to search in
263 * @param string $search Term
264 * @param int $limit Max number of items to return
265 * @return array Array of Title objects
266 */
267 protected function defaultSearchBackend( $namespaces, $search, $limit ) {
268 $ns = array_shift( $namespaces ); // support only one namespace
269 if ( in_array( NS_MAIN, $namespaces ) ) {
270 $ns = NS_MAIN; // if searching on many always default to main
271 }
272
273 $t = Title::newFromText( $search, $ns );
274 $prefix = $t ? $t->getDBkey() : '';
275 $dbr = wfGetDB( DB_SLAVE );
276 $res = $dbr->select( 'page',
277 array( 'page_id', 'page_namespace', 'page_title' ),
278 array(
279 'page_namespace' => $ns,
280 'page_title ' . $dbr->buildLike( $prefix, $dbr->anyString() )
281 ),
282 __METHOD__,
283 array( 'LIMIT' => $limit, 'ORDER BY' => 'page_title' )
284 );
285 $srchres = array();
286 foreach ( $res as $row ) {
287 $srchres[] = Title::newFromRow( $row );
288 }
289 return $srchres;
290 }
291
292 /**
293 * Validate an array of numerical namespace indexes
294 *
295 * @param array $namespaces
296 * @return array (default: contains only NS_MAIN)
297 */
298 protected function validateNamespaces( $namespaces ) {
299 global $wgContLang;
300
301 // We will look at each given namespace against wgContLang namespaces
302 $validNamespaces = $wgContLang->getNamespaces();
303 if ( is_array( $namespaces ) && count( $namespaces ) > 0 ) {
304 $valid = array();
305 foreach ( $namespaces as $ns ) {
306 if ( is_numeric( $ns ) && array_key_exists( $ns, $validNamespaces ) ) {
307 $valid[] = $ns;
308 }
309 }
310 if ( count( $valid ) > 0 ) {
311 return $valid;
312 }
313 }
314
315 return array( NS_MAIN );
316 }
317 }
318
319 /**
320 * Performs prefix search, returning Title objects
321 * @ingroup Search
322 */
323 class TitlePrefixSearch extends PrefixSearch {
324
325 protected function titles( array $titles ) {
326 return $titles;
327 }
328
329 protected function strings( array $strings ) {
330 $titles = array_map( 'Title::newFromText', $strings );
331 $lb = new LinkBatch( $titles );
332 $lb->setCaller( __METHOD__ );
333 $lb->execute();
334 return $titles;
335 }
336 }
337
338 /**
339 * Performs prefix search, returning strings
340 * @ingroup Search
341 */
342 class StringPrefixSearch extends PrefixSearch {
343
344 protected function titles( array $titles ) {
345 return array_map( function ( Title $t ) {
346 return $t->getPrefixedText();
347 }, $titles );
348 }
349
350 protected function strings( array $strings ) {
351 return $strings;
352 }
353 }