MediaWiki REL1_37
LocalFile.php
Go to the documentation of this file.
1<?php
36
63class LocalFile extends File {
64 private const VERSION = 13; // cache version
65
66 private const CACHE_FIELD_MAX_LEN = 1000;
67
69 private const MDS_EMPTY = 'empty';
70
72 private const MDS_LEGACY = 'legacy';
73
75 private const MDS_PHP = 'php';
76
78 private const MDS_JSON = 'json';
79
81 private const MAX_PAGE_RENDER_JOBS = 50;
82
84 protected $fileExists;
85
87 protected $width;
88
90 protected $height;
91
93 protected $bits;
94
96 protected $media_type;
97
99 protected $mime;
100
102 protected $size;
103
105 protected $metadataArray = [];
106
114
116 protected $metadataBlobs = [];
117
124 protected $unloadedMetadataBlobs = [];
125
127 protected $sha1;
128
130 protected $dataLoaded;
131
134
136 protected $deleted;
137
139 protected $repoClass = LocalRepo::class;
140
143
145 private $historyRes;
146
148 private $major_mime;
149
151 private $minor_mime;
152
154 private $timestamp;
155
157 private $user;
158
161
164
166 private $upgraded;
167
169 private $upgrading;
170
172 private $locked;
173
176
178 private $missing;
179
180 // @note: higher than IDBAccessObject constants
181 private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
182
183 private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
184
199 public static function newFromTitle( $title, $repo, $unused = null ) {
200 return new static( $title, $repo );
201 }
202
214 public static function newFromRow( $row, $repo ) {
215 $title = Title::makeTitle( NS_FILE, $row->img_name );
216 $file = new static( $title, $repo );
217 $file->loadFromRow( $row );
218
219 return $file;
220 }
221
233 public static function newFromKey( $sha1, $repo, $timestamp = false ) {
234 $dbr = $repo->getReplicaDB();
235
236 $conds = [ 'img_sha1' => $sha1 ];
237 if ( $timestamp ) {
238 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
239 }
240
241 $fileQuery = static::getQueryInfo();
242 $row = $dbr->selectRow(
243 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__, [], $fileQuery['joins']
244 );
245 if ( $row ) {
246 return static::newFromRow( $row, $repo );
247 } else {
248 return false;
249 }
250 }
251
270 public static function getQueryInfo( array $options = [] ) {
271 $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'img_description' );
272 $ret = [
273 'tables' => [
274 'image',
275 'image_actor' => 'actor'
276 ] + $commentQuery['tables'],
277 'fields' => [
278 'img_name',
279 'img_size',
280 'img_width',
281 'img_height',
282 'img_metadata',
283 'img_bits',
284 'img_media_type',
285 'img_major_mime',
286 'img_minor_mime',
287 'img_timestamp',
288 'img_sha1',
289 'img_actor',
290 'img_user' => 'image_actor.actor_user',
291 'img_user_text' => 'image_actor.actor_name',
292 ] + $commentQuery['fields'],
293 'joins' => [
294 'image_actor' => [ 'JOIN', 'actor_id=img_actor' ]
295 ] + $commentQuery['joins'],
296 ];
297
298 if ( in_array( 'omit-nonlazy', $options, true ) ) {
299 // Internal use only for getting only the lazy fields
300 $ret['fields'] = [];
301 }
302 if ( !in_array( 'omit-lazy', $options, true ) ) {
303 // Note: Keep this in sync with self::getLazyCacheFields() and
304 // self::loadExtraFromDB()
305 $ret['fields'][] = 'img_metadata';
306 }
307
308 return $ret;
309 }
310
318 public function __construct( $title, $repo ) {
319 parent::__construct( $title, $repo );
320
321 $this->historyLine = 0;
322 $this->historyRes = null;
323 $this->dataLoaded = false;
324 $this->extraDataLoaded = false;
325
326 $this->assertRepoDefined();
327 $this->assertTitleDefined();
328 }
329
333 public function getRepo() {
334 return $this->repo;
335 }
336
343 protected function getCacheKey() {
344 return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
345 }
346
353 return [ $this->getCacheKey() ];
354 }
355
359 private function loadFromCache() {
360 $this->dataLoaded = false;
361 $this->extraDataLoaded = false;
362
363 $key = $this->getCacheKey();
364 if ( !$key ) {
365 $this->loadFromDB( self::READ_NORMAL );
366
367 return;
368 }
369
370 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
371 $cachedValues = $cache->getWithSetCallback(
372 $key,
373 $cache::TTL_WEEK,
374 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
375 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
376
377 $this->loadFromDB( self::READ_NORMAL );
378
379 $fields = $this->getCacheFields( '' );
380 $cacheVal = [];
381 $cacheVal['fileExists'] = $this->fileExists;
382 if ( $this->fileExists ) {
383 foreach ( $fields as $field ) {
384 $cacheVal[$field] = $this->$field;
385 }
386 }
387 if ( $this->user ) {
388 $cacheVal['user'] = $this->user->getId();
389 $cacheVal['user_text'] = $this->user->getName();
390 }
391
392 // Don't cache metadata items stored as blobs, since they tend to be large
393 if ( $this->metadataBlobs ) {
394 $cacheVal['metadata'] = array_diff_key(
395 $this->metadataArray, $this->metadataBlobs );
396 // Save the blob addresses
397 $cacheVal['metadataBlobs'] = $this->metadataBlobs;
398 } else {
399 $cacheVal['metadata'] = $this->metadataArray;
400 }
401
402 // Strip off excessive entries from the subset of fields that can become large.
403 // If the cache value gets too large and might not fit in the cache,
404 // causing repeat database queries for each access to the file.
405 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
406 if ( isset( $cacheVal[$field] )
407 && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
408 ) {
409 unset( $cacheVal[$field] ); // don't let the value get too big
410 if ( $field === 'metadata' ) {
411 unset( $cacheVal['metadataBlobs'] );
412 }
413 }
414 }
415
416 if ( $this->fileExists ) {
417 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
418 } else {
419 $ttl = $cache::TTL_DAY;
420 }
421
422 return $cacheVal;
423 },
424 [ 'version' => self::VERSION ]
425 );
426
427 $this->fileExists = $cachedValues['fileExists'];
428 if ( $this->fileExists ) {
429 $this->setProps( $cachedValues );
430 }
431
432 $this->dataLoaded = true;
433 $this->extraDataLoaded = true;
434 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
435 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
436 }
437 }
438
442 public function invalidateCache() {
443 $key = $this->getCacheKey();
444 if ( !$key ) {
445 return;
446 }
447
448 $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
449 static function () use ( $key ) {
450 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
451 },
452 __METHOD__
453 );
454 }
455
463 public function loadFromFile( $path = null ) {
464 $props = $this->repo->getFileProps( $path ?? $this->getVirtualUrl() );
465 $this->setProps( $props );
466 }
467
475 protected function getCacheFields( $prefix = 'img_' ) {
476 if ( $prefix !== '' ) {
477 throw new InvalidArgumentException(
478 __METHOD__ . ' with a non-empty prefix is no longer supported.'
479 );
480 }
481
482 // See self::getQueryInfo() for the fetching of the data from the DB,
483 // self::loadFromRow() for the loading of the object from the DB row,
484 // and self::loadFromCache() for the caching, and self::setProps() for
485 // populating the object from an array of data.
486 return [ 'size', 'width', 'height', 'bits', 'media_type',
487 'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
488 }
489
497 protected function getLazyCacheFields( $prefix = 'img_' ) {
498 if ( $prefix !== '' ) {
499 throw new InvalidArgumentException(
500 __METHOD__ . ' with a non-empty prefix is no longer supported.'
501 );
502 }
503
504 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
505 return [ 'metadata' ];
506 }
507
513 protected function loadFromDB( $flags = 0 ) {
514 $fname = static::class . '::' . __FUNCTION__;
515
516 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
517 $this->dataLoaded = true;
518 $this->extraDataLoaded = true;
519
520 $dbr = ( $flags & self::READ_LATEST )
521 ? $this->repo->getPrimaryDB()
522 : $this->repo->getReplicaDB();
523
524 $fileQuery = static::getQueryInfo();
525 $row = $dbr->selectRow(
526 $fileQuery['tables'],
527 $fileQuery['fields'],
528 [ 'img_name' => $this->getName() ],
529 $fname,
530 [],
531 $fileQuery['joins']
532 );
533
534 if ( $row ) {
535 $this->loadFromRow( $row );
536 } else {
537 $this->fileExists = false;
538 }
539 }
540
546 protected function loadExtraFromDB() {
547 if ( !$this->title ) {
548 return; // Avoid hard failure when the file does not exist. T221812
549 }
550
551 $fname = static::class . '::' . __FUNCTION__;
552
553 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
554 $this->extraDataLoaded = true;
555
556 $db = $this->repo->getReplicaDB();
557 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
558 if ( !$fieldMap ) {
559 $db = $this->repo->getPrimaryDB();
560 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
561 }
562
563 if ( $fieldMap ) {
564 if ( isset( $fieldMap['metadata'] ) ) {
565 $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
566 }
567 } else {
568 throw new MWException( "Could not find data for image '{$this->getName()}'." );
569 }
570 }
571
577 private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
578 $fieldMap = false;
579
580 $fileQuery = self::getQueryInfo( [ 'omit-nonlazy' ] );
581 $row = $dbr->selectRow(
582 $fileQuery['tables'],
583 $fileQuery['fields'],
584 [
585 'img_name' => $this->getName(),
586 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
587 ],
588 $fname,
589 [],
590 $fileQuery['joins']
591 );
592 if ( $row ) {
593 $fieldMap = $this->unprefixRow( $row, 'img_' );
594 } else {
595 # File may have been uploaded over in the meantime; check the old versions
596 $fileQuery = OldLocalFile::getQueryInfo( [ 'omit-nonlazy' ] );
597 $row = $dbr->selectRow(
598 $fileQuery['tables'],
599 $fileQuery['fields'],
600 [
601 'oi_name' => $this->getName(),
602 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
603 ],
604 $fname,
605 [],
606 $fileQuery['joins']
607 );
608 if ( $row ) {
609 $fieldMap = $this->unprefixRow( $row, 'oi_' );
610 }
611 }
612
613 return $fieldMap;
614 }
615
622 protected function unprefixRow( $row, $prefix = 'img_' ) {
623 $array = (array)$row;
624 $prefixLength = strlen( $prefix );
625
626 // Sanity check prefix once
627 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
628 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
629 }
630
631 $decoded = [];
632 foreach ( $array as $name => $value ) {
633 $decoded[substr( $name, $prefixLength )] = $value;
634 }
635
636 return $decoded;
637 }
638
654 public function loadFromRow( $row, $prefix = 'img_' ) {
655 $this->dataLoaded = true;
656
657 $unprefixed = $this->unprefixRow( $row, $prefix );
658
659 $this->name = $unprefixed['name'];
660 $this->media_type = $unprefixed['media_type'];
661
662 $this->description = MediaWikiServices::getInstance()->getCommentStore()
663 ->getComment( "{$prefix}description", $row )->text;
664
665 $this->user = User::newFromAnyId(
666 $unprefixed['user'] ?? null,
667 $unprefixed['user_text'] ?? null,
668 $unprefixed['actor'] ?? null
669 );
670
671 $this->timestamp = wfTimestamp( TS_MW, $unprefixed['timestamp'] );
672
674 $this->repo->getReplicaDB(), $unprefixed['metadata'] );
675
676 if ( empty( $unprefixed['major_mime'] ) ) {
677 $this->major_mime = 'unknown';
678 $this->minor_mime = 'unknown';
679 $this->mime = 'unknown/unknown';
680 } else {
681 if ( !$unprefixed['minor_mime'] ) {
682 $unprefixed['minor_mime'] = 'unknown';
683 }
684 $this->major_mime = $unprefixed['major_mime'];
685 $this->minor_mime = $unprefixed['minor_mime'];
686 $this->mime = $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
687 }
688
689 // Trim zero padding from char/binary field
690 $this->sha1 = rtrim( $unprefixed['sha1'], "\0" );
691
692 // Normalize some fields to integer type, per their database definition.
693 // Use unary + so that overflows will be upgraded to double instead of
694 // being trucated as with intval(). This is important to allow > 2 GiB
695 // files on 32-bit systems.
696 $this->size = +$unprefixed['size'];
697 $this->width = +$unprefixed['width'];
698 $this->height = +$unprefixed['height'];
699 $this->bits = +$unprefixed['bits'];
700
701 // Check for extra fields (deprecated since MW 1.37)
702 $extraFields = array_diff(
703 array_keys( $unprefixed ),
704 [
705 'name', 'media_type', 'description_text', 'description_data',
706 'description_cid', 'user', 'user_text', 'actor', 'timestamp',
707 'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
708 'height', 'bits'
709 ]
710 );
711 if ( $extraFields ) {
713 'Passing extra fields (' .
714 implode( ', ', $extraFields )
715 . ') to ' . __METHOD__ . ' was deprecated in MediaWiki 1.37. ' .
716 'Property assignment will be removed in a later version.',
717 '1.37' );
718 foreach ( $extraFields as $field ) {
719 $this->$field = $unprefixed[$field];
720 }
721 }
722
723 $this->fileExists = true;
724 }
725
731 public function load( $flags = 0 ) {
732 if ( !$this->dataLoaded ) {
733 if ( $flags & self::READ_LATEST ) {
734 $this->loadFromDB( $flags );
735 } else {
736 $this->loadFromCache();
737 }
738 }
739
740 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
741 // @note: loads on name/timestamp to reduce race condition problems
742 $this->loadExtraFromDB();
743 }
744 }
745
750 public function maybeUpgradeRow() {
751 if ( wfReadOnly() || $this->upgrading ) {
752 return;
753 }
754
755 $upgrade = false;
756 $reserialize = false;
757 if ( $this->media_type === null || $this->mime == 'image/svg' ) {
758 $upgrade = true;
759 } else {
760 $handler = $this->getHandler();
761 if ( $handler ) {
762 $validity = $handler->isFileMetadataValid( $this );
763 if ( $validity === MediaHandler::METADATA_BAD ) {
764 $upgrade = true;
765 } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE
766 && $this->repo->isMetadataUpdateEnabled()
767 ) {
768 $upgrade = true;
769 } elseif ( $this->repo->isJsonMetadataEnabled()
770 && $this->repo->isMetadataReserializeEnabled()
771 ) {
772 if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
773 $reserialize = true;
774 } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
775 $this->metadataSerializationFormat !== self::MDS_JSON ) {
776 $reserialize = true;
777 }
778 }
779 }
780 }
781
782 if ( $upgrade || $reserialize ) {
783 $this->upgrading = true;
784 // Defer updates unless in auto-commit CLI mode
785 DeferredUpdates::addCallableUpdate( function () use ( $upgrade ) {
786 $this->upgrading = false; // avoid duplicate updates
787 try {
788 if ( $upgrade ) {
789 $this->upgradeRow();
790 } else {
791 $this->reserializeMetadata();
792 }
793 } catch ( LocalFileLockError $e ) {
794 // let the other process handle it (or do it next time)
795 }
796 } );
797 }
798 }
799
803 public function getUpgraded() {
804 return $this->upgraded;
805 }
806
811 public function upgradeRow() {
812 $this->lock();
813
814 $this->loadFromFile();
815
816 # Don't destroy file info of missing files
817 if ( !$this->fileExists ) {
818 $this->unlock();
819 wfDebug( __METHOD__ . ": file does not exist, aborting" );
820
821 return;
822 }
823
824 $dbw = $this->repo->getPrimaryDB();
825 list( $major, $minor ) = self::splitMime( $this->mime );
826
827 if ( wfReadOnly() ) {
828 $this->unlock();
829
830 return;
831 }
832 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
833
834 $dbw->update( 'image',
835 [
836 'img_size' => $this->size, // sanity
837 'img_width' => $this->width,
838 'img_height' => $this->height,
839 'img_bits' => $this->bits,
840 'img_media_type' => $this->media_type,
841 'img_major_mime' => $major,
842 'img_minor_mime' => $minor,
843 'img_metadata' => $this->getMetadataForDb( $dbw ),
844 'img_sha1' => $this->sha1,
845 ],
846 [ 'img_name' => $this->getName() ],
847 __METHOD__
848 );
849
850 $this->invalidateCache();
851
852 $this->unlock();
853 $this->upgraded = true; // avoid rework/retries
854 }
855
860 protected function reserializeMetadata() {
861 if ( wfReadOnly() ) {
862 return;
863 }
864 $dbw = $this->repo->getPrimaryDB();
865 $dbw->update(
866 'image',
867 [ 'img_metadata' => $this->getMetadataForDb( $dbw ) ],
868 [
869 'img_name' => $this->name,
870 'img_timestamp' => $dbw->timestamp( $this->timestamp ),
871 ],
872 __METHOD__
873 );
874 $this->upgraded = true;
875 }
876
888 protected function setProps( $info ) {
889 $this->dataLoaded = true;
890 $fields = $this->getCacheFields( '' );
891 $fields[] = 'fileExists';
892
893 foreach ( $fields as $field ) {
894 if ( isset( $info[$field] ) ) {
895 $this->$field = $info[$field];
896 }
897 }
898
899 // Only our own cache sets these properties, so they both should be present.
900 if ( isset( $info['user'] ) &&
901 isset( $info['user_text'] ) &&
902 $info['user_text'] !== ''
903 ) {
904 $this->user = new UserIdentityValue( $info['user'], $info['user_text'] );
905 }
906
907 // Fix up mime fields
908 if ( isset( $info['major_mime'] ) ) {
909 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
910 } elseif ( isset( $info['mime'] ) ) {
911 $this->mime = $info['mime'];
912 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
913 }
914
915 if ( isset( $info['metadata'] ) ) {
916 if ( is_string( $info['metadata'] ) ) {
917 $this->loadMetadataFromString( $info['metadata'] );
918 } elseif ( is_array( $info['metadata'] ) ) {
919 $this->metadataArray = $info['metadata'];
920 if ( isset( $info['metadataBlobs'] ) ) {
921 $this->metadataBlobs = $info['metadataBlobs'];
922 $this->unloadedMetadataBlobs = array_diff_key(
923 $this->metadataBlobs,
924 $this->metadataArray
925 );
926 } else {
927 $this->metadataBlobs = [];
928 $this->unloadedMetadataBlobs = [];
929 }
930 } else {
931 $logger = LoggerFactory::getInstance( 'LocalFile' );
932 $logger->warning( __METHOD__ . ' given invalid metadata of type ' .
933 gettype( $info['metadata'] ) );
934 $this->metadataArray = [];
935 }
936 $this->extraDataLoaded = true;
937 }
938 }
939
955 public function isMissing() {
956 if ( $this->missing === null ) {
957 $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
958 $this->missing = !$fileExists;
959 }
960
961 return $this->missing;
962 }
963
971 public function getWidth( $page = 1 ) {
972 $page = (int)$page;
973 if ( $page < 1 ) {
974 $page = 1;
975 }
976
977 $this->load();
978
979 if ( $this->isMultipage() ) {
980 $handler = $this->getHandler();
981 if ( !$handler ) {
982 return 0;
983 }
984 $dim = $handler->getPageDimensions( $this, $page );
985 if ( $dim ) {
986 return $dim['width'];
987 } else {
988 // For non-paged media, the false goes through an
989 // intval, turning failure into 0, so do same here.
990 return 0;
991 }
992 } else {
993 return $this->width;
994 }
995 }
996
1004 public function getHeight( $page = 1 ) {
1005 $page = (int)$page;
1006 if ( $page < 1 ) {
1007 $page = 1;
1008 }
1009
1010 $this->load();
1011
1012 if ( $this->isMultipage() ) {
1013 $handler = $this->getHandler();
1014 if ( !$handler ) {
1015 return 0;
1016 }
1017 $dim = $handler->getPageDimensions( $this, $page );
1018 if ( $dim ) {
1019 return $dim['height'];
1020 } else {
1021 // For non-paged media, the false goes through an
1022 // intval, turning failure into 0, so do same here.
1023 return 0;
1024 }
1025 } else {
1026 return $this->height;
1027 }
1028 }
1029
1037 public function getDescriptionShortUrl() {
1038 if ( !$this->title ) {
1039 return null; // Avoid hard failure when the file does not exist. T221812
1040 }
1041
1042 $pageId = $this->title->getArticleID();
1043
1044 if ( $pageId ) {
1045 $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
1046 if ( $url !== false ) {
1047 return $url;
1048 }
1049 }
1050 return null;
1051 }
1052
1059 public function getMetadata() {
1060 $data = $this->getMetadataArray();
1061 if ( !$data ) {
1062 return '';
1063 } elseif ( array_keys( $data ) === [ '_error' ] ) {
1064 // Legacy error encoding
1065 return $data['_error'];
1066 } else {
1067 return serialize( $this->getMetadataArray() );
1068 }
1069 }
1070
1077 public function getMetadataArray(): array {
1078 $this->load( self::LOAD_ALL );
1079 if ( $this->unloadedMetadataBlobs ) {
1080 return $this->getMetadataItems(
1081 array_unique( array_merge(
1082 array_keys( $this->metadataArray ),
1083 array_keys( $this->unloadedMetadataBlobs )
1084 ) )
1085 );
1086 }
1087 return $this->metadataArray;
1088 }
1089
1090 public function getMetadataItems( array $itemNames ): array {
1091 $this->load( self::LOAD_ALL );
1092 $result = [];
1093 $addresses = [];
1094 foreach ( $itemNames as $itemName ) {
1095 if ( array_key_exists( $itemName, $this->metadataArray ) ) {
1096 $result[$itemName] = $this->metadataArray[$itemName];
1097 } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
1098 $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
1099 }
1100 }
1101 if ( $addresses ) {
1102 $blobStore = $this->repo->getBlobStore();
1103 if ( !$blobStore ) {
1104 LoggerFactory::getInstance( 'LocalFile' )->warning(
1105 "Unable to load metadata: repo has no blob store" );
1106 return $result;
1107 }
1108 $status = $blobStore->getBlobBatch( $addresses );
1109 if ( !$status->isGood() ) {
1110 $msg = Status::wrap( $status )->getWikiText(
1111 false, false, 'en' );
1112 LoggerFactory::getInstance( 'LocalFile' )->warning(
1113 "Error loading metadata from BlobStore: $msg" );
1114 }
1115 foreach ( $addresses as $itemName => $address ) {
1116 unset( $this->unloadedMetadataBlobs[$itemName] );
1117 $json = $status->getValue()[$address] ?? null;
1118 if ( $json !== null ) {
1119 $value = $this->jsonDecode( $json );
1120 $result[$itemName] = $value;
1121 $this->metadataArray[$itemName] = $value;
1122 }
1123 }
1124 }
1125 return $result;
1126 }
1127
1136 private function jsonEncode( $data ): string {
1137 $s = json_encode( $data,
1138 JSON_INVALID_UTF8_IGNORE |
1139 JSON_UNESCAPED_SLASHES |
1140 JSON_UNESCAPED_UNICODE );
1141 if ( $s === false ) {
1142 throw new MWException( __METHOD__ . ': metadata is not JSON-serializable ' .
1143 '(type = ' . $this->getMimeType() . ')' );
1144 }
1145 return $s;
1146 }
1147
1159 private function jsonDecode( string $s ) {
1160 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1161 return @json_decode( $s, true, 512, JSON_INVALID_UTF8_IGNORE );
1162 }
1163
1175 public function getMetadataForDb( IDatabase $db ) {
1176 $this->load( self::LOAD_ALL );
1177 if ( !$this->metadataArray && !$this->metadataBlobs ) {
1178 $s = '';
1179 } elseif ( $this->repo->isJsonMetadataEnabled() ) {
1180 $s = $this->getJsonMetadata();
1181 } else {
1182 $s = serialize( $this->getMetadataArray() );
1183 }
1184 if ( !is_string( $s ) ) {
1185 throw new MWException( 'Could not serialize image metadata value for DB' );
1186 }
1187 return $db->encodeBlob( $s );
1188 }
1189
1196 private function getJsonMetadata() {
1197 // Directly store data that is not already in BlobStore
1198 $envelope = [
1199 'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
1200 ];
1201
1202 // Also store the blob addresses
1203 if ( $this->metadataBlobs ) {
1204 $envelope['blobs'] = $this->metadataBlobs;
1205 }
1206
1207 // Try encoding
1208 $s = $this->jsonEncode( $envelope );
1209
1210 // Decide whether to try splitting the metadata.
1211 // Return early if it's not going to happen.
1212 if ( !$this->repo->isSplitMetadataEnabled()
1213 || !$this->getHandler()
1214 || !$this->getHandler()->useSplitMetadata()
1215 ) {
1216 return $s;
1217 }
1218 $threshold = $this->repo->getSplitMetadataThreshold();
1219 if ( !$threshold || strlen( $s ) <= $threshold ) {
1220 return $s;
1221 }
1222 $blobStore = $this->repo->getBlobStore();
1223 if ( !$blobStore ) {
1224 return $s;
1225 }
1226
1227 // The data as a whole is above the item threshold. Look for
1228 // large items that can be split out.
1229 $blobAddresses = [];
1230 foreach ( $envelope['data'] as $name => $value ) {
1231 $encoded = $this->jsonEncode( $value );
1232 if ( strlen( $encoded ) > $threshold ) {
1233 $blobAddresses[$name] = $blobStore->storeBlob(
1234 $encoded,
1235 [ BlobStore::IMAGE_HINT => $this->getName() ]
1236 );
1237 }
1238 }
1239 // Remove any items that were split out
1240 $envelope['data'] = array_diff_key( $envelope['data'], $blobAddresses );
1241 $envelope['blobs'] = $blobAddresses;
1242 $s = $this->jsonEncode( $envelope );
1243
1244 // Repeated calls to this function should not keep inserting more blobs
1245 $this->metadataBlobs += $blobAddresses;
1246
1247 return $s;
1248 }
1249
1256 private function isMetadataOversize() {
1257 if ( !$this->repo->isSplitMetadataEnabled() ) {
1258 return false;
1259 }
1260 $threshold = $this->repo->getSplitMetadataThreshold();
1261 $directItems = array_diff_key( $this->metadataArray, $this->metadataBlobs );
1262 foreach ( $directItems as $value ) {
1263 if ( strlen( $this->jsonEncode( $value ) ) > $threshold ) {
1264 return true;
1265 }
1266 }
1267 return false;
1268 }
1269
1278 protected function loadMetadataFromDbFieldValue( IDatabase $db, $metadataBlob ) {
1279 $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
1280 }
1281
1289 protected function loadMetadataFromString( $metadataString ) {
1290 $this->extraDataLoaded = true;
1291 $this->metadataArray = [];
1292 $this->metadataBlobs = [];
1293 $this->unloadedMetadataBlobs = [];
1294 $metadataString = (string)$metadataString;
1295 if ( $metadataString === '' ) {
1296 $this->metadataSerializationFormat = self::MDS_EMPTY;
1297 return;
1298 }
1299 if ( $metadataString[0] === '{' ) {
1300 $envelope = $this->jsonDecode( $metadataString );
1301 if ( !$envelope ) {
1302 // Legacy error encoding
1303 $this->metadataArray = [ '_error' => $metadataString ];
1304 $this->metadataSerializationFormat = self::MDS_LEGACY;
1305 } else {
1306 $this->metadataSerializationFormat = self::MDS_JSON;
1307 if ( isset( $envelope['data'] ) ) {
1308 $this->metadataArray = $envelope['data'];
1309 }
1310 if ( isset( $envelope['blobs'] ) ) {
1311 $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope['blobs'];
1312 }
1313 }
1314 } else {
1315 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1316 $data = @unserialize( $metadataString );
1317 if ( !is_array( $data ) ) {
1318 // Legacy error encoding
1319 $data = [ '_error' => $metadataString ];
1320 $this->metadataSerializationFormat = self::MDS_LEGACY;
1321 } else {
1322 $this->metadataSerializationFormat = self::MDS_PHP;
1323 }
1324 $this->metadataArray = $data;
1325 }
1326 }
1327
1332 public function getBitDepth() {
1333 $this->load();
1334
1335 return (int)$this->bits;
1336 }
1337
1343 public function getSize() {
1344 $this->load();
1345
1346 return $this->size;
1347 }
1348
1354 public function getMimeType() {
1355 $this->load();
1356
1357 return $this->mime;
1358 }
1359
1366 public function getMediaType() {
1367 $this->load();
1368
1369 return $this->media_type;
1370 }
1371
1383 public function exists() {
1384 $this->load();
1385
1386 return $this->fileExists;
1387 }
1388
1405 protected function getThumbnails( $archiveName = false ) {
1406 if ( $archiveName ) {
1407 $dir = $this->getArchiveThumbPath( $archiveName );
1408 } else {
1409 $dir = $this->getThumbPath();
1410 }
1411
1412 $backend = $this->repo->getBackend();
1413 $files = [ $dir ];
1414 try {
1415 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1416 if ( $iterator !== null ) {
1417 foreach ( $iterator as $file ) {
1418 $files[] = $file;
1419 }
1420 }
1421 } catch ( FileBackendError $e ) {
1422 } // suppress (T56674)
1423
1424 return $files;
1425 }
1426
1430 private function purgeMetadataCache() {
1431 $this->invalidateCache();
1432 }
1433
1442 public function purgeCache( $options = [] ) {
1443 // Refresh metadata cache
1444 $this->maybeUpgradeRow();
1445 $this->purgeMetadataCache();
1446
1447 // Delete thumbnails
1448 $this->purgeThumbnails( $options );
1449
1450 // Purge CDN cache for this file
1451 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1452 $hcu->purgeUrls(
1453 $this->getUrl(),
1454 !empty( $options['forThumbRefresh'] )
1455 ? $hcu::PURGE_PRESEND // just a manual purge
1456 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1457 );
1458 }
1459
1465 public function purgeOldThumbnails( $archiveName ) {
1466 // Get a list of old thumbnails
1467 $thumbs = $this->getThumbnails( $archiveName );
1468
1469 // Delete thumbnails from storage, and prevent the directory itself from being purged
1470 $dir = array_shift( $thumbs );
1471 $this->purgeThumbList( $dir, $thumbs );
1472
1473 $urls = [];
1474 foreach ( $thumbs as $thumb ) {
1475 $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1476 }
1477
1478 // Purge any custom thumbnail caches
1479 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1480
1481 // Purge the CDN
1482 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1483 $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1484 }
1485
1492 public function purgeThumbnails( $options = [] ) {
1493 $thumbs = $this->getThumbnails();
1494
1495 // Delete thumbnails from storage, and prevent the directory itself from being purged
1496 $dir = array_shift( $thumbs );
1497 $this->purgeThumbList( $dir, $thumbs );
1498
1499 // Always purge all files from CDN regardless of handler filters
1500 $urls = [];
1501 foreach ( $thumbs as $thumb ) {
1502 $urls[] = $this->getThumbUrl( $thumb );
1503 }
1504
1505 // Give the media handler a chance to filter the file purge list
1506 if ( !empty( $options['forThumbRefresh'] ) ) {
1507 $handler = $this->getHandler();
1508 if ( $handler ) {
1509 $handler->filterThumbnailPurgeList( $thumbs, $options );
1510 }
1511 }
1512
1513 // Purge any custom thumbnail caches
1514 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1515
1516 // Purge the CDN
1517 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1518 $hcu->purgeUrls(
1519 $urls,
1520 !empty( $options['forThumbRefresh'] )
1521 ? $hcu::PURGE_PRESEND // just a manual purge
1522 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1523 );
1524 }
1525
1532 public function prerenderThumbnails() {
1534
1535 $jobs = [];
1536
1538 rsort( $sizes );
1539
1540 foreach ( $sizes as $size ) {
1541 if ( $this->isMultipage() ) {
1542 // (T309114) Only trigger render jobs up to MAX_PAGE_RENDER_JOBS to avoid
1543 // a flood of jobs for huge files.
1544 $pageLimit = min( $this->pageCount(), self::MAX_PAGE_RENDER_JOBS );
1545
1546 for ( $page = 1; $page <= $pageLimit; $page++ ) {
1547 $jobs[] = new ThumbnailRenderJob(
1548 $this->getTitle(),
1549 [ 'transformParams' => [
1550 'width' => $size,
1551 'page' => $page,
1552 ] ]
1553 );
1554 }
1555 } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1556 $jobs[] = new ThumbnailRenderJob(
1557 $this->getTitle(),
1558 [ 'transformParams' => [ 'width' => $size ] ]
1559 );
1560 }
1561 }
1562
1563 if ( $jobs ) {
1564 JobQueueGroup::singleton()->lazyPush( $jobs );
1565 }
1566 }
1567
1574 protected function purgeThumbList( $dir, $files ) {
1575 $fileListDebug = strtr(
1576 var_export( $files, true ),
1577 [ "\n" => '' ]
1578 );
1579 wfDebug( __METHOD__ . ": $fileListDebug" );
1580
1581 if ( $this->repo->supportsSha1URLs() ) {
1582 $reference = $this->getSha1();
1583 } else {
1584 $reference = $this->getName();
1585 }
1586
1587 $purgeList = [];
1588 foreach ( $files as $file ) {
1589 # Check that the reference (filename or sha1) is part of the thumb name
1590 # This is a basic sanity check to avoid erasing unrelated directories
1591 if ( strpos( $file, $reference ) !== false
1592 || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1593 ) {
1594 $purgeList[] = "{$dir}/{$file}";
1595 }
1596 }
1597
1598 # Delete the thumbnails
1599 $this->repo->quickPurgeBatch( $purgeList );
1600 # Clear out the thumbnail directory if empty
1601 $this->repo->quickCleanDir( $dir );
1602 }
1603
1615 public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1616 if ( !$this->exists() ) {
1617 return []; // Avoid hard failure when the file does not exist. T221812
1618 }
1619
1620 $dbr = $this->repo->getReplicaDB();
1621 $oldFileQuery = OldLocalFile::getQueryInfo();
1622
1623 $tables = $oldFileQuery['tables'];
1624 $fields = $oldFileQuery['fields'];
1625 $join_conds = $oldFileQuery['joins'];
1626 $conds = $opts = [];
1627 $eq = $inc ? '=' : '';
1628 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1629
1630 if ( $start ) {
1631 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1632 }
1633
1634 if ( $end ) {
1635 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1636 }
1637
1638 if ( $limit ) {
1639 $opts['LIMIT'] = $limit;
1640 }
1641
1642 // Search backwards for time > x queries
1643 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1644 $opts['ORDER BY'] = "oi_timestamp $order";
1645 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1646
1647 $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1648 $conds, $opts, $join_conds );
1649
1650 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1651 $r = [];
1652
1653 foreach ( $res as $row ) {
1654 $r[] = $this->repo->newFileFromRow( $row );
1655 }
1656
1657 if ( $order == 'ASC' ) {
1658 $r = array_reverse( $r ); // make sure it ends up descending
1659 }
1660
1661 return $r;
1662 }
1663
1674 public function nextHistoryLine() {
1675 if ( !$this->exists() ) {
1676 return false; // Avoid hard failure when the file does not exist. T221812
1677 }
1678
1679 # Polymorphic function name to distinguish foreign and local fetches
1680 $fname = static::class . '::' . __FUNCTION__;
1681
1682 $dbr = $this->repo->getReplicaDB();
1683
1684 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1685 $fileQuery = self::getQueryInfo();
1686 $this->historyRes = $dbr->select( $fileQuery['tables'],
1687 $fileQuery['fields'] + [
1688 'oi_archive_name' => $dbr->addQuotes( '' ),
1689 'oi_deleted' => 0,
1690 ],
1691 [ 'img_name' => $this->title->getDBkey() ],
1692 $fname,
1693 [],
1694 $fileQuery['joins']
1695 );
1696
1697 if ( $dbr->numRows( $this->historyRes ) == 0 ) {
1698 $this->historyRes = null;
1699
1700 return false;
1701 }
1702 } elseif ( $this->historyLine == 1 ) {
1703 $fileQuery = OldLocalFile::getQueryInfo();
1704 $this->historyRes = $dbr->select(
1705 $fileQuery['tables'],
1706 $fileQuery['fields'],
1707 [ 'oi_name' => $this->title->getDBkey() ],
1708 $fname,
1709 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1710 $fileQuery['joins']
1711 );
1712 }
1713 $this->historyLine++;
1714
1715 return $dbr->fetchObject( $this->historyRes );
1716 }
1717
1722 public function resetHistory() {
1723 $this->historyLine = 0;
1724
1725 if ( $this->historyRes !== null ) {
1726 $this->historyRes = null;
1727 }
1728 }
1729
1763 public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1764 $timestamp = false, Authority $uploader = null, $tags = [],
1765 $createNullRevision = true, $revert = false
1766 ) {
1767 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1768 return $this->readOnlyFatalStatus();
1769 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1770 // Check this in advance to avoid writing to FileBackend and the file tables,
1771 // only to fail on insert the revision due to the text store being unavailable.
1772 return $this->readOnlyFatalStatus();
1773 }
1774
1775 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1776 if ( !$props ) {
1777 if ( FileRepo::isVirtualUrl( $srcPath )
1778 || FileBackend::isStoragePath( $srcPath )
1779 ) {
1780 $props = $this->repo->getFileProps( $srcPath );
1781 } else {
1782 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1783 $props = $mwProps->getPropsFromPath( $srcPath, true );
1784 }
1785 }
1786
1787 $options = [];
1788 $handler = MediaHandler::getHandler( $props['mime'] );
1789 if ( $handler ) {
1790 if ( is_string( $props['metadata'] ) ) {
1791 // This supports callers directly fabricating a metadata
1792 // property using serialize(). Normally the metadata property
1793 // comes from MWFileProps, in which case it won't be a string.
1794 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1795 $metadata = @unserialize( $props['metadata'] );
1796 } else {
1797 $metadata = $props['metadata'];
1798 }
1799
1800 if ( is_array( $metadata ) ) {
1801 $options['headers'] = $handler->getContentHeaders( $metadata );
1802 }
1803 } else {
1804 $options['headers'] = [];
1805 }
1806
1807 // Trim spaces on user supplied text
1808 $comment = trim( $comment );
1809
1810 $this->lock();
1811 $status = $this->publish( $src, $flags, $options );
1812
1813 if ( $status->successCount >= 2 ) {
1814 // There will be a copy+(one of move,copy,store).
1815 // The first succeeding does not commit us to updating the DB
1816 // since it simply copied the current version to a timestamped file name.
1817 // It is only *preferable* to avoid leaving such files orphaned.
1818 // Once the second operation goes through, then the current version was
1819 // updated and we must therefore update the DB too.
1820 $oldver = $status->value;
1821
1822 if ( $uploader === null ) {
1823 // Uploader argument is optional, fall back to the context authority
1824 $uploader = RequestContext::getMain()->getAuthority();
1825 }
1826
1827 $uploadStatus = $this->recordUpload3(
1828 $oldver,
1829 $comment,
1830 $pageText,
1831 $uploader,
1832 $props,
1833 $timestamp,
1834 $tags,
1835 $createNullRevision,
1836 $revert
1837 );
1838 if ( !$uploadStatus->isOK() ) {
1839 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1840 // update filenotfound error with more specific path
1841 $status->fatal( 'filenotfound', $srcPath );
1842 } else {
1843 $status->merge( $uploadStatus );
1844 }
1845 }
1846 }
1847
1848 $this->unlock();
1849 return $status;
1850 }
1851
1868 public function recordUpload3(
1869 string $oldver,
1870 string $comment,
1871 string $pageText,
1872 Authority $performer,
1873 $props = false,
1874 $timestamp = false,
1875 $tags = [],
1876 bool $createNullRevision = true,
1877 bool $revert = false
1878 ): Status {
1879 $dbw = $this->repo->getPrimaryDB();
1880
1881 # Imports or such might force a certain timestamp; otherwise we generate
1882 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1883 if ( $timestamp === false ) {
1884 $timestamp = $dbw->timestamp();
1885 $allowTimeKludge = true;
1886 } else {
1887 $allowTimeKludge = false;
1888 }
1889
1890 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1891 $props['description'] = $comment;
1892 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1893 $this->setProps( $props );
1894
1895 # Fail now if the file isn't there
1896 if ( !$this->fileExists ) {
1897 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1898
1899 return Status::newFatal( 'filenotfound', $this->getRel() );
1900 }
1901
1902 $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1903
1904 $dbw->startAtomic( __METHOD__ );
1905
1906 $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1907 $this->user = $performer->getUser();
1908
1909 # Test to see if the row exists using INSERT IGNORE
1910 # This avoids race conditions by locking the row until the commit, and also
1911 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1912 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1913 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1914 $actorFields = [ 'img_actor' => $actorId ];
1915 $dbw->insert( 'image',
1916 [
1917 'img_name' => $this->getName(),
1918 'img_size' => $this->size,
1919 'img_width' => intval( $this->width ),
1920 'img_height' => intval( $this->height ),
1921 'img_bits' => $this->bits,
1922 'img_media_type' => $this->media_type,
1923 'img_major_mime' => $this->major_mime,
1924 'img_minor_mime' => $this->minor_mime,
1925 'img_timestamp' => $timestamp,
1926 'img_metadata' => $this->getMetadataForDb( $dbw ),
1927 'img_sha1' => $this->sha1
1928 ] + $commentFields + $actorFields,
1929 __METHOD__,
1930 [ 'IGNORE' ]
1931 );
1932 $reupload = ( $dbw->affectedRows() == 0 );
1933
1934 if ( $reupload ) {
1935 $row = $dbw->selectRow(
1936 'image',
1937 [ 'img_timestamp', 'img_sha1' ],
1938 [ 'img_name' => $this->getName() ],
1939 __METHOD__,
1940 [ 'LOCK IN SHARE MODE' ]
1941 );
1942
1943 if ( $row && $row->img_sha1 === $this->sha1 ) {
1944 $dbw->endAtomic( __METHOD__ );
1945 wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1946 $title = Title::newFromText( $this->getName(), NS_FILE );
1947 return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1948 }
1949
1950 if ( $allowTimeKludge ) {
1951 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1952 $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1953 # Avoid a timestamp that is not newer than the last version
1954 # TODO: the image/oldimage tables should be like page/revision with an ID field
1955 if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1956 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1957 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1958 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1959 }
1960 }
1961
1962 $tables = [ 'image' ];
1963 $fields = [
1964 'oi_name' => 'img_name',
1965 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1966 'oi_size' => 'img_size',
1967 'oi_width' => 'img_width',
1968 'oi_height' => 'img_height',
1969 'oi_bits' => 'img_bits',
1970 'oi_description_id' => 'img_description_id',
1971 'oi_timestamp' => 'img_timestamp',
1972 'oi_metadata' => 'img_metadata',
1973 'oi_media_type' => 'img_media_type',
1974 'oi_major_mime' => 'img_major_mime',
1975 'oi_minor_mime' => 'img_minor_mime',
1976 'oi_sha1' => 'img_sha1',
1977 'oi_actor' => 'img_actor',
1978 ];
1979 $joins = [];
1980
1981 # (T36993) Note: $oldver can be empty here, if the previous
1982 # version of the file was broken. Allow registration of the new
1983 # version to continue anyway, because that's better than having
1984 # an image that's not fixable by user operations.
1985 # Collision, this is an update of a file
1986 # Insert previous contents into oldimage
1987 $dbw->insertSelect( 'oldimage', $tables, $fields,
1988 [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1989
1990 # Update the current image row
1991 $dbw->update( 'image',
1992 [
1993 'img_size' => $this->size,
1994 'img_width' => intval( $this->width ),
1995 'img_height' => intval( $this->height ),
1996 'img_bits' => $this->bits,
1997 'img_media_type' => $this->media_type,
1998 'img_major_mime' => $this->major_mime,
1999 'img_minor_mime' => $this->minor_mime,
2000 'img_timestamp' => $timestamp,
2001 'img_metadata' => $this->getMetadataForDb( $dbw ),
2002 'img_sha1' => $this->sha1
2003 ] + $commentFields + $actorFields,
2004 [ 'img_name' => $this->getName() ],
2005 __METHOD__
2006 );
2007 }
2008
2009 $descTitle = $this->getTitle();
2010 $descId = $descTitle->getArticleID();
2011 $wikiPage = new WikiFilePage( $descTitle );
2012 $wikiPage->setFile( $this );
2013
2014 // Determine log action. If reupload is done by reverting, use a special log_action.
2015 if ( $revert ) {
2016 $logAction = 'revert';
2017 } elseif ( $reupload ) {
2018 $logAction = 'overwrite';
2019 } else {
2020 $logAction = 'upload';
2021 }
2022 // Add the log entry...
2023 $logEntry = new ManualLogEntry( 'upload', $logAction );
2024 $logEntry->setTimestamp( $this->timestamp );
2025 $logEntry->setPerformer( $performer->getUser() );
2026 $logEntry->setComment( $comment );
2027 $logEntry->setTarget( $descTitle );
2028 // Allow people using the api to associate log entries with the upload.
2029 // Log has a timestamp, but sometimes different from upload timestamp.
2030 $logEntry->setParameters(
2031 [
2032 'img_sha1' => $this->sha1,
2033 'img_timestamp' => $timestamp,
2034 ]
2035 );
2036 // Note we keep $logId around since during new image
2037 // creation, page doesn't exist yet, so log_page = 0
2038 // but we want it to point to the page we're making,
2039 // so we later modify the log entry.
2040 // For a similar reason, we avoid making an RC entry
2041 // now and wait until the page exists.
2042 $logId = $logEntry->insert();
2043
2044 if ( $descTitle->exists() ) {
2045 if ( $createNullRevision ) {
2046 $revStore = MediaWikiServices::getInstance()->getRevisionStore();
2047 // Use own context to get the action text in content language
2048 $formatter = LogFormatter::newFromEntry( $logEntry );
2049 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
2050 $editSummary = $formatter->getPlainActionText();
2051 $summary = CommentStoreComment::newUnsavedComment( $editSummary );
2052 $nullRevRecord = $revStore->newNullRevision(
2053 $dbw,
2054 $descTitle,
2055 $summary,
2056 false,
2057 $performer->getUser()
2058 );
2059
2060 if ( $nullRevRecord ) {
2061 $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
2062
2063 $this->getHookRunner()->onRevisionFromEditComplete(
2064 $wikiPage,
2065 $inserted,
2066 $inserted->getParentId(),
2067 $performer->getUser(),
2068 $tags
2069 );
2070
2071 $wikiPage->updateRevisionOn( $dbw, $inserted );
2072 // Associate null revision id
2073 $logEntry->setAssociatedRevId( $inserted->getId() );
2074 }
2075 }
2076
2077 $newPageContent = null;
2078 } else {
2079 // Make the description page and RC log entry post-commit
2080 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
2081 }
2082
2083 // NOTE: Even after ending this atomic section, we are probably still in the transaction
2084 // started by the call to lock() in publishTo(). We cannot yet safely schedule jobs,
2085 // see T263301.
2086 $dbw->endAtomic( __METHOD__ );
2087 $fname = __METHOD__;
2088
2089 # Do some cache purges after final commit so that:
2090 # a) Changes are more likely to be seen post-purge
2091 # b) They won't cause rollback of the log publish/update above
2092 $purgeUpdate = new AutoCommitUpdate(
2093 $dbw,
2094 __METHOD__,
2096 function () use (
2097 $reupload, $wikiPage, $newPageContent, $comment, $performer,
2098 $logEntry, $logId, $descId, $tags, $fname
2099 ) {
2100 # Update memcache after the commit
2101 $this->invalidateCache();
2102
2103 $updateLogPage = false;
2104 if ( $newPageContent ) {
2105 # New file page; create the description page.
2106 # There's already a log entry, so don't make a second RC entry
2107 # CDN and file cache for the description page are purged by doUserEditContent.
2108 $status = $wikiPage->doUserEditContent(
2109 $newPageContent,
2110 $performer,
2111 $comment,
2113 );
2114
2115 if ( isset( $status->value['revision-record'] ) ) {
2117 $revRecord = $status->value['revision-record'];
2118 // Associate new page revision id
2119 $logEntry->setAssociatedRevId( $revRecord->getId() );
2120 }
2121 // This relies on the resetArticleID() call in WikiPage::insertOn(),
2122 // which is triggered on $descTitle by doUserEditContent() above.
2123 if ( isset( $status->value['revision-record'] ) ) {
2125 $revRecord = $status->value['revision-record'];
2126 $updateLogPage = $revRecord->getPageId();
2127 }
2128 } else {
2129 # Existing file page: invalidate description page cache
2130 $title = $wikiPage->getTitle();
2131 $title->invalidateCache();
2132 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2133 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2134 # Allow the new file version to be patrolled from the page footer
2136 }
2137
2138 # Update associated rev id. This should be done by $logEntry->insert() earlier,
2139 # but setAssociatedRevId() wasn't called at that point yet...
2140 $logParams = $logEntry->getParameters();
2141 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
2142 $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
2143 if ( $updateLogPage ) {
2144 # Also log page, in case where we just created it above
2145 $update['log_page'] = $updateLogPage;
2146 }
2147 $this->getRepo()->getPrimaryDB()->update(
2148 'logging',
2149 $update,
2150 [ 'log_id' => $logId ],
2151 $fname
2152 );
2153 $this->getRepo()->getPrimaryDB()->insert(
2154 'log_search',
2155 [
2156 'ls_field' => 'associated_rev_id',
2157 'ls_value' => (string)$logEntry->getAssociatedRevId(),
2158 'ls_log_id' => $logId,
2159 ],
2160 $fname
2161 );
2162
2163 # Add change tags, if any
2164 if ( $tags ) {
2165 $logEntry->addTags( $tags );
2166 }
2167
2168 # Uploads can be patrolled
2169 $logEntry->setIsPatrollable( true );
2170
2171 # Now that the log entry is up-to-date, make an RC entry.
2172 $logEntry->publish( $logId );
2173
2174 # Run hook for other updates (typically more cache purging)
2175 $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2176
2177 if ( $reupload ) {
2178 # Delete old thumbnails
2179 $this->purgeThumbnails();
2180 # Remove the old file from the CDN cache
2181 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2182 $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2183 } else {
2184 # Update backlink pages pointing to this title if created
2185 $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2187 $this->getTitle(),
2188 'imagelinks',
2189 'upload-image',
2190 $performer->getUser()->getName(),
2191 $blcFactory->getBacklinkCache( $this->getTitle() )
2192 );
2193 }
2194
2195 $this->prerenderThumbnails();
2196 }
2197 );
2198
2199 # Invalidate cache for all pages using this file
2200 $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
2201 $this->getTitle(),
2202 'imagelinks',
2203 [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2204 );
2205
2206 // NOTE: We are probably still in the transaction started by the call to lock() in
2207 // publishTo(). We should only schedule jobs after that transaction was committed,
2208 // so a job queue failure doesn't cause the upload to fail (T263301).
2209 // Also, we should generally not schedule any Jobs or the DeferredUpdates that
2210 // assume the update is complete until after the transaction has been committed and
2211 // we are sure that the upload was indeed successful.
2212 $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2213 DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2214
2215 if ( !$reupload ) {
2216 // This is a new file, so update the image count
2217 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2218 }
2219
2220 JobQueueGroup::singleton()->lazyPush( $cacheUpdateJob );
2221 }, __METHOD__ );
2222
2223 return Status::newGood();
2224 }
2225
2242 public function publish( $src, $flags = 0, array $options = [] ) {
2243 return $this->publishTo( $src, $this->getRel(), $flags, $options );
2244 }
2245
2262 protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2263 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
2264
2265 $repo = $this->getRepo();
2266 if ( $repo->getReadOnlyReason() !== false ) {
2267 return $this->readOnlyFatalStatus();
2268 }
2269
2270 $this->lock();
2271
2272 if ( $this->isOld() ) {
2273 $archiveRel = $dstRel;
2274 $archiveName = basename( $archiveRel );
2275 } else {
2276 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
2277 $archiveRel = $this->getArchiveRel( $archiveName );
2278 }
2279
2280 if ( $repo->hasSha1Storage() ) {
2281 $sha1 = FileRepo::isVirtualUrl( $srcPath )
2282 ? $repo->getFileSha1( $srcPath )
2283 : FSFile::getSha1Base36FromPath( $srcPath );
2285 $wrapperBackend = $repo->getBackend();
2286 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2287 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2288 $status = $repo->quickImport( $src, $dst );
2289 if ( $flags & File::DELETE_SOURCE ) {
2290 unlink( $srcPath );
2291 }
2292
2293 if ( $this->exists() ) {
2294 $status->value = $archiveName;
2295 }
2296 } else {
2297 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2298 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2299
2300 if ( $status->value == 'new' ) {
2301 $status->value = '';
2302 } else {
2303 $status->value = $archiveName;
2304 }
2305 }
2306
2307 $this->unlock();
2308 return $status;
2309 }
2310
2329 public function move( $target ) {
2330 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2331 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2332 return $this->readOnlyFatalStatus();
2333 }
2334
2335 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2336 $batch = new LocalFileMoveBatch( $this, $target );
2337
2338 $this->lock();
2339 $batch->addCurrent();
2340 $archiveNames = $batch->addOlds();
2341 $status = $batch->execute();
2342 $this->unlock();
2343
2344 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2345
2346 // Purge the source and target files outside the transaction...
2347 $oldTitleFile = $localRepo->newFile( $this->title );
2348 $newTitleFile = $localRepo->newFile( $target );
2349 DeferredUpdates::addUpdate(
2350 new AutoCommitUpdate(
2351 $this->getRepo()->getPrimaryDB(),
2352 __METHOD__,
2353 static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2354 $oldTitleFile->purgeEverything();
2355 foreach ( $archiveNames as $archiveName ) {
2357 '@phan-var OldLocalFile $oldTitleFile';
2358 $oldTitleFile->purgeOldThumbnails( $archiveName );
2359 }
2360 $newTitleFile->purgeEverything();
2361 }
2362 ),
2363 DeferredUpdates::PRESEND
2364 );
2365
2366 if ( $status->isOK() ) {
2367 // Now switch the object
2368 $this->title = $target;
2369 // Force regeneration of the name and hashpath
2370 $this->name = null;
2371 $this->hashPath = null;
2372 }
2373
2374 return $status;
2375 }
2376
2393 public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2394 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2395 return $this->readOnlyFatalStatus();
2396 }
2397
2398 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2399
2400 $this->lock();
2401 $batch->addCurrent();
2402 // Get old version relative paths
2403 $archiveNames = $batch->addOlds();
2404 $status = $batch->execute();
2405 $this->unlock();
2406
2407 if ( $status->isOK() ) {
2408 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2409 }
2410
2411 // To avoid slow purges in the transaction, move them outside...
2412 DeferredUpdates::addUpdate(
2413 new AutoCommitUpdate(
2414 $this->getRepo()->getPrimaryDB(),
2415 __METHOD__,
2416 function () use ( $archiveNames ) {
2417 $this->purgeEverything();
2418 foreach ( $archiveNames as $archiveName ) {
2419 $this->purgeOldThumbnails( $archiveName );
2420 }
2421 }
2422 ),
2423 DeferredUpdates::PRESEND
2424 );
2425
2426 // Purge the CDN
2427 $purgeUrls = [];
2428 foreach ( $archiveNames as $archiveName ) {
2429 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2430 }
2431
2432 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2433 $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2434
2435 return $status;
2436 }
2437
2456 public function deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress = false ) {
2457 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2458 return $this->readOnlyFatalStatus();
2459 }
2460
2461 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2462
2463 $this->lock();
2464 $batch->addOld( $archiveName );
2465 $status = $batch->execute();
2466 $this->unlock();
2467
2468 $this->purgeOldThumbnails( $archiveName );
2469 if ( $status->isOK() ) {
2470 $this->purgeDescription();
2471 }
2472
2473 $url = $this->getArchiveUrl( $archiveName );
2474 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2475 $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2476
2477 return $status;
2478 }
2479
2492 public function restore( $versions = [], $unsuppress = false ) {
2493 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2494 return $this->readOnlyFatalStatus();
2495 }
2496
2497 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2498
2499 $this->lock();
2500 if ( !$versions ) {
2501 $batch->addAll();
2502 } else {
2503 $batch->addIds( $versions );
2504 }
2505 $status = $batch->execute();
2506 if ( $status->isGood() ) {
2507 $cleanupStatus = $batch->cleanup();
2508 $cleanupStatus->successCount = 0;
2509 $cleanupStatus->failCount = 0;
2510 $status->merge( $cleanupStatus );
2511 }
2512
2513 $this->unlock();
2514 return $status;
2515 }
2516
2527 public function getDescriptionUrl() {
2528 if ( !$this->title ) {
2529 return false; // Avoid hard failure when the file does not exist. T221812
2530 }
2531
2532 return $this->title->getLocalURL();
2533 }
2534
2544 public function getDescriptionText( Language $lang = null ) {
2545 if ( !$this->title ) {
2546 return false; // Avoid hard failure when the file does not exist. T221812
2547 }
2548
2549 $store = MediaWikiServices::getInstance()->getRevisionStore();
2550 $revision = $store->getRevisionByTitle( $this->title, 0, RevisionStore::READ_NORMAL );
2551 if ( !$revision ) {
2552 return false;
2553 }
2554
2555 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2556 $rendered = $renderer->getRenderedRevision(
2557 $revision,
2558 ParserOptions::newFromUserAndLang(
2559 RequestContext::getMain()->getUser(),
2560 $lang
2561 )
2562 );
2563
2564 if ( !$rendered ) {
2565 // audience check failed
2566 return false;
2567 }
2568
2569 $pout = $rendered->getRevisionParserOutput();
2570 return $pout->getText();
2571 }
2572
2580 public function getUploader( int $audience = self::FOR_PUBLIC, Authority $performer = null ): ?UserIdentity {
2581 $this->load();
2582 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2583 return null;
2584 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2585 return null;
2586 } else {
2587 return $this->user;
2588 }
2589 }
2590
2597 public function getDescription( $audience = self::FOR_PUBLIC, Authority $performer = null ) {
2598 $this->load();
2599 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2600 return '';
2601 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2602 return '';
2603 } else {
2604 return $this->description;
2605 }
2606 }
2607
2612 public function getTimestamp() {
2613 $this->load();
2614
2615 return $this->timestamp;
2616 }
2617
2622 public function getDescriptionTouched() {
2623 if ( !$this->exists() ) {
2624 return false; // Avoid hard failure when the file does not exist. T221812
2625 }
2626
2627 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2628 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2629 // need to differentiate between null (uninitialized) and false (failed to load).
2630 if ( $this->descriptionTouched === null ) {
2631 $cond = [
2632 'page_namespace' => $this->title->getNamespace(),
2633 'page_title' => $this->title->getDBkey()
2634 ];
2635 $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2636 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2637 }
2638
2639 return $this->descriptionTouched;
2640 }
2641
2646 public function getSha1() {
2647 $this->load();
2648 // Initialise now if necessary
2649 if ( $this->sha1 == '' && $this->fileExists ) {
2650 $this->lock();
2651
2652 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2653 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2654 $dbw = $this->repo->getPrimaryDB();
2655 $dbw->update( 'image',
2656 [ 'img_sha1' => $this->sha1 ],
2657 [ 'img_name' => $this->getName() ],
2658 __METHOD__ );
2659 $this->invalidateCache();
2660 }
2661
2662 $this->unlock();
2663 }
2664
2665 return $this->sha1;
2666 }
2667
2671 public function isCacheable() {
2672 $this->load();
2673
2674 // If extra data (metadata) was not loaded then it must have been large
2675 return $this->extraDataLoaded
2676 && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2677 }
2678
2683 public function acquireFileLock() {
2684 return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2685 [ $this->getPath() ], LockManager::LOCK_EX, 10
2686 ) );
2687 }
2688
2693 public function releaseFileLock() {
2694 return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2695 [ $this->getPath() ], LockManager::LOCK_EX
2696 ) );
2697 }
2698
2708 public function lock() {
2709 if ( !$this->locked ) {
2710 $logger = LoggerFactory::getInstance( 'LocalFile' );
2711
2712 $dbw = $this->repo->getPrimaryDB();
2713 $makesTransaction = !$dbw->trxLevel();
2714 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2715 // T56736: use simple lock to handle when the file does not exist.
2716 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2717 // Also, that would cause contention on INSERT of similarly named rows.
2718 $status = $this->acquireFileLock(); // represents all versions of the file
2719 if ( !$status->isGood() ) {
2720 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2721 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2722
2723 throw new LocalFileLockError( $status );
2724 }
2725 // Release the lock *after* commit to avoid row-level contention.
2726 // Make sure it triggers on rollback() as well as commit() (T132921).
2727 $dbw->onTransactionResolution(
2728 function () use ( $logger ) {
2729 $status = $this->releaseFileLock();
2730 if ( !$status->isGood() ) {
2731 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2732 }
2733 },
2734 __METHOD__
2735 );
2736 // Callers might care if the SELECT snapshot is safely fresh
2737 $this->lockedOwnTrx = $makesTransaction;
2738 }
2739
2740 $this->locked++;
2741
2742 return $this->lockedOwnTrx;
2743 }
2744
2753 public function unlock() {
2754 if ( $this->locked ) {
2755 --$this->locked;
2756 if ( !$this->locked ) {
2757 $dbw = $this->repo->getPrimaryDB();
2758 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2759 $this->lockedOwnTrx = false;
2760 }
2761 }
2762 }
2763
2767 protected function readOnlyFatalStatus() {
2768 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2769 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2770 }
2771
2775 public function __destruct() {
2776 $this->unlock();
2777 }
2778}
serialize()
unserialize( $serialized)
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
const NS_FILE
Definition Defines.php:70
const EDIT_SUPPRESS_RC
Definition Defines.php:128
const EDIT_NEW
Definition Defines.php:125
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfReadOnly()
Check whether the wiki is in read-only mode.
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:1282
Deferrable Update for closure/callback updates that should use auto-commit mode.
static newUnsavedComment( $comment, array $data=null)
Create a new, unsaved CommentStoreComment.
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.
const DELETE_SOURCE
Definition FileRepo.php:46
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition FileRepo.php:290
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:66
string $url
The URL corresponding to one of the four basic zones.
Definition File.php:134
MediaHandler $handler
Definition File.php:131
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition File.php:2470
getName()
Return the name of this file.
Definition File.php:330
const DELETE_SOURCE
Definition File.php:83
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
Definition File.php:1908
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition File.php:2480
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition File.php:2146
string $name
The name of a file from its title object.
Definition File.php:140
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition File.php:113
getHandler()
Get a MediaHandler instance for this file.
Definition File.php:1545
static newForBacklinks(PageReference $page, $table, $params=[])
static singleton( $domain=false)
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition Language.php:42
static queueRecursiveJobsForTable(PageIdentity $page, $table, $action='unknown', $userName='unknown', ?BacklinkCache $backlinkCache=null)
Queue a RefreshLinks job for any table.
Helper class for file deletion.
Helper class for file movement.
Helper class for file undeletion.
Class to represent a local file in the wiki's own database.
Definition LocalFile.php:63
exists()
canRender inherited
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info.
string $major_mime
Major MIME type.
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.
const VERSION
Definition LocalFile.php:64
string $mime
MIME type, determined by MimeAnalyzer::guessMimeType.
Definition LocalFile.php:99
reserializeMetadata()
Write the metadata back to the database with the current serialization format.
isMissing()
splitMime inherited
isMetadataOversize()
Determine whether the loaded metadata may be a candidate for splitting, by measuring its serialized s...
getDescriptionUrl()
isMultipage inherited
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
getMutableCacheKeys(WANObjectCache $cache)
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object.
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...
bool $upgrading
Whether the row was scheduled to upgrade on load.
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition LocalFile.php:96
deleteFile( $reason, UserIdentity $user, $suppress=false)
Delete all versions of the file.
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
getDescriptionTouched()
const LOAD_ALL
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)
string $minor_mime
Minor MIME type.
jsonDecode(string $s)
Do JSON decoding with local flags.
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
getThumbnails( $archiveName=false)
getTransformScript inherited
bool $upgraded
Whether the row was upgraded on load.
static newFromTitle( $title, $repo, $unused=null)
Create a LocalFile from a title Do not call this except from inside a repo class.
purgeMetadataCache()
Refresh metadata in memcached, but don't touch thumbnails or CDN.
getMetadataForDb(IDatabase $db)
Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.
string $timestamp
Upload timestamp.
jsonEncode( $data)
Do JSON encoding with local flags.
int $height
Image height.
Definition LocalFile.php:90
const ATOMIC_SECTION_LOCK
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.
UserIdentity null $user
Uploader.
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
string $description
Description of current revision of the file.
const CACHE_FIELD_MAX_LEN
Definition LocalFile.php:66
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
IResultWrapper null $historyRes
Result of the query for the file's history (nextHistoryLine)
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.
loadExtraFieldsWithTimestamp( $dbr, $fname)
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.
int $historyLine
Number of line to return by nextHistoryLine() (constructor)
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.
bool $locked
True if the image row is locked.
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
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.
getJsonMetadata()
Get metadata in JSON format ready for DB insertion, optionally splitting items out to BlobStore.
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:93
getMetadataItems(array $itemNames)
Get multiple elements of the unserialized handler-specific metadata.
bool $missing
True if file is not present in file system.
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:87
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.
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
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:84
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,...
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Page revision base class.
Service for looking up page revisions.
Value object representing a user's identity.
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:44
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition Status.php:62
Job for asynchronous rendering of thumbnails.
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition Title.php:383
static newFromAnyId( $userId, $userName, $actorId, $dbDomain=false)
Static factory method for creation from an ID, name, and/or actor ID.
Definition User.php:713
Multi-datacenter aware caching interface.
Special handling for file pages.
Relational database abstraction object.
Definition Database.php:52
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.
Service for loading and storing data blobs.
Definition BlobStore.php:35
Interface for objects representing user identity.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
Result wrapper for grabbing data queried from an IDatabase object.
$cache
Definition mcc.php:33
foreach( $mmfl['setupFiles'] as $fileName) if($queue) if(empty( $mmfl['quiet'])) $s
$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