MediaWiki master
LocalFile.php
Go to the documentation of this file.
1<?php
41
68class LocalFile extends File {
69 private const VERSION = 13; // cache version
70
71 private const CACHE_FIELD_MAX_LEN = 1000;
72
74 private const MDS_EMPTY = 'empty';
75
77 private const MDS_LEGACY = 'legacy';
78
80 private const MDS_PHP = 'php';
81
83 private const MDS_JSON = 'json';
84
86 private const MAX_PAGE_RENDER_JOBS = 50;
87
89 protected $fileExists;
90
92 protected $width;
93
95 protected $height;
96
98 protected $bits;
99
101 protected $media_type;
102
104 protected $mime;
105
107 protected $size;
108
110 protected $metadataArray = [];
111
119
121 protected $metadataBlobs = [];
122
129 protected $unloadedMetadataBlobs = [];
130
132 protected $sha1;
133
135 protected $dataLoaded = false;
136
138 protected $extraDataLoaded = false;
139
141 protected $deleted;
142
144 protected $repoClass = LocalRepo::class;
145
147 private $historyLine = 0;
148
150 private $historyRes = null;
151
153 private $major_mime;
154
156 private $minor_mime;
157
159 private $timestamp;
160
162 private $user;
163
165 private $description;
166
168 private $descriptionTouched;
169
171 private $upgraded;
172
174 private $upgrading;
175
177 private $locked;
178
180 private $lockedOwnTrx;
181
183 private $missing;
184
186 private $metadataStorageHelper;
187
188 // @note: higher than IDBAccessObject constants
189 private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
190
191 private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
192
207 public static function newFromTitle( $title, $repo, $unused = null ) {
208 return new static( $title, $repo );
209 }
210
222 public static function newFromRow( $row, $repo ) {
223 $title = Title::makeTitle( NS_FILE, $row->img_name );
224 $file = new static( $title, $repo );
225 $file->loadFromRow( $row );
226
227 return $file;
228 }
229
241 public static function newFromKey( $sha1, $repo, $timestamp = false ) {
242 $dbr = $repo->getReplicaDB();
243 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
244
245 $queryBuilder->where( [ 'img_sha1' => $sha1 ] );
246
247 if ( $timestamp ) {
248 $queryBuilder->andWhere( [ 'img_timestamp' => $dbr->timestamp( $timestamp ) ] );
249 }
250
251 $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
252 if ( $row ) {
253 return static::newFromRow( $row, $repo );
254 } else {
255 return false;
256 }
257 }
258
279 public static function getQueryInfo( array $options = [] ) {
280 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
281 $queryInfo = FileSelectQueryBuilder::newForFile( $dbr, $options )->getQueryInfo();
282 // needs remapping...
283 return [
284 'tables' => $queryInfo['tables'],
285 'fields' => $queryInfo['fields'],
286 'joins' => $queryInfo['join_conds'],
287 ];
288 }
289
297 public function __construct( $title, $repo ) {
298 parent::__construct( $title, $repo );
299 $this->metadataStorageHelper = new MetadataStorageHelper( $repo );
300
301 $this->assertRepoDefined();
302 $this->assertTitleDefined();
303 }
304
308 public function getRepo() {
309 return $this->repo;
310 }
311
318 protected function getCacheKey() {
319 return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
320 }
321
325 private function loadFromCache() {
326 $this->dataLoaded = false;
327 $this->extraDataLoaded = false;
328
329 $key = $this->getCacheKey();
330 if ( !$key ) {
331 $this->loadFromDB( IDBAccessObject::READ_NORMAL );
332
333 return;
334 }
335
336 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
337 $cachedValues = $cache->getWithSetCallback(
338 $key,
339 $cache::TTL_WEEK,
340 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
341 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
342
343 $this->loadFromDB( IDBAccessObject::READ_NORMAL );
344
345 $fields = $this->getCacheFields( '' );
346 $cacheVal = [];
347 $cacheVal['fileExists'] = $this->fileExists;
348 if ( $this->fileExists ) {
349 foreach ( $fields as $field ) {
350 $cacheVal[$field] = $this->$field;
351 }
352 }
353 if ( $this->user ) {
354 $cacheVal['user'] = $this->user->getId();
355 $cacheVal['user_text'] = $this->user->getName();
356 }
357
358 // Don't cache metadata items stored as blobs, since they tend to be large
359 if ( $this->metadataBlobs ) {
360 $cacheVal['metadata'] = array_diff_key(
361 $this->metadataArray, $this->metadataBlobs );
362 // Save the blob addresses
363 $cacheVal['metadataBlobs'] = $this->metadataBlobs;
364 } else {
365 $cacheVal['metadata'] = $this->metadataArray;
366 }
367
368 // Strip off excessive entries from the subset of fields that can become large.
369 // If the cache value gets too large and might not fit in the cache,
370 // causing repeat database queries for each access to the file.
371 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
372 if ( isset( $cacheVal[$field] )
373 && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
374 ) {
375 unset( $cacheVal[$field] ); // don't let the value get too big
376 if ( $field === 'metadata' ) {
377 unset( $cacheVal['metadataBlobs'] );
378 }
379 }
380 }
381
382 if ( $this->fileExists ) {
383 $ttl = $cache->adaptiveTTL( (int)wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
384 } else {
385 $ttl = $cache::TTL_DAY;
386 }
387
388 return $cacheVal;
389 },
390 [ 'version' => self::VERSION ]
391 );
392
393 $this->fileExists = $cachedValues['fileExists'];
394 if ( $this->fileExists ) {
395 $this->setProps( $cachedValues );
396 }
397
398 $this->dataLoaded = true;
399 $this->extraDataLoaded = true;
400 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
401 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
402 }
403 }
404
408 public function invalidateCache() {
409 $key = $this->getCacheKey();
410 if ( !$key ) {
411 return;
412 }
413
414 $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
415 static function () use ( $key ) {
416 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
417 },
418 __METHOD__
419 );
420 }
421
429 public function loadFromFile( $path = null ) {
430 $props = $this->repo->getFileProps( $path ?? $this->getVirtualUrl() );
431 $this->setProps( $props );
432 }
433
441 protected function getCacheFields( $prefix = 'img_' ) {
442 if ( $prefix !== '' ) {
443 throw new InvalidArgumentException(
444 __METHOD__ . ' with a non-empty prefix is no longer supported.'
445 );
446 }
447
448 // See self::getQueryInfo() for the fetching of the data from the DB,
449 // self::loadFromRow() for the loading of the object from the DB row,
450 // and self::loadFromCache() for the caching, and self::setProps() for
451 // populating the object from an array of data.
452 return [ 'size', 'width', 'height', 'bits', 'media_type',
453 'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
454 }
455
463 protected function getLazyCacheFields( $prefix = 'img_' ) {
464 if ( $prefix !== '' ) {
465 throw new InvalidArgumentException(
466 __METHOD__ . ' with a non-empty prefix is no longer supported.'
467 );
468 }
469
470 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
471 return [ 'metadata' ];
472 }
473
479 protected function loadFromDB( $flags = 0 ) {
480 $fname = static::class . '::' . __FUNCTION__;
481
482 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
483 $this->dataLoaded = true;
484 $this->extraDataLoaded = true;
485
486 $dbr = ( $flags & IDBAccessObject::READ_LATEST )
487 ? $this->repo->getPrimaryDB()
488 : $this->repo->getReplicaDB();
489 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
490
491 $queryBuilder->where( [ 'img_name' => $this->getName() ] );
492 $row = $queryBuilder->caller( $fname )->fetchRow();
493
494 if ( $row ) {
495 $this->loadFromRow( $row );
496 } else {
497 $this->fileExists = false;
498 }
499 }
500
506 protected function loadExtraFromDB() {
507 if ( !$this->title ) {
508 return; // Avoid hard failure when the file does not exist. T221812
509 }
510
511 $fname = static::class . '::' . __FUNCTION__;
512
513 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
514 $this->extraDataLoaded = true;
515
516 $db = $this->repo->getReplicaDB();
517 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
518 if ( !$fieldMap ) {
519 $db = $this->repo->getPrimaryDB();
520 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
521 }
522
523 if ( $fieldMap ) {
524 if ( isset( $fieldMap['metadata'] ) ) {
525 $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
526 }
527 } else {
528 throw new RuntimeException( "Could not find data for image '{$this->getName()}'." );
529 }
530 }
531
537 private function loadExtraFieldsWithTimestamp( IReadableDatabase $dbr, $fname ) {
538 $fieldMap = false;
539
540 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr, [ 'omit-nonlazy' ] );
541 $queryBuilder->where( [ 'img_name' => $this->getName() ] )
542 ->andWhere( [ 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] );
543 $row = $queryBuilder->caller( $fname )->fetchRow();
544 if ( $row ) {
545 $fieldMap = $this->unprefixRow( $row, 'img_' );
546 } else {
547 # File may have been uploaded over in the meantime; check the old versions
548 $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr, [ 'omit-nonlazy' ] );
549 $row = $queryBuilder->where( [ 'oi_name' => $this->getName() ] )
550 ->andWhere( [ 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] )
551 ->caller( __METHOD__ )->fetchRow();
552 if ( $row ) {
553 $fieldMap = $this->unprefixRow( $row, 'oi_' );
554 }
555 }
556
557 return $fieldMap;
558 }
559
565 protected function unprefixRow( $row, $prefix = 'img_' ) {
566 $array = (array)$row;
567 $prefixLength = strlen( $prefix );
568
569 // Double check prefix once
570 if ( substr( array_key_first( $array ), 0, $prefixLength ) !== $prefix ) {
571 throw new InvalidArgumentException( __METHOD__ . ': incorrect $prefix parameter' );
572 }
573
574 $decoded = [];
575 foreach ( $array as $name => $value ) {
576 $decoded[substr( $name, $prefixLength )] = $value;
577 }
578
579 return $decoded;
580 }
581
597 public function loadFromRow( $row, $prefix = 'img_' ) {
598 $this->dataLoaded = true;
599
600 $unprefixed = $this->unprefixRow( $row, $prefix );
601
602 $this->name = $unprefixed['name'];
603 $this->media_type = $unprefixed['media_type'];
604
605 $services = MediaWikiServices::getInstance();
606 $this->description = $services->getCommentStore()
607 ->getComment( "{$prefix}description", $row )->text;
608
609 $this->user = $services->getUserFactory()->newFromAnyId(
610 $unprefixed['user'] ?? null,
611 $unprefixed['user_text'] ?? null,
612 $unprefixed['actor'] ?? null
613 );
614
615 $this->timestamp = wfTimestamp( TS_MW, $unprefixed['timestamp'] );
616
618 $this->repo->getReplicaDB(), $unprefixed['metadata'] );
619
620 if ( empty( $unprefixed['major_mime'] ) ) {
621 $this->major_mime = 'unknown';
622 $this->minor_mime = 'unknown';
623 $this->mime = 'unknown/unknown';
624 } else {
625 if ( !$unprefixed['minor_mime'] ) {
626 $unprefixed['minor_mime'] = 'unknown';
627 }
628 $this->major_mime = $unprefixed['major_mime'];
629 $this->minor_mime = $unprefixed['minor_mime'];
630 $this->mime = $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
631 }
632
633 // Trim zero padding from char/binary field
634 $this->sha1 = rtrim( $unprefixed['sha1'], "\0" );
635
636 // Normalize some fields to integer type, per their database definition.
637 // Use unary + so that overflows will be upgraded to double instead of
638 // being truncated as with intval(). This is important to allow > 2 GiB
639 // files on 32-bit systems.
640 $this->size = +$unprefixed['size'];
641 $this->width = +$unprefixed['width'];
642 $this->height = +$unprefixed['height'];
643 $this->bits = +$unprefixed['bits'];
644
645 // Check for extra fields (deprecated since MW 1.37)
646 $extraFields = array_diff(
647 array_keys( $unprefixed ),
648 [
649 'name', 'media_type', 'description_text', 'description_data',
650 'description_cid', 'user', 'user_text', 'actor', 'timestamp',
651 'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
652 'height', 'bits'
653 ]
654 );
655 if ( $extraFields ) {
657 'Passing extra fields (' .
658 implode( ', ', $extraFields )
659 . ') to ' . __METHOD__ . ' was deprecated in MediaWiki 1.37. ' .
660 'Property assignment will be removed in a later version.',
661 '1.37' );
662 foreach ( $extraFields as $field ) {
663 $this->$field = $unprefixed[$field];
664 }
665 }
666
667 $this->fileExists = true;
668 }
669
675 public function load( $flags = 0 ) {
676 if ( !$this->dataLoaded ) {
677 if ( $flags & IDBAccessObject::READ_LATEST ) {
678 $this->loadFromDB( $flags );
679 } else {
680 $this->loadFromCache();
681 }
682 }
683
684 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
685 // @note: loads on name/timestamp to reduce race condition problems
686 $this->loadExtraFromDB();
687 }
688 }
689
694 public function maybeUpgradeRow() {
695 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() || $this->upgrading ) {
696 return;
697 }
698
699 $upgrade = false;
700 $reserialize = false;
701 if ( $this->media_type === null || $this->mime == 'image/svg' ) {
702 $upgrade = true;
703 } else {
704 $handler = $this->getHandler();
705 if ( $handler ) {
706 $validity = $handler->isFileMetadataValid( $this );
707 if ( $validity === MediaHandler::METADATA_BAD ) {
708 $upgrade = true;
709 } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE
710 && $this->repo->isMetadataUpdateEnabled()
711 ) {
712 $upgrade = true;
713 } elseif ( $this->repo->isJsonMetadataEnabled()
714 && $this->repo->isMetadataReserializeEnabled()
715 ) {
716 if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
717 $reserialize = true;
718 } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
719 $this->metadataSerializationFormat !== self::MDS_JSON ) {
720 $reserialize = true;
721 }
722 }
723 }
724 }
725
726 if ( $upgrade || $reserialize ) {
727 $this->upgrading = true;
728 // Defer updates unless in auto-commit CLI mode
729 DeferredUpdates::addCallableUpdate( function () use ( $upgrade ) {
730 $this->upgrading = false; // avoid duplicate updates
731 try {
732 if ( $upgrade ) {
733 $this->upgradeRow();
734 } else {
735 $this->reserializeMetadata();
736 }
737 } catch ( LocalFileLockError $e ) {
738 // let the other process handle it (or do it next time)
739 }
740 } );
741 }
742 }
743
747 public function getUpgraded() {
748 return $this->upgraded;
749 }
750
755 public function upgradeRow() {
756 $dbw = $this->repo->getPrimaryDB();
757
758 // Make a DB query condition that will fail to match the image row if the
759 // image was reuploaded while the upgrade was in process.
760 $freshnessCondition = [ 'img_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ];
761
762 $this->loadFromFile();
763
764 # Don't destroy file info of missing files
765 if ( !$this->fileExists ) {
766 wfDebug( __METHOD__ . ": file does not exist, aborting" );
767
768 return;
769 }
770
771 [ $major, $minor ] = self::splitMime( $this->mime );
772
773 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
774
775 $dbw->newUpdateQueryBuilder()
776 ->update( 'image' )
777 ->set( [
778 'img_size' => $this->size,
779 'img_width' => $this->width,
780 'img_height' => $this->height,
781 'img_bits' => $this->bits,
782 'img_media_type' => $this->media_type,
783 'img_major_mime' => $major,
784 'img_minor_mime' => $minor,
785 'img_metadata' => $this->getMetadataForDb( $dbw ),
786 'img_sha1' => $this->sha1,
787 ] )
788 ->where( [ 'img_name' => $this->getName() ] )
789 ->andWhere( $freshnessCondition )
790 ->caller( __METHOD__ )->execute();
791
792 $this->invalidateCache();
793
794 $this->upgraded = true; // avoid rework/retries
795 }
796
801 protected function reserializeMetadata() {
802 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
803 return;
804 }
805 $dbw = $this->repo->getPrimaryDB();
806 $dbw->newUpdateQueryBuilder()
807 ->update( 'image' )
808 ->set( [ 'img_metadata' => $this->getMetadataForDb( $dbw ) ] )
809 ->where( [
810 'img_name' => $this->name,
811 'img_timestamp' => $dbw->timestamp( $this->timestamp ),
812 ] )
813 ->caller( __METHOD__ )->execute();
814 $this->upgraded = true;
815 }
816
828 protected function setProps( $info ) {
829 $this->dataLoaded = true;
830 $fields = $this->getCacheFields( '' );
831 $fields[] = 'fileExists';
832
833 foreach ( $fields as $field ) {
834 if ( isset( $info[$field] ) ) {
835 $this->$field = $info[$field];
836 }
837 }
838
839 // Only our own cache sets these properties, so they both should be present.
840 if ( isset( $info['user'] ) &&
841 isset( $info['user_text'] ) &&
842 $info['user_text'] !== ''
843 ) {
844 $this->user = new UserIdentityValue( $info['user'], $info['user_text'] );
845 }
846
847 // Fix up mime fields
848 if ( isset( $info['major_mime'] ) ) {
849 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
850 } elseif ( isset( $info['mime'] ) ) {
851 $this->mime = $info['mime'];
852 [ $this->major_mime, $this->minor_mime ] = self::splitMime( $this->mime );
853 }
854
855 if ( isset( $info['metadata'] ) ) {
856 if ( is_string( $info['metadata'] ) ) {
857 $this->loadMetadataFromString( $info['metadata'] );
858 } elseif ( is_array( $info['metadata'] ) ) {
859 $this->metadataArray = $info['metadata'];
860 if ( isset( $info['metadataBlobs'] ) ) {
861 $this->metadataBlobs = $info['metadataBlobs'];
862 $this->unloadedMetadataBlobs = array_diff_key(
863 $this->metadataBlobs,
864 $this->metadataArray
865 );
866 } else {
867 $this->metadataBlobs = [];
868 $this->unloadedMetadataBlobs = [];
869 }
870 } else {
871 $logger = LoggerFactory::getInstance( 'LocalFile' );
872 $logger->warning( __METHOD__ . ' given invalid metadata of type ' .
873 gettype( $info['metadata'] ) );
874 $this->metadataArray = [];
875 }
876 $this->extraDataLoaded = true;
877 }
878 }
879
895 public function isMissing() {
896 if ( $this->missing === null ) {
897 $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
898 $this->missing = !$fileExists;
899 }
900
901 return $this->missing;
902 }
903
911 public function getWidth( $page = 1 ) {
912 $page = (int)$page;
913 if ( $page < 1 ) {
914 $page = 1;
915 }
916
917 $this->load();
918
919 if ( $this->isMultipage() ) {
920 $handler = $this->getHandler();
921 if ( !$handler ) {
922 return 0;
923 }
924 $dim = $handler->getPageDimensions( $this, $page );
925 if ( $dim ) {
926 return $dim['width'];
927 } else {
928 // For non-paged media, the false goes through an
929 // intval, turning failure into 0, so do same here.
930 return 0;
931 }
932 } else {
933 return $this->width;
934 }
935 }
936
944 public function getHeight( $page = 1 ) {
945 $page = (int)$page;
946 if ( $page < 1 ) {
947 $page = 1;
948 }
949
950 $this->load();
951
952 if ( $this->isMultipage() ) {
953 $handler = $this->getHandler();
954 if ( !$handler ) {
955 return 0;
956 }
957 $dim = $handler->getPageDimensions( $this, $page );
958 if ( $dim ) {
959 return $dim['height'];
960 } else {
961 // For non-paged media, the false goes through an
962 // intval, turning failure into 0, so do same here.
963 return 0;
964 }
965 } else {
966 return $this->height;
967 }
968 }
969
977 public function getDescriptionShortUrl() {
978 if ( !$this->title ) {
979 return null; // Avoid hard failure when the file does not exist. T221812
980 }
981
982 $pageId = $this->title->getArticleID();
983
984 if ( $pageId ) {
985 $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
986 if ( $url !== false ) {
987 return $url;
988 }
989 }
990 return null;
991 }
992
999 public function getMetadata() {
1000 $data = $this->getMetadataArray();
1001 if ( !$data ) {
1002 return '';
1003 } elseif ( array_keys( $data ) === [ '_error' ] ) {
1004 // Legacy error encoding
1005 return $data['_error'];
1006 } else {
1007 return serialize( $this->getMetadataArray() );
1008 }
1009 }
1010
1017 public function getMetadataArray(): array {
1018 $this->load( self::LOAD_ALL );
1019 if ( $this->unloadedMetadataBlobs ) {
1020 return $this->getMetadataItems(
1021 array_unique( array_merge(
1022 array_keys( $this->metadataArray ),
1023 array_keys( $this->unloadedMetadataBlobs )
1024 ) )
1025 );
1026 }
1027 return $this->metadataArray;
1028 }
1029
1030 public function getMetadataItems( array $itemNames ): array {
1031 $this->load( self::LOAD_ALL );
1032 $result = [];
1033 $addresses = [];
1034 foreach ( $itemNames as $itemName ) {
1035 if ( array_key_exists( $itemName, $this->metadataArray ) ) {
1036 $result[$itemName] = $this->metadataArray[$itemName];
1037 } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
1038 $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
1039 }
1040 }
1041
1042 if ( $addresses ) {
1043 $resultFromBlob = $this->metadataStorageHelper->getMetadataFromBlobStore( $addresses );
1044 foreach ( $addresses as $itemName => $address ) {
1045 unset( $this->unloadedMetadataBlobs[$itemName] );
1046 $value = $resultFromBlob[$itemName] ?? null;
1047 if ( $value !== null ) {
1048 $result[$itemName] = $value;
1049 $this->metadataArray[$itemName] = $value;
1050 }
1051 }
1052 }
1053 return $result;
1054 }
1055
1067 public function getMetadataForDb( IReadableDatabase $db ) {
1068 $this->load( self::LOAD_ALL );
1069 if ( !$this->metadataArray && !$this->metadataBlobs ) {
1070 $s = '';
1071 } elseif ( $this->repo->isJsonMetadataEnabled() ) {
1072 $s = $this->getJsonMetadata();
1073 } else {
1074 $s = serialize( $this->getMetadataArray() );
1075 }
1076 if ( !is_string( $s ) ) {
1077 throw new RuntimeException( 'Could not serialize image metadata value for DB' );
1078 }
1079 return $db->encodeBlob( $s );
1080 }
1081
1088 private function getJsonMetadata() {
1089 // Directly store data that is not already in BlobStore
1090 $envelope = [
1091 'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
1092 ];
1093
1094 // Also store the blob addresses
1095 if ( $this->metadataBlobs ) {
1096 $envelope['blobs'] = $this->metadataBlobs;
1097 }
1098
1099 [ $s, $blobAddresses ] = $this->metadataStorageHelper->getJsonMetadata( $this, $envelope );
1100
1101 // Repeated calls to this function should not keep inserting more blobs
1102 $this->metadataBlobs += $blobAddresses;
1103
1104 return $s;
1105 }
1106
1113 private function isMetadataOversize() {
1114 if ( !$this->repo->isSplitMetadataEnabled() ) {
1115 return false;
1116 }
1117 $threshold = $this->repo->getSplitMetadataThreshold();
1118 $directItems = array_diff_key( $this->metadataArray, $this->metadataBlobs );
1119 foreach ( $directItems as $value ) {
1120 if ( strlen( $this->metadataStorageHelper->jsonEncode( $value ) ) > $threshold ) {
1121 return true;
1122 }
1123 }
1124 return false;
1125 }
1126
1135 protected function loadMetadataFromDbFieldValue( IReadableDatabase $db, $metadataBlob ) {
1136 $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
1137 }
1138
1146 protected function loadMetadataFromString( $metadataString ) {
1147 $this->extraDataLoaded = true;
1148 $this->metadataArray = [];
1149 $this->metadataBlobs = [];
1150 $this->unloadedMetadataBlobs = [];
1151 $metadataString = (string)$metadataString;
1152 if ( $metadataString === '' ) {
1153 $this->metadataSerializationFormat = self::MDS_EMPTY;
1154 return;
1155 }
1156 if ( $metadataString[0] === '{' ) {
1157 $envelope = $this->metadataStorageHelper->jsonDecode( $metadataString );
1158 if ( !$envelope ) {
1159 // Legacy error encoding
1160 $this->metadataArray = [ '_error' => $metadataString ];
1161 $this->metadataSerializationFormat = self::MDS_LEGACY;
1162 } else {
1163 $this->metadataSerializationFormat = self::MDS_JSON;
1164 if ( isset( $envelope['data'] ) ) {
1165 $this->metadataArray = $envelope['data'];
1166 }
1167 if ( isset( $envelope['blobs'] ) ) {
1168 $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope['blobs'];
1169 }
1170 }
1171 } else {
1172 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1173 $data = @unserialize( $metadataString );
1174 if ( !is_array( $data ) ) {
1175 // Legacy error encoding
1176 $data = [ '_error' => $metadataString ];
1177 $this->metadataSerializationFormat = self::MDS_LEGACY;
1178 } else {
1179 $this->metadataSerializationFormat = self::MDS_PHP;
1180 }
1181 $this->metadataArray = $data;
1182 }
1183 }
1184
1189 public function getBitDepth() {
1190 $this->load();
1191
1192 return (int)$this->bits;
1193 }
1194
1200 public function getSize() {
1201 $this->load();
1202
1203 return $this->size;
1204 }
1205
1211 public function getMimeType() {
1212 $this->load();
1213
1214 return $this->mime;
1215 }
1216
1223 public function getMediaType() {
1224 $this->load();
1225
1226 return $this->media_type;
1227 }
1228
1240 public function exists() {
1241 $this->load();
1242
1243 return $this->fileExists;
1244 }
1245
1267 protected function getThumbnails( $archiveName = false ) {
1268 if ( $archiveName ) {
1269 $dir = $this->getArchiveThumbPath( $archiveName );
1270 } else {
1271 $dir = $this->getThumbPath();
1272 }
1273
1274 $backend = $this->repo->getBackend();
1275 $files = [ $dir ];
1276 try {
1277 $iterator = $backend->getFileList( [ 'dir' => $dir, 'forWrite' => true ] );
1278 if ( $iterator !== null ) {
1279 foreach ( $iterator as $file ) {
1280 $files[] = $file;
1281 }
1282 }
1283 } catch ( FileBackendError $e ) {
1284 } // suppress (T56674)
1285
1286 return $files;
1287 }
1288
1297 public function purgeCache( $options = [] ) {
1298 // Refresh metadata in memcached, but don't touch thumbnails or CDN
1299 $this->maybeUpgradeRow();
1300 $this->invalidateCache();
1301
1302 // Delete thumbnails
1303 $this->purgeThumbnails( $options );
1304
1305 // Purge CDN cache for this file
1306 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1307 $hcu->purgeUrls(
1308 $this->getUrl(),
1309 !empty( $options['forThumbRefresh'] )
1310 ? $hcu::PURGE_PRESEND // just a manual purge
1311 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1312 );
1313 }
1314
1320 public function purgeOldThumbnails( $archiveName ) {
1321 // Get a list of old thumbnails
1322 $thumbs = $this->getThumbnails( $archiveName );
1323
1324 // Delete thumbnails from storage, and prevent the directory itself from being purged
1325 $dir = array_shift( $thumbs );
1326 $this->purgeThumbList( $dir, $thumbs );
1327
1328 $urls = [];
1329 foreach ( $thumbs as $thumb ) {
1330 $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1331 }
1332
1333 // Purge any custom thumbnail caches
1334 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1335
1336 // Purge the CDN
1337 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1338 $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1339 }
1340
1347 public function purgeThumbnails( $options = [] ) {
1348 $thumbs = $this->getThumbnails();
1349
1350 // Delete thumbnails from storage, and prevent the directory itself from being purged
1351 $dir = array_shift( $thumbs );
1352 $this->purgeThumbList( $dir, $thumbs );
1353
1354 // Always purge all files from CDN regardless of handler filters
1355 $urls = [];
1356 foreach ( $thumbs as $thumb ) {
1357 $urls[] = $this->getThumbUrl( $thumb );
1358 }
1359
1360 // Give the media handler a chance to filter the file purge list
1361 if ( !empty( $options['forThumbRefresh'] ) ) {
1362 $handler = $this->getHandler();
1363 if ( $handler ) {
1364 $handler->filterThumbnailPurgeList( $thumbs, $options );
1365 }
1366 }
1367
1368 // Purge any custom thumbnail caches
1369 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1370
1371 // Purge the CDN
1372 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1373 $hcu->purgeUrls(
1374 $urls,
1375 !empty( $options['forThumbRefresh'] )
1376 ? $hcu::PURGE_PRESEND // just a manual purge
1377 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1378 );
1379 }
1380
1387 public function prerenderThumbnails() {
1388 $uploadThumbnailRenderMap = MediaWikiServices::getInstance()
1389 ->getMainConfig()->get( MainConfigNames::UploadThumbnailRenderMap );
1390
1391 $jobs = [];
1392
1393 $sizes = $uploadThumbnailRenderMap;
1394 rsort( $sizes );
1395
1396 foreach ( $sizes as $size ) {
1397 if ( $this->isMultipage() ) {
1398 // (T309114) Only trigger render jobs up to MAX_PAGE_RENDER_JOBS to avoid
1399 // a flood of jobs for huge files.
1400 $pageLimit = min( $this->pageCount(), self::MAX_PAGE_RENDER_JOBS );
1401
1402 $jobs[] = new ThumbnailRenderJob(
1403 $this->getTitle(),
1404 [
1405 'transformParams' => [ 'width' => $size, 'page' => 1 ],
1406 'enqueueNextPage' => true,
1407 'pageLimit' => $pageLimit
1408 ]
1409 );
1410 } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1411 $jobs[] = new ThumbnailRenderJob(
1412 $this->getTitle(),
1413 [ 'transformParams' => [ 'width' => $size ] ]
1414 );
1415 }
1416 }
1417
1418 if ( $jobs ) {
1419 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
1420 }
1421 }
1422
1429 protected function purgeThumbList( $dir, $files ) {
1430 $fileListDebug = strtr(
1431 var_export( $files, true ),
1432 [ "\n" => '' ]
1433 );
1434 wfDebug( __METHOD__ . ": $fileListDebug" );
1435
1436 if ( $this->repo->supportsSha1URLs() ) {
1437 $reference = $this->getSha1();
1438 } else {
1439 $reference = $this->getName();
1440 }
1441
1442 $purgeList = [];
1443 foreach ( $files as $file ) {
1444 # Check that the reference (filename or sha1) is part of the thumb name
1445 # This is a basic check to avoid erasing unrelated directories
1446 if ( str_contains( $file, $reference )
1447 || str_contains( $file, "-thumbnail" ) // "short" thumb name
1448 ) {
1449 $purgeList[] = "{$dir}/{$file}";
1450 }
1451 }
1452
1453 # Delete the thumbnails
1454 $this->repo->quickPurgeBatch( $purgeList );
1455 # Clear out the thumbnail directory if empty
1456 $this->repo->quickCleanDir( $dir );
1457 }
1458
1470 public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1471 if ( !$this->exists() ) {
1472 return []; // Avoid hard failure when the file does not exist. T221812
1473 }
1474
1475 $dbr = $this->repo->getReplicaDB();
1476 $oldFileQuery = OldLocalFile::getQueryInfo();
1477
1478 $tables = $oldFileQuery['tables'];
1479 $fields = $oldFileQuery['fields'];
1480 $join_conds = $oldFileQuery['joins'];
1481 $conds = $opts = [];
1482 $eq = $inc ? '=' : '';
1483 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1484
1485 if ( $start ) {
1486 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1487 }
1488
1489 if ( $end ) {
1490 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1491 }
1492
1493 if ( $limit ) {
1494 $opts['LIMIT'] = $limit;
1495 }
1496
1497 // Search backwards for time > x queries
1498 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1499 $opts['ORDER BY'] = "oi_timestamp $order";
1500 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1501
1502 $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1503 $conds, $opts, $join_conds );
1504
1505 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1506 $r = [];
1507
1508 foreach ( $res as $row ) {
1509 $r[] = $this->repo->newFileFromRow( $row );
1510 }
1511
1512 if ( $order == 'ASC' ) {
1513 $r = array_reverse( $r ); // make sure it ends up descending
1514 }
1515
1516 return $r;
1517 }
1518
1529 public function nextHistoryLine() {
1530 if ( !$this->exists() ) {
1531 return false; // Avoid hard failure when the file does not exist. T221812
1532 }
1533
1534 # Polymorphic function name to distinguish foreign and local fetches
1535 $fname = static::class . '::' . __FUNCTION__;
1536
1537 $dbr = $this->repo->getReplicaDB();
1538
1539 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1540 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
1541
1542 $queryBuilder->fields( [ 'oi_archive_name' => $dbr->addQuotes( '' ), 'oi_deleted' => '0' ] )
1543 ->where( [ 'img_name' => $this->title->getDBkey() ] );
1544 $this->historyRes = $queryBuilder->caller( $fname )->fetchResultSet();
1545
1546 if ( $this->historyRes->numRows() == 0 ) {
1547 $this->historyRes = null;
1548
1549 return false;
1550 }
1551 } elseif ( $this->historyLine == 1 ) {
1552 $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr );
1553
1554 $this->historyRes = $queryBuilder->where( [ 'oi_name' => $this->title->getDBkey() ] )
1555 ->orderBy( 'oi_timestamp', SelectQueryBuilder::SORT_DESC )
1556 ->caller( $fname )->fetchResultSet();
1557 }
1558 $this->historyLine++;
1559
1560 return $this->historyRes->fetchObject();
1561 }
1562
1567 public function resetHistory() {
1568 $this->historyLine = 0;
1569
1570 if ( $this->historyRes !== null ) {
1571 $this->historyRes = null;
1572 }
1573 }
1574
1608 public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1609 $timestamp = false, Authority $uploader = null, $tags = [],
1610 $createNullRevision = true, $revert = false
1611 ) {
1612 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1613 return $this->readOnlyFatalStatus();
1614 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1615 // Check this in advance to avoid writing to FileBackend and the file tables,
1616 // only to fail on insert the revision due to the text store being unavailable.
1617 return $this->readOnlyFatalStatus();
1618 }
1619
1620 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1621 if ( !$props ) {
1622 if ( FileRepo::isVirtualUrl( $srcPath )
1623 || FileBackend::isStoragePath( $srcPath )
1624 ) {
1625 $props = $this->repo->getFileProps( $srcPath );
1626 } else {
1627 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1628 $props = $mwProps->getPropsFromPath( $srcPath, true );
1629 }
1630 }
1631
1632 $options = [];
1633 $handler = MediaHandler::getHandler( $props['mime'] );
1634 if ( $handler ) {
1635 if ( is_string( $props['metadata'] ) ) {
1636 // This supports callers directly fabricating a metadata
1637 // property using serialize(). Normally the metadata property
1638 // comes from MWFileProps, in which case it won't be a string.
1639 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1640 $metadata = @unserialize( $props['metadata'] );
1641 } else {
1642 $metadata = $props['metadata'];
1643 }
1644
1645 if ( is_array( $metadata ) ) {
1646 $options['headers'] = $handler->getContentHeaders( $metadata );
1647 }
1648 } else {
1649 $options['headers'] = [];
1650 }
1651
1652 // Trim spaces on user supplied text
1653 $comment = trim( $comment );
1654
1655 $status = $this->publish( $src, $flags, $options );
1656
1657 if ( $status->successCount >= 2 ) {
1658 // There will be a copy+(one of move,copy,store).
1659 // The first succeeding does not commit us to updating the DB
1660 // since it simply copied the current version to a timestamped file name.
1661 // It is only *preferable* to avoid leaving such files orphaned.
1662 // Once the second operation goes through, then the current version was
1663 // updated and we must therefore update the DB too.
1664 $oldver = $status->value;
1665
1666 $uploadStatus = $this->recordUpload3(
1667 $oldver,
1668 $comment,
1669 $pageText,
1670 $uploader ?? RequestContext::getMain()->getAuthority(),
1671 $props,
1672 $timestamp,
1673 $tags,
1674 $createNullRevision,
1675 $revert
1676 );
1677 if ( !$uploadStatus->isOK() ) {
1678 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1679 // update filenotfound error with more specific path
1680 $status->fatal( 'filenotfound', $srcPath );
1681 } else {
1682 $status->merge( $uploadStatus );
1683 }
1684 }
1685 }
1686
1687 return $status;
1688 }
1689
1706 public function recordUpload3(
1707 string $oldver,
1708 string $comment,
1709 string $pageText,
1710 Authority $performer,
1711 $props = false,
1712 $timestamp = false,
1713 $tags = [],
1714 bool $createNullRevision = true,
1715 bool $revert = false
1716 ): Status {
1717 $dbw = $this->repo->getPrimaryDB();
1718
1719 # Imports or such might force a certain timestamp; otherwise we generate
1720 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1721 if ( $timestamp === false ) {
1722 $timestamp = $dbw->timestamp();
1723 $allowTimeKludge = true;
1724 } else {
1725 $allowTimeKludge = false;
1726 }
1727
1728 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1729 $props['description'] = $comment;
1730 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1731 $this->setProps( $props );
1732
1733 # Fail now if the file isn't there
1734 if ( !$this->fileExists ) {
1735 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1736
1737 return Status::newFatal( 'filenotfound', $this->getRel() );
1738 }
1739
1740 $mimeAnalyzer = MediaWikiServices::getInstance()->getMimeAnalyzer();
1741 if ( !$mimeAnalyzer->isValidMajorMimeType( $this->major_mime ) ) {
1742 $this->major_mime = 'unknown';
1743 }
1744
1745 $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1746
1747 $dbw->startAtomic( __METHOD__ );
1748
1749 $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1750 $this->user = $performer->getUser();
1751
1752 # Test to see if the row exists using INSERT IGNORE
1753 # This avoids race conditions by locking the row until the commit, and also
1754 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1755 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1756 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1757 $actorFields = [ 'img_actor' => $actorId ];
1758 $dbw->newInsertQueryBuilder()
1759 ->insertInto( 'image' )
1760 ->ignore()
1761 ->row( [
1762 'img_name' => $this->getName(),
1763 'img_size' => $this->size,
1764 'img_width' => intval( $this->width ),
1765 'img_height' => intval( $this->height ),
1766 'img_bits' => $this->bits,
1767 'img_media_type' => $this->media_type,
1768 'img_major_mime' => $this->major_mime,
1769 'img_minor_mime' => $this->minor_mime,
1770 'img_timestamp' => $dbw->timestamp( $timestamp ),
1771 'img_metadata' => $this->getMetadataForDb( $dbw ),
1772 'img_sha1' => $this->sha1
1773 ] + $commentFields + $actorFields )
1774 ->caller( __METHOD__ )->execute();
1775 $reupload = ( $dbw->affectedRows() == 0 );
1776
1777 if ( $reupload ) {
1778 $row = $dbw->newSelectQueryBuilder()
1779 ->select( [ 'img_timestamp', 'img_sha1' ] )
1780 ->from( 'image' )
1781 ->where( [ 'img_name' => $this->getName() ] )
1782 ->caller( __METHOD__ )->fetchRow();
1783
1784 if ( $row && $row->img_sha1 === $this->sha1 ) {
1785 $dbw->endAtomic( __METHOD__ );
1786 wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1787 $title = Title::newFromText( $this->getName(), NS_FILE );
1788 return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1789 }
1790
1791 if ( $allowTimeKludge ) {
1792 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1793 $lUnixtime = $row ? (int)wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1794 # Avoid a timestamp that is not newer than the last version
1795 # TODO: the image/oldimage tables should be like page/revision with an ID field
1796 if ( $lUnixtime && (int)wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1797 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1798 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1799 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1800 }
1801 }
1802
1803 $tables = [ 'image' ];
1804 $fields = [
1805 'oi_name' => 'img_name',
1806 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1807 'oi_size' => 'img_size',
1808 'oi_width' => 'img_width',
1809 'oi_height' => 'img_height',
1810 'oi_bits' => 'img_bits',
1811 'oi_description_id' => 'img_description_id',
1812 'oi_timestamp' => 'img_timestamp',
1813 'oi_metadata' => 'img_metadata',
1814 'oi_media_type' => 'img_media_type',
1815 'oi_major_mime' => 'img_major_mime',
1816 'oi_minor_mime' => 'img_minor_mime',
1817 'oi_sha1' => 'img_sha1',
1818 'oi_actor' => 'img_actor',
1819 ];
1820 $joins = [];
1821
1822 # (T36993) Note: $oldver can be empty here, if the previous
1823 # version of the file was broken. Allow registration of the new
1824 # version to continue anyway, because that's better than having
1825 # an image that's not fixable by user operations.
1826 # Collision, this is an update of a file
1827 # Insert previous contents into oldimage
1828 $dbw->insertSelect( 'oldimage', $tables, $fields,
1829 [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1830
1831 # Update the current image row
1832 $dbw->newUpdateQueryBuilder()
1833 ->update( 'image' )
1834 ->set( [
1835 'img_size' => $this->size,
1836 'img_width' => intval( $this->width ),
1837 'img_height' => intval( $this->height ),
1838 'img_bits' => $this->bits,
1839 'img_media_type' => $this->media_type,
1840 'img_major_mime' => $this->major_mime,
1841 'img_minor_mime' => $this->minor_mime,
1842 'img_timestamp' => $dbw->timestamp( $timestamp ),
1843 'img_metadata' => $this->getMetadataForDb( $dbw ),
1844 'img_sha1' => $this->sha1
1845 ] + $commentFields + $actorFields )
1846 ->where( [ 'img_name' => $this->getName() ] )
1847 ->caller( __METHOD__ )->execute();
1848 }
1849
1850 $descTitle = $this->getTitle();
1851 $descId = $descTitle->getArticleID();
1852 $wikiPage = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $descTitle );
1853 if ( !$wikiPage instanceof WikiFilePage ) {
1854 throw new UnexpectedValueException( 'Cannot obtain instance of WikiFilePage for ' . $this->getName()
1855 . ', got instance of ' . get_class( $wikiPage ) );
1856 }
1857 $wikiPage->setFile( $this );
1858
1859 // Determine log action. If reupload is done by reverting, use a special log_action.
1860 if ( $revert ) {
1861 $logAction = 'revert';
1862 } elseif ( $reupload ) {
1863 $logAction = 'overwrite';
1864 } else {
1865 $logAction = 'upload';
1866 }
1867 // Add the log entry...
1868 $logEntry = new ManualLogEntry( 'upload', $logAction );
1869 $logEntry->setTimestamp( $this->timestamp );
1870 $logEntry->setPerformer( $performer->getUser() );
1871 $logEntry->setComment( $comment );
1872 $logEntry->setTarget( $descTitle );
1873 // Allow people using the api to associate log entries with the upload.
1874 // Log has a timestamp, but sometimes different from upload timestamp.
1875 $logEntry->setParameters(
1876 [
1877 'img_sha1' => $this->sha1,
1878 'img_timestamp' => $timestamp,
1879 ]
1880 );
1881 // Note we keep $logId around since during new image
1882 // creation, page doesn't exist yet, so log_page = 0
1883 // but we want it to point to the page we're making,
1884 // so we later modify the log entry.
1885 // For a similar reason, we avoid making an RC entry
1886 // now and wait until the page exists.
1887 $logId = $logEntry->insert();
1888
1889 if ( $descTitle->exists() ) {
1890 if ( $createNullRevision ) {
1891 $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1892 // Use own context to get the action text in content language
1893 $formatter = LogFormatter::newFromEntry( $logEntry );
1894 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1895 $editSummary = $formatter->getPlainActionText();
1896 $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1897 $nullRevRecord = $revStore->newNullRevision(
1898 $dbw,
1899 $descTitle,
1900 $summary,
1901 false,
1902 $performer->getUser()
1903 );
1904
1905 if ( $nullRevRecord ) {
1906 $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1907
1908 $this->getHookRunner()->onRevisionFromEditComplete(
1909 $wikiPage,
1910 $inserted,
1911 $inserted->getParentId(),
1912 $performer->getUser(),
1913 $tags
1914 );
1915
1916 $wikiPage->updateRevisionOn( $dbw, $inserted );
1917 // Associate null revision id
1918 $logEntry->setAssociatedRevId( $inserted->getId() );
1919 }
1920 }
1921
1922 $newPageContent = null;
1923 } else {
1924 // Make the description page and RC log entry post-commit
1925 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1926 }
1927
1928 // NOTE: Even after ending this atomic section, we are probably still in the implicit
1929 // transaction started by any prior master query in the request. We cannot yet safely
1930 // schedule jobs, see T263301.
1931 $dbw->endAtomic( __METHOD__ );
1932 $fname = __METHOD__;
1933
1934 # Do some cache purges after final commit so that:
1935 # a) Changes are more likely to be seen post-purge
1936 # b) They won't cause rollback of the log publish/update above
1937 $purgeUpdate = new AutoCommitUpdate(
1938 $dbw,
1939 __METHOD__,
1940 function () use (
1941 $reupload, $wikiPage, $newPageContent, $comment, $performer,
1942 $logEntry, $logId, $descId, $tags, $fname
1943 ) {
1944 # Update memcache after the commit
1945 $this->invalidateCache();
1946
1947 $updateLogPage = false;
1948 if ( $newPageContent ) {
1949 # New file page; create the description page.
1950 # There's already a log entry, so don't make a second RC entry
1951 # CDN and file cache for the description page are purged by doUserEditContent.
1952 $status = $wikiPage->doUserEditContent(
1953 $newPageContent,
1954 $performer,
1955 $comment,
1957 );
1958
1959 $revRecord = $status->getNewRevision();
1960 if ( $revRecord ) {
1961 // Associate new page revision id
1962 $logEntry->setAssociatedRevId( $revRecord->getId() );
1963
1964 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1965 // which is triggered on $descTitle by doUserEditContent() above.
1966 $updateLogPage = $revRecord->getPageId();
1967 }
1968 } else {
1969 # Existing file page: invalidate description page cache
1970 $title = $wikiPage->getTitle();
1971 $title->invalidateCache();
1972 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1973 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1974 # Allow the new file version to be patrolled from the page footer
1976 }
1977
1978 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1979 # but setAssociatedRevId() wasn't called at that point yet...
1980 $logParams = $logEntry->getParameters();
1981 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1982 $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1983 if ( $updateLogPage ) {
1984 # Also log page, in case where we just created it above
1985 $update['log_page'] = $updateLogPage;
1986 }
1987 $this->getRepo()->getPrimaryDB()->newUpdateQueryBuilder()
1988 ->update( 'logging' )
1989 ->set( $update )
1990 ->where( [ 'log_id' => $logId ] )
1991 ->caller( $fname )->execute();
1992
1993 $this->getRepo()->getPrimaryDB()->newInsertQueryBuilder()
1994 ->insertInto( 'log_search' )
1995 ->row( [
1996 'ls_field' => 'associated_rev_id',
1997 'ls_value' => (string)$logEntry->getAssociatedRevId(),
1998 'ls_log_id' => $logId,
1999 ] )
2000 ->caller( $fname )->execute();
2001
2002 # Add change tags, if any
2003 if ( $tags ) {
2004 $logEntry->addTags( $tags );
2005 }
2006
2007 # Uploads can be patrolled
2008 $logEntry->setIsPatrollable( true );
2009
2010 # Now that the log entry is up-to-date, make an RC entry.
2011 $logEntry->publish( $logId );
2012
2013 # Run hook for other updates (typically more cache purging)
2014 $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2015
2016 if ( $reupload ) {
2017 # Delete old thumbnails
2018 $this->purgeThumbnails();
2019 # Remove the old file from the CDN cache
2020 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2021 $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2022 } else {
2023 # Update backlink pages pointing to this title if created
2024 $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2025 LinksUpdate::queueRecursiveJobsForTable(
2026 $this->getTitle(),
2027 'imagelinks',
2028 'upload-image',
2029 $performer->getUser()->getName(),
2030 $blcFactory->getBacklinkCache( $this->getTitle() )
2031 );
2032 }
2033
2034 $this->prerenderThumbnails();
2035 }
2036 );
2037
2038 # Invalidate cache for all pages using this file
2039 $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
2040 $this->getTitle(),
2041 'imagelinks',
2042 [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2043 );
2044
2045 // NOTE: We are probably still in the implicit transaction started by DBO_TRX. We should
2046 // only schedule jobs after that transaction was committed, so a job queue failure
2047 // doesn't cause the upload to fail (T263301). Also, we should generally not schedule any
2048 // Jobs or the DeferredUpdates that assume the update is complete until after the
2049 // transaction has been committed and we are sure that the upload was indeed successful.
2050 $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2051 DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2052
2053 if ( !$reupload ) {
2054 // This is a new file, so update the image count
2055 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2056 }
2057
2058 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $cacheUpdateJob );
2059 }, __METHOD__ );
2060
2061 return Status::newGood();
2062 }
2063
2080 public function publish( $src, $flags = 0, array $options = [] ) {
2081 return $this->publishTo( $src, $this->getRel(), $flags, $options );
2082 }
2083
2100 protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2101 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
2102
2103 $repo = $this->getRepo();
2104 if ( $repo->getReadOnlyReason() !== false ) {
2105 return $this->readOnlyFatalStatus();
2106 }
2107
2108 $status = $this->acquireFileLock();
2109 if ( !$status->isOK() ) {
2110 return $status;
2111 }
2112
2113 if ( $this->isOld() ) {
2114 $archiveRel = $dstRel;
2115 $archiveName = basename( $archiveRel );
2116 } else {
2117 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
2118 $archiveRel = $this->getArchiveRel( $archiveName );
2119 }
2120
2121 if ( $repo->hasSha1Storage() ) {
2122 $sha1 = FileRepo::isVirtualUrl( $srcPath )
2123 ? $repo->getFileSha1( $srcPath )
2124 : FSFile::getSha1Base36FromPath( $srcPath );
2126 $wrapperBackend = $repo->getBackend();
2127 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2128 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2129 $status = $repo->quickImport( $src, $dst );
2130 if ( $flags & File::DELETE_SOURCE ) {
2131 unlink( $srcPath );
2132 }
2133
2134 if ( $this->exists() ) {
2135 $status->value = $archiveName;
2136 }
2137 } else {
2138 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2139 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2140
2141 if ( $status->value == 'new' ) {
2142 $status->value = '';
2143 } else {
2144 $status->value = $archiveName;
2145 }
2146 }
2147
2148 $this->releaseFileLock();
2149 return $status;
2150 }
2151
2170 public function move( $target ) {
2171 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2172 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2173 return $this->readOnlyFatalStatus();
2174 }
2175
2176 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2177 $batch = new LocalFileMoveBatch( $this, $target );
2178
2179 $status = $batch->addCurrent();
2180 if ( !$status->isOK() ) {
2181 return $status;
2182 }
2183 $archiveNames = $batch->addOlds();
2184 $status = $batch->execute();
2185
2186 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2187
2188 // Purge the source and target files outside the transaction...
2189 $oldTitleFile = $localRepo->newFile( $this->title );
2190 $newTitleFile = $localRepo->newFile( $target );
2191 DeferredUpdates::addUpdate(
2192 new AutoCommitUpdate(
2193 $this->getRepo()->getPrimaryDB(),
2194 __METHOD__,
2195 static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2196 $oldTitleFile->purgeEverything();
2197 foreach ( $archiveNames as $archiveName ) {
2199 '@phan-var OldLocalFile $oldTitleFile';
2200 $oldTitleFile->purgeOldThumbnails( $archiveName );
2201 }
2202 $newTitleFile->purgeEverything();
2203 }
2204 ),
2205 DeferredUpdates::PRESEND
2206 );
2207
2208 if ( $status->isOK() ) {
2209 // Now switch the object
2210 $this->title = $target;
2211 // Force regeneration of the name and hashpath
2212 $this->name = null;
2213 $this->hashPath = null;
2214 }
2215
2216 return $status;
2217 }
2218
2235 public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2236 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2237 return $this->readOnlyFatalStatus();
2238 }
2239
2240 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2241
2242 $batch->addCurrent();
2243 // Get old version relative paths
2244 $archiveNames = $batch->addOlds();
2245 $status = $batch->execute();
2246
2247 if ( $status->isOK() ) {
2248 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2249 }
2250
2251 // To avoid slow purges in the transaction, move them outside...
2252 DeferredUpdates::addUpdate(
2253 new AutoCommitUpdate(
2254 $this->getRepo()->getPrimaryDB(),
2255 __METHOD__,
2256 function () use ( $archiveNames ) {
2257 $this->purgeEverything();
2258 foreach ( $archiveNames as $archiveName ) {
2259 $this->purgeOldThumbnails( $archiveName );
2260 }
2261 }
2262 ),
2263 DeferredUpdates::PRESEND
2264 );
2265
2266 // Purge the CDN
2267 $purgeUrls = [];
2268 foreach ( $archiveNames as $archiveName ) {
2269 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2270 }
2271
2272 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2273 $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2274
2275 return $status;
2276 }
2277
2295 public function deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress = false ) {
2296 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2297 return $this->readOnlyFatalStatus();
2298 }
2299
2300 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2301
2302 $batch->addOld( $archiveName );
2303 $status = $batch->execute();
2304
2305 $this->purgeOldThumbnails( $archiveName );
2306 if ( $status->isOK() ) {
2307 $this->purgeDescription();
2308 }
2309
2310 $url = $this->getArchiveUrl( $archiveName );
2311 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2312 $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2313
2314 return $status;
2315 }
2316
2329 public function restore( $versions = [], $unsuppress = false ) {
2330 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2331 return $this->readOnlyFatalStatus();
2332 }
2333
2334 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2335
2336 if ( !$versions ) {
2337 $batch->addAll();
2338 } else {
2339 $batch->addIds( $versions );
2340 }
2341 $status = $batch->execute();
2342 if ( $status->isGood() ) {
2343 $cleanupStatus = $batch->cleanup();
2344 $cleanupStatus->successCount = 0;
2345 $cleanupStatus->failCount = 0;
2346 $status->merge( $cleanupStatus );
2347 }
2348
2349 return $status;
2350 }
2351
2362 public function getDescriptionUrl() {
2363 // Avoid hard failure when the file does not exist. T221812
2364 return $this->title ? $this->title->getLocalURL() : false;
2365 }
2366
2376 public function getDescriptionText( Language $lang = null ) {
2377 if ( !$this->title ) {
2378 return false; // Avoid hard failure when the file does not exist. T221812
2379 }
2380
2381 $services = MediaWikiServices::getInstance();
2382 $page = $services->getPageStore()->getPageByReference( $this->getTitle() );
2383 if ( !$page ) {
2384 return false;
2385 }
2386
2387 if ( $lang ) {
2388 $parserOptions = ParserOptions::newFromUserAndLang(
2389 RequestContext::getMain()->getUser(),
2390 $lang
2391 );
2392 } else {
2393 $parserOptions = ParserOptions::newFromContext( RequestContext::getMain() );
2394 }
2395
2396 $parseStatus = $services->getParserOutputAccess()
2397 ->getParserOutput( $page, $parserOptions );
2398
2399 if ( !$parseStatus->isGood() ) {
2400 // Rendering failed.
2401 return false;
2402 }
2403 return $parseStatus->getValue()->getText();
2404 }
2405
2413 public function getUploader( int $audience = self::FOR_PUBLIC, Authority $performer = null ): ?UserIdentity {
2414 $this->load();
2415 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2416 return null;
2417 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2418 return null;
2419 } else {
2420 return $this->user;
2421 }
2422 }
2423
2430 public function getDescription( $audience = self::FOR_PUBLIC, Authority $performer = null ) {
2431 $this->load();
2432 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2433 return '';
2434 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2435 return '';
2436 } else {
2437 return $this->description;
2438 }
2439 }
2440
2445 public function getTimestamp() {
2446 $this->load();
2447
2448 return $this->timestamp;
2449 }
2450
2455 public function getDescriptionTouched() {
2456 if ( !$this->exists() ) {
2457 return false; // Avoid hard failure when the file does not exist. T221812
2458 }
2459
2460 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2461 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2462 // need to differentiate between null (uninitialized) and false (failed to load).
2463 if ( $this->descriptionTouched === null ) {
2464 $touched = $this->repo->getReplicaDB()->newSelectQueryBuilder()
2465 ->select( 'page_touched' )
2466 ->from( 'page' )
2467 ->where( [ 'page_namespace' => $this->title->getNamespace() ] )
2468 ->andWhere( [ 'page_title' => $this->title->getDBkey() ] )
2469 ->caller( __METHOD__ )->fetchField();
2470 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2471 }
2472
2473 return $this->descriptionTouched;
2474 }
2475
2480 public function getSha1() {
2481 $this->load();
2482 return $this->sha1;
2483 }
2484
2488 public function isCacheable() {
2489 $this->load();
2490
2491 // If extra data (metadata) was not loaded then it must have been large
2492 return $this->extraDataLoaded
2493 && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2494 }
2495
2504 public function acquireFileLock( $timeout = 0 ) {
2505 return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2506 [ $this->getPath() ], LockManager::LOCK_EX, $timeout
2507 ) );
2508 }
2509
2516 public function releaseFileLock() {
2517 return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2518 [ $this->getPath() ], LockManager::LOCK_EX
2519 ) );
2520 }
2521
2532 public function lock() {
2533 if ( !$this->locked ) {
2534 $logger = LoggerFactory::getInstance( 'LocalFile' );
2535
2536 $dbw = $this->repo->getPrimaryDB();
2537 $makesTransaction = !$dbw->trxLevel();
2538 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2539 // T56736: use simple lock to handle when the file does not exist.
2540 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2541 // Also, that would cause contention on INSERT of similarly named rows.
2542 $status = $this->acquireFileLock( 10 ); // represents all versions of the file
2543 if ( !$status->isGood() ) {
2544 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2545 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2546
2547 throw new LocalFileLockError( $status );
2548 }
2549 // Release the lock *after* commit to avoid row-level contention.
2550 // Make sure it triggers on rollback() as well as commit() (T132921).
2551 $dbw->onTransactionResolution(
2552 function () use ( $logger ) {
2553 $status = $this->releaseFileLock();
2554 if ( !$status->isGood() ) {
2555 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2556 }
2557 },
2558 __METHOD__
2559 );
2560 // Callers might care if the SELECT snapshot is safely fresh
2561 $this->lockedOwnTrx = $makesTransaction;
2562 }
2563
2564 $this->locked++;
2565
2566 return $this->lockedOwnTrx;
2567 }
2568
2579 public function unlock() {
2580 if ( $this->locked ) {
2581 --$this->locked;
2582 if ( !$this->locked ) {
2583 $dbw = $this->repo->getPrimaryDB();
2584 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2585 $this->lockedOwnTrx = false;
2586 }
2587 }
2588 }
2589
2593 protected function readOnlyFatalStatus() {
2594 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2595 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2596 }
2597
2601 public function __destruct() {
2602 $this->unlock();
2603 }
2604}
getUser()
getAuthority()
const NS_FILE
Definition Defines.php:70
const EDIT_SUPPRESS_RC
Definition Defines.php:129
const EDIT_NEW
Definition Defines.php:126
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getCacheKey()
Get the cache key used to store status.
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Definition Article.php:1422
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Class representing a non-directory file on the file system.
Definition FSFile.php:32
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
Definition FSFile.php:225
File backend exception for checked exceptions (e.g.
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition FileRepo.php:287
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:73
string $url
The URL corresponding to one of the four basic zones.
Definition File.php:144
MediaHandler $handler
Definition File.php:141
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition File.php:2466
getName()
Return the name of this file.
Definition File.php:341
const DELETE_SOURCE
Definition File.php:90
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
Definition File.php:1929
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition File.php:2475
FileRepo LocalRepo ForeignAPIRepo false $repo
Some member variables can be lazy-initialised using __get().
Definition File.php:120
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition File.php:2163
Title string false $title
Definition File.php:123
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1548
string null $name
The name of a file from its title object.
Definition File.php:150
static newForBacklinks(PageReference $page, $table, $params=[])
Base class for language-specific code.
Definition Language.php:63
Helper class for file deletion.
Helper class for file movement.
Helper class for file undeletion.
Local file in the wiki's own database.
Definition LocalFile.php:68
exists()
canRender inherited
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info.
maybeUpgradeRow()
Upgrade a row if it needs it.
static newFromKey( $sha1, $repo, $timestamp=false)
Create a LocalFile from a SHA-1 key Do not call this except from inside a repo class.
array $metadataArray
Unserialized metadata.
getMediaType()
Returns the type of the media in the file.
string[] $unloadedMetadataBlobs
Map of metadata item name to blob address for items that exist but have not yet been loaded into $thi...
deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress=false)
Delete an old version of the file.
move( $target)
getLinksTo inherited
lock()
Start an atomic DB section and lock the image for update or increments a reference counter if the loc...
loadFromRow( $row, $prefix='img_')
Load file metadata from a DB result row.
loadMetadataFromDbFieldValue(IReadableDatabase $db, $metadataBlob)
Unserialize a metadata blob which came from the database and store it in $this.
getCacheKey()
Get the memcached key for the main data for this file, or false if there is no access to the shared c...
getWidth( $page=1)
Return the width of the image.
__destruct()
Clean up any dangling locks.
string $mime
MIME type, determined by MimeAnalyzer::guessMimeType.
reserializeMetadata()
Write the metadata back to the database with the current serialization format.
isMissing()
splitMime inherited
getDescriptionUrl()
isMultipage inherited
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object.
releaseFileLock()
Release a lock acquired with acquireFileLock().
getUploader(int $audience=self::FOR_PUBLIC, Authority $performer=null)
loadFromDB( $flags=0)
Load file metadata from the DB.
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
loadMetadataFromString( $metadataString)
Unserialize a metadata string which came from some non-DB source, or is the return value of IReadable...
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
deleteFile( $reason, UserIdentity $user, $suppress=false)
Delete all versions of the file.
acquireFileLock( $timeout=0)
Acquire an exclusive lock on the file, indicating an intention to write to the file backend.
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
getDescriptionTouched()
loadFromFile( $path=null)
Load metadata from the file itself.
string null $metadataSerializationFormat
One of the MDS_* constants, giving the format of the metadata as stored in the DB,...
int $size
Size in bytes (loadFromXxx)
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
getThumbnails( $archiveName=false)
getTransformScript inherited
static newFromTitle( $title, $repo, $unused=null)
Create a LocalFile from a title Do not call this except from inside a repo class.
int $height
Image height.
Definition LocalFile.php:95
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
publishTo( $src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
getMetadataForDb(IReadableDatabase $db)
Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
getLazyCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache, only when they're not too...
getSize()
Returns the size of the image file, in bytes.
invalidateCache()
Purge the file object/metadata cache.
getMimeType()
Returns the MIME type of the file.
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
readOnlyFatalStatus()
string $sha1
SHA-1 base 36 content hash.
getDescription( $audience=self::FOR_PUBLIC, Authority $performer=null)
getHeight( $page=1)
Return the height of the image.
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
resetHistory()
Reset the history pointer to the first element of the history.
unprefixRow( $row, $prefix='img_')
static newFromRow( $row, $repo)
Create a LocalFile from a title Do not call this except from inside a repo class.
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
getCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache.
int $bits
Returned by getimagesize (loadFromXxx)
Definition LocalFile.php:98
getMetadataItems(array $itemNames)
Get multiple elements of the unserialized handler-specific metadata.
getDescriptionText(Language $lang=null)
Get the HTML text of the description page This is not used by ImagePage for local files,...
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
loadExtraFromDB()
Load lazy file metadata from the DB.
string $repoClass
int $width
Image width.
Definition LocalFile.php:92
nextHistoryLine()
Returns the history of this file, line by line.
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file.
int $deleted
Bitfield akin to rev_deleted.
getMetadata()
Get handler-specific metadata as a serialized string.
getMetadataArray()
Get unserialized handler-specific metadata.
__construct( $title, $repo)
Do not call this except from inside a repo class.
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
bool $fileExists
Does the file exist on disk? (loadFromXxx)
Definition LocalFile.php:89
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, Authority $uploader=null, $tags=[], $createNullRevision=true, $revert=false)
getHashPath inherited
recordUpload3(string $oldver, string $comment, string $pageText, Authority $performer, $props=false, $timestamp=false, $tags=[], bool $createNullRevision=true, bool $revert=false)
Record a file upload in the upload log and the image table (version 3)
string[] $metadataBlobs
Map of metadata item name to blob address.
static makeParamBlob( $params)
Create a blob from a parameter array.
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
MimeMagic helper wrapper.
Class for creating new log entries and inserting them into the database.
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
Value object for a comment stored by CommentStore.
Group all the pieces relevant to the context of a request into one instance.
Deferrable Update for closure/callback updates that should use auto-commit mode.
Defer callable updates to run later in the PHP process.
Class the manages updates of *_link tables as well as similar extension-managed tables.
Class for handling updates to the site_stats table.
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:54
Represents a title within MediaWiki.
Definition Title.php:78
Value object representing a user's identity.
Helper for storage of metadata.
Job for asynchronous rendering of thumbnails, e.g.
Special handling for representing file pages.
Build SELECT queries with a fluent interface.
This interface represents the authority associated with the current execution context,...
Definition Authority.php:37
getUser()
Returns the performer of the actions associated with this authority.
Interface for objects representing user identity.
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.
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.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Result wrapper for grabbing data queried from an IDatabase object.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...