MediaWiki REL1_40
LocalFile.php
Go to the documentation of this file.
1<?php
34
61class LocalFile extends File {
62 private const VERSION = 13; // cache version
63
64 private const CACHE_FIELD_MAX_LEN = 1000;
65
67 private const MDS_EMPTY = 'empty';
68
70 private const MDS_LEGACY = 'legacy';
71
73 private const MDS_PHP = 'php';
74
76 private const MDS_JSON = 'json';
77
79 private const MAX_PAGE_RENDER_JOBS = 50;
80
82 protected $fileExists;
83
85 protected $width;
86
88 protected $height;
89
91 protected $bits;
92
94 protected $media_type;
95
97 protected $mime;
98
100 protected $size;
101
103 protected $metadataArray = [];
104
112
114 protected $metadataBlobs = [];
115
122 protected $unloadedMetadataBlobs = [];
123
125 protected $sha1;
126
128 protected $dataLoaded = false;
129
131 protected $extraDataLoaded = false;
132
134 protected $deleted;
135
137 protected $repoClass = LocalRepo::class;
138
140 private $historyLine = 0;
141
143 private $historyRes = null;
144
146 private $major_mime;
147
149 private $minor_mime;
150
152 private $timestamp;
153
155 private $user;
156
158 private $description;
159
161 private $descriptionTouched;
162
164 private $upgraded;
165
167 private $upgrading;
168
170 private $locked;
171
173 private $lockedOwnTrx;
174
176 private $missing;
177
179 private $metadataStorageHelper;
180
181 // @note: higher than IDBAccessObject constants
182 private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
183
184 private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
185
200 public static function newFromTitle( $title, $repo, $unused = null ) {
201 return new static( $title, $repo );
202 }
203
215 public static function newFromRow( $row, $repo ) {
216 $title = Title::makeTitle( NS_FILE, $row->img_name );
217 $file = new static( $title, $repo );
218 $file->loadFromRow( $row );
219
220 return $file;
221 }
222
234 public static function newFromKey( $sha1, $repo, $timestamp = false ) {
235 $dbr = $repo->getReplicaDB();
236
237 $conds = [ 'img_sha1' => $sha1 ];
238 if ( $timestamp ) {
239 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
240 }
241
242 $fileQuery = static::getQueryInfo();
243 $row = $dbr->selectRow(
244 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__, [], $fileQuery['joins']
245 );
246 if ( $row ) {
247 return static::newFromRow( $row, $repo );
248 } else {
249 return false;
250 }
251 }
252
272 public static function getQueryInfo( array $options = [] ) {
273 $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'img_description' );
274 $ret = [
275 'tables' => [
276 'image',
277 'image_actor' => 'actor'
278 ] + $commentQuery['tables'],
279 'fields' => [
280 'img_name',
281 'img_size',
282 'img_width',
283 'img_height',
284 'img_metadata',
285 'img_bits',
286 'img_media_type',
287 'img_major_mime',
288 'img_minor_mime',
289 'img_timestamp',
290 'img_sha1',
291 'img_actor',
292 'img_user' => 'image_actor.actor_user',
293 'img_user_text' => 'image_actor.actor_name',
294 ] + $commentQuery['fields'],
295 'joins' => [
296 'image_actor' => [ 'JOIN', 'actor_id=img_actor' ]
297 ] + $commentQuery['joins'],
298 ];
299
300 if ( in_array( 'omit-nonlazy', $options, true ) ) {
301 // Internal use only for getting only the lazy fields
302 $ret['fields'] = [];
303 }
304 if ( !in_array( 'omit-lazy', $options, true ) ) {
305 // Note: Keep this in sync with self::getLazyCacheFields() and
306 // self::loadExtraFromDB()
307 $ret['fields'][] = 'img_metadata';
308 }
309
310 return $ret;
311 }
312
320 public function __construct( $title, $repo ) {
321 parent::__construct( $title, $repo );
322 $this->metadataStorageHelper = new MetadataStorageHelper( $repo );
323
324 $this->assertRepoDefined();
325 $this->assertTitleDefined();
326 }
327
331 public function getRepo() {
332 return $this->repo;
333 }
334
341 protected function getCacheKey() {
342 return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
343 }
344
348 private function loadFromCache() {
349 $this->dataLoaded = false;
350 $this->extraDataLoaded = false;
351
352 $key = $this->getCacheKey();
353 if ( !$key ) {
354 $this->loadFromDB( self::READ_NORMAL );
355
356 return;
357 }
358
359 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
360 $cachedValues = $cache->getWithSetCallback(
361 $key,
362 $cache::TTL_WEEK,
363 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
364 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
365
366 $this->loadFromDB( self::READ_NORMAL );
367
368 $fields = $this->getCacheFields( '' );
369 $cacheVal = [];
370 $cacheVal['fileExists'] = $this->fileExists;
371 if ( $this->fileExists ) {
372 foreach ( $fields as $field ) {
373 $cacheVal[$field] = $this->$field;
374 }
375 }
376 if ( $this->user ) {
377 $cacheVal['user'] = $this->user->getId();
378 $cacheVal['user_text'] = $this->user->getName();
379 }
380
381 // Don't cache metadata items stored as blobs, since they tend to be large
382 if ( $this->metadataBlobs ) {
383 $cacheVal['metadata'] = array_diff_key(
384 $this->metadataArray, $this->metadataBlobs );
385 // Save the blob addresses
386 $cacheVal['metadataBlobs'] = $this->metadataBlobs;
387 } else {
388 $cacheVal['metadata'] = $this->metadataArray;
389 }
390
391 // Strip off excessive entries from the subset of fields that can become large.
392 // If the cache value gets too large and might not fit in the cache,
393 // causing repeat database queries for each access to the file.
394 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
395 if ( isset( $cacheVal[$field] )
396 && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
397 ) {
398 unset( $cacheVal[$field] ); // don't let the value get too big
399 if ( $field === 'metadata' ) {
400 unset( $cacheVal['metadataBlobs'] );
401 }
402 }
403 }
404
405 if ( $this->fileExists ) {
406 $ttl = $cache->adaptiveTTL( (int)wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
407 } else {
408 $ttl = $cache::TTL_DAY;
409 }
410
411 return $cacheVal;
412 },
413 [ 'version' => self::VERSION ]
414 );
415
416 $this->fileExists = $cachedValues['fileExists'];
417 if ( $this->fileExists ) {
418 $this->setProps( $cachedValues );
419 }
420
421 $this->dataLoaded = true;
422 $this->extraDataLoaded = true;
423 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
424 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
425 }
426 }
427
431 public function invalidateCache() {
432 $key = $this->getCacheKey();
433 if ( !$key ) {
434 return;
435 }
436
437 $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
438 static function () use ( $key ) {
439 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
440 },
441 __METHOD__
442 );
443 }
444
452 public function loadFromFile( $path = null ) {
453 $props = $this->repo->getFileProps( $path ?? $this->getVirtualUrl() );
454 $this->setProps( $props );
455 }
456
464 protected function getCacheFields( $prefix = 'img_' ) {
465 if ( $prefix !== '' ) {
466 throw new InvalidArgumentException(
467 __METHOD__ . ' with a non-empty prefix is no longer supported.'
468 );
469 }
470
471 // See self::getQueryInfo() for the fetching of the data from the DB,
472 // self::loadFromRow() for the loading of the object from the DB row,
473 // and self::loadFromCache() for the caching, and self::setProps() for
474 // populating the object from an array of data.
475 return [ 'size', 'width', 'height', 'bits', 'media_type',
476 'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
477 }
478
486 protected function getLazyCacheFields( $prefix = 'img_' ) {
487 if ( $prefix !== '' ) {
488 throw new InvalidArgumentException(
489 __METHOD__ . ' with a non-empty prefix is no longer supported.'
490 );
491 }
492
493 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
494 return [ 'metadata' ];
495 }
496
502 protected function loadFromDB( $flags = 0 ) {
503 $fname = static::class . '::' . __FUNCTION__;
504
505 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
506 $this->dataLoaded = true;
507 $this->extraDataLoaded = true;
508
509 $dbr = ( $flags & self::READ_LATEST )
510 ? $this->repo->getPrimaryDB()
511 : $this->repo->getReplicaDB();
512
513 $fileQuery = static::getQueryInfo();
514 $row = $dbr->selectRow(
515 $fileQuery['tables'],
516 $fileQuery['fields'],
517 [ 'img_name' => $this->getName() ],
518 $fname,
519 [],
520 $fileQuery['joins']
521 );
522
523 if ( $row ) {
524 $this->loadFromRow( $row );
525 } else {
526 $this->fileExists = false;
527 }
528 }
529
535 protected function loadExtraFromDB() {
536 if ( !$this->title ) {
537 return; // Avoid hard failure when the file does not exist. T221812
538 }
539
540 $fname = static::class . '::' . __FUNCTION__;
541
542 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
543 $this->extraDataLoaded = true;
544
545 $db = $this->repo->getReplicaDB();
546 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
547 if ( !$fieldMap ) {
548 $db = $this->repo->getPrimaryDB();
549 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
550 }
551
552 if ( $fieldMap ) {
553 if ( isset( $fieldMap['metadata'] ) ) {
554 $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
555 }
556 } else {
557 throw new MWException( "Could not find data for image '{$this->getName()}'." );
558 }
559 }
560
566 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
567 $fieldMap = false;
568
569 $fileQuery = self::getQueryInfo( [ 'omit-nonlazy' ] );
570 $row = $dbr->selectRow(
571 $fileQuery['tables'],
572 $fileQuery['fields'],
573 [
574 'img_name' => $this->getName(),
575 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
576 ],
577 $fname,
578 [],
579 $fileQuery['joins']
580 );
581 if ( $row ) {
582 $fieldMap = $this->unprefixRow( $row, 'img_' );
583 } else {
584 # File may have been uploaded over in the meantime; check the old versions
585 $fileQuery = OldLocalFile::getQueryInfo( [ 'omit-nonlazy' ] );
586 $row = $dbr->selectRow(
587 $fileQuery['tables'],
588 $fileQuery['fields'],
589 [
590 'oi_name' => $this->getName(),
591 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
592 ],
593 $fname,
594 [],
595 $fileQuery['joins']
596 );
597 if ( $row ) {
598 $fieldMap = $this->unprefixRow( $row, 'oi_' );
599 }
600 }
601
602 return $fieldMap;
603 }
604
611 protected function unprefixRow( $row, $prefix = 'img_' ) {
612 $array = (array)$row;
613 $prefixLength = strlen( $prefix );
614
615 // Double check prefix once
616 if ( substr( array_key_first( $array ), 0, $prefixLength ) !== $prefix ) {
617 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
618 }
619
620 $decoded = [];
621 foreach ( $array as $name => $value ) {
622 $decoded[substr( $name, $prefixLength )] = $value;
623 }
624
625 return $decoded;
626 }
627
643 public function loadFromRow( $row, $prefix = 'img_' ) {
644 $this->dataLoaded = true;
645
646 $unprefixed = $this->unprefixRow( $row, $prefix );
647
648 $this->name = $unprefixed['name'];
649 $this->media_type = $unprefixed['media_type'];
650
651 $services = MediaWikiServices::getInstance();
652 $this->description = $services->getCommentStore()
653 ->getComment( "{$prefix}description", $row )->text;
654
655 $this->user = $services->getUserFactory()->newFromAnyId(
656 $unprefixed['user'] ?? null,
657 $unprefixed['user_text'] ?? null,
658 $unprefixed['actor'] ?? null
659 );
660
661 $this->timestamp = wfTimestamp( TS_MW, $unprefixed['timestamp'] );
662
664 $this->repo->getReplicaDB(), $unprefixed['metadata'] );
665
666 if ( empty( $unprefixed['major_mime'] ) ) {
667 $this->major_mime = 'unknown';
668 $this->minor_mime = 'unknown';
669 $this->mime = 'unknown/unknown';
670 } else {
671 if ( !$unprefixed['minor_mime'] ) {
672 $unprefixed['minor_mime'] = 'unknown';
673 }
674 $this->major_mime = $unprefixed['major_mime'];
675 $this->minor_mime = $unprefixed['minor_mime'];
676 $this->mime = $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
677 }
678
679 // Trim zero padding from char/binary field
680 $this->sha1 = rtrim( $unprefixed['sha1'], "\0" );
681
682 // Normalize some fields to integer type, per their database definition.
683 // Use unary + so that overflows will be upgraded to double instead of
684 // being truncated as with intval(). This is important to allow > 2 GiB
685 // files on 32-bit systems.
686 $this->size = +$unprefixed['size'];
687 $this->width = +$unprefixed['width'];
688 $this->height = +$unprefixed['height'];
689 $this->bits = +$unprefixed['bits'];
690
691 // Check for extra fields (deprecated since MW 1.37)
692 $extraFields = array_diff(
693 array_keys( $unprefixed ),
694 [
695 'name', 'media_type', 'description_text', 'description_data',
696 'description_cid', 'user', 'user_text', 'actor', 'timestamp',
697 'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
698 'height', 'bits'
699 ]
700 );
701 if ( $extraFields ) {
703 'Passing extra fields (' .
704 implode( ', ', $extraFields )
705 . ') to ' . __METHOD__ . ' was deprecated in MediaWiki 1.37. ' .
706 'Property assignment will be removed in a later version.',
707 '1.37' );
708 foreach ( $extraFields as $field ) {
709 $this->$field = $unprefixed[$field];
710 }
711 }
712
713 $this->fileExists = true;
714 }
715
721 public function load( $flags = 0 ) {
722 if ( !$this->dataLoaded ) {
723 if ( $flags & self::READ_LATEST ) {
724 $this->loadFromDB( $flags );
725 } else {
726 $this->loadFromCache();
727 }
728 }
729
730 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
731 // @note: loads on name/timestamp to reduce race condition problems
732 $this->loadExtraFromDB();
733 }
734 }
735
740 public function maybeUpgradeRow() {
741 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() || $this->upgrading ) {
742 return;
743 }
744
745 $upgrade = false;
746 $reserialize = false;
747 if ( $this->media_type === null || $this->mime == 'image/svg' ) {
748 $upgrade = true;
749 } else {
750 $handler = $this->getHandler();
751 if ( $handler ) {
752 $validity = $handler->isFileMetadataValid( $this );
753 if ( $validity === MediaHandler::METADATA_BAD ) {
754 $upgrade = true;
755 } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE
756 && $this->repo->isMetadataUpdateEnabled()
757 ) {
758 $upgrade = true;
759 } elseif ( $this->repo->isJsonMetadataEnabled()
760 && $this->repo->isMetadataReserializeEnabled()
761 ) {
762 if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
763 $reserialize = true;
764 } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
765 $this->metadataSerializationFormat !== self::MDS_JSON ) {
766 $reserialize = true;
767 }
768 }
769 }
770 }
771
772 if ( $upgrade || $reserialize ) {
773 $this->upgrading = true;
774 // Defer updates unless in auto-commit CLI mode
775 DeferredUpdates::addCallableUpdate( function () use ( $upgrade ) {
776 $this->upgrading = false; // avoid duplicate updates
777 try {
778 if ( $upgrade ) {
779 $this->upgradeRow();
780 } else {
781 $this->reserializeMetadata();
782 }
783 } catch ( LocalFileLockError $e ) {
784 // let the other process handle it (or do it next time)
785 }
786 } );
787 }
788 }
789
793 public function getUpgraded() {
794 return $this->upgraded;
795 }
796
801 public function upgradeRow() {
802 $dbw = $this->repo->getPrimaryDB();
803
804 // Make a DB query condition that will fail to match the image row if the
805 // image was reuploaded while the upgrade was in process.
806 $freshnessCondition = [ 'img_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ];
807
808 $this->loadFromFile();
809
810 # Don't destroy file info of missing files
811 if ( !$this->fileExists ) {
812 wfDebug( __METHOD__ . ": file does not exist, aborting" );
813
814 return;
815 }
816
817 [ $major, $minor ] = self::splitMime( $this->mime );
818
819 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
820
821 $dbw->update( 'image',
822 [
823 'img_size' => $this->size,
824 'img_width' => $this->width,
825 'img_height' => $this->height,
826 'img_bits' => $this->bits,
827 'img_media_type' => $this->media_type,
828 'img_major_mime' => $major,
829 'img_minor_mime' => $minor,
830 'img_metadata' => $this->getMetadataForDb( $dbw ),
831 'img_sha1' => $this->sha1,
832 ],
833 array_merge(
834 [ 'img_name' => $this->getName() ],
835 $freshnessCondition
836 ),
837 __METHOD__
838 );
839
840 $this->invalidateCache();
841
842 $this->upgraded = true; // avoid rework/retries
843 }
844
849 protected function reserializeMetadata() {
850 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
851 return;
852 }
853 $dbw = $this->repo->getPrimaryDB();
854 $dbw->update(
855 'image',
856 [ 'img_metadata' => $this->getMetadataForDb( $dbw ) ],
857 [
858 'img_name' => $this->name,
859 'img_timestamp' => $dbw->timestamp( $this->timestamp ),
860 ],
861 __METHOD__
862 );
863 $this->upgraded = true;
864 }
865
877 protected function setProps( $info ) {
878 $this->dataLoaded = true;
879 $fields = $this->getCacheFields( '' );
880 $fields[] = 'fileExists';
881
882 foreach ( $fields as $field ) {
883 if ( isset( $info[$field] ) ) {
884 $this->$field = $info[$field];
885 }
886 }
887
888 // Only our own cache sets these properties, so they both should be present.
889 if ( isset( $info['user'] ) &&
890 isset( $info['user_text'] ) &&
891 $info['user_text'] !== ''
892 ) {
893 $this->user = new UserIdentityValue( $info['user'], $info['user_text'] );
894 }
895
896 // Fix up mime fields
897 if ( isset( $info['major_mime'] ) ) {
898 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
899 } elseif ( isset( $info['mime'] ) ) {
900 $this->mime = $info['mime'];
901 [ $this->major_mime, $this->minor_mime ] = self::splitMime( $this->mime );
902 }
903
904 if ( isset( $info['metadata'] ) ) {
905 if ( is_string( $info['metadata'] ) ) {
906 $this->loadMetadataFromString( $info['metadata'] );
907 } elseif ( is_array( $info['metadata'] ) ) {
908 $this->metadataArray = $info['metadata'];
909 if ( isset( $info['metadataBlobs'] ) ) {
910 $this->metadataBlobs = $info['metadataBlobs'];
911 $this->unloadedMetadataBlobs = array_diff_key(
912 $this->metadataBlobs,
913 $this->metadataArray
914 );
915 } else {
916 $this->metadataBlobs = [];
917 $this->unloadedMetadataBlobs = [];
918 }
919 } else {
920 $logger = LoggerFactory::getInstance( 'LocalFile' );
921 $logger->warning( __METHOD__ . ' given invalid metadata of type ' .
922 gettype( $info['metadata'] ) );
923 $this->metadataArray = [];
924 }
925 $this->extraDataLoaded = true;
926 }
927 }
928
944 public function isMissing() {
945 if ( $this->missing === null ) {
946 $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
947 $this->missing = !$fileExists;
948 }
949
950 return $this->missing;
951 }
952
960 public function getWidth( $page = 1 ) {
961 $page = (int)$page;
962 if ( $page < 1 ) {
963 $page = 1;
964 }
965
966 $this->load();
967
968 if ( $this->isMultipage() ) {
969 $handler = $this->getHandler();
970 if ( !$handler ) {
971 return 0;
972 }
973 $dim = $handler->getPageDimensions( $this, $page );
974 if ( $dim ) {
975 return $dim['width'];
976 } else {
977 // For non-paged media, the false goes through an
978 // intval, turning failure into 0, so do same here.
979 return 0;
980 }
981 } else {
982 return $this->width;
983 }
984 }
985
993 public function getHeight( $page = 1 ) {
994 $page = (int)$page;
995 if ( $page < 1 ) {
996 $page = 1;
997 }
998
999 $this->load();
1000
1001 if ( $this->isMultipage() ) {
1002 $handler = $this->getHandler();
1003 if ( !$handler ) {
1004 return 0;
1005 }
1006 $dim = $handler->getPageDimensions( $this, $page );
1007 if ( $dim ) {
1008 return $dim['height'];
1009 } else {
1010 // For non-paged media, the false goes through an
1011 // intval, turning failure into 0, so do same here.
1012 return 0;
1013 }
1014 } else {
1015 return $this->height;
1016 }
1017 }
1018
1026 public function getDescriptionShortUrl() {
1027 if ( !$this->title ) {
1028 return null; // Avoid hard failure when the file does not exist. T221812
1029 }
1030
1031 $pageId = $this->title->getArticleID();
1032
1033 if ( $pageId ) {
1034 $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
1035 if ( $url !== false ) {
1036 return $url;
1037 }
1038 }
1039 return null;
1040 }
1041
1048 public function getMetadata() {
1049 $data = $this->getMetadataArray();
1050 if ( !$data ) {
1051 return '';
1052 } elseif ( array_keys( $data ) === [ '_error' ] ) {
1053 // Legacy error encoding
1054 return $data['_error'];
1055 } else {
1056 return serialize( $this->getMetadataArray() );
1057 }
1058 }
1059
1066 public function getMetadataArray(): array {
1067 $this->load( self::LOAD_ALL );
1068 if ( $this->unloadedMetadataBlobs ) {
1069 return $this->getMetadataItems(
1070 array_unique( array_merge(
1071 array_keys( $this->metadataArray ),
1072 array_keys( $this->unloadedMetadataBlobs )
1073 ) )
1074 );
1075 }
1076 return $this->metadataArray;
1077 }
1078
1079 public function getMetadataItems( array $itemNames ): array {
1080 $this->load( self::LOAD_ALL );
1081 $result = [];
1082 $addresses = [];
1083 foreach ( $itemNames as $itemName ) {
1084 if ( array_key_exists( $itemName, $this->metadataArray ) ) {
1085 $result[$itemName] = $this->metadataArray[$itemName];
1086 } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
1087 $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
1088 }
1089 }
1090
1091 if ( $addresses ) {
1092 $resultFromBlob = $this->metadataStorageHelper->getMetadataFromBlobStore( $addresses );
1093 foreach ( $addresses as $itemName => $address ) {
1094 unset( $this->unloadedMetadataBlobs[$itemName] );
1095 $value = $resultFromBlob[$itemName] ?? null;
1096 if ( $value !== null ) {
1097 $result[$itemName] = $value;
1098 $this->metadataArray[$itemName] = $value;
1099 }
1100 }
1101 }
1102 return $result;
1103 }
1104
1116 public function getMetadataForDb( IDatabase $db ) {
1117 $this->load( self::LOAD_ALL );
1118 if ( !$this->metadataArray && !$this->metadataBlobs ) {
1119 $s = '';
1120 } elseif ( $this->repo->isJsonMetadataEnabled() ) {
1121 $s = $this->getJsonMetadata();
1122 } else {
1123 $s = serialize( $this->getMetadataArray() );
1124 }
1125 if ( !is_string( $s ) ) {
1126 throw new MWException( 'Could not serialize image metadata value for DB' );
1127 }
1128 return $db->encodeBlob( $s );
1129 }
1130
1137 private function getJsonMetadata() {
1138 // Directly store data that is not already in BlobStore
1139 $envelope = [
1140 'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
1141 ];
1142
1143 // Also store the blob addresses
1144 if ( $this->metadataBlobs ) {
1145 $envelope['blobs'] = $this->metadataBlobs;
1146 }
1147
1148 [ $s, $blobAddresses ] = $this->metadataStorageHelper->getJsonMetadata( $this, $envelope );
1149
1150 // Repeated calls to this function should not keep inserting more blobs
1151 $this->metadataBlobs += $blobAddresses;
1152
1153 return $s;
1154 }
1155
1162 private function isMetadataOversize() {
1163 if ( !$this->repo->isSplitMetadataEnabled() ) {
1164 return false;
1165 }
1166 $threshold = $this->repo->getSplitMetadataThreshold();
1167 $directItems = array_diff_key( $this->metadataArray, $this->metadataBlobs );
1168 foreach ( $directItems as $value ) {
1169 if ( strlen( $this->metadataStorageHelper->jsonEncode( $value ) ) > $threshold ) {
1170 return true;
1171 }
1172 }
1173 return false;
1174 }
1175
1184 protected function loadMetadataFromDbFieldValue( IDatabase $db, $metadataBlob ) {
1185 $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
1186 }
1187
1195 protected function loadMetadataFromString( $metadataString ) {
1196 $this->extraDataLoaded = true;
1197 $this->metadataArray = [];
1198 $this->metadataBlobs = [];
1199 $this->unloadedMetadataBlobs = [];
1200 $metadataString = (string)$metadataString;
1201 if ( $metadataString === '' ) {
1202 $this->metadataSerializationFormat = self::MDS_EMPTY;
1203 return;
1204 }
1205 if ( $metadataString[0] === '{' ) {
1206 $envelope = $this->metadataStorageHelper->jsonDecode( $metadataString );
1207 if ( !$envelope ) {
1208 // Legacy error encoding
1209 $this->metadataArray = [ '_error' => $metadataString ];
1210 $this->metadataSerializationFormat = self::MDS_LEGACY;
1211 } else {
1212 $this->metadataSerializationFormat = self::MDS_JSON;
1213 if ( isset( $envelope['data'] ) ) {
1214 $this->metadataArray = $envelope['data'];
1215 }
1216 if ( isset( $envelope['blobs'] ) ) {
1217 $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope['blobs'];
1218 }
1219 }
1220 } else {
1221 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1222 $data = @unserialize( $metadataString );
1223 if ( !is_array( $data ) ) {
1224 // Legacy error encoding
1225 $data = [ '_error' => $metadataString ];
1226 $this->metadataSerializationFormat = self::MDS_LEGACY;
1227 } else {
1228 $this->metadataSerializationFormat = self::MDS_PHP;
1229 }
1230 $this->metadataArray = $data;
1231 }
1232 }
1233
1238 public function getBitDepth() {
1239 $this->load();
1240
1241 return (int)$this->bits;
1242 }
1243
1249 public function getSize() {
1250 $this->load();
1251
1252 return $this->size;
1253 }
1254
1260 public function getMimeType() {
1261 $this->load();
1262
1263 return $this->mime;
1264 }
1265
1272 public function getMediaType() {
1273 $this->load();
1274
1275 return $this->media_type;
1276 }
1277
1289 public function exists() {
1290 $this->load();
1291
1292 return $this->fileExists;
1293 }
1294
1311 protected function getThumbnails( $archiveName = false ) {
1312 if ( $archiveName ) {
1313 $dir = $this->getArchiveThumbPath( $archiveName );
1314 } else {
1315 $dir = $this->getThumbPath();
1316 }
1317
1318 $backend = $this->repo->getBackend();
1319 $files = [ $dir ];
1320 try {
1321 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1322 if ( $iterator !== null ) {
1323 foreach ( $iterator as $file ) {
1324 $files[] = $file;
1325 }
1326 }
1327 } catch ( FileBackendError $e ) {
1328 } // suppress (T56674)
1329
1330 return $files;
1331 }
1332
1336 private function purgeMetadataCache() {
1337 $this->invalidateCache();
1338 }
1339
1348 public function purgeCache( $options = [] ) {
1349 // Refresh metadata cache
1350 $this->maybeUpgradeRow();
1351 $this->purgeMetadataCache();
1352
1353 // Delete thumbnails
1354 $this->purgeThumbnails( $options );
1355
1356 // Purge CDN cache for this file
1357 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1358 $hcu->purgeUrls(
1359 $this->getUrl(),
1360 !empty( $options['forThumbRefresh'] )
1361 ? $hcu::PURGE_PRESEND // just a manual purge
1362 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1363 );
1364 }
1365
1371 public function purgeOldThumbnails( $archiveName ) {
1372 // Get a list of old thumbnails
1373 $thumbs = $this->getThumbnails( $archiveName );
1374
1375 // Delete thumbnails from storage, and prevent the directory itself from being purged
1376 $dir = array_shift( $thumbs );
1377 $this->purgeThumbList( $dir, $thumbs );
1378
1379 $urls = [];
1380 foreach ( $thumbs as $thumb ) {
1381 $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1382 }
1383
1384 // Purge any custom thumbnail caches
1385 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1386
1387 // Purge the CDN
1388 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1389 $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1390 }
1391
1398 public function purgeThumbnails( $options = [] ) {
1399 $thumbs = $this->getThumbnails();
1400
1401 // Delete thumbnails from storage, and prevent the directory itself from being purged
1402 $dir = array_shift( $thumbs );
1403 $this->purgeThumbList( $dir, $thumbs );
1404
1405 // Always purge all files from CDN regardless of handler filters
1406 $urls = [];
1407 foreach ( $thumbs as $thumb ) {
1408 $urls[] = $this->getThumbUrl( $thumb );
1409 }
1410
1411 // Give the media handler a chance to filter the file purge list
1412 if ( !empty( $options['forThumbRefresh'] ) ) {
1413 $handler = $this->getHandler();
1414 if ( $handler ) {
1415 $handler->filterThumbnailPurgeList( $thumbs, $options );
1416 }
1417 }
1418
1419 // Purge any custom thumbnail caches
1420 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1421
1422 // Purge the CDN
1423 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1424 $hcu->purgeUrls(
1425 $urls,
1426 !empty( $options['forThumbRefresh'] )
1427 ? $hcu::PURGE_PRESEND // just a manual purge
1428 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1429 );
1430 }
1431
1438 public function prerenderThumbnails() {
1439 $uploadThumbnailRenderMap = MediaWikiServices::getInstance()
1440 ->getMainConfig()->get( MainConfigNames::UploadThumbnailRenderMap );
1441
1442 $jobs = [];
1443
1444 $sizes = $uploadThumbnailRenderMap;
1445 rsort( $sizes );
1446
1447 foreach ( $sizes as $size ) {
1448 if ( $this->isMultipage() ) {
1449 // (T309114) Only trigger render jobs up to MAX_PAGE_RENDER_JOBS to avoid
1450 // a flood of jobs for huge files.
1451 $pageLimit = min( $this->pageCount(), self::MAX_PAGE_RENDER_JOBS );
1452
1453 for ( $page = 1; $page <= $pageLimit; $page++ ) {
1454 $jobs[] = new ThumbnailRenderJob(
1455 $this->getTitle(),
1456 [ 'transformParams' => [
1457 'width' => $size,
1458 'page' => $page,
1459 ] ]
1460 );
1461 }
1462 } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1463 $jobs[] = new ThumbnailRenderJob(
1464 $this->getTitle(),
1465 [ 'transformParams' => [ 'width' => $size ] ]
1466 );
1467 }
1468 }
1469
1470 if ( $jobs ) {
1471 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
1472 }
1473 }
1474
1481 protected function purgeThumbList( $dir, $files ) {
1482 $fileListDebug = strtr(
1483 var_export( $files, true ),
1484 [ "\n" => '' ]
1485 );
1486 wfDebug( __METHOD__ . ": $fileListDebug" );
1487
1488 if ( $this->repo->supportsSha1URLs() ) {
1489 $reference = $this->getSha1();
1490 } else {
1491 $reference = $this->getName();
1492 }
1493
1494 $purgeList = [];
1495 foreach ( $files as $file ) {
1496 # Check that the reference (filename or sha1) is part of the thumb name
1497 # This is a basic check to avoid erasing unrelated directories
1498 if ( str_contains( $file, $reference )
1499 || str_contains( $file, "-thumbnail" ) // "short" thumb name
1500 ) {
1501 $purgeList[] = "{$dir}/{$file}";
1502 }
1503 }
1504
1505 # Delete the thumbnails
1506 $this->repo->quickPurgeBatch( $purgeList );
1507 # Clear out the thumbnail directory if empty
1508 $this->repo->quickCleanDir( $dir );
1509 }
1510
1522 public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1523 if ( !$this->exists() ) {
1524 return []; // Avoid hard failure when the file does not exist. T221812
1525 }
1526
1527 $dbr = $this->repo->getReplicaDB();
1528 $oldFileQuery = OldLocalFile::getQueryInfo();
1529
1530 $tables = $oldFileQuery['tables'];
1531 $fields = $oldFileQuery['fields'];
1532 $join_conds = $oldFileQuery['joins'];
1533 $conds = $opts = [];
1534 $eq = $inc ? '=' : '';
1535 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1536
1537 if ( $start ) {
1538 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1539 }
1540
1541 if ( $end ) {
1542 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1543 }
1544
1545 if ( $limit ) {
1546 $opts['LIMIT'] = $limit;
1547 }
1548
1549 // Search backwards for time > x queries
1550 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1551 $opts['ORDER BY'] = "oi_timestamp $order";
1552 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1553
1554 $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1555 $conds, $opts, $join_conds );
1556
1557 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1558 $r = [];
1559
1560 foreach ( $res as $row ) {
1561 $r[] = $this->repo->newFileFromRow( $row );
1562 }
1563
1564 if ( $order == 'ASC' ) {
1565 $r = array_reverse( $r ); // make sure it ends up descending
1566 }
1567
1568 return $r;
1569 }
1570
1581 public function nextHistoryLine() {
1582 if ( !$this->exists() ) {
1583 return false; // Avoid hard failure when the file does not exist. T221812
1584 }
1585
1586 # Polymorphic function name to distinguish foreign and local fetches
1587 $fname = static::class . '::' . __FUNCTION__;
1588
1589 $dbr = $this->repo->getReplicaDB();
1590
1591 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1592 $fileQuery = self::getQueryInfo();
1593 $this->historyRes = $dbr->select( $fileQuery['tables'],
1594 $fileQuery['fields'] + [
1595 'oi_archive_name' => $dbr->addQuotes( '' ),
1596 'oi_deleted' => 0,
1597 ],
1598 [ 'img_name' => $this->title->getDBkey() ],
1599 $fname,
1600 [],
1601 $fileQuery['joins']
1602 );
1603
1604 if ( $this->historyRes->numRows() == 0 ) {
1605 $this->historyRes = null;
1606
1607 return false;
1608 }
1609 } elseif ( $this->historyLine == 1 ) {
1610 $fileQuery = OldLocalFile::getQueryInfo();
1611 $this->historyRes = $dbr->select(
1612 $fileQuery['tables'],
1613 $fileQuery['fields'],
1614 [ 'oi_name' => $this->title->getDBkey() ],
1615 $fname,
1616 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1617 $fileQuery['joins']
1618 );
1619 }
1620 $this->historyLine++;
1621
1622 return $this->historyRes->fetchObject();
1623 }
1624
1629 public function resetHistory() {
1630 $this->historyLine = 0;
1631
1632 if ( $this->historyRes !== null ) {
1633 $this->historyRes = null;
1634 }
1635 }
1636
1670 public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1671 $timestamp = false, Authority $uploader = null, $tags = [],
1672 $createNullRevision = true, $revert = false
1673 ) {
1674 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1675 return $this->readOnlyFatalStatus();
1676 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1677 // Check this in advance to avoid writing to FileBackend and the file tables,
1678 // only to fail on insert the revision due to the text store being unavailable.
1679 return $this->readOnlyFatalStatus();
1680 }
1681
1682 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1683 if ( !$props ) {
1684 if ( FileRepo::isVirtualUrl( $srcPath )
1685 || FileBackend::isStoragePath( $srcPath )
1686 ) {
1687 $props = $this->repo->getFileProps( $srcPath );
1688 } else {
1689 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1690 $props = $mwProps->getPropsFromPath( $srcPath, true );
1691 }
1692 }
1693
1694 $options = [];
1695 $handler = MediaHandler::getHandler( $props['mime'] );
1696 if ( $handler ) {
1697 if ( is_string( $props['metadata'] ) ) {
1698 // This supports callers directly fabricating a metadata
1699 // property using serialize(). Normally the metadata property
1700 // comes from MWFileProps, in which case it won't be a string.
1701 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1702 $metadata = @unserialize( $props['metadata'] );
1703 } else {
1704 $metadata = $props['metadata'];
1705 }
1706
1707 if ( is_array( $metadata ) ) {
1708 $options['headers'] = $handler->getContentHeaders( $metadata );
1709 }
1710 } else {
1711 $options['headers'] = [];
1712 }
1713
1714 // Trim spaces on user supplied text
1715 $comment = trim( $comment );
1716
1717 $status = $this->publish( $src, $flags, $options );
1718
1719 if ( $status->successCount >= 2 ) {
1720 // There will be a copy+(one of move,copy,store).
1721 // The first succeeding does not commit us to updating the DB
1722 // since it simply copied the current version to a timestamped file name.
1723 // It is only *preferable* to avoid leaving such files orphaned.
1724 // Once the second operation goes through, then the current version was
1725 // updated and we must therefore update the DB too.
1726 $oldver = $status->value;
1727
1728 $uploadStatus = $this->recordUpload3(
1729 $oldver,
1730 $comment,
1731 $pageText,
1732 $uploader ?? RequestContext::getMain()->getAuthority(),
1733 $props,
1734 $timestamp,
1735 $tags,
1736 $createNullRevision,
1737 $revert
1738 );
1739 if ( !$uploadStatus->isOK() ) {
1740 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1741 // update filenotfound error with more specific path
1742 $status->fatal( 'filenotfound', $srcPath );
1743 } else {
1744 $status->merge( $uploadStatus );
1745 }
1746 }
1747 }
1748
1749 return $status;
1750 }
1751
1768 public function recordUpload3(
1769 string $oldver,
1770 string $comment,
1771 string $pageText,
1772 Authority $performer,
1773 $props = false,
1774 $timestamp = false,
1775 $tags = [],
1776 bool $createNullRevision = true,
1777 bool $revert = false
1778 ): Status {
1779 $dbw = $this->repo->getPrimaryDB();
1780
1781 # Imports or such might force a certain timestamp; otherwise we generate
1782 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1783 if ( $timestamp === false ) {
1784 $timestamp = $dbw->timestamp();
1785 $allowTimeKludge = true;
1786 } else {
1787 $allowTimeKludge = false;
1788 }
1789
1790 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1791 $props['description'] = $comment;
1792 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1793 $this->setProps( $props );
1794 $mimeAnalyzer = MediaWikiServices::getInstance()->getMimeAnalyzer();
1795 if ( !$mimeAnalyzer->isValidMajorMimeType( $this->major_mime ) ) {
1796 $this->major_mime = 'unknown';
1797 }
1798
1799 # Fail now if the file isn't there
1800 if ( !$this->fileExists ) {
1801 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1802
1803 return Status::newFatal( 'filenotfound', $this->getRel() );
1804 }
1805
1806 $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1807
1808 $dbw->startAtomic( __METHOD__ );
1809
1810 $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1811 $this->user = $performer->getUser();
1812
1813 # Test to see if the row exists using INSERT IGNORE
1814 # This avoids race conditions by locking the row until the commit, and also
1815 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1816 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1817 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1818 $actorFields = [ 'img_actor' => $actorId ];
1819 $dbw->insert( 'image',
1820 [
1821 'img_name' => $this->getName(),
1822 'img_size' => $this->size,
1823 'img_width' => intval( $this->width ),
1824 'img_height' => intval( $this->height ),
1825 'img_bits' => $this->bits,
1826 'img_media_type' => $this->media_type,
1827 'img_major_mime' => $this->major_mime,
1828 'img_minor_mime' => $this->minor_mime,
1829 'img_timestamp' => $dbw->timestamp( $timestamp ),
1830 'img_metadata' => $this->getMetadataForDb( $dbw ),
1831 'img_sha1' => $this->sha1
1832 ] + $commentFields + $actorFields,
1833 __METHOD__,
1834 [ 'IGNORE' ]
1835 );
1836 $reupload = ( $dbw->affectedRows() == 0 );
1837
1838 if ( $reupload ) {
1839 $row = $dbw->selectRow(
1840 'image',
1841 [ 'img_timestamp', 'img_sha1' ],
1842 [ 'img_name' => $this->getName() ],
1843 __METHOD__,
1844 [ 'LOCK IN SHARE MODE' ]
1845 );
1846
1847 if ( $row && $row->img_sha1 === $this->sha1 ) {
1848 $dbw->endAtomic( __METHOD__ );
1849 wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1850 $title = Title::newFromText( $this->getName(), NS_FILE );
1851 return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1852 }
1853
1854 if ( $allowTimeKludge ) {
1855 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1856 $lUnixtime = $row ? (int)wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1857 # Avoid a timestamp that is not newer than the last version
1858 # TODO: the image/oldimage tables should be like page/revision with an ID field
1859 if ( $lUnixtime && (int)wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1860 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1861 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1862 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1863 }
1864 }
1865
1866 $tables = [ 'image' ];
1867 $fields = [
1868 'oi_name' => 'img_name',
1869 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1870 'oi_size' => 'img_size',
1871 'oi_width' => 'img_width',
1872 'oi_height' => 'img_height',
1873 'oi_bits' => 'img_bits',
1874 'oi_description_id' => 'img_description_id',
1875 'oi_timestamp' => 'img_timestamp',
1876 'oi_metadata' => 'img_metadata',
1877 'oi_media_type' => 'img_media_type',
1878 'oi_major_mime' => 'img_major_mime',
1879 'oi_minor_mime' => 'img_minor_mime',
1880 'oi_sha1' => 'img_sha1',
1881 'oi_actor' => 'img_actor',
1882 ];
1883 $joins = [];
1884
1885 # (T36993) Note: $oldver can be empty here, if the previous
1886 # version of the file was broken. Allow registration of the new
1887 # version to continue anyway, because that's better than having
1888 # an image that's not fixable by user operations.
1889 # Collision, this is an update of a file
1890 # Insert previous contents into oldimage
1891 $dbw->insertSelect( 'oldimage', $tables, $fields,
1892 [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1893
1894 # Update the current image row
1895 $dbw->update( 'image',
1896 [
1897 'img_size' => $this->size,
1898 'img_width' => intval( $this->width ),
1899 'img_height' => intval( $this->height ),
1900 'img_bits' => $this->bits,
1901 'img_media_type' => $this->media_type,
1902 'img_major_mime' => $this->major_mime,
1903 'img_minor_mime' => $this->minor_mime,
1904 'img_timestamp' => $dbw->timestamp( $timestamp ),
1905 'img_metadata' => $this->getMetadataForDb( $dbw ),
1906 'img_sha1' => $this->sha1
1907 ] + $commentFields + $actorFields,
1908 [ 'img_name' => $this->getName() ],
1909 __METHOD__
1910 );
1911 }
1912
1913 $descTitle = $this->getTitle();
1914 $descId = $descTitle->getArticleID();
1915 $wikiPage = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $descTitle );
1916 if ( !$wikiPage instanceof WikiFilePage ) {
1917 throw new MWException( 'Cannot instance WikiFilePage for ' . $this->getName()
1918 . ', got instance of ' . get_class( $wikiPage ) );
1919 }
1920 $wikiPage->setFile( $this );
1921
1922 // Determine log action. If reupload is done by reverting, use a special log_action.
1923 if ( $revert ) {
1924 $logAction = 'revert';
1925 } elseif ( $reupload ) {
1926 $logAction = 'overwrite';
1927 } else {
1928 $logAction = 'upload';
1929 }
1930 // Add the log entry...
1931 $logEntry = new ManualLogEntry( 'upload', $logAction );
1932 $logEntry->setTimestamp( $this->timestamp );
1933 $logEntry->setPerformer( $performer->getUser() );
1934 $logEntry->setComment( $comment );
1935 $logEntry->setTarget( $descTitle );
1936 // Allow people using the api to associate log entries with the upload.
1937 // Log has a timestamp, but sometimes different from upload timestamp.
1938 $logEntry->setParameters(
1939 [
1940 'img_sha1' => $this->sha1,
1941 'img_timestamp' => $timestamp,
1942 ]
1943 );
1944 // Note we keep $logId around since during new image
1945 // creation, page doesn't exist yet, so log_page = 0
1946 // but we want it to point to the page we're making,
1947 // so we later modify the log entry.
1948 // For a similar reason, we avoid making an RC entry
1949 // now and wait until the page exists.
1950 $logId = $logEntry->insert();
1951
1952 if ( $descTitle->exists() ) {
1953 if ( $createNullRevision ) {
1954 $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1955 // Use own context to get the action text in content language
1956 $formatter = LogFormatter::newFromEntry( $logEntry );
1957 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1958 $editSummary = $formatter->getPlainActionText();
1959 $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1960 $nullRevRecord = $revStore->newNullRevision(
1961 $dbw,
1962 $descTitle,
1963 $summary,
1964 false,
1965 $performer->getUser()
1966 );
1967
1968 if ( $nullRevRecord ) {
1969 $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1970
1971 $this->getHookRunner()->onRevisionFromEditComplete(
1972 $wikiPage,
1973 $inserted,
1974 $inserted->getParentId(),
1975 $performer->getUser(),
1976 $tags
1977 );
1978
1979 $wikiPage->updateRevisionOn( $dbw, $inserted );
1980 // Associate null revision id
1981 $logEntry->setAssociatedRevId( $inserted->getId() );
1982 }
1983 }
1984
1985 $newPageContent = null;
1986 } else {
1987 // Make the description page and RC log entry post-commit
1988 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1989 }
1990
1991 // NOTE: Even after ending this atomic section, we are probably still in the implicit
1992 // transaction started by any prior master query in the request. We cannot yet safely
1993 // schedule jobs, see T263301.
1994 $dbw->endAtomic( __METHOD__ );
1995 $fname = __METHOD__;
1996
1997 # Do some cache purges after final commit so that:
1998 # a) Changes are more likely to be seen post-purge
1999 # b) They won't cause rollback of the log publish/update above
2000 $purgeUpdate = new AutoCommitUpdate(
2001 $dbw,
2002 __METHOD__,
2003 function () use (
2004 $reupload, $wikiPage, $newPageContent, $comment, $performer,
2005 $logEntry, $logId, $descId, $tags, $fname
2006 ) {
2007 # Update memcache after the commit
2008 $this->invalidateCache();
2009
2010 $updateLogPage = false;
2011 if ( $newPageContent ) {
2012 # New file page; create the description page.
2013 # There's already a log entry, so don't make a second RC entry
2014 # CDN and file cache for the description page are purged by doUserEditContent.
2015 $status = $wikiPage->doUserEditContent(
2016 $newPageContent,
2017 $performer,
2018 $comment,
2020 );
2021
2022 $revRecord = $status->getNewRevision();
2023 if ( $revRecord ) {
2024 // Associate new page revision id
2025 $logEntry->setAssociatedRevId( $revRecord->getId() );
2026
2027 // This relies on the resetArticleID() call in WikiPage::insertOn(),
2028 // which is triggered on $descTitle by doUserEditContent() above.
2029 $updateLogPage = $revRecord->getPageId();
2030 }
2031 } else {
2032 # Existing file page: invalidate description page cache
2033 $title = $wikiPage->getTitle();
2034 $title->invalidateCache();
2035 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2036 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2037 # Allow the new file version to be patrolled from the page footer
2039 }
2040
2041 # Update associated rev id. This should be done by $logEntry->insert() earlier,
2042 # but setAssociatedRevId() wasn't called at that point yet...
2043 $logParams = $logEntry->getParameters();
2044 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
2045 $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
2046 if ( $updateLogPage ) {
2047 # Also log page, in case where we just created it above
2048 $update['log_page'] = $updateLogPage;
2049 }
2050 $this->getRepo()->getPrimaryDB()->update(
2051 'logging',
2052 $update,
2053 [ 'log_id' => $logId ],
2054 $fname
2055 );
2056 $this->getRepo()->getPrimaryDB()->insert(
2057 'log_search',
2058 [
2059 'ls_field' => 'associated_rev_id',
2060 'ls_value' => (string)$logEntry->getAssociatedRevId(),
2061 'ls_log_id' => $logId,
2062 ],
2063 $fname
2064 );
2065
2066 # Add change tags, if any
2067 if ( $tags ) {
2068 $logEntry->addTags( $tags );
2069 }
2070
2071 # Uploads can be patrolled
2072 $logEntry->setIsPatrollable( true );
2073
2074 # Now that the log entry is up-to-date, make an RC entry.
2075 $logEntry->publish( $logId );
2076
2077 # Run hook for other updates (typically more cache purging)
2078 $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2079
2080 if ( $reupload ) {
2081 # Delete old thumbnails
2082 $this->purgeThumbnails();
2083 # Remove the old file from the CDN cache
2084 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2085 $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2086 } else {
2087 # Update backlink pages pointing to this title if created
2088 $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2089 LinksUpdate::queueRecursiveJobsForTable(
2090 $this->getTitle(),
2091 'imagelinks',
2092 'upload-image',
2093 $performer->getUser()->getName(),
2094 $blcFactory->getBacklinkCache( $this->getTitle() )
2095 );
2096 }
2097
2098 $this->prerenderThumbnails();
2099 }
2100 );
2101
2102 # Invalidate cache for all pages using this file
2103 $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
2104 $this->getTitle(),
2105 'imagelinks',
2106 [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2107 );
2108
2109 // NOTE: We are probably still in the implicit transaction started by DBO_TRX. We should
2110 // only schedule jobs after that transaction was committed, so a job queue failure
2111 // doesn't cause the upload to fail (T263301). Also, we should generally not schedule any
2112 // Jobs or the DeferredUpdates that assume the update is complete until after the
2113 // transaction has been committed and we are sure that the upload was indeed successful.
2114 $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2115 DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2116
2117 if ( !$reupload ) {
2118 // This is a new file, so update the image count
2119 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2120 }
2121
2122 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $cacheUpdateJob );
2123 }, __METHOD__ );
2124
2125 return Status::newGood();
2126 }
2127
2144 public function publish( $src, $flags = 0, array $options = [] ) {
2145 return $this->publishTo( $src, $this->getRel(), $flags, $options );
2146 }
2147
2164 protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2165 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
2166
2167 $repo = $this->getRepo();
2168 if ( $repo->getReadOnlyReason() !== false ) {
2169 return $this->readOnlyFatalStatus();
2170 }
2171
2172 $status = $this->acquireFileLock();
2173 if ( !$status->isOK() ) {
2174 return $status;
2175 }
2176
2177 if ( $this->isOld() ) {
2178 $archiveRel = $dstRel;
2179 $archiveName = basename( $archiveRel );
2180 } else {
2181 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
2182 $archiveRel = $this->getArchiveRel( $archiveName );
2183 }
2184
2185 if ( $repo->hasSha1Storage() ) {
2186 $sha1 = FileRepo::isVirtualUrl( $srcPath )
2187 ? $repo->getFileSha1( $srcPath )
2188 : FSFile::getSha1Base36FromPath( $srcPath );
2190 $wrapperBackend = $repo->getBackend();
2191 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2192 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2193 $status = $repo->quickImport( $src, $dst );
2194 if ( $flags & File::DELETE_SOURCE ) {
2195 unlink( $srcPath );
2196 }
2197
2198 if ( $this->exists() ) {
2199 $status->value = $archiveName;
2200 }
2201 } else {
2202 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2203 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2204
2205 if ( $status->value == 'new' ) {
2206 $status->value = '';
2207 } else {
2208 $status->value = $archiveName;
2209 }
2210 }
2211
2212 $this->releaseFileLock();
2213 return $status;
2214 }
2215
2234 public function move( $target ) {
2235 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2236 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2237 return $this->readOnlyFatalStatus();
2238 }
2239
2240 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2241 $batch = new LocalFileMoveBatch( $this, $target );
2242
2243 $status = $batch->addCurrent();
2244 if ( !$status->isOK() ) {
2245 return $status;
2246 }
2247 $archiveNames = $batch->addOlds();
2248 $status = $batch->execute();
2249
2250 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2251
2252 // Purge the source and target files outside the transaction...
2253 $oldTitleFile = $localRepo->newFile( $this->title );
2254 $newTitleFile = $localRepo->newFile( $target );
2255 DeferredUpdates::addUpdate(
2256 new AutoCommitUpdate(
2257 $this->getRepo()->getPrimaryDB(),
2258 __METHOD__,
2259 static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2260 $oldTitleFile->purgeEverything();
2261 foreach ( $archiveNames as $archiveName ) {
2263 '@phan-var OldLocalFile $oldTitleFile';
2264 $oldTitleFile->purgeOldThumbnails( $archiveName );
2265 }
2266 $newTitleFile->purgeEverything();
2267 }
2268 ),
2269 DeferredUpdates::PRESEND
2270 );
2271
2272 if ( $status->isOK() ) {
2273 // Now switch the object
2274 $this->title = $target;
2275 // Force regeneration of the name and hashpath
2276 $this->name = null;
2277 $this->hashPath = null;
2278 }
2279
2280 return $status;
2281 }
2282
2299 public function deleteFile( $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->addCurrent();
2307 // Get old version relative paths
2308 $archiveNames = $batch->addOlds();
2309 $status = $batch->execute();
2310
2311 if ( $status->isOK() ) {
2312 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2313 }
2314
2315 // To avoid slow purges in the transaction, move them outside...
2316 DeferredUpdates::addUpdate(
2317 new AutoCommitUpdate(
2318 $this->getRepo()->getPrimaryDB(),
2319 __METHOD__,
2320 function () use ( $archiveNames ) {
2321 $this->purgeEverything();
2322 foreach ( $archiveNames as $archiveName ) {
2323 $this->purgeOldThumbnails( $archiveName );
2324 }
2325 }
2326 ),
2327 DeferredUpdates::PRESEND
2328 );
2329
2330 // Purge the CDN
2331 $purgeUrls = [];
2332 foreach ( $archiveNames as $archiveName ) {
2333 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2334 }
2335
2336 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2337 $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2338
2339 return $status;
2340 }
2341
2360 public function deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress = false ) {
2361 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2362 return $this->readOnlyFatalStatus();
2363 }
2364
2365 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2366
2367 $batch->addOld( $archiveName );
2368 $status = $batch->execute();
2369
2370 $this->purgeOldThumbnails( $archiveName );
2371 if ( $status->isOK() ) {
2372 $this->purgeDescription();
2373 }
2374
2375 $url = $this->getArchiveUrl( $archiveName );
2376 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2377 $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2378
2379 return $status;
2380 }
2381
2394 public function restore( $versions = [], $unsuppress = false ) {
2395 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2396 return $this->readOnlyFatalStatus();
2397 }
2398
2399 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2400
2401 if ( !$versions ) {
2402 $batch->addAll();
2403 } else {
2404 $batch->addIds( $versions );
2405 }
2406 $status = $batch->execute();
2407 if ( $status->isGood() ) {
2408 $cleanupStatus = $batch->cleanup();
2409 $cleanupStatus->successCount = 0;
2410 $cleanupStatus->failCount = 0;
2411 $status->merge( $cleanupStatus );
2412 }
2413
2414 return $status;
2415 }
2416
2427 public function getDescriptionUrl() {
2428 // Avoid hard failure when the file does not exist. T221812
2429 return $this->title ? $this->title->getLocalURL() : false;
2430 }
2431
2441 public function getDescriptionText( Language $lang = null ) {
2442 if ( !$this->title ) {
2443 return false; // Avoid hard failure when the file does not exist. T221812
2444 }
2445
2446 $services = MediaWikiServices::getInstance();
2447 $page = $services->getPageStore()->getPageByReference( $this->getTitle() );
2448 if ( !$page ) {
2449 return false;
2450 }
2451
2452 if ( $lang ) {
2453 $parserOptions = ParserOptions::newFromUserAndLang(
2454 RequestContext::getMain()->getUser(),
2455 $lang
2456 );
2457 } else {
2458 $parserOptions = ParserOptions::newFromContext( RequestContext::getMain() );
2459 }
2460
2461 $parseStatus = $services->getParserOutputAccess()
2462 ->getParserOutput( $page, $parserOptions );
2463
2464 if ( !$parseStatus->isGood() ) {
2465 // Rendering failed.
2466 return false;
2467 }
2468 return $parseStatus->getValue()->getText();
2469 }
2470
2478 public function getUploader( int $audience = self::FOR_PUBLIC, Authority $performer = null ): ?UserIdentity {
2479 $this->load();
2480 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2481 return null;
2482 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2483 return null;
2484 } else {
2485 return $this->user;
2486 }
2487 }
2488
2495 public function getDescription( $audience = self::FOR_PUBLIC, Authority $performer = null ) {
2496 $this->load();
2497 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2498 return '';
2499 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2500 return '';
2501 } else {
2502 return $this->description;
2503 }
2504 }
2505
2510 public function getTimestamp() {
2511 $this->load();
2512
2513 return $this->timestamp;
2514 }
2515
2520 public function getDescriptionTouched() {
2521 if ( !$this->exists() ) {
2522 return false; // Avoid hard failure when the file does not exist. T221812
2523 }
2524
2525 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2526 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2527 // need to differentiate between null (uninitialized) and false (failed to load).
2528 if ( $this->descriptionTouched === null ) {
2529 $cond = [
2530 'page_namespace' => $this->title->getNamespace(),
2531 'page_title' => $this->title->getDBkey()
2532 ];
2533 $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2534 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2535 }
2536
2537 return $this->descriptionTouched;
2538 }
2539
2544 public function getSha1() {
2545 $this->load();
2546 return $this->sha1;
2547 }
2548
2552 public function isCacheable() {
2553 $this->load();
2554
2555 // If extra data (metadata) was not loaded then it must have been large
2556 return $this->extraDataLoaded
2557 && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2558 }
2559
2568 public function acquireFileLock( $timeout = 0 ) {
2569 return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2570 [ $this->getPath() ], LockManager::LOCK_EX, $timeout
2571 ) );
2572 }
2573
2580 public function releaseFileLock() {
2581 return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2582 [ $this->getPath() ], LockManager::LOCK_EX
2583 ) );
2584 }
2585
2596 public function lock() {
2597 if ( !$this->locked ) {
2598 $logger = LoggerFactory::getInstance( 'LocalFile' );
2599
2600 $dbw = $this->repo->getPrimaryDB();
2601 $makesTransaction = !$dbw->trxLevel();
2602 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2603 // T56736: use simple lock to handle when the file does not exist.
2604 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2605 // Also, that would cause contention on INSERT of similarly named rows.
2606 $status = $this->acquireFileLock( 10 ); // represents all versions of the file
2607 if ( !$status->isGood() ) {
2608 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2609 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2610
2611 throw new LocalFileLockError( $status );
2612 }
2613 // Release the lock *after* commit to avoid row-level contention.
2614 // Make sure it triggers on rollback() as well as commit() (T132921).
2615 $dbw->onTransactionResolution(
2616 function () use ( $logger ) {
2617 $status = $this->releaseFileLock();
2618 if ( !$status->isGood() ) {
2619 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2620 }
2621 },
2622 __METHOD__
2623 );
2624 // Callers might care if the SELECT snapshot is safely fresh
2625 $this->lockedOwnTrx = $makesTransaction;
2626 }
2627
2628 $this->locked++;
2629
2630 return $this->lockedOwnTrx;
2631 }
2632
2643 public function unlock() {
2644 if ( $this->locked ) {
2645 --$this->locked;
2646 if ( !$this->locked ) {
2647 $dbw = $this->repo->getPrimaryDB();
2648 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2649 $this->lockedOwnTrx = false;
2650 }
2651 }
2652 }
2653
2657 protected function readOnlyFatalStatus() {
2658 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2659 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2660 }
2661
2665 public function __destruct() {
2666 $this->unlock();
2667 }
2668}
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:1372
Deferrable Update for closure/callback updates that should use auto-commit mode.
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
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:286
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:68
string $url
The URL corresponding to one of the four basic zones.
Definition File.php:136
MediaHandler $handler
Definition File.php:133
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition File.php:2459
getName()
Return the name of this file.
Definition File.php:334
const DELETE_SOURCE
Definition File.php:85
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
Definition File.php:1921
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition File.php:2469
FileRepo LocalRepo ForeignAPIRepo false $repo
Some member variables can be lazy-initialised using __get().
Definition File.php:115
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition File.php:2156
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1540
string null $name
The name of a file from its title object.
Definition File.php:142
static newForBacklinks(PageReference $page, $table, $params=[])
Base class for language-specific code.
Definition Language.php:56
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:61
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.
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.
Definition LocalFile.php:97
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)
loadMetadataFromDbFieldValue(IDatabase $db, $metadataBlob)
Unserialize a metadata blob which came from the database and store it in $this.
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 IDatabase...
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition LocalFile.php:94
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.
getMetadataForDb(IDatabase $db)
Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.
int $height
Image height.
Definition LocalFile.php:88
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.
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:91
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:85
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:82
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.
Class the manages updates of *_link tables as well as similar extension-managed tables.
PSR-3 logger instance factory.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Represents a title within MediaWiki.
Definition Title.php:82
Value object representing a user's identity.
Helper for storage of metadata.
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new oldlocalfile object.
static newFatal( $message,... $parameters)
Factory function for fatal errors.
static newGood( $value=null)
Factory function for good results.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:46
Job for asynchronous rendering of thumbnails, e.g.
Special handling for representing file pages.
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.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:36
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.
Result wrapper for grabbing data queried from an IDatabase object.
$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
if(!isset( $args[0])) $lang