MediaWiki master
FullSearchResultWidget.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki\Search\SearchWidgets;
4
5use MediaWiki\Category\Category;
6use MediaWiki\FileRepo\File\File;
7use MediaWiki\FileRepo\RepoGroup;
8use MediaWiki\HookContainer\HookContainer;
9use MediaWiki\HookContainer\HookRunner;
10use MediaWiki\Html\Html;
11use MediaWiki\Linker\LinkRenderer;
12use MediaWiki\MainConfigNames;
13use MediaWiki\Media\MediaTransformOutput;
14use MediaWiki\Media\ThumbnailImage;
15use MediaWiki\Message\Message;
16use MediaWiki\Parser\Sanitizer;
17use MediaWiki\Search\Entity\SearchResultThumbnail;
18use MediaWiki\Search\SearchResult;
19use MediaWiki\Search\SearchResultThumbnailProvider;
20use MediaWiki\Specials\SpecialSearch;
21use MediaWiki\Title\Title;
22use MediaWiki\User\Options\UserOptionsManager;
23use Wikimedia\HtmlArmor\HtmlArmor;
24
33
34 public const THUMBNAIL_SIZE = 90;
35
38 private HookRunner $hookRunner;
39 private RepoGroup $repoGroup;
40 private SearchResultThumbnailProvider $thumbnailProvider;
41 private UserOptionsManager $userOptionsManager;
42
44 private $thumbnailPlaceholderHtml;
45
46 public function __construct(
49 HookContainer $hookContainer,
50 RepoGroup $repoGroup,
51 SearchResultThumbnailProvider $thumbnailProvider,
52 UserOptionsManager $userOptionsManager
53 ) {
54 $this->specialPage = $specialPage;
55 $this->linkRenderer = $linkRenderer;
56 $this->hookRunner = new HookRunner( $hookContainer );
57 $this->repoGroup = $repoGroup;
58 $this->thumbnailProvider = $thumbnailProvider;
59 $this->userOptionsManager = $userOptionsManager;
60 }
61
67 public function render( SearchResult $result, $position ) {
68 // If the page doesn't *exist*... our search index is out of date.
69 // The least confusing at this point is to drop the result.
70 // You may get less results, but... on well. :P
71 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
72 return '';
73 }
74
75 $link = $this->generateMainLinkHtml( $result, $position );
76 // If page content is not readable, just return ths title.
77 // This is not quite safe, but better than showing excerpts from
78 // non-readable pages. Note that hiding the entry entirely would
79 // screw up paging (really?).
80 if ( !$this->specialPage->getAuthority()->definitelyCan( 'read', $result->getTitle() ) ) {
81 return Html::rawElement( 'li', [], $link );
82 }
83
84 $redirect = $this->generateRedirectHtml( $result );
85 $section = $this->generateSectionHtml( $result );
86 $category = $this->generateCategoryHtml( $result );
87 $date = htmlspecialchars(
88 $this->specialPage->getLanguage()->userTimeAndDate(
89 $result->getTimestamp(),
90 $this->specialPage->getUser()
91 )
92 );
93 [ $file, $desc, $thumb ] = $this->generateFileHtml( $result );
94 $snippet = $result->getTextSnippet();
95 if ( $snippet ) {
96 $snippetWithEllipsis = $snippet . $this->specialPage->msg( 'ellipsis' );
97 $extract = Html::rawElement( 'div', [ 'class' => 'searchresult' ], $snippetWithEllipsis );
98 } else {
99 $extract = '';
100 }
101
102 if ( $result->getTitle() && $result->getTitle()->getNamespace() !== NS_FILE ) {
103 // If no file, then the description is about size
104 $desc = $this->generateSizeHtml( $result );
105
106 // Let hooks do their own final construction if desired.
107 // FIXME: Not sure why this is only for results without thumbnails,
108 // but keeping it as-is for now to prevent breaking hook consumers.
109 $html = null;
110 $score = '';
111 $related = '';
112 // TODO: remove this instanceof and always pass [], let implementers do the cast if
113 // they want to be SearchDatabase specific
114 $terms = $result instanceof \MediaWiki\Search\SqlSearchResult ? $result->getTermMatches() : [];
115 if ( !$this->hookRunner->onShowSearchHit( $this->specialPage, $result,
116 $terms, $link, $redirect, $section, $extract, $score,
117 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
118 $desc, $date, $related, $html )
119 ) {
120 return $html;
121 }
122 }
123
124 // All the pieces have been collected. Now generate the final HTML
125 $joined = "{$link} {$redirect} {$category} {$section} {$file}";
126 $meta = $this->buildMeta( $desc, $date );
127
128 // Text portion of the search result
129 $html = Html::rawElement(
130 'div',
131 [ 'class' => 'mw-search-result-heading' ],
132 $joined
133 );
134 $html .= $extract . ' ' . $meta;
135
136 // If the result has a thumbnail, place it next to the text block
137 if ( $thumb ) {
138 $gridCells = Html::rawElement(
139 'div',
140 [ 'class' => 'searchResultImage-thumbnail' ],
141 $thumb
142 ) . Html::rawElement(
143 'div',
144 [ 'class' => 'searchResultImage-text' ],
145 $html
146 );
147 $html = Html::rawElement(
148 'div',
149 [ 'class' => 'searchResultImage' ],
150 $gridCells
151 );
152 }
153
154 return Html::rawElement(
155 'li',
156 [ 'class' => [ 'mw-search-result', 'mw-search-result-ns-' . $result->getTitle()->getNamespace() ] ],
157 $html
158 );
159 }
160
171 protected function generateMainLinkHtml( SearchResult $result, $position ) {
172 $snippet = $result->getTitleSnippet();
173 if ( $snippet === '' ) {
174 $snippet = null;
175 } else {
176 $snippet = new HtmlArmor( $snippet );
177 }
178
179 // clone to prevent hook from changing the title stored inside $result
180 $title = clone $result->getTitle();
181 $query = [];
182 if ( $title->isRedirect() ) {
183 // If the search engine is returning a redirect, send them directly to the redirect. If
184 // instead the engine wants to send the user via redirect to the destination page then
185 // $result->getTitle() must be the final destination, and $result->getRedirectTarget()
186 // must hold the redirect.
187 $query['redirect'] = 'no';
188 }
189
190 $attributes = [ 'data-serp-pos' => $position ];
191 $this->hookRunner->onShowSearchHitTitle( $title, $snippet, $result,
192 $result instanceof \MediaWiki\Search\SqlSearchResult ? $result->getTermMatches() : [],
193 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
194 $this->specialPage, $query, $attributes );
195
196 $link = $this->linkRenderer->makeLink(
197 $title,
198 $snippet,
199 $attributes,
200 $query
201 );
202
203 return $link;
204 }
205
216 protected function generateAltTitleHtml( $msgKey, ?Title $title, $text ) {
217 $inner = $title === null
218 ? $text
219 : $this->linkRenderer->makeLink( $title, $text ? new HtmlArmor( $text ) : null );
220
221 return "<span class='searchalttitle'>" .
222 $this->specialPage->msg( $msgKey )->rawParams( $inner )->parse()
223 . "</span>";
224 }
225
230 protected function generateRedirectHtml( SearchResult $result ) {
231 $title = $result->getRedirectTitle();
232 return $title === null
233 ? ''
234 : $this->generateAltTitleHtml( 'search-redirect', $title, $result->getRedirectSnippet() );
235 }
236
241 protected function generateSectionHtml( SearchResult $result ) {
242 $title = $result->getSectionTitle();
243 return $title === null
244 ? ''
245 : $this->generateAltTitleHtml( 'search-section', $title, $result->getSectionSnippet() );
246 }
247
252 protected function generateCategoryHtml( SearchResult $result ) {
253 $snippet = $result->getCategorySnippet();
254 return $snippet
255 ? $this->generateAltTitleHtml( 'search-category', null, $snippet )
256 : '';
257 }
258
263 protected function generateSizeHtml( SearchResult $result ) {
264 $title = $result->getTitle();
265 if ( $title->getNamespace() === NS_CATEGORY ) {
266 $cat = Category::newFromTitle( $title );
267 return $this->specialPage->msg( 'search-result-category-size' )
268 ->numParams( $cat->getMemberCount(), $cat->getSubcatCount(), $cat->getFileCount() )
269 ->escaped();
270 // TODO: This is a bit odd...but requires changing the i18n message to fix
271 } elseif ( $result->getByteSize() !== null || $result->getWordCount() > 0 ) {
272 return $this->specialPage->msg( 'search-result-size' )
273 ->sizeParams( $result->getByteSize() )
274 ->numParams( $result->getWordCount() )
275 ->escaped();
276 }
277
278 return '';
279 }
280
287 protected function generateFileHtml( SearchResult $result ) {
288 $title = $result->getTitle();
289 // don't assume that result is a valid title; e.g. could be an interwiki link target
290 if ( $title === null || !$title->canExist() ) {
291 return [ '', null, null ];
292 }
293
294 $html = '';
295 if ( $result->isFileMatch() ) {
296 $html = Html::element( 'span',
297 [ 'class' => 'searchalttitle' ],
298 $this->specialPage->msg( 'search-file-match' )->text()
299 );
300 }
301
302 $allowExtraThumbsFromRequest = $this->specialPage->getRequest()->getVal( 'search-thumbnail-extra-namespaces' );
303 $allowExtraThumbsFromPreference = $this->userOptionsManager->getOption(
304 $this->specialPage->getUser(),
305 'search-thumbnail-extra-namespaces'
306 );
307 $allowExtraThumbs = (bool)( $allowExtraThumbsFromRequest ?? $allowExtraThumbsFromPreference );
308 if ( !$allowExtraThumbs && $title->getNamespace() !== NS_FILE ) {
309 return [ $html, null, null ];
310 }
311
312 $thumbnail = $this->getThumbnail( $result, self::THUMBNAIL_SIZE );
313 $thumbnailName = $thumbnail ? $thumbnail->getName() : null;
314 if ( !$thumbnailName ) {
315 return [ $html, null, $this->generateThumbnailHtml( $result ) ];
316 }
317
318 $img = $this->repoGroup->findFile( $thumbnailName );
319 if ( !$img ) {
320 return [ $html, null, $this->generateThumbnailHtml( $result ) ];
321 }
322
323 // File::getShortDesc() is documented to return HTML, but many handlers used to incorrectly
324 // return plain text (T395834), so sanitize it in case the same bug is present in extensions.
325 $unsafeShortDesc = $img->getShortDesc( $this->specialPage->getLanguage() );
326 $shortDesc = Sanitizer::removeSomeTags( $unsafeShortDesc );
327
328 return [
329 $html,
330 $this->specialPage->msg( 'parentheses' )->rawParams( $shortDesc )->escaped(),
331 $this->generateThumbnailHtml( $result, $thumbnail )
332 ];
333 }
334
340 private function getThumbnail( SearchResult $result, int $size ): ?SearchResultThumbnail {
341 $title = $result->getTitle();
342 // don't assume that result is a valid title; e.g. could be an interwiki link target
343 if ( $title === null || !$title->canExist() ) {
344 return null;
345 }
346
347 $thumbnails = $this->thumbnailProvider->getThumbnails( [ $title->getArticleID() => $title ], $size );
348
349 return $thumbnails[ $title->getArticleID() ] ?? null;
350 }
351
357 private function generateThumbnailHtml( SearchResult $result, ?SearchResultThumbnail $thumbnail = null ): ?string {
358 $title = $result->getTitle();
359 // don't assume that result is a valid title; e.g. could be an interwiki link target
360 if ( $title === null || !$title->canExist() ) {
361 return null;
362 }
363
364 $thumbnailNamespaces = $this->specialPage->getConfig()->get( MainConfigNames::ThumbnailNamespaces );
365 if ( !$title->inNamespaces( $thumbnailNamespaces ) ) {
366 return null;
367 }
368
369 $thumbnailName = $thumbnail?->getName();
370 if ( $thumbnailName === null ) {
371 return $this->generateThumbnailPlaceholderHtml();
372 }
373
374 $img = $this->repoGroup->findFile( $thumbnailName );
375 if ( !$img ) {
376 return $this->generateThumbnailPlaceholderHtml();
377 }
378
379 $thumb = $this->transformThumbnail( $img, $thumbnail );
380 if ( $thumb ) {
381 if ( $title->getNamespace() === NS_FILE ) {
382 // don't use a custom link, just use traditional thumbnail HTML
383 return $thumb->toHtml( [
384 'desc-link' => true,
385 'loading' => 'lazy',
386 'alt' => $this->specialPage->msg( 'search-thumbnail-alt', $title->getPrefixedText() ),
387 ] );
388 }
389
390 // thumbnails for non-file results should link to the relevant title
391 return $thumb->toHtml( [
392 'desc-link' => true,
393 'custom-title-link' => $title,
394 'loading' => 'lazy',
395 'alt' => $this->specialPage->msg( 'search-thumbnail-alt', $title->getPrefixedText() ),
396 ] );
397 }
398
399 return $this->generateThumbnailPlaceholderHtml();
400 }
401
407 private function transformThumbnail( File $img, SearchResultThumbnail $thumbnail ) {
408 $optimalThumbnailWidth = $thumbnail->getWidth();
409
410 // $thumb will have rescaled to fit within a <$size>x<$size> bounding
411 // box, but we want it to cover a full square (at the cost of losing
412 // some of the edges)
413 // instead of the largest side matching up with $size, we want the
414 // smallest size to match (or exceed) $size
415 $thumbnailMaxDimension = max( $thumbnail->getWidth(), $thumbnail->getHeight() );
416 $thumbnailMinDimension = min( $thumbnail->getWidth(), $thumbnail->getHeight() );
417 $rescaleCoefficient = $thumbnailMinDimension
418 ? $thumbnailMaxDimension / $thumbnailMinDimension : 1;
419
420 // we'll only deal with width from now on since conventions for
421 // standard sizes have formed around width; height will simply
422 // follow according to aspect ratio
423 $rescaledWidth = (int)round( $rescaleCoefficient * $thumbnail->getWidth() );
424
425 // we'll also be looking at $wgThumbLimits to ensure that we pick
426 // from within the predefined list of sizes
427 // NOTE: only do this when there is a difference in the rescaled
428 // size vs the original thumbnail size - some media types are
429 // different and thumb limits don't matter (e.g. for audio, the
430 // player must remain at the size we want, regardless of whether or
431 // not it fits the thumb limits, which in this case are irrelevant)
432 if ( $rescaledWidth !== $thumbnail->getWidth() ) {
433 $thumbLimits = $this->specialPage->getConfig()->get( MainConfigNames::ThumbLimits );
434 $largerThumbLimits = array_filter(
435 $thumbLimits,
436 static function ( $limit ) use ( $rescaledWidth ) {
437 return $limit >= $rescaledWidth;
438 }
439 );
440 $optimalThumbnailWidth = $largerThumbLimits ? min( $largerThumbLimits ) : max( $thumbLimits );
441 }
442
443 return $img->transform( [ 'width' => $optimalThumbnailWidth ] );
444 }
445
446 private function generateThumbnailPlaceholderHtml(): string {
447 if ( $this->thumbnailPlaceholderHtml ) {
448 return $this->thumbnailPlaceholderHtml;
449 }
450
451 $path = MW_INSTALL_PATH . '/resources/lib/ooui/themes/wikimediaui/images/icons/imageLayoutFrameless.svg';
452 $this->thumbnailPlaceholderHtml = Html::rawElement(
453 'div',
454 [
455 'class' => 'searchResultImage-thumbnail-placeholder',
456 'aria-hidden' => 'true',
457 ],
458 file_get_contents( $path )
459 );
460 return $this->thumbnailPlaceholderHtml;
461 }
462
470 protected function buildMeta( $desc, $date ) {
471 if ( $desc && $date ) {
472 $meta = $this->specialPage->msg( 'search-result-meta-separator',
473 Message::rawParam( $desc ),
474 Message::rawParam( $date )
475 )->escaped();
476 } elseif ( $desc ) {
477 $meta = $desc;
478 } elseif ( $date ) {
479 $meta = $date;
480 } else {
481 return '';
482 }
483
484 return "<div class='mw-search-result-data'>{$meta}</div>";
485 }
486}
const NS_FILE
Definition Defines.php:57
const NS_CATEGORY
Definition Defines.php:65
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:72
Title string false $title
Definition File.php:130
Prioritized list of file repositories.
Definition RepoGroup.php:30
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Class that generates HTML for internal links.
const ThumbnailNamespaces
Name constant for the ThumbnailNamespaces setting, for use with Config\get().
Class that stores information about thumbnail, e.
An abstract base class representing a search engine result.
isMissingRevision()
Check if target page is missing, happens when index is out of date.
isFileMatch()
Did this match file contents (eg: PDF/DJVU)?
isBrokenTitle()
Check if this is result points to an invalid title.
Renders a 'full' multi-line search result with metadata.
generateAltTitleHtml( $msgKey, ?Title $title, $text)
Generates an alternate title link, such as (redirect from Foo).
generateMainLinkHtml(SearchResult $result, $position)
Generates HTML for the primary call to action.
__construct(SpecialSearch $specialPage, LinkRenderer $linkRenderer, HookContainer $hookContainer, RepoGroup $repoGroup, SearchResultThumbnailProvider $thumbnailProvider, UserOptionsManager $userOptionsManager)
Run text & title search and display the output.
Represents a title within MediaWiki.
Definition Title.php:69
A service class to control user options.
Marks HTML that shouldn't be escaped.
Definition HtmlArmor.php:18
Renders a single search result to HTML.
element(SerializerNode $parent, SerializerNode $node, $contents)