| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\Search; |
| 4 |
|
| 5 |
use File; |
| 6 |
use MediaWiki\HookContainer\HookContainer; |
| 7 |
use MediaWiki\HookContainer\HookRunner; |
| 8 |
use MediaWiki\MediaWikiServices; |
| 9 |
use MediaWiki\Page\PageIdentity; |
| 10 |
use MediaWiki\Search\Entity\SearchResultThumbnail; |
| 11 |
use RepoGroup; |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
class SearchResultThumbnailProvider { |
| 19 |
|
| 20 |
public const THUMBNAIL_SIZE = 60; |
| 21 |
|
| 22 |
|
| 23 |
private $repoGroup; |
| 24 |
|
| 25 |
|
| 26 |
private $hookRunner; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
public function __construct( RepoGroup $repoGroup, HookContainer $hookContainer ) { |
| 33 |
$this->repoGroup = $repoGroup; |
| 34 |
$this->hookRunner = new HookRunner( $hookContainer ); |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
private function getFileNamesByPageId( array $identitiesByPageId ): array { |
| 45 |
$fileIdentitiesByPageId = array_filter( |
| 46 |
$identitiesByPageId, |
| 47 |
static function ( PageIdentity $pageIdentity ) { |
| 48 |
return $pageIdentity->getNamespace() === NS_FILE; |
| 49 |
} |
| 50 |
); |
| 51 |
|
| 52 |
return array_map( |
| 53 |
static function ( PageIdentity $pageIdentity ) { |
| 54 |
return $pageIdentity->getDBkey(); |
| 55 |
}, |
| 56 |
$fileIdentitiesByPageId |
| 57 |
); |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
public function buildSearchResultThumbnailFromFile( File $file, ?int $size = null ): ?SearchResultThumbnail { |
| 68 |
$size ??= self::THUMBNAIL_SIZE; |
| 69 |
|
| 70 |
$thumb = $file->transform( [ 'width' => $size ] ); |
| 71 |
if ( !$thumb || $thumb->isError() ) { |
| 72 |
return null; |
| 73 |
} |
| 74 |
|
| 75 |
$urlUtils = MediaWikiServices::getInstance()->getUrlUtils(); |
| 76 |
return new SearchResultThumbnail( |
| 77 |
$thumb->getFile()->getMimeType(), |
| 78 |
null, |
| 79 |
$thumb->getWidth(), |
| 80 |
$thumb->getHeight(), |
| 81 |
null, |
| 82 |
$urlUtils->expand( $thumb->getUrl(), PROTO_RELATIVE ) ?? false, |
| 83 |
$file->getName() |
| 84 |
); |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
public function getThumbnails( array $pageIdentities, ?int $size = 60 ): array { |
| 93 |
|
| 94 |
$fileNamesByPageId = $this->getFileNamesByPageId( $pageIdentities ); |
| 95 |
$results = []; |
| 96 |
foreach ( $fileNamesByPageId as $pageId => $fileName ) { |
| 97 |
$file = $this->repoGroup->findFile( $fileName ); |
| 98 |
if ( !$file ) { |
| 99 |
continue; |
| 100 |
} |
| 101 |
$thumbnail = $this->buildSearchResultThumbnailFromFile( $file, $size ); |
| 102 |
if ( $thumbnail ) { |
| 103 |
$results[$pageId] = $thumbnail; |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
|
| 108 |
$this->hookRunner->onSearchResultProvideThumbnail( $pageIdentities, $results, $size ); |
| 109 |
|
| 110 |
return $results; |
| 111 |
} |
| 112 |
} |