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