Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / filerepo / file / ArchivedFile.php
blob9dd0fad0b9e42ebdce3691f48831593dd04dc39d
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
21 use MediaWiki\FileRepo\File\FileSelectQueryBuilder;
22 use MediaWiki\MediaWikiServices;
23 use MediaWiki\Permissions\Authority;
24 use MediaWiki\Revision\RevisionRecord;
25 use MediaWiki\Title\Title;
26 use MediaWiki\User\UserIdentity;
27 use Wikimedia\Rdbms\Blob;
28 use Wikimedia\Rdbms\IReadableDatabase;
29 use Wikimedia\Rdbms\SelectQueryBuilder;
31 /**
32 * Deleted file in the 'filearchive' table.
34 * @stable to extend
35 * @ingroup FileAbstraction
37 class ArchivedFile {
39 // Audience options for ::getDescription() and ::getUploader()
40 public const FOR_PUBLIC = 1;
41 public const FOR_THIS_USER = 2;
42 public const RAW = 3;
44 /** @var string Metadata serialization: empty string. This is a compact non-legacy format. */
45 private const MDS_EMPTY = 'empty';
47 /** @var string Metadata serialization: some other string */
48 private const MDS_LEGACY = 'legacy';
50 /** @var string Metadata serialization: PHP serialize() */
51 private const MDS_PHP = 'php';
53 /** @var string Metadata serialization: JSON */
54 private const MDS_JSON = 'json';
56 /** @var int Filearchive row ID */
57 private $id;
59 /** @var string|false File name */
60 private $name;
62 /** @var string FileStore storage group */
63 private $group;
65 /** @var string FileStore SHA-1 key */
66 private $key;
68 /** @var int File size in bytes */
69 private $size;
71 /** @var int Bitdepth */
72 private $bits;
74 /** @var int */
75 private $width;
77 /** @var int */
78 private $height;
80 /** @var array Unserialized metadata */
81 protected $metadataArray = [];
83 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
84 protected $extraDataLoaded = false;
86 /**
87 * One of the MDS_* constants, giving the format of the metadata as stored
88 * in the DB, or null if the data was not loaded from the DB.
90 * @var string|null
92 protected $metadataSerializationFormat;
94 /** @var string[] Map of metadata item name to blob address */
95 protected $metadataBlobs = [];
97 /**
98 * Map of metadata item name to blob address for items that exist but
99 * have not yet been loaded into $this->metadataArray
101 * @var string[]
103 protected $unloadedMetadataBlobs = [];
105 /** @var string MIME type */
106 private $mime;
108 /** @var string Media type */
109 private $media_type;
111 /** @var string Upload description */
112 private $description;
114 /** @var UserIdentity|null Uploader */
115 private $user;
117 /** @var string|null Time of upload */
118 private $timestamp;
120 /** @var bool Whether or not all this has been loaded from the database (loadFromXxx) */
121 private $dataLoaded;
123 /** @var int Bitfield akin to rev_deleted */
124 private $deleted;
126 /** @var string SHA-1 hash of file content */
127 private $sha1;
129 /** @var int|false Number of pages of a multipage document, or false for
130 * documents which aren't multipage documents
132 private $pageCount;
134 /** @var string Original base filename */
135 private $archive_name;
137 /** @var MediaHandler */
138 protected $handler;
140 /** @var Title|null */
141 protected $title; # image title
143 /** @var bool */
144 protected $exists;
146 /** @var LocalRepo */
147 private $repo;
149 /** @var MetadataStorageHelper */
150 private $metadataStorageHelper;
153 * @stable to call
154 * @param Title|null $title
155 * @param int $id
156 * @param string $key
157 * @param string $sha1
159 public function __construct( $title, $id = 0, $key = '', $sha1 = '' ) {
160 $this->id = -1;
161 $this->title = null;
162 $this->name = false;
163 $this->group = 'deleted'; // needed for direct use of constructor
164 $this->key = '';
165 $this->size = 0;
166 $this->bits = 0;
167 $this->width = 0;
168 $this->height = 0;
169 $this->mime = "unknown/unknown";
170 $this->media_type = '';
171 $this->description = '';
172 $this->user = null;
173 $this->timestamp = null;
174 $this->deleted = 0;
175 $this->dataLoaded = false;
176 $this->exists = false;
177 $this->sha1 = '';
179 if ( $title instanceof Title ) {
180 $this->title = File::normalizeTitle( $title, 'exception' );
181 $this->name = $title->getDBkey();
184 if ( $id ) {
185 $this->id = $id;
188 if ( $key ) {
189 $this->key = $key;
192 if ( $sha1 ) {
193 $this->sha1 = $sha1;
196 if ( !$id && !$key && !( $title instanceof Title ) && !$sha1 ) {
197 throw new BadMethodCallException( "No specifications provided to ArchivedFile constructor." );
200 $this->repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
201 $this->metadataStorageHelper = new MetadataStorageHelper( $this->repo );
205 * Loads a file object from the filearchive table
206 * @stable to override
207 * @return bool|null True on success or null
209 public function load() {
210 if ( $this->dataLoaded ) {
211 return true;
213 $conds = [];
215 if ( $this->id > 0 ) {
216 $conds['fa_id'] = $this->id;
218 if ( $this->key ) {
219 $conds['fa_storage_group'] = $this->group;
220 $conds['fa_storage_key'] = $this->key;
222 if ( $this->title ) {
223 $conds['fa_name'] = $this->title->getDBkey();
225 if ( $this->sha1 ) {
226 $conds['fa_sha1'] = $this->sha1;
229 if ( $conds === [] ) {
230 throw new RuntimeException( "No specific information for retrieving archived file" );
233 if ( !$this->title || $this->title->getNamespace() === NS_FILE ) {
234 $this->dataLoaded = true; // set it here, to have also true on miss
235 $dbr = $this->repo->getReplicaDB();
236 $queryBuilder = FileSelectQueryBuilder::newForArchivedFile( $dbr );
237 $row = $queryBuilder->where( $conds )
238 ->orderBy( 'fa_timestamp', SelectQueryBuilder::SORT_DESC )
239 ->caller( __METHOD__ )->fetchRow();
240 if ( !$row ) {
241 // this revision does not exist?
242 return null;
245 // initialize fields for filestore image object
246 $this->loadFromRow( $row );
247 } else {
248 throw new UnexpectedValueException( 'This title does not correspond to an image page.' );
251 return true;
255 * Loads a file object from the filearchive table
256 * @stable to override
258 * @param stdClass $row
259 * @return ArchivedFile
261 public static function newFromRow( $row ) {
262 $file = new ArchivedFile( Title::makeTitle( NS_FILE, $row->fa_name ) );
263 $file->loadFromRow( $row );
265 return $file;
269 * Return the tables, fields, and join conditions to be selected to create
270 * a new archivedfile object.
272 * Since 1.34, fa_user and fa_user_text have not been present in the
273 * database, but they continue to be available in query results as an
274 * alias.
276 * @since 1.31
277 * @stable to override
278 * @deprecated since 1.41 use FileSelectQueryBuilder instead
279 * @return array[] With three keys:
280 * - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
281 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
282 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
283 * @phan-return array{tables:string[],fields:string[],joins:array}
285 public static function getQueryInfo() {
286 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
287 $queryInfo = ( FileSelectQueryBuilder::newForArchivedFile( $dbr ) )->getQueryInfo();
288 return [
289 'tables' => $queryInfo['tables'],
290 'fields' => $queryInfo['fields'],
291 'joins' => $queryInfo['join_conds'],
296 * Load ArchivedFile object fields from a DB row.
297 * @stable to override
299 * @param stdClass $row Object database row
300 * @since 1.21
302 public function loadFromRow( $row ) {
303 $this->id = intval( $row->fa_id );
304 $this->name = $row->fa_name;
305 $this->archive_name = $row->fa_archive_name;
306 $this->group = $row->fa_storage_group;
307 $this->key = $row->fa_storage_key;
308 $this->size = $row->fa_size;
309 $this->bits = $row->fa_bits;
310 $this->width = $row->fa_width;
311 $this->height = $row->fa_height;
312 $this->loadMetadataFromDbFieldValue(
313 $this->repo->getReplicaDB(), $row->fa_metadata );
314 $this->mime = "$row->fa_major_mime/$row->fa_minor_mime";
315 $this->media_type = $row->fa_media_type;
316 $services = MediaWikiServices::getInstance();
317 $this->description = $services->getCommentStore()
318 // Legacy because $row may have come from self::selectFields()
319 ->getCommentLegacy( $this->repo->getReplicaDB(), 'fa_description', $row )->text;
320 $this->user = $services->getUserFactory()
321 ->newFromAnyId( $row->fa_user, $row->fa_user_text, $row->fa_actor );
322 $this->timestamp = $row->fa_timestamp;
323 $this->deleted = $row->fa_deleted;
324 if ( isset( $row->fa_sha1 ) ) {
325 $this->sha1 = $row->fa_sha1;
326 } else {
327 // old row, populate from key
328 $this->sha1 = LocalRepo::getHashFromKey( $this->key );
330 if ( !$this->title ) {
331 $this->title = Title::makeTitleSafe( NS_FILE, $row->fa_name );
333 $this->exists = $row->fa_archive_name !== '';
337 * Return the associated title object
339 * @return Title
341 public function getTitle() {
342 if ( !$this->title ) {
343 $this->load();
345 return $this->title;
349 * Return the file name
351 * @return string
353 public function getName() {
354 if ( $this->name === false ) {
355 $this->load();
358 return $this->name;
362 * @return int
364 public function getID() {
365 $this->load();
367 return $this->id;
371 * @return bool
373 public function exists() {
374 $this->load();
376 return $this->exists;
380 * Return the FileStore key
381 * @return string
383 public function getKey() {
384 $this->load();
386 return $this->key;
390 * Return the FileStore key (overriding base File class)
391 * @return string
393 public function getStorageKey() {
394 return $this->getKey();
398 * Return the FileStore storage group
399 * @return string
401 public function getGroup() {
402 return $this->group;
406 * Return the width of the image
407 * @return int
409 public function getWidth() {
410 $this->load();
412 return $this->width;
416 * Return the height of the image
417 * @return int
419 public function getHeight() {
420 $this->load();
422 return $this->height;
426 * Get handler-specific metadata as a serialized string
428 * @deprecated since 1.37 use getMetadataArray() or getMetadataItem()
429 * @return string
431 public function getMetadata() {
432 $data = $this->getMetadataArray();
433 if ( !$data ) {
434 return '';
435 } elseif ( array_keys( $data ) === [ '_error' ] ) {
436 // Legacy error encoding
437 return $data['_error'];
438 } else {
439 return serialize( $this->getMetadataArray() );
444 * Get unserialized handler-specific metadata
446 * @since 1.39
447 * @return array
449 public function getMetadataArray(): array {
450 $this->load();
451 if ( $this->unloadedMetadataBlobs ) {
452 return $this->getMetadataItems(
453 array_unique( array_merge(
454 array_keys( $this->metadataArray ),
455 array_keys( $this->unloadedMetadataBlobs )
459 return $this->metadataArray;
462 public function getMetadataItems( array $itemNames ): array {
463 $this->load();
464 $result = [];
465 $addresses = [];
466 foreach ( $itemNames as $itemName ) {
467 if ( array_key_exists( $itemName, $this->metadataArray ) ) {
468 $result[$itemName] = $this->metadataArray[$itemName];
469 } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
470 $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
474 if ( $addresses ) {
475 $resultFromBlob = $this->metadataStorageHelper->getMetadataFromBlobStore( $addresses );
476 foreach ( $addresses as $itemName => $address ) {
477 unset( $this->unloadedMetadataBlobs[$itemName] );
478 $value = $resultFromBlob[$itemName] ?? null;
479 if ( $value !== null ) {
480 $result[$itemName] = $value;
481 $this->metadataArray[$itemName] = $value;
485 return $result;
489 * Serialize the metadata array for insertion into img_metadata, oi_metadata
490 * or fa_metadata.
492 * If metadata splitting is enabled, this may write blobs to the database,
493 * returning their addresses.
495 * @internal
496 * @param IReadableDatabase $db
497 * @return string|Blob
499 public function getMetadataForDb( IReadableDatabase $db ) {
500 $this->load();
501 if ( !$this->metadataArray && !$this->metadataBlobs ) {
502 $s = '';
503 } elseif ( $this->repo->isJsonMetadataEnabled() ) {
504 $s = $this->getJsonMetadata();
505 } else {
506 $s = serialize( $this->getMetadataArray() );
508 if ( !is_string( $s ) ) {
509 throw new RuntimeException( 'Could not serialize image metadata value for DB' );
511 return $db->encodeBlob( $s );
515 * Get metadata in JSON format ready for DB insertion, optionally splitting
516 * items out to BlobStore.
518 * @return string
520 private function getJsonMetadata() {
521 // Directly store data that is not already in BlobStore
522 $envelope = [
523 'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
526 // Also store the blob addresses
527 if ( $this->metadataBlobs ) {
528 $envelope['blobs'] = $this->metadataBlobs;
531 [ $s, $blobAddresses ] = $this->metadataStorageHelper->getJsonMetadata( $this, $envelope );
533 // Repeated calls to this function should not keep inserting more blobs
534 $this->metadataBlobs += $blobAddresses;
536 return $s;
540 * Unserialize a metadata blob which came from the database and store it
541 * in $this.
543 * @since 1.39
544 * @param IReadableDatabase $db
545 * @param string|Blob $metadataBlob
547 protected function loadMetadataFromDbFieldValue( IReadableDatabase $db, $metadataBlob ) {
548 $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
552 * Unserialize a metadata string which came from some non-DB source, or is
553 * the return value of IReadableDatabase::decodeBlob().
555 * @since 1.37
556 * @param string $metadataString
558 protected function loadMetadataFromString( $metadataString ) {
559 $this->extraDataLoaded = true;
560 $this->metadataArray = [];
561 $this->metadataBlobs = [];
562 $this->unloadedMetadataBlobs = [];
563 $metadataString = (string)$metadataString;
564 if ( $metadataString === '' ) {
565 $this->metadataSerializationFormat = self::MDS_EMPTY;
566 return;
568 if ( $metadataString[0] === '{' ) {
569 $envelope = $this->metadataStorageHelper->jsonDecode( $metadataString );
570 if ( !$envelope ) {
571 // Legacy error encoding
572 $this->metadataArray = [ '_error' => $metadataString ];
573 $this->metadataSerializationFormat = self::MDS_LEGACY;
574 } else {
575 $this->metadataSerializationFormat = self::MDS_JSON;
576 if ( isset( $envelope['data'] ) ) {
577 $this->metadataArray = $envelope['data'];
579 if ( isset( $envelope['blobs'] ) ) {
580 $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope['blobs'];
583 } else {
584 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
585 $data = @unserialize( $metadataString );
586 if ( !is_array( $data ) ) {
587 // Legacy error encoding
588 $data = [ '_error' => $metadataString ];
589 $this->metadataSerializationFormat = self::MDS_LEGACY;
590 } else {
591 $this->metadataSerializationFormat = self::MDS_PHP;
593 $this->metadataArray = $data;
598 * Return the size of the image file, in bytes
599 * @return int
601 public function getSize() {
602 $this->load();
604 return $this->size;
608 * @return int
610 public function getBits() {
611 $this->load();
613 return $this->bits;
617 * Returns the MIME type of the file.
618 * @return string
620 public function getMimeType() {
621 $this->load();
623 return $this->mime;
627 * Get a MediaHandler instance for this file
628 * @return MediaHandler
630 private function getHandler() {
631 if ( !$this->handler ) {
632 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
635 return $this->handler;
639 * Returns the number of pages of a multipage document, or false for
640 * documents which aren't multipage documents
641 * @stable to override
642 * @return int|false
644 public function pageCount() {
645 if ( $this->pageCount === null ) {
646 // @FIXME: callers expect File objects
647 // @phan-suppress-next-line PhanTypeMismatchArgument
648 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
649 // @phan-suppress-next-line PhanTypeMismatchArgument
650 $this->pageCount = $this->handler->pageCount( $this );
651 } else {
652 $this->pageCount = false;
656 return $this->pageCount;
660 * Return the type of the media in the file.
661 * Use the value returned by this function with the MEDIATYPE_xxx constants.
662 * @return string
664 public function getMediaType() {
665 $this->load();
667 return $this->media_type;
671 * Return upload timestamp.
673 * @return string
675 public function getTimestamp() {
676 $this->load();
678 return wfTimestamp( TS_MW, $this->timestamp );
682 * Get the SHA-1 base 36 hash of the file
684 * @return string
685 * @since 1.21
687 public function getSha1() {
688 $this->load();
690 return $this->sha1;
694 * @since 1.37
695 * @stable to override
696 * @param int $audience One of:
697 * File::FOR_PUBLIC to be displayed to all users
698 * File::FOR_THIS_USER to be displayed to the given user
699 * File::RAW get the description regardless of permissions
700 * @param Authority|null $performer to check for, only if FOR_THIS_USER is
701 * passed to the $audience parameter
702 * @return UserIdentity|null
704 public function getUploader( int $audience = self::FOR_PUBLIC, ?Authority $performer = null ): ?UserIdentity {
705 $this->load();
706 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( File::DELETED_USER ) ) {
707 return null;
708 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( File::DELETED_USER, $performer ) ) {
709 return null;
710 } else {
711 return $this->user;
716 * Return upload description.
718 * @since 1.37 the method takes $audience and $performer parameters.
719 * @param int $audience One of:
720 * File::FOR_PUBLIC to be displayed to all users
721 * File::FOR_THIS_USER to be displayed to the given user
722 * File::RAW get the description regardless of permissions
723 * @param Authority|null $performer to check for, only if FOR_THIS_USER is
724 * passed to the $audience parameter
725 * @return string
727 public function getDescription( int $audience = self::FOR_PUBLIC, ?Authority $performer = null ): string {
728 $this->load();
729 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( File::DELETED_COMMENT ) ) {
730 return '';
731 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( File::DELETED_COMMENT, $performer ) ) {
732 return '';
733 } else {
734 return $this->description;
739 * Returns the deletion bitfield
740 * @return int
742 public function getVisibility() {
743 $this->load();
745 return $this->deleted;
749 * for file or revision rows
751 * @param int $field One of DELETED_* bitfield constants
752 * @return bool
754 public function isDeleted( $field ) {
755 $this->load();
757 return ( $this->deleted & $field ) == $field;
761 * Determine if the current user is allowed to view a particular
762 * field of this FileStore image file, if it's marked as deleted.
763 * @param int $field
764 * @param Authority $performer
765 * @return bool
767 public function userCan( $field, Authority $performer ) {
768 $this->load();
769 $title = $this->getTitle();
771 return RevisionRecord::userCanBitfield(
772 $this->deleted,
773 $field,
774 $performer,
775 $title ?: null