Debian Codegraph @

includes/search/searchwidgets/FullSearchResultWidget.php

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