MediaWiki  master
LocalFile.php
Go to the documentation of this file.
1 <?php
35 
62 class LocalFile extends File {
63  private const VERSION = 13; // cache version
64 
65  private const CACHE_FIELD_MAX_LEN = 1000;
66 
68  protected $fileExists;
69 
71  protected $width;
72 
74  protected $height;
75 
77  protected $bits;
78 
80  protected $media_type;
81 
83  protected $mime;
84 
86  protected $size;
87 
89  protected $metadataArray = [];
90 
92  protected $sha1;
93 
95  protected $dataLoaded;
96 
98  protected $extraDataLoaded;
99 
101  protected $deleted;
102 
104  protected $repoClass = LocalRepo::class;
105 
107  private $historyLine;
108 
110  private $historyRes;
111 
113  private $major_mime;
114 
116  private $minor_mime;
117 
119  private $timestamp;
120 
122  private $user;
123 
125  private $description;
126 
129 
131  private $upgraded;
132 
134  private $upgrading;
135 
137  private $locked;
138 
140  private $lockedOwnTrx;
141 
143  private $missing;
144 
145  // @note: higher than IDBAccessObject constants
146  private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
147 
148  private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
149 
164  public static function newFromTitle( $title, $repo, $unused = null ) {
165  return new static( $title, $repo );
166  }
167 
179  public static function newFromRow( $row, $repo ) {
180  $title = Title::makeTitle( NS_FILE, $row->img_name );
181  $file = new static( $title, $repo );
182  $file->loadFromRow( $row );
183 
184  return $file;
185  }
186 
198  public static function newFromKey( $sha1, $repo, $timestamp = false ) {
199  $dbr = $repo->getReplicaDB();
200 
201  $conds = [ 'img_sha1' => $sha1 ];
202  if ( $timestamp ) {
203  $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
204  }
205 
206  $fileQuery = static::getQueryInfo();
207  $row = $dbr->selectRow(
208  $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__, [], $fileQuery['joins']
209  );
210  if ( $row ) {
211  return static::newFromRow( $row, $repo );
212  } else {
213  return false;
214  }
215  }
216 
235  public static function getQueryInfo( array $options = [] ) {
236  $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'img_description' );
237  $ret = [
238  'tables' => [
239  'image',
240  'image_actor' => 'actor'
241  ] + $commentQuery['tables'],
242  'fields' => [
243  'img_name',
244  'img_size',
245  'img_width',
246  'img_height',
247  'img_metadata',
248  'img_bits',
249  'img_media_type',
250  'img_major_mime',
251  'img_minor_mime',
252  'img_timestamp',
253  'img_sha1',
254  'img_actor',
255  'img_user' => 'image_actor.actor_user',
256  'img_user_text' => 'image_actor.actor_name',
257  ] + $commentQuery['fields'],
258  'joins' => [
259  'image_actor' => [ 'JOIN', 'actor_id=img_actor' ]
260  ] + $commentQuery['joins'],
261  ];
262 
263  if ( in_array( 'omit-nonlazy', $options, true ) ) {
264  // Internal use only for getting only the lazy fields
265  $ret['fields'] = [];
266  }
267  if ( !in_array( 'omit-lazy', $options, true ) ) {
268  // Note: Keep this in sync with self::getLazyCacheFields() and
269  // self::loadExtraFromDB()
270  $ret['fields'][] = 'img_metadata';
271  }
272 
273  return $ret;
274  }
275 
283  public function __construct( $title, $repo ) {
284  parent::__construct( $title, $repo );
285 
286  $this->historyLine = 0;
287  $this->historyRes = null;
288  $this->dataLoaded = false;
289  $this->extraDataLoaded = false;
290 
291  $this->assertRepoDefined();
292  $this->assertTitleDefined();
293  }
294 
298  public function getRepo() {
299  return $this->repo;
300  }
301 
308  protected function getCacheKey() {
309  return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
310  }
311 
318  return [ $this->getCacheKey() ];
319  }
320 
324  private function loadFromCache() {
325  $this->dataLoaded = false;
326  $this->extraDataLoaded = false;
327 
328  $key = $this->getCacheKey();
329  if ( !$key ) {
330  $this->loadFromDB( self::READ_NORMAL );
331 
332  return;
333  }
334 
335  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
336  $cachedValues = $cache->getWithSetCallback(
337  $key,
338  $cache::TTL_WEEK,
339  function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
340  $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
341 
342  $this->loadFromDB( self::READ_NORMAL );
343 
344  $fields = $this->getCacheFields( '' );
345  $cacheVal = [];
346  $cacheVal['fileExists'] = $this->fileExists;
347  if ( $this->fileExists ) {
348  foreach ( $fields as $field ) {
349  $cacheVal[$field] = $this->$field;
350  }
351  }
352  if ( $this->user ) {
353  $cacheVal['user'] = $this->user->getId();
354  $cacheVal['user_text'] = $this->user->getName();
355  }
356  $cacheVal['metadata'] = $this->metadataArray;
357 
358  // Strip off excessive entries from the subset of fields that can become large.
359  // If the cache value gets too large and might not fit in the cache,
360  // causing repeat database queries for each access to the file.
361  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
362  if ( isset( $cacheVal[$field] )
363  && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
364  ) {
365  unset( $cacheVal[$field] ); // don't let the value get too big
366  }
367  }
368 
369  if ( $this->fileExists ) {
370  $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
371  } else {
372  $ttl = $cache::TTL_DAY;
373  }
374 
375  return $cacheVal;
376  },
377  [ 'version' => self::VERSION ]
378  );
379 
380  $this->fileExists = $cachedValues['fileExists'];
381  if ( $this->fileExists ) {
382  $this->setProps( $cachedValues );
383  }
384 
385  $this->dataLoaded = true;
386  $this->extraDataLoaded = true;
387  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
388  $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
389  }
390  }
391 
395  public function invalidateCache() {
396  $key = $this->getCacheKey();
397  if ( !$key ) {
398  return;
399  }
400 
401  $this->repo->getMasterDB()->onTransactionPreCommitOrIdle(
402  static function () use ( $key ) {
403  MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
404  },
405  __METHOD__
406  );
407  }
408 
416  public function loadFromFile( $path = null ) {
417  $props = $this->repo->getFileProps( $path ?? $this->getVirtualUrl() );
418  $this->setProps( $props );
419  }
420 
428  protected function getCacheFields( $prefix = 'img_' ) {
429  if ( $prefix !== '' ) {
430  throw new InvalidArgumentException(
431  __METHOD__ . ' with a non-empty prefix is no longer supported.'
432  );
433  }
434 
435  // See self::getQueryInfo() for the fetching of the data from the DB,
436  // self::loadFromRow() for the loading of the object from the DB row,
437  // and self::loadFromCache() for the caching, and self::setProps() for
438  // populating the object from an array of data.
439  return [ 'size', 'width', 'height', 'bits', 'media_type',
440  'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
441  }
442 
450  protected function getLazyCacheFields( $prefix = 'img_' ) {
451  if ( $prefix !== '' ) {
452  throw new InvalidArgumentException(
453  __METHOD__ . ' with a non-empty prefix is no longer supported.'
454  );
455  }
456 
457  // Keep this in sync with the omit-lazy option in self::getQueryInfo().
458  return [ 'metadata' ];
459  }
460 
466  protected function loadFromDB( $flags = 0 ) {
467  $fname = static::class . '::' . __FUNCTION__;
468 
469  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
470  $this->dataLoaded = true;
471  $this->extraDataLoaded = true;
472 
473  $dbr = ( $flags & self::READ_LATEST )
474  ? $this->repo->getMasterDB()
475  : $this->repo->getReplicaDB();
476 
477  $fileQuery = static::getQueryInfo();
478  $row = $dbr->selectRow(
479  $fileQuery['tables'],
480  $fileQuery['fields'],
481  [ 'img_name' => $this->getName() ],
482  $fname,
483  [],
484  $fileQuery['joins']
485  );
486 
487  if ( $row ) {
488  $this->loadFromRow( $row );
489  } else {
490  $this->fileExists = false;
491  }
492  }
493 
499  protected function loadExtraFromDB() {
500  if ( !$this->title ) {
501  return; // Avoid hard failure when the file does not exist. T221812
502  }
503 
504  $fname = static::class . '::' . __FUNCTION__;
505 
506  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
507  $this->extraDataLoaded = true;
508 
509  $db = $this->repo->getReplicaDB();
510  $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
511  if ( !$fieldMap ) {
512  $db = $this->repo->getMasterDB();
513  $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
514  }
515 
516  if ( $fieldMap ) {
517  if ( isset( $fieldMap['metadata'] ) ) {
518  $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
519  }
520  } else {
521  throw new MWException( "Could not find data for image '{$this->getName()}'." );
522  }
523  }
524 
530  private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
531  $fieldMap = false;
532 
533  $fileQuery = self::getQueryInfo( [ 'omit-nonlazy' ] );
534  $row = $dbr->selectRow(
535  $fileQuery['tables'],
536  $fileQuery['fields'],
537  [
538  'img_name' => $this->getName(),
539  'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
540  ],
541  $fname,
542  [],
543  $fileQuery['joins']
544  );
545  if ( $row ) {
546  $fieldMap = $this->unprefixRow( $row, 'img_' );
547  } else {
548  # File may have been uploaded over in the meantime; check the old versions
549  $fileQuery = OldLocalFile::getQueryInfo( [ 'omit-nonlazy' ] );
550  $row = $dbr->selectRow(
551  $fileQuery['tables'],
552  $fileQuery['fields'],
553  [
554  'oi_name' => $this->getName(),
555  'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
556  ],
557  $fname,
558  [],
559  $fileQuery['joins']
560  );
561  if ( $row ) {
562  $fieldMap = $this->unprefixRow( $row, 'oi_' );
563  }
564  }
565 
566  return $fieldMap;
567  }
568 
575  protected function unprefixRow( $row, $prefix = 'img_' ) {
576  $array = (array)$row;
577  $prefixLength = strlen( $prefix );
578 
579  // Sanity check prefix once
580  if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
581  throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
582  }
583 
584  $decoded = [];
585  foreach ( $array as $name => $value ) {
586  $decoded[substr( $name, $prefixLength )] = $value;
587  }
588 
589  return $decoded;
590  }
591 
607  public function loadFromRow( $row, $prefix = 'img_' ) {
608  $this->dataLoaded = true;
609 
610  $unprefixed = $this->unprefixRow( $row, $prefix );
611 
612  $this->name = $unprefixed['name'];
613  $this->media_type = $unprefixed['media_type'];
614 
615  $this->description = MediaWikiServices::getInstance()->getCommentStore()
616  ->getComment( "{$prefix}description", $row )->text;
617 
618  $this->user = User::newFromAnyId(
619  $unprefixed['user'] ?? null,
620  $unprefixed['user_text'] ?? null,
621  $unprefixed['actor'] ?? null
622  );
623 
624  $this->timestamp = wfTimestamp( TS_MW, $unprefixed['timestamp'] );
625 
627  $this->repo->getReplicaDB(), $unprefixed['metadata'] );
628 
629  if ( empty( $unprefixed['major_mime'] ) ) {
630  $this->major_mime = 'unknown';
631  $this->minor_mime = 'unknown';
632  $this->mime = 'unknown/unknown';
633  } else {
634  if ( !$unprefixed['minor_mime'] ) {
635  $unprefixed['minor_mime'] = 'unknown';
636  }
637  $this->major_mime = $unprefixed['major_mime'];
638  $this->minor_mime = $unprefixed['minor_mime'];
639  $this->mime = $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
640  }
641 
642  // Trim zero padding from char/binary field
643  $this->sha1 = rtrim( $unprefixed['sha1'], "\0" );
644 
645  // Normalize some fields to integer type, per their database definition.
646  // Use unary + so that overflows will be upgraded to double instead of
647  // being trucated as with intval(). This is important to allow >2GB
648  // files on 32-bit systems.
649  $this->size = +$unprefixed['size'];
650  $this->width = +$unprefixed['width'];
651  $this->height = +$unprefixed['height'];
652  $this->bits = +$unprefixed['bits'];
653 
654  // Check for extra fields (deprecated since MW 1.37)
655  $extraFields = array_diff(
656  array_keys( $unprefixed ),
657  [
658  'name', 'media_type', 'description_text', 'description_data',
659  'description_cid', 'user', 'user_text', 'actor', 'timestamp',
660  'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
661  'height', 'bits'
662  ]
663  );
664  if ( $extraFields ) {
666  'Passing extra fields (' .
667  implode( ', ', $extraFields )
668  . ') to ' . __METHOD__ . ' was deprecated in MediaWiki 1.37. ' .
669  'Property assignment will be removed in a later version.',
670  '1.37' );
671  foreach ( $extraFields as $field ) {
672  $this->$field = $unprefixed[$field];
673  }
674  }
675 
676  $this->fileExists = true;
677  }
678 
684  public function load( $flags = 0 ) {
685  if ( !$this->dataLoaded ) {
686  if ( $flags & self::READ_LATEST ) {
687  $this->loadFromDB( $flags );
688  } else {
689  $this->loadFromCache();
690  }
691  }
692 
693  if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
694  // @note: loads on name/timestamp to reduce race condition problems
695  $this->loadExtraFromDB();
696  }
697  }
698 
702  protected function maybeUpgradeRow() {
704 
705  if ( wfReadOnly() || $this->upgrading ) {
706  return;
707  }
708 
709  $upgrade = false;
710  if ( $this->media_type === null || $this->mime == 'image/svg' ) {
711  $upgrade = true;
712  } else {
713  $handler = $this->getHandler();
714  if ( $handler ) {
715  $validity = $handler->isFileMetadataValid( $this );
716  if ( $validity === MediaHandler::METADATA_BAD ) {
717  $upgrade = true;
718  } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE ) {
719  $upgrade = $wgUpdateCompatibleMetadata;
720  }
721  }
722  }
723 
724  if ( $upgrade ) {
725  $this->upgrading = true;
726  // Defer updates unless in auto-commit CLI mode
728  $this->upgrading = false; // avoid duplicate updates
729  try {
730  $this->upgradeRow();
731  } catch ( LocalFileLockError $e ) {
732  // let the other process handle it (or do it next time)
733  }
734  } );
735  }
736  }
737 
741  public function getUpgraded() {
742  return $this->upgraded;
743  }
744 
749  public function upgradeRow() {
750  $this->lock();
751 
752  $this->loadFromFile();
753 
754  # Don't destroy file info of missing files
755  if ( !$this->fileExists ) {
756  $this->unlock();
757  wfDebug( __METHOD__ . ": file does not exist, aborting" );
758 
759  return;
760  }
761 
762  $dbw = $this->repo->getMasterDB();
763  list( $major, $minor ) = self::splitMime( $this->mime );
764 
765  if ( wfReadOnly() ) {
766  $this->unlock();
767 
768  return;
769  }
770  wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
771 
772  $dbw->update( 'image',
773  [
774  'img_size' => $this->size, // sanity
775  'img_width' => $this->width,
776  'img_height' => $this->height,
777  'img_bits' => $this->bits,
778  'img_media_type' => $this->media_type,
779  'img_major_mime' => $major,
780  'img_minor_mime' => $minor,
781  'img_metadata' => $this->getMetadataForDb( $dbw ),
782  'img_sha1' => $this->sha1,
783  ],
784  [ 'img_name' => $this->getName() ],
785  __METHOD__
786  );
787 
788  $this->invalidateCache();
789 
790  $this->unlock();
791  $this->upgraded = true; // avoid rework/retries
792  }
793 
805  protected function setProps( $info ) {
806  $this->dataLoaded = true;
807  $fields = $this->getCacheFields( '' );
808  $fields[] = 'fileExists';
809 
810  foreach ( $fields as $field ) {
811  if ( isset( $info[$field] ) ) {
812  $this->$field = $info[$field];
813  }
814  }
815 
816  // Only our own cache sets these properties, so they both should be present.
817  if ( isset( $info['user'] ) &&
818  isset( $info['user_text'] ) &&
819  $info['user_text'] !== ''
820  ) {
821  $this->user = new UserIdentityValue( $info['user'], $info['user_text'] );
822  }
823 
824  // Fix up mime fields
825  if ( isset( $info['major_mime'] ) ) {
826  $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
827  } elseif ( isset( $info['mime'] ) ) {
828  $this->mime = $info['mime'];
829  list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
830  }
831 
832  if ( isset( $info['metadata'] ) ) {
833  if ( is_string( $info['metadata'] ) ) {
834  $this->loadMetadataFromString( $info['metadata'] );
835  } elseif ( is_array( $info['metadata'] ) ) {
836  $this->metadataArray = $info['metadata'];
837  } else {
838  $logger = LoggerFactory::getInstance( 'LocalFile' );
839  $logger->warning( __METHOD__ . ' given invalid metadata of type ' .
840  gettype( $info['metadata'] ) );
841  $this->metadataArray = [];
842  }
843  $this->extraDataLoaded = true;
844  }
845  }
846 
862  public function isMissing() {
863  if ( $this->missing === null ) {
864  $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
865  $this->missing = !$fileExists;
866  }
867 
868  return $this->missing;
869  }
870 
878  public function getWidth( $page = 1 ) {
879  $page = (int)$page;
880  if ( $page < 1 ) {
881  $page = 1;
882  }
883 
884  $this->load();
885 
886  if ( $this->isMultipage() ) {
887  $handler = $this->getHandler();
888  if ( !$handler ) {
889  return 0;
890  }
891  $dim = $handler->getPageDimensions( $this, $page );
892  if ( $dim ) {
893  return $dim['width'];
894  } else {
895  // For non-paged media, the false goes through an
896  // intval, turning failure into 0, so do same here.
897  return 0;
898  }
899  } else {
900  return $this->width;
901  }
902  }
903 
911  public function getHeight( $page = 1 ) {
912  $page = (int)$page;
913  if ( $page < 1 ) {
914  $page = 1;
915  }
916 
917  $this->load();
918 
919  if ( $this->isMultipage() ) {
920  $handler = $this->getHandler();
921  if ( !$handler ) {
922  return 0;
923  }
924  $dim = $handler->getPageDimensions( $this, $page );
925  if ( $dim ) {
926  return $dim['height'];
927  } else {
928  // For non-paged media, the false goes through an
929  // intval, turning failure into 0, so do same here.
930  return 0;
931  }
932  } else {
933  return $this->height;
934  }
935  }
936 
944  public function getDescriptionShortUrl() {
945  if ( !$this->title ) {
946  return null; // Avoid hard failure when the file does not exist. T221812
947  }
948 
949  $pageId = $this->title->getArticleID();
950 
951  if ( $pageId ) {
952  $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
953  if ( $url !== false ) {
954  return $url;
955  }
956  }
957  return null;
958  }
959 
966  public function getMetadata() {
967  $data = $this->getMetadataArray();
968  if ( !$data ) {
969  return '';
970  } elseif ( array_keys( $data ) === [ '_error' ] ) {
971  // Legacy error encoding
972  return $data['_error'];
973  } else {
974  return serialize( $this->getMetadataArray() );
975  }
976  }
977 
984  public function getMetadataArray(): array {
985  $this->load( self::LOAD_ALL );
986  return $this->metadataArray;
987  }
988 
997  public function getMetadataForDb( IDatabase $db ) {
998  $this->load( self::LOAD_ALL );
999  if ( !$this->metadataArray ) {
1000  $s = '';
1001  } else {
1002  $s = serialize( $this->metadataArray );
1003  }
1004  if ( !is_string( $s ) ) {
1005  throw new MWException( 'Could not serialize image metadata value for DB' );
1006  }
1007  return $db->encodeBlob( $s );
1008  }
1009 
1018  protected function loadMetadataFromDbFieldValue( IDatabase $db, $metadataBlob ) {
1019  $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
1020  }
1021 
1029  protected function loadMetadataFromString( $metadataString ) {
1030  $this->extraDataLoaded = true;
1031  $metadataString = (string)$metadataString;
1032  if ( $metadataString === '' ) {
1033  $this->metadataArray = [];
1034  } else {
1035  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1036  $data = @unserialize( $metadataString );
1037  if ( !is_array( $data ) ) {
1038  // Legacy error encoding
1039  $this->metadataArray = [ '_error' => $metadataString ];
1040  } else {
1041  $this->metadataArray = $data;
1042  }
1043  }
1044  }
1045 
1050  public function getBitDepth() {
1051  $this->load();
1052 
1053  return (int)$this->bits;
1054  }
1055 
1061  public function getSize() {
1062  $this->load();
1063 
1064  return $this->size;
1065  }
1066 
1072  public function getMimeType() {
1073  $this->load();
1074 
1075  return $this->mime;
1076  }
1077 
1084  public function getMediaType() {
1085  $this->load();
1086 
1087  return $this->media_type;
1088  }
1089 
1101  public function exists() {
1102  $this->load();
1103 
1104  return $this->fileExists;
1105  }
1106 
1123  protected function getThumbnails( $archiveName = false ) {
1124  if ( $archiveName ) {
1125  $dir = $this->getArchiveThumbPath( $archiveName );
1126  } else {
1127  $dir = $this->getThumbPath();
1128  }
1129 
1130  $backend = $this->repo->getBackend();
1131  $files = [ $dir ];
1132  try {
1133  $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1134  if ( $iterator !== null ) {
1135  foreach ( $iterator as $file ) {
1136  $files[] = $file;
1137  }
1138  }
1139  } catch ( FileBackendError $e ) {
1140  } // suppress (T56674)
1141 
1142  return $files;
1143  }
1144 
1148  private function purgeMetadataCache() {
1149  $this->invalidateCache();
1150  }
1151 
1160  public function purgeCache( $options = [] ) {
1161  // Refresh metadata cache
1162  $this->maybeUpgradeRow();
1163  $this->purgeMetadataCache();
1164 
1165  // Delete thumbnails
1166  $this->purgeThumbnails( $options );
1167 
1168  // Purge CDN cache for this file
1169  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1170  $hcu->purgeUrls(
1171  $this->getUrl(),
1172  !empty( $options['forThumbRefresh'] )
1173  ? $hcu::PURGE_PRESEND // just a manual purge
1174  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1175  );
1176  }
1177 
1183  public function purgeOldThumbnails( $archiveName ) {
1184  // Get a list of old thumbnails
1185  $thumbs = $this->getThumbnails( $archiveName );
1186 
1187  // Delete thumbnails from storage, and prevent the directory itself from being purged
1188  $dir = array_shift( $thumbs );
1189  $this->purgeThumbList( $dir, $thumbs );
1190 
1191  $urls = [];
1192  foreach ( $thumbs as $thumb ) {
1193  $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1194  }
1195 
1196  // Purge any custom thumbnail caches
1197  $this->hookRunner->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1198 
1199  // Purge the CDN
1200  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1201  $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1202  }
1203 
1210  public function purgeThumbnails( $options = [] ) {
1211  $thumbs = $this->getThumbnails();
1212 
1213  // Delete thumbnails from storage, and prevent the directory itself from being purged
1214  $dir = array_shift( $thumbs );
1215  $this->purgeThumbList( $dir, $thumbs );
1216 
1217  // Always purge all files from CDN regardless of handler filters
1218  $urls = [];
1219  foreach ( $thumbs as $thumb ) {
1220  $urls[] = $this->getThumbUrl( $thumb );
1221  }
1222 
1223  // Give the media handler a chance to filter the file purge list
1224  if ( !empty( $options['forThumbRefresh'] ) ) {
1225  $handler = $this->getHandler();
1226  if ( $handler ) {
1227  $handler->filterThumbnailPurgeList( $thumbs, $options );
1228  }
1229  }
1230 
1231  // Purge any custom thumbnail caches
1232  $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1233 
1234  // Purge the CDN
1235  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1236  $hcu->purgeUrls(
1237  $urls,
1238  !empty( $options['forThumbRefresh'] )
1239  ? $hcu::PURGE_PRESEND // just a manual purge
1240  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1241  );
1242  }
1243 
1250  public function prerenderThumbnails() {
1252 
1253  $jobs = [];
1254 
1255  $sizes = $wgUploadThumbnailRenderMap;
1256  rsort( $sizes );
1257 
1258  foreach ( $sizes as $size ) {
1259  if ( $this->isVectorized() || $this->getWidth() > $size ) {
1260  $jobs[] = new ThumbnailRenderJob(
1261  $this->getTitle(),
1262  [ 'transformParams' => [ 'width' => $size ] ]
1263  );
1264  }
1265  }
1266 
1267  if ( $jobs ) {
1268  JobQueueGroup::singleton()->lazyPush( $jobs );
1269  }
1270  }
1271 
1278  protected function purgeThumbList( $dir, $files ) {
1279  $fileListDebug = strtr(
1280  var_export( $files, true ),
1281  [ "\n" => '' ]
1282  );
1283  wfDebug( __METHOD__ . ": $fileListDebug" );
1284 
1285  if ( $this->repo->supportsSha1URLs() ) {
1286  $reference = $this->getSha1();
1287  } else {
1288  $reference = $this->getName();
1289  }
1290 
1291  $purgeList = [];
1292  foreach ( $files as $file ) {
1293  # Check that the reference (filename or sha1) is part of the thumb name
1294  # This is a basic sanity check to avoid erasing unrelated directories
1295  if ( strpos( $file, $reference ) !== false
1296  || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1297  ) {
1298  $purgeList[] = "{$dir}/{$file}";
1299  }
1300  }
1301 
1302  # Delete the thumbnails
1303  $this->repo->quickPurgeBatch( $purgeList );
1304  # Clear out the thumbnail directory if empty
1305  $this->repo->quickCleanDir( $dir );
1306  }
1307 
1319  public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1320  if ( !$this->exists() ) {
1321  return []; // Avoid hard failure when the file does not exist. T221812
1322  }
1323 
1324  $dbr = $this->repo->getReplicaDB();
1325  $oldFileQuery = OldLocalFile::getQueryInfo();
1326 
1327  $tables = $oldFileQuery['tables'];
1328  $fields = $oldFileQuery['fields'];
1329  $join_conds = $oldFileQuery['joins'];
1330  $conds = $opts = [];
1331  $eq = $inc ? '=' : '';
1332  $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1333 
1334  if ( $start ) {
1335  $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1336  }
1337 
1338  if ( $end ) {
1339  $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1340  }
1341 
1342  if ( $limit ) {
1343  $opts['LIMIT'] = $limit;
1344  }
1345 
1346  // Search backwards for time > x queries
1347  $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1348  $opts['ORDER BY'] = "oi_timestamp $order";
1349  $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1350 
1351  $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1352  $conds, $opts, $join_conds );
1353 
1354  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1355  $r = [];
1356 
1357  foreach ( $res as $row ) {
1358  $r[] = $this->repo->newFileFromRow( $row );
1359  }
1360 
1361  if ( $order == 'ASC' ) {
1362  $r = array_reverse( $r ); // make sure it ends up descending
1363  }
1364 
1365  return $r;
1366  }
1367 
1378  public function nextHistoryLine() {
1379  if ( !$this->exists() ) {
1380  return false; // Avoid hard failure when the file does not exist. T221812
1381  }
1382 
1383  # Polymorphic function name to distinguish foreign and local fetches
1384  $fname = static::class . '::' . __FUNCTION__;
1385 
1386  $dbr = $this->repo->getReplicaDB();
1387 
1388  if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1389  $fileQuery = self::getQueryInfo();
1390  $this->historyRes = $dbr->select( $fileQuery['tables'],
1391  $fileQuery['fields'] + [
1392  'oi_archive_name' => $dbr->addQuotes( '' ),
1393  'oi_deleted' => 0,
1394  ],
1395  [ 'img_name' => $this->title->getDBkey() ],
1396  $fname,
1397  [],
1398  $fileQuery['joins']
1399  );
1400 
1401  if ( $dbr->numRows( $this->historyRes ) == 0 ) {
1402  $this->historyRes = null;
1403 
1404  return false;
1405  }
1406  } elseif ( $this->historyLine == 1 ) {
1407  $fileQuery = OldLocalFile::getQueryInfo();
1408  $this->historyRes = $dbr->select(
1409  $fileQuery['tables'],
1410  $fileQuery['fields'],
1411  [ 'oi_name' => $this->title->getDBkey() ],
1412  $fname,
1413  [ 'ORDER BY' => 'oi_timestamp DESC' ],
1414  $fileQuery['joins']
1415  );
1416  }
1417  $this->historyLine++;
1418 
1419  return $dbr->fetchObject( $this->historyRes );
1420  }
1421 
1426  public function resetHistory() {
1427  $this->historyLine = 0;
1428 
1429  if ( $this->historyRes !== null ) {
1430  $this->historyRes = null;
1431  }
1432  }
1433 
1467  public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1468  $timestamp = false, Authority $uploader = null, $tags = [],
1469  $createNullRevision = true, $revert = false
1470  ) {
1471  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1472  return $this->readOnlyFatalStatus();
1473  } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1474  // Check this in advance to avoid writing to FileBackend and the file tables,
1475  // only to fail on insert the revision due to the text store being unavailable.
1476  return $this->readOnlyFatalStatus();
1477  }
1478 
1479  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1480  if ( !$props ) {
1481  if ( FileRepo::isVirtualUrl( $srcPath )
1482  || FileBackend::isStoragePath( $srcPath )
1483  ) {
1484  $props = $this->repo->getFileProps( $srcPath );
1485  } else {
1486  $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1487  $props = $mwProps->getPropsFromPath( $srcPath, true );
1488  }
1489  }
1490 
1491  $options = [];
1492  $handler = MediaHandler::getHandler( $props['mime'] );
1493  if ( $handler ) {
1494  if ( is_string( $props['metadata'] ) ) {
1495  // This supports callers directly fabricating a metadata
1496  // property using serialize(). Normally the metadata property
1497  // comes from MWFileProps, in which case it won't be a string.
1498  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1499  $metadata = @unserialize( $props['metadata'] );
1500  } else {
1501  $metadata = $props['metadata'];
1502  }
1503 
1504  if ( is_array( $metadata ) ) {
1505  $options['headers'] = $handler->getContentHeaders( $metadata );
1506  }
1507  } else {
1508  $options['headers'] = [];
1509  }
1510 
1511  // Trim spaces on user supplied text
1512  $comment = trim( $comment );
1513 
1514  $this->lock();
1515  $status = $this->publish( $src, $flags, $options );
1516 
1517  if ( $status->successCount >= 2 ) {
1518  // There will be a copy+(one of move,copy,store).
1519  // The first succeeding does not commit us to updating the DB
1520  // since it simply copied the current version to a timestamped file name.
1521  // It is only *preferable* to avoid leaving such files orphaned.
1522  // Once the second operation goes through, then the current version was
1523  // updated and we must therefore update the DB too.
1524  $oldver = $status->value;
1525 
1526  if ( $uploader === null ) {
1527  // Uploader argument is optional, fall back to the context authority
1528  $uploader = RequestContext::getMain()->getAuthority();
1529  }
1530 
1531  $uploadStatus = $this->recordUpload3(
1532  $oldver,
1533  $comment,
1534  $pageText,
1535  $uploader,
1536  $props,
1537  $timestamp,
1538  $tags,
1539  $createNullRevision,
1540  $revert
1541  );
1542  if ( !$uploadStatus->isOK() ) {
1543  if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1544  // update filenotfound error with more specific path
1545  $status->fatal( 'filenotfound', $srcPath );
1546  } else {
1547  $status->merge( $uploadStatus );
1548  }
1549  }
1550  }
1551 
1552  $this->unlock();
1553  return $status;
1554  }
1555 
1572  public function recordUpload3(
1573  string $oldver,
1574  string $comment,
1575  string $pageText,
1576  Authority $performer,
1577  $props = false,
1578  $timestamp = false,
1579  $tags = [],
1580  bool $createNullRevision = true,
1581  bool $revert = false
1582  ) : Status {
1583  $dbw = $this->repo->getMasterDB();
1584 
1585  # Imports or such might force a certain timestamp; otherwise we generate
1586  # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1587  if ( $timestamp === false ) {
1588  $timestamp = $dbw->timestamp();
1589  $allowTimeKludge = true;
1590  } else {
1591  $allowTimeKludge = false;
1592  }
1593 
1594  $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1595  $props['description'] = $comment;
1596  $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1597  $this->setProps( $props );
1598 
1599  # Fail now if the file isn't there
1600  if ( !$this->fileExists ) {
1601  wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1602 
1603  return Status::newFatal( 'filenotfound', $this->getRel() );
1604  }
1605 
1606  $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1607 
1608  $dbw->startAtomic( __METHOD__ );
1609 
1610  $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1611  $this->user = $performer->getUser();
1612 
1613  # Test to see if the row exists using INSERT IGNORE
1614  # This avoids race conditions by locking the row until the commit, and also
1615  # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1616  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1617  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1618  $actorFields = [ 'img_actor' => $actorId ];
1619  $dbw->insert( 'image',
1620  [
1621  'img_name' => $this->getName(),
1622  'img_size' => $this->size,
1623  'img_width' => intval( $this->width ),
1624  'img_height' => intval( $this->height ),
1625  'img_bits' => $this->bits,
1626  'img_media_type' => $this->media_type,
1627  'img_major_mime' => $this->major_mime,
1628  'img_minor_mime' => $this->minor_mime,
1629  'img_timestamp' => $timestamp,
1630  'img_metadata' => $this->getMetadataForDb( $dbw ),
1631  'img_sha1' => $this->sha1
1632  ] + $commentFields + $actorFields,
1633  __METHOD__,
1634  [ 'IGNORE' ]
1635  );
1636  $reupload = ( $dbw->affectedRows() == 0 );
1637 
1638  if ( $reupload ) {
1639  $row = $dbw->selectRow(
1640  'image',
1641  [ 'img_timestamp', 'img_sha1' ],
1642  [ 'img_name' => $this->getName() ],
1643  __METHOD__,
1644  [ 'LOCK IN SHARE MODE' ]
1645  );
1646 
1647  if ( $row && $row->img_sha1 === $this->sha1 ) {
1648  $dbw->endAtomic( __METHOD__ );
1649  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1650  $title = Title::newFromText( $this->getName(), NS_FILE );
1651  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1652  }
1653 
1654  if ( $allowTimeKludge ) {
1655  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1656  $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1657  # Avoid a timestamp that is not newer than the last version
1658  # TODO: the image/oldimage tables should be like page/revision with an ID field
1659  if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1660  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1661  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1662  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1663  }
1664  }
1665 
1666  $tables = [ 'image' ];
1667  $fields = [
1668  'oi_name' => 'img_name',
1669  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1670  'oi_size' => 'img_size',
1671  'oi_width' => 'img_width',
1672  'oi_height' => 'img_height',
1673  'oi_bits' => 'img_bits',
1674  'oi_description_id' => 'img_description_id',
1675  'oi_timestamp' => 'img_timestamp',
1676  'oi_metadata' => 'img_metadata',
1677  'oi_media_type' => 'img_media_type',
1678  'oi_major_mime' => 'img_major_mime',
1679  'oi_minor_mime' => 'img_minor_mime',
1680  'oi_sha1' => 'img_sha1',
1681  'oi_actor' => 'img_actor',
1682  ];
1683  $joins = [];
1684 
1685  # (T36993) Note: $oldver can be empty here, if the previous
1686  # version of the file was broken. Allow registration of the new
1687  # version to continue anyway, because that's better than having
1688  # an image that's not fixable by user operations.
1689  # Collision, this is an update of a file
1690  # Insert previous contents into oldimage
1691  $dbw->insertSelect( 'oldimage', $tables, $fields,
1692  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1693 
1694  # Update the current image row
1695  $dbw->update( 'image',
1696  [
1697  'img_size' => $this->size,
1698  'img_width' => intval( $this->width ),
1699  'img_height' => intval( $this->height ),
1700  'img_bits' => $this->bits,
1701  'img_media_type' => $this->media_type,
1702  'img_major_mime' => $this->major_mime,
1703  'img_minor_mime' => $this->minor_mime,
1704  'img_timestamp' => $timestamp,
1705  'img_metadata' => $this->getMetadataForDb( $dbw ),
1706  'img_sha1' => $this->sha1
1707  ] + $commentFields + $actorFields,
1708  [ 'img_name' => $this->getName() ],
1709  __METHOD__
1710  );
1711  }
1712 
1713  $descTitle = $this->getTitle();
1714  $descId = $descTitle->getArticleID();
1715  $wikiPage = new WikiFilePage( $descTitle );
1716  $wikiPage->setFile( $this );
1717 
1718  // Determine log action. If reupload is done by reverting, use a special log_action.
1719  if ( $revert === true ) {
1720  $logAction = 'revert';
1721  } elseif ( $reupload === true ) {
1722  $logAction = 'overwrite';
1723  } else {
1724  $logAction = 'upload';
1725  }
1726  // Add the log entry...
1727  $logEntry = new ManualLogEntry( 'upload', $logAction );
1728  $logEntry->setTimestamp( $this->timestamp );
1729  $logEntry->setPerformer( $performer->getUser() );
1730  $logEntry->setComment( $comment );
1731  $logEntry->setTarget( $descTitle );
1732  // Allow people using the api to associate log entries with the upload.
1733  // Log has a timestamp, but sometimes different from upload timestamp.
1734  $logEntry->setParameters(
1735  [
1736  'img_sha1' => $this->sha1,
1737  'img_timestamp' => $timestamp,
1738  ]
1739  );
1740  // Note we keep $logId around since during new image
1741  // creation, page doesn't exist yet, so log_page = 0
1742  // but we want it to point to the page we're making,
1743  // so we later modify the log entry.
1744  // For a similar reason, we avoid making an RC entry
1745  // now and wait until the page exists.
1746  $logId = $logEntry->insert();
1747 
1748  if ( $descTitle->exists() ) {
1749  if ( $createNullRevision !== false ) {
1750  $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1751  // Use own context to get the action text in content language
1752  $formatter = LogFormatter::newFromEntry( $logEntry );
1753  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1754  $editSummary = $formatter->getPlainActionText();
1755  $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1756  $nullRevRecord = $revStore->newNullRevision(
1757  $dbw,
1758  $descTitle,
1759  $summary,
1760  false,
1761  $performer->getUser()
1762  );
1763 
1764  if ( $nullRevRecord ) {
1765  $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1766 
1767  $this->getHookRunner()->onRevisionFromEditComplete(
1768  $wikiPage,
1769  $inserted,
1770  $inserted->getParentId(),
1771  $performer->getUser(),
1772  $tags
1773  );
1774 
1775  $wikiPage->updateRevisionOn( $dbw, $inserted );
1776  // Associate null revision id
1777  $logEntry->setAssociatedRevId( $inserted->getId() );
1778  }
1779  }
1780 
1781  $newPageContent = null;
1782  } else {
1783  // Make the description page and RC log entry post-commit
1784  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1785  }
1786 
1787  // NOTE: Even after ending this atomic section, we are probably still in the transaction
1788  // started by the call to lock() in publishTo(). We cannot yet safely schedule jobs,
1789  // see T263301.
1790  $dbw->endAtomic( __METHOD__ );
1791  $fname = __METHOD__;
1792 
1793  # Do some cache purges after final commit so that:
1794  # a) Changes are more likely to be seen post-purge
1795  # b) They won't cause rollback of the log publish/update above
1796  $purgeUpdate = new AutoCommitUpdate(
1797  $dbw,
1798  __METHOD__,
1800  function () use (
1801  $reupload, $wikiPage, $newPageContent, $comment, $performer,
1802  $logEntry, $logId, $descId, $tags, $fname
1803  ) {
1804  # Update memcache after the commit
1805  $this->invalidateCache();
1806 
1807  $updateLogPage = false;
1808  if ( $newPageContent ) {
1809  # New file page; create the description page.
1810  # There's already a log entry, so don't make a second RC entry
1811  # CDN and file cache for the description page are purged by doEditContent.
1812  $status = $wikiPage->doEditContent(
1813  $newPageContent,
1814  $comment,
1816  false,
1817  $performer
1818  );
1819 
1820  if ( isset( $status->value['revision-record'] ) ) {
1822  $revRecord = $status->value['revision-record'];
1823  // Associate new page revision id
1824  $logEntry->setAssociatedRevId( $revRecord->getId() );
1825  }
1826  // This relies on the resetArticleID() call in WikiPage::insertOn(),
1827  // which is triggered on $descTitle by doEditContent() above.
1828  if ( isset( $status->value['revision-record'] ) ) {
1830  $revRecord = $status->value['revision-record'];
1831  $updateLogPage = $revRecord->getPageId();
1832  }
1833  } else {
1834  # Existing file page: invalidate description page cache
1835  $title = $wikiPage->getTitle();
1837  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1838  $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1839  # Allow the new file version to be patrolled from the page footer
1841  }
1842 
1843  # Update associated rev id. This should be done by $logEntry->insert() earlier,
1844  # but setAssociatedRevId() wasn't called at that point yet...
1845  $logParams = $logEntry->getParameters();
1846  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1847  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1848  if ( $updateLogPage ) {
1849  # Also log page, in case where we just created it above
1850  $update['log_page'] = $updateLogPage;
1851  }
1852  $this->getRepo()->getMasterDB()->update(
1853  'logging',
1854  $update,
1855  [ 'log_id' => $logId ],
1856  $fname
1857  );
1858  $this->getRepo()->getMasterDB()->insert(
1859  'log_search',
1860  [
1861  'ls_field' => 'associated_rev_id',
1862  'ls_value' => (string)$logEntry->getAssociatedRevId(),
1863  'ls_log_id' => $logId,
1864  ],
1865  $fname
1866  );
1867 
1868  # Add change tags, if any
1869  if ( $tags ) {
1870  $logEntry->addTags( $tags );
1871  }
1872 
1873  # Uploads can be patrolled
1874  $logEntry->setIsPatrollable( true );
1875 
1876  # Now that the log entry is up-to-date, make an RC entry.
1877  $logEntry->publish( $logId );
1878 
1879  # Run hook for other updates (typically more cache purging)
1880  $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
1881 
1882  if ( $reupload ) {
1883  # Delete old thumbnails
1884  $this->purgeThumbnails();
1885  # Remove the old file from the CDN cache
1886  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1887  $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1888  } else {
1889  # Update backlink pages pointing to this title if created
1891  $this->getTitle(),
1892  'imagelinks',
1893  'upload-image',
1894  $performer->getUser()->getName()
1895  );
1896  }
1897 
1898  $this->prerenderThumbnails();
1899  }
1900  );
1901 
1902  # Invalidate cache for all pages using this file
1903  $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
1904  $this->getTitle(),
1905  'imagelinks',
1906  [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
1907  );
1908 
1909  // NOTE: We are probably still in the transaction started by the call to lock() in
1910  // publishTo(). We should only schedule jobs after that transaction was committed,
1911  // so a job queue failure doesn't cause the upload to fail (T263301).
1912  // Also, we should generally not schedule any Jobs or the DeferredUpdates that
1913  // assume the update is complete until after the transaction has been committed and
1914  // we are sure that the upload was indeed successful.
1915  $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
1916  DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
1917 
1918  if ( !$reupload ) {
1919  // This is a new file, so update the image count
1920  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1921  }
1922 
1923  JobQueueGroup::singleton()->lazyPush( $cacheUpdateJob );
1924  }, __METHOD__ );
1925 
1926  return Status::newGood();
1927  }
1928 
1945  public function publish( $src, $flags = 0, array $options = [] ) {
1946  return $this->publishTo( $src, $this->getRel(), $flags, $options );
1947  }
1948 
1965  protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1966  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1967 
1968  $repo = $this->getRepo();
1969  if ( $repo->getReadOnlyReason() !== false ) {
1970  return $this->readOnlyFatalStatus();
1971  }
1972 
1973  $this->lock();
1974 
1975  if ( $this->isOld() ) {
1976  $archiveRel = $dstRel;
1977  $archiveName = basename( $archiveRel );
1978  } else {
1979  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1980  $archiveRel = $this->getArchiveRel( $archiveName );
1981  }
1982 
1983  if ( $repo->hasSha1Storage() ) {
1984  $sha1 = FileRepo::isVirtualUrl( $srcPath )
1985  ? $repo->getFileSha1( $srcPath )
1986  : FSFile::getSha1Base36FromPath( $srcPath );
1988  $wrapperBackend = $repo->getBackend();
1989  '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
1990  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1991  $status = $repo->quickImport( $src, $dst );
1992  if ( $flags & File::DELETE_SOURCE ) {
1993  unlink( $srcPath );
1994  }
1995 
1996  if ( $this->exists() ) {
1997  $status->value = $archiveName;
1998  }
1999  } else {
2000  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2001  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2002 
2003  if ( $status->value == 'new' ) {
2004  $status->value = '';
2005  } else {
2006  $status->value = $archiveName;
2007  }
2008  }
2009 
2010  $this->unlock();
2011  return $status;
2012  }
2013 
2032  public function move( $target ) {
2033  $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2034  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2035  return $this->readOnlyFatalStatus();
2036  }
2037 
2038  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2039  $batch = new LocalFileMoveBatch( $this, $target );
2040 
2041  $this->lock();
2042  $batch->addCurrent();
2043  $archiveNames = $batch->addOlds();
2044  $status = $batch->execute();
2045  $this->unlock();
2046 
2047  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2048 
2049  // Purge the source and target files outside the transaction...
2050  $oldTitleFile = $localRepo->newFile( $this->title );
2051  $newTitleFile = $localRepo->newFile( $target );
2053  new AutoCommitUpdate(
2054  $this->getRepo()->getMasterDB(),
2055  __METHOD__,
2056  static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2057  $oldTitleFile->purgeEverything();
2058  foreach ( $archiveNames as $archiveName ) {
2060  '@phan-var OldLocalFile $oldTitleFile';
2061  $oldTitleFile->purgeOldThumbnails( $archiveName );
2062  }
2063  $newTitleFile->purgeEverything();
2064  }
2065  ),
2066  DeferredUpdates::PRESEND
2067  );
2068 
2069  if ( $status->isOK() ) {
2070  // Now switch the object
2071  $this->title = $target;
2072  // Force regeneration of the name and hashpath
2073  $this->name = null;
2074  $this->hashPath = null;
2075  }
2076 
2077  return $status;
2078  }
2079 
2096  public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2097  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2098  return $this->readOnlyFatalStatus();
2099  }
2100 
2101  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2102 
2103  $this->lock();
2104  $batch->addCurrent();
2105  // Get old version relative paths
2106  $archiveNames = $batch->addOlds();
2107  $status = $batch->execute();
2108  $this->unlock();
2109 
2110  if ( $status->isOK() ) {
2111  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2112  }
2113 
2114  // To avoid slow purges in the transaction, move them outside...
2116  new AutoCommitUpdate(
2117  $this->getRepo()->getMasterDB(),
2118  __METHOD__,
2119  function () use ( $archiveNames ) {
2120  $this->purgeEverything();
2121  foreach ( $archiveNames as $archiveName ) {
2122  $this->purgeOldThumbnails( $archiveName );
2123  }
2124  }
2125  ),
2126  DeferredUpdates::PRESEND
2127  );
2128 
2129  // Purge the CDN
2130  $purgeUrls = [];
2131  foreach ( $archiveNames as $archiveName ) {
2132  $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2133  }
2134 
2135  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2136  $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2137 
2138  return $status;
2139  }
2140 
2159  public function deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress = false ) {
2160  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2161  return $this->readOnlyFatalStatus();
2162  }
2163 
2164  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2165 
2166  $this->lock();
2167  $batch->addOld( $archiveName );
2168  $status = $batch->execute();
2169  $this->unlock();
2170 
2171  $this->purgeOldThumbnails( $archiveName );
2172  if ( $status->isOK() ) {
2173  $this->purgeDescription();
2174  }
2175 
2176  $url = $this->getArchiveUrl( $archiveName );
2177  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2178  $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2179 
2180  return $status;
2181  }
2182 
2195  public function restore( $versions = [], $unsuppress = false ) {
2196  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2197  return $this->readOnlyFatalStatus();
2198  }
2199 
2200  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2201 
2202  $this->lock();
2203  if ( !$versions ) {
2204  $batch->addAll();
2205  } else {
2206  $batch->addIds( $versions );
2207  }
2208  $status = $batch->execute();
2209  if ( $status->isGood() ) {
2210  $cleanupStatus = $batch->cleanup();
2211  $cleanupStatus->successCount = 0;
2212  $cleanupStatus->failCount = 0;
2213  $status->merge( $cleanupStatus );
2214  }
2215 
2216  $this->unlock();
2217  return $status;
2218  }
2219 
2230  public function getDescriptionUrl() {
2231  if ( !$this->title ) {
2232  return false; // Avoid hard failure when the file does not exist. T221812
2233  }
2234 
2235  return $this->title->getLocalURL();
2236  }
2237 
2247  public function getDescriptionText( Language $lang = null ) {
2248  if ( !$this->title ) {
2249  return false; // Avoid hard failure when the file does not exist. T221812
2250  }
2251 
2252  $store = MediaWikiServices::getInstance()->getRevisionStore();
2253  $revision = $store->getRevisionByTitle( $this->title, 0, RevisionStore::READ_NORMAL );
2254  if ( !$revision ) {
2255  return false;
2256  }
2257 
2258  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2259  $rendered = $renderer->getRenderedRevision(
2260  $revision,
2263  $lang
2264  )
2265  );
2266 
2267  if ( !$rendered ) {
2268  // audience check failed
2269  return false;
2270  }
2271 
2272  $pout = $rendered->getRevisionParserOutput();
2273  return $pout->getText();
2274  }
2275 
2283  public function getUploader( int $audience = self::FOR_PUBLIC, Authority $performer = null ): ?UserIdentity {
2284  $this->load();
2285  if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2286  return null;
2287  } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2288  return null;
2289  } else {
2290  return $this->user;
2291  }
2292  }
2293 
2300  public function getDescription( $audience = self::FOR_PUBLIC, Authority $performer = null ) {
2301  $this->load();
2302  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2303  return '';
2304  } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2305  return '';
2306  } else {
2307  return $this->description;
2308  }
2309  }
2310 
2315  public function getTimestamp() {
2316  $this->load();
2317 
2318  return $this->timestamp;
2319  }
2320 
2325  public function getDescriptionTouched() {
2326  if ( !$this->exists() ) {
2327  return false; // Avoid hard failure when the file does not exist. T221812
2328  }
2329 
2330  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2331  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2332  // need to differentiate between null (uninitialized) and false (failed to load).
2333  if ( $this->descriptionTouched === null ) {
2334  $cond = [
2335  'page_namespace' => $this->title->getNamespace(),
2336  'page_title' => $this->title->getDBkey()
2337  ];
2338  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2339  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2340  }
2341 
2343  }
2344 
2349  public function getSha1() {
2350  $this->load();
2351  // Initialise now if necessary
2352  if ( $this->sha1 == '' && $this->fileExists ) {
2353  $this->lock();
2354 
2355  $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2356  if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2357  $dbw = $this->repo->getMasterDB();
2358  $dbw->update( 'image',
2359  [ 'img_sha1' => $this->sha1 ],
2360  [ 'img_name' => $this->getName() ],
2361  __METHOD__ );
2362  $this->invalidateCache();
2363  }
2364 
2365  $this->unlock();
2366  }
2367 
2368  return $this->sha1;
2369  }
2370 
2374  public function isCacheable() {
2375  $this->load();
2376 
2377  // If extra data (metadata) was not loaded then it must have been large
2378  return $this->extraDataLoaded
2379  && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2380  }
2381 
2386  public function acquireFileLock() {
2387  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2388  [ $this->getPath() ], LockManager::LOCK_EX, 10
2389  ) );
2390  }
2391 
2396  public function releaseFileLock() {
2397  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2398  [ $this->getPath() ], LockManager::LOCK_EX
2399  ) );
2400  }
2401 
2411  public function lock() {
2412  if ( !$this->locked ) {
2413  $logger = LoggerFactory::getInstance( 'LocalFile' );
2414 
2415  $dbw = $this->repo->getMasterDB();
2416  $makesTransaction = !$dbw->trxLevel();
2417  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2418  // T56736: use simple lock to handle when the file does not exist.
2419  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2420  // Also, that would cause contention on INSERT of similarly named rows.
2421  $status = $this->acquireFileLock(); // represents all versions of the file
2422  if ( !$status->isGood() ) {
2423  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2424  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2425 
2426  throw new LocalFileLockError( $status );
2427  }
2428  // Release the lock *after* commit to avoid row-level contention.
2429  // Make sure it triggers on rollback() as well as commit() (T132921).
2430  $dbw->onTransactionResolution(
2431  function () use ( $logger ) {
2432  $status = $this->releaseFileLock();
2433  if ( !$status->isGood() ) {
2434  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2435  }
2436  },
2437  __METHOD__
2438  );
2439  // Callers might care if the SELECT snapshot is safely fresh
2440  $this->lockedOwnTrx = $makesTransaction;
2441  }
2442 
2443  $this->locked++;
2444 
2445  return $this->lockedOwnTrx;
2446  }
2447 
2456  public function unlock() {
2457  if ( $this->locked ) {
2458  --$this->locked;
2459  if ( !$this->locked ) {
2460  $dbw = $this->repo->getMasterDB();
2461  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2462  $this->lockedOwnTrx = false;
2463  }
2464  }
2465  }
2466 
2470  protected function readOnlyFatalStatus() {
2471  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2472  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2473  }
2474 
2478  public function __destruct() {
2479  $this->unlock();
2480  }
2481 }
LocalFile\$media_type
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition: LocalFile.php:80
LocalFile\getSha1
getSha1()
Definition: LocalFile.php:2349
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:148
LocalFile\$fileExists
bool $fileExists
Does the file exist on disk? (loadFromXxx)
Definition: LocalFile.php:68
File\getPath
getPath()
Return the storage path to the file.
Definition: File.php:456
$wgUpdateCompatibleMetadata
$wgUpdateCompatibleMetadata
If to automatically update the img_metadata field if the metadata field is outdated but compatible wi...
Definition: DefaultSettings.php:947
LocalFile\maybeUpgradeRow
maybeUpgradeRow()
Upgrade a row if it needs it.
Definition: LocalFile.php:702
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:52
LocalFileRestoreBatch
Helper class for file undeletion.
Definition: LocalFileRestoreBatch.php:30
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:317
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:575
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:385
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:71
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:283
LocalFile\unlock
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
Definition: LocalFile.php:2456
LocalFile\getTimestamp
getTimestamp()
Definition: LocalFile.php:2315
File\isMultipage
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition: File.php:2145
LocalFile\getRepo
getRepo()
Definition: LocalFile.php:298
LocalFile\loadFromDB
loadFromDB( $flags=0)
Load file metadata from the DB.
Definition: LocalFile.php:466
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:180
$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:1278
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:143
LocalFileDeleteBatch
Helper class for file deletion.
Definition: LocalFileDeleteBatch.php:32
MediaHandler\filterThumbnailPurgeList
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
Definition: MediaHandler.php:963
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1692
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:131
LocalFile\getDescriptionShortUrl
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
Definition: LocalFile.php:944
LocalFile\getCacheFields
getCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache.
Definition: LocalFile.php:428
Title\getPrefixedText
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1895
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:1088
LocalFile\getHistory
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
Definition: LocalFile.php:1319
LocalFile\getMediaType
getMediaType()
Returns the type of the media in the file.
Definition: LocalFile.php:1084
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:95
$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:2470
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:164
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1099
RequestContext\newExtraneousContext
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
Definition: RequestContext.php:653
LocalFile\$upgrading
bool $upgrading
Whether the row was scheduled to upgrade on load.
Definition: LocalFile.php:134
LocalFile\getSize
getSize()
Returns the size of the image file, in bytes @stable to override.
Definition: LocalFile.php:1061
LocalFile\purgeOldThumbnails
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
Definition: LocalFile.php:1183
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:1123
LocalFile\$sha1
string $sha1
SHA-1 base 36 content hash.
Definition: LocalFile.php:92
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:116
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:2055
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:2386
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
$dbr
$dbr
Definition: testCompression.php:54
LocalFile\isCacheable
isCacheable()
Definition: LocalFile.php:2374
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:1265
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:77
LocalFile\purgeThumbnails
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
Definition: LocalFile.php:1210
FileRepo\hasSha1Storage
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:2016
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:499
LocalFile\publishTo
publishTo( $src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
Definition: LocalFile.php:1965
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:179
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:2325
LocalFile\purgeMetadataCache
purgeMetadataCache()
Refresh metadata in memcached, but don't touch thumbnails or CDN.
Definition: LocalFile.php:1148
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:24
FileRepo\quickImport
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:1055
LocalFile\getUpgraded
getUpgraded()
Definition: LocalFile.php:741
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:65
LocalFile\loadFromRow
loadFromRow( $row, $prefix='img_')
Load file metadata from a DB result row.
Definition: LocalFile.php:607
LocalFile\__destruct
__destruct()
Clean up any dangling locks.
Definition: LocalFile.php:2478
LocalFile\$deleted
int $deleted
Bitfield akin to rev_deleted.
Definition: LocalFile.php:101
$wgUploadThumbnailRenderMap
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
Definition: DefaultSettings.php:1664
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:110
MediaHandler\isFileMetadataValid
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.
Definition: MediaHandler.php:374
EDIT_NEW
const EDIT_NEW
Definition: Defines.php:125
LocalFile\$user
UserIdentity null $user
Uploader.
Definition: LocalFile.php:122
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:2247
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:2365
LocalFile\prerenderThumbnails
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
Definition: LocalFile.php:1250
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:1572
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:308
MediaHandler\getPageDimensions
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
Definition: MediaHandler.php:608
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:698
$revStore
$revStore
Definition: testCompression.php:55
LocalFile\$mime
string $mime
MIME type, determined by MimeAnalyzer::guessMimeType.
Definition: LocalFile.php:83
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:805
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:1029
FileRepo\getFileSha1
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1677
LocalFile
Class to represent a local file in the wiki's own database.
Definition: LocalFile.php:62
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:144
LocalFile\loadFromFile
loadFromFile( $path=null)
Load metadata from the file itself.
Definition: LocalFile.php:416
LocalFile\getMimeType
getMimeType()
Returns the MIME type of the file.
Definition: LocalFile.php:1072
LocalFile\$extraDataLoaded
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
Definition: LocalFile.php:98
ThumbnailRenderJob
Job for asynchronous rendering of thumbnails.
Definition: ThumbnailRenderJob.php:31
LocalFile\$size
int $size
Size in bytes (loadFromXxx)
Definition: LocalFile.php:86
MediaWiki\Permissions\Authority
This interface represents the authority associated the current execution context, such as a web reque...
Definition: Authority.php:35
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:146
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:2411
File\isOld
isOld()
Returns true if the image is an old version STUB.
Definition: File.php:2043
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:2479
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:107
LocalFile\$metadataArray
array $metadataArray
Unserialized metadata.
Definition: LocalFile.php:89
LocalFile\releaseFileLock
releaseFileLock()
Definition: LocalFile.php:2396
LocalFile\upgradeRow
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file.
Definition: LocalFile.php:749
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:684
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:129
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:198
LocalFile\nextHistoryLine
nextHistoryLine()
Returns the history of this file, line by line.
Definition: LocalFile.php:1378
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:1467
File\$title
Title string bool $title
Definition: File.php:116
LocalFile\getBitDepth
getBitDepth()
@stable to override
Definition: LocalFile.php:1050
LocalFile\getMetadataForDb
getMetadataForDb(IDatabase $db)
Serialize the metadata array for insertion into img_metadata, oi_metadata or fa_metadata.
Definition: LocalFile.php:997
LocalFile\$height
int $height
Image height.
Definition: LocalFile.php:74
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:1018
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
FSFile
Class representing a non-directory file on the file system.
Definition: FSFile.php:32
LocalFile\$timestamp
string $timestamp
Upload timestamp.
Definition: LocalFile.php:119
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:483
LocalFile\$descriptionTouched
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
Definition: LocalFile.php:128
File\DELETE_SOURCE
const DELETE_SOURCE
Definition: File.php:83
LocalFile\deleteFile
deleteFile( $reason, UserIdentity $user, $suppress=false)
Delete all versions of the file.
Definition: LocalFile.php:2096
LocalFile\$locked
bool $locked
True if the image row is locked.
Definition: LocalFile.php:137
LocalFile\deleteOldFile
deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress=false)
Delete an old version of the file.
Definition: LocalFile.php:2159
unserialize
unserialize( $serialized)
Definition: ApiMessageTrait.php:146
LocalFile\$description
string $description
Description of current revision of the file.
Definition: LocalFile.php:125
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:450
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:235
LocalFile\getMetadata
getMetadata()
Get handler-specific metadata as a serialized string.
Definition: LocalFile.php:966
LinksUpdate\queueRecursiveJobsForTable
static queueRecursiveJobsForTable(PageIdentity $page, $table, $action='unknown', $userName='unknown')
Queue a RefreshLinks job for any table.
Definition: LinksUpdate.php:392
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:1199
$cache
$cache
Definition: mcc.php:33
File\assertRepoDefined
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition: File.php:2469
LocalFile\resetHistory
resetHistory()
Reset the history pointer to the first element of the history.
Definition: LocalFile.php:1426
LocalFile\getDescription
getDescription( $audience=self::FOR_PUBLIC, Authority $performer=null)
Definition: LocalFile.php:2300
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:530
LocalFileMoveBatch
Helper class for file movement.
Definition: LocalFileMoveBatch.php:33
LocalFile\getUploader
getUploader(int $audience=self::FOR_PUBLIC, Authority $performer=null)
Definition: LocalFile.php:2283
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:43
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:1945
Title\invalidateCache
invalidateCache( $purgeTime=null)
Updates page_touched for this page; called from LinksUpdate.php.
Definition: Title.php:4029
LocalFile\getWidth
getWidth( $page=1)
Return the width of the image @stable to override.
Definition: LocalFile.php:878
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:113
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:911
LocalFile\isMissing
isMissing()
splitMime inherited
Definition: LocalFile.php:862
LocalFile\invalidateCache
invalidateCache()
Purge the file object/metadata cache.
Definition: LocalFile.php:395
LocalFile\$lockedOwnTrx
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
Definition: LocalFile.php:140
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:63
LocalFile\getDescriptionUrl
getDescriptionUrl()
isMultipage inherited
Definition: LocalFile.php:2230
LocalFile\move
move( $target)
getLinksTo inherited
Definition: LocalFile.php:2032
LocalFile\$repoClass
string $repoClass
Definition: LocalFile.php:104
LocalFile\restore
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition: LocalFile.php:2195
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:1101
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:984
LocalFile\loadFromCache
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
Definition: LocalFile.php:324
LocalFile\purgeCache
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
Definition: LocalFile.php:1160
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:1336
Wikimedia\Rdbms\Blob
@newable
Definition: Blob.php:9