MediaWiki  1.27.1
ForeignAPIFile.php
Go to the documentation of this file.
1 <?php
30 class ForeignAPIFile extends File {
31  private $mExists;
32 
33  protected $repoClass = 'ForeignApiRepo';
34 
41  function __construct( $title, $repo, $info, $exists = false ) {
42  parent::__construct( $title, $repo );
43 
44  $this->mInfo = $info;
45  $this->mExists = $exists;
46 
47  $this->assertRepoDefined();
48  }
49 
55  static function newFromTitle( Title $title, $repo ) {
56  $data = $repo->fetchImageQuery( [
57  'titles' => 'File:' . $title->getDBkey(),
58  'iiprop' => self::getProps(),
59  'prop' => 'imageinfo',
60  'iimetadataversion' => MediaHandler::getMetadataVersion(),
61  // extmetadata is language-dependant, accessing the current language here
62  // would be problematic, so we just get them all
63  'iiextmetadatamultilang' => 1,
64  ] );
65 
66  $info = $repo->getImageInfo( $data );
67 
68  if ( $info ) {
69  $lastRedirect = isset( $data['query']['redirects'] )
70  ? count( $data['query']['redirects'] ) - 1
71  : -1;
72  if ( $lastRedirect >= 0 ) {
73  $newtitle = Title::newFromText( $data['query']['redirects'][$lastRedirect]['to'] );
74  $img = new self( $newtitle, $repo, $info, true );
75  if ( $img ) {
76  $img->redirectedFrom( $title->getDBkey() );
77  }
78  } else {
79  $img = new self( $title, $repo, $info, true );
80  }
81 
82  return $img;
83  } else {
84  return null;
85  }
86  }
87 
92  static function getProps() {
93  return 'timestamp|user|comment|url|size|sha1|metadata|mime|mediatype|extmetadata';
94  }
95 
96  // Dummy functions...
97 
101  public function exists() {
102  return $this->mExists;
103  }
104 
108  public function getPath() {
109  return false;
110  }
111 
117  function transform( $params, $flags = 0 ) {
118  if ( !$this->canRender() ) {
119  // show icon
120  return parent::transform( $params, $flags );
121  }
122 
123  // Note, the this->canRender() check above implies
124  // that we have a handler, and it can do makeParamString.
125  $otherParams = $this->handler->makeParamString( $params );
126  $width = isset( $params['width'] ) ? $params['width'] : -1;
127  $height = isset( $params['height'] ) ? $params['height'] : -1;
128 
129  $thumbUrl = $this->repo->getThumbUrlFromCache(
130  $this->getName(),
131  $width,
132  $height,
133  $otherParams
134  );
135  if ( $thumbUrl === false ) {
136  global $wgLang;
137 
138  return $this->repo->getThumbError(
139  $this->getName(),
140  $width,
141  $height,
142  $otherParams,
143  $wgLang->getCode()
144  );
145  }
146 
147  return $this->handler->getTransform( $this, 'bogus', $thumbUrl, $params );
148  }
149 
150  // Info we can get from API...
151 
156  public function getWidth( $page = 1 ) {
157  return isset( $this->mInfo['width'] ) ? intval( $this->mInfo['width'] ) : 0;
158  }
159 
164  public function getHeight( $page = 1 ) {
165  return isset( $this->mInfo['height'] ) ? intval( $this->mInfo['height'] ) : 0;
166  }
167 
171  public function getMetadata() {
172  if ( isset( $this->mInfo['metadata'] ) ) {
173  return serialize( self::parseMetadata( $this->mInfo['metadata'] ) );
174  }
175 
176  return null;
177  }
178 
183  public function getExtendedMetadata() {
184  if ( isset( $this->mInfo['extmetadata'] ) ) {
185  return $this->mInfo['extmetadata'];
186  }
187 
188  return null;
189  }
190 
195  public static function parseMetadata( $metadata ) {
196  if ( !is_array( $metadata ) ) {
197  return $metadata;
198  }
199  $ret = [];
200  foreach ( $metadata as $meta ) {
201  $ret[$meta['name']] = self::parseMetadata( $meta['value'] );
202  }
203 
204  return $ret;
205  }
206 
210  public function getSize() {
211  return isset( $this->mInfo['size'] ) ? intval( $this->mInfo['size'] ) : null;
212  }
213 
217  public function getUrl() {
218  return isset( $this->mInfo['url'] ) ? strval( $this->mInfo['url'] ) : null;
219  }
220 
228  public function getDescriptionShortUrl() {
229  if ( isset( $this->mInfo['descriptionshorturl'] ) ) {
230  return $this->mInfo['descriptionshorturl'];
231  } elseif ( isset( $this->mInfo['pageid'] ) ) {
232  $url = $this->repo->makeUrl( [ 'curid' => $this->mInfo['pageid'] ] );
233  if ( $url !== false ) {
234  return $url;
235  }
236  }
237  return null;
238  }
239 
244  public function getUser( $type = 'text' ) {
245  if ( $type == 'text' ) {
246  return isset( $this->mInfo['user'] ) ? strval( $this->mInfo['user'] ) : null;
247  } elseif ( $type == 'id' ) {
248  return 0; // What makes sense here, for a remote user?
249  }
250  }
251 
257  public function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
258  return isset( $this->mInfo['comment'] ) ? strval( $this->mInfo['comment'] ) : null;
259  }
260 
264  function getSha1() {
265  return isset( $this->mInfo['sha1'] )
266  ? Wikimedia\base_convert( strval( $this->mInfo['sha1'] ), 16, 36, 31 )
267  : null;
268  }
269 
273  function getTimestamp() {
274  return wfTimestamp( TS_MW,
275  isset( $this->mInfo['timestamp'] )
276  ? strval( $this->mInfo['timestamp'] )
277  : null
278  );
279  }
280 
284  function getMimeType() {
285  if ( !isset( $this->mInfo['mime'] ) ) {
286  $magic = MimeMagic::singleton();
287  $this->mInfo['mime'] = $magic->guessTypesForExtension( $this->getExtension() );
288  }
289 
290  return $this->mInfo['mime'];
291  }
292 
296  function getMediaType() {
297  if ( isset( $this->mInfo['mediatype'] ) ) {
298  return $this->mInfo['mediatype'];
299  }
300  $magic = MimeMagic::singleton();
301 
302  return $magic->getMediaType( null, $this->getMimeType() );
303  }
304 
308  function getDescriptionUrl() {
309  return isset( $this->mInfo['descriptionurl'] )
310  ? $this->mInfo['descriptionurl']
311  : false;
312  }
313 
319  function getThumbPath( $suffix = '' ) {
320  if ( $this->repo->canCacheThumbs() ) {
321  $path = $this->repo->getZonePath( 'thumb' ) . '/' . $this->getHashPath( $this->getName() );
322  if ( $suffix ) {
323  $path = $path . $suffix . '/';
324  }
325 
326  return $path;
327  } else {
328  return null;
329  }
330  }
331 
335  function getThumbnails() {
336  $dir = $this->getThumbPath( $this->getName() );
337  $iter = $this->repo->getBackend()->getFileList( [ 'dir' => $dir ] );
338 
339  $files = [];
340  foreach ( $iter as $file ) {
341  $files[] = $file;
342  }
343 
344  return $files;
345  }
346 
350  function purgeCache( $options = [] ) {
351  $this->purgeThumbnails( $options );
352  $this->purgeDescriptionPage();
353  }
354 
355  function purgeDescriptionPage() {
357 
358  $url = $this->repo->getDescriptionRenderUrl( $this->getName(), $wgContLang->getCode() );
359  $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', md5( $url ) );
360 
362  }
363 
367  function purgeThumbnails( $options = [] ) {
368  $key = $this->repo->getLocalCacheKey( 'ForeignAPIRepo', 'ThumbUrl', $this->getName() );
370 
371  $files = $this->getThumbnails();
372  // Give media handler a chance to filter the purge list
373  $handler = $this->getHandler();
374  if ( $handler ) {
376  }
377 
378  $dir = $this->getThumbPath( $this->getName() );
379  $purgeList = [];
380  foreach ( $files as $file ) {
381  $purgeList[] = "{$dir}{$file}";
382  }
383 
384  # Delete the thumbnails
385  $this->repo->quickPurgeBatch( $purgeList );
386  # Clear out the thumbnail directory if empty
387  $this->repo->quickCleanDir( $dir );
388  }
389 
395  public function isTransformedLocally() {
396  return false;
397  }
398 }
static getMainWANInstance()
Get the main WAN cache object.
purgeCache($options=[])
MediaHandler $handler
Definition: File.php:113
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
if(count($args)==0) $dir
static getMetadataVersion()
Get metadata version.
static singleton()
Get an instance of this class.
Definition: MimeMagic.php:366
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:1798
getDescriptionShortUrl()
Get short description URL for a file based on the foreign API response, or if unavailable, the short URL is constructed from the foreign page ID.
getDescription($audience=self::FOR_PUBLIC, User $user=null)
canRender()
Checks if the output of transform() for this file is likely to be valid.
Definition: File.php:733
$files
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition: File.php:2248
getName()
Return the name of this file.
Definition: File.php:296
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
Represents a title within MediaWiki.
Definition: Title.php:34
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
Title string bool $title
Definition: File.php:98
getHashPath()
Get the filename hash component of the directory including trailing slash, e.g.
Definition: File.php:1497
getUser($type= 'text')
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition: design.txt:56
transform($params, $flags=0)
getThumbPath($suffix= '')
Only useful if we're locally caching thumbs anyway...
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
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:1798
Foreign file accessible through api.php requests.
purgeThumbnails($options=[])
getDBkey()
Get the main part with underscores.
Definition: Title.php:911
isTransformedLocally()
The thumbnail is created on the foreign server and fetched over internet.
getHandler()
Get a MediaHandler instance for this file.
Definition: File.php:1365
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1004
static newFromTitle(Title $title, $repo)
static getProps()
Get the property string for iiprop and aiprop.
$params
getExtension()
Get the file extension, e.g.
Definition: File.php:310
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition: File.php:95
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
Definition: distributors.txt:9
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
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:762
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
__construct($title, $repo, $info, $exists=false)
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:35
string $url
The URL corresponding to one of the four basic zones.
Definition: File.php:116
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
serialize()
Definition: ApiMessage.php:94
string $path
The storage path corresponding to one of the zones.
Definition: File.php:125
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:50
static parseMetadata($metadata)
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2338
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2338