MediaWiki master
PrefixSearch.php
Go to the documentation of this file.
1<?php
31
40abstract class PrefixSearch {
50 public function search( $search, $limit, $namespaces = [], $offset = 0 ) {
51 $search = trim( $search );
52 if ( $search == '' ) {
53 return []; // Return empty result
54 }
55
56 $hasNamespace = SearchEngine::parseNamespacePrefixes( $search, false, true );
57 if ( $hasNamespace !== false ) {
58 [ $search, $namespaces ] = $hasNamespace;
59 }
60
61 return $this->searchBackend( $namespaces, $search, $limit, $offset );
62 }
63
73 public function searchWithVariants( $search, $limit, array $namespaces, $offset = 0 ) {
74 $searches = $this->search( $search, $limit, $namespaces, $offset );
75
76 // if the content language has variants, try to retrieve fallback results
77 $fallbackLimit = $limit - count( $searches );
78 if ( $fallbackLimit > 0 ) {
79 $services = MediaWikiServices::getInstance();
80 $fallbackSearches = $services->getLanguageConverterFactory()
81 ->getLanguageConverter( $services->getContentLanguage() )
82 ->autoConvertToAllVariants( $search );
83 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
84
85 foreach ( $fallbackSearches as $fbs ) {
86 $fallbackSearchResult = $this->search( $fbs, $fallbackLimit, $namespaces );
87 $searches = array_merge( $searches, $fallbackSearchResult );
88 $fallbackLimit -= count( $fallbackSearchResult );
89
90 if ( $fallbackLimit == 0 ) {
91 break;
92 }
93 }
94 }
95 return $searches;
96 }
97
105 abstract protected function titles( array $titles );
106
114 abstract protected function strings( array $strings );
115
124 protected function searchBackend( $namespaces, $search, $limit, $offset ) {
125 if ( count( $namespaces ) == 1 ) {
126 $ns = $namespaces[0];
127 if ( $ns == NS_MEDIA ) {
128 $namespaces = [ NS_FILE ];
129 } elseif ( $ns == NS_SPECIAL ) {
130 return $this->titles( $this->specialSearch( $search, $limit, $offset ) );
131 }
132 }
133 $srchres = [];
134 if ( ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onPrefixSearchBackend(
135 $namespaces, $search, $limit, $srchres, $offset )
136 ) {
137 return $this->titles( $this->defaultSearchBackend( $namespaces, $search, $limit, $offset ) );
138 }
139 return $this->strings(
140 $this->handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) );
141 }
142
143 private function handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) {
144 if ( $offset === 0 ) {
145 // Only perform exact db match if offset === 0
146 // This is still far from perfect but at least we avoid returning the
147 // same title again and again when the user is scrolling with a query
148 // that matches a title in the db.
149 $rescorer = new SearchExactMatchRescorer();
150 $srchres = $rescorer->rescore( $search, $namespaces, $srchres, $limit );
151 }
152 return $srchres;
153 }
154
163 protected function specialSearch( $search, $limit, $offset ) {
164 $searchParts = explode( '/', $search, 2 );
165 $searchKey = $searchParts[0];
166 $subpageSearch = $searchParts[1] ?? null;
167
168 // Handle subpage search separately.
169 $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
170 if ( $subpageSearch !== null ) {
171 // Try matching the full search string as a page name
172 $specialTitle = Title::makeTitleSafe( NS_SPECIAL, $searchKey );
173 if ( !$specialTitle ) {
174 return [];
175 }
176 $special = $spFactory->getPage( $specialTitle->getText() );
177 if ( $special ) {
178 $subpages = $special->prefixSearchSubpages( $subpageSearch, $limit, $offset );
179 return array_map( [ $specialTitle, 'getSubpage' ], $subpages );
180 } else {
181 return [];
182 }
183 }
184
185 # normalize searchKey, so aliases with spaces can be found - T27675
186 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
187 $searchKey = str_replace( ' ', '_', $searchKey );
188 $searchKey = $contLang->caseFold( $searchKey );
189
190 // Unlike SpecialPage itself, we want the canonical forms of both
191 // canonical and alias title forms...
192 $keys = [];
193 foreach ( $spFactory->getNames() as $page ) {
194 $keys[$contLang->caseFold( $page )] = [ 'page' => $page, 'rank' => 0 ];
195 }
196
197 foreach ( $contLang->getSpecialPageAliases() as $page => $aliases ) {
198 if ( !in_array( $page, $spFactory->getNames() ) ) {# T22885
199 continue;
200 }
201
202 foreach ( $aliases as $key => $alias ) {
203 $keys[$contLang->caseFold( $alias )] = [ 'page' => $alias, 'rank' => $key ];
204 }
205 }
206 ksort( $keys );
207
208 $matches = [];
209 foreach ( $keys as $pageKey => $page ) {
210 if ( $searchKey === '' || strpos( $pageKey, $searchKey ) === 0 ) {
211 // T29671: Don't use SpecialPage::getTitleFor() here because it
212 // localizes its input leading to searches for e.g. Special:All
213 // returning Spezial:MediaWiki-Systemnachrichten and returning
214 // Spezial:Alle_Seiten twice when $wgLanguageCode == 'de'
215 $matches[$page['rank']][] = Title::makeTitleSafe( NS_SPECIAL, $page['page'] );
216
217 if ( isset( $matches[0] ) && count( $matches[0] ) >= $limit + $offset ) {
218 // We have enough items in primary rank, no use to continue
219 break;
220 }
221 }
222
223 }
224
225 // Ensure keys are in order
226 ksort( $matches );
227 // Flatten the array
228 $matches = array_reduce( $matches, 'array_merge', [] );
229
230 return array_slice( $matches, $offset, $limit );
231 }
232
245 public function defaultSearchBackend( $namespaces, $search, $limit, $offset ) {
246 if ( !$namespaces ) {
247 $namespaces = [ NS_MAIN ];
248 }
249
250 if ( in_array( NS_SPECIAL, $namespaces ) ) {
251 // For now, if special is included, ignore the other namespaces
252 return $this->specialSearch( $search, $limit, $offset );
253 }
254
255 // Construct suitable prefix for each namespace. They differ in cases where
256 // some namespaces always capitalize and some don't.
257 $prefixes = [];
258 // Allow to do a prefix search for e.g. "Talk:"
259 if ( $search === '' ) {
260 $prefixes[$search] = $namespaces;
261 } else {
262 // Don't just ignore input like "[[Foo]]", but try to search for "Foo"
263 $search = preg_replace( MediaWikiTitleCodec::getTitleInvalidRegex(), '', $search );
264 foreach ( $namespaces as $namespace ) {
265 $title = Title::makeTitleSafe( $namespace, $search );
266 if ( $title ) {
267 $prefixes[ $title->getDBkey() ][] = $namespace;
268 }
269 }
270 }
271 if ( !$prefixes ) {
272 return [];
273 }
274
275 $services = MediaWikiServices::getInstance();
276 $dbr = $services->getConnectionProvider()->getReplicaDatabase();
277 // Often there is only one prefix that applies to all requested namespaces,
278 // but sometimes there are two if some namespaces do not always capitalize.
279 $conds = [];
280 foreach ( $prefixes as $prefix => $namespaces ) {
281 $condition = [ $dbr->expr( 'page_namespace', '=', $namespaces ) ];
282 if ( $prefix !== '' ) {
283 $condition[] = $dbr->expr(
284 'page_title',
285 IExpression::LIKE,
286 new LikeValue( $prefix, $dbr->anyString() )
287 );
288 }
289 $conds[] = new AndExpressionGroup( ...$condition );
290 }
291
292 $queryBuilder = $dbr->newSelectQueryBuilder()
293 ->select( [ 'page_id', 'page_namespace', 'page_title' ] )
294 ->from( 'page' )
295 ->where( new OrExpressionGroup( ...$conds ) )
296 ->orderBy( [ 'page_title', 'page_namespace' ] )
297 ->limit( $limit )
298 ->offset( $offset );
299 $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
300
301 return iterator_to_array( $services->getTitleFactory()->newTitleArrayFromResult( $res ) );
302 }
303}
const NS_FILE
Definition Defines.php:70
const NS_MAIN
Definition Defines.php:64
const NS_SPECIAL
Definition Defines.php:53
const NS_MEDIA
Definition Defines.php:52
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Service locator for MediaWiki core services.
A codec for MediaWiki page titles.
Represents a title within MediaWiki.
Definition Title.php:78
Handles searching prefixes of titles and finding any page names that match.
searchWithVariants( $search, $limit, array $namespaces, $offset=0)
Do a prefix search for all possible variants of the prefix.
search( $search, $limit, $namespaces=[], $offset=0)
Do a prefix search of titles and return a list of matching page names.
specialSearch( $search, $limit, $offset)
Prefix search special-case for Special: namespace.
titles(array $titles)
When implemented in a descendant class, receives an array of Title objects and returns either an unmo...
defaultSearchBackend( $namespaces, $search, $limit, $offset)
Unless overridden by PrefixSearchBackend hook... This is case-sensitive (First character may be autom...
strings(array $strings)
When implemented in a descendant class, receives an array of titles as strings and returns either an ...
searchBackend( $namespaces, $search, $limit, $offset)
Do a prefix search of titles and return a list of matching page names.
An utility class to rescore search results by looking for an exact match in the db and add the page f...
Representing a group of expressions chained via AND.
Content of like value.
Definition LikeValue.php:14
Representing a group of expressions chained via OR.