MediaWiki master
ArchivedFile.php
Go to the documentation of this file.
1<?php
6
8
9use BadMethodCallException;
17use RuntimeException;
18use stdClass;
19use UnexpectedValueException;
23use Wikimedia\Timestamp\TimestampFormat as TS;
24
32
33 // Audience options for ::getDescription() and ::getUploader()
34 public const FOR_PUBLIC = 1;
35 public const FOR_THIS_USER = 2;
36 public const RAW = 3;
37
39 private const MDS_EMPTY = 'empty';
40
42 private const MDS_LEGACY = 'legacy';
43
45 private const MDS_PHP = 'php';
46
48 private const MDS_JSON = 'json';
49
51 private $id;
52
54 private $name;
55
57 private $group;
58
60 private $key;
61
63 private $size;
64
66 private $bits;
67
69 private $width;
70
72 private $height;
73
75 protected $metadataArray = [];
76
78 protected $extraDataLoaded = false;
79
87
89 protected $metadataBlobs = [];
90
97 protected $unloadedMetadataBlobs = [];
98
100 private $mime;
101
103 private $media_type;
104
106 private $description;
107
109 private $user;
110
112 private $timestamp;
113
115 private $dataLoaded;
116
118 private $deleted;
119
121 private $sha1;
122
126 private $pageCount;
127
129 private $archive_name;
130
132 protected $handler;
133
135 protected $title; # image title
136
138 protected $exists;
139
141 private $repo;
142
144 private $metadataStorageHelper;
145
153 public function __construct( $title, $id = 0, $key = '', $sha1 = '' ) {
154 $this->id = -1;
155 $this->title = null;
156 $this->name = false;
157 $this->group = 'deleted'; // needed for direct use of constructor
158 $this->key = '';
159 $this->size = 0;
160 $this->bits = 0;
161 $this->width = 0;
162 $this->height = 0;
163 $this->mime = "unknown/unknown";
164 $this->media_type = '';
165 $this->description = '';
166 $this->user = null;
167 $this->timestamp = null;
168 $this->deleted = 0;
169 $this->dataLoaded = false;
170 $this->exists = false;
171 $this->sha1 = '';
172
173 if ( $title instanceof Title ) {
174 $this->title = File::normalizeTitle( $title, 'exception' );
175 $this->name = $title->getDBkey();
176 }
177
178 if ( $id ) {
179 $this->id = $id;
180 }
181
182 if ( $key ) {
183 $this->key = $key;
184 }
185
186 if ( $sha1 ) {
187 $this->sha1 = $sha1;
188 }
189
190 if ( !$id && !$key && !( $title instanceof Title ) && !$sha1 ) {
191 throw new BadMethodCallException( "No specifications provided to ArchivedFile constructor." );
192 }
193
194 $this->repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
195 $this->metadataStorageHelper = new MetadataStorageHelper( $this->repo );
196 }
197
203 public function load() {
204 if ( $this->dataLoaded ) {
205 return true;
206 }
207 $conds = [];
208
209 if ( $this->id > 0 ) {
210 $conds['fa_id'] = $this->id;
211 }
212 if ( $this->key ) {
213 $conds['fa_storage_group'] = $this->group;
214 $conds['fa_storage_key'] = $this->key;
215 }
216 if ( $this->title ) {
217 $conds['fa_name'] = $this->title->getDBkey();
218 }
219 if ( $this->sha1 ) {
220 $conds['fa_sha1'] = $this->sha1;
221 }
222
223 if ( $conds === [] ) {
224 throw new RuntimeException( "No specific information for retrieving archived file" );
225 }
226
227 if ( !$this->title || $this->title->getNamespace() === NS_FILE ) {
228 $this->dataLoaded = true; // set it here, to have also true on miss
229 $dbr = $this->repo->getReplicaDB();
230 $queryBuilder = FileSelectQueryBuilder::newForArchivedFile( $dbr );
231 $row = $queryBuilder->where( $conds )
232 ->orderBy( 'fa_timestamp', SelectQueryBuilder::SORT_DESC )
233 ->caller( __METHOD__ )->fetchRow();
234 if ( !$row ) {
235 // this revision does not exist?
236 return null;
237 }
238
239 // initialize fields for filestore image object
240 $this->loadFromRow( $row );
241 } else {
242 throw new UnexpectedValueException( 'This title does not correspond to an image page.' );
243 }
244
245 return true;
246 }
247
255 public static function newFromRow( $row ) {
256 $file = new ArchivedFile( Title::makeTitle( NS_FILE, $row->fa_name ) );
257 $file->loadFromRow( $row );
258
259 return $file;
260 }
261
279 public static function getQueryInfo() {
280 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
282 return [
283 'tables' => $queryInfo['tables'],
284 'fields' => $queryInfo['fields'],
285 'joins' => $queryInfo['join_conds'],
286 ];
287 }
288
296 public function loadFromRow( $row ) {
297 $this->id = intval( $row->fa_id );
298 $this->name = $row->fa_name;
299 $this->archive_name = $row->fa_archive_name;
300 $this->group = $row->fa_storage_group;
301 $this->key = $row->fa_storage_key;
302 $this->size = $row->fa_size;
303 $this->bits = $row->fa_bits;
304 $this->width = $row->fa_width;
305 $this->height = $row->fa_height;
307 $this->repo->getReplicaDB(), $row->fa_metadata );
308 $this->mime = "$row->fa_major_mime/$row->fa_minor_mime";
309 $this->media_type = $row->fa_media_type;
310 $services = MediaWikiServices::getInstance();
311 $this->description = $services->getCommentStore()
312 // Legacy because $row may have come from self::selectFields()
313 ->getCommentLegacy( $this->repo->getReplicaDB(), 'fa_description', $row )->text;
314 $this->user = $services->getUserFactory()
315 ->newFromAnyId( $row->fa_user, $row->fa_user_text, $row->fa_actor );
316 $this->timestamp = $row->fa_timestamp;
317 $this->deleted = $row->fa_deleted;
318 if ( isset( $row->fa_sha1 ) ) {
319 $this->sha1 = $row->fa_sha1;
320 } else {
321 // old row, populate from key
322 $this->sha1 = LocalRepo::getHashFromKey( $this->key );
323 }
324 $this->title ??= Title::makeTitleSafe( NS_FILE, $row->fa_name );
325 $this->exists = $row->fa_archive_name !== '';
326 }
327
333 public function getTitle() {
334 if ( !$this->title ) {
335 $this->load();
336 }
337 return $this->title;
338 }
339
345 public function getName() {
346 if ( $this->name === false ) {
347 $this->load();
348 }
349
350 return $this->name;
351 }
352
356 public function getID() {
357 $this->load();
358
359 return $this->id;
360 }
361
365 public function exists() {
366 $this->load();
367
368 return $this->exists;
369 }
370
375 public function getKey() {
376 $this->load();
377
378 return $this->key;
379 }
380
385 public function getStorageKey() {
386 return $this->getKey();
387 }
388
393 public function getGroup() {
394 return $this->group;
395 }
396
401 public function getWidth() {
402 $this->load();
403
404 return $this->width;
405 }
406
411 public function getHeight() {
412 $this->load();
413
414 return $this->height;
415 }
416
423 public function getMetadata() {
424 wfDeprecated( __METHOD__, '1.37' ); // since 1.47
425 $data = $this->getMetadataArray();
426 if ( !$data ) {
427 return '';
428 } elseif ( array_keys( $data ) === [ '_error' ] ) {
429 // Legacy error encoding
430 return $data['_error'];
431 } else {
432 return serialize( $this->getMetadataArray() );
433 }
434 }
435
442 public function getMetadataArray(): array {
443 $this->load();
444 if ( $this->unloadedMetadataBlobs ) {
445 return $this->getMetadataItems(
446 array_unique( array_merge(
447 array_keys( $this->metadataArray ),
448 array_keys( $this->unloadedMetadataBlobs )
449 ) )
450 );
451 }
453 }
454
455 public function getMetadataItems( array $itemNames ): array {
456 $this->load();
457 $result = [];
458 $addresses = [];
459 foreach ( $itemNames as $itemName ) {
460 if ( array_key_exists( $itemName, $this->metadataArray ) ) {
461 $result[$itemName] = $this->metadataArray[$itemName];
462 } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
463 $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
464 }
465 }
466
467 if ( $addresses ) {
468 $resultFromBlob = $this->metadataStorageHelper->getMetadataFromBlobStore( $addresses );
469 foreach ( $addresses as $itemName => $address ) {
470 unset( $this->unloadedMetadataBlobs[$itemName] );
471 $value = $resultFromBlob[$itemName] ?? null;
472 if ( $value !== null ) {
473 $result[$itemName] = $value;
474 $this->metadataArray[$itemName] = $value;
475 }
476 }
477 }
478 return $result;
479 }
480
492 public function getMetadataForDb( IReadableDatabase $db ) {
493 $this->load();
494 if ( !$this->metadataArray && !$this->metadataBlobs ) {
495 $s = '';
496 } elseif ( $this->repo->isJsonMetadataEnabled() ) {
497 $s = $this->getJsonMetadata();
498 } else {
499 $s = serialize( $this->getMetadataArray() );
500 }
501 if ( !is_string( $s ) ) {
502 throw new RuntimeException( 'Could not serialize image metadata value for DB' );
503 }
504 return $db->encodeBlob( $s );
505 }
506
513 private function getJsonMetadata() {
514 // Directly store data that is not already in BlobStore
515 $envelope = [
516 'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
517 ];
518
519 // Also store the blob addresses
520 if ( $this->metadataBlobs ) {
521 $envelope['blobs'] = $this->metadataBlobs;
522 }
523
524 [ $s, $blobAddresses ] = $this->metadataStorageHelper->getJsonMetadata( $this, $envelope );
525
526 // Repeated calls to this function should not keep inserting more blobs
527 $this->metadataBlobs += $blobAddresses;
528
529 return $s;
530 }
531
540 protected function loadMetadataFromDbFieldValue( IReadableDatabase $db, $metadataBlob ) {
541 $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
542 }
543
551 protected function loadMetadataFromString( $metadataString ) {
552 $this->extraDataLoaded = true;
553 $this->metadataArray = [];
554 $this->metadataBlobs = [];
555 $this->unloadedMetadataBlobs = [];
556 $metadataString = (string)$metadataString;
557 if ( $metadataString === '' ) {
558 $this->metadataSerializationFormat = self::MDS_EMPTY;
559 return;
560 }
561 if ( $metadataString[0] === '{' ) {
562 $envelope = $this->metadataStorageHelper->jsonDecode( $metadataString );
563 if ( !$envelope ) {
564 // Legacy error encoding
565 $this->metadataArray = [ '_error' => $metadataString ];
566 $this->metadataSerializationFormat = self::MDS_LEGACY;
567 } else {
568 $this->metadataSerializationFormat = self::MDS_JSON;
569 if ( isset( $envelope['data'] ) ) {
570 $this->metadataArray = $envelope['data'];
571 }
572 if ( isset( $envelope['blobs'] ) ) {
573 $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope['blobs'];
574 }
575 }
576 } else {
577 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
578 $data = @unserialize( $metadataString );
579 if ( !is_array( $data ) ) {
580 // Legacy error encoding
581 $data = [ '_error' => $metadataString ];
582 $this->metadataSerializationFormat = self::MDS_LEGACY;
583 } else {
584 $this->metadataSerializationFormat = self::MDS_PHP;
585 }
586 $this->metadataArray = $data;
587 }
588 }
589
594 public function getSize() {
595 $this->load();
596
597 return $this->size;
598 }
599
603 public function getBits() {
604 $this->load();
605
606 return $this->bits;
607 }
608
613 public function getMimeType() {
614 $this->load();
615
616 return $this->mime;
617 }
618
623 private function getHandler() {
624 $this->handler ??= MediaHandler::getHandler( $this->getMimeType() );
625 return $this->handler;
626 }
627
634 public function pageCount() {
635 if ( $this->pageCount === null ) {
636 // @FIXME: callers expect File objects
637 // @phan-suppress-next-line PhanTypeMismatchArgument
638 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
639 // @phan-suppress-next-line PhanTypeMismatchArgument
640 $this->pageCount = $this->handler->pageCount( $this );
641 } else {
642 $this->pageCount = false;
643 }
644 }
645
646 return $this->pageCount;
647 }
648
654 public function getMediaType() {
655 $this->load();
656
657 return $this->media_type;
658 }
659
665 public function getTimestamp() {
666 $this->load();
667
668 return wfTimestamp( TS::MW, $this->timestamp );
669 }
670
677 public function getSha1() {
678 $this->load();
679
680 return $this->sha1;
681 }
682
694 public function getUploader( int $audience = self::FOR_PUBLIC, ?Authority $performer = null ): ?UserIdentity {
695 $this->load();
696 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( File::DELETED_USER ) ) {
697 return null;
698 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( File::DELETED_USER, $performer ) ) {
699 return null;
700 } else {
701 return $this->user;
702 }
703 }
704
717 public function getDescription( int $audience = self::FOR_PUBLIC, ?Authority $performer = null ): string {
718 $this->load();
719 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( File::DELETED_COMMENT ) ) {
720 return '';
721 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( File::DELETED_COMMENT, $performer ) ) {
722 return '';
723 } else {
724 return $this->description;
725 }
726 }
727
732 public function getVisibility() {
733 $this->load();
734
735 return $this->deleted;
736 }
737
744 public function isDeleted( $field ) {
745 $this->load();
746
747 return ( $this->deleted & $field ) == $field;
748 }
749
757 public function userCan( $field, Authority $performer ) {
758 $this->load();
759 $title = $this->getTitle();
760
761 return RevisionRecord::userCanBitfield(
762 $this->deleted,
763 $field,
764 $performer,
765 $title ?: null
766 );
767 }
768}
769
771class_alias( ArchivedFile::class, 'ArchivedFile' );
const NS_FILE
Definition Defines.php:57
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
Deleted file in the 'filearchive' table.
string[] $metadataBlobs
Map of metadata item name to blob address.
getSize()
Return the size of the image file, in bytes.
getMimeType()
Returns the MIME type of the file.
getTimestamp()
Return upload timestamp.
getWidth()
Return the width of the image.
getVisibility()
Returns the deletion bitfield.
load()
Loads a file object from the filearchive table.
static newFromRow( $row)
Loads a file object from the filearchive table.
getHeight()
Return the height of the image.
getDescription(int $audience=self::FOR_PUBLIC, ?Authority $performer=null)
Return upload description.
array $metadataArray
Unserialized metadata.
__construct( $title, $id=0, $key='', $sha1='')
getGroup()
Return the FileStore storage group.
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new archivedfile object.
loadMetadataFromString( $metadataString)
Unserialize a metadata string which came from some non-DB source, or is the return value of IReadable...
getSha1()
Get the SHA-1 base 36 hash of the file.
getStorageKey()
Return the FileStore key (overriding base File class).
userCan( $field, Authority $performer)
Determine if the current user is allowed to view a particular field of this FileStore image file,...
string null $metadataSerializationFormat
One of the MDS_* constants, giving the format of the metadata as stored in the DB,...
loadMetadataFromDbFieldValue(IReadableDatabase $db, $metadataBlob)
Unserialize a metadata blob which came from the database and store it in $this.
getUploader(int $audience=self::FOR_PUBLIC, ?Authority $performer=null)
getMetadataArray()
Get unserialized handler-specific metadata.
pageCount()
Returns the number of pages of a multipage document, or false for documents which aren't multipage do...
string[] $unloadedMetadataBlobs
Map of metadata item name to blob address for items that exist but have not yet been loaded into $thi...
isDeleted( $field)
for file or revision rows
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
getMetadata()
Get handler-specific metadata as a serialized string.
getKey()
Return the FileStore key.
getMetadataForDb(IReadableDatabase $db)
Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.
getTitle()
Return the associated title object.
getMediaType()
Return the type of the media in the file.
loadFromRow( $row)
Load ArchivedFile object fields from a DB row.
static newForArchivedFile(IReadableDatabase $db, array $options=[])
static normalizeTitle( $title, $exception=false)
Given a string or Title object return either a valid Title object with namespace NS_FILE or null.
Definition File.php:221
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:43
static getHashFromKey( $key)
Gets the SHA1 hash from a storage key.
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Base media handler class.
Page revision base class.
Represents a title within MediaWiki.
Definition Title.php:69
getDBkey()
Get the main part with underscores.
Definition Title.php:1020
Build SELECT queries with a fluent interface.
This interface represents the authority associated with the current execution context,...
Definition Authority.php:23
Interface for objects representing user identity.
A database connection without write operations.
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.