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( 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  // Sanity 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  $this->description = MediaWikiServices::getInstance()->getCommentStore()
660  ->getComment( "{$prefix}description", $row )->text;
661 
662  $this->user = User::newFromAnyId(
663  $unprefixed['user'] ?? null,
664  $unprefixed['user_text'] ?? null,
665  $unprefixed['actor'] ?? null
666  );
667 
668  $this->timestamp = wfTimestamp( TS_MW, $unprefixed['timestamp'] );
669 
671  $this->repo->getReplicaDB(), $unprefixed['metadata'] );
672 
673  if ( empty( $unprefixed['major_mime'] ) ) {
674  $this->major_mime = 'unknown';
675  $this->minor_mime = 'unknown';
676  $this->mime = 'unknown/unknown';
677  } else {
678  if ( !$unprefixed['minor_mime'] ) {
679  $unprefixed['minor_mime'] = 'unknown';
680  }
681  $this->major_mime = $unprefixed['major_mime'];
682  $this->minor_mime = $unprefixed['minor_mime'];
683  $this->mime = $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
684  }
685 
686  // Trim zero padding from char/binary field
687  $this->sha1 = rtrim( $unprefixed['sha1'], "\0" );
688 
689  // Normalize some fields to integer type, per their database definition.
690  // Use unary + so that overflows will be upgraded to double instead of
691  // being trucated as with intval(). This is important to allow > 2 GiB
692  // files on 32-bit systems.
693  $this->size = +$unprefixed['size'];
694  $this->width = +$unprefixed['width'];
695  $this->height = +$unprefixed['height'];
696  $this->bits = +$unprefixed['bits'];
697 
698  // Check for extra fields (deprecated since MW 1.37)
699  $extraFields = array_diff(
700  array_keys( $unprefixed ),
701  [
702  'name', 'media_type', 'description_text', 'description_data',
703  'description_cid', 'user', 'user_text', 'actor', 'timestamp',
704  'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
705  'height', 'bits'
706  ]
707  );
708  if ( $extraFields ) {
710  'Passing extra fields (' .
711  implode( ', ', $extraFields )
712  . ') to ' . __METHOD__ . ' was deprecated in MediaWiki 1.37. ' .
713  'Property assignment will be removed in a later version.',
714  '1.37' );
715  foreach ( $extraFields as $field ) {
716  $this->$field = $unprefixed[$field];
717  }
718  }
719 
720  $this->fileExists = true;
721  }
722 
728  public function load( $flags = 0 ) {
729  if ( !$this->dataLoaded ) {
730  if ( $flags & self::READ_LATEST ) {
731  $this->loadFromDB( $flags );
732  } else {
733  $this->loadFromCache();
734  }
735  }
736 
737  if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
738  // @note: loads on name/timestamp to reduce race condition problems
739  $this->loadExtraFromDB();
740  }
741  }
742 
747  public function maybeUpgradeRow() {
748  if ( wfReadOnly() || $this->upgrading ) {
749  return;
750  }
751 
752  $upgrade = false;
753  $reserialize = false;
754  if ( $this->media_type === null || $this->mime == 'image/svg' ) {
755  $upgrade = true;
756  } else {
757  $handler = $this->getHandler();
758  if ( $handler ) {
759  $validity = $handler->isFileMetadataValid( $this );
760  if ( $validity === MediaHandler::METADATA_BAD ) {
761  $upgrade = true;
762  } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE
763  && $this->repo->isMetadataUpdateEnabled()
764  ) {
765  $upgrade = true;
766  } elseif ( $this->repo->isJsonMetadataEnabled()
767  && $this->repo->isMetadataReserializeEnabled()
768  ) {
769  if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
770  $reserialize = true;
771  } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
772  $this->metadataSerializationFormat !== self::MDS_JSON ) {
773  $reserialize = true;
774  }
775  }
776  }
777  }
778 
779  if ( $upgrade || $reserialize ) {
780  $this->upgrading = true;
781  // Defer updates unless in auto-commit CLI mode
782  DeferredUpdates::addCallableUpdate( function () use ( $upgrade ) {
783  $this->upgrading = false; // avoid duplicate updates
784  try {
785  if ( $upgrade ) {
786  $this->upgradeRow();
787  } else {
788  $this->reserializeMetadata();
789  }
790  } catch ( LocalFileLockError $e ) {
791  // let the other process handle it (or do it next time)
792  }
793  } );
794  }
795  }
796 
800  public function getUpgraded() {
801  return $this->upgraded;
802  }
803 
808  public function upgradeRow() {
809  $this->lock();
810 
811  $this->loadFromFile();
812 
813  # Don't destroy file info of missing files
814  if ( !$this->fileExists ) {
815  $this->unlock();
816  wfDebug( __METHOD__ . ": file does not exist, aborting" );
817 
818  return;
819  }
820 
821  $dbw = $this->repo->getPrimaryDB();
822  list( $major, $minor ) = self::splitMime( $this->mime );
823 
824  if ( wfReadOnly() ) {
825  $this->unlock();
826 
827  return;
828  }
829  wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
830 
831  $dbw->update( 'image',
832  [
833  'img_size' => $this->size, // sanity
834  'img_width' => $this->width,
835  'img_height' => $this->height,
836  'img_bits' => $this->bits,
837  'img_media_type' => $this->media_type,
838  'img_major_mime' => $major,
839  'img_minor_mime' => $minor,
840  'img_metadata' => $this->getMetadataForDb( $dbw ),
841  'img_sha1' => $this->sha1,
842  ],
843  [ 'img_name' => $this->getName() ],
844  __METHOD__
845  );
846 
847  $this->invalidateCache();
848 
849  $this->unlock();
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->hookRunner->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() {
1531 
1532  $jobs = [];
1533 
1534  $sizes = $wgUploadThumbnailRenderMap;
1535  rsort( $sizes );
1536 
1537  foreach ( $sizes as $size ) {
1538  if ( $this->isMultipage() ) {
1539  for ( $page = 1; $page <= $this->pageCount(); $page++ ) {
1540  $jobs[] = new ThumbnailRenderJob(
1541  $this->getTitle(),
1542  [ 'transformParams' => [
1543  'width' => $size,
1544  'page' => $page,
1545  ] ]
1546  );
1547  }
1548  } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1549  $jobs[] = new ThumbnailRenderJob(
1550  $this->getTitle(),
1551  [ 'transformParams' => [ 'width' => $size ] ]
1552  );
1553  }
1554  }
1555 
1556  if ( $jobs ) {
1557  JobQueueGroup::singleton()->lazyPush( $jobs );
1558  }
1559  }
1560 
1567  protected function purgeThumbList( $dir, $files ) {
1568  $fileListDebug = strtr(
1569  var_export( $files, true ),
1570  [ "\n" => '' ]
1571  );
1572  wfDebug( __METHOD__ . ": $fileListDebug" );
1573 
1574  if ( $this->repo->supportsSha1URLs() ) {
1575  $reference = $this->getSha1();
1576  } else {
1577  $reference = $this->getName();
1578  }
1579 
1580  $purgeList = [];
1581  foreach ( $files as $file ) {
1582  # Check that the reference (filename or sha1) is part of the thumb name
1583  # This is a basic sanity check to avoid erasing unrelated directories
1584  if ( strpos( $file, $reference ) !== false
1585  || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1586  ) {
1587  $purgeList[] = "{$dir}/{$file}";
1588  }
1589  }
1590 
1591  # Delete the thumbnails
1592  $this->repo->quickPurgeBatch( $purgeList );
1593  # Clear out the thumbnail directory if empty
1594  $this->repo->quickCleanDir( $dir );
1595  }
1596 
1608  public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1609  if ( !$this->exists() ) {
1610  return []; // Avoid hard failure when the file does not exist. T221812
1611  }
1612 
1613  $dbr = $this->repo->getReplicaDB();
1614  $oldFileQuery = OldLocalFile::getQueryInfo();
1615 
1616  $tables = $oldFileQuery['tables'];
1617  $fields = $oldFileQuery['fields'];
1618  $join_conds = $oldFileQuery['joins'];
1619  $conds = $opts = [];
1620  $eq = $inc ? '=' : '';
1621  $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1622 
1623  if ( $start ) {
1624  $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1625  }
1626 
1627  if ( $end ) {
1628  $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1629  }
1630 
1631  if ( $limit ) {
1632  $opts['LIMIT'] = $limit;
1633  }
1634 
1635  // Search backwards for time > x queries
1636  $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1637  $opts['ORDER BY'] = "oi_timestamp $order";
1638  $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1639 
1640  $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1641  $conds, $opts, $join_conds );
1642 
1643  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1644  $r = [];
1645 
1646  foreach ( $res as $row ) {
1647  $r[] = $this->repo->newFileFromRow( $row );
1648  }
1649 
1650  if ( $order == 'ASC' ) {
1651  $r = array_reverse( $r ); // make sure it ends up descending
1652  }
1653 
1654  return $r;
1655  }
1656 
1667  public function nextHistoryLine() {
1668  if ( !$this->exists() ) {
1669  return false; // Avoid hard failure when the file does not exist. T221812
1670  }
1671 
1672  # Polymorphic function name to distinguish foreign and local fetches
1673  $fname = static::class . '::' . __FUNCTION__;
1674 
1675  $dbr = $this->repo->getReplicaDB();
1676 
1677  if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1678  $fileQuery = self::getQueryInfo();
1679  $this->historyRes = $dbr->select( $fileQuery['tables'],
1680  $fileQuery['fields'] + [
1681  'oi_archive_name' => $dbr->addQuotes( '' ),
1682  'oi_deleted' => 0,
1683  ],
1684  [ 'img_name' => $this->title->getDBkey() ],
1685  $fname,
1686  [],
1687  $fileQuery['joins']
1688  );
1689 
1690  if ( $dbr->numRows( $this->historyRes ) == 0 ) {
1691  $this->historyRes = null;
1692 
1693  return false;
1694  }
1695  } elseif ( $this->historyLine == 1 ) {
1696  $fileQuery = OldLocalFile::getQueryInfo();
1697  $this->historyRes = $dbr->select(
1698  $fileQuery['tables'],
1699  $fileQuery['fields'],
1700  [ 'oi_name' => $this->title->getDBkey() ],
1701  $fname,
1702  [ 'ORDER BY' => 'oi_timestamp DESC' ],
1703  $fileQuery['joins']
1704  );
1705  }
1706  $this->historyLine++;
1707 
1708  return $dbr->fetchObject( $this->historyRes );
1709  }
1710 
1715  public function resetHistory() {
1716  $this->historyLine = 0;
1717 
1718  if ( $this->historyRes !== null ) {
1719  $this->historyRes = null;
1720  }
1721  }
1722 
1756  public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1757  $timestamp = false, Authority $uploader = null, $tags = [],
1758  $createNullRevision = true, $revert = false
1759  ) {
1760  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1761  return $this->readOnlyFatalStatus();
1762  } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1763  // Check this in advance to avoid writing to FileBackend and the file tables,
1764  // only to fail on insert the revision due to the text store being unavailable.
1765  return $this->readOnlyFatalStatus();
1766  }
1767 
1768  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1769  if ( !$props ) {
1770  if ( FileRepo::isVirtualUrl( $srcPath )
1771  || FileBackend::isStoragePath( $srcPath )
1772  ) {
1773  $props = $this->repo->getFileProps( $srcPath );
1774  } else {
1775  $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1776  $props = $mwProps->getPropsFromPath( $srcPath, true );
1777  }
1778  }
1779 
1780  $options = [];
1781  $handler = MediaHandler::getHandler( $props['mime'] );
1782  if ( $handler ) {
1783  if ( is_string( $props['metadata'] ) ) {
1784  // This supports callers directly fabricating a metadata
1785  // property using serialize(). Normally the metadata property
1786  // comes from MWFileProps, in which case it won't be a string.
1787  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1788  $metadata = @unserialize( $props['metadata'] );
1789  } else {
1790  $metadata = $props['metadata'];
1791  }
1792 
1793  if ( is_array( $metadata ) ) {
1794  $options['headers'] = $handler->getContentHeaders( $metadata );
1795  }
1796  } else {
1797  $options['headers'] = [];
1798  }
1799 
1800  // Trim spaces on user supplied text
1801  $comment = trim( $comment );
1802 
1803  $this->lock();
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  $this->unlock();
1842  return $status;
1843  }
1844 
1861  public function recordUpload3(
1862  string $oldver,
1863  string $comment,
1864  string $pageText,
1865  Authority $performer,
1866  $props = false,
1867  $timestamp = false,
1868  $tags = [],
1869  bool $createNullRevision = true,
1870  bool $revert = false
1871  ): Status {
1872  $dbw = $this->repo->getPrimaryDB();
1873 
1874  # Imports or such might force a certain timestamp; otherwise we generate
1875  # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1876  if ( $timestamp === false ) {
1877  $timestamp = $dbw->timestamp();
1878  $allowTimeKludge = true;
1879  } else {
1880  $allowTimeKludge = false;
1881  }
1882 
1883  $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1884  $props['description'] = $comment;
1885  $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1886  $this->setProps( $props );
1887 
1888  # Fail now if the file isn't there
1889  if ( !$this->fileExists ) {
1890  wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1891 
1892  return Status::newFatal( 'filenotfound', $this->getRel() );
1893  }
1894 
1895  $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1896 
1897  $dbw->startAtomic( __METHOD__ );
1898 
1899  $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1900  $this->user = $performer->getUser();
1901 
1902  # Test to see if the row exists using INSERT IGNORE
1903  # This avoids race conditions by locking the row until the commit, and also
1904  # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1905  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1906  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1907  $actorFields = [ 'img_actor' => $actorId ];
1908  $dbw->insert( 'image',
1909  [
1910  'img_name' => $this->getName(),
1911  'img_size' => $this->size,
1912  'img_width' => intval( $this->width ),
1913  'img_height' => intval( $this->height ),
1914  'img_bits' => $this->bits,
1915  'img_media_type' => $this->media_type,
1916  'img_major_mime' => $this->major_mime,
1917  'img_minor_mime' => $this->minor_mime,
1918  'img_timestamp' => $timestamp,
1919  'img_metadata' => $this->getMetadataForDb( $dbw ),
1920  'img_sha1' => $this->sha1
1921  ] + $commentFields + $actorFields,
1922  __METHOD__,
1923  [ 'IGNORE' ]
1924  );
1925  $reupload = ( $dbw->affectedRows() == 0 );
1926 
1927  if ( $reupload ) {
1928  $row = $dbw->selectRow(
1929  'image',
1930  [ 'img_timestamp', 'img_sha1' ],
1931  [ 'img_name' => $this->getName() ],
1932  __METHOD__,
1933  [ 'LOCK IN SHARE MODE' ]
1934  );
1935 
1936  if ( $row && $row->img_sha1 === $this->sha1 ) {
1937  $dbw->endAtomic( __METHOD__ );
1938  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1939  $title = Title::newFromText( $this->getName(), NS_FILE );
1940  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1941  }
1942 
1943  if ( $allowTimeKludge ) {
1944  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1945  $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1946  # Avoid a timestamp that is not newer than the last version
1947  # TODO: the image/oldimage tables should be like page/revision with an ID field
1948  if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1949  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1950  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1951  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1952  }
1953  }
1954 
1955  $tables = [ 'image' ];
1956  $fields = [
1957  'oi_name' => 'img_name',
1958  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1959  'oi_size' => 'img_size',
1960  'oi_width' => 'img_width',
1961  'oi_height' => 'img_height',
1962  'oi_bits' => 'img_bits',
1963  'oi_description_id' => 'img_description_id',
1964  'oi_timestamp' => 'img_timestamp',
1965  'oi_metadata' => 'img_metadata',
1966  'oi_media_type' => 'img_media_type',
1967  'oi_major_mime' => 'img_major_mime',
1968  'oi_minor_mime' => 'img_minor_mime',
1969  'oi_sha1' => 'img_sha1',
1970  'oi_actor' => 'img_actor',
1971  ];
1972  $joins = [];
1973 
1974  # (T36993) Note: $oldver can be empty here, if the previous
1975  # version of the file was broken. Allow registration of the new
1976  # version to continue anyway, because that's better than having
1977  # an image that's not fixable by user operations.
1978  # Collision, this is an update of a file
1979  # Insert previous contents into oldimage
1980  $dbw->insertSelect( 'oldimage', $tables, $fields,
1981  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1982 
1983  # Update the current image row
1984  $dbw->update( 'image',
1985  [
1986  'img_size' => $this->size,
1987  'img_width' => intval( $this->width ),
1988  'img_height' => intval( $this->height ),
1989  'img_bits' => $this->bits,
1990  'img_media_type' => $this->media_type,
1991  'img_major_mime' => $this->major_mime,
1992  'img_minor_mime' => $this->minor_mime,
1993  'img_timestamp' => $timestamp,
1994  'img_metadata' => $this->getMetadataForDb( $dbw ),
1995  'img_sha1' => $this->sha1
1996  ] + $commentFields + $actorFields,
1997  [ 'img_name' => $this->getName() ],
1998  __METHOD__
1999  );
2000  }
2001 
2002  $descTitle = $this->getTitle();
2003  $descId = $descTitle->getArticleID();
2004  $wikiPage = new WikiFilePage( $descTitle );
2005  $wikiPage->setFile( $this );
2006 
2007  // Determine log action. If reupload is done by reverting, use a special log_action.
2008  if ( $revert ) {
2009  $logAction = 'revert';
2010  } elseif ( $reupload ) {
2011  $logAction = 'overwrite';
2012  } else {
2013  $logAction = 'upload';
2014  }
2015  // Add the log entry...
2016  $logEntry = new ManualLogEntry( 'upload', $logAction );
2017  $logEntry->setTimestamp( $this->timestamp );
2018  $logEntry->setPerformer( $performer->getUser() );
2019  $logEntry->setComment( $comment );
2020  $logEntry->setTarget( $descTitle );
2021  // Allow people using the api to associate log entries with the upload.
2022  // Log has a timestamp, but sometimes different from upload timestamp.
2023  $logEntry->setParameters(
2024  [
2025  'img_sha1' => $this->sha1,
2026  'img_timestamp' => $timestamp,
2027  ]
2028  );
2029  // Note we keep $logId around since during new image
2030  // creation, page doesn't exist yet, so log_page = 0
2031  // but we want it to point to the page we're making,
2032  // so we later modify the log entry.
2033  // For a similar reason, we avoid making an RC entry
2034  // now and wait until the page exists.
2035  $logId = $logEntry->insert();
2036 
2037  if ( $descTitle->exists() ) {
2038  if ( $createNullRevision ) {
2039  $revStore = MediaWikiServices::getInstance()->getRevisionStore();
2040  // Use own context to get the action text in content language
2041  $formatter = LogFormatter::newFromEntry( $logEntry );
2042  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
2043  $editSummary = $formatter->getPlainActionText();
2044  $summary = CommentStoreComment::newUnsavedComment( $editSummary );
2045  $nullRevRecord = $revStore->newNullRevision(
2046  $dbw,
2047  $descTitle,
2048  $summary,
2049  false,
2050  $performer->getUser()
2051  );
2052 
2053  if ( $nullRevRecord ) {
2054  $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
2055 
2056  $this->getHookRunner()->onRevisionFromEditComplete(
2057  $wikiPage,
2058  $inserted,
2059  $inserted->getParentId(),
2060  $performer->getUser(),
2061  $tags
2062  );
2063 
2064  $wikiPage->updateRevisionOn( $dbw, $inserted );
2065  // Associate null revision id
2066  $logEntry->setAssociatedRevId( $inserted->getId() );
2067  }
2068  }
2069 
2070  $newPageContent = null;
2071  } else {
2072  // Make the description page and RC log entry post-commit
2073  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
2074  }
2075 
2076  // NOTE: Even after ending this atomic section, we are probably still in the transaction
2077  // started by the call to lock() in publishTo(). We cannot yet safely schedule jobs,
2078  // see T263301.
2079  $dbw->endAtomic( __METHOD__ );
2080  $fname = __METHOD__;
2081 
2082  # Do some cache purges after final commit so that:
2083  # a) Changes are more likely to be seen post-purge
2084  # b) They won't cause rollback of the log publish/update above
2085  $purgeUpdate = new AutoCommitUpdate(
2086  $dbw,
2087  __METHOD__,
2089  function () use (
2090  $reupload, $wikiPage, $newPageContent, $comment, $performer,
2091  $logEntry, $logId, $descId, $tags, $fname
2092  ) {
2093  # Update memcache after the commit
2094  $this->invalidateCache();
2095 
2096  $updateLogPage = false;
2097  if ( $newPageContent ) {
2098  # New file page; create the description page.
2099  # There's already a log entry, so don't make a second RC entry
2100  # CDN and file cache for the description page are purged by doUserEditContent.
2101  $status = $wikiPage->doUserEditContent(
2102  $newPageContent,
2103  $performer,
2104  $comment,
2106  );
2107 
2108  if ( isset( $status->value['revision-record'] ) ) {
2110  $revRecord = $status->value['revision-record'];
2111  // Associate new page revision id
2112  $logEntry->setAssociatedRevId( $revRecord->getId() );
2113  }
2114  // This relies on the resetArticleID() call in WikiPage::insertOn(),
2115  // which is triggered on $descTitle by doUserEditContent() above.
2116  if ( isset( $status->value['revision-record'] ) ) {
2118  $revRecord = $status->value['revision-record'];
2119  $updateLogPage = $revRecord->getPageId();
2120  }
2121  } else {
2122  # Existing file page: invalidate description page cache
2123  $title = $wikiPage->getTitle();
2125  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2126  $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2127  # Allow the new file version to be patrolled from the page footer
2129  }
2130 
2131  # Update associated rev id. This should be done by $logEntry->insert() earlier,
2132  # but setAssociatedRevId() wasn't called at that point yet...
2133  $logParams = $logEntry->getParameters();
2134  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
2135  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
2136  if ( $updateLogPage ) {
2137  # Also log page, in case where we just created it above
2138  $update['log_page'] = $updateLogPage;
2139  }
2140  $this->getRepo()->getPrimaryDB()->update(
2141  'logging',
2142  $update,
2143  [ 'log_id' => $logId ],
2144  $fname
2145  );
2146  $this->getRepo()->getPrimaryDB()->insert(
2147  'log_search',
2148  [
2149  'ls_field' => 'associated_rev_id',
2150  'ls_value' => (string)$logEntry->getAssociatedRevId(),
2151  'ls_log_id' => $logId,
2152  ],
2153  $fname
2154  );
2155 
2156  # Add change tags, if any
2157  if ( $tags ) {
2158  $logEntry->addTags( $tags );
2159  }
2160 
2161  # Uploads can be patrolled
2162  $logEntry->setIsPatrollable( true );
2163 
2164  # Now that the log entry is up-to-date, make an RC entry.
2165  $logEntry->publish( $logId );
2166 
2167  # Run hook for other updates (typically more cache purging)
2168  $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2169 
2170  if ( $reupload ) {
2171  # Delete old thumbnails
2172  $this->purgeThumbnails();
2173  # Remove the old file from the CDN cache
2174  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2175  $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2176  } else {
2177  # Update backlink pages pointing to this title if created
2178  $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2180  $this->getTitle(),
2181  'imagelinks',
2182  'upload-image',
2183  $performer->getUser()->getName(),
2184  $blcFactory->getBacklinkCache( $this->getTitle() )
2185  );
2186  }
2187 
2188  $this->prerenderThumbnails();
2189  }
2190  );
2191 
2192  # Invalidate cache for all pages using this file
2193  $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
2194  $this->getTitle(),
2195  'imagelinks',
2196  [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2197  );
2198 
2199  // NOTE: We are probably still in the transaction started by the call to lock() in
2200  // publishTo(). We should only schedule jobs after that transaction was committed,
2201  // so a job queue failure doesn't cause the upload to fail (T263301).
2202  // Also, we should generally not schedule any Jobs or the DeferredUpdates that
2203  // assume the update is complete until after the transaction has been committed and
2204  // we are sure that the upload was indeed successful.
2205  $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2206  DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2207 
2208  if ( !$reupload ) {
2209  // This is a new file, so update the image count
2210  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2211  }
2212 
2213  JobQueueGroup::singleton()->lazyPush( $cacheUpdateJob );
2214  }, __METHOD__ );
2215 
2216  return Status::newGood();
2217  }
2218 
2235  public function publish( $src, $flags = 0, array $options = [] ) {
2236  return $this->publishTo( $src, $this->getRel(), $flags, $options );
2237  }
2238 
2255  protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2256  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
2257 
2258  $repo = $this->getRepo();
2259  if ( $repo->getReadOnlyReason() !== false ) {
2260  return $this->readOnlyFatalStatus();
2261  }
2262 
2263  $this->lock();
2264 
2265  if ( $this->isOld() ) {
2266  $archiveRel = $dstRel;
2267  $archiveName = basename( $archiveRel );
2268  } else {
2269  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
2270  $archiveRel = $this->getArchiveRel( $archiveName );
2271  }
2272 
2273  if ( $repo->hasSha1Storage() ) {
2274  $sha1 = FileRepo::isVirtualUrl( $srcPath )
2275  ? $repo->getFileSha1( $srcPath )
2276  : FSFile::getSha1Base36FromPath( $srcPath );
2278  $wrapperBackend = $repo->getBackend();
2279  '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2280  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2281  $status = $repo->quickImport( $src, $dst );
2282  if ( $flags & File::DELETE_SOURCE ) {
2283  unlink( $srcPath );
2284  }
2285 
2286  if ( $this->exists() ) {
2287  $status->value = $archiveName;
2288  }
2289  } else {
2290  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2291  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2292 
2293  if ( $status->value == 'new' ) {
2294  $status->value = '';
2295  } else {
2296  $status->value = $archiveName;
2297  }
2298  }
2299 
2300  $this->unlock();
2301  return $status;
2302  }
2303 
2322  public function move( $target ) {
2323  $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2324  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2325  return $this->readOnlyFatalStatus();
2326  }
2327 
2328  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2329  $batch = new LocalFileMoveBatch( $this, $target );
2330 
2331  $this->lock();
2332  $batch->addCurrent();
2333  $archiveNames = $batch->addOlds();
2334  $status = $batch->execute();
2335  $this->unlock();
2336 
2337  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2338 
2339  // Purge the source and target files outside the transaction...
2340  $oldTitleFile = $localRepo->newFile( $this->title );
2341  $newTitleFile = $localRepo->newFile( $target );
2343  new AutoCommitUpdate(
2344  $this->getRepo()->getPrimaryDB(),
2345  __METHOD__,
2346  static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2347  $oldTitleFile->purgeEverything();
2348  foreach ( $archiveNames as $archiveName ) {
2350  '@phan-var OldLocalFile $oldTitleFile';
2351  $oldTitleFile->purgeOldThumbnails( $archiveName );
2352  }
2353  $newTitleFile->purgeEverything();
2354  }
2355  ),
2356  DeferredUpdates::PRESEND
2357  );
2358 
2359  if ( $status->isOK() ) {
2360  // Now switch the object
2361  $this->title = $target;
2362  // Force regeneration of the name and hashpath
2363  $this->name = null;
2364  $this->hashPath = null;
2365  }
2366 
2367  return $status;
2368  }
2369 
2386  public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2387  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2388  return $this->readOnlyFatalStatus();
2389  }
2390 
2391  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2392 
2393  $this->lock();
2394  $batch->addCurrent();
2395  // Get old version relative paths
2396  $archiveNames = $batch->addOlds();
2397  $status = $batch->execute();
2398  $this->unlock();
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  $this->lock();
2457  $batch->addOld( $archiveName );
2458  $status = $batch->execute();
2459  $this->unlock();
2460 
2461  $this->purgeOldThumbnails( $archiveName );
2462  if ( $status->isOK() ) {
2463  $this->purgeDescription();
2464  }
2465 
2466  $url = $this->getArchiveUrl( $archiveName );
2467  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2468  $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2469 
2470  return $status;
2471  }
2472 
2485  public function restore( $versions = [], $unsuppress = false ) {
2486  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2487  return $this->readOnlyFatalStatus();
2488  }
2489 
2490  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2491 
2492  $this->lock();
2493  if ( !$versions ) {
2494  $batch->addAll();
2495  } else {
2496  $batch->addIds( $versions );
2497  }
2498  $status = $batch->execute();
2499  if ( $status->isGood() ) {
2500  $cleanupStatus = $batch->cleanup();
2501  $cleanupStatus->successCount = 0;
2502  $cleanupStatus->failCount = 0;
2503  $status->merge( $cleanupStatus );
2504  }
2505 
2506  $this->unlock();
2507  return $status;
2508  }
2509 
2520  public function getDescriptionUrl() {
2521  if ( !$this->title ) {
2522  return false; // Avoid hard failure when the file does not exist. T221812
2523  }
2524 
2525  return $this->title->getLocalURL();
2526  }
2527 
2537  public function getDescriptionText( Language $lang = null ) {
2538  if ( !$this->title ) {
2539  return false; // Avoid hard failure when the file does not exist. T221812
2540  }
2541 
2542  $store = MediaWikiServices::getInstance()->getRevisionStore();
2543  $revision = $store->getRevisionByTitle( $this->title, 0, RevisionStore::READ_NORMAL );
2544  if ( !$revision ) {
2545  return false;
2546  }
2547 
2548  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2549  $rendered = $renderer->getRenderedRevision(
2550  $revision,
2553  $lang
2554  )
2555  );
2556 
2557  if ( !$rendered ) {
2558  // audience check failed
2559  return false;
2560  }
2561 
2562  $pout = $rendered->getRevisionParserOutput();
2563  return $pout->getText();
2564  }
2565 
2573  public function getUploader( int $audience = self::FOR_PUBLIC, Authority $performer = null ): ?UserIdentity {
2574  $this->load();
2575  if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2576  return null;
2577  } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2578  return null;
2579  } else {
2580  return $this->user;
2581  }
2582  }
2583 
2590  public function getDescription( $audience = self::FOR_PUBLIC, Authority $performer = null ) {
2591  $this->load();
2592  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2593  return '';
2594  } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2595  return '';
2596  } else {
2597  return $this->description;
2598  }
2599  }
2600 
2605  public function getTimestamp() {
2606  $this->load();
2607 
2608  return $this->timestamp;
2609  }
2610 
2615  public function getDescriptionTouched() {
2616  if ( !$this->exists() ) {
2617  return false; // Avoid hard failure when the file does not exist. T221812
2618  }
2619 
2620  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2621  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2622  // need to differentiate between null (uninitialized) and false (failed to load).
2623  if ( $this->descriptionTouched === null ) {
2624  $cond = [
2625  'page_namespace' => $this->title->getNamespace(),
2626  'page_title' => $this->title->getDBkey()
2627  ];
2628  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2629  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2630  }
2631 
2633  }
2634 
2639  public function getSha1() {
2640  $this->load();
2641  // Initialise now if necessary
2642  if ( $this->sha1 == '' && $this->fileExists ) {
2643  $this->lock();
2644 
2645  $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2646  if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2647  $dbw = $this->repo->getPrimaryDB();
2648  $dbw->update( 'image',
2649  [ 'img_sha1' => $this->sha1 ],
2650  [ 'img_name' => $this->getName() ],
2651  __METHOD__ );
2652  $this->invalidateCache();
2653  }
2654 
2655  $this->unlock();
2656  }
2657 
2658  return $this->sha1;
2659  }
2660 
2664  public function isCacheable() {
2665  $this->load();
2666 
2667  // If extra data (metadata) was not loaded then it must have been large
2668  return $this->extraDataLoaded
2669  && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2670  }
2671 
2676  public function acquireFileLock() {
2677  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2678  [ $this->getPath() ], LockManager::LOCK_EX, 10
2679  ) );
2680  }
2681 
2686  public function releaseFileLock() {
2687  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2688  [ $this->getPath() ], LockManager::LOCK_EX
2689  ) );
2690  }
2691 
2701  public function lock() {
2702  if ( !$this->locked ) {
2703  $logger = LoggerFactory::getInstance( 'LocalFile' );
2704 
2705  $dbw = $this->repo->getPrimaryDB();
2706  $makesTransaction = !$dbw->trxLevel();
2707  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2708  // T56736: use simple lock to handle when the file does not exist.
2709  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2710  // Also, that would cause contention on INSERT of similarly named rows.
2711  $status = $this->acquireFileLock(); // represents all versions of the file
2712  if ( !$status->isGood() ) {
2713  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2714  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2715 
2716  throw new LocalFileLockError( $status );
2717  }
2718  // Release the lock *after* commit to avoid row-level contention.
2719  // Make sure it triggers on rollback() as well as commit() (T132921).
2720  $dbw->onTransactionResolution(
2721  function () use ( $logger ) {
2722  $status = $this->releaseFileLock();
2723  if ( !$status->isGood() ) {
2724  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2725  }
2726  },
2727  __METHOD__
2728  );
2729  // Callers might care if the SELECT snapshot is safely fresh
2730  $this->lockedOwnTrx = $makesTransaction;
2731  }
2732 
2733  $this->locked++;
2734 
2735  return $this->lockedOwnTrx;
2736  }
2737 
2746  public function unlock() {
2747  if ( $this->locked ) {
2748  --$this->locked;
2749  if ( !$this->locked ) {
2750  $dbw = $this->repo->getPrimaryDB();
2751  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2752  $this->lockedOwnTrx = false;
2753  }
2754  }
2755  }
2756 
2760  protected function readOnlyFatalStatus() {
2761  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2762  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2763  }
2764 
2768  public function __destruct() {
2769  $this->unlock();
2770  }
2771 }
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:2639
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:456
LocalFile\maybeUpgradeRow
maybeUpgradeRow()
Upgrade a row if it needs it.
Definition: LocalFile.php:747
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:52
LocalFileRestoreBatch
Helper class for file undeletion.
Definition: LocalFileRestoreBatch.php:30
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:382
File\$repo
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition: File.php:113
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:1790
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:2746
LocalFile\getTimestamp
getTimestamp()
Definition: LocalFile.php:2605
File\isMultipage
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition: File.php:2146
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:193
$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:1567
File\getRel
getRel()
Get the path of the file relative to the public zone root.
Definition: File.php:1703
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
MediaWiki\Revision\RevisionStore
Service for looking up page revisions.
Definition: RevisionStore.php:88
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:32
MediaHandler\filterThumbnailPurgeList
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
Definition: MediaHandler.php:961
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1668
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:1911
File\getUser
getUser( $type='text')
Returns ID or name of user who uploaded the file STUB.
Definition: File.php:614
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:119
ParserOptions\newFromUserAndLang
static newFromUserAndLang(UserIdentity $user, Language $lang)
Get a ParserOptions object from a given user and language.
Definition: ParserOptions.php:1087
LocalFile\getHistory
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
Definition: LocalFile.php:1608
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:383
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:2760
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:1101
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:305
$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:1715
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:2056
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
LocalFile\acquireFileLock
acquireFileLock()
Definition: LocalFile.php:2676
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:2664
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:1263
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:143
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
FileRepo\hasSha1Storage
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:2008
MediaHandler\METADATA_COMPATIBLE
const METADATA_COMPATIBLE
Definition: MediaHandler.php:41
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:66
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:2255
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:134
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:2615
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:1804
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:2157
FileRepo\quickImport
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:1054
LocalFile\getUpgraded
getUpgraded()
Definition: LocalFile.php:800
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1525
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:2768
LocalFile\$deleted
int $deleted
Bitfield akin to rev_deleted.
Definition: LocalFile.php:133
$wgUploadThumbnailRenderMap
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
Definition: DefaultSettings.php:1698
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:371
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:2537
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:2366
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:650
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:1861
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:605
LocalFile\$locked
int $locked
If >= 1 the image row is locked.
Definition: LocalFile.php:169
User\newFromAnyId
static newFromAnyId( $userId, $userName, $actorId, $dbDomain=false)
Static factory method for creation from an ID, name, and/or actor ID.
Definition: User.php:712
$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:1670
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:146
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:1611
$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:2701
File\isOld
isOld()
Returns true if the image is an old version STUB.
Definition: File.php:2044
File\$handler
MediaHandler $handler
Definition: File.php:131
LocalFileLockError
@newable
Definition: LocalFileLockError.php:28
File\assertTitleDefined
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition: File.php:2480
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()
Definition: LocalFile.php:2686
LocalFile\upgradeRow
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file.
Definition: LocalFile.php:808
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:728
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:128
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:1667
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:1756
File\$title
Title string bool $title
Definition: File.php:116
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:1850
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:330
File\getArchiveUrl
getArchiveUrl( $suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified.
Definition: File.php:1829
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:83
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:2386
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
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:360
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:1197
LinksUpdate\queueRecursiveJobsForTable
static queueRecursiveJobsForTable(PageIdentity $page, $table, $action='unknown', $userName='unknown', ?BacklinkCache $backlinkCache=null)
Queue a RefreshLinks job for any table.
Definition: LinksUpdate.php:399
$cache
$cache
Definition: mcc.php:33
File\assertRepoDefined
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition: File.php:2470
LocalFile\resetHistory
resetHistory()
Reset the history pointer to the first element of the history.
Definition: LocalFile.php:1715
LocalFile\getDescription
getDescription( $audience=self::FOR_PUBLIC, Authority $performer=null)
Definition: LocalFile.php:2590
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:53
FileRepo\isVirtualUrl
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:290
LocalFile\loadExtraFieldsWithTimestamp
loadExtraFieldsWithTimestamp( $dbr, $fname)
Definition: LocalFile.php:574
LocalFileMoveBatch
Helper class for file movement.
Definition: LocalFileMoveBatch.php:33
LocalFile\getUploader
getUploader(int $audience=self::FOR_PUBLIC, Authority $performer=null)
Definition: LocalFile.php:2573
MediaHandler\METADATA_BAD
const METADATA_BAD
Definition: MediaHandler.php:40
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: ManualLogEntry.php:44
FileRepo\DELETE_SOURCE
const DELETE_SOURCE
Definition: FileRepo.php:46
WikiFilePage
Special handling for file pages.
Definition: WikiFilePage.php:31
File\$name
string $name
The name of a file from its title object.
Definition: File.php:140
LocalFile\publish
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
Definition: LocalFile.php:2235
Title\invalidateCache
invalidateCache( $purgeTime=null)
Updates page_touched for this page; called from LinksUpdate.php.
Definition: Title.php:3715
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:1887
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:647
File\getHandler
getHandler()
Get a MediaHandler instance for this file.
Definition: File.php:1545
LockManager\LOCK_EX
const LOCK_EX
Definition: LockManager.php:71
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:145
LocalFile\VERSION
const VERSION
Definition: LocalFile.php:64
LocalFile\getDescriptionUrl
getDescriptionUrl()
isMultipage inherited
Definition: LocalFile.php:2520
LocalFile\move
move( $target)
getLinksTo inherited
Definition: LocalFile.php:2322
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:2485
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:1624
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:1591
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:1908
LogFormatter\newFromEntry
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
Definition: LogFormatter.php:54
Article\purgePatrolFooterCache
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Definition: Article.php:1285
Wikimedia\Rdbms\Blob
@newable
Definition: Blob.php:9