aboutsummaryrefslogtreecommitdiffstats
path: root/includes/Rest/Handler/SearchHandler.php
blob: ba2f6f2bc129dcb7efd449aec91597e2c79e41b3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
<?php

namespace MediaWiki\Rest\Handler;

use InvalidArgumentException;
use ISearchResultSet;
use MediaWiki\Cache\CacheKeyHelper;
use MediaWiki\Config\Config;
use MediaWiki\MainConfigNames;
use MediaWiki\Page\PageIdentity;
use MediaWiki\Page\PageStore;
use MediaWiki\Page\RedirectLookup;
use MediaWiki\Permissions\PermissionManager;
use MediaWiki\Rest\Handler;
use MediaWiki\Rest\Handler\Helper\RestStatusTrait;
use MediaWiki\Rest\LocalizedHttpException;
use MediaWiki\Rest\Response;
use MediaWiki\Search\Entity\SearchResultThumbnail;
use MediaWiki\Search\SearchResultThumbnailProvider;
use MediaWiki\Title\TitleFormatter;
use SearchEngine;
use SearchEngineConfig;
use SearchEngineFactory;
use SearchResult;
use SearchSuggestion;
use StatusValue;
use Wikimedia\Message\MessageValue;
use Wikimedia\ParamValidator\ParamValidator;
use Wikimedia\ParamValidator\TypeDef\IntegerDef;

/**
 * Handler class for Core REST API endpoint that handles basic search
 */
class SearchHandler extends Handler {
	use RestStatusTrait;

	private SearchEngineFactory $searchEngineFactory;
	private SearchEngineConfig $searchEngineConfig;
	private SearchResultThumbnailProvider $searchResultThumbnailProvider;
	private PermissionManager $permissionManager;
	private RedirectLookup $redirectLookup;
	private PageStore $pageStore;
	private TitleFormatter $titleFormatter;

	/**
	 * Search page body and titles.
	 */
	public const FULLTEXT_MODE = 'fulltext';

	/**
	 * Search title completion matches.
	 */
	public const COMPLETION_MODE = 'completion';

	/**
	 * Supported modes
	 */
	private const SUPPORTED_MODES = [ self::FULLTEXT_MODE, self::COMPLETION_MODE ];

	/**
	 * @var string
	 */
	private $mode = null;

	/** Limit results to 50 pages by default */
	private const LIMIT = 50;

	/** Hard limit results to 100 pages */
	private const MAX_LIMIT = 100;

	/** Default to first page */
	private const OFFSET = 0;

	/**
	 * Expiry time for use as max-age value in the cache-control header
	 * of completion search responses.
	 * @see $wgSearchSuggestCacheExpiry
	 * @var int|null
	 */
	private $completionCacheExpiry;

	public function __construct(
		Config $config,
		SearchEngineFactory $searchEngineFactory,
		SearchEngineConfig $searchEngineConfig,
		SearchResultThumbnailProvider $searchResultThumbnailProvider,
		PermissionManager $permissionManager,
		RedirectLookup $redirectLookup,
		PageStore $pageStore,
		TitleFormatter $titleFormatter
	) {
		$this->searchEngineFactory = $searchEngineFactory;
		$this->searchEngineConfig = $searchEngineConfig;
		$this->searchResultThumbnailProvider = $searchResultThumbnailProvider;
		$this->permissionManager = $permissionManager;
		$this->redirectLookup = $redirectLookup;
		$this->pageStore = $pageStore;
		$this->titleFormatter = $titleFormatter;

		// @todo Avoid injecting the entire config, see T246377
		$this->completionCacheExpiry = $config->get( MainConfigNames::SearchSuggestCacheExpiry );
	}

	protected function postInitSetup() {
		$this->mode = $this->getConfig()['mode'] ?? self::FULLTEXT_MODE;

		if ( !in_array( $this->mode, self::SUPPORTED_MODES ) ) {
			throw new InvalidArgumentException(
				"Unsupported search mode `{$this->mode}` configured. Supported modes: " .
				implode( ', ', self::SUPPORTED_MODES )
			);
		}
	}

	/**
	 * @return SearchEngine
	 */
	private function createSearchEngine() {
		$limit = $this->getValidatedParams()['limit'];

		$searchEngine = $this->searchEngineFactory->create();
		$searchEngine->setNamespaces( $this->searchEngineConfig->defaultNamespaces() );
		$searchEngine->setLimitOffset( $limit, self::OFFSET );
		return $searchEngine;
	}

	public function needsWriteAccess() {
		return false;
	}

	/**
	 * Get SearchResults when results are either SearchResultSet or Status objects
	 * @param ISearchResultSet|StatusValue|null $results
	 * @return SearchResult[]
	 * @throws LocalizedHttpException
	 */
	private function getSearchResultsOrThrow( $results ) {
		if ( $results ) {
			if ( $results instanceof StatusValue ) {
				$status = $results;
				if ( !$status->isOK() ) {
					if ( $status->getMessages( 'error' ) ) { // Only throw for errors, suppress warnings (for now)
						$this->throwExceptionForStatus( $status, 'rest-search-error', 500 );
					}
				}
				$statusValue = $status->getValue();
				if ( $statusValue instanceof ISearchResultSet ) {
					return $statusValue->extractResults();
				}
			} else {
				return $results->extractResults();
			}
		}
		return [];
	}

	/**
	 * Execute search and return info about pages for further processing.
	 *
	 * @param SearchEngine $searchEngine
	 * @return array[]
	 * @throws LocalizedHttpException
	 */
	private function doSearch( $searchEngine ) {
		$query = $this->getValidatedParams()['q'];

		if ( $this->mode == self::COMPLETION_MODE ) {
			$completionSearch = $searchEngine->completionSearchWithVariants( $query );
			return $this->buildPageObjects( $completionSearch->getSuggestions() );
		} else {
			$titleSearch = $searchEngine->searchTitle( $query );
			$textSearch = $searchEngine->searchText( $query );

			$titleSearchResults = $this->getSearchResultsOrThrow( $titleSearch );
			$textSearchResults = $this->getSearchResultsOrThrow( $textSearch );

			$mergedResults = array_merge( $titleSearchResults, $textSearchResults );
			return $this->buildPageObjects( $mergedResults );
		}
	}

	/**
	 * Build an array of pageInfo objects.
	 * @param SearchSuggestion[]|SearchResult[] $searchResponse
	 *
	 * @phpcs:ignore Generic.Files.LineLength
	 * @phan-return array{int:array{pageIdentity:PageIdentity,suggestion:?SearchSuggestion,result:?SearchResult,redirect:?PageIdentity}} $pageInfos
	 * @return array Associative array mapping pageID to pageInfo objects:
	 *   - pageIdentity: PageIdentity of page to return as the match
	 *   - suggestion: SearchSuggestion or null if $searchResponse is SearchResults[]
	 *   - result: SearchResult or null if $searchResponse is SearchSuggestions[]
	 *   - redirect: PageIdentity or null if the SearchResult|SearchSuggestion was not a redirect
	 */
	private function buildPageObjects( array $searchResponse ): array {
		$pageInfos = [];
		foreach ( $searchResponse as $response ) {
			$isSearchResult = $response instanceof SearchResult;
			if ( $isSearchResult ) {
				if ( $response->isBrokenTitle() || $response->isMissingRevision() ) {
					continue;
				}
				$title = $response->getTitle();
			} else {
				$title = $response->getSuggestedTitle();
			}
			$pageObj = $this->buildSinglePage( $title, $response );
			if ( $pageObj ) {
				$pageNsAndID = CacheKeyHelper::getKeyForPage( $pageObj['pageIdentity'] );
				// This handles the edge case where we have both the redirect source and redirect target page come back
				// in our search results. In such event, we prefer (and thus replace) with  the redirect target page.
				if ( isset( $pageInfos[$pageNsAndID] ) ) {
					if ( $pageInfos[$pageNsAndID]['redirect'] !== null ) {
						$pageInfos[$pageNsAndID]['result'] = $isSearchResult ? $response : null;
						$pageInfos[$pageNsAndID]['suggestion'] = $isSearchResult ? null : $response;
					}
					continue;
				}
				$pageInfos[$pageNsAndID] = $pageObj;
			}
		}
		return $pageInfos;
	}

	/**
	 * Build one pageInfo object from either a SearchResult or SearchSuggestion.
	 * @param PageIdentity $title
	 * @param SearchResult|SearchSuggestion $result
	 *
	 * @phpcs:ignore Generic.Files.LineLength
	 * @phan-return (false|array{pageIdentity:PageIdentity,suggestion:?SearchSuggestion,result:?SearchResult,redirect:?PageIdentity}) $pageInfos
	 * @return bool|array Objects representing a given page:
	 *   - pageIdentity: PageIdentity of page to return as the match
	 *   - suggestion: SearchSuggestion or null if $searchResponse is SearchResults
	 *   - result: SearchResult or null if $searchResponse is SearchSuggestions
	 *   - redirect: PageIdentity|null depending on if the SearchResult|SearchSuggestion was a redirect
	 */
	private function buildSinglePage( $title, $result ) {
		$redirectTarget = $title->canExist() ? $this->redirectLookup->getRedirectTarget( $title ) : null;
		// Our page has a redirect that is not in a virtual namespace and is not an interwiki link.
		// See T301346, T303352
		if ( $redirectTarget && $redirectTarget->getNamespace() > -1 && !$redirectTarget->isExternal() ) {
			$redirectSource = $title;
			$title = $this->pageStore->getPageForLink( $redirectTarget );
		} else {
			$redirectSource = null;
		}
		if ( !$title || !$this->getAuthority()->probablyCan( 'read', $title ) ) {
			return false;
		}
		return [
			'pageIdentity' => $title,
			'suggestion' => $result instanceof SearchSuggestion ? $result : null,
			'result' => $result instanceof SearchResult ? $result : null,
			'redirect' => $redirectSource
		];
	}

	/**
	 * Turn array of page info into serializable array with common information about the page
	 * @param array $pageInfos Page Info objects
	 * @param array $thumbsAndDesc Associative array mapping pageId to array of description and thumbnail
	 * @phpcs:ignore Generic.Files.LineLength
	 * @phan-param array<int,array{pageIdentity:PageIdentity,suggestion:SearchSuggestion,result:SearchResult,redirect:?PageIdentity}> $pageInfos
	 * @phan-param array<int,array{description:array,thumbnail:array}> $thumbsAndDesc
	 *
	 * @phpcs:ignore Generic.Files.LineLength
	 * @phan-return array<int,array{id:int,key:string,title:string,excerpt:?string,matched_title:?string, description:?array, thumbnail:?array}> $pages
	 * @return array[] of [ id, key, title, excerpt, matched_title ]
	 */
	private function buildResultFromPageInfos( array $pageInfos, array $thumbsAndDesc ): array {
		$pages = [];
		foreach ( $pageInfos as $pageInfo ) {
			[
				'pageIdentity' => $page,
				'suggestion' => $sugg,
				'result' => $result,
				'redirect' => $redirect
			] = $pageInfo;
			$excerpt = $sugg ? $sugg->getText() : $result->getTextSnippet();
			$id = ( $page instanceof PageIdentity && $page->canExist() ) ? $page->getId() : 0;
			$pages[] = [
				'id' => $id,
				'key' => $this->titleFormatter->getPrefixedDBkey( $page ),
				'title' => $this->titleFormatter->getPrefixedText( $page ),
				'excerpt' => $excerpt ?: null,
				'matched_title' => $redirect ? $this->titleFormatter->getPrefixedText( $redirect ) : null,
				'description' => $id > 0 ? $thumbsAndDesc[$id]['description'] : null,
				'thumbnail' => $id > 0 ? $thumbsAndDesc[$id]['thumbnail'] : null,
			];
		}
		return $pages;
	}

	/**
	 * Converts SearchResultThumbnail object into serializable array
	 *
	 * @param SearchResultThumbnail|null $thumbnail
	 *
	 * @return array|null
	 */
	private function serializeThumbnail( ?SearchResultThumbnail $thumbnail ): ?array {
		if ( $thumbnail == null ) {
			return null;
		}

		return [
			'mimetype' => $thumbnail->getMimeType(),
			'width' => $thumbnail->getWidth(),
			'height' => $thumbnail->getHeight(),
			'duration' => $thumbnail->getDuration(),
			'url' => $thumbnail->getUrl(),
		];
	}

	/**
	 * Turn page info into serializable array with description field for the page.
	 *
	 * The information about description should be provided by extension by implementing
	 * 'SearchResultProvideDescription' hook. Description is set to null if no extensions
	 * implement the hook.
	 * @param PageIdentity[] $pageIdentities
	 *
	 * @return array
	 */
	private function buildDescriptionsFromPageIdentities( array $pageIdentities ) {
		$descriptions = array_fill_keys( array_keys( $pageIdentities ), null );

		$this->getHookRunner()->onSearchResultProvideDescription( $pageIdentities, $descriptions );

		return array_map( static function ( $description ) {
			return [ 'description' => $description ];
		}, $descriptions );
	}

	/**
	 * Turn page info into serializable array with thumbnail information for the page.
	 *
	 * The information about thumbnail should be provided by extension by implementing
	 * 'SearchResultProvideThumbnail' hook. Thumbnail is set to null if no extensions implement
	 * the hook.
	 *
	 * @param PageIdentity[] $pageIdentities
	 *
	 * @return array
	 */
	private function buildThumbnailsFromPageIdentities( array $pageIdentities ) {
		$thumbnails = $this->searchResultThumbnailProvider->getThumbnails( $pageIdentities );
		$thumbnails += array_fill_keys( array_keys( $pageIdentities ), null );

		return array_map( function ( $thumbnail ) {
			return [ 'thumbnail' => $this->serializeThumbnail( $thumbnail ) ];
		}, $thumbnails );
	}

	/**
	 * @return Response
	 * @throws LocalizedHttpException
	 */
	public function execute() {
		$searchEngine = $this->createSearchEngine();
		$pageInfos = $this->doSearch( $searchEngine );

		// We can only pass validated "real" PageIdentities to our hook handlers below
		$pageIdentities = array_reduce(
			array_values( $pageInfos ),
			static function ( $realPages, $item ) {
				$page = $item['pageIdentity'];
				if ( $page instanceof PageIdentity && $page->exists() ) {
					$realPages[$item['pageIdentity']->getId()] = $item['pageIdentity'];
				}
				return $realPages;
			}, []
		);

		$descriptions = $this->buildDescriptionsFromPageIdentities( $pageIdentities );
		$thumbs = $this->buildThumbnailsFromPageIdentities( $pageIdentities );

		$thumbsAndDescriptions = [];
		foreach ( $descriptions as $pageId => $description ) {
			$thumbsAndDescriptions[$pageId] = $description + $thumbs[$pageId];
		}

		$result = $this->buildResultFromPageInfos( $pageInfos, $thumbsAndDescriptions );

		$response = $this->getResponseFactory()->createJson( [ 'pages' => $result ] );

		if ( $this->mode === self::COMPLETION_MODE && $this->completionCacheExpiry ) {
			// Type-ahead completion matches should be cached by the client and
			// in the CDN, especially for short prefixes.
			// See also $wgSearchSuggestCacheExpiry and ApiOpenSearch
			if ( $this->permissionManager->isEveryoneAllowed( 'read' ) ) {
				$response->setHeader( 'Cache-Control', 'public, max-age=' . $this->completionCacheExpiry );
			} else {
				$response->setHeader( 'Cache-Control', 'no-store, max-age=0' );
			}
		}

		return $response;
	}

	public function getParamSettings() {
		return [
			'q' => [
				self::PARAM_SOURCE => 'query',
				ParamValidator::PARAM_TYPE => 'string',
				ParamValidator::PARAM_REQUIRED => true,
				Handler::PARAM_DESCRIPTION => new MessageValue( 'rest-param-desc-search-q' ),
			],
			'limit' => [
				self::PARAM_SOURCE => 'query',
				ParamValidator::PARAM_TYPE => 'integer',
				ParamValidator::PARAM_REQUIRED => false,
				ParamValidator::PARAM_DEFAULT => self::LIMIT,
				IntegerDef::PARAM_MIN => 1,
				IntegerDef::PARAM_MAX => self::MAX_LIMIT,
				Handler::PARAM_DESCRIPTION => new MessageValue( 'rest-param-desc-search-limit' ),
			],
		];
	}

	public function getResponseBodySchemaFileName( string $method ): ?string {
		return 'includes/Rest/Handler/Schema/SearchResults.json';
	}
}