MediaWiki master
LocalFile.php
Go to the documentation of this file.
1<?php
40
67class LocalFile extends File {
68 private const VERSION = 13; // cache version
69
70 private const CACHE_FIELD_MAX_LEN = 1000;
71
73 private const MDS_EMPTY = 'empty';
74
76 private const MDS_LEGACY = 'legacy';
77
79 private const MDS_PHP = 'php';
80
82 private const MDS_JSON = 'json';
83
85 private const MAX_PAGE_RENDER_JOBS = 50;
86
88 protected $fileExists;
89
91 protected $width;
92
94 protected $height;
95
97 protected $bits;
98
100 protected $media_type;
101
103 protected $mime;
104
106 protected $size;
107
109 protected $metadataArray = [];
110
118
120 protected $metadataBlobs = [];
121
128 protected $unloadedMetadataBlobs = [];
129
131 protected $sha1;
132
134 protected $dataLoaded = false;
135
137 protected $extraDataLoaded = false;
138
140 protected $deleted;
141
143 protected $repoClass = LocalRepo::class;
144
146 private $historyLine = 0;
147
149 private $historyRes = null;
150
152 private $major_mime;
153
155 private $minor_mime;
156
158 private $timestamp;
159
161 private $user;
162
164 private $description;
165
167 private $descriptionTouched;
168
170 private $upgraded;
171
173 private $upgrading;
174
176 private $locked;
177
179 private $lockedOwnTrx;
180
182 private $missing;
183
185 private $metadataStorageHelper;
186
187 // @note: higher than IDBAccessObject constants
188 private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
189
190 private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
191
206 public static function newFromTitle( $title, $repo, $unused = null ) {
207 return new static( $title, $repo );
208 }
209
221 public static function newFromRow( $row, $repo ) {
222 $title = Title::makeTitle( NS_FILE, $row->img_name );
223 $file = new static( $title, $repo );
224 $file->loadFromRow( $row );
225
226 return $file;
227 }
228
240 public static function newFromKey( $sha1, $repo, $timestamp = false ) {
241 $dbr = $repo->getReplicaDB();
242 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
243
244 $queryBuilder->where( [ 'img_sha1' => $sha1 ] );
245
246 if ( $timestamp ) {
247 $queryBuilder->andWhere( [ 'img_timestamp' => $dbr->timestamp( $timestamp ) ] );
248 }
249
250 $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
251 if ( $row ) {
252 return static::newFromRow( $row, $repo );
253 } else {
254 return false;
255 }
256 }
257
278 public static function getQueryInfo( array $options = [] ) {
279 $dbr = MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->getReplicaDatabase();
280 $queryInfo = FileSelectQueryBuilder::newForFile( $dbr, $options )->getQueryInfo();
281 // needs remapping...
282 return [
283 'tables' => $queryInfo['tables'],
284 'fields' => $queryInfo['fields'],
285 'joins' => $queryInfo['join_conds'],
286 ];
287 }
288
296 public function __construct( $title, $repo ) {
297 parent::__construct( $title, $repo );
298 $this->metadataStorageHelper = new MetadataStorageHelper( $repo );
299
300 $this->assertRepoDefined();
301 $this->assertTitleDefined();
302 }
303
307 public function getRepo() {
308 return $this->repo;
309 }
310
317 protected function getCacheKey() {
318 return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
319 }
320
324 private function loadFromCache() {
325 $this->dataLoaded = false;
326 $this->extraDataLoaded = false;
327
328 $key = $this->getCacheKey();
329 if ( !$key ) {
330 $this->loadFromDB( self::READ_NORMAL );
331
332 return;
333 }
334
335 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
336 $cachedValues = $cache->getWithSetCallback(
337 $key,
338 $cache::TTL_WEEK,
339 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
340 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
341
342 $this->loadFromDB( self::READ_NORMAL );
343
344 $fields = $this->getCacheFields( '' );
345 $cacheVal = [];
346 $cacheVal['fileExists'] = $this->fileExists;
347 if ( $this->fileExists ) {
348 foreach ( $fields as $field ) {
349 $cacheVal[$field] = $this->$field;
350 }
351 }
352 if ( $this->user ) {
353 $cacheVal['user'] = $this->user->getId();
354 $cacheVal['user_text'] = $this->user->getName();
355 }
356
357 // Don't cache metadata items stored as blobs, since they tend to be large
358 if ( $this->metadataBlobs ) {
359 $cacheVal['metadata'] = array_diff_key(
360 $this->metadataArray, $this->metadataBlobs );
361 // Save the blob addresses
362 $cacheVal['metadataBlobs'] = $this->metadataBlobs;
363 } else {
364 $cacheVal['metadata'] = $this->metadataArray;
365 }
366
367 // Strip off excessive entries from the subset of fields that can become large.
368 // If the cache value gets too large and might not fit in the cache,
369 // causing repeat database queries for each access to the file.
370 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
371 if ( isset( $cacheVal[$field] )
372 && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
373 ) {
374 unset( $cacheVal[$field] ); // don't let the value get too big
375 if ( $field === 'metadata' ) {
376 unset( $cacheVal['metadataBlobs'] );
377 }
378 }
379 }
380
381 if ( $this->fileExists ) {
382 $ttl = $cache->adaptiveTTL( (int)wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
383 } else {
384 $ttl = $cache::TTL_DAY;
385 }
386
387 return $cacheVal;
388 },
389 [ 'version' => self::VERSION ]
390 );
391
392 $this->fileExists = $cachedValues['fileExists'];
393 if ( $this->fileExists ) {
394 $this->setProps( $cachedValues );
395 }
396
397 $this->dataLoaded = true;
398 $this->extraDataLoaded = true;
399 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
400 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
401 }
402 }
403
407 public function invalidateCache() {
408 $key = $this->getCacheKey();
409 if ( !$key ) {
410 return;
411 }
412
413 $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
414 static function () use ( $key ) {
415 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
416 },
417 __METHOD__
418 );
419 }
420
428 public function loadFromFile( $path = null ) {
429 $props = $this->repo->getFileProps( $path ?? $this->getVirtualUrl() );
430 $this->setProps( $props );
431 }
432
440 protected function getCacheFields( $prefix = 'img_' ) {
441 if ( $prefix !== '' ) {
442 throw new InvalidArgumentException(
443 __METHOD__ . ' with a non-empty prefix is no longer supported.'
444 );
445 }
446
447 // See self::getQueryInfo() for the fetching of the data from the DB,
448 // self::loadFromRow() for the loading of the object from the DB row,
449 // and self::loadFromCache() for the caching, and self::setProps() for
450 // populating the object from an array of data.
451 return [ 'size', 'width', 'height', 'bits', 'media_type',
452 'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
453 }
454
462 protected function getLazyCacheFields( $prefix = 'img_' ) {
463 if ( $prefix !== '' ) {
464 throw new InvalidArgumentException(
465 __METHOD__ . ' with a non-empty prefix is no longer supported.'
466 );
467 }
468
469 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
470 return [ 'metadata' ];
471 }
472
478 protected function loadFromDB( $flags = 0 ) {
479 $fname = static::class . '::' . __FUNCTION__;
480
481 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
482 $this->dataLoaded = true;
483 $this->extraDataLoaded = true;
484
485 $dbr = ( $flags & self::READ_LATEST )
486 ? $this->repo->getPrimaryDB()
487 : $this->repo->getReplicaDB();
488 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
489
490 $queryBuilder->where( [ 'img_name' => $this->getName() ] );
491 $row = $queryBuilder->caller( $fname )->fetchRow();
492
493 if ( $row ) {
494 $this->loadFromRow( $row );
495 } else {
496 $this->fileExists = false;
497 }
498 }
499
505 protected function loadExtraFromDB() {
506 if ( !$this->title ) {
507 return; // Avoid hard failure when the file does not exist. T221812
508 }
509
510 $fname = static::class . '::' . __FUNCTION__;
511
512 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
513 $this->extraDataLoaded = true;
514
515 $db = $this->repo->getReplicaDB();
516 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
517 if ( !$fieldMap ) {
518 $db = $this->repo->getPrimaryDB();
519 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
520 }
521
522 if ( $fieldMap ) {
523 if ( isset( $fieldMap['metadata'] ) ) {
524 $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
525 }
526 } else {
527 throw new MWException( "Could not find data for image '{$this->getName()}'." );
528 }
529 }
530
536 private function loadExtraFieldsWithTimestamp( IReadableDatabase $dbr, $fname ) {
537 $fieldMap = false;
538
539 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr, [ 'omit-nonlazy' ] );
540 $queryBuilder->where( [ 'img_name' => $this->getName() ] )
541 ->andWhere( [ 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] );
542 $row = $queryBuilder->caller( $fname )->fetchRow();
543 if ( $row ) {
544 $fieldMap = $this->unprefixRow( $row, 'img_' );
545 } else {
546 # File may have been uploaded over in the meantime; check the old versions
547 $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr, [ 'omit-nonlazy' ] );
548 $row = $queryBuilder->where( [ 'oi_name' => $this->getName() ] )
549 ->andWhere( [ 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] )
550 ->caller( __METHOD__ )->fetchRow();
551 if ( $row ) {
552 $fieldMap = $this->unprefixRow( $row, 'oi_' );
553 }
554 }
555
556 return $fieldMap;
557 }
558
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 MWException( __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 & self::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 MWException( '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
1292 private function purgeMetadataCache() {
1293 $this->invalidateCache();
1294 }
1295
1304 public function purgeCache( $options = [] ) {
1305 // Refresh metadata cache
1306 $this->maybeUpgradeRow();
1307 $this->purgeMetadataCache();
1308
1309 // Delete thumbnails
1310 $this->purgeThumbnails( $options );
1311
1312 // Purge CDN cache for this file
1313 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1314 $hcu->purgeUrls(
1315 $this->getUrl(),
1316 !empty( $options['forThumbRefresh'] )
1317 ? $hcu::PURGE_PRESEND // just a manual purge
1318 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1319 );
1320 }
1321
1327 public function purgeOldThumbnails( $archiveName ) {
1328 // Get a list of old thumbnails
1329 $thumbs = $this->getThumbnails( $archiveName );
1330
1331 // Delete thumbnails from storage, and prevent the directory itself from being purged
1332 $dir = array_shift( $thumbs );
1333 $this->purgeThumbList( $dir, $thumbs );
1334
1335 $urls = [];
1336 foreach ( $thumbs as $thumb ) {
1337 $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1338 }
1339
1340 // Purge any custom thumbnail caches
1341 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1342
1343 // Purge the CDN
1344 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1345 $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1346 }
1347
1354 public function purgeThumbnails( $options = [] ) {
1355 $thumbs = $this->getThumbnails();
1356
1357 // Delete thumbnails from storage, and prevent the directory itself from being purged
1358 $dir = array_shift( $thumbs );
1359 $this->purgeThumbList( $dir, $thumbs );
1360
1361 // Always purge all files from CDN regardless of handler filters
1362 $urls = [];
1363 foreach ( $thumbs as $thumb ) {
1364 $urls[] = $this->getThumbUrl( $thumb );
1365 }
1366
1367 // Give the media handler a chance to filter the file purge list
1368 if ( !empty( $options['forThumbRefresh'] ) ) {
1369 $handler = $this->getHandler();
1370 if ( $handler ) {
1371 $handler->filterThumbnailPurgeList( $thumbs, $options );
1372 }
1373 }
1374
1375 // Purge any custom thumbnail caches
1376 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1377
1378 // Purge the CDN
1379 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1380 $hcu->purgeUrls(
1381 $urls,
1382 !empty( $options['forThumbRefresh'] )
1383 ? $hcu::PURGE_PRESEND // just a manual purge
1384 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1385 );
1386 }
1387
1394 public function prerenderThumbnails() {
1395 $uploadThumbnailRenderMap = MediaWikiServices::getInstance()
1396 ->getMainConfig()->get( MainConfigNames::UploadThumbnailRenderMap );
1397
1398 $jobs = [];
1399
1400 $sizes = $uploadThumbnailRenderMap;
1401 rsort( $sizes );
1402
1403 foreach ( $sizes as $size ) {
1404 if ( $this->isMultipage() ) {
1405 // (T309114) Only trigger render jobs up to MAX_PAGE_RENDER_JOBS to avoid
1406 // a flood of jobs for huge files.
1407 $pageLimit = min( $this->pageCount(), self::MAX_PAGE_RENDER_JOBS );
1408
1409 $jobs[] = new ThumbnailRenderJob(
1410 $this->getTitle(),
1411 [
1412 'transformParams' => [ 'width' => $size, 'page' => 1 ],
1413 'enqueueNextPage' => true,
1414 'pageLimit' => $pageLimit
1415 ]
1416 );
1417 } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1418 $jobs[] = new ThumbnailRenderJob(
1419 $this->getTitle(),
1420 [ 'transformParams' => [ 'width' => $size ] ]
1421 );
1422 }
1423 }
1424
1425 if ( $jobs ) {
1426 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
1427 }
1428 }
1429
1436 protected function purgeThumbList( $dir, $files ) {
1437 $fileListDebug = strtr(
1438 var_export( $files, true ),
1439 [ "\n" => '' ]
1440 );
1441 wfDebug( __METHOD__ . ": $fileListDebug" );
1442
1443 if ( $this->repo->supportsSha1URLs() ) {
1444 $reference = $this->getSha1();
1445 } else {
1446 $reference = $this->getName();
1447 }
1448
1449 $purgeList = [];
1450 foreach ( $files as $file ) {
1451 # Check that the reference (filename or sha1) is part of the thumb name
1452 # This is a basic check to avoid erasing unrelated directories
1453 if ( str_contains( $file, $reference )
1454 || str_contains( $file, "-thumbnail" ) // "short" thumb name
1455 ) {
1456 $purgeList[] = "{$dir}/{$file}";
1457 }
1458 }
1459
1460 # Delete the thumbnails
1461 $this->repo->quickPurgeBatch( $purgeList );
1462 # Clear out the thumbnail directory if empty
1463 $this->repo->quickCleanDir( $dir );
1464 }
1465
1477 public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1478 if ( !$this->exists() ) {
1479 return []; // Avoid hard failure when the file does not exist. T221812
1480 }
1481
1482 $dbr = $this->repo->getReplicaDB();
1483 $oldFileQuery = OldLocalFile::getQueryInfo();
1484
1485 $tables = $oldFileQuery['tables'];
1486 $fields = $oldFileQuery['fields'];
1487 $join_conds = $oldFileQuery['joins'];
1488 $conds = $opts = [];
1489 $eq = $inc ? '=' : '';
1490 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1491
1492 if ( $start ) {
1493 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1494 }
1495
1496 if ( $end ) {
1497 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1498 }
1499
1500 if ( $limit ) {
1501 $opts['LIMIT'] = $limit;
1502 }
1503
1504 // Search backwards for time > x queries
1505 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1506 $opts['ORDER BY'] = "oi_timestamp $order";
1507 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1508
1509 $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1510 $conds, $opts, $join_conds );
1511
1512 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1513 $r = [];
1514
1515 foreach ( $res as $row ) {
1516 $r[] = $this->repo->newFileFromRow( $row );
1517 }
1518
1519 if ( $order == 'ASC' ) {
1520 $r = array_reverse( $r ); // make sure it ends up descending
1521 }
1522
1523 return $r;
1524 }
1525
1536 public function nextHistoryLine() {
1537 if ( !$this->exists() ) {
1538 return false; // Avoid hard failure when the file does not exist. T221812
1539 }
1540
1541 # Polymorphic function name to distinguish foreign and local fetches
1542 $fname = static::class . '::' . __FUNCTION__;
1543
1544 $dbr = $this->repo->getReplicaDB();
1545
1546 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1547 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
1548
1549 $queryBuilder->fields( [ 'oi_archive_name' => $dbr->addQuotes( '' ), 'oi_deleted' => '0' ] )
1550 ->where( [ 'img_name' => $this->title->getDBkey() ] );
1551 $this->historyRes = $queryBuilder->caller( $fname )->fetchResultSet();
1552
1553 if ( $this->historyRes->numRows() == 0 ) {
1554 $this->historyRes = null;
1555
1556 return false;
1557 }
1558 } elseif ( $this->historyLine == 1 ) {
1559 $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr );
1560
1561 $this->historyRes = $queryBuilder->where( [ 'oi_name' => $this->title->getDBkey() ] )
1562 ->orderBy( 'oi_timestamp', SelectQueryBuilder::SORT_DESC )
1563 ->caller( $fname )->fetchResultSet();
1564 }
1565 $this->historyLine++;
1566
1567 return $this->historyRes->fetchObject();
1568 }
1569
1574 public function resetHistory() {
1575 $this->historyLine = 0;
1576
1577 if ( $this->historyRes !== null ) {
1578 $this->historyRes = null;
1579 }
1580 }
1581
1615 public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1616 $timestamp = false, Authority $uploader = null, $tags = [],
1617 $createNullRevision = true, $revert = false
1618 ) {
1619 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1620 return $this->readOnlyFatalStatus();
1621 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1622 // Check this in advance to avoid writing to FileBackend and the file tables,
1623 // only to fail on insert the revision due to the text store being unavailable.
1624 return $this->readOnlyFatalStatus();
1625 }
1626
1627 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1628 if ( !$props ) {
1629 if ( FileRepo::isVirtualUrl( $srcPath )
1630 || FileBackend::isStoragePath( $srcPath )
1631 ) {
1632 $props = $this->repo->getFileProps( $srcPath );
1633 } else {
1634 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1635 $props = $mwProps->getPropsFromPath( $srcPath, true );
1636 }
1637 }
1638
1639 $options = [];
1640 $handler = MediaHandler::getHandler( $props['mime'] );
1641 if ( $handler ) {
1642 if ( is_string( $props['metadata'] ) ) {
1643 // This supports callers directly fabricating a metadata
1644 // property using serialize(). Normally the metadata property
1645 // comes from MWFileProps, in which case it won't be a string.
1646 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1647 $metadata = @unserialize( $props['metadata'] );
1648 } else {
1649 $metadata = $props['metadata'];
1650 }
1651
1652 if ( is_array( $metadata ) ) {
1653 $options['headers'] = $handler->getContentHeaders( $metadata );
1654 }
1655 } else {
1656 $options['headers'] = [];
1657 }
1658
1659 // Trim spaces on user supplied text
1660 $comment = trim( $comment );
1661
1662 $status = $this->publish( $src, $flags, $options );
1663
1664 if ( $status->successCount >= 2 ) {
1665 // There will be a copy+(one of move,copy,store).
1666 // The first succeeding does not commit us to updating the DB
1667 // since it simply copied the current version to a timestamped file name.
1668 // It is only *preferable* to avoid leaving such files orphaned.
1669 // Once the second operation goes through, then the current version was
1670 // updated and we must therefore update the DB too.
1671 $oldver = $status->value;
1672
1673 $uploadStatus = $this->recordUpload3(
1674 $oldver,
1675 $comment,
1676 $pageText,
1677 $uploader ?? RequestContext::getMain()->getAuthority(),
1678 $props,
1679 $timestamp,
1680 $tags,
1681 $createNullRevision,
1682 $revert
1683 );
1684 if ( !$uploadStatus->isOK() ) {
1685 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1686 // update filenotfound error with more specific path
1687 $status->fatal( 'filenotfound', $srcPath );
1688 } else {
1689 $status->merge( $uploadStatus );
1690 }
1691 }
1692 }
1693
1694 return $status;
1695 }
1696
1713 public function recordUpload3(
1714 string $oldver,
1715 string $comment,
1716 string $pageText,
1717 Authority $performer,
1718 $props = false,
1719 $timestamp = false,
1720 $tags = [],
1721 bool $createNullRevision = true,
1722 bool $revert = false
1723 ): Status {
1724 $dbw = $this->repo->getPrimaryDB();
1725
1726 # Imports or such might force a certain timestamp; otherwise we generate
1727 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1728 if ( $timestamp === false ) {
1729 $timestamp = $dbw->timestamp();
1730 $allowTimeKludge = true;
1731 } else {
1732 $allowTimeKludge = false;
1733 }
1734
1735 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1736 $props['description'] = $comment;
1737 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1738 $this->setProps( $props );
1739
1740 # Fail now if the file isn't there
1741 if ( !$this->fileExists ) {
1742 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1743
1744 return Status::newFatal( 'filenotfound', $this->getRel() );
1745 }
1746
1747 $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1748
1749 $dbw->startAtomic( __METHOD__ );
1750
1751 $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1752 $this->user = $performer->getUser();
1753
1754 # Test to see if the row exists using INSERT IGNORE
1755 # This avoids race conditions by locking the row until the commit, and also
1756 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1757 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1758 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1759 $actorFields = [ 'img_actor' => $actorId ];
1760 $dbw->newInsertQueryBuilder()
1761 ->insertInto( 'image' )
1762 ->ignore()
1763 ->row( [
1764 'img_name' => $this->getName(),
1765 'img_size' => $this->size,
1766 'img_width' => intval( $this->width ),
1767 'img_height' => intval( $this->height ),
1768 'img_bits' => $this->bits,
1769 'img_media_type' => $this->media_type,
1770 'img_major_mime' => $this->major_mime,
1771 'img_minor_mime' => $this->minor_mime,
1772 'img_timestamp' => $dbw->timestamp( $timestamp ),
1773 'img_metadata' => $this->getMetadataForDb( $dbw ),
1774 'img_sha1' => $this->sha1
1775 ] + $commentFields + $actorFields )
1776 ->caller( __METHOD__ )->execute();
1777 $reupload = ( $dbw->affectedRows() == 0 );
1778
1779 if ( $reupload ) {
1780 $row = $dbw->newSelectQueryBuilder()
1781 ->select( [ 'img_timestamp', 'img_sha1' ] )
1782 ->from( 'image' )
1783 ->where( [ 'img_name' => $this->getName() ] )
1784 ->caller( __METHOD__ )->fetchRow();
1785
1786 if ( $row && $row->img_sha1 === $this->sha1 ) {
1787 $dbw->endAtomic( __METHOD__ );
1788 wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1789 $title = Title::newFromText( $this->getName(), NS_FILE );
1790 return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1791 }
1792
1793 if ( $allowTimeKludge ) {
1794 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1795 $lUnixtime = $row ? (int)wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1796 # Avoid a timestamp that is not newer than the last version
1797 # TODO: the image/oldimage tables should be like page/revision with an ID field
1798 if ( $lUnixtime && (int)wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1799 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1800 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1801 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1802 }
1803 }
1804
1805 $tables = [ 'image' ];
1806 $fields = [
1807 'oi_name' => 'img_name',
1808 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1809 'oi_size' => 'img_size',
1810 'oi_width' => 'img_width',
1811 'oi_height' => 'img_height',
1812 'oi_bits' => 'img_bits',
1813 'oi_description_id' => 'img_description_id',
1814 'oi_timestamp' => 'img_timestamp',
1815 'oi_metadata' => 'img_metadata',
1816 'oi_media_type' => 'img_media_type',
1817 'oi_major_mime' => 'img_major_mime',
1818 'oi_minor_mime' => 'img_minor_mime',
1819 'oi_sha1' => 'img_sha1',
1820 'oi_actor' => 'img_actor',
1821 ];
1822 $joins = [];
1823
1824 # (T36993) Note: $oldver can be empty here, if the previous
1825 # version of the file was broken. Allow registration of the new
1826 # version to continue anyway, because that's better than having
1827 # an image that's not fixable by user operations.
1828 # Collision, this is an update of a file
1829 # Insert previous contents into oldimage
1830 $dbw->insertSelect( 'oldimage', $tables, $fields,
1831 [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1832
1833 # Update the current image row
1834 $dbw->newUpdateQueryBuilder()
1835 ->update( 'image' )
1836 ->set( [
1837 'img_size' => $this->size,
1838 'img_width' => intval( $this->width ),
1839 'img_height' => intval( $this->height ),
1840 'img_bits' => $this->bits,
1841 'img_media_type' => $this->media_type,
1842 'img_major_mime' => $this->major_mime,
1843 'img_minor_mime' => $this->minor_mime,
1844 'img_timestamp' => $dbw->timestamp( $timestamp ),
1845 'img_metadata' => $this->getMetadataForDb( $dbw ),
1846 'img_sha1' => $this->sha1
1847 ] + $commentFields + $actorFields )
1848 ->where( [ 'img_name' => $this->getName() ] )
1849 ->caller( __METHOD__ )->execute();
1850 }
1851
1852 $descTitle = $this->getTitle();
1853 $descId = $descTitle->getArticleID();
1854 $wikiPage = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $descTitle );
1855 if ( !$wikiPage instanceof WikiFilePage ) {
1856 throw new MWException( 'Cannot instance WikiFilePage for ' . $this->getName()
1857 . ', got instance of ' . get_class( $wikiPage ) );
1858 }
1859 $wikiPage->setFile( $this );
1860
1861 // Determine log action. If reupload is done by reverting, use a special log_action.
1862 if ( $revert ) {
1863 $logAction = 'revert';
1864 } elseif ( $reupload ) {
1865 $logAction = 'overwrite';
1866 } else {
1867 $logAction = 'upload';
1868 }
1869 // Add the log entry...
1870 $logEntry = new ManualLogEntry( 'upload', $logAction );
1871 $logEntry->setTimestamp( $this->timestamp );
1872 $logEntry->setPerformer( $performer->getUser() );
1873 $logEntry->setComment( $comment );
1874 $logEntry->setTarget( $descTitle );
1875 // Allow people using the api to associate log entries with the upload.
1876 // Log has a timestamp, but sometimes different from upload timestamp.
1877 $logEntry->setParameters(
1878 [
1879 'img_sha1' => $this->sha1,
1880 'img_timestamp' => $timestamp,
1881 ]
1882 );
1883 // Note we keep $logId around since during new image
1884 // creation, page doesn't exist yet, so log_page = 0
1885 // but we want it to point to the page we're making,
1886 // so we later modify the log entry.
1887 // For a similar reason, we avoid making an RC entry
1888 // now and wait until the page exists.
1889 $logId = $logEntry->insert();
1890
1891 if ( $descTitle->exists() ) {
1892 if ( $createNullRevision ) {
1893 $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1894 // Use own context to get the action text in content language
1895 $formatter = LogFormatter::newFromEntry( $logEntry );
1896 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1897 $editSummary = $formatter->getPlainActionText();
1898 $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1899 $nullRevRecord = $revStore->newNullRevision(
1900 $dbw,
1901 $descTitle,
1902 $summary,
1903 false,
1904 $performer->getUser()
1905 );
1906
1907 if ( $nullRevRecord ) {
1908 $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1909
1910 $this->getHookRunner()->onRevisionFromEditComplete(
1911 $wikiPage,
1912 $inserted,
1913 $inserted->getParentId(),
1914 $performer->getUser(),
1915 $tags
1916 );
1917
1918 $wikiPage->updateRevisionOn( $dbw, $inserted );
1919 // Associate null revision id
1920 $logEntry->setAssociatedRevId( $inserted->getId() );
1921 }
1922 }
1923
1924 $newPageContent = null;
1925 } else {
1926 // Make the description page and RC log entry post-commit
1927 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1928 }
1929
1930 // NOTE: Even after ending this atomic section, we are probably still in the implicit
1931 // transaction started by any prior master query in the request. We cannot yet safely
1932 // schedule jobs, see T263301.
1933 $dbw->endAtomic( __METHOD__ );
1934 $fname = __METHOD__;
1935
1936 # Do some cache purges after final commit so that:
1937 # a) Changes are more likely to be seen post-purge
1938 # b) They won't cause rollback of the log publish/update above
1939 $purgeUpdate = new AutoCommitUpdate(
1940 $dbw,
1941 __METHOD__,
1942 function () use (
1943 $reupload, $wikiPage, $newPageContent, $comment, $performer,
1944 $logEntry, $logId, $descId, $tags, $fname
1945 ) {
1946 # Update memcache after the commit
1947 $this->invalidateCache();
1948
1949 $updateLogPage = false;
1950 if ( $newPageContent ) {
1951 # New file page; create the description page.
1952 # There's already a log entry, so don't make a second RC entry
1953 # CDN and file cache for the description page are purged by doUserEditContent.
1954 $status = $wikiPage->doUserEditContent(
1955 $newPageContent,
1956 $performer,
1957 $comment,
1959 );
1960
1961 $revRecord = $status->getNewRevision();
1962 if ( $revRecord ) {
1963 // Associate new page revision id
1964 $logEntry->setAssociatedRevId( $revRecord->getId() );
1965
1966 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1967 // which is triggered on $descTitle by doUserEditContent() above.
1968 $updateLogPage = $revRecord->getPageId();
1969 }
1970 } else {
1971 # Existing file page: invalidate description page cache
1972 $title = $wikiPage->getTitle();
1973 $title->invalidateCache();
1974 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1975 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1976 # Allow the new file version to be patrolled from the page footer
1978 }
1979
1980 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1981 # but setAssociatedRevId() wasn't called at that point yet...
1982 $logParams = $logEntry->getParameters();
1983 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1984 $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1985 if ( $updateLogPage ) {
1986 # Also log page, in case where we just created it above
1987 $update['log_page'] = $updateLogPage;
1988 }
1989 $this->getRepo()->getPrimaryDB()->newUpdateQueryBuilder()
1990 ->update( 'logging' )
1991 ->set( $update )
1992 ->where( [ 'log_id' => $logId ] )
1993 ->caller( $fname )->execute();
1994
1995 $this->getRepo()->getPrimaryDB()->insert(
1996 'log_search',
1997 [
1998 'ls_field' => 'associated_rev_id',
1999 'ls_value' => (string)$logEntry->getAssociatedRevId(),
2000 'ls_log_id' => $logId,
2001 ],
2002 $fname
2003 );
2004
2005 # Add change tags, if any
2006 if ( $tags ) {
2007 $logEntry->addTags( $tags );
2008 }
2009
2010 # Uploads can be patrolled
2011 $logEntry->setIsPatrollable( true );
2012
2013 # Now that the log entry is up-to-date, make an RC entry.
2014 $logEntry->publish( $logId );
2015
2016 # Run hook for other updates (typically more cache purging)
2017 $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2018
2019 if ( $reupload ) {
2020 # Delete old thumbnails
2021 $this->purgeThumbnails();
2022 # Remove the old file from the CDN cache
2023 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2024 $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2025 } else {
2026 # Update backlink pages pointing to this title if created
2027 $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2028 LinksUpdate::queueRecursiveJobsForTable(
2029 $this->getTitle(),
2030 'imagelinks',
2031 'upload-image',
2032 $performer->getUser()->getName(),
2033 $blcFactory->getBacklinkCache( $this->getTitle() )
2034 );
2035 }
2036
2037 $this->prerenderThumbnails();
2038 }
2039 );
2040
2041 # Invalidate cache for all pages using this file
2042 $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
2043 $this->getTitle(),
2044 'imagelinks',
2045 [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2046 );
2047
2048 // NOTE: We are probably still in the implicit transaction started by DBO_TRX. We should
2049 // only schedule jobs after that transaction was committed, so a job queue failure
2050 // doesn't cause the upload to fail (T263301). Also, we should generally not schedule any
2051 // Jobs or the DeferredUpdates that assume the update is complete until after the
2052 // transaction has been committed and we are sure that the upload was indeed successful.
2053 $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2054 DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2055
2056 if ( !$reupload ) {
2057 // This is a new file, so update the image count
2058 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2059 }
2060
2061 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $cacheUpdateJob );
2062 }, __METHOD__ );
2063
2064 return Status::newGood();
2065 }
2066
2083 public function publish( $src, $flags = 0, array $options = [] ) {
2084 return $this->publishTo( $src, $this->getRel(), $flags, $options );
2085 }
2086
2103 protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2104 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
2105
2106 $repo = $this->getRepo();
2107 if ( $repo->getReadOnlyReason() !== false ) {
2108 return $this->readOnlyFatalStatus();
2109 }
2110
2111 $status = $this->acquireFileLock();
2112 if ( !$status->isOK() ) {
2113 return $status;
2114 }
2115
2116 if ( $this->isOld() ) {
2117 $archiveRel = $dstRel;
2118 $archiveName = basename( $archiveRel );
2119 } else {
2120 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
2121 $archiveRel = $this->getArchiveRel( $archiveName );
2122 }
2123
2124 if ( $repo->hasSha1Storage() ) {
2125 $sha1 = FileRepo::isVirtualUrl( $srcPath )
2126 ? $repo->getFileSha1( $srcPath )
2127 : FSFile::getSha1Base36FromPath( $srcPath );
2129 $wrapperBackend = $repo->getBackend();
2130 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2131 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2132 $status = $repo->quickImport( $src, $dst );
2133 if ( $flags & File::DELETE_SOURCE ) {
2134 unlink( $srcPath );
2135 }
2136
2137 if ( $this->exists() ) {
2138 $status->value = $archiveName;
2139 }
2140 } else {
2141 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2142 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2143
2144 if ( $status->value == 'new' ) {
2145 $status->value = '';
2146 } else {
2147 $status->value = $archiveName;
2148 }
2149 }
2150
2151 $this->releaseFileLock();
2152 return $status;
2153 }
2154
2173 public function move( $target ) {
2174 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2175 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2176 return $this->readOnlyFatalStatus();
2177 }
2178
2179 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2180 $batch = new LocalFileMoveBatch( $this, $target );
2181
2182 $status = $batch->addCurrent();
2183 if ( !$status->isOK() ) {
2184 return $status;
2185 }
2186 $archiveNames = $batch->addOlds();
2187 $status = $batch->execute();
2188
2189 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2190
2191 // Purge the source and target files outside the transaction...
2192 $oldTitleFile = $localRepo->newFile( $this->title );
2193 $newTitleFile = $localRepo->newFile( $target );
2194 DeferredUpdates::addUpdate(
2195 new AutoCommitUpdate(
2196 $this->getRepo()->getPrimaryDB(),
2197 __METHOD__,
2198 static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2199 $oldTitleFile->purgeEverything();
2200 foreach ( $archiveNames as $archiveName ) {
2202 '@phan-var OldLocalFile $oldTitleFile';
2203 $oldTitleFile->purgeOldThumbnails( $archiveName );
2204 }
2205 $newTitleFile->purgeEverything();
2206 }
2207 ),
2208 DeferredUpdates::PRESEND
2209 );
2210
2211 if ( $status->isOK() ) {
2212 // Now switch the object
2213 $this->title = $target;
2214 // Force regeneration of the name and hashpath
2215 $this->name = null;
2216 $this->hashPath = null;
2217 }
2218
2219 return $status;
2220 }
2221
2238 public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2239 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2240 return $this->readOnlyFatalStatus();
2241 }
2242
2243 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2244
2245 $batch->addCurrent();
2246 // Get old version relative paths
2247 $archiveNames = $batch->addOlds();
2248 $status = $batch->execute();
2249
2250 if ( $status->isOK() ) {
2251 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2252 }
2253
2254 // To avoid slow purges in the transaction, move them outside...
2255 DeferredUpdates::addUpdate(
2256 new AutoCommitUpdate(
2257 $this->getRepo()->getPrimaryDB(),
2258 __METHOD__,
2259 function () use ( $archiveNames ) {
2260 $this->purgeEverything();
2261 foreach ( $archiveNames as $archiveName ) {
2262 $this->purgeOldThumbnails( $archiveName );
2263 }
2264 }
2265 ),
2266 DeferredUpdates::PRESEND
2267 );
2268
2269 // Purge the CDN
2270 $purgeUrls = [];
2271 foreach ( $archiveNames as $archiveName ) {
2272 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2273 }
2274
2275 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2276 $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2277
2278 return $status;
2279 }
2280
2299 public function deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress = false ) {
2300 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2301 return $this->readOnlyFatalStatus();
2302 }
2303
2304 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2305
2306 $batch->addOld( $archiveName );
2307 $status = $batch->execute();
2308
2309 $this->purgeOldThumbnails( $archiveName );
2310 if ( $status->isOK() ) {
2311 $this->purgeDescription();
2312 }
2313
2314 $url = $this->getArchiveUrl( $archiveName );
2315 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2316 $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2317
2318 return $status;
2319 }
2320
2333 public function restore( $versions = [], $unsuppress = false ) {
2334 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2335 return $this->readOnlyFatalStatus();
2336 }
2337
2338 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2339
2340 if ( !$versions ) {
2341 $batch->addAll();
2342 } else {
2343 $batch->addIds( $versions );
2344 }
2345 $status = $batch->execute();
2346 if ( $status->isGood() ) {
2347 $cleanupStatus = $batch->cleanup();
2348 $cleanupStatus->successCount = 0;
2349 $cleanupStatus->failCount = 0;
2350 $status->merge( $cleanupStatus );
2351 }
2352
2353 return $status;
2354 }
2355
2366 public function getDescriptionUrl() {
2367 // Avoid hard failure when the file does not exist. T221812
2368 return $this->title ? $this->title->getLocalURL() : false;
2369 }
2370
2380 public function getDescriptionText( Language $lang = null ) {
2381 if ( !$this->title ) {
2382 return false; // Avoid hard failure when the file does not exist. T221812
2383 }
2384
2385 $services = MediaWikiServices::getInstance();
2386 $page = $services->getPageStore()->getPageByReference( $this->getTitle() );
2387 if ( !$page ) {
2388 return false;
2389 }
2390
2391 if ( $lang ) {
2392 $parserOptions = ParserOptions::newFromUserAndLang(
2393 RequestContext::getMain()->getUser(),
2394 $lang
2395 );
2396 } else {
2397 $parserOptions = ParserOptions::newFromContext( RequestContext::getMain() );
2398 }
2399
2400 $parseStatus = $services->getParserOutputAccess()
2401 ->getParserOutput( $page, $parserOptions );
2402
2403 if ( !$parseStatus->isGood() ) {
2404 // Rendering failed.
2405 return false;
2406 }
2407 return $parseStatus->getValue()->getText();
2408 }
2409
2417 public function getUploader( int $audience = self::FOR_PUBLIC, Authority $performer = null ): ?UserIdentity {
2418 $this->load();
2419 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2420 return null;
2421 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2422 return null;
2423 } else {
2424 return $this->user;
2425 }
2426 }
2427
2434 public function getDescription( $audience = self::FOR_PUBLIC, Authority $performer = null ) {
2435 $this->load();
2436 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2437 return '';
2438 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2439 return '';
2440 } else {
2441 return $this->description;
2442 }
2443 }
2444
2449 public function getTimestamp() {
2450 $this->load();
2451
2452 return $this->timestamp;
2453 }
2454
2459 public function getDescriptionTouched() {
2460 if ( !$this->exists() ) {
2461 return false; // Avoid hard failure when the file does not exist. T221812
2462 }
2463
2464 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2465 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2466 // need to differentiate between null (uninitialized) and false (failed to load).
2467 if ( $this->descriptionTouched === null ) {
2468 $touched = $this->repo->getReplicaDB()->newSelectQueryBuilder()
2469 ->select( 'page_touched' )
2470 ->from( 'page' )
2471 ->where( [ 'page_namespace' => $this->title->getNamespace() ] )
2472 ->andWhere( [ 'page_title' => $this->title->getDBkey() ] )
2473 ->caller( __METHOD__ )->fetchField();
2474 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2475 }
2476
2477 return $this->descriptionTouched;
2478 }
2479
2484 public function getSha1() {
2485 $this->load();
2486 return $this->sha1;
2487 }
2488
2492 public function isCacheable() {
2493 $this->load();
2494
2495 // If extra data (metadata) was not loaded then it must have been large
2496 return $this->extraDataLoaded
2497 && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2498 }
2499
2508 public function acquireFileLock( $timeout = 0 ) {
2509 return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2510 [ $this->getPath() ], LockManager::LOCK_EX, $timeout
2511 ) );
2512 }
2513
2520 public function releaseFileLock() {
2521 return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2522 [ $this->getPath() ], LockManager::LOCK_EX
2523 ) );
2524 }
2525
2536 public function lock() {
2537 if ( !$this->locked ) {
2538 $logger = LoggerFactory::getInstance( 'LocalFile' );
2539
2540 $dbw = $this->repo->getPrimaryDB();
2541 $makesTransaction = !$dbw->trxLevel();
2542 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2543 // T56736: use simple lock to handle when the file does not exist.
2544 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2545 // Also, that would cause contention on INSERT of similarly named rows.
2546 $status = $this->acquireFileLock( 10 ); // represents all versions of the file
2547 if ( !$status->isGood() ) {
2548 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2549 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2550
2551 throw new LocalFileLockError( $status );
2552 }
2553 // Release the lock *after* commit to avoid row-level contention.
2554 // Make sure it triggers on rollback() as well as commit() (T132921).
2555 $dbw->onTransactionResolution(
2556 function () use ( $logger ) {
2557 $status = $this->releaseFileLock();
2558 if ( !$status->isGood() ) {
2559 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2560 }
2561 },
2562 __METHOD__
2563 );
2564 // Callers might care if the SELECT snapshot is safely fresh
2565 $this->lockedOwnTrx = $makesTransaction;
2566 }
2567
2568 $this->locked++;
2569
2570 return $this->lockedOwnTrx;
2571 }
2572
2583 public function unlock() {
2584 if ( $this->locked ) {
2585 --$this->locked;
2586 if ( !$this->locked ) {
2587 $dbw = $this->repo->getPrimaryDB();
2588 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2589 $this->lockedOwnTrx = false;
2590 }
2591 }
2592 }
2593
2597 protected function readOnlyFatalStatus() {
2598 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2599 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2600 }
2601
2605 public function __destruct() {
2606 $this->unlock();
2607 }
2608}
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.
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Definition Article.php:1418
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:288
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:70
string $url
The URL corresponding to one of the four basic zones.
Definition File.php:138
MediaHandler $handler
Definition File.php:135
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition File.php:2458
getName()
Return the name of this file.
Definition File.php:336
const DELETE_SOURCE
Definition File.php:87
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
Definition File.php:1920
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition File.php:2468
FileRepo LocalRepo ForeignAPIRepo false $repo
Some member variables can be lazy-initialised using __get().
Definition File.php:117
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition File.php:2155
Title string false $title
Definition File.php:120
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1539
string null $name
The name of a file from its title object.
Definition File.php:144
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:67
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:94
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:97
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:91
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:88
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.
MediaWiki exception.
MimeMagic helper wrapper.
Class for creating new log entries and inserting them into the database.
const METADATA_COMPATIBLE
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
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.
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:79
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 the current execution context, such as a web reque...
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...
$mime
Definition router.php:60
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42