Debian Codegraph @

extensions/PageImages/includes/PageImages.php

raw symbols SCIP
1 <?php
2
3 namespace PageImages;
4
5 use File;
6 use MapCacheLRU;
7 use MediaWiki\Api\ApiBase;
8 use MediaWiki\Api\ApiMain;
9 use MediaWiki\Api\Hook\ApiOpenSearchSuggestHook;
10 use MediaWiki\Cache\CacheKeyHelper;
11 use MediaWiki\Config\Config;
12 use MediaWiki\Context\IContextSource;
13 use MediaWiki\Hook\InfoActionHook;
14 use MediaWiki\MainConfigNames;
15 use MediaWiki\MediaWikiServices;
16 use MediaWiki\Output\Hook\BeforePageDisplayHook;
17 use MediaWiki\Output\OutputPage;
18 use MediaWiki\Request\FauxRequest;
19 use MediaWiki\Settings\SettingsBuilder;
20 use MediaWiki\Title\Title;
21 use MediaWiki\User\Options\UserOptionsLookup;
22 use RepoGroup;
23 use Skin;
24 use Wikimedia\Rdbms\IConnectionProvider;
25
26 /**
27 * @license WTFPL
28 * @author Max Semenik
29 * @author Brad Jorsch
30 * @author Thiemo Kreuz
31 */
32 class PageImages implements
33 ApiOpenSearchSuggestHook,
34 BeforePageDisplayHook,
35 InfoActionHook
36 {
37 /**
38 * @const value for free images
39 */
40 public const LICENSE_FREE = 'free';
41
42 /**
43 * @const value for images with any type of license
44 */
45 public const LICENSE_ANY = 'any';
46
47 /**
48 * Page property used to store the best page image information.
49 * If the best image is the same as the best image with free license,
50 * then nothing is stored under this property.
51 * Note changing this value is not advised as it will invalidate all
52 * existing page property names on a production instance
53 * and cause them to be regenerated.
54 * @see PageImages::PROP_NAME_FREE
55 */
56 public const PROP_NAME = 'page_image';
57
58 /**
59 * Page property used to store the best free page image information
60 * Note changing this value is not advised as it will invalidate all
61 * existing page property names on a production instance
62 * and cause them to be regenerated.
63 */
64 public const PROP_NAME_FREE = 'page_image_free';
65
66 /** @var Config */
67 private $config;
68
69 /** @var IConnectionProvider */
70 private $dbProvider;
71
72 /** @var RepoGroup */
73 private $repoGroup;
74
75 /** @var UserOptionsLookup */
76 private $userOptionsLookup;
77
78 /** @var MapCacheLRU */
79 private static $cache = null;
80
81 /**
82 * @return PageImages
83 */
84 private static function factory(): self {
85 $services = MediaWikiServices::getInstance();
86 return new self(
87 $services->getMainConfig(),
88 $services->getDBLoadBalancerFactory(),
89 $services->getRepoGroup(),
90 $services->getUserOptionsLookup()
91 );
92 }
93
94 /**
95 * @param Config $config
96 * @param IConnectionProvider $dbProvider
97 * @param RepoGroup $repoGroup
98 * @param UserOptionsLookup $userOptionsLookup
99 */
100 public function __construct(
101 Config $config,
102 IConnectionProvider $dbProvider,
103 RepoGroup $repoGroup,
104 UserOptionsLookup $userOptionsLookup
105 ) {
106 $this->config = $config;
107 $this->dbProvider = $dbProvider;
108 $this->repoGroup = $repoGroup;
109 $this->userOptionsLookup = $userOptionsLookup;
110 }
111
112 /**
113 * Set dynamic default value for PageImagesNamespaces configuration option.
114 *
115 * @param array $extInfo An array containing information about the extension
116 * @param SettingsBuilder $settings
117 */
118 public static function onRegistration(
119 array $extInfo,
120 SettingsBuilder $settings
121 ) {
122 if ( $settings->getConfig()->get( 'PageImagesNamespaces' ) === false ) {
123 $settings->overrideConfigValue(
124 'PageImagesNamespaces',
125 $settings->getConfig()->get( MainConfigNames::ContentNamespaces )
126 );
127 }
128 }
129
130 /**
131 * Get property name used in page_props table. When a page image
132 * is stored it will be stored under this property name on the corresponding
133 * article.
134 *
135 * @param bool $isFree Whether the image is a free-license image
136 * @return string
137 */
138 public static function getPropName( $isFree ) {
139 return $isFree ? self::PROP_NAME_FREE : self::PROP_NAME;
140 }
141
142 /**
143 * Get property names used in page_props table
144 *
145 * If the license is free, then only the free property name will be returned,
146 * otherwise both free and non-free property names will be returned. That's
147 * because we save the image name only once if it's free and the best image.
148 *
149 * @param string $license either LICENSE_FREE or LICENSE_ANY,
150 * specifying whether to return the non-free property name or not
151 * @return string|array
152 */
153 public static function getPropNames( $license ) {
154 if ( $license === self::LICENSE_FREE ) {
155 return self::getPropName( true );
156 }
157 return [ self::getPropName( true ), self::getPropName( false ) ];
158 }
159
160 /**
161 * Return page image for a given title
162 *
163 * @param Title $title Title to get page image for
164 * @return File|false
165 */
166 public static function getPageImage( Title $title ) {
167 // Cast any cacheable null to false
168 return self::factory()->getPageImageInternal( $title ) ?? false;
169 }
170
171 /**
172 * Return page image for a given title
173 *
174 * @param Title $title Title to get page image for
175 * @return File|null
176 */
177 public function getPageImageInternal( Title $title ): ?File {
178 self::$cache ??= new MapCacheLRU( 100 );
179
180 $file = self::$cache->getWithSetCallback(
181 CacheKeyHelper::getKeyForPage( $title ),
182 fn () => $this->fetchPageImage( $title )
183 );
184
185 // Cast false to null
186 return $file ?: null;
187 }
188
189 /**
190 * @param Title $title Title to get page image for
191 * @return File|null|false
192 */
193 private function fetchPageImage( Title $title ) {
194 if ( !$title->canExist() ) {
195 // Optimization: Do not query for special pages or other titles never in the database
196 return false;
197 }
198
199 if ( $title->inNamespace( NS_FILE ) ) {
200 return $this->repoGroup->findFile( $title );
201 }
202
203 $pageId = $title->getArticleID();
204 if ( !$pageId ) {
205 // No page id to select from
206 // Allow caching, cast null to false later
207 return null;
208 }
209
210 $dbr = $this->dbProvider->getReplicaDatabase();
211 $fileName = $dbr->newSelectQueryBuilder()
212 ->select( 'pp_value' )
213 ->from( 'page_props' )
214 ->where( [
215 'pp_page' => $pageId,
216 'pp_propname' => [ self::PROP_NAME, self::PROP_NAME_FREE ]
217 ] )
218 ->orderBy( 'pp_propname' )
219 ->caller( __METHOD__ )
220 ->fetchField();
221 if ( !$fileName ) {
222 // Return not found without caching.
223 return false;
224 }
225
226 return $this->repoGroup->findFile( $fileName );
227 }
228
229 /**
230 * InfoAction hook handler, adds the page image to the info=action page
231 *
232 * @see https://www.mediawiki.org/wiki/Manual:Hooks/InfoAction
233 *
234 * @param IContextSource $context Context, used to extract the title of the page
235 * @param array[] &$pageInfo Auxillary information about the page.
236 */
237 public function onInfoAction( $context, &$pageInfo ) {
238 $imageFile = $this->getPageImageInternal( $context->getTitle() );
239 if ( !$imageFile ) {
240 // The page has no image
241 return;
242 }
243
244 $thumbSetting = $this->userOptionsLookup->getOption( $context->getUser(), 'thumbsize' );
245 $thumbSize = $this->config->get( MainConfigNames::ThumbLimits )[$thumbSetting];
246
247 $thumb = $imageFile->transform( [ 'width' => $thumbSize ] );
248 if ( !$thumb ) {
249 return;
250 }
251 $imageHtml = $thumb->toHtml(
252 [
253 'alt' => $imageFile->getTitle()->getText(),
254 'desc-link' => true,
255 ]
256 );
257
258 $pageInfo['header-basic'][] = [
259 $context->msg( 'pageimages-info-label' ),
260 $imageHtml
261 ];
262 }
263
264 /**
265 * ApiOpenSearchSuggest hook handler, enhances ApiOpenSearch results with this extension's data
266 *
267 * @param array[] &$results Array of results to add page images too
268 */
269 public function onApiOpenSearchSuggest( &$results ) {
270 if ( !$this->config->get( 'PageImagesExpandOpenSearchXml' ) || !count( $results ) ) {
271 return;
272 }
273
274 $pageIds = array_keys( $results );
275 $data = self::getImages( $pageIds, 50 );
276 foreach ( $pageIds as $id ) {
277 if ( isset( $data[$id]['thumbnail'] ) ) {
278 $results[$id]['image'] = $data[$id]['thumbnail'];
279 } else {
280 $results[$id]['image'] = null;
281 }
282 }
283 }
284
285 /**
286 * Returns image information for pages with given ids
287 *
288 * @param int[] $pageIds
289 * @param int $size
290 *
291 * @return array[]
292 */
293 public static function getImages( array $pageIds, $size = 0 ) {
294 $ret = [];
295 foreach ( array_chunk( $pageIds, ApiBase::LIMIT_SML1 ) as $chunk ) {
296 $request = [
297 'action' => 'query',
298 'prop' => 'pageimages',
299 'piprop' => 'name',
300 'pageids' => implode( '|', $chunk ),
301 'pilimit' => 'max',
302 ];
303
304 if ( $size ) {
305 $request['piprop'] = 'thumbnail';
306 $request['pithumbsize'] = $size;
307 }
308
309 $api = new ApiMain( new FauxRequest( $request ) );
310 $api->execute();
311
312 $ret += (array)$api->getResult()->getResultData(
313 [ 'query', 'pages' ], [ 'Strip' => 'base' ]
314 );
315 }
316 return $ret;
317 }
318
319 /**
320 * @param OutputPage $out The page being output.
321 * @param Skin $skin Skin object used to generate the page. Ignored
322 */
323 public function onBeforePageDisplay( $out, $skin ): void {
324 if ( !$out->getConfig()->get( 'PageImagesOpenGraph' ) ) {
325 return;
326 }
327 $imageFile = $this->getPageImageInternal( $out->getContext()->getTitle() );
328 if ( !$imageFile ) {
329 $fallback = $out->getConfig()->get( 'PageImagesOpenGraphFallbackImage' );
330 if ( $fallback ) {
331 $out->addMeta( 'og:image', wfExpandUrl( $fallback, PROTO_CANONICAL ) );
332 }
333 return;
334 }
335
336 // Open Graph protocol -- https://ogp.me/
337 // Multiple images are supported according to https://ogp.me/#array
338 // See https://developers.facebook.com/docs/sharing/best-practices?locale=en_US#images
339 // See T282065: WhatsApp expects an image <300kB
340 foreach ( [ 1200, 800, 640 ] as $width ) {
341 $thumb = $imageFile->transform( [ 'width' => $width ] );
342 if ( !$thumb ) {
343 continue;
344 }
345 $out->addMeta( 'og:image', wfExpandUrl( $thumb->getUrl(), PROTO_CANONICAL ) );
346 $out->addMeta( 'og:image:width', strval( $thumb->getWidth() ) );
347 $out->addMeta( 'og:image:height', strval( $thumb->getHeight() ) );
348 }
349 }
350
351 }