MediaWiki  master
LocalFile.php
Go to the documentation of this file.
1 <?php
36 
63 class LocalFile extends File {
64  private const VERSION = 13; // cache version
65 
66  private const CACHE_FIELD_MAX_LEN = 1000;
67 
69  private const MDS_EMPTY = 'empty';
70 
72  private const MDS_LEGACY = 'legacy';
73 
75  private const MDS_PHP = 'php';
76 
78  private const MDS_JSON = 'json';
79 
81  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;
128 
130  protected $extraDataLoaded;
131 
133  protected $deleted;
134 
136  protected $repoClass = LocalRepo::class;
137 
139  private $historyLine;
140 
142  private $historyRes;
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 
177  // @note: higher than IDBAccessObject constants
178  private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
179 
180  private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
181 
196  public static function newFromTitle( $title, $repo, $unused = null ) {
197  return new static( $title, $repo );
198  }
199 
211  public static function newFromRow( $row, $repo ) {
212  $title = Title::makeTitle( NS_FILE, $row->img_name );
213  $file = new static( $title, $repo );
214  $file->loadFromRow( $row );
215 
216  return $file;
217  }
218 
230  public static function newFromKey( $sha1, $repo, $timestamp = false ) {
231  $dbr = $repo->getReplicaDB();
232 
233  $conds = [ 'img_sha1' => $sha1 ];
234  if ( $timestamp ) {
235  $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
236  }
237 
238  $fileQuery = static::getQueryInfo();
239  $row = $dbr->selectRow(
240  $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__, [], $fileQuery['joins']
241  );
242  if ( $row ) {
243  return static::newFromRow( $row, $repo );
244  } else {
245  return false;
246  }
247  }
248 
267  public static function getQueryInfo( array $options = [] ) {
268  $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'img_description' );
269  $ret = [
270  'tables' => [
271  'image',
272  'image_actor' => 'actor'
273  ] + $commentQuery['tables'],
274  'fields' => [
275  'img_name',
276  'img_size',
277  'img_width',
278  'img_height',
279  'img_metadata',
280  'img_bits',
281  'img_media_type',
282  'img_major_mime',
283  'img_minor_mime',
284  'img_timestamp',
285  'img_sha1',
286  'img_actor',
287  'img_user' => 'image_actor.actor_user',
288  'img_user_text' => 'image_actor.actor_name',
289  ] + $commentQuery['fields'],
290  'joins' => [
291  'image_actor' => [ 'JOIN', 'actor_id=img_actor' ]
292  ] + $commentQuery['joins'],
293  ];
294 
295  if ( in_array( 'omit-nonlazy', $options, true ) ) {
296  // Internal use only for getting only the lazy fields
297  $ret['fields'] = [];
298  }
299  if ( !in_array( 'omit-lazy', $options, true ) ) {
300  // Note: Keep this in sync with self::getLazyCacheFields() and
301  // self::loadExtraFromDB()
302  $ret['fields'][] = 'img_metadata';
303  }
304 
305  return $ret;
306  }
307 
315  public function __construct( $title, $repo ) {
316  parent::__construct( $title, $repo );
317 
318  $this->historyLine = 0;
319  $this->historyRes = null;
320  $this->dataLoaded = false;
321  $this->extraDataLoaded = false;
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 
350  return [ $this->getCacheKey() ];
351  }
352 
356  private function loadFromCache() {
357  $this->dataLoaded = false;
358  $this->extraDataLoaded = false;
359 
360  $key = $this->getCacheKey();
361  if ( !$key ) {
362  $this->loadFromDB( self::READ_NORMAL );
363 
364  return;
365  }
366 
367  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
368  $cachedValues = $cache->getWithSetCallback(
369  $key,
370  $cache::TTL_WEEK,
371  function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
372  $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
373 
374  $this->loadFromDB( self::READ_NORMAL );
375 
376  $fields = $this->getCacheFields( '' );
377  $cacheVal = [];
378  $cacheVal['fileExists'] = $this->fileExists;
379  if ( $this->fileExists ) {
380  foreach ( $fields as $field ) {
381  $cacheVal[$field] = $this->$field;
382  }
383  }
384  if ( $this->user ) {
385  $cacheVal['user'] = $this->user->getId();
386  $cacheVal['user_text'] = $this->user->getName();
387  }
388 
389  // Don't cache metadata items stored as blobs, since they tend to be large
390  if ( $this->metadataBlobs ) {
391  $cacheVal['metadata'] = array_diff_key(
392  $this->metadataArray, $this->metadataBlobs );
393  // Save the blob addresses
394  $cacheVal['metadataBlobs'] = $this->metadataBlobs;
395  } else {
396  $cacheVal['metadata'] = $this->metadataArray;
397  }
398 
399  // Strip off excessive entries from the subset of fields that can become large.
400  // If the cache value gets too large and might not fit in the cache,
401  // causing repeat database queries for each access to the file.
402  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
403  if ( isset( $cacheVal[$field] )
404  && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
405  ) {
406  unset( $cacheVal[$field] ); // don't let the value get too big
407  if ( $field === 'metadata' ) {
408  unset( $cacheVal['metadataBlobs'] );
409  }
410  }
411  }
412 
413  if ( $this->fileExists ) {
414  $ttl = $cache->adaptiveTTL( (int)wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
415  } else {
416  $ttl = $cache::TTL_DAY;
417  }
418 
419  return $cacheVal;
420  },
421  [ 'version' => self::VERSION ]
422  );
423 
424  $this->fileExists = $cachedValues['fileExists'];
425  if ( $this->fileExists ) {
426  $this->setProps( $cachedValues );
427  }
428 
429  $this->dataLoaded = true;
430  $this->extraDataLoaded = true;
431  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
432  $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
433  }
434  }
435 
439  public function invalidateCache() {
440  $key = $this->getCacheKey();
441  if ( !$key ) {
442  return;
443  }
444 
445  $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
446  static function () use ( $key ) {
447  MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
448  },
449  __METHOD__
450  );
451  }
452 
460  public function loadFromFile( $path = null ) {
461  $props = $this->repo->getFileProps( $path ?? $this->getVirtualUrl() );
462  $this->setProps( $props );
463  }
464 
472  protected function getCacheFields( $prefix = 'img_' ) {
473  if ( $prefix !== '' ) {
474  throw new InvalidArgumentException(
475  __METHOD__ . ' with a non-empty prefix is no longer supported.'
476  );
477  }
478 
479  // See self::getQueryInfo() for the fetching of the data from the DB,
480  // self::loadFromRow() for the loading of the object from the DB row,
481  // and self::loadFromCache() for the caching, and self::setProps() for
482  // populating the object from an array of data.
483  return [ 'size', 'width', 'height', 'bits', 'media_type',
484  'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
485  }
486 
494  protected function getLazyCacheFields( $prefix = 'img_' ) {
495  if ( $prefix !== '' ) {
496  throw new InvalidArgumentException(
497  __METHOD__ . ' with a non-empty prefix is no longer supported.'
498  );
499  }
500 
501  // Keep this in sync with the omit-lazy option in self::getQueryInfo().
502  return [ 'metadata' ];
503  }
504 
510  protected function loadFromDB( $flags = 0 ) {
511  $fname = static::class . '::' . __FUNCTION__;
512 
513  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
514  $this->dataLoaded = true;
515  $this->extraDataLoaded = true;
516 
517  $dbr = ( $flags & self::READ_LATEST )
518  ? $this->repo->getPrimaryDB()
519  : $this->repo->getReplicaDB();
520 
521  $fileQuery = static::getQueryInfo();
522  $row = $dbr->selectRow(
523  $fileQuery['tables'],
524  $fileQuery['fields'],
525  [ 'img_name' => $this->getName() ],
526  $fname,
527  [],
528  $fileQuery['joins']
529  );
530 
531  if ( $row ) {
532  $this->loadFromRow( $row );
533  } else {
534  $this->fileExists = false;
535  }
536  }
537 
543  protected function loadExtraFromDB() {
544  if ( !$this->title ) {
545  return; // Avoid hard failure when the file does not exist. T221812
546  }
547 
548  $fname = static::class . '::' . __FUNCTION__;
549 
550  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
551  $this->extraDataLoaded = true;
552 
553  $db = $this->repo->getReplicaDB();
554  $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
555  if ( !$fieldMap ) {
556  $db = $this->repo->getPrimaryDB();
557  $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
558  }
559 
560  if ( $fieldMap ) {
561  if ( isset( $fieldMap['metadata'] ) ) {
562  $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
563  }
564  } else {
565  throw new MWException( "Could not find data for image '{$this->getName()}'." );
566  }
567  }
568 
574  private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
575  $fieldMap = false;
576 
577  $fileQuery = self::getQueryInfo( [ 'omit-nonlazy' ] );
578  $row = $dbr->selectRow(
579  $fileQuery['tables'],
580  $fileQuery['fields'],
581  [
582  'img_name' => $this->getName(),
583  'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
584  ],
585  $fname,
586  [],
587  $fileQuery['joins']
588  );
589  if ( $row ) {
590  $fieldMap = $this->unprefixRow( $row, 'img_' );
591  } else {
592  # File may have been uploaded over in the meantime; check the old versions
593  $fileQuery = OldLocalFile::getQueryInfo( [ 'omit-nonlazy' ] );
594  $row = $dbr->selectRow(
595  $fileQuery['tables'],
596  $fileQuery['fields'],
597  [
598  'oi_name' => $this->getName(),
599  'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
600  ],
601  $fname,
602  [],
603  $fileQuery['joins']
604  );
605  if ( $row ) {
606  $fieldMap = $this->unprefixRow( $row, 'oi_' );
607  }
608  }
609 
610  return $fieldMap;
611  }
612 
619  protected function unprefixRow( $row, $prefix = 'img_' ) {
620  $array = (array)$row;
621  $prefixLength = strlen( $prefix );
622 
623  // Double check prefix once
624  if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
625  throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
626  }
627 
628  $decoded = [];
629  foreach ( $array as $name => $value ) {
630  $decoded[substr( $name, $prefixLength )] = $value;
631  }
632 
633  return $decoded;
634  }
635 
651  public function loadFromRow( $row, $prefix = 'img_' ) {
652  $this->dataLoaded = true;
653 
654  $unprefixed = $this->unprefixRow( $row, $prefix );
655 
656  $this->name = $unprefixed['name'];
657  $this->media_type = $unprefixed['media_type'];
658 
659  $services = MediaWikiServices::getInstance();
660  $this->description = $services->getCommentStore()
661  ->getComment( "{$prefix}description", $row )->text;
662 
663  $this->user = $services->getUserFactory()->newFromAnyId(
664  $unprefixed['user'] ?? null,
665  $unprefixed['user_text'] ?? null,
666  $unprefixed['actor'] ?? null
667  );
668 
669  $this->timestamp = wfTimestamp( TS_MW, $unprefixed['timestamp'] );
670 
672  $this->repo->getReplicaDB(), $unprefixed['metadata'] );
673 
674  if ( empty( $unprefixed['major_mime'] ) ) {
675  $this->major_mime = 'unknown';
676  $this->minor_mime = 'unknown';
677  $this->mime = 'unknown/unknown';
678  } else {
679  if ( !$unprefixed['minor_mime'] ) {
680  $unprefixed['minor_mime'] = 'unknown';
681  }
682  $this->major_mime = $unprefixed['major_mime'];
683  $this->minor_mime = $unprefixed['minor_mime'];
684  $this->mime = $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
685  }
686 
687  // Trim zero padding from char/binary field
688  $this->sha1 = rtrim( $unprefixed['sha1'], "\0" );
689 
690  // Normalize some fields to integer type, per their database definition.
691  // Use unary + so that overflows will be upgraded to double instead of
692  // being truncated as with intval(). This is important to allow > 2 GiB
693  // files on 32-bit systems.
694  $this->size = +$unprefixed['size'];
695  $this->width = +$unprefixed['width'];
696  $this->height = +$unprefixed['height'];
697  $this->bits = +$unprefixed['bits'];
698 
699  // Check for extra fields (deprecated since MW 1.37)
700  $extraFields = array_diff(
701  array_keys( $unprefixed ),
702  [
703  'name', 'media_type', 'description_text', 'description_data',
704  'description_cid', 'user', 'user_text', 'actor', 'timestamp',
705  'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
706  'height', 'bits'
707  ]
708  );
709  if ( $extraFields ) {
711  'Passing extra fields (' .
712  implode( ', ', $extraFields )
713  . ') to ' . __METHOD__ . ' was deprecated in MediaWiki 1.37. ' .
714  'Property assignment will be removed in a later version.',
715  '1.37' );
716  foreach ( $extraFields as $field ) {
717  $this->$field = $unprefixed[$field];
718  }
719  }
720 
721  $this->fileExists = true;
722  }
723 
729  public function load( $flags = 0 ) {
730  if ( !$this->dataLoaded ) {
731  if ( $flags & self::READ_LATEST ) {
732  $this->loadFromDB( $flags );
733  } else {
734  $this->loadFromCache();
735  }
736  }
737 
738  if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
739  // @note: loads on name/timestamp to reduce race condition problems
740  $this->loadExtraFromDB();
741  }
742  }
743 
748  public function maybeUpgradeRow() {
749  if ( wfReadOnly() || $this->upgrading ) {
750  return;
751  }
752 
753  $upgrade = false;
754  $reserialize = false;
755  if ( $this->media_type === null || $this->mime == 'image/svg' ) {
756  $upgrade = true;
757  } else {
758  $handler = $this->getHandler();
759  if ( $handler ) {
760  $validity = $handler->isFileMetadataValid( $this );
761  if ( $validity === MediaHandler::METADATA_BAD ) {
762  $upgrade = true;
763  } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE
764  && $this->repo->isMetadataUpdateEnabled()
765  ) {
766  $upgrade = true;
767  } elseif ( $this->repo->isJsonMetadataEnabled()
768  && $this->repo->isMetadataReserializeEnabled()
769  ) {
770  if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
771  $reserialize = true;
772  } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
773  $this->metadataSerializationFormat !== self::MDS_JSON ) {
774  $reserialize = true;
775  }
776  }
777  }
778  }
779 
780  if ( $upgrade || $reserialize ) {
781  $this->upgrading = true;
782  // Defer updates unless in auto-commit CLI mode
783  DeferredUpdates::addCallableUpdate( function () use ( $upgrade ) {
784  $this->upgrading = false; // avoid duplicate updates
785  try {
786  if ( $upgrade ) {
787  $this->upgradeRow();
788  } else {
789  $this->reserializeMetadata();
790  }
791  } catch ( LocalFileLockError $e ) {
792  // let the other process handle it (or do it next time)
793  }
794  } );
795  }
796  }
797 
801  public function getUpgraded() {
802  return $this->upgraded;
803  }
804 
809  public function upgradeRow() {
810  $dbw = $this->repo->getPrimaryDB();
811 
812  // Make a DB query condition that will fail to match the image row if the
813  // image was reuploaded while the upgrade was in process.
814  $freshnessCondition = [ 'img_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ];
815 
816  $this->loadFromFile();
817 
818  # Don't destroy file info of missing files
819  if ( !$this->fileExists ) {
820  wfDebug( __METHOD__ . ": file does not exist, aborting" );
821 
822  return;
823  }
824 
825  list( $major, $minor ) = self::splitMime( $this->mime );
826 
827  wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
828 
829  $dbw->update( 'image',
830  [
831  'img_size' => $this->size,
832  'img_width' => $this->width,
833  'img_height' => $this->height,
834  'img_bits' => $this->bits,
835  'img_media_type' => $this->media_type,
836  'img_major_mime' => $major,
837  'img_minor_mime' => $minor,
838  'img_metadata' => $this->getMetadataForDb( $dbw ),
839  'img_sha1' => $this->sha1,
840  ],
841  array_merge(
842  [ 'img_name' => $this->getName() ],
843  $freshnessCondition
844  ),
845  __METHOD__
846  );
847 
848  $this->invalidateCache();
849 
850  $this->upgraded = true; // avoid rework/retries
851  }
852 
857  protected function reserializeMetadata() {
858  if ( wfReadOnly() ) {
859  return;
860  }
861  $dbw = $this->repo->getPrimaryDB();
862  $dbw->update(
863  'image',
864  [ 'img_metadata' => $this->getMetadataForDb( $dbw ) ],
865  [
866  'img_name' => $this->name,
867  'img_timestamp' => $dbw->timestamp( $this->timestamp ),
868  ],
869  __METHOD__
870  );
871  $this->upgraded = true;
872  }
873 
885  protected function setProps( $info ) {
886  $this->dataLoaded = true;
887  $fields = $this->getCacheFields( '' );
888  $fields[] = 'fileExists';
889 
890  foreach ( $fields as $field ) {
891  if ( isset( $info[$field] ) ) {
892  $this->$field = $info[$field];
893  }
894  }
895 
896  // Only our own cache sets these properties, so they both should be present.
897  if ( isset( $info['user'] ) &&
898  isset( $info['user_text'] ) &&
899  $info['user_text'] !== ''
900  ) {
901  $this->user = new UserIdentityValue( $info['user'], $info['user_text'] );
902  }
903 
904  // Fix up mime fields
905  if ( isset( $info['major_mime'] ) ) {
906  $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
907  } elseif ( isset( $info['mime'] ) ) {
908  $this->mime = $info['mime'];
909  list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
910  }
911 
912  if ( isset( $info['metadata'] ) ) {
913  if ( is_string( $info['metadata'] ) ) {
914  $this->loadMetadataFromString( $info['metadata'] );
915  } elseif ( is_array( $info['metadata'] ) ) {
916  $this->metadataArray = $info['metadata'];
917  if ( isset( $info['metadataBlobs'] ) ) {
918  $this->metadataBlobs = $info['metadataBlobs'];
919  $this->unloadedMetadataBlobs = array_diff_key(
920  $this->metadataBlobs,
921  $this->metadataArray
922  );
923  } else {
924  $this->metadataBlobs = [];
925  $this->unloadedMetadataBlobs = [];
926  }
927  } else {
928  $logger = LoggerFactory::getInstance( 'LocalFile' );
929  $logger->warning( __METHOD__ . ' given invalid metadata of type ' .
930  gettype( $info['metadata'] ) );
931  $this->metadataArray = [];
932  }
933  $this->extraDataLoaded = true;
934  }
935  }
936 
952  public function isMissing() {
953  if ( $this->missing === null ) {
954  $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
955  $this->missing = !$fileExists;
956  }
957 
958  return $this->missing;
959  }
960 
968  public function getWidth( $page = 1 ) {
969  $page = (int)$page;
970  if ( $page < 1 ) {
971  $page = 1;
972  }
973 
974  $this->load();
975 
976  if ( $this->isMultipage() ) {
977  $handler = $this->getHandler();
978  if ( !$handler ) {
979  return 0;
980  }
981  $dim = $handler->getPageDimensions( $this, $page );
982  if ( $dim ) {
983  return $dim['width'];
984  } else {
985  // For non-paged media, the false goes through an
986  // intval, turning failure into 0, so do same here.
987  return 0;
988  }
989  } else {
990  return $this->width;
991  }
992  }
993 
1001  public function getHeight( $page = 1 ) {
1002  $page = (int)$page;
1003  if ( $page < 1 ) {
1004  $page = 1;
1005  }
1006 
1007  $this->load();
1008 
1009  if ( $this->isMultipage() ) {
1010  $handler = $this->getHandler();
1011  if ( !$handler ) {
1012  return 0;
1013  }
1014  $dim = $handler->getPageDimensions( $this, $page );
1015  if ( $dim ) {
1016  return $dim['height'];
1017  } else {
1018  // For non-paged media, the false goes through an
1019  // intval, turning failure into 0, so do same here.
1020  return 0;
1021  }
1022  } else {
1023  return $this->height;
1024  }
1025  }
1026 
1034  public function getDescriptionShortUrl() {
1035  if ( !$this->title ) {
1036  return null; // Avoid hard failure when the file does not exist. T221812
1037  }
1038 
1039  $pageId = $this->title->getArticleID();
1040 
1041  if ( $pageId ) {
1042  $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
1043  if ( $url !== false ) {
1044  return $url;
1045  }
1046  }
1047  return null;
1048  }
1049 
1056  public function getMetadata() {
1057  $data = $this->getMetadataArray();
1058  if ( !$data ) {
1059  return '';
1060  } elseif ( array_keys( $data ) === [ '_error' ] ) {
1061  // Legacy error encoding
1062  return $data['_error'];
1063  } else {
1064  return serialize( $this->getMetadataArray() );
1065  }
1066  }
1067 
1074  public function getMetadataArray(): array {
1075  $this->load( self::LOAD_ALL );
1076  if ( $this->unloadedMetadataBlobs ) {
1077  return $this->getMetadataItems(
1078  array_unique( array_merge(
1079  array_keys( $this->metadataArray ),
1080  array_keys( $this->unloadedMetadataBlobs )
1081  ) )
1082  );
1083  }
1084  return $this->metadataArray;
1085  }
1086 
1087  public function getMetadataItems( array $itemNames ): array {
1088  $this->load( self::LOAD_ALL );
1089  $result = [];
1090  $addresses = [];
1091  foreach ( $itemNames as $itemName ) {
1092  if ( array_key_exists( $itemName, $this->metadataArray ) ) {
1093  $result[$itemName] = $this->metadataArray[$itemName];
1094  } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
1095  $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
1096  }
1097  }
1098  if ( $addresses ) {
1099  $blobStore = $this->repo->getBlobStore();
1100  if ( !$blobStore ) {
1101  LoggerFactory::getInstance( 'LocalFile' )->warning(
1102  "Unable to load metadata: repo has no blob store" );
1103  return $result;
1104  }
1105  $status = $blobStore->getBlobBatch( $addresses );
1106  if ( !$status->isGood() ) {
1107  $msg = Status::wrap( $status )->getWikiText(
1108  false, false, 'en' );
1109  LoggerFactory::getInstance( 'LocalFile' )->warning(
1110  "Error loading metadata from BlobStore: $msg" );
1111  }
1112  foreach ( $addresses as $itemName => $address ) {
1113  unset( $this->unloadedMetadataBlobs[$itemName] );
1114  $json = $status->getValue()[$address] ?? null;
1115  if ( $json !== null ) {
1116  $value = $this->jsonDecode( $json );
1117  $result[$itemName] = $value;
1118  $this->metadataArray[$itemName] = $value;
1119  }
1120  }
1121  }
1122  return $result;
1123  }
1124 
1133  private function jsonEncode( $data ): string {
1134  $s = json_encode( $data,
1135  JSON_INVALID_UTF8_IGNORE |
1136  JSON_UNESCAPED_SLASHES |
1137  JSON_UNESCAPED_UNICODE );
1138  if ( $s === false ) {
1139  throw new MWException( __METHOD__ . ': metadata is not JSON-serializable ' .
1140  '(type = ' . $this->getMimeType() . ')' );
1141  }
1142  return $s;
1143  }
1144 
1156  private function jsonDecode( string $s ) {
1157  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1158  return @json_decode( $s, true, 512, JSON_INVALID_UTF8_IGNORE );
1159  }
1160 
1172  public function getMetadataForDb( IDatabase $db ) {
1173  $this->load( self::LOAD_ALL );
1174  if ( !$this->metadataArray && !$this->metadataBlobs ) {
1175  $s = '';
1176  } elseif ( $this->repo->isJsonMetadataEnabled() ) {
1177  $s = $this->getJsonMetadata();
1178  } else {
1179  $s = serialize( $this->getMetadataArray() );
1180  }
1181  if ( !is_string( $s ) ) {
1182  throw new MWException( 'Could not serialize image metadata value for DB' );
1183  }
1184  return $db->encodeBlob( $s );
1185  }
1186 
1193  private function getJsonMetadata() {
1194  // Directly store data that is not already in BlobStore
1195  $envelope = [
1196  'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
1197  ];
1198 
1199  // Also store the blob addresses
1200  if ( $this->metadataBlobs ) {
1201  $envelope['blobs'] = $this->metadataBlobs;
1202  }
1203 
1204  // Try encoding
1205  $s = $this->jsonEncode( $envelope );
1206 
1207  // Decide whether to try splitting the metadata.
1208  // Return early if it's not going to happen.
1209  if ( !$this->repo->isSplitMetadataEnabled()
1210  || !$this->getHandler()
1211  || !$this->getHandler()->useSplitMetadata()
1212  ) {
1213  return $s;
1214  }
1215  $threshold = $this->repo->getSplitMetadataThreshold();
1216  if ( !$threshold || strlen( $s ) <= $threshold ) {
1217  return $s;
1218  }
1219  $blobStore = $this->repo->getBlobStore();
1220  if ( !$blobStore ) {
1221  return $s;
1222  }
1223 
1224  // The data as a whole is above the item threshold. Look for
1225  // large items that can be split out.
1226  $blobAddresses = [];
1227  foreach ( $envelope['data'] as $name => $value ) {
1228  $encoded = $this->jsonEncode( $value );
1229  if ( strlen( $encoded ) > $threshold ) {
1230  $blobAddresses[$name] = $blobStore->storeBlob(
1231  $encoded,
1232  [ BlobStore::IMAGE_HINT => $this->getName() ]
1233  );
1234  }
1235  }
1236  // Remove any items that were split out
1237  $envelope['data'] = array_diff_key( $envelope['data'], $blobAddresses );
1238  $envelope['blobs'] = $blobAddresses;
1239  $s = $this->jsonEncode( $envelope );
1240 
1241  // Repeated calls to this function should not keep inserting more blobs
1242  $this->metadataBlobs += $blobAddresses;
1243 
1244  return $s;
1245  }
1246 
1253  private function isMetadataOversize() {
1254  if ( !$this->repo->isSplitMetadataEnabled() ) {
1255  return false;
1256  }
1257  $threshold = $this->repo->getSplitMetadataThreshold();
1258  $directItems = array_diff_key( $this->metadataArray, $this->metadataBlobs );
1259  foreach ( $directItems as $value ) {
1260  if ( strlen( $this->jsonEncode( $value ) ) > $threshold ) {
1261  return true;
1262  }
1263  }
1264  return false;
1265  }
1266 
1275  protected function loadMetadataFromDbFieldValue( IDatabase $db, $metadataBlob ) {
1276  $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
1277  }
1278 
1286  protected function loadMetadataFromString( $metadataString ) {
1287  $this->extraDataLoaded = true;
1288  $this->metadataArray = [];
1289  $this->metadataBlobs = [];
1290  $this->unloadedMetadataBlobs = [];
1291  $metadataString = (string)$metadataString;
1292  if ( $metadataString === '' ) {
1293  $this->metadataSerializationFormat = self::MDS_EMPTY;
1294  return;
1295  }
1296  if ( $metadataString[0] === '{' ) {
1297  $envelope = $this->jsonDecode( $metadataString );
1298  if ( !$envelope ) {
1299  // Legacy error encoding
1300  $this->metadataArray = [ '_error' => $metadataString ];
1301  $this->metadataSerializationFormat = self::MDS_LEGACY;
1302  } else {
1303  $this->metadataSerializationFormat = self::MDS_JSON;
1304  if ( isset( $envelope['data'] ) ) {
1305  $this->metadataArray = $envelope['data'];
1306  }
1307  if ( isset( $envelope['blobs'] ) ) {
1308  $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope['blobs'];
1309  }
1310  }
1311  } else {
1312  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1313  $data = @unserialize( $metadataString );
1314  if ( !is_array( $data ) ) {
1315  // Legacy error encoding
1316  $data = [ '_error' => $metadataString ];
1317  $this->metadataSerializationFormat = self::MDS_LEGACY;
1318  } else {
1319  $this->metadataSerializationFormat = self::MDS_PHP;
1320  }
1321  $this->metadataArray = $data;
1322  }
1323  }
1324 
1329  public function getBitDepth() {
1330  $this->load();
1331 
1332  return (int)$this->bits;
1333  }
1334 
1340  public function getSize() {
1341  $this->load();
1342 
1343  return $this->size;
1344  }
1345 
1351  public function getMimeType() {
1352  $this->load();
1353 
1354  return $this->mime;
1355  }
1356 
1363  public function getMediaType() {
1364  $this->load();
1365 
1366  return $this->media_type;
1367  }
1368 
1380  public function exists() {
1381  $this->load();
1382 
1383  return $this->fileExists;
1384  }
1385 
1402  protected function getThumbnails( $archiveName = false ) {
1403  if ( $archiveName ) {
1404  $dir = $this->getArchiveThumbPath( $archiveName );
1405  } else {
1406  $dir = $this->getThumbPath();
1407  }
1408 
1409  $backend = $this->repo->getBackend();
1410  $files = [ $dir ];
1411  try {
1412  $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1413  if ( $iterator !== null ) {
1414  foreach ( $iterator as $file ) {
1415  $files[] = $file;
1416  }
1417  }
1418  } catch ( FileBackendError $e ) {
1419  } // suppress (T56674)
1420 
1421  return $files;
1422  }
1423 
1427  private function purgeMetadataCache() {
1428  $this->invalidateCache();
1429  }
1430 
1439  public function purgeCache( $options = [] ) {
1440  // Refresh metadata cache
1441  $this->maybeUpgradeRow();
1442  $this->purgeMetadataCache();
1443 
1444  // Delete thumbnails
1445  $this->purgeThumbnails( $options );
1446 
1447  // Purge CDN cache for this file
1448  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1449  $hcu->purgeUrls(
1450  $this->getUrl(),
1451  !empty( $options['forThumbRefresh'] )
1452  ? $hcu::PURGE_PRESEND // just a manual purge
1453  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1454  );
1455  }
1456 
1462  public function purgeOldThumbnails( $archiveName ) {
1463  // Get a list of old thumbnails
1464  $thumbs = $this->getThumbnails( $archiveName );
1465 
1466  // Delete thumbnails from storage, and prevent the directory itself from being purged
1467  $dir = array_shift( $thumbs );
1468  $this->purgeThumbList( $dir, $thumbs );
1469 
1470  $urls = [];
1471  foreach ( $thumbs as $thumb ) {
1472  $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1473  }
1474 
1475  // Purge any custom thumbnail caches
1476  $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1477 
1478  // Purge the CDN
1479  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1480  $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1481  }
1482 
1489  public function purgeThumbnails( $options = [] ) {
1490  $thumbs = $this->getThumbnails();
1491 
1492  // Delete thumbnails from storage, and prevent the directory itself from being purged
1493  $dir = array_shift( $thumbs );
1494  $this->purgeThumbList( $dir, $thumbs );
1495 
1496  // Always purge all files from CDN regardless of handler filters
1497  $urls = [];
1498  foreach ( $thumbs as $thumb ) {
1499  $urls[] = $this->getThumbUrl( $thumb );
1500  }
1501 
1502  // Give the media handler a chance to filter the file purge list
1503  if ( !empty( $options['forThumbRefresh'] ) ) {
1504  $handler = $this->getHandler();
1505  if ( $handler ) {
1506  $handler->filterThumbnailPurgeList( $thumbs, $options );
1507  }
1508  }
1509 
1510  // Purge any custom thumbnail caches
1511  $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1512 
1513  // Purge the CDN
1514  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1515  $hcu->purgeUrls(
1516  $urls,
1517  !empty( $options['forThumbRefresh'] )
1518  ? $hcu::PURGE_PRESEND // just a manual purge
1519  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1520  );
1521  }
1522 
1529  public function prerenderThumbnails() {
1530  $uploadThumbnailRenderMap = MediaWikiServices::getInstance()
1531  ->getMainConfig()->get( 'UploadThumbnailRenderMap' );
1532 
1533  $jobs = [];
1534 
1535  $sizes = $uploadThumbnailRenderMap;
1536  rsort( $sizes );
1537 
1538  foreach ( $sizes as $size ) {
1539  if ( $this->isMultipage() ) {
1540  for ( $page = 1; $page <= $this->pageCount(); $page++ ) {
1541  $jobs[] = new ThumbnailRenderJob(
1542  $this->getTitle(),
1543  [ 'transformParams' => [
1544  'width' => $size,
1545  'page' => $page,
1546  ] ]
1547  );
1548  }
1549  } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1550  $jobs[] = new ThumbnailRenderJob(
1551  $this->getTitle(),
1552  [ 'transformParams' => [ 'width' => $size ] ]
1553  );
1554  }
1555  }
1556 
1557  if ( $jobs ) {
1558  JobQueueGroup::singleton()->lazyPush( $jobs );
1559  }
1560  }
1561 
1568  protected function purgeThumbList( $dir, $files ) {
1569  $fileListDebug = strtr(
1570  var_export( $files, true ),
1571  [ "\n" => '' ]
1572  );
1573  wfDebug( __METHOD__ . ": $fileListDebug" );
1574 
1575  if ( $this->repo->supportsSha1URLs() ) {
1576  $reference = $this->getSha1();
1577  } else {
1578  $reference = $this->getName();
1579  }
1580 
1581  $purgeList = [];
1582  foreach ( $files as $file ) {
1583  # Check that the reference (filename or sha1) is part of the thumb name
1584  # This is a basic check to avoid erasing unrelated directories
1585  if ( strpos( $file, $reference ) !== false
1586  || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1587  ) {
1588  $purgeList[] = "{$dir}/{$file}";
1589  }
1590  }
1591 
1592  # Delete the thumbnails
1593  $this->repo->quickPurgeBatch( $purgeList );
1594  # Clear out the thumbnail directory if empty
1595  $this->repo->quickCleanDir( $dir );
1596  }
1597 
1609  public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1610  if ( !$this->exists() ) {
1611  return []; // Avoid hard failure when the file does not exist. T221812
1612  }
1613 
1614  $dbr = $this->repo->getReplicaDB();
1615  $oldFileQuery = OldLocalFile::getQueryInfo();
1616 
1617  $tables = $oldFileQuery['tables'];
1618  $fields = $oldFileQuery['fields'];
1619  $join_conds = $oldFileQuery['joins'];
1620  $conds = $opts = [];
1621  $eq = $inc ? '=' : '';
1622  $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1623 
1624  if ( $start ) {
1625  $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1626  }
1627 
1628  if ( $end ) {
1629  $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1630  }
1631 
1632  if ( $limit ) {
1633  $opts['LIMIT'] = $limit;
1634  }
1635 
1636  // Search backwards for time > x queries
1637  $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1638  $opts['ORDER BY'] = "oi_timestamp $order";
1639  $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1640 
1641  $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1642  $conds, $opts, $join_conds );
1643 
1644  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1645  $r = [];
1646 
1647  foreach ( $res as $row ) {
1648  $r[] = $this->repo->newFileFromRow( $row );
1649  }
1650 
1651  if ( $order == 'ASC' ) {
1652  $r = array_reverse( $r ); // make sure it ends up descending
1653  }
1654 
1655  return $r;
1656  }
1657 
1668  public function nextHistoryLine() {
1669  if ( !$this->exists() ) {
1670  return false; // Avoid hard failure when the file does not exist. T221812
1671  }
1672 
1673  # Polymorphic function name to distinguish foreign and local fetches
1674  $fname = static::class . '::' . __FUNCTION__;
1675 
1676  $dbr = $this->repo->getReplicaDB();
1677 
1678  if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1679  $fileQuery = self::getQueryInfo();
1680  $this->historyRes = $dbr->select( $fileQuery['tables'],
1681  $fileQuery['fields'] + [
1682  'oi_archive_name' => $dbr->addQuotes( '' ),
1683  'oi_deleted' => 0,
1684  ],
1685  [ 'img_name' => $this->title->getDBkey() ],
1686  $fname,
1687  [],
1688  $fileQuery['joins']
1689  );
1690 
1691  if ( $this->historyRes->numRows() == 0 ) {
1692  $this->historyRes = null;
1693 
1694  return false;
1695  }
1696  } elseif ( $this->historyLine == 1 ) {
1697  $fileQuery = OldLocalFile::getQueryInfo();
1698  $this->historyRes = $dbr->select(
1699  $fileQuery['tables'],
1700  $fileQuery['fields'],
1701  [ 'oi_name' => $this->title->getDBkey() ],
1702  $fname,
1703  [ 'ORDER BY' => 'oi_timestamp DESC' ],
1704  $fileQuery['joins']
1705  );
1706  }
1707  $this->historyLine++;
1708 
1709  return $this->historyRes->fetchObject();
1710  }
1711 
1716  public function resetHistory() {
1717  $this->historyLine = 0;
1718 
1719  if ( $this->historyRes !== null ) {
1720  $this->historyRes = null;
1721  }
1722  }
1723 
1757  public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1758  $timestamp = false, Authority $uploader = null, $tags = [],
1759  $createNullRevision = true, $revert = false
1760  ) {
1761  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1762  return $this->readOnlyFatalStatus();
1763  } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1764  // Check this in advance to avoid writing to FileBackend and the file tables,
1765  // only to fail on insert the revision due to the text store being unavailable.
1766  return $this->readOnlyFatalStatus();
1767  }
1768 
1769  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1770  if ( !$props ) {
1771  if ( FileRepo::isVirtualUrl( $srcPath )
1772  || FileBackend::isStoragePath( $srcPath )
1773  ) {
1774  $props = $this->repo->getFileProps( $srcPath );
1775  } else {
1776  $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1777  $props = $mwProps->getPropsFromPath( $srcPath, true );
1778  }
1779  }
1780 
1781  $options = [];
1782  $handler = MediaHandler::getHandler( $props['mime'] );
1783  if ( $handler ) {
1784  if ( is_string( $props['metadata'] ) ) {
1785  // This supports callers directly fabricating a metadata
1786  // property using serialize(). Normally the metadata property
1787  // comes from MWFileProps, in which case it won't be a string.
1788  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1789  $metadata = @unserialize( $props['metadata'] );
1790  } else {
1791  $metadata = $props['metadata'];
1792  }
1793 
1794  if ( is_array( $metadata ) ) {
1795  $options['headers'] = $handler->getContentHeaders( $metadata );
1796  }
1797  } else {
1798  $options['headers'] = [];
1799  }
1800 
1801  // Trim spaces on user supplied text
1802  $comment = trim( $comment );
1803 
1804  $status = $this->publish( $src, $flags, $options );
1805 
1806  if ( $status->successCount >= 2 ) {
1807  // There will be a copy+(one of move,copy,store).
1808  // The first succeeding does not commit us to updating the DB
1809  // since it simply copied the current version to a timestamped file name.
1810  // It is only *preferable* to avoid leaving such files orphaned.
1811  // Once the second operation goes through, then the current version was
1812  // updated and we must therefore update the DB too.
1813  $oldver = $status->value;
1814 
1815  if ( $uploader === null ) {
1816  // Uploader argument is optional, fall back to the context authority
1817  $uploader = RequestContext::getMain()->getAuthority();
1818  }
1819 
1820  $uploadStatus = $this->recordUpload3(
1821  $oldver,
1822  $comment,
1823  $pageText,
1824  $uploader,
1825  $props,
1826  $timestamp,
1827  $tags,
1828  $createNullRevision,
1829  $revert
1830  );
1831  if ( !$uploadStatus->isOK() ) {
1832  if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1833  // update filenotfound error with more specific path
1834  $status->fatal( 'filenotfound', $srcPath );
1835  } else {
1836  $status->merge( $uploadStatus );
1837  }
1838  }
1839  }
1840 
1841  return $status;
1842  }
1843 
1860  public function recordUpload3(
1861  string $oldver,
1862  string $comment,
1863  string $pageText,
1864  Authority $performer,
1865  $props = false,
1866  $timestamp = false,
1867  $tags = [],
1868  bool $createNullRevision = true,
1869  bool $revert = false
1870  ): Status {
1871  $dbw = $this->repo->getPrimaryDB();
1872 
1873  # Imports or such might force a certain timestamp; otherwise we generate
1874  # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1875  if ( $timestamp === false ) {
1876  $timestamp = $dbw->timestamp();
1877  $allowTimeKludge = true;
1878  } else {
1879  $allowTimeKludge = false;
1880  }
1881 
1882  $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1883  $props['description'] = $comment;
1884  $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1885  $this->setProps( $props );
1886 
1887  # Fail now if the file isn't there
1888  if ( !$this->fileExists ) {
1889  wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1890 
1891  return Status::newFatal( 'filenotfound', $this->getRel() );
1892  }
1893 
1894  $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1895 
1896  $dbw->startAtomic( __METHOD__ );
1897 
1898  $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1899  $this->user = $performer->getUser();
1900 
1901  # Test to see if the row exists using INSERT IGNORE
1902  # This avoids race conditions by locking the row until the commit, and also
1903  # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1904  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1905  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1906  $actorFields = [ 'img_actor' => $actorId ];
1907  $dbw->insert( 'image',
1908  [
1909  'img_name' => $this->getName(),
1910  'img_size' => $this->size,
1911  'img_width' => intval( $this->width ),
1912  'img_height' => intval( $this->height ),
1913  'img_bits' => $this->bits,
1914  'img_media_type' => $this->media_type,
1915  'img_major_mime' => $this->major_mime,
1916  'img_minor_mime' => $this->minor_mime,
1917  'img_timestamp' => $timestamp,
1918  'img_metadata' => $this->getMetadataForDb( $dbw ),
1919  'img_sha1' => $this->sha1
1920  ] + $commentFields + $actorFields,
1921  __METHOD__,
1922  [ 'IGNORE' ]
1923  );
1924  $reupload = ( $dbw->affectedRows() == 0 );
1925 
1926  if ( $reupload ) {
1927  $row = $dbw->selectRow(
1928  'image',
1929  [ 'img_timestamp', 'img_sha1' ],
1930  [ 'img_name' => $this->getName() ],
1931  __METHOD__,
1932  [ 'LOCK IN SHARE MODE' ]
1933  );
1934 
1935  if ( $row && $row->img_sha1 === $this->sha1 ) {
1936  $dbw->endAtomic( __METHOD__ );
1937  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1938  $title = Title::newFromText( $this->getName(), NS_FILE );
1939  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1940  }
1941 
1942  if ( $allowTimeKludge ) {
1943  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1944  $lUnixtime = $row ? (int)wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1945  # Avoid a timestamp that is not newer than the last version
1946  # TODO: the image/oldimage tables should be like page/revision with an ID field
1947  if ( $lUnixtime && (int)wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1948  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1949  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1950  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1951  }
1952  }
1953 
1954  $tables = [ 'image' ];
1955  $fields = [
1956  'oi_name' => 'img_name',
1957  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1958  'oi_size' => 'img_size',
1959  'oi_width' => 'img_width',
1960  'oi_height' => 'img_height',
1961  'oi_bits' => 'img_bits',
1962  'oi_description_id' => 'img_description_id',
1963  'oi_timestamp' => 'img_timestamp',
1964  'oi_metadata' => 'img_metadata',
1965  'oi_media_type' => 'img_media_type',
1966  'oi_major_mime' => 'img_major_mime',
1967  'oi_minor_mime' => 'img_minor_mime',
1968  'oi_sha1' => 'img_sha1',
1969  'oi_actor' => 'img_actor',
1970  ];
1971  $joins = [];
1972 
1973  # (T36993) Note: $oldver can be empty here, if the previous
1974  # version of the file was broken. Allow registration of the new
1975  # version to continue anyway, because that's better than having
1976  # an image that's not fixable by user operations.
1977  # Collision, this is an update of a file
1978  # Insert previous contents into oldimage
1979  $dbw->insertSelect( 'oldimage', $tables, $fields,
1980  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1981 
1982  # Update the current image row
1983  $dbw->update( 'image',
1984  [
1985  'img_size' => $this->size,
1986  'img_width' => intval( $this->width ),
1987  'img_height' => intval( $this->height ),
1988  'img_bits' => $this->bits,
1989  'img_media_type' => $this->media_type,
1990  'img_major_mime' => $this->major_mime,
1991  'img_minor_mime' => $this->minor_mime,
1992  'img_timestamp' => $timestamp,
1993  'img_metadata' => $this->getMetadataForDb( $dbw ),
1994  'img_sha1' => $this->sha1
1995  ] + $commentFields + $actorFields,
1996  [ 'img_name' => $this->getName() ],
1997  __METHOD__
1998  );
1999  }
2000 
2001  $descTitle = $this->getTitle();
2002  $descId = $descTitle->getArticleID();
2003  $wikiPage = new WikiFilePage( $descTitle );
2004  $wikiPage->setFile( $this );
2005 
2006  // Determine log action. If reupload is done by reverting, use a special log_action.
2007  if ( $revert ) {
2008  $logAction = 'revert';
2009  } elseif ( $reupload ) {
2010  $logAction = 'overwrite';
2011  } else {
2012  $logAction = 'upload';
2013  }
2014  // Add the log entry...
2015  $logEntry = new ManualLogEntry( 'upload', $logAction );
2016  $logEntry->setTimestamp( $this->timestamp );
2017  $logEntry->setPerformer( $performer->getUser() );
2018  $logEntry->setComment( $comment );
2019  $logEntry->setTarget( $descTitle );
2020  // Allow people using the api to associate log entries with the upload.
2021  // Log has a timestamp, but sometimes different from upload timestamp.
2022  $logEntry->setParameters(
2023  [
2024  'img_sha1' => $this->sha1,
2025  'img_timestamp' => $timestamp,
2026  ]
2027  );
2028  // Note we keep $logId around since during new image
2029  // creation, page doesn't exist yet, so log_page = 0
2030  // but we want it to point to the page we're making,
2031  // so we later modify the log entry.
2032  // For a similar reason, we avoid making an RC entry
2033  // now and wait until the page exists.
2034  $logId = $logEntry->insert();
2035 
2036  if ( $descTitle->exists() ) {
2037  if ( $createNullRevision ) {
2038  $revStore = MediaWikiServices::getInstance()->getRevisionStore();
2039  // Use own context to get the action text in content language
2040  $formatter = LogFormatter::newFromEntry( $logEntry );
2041  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
2042  $editSummary = $formatter->getPlainActionText();
2043  $summary = CommentStoreComment::newUnsavedComment( $editSummary );
2044  $nullRevRecord = $revStore->newNullRevision(
2045  $dbw,
2046  $descTitle,
2047  $summary,
2048  false,
2049  $performer->getUser()
2050  );
2051 
2052  if ( $nullRevRecord ) {
2053  $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
2054 
2055  $this->getHookRunner()->onRevisionFromEditComplete(
2056  $wikiPage,
2057  $inserted,
2058  $inserted->getParentId(),
2059  $performer->getUser(),
2060  $tags
2061  );
2062 
2063  $wikiPage->updateRevisionOn( $dbw, $inserted );
2064  // Associate null revision id
2065  $logEntry->setAssociatedRevId( $inserted->getId() );
2066  }
2067  }
2068 
2069  $newPageContent = null;
2070  } else {
2071  // Make the description page and RC log entry post-commit
2072  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
2073  }
2074 
2075  // NOTE: Even after ending this atomic section, we are probably still in the implicit
2076  // transaction started by any prior master query in the request. We cannot yet safely
2077  // schedule jobs, see T263301.
2078  $dbw->endAtomic( __METHOD__ );
2079  $fname = __METHOD__;
2080 
2081  # Do some cache purges after final commit so that:
2082  # a) Changes are more likely to be seen post-purge
2083  # b) They won't cause rollback of the log publish/update above
2084  $purgeUpdate = new AutoCommitUpdate(
2085  $dbw,
2086  __METHOD__,
2088  function () use (
2089  $reupload, $wikiPage, $newPageContent, $comment, $performer,
2090  $logEntry, $logId, $descId, $tags, $fname
2091  ) {
2092  # Update memcache after the commit
2093  $this->invalidateCache();
2094 
2095  $updateLogPage = false;
2096  if ( $newPageContent ) {
2097  # New file page; create the description page.
2098  # There's already a log entry, so don't make a second RC entry
2099  # CDN and file cache for the description page are purged by doUserEditContent.
2100  $status = $wikiPage->doUserEditContent(
2101  $newPageContent,
2102  $performer,
2103  $comment,
2105  );
2106 
2107  if ( isset( $status->value['revision-record'] ) ) {
2109  $revRecord = $status->value['revision-record'];
2110  // Associate new page revision id
2111  $logEntry->setAssociatedRevId( $revRecord->getId() );
2112  }
2113  // This relies on the resetArticleID() call in WikiPage::insertOn(),
2114  // which is triggered on $descTitle by doUserEditContent() above.
2115  if ( isset( $status->value['revision-record'] ) ) {
2117  $revRecord = $status->value['revision-record'];
2118  $updateLogPage = $revRecord->getPageId();
2119  }
2120  } else {
2121  # Existing file page: invalidate description page cache
2122  $title = $wikiPage->getTitle();
2124  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2125  $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2126  # Allow the new file version to be patrolled from the page footer
2128  }
2129 
2130  # Update associated rev id. This should be done by $logEntry->insert() earlier,
2131  # but setAssociatedRevId() wasn't called at that point yet...
2132  $logParams = $logEntry->getParameters();
2133  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
2134  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
2135  if ( $updateLogPage ) {
2136  # Also log page, in case where we just created it above
2137  $update['log_page'] = $updateLogPage;
2138  }
2139  $this->getRepo()->getPrimaryDB()->update(
2140  'logging',
2141  $update,
2142  [ 'log_id' => $logId ],
2143  $fname
2144  );
2145  $this->getRepo()->getPrimaryDB()->insert(
2146  'log_search',
2147  [
2148  'ls_field' => 'associated_rev_id',
2149  'ls_value' => (string)$logEntry->getAssociatedRevId(),
2150  'ls_log_id' => $logId,
2151  ],
2152  $fname
2153  );
2154 
2155  # Add change tags, if any
2156  if ( $tags ) {
2157  $logEntry->addTags( $tags );
2158  }
2159 
2160  # Uploads can be patrolled
2161  $logEntry->setIsPatrollable( true );
2162 
2163  # Now that the log entry is up-to-date, make an RC entry.
2164  $logEntry->publish( $logId );
2165 
2166  # Run hook for other updates (typically more cache purging)
2167  $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2168 
2169  if ( $reupload ) {
2170  # Delete old thumbnails
2171  $this->purgeThumbnails();
2172  # Remove the old file from the CDN cache
2173  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2174  $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2175  } else {
2176  # Update backlink pages pointing to this title if created
2177  $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2178  LinksUpdate::queueRecursiveJobsForTable(
2179  $this->getTitle(),
2180  'imagelinks',
2181  'upload-image',
2182  $performer->getUser()->getName(),
2183  $blcFactory->getBacklinkCache( $this->getTitle() )
2184  );
2185  }
2186 
2187  $this->prerenderThumbnails();
2188  }
2189  );
2190 
2191  # Invalidate cache for all pages using this file
2192  $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
2193  $this->getTitle(),
2194  'imagelinks',
2195  [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2196  );
2197 
2198  // NOTE: We are probably still in the implicit transaction started by DBO_TRX. We should
2199  // only schedule jobs after that transaction was committed, so a job queue failure
2200  // doesn't cause the upload to fail (T263301). Also, we should generally not schedule any
2201  // Jobs or the DeferredUpdates that assume the update is complete until after the
2202  // transaction has been committed and we are sure that the upload was indeed successful.
2203  $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2204  DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2205 
2206  if ( !$reupload ) {
2207  // This is a new file, so update the image count
2208  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2209  }
2210 
2211  JobQueueGroup::singleton()->lazyPush( $cacheUpdateJob );
2212  }, __METHOD__ );
2213 
2214  return Status::newGood();
2215  }
2216 
2233  public function publish( $src, $flags = 0, array $options = [] ) {
2234  return $this->publishTo( $src, $this->getRel(), $flags, $options );
2235  }
2236 
2253  protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2254  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
2255 
2256  $repo = $this->getRepo();
2257  if ( $repo->getReadOnlyReason() !== false ) {
2258  return $this->readOnlyFatalStatus();
2259  }
2260 
2261  $status = $this->acquireFileLock();
2262  if ( !$status->isOK() ) {
2263  return $status;
2264  }
2265 
2266  if ( $this->isOld() ) {
2267  $archiveRel = $dstRel;
2268  $archiveName = basename( $archiveRel );
2269  } else {
2270  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
2271  $archiveRel = $this->getArchiveRel( $archiveName );
2272  }
2273 
2274  if ( $repo->hasSha1Storage() ) {
2275  $sha1 = FileRepo::isVirtualUrl( $srcPath )
2276  ? $repo->getFileSha1( $srcPath )
2277  : FSFile::getSha1Base36FromPath( $srcPath );
2279  $wrapperBackend = $repo->getBackend();
2280  '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2281  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2282  $status = $repo->quickImport( $src, $dst );
2283  if ( $flags & File::DELETE_SOURCE ) {
2284  unlink( $srcPath );
2285  }
2286 
2287  if ( $this->exists() ) {
2288  $status->value = $archiveName;
2289  }
2290  } else {
2291  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2292  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2293 
2294  if ( $status->value == 'new' ) {
2295  $status->value = '';
2296  } else {
2297  $status->value = $archiveName;
2298  }
2299  }
2300 
2301  $this->releaseFileLock();
2302  return $status;
2303  }
2304 
2323  public function move( $target ) {
2324  $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2325  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2326  return $this->readOnlyFatalStatus();
2327  }
2328 
2329  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2330  $batch = new LocalFileMoveBatch( $this, $target );
2331 
2332  $status = $batch->addCurrent();
2333  if ( !$status->isOK() ) {
2334  return $status;
2335  }
2336  $archiveNames = $batch->addOlds();
2337  $status = $batch->execute();
2338 
2339  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2340 
2341  // Purge the source and target files outside the transaction...
2342  $oldTitleFile = $localRepo->newFile( $this->title );
2343  $newTitleFile = $localRepo->newFile( $target );
2345  new AutoCommitUpdate(
2346  $this->getRepo()->getPrimaryDB(),
2347  __METHOD__,
2348  static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2349  $oldTitleFile->purgeEverything();
2350  foreach ( $archiveNames as $archiveName ) {
2352  '@phan-var OldLocalFile $oldTitleFile';
2353  $oldTitleFile->purgeOldThumbnails( $archiveName );
2354  }
2355  $newTitleFile->purgeEverything();
2356  }
2357  ),
2358  DeferredUpdates::PRESEND
2359  );
2360 
2361  if ( $status->isOK() ) {
2362  // Now switch the object
2363  $this->title = $target;
2364  // Force regeneration of the name and hashpath
2365  $this->name = null;
2366  $this->hashPath = null;
2367  }
2368 
2369  return $status;
2370  }
2371 
2388  public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2389  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2390  return $this->readOnlyFatalStatus();
2391  }
2392 
2393  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2394 
2395  $batch->addCurrent();
2396  // Get old version relative paths
2397  $archiveNames = $batch->addOlds();
2398  $status = $batch->execute();
2399 
2400  if ( $status->isOK() ) {
2401  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2402  }
2403 
2404  // To avoid slow purges in the transaction, move them outside...
2406  new AutoCommitUpdate(
2407  $this->getRepo()->getPrimaryDB(),
2408  __METHOD__,
2409  function () use ( $archiveNames ) {
2410  $this->purgeEverything();
2411  foreach ( $archiveNames as $archiveName ) {
2412  $this->purgeOldThumbnails( $archiveName );
2413  }
2414  }
2415  ),
2416  DeferredUpdates::PRESEND
2417  );
2418 
2419  // Purge the CDN
2420  $purgeUrls = [];
2421  foreach ( $archiveNames as $archiveName ) {
2422  $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2423  }
2424 
2425  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2426  $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2427 
2428  return $status;
2429  }
2430 
2449  public function deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress = false ) {
2450  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2451  return $this->readOnlyFatalStatus();
2452  }
2453 
2454  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2455 
2456  $batch->addOld( $archiveName );
2457  $status = $batch->execute();
2458 
2459  $this->purgeOldThumbnails( $archiveName );
2460  if ( $status->isOK() ) {
2461  $this->purgeDescription();
2462  }
2463 
2464  $url = $this->getArchiveUrl( $archiveName );
2465  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2466  $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2467 
2468  return $status;
2469  }
2470 
2483  public function restore( $versions = [], $unsuppress = false ) {
2484  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2485  return $this->readOnlyFatalStatus();
2486  }
2487 
2488  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2489 
2490  if ( !$versions ) {
2491  $batch->addAll();
2492  } else {
2493  $batch->addIds( $versions );
2494  }
2495  $status = $batch->execute();
2496  if ( $status->isGood() ) {
2497  $cleanupStatus = $batch->cleanup();
2498  $cleanupStatus->successCount = 0;
2499  $cleanupStatus->failCount = 0;
2500  $status->merge( $cleanupStatus );
2501  }
2502 
2503  return $status;
2504  }
2505 
2516  public function getDescriptionUrl() {
2517  if ( !$this->title ) {
2518  return false; // Avoid hard failure when the file does not exist. T221812
2519  }
2520 
2521  return $this->title->getLocalURL();
2522  }
2523 
2533  public function getDescriptionText( Language $lang = null ) {
2534  if ( !$this->title ) {
2535  return false; // Avoid hard failure when the file does not exist. T221812
2536  }
2537 
2538  $services = MediaWikiServices::getInstance();
2539  $page = $services->getPageStore()->getPageByReference( $this->getTitle() );
2540  if ( !$page ) {
2541  return false;
2542  }
2543 
2544  if ( $lang ) {
2545  $parserOptions = ParserOptions::newFromUserAndLang(
2547  $lang
2548  );
2549  } else {
2551  }
2552 
2553  $parseStatus = $services->getParserOutputAccess()
2554  ->getParserOutput( $page, $parserOptions );
2555 
2556  if ( !$parseStatus->isGood() ) {
2557  // Rendering failed.
2558  return false;
2559  }
2560  return $parseStatus->getValue()->getText();
2561  }
2562 
2570  public function getUploader( int $audience = self::FOR_PUBLIC, Authority $performer = null ): ?UserIdentity {
2571  $this->load();
2572  if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2573  return null;
2574  } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2575  return null;
2576  } else {
2577  return $this->user;
2578  }
2579  }
2580 
2587  public function getDescription( $audience = self::FOR_PUBLIC, Authority $performer = null ) {
2588  $this->load();
2589  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2590  return '';
2591  } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2592  return '';
2593  } else {
2594  return $this->description;
2595  }
2596  }
2597 
2602  public function getTimestamp() {
2603  $this->load();
2604 
2605  return $this->timestamp;
2606  }
2607 
2612  public function getDescriptionTouched() {
2613  if ( !$this->exists() ) {
2614  return false; // Avoid hard failure when the file does not exist. T221812
2615  }
2616 
2617  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2618  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2619  // need to differentiate between null (uninitialized) and false (failed to load).
2620  if ( $this->descriptionTouched === null ) {
2621  $cond = [
2622  'page_namespace' => $this->title->getNamespace(),
2623  'page_title' => $this->title->getDBkey()
2624  ];
2625  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2626  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2627  }
2628 
2630  }
2631 
2636  public function getSha1() {
2637  $this->load();
2638  return $this->sha1;
2639  }
2640 
2644  public function isCacheable() {
2645  $this->load();
2646 
2647  // If extra data (metadata) was not loaded then it must have been large
2648  return $this->extraDataLoaded
2649  && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2650  }
2651 
2660  public function acquireFileLock( $timeout = 0 ) {
2661  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2662  [ $this->getPath() ], LockManager::LOCK_EX, $timeout
2663  ) );
2664  }
2665 
2672  public function releaseFileLock() {
2673  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2674  [ $this->getPath() ], LockManager::LOCK_EX
2675  ) );
2676  }
2677 
2688  public function lock() {
2689  if ( !$this->locked ) {
2690  $logger = LoggerFactory::getInstance( 'LocalFile' );
2691 
2692  $dbw = $this->repo->getPrimaryDB();
2693  $makesTransaction = !$dbw->trxLevel();
2694  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2695  // T56736: use simple lock to handle when the file does not exist.
2696  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2697  // Also, that would cause contention on INSERT of similarly named rows.
2698  $status = $this->acquireFileLock( 10 ); // represents all versions of the file
2699  if ( !$status->isGood() ) {
2700  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2701  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2702 
2703  throw new LocalFileLockError( $status );
2704  }
2705  // Release the lock *after* commit to avoid row-level contention.
2706  // Make sure it triggers on rollback() as well as commit() (T132921).
2707  $dbw->onTransactionResolution(
2708  function () use ( $logger ) {
2709  $status = $this->releaseFileLock();
2710  if ( !$status->isGood() ) {
2711  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2712  }
2713  },
2714  __METHOD__
2715  );
2716  // Callers might care if the SELECT snapshot is safely fresh
2717  $this->lockedOwnTrx = $makesTransaction;
2718  }
2719 
2720  $this->locked++;
2721 
2722  return $this->lockedOwnTrx;
2723  }
2724 
2735  public function unlock() {
2736  if ( $this->locked ) {
2737  --$this->locked;
2738  if ( !$this->locked ) {
2739  $dbw = $this->repo->getPrimaryDB();
2740  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2741  $this->lockedOwnTrx = false;
2742  }
2743  }
2744  }
2745 
2749  protected function readOnlyFatalStatus() {
2750  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2751  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2752  }
2753 
2757  public function __destruct() {
2758  $this->unlock();
2759  }
2760 }
LocalFile\$media_type
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition: LocalFile.php:93
LocalFile\$unloadedMetadataBlobs
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
LocalFile\getSha1
getSha1()
Definition: LocalFile.php:2636
MediaWiki\User\UserIdentityValue
Value object representing a user's identity.
Definition: UserIdentityValue.php:35
LocalFile\ATOMIC_SECTION_LOCK
const ATOMIC_SECTION_LOCK
Definition: LocalFile.php:180
LocalFile\$fileExists
bool $fileExists
Does the file exist on disk? (loadFromXxx)
Definition: LocalFile.php:77
File\getPath
getPath()
Return the storage path to the file.
Definition: File.php:457
LocalFile\maybeUpgradeRow
maybeUpgradeRow()
Upgrade a row if it needs it.
Definition: LocalFile.php:748
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:52
LocalFileRestoreBatch
Helper class for file undeletion.
Definition: LocalFileRestoreBatch.php:31
LocalFile\reserializeMetadata
reserializeMetadata()
Write the metadata back to the database with the current serialization format.
Definition: LocalFile.php:857
CommentStoreComment\newUnsavedComment
static newUnsavedComment( $comment, array $data=null)
Create a new, unsaved CommentStoreComment.
Definition: CommentStoreComment.php:67
LocalFile\getMutableCacheKeys
getMutableCacheKeys(WANObjectCache $cache)
Definition: LocalFile.php:349
LocalFile\$metadataBlobs
string[] $metadataBlobs
Map of metadata item name to blob address.
Definition: LocalFile.php:113
FileRepo\getReadOnlyReason
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition: FileRepo.php:261
LocalFile\unprefixRow
unprefixRow( $row, $prefix='img_')
Definition: LocalFile.php:619
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:377
File\$repo
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition: File.php:114
LocalFile\$width
int $width
Image width.
Definition: LocalFile.php:84
File\getArchiveThumbPath
getArchiveThumbPath( $archiveName, $suffix=false)
Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified.
Definition: File.php:1773
MediaWiki\Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:47
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
LocalFile\__construct
__construct( $title, $repo)
Do not call this except from inside a repo class.
Definition: LocalFile.php:315
LocalFile\unlock
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
Definition: LocalFile.php:2735
LocalFile\getTimestamp
getTimestamp()
Definition: LocalFile.php:2602
File\isMultipage
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition: File.php:2129
LocalFile\getRepo
getRepo()
Definition: LocalFile.php:330
LocalFile\loadFromDB
loadFromDB( $flags=0)
Load file metadata from the DB.
Definition: LocalFile.php:510
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:204
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
LocalFile\purgeThumbList
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
Definition: LocalFile.php:1568
File\getRel
getRel()
Get the path of the file relative to the public zone root.
Definition: File.php:1686
AutoCommitUpdate
Deferrable Update for closure/callback updates that should use auto-commit mode.
Definition: AutoCommitUpdate.php:9
OldLocalFile\getQueryInfo
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new oldlocalfile object.
Definition: OldLocalFile.php:137
LocalFile\$missing
bool $missing
True if file is not present in file system.
Definition: LocalFile.php:175
LocalFileDeleteBatch
Helper class for file deletion.
Definition: LocalFileDeleteBatch.php:33
MediaHandler\filterThumbnailPurgeList
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
Definition: MediaHandler.php:962
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1649
FileBackendError
File backend exception for checked exceptions (e.g.
Definition: FileBackendError.php:10
LocalFile\$upgraded
bool $upgraded
Whether the row was upgraded on load.
Definition: LocalFile.php:163
LocalFile\getDescriptionShortUrl
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
Definition: LocalFile.php:1034
LocalFile\getCacheFields
getCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache.
Definition: LocalFile.php:472
Title\getPrefixedText
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1893
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:125
ParserOptions\newFromUserAndLang
static newFromUserAndLang(UserIdentity $user, Language $lang)
Get a ParserOptions object from a given user and language.
Definition: ParserOptions.php:1055
LocalFile\getHistory
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
Definition: LocalFile.php:1609
LocalFile\getMediaType
getMediaType()
Returns the type of the media in the file.
Definition: LocalFile.php:1363
File\getUrl
getUrl()
Return the URL of the file.
Definition: File.php:384
LocalFile\$dataLoaded
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
Definition: LocalFile.php:127
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
LocalFile\readOnlyFatalStatus
readOnlyFatalStatus()
Definition: LocalFile.php:2749
LocalFile\newFromTitle
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:196
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1082
LocalFile\jsonDecode
jsonDecode(string $s)
Do JSON decoding with local flags.
Definition: LocalFile.php:1156
RequestContext\newExtraneousContext
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
Definition: RequestContext.php:658
LocalFile\$upgrading
bool $upgrading
Whether the row was scheduled to upgrade on load.
Definition: LocalFile.php:166
LocalFile\getSize
getSize()
Returns the size of the image file, in bytes.
Definition: LocalFile.php:1340
LocalFile\purgeOldThumbnails
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
Definition: LocalFile.php:1462
LocalFile\getMetadataItems
getMetadataItems(array $itemNames)
Get multiple elements of the unserialized handler-specific metadata.
Definition: LocalFile.php:1087
Wikimedia\Rdbms\IDatabase\decodeBlob
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
LocalFile\getThumbnails
getThumbnails( $archiveName=false)
getTransformScript inherited
Definition: LocalFile.php:1402
LocalFile\$metadataSerializationFormat
string null $metadataSerializationFormat
One of the MDS_* constants, giving the format of the metadata as stored in the DB,...
Definition: LocalFile.php:110
LocalFile\$sha1
string $sha1
SHA-1 base 36 content hash.
Definition: LocalFile.php:124
File\splitMime
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:306
$res
$res
Definition: testCompression.php:57
serialize
serialize()
Definition: ApiMessageTrait.php:138
LocalFile\$minor_mime
string $minor_mime
Minor MIME type.
Definition: LocalFile.php:148
File\getArchiveRel
getArchiveRel( $suffix=false)
Get the path of an archived file relative to the public zone root.
Definition: File.php:1698
MediaWiki\Permissions\Authority\getUser
getUser()
Returns the performer of the actions associated with this authority.
File\isDeleted
isDeleted( $field)
Is this file a "deleted" file in a private archive? STUB.
Definition: File.php:2039
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:958
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:39
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
LocalFile\jsonEncode
jsonEncode( $data)
Do JSON encoding with local flags.
Definition: LocalFile.php:1133
$dbr
$dbr
Definition: testCompression.php:54
LocalFile\isCacheable
isCacheable()
Definition: LocalFile.php:2644
FileRepo\publish
publish( $src, $dstRel, $archiveRel, $flags=0, array $options=[])
Copy or move a file either from a storage path, virtual URL, or file system path, into this repositor...
Definition: FileRepo.php:1259
Status
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:44
File\$path
string $path
The storage path corresponding to one of the zones.
Definition: File.php:144
LocalFile\$bits
int $bits
Returned by getimagesize (loadFromXxx)
Definition: LocalFile.php:90
LocalFile\purgeThumbnails
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
Definition: LocalFile.php:1489
getUser
getUser()
FileRepo\hasSha1Storage
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:1999
MediaHandler\METADATA_COMPATIBLE
const METADATA_COMPATIBLE
Definition: MediaHandler.php:42
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:67
LocalFile\loadExtraFromDB
loadExtraFromDB()
Load lazy file metadata from the DB.
Definition: LocalFile.php:543
LocalFile\publishTo
publishTo( $src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
Definition: LocalFile.php:2253
wfDeprecatedMsg
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: GlobalFunctions.php:1028
File\$url
string $url
The URL corresponding to one of the four basic zones.
Definition: File.php:135
MWException
MediaWiki exception.
Definition: MWException.php:29
LocalFile\newFromRow
static newFromRow( $row, $repo)
Create a LocalFile from a title Do not call this except from inside a repo class.
Definition: LocalFile.php:211
Wikimedia\Rdbms\IDatabase\encodeBlob
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
LocalFile\getDescriptionTouched
getDescriptionTouched()
Definition: LocalFile.php:2612
LocalFile\purgeMetadataCache
purgeMetadataCache()
Refresh metadata in memcached, but don't touch thumbnails or CDN.
Definition: LocalFile.php:1427
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
File\getThumbPath
getThumbPath( $suffix=false)
Get the path of the thumbnail directory, or a particular file if $suffix is specified.
Definition: File.php:1787
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:26
File\pageCount
pageCount()
Returns the number of pages of a multipage document, or false for documents which aren't multipage do...
Definition: File.php:2140
FileRepo\quickImport
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:1050
LocalFile\getUpgraded
getUpgraded()
Definition: LocalFile.php:801
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1510
Status\wrap
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:62
LocalFile\CACHE_FIELD_MAX_LEN
const CACHE_FIELD_MAX_LEN
Definition: LocalFile.php:66
LocalFile\loadFromRow
loadFromRow( $row, $prefix='img_')
Load file metadata from a DB result row.
Definition: LocalFile.php:651
LocalFile\__destruct
__destruct()
Clean up any dangling locks.
Definition: LocalFile.php:2757
LocalFile\$deleted
int $deleted
Bitfield akin to rev_deleted.
Definition: LocalFile.php:133
FSFile\getSha1Base36FromPath
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
LocalFile\$historyRes
IResultWrapper null $historyRes
Result of the query for the file's history (nextHistoryLine)
Definition: LocalFile.php:142
MediaHandler\isFileMetadataValid
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.
Definition: MediaHandler.php:372
EDIT_NEW
const EDIT_NEW
Definition: Defines.php:125
LocalFile\$user
UserIdentity null $user
Uploader.
Definition: LocalFile.php:154
LocalFile\getDescriptionText
getDescriptionText(Language $lang=null)
Get the HTML text of the description page This is not used by ImagePage for local files,...
Definition: LocalFile.php:2533
SiteStatsUpdate\factory
static factory(array $deltas)
Definition: SiteStatsUpdate.php:71
MWFileProps
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
File\userCan
userCan( $field, Authority $performer)
Determine if the current user is allowed to view a particular field of this file, if it's marked as d...
Definition: File.php:2328
LocalFile\prerenderThumbnails
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
Definition: LocalFile.php:1529
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:648
LocalFile\recordUpload3
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:1860
LocalFile\getCacheKey
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
MediaHandler\getPageDimensions
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
Definition: MediaHandler.php:606
LocalFile\$locked
int $locked
If >= 1 the image row is locked.
Definition: LocalFile.php:169
$revStore
$revStore
Definition: testCompression.php:55
LocalFile\$mime
string $mime
MIME type, determined by MimeAnalyzer::guessMimeType.
Definition: LocalFile.php:96
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:894
LocalFile\setProps
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info.
Definition: LocalFile.php:885
LocalFile\loadMetadataFromString
loadMetadataFromString( $metadataString)
Unserialize a metadata string which came from some non-DB source, or is the return value of IDatabase...
Definition: LocalFile.php:1286
FileRepo\getFileSha1
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1661
LocalFile
Class to represent a local file in the wiki's own database.
Definition: LocalFile.php:63
ContentHandler\makeContent
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Definition: ContentHandler.php:149
LocalFile\loadFromFile
loadFromFile( $path=null)
Load metadata from the file itself.
Definition: LocalFile.php:460
LocalFile\getMimeType
getMimeType()
Returns the MIME type of the file.
Definition: LocalFile.php:1351
LocalFile\$extraDataLoaded
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
Definition: LocalFile.php:130
ThumbnailRenderJob
Job for asynchronous rendering of thumbnails.
Definition: ThumbnailRenderJob.php:31
LocalFile\$size
int $size
Size in bytes (loadFromXxx)
Definition: LocalFile.php:99
MediaWiki\Permissions\Authority
This interface represents the authority associated the current execution context, such as a web reque...
Definition: Authority.php:37
LocalFile\getJsonMetadata
getJsonMetadata()
Get metadata in JSON format ready for DB insertion, optionally splitting items out to BlobStore.
Definition: LocalFile.php:1193
File\purgeDescription
purgeDescription()
Purge the file description page, but don't go after pages using the file.
Definition: File.php:1594
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
LocalFile\LOAD_ALL
const LOAD_ALL
Definition: LocalFile.php:178
LocalFile\lock
lock()
Start an atomic DB section and lock the image for update or increments a reference counter if the loc...
Definition: LocalFile.php:2688
File\isOld
isOld()
Returns true if the image is an old version STUB.
Definition: File.php:2027
File\$handler
MediaHandler $handler
Definition: File.php:132
ParserOptions\newFromContext
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
Definition: ParserOptions.php:1065
LocalFileLockError
Definition: LocalFileLockError.php:28
File\assertTitleDefined
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition: File.php:2442
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
LocalFile\$historyLine
int $historyLine
Number of line to return by nextHistoryLine() (constructor)
Definition: LocalFile.php:139
LocalFile\$metadataArray
array $metadataArray
Unserialized metadata.
Definition: LocalFile.php:102
LocalFile\releaseFileLock
releaseFileLock()
Release a lock acquired with acquireFileLock().
Definition: LocalFile.php:2672
LocalFile\upgradeRow
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file.
Definition: LocalFile.php:809
HTMLCacheUpdateJob\newForBacklinks
static newForBacklinks(PageReference $page, $table, $params=[])
Definition: HTMLCacheUpdateJob.php:61
LocalFile\load
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
Definition: LocalFile.php:729
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:131
LocalFile\newFromKey
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:230
LocalFile\nextHistoryLine
nextHistoryLine()
Returns the history of this file, line by line.
Definition: LocalFile.php:1668
LocalFile\upload
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, Authority $uploader=null, $tags=[], $createNullRevision=true, $revert=false)
getHashPath inherited
Definition: LocalFile.php:1757
File\$title
Title string bool $title
Definition: File.php:117
LocalFile\getBitDepth
getBitDepth()
Definition: LocalFile.php:1329
LocalFile\getMetadataForDb
getMetadataForDb(IDatabase $db)
Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.
Definition: LocalFile.php:1172
LocalFile\$height
int $height
Image height.
Definition: LocalFile.php:87
File\getArchiveThumbUrl
getArchiveThumbUrl( $archiveName, $suffix=false)
Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified.
Definition: File.php:1833
EDIT_SUPPRESS_RC
const EDIT_SUPPRESS_RC
Definition: Defines.php:128
LocalFile\loadMetadataFromDbFieldValue
loadMetadataFromDbFieldValue(IDatabase $db, $metadataBlob)
Unserialize a metadata blob which came from the database and store it in $this.
Definition: LocalFile.php:1275
File\getName
getName()
Return the name of this file.
Definition: File.php:331
File\getArchiveUrl
getArchiveUrl( $suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified.
Definition: File.php:1812
LocalFile\isMetadataOversize
isMetadataOversize()
Determine whether the loaded metadata may be a candidate for splitting, by measuring its serialized s...
Definition: LocalFile.php:1253
FSFile
Class representing a non-directory file on the file system.
Definition: FSFile.php:32
LocalFile\$timestamp
string $timestamp
Upload timestamp.
Definition: LocalFile.php:151
FileRepo\getBackend
getBackend()
Get the file backend instance.
Definition: FileRepo.php:251
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:484
LocalFile\$descriptionTouched
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
Definition: LocalFile.php:160
File\DELETE_SOURCE
const DELETE_SOURCE
Definition: File.php:84
MediaWiki\Storage\BlobStore
Service for loading and storing data blobs.
Definition: BlobStore.php:35
LocalFile\deleteFile
deleteFile( $reason, UserIdentity $user, $suppress=false)
Delete all versions of the file.
Definition: LocalFile.php:2388
LocalFile\deleteOldFile
deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress=false)
Delete an old version of the file.
Definition: LocalFile.php:2449
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:146
LocalFile\$description
string $description
Description of current revision of the file.
Definition: LocalFile.php:157
MediaWiki\Deferred\LinksUpdate\LinksUpdate
Class the manages updates of *_link tables as well as similar extension-managed tables.
Definition: LinksUpdate.php:55
LocalFile\getLazyCacheFields
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:494
File\getTitle
getTitle()
Return the associated title object.
Definition: File.php:361
LocalFile\getQueryInfo
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object.
Definition: LocalFile.php:267
LocalFile\getMetadata
getMetadata()
Get handler-specific metadata as a serialized string.
Definition: LocalFile.php:1056
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:114
MediaHandler\getContentHeaders
getContentHeaders( $metadata)
Get useful response headers for GET/HEAD requests for a file with the given metadata.
Definition: MediaHandler.php:1198
$cache
$cache
Definition: mcc.php:33
File\assertRepoDefined
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition: File.php:2432
LocalFile\resetHistory
resetHistory()
Reset the history pointer to the first element of the history.
Definition: LocalFile.php:1716
LocalFile\getDescription
getDescription( $audience=self::FOR_PUBLIC, Authority $performer=null)
Definition: LocalFile.php:2587
LogEntryBase\makeParamBlob
static makeParamBlob( $params)
Create a blob from a parameter array.
Definition: LogEntryBase.php:58
MediaHandler\getHandler
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
Definition: MediaHandler.php:54
FileRepo\isVirtualUrl
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:286
LocalFile\acquireFileLock
acquireFileLock( $timeout=0)
Acquire an exclusive lock on the file, indicating an intention to write to the file backend.
Definition: LocalFile.php:2660
LocalFile\loadExtraFieldsWithTimestamp
loadExtraFieldsWithTimestamp( $dbr, $fname)
Definition: LocalFile.php:574
LocalFileMoveBatch
Helper class for file movement.
Definition: LocalFileMoveBatch.php:34
LocalFile\getUploader
getUploader(int $audience=self::FOR_PUBLIC, Authority $performer=null)
Definition: LocalFile.php:2570
MediaHandler\METADATA_BAD
const METADATA_BAD
Definition: MediaHandler.php:41
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: ManualLogEntry.php:45
FileRepo\DELETE_SOURCE
const DELETE_SOURCE
Definition: FileRepo.php:46
WikiFilePage
Special handling for file pages.
Definition: WikiFilePage.php:32
LocalFile\publish
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
Definition: LocalFile.php:2233
Title\invalidateCache
invalidateCache( $purgeTime=null)
Updates page_touched for this page; called from LinksUpdate.php.
Definition: Title.php:3660
LocalFile\getWidth
getWidth( $page=1)
Return the width of the image @stable to override.
Definition: LocalFile.php:968
NS_FILE
const NS_FILE
Definition: Defines.php:70
File\getThumbUrl
getThumbUrl( $suffix=false)
Get the URL of the thumbnail directory, or a particular file if $suffix is specified.
Definition: File.php:1870
LocalFile\$major_mime
string $major_mime
Major MIME type.
Definition: LocalFile.php:145
File\isVectorized
isVectorized()
Return true if the file is vectorized.
Definition: File.php:629
File\getHandler
getHandler()
Get a MediaHandler instance for this file.
Definition: File.php:1527
LockManager\LOCK_EX
const LOCK_EX
Definition: LockManager.php:72
LocalFile\getHeight
getHeight( $page=1)
Return the height of the image @stable to override.
Definition: LocalFile.php:1001
LocalFile\isMissing
isMissing()
splitMime inherited
Definition: LocalFile.php:952
LocalFile\invalidateCache
invalidateCache()
Purge the file object/metadata cache.
Definition: LocalFile.php:439
LocalFile\$lockedOwnTrx
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
Definition: LocalFile.php:172
DeferredUpdates\addCallableUpdate
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add an update to the pending update queue that invokes the specified callback when run.
Definition: DeferredUpdates.php:151
LocalFile\VERSION
const VERSION
Definition: LocalFile.php:64
LocalFile\getDescriptionUrl
getDescriptionUrl()
isMultipage inherited
Definition: LocalFile.php:2516
LocalFile\move
move( $target)
getLinksTo inherited
Definition: LocalFile.php:2323
File\$name
string null $name
The name of a file from its title object.
Definition: File.php:141
LocalFile\$repoClass
string $repoClass
Definition: LocalFile.php:136
LocalFile\restore
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition: LocalFile.php:2483
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:42
File\purgeEverything
purgeEverything()
Purge metadata and all affected pages when the file is created, deleted, or majorly updated.
Definition: File.php:1607
LocalFile\exists
exists()
canRender inherited
Definition: LocalFile.php:1380
File\getThumbnails
getThumbnails()
Get all thumbnail names previously generated for this file STUB Overridden by LocalFile.
Definition: File.php:1574
LocalFile\getMetadataArray
getMetadataArray()
Get unserialized handler-specific metadata.
Definition: LocalFile.php:1074
LocalFile\loadFromCache
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
Definition: LocalFile.php:356
LocalFile\purgeCache
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
Definition: LocalFile.php:1439
File\getVirtualUrl
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
Definition: File.php:1891
LogFormatter\newFromEntry
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
Definition: LogFormatter.php:55
Article\purgePatrolFooterCache
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Definition: Article.php:1301
Wikimedia\Rdbms\Blob
Definition: Blob.php:9