MediaWiki REL1_32
ForeignAPIFile.php
Go to the documentation of this file.
1<?php
25
32class ForeignAPIFile extends File {
34 private $mExists;
36 private $mInfo = [];
37
38 protected $repoClass = ForeignAPIRepo::class;
39
46 function __construct( $title, $repo, $info, $exists = false ) {
47 parent::__construct( $title, $repo );
48
49 $this->mInfo = $info;
50 $this->mExists = $exists;
51
52 $this->assertRepoDefined();
53 }
54
60 static function newFromTitle( Title $title, $repo ) {
61 $data = $repo->fetchImageQuery( [
62 'titles' => 'File:' . $title->getDBkey(),
63 'iiprop' => self::getProps(),
64 'prop' => 'imageinfo',
65 'iimetadataversion' => MediaHandler::getMetadataVersion(),
66 // extmetadata is language-dependant, accessing the current language here
67 // would be problematic, so we just get them all
68 'iiextmetadatamultilang' => 1,
69 ] );
70
71 $info = $repo->getImageInfo( $data );
72
73 if ( $info ) {
74 $lastRedirect = isset( $data['query']['redirects'] )
75 ? count( $data['query']['redirects'] ) - 1
76 : -1;
77 if ( $lastRedirect >= 0 ) {
78 $newtitle = Title::newFromText( $data['query']['redirects'][$lastRedirect]['to'] );
79 $img = new self( $newtitle, $repo, $info, true );
80 if ( $img ) {
81 $img->redirectedFrom( $title->getDBkey() );
82 }
83 } else {
84 $img = new self( $title, $repo, $info, true );
85 }
86
87 return $img;
88 } else {
89 return null;
90 }
91 }
92
97 static function getProps() {
98 return 'timestamp|user|comment|url|size|sha1|metadata|mime|mediatype|extmetadata';
99 }
100
101 // Dummy functions...
102
106 public function exists() {
107 return $this->mExists;
108 }
109
113 public function getPath() {
114 return false;
115 }
116
122 function transform( $params, $flags = 0 ) {
123 if ( !$this->canRender() ) {
124 // show icon
125 return parent::transform( $params, $flags );
126 }
127
128 // Note, the this->canRender() check above implies
129 // that we have a handler, and it can do makeParamString.
130 $otherParams = $this->handler->makeParamString( $params );
131 $width = $params['width'] ?? -1;
132 $height = $params['height'] ?? -1;
133
134 $thumbUrl = $this->repo->getThumbUrlFromCache(
135 $this->getName(),
136 $width,
137 $height,
138 $otherParams
139 );
140 if ( $thumbUrl === false ) {
141 global $wgLang;
142
143 return $this->repo->getThumbError(
144 $this->getName(),
145 $width,
146 $height,
147 $otherParams,
148 $wgLang->getCode()
149 );
150 }
151
152 return $this->handler->getTransform( $this, 'bogus', $thumbUrl, $params );
153 }
154
155 // Info we can get from API...
156
161 public function getWidth( $page = 1 ) {
162 return isset( $this->mInfo['width'] ) ? intval( $this->mInfo['width'] ) : 0;
163 }
164
169 public function getHeight( $page = 1 ) {
170 return isset( $this->mInfo['height'] ) ? intval( $this->mInfo['height'] ) : 0;
171 }
172
176 public function getMetadata() {
177 if ( isset( $this->mInfo['metadata'] ) ) {
178 return serialize( self::parseMetadata( $this->mInfo['metadata'] ) );
179 }
180
181 return null;
182 }
183
188 public function getExtendedMetadata() {
189 if ( isset( $this->mInfo['extmetadata'] ) ) {
190 return $this->mInfo['extmetadata'];
191 }
192
193 return null;
194 }
195
200 public static function parseMetadata( $metadata ) {
201 if ( !is_array( $metadata ) ) {
202 return $metadata;
203 }
204 $ret = [];
205 foreach ( $metadata as $meta ) {
206 $ret[$meta['name']] = self::parseMetadata( $meta['value'] );
207 }
208
209 return $ret;
210 }
211
215 public function getSize() {
216 return isset( $this->mInfo['size'] ) ? intval( $this->mInfo['size'] ) : null;
217 }
218
222 public function getUrl() {
223 return isset( $this->mInfo['url'] ) ? strval( $this->mInfo['url'] ) : null;
224 }
225
233 public function getDescriptionShortUrl() {
234 if ( isset( $this->mInfo['descriptionshorturl'] ) ) {
235 return $this->mInfo['descriptionshorturl'];
236 } elseif ( isset( $this->mInfo['pageid'] ) ) {
237 $url = $this->repo->makeUrl( [ 'curid' => $this->mInfo['pageid'] ] );
238 if ( $url !== false ) {
239 return $url;
240 }
241 }
242 return null;
243 }
244
249 public function getUser( $type = 'text' ) {
250 if ( $type == 'text' ) {
251 return isset( $this->mInfo['user'] ) ? strval( $this->mInfo['user'] ) : null;
252 } else {
253 return 0; // What makes sense here, for a remote user?
254 }
255 }
256
262 public function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
263 return isset( $this->mInfo['comment'] ) ? strval( $this->mInfo['comment'] ) : null;
264 }
265
269 function getSha1() {
270 return isset( $this->mInfo['sha1'] )
271 ? Wikimedia\base_convert( strval( $this->mInfo['sha1'] ), 16, 36, 31 )
272 : null;
273 }
274
278 function getTimestamp() {
279 return wfTimestamp( TS_MW,
280 isset( $this->mInfo['timestamp'] )
281 ? strval( $this->mInfo['timestamp'] )
282 : null
283 );
284 }
285
289 function getMimeType() {
290 if ( !isset( $this->mInfo['mime'] ) ) {
291 $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
292 $this->mInfo['mime'] = $magic->guessTypesForExtension( $this->getExtension() );
293 }
294
295 return $this->mInfo['mime'];
296 }
297
301 function getMediaType() {
302 if ( isset( $this->mInfo['mediatype'] ) ) {
303 return $this->mInfo['mediatype'];
304 }
305 $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
306
307 return $magic->getMediaType( null, $this->getMimeType() );
308 }
309
313 function getDescriptionUrl() {
314 return $this->mInfo['descriptionurl'] ?? false;
315 }
316
322 function getThumbPath( $suffix = '' ) {
323 if ( $this->repo->canCacheThumbs() ) {
324 $path = $this->repo->getZonePath( 'thumb' ) . '/' . $this->getHashPath( $this->getName() );
325 if ( $suffix ) {
326 $path = $path . $suffix . '/';
327 }
328
329 return $path;
330 } else {
331 return null;
332 }
333 }
334
338 function getThumbnails() {
339 $dir = $this->getThumbPath( $this->getName() );
340 $iter = $this->repo->getBackend()->getFileList( [ 'dir' => $dir ] );
341
342 $files = [];
343 if ( $iter ) {
344 foreach ( $iter as $file ) {
345 $files[] = $file;
346 }
347 }
348
349 return $files;
350 }
351
352 function purgeCache( $options = [] ) {
353 $this->purgeThumbnails( $options );
354 $this->purgeDescriptionPage();
355 }
356
358 $services = MediaWikiServices::getInstance();
359 $url = $this->repo->getDescriptionRenderUrl(
360 $this->getName(), $services->getContentLanguage()->getCode() );
361 $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', md5( $url ) );
362
363 $services->getMainWANObjectCache()->delete( $key );
364 }
365
369 function purgeThumbnails( $options = [] ) {
370 $key = $this->repo->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $this->getName() );
371 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
372
373 $files = $this->getThumbnails();
374 // Give media handler a chance to filter the purge list
375 $handler = $this->getHandler();
376 if ( $handler ) {
378 }
379
380 $dir = $this->getThumbPath( $this->getName() );
381 $purgeList = [];
382 foreach ( $files as $file ) {
383 $purgeList[] = "{$dir}{$file}";
384 }
385
386 # Delete the thumbnails
387 $this->repo->quickPurgeBatch( $purgeList );
388 # Clear out the thumbnail directory if empty
389 $this->repo->quickCleanDir( $dir );
390 }
391
397 public function isTransformedLocally() {
398 return false;
399 }
400}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
serialize()
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$wgLang
Definition Setup.php:910
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:51
string $url
The URL corresponding to one of the four basic zones.
Definition File.php:117
MediaHandler $handler
Definition File.php:114
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition File.php:2279
getName()
Return the name of this file.
Definition File.php:297
canRender()
Checks if the output of transform() for this file is likely to be valid.
Definition File.php:753
getExtension()
Get the file extension, e.g.
Definition File.php:311
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition File.php:96
string $path
The storage path corresponding to one of the zones.
Definition File.php:126
Title string bool $title
Definition File.php:99
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1383
getHashPath()
Get the filename hash component of the directory including trailing slash, e.g.
Definition File.php:1517
Foreign file accessible through api.php requests.
getThumbPath( $suffix='')
Only useful if we're locally caching thumbs anyway...
__construct( $title, $repo, $info, $exists=false)
purgeCache( $options=[])
Purge shared caches such as thumbnails and DB data caching STUB Overridden by LocalFile.
isTransformedLocally()
The thumbnail is created on the foreign server and fetched over internet.
static parseMetadata( $metadata)
static newFromTitle(Title $title, $repo)
getUser( $type='text')
purgeThumbnails( $options=[])
getDescription( $audience=self::FOR_PUBLIC, User $user=null)
transform( $params, $flags=0)
getDescriptionShortUrl()
Get short description URL for a file based on the foreign API response, or if unavailable,...
static getProps()
Get the property string for iiprop and aiprop.
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
static getMetadataVersion()
Get metadata version.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Represents a title within MediaWiki.
Definition Title.php:39
getDBkey()
Get the main part with underscores.
Definition Title.php:951
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:47
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2050
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves set to a MediaTransformOutput the error message to be returned in an array you should do so by altering $wgNamespaceProtection and $wgNamespaceContentModels outside the handler
Definition hooks.txt:960
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:2055
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition hooks.txt:2335
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:2054
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$params