MediaWiki  master
LocalFile.php
Go to the documentation of this file.
1 <?php
33 
60 class LocalFile extends File {
61  private const VERSION = 13; // cache version
62 
63  private const CACHE_FIELD_MAX_LEN = 1000;
64 
66  private const MDS_EMPTY = 'empty';
67 
69  private const MDS_LEGACY = 'legacy';
70 
72  private const MDS_PHP = 'php';
73 
75  private const MDS_JSON = 'json';
76 
78  private const MAX_PAGE_RENDER_JOBS = 50;
79 
81  protected $fileExists;
82 
84  protected $width;
85 
87  protected $height;
88 
90  protected $bits;
91 
93  protected $media_type;
94 
96  protected $mime;
97 
99  protected $size;
100 
102  protected $metadataArray = [];
103 
111 
113  protected $metadataBlobs = [];
114 
121  protected $unloadedMetadataBlobs = [];
122 
124  protected $sha1;
125 
127  protected $dataLoaded = false;
128 
130  protected $extraDataLoaded = false;
131 
133  protected $deleted;
134 
136  protected $repoClass = LocalRepo::class;
137 
139  private $historyLine = 0;
140 
142  private $historyRes = null;
143 
145  private $major_mime;
146 
148  private $minor_mime;
149 
151  private $timestamp;
152 
154  private $user;
155 
157  private $description;
158 
161 
163  private $upgraded;
164 
166  private $upgrading;
167 
169  private $locked;
170 
172  private $lockedOwnTrx;
173 
175  private $missing;
176 
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  $this->metadataStorageHelper = new MetadataStorageHelper( $repo );
321 
322  $this->assertRepoDefined();
323  $this->assertTitleDefined();
324  }
325 
329  public function getRepo() {
330  return $this->repo;
331  }
332 
339  protected function getCacheKey() {
340  return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
341  }
342 
349  return [ $this->getCacheKey() ];
350  }
351 
355  private function loadFromCache() {
356  $this->dataLoaded = false;
357  $this->extraDataLoaded = false;
358 
359  $key = $this->getCacheKey();
360  if ( !$key ) {
361  $this->loadFromDB( self::READ_NORMAL );
362 
363  return;
364  }
365 
366  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
367  $cachedValues = $cache->getWithSetCallback(
368  $key,
369  $cache::TTL_WEEK,
370  function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
371  $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
372 
373  $this->loadFromDB( self::READ_NORMAL );
374 
375  $fields = $this->getCacheFields( '' );
376  $cacheVal = [];
377  $cacheVal['fileExists'] = $this->fileExists;
378  if ( $this->fileExists ) {
379  foreach ( $fields as $field ) {
380  $cacheVal[$field] = $this->$field;
381  }
382  }
383  if ( $this->user ) {
384  $cacheVal['user'] = $this->user->getId();
385  $cacheVal['user_text'] = $this->user->getName();
386  }
387 
388  // Don't cache metadata items stored as blobs, since they tend to be large
389  if ( $this->metadataBlobs ) {
390  $cacheVal['metadata'] = array_diff_key(
391  $this->metadataArray, $this->metadataBlobs );
392  // Save the blob addresses
393  $cacheVal['metadataBlobs'] = $this->metadataBlobs;
394  } else {
395  $cacheVal['metadata'] = $this->metadataArray;
396  }
397 
398  // Strip off excessive entries from the subset of fields that can become large.
399  // If the cache value gets too large and might not fit in the cache,
400  // causing repeat database queries for each access to the file.
401  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
402  if ( isset( $cacheVal[$field] )
403  && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
404  ) {
405  unset( $cacheVal[$field] ); // don't let the value get too big
406  if ( $field === 'metadata' ) {
407  unset( $cacheVal['metadataBlobs'] );
408  }
409  }
410  }
411 
412  if ( $this->fileExists ) {
413  $ttl = $cache->adaptiveTTL( (int)wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
414  } else {
415  $ttl = $cache::TTL_DAY;
416  }
417 
418  return $cacheVal;
419  },
420  [ 'version' => self::VERSION ]
421  );
422 
423  $this->fileExists = $cachedValues['fileExists'];
424  if ( $this->fileExists ) {
425  $this->setProps( $cachedValues );
426  }
427 
428  $this->dataLoaded = true;
429  $this->extraDataLoaded = true;
430  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
431  $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
432  }
433  }
434 
438  public function invalidateCache() {
439  $key = $this->getCacheKey();
440  if ( !$key ) {
441  return;
442  }
443 
444  $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
445  static function () use ( $key ) {
446  MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
447  },
448  __METHOD__
449  );
450  }
451 
459  public function loadFromFile( $path = null ) {
460  $props = $this->repo->getFileProps( $path ?? $this->getVirtualUrl() );
461  $this->setProps( $props );
462  }
463 
471  protected function getCacheFields( $prefix = 'img_' ) {
472  if ( $prefix !== '' ) {
473  throw new InvalidArgumentException(
474  __METHOD__ . ' with a non-empty prefix is no longer supported.'
475  );
476  }
477 
478  // See self::getQueryInfo() for the fetching of the data from the DB,
479  // self::loadFromRow() for the loading of the object from the DB row,
480  // and self::loadFromCache() for the caching, and self::setProps() for
481  // populating the object from an array of data.
482  return [ 'size', 'width', 'height', 'bits', 'media_type',
483  'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
484  }
485 
493  protected function getLazyCacheFields( $prefix = 'img_' ) {
494  if ( $prefix !== '' ) {
495  throw new InvalidArgumentException(
496  __METHOD__ . ' with a non-empty prefix is no longer supported.'
497  );
498  }
499 
500  // Keep this in sync with the omit-lazy option in self::getQueryInfo().
501  return [ 'metadata' ];
502  }
503 
509  protected function loadFromDB( $flags = 0 ) {
510  $fname = static::class . '::' . __FUNCTION__;
511 
512  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
513  $this->dataLoaded = true;
514  $this->extraDataLoaded = true;
515 
516  $dbr = ( $flags & self::READ_LATEST )
517  ? $this->repo->getPrimaryDB()
518  : $this->repo->getReplicaDB();
519 
520  $fileQuery = static::getQueryInfo();
521  $row = $dbr->selectRow(
522  $fileQuery['tables'],
523  $fileQuery['fields'],
524  [ 'img_name' => $this->getName() ],
525  $fname,
526  [],
527  $fileQuery['joins']
528  );
529 
530  if ( $row ) {
531  $this->loadFromRow( $row );
532  } else {
533  $this->fileExists = false;
534  }
535  }
536 
542  protected function loadExtraFromDB() {
543  if ( !$this->title ) {
544  return; // Avoid hard failure when the file does not exist. T221812
545  }
546 
547  $fname = static::class . '::' . __FUNCTION__;
548 
549  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
550  $this->extraDataLoaded = true;
551 
552  $db = $this->repo->getReplicaDB();
553  $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
554  if ( !$fieldMap ) {
555  $db = $this->repo->getPrimaryDB();
556  $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
557  }
558 
559  if ( $fieldMap ) {
560  if ( isset( $fieldMap['metadata'] ) ) {
561  $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
562  }
563  } else {
564  throw new MWException( "Could not find data for image '{$this->getName()}'." );
565  }
566  }
567 
573  private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
574  $fieldMap = false;
575 
576  $fileQuery = self::getQueryInfo( [ 'omit-nonlazy' ] );
577  $row = $dbr->selectRow(
578  $fileQuery['tables'],
579  $fileQuery['fields'],
580  [
581  'img_name' => $this->getName(),
582  'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
583  ],
584  $fname,
585  [],
586  $fileQuery['joins']
587  );
588  if ( $row ) {
589  $fieldMap = $this->unprefixRow( $row, 'img_' );
590  } else {
591  # File may have been uploaded over in the meantime; check the old versions
592  $fileQuery = OldLocalFile::getQueryInfo( [ 'omit-nonlazy' ] );
593  $row = $dbr->selectRow(
594  $fileQuery['tables'],
595  $fileQuery['fields'],
596  [
597  'oi_name' => $this->getName(),
598  'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
599  ],
600  $fname,
601  [],
602  $fileQuery['joins']
603  );
604  if ( $row ) {
605  $fieldMap = $this->unprefixRow( $row, 'oi_' );
606  }
607  }
608 
609  return $fieldMap;
610  }
611 
618  protected function unprefixRow( $row, $prefix = 'img_' ) {
619  $array = (array)$row;
620  $prefixLength = strlen( $prefix );
621 
622  // Double check prefix once
623  if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
624  throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
625  }
626 
627  $decoded = [];
628  foreach ( $array as $name => $value ) {
629  $decoded[substr( $name, $prefixLength )] = $value;
630  }
631 
632  return $decoded;
633  }
634 
650  public function loadFromRow( $row, $prefix = 'img_' ) {
651  $this->dataLoaded = true;
652 
653  $unprefixed = $this->unprefixRow( $row, $prefix );
654 
655  $this->name = $unprefixed['name'];
656  $this->media_type = $unprefixed['media_type'];
657 
658  $services = MediaWikiServices::getInstance();
659  $this->description = $services->getCommentStore()
660  ->getComment( "{$prefix}description", $row )->text;
661 
662  $this->user = $services->getUserFactory()->newFromAnyId(
663  $unprefixed['user'] ?? null,
664  $unprefixed['user_text'] ?? null,
665  $unprefixed['actor'] ?? null
666  );
667 
668  $this->timestamp = wfTimestamp( TS_MW, $unprefixed['timestamp'] );
669 
671  $this->repo->getReplicaDB(), $unprefixed['metadata'] );
672 
673  if ( empty( $unprefixed['major_mime'] ) ) {
674  $this->major_mime = 'unknown';
675  $this->minor_mime = 'unknown';
676  $this->mime = 'unknown/unknown';
677  } else {
678  if ( !$unprefixed['minor_mime'] ) {
679  $unprefixed['minor_mime'] = 'unknown';
680  }
681  $this->major_mime = $unprefixed['major_mime'];
682  $this->minor_mime = $unprefixed['minor_mime'];
683  $this->mime = $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
684  }
685 
686  // Trim zero padding from char/binary field
687  $this->sha1 = rtrim( $unprefixed['sha1'], "\0" );
688 
689  // Normalize some fields to integer type, per their database definition.
690  // Use unary + so that overflows will be upgraded to double instead of
691  // being truncated as with intval(). This is important to allow > 2 GiB
692  // files on 32-bit systems.
693  $this->size = +$unprefixed['size'];
694  $this->width = +$unprefixed['width'];
695  $this->height = +$unprefixed['height'];
696  $this->bits = +$unprefixed['bits'];
697 
698  // Check for extra fields (deprecated since MW 1.37)
699  $extraFields = array_diff(
700  array_keys( $unprefixed ),
701  [
702  'name', 'media_type', 'description_text', 'description_data',
703  'description_cid', 'user', 'user_text', 'actor', 'timestamp',
704  'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
705  'height', 'bits'
706  ]
707  );
708  if ( $extraFields ) {
710  'Passing extra fields (' .
711  implode( ', ', $extraFields )
712  . ') to ' . __METHOD__ . ' was deprecated in MediaWiki 1.37. ' .
713  'Property assignment will be removed in a later version.',
714  '1.37' );
715  foreach ( $extraFields as $field ) {
716  $this->$field = $unprefixed[$field];
717  }
718  }
719 
720  $this->fileExists = true;
721  }
722 
728  public function load( $flags = 0 ) {
729  if ( !$this->dataLoaded ) {
730  if ( $flags & self::READ_LATEST ) {
731  $this->loadFromDB( $flags );
732  } else {
733  $this->loadFromCache();
734  }
735  }
736 
737  if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
738  // @note: loads on name/timestamp to reduce race condition problems
739  $this->loadExtraFromDB();
740  }
741  }
742 
747  public function maybeUpgradeRow() {
748  if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() || $this->upgrading ) {
749  return;
750  }
751 
752  $upgrade = false;
753  $reserialize = false;
754  if ( $this->media_type === null || $this->mime == 'image/svg' ) {
755  $upgrade = true;
756  } else {
757  $handler = $this->getHandler();
758  if ( $handler ) {
759  $validity = $handler->isFileMetadataValid( $this );
760  if ( $validity === MediaHandler::METADATA_BAD ) {
761  $upgrade = true;
762  } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE
763  && $this->repo->isMetadataUpdateEnabled()
764  ) {
765  $upgrade = true;
766  } elseif ( $this->repo->isJsonMetadataEnabled()
767  && $this->repo->isMetadataReserializeEnabled()
768  ) {
769  if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
770  $reserialize = true;
771  } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
772  $this->metadataSerializationFormat !== self::MDS_JSON ) {
773  $reserialize = true;
774  }
775  }
776  }
777  }
778 
779  if ( $upgrade || $reserialize ) {
780  $this->upgrading = true;
781  // Defer updates unless in auto-commit CLI mode
782  DeferredUpdates::addCallableUpdate( function () use ( $upgrade ) {
783  $this->upgrading = false; // avoid duplicate updates
784  try {
785  if ( $upgrade ) {
786  $this->upgradeRow();
787  } else {
788  $this->reserializeMetadata();
789  }
790  } catch ( LocalFileLockError $e ) {
791  // let the other process handle it (or do it next time)
792  }
793  } );
794  }
795  }
796 
800  public function getUpgraded() {
801  return $this->upgraded;
802  }
803 
808  public function upgradeRow() {
809  $dbw = $this->repo->getPrimaryDB();
810 
811  // Make a DB query condition that will fail to match the image row if the
812  // image was reuploaded while the upgrade was in process.
813  $freshnessCondition = [ 'img_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ];
814 
815  $this->loadFromFile();
816 
817  # Don't destroy file info of missing files
818  if ( !$this->fileExists ) {
819  wfDebug( __METHOD__ . ": file does not exist, aborting" );
820 
821  return;
822  }
823 
824  list( $major, $minor ) = self::splitMime( $this->mime );
825 
826  wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
827 
828  $dbw->update( 'image',
829  [
830  'img_size' => $this->size,
831  'img_width' => $this->width,
832  'img_height' => $this->height,
833  'img_bits' => $this->bits,
834  'img_media_type' => $this->media_type,
835  'img_major_mime' => $major,
836  'img_minor_mime' => $minor,
837  'img_metadata' => $this->getMetadataForDb( $dbw ),
838  'img_sha1' => $this->sha1,
839  ],
840  array_merge(
841  [ 'img_name' => $this->getName() ],
842  $freshnessCondition
843  ),
844  __METHOD__
845  );
846 
847  $this->invalidateCache();
848 
849  $this->upgraded = true; // avoid rework/retries
850  }
851 
856  protected function reserializeMetadata() {
857  if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
858  return;
859  }
860  $dbw = $this->repo->getPrimaryDB();
861  $dbw->update(
862  'image',
863  [ 'img_metadata' => $this->getMetadataForDb( $dbw ) ],
864  [
865  'img_name' => $this->name,
866  'img_timestamp' => $dbw->timestamp( $this->timestamp ),
867  ],
868  __METHOD__
869  );
870  $this->upgraded = true;
871  }
872 
884  protected function setProps( $info ) {
885  $this->dataLoaded = true;
886  $fields = $this->getCacheFields( '' );
887  $fields[] = 'fileExists';
888 
889  foreach ( $fields as $field ) {
890  if ( isset( $info[$field] ) ) {
891  $this->$field = $info[$field];
892  }
893  }
894 
895  // Only our own cache sets these properties, so they both should be present.
896  if ( isset( $info['user'] ) &&
897  isset( $info['user_text'] ) &&
898  $info['user_text'] !== ''
899  ) {
900  $this->user = new UserIdentityValue( $info['user'], $info['user_text'] );
901  }
902 
903  // Fix up mime fields
904  if ( isset( $info['major_mime'] ) ) {
905  $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
906  } elseif ( isset( $info['mime'] ) ) {
907  $this->mime = $info['mime'];
908  list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
909  }
910 
911  if ( isset( $info['metadata'] ) ) {
912  if ( is_string( $info['metadata'] ) ) {
913  $this->loadMetadataFromString( $info['metadata'] );
914  } elseif ( is_array( $info['metadata'] ) ) {
915  $this->metadataArray = $info['metadata'];
916  if ( isset( $info['metadataBlobs'] ) ) {
917  $this->metadataBlobs = $info['metadataBlobs'];
918  $this->unloadedMetadataBlobs = array_diff_key(
919  $this->metadataBlobs,
920  $this->metadataArray
921  );
922  } else {
923  $this->metadataBlobs = [];
924  $this->unloadedMetadataBlobs = [];
925  }
926  } else {
927  $logger = LoggerFactory::getInstance( 'LocalFile' );
928  $logger->warning( __METHOD__ . ' given invalid metadata of type ' .
929  gettype( $info['metadata'] ) );
930  $this->metadataArray = [];
931  }
932  $this->extraDataLoaded = true;
933  }
934  }
935 
951  public function isMissing() {
952  if ( $this->missing === null ) {
953  $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
954  $this->missing = !$fileExists;
955  }
956 
957  return $this->missing;
958  }
959 
967  public function getWidth( $page = 1 ) {
968  $page = (int)$page;
969  if ( $page < 1 ) {
970  $page = 1;
971  }
972 
973  $this->load();
974 
975  if ( $this->isMultipage() ) {
976  $handler = $this->getHandler();
977  if ( !$handler ) {
978  return 0;
979  }
980  $dim = $handler->getPageDimensions( $this, $page );
981  if ( $dim ) {
982  return $dim['width'];
983  } else {
984  // For non-paged media, the false goes through an
985  // intval, turning failure into 0, so do same here.
986  return 0;
987  }
988  } else {
989  return $this->width;
990  }
991  }
992 
1000  public function getHeight( $page = 1 ) {
1001  $page = (int)$page;
1002  if ( $page < 1 ) {
1003  $page = 1;
1004  }
1005 
1006  $this->load();
1007 
1008  if ( $this->isMultipage() ) {
1009  $handler = $this->getHandler();
1010  if ( !$handler ) {
1011  return 0;
1012  }
1013  $dim = $handler->getPageDimensions( $this, $page );
1014  if ( $dim ) {
1015  return $dim['height'];
1016  } else {
1017  // For non-paged media, the false goes through an
1018  // intval, turning failure into 0, so do same here.
1019  return 0;
1020  }
1021  } else {
1022  return $this->height;
1023  }
1024  }
1025 
1033  public function getDescriptionShortUrl() {
1034  if ( !$this->title ) {
1035  return null; // Avoid hard failure when the file does not exist. T221812
1036  }
1037 
1038  $pageId = $this->title->getArticleID();
1039 
1040  if ( $pageId ) {
1041  $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
1042  if ( $url !== false ) {
1043  return $url;
1044  }
1045  }
1046  return null;
1047  }
1048 
1055  public function getMetadata() {
1056  $data = $this->getMetadataArray();
1057  if ( !$data ) {
1058  return '';
1059  } elseif ( array_keys( $data ) === [ '_error' ] ) {
1060  // Legacy error encoding
1061  return $data['_error'];
1062  } else {
1063  return serialize( $this->getMetadataArray() );
1064  }
1065  }
1066 
1073  public function getMetadataArray(): array {
1074  $this->load( self::LOAD_ALL );
1075  if ( $this->unloadedMetadataBlobs ) {
1076  return $this->getMetadataItems(
1077  array_unique( array_merge(
1078  array_keys( $this->metadataArray ),
1079  array_keys( $this->unloadedMetadataBlobs )
1080  ) )
1081  );
1082  }
1083  return $this->metadataArray;
1084  }
1085 
1086  public function getMetadataItems( array $itemNames ): array {
1087  $this->load( self::LOAD_ALL );
1088  $result = [];
1089  $addresses = [];
1090  foreach ( $itemNames as $itemName ) {
1091  if ( array_key_exists( $itemName, $this->metadataArray ) ) {
1092  $result[$itemName] = $this->metadataArray[$itemName];
1093  } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
1094  $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
1095  }
1096  }
1097 
1098  if ( $addresses ) {
1099  $resultFromBlob = $this->metadataStorageHelper->getMetadataFromBlobStore( $addresses );
1100  foreach ( $addresses as $itemName => $address ) {
1101  unset( $this->unloadedMetadataBlobs[$itemName] );
1102  $value = $resultFromBlob[$itemName] ?? null;
1103  if ( $value !== null ) {
1104  $result[$itemName] = $value;
1105  $this->metadataArray[$itemName] = $value;
1106  }
1107  }
1108  }
1109  return $result;
1110  }
1111 
1123  public function getMetadataForDb( IDatabase $db ) {
1124  $this->load( self::LOAD_ALL );
1125  if ( !$this->metadataArray && !$this->metadataBlobs ) {
1126  $s = '';
1127  } elseif ( $this->repo->isJsonMetadataEnabled() ) {
1128  $s = $this->getJsonMetadata();
1129  } else {
1130  $s = serialize( $this->getMetadataArray() );
1131  }
1132  if ( !is_string( $s ) ) {
1133  throw new MWException( 'Could not serialize image metadata value for DB' );
1134  }
1135  return $db->encodeBlob( $s );
1136  }
1137 
1144  private function getJsonMetadata() {
1145  // Directly store data that is not already in BlobStore
1146  $envelope = [
1147  'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
1148  ];
1149 
1150  // Also store the blob addresses
1151  if ( $this->metadataBlobs ) {
1152  $envelope['blobs'] = $this->metadataBlobs;
1153  }
1154 
1155  list( $s, $blobAddresses ) = $this->metadataStorageHelper->getJsonMetadata( $this, $envelope );
1156 
1157  // Repeated calls to this function should not keep inserting more blobs
1158  $this->metadataBlobs += $blobAddresses;
1159 
1160  return $s;
1161  }
1162 
1169  private function isMetadataOversize() {
1170  if ( !$this->repo->isSplitMetadataEnabled() ) {
1171  return false;
1172  }
1173  $threshold = $this->repo->getSplitMetadataThreshold();
1174  $directItems = array_diff_key( $this->metadataArray, $this->metadataBlobs );
1175  foreach ( $directItems as $value ) {
1176  if ( strlen( $this->metadataStorageHelper->jsonEncode( $value ) ) > $threshold ) {
1177  return true;
1178  }
1179  }
1180  return false;
1181  }
1182 
1191  protected function loadMetadataFromDbFieldValue( IDatabase $db, $metadataBlob ) {
1192  $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
1193  }
1194 
1202  protected function loadMetadataFromString( $metadataString ) {
1203  $this->extraDataLoaded = true;
1204  $this->metadataArray = [];
1205  $this->metadataBlobs = [];
1206  $this->unloadedMetadataBlobs = [];
1207  $metadataString = (string)$metadataString;
1208  if ( $metadataString === '' ) {
1209  $this->metadataSerializationFormat = self::MDS_EMPTY;
1210  return;
1211  }
1212  if ( $metadataString[0] === '{' ) {
1213  $envelope = $this->metadataStorageHelper->jsonDecode( $metadataString );
1214  if ( !$envelope ) {
1215  // Legacy error encoding
1216  $this->metadataArray = [ '_error' => $metadataString ];
1217  $this->metadataSerializationFormat = self::MDS_LEGACY;
1218  } else {
1219  $this->metadataSerializationFormat = self::MDS_JSON;
1220  if ( isset( $envelope['data'] ) ) {
1221  $this->metadataArray = $envelope['data'];
1222  }
1223  if ( isset( $envelope['blobs'] ) ) {
1224  $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope['blobs'];
1225  }
1226  }
1227  } else {
1228  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1229  $data = @unserialize( $metadataString );
1230  if ( !is_array( $data ) ) {
1231  // Legacy error encoding
1232  $data = [ '_error' => $metadataString ];
1233  $this->metadataSerializationFormat = self::MDS_LEGACY;
1234  } else {
1235  $this->metadataSerializationFormat = self::MDS_PHP;
1236  }
1237  $this->metadataArray = $data;
1238  }
1239  }
1240 
1245  public function getBitDepth() {
1246  $this->load();
1247 
1248  return (int)$this->bits;
1249  }
1250 
1256  public function getSize() {
1257  $this->load();
1258 
1259  return $this->size;
1260  }
1261 
1267  public function getMimeType() {
1268  $this->load();
1269 
1270  return $this->mime;
1271  }
1272 
1279  public function getMediaType() {
1280  $this->load();
1281 
1282  return $this->media_type;
1283  }
1284 
1296  public function exists() {
1297  $this->load();
1298 
1299  return $this->fileExists;
1300  }
1301 
1318  protected function getThumbnails( $archiveName = false ) {
1319  if ( $archiveName ) {
1320  $dir = $this->getArchiveThumbPath( $archiveName );
1321  } else {
1322  $dir = $this->getThumbPath();
1323  }
1324 
1325  $backend = $this->repo->getBackend();
1326  $files = [ $dir ];
1327  try {
1328  $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1329  if ( $iterator !== null ) {
1330  foreach ( $iterator as $file ) {
1331  $files[] = $file;
1332  }
1333  }
1334  } catch ( FileBackendError $e ) {
1335  } // suppress (T56674)
1336 
1337  return $files;
1338  }
1339 
1343  private function purgeMetadataCache() {
1344  $this->invalidateCache();
1345  }
1346 
1355  public function purgeCache( $options = [] ) {
1356  // Refresh metadata cache
1357  $this->maybeUpgradeRow();
1358  $this->purgeMetadataCache();
1359 
1360  // Delete thumbnails
1361  $this->purgeThumbnails( $options );
1362 
1363  // Purge CDN cache for this file
1364  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1365  $hcu->purgeUrls(
1366  $this->getUrl(),
1367  !empty( $options['forThumbRefresh'] )
1368  ? $hcu::PURGE_PRESEND // just a manual purge
1369  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1370  );
1371  }
1372 
1378  public function purgeOldThumbnails( $archiveName ) {
1379  // Get a list of old thumbnails
1380  $thumbs = $this->getThumbnails( $archiveName );
1381 
1382  // Delete thumbnails from storage, and prevent the directory itself from being purged
1383  $dir = array_shift( $thumbs );
1384  $this->purgeThumbList( $dir, $thumbs );
1385 
1386  $urls = [];
1387  foreach ( $thumbs as $thumb ) {
1388  $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1389  }
1390 
1391  // Purge any custom thumbnail caches
1392  $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1393 
1394  // Purge the CDN
1395  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1396  $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1397  }
1398 
1405  public function purgeThumbnails( $options = [] ) {
1406  $thumbs = $this->getThumbnails();
1407 
1408  // Delete thumbnails from storage, and prevent the directory itself from being purged
1409  $dir = array_shift( $thumbs );
1410  $this->purgeThumbList( $dir, $thumbs );
1411 
1412  // Always purge all files from CDN regardless of handler filters
1413  $urls = [];
1414  foreach ( $thumbs as $thumb ) {
1415  $urls[] = $this->getThumbUrl( $thumb );
1416  }
1417 
1418  // Give the media handler a chance to filter the file purge list
1419  if ( !empty( $options['forThumbRefresh'] ) ) {
1420  $handler = $this->getHandler();
1421  if ( $handler ) {
1422  $handler->filterThumbnailPurgeList( $thumbs, $options );
1423  }
1424  }
1425 
1426  // Purge any custom thumbnail caches
1427  $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1428 
1429  // Purge the CDN
1430  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1431  $hcu->purgeUrls(
1432  $urls,
1433  !empty( $options['forThumbRefresh'] )
1434  ? $hcu::PURGE_PRESEND // just a manual purge
1435  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1436  );
1437  }
1438 
1445  public function prerenderThumbnails() {
1446  $uploadThumbnailRenderMap = MediaWikiServices::getInstance()
1447  ->getMainConfig()->get( MainConfigNames::UploadThumbnailRenderMap );
1448 
1449  $jobs = [];
1450 
1451  $sizes = $uploadThumbnailRenderMap;
1452  rsort( $sizes );
1453 
1454  foreach ( $sizes as $size ) {
1455  if ( $this->isMultipage() ) {
1456  // (T309114) Only trigger render jobs up to MAX_PAGE_RENDER_JOBS to avoid
1457  // a flood of jobs for huge files.
1458  $pageLimit = min( $this->pageCount(), self::MAX_PAGE_RENDER_JOBS );
1459 
1460  for ( $page = 1; $page <= $pageLimit; $page++ ) {
1461  $jobs[] = new ThumbnailRenderJob(
1462  $this->getTitle(),
1463  [ 'transformParams' => [
1464  'width' => $size,
1465  'page' => $page,
1466  ] ]
1467  );
1468  }
1469  } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1470  $jobs[] = new ThumbnailRenderJob(
1471  $this->getTitle(),
1472  [ 'transformParams' => [ 'width' => $size ] ]
1473  );
1474  }
1475  }
1476 
1477  if ( $jobs ) {
1478  MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
1479  }
1480  }
1481 
1488  protected function purgeThumbList( $dir, $files ) {
1489  $fileListDebug = strtr(
1490  var_export( $files, true ),
1491  [ "\n" => '' ]
1492  );
1493  wfDebug( __METHOD__ . ": $fileListDebug" );
1494 
1495  if ( $this->repo->supportsSha1URLs() ) {
1496  $reference = $this->getSha1();
1497  } else {
1498  $reference = $this->getName();
1499  }
1500 
1501  $purgeList = [];
1502  foreach ( $files as $file ) {
1503  # Check that the reference (filename or sha1) is part of the thumb name
1504  # This is a basic check to avoid erasing unrelated directories
1505  if ( strpos( $file, $reference ) !== false
1506  || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1507  ) {
1508  $purgeList[] = "{$dir}/{$file}";
1509  }
1510  }
1511 
1512  # Delete the thumbnails
1513  $this->repo->quickPurgeBatch( $purgeList );
1514  # Clear out the thumbnail directory if empty
1515  $this->repo->quickCleanDir( $dir );
1516  }
1517 
1529  public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1530  if ( !$this->exists() ) {
1531  return []; // Avoid hard failure when the file does not exist. T221812
1532  }
1533 
1534  $dbr = $this->repo->getReplicaDB();
1535  $oldFileQuery = OldLocalFile::getQueryInfo();
1536 
1537  $tables = $oldFileQuery['tables'];
1538  $fields = $oldFileQuery['fields'];
1539  $join_conds = $oldFileQuery['joins'];
1540  $conds = $opts = [];
1541  $eq = $inc ? '=' : '';
1542  $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1543 
1544  if ( $start ) {
1545  $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1546  }
1547 
1548  if ( $end ) {
1549  $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1550  }
1551 
1552  if ( $limit ) {
1553  $opts['LIMIT'] = $limit;
1554  }
1555 
1556  // Search backwards for time > x queries
1557  $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1558  $opts['ORDER BY'] = "oi_timestamp $order";
1559  $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1560 
1561  $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1562  $conds, $opts, $join_conds );
1563 
1564  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1565  $r = [];
1566 
1567  foreach ( $res as $row ) {
1568  $r[] = $this->repo->newFileFromRow( $row );
1569  }
1570 
1571  if ( $order == 'ASC' ) {
1572  $r = array_reverse( $r ); // make sure it ends up descending
1573  }
1574 
1575  return $r;
1576  }
1577 
1588  public function nextHistoryLine() {
1589  if ( !$this->exists() ) {
1590  return false; // Avoid hard failure when the file does not exist. T221812
1591  }
1592 
1593  # Polymorphic function name to distinguish foreign and local fetches
1594  $fname = static::class . '::' . __FUNCTION__;
1595 
1596  $dbr = $this->repo->getReplicaDB();
1597 
1598  if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1599  $fileQuery = self::getQueryInfo();
1600  $this->historyRes = $dbr->select( $fileQuery['tables'],
1601  $fileQuery['fields'] + [
1602  'oi_archive_name' => $dbr->addQuotes( '' ),
1603  'oi_deleted' => 0,
1604  ],
1605  [ 'img_name' => $this->title->getDBkey() ],
1606  $fname,
1607  [],
1608  $fileQuery['joins']
1609  );
1610 
1611  if ( $this->historyRes->numRows() == 0 ) {
1612  $this->historyRes = null;
1613 
1614  return false;
1615  }
1616  } elseif ( $this->historyLine == 1 ) {
1617  $fileQuery = OldLocalFile::getQueryInfo();
1618  $this->historyRes = $dbr->select(
1619  $fileQuery['tables'],
1620  $fileQuery['fields'],
1621  [ 'oi_name' => $this->title->getDBkey() ],
1622  $fname,
1623  [ 'ORDER BY' => 'oi_timestamp DESC' ],
1624  $fileQuery['joins']
1625  );
1626  }
1627  $this->historyLine++;
1628 
1629  return $this->historyRes->fetchObject();
1630  }
1631 
1636  public function resetHistory() {
1637  $this->historyLine = 0;
1638 
1639  if ( $this->historyRes !== null ) {
1640  $this->historyRes = null;
1641  }
1642  }
1643 
1677  public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1678  $timestamp = false, Authority $uploader = null, $tags = [],
1679  $createNullRevision = true, $revert = false
1680  ) {
1681  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1682  return $this->readOnlyFatalStatus();
1683  } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1684  // Check this in advance to avoid writing to FileBackend and the file tables,
1685  // only to fail on insert the revision due to the text store being unavailable.
1686  return $this->readOnlyFatalStatus();
1687  }
1688 
1689  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1690  if ( !$props ) {
1691  if ( FileRepo::isVirtualUrl( $srcPath )
1692  || FileBackend::isStoragePath( $srcPath )
1693  ) {
1694  $props = $this->repo->getFileProps( $srcPath );
1695  } else {
1696  $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1697  $props = $mwProps->getPropsFromPath( $srcPath, true );
1698  }
1699  }
1700 
1701  $options = [];
1702  $handler = MediaHandler::getHandler( $props['mime'] );
1703  if ( $handler ) {
1704  if ( is_string( $props['metadata'] ) ) {
1705  // This supports callers directly fabricating a metadata
1706  // property using serialize(). Normally the metadata property
1707  // comes from MWFileProps, in which case it won't be a string.
1708  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1709  $metadata = @unserialize( $props['metadata'] );
1710  } else {
1711  $metadata = $props['metadata'];
1712  }
1713 
1714  if ( is_array( $metadata ) ) {
1715  $options['headers'] = $handler->getContentHeaders( $metadata );
1716  }
1717  } else {
1718  $options['headers'] = [];
1719  }
1720 
1721  // Trim spaces on user supplied text
1722  $comment = trim( $comment );
1723 
1724  $status = $this->publish( $src, $flags, $options );
1725 
1726  if ( $status->successCount >= 2 ) {
1727  // There will be a copy+(one of move,copy,store).
1728  // The first succeeding does not commit us to updating the DB
1729  // since it simply copied the current version to a timestamped file name.
1730  // It is only *preferable* to avoid leaving such files orphaned.
1731  // Once the second operation goes through, then the current version was
1732  // updated and we must therefore update the DB too.
1733  $oldver = $status->value;
1734 
1735  if ( $uploader === null ) {
1736  // Uploader argument is optional, fall back to the context authority
1737  $uploader = RequestContext::getMain()->getAuthority();
1738  }
1739 
1740  $uploadStatus = $this->recordUpload3(
1741  $oldver,
1742  $comment,
1743  $pageText,
1744  $uploader,
1745  $props,
1746  $timestamp,
1747  $tags,
1748  $createNullRevision,
1749  $revert
1750  );
1751  if ( !$uploadStatus->isOK() ) {
1752  if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1753  // update filenotfound error with more specific path
1754  $status->fatal( 'filenotfound', $srcPath );
1755  } else {
1756  $status->merge( $uploadStatus );
1757  }
1758  }
1759  }
1760 
1761  return $status;
1762  }
1763 
1780  public function recordUpload3(
1781  string $oldver,
1782  string $comment,
1783  string $pageText,
1784  Authority $performer,
1785  $props = false,
1786  $timestamp = false,
1787  $tags = [],
1788  bool $createNullRevision = true,
1789  bool $revert = false
1790  ): Status {
1791  $dbw = $this->repo->getPrimaryDB();
1792 
1793  # Imports or such might force a certain timestamp; otherwise we generate
1794  # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1795  if ( $timestamp === false ) {
1796  $timestamp = $dbw->timestamp();
1797  $allowTimeKludge = true;
1798  } else {
1799  $allowTimeKludge = false;
1800  }
1801 
1802  $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1803  $props['description'] = $comment;
1804  $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1805  $this->setProps( $props );
1806 
1807  # Fail now if the file isn't there
1808  if ( !$this->fileExists ) {
1809  wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1810 
1811  return Status::newFatal( 'filenotfound', $this->getRel() );
1812  }
1813 
1814  $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1815 
1816  $dbw->startAtomic( __METHOD__ );
1817 
1818  $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1819  $this->user = $performer->getUser();
1820 
1821  # Test to see if the row exists using INSERT IGNORE
1822  # This avoids race conditions by locking the row until the commit, and also
1823  # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1824  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1825  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1826  $actorFields = [ 'img_actor' => $actorId ];
1827  $dbw->insert( 'image',
1828  [
1829  'img_name' => $this->getName(),
1830  'img_size' => $this->size,
1831  'img_width' => intval( $this->width ),
1832  'img_height' => intval( $this->height ),
1833  'img_bits' => $this->bits,
1834  'img_media_type' => $this->media_type,
1835  'img_major_mime' => $this->major_mime,
1836  'img_minor_mime' => $this->minor_mime,
1837  'img_timestamp' => $timestamp,
1838  'img_metadata' => $this->getMetadataForDb( $dbw ),
1839  'img_sha1' => $this->sha1
1840  ] + $commentFields + $actorFields,
1841  __METHOD__,
1842  [ 'IGNORE' ]
1843  );
1844  $reupload = ( $dbw->affectedRows() == 0 );
1845 
1846  if ( $reupload ) {
1847  $row = $dbw->selectRow(
1848  'image',
1849  [ 'img_timestamp', 'img_sha1' ],
1850  [ 'img_name' => $this->getName() ],
1851  __METHOD__,
1852  [ 'LOCK IN SHARE MODE' ]
1853  );
1854 
1855  if ( $row && $row->img_sha1 === $this->sha1 ) {
1856  $dbw->endAtomic( __METHOD__ );
1857  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1858  $title = Title::newFromText( $this->getName(), NS_FILE );
1859  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1860  }
1861 
1862  if ( $allowTimeKludge ) {
1863  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1864  $lUnixtime = $row ? (int)wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1865  # Avoid a timestamp that is not newer than the last version
1866  # TODO: the image/oldimage tables should be like page/revision with an ID field
1867  if ( $lUnixtime && (int)wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1868  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1869  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1870  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1871  }
1872  }
1873 
1874  $tables = [ 'image' ];
1875  $fields = [
1876  'oi_name' => 'img_name',
1877  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1878  'oi_size' => 'img_size',
1879  'oi_width' => 'img_width',
1880  'oi_height' => 'img_height',
1881  'oi_bits' => 'img_bits',
1882  'oi_description_id' => 'img_description_id',
1883  'oi_timestamp' => 'img_timestamp',
1884  'oi_metadata' => 'img_metadata',
1885  'oi_media_type' => 'img_media_type',
1886  'oi_major_mime' => 'img_major_mime',
1887  'oi_minor_mime' => 'img_minor_mime',
1888  'oi_sha1' => 'img_sha1',
1889  'oi_actor' => 'img_actor',
1890  ];
1891  $joins = [];
1892 
1893  # (T36993) Note: $oldver can be empty here, if the previous
1894  # version of the file was broken. Allow registration of the new
1895  # version to continue anyway, because that's better than having
1896  # an image that's not fixable by user operations.
1897  # Collision, this is an update of a file
1898  # Insert previous contents into oldimage
1899  $dbw->insertSelect( 'oldimage', $tables, $fields,
1900  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1901 
1902  # Update the current image row
1903  $dbw->update( 'image',
1904  [
1905  'img_size' => $this->size,
1906  'img_width' => intval( $this->width ),
1907  'img_height' => intval( $this->height ),
1908  'img_bits' => $this->bits,
1909  'img_media_type' => $this->media_type,
1910  'img_major_mime' => $this->major_mime,
1911  'img_minor_mime' => $this->minor_mime,
1912  'img_timestamp' => $timestamp,
1913  'img_metadata' => $this->getMetadataForDb( $dbw ),
1914  'img_sha1' => $this->sha1
1915  ] + $commentFields + $actorFields,
1916  [ 'img_name' => $this->getName() ],
1917  __METHOD__
1918  );
1919  }
1920 
1921  $descTitle = $this->getTitle();
1922  $descId = $descTitle->getArticleID();
1923  $wikiPage = new WikiFilePage( $descTitle );
1924  $wikiPage->setFile( $this );
1925 
1926  // Determine log action. If reupload is done by reverting, use a special log_action.
1927  if ( $revert ) {
1928  $logAction = 'revert';
1929  } elseif ( $reupload ) {
1930  $logAction = 'overwrite';
1931  } else {
1932  $logAction = 'upload';
1933  }
1934  // Add the log entry...
1935  $logEntry = new ManualLogEntry( 'upload', $logAction );
1936  $logEntry->setTimestamp( $this->timestamp );
1937  $logEntry->setPerformer( $performer->getUser() );
1938  $logEntry->setComment( $comment );
1939  $logEntry->setTarget( $descTitle );
1940  // Allow people using the api to associate log entries with the upload.
1941  // Log has a timestamp, but sometimes different from upload timestamp.
1942  $logEntry->setParameters(
1943  [
1944  'img_sha1' => $this->sha1,
1945  'img_timestamp' => $timestamp,
1946  ]
1947  );
1948  // Note we keep $logId around since during new image
1949  // creation, page doesn't exist yet, so log_page = 0
1950  // but we want it to point to the page we're making,
1951  // so we later modify the log entry.
1952  // For a similar reason, we avoid making an RC entry
1953  // now and wait until the page exists.
1954  $logId = $logEntry->insert();
1955 
1956  if ( $descTitle->exists() ) {
1957  if ( $createNullRevision ) {
1958  $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1959  // Use own context to get the action text in content language
1960  $formatter = LogFormatter::newFromEntry( $logEntry );
1961  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1962  $editSummary = $formatter->getPlainActionText();
1963  $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1964  $nullRevRecord = $revStore->newNullRevision(
1965  $dbw,
1966  $descTitle,
1967  $summary,
1968  false,
1969  $performer->getUser()
1970  );
1971 
1972  if ( $nullRevRecord ) {
1973  $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1974 
1975  $this->getHookRunner()->onRevisionFromEditComplete(
1976  $wikiPage,
1977  $inserted,
1978  $inserted->getParentId(),
1979  $performer->getUser(),
1980  $tags
1981  );
1982 
1983  $wikiPage->updateRevisionOn( $dbw, $inserted );
1984  // Associate null revision id
1985  $logEntry->setAssociatedRevId( $inserted->getId() );
1986  }
1987  }
1988 
1989  $newPageContent = null;
1990  } else {
1991  // Make the description page and RC log entry post-commit
1992  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1993  }
1994 
1995  // NOTE: Even after ending this atomic section, we are probably still in the implicit
1996  // transaction started by any prior master query in the request. We cannot yet safely
1997  // schedule jobs, see T263301.
1998  $dbw->endAtomic( __METHOD__ );
1999  $fname = __METHOD__;
2000 
2001  # Do some cache purges after final commit so that:
2002  # a) Changes are more likely to be seen post-purge
2003  # b) They won't cause rollback of the log publish/update above
2004  $purgeUpdate = new AutoCommitUpdate(
2005  $dbw,
2006  __METHOD__,
2008  function () use (
2009  $reupload, $wikiPage, $newPageContent, $comment, $performer,
2010  $logEntry, $logId, $descId, $tags, $fname
2011  ) {
2012  # Update memcache after the commit
2013  $this->invalidateCache();
2014 
2015  $updateLogPage = false;
2016  if ( $newPageContent ) {
2017  # New file page; create the description page.
2018  # There's already a log entry, so don't make a second RC entry
2019  # CDN and file cache for the description page are purged by doUserEditContent.
2020  $status = $wikiPage->doUserEditContent(
2021  $newPageContent,
2022  $performer,
2023  $comment,
2025  );
2026 
2027  if ( isset( $status->value['revision-record'] ) ) {
2029  $revRecord = $status->value['revision-record'];
2030  // Associate new page revision id
2031  $logEntry->setAssociatedRevId( $revRecord->getId() );
2032  }
2033  // This relies on the resetArticleID() call in WikiPage::insertOn(),
2034  // which is triggered on $descTitle by doUserEditContent() above.
2035  if ( isset( $status->value['revision-record'] ) ) {
2037  $revRecord = $status->value['revision-record'];
2038  $updateLogPage = $revRecord->getPageId();
2039  }
2040  } else {
2041  # Existing file page: invalidate description page cache
2042  $title = $wikiPage->getTitle();
2043  $title->invalidateCache();
2044  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2045  $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2046  # Allow the new file version to be patrolled from the page footer
2048  }
2049 
2050  # Update associated rev id. This should be done by $logEntry->insert() earlier,
2051  # but setAssociatedRevId() wasn't called at that point yet...
2052  $logParams = $logEntry->getParameters();
2053  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
2054  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
2055  if ( $updateLogPage ) {
2056  # Also log page, in case where we just created it above
2057  $update['log_page'] = $updateLogPage;
2058  }
2059  $this->getRepo()->getPrimaryDB()->update(
2060  'logging',
2061  $update,
2062  [ 'log_id' => $logId ],
2063  $fname
2064  );
2065  $this->getRepo()->getPrimaryDB()->insert(
2066  'log_search',
2067  [
2068  'ls_field' => 'associated_rev_id',
2069  'ls_value' => (string)$logEntry->getAssociatedRevId(),
2070  'ls_log_id' => $logId,
2071  ],
2072  $fname
2073  );
2074 
2075  # Add change tags, if any
2076  if ( $tags ) {
2077  $logEntry->addTags( $tags );
2078  }
2079 
2080  # Uploads can be patrolled
2081  $logEntry->setIsPatrollable( true );
2082 
2083  # Now that the log entry is up-to-date, make an RC entry.
2084  $logEntry->publish( $logId );
2085 
2086  # Run hook for other updates (typically more cache purging)
2087  $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2088 
2089  if ( $reupload ) {
2090  # Delete old thumbnails
2091  $this->purgeThumbnails();
2092  # Remove the old file from the CDN cache
2093  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2094  $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2095  } else {
2096  # Update backlink pages pointing to this title if created
2097  $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2098  LinksUpdate::queueRecursiveJobsForTable(
2099  $this->getTitle(),
2100  'imagelinks',
2101  'upload-image',
2102  $performer->getUser()->getName(),
2103  $blcFactory->getBacklinkCache( $this->getTitle() )
2104  );
2105  }
2106 
2107  $this->prerenderThumbnails();
2108  }
2109  );
2110 
2111  # Invalidate cache for all pages using this file
2112  $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
2113  $this->getTitle(),
2114  'imagelinks',
2115  [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2116  );
2117 
2118  // NOTE: We are probably still in the implicit transaction started by DBO_TRX. We should
2119  // only schedule jobs after that transaction was committed, so a job queue failure
2120  // doesn't cause the upload to fail (T263301). Also, we should generally not schedule any
2121  // Jobs or the DeferredUpdates that assume the update is complete until after the
2122  // transaction has been committed and we are sure that the upload was indeed successful.
2123  $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2124  DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2125 
2126  if ( !$reupload ) {
2127  // This is a new file, so update the image count
2128  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2129  }
2130 
2131  MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $cacheUpdateJob );
2132  }, __METHOD__ );
2133 
2134  return Status::newGood();
2135  }
2136 
2153  public function publish( $src, $flags = 0, array $options = [] ) {
2154  return $this->publishTo( $src, $this->getRel(), $flags, $options );
2155  }
2156 
2173  protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2174  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
2175 
2176  $repo = $this->getRepo();
2177  if ( $repo->getReadOnlyReason() !== false ) {
2178  return $this->readOnlyFatalStatus();
2179  }
2180 
2181  $status = $this->acquireFileLock();
2182  if ( !$status->isOK() ) {
2183  return $status;
2184  }
2185 
2186  if ( $this->isOld() ) {
2187  $archiveRel = $dstRel;
2188  $archiveName = basename( $archiveRel );
2189  } else {
2190  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
2191  $archiveRel = $this->getArchiveRel( $archiveName );
2192  }
2193 
2194  if ( $repo->hasSha1Storage() ) {
2195  $sha1 = FileRepo::isVirtualUrl( $srcPath )
2196  ? $repo->getFileSha1( $srcPath )
2197  : FSFile::getSha1Base36FromPath( $srcPath );
2199  $wrapperBackend = $repo->getBackend();
2200  '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2201  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2202  $status = $repo->quickImport( $src, $dst );
2203  if ( $flags & File::DELETE_SOURCE ) {
2204  unlink( $srcPath );
2205  }
2206 
2207  if ( $this->exists() ) {
2208  $status->value = $archiveName;
2209  }
2210  } else {
2211  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2212  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2213 
2214  if ( $status->value == 'new' ) {
2215  $status->value = '';
2216  } else {
2217  $status->value = $archiveName;
2218  }
2219  }
2220 
2221  $this->releaseFileLock();
2222  return $status;
2223  }
2224 
2243  public function move( $target ) {
2244  $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2245  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2246  return $this->readOnlyFatalStatus();
2247  }
2248 
2249  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2250  $batch = new LocalFileMoveBatch( $this, $target );
2251 
2252  $status = $batch->addCurrent();
2253  if ( !$status->isOK() ) {
2254  return $status;
2255  }
2256  $archiveNames = $batch->addOlds();
2257  $status = $batch->execute();
2258 
2259  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2260 
2261  // Purge the source and target files outside the transaction...
2262  $oldTitleFile = $localRepo->newFile( $this->title );
2263  $newTitleFile = $localRepo->newFile( $target );
2265  new AutoCommitUpdate(
2266  $this->getRepo()->getPrimaryDB(),
2267  __METHOD__,
2268  static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2269  $oldTitleFile->purgeEverything();
2270  foreach ( $archiveNames as $archiveName ) {
2272  '@phan-var OldLocalFile $oldTitleFile';
2273  $oldTitleFile->purgeOldThumbnails( $archiveName );
2274  }
2275  $newTitleFile->purgeEverything();
2276  }
2277  ),
2278  DeferredUpdates::PRESEND
2279  );
2280 
2281  if ( $status->isOK() ) {
2282  // Now switch the object
2283  $this->title = $target;
2284  // Force regeneration of the name and hashpath
2285  $this->name = null;
2286  $this->hashPath = null;
2287  }
2288 
2289  return $status;
2290  }
2291 
2308  public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2309  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2310  return $this->readOnlyFatalStatus();
2311  }
2312 
2313  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2314 
2315  $batch->addCurrent();
2316  // Get old version relative paths
2317  $archiveNames = $batch->addOlds();
2318  $status = $batch->execute();
2319 
2320  if ( $status->isOK() ) {
2321  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2322  }
2323 
2324  // To avoid slow purges in the transaction, move them outside...
2326  new AutoCommitUpdate(
2327  $this->getRepo()->getPrimaryDB(),
2328  __METHOD__,
2329  function () use ( $archiveNames ) {
2330  $this->purgeEverything();
2331  foreach ( $archiveNames as $archiveName ) {
2332  $this->purgeOldThumbnails( $archiveName );
2333  }
2334  }
2335  ),
2336  DeferredUpdates::PRESEND
2337  );
2338 
2339  // Purge the CDN
2340  $purgeUrls = [];
2341  foreach ( $archiveNames as $archiveName ) {
2342  $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2343  }
2344 
2345  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2346  $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2347 
2348  return $status;
2349  }
2350 
2369  public function deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress = false ) {
2370  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2371  return $this->readOnlyFatalStatus();
2372  }
2373 
2374  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2375 
2376  $batch->addOld( $archiveName );
2377  $status = $batch->execute();
2378 
2379  $this->purgeOldThumbnails( $archiveName );
2380  if ( $status->isOK() ) {
2381  $this->purgeDescription();
2382  }
2383 
2384  $url = $this->getArchiveUrl( $archiveName );
2385  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2386  $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2387 
2388  return $status;
2389  }
2390 
2403  public function restore( $versions = [], $unsuppress = false ) {
2404  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2405  return $this->readOnlyFatalStatus();
2406  }
2407 
2408  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2409 
2410  if ( !$versions ) {
2411  $batch->addAll();
2412  } else {
2413  $batch->addIds( $versions );
2414  }
2415  $status = $batch->execute();
2416  if ( $status->isGood() ) {
2417  $cleanupStatus = $batch->cleanup();
2418  $cleanupStatus->successCount = 0;
2419  $cleanupStatus->failCount = 0;
2420  $status->merge( $cleanupStatus );
2421  }
2422 
2423  return $status;
2424  }
2425 
2436  public function getDescriptionUrl() {
2437  if ( !$this->title ) {
2438  return false; // Avoid hard failure when the file does not exist. T221812
2439  }
2440 
2441  return $this->title->getLocalURL();
2442  }
2443 
2453  public function getDescriptionText( Language $lang = null ) {
2454  if ( !$this->title ) {
2455  return false; // Avoid hard failure when the file does not exist. T221812
2456  }
2457 
2458  $services = MediaWikiServices::getInstance();
2459  $page = $services->getPageStore()->getPageByReference( $this->getTitle() );
2460  if ( !$page ) {
2461  return false;
2462  }
2463 
2464  if ( $lang ) {
2465  $parserOptions = ParserOptions::newFromUserAndLang(
2467  $lang
2468  );
2469  } else {
2471  }
2472 
2473  $parseStatus = $services->getParserOutputAccess()
2474  ->getParserOutput( $page, $parserOptions );
2475 
2476  if ( !$parseStatus->isGood() ) {
2477  // Rendering failed.
2478  return false;
2479  }
2480  return $parseStatus->getValue()->getText();
2481  }
2482 
2490  public function getUploader( int $audience = self::FOR_PUBLIC, Authority $performer = null ): ?UserIdentity {
2491  $this->load();
2492  if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2493  return null;
2494  } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2495  return null;
2496  } else {
2497  return $this->user;
2498  }
2499  }
2500 
2507  public function getDescription( $audience = self::FOR_PUBLIC, Authority $performer = null ) {
2508  $this->load();
2509  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2510  return '';
2511  } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2512  return '';
2513  } else {
2514  return $this->description;
2515  }
2516  }
2517 
2522  public function getTimestamp() {
2523  $this->load();
2524 
2525  return $this->timestamp;
2526  }
2527 
2532  public function getDescriptionTouched() {
2533  if ( !$this->exists() ) {
2534  return false; // Avoid hard failure when the file does not exist. T221812
2535  }
2536 
2537  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2538  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2539  // need to differentiate between null (uninitialized) and false (failed to load).
2540  if ( $this->descriptionTouched === null ) {
2541  $cond = [
2542  'page_namespace' => $this->title->getNamespace(),
2543  'page_title' => $this->title->getDBkey()
2544  ];
2545  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2546  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2547  }
2548 
2549  return $this->descriptionTouched;
2550  }
2551 
2556  public function getSha1() {
2557  $this->load();
2558  return $this->sha1;
2559  }
2560 
2564  public function isCacheable() {
2565  $this->load();
2566 
2567  // If extra data (metadata) was not loaded then it must have been large
2568  return $this->extraDataLoaded
2569  && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2570  }
2571 
2580  public function acquireFileLock( $timeout = 0 ) {
2581  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2582  [ $this->getPath() ], LockManager::LOCK_EX, $timeout
2583  ) );
2584  }
2585 
2592  public function releaseFileLock() {
2593  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2594  [ $this->getPath() ], LockManager::LOCK_EX
2595  ) );
2596  }
2597 
2608  public function lock() {
2609  if ( !$this->locked ) {
2610  $logger = LoggerFactory::getInstance( 'LocalFile' );
2611 
2612  $dbw = $this->repo->getPrimaryDB();
2613  $makesTransaction = !$dbw->trxLevel();
2614  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2615  // T56736: use simple lock to handle when the file does not exist.
2616  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2617  // Also, that would cause contention on INSERT of similarly named rows.
2618  $status = $this->acquireFileLock( 10 ); // represents all versions of the file
2619  if ( !$status->isGood() ) {
2620  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2621  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2622 
2623  throw new LocalFileLockError( $status );
2624  }
2625  // Release the lock *after* commit to avoid row-level contention.
2626  // Make sure it triggers on rollback() as well as commit() (T132921).
2627  $dbw->onTransactionResolution(
2628  function () use ( $logger ) {
2629  $status = $this->releaseFileLock();
2630  if ( !$status->isGood() ) {
2631  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2632  }
2633  },
2634  __METHOD__
2635  );
2636  // Callers might care if the SELECT snapshot is safely fresh
2637  $this->lockedOwnTrx = $makesTransaction;
2638  }
2639 
2640  $this->locked++;
2641 
2642  return $this->lockedOwnTrx;
2643  }
2644 
2655  public function unlock() {
2656  if ( $this->locked ) {
2657  --$this->locked;
2658  if ( !$this->locked ) {
2659  $dbw = $this->repo->getPrimaryDB();
2660  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2661  $this->lockedOwnTrx = false;
2662  }
2663  }
2664  }
2665 
2669  protected function readOnlyFatalStatus() {
2670  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2671  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2672  }
2673 
2677  public function __destruct() {
2678  $this->unlock();
2679  }
2680 }
getUser()
serialize()
unserialize( $serialized)
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.
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:1303
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.
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add an update to the pending update queue that invokes the specified callback when run.
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:48
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:288
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php: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:2462
getName()
Return the name of this file.
Definition: File.php:332
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:2472
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition: File.php:2159
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition: File.php:115
string $path
The storage path corresponding to one of the zones.
Definition: File.php:145
static splitMime( $mime)
Split an internet media type into its two components; if not a two-part name, set the minor type to '...
Definition: File.php:307
Title string bool $title
Definition: File.php:118
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=[])
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:45
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:60
exists()
canRender inherited
Definition: LocalFile.php:1296
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info.
Definition: LocalFile.php:884
string $major_mime
Major MIME type.
Definition: LocalFile.php:145
maybeUpgradeRow()
Upgrade a row if it needs it.
Definition: LocalFile.php:747
static newFromKey( $sha1, $repo, $timestamp=false)
Create a LocalFile from a SHA-1 key Do not call this except from inside a repo class.
Definition: LocalFile.php:233
array $metadataArray
Unserialized metadata.
Definition: LocalFile.php:102
getMediaType()
Returns the type of the media in the file.
Definition: LocalFile.php:1279
string[] $unloadedMetadataBlobs
Map of metadata item name to blob address for items that exist but have not yet been loaded into $thi...
Definition: LocalFile.php:121
deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress=false)
Delete an old version of the file.
Definition: LocalFile.php:2369
move( $target)
getLinksTo inherited
Definition: LocalFile.php:2243
lock()
Start an atomic DB section and lock the image for update or increments a reference counter if the loc...
Definition: LocalFile.php:2608
loadFromRow( $row, $prefix='img_')
Load file metadata from a DB result row.
Definition: LocalFile.php:650
getCacheKey()
Get the memcached key for the main data for this file, or false if there is no access to the shared c...
Definition: LocalFile.php:339
getWidth( $page=1)
Return the width of the image @stable to override.
Definition: LocalFile.php:967
__destruct()
Clean up any dangling locks.
Definition: LocalFile.php:2677
const VERSION
Definition: LocalFile.php:61
string $mime
MIME type, determined by MimeAnalyzer::guessMimeType.
Definition: LocalFile.php:96
reserializeMetadata()
Write the metadata back to the database with the current serialization format.
Definition: LocalFile.php:856
isMissing()
splitMime inherited
Definition: LocalFile.php:951
isMetadataOversize()
Determine whether the loaded metadata may be a candidate for splitting, by measuring its serialized s...
Definition: LocalFile.php:1169
getDescriptionUrl()
isMultipage inherited
Definition: LocalFile.php:2436
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
Definition: LocalFile.php:1529
getMutableCacheKeys(WANObjectCache $cache)
Definition: LocalFile.php:348
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object.
Definition: LocalFile.php:270
releaseFileLock()
Release a lock acquired with acquireFileLock().
Definition: LocalFile.php:2592
getUploader(int $audience=self::FOR_PUBLIC, Authority $performer=null)
Definition: LocalFile.php:2490
loadMetadataFromDbFieldValue(IDatabase $db, $metadataBlob)
Unserialize a metadata blob which came from the database and store it in $this.
Definition: LocalFile.php:1191
loadFromDB( $flags=0)
Load file metadata from the DB.
Definition: LocalFile.php:509
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
Definition: LocalFile.php:728
loadMetadataFromString( $metadataString)
Unserialize a metadata string which came from some non-DB source, or is the return value of IDatabase...
Definition: LocalFile.php:1202
bool $upgrading
Whether the row was scheduled to upgrade on load.
Definition: LocalFile.php:166
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition: LocalFile.php:93
deleteFile( $reason, UserIdentity $user, $suppress=false)
Delete all versions of the file.
Definition: LocalFile.php:2308
acquireFileLock( $timeout=0)
Acquire an exclusive lock on the file, indicating an intention to write to the file backend.
Definition: LocalFile.php:2580
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
Definition: LocalFile.php:1355
getDescriptionTouched()
Definition: LocalFile.php:2532
const LOAD_ALL
Definition: LocalFile.php:181
loadFromFile( $path=null)
Load metadata from the file itself.
Definition: LocalFile.php:459
getBitDepth()
@stable to override
Definition: LocalFile.php:1245
string null $metadataSerializationFormat
One of the MDS_* constants, giving the format of the metadata as stored in the DB,...
Definition: LocalFile.php:110
int $size
Size in bytes (loadFromXxx)
Definition: LocalFile.php:99
string $minor_mime
Minor MIME type.
Definition: LocalFile.php:148
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
Definition: LocalFile.php:1033
getThumbnails( $archiveName=false)
getTransformScript inherited
Definition: LocalFile.php:1318
bool $upgraded
Whether the row was upgraded on load.
Definition: LocalFile.php:163
static newFromTitle( $title, $repo, $unused=null)
Create a LocalFile from a title Do not call this except from inside a repo class.
Definition: LocalFile.php:199
MetadataStorageHelper $metadataStorageHelper
Definition: LocalFile.php:178
purgeMetadataCache()
Refresh metadata in memcached, but don't touch thumbnails or CDN.
Definition: LocalFile.php:1343
getMetadataForDb(IDatabase $db)
Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.
Definition: LocalFile.php:1123
string $timestamp
Upload timestamp.
Definition: LocalFile.php:151
int $height
Image height.
Definition: LocalFile.php:87
const ATOMIC_SECTION_LOCK
Definition: LocalFile.php:183
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
Definition: LocalFile.php:1378
publishTo( $src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
Definition: LocalFile.php:2173
UserIdentity null $user
Uploader.
Definition: LocalFile.php:154
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
Definition: LocalFile.php:1488
string $description
Description of current revision of the file.
Definition: LocalFile.php:157
const CACHE_FIELD_MAX_LEN
Definition: LocalFile.php:63
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
Definition: LocalFile.php:2655
IResultWrapper null $historyRes
Result of the query for the file's history (nextHistoryLine)
Definition: LocalFile.php:142
getLazyCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache, only when they're not too...
Definition: LocalFile.php:493
getSize()
Returns the size of the image file, in bytes @stable to override.
Definition: LocalFile.php:1256
loadExtraFieldsWithTimestamp( $dbr, $fname)
Definition: LocalFile.php:573
invalidateCache()
Purge the file object/metadata cache.
Definition: LocalFile.php:438
getMimeType()
Returns the MIME type of the file.
Definition: LocalFile.php:1267
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
Definition: LocalFile.php:130
int $historyLine
Number of line to return by nextHistoryLine() (constructor)
Definition: LocalFile.php:139
readOnlyFatalStatus()
Definition: LocalFile.php:2669
string $sha1
SHA-1 base 36 content hash.
Definition: LocalFile.php:124
getDescription( $audience=self::FOR_PUBLIC, Authority $performer=null)
Definition: LocalFile.php:2507
getHeight( $page=1)
Return the height of the image @stable to override.
Definition: LocalFile.php:1000
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
Definition: LocalFile.php:1445
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
Definition: LocalFile.php:172
resetHistory()
Reset the history pointer to the first element of the history.
Definition: LocalFile.php:1636
unprefixRow( $row, $prefix='img_')
Definition: LocalFile.php:618
static newFromRow( $row, $repo)
Create a LocalFile from a title Do not call this except from inside a repo class.
Definition: LocalFile.php:214
getJsonMetadata()
Get metadata in JSON format ready for DB insertion, optionally splitting items out to BlobStore.
Definition: LocalFile.php:1144
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
Definition: LocalFile.php:2153
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition: LocalFile.php:2403
getCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache.
Definition: LocalFile.php:471
int $locked
If >= 1 the image row is locked.
Definition: LocalFile.php:169
int $bits
Returned by getimagesize (loadFromXxx)
Definition: LocalFile.php:90
getMetadataItems(array $itemNames)
Get multiple elements of the unserialized handler-specific metadata.
Definition: LocalFile.php:1086
bool $missing
True if file is not present in file system.
Definition: LocalFile.php:175
getDescriptionText(Language $lang=null)
Get the HTML text of the description page This is not used by ImagePage for local files,...
Definition: LocalFile.php:2453
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
Definition: LocalFile.php:1405
loadExtraFromDB()
Load lazy file metadata from the DB.
Definition: LocalFile.php:542
string $repoClass
Definition: LocalFile.php:136
int $width
Image width.
Definition: LocalFile.php:84
nextHistoryLine()
Returns the history of this file, line by line.
Definition: LocalFile.php:1588
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file.
Definition: LocalFile.php:808
int $deleted
Bitfield akin to rev_deleted.
Definition: LocalFile.php:133
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
Definition: LocalFile.php:355
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
Definition: LocalFile.php:160
getMetadata()
Get handler-specific metadata as a serialized string.
Definition: LocalFile.php:1055
getMetadataArray()
Get unserialized handler-specific metadata.
Definition: LocalFile.php:1073
__construct( $title, $repo)
Do not call this except from inside a repo class.
Definition: LocalFile.php:318
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
Definition: LocalFile.php:127
bool $fileExists
Does the file exist on disk? (loadFromXxx)
Definition: LocalFile.php:77
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, Authority $uploader=null, $tags=[], $createNullRevision=true, $revert=false)
getHashPath inherited
Definition: LocalFile.php:1677
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)
Definition: LocalFile.php:1780
string[] $metadataBlobs
Map of metadata item name to blob address.
Definition: LocalFile.php:113
const LOCK_EX
Definition: LockManager.php:72
static makeParamBlob( $params)
Create a blob from a parameter array.
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
MediaWiki exception.
Definition: MWException.php:29
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
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.
const METADATA_BAD
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
Class the manages updates of *_link tables as well as similar extension-managed tables.
Definition: LinksUpdate.php:55
PSR-3 logger instance factory.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Page revision base class.
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 newFromUserAndLang(UserIdentity $user, Language $lang)
Get a ParserOptions object from a given user and language.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
static getMain()
Get the RequestContext object associated with the main request.
static factory(array $deltas)
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
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:370
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:638
Multi-datacenter aware caching interface.
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:39
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
$revStore