MediaWiki  master
LocalFile.php
Go to the documentation of this file.
1 <?php
28 use Wikimedia\AtEase\AtEase;
32 
59 class LocalFile extends File {
60  private const VERSION = 12; // cache version
61 
62  private const CACHE_FIELD_MAX_LEN = 1000;
63 
65  protected $fileExists;
66 
68  protected $width;
69 
71  protected $height;
72 
74  protected $bits;
75 
77  protected $media_type;
78 
80  protected $mime;
81 
83  protected $size;
84 
86  protected $metadata;
87 
89  protected $sha1;
90 
92  protected $dataLoaded;
93 
95  protected $extraDataLoaded;
96 
98  protected $deleted;
99 
101  protected $repoClass = LocalRepo::class;
102 
104  private $historyLine;
105 
107  private $historyRes;
108 
110  private $major_mime;
111 
113  private $minor_mime;
114 
116  private $timestamp;
117 
119  private $user;
120 
122  private $description;
123 
126 
128  private $upgraded;
129 
131  private $upgrading;
132 
134  private $locked;
135 
137  private $lockedOwnTrx;
138 
140  private $missing;
141 
142  // @note: higher than IDBAccessObject constants
143  private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
144 
145  private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
146 
161  public static function newFromTitle( $title, $repo, $unused = null ) {
162  return new static( $title, $repo );
163  }
164 
176  public static function newFromRow( $row, $repo ) {
177  $title = Title::makeTitle( NS_FILE, $row->img_name );
178  $file = new static( $title, $repo );
179  $file->loadFromRow( $row );
180 
181  return $file;
182  }
183 
195  public static function newFromKey( $sha1, $repo, $timestamp = false ) {
196  $dbr = $repo->getReplicaDB();
197 
198  $conds = [ 'img_sha1' => $sha1 ];
199  if ( $timestamp ) {
200  $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
201  }
202 
203  $fileQuery = static::getQueryInfo();
204  $row = $dbr->selectRow(
205  $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__, [], $fileQuery['joins']
206  );
207  if ( $row ) {
208  return static::newFromRow( $row, $repo );
209  } else {
210  return false;
211  }
212  }
213 
227  public static function getQueryInfo( array $options = [] ) {
228  $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'img_description' );
229  $actorQuery = ActorMigration::newMigration()->getJoin( 'img_user' );
230  $ret = [
231  'tables' => [ 'image' ] + $commentQuery['tables'] + $actorQuery['tables'],
232  'fields' => [
233  'img_name',
234  'img_size',
235  'img_width',
236  'img_height',
237  'img_metadata',
238  'img_bits',
239  'img_media_type',
240  'img_major_mime',
241  'img_minor_mime',
242  'img_timestamp',
243  'img_sha1',
244  ] + $commentQuery['fields'] + $actorQuery['fields'],
245  'joins' => $commentQuery['joins'] + $actorQuery['joins'],
246  ];
247 
248  if ( in_array( 'omit-nonlazy', $options, true ) ) {
249  // Internal use only for getting only the lazy fields
250  $ret['fields'] = [];
251  }
252  if ( !in_array( 'omit-lazy', $options, true ) ) {
253  // Note: Keep this in sync with self::getLazyCacheFields()
254  $ret['fields'][] = 'img_metadata';
255  }
256 
257  return $ret;
258  }
259 
267  public function __construct( $title, $repo ) {
268  parent::__construct( $title, $repo );
269 
270  $this->metadata = '';
271  $this->historyLine = 0;
272  $this->historyRes = null;
273  $this->dataLoaded = false;
274  $this->extraDataLoaded = false;
275 
276  $this->assertRepoDefined();
277  $this->assertTitleDefined();
278  }
279 
283  public function getRepo() {
284  return $this->repo;
285  }
286 
293  protected function getCacheKey() {
294  return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
295  }
296 
303  return [ $this->getCacheKey() ];
304  }
305 
309  private function loadFromCache() {
310  $this->dataLoaded = false;
311  $this->extraDataLoaded = false;
312 
313  $key = $this->getCacheKey();
314  if ( !$key ) {
315  $this->loadFromDB( self::READ_NORMAL );
316 
317  return;
318  }
319 
320  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
321  $cachedValues = $cache->getWithSetCallback(
322  $key,
323  $cache::TTL_WEEK,
324  function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
325  $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
326 
327  $this->loadFromDB( self::READ_NORMAL );
328 
329  $fields = $this->getCacheFields( '' );
330  $cacheVal = [];
331  $cacheVal['fileExists'] = $this->fileExists;
332  if ( $this->fileExists ) {
333  foreach ( $fields as $field ) {
334  $cacheVal[$field] = $this->$field;
335  }
336  }
337  $cacheVal['user'] = $this->user ? $this->user->getId() : 0;
338  $cacheVal['user_text'] = $this->user ? $this->user->getName() : '';
339  $cacheVal['actor'] = $this->user ? $this->user->getActorId() : null;
340 
341  // Strip off excessive entries from the subset of fields that can become large.
342  // If the cache value gets to large it will not fit in memcached and nothing will
343  // get cached at all, causing master queries for any file access.
344  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
345  if ( isset( $cacheVal[$field] )
346  && strlen( $cacheVal[$field] ) > 100 * 1024
347  ) {
348  unset( $cacheVal[$field] ); // don't let the value get too big
349  }
350  }
351 
352  if ( $this->fileExists ) {
353  $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
354  } else {
355  $ttl = $cache::TTL_DAY;
356  }
357 
358  return $cacheVal;
359  },
360  [ 'version' => self::VERSION ]
361  );
362 
363  $this->fileExists = $cachedValues['fileExists'];
364  if ( $this->fileExists ) {
365  $this->setProps( $cachedValues );
366  }
367 
368  $this->dataLoaded = true;
369  $this->extraDataLoaded = true;
370  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
371  $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
372  }
373  }
374 
378  public function invalidateCache() {
379  $key = $this->getCacheKey();
380  if ( !$key ) {
381  return;
382  }
383 
384  $this->repo->getMasterDB()->onTransactionPreCommitOrIdle(
385  static function () use ( $key ) {
386  MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
387  },
388  __METHOD__
389  );
390  }
391 
395  protected function loadFromFile() {
396  $props = $this->repo->getFileProps( $this->getVirtualUrl() );
397  $this->setProps( $props );
398  }
399 
407  protected function getCacheFields( $prefix = 'img_' ) {
408  if ( $prefix !== '' ) {
409  throw new InvalidArgumentException(
410  __METHOD__ . ' with a non-empty prefix is no longer supported.'
411  );
412  }
413 
414  // See self::getQueryInfo() for the fetching of the data from the DB,
415  // self::loadFromRow() for the loading of the object from the DB row,
416  // and self::loadFromCache() for the caching, and self::setProps() for
417  // populating the object from an array of data.
418  return [ 'size', 'width', 'height', 'bits', 'media_type',
419  'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
420  }
421 
429  protected function getLazyCacheFields( $prefix = 'img_' ) {
430  if ( $prefix !== '' ) {
431  throw new InvalidArgumentException(
432  __METHOD__ . ' with a non-empty prefix is no longer supported.'
433  );
434  }
435 
436  // Keep this in sync with the omit-lazy option in self::getQueryInfo().
437  return [ 'metadata' ];
438  }
439 
445  protected function loadFromDB( $flags = 0 ) {
446  $fname = static::class . '::' . __FUNCTION__;
447 
448  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
449  $this->dataLoaded = true;
450  $this->extraDataLoaded = true;
451 
452  $dbr = ( $flags & self::READ_LATEST )
453  ? $this->repo->getMasterDB()
454  : $this->repo->getReplicaDB();
455 
456  $fileQuery = static::getQueryInfo();
457  $row = $dbr->selectRow(
458  $fileQuery['tables'],
459  $fileQuery['fields'],
460  [ 'img_name' => $this->getName() ],
461  $fname,
462  [],
463  $fileQuery['joins']
464  );
465 
466  if ( $row ) {
467  $this->loadFromRow( $row );
468  } else {
469  $this->fileExists = false;
470  }
471  }
472 
478  protected function loadExtraFromDB() {
479  if ( !$this->title ) {
480  return; // Avoid hard failure when the file does not exist. T221812
481  }
482 
483  $fname = static::class . '::' . __FUNCTION__;
484 
485  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
486  $this->extraDataLoaded = true;
487 
488  $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo->getReplicaDB(), $fname );
489  if ( !$fieldMap ) {
490  $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo->getMasterDB(), $fname );
491  }
492 
493  if ( $fieldMap ) {
494  foreach ( $fieldMap as $name => $value ) {
495  $this->$name = $value;
496  }
497  } else {
498  throw new MWException( "Could not find data for image '{$this->getName()}'." );
499  }
500  }
501 
507  private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
508  $fieldMap = false;
509 
510  $fileQuery = self::getQueryInfo( [ 'omit-nonlazy' ] );
511  $row = $dbr->selectRow(
512  $fileQuery['tables'],
513  $fileQuery['fields'],
514  [
515  'img_name' => $this->getName(),
516  'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
517  ],
518  $fname,
519  [],
520  $fileQuery['joins']
521  );
522  if ( $row ) {
523  $fieldMap = $this->unprefixRow( $row, 'img_' );
524  } else {
525  # File may have been uploaded over in the meantime; check the old versions
526  $fileQuery = OldLocalFile::getQueryInfo( [ 'omit-nonlazy' ] );
527  $row = $dbr->selectRow(
528  $fileQuery['tables'],
529  $fileQuery['fields'],
530  [
531  'oi_name' => $this->getName(),
532  'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
533  ],
534  $fname,
535  [],
536  $fileQuery['joins']
537  );
538  if ( $row ) {
539  $fieldMap = $this->unprefixRow( $row, 'oi_' );
540  }
541  }
542 
543  if ( isset( $fieldMap['metadata'] ) ) {
544  $fieldMap['metadata'] = $this->repo->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
545  }
546 
547  return $fieldMap;
548  }
549 
556  protected function unprefixRow( $row, $prefix = 'img_' ) {
557  $array = (array)$row;
558  $prefixLength = strlen( $prefix );
559 
560  // Sanity check prefix once
561  if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
562  throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
563  }
564 
565  $decoded = [];
566  foreach ( $array as $name => $value ) {
567  $decoded[substr( $name, $prefixLength )] = $value;
568  }
569 
570  return $decoded;
571  }
572 
581  private function decodeRow( $row, $prefix = 'img_' ) {
582  $decoded = $this->unprefixRow( $row, $prefix );
583 
584  $decoded['description'] = MediaWikiServices::getInstance()->getCommentStore()
585  ->getComment( 'description', (object)$decoded )->text;
586 
587  $decoded['user'] = User::newFromAnyId(
588  $decoded['user'] ?? null,
589  $decoded['user_text'] ?? null,
590  $decoded['actor'] ?? null
591  );
592  unset( $decoded['user_text'], $decoded['actor'] );
593 
594  $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
595 
596  $decoded['metadata'] = $this->repo->getReplicaDB()->decodeBlob( $decoded['metadata'] );
597 
598  if ( empty( $decoded['major_mime'] ) ) {
599  $decoded['mime'] = 'unknown/unknown';
600  } else {
601  if ( !$decoded['minor_mime'] ) {
602  $decoded['minor_mime'] = 'unknown';
603  }
604  $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
605  }
606 
607  // Trim zero padding from char/binary field
608  $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
609 
610  // Normalize some fields to integer type, per their database definition.
611  // Use unary + so that overflows will be upgraded to double instead of
612  // being trucated as with intval(). This is important to allow >2GB
613  // files on 32-bit systems.
614  foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
615  $decoded[$field] = +$decoded[$field];
616  }
617 
618  return $decoded;
619  }
620 
628  public function loadFromRow( $row, $prefix = 'img_' ) {
629  $this->dataLoaded = true;
630  $this->extraDataLoaded = true;
631 
632  $array = $this->decodeRow( $row, $prefix );
633 
634  foreach ( $array as $name => $value ) {
635  $this->$name = $value;
636  }
637 
638  $this->fileExists = true;
639  }
640 
646  public function load( $flags = 0 ) {
647  if ( !$this->dataLoaded ) {
648  if ( $flags & self::READ_LATEST ) {
649  $this->loadFromDB( $flags );
650  } else {
651  $this->loadFromCache();
652  }
653  }
654 
655  if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
656  // @note: loads on name/timestamp to reduce race condition problems
657  $this->loadExtraFromDB();
658  }
659  }
660 
664  protected function maybeUpgradeRow() {
666 
667  if ( wfReadOnly() || $this->upgrading ) {
668  return;
669  }
670 
671  $upgrade = false;
672  if ( $this->media_type === null || $this->mime == 'image/svg' ) {
673  $upgrade = true;
674  } else {
675  $handler = $this->getHandler();
676  if ( $handler ) {
677  $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
678  if ( $validity === MediaHandler::METADATA_BAD ) {
679  $upgrade = true;
680  } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE ) {
681  $upgrade = $wgUpdateCompatibleMetadata;
682  }
683  }
684  }
685 
686  if ( $upgrade ) {
687  $this->upgrading = true;
688  // Defer updates unless in auto-commit CLI mode
690  $this->upgrading = false; // avoid duplicate updates
691  try {
692  $this->upgradeRow();
693  } catch ( LocalFileLockError $e ) {
694  // let the other process handle it (or do it next time)
695  }
696  } );
697  }
698  }
699 
703  public function getUpgraded() {
704  return $this->upgraded;
705  }
706 
711  public function upgradeRow() {
712  $this->lock();
713 
714  $this->loadFromFile();
715 
716  # Don't destroy file info of missing files
717  if ( !$this->fileExists ) {
718  $this->unlock();
719  wfDebug( __METHOD__ . ": file does not exist, aborting" );
720 
721  return;
722  }
723 
724  $dbw = $this->repo->getMasterDB();
725  list( $major, $minor ) = self::splitMime( $this->mime );
726 
727  if ( wfReadOnly() ) {
728  $this->unlock();
729 
730  return;
731  }
732  wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
733 
734  $dbw->update( 'image',
735  [
736  'img_size' => $this->size, // sanity
737  'img_width' => $this->width,
738  'img_height' => $this->height,
739  'img_bits' => $this->bits,
740  'img_media_type' => $this->media_type,
741  'img_major_mime' => $major,
742  'img_minor_mime' => $minor,
743  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
744  'img_sha1' => $this->sha1,
745  ],
746  [ 'img_name' => $this->getName() ],
747  __METHOD__
748  );
749 
750  $this->invalidateCache();
751 
752  $this->unlock();
753  $this->upgraded = true; // avoid rework/retries
754  }
755 
767  protected function setProps( $info ) {
768  $this->dataLoaded = true;
769  $fields = $this->getCacheFields( '' );
770  $fields[] = 'fileExists';
771 
772  foreach ( $fields as $field ) {
773  if ( isset( $info[$field] ) ) {
774  $this->$field = $info[$field];
775  }
776  }
777 
778  if ( isset( $info['user'] ) || isset( $info['user_text'] ) || isset( $info['actor'] ) ) {
779  $this->user = User::newFromAnyId(
780  $info['user'] ?? null,
781  $info['user_text'] ?? null,
782  $info['actor'] ?? null
783  );
784  }
785 
786  // Fix up mime fields
787  if ( isset( $info['major_mime'] ) ) {
788  $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
789  } elseif ( isset( $info['mime'] ) ) {
790  $this->mime = $info['mime'];
791  list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
792  }
793  }
794 
810  public function isMissing() {
811  if ( $this->missing === null ) {
812  $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
813  $this->missing = !$fileExists;
814  }
815 
816  return $this->missing;
817  }
818 
826  public function getWidth( $page = 1 ) {
827  $page = (int)$page;
828  if ( $page < 1 ) {
829  $page = 1;
830  }
831 
832  $this->load();
833 
834  if ( $this->isMultipage() ) {
835  $handler = $this->getHandler();
836  if ( !$handler ) {
837  return 0;
838  }
839  $dim = $handler->getPageDimensions( $this, $page );
840  if ( $dim ) {
841  return $dim['width'];
842  } else {
843  // For non-paged media, the false goes through an
844  // intval, turning failure into 0, so do same here.
845  return 0;
846  }
847  } else {
848  return $this->width;
849  }
850  }
851 
859  public function getHeight( $page = 1 ) {
860  $page = (int)$page;
861  if ( $page < 1 ) {
862  $page = 1;
863  }
864 
865  $this->load();
866 
867  if ( $this->isMultipage() ) {
868  $handler = $this->getHandler();
869  if ( !$handler ) {
870  return 0;
871  }
872  $dim = $handler->getPageDimensions( $this, $page );
873  if ( $dim ) {
874  return $dim['height'];
875  } else {
876  // For non-paged media, the false goes through an
877  // intval, turning failure into 0, so do same here.
878  return 0;
879  }
880  } else {
881  return $this->height;
882  }
883  }
884 
893  public function getUser( $type = 'text' ) {
894  $this->load();
895 
896  if ( !$this->user ) {
897  // If the file does not exist, $this->user will be null, see T221812.
898  // Note: 'Unknown user' this is a reserved user name.
899  if ( $type === 'object' ) {
900  return User::newFromName( 'Unknown user', false );
901  } elseif ( $type === 'text' ) {
902  return 'Unknown user';
903  } elseif ( $type === 'id' ) {
904  return 0;
905  }
906  } else {
907  if ( $type === 'object' ) {
908  return $this->user;
909  } elseif ( $type === 'text' ) {
910  return $this->user->getName();
911  } elseif ( $type === 'id' ) {
912  return $this->user->getId();
913  }
914  }
915 
916  throw new MWException( "Unknown type '$type'." );
917  }
918 
926  public function getDescriptionShortUrl() {
927  if ( !$this->title ) {
928  return null; // Avoid hard failure when the file does not exist. T221812
929  }
930 
931  $pageId = $this->title->getArticleID();
932 
933  if ( $pageId ) {
934  $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
935  if ( $url !== false ) {
936  return $url;
937  }
938  }
939  return null;
940  }
941 
947  public function getMetadata() {
948  $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
949  return $this->metadata;
950  }
951 
956  public function getBitDepth() {
957  $this->load();
958 
959  return (int)$this->bits;
960  }
961 
967  public function getSize() {
968  $this->load();
969 
970  return $this->size;
971  }
972 
978  public function getMimeType() {
979  $this->load();
980 
981  return $this->mime;
982  }
983 
990  public function getMediaType() {
991  $this->load();
992 
993  return $this->media_type;
994  }
995 
1007  public function exists() {
1008  $this->load();
1009 
1010  return $this->fileExists;
1011  }
1012 
1029  protected function getThumbnails( $archiveName = false ) {
1030  if ( $archiveName ) {
1031  $dir = $this->getArchiveThumbPath( $archiveName );
1032  } else {
1033  $dir = $this->getThumbPath();
1034  }
1035 
1036  $backend = $this->repo->getBackend();
1037  $files = [ $dir ];
1038  try {
1039  $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1040  if ( $iterator !== null ) {
1041  foreach ( $iterator as $file ) {
1042  $files[] = $file;
1043  }
1044  }
1045  } catch ( FileBackendError $e ) {
1046  } // suppress (T56674)
1047 
1048  return $files;
1049  }
1050 
1054  private function purgeMetadataCache() {
1055  $this->invalidateCache();
1056  }
1057 
1066  public function purgeCache( $options = [] ) {
1067  // Refresh metadata cache
1068  $this->maybeUpgradeRow();
1069  $this->purgeMetadataCache();
1070 
1071  // Delete thumbnails
1072  $this->purgeThumbnails( $options );
1073 
1074  // Purge CDN cache for this file
1075  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1076  $hcu->purgeUrls(
1077  $this->getUrl(),
1078  !empty( $options['forThumbRefresh'] )
1079  ? $hcu::PURGE_PRESEND // just a manual purge
1080  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1081  );
1082  }
1083 
1089  public function purgeOldThumbnails( $archiveName ) {
1090  // Get a list of old thumbnails and URLs
1091  $files = $this->getThumbnails( $archiveName );
1092 
1093  // Purge any custom thumbnail caches
1094  $this->hookRunner->onLocalFilePurgeThumbnails( $this, $archiveName );
1095 
1096  // Delete thumbnails
1097  $dir = array_shift( $files );
1098  $this->purgeThumbList( $dir, $files );
1099 
1100  // Purge the CDN
1101  $urls = [];
1102  foreach ( $files as $file ) {
1103  $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1104  }
1105 
1106  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1107  $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1108  }
1109 
1116  public function purgeThumbnails( $options = [] ) {
1117  $files = $this->getThumbnails();
1118  // Always purge all files from CDN regardless of handler filters
1119  $urls = [];
1120  foreach ( $files as $file ) {
1121  $urls[] = $this->getThumbUrl( $file );
1122  }
1123  array_shift( $urls ); // don't purge directory
1124 
1125  // Give media handler a chance to filter the file purge list
1126  if ( !empty( $options['forThumbRefresh'] ) ) {
1127  $handler = $this->getHandler();
1128  if ( $handler ) {
1129  $handler->filterThumbnailPurgeList( $files, $options );
1130  }
1131  }
1132 
1133  // Purge any custom thumbnail caches
1134  $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false );
1135 
1136  // Delete thumbnails
1137  $dir = array_shift( $files );
1138  $this->purgeThumbList( $dir, $files );
1139 
1140  // Purge the CDN
1141  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1142  $hcu->purgeUrls(
1143  $urls,
1144  !empty( $options['forThumbRefresh'] )
1145  ? $hcu::PURGE_PRESEND // just a manual purge
1146  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1147  );
1148  }
1149 
1156  public function prerenderThumbnails() {
1158 
1159  $jobs = [];
1160 
1161  $sizes = $wgUploadThumbnailRenderMap;
1162  rsort( $sizes );
1163 
1164  foreach ( $sizes as $size ) {
1165  if ( $this->isVectorized() || $this->getWidth() > $size ) {
1166  $jobs[] = new ThumbnailRenderJob(
1167  $this->getTitle(),
1168  [ 'transformParams' => [ 'width' => $size ] ]
1169  );
1170  }
1171  }
1172 
1173  if ( $jobs ) {
1174  JobQueueGroup::singleton()->lazyPush( $jobs );
1175  }
1176  }
1177 
1184  protected function purgeThumbList( $dir, $files ) {
1185  $fileListDebug = strtr(
1186  var_export( $files, true ),
1187  [ "\n" => '' ]
1188  );
1189  wfDebug( __METHOD__ . ": $fileListDebug" );
1190 
1191  $purgeList = [];
1192  foreach ( $files as $file ) {
1193  if ( $this->repo->supportsSha1URLs() ) {
1194  $reference = $this->getSha1();
1195  } else {
1196  $reference = $this->getName();
1197  }
1198 
1199  # Check that the reference (filename or sha1) is part of the thumb name
1200  # This is a basic sanity check to avoid erasing unrelated directories
1201  if ( strpos( $file, $reference ) !== false
1202  || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1203  ) {
1204  $purgeList[] = "{$dir}/{$file}";
1205  }
1206  }
1207 
1208  # Delete the thumbnails
1209  $this->repo->quickPurgeBatch( $purgeList );
1210  # Clear out the thumbnail directory if empty
1211  $this->repo->quickCleanDir( $dir );
1212  }
1213 
1225  public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1226  if ( !$this->exists() ) {
1227  return []; // Avoid hard failure when the file does not exist. T221812
1228  }
1229 
1230  $dbr = $this->repo->getReplicaDB();
1231  $oldFileQuery = OldLocalFile::getQueryInfo();
1232 
1233  $tables = $oldFileQuery['tables'];
1234  $fields = $oldFileQuery['fields'];
1235  $join_conds = $oldFileQuery['joins'];
1236  $conds = $opts = [];
1237  $eq = $inc ? '=' : '';
1238  $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1239 
1240  if ( $start ) {
1241  $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1242  }
1243 
1244  if ( $end ) {
1245  $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1246  }
1247 
1248  if ( $limit ) {
1249  $opts['LIMIT'] = $limit;
1250  }
1251 
1252  // Search backwards for time > x queries
1253  $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1254  $opts['ORDER BY'] = "oi_timestamp $order";
1255  $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1256 
1257  $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1258  $conds, $opts, $join_conds );
1259 
1260  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1261  $r = [];
1262 
1263  foreach ( $res as $row ) {
1264  $r[] = $this->repo->newFileFromRow( $row );
1265  }
1266 
1267  if ( $order == 'ASC' ) {
1268  $r = array_reverse( $r ); // make sure it ends up descending
1269  }
1270 
1271  return $r;
1272  }
1273 
1284  public function nextHistoryLine() {
1285  if ( !$this->exists() ) {
1286  return false; // Avoid hard failure when the file does not exist. T221812
1287  }
1288 
1289  # Polymorphic function name to distinguish foreign and local fetches
1290  $fname = static::class . '::' . __FUNCTION__;
1291 
1292  $dbr = $this->repo->getReplicaDB();
1293 
1294  if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1295  $fileQuery = self::getQueryInfo();
1296  $this->historyRes = $dbr->select( $fileQuery['tables'],
1297  $fileQuery['fields'] + [
1298  'oi_archive_name' => $dbr->addQuotes( '' ),
1299  'oi_deleted' => 0,
1300  ],
1301  [ 'img_name' => $this->title->getDBkey() ],
1302  $fname,
1303  [],
1304  $fileQuery['joins']
1305  );
1306 
1307  if ( $dbr->numRows( $this->historyRes ) == 0 ) {
1308  $this->historyRes = null;
1309 
1310  return false;
1311  }
1312  } elseif ( $this->historyLine == 1 ) {
1313  $fileQuery = OldLocalFile::getQueryInfo();
1314  $this->historyRes = $dbr->select(
1315  $fileQuery['tables'],
1316  $fileQuery['fields'],
1317  [ 'oi_name' => $this->title->getDBkey() ],
1318  $fname,
1319  [ 'ORDER BY' => 'oi_timestamp DESC' ],
1320  $fileQuery['joins']
1321  );
1322  }
1323  $this->historyLine++;
1324 
1325  return $dbr->fetchObject( $this->historyRes );
1326  }
1327 
1332  public function resetHistory() {
1333  $this->historyLine = 0;
1334 
1335  if ( $this->historyRes !== null ) {
1336  $this->historyRes = null;
1337  }
1338  }
1339 
1373  public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1374  $timestamp = false, $user = null, $tags = [],
1375  $createNullRevision = true, $revert = false
1376  ) {
1377  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1378  return $this->readOnlyFatalStatus();
1379  } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1380  // Check this in advance to avoid writing to FileBackend and the file tables,
1381  // only to fail on insert the revision due to the text store being unavailable.
1382  return $this->readOnlyFatalStatus();
1383  }
1384 
1385  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1386  if ( !$props ) {
1387  if ( FileRepo::isVirtualUrl( $srcPath )
1388  || FileBackend::isStoragePath( $srcPath )
1389  ) {
1390  $props = $this->repo->getFileProps( $srcPath );
1391  } else {
1392  $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1393  $props = $mwProps->getPropsFromPath( $srcPath, true );
1394  }
1395  }
1396 
1397  $options = [];
1398  $handler = MediaHandler::getHandler( $props['mime'] );
1399  if ( $handler ) {
1400  $metadata = AtEase::quietCall( 'unserialize', $props['metadata'] );
1401 
1402  if ( !is_array( $metadata ) ) {
1403  $metadata = [];
1404  }
1405 
1406  $options['headers'] = $handler->getContentHeaders( $metadata );
1407  } else {
1408  $options['headers'] = [];
1409  }
1410 
1411  // Trim spaces on user supplied text
1412  $comment = trim( $comment );
1413 
1414  $this->lock();
1415  $status = $this->publish( $src, $flags, $options );
1416 
1417  if ( $status->successCount >= 2 ) {
1418  // There will be a copy+(one of move,copy,store).
1419  // The first succeeding does not commit us to updating the DB
1420  // since it simply copied the current version to a timestamped file name.
1421  // It is only *preferable* to avoid leaving such files orphaned.
1422  // Once the second operation goes through, then the current version was
1423  // updated and we must therefore update the DB too.
1424  $oldver = $status->value;
1425 
1426  if ( $user === null ) {
1427  // User argument is optional, fall back to the context user
1428  $user = RequestContext::getMain()->getUser();
1429  }
1430 
1431  $uploadStatus = $this->recordUpload3(
1432  $oldver,
1433  $comment,
1434  $pageText,
1435  $user,
1436  $props,
1437  $timestamp,
1438  $tags,
1439  $createNullRevision,
1440  $revert
1441  );
1442  if ( !$uploadStatus->isOK() ) {
1443  if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1444  // update filenotfound error with more specific path
1445  $status->fatal( 'filenotfound', $srcPath );
1446  } else {
1447  $status->merge( $uploadStatus );
1448  }
1449  }
1450  }
1451 
1452  $this->unlock();
1453  return $status;
1454  }
1455 
1471  public function recordUpload2(
1472  $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1473  $createNullRevision = true, $revert = false
1474  ) {
1475  wfDeprecated( __METHOD__, '1.35' );
1476  if ( $user === null ) {
1477  global $wgUser;
1478  $user = $wgUser;
1479  }
1480  return $this->recordUpload3(
1481  $oldver, $comment, $pageText,
1482  $user, $props, $timestamp, $tags,
1483  $createNullRevision, $revert
1484  );
1485  }
1486 
1503  public function recordUpload3(
1504  string $oldver,
1505  string $comment,
1506  string $pageText,
1507  User $user,
1508  $props = false,
1509  $timestamp = false,
1510  $tags = [],
1511  bool $createNullRevision = true,
1512  bool $revert = false
1513  ) : Status {
1514  $dbw = $this->repo->getMasterDB();
1515 
1516  # Imports or such might force a certain timestamp; otherwise we generate
1517  # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1518  if ( $timestamp === false ) {
1519  $timestamp = $dbw->timestamp();
1520  $allowTimeKludge = true;
1521  } else {
1522  $allowTimeKludge = false;
1523  }
1524 
1525  $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1526  $props['description'] = $comment;
1527  $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1528  $this->setProps( $props );
1529 
1530  # Fail now if the file isn't there
1531  if ( !$this->fileExists ) {
1532  wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1533 
1534  return Status::newFatal( 'filenotfound', $this->getRel() );
1535  }
1536 
1537  $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1538 
1539  $dbw->startAtomic( __METHOD__ );
1540 
1541  $actorId = $actorNormalizaton->acquireActorId( $user );
1542  $this->user = $user;
1543 
1544  # Test to see if the row exists using INSERT IGNORE
1545  # This avoids race conditions by locking the row until the commit, and also
1546  # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1547  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1548  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1549  $actorFields = [ 'img_actor' => $actorId ];
1550  $dbw->insert( 'image',
1551  [
1552  'img_name' => $this->getName(),
1553  'img_size' => $this->size,
1554  'img_width' => intval( $this->width ),
1555  'img_height' => intval( $this->height ),
1556  'img_bits' => $this->bits,
1557  'img_media_type' => $this->media_type,
1558  'img_major_mime' => $this->major_mime,
1559  'img_minor_mime' => $this->minor_mime,
1560  'img_timestamp' => $timestamp,
1561  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1562  'img_sha1' => $this->sha1
1563  ] + $commentFields + $actorFields,
1564  __METHOD__,
1565  [ 'IGNORE' ]
1566  );
1567  $reupload = ( $dbw->affectedRows() == 0 );
1568 
1569  if ( $reupload ) {
1570  $row = $dbw->selectRow(
1571  'image',
1572  [ 'img_timestamp', 'img_sha1' ],
1573  [ 'img_name' => $this->getName() ],
1574  __METHOD__,
1575  [ 'LOCK IN SHARE MODE' ]
1576  );
1577 
1578  if ( $row && $row->img_sha1 === $this->sha1 ) {
1579  $dbw->endAtomic( __METHOD__ );
1580  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1581  $title = Title::newFromText( $this->getName(), NS_FILE );
1582  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1583  }
1584 
1585  if ( $allowTimeKludge ) {
1586  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1587  $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1588  # Avoid a timestamp that is not newer than the last version
1589  # TODO: the image/oldimage tables should be like page/revision with an ID field
1590  if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1591  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1592  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1593  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1594  }
1595  }
1596 
1597  $tables = [ 'image' ];
1598  $fields = [
1599  'oi_name' => 'img_name',
1600  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1601  'oi_size' => 'img_size',
1602  'oi_width' => 'img_width',
1603  'oi_height' => 'img_height',
1604  'oi_bits' => 'img_bits',
1605  'oi_description_id' => 'img_description_id',
1606  'oi_timestamp' => 'img_timestamp',
1607  'oi_metadata' => 'img_metadata',
1608  'oi_media_type' => 'img_media_type',
1609  'oi_major_mime' => 'img_major_mime',
1610  'oi_minor_mime' => 'img_minor_mime',
1611  'oi_sha1' => 'img_sha1',
1612  'oi_actor' => 'img_actor',
1613  ];
1614  $joins = [];
1615 
1616  # (T36993) Note: $oldver can be empty here, if the previous
1617  # version of the file was broken. Allow registration of the new
1618  # version to continue anyway, because that's better than having
1619  # an image that's not fixable by user operations.
1620  # Collision, this is an update of a file
1621  # Insert previous contents into oldimage
1622  $dbw->insertSelect( 'oldimage', $tables, $fields,
1623  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1624 
1625  # Update the current image row
1626  $dbw->update( 'image',
1627  [
1628  'img_size' => $this->size,
1629  'img_width' => intval( $this->width ),
1630  'img_height' => intval( $this->height ),
1631  'img_bits' => $this->bits,
1632  'img_media_type' => $this->media_type,
1633  'img_major_mime' => $this->major_mime,
1634  'img_minor_mime' => $this->minor_mime,
1635  'img_timestamp' => $timestamp,
1636  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1637  'img_sha1' => $this->sha1
1638  ] + $commentFields + $actorFields,
1639  [ 'img_name' => $this->getName() ],
1640  __METHOD__
1641  );
1642  }
1643 
1644  $descTitle = $this->getTitle();
1645  $descId = $descTitle->getArticleID();
1646  $wikiPage = new WikiFilePage( $descTitle );
1647  $wikiPage->setFile( $this );
1648 
1649  // Determine log action. If reupload is done by reverting, use a special log_action.
1650  if ( $revert === true ) {
1651  $logAction = 'revert';
1652  } elseif ( $reupload === true ) {
1653  $logAction = 'overwrite';
1654  } else {
1655  $logAction = 'upload';
1656  }
1657  // Add the log entry...
1658  $logEntry = new ManualLogEntry( 'upload', $logAction );
1659  $logEntry->setTimestamp( $this->timestamp );
1660  $logEntry->setPerformer( $user );
1661  $logEntry->setComment( $comment );
1662  $logEntry->setTarget( $descTitle );
1663  // Allow people using the api to associate log entries with the upload.
1664  // Log has a timestamp, but sometimes different from upload timestamp.
1665  $logEntry->setParameters(
1666  [
1667  'img_sha1' => $this->sha1,
1668  'img_timestamp' => $timestamp,
1669  ]
1670  );
1671  // Note we keep $logId around since during new image
1672  // creation, page doesn't exist yet, so log_page = 0
1673  // but we want it to point to the page we're making,
1674  // so we later modify the log entry.
1675  // For a similar reason, we avoid making an RC entry
1676  // now and wait until the page exists.
1677  $logId = $logEntry->insert();
1678 
1679  if ( $descTitle->exists() ) {
1680  if ( $createNullRevision !== false ) {
1681  $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1682  // Use own context to get the action text in content language
1683  $formatter = LogFormatter::newFromEntry( $logEntry );
1684  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1685  $editSummary = $formatter->getPlainActionText();
1686  $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1687  $nullRevRecord = $revStore->newNullRevision(
1688  $dbw,
1689  $descTitle,
1690  $summary,
1691  false,
1692  $user
1693  );
1694 
1695  if ( $nullRevRecord ) {
1696  $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1697 
1698  $this->getHookRunner()->onRevisionFromEditComplete(
1699  $wikiPage,
1700  $inserted,
1701  $inserted->getParentId(),
1702  $user,
1703  $tags
1704  );
1705 
1706  // Hook is hard deprecated since 1.35
1707  if ( $this->getHookContainer()->isRegistered( 'NewRevisionFromEditComplete' ) ) {
1708  // Only create the Revision object if needed
1709  $nullRevision = new Revision( $inserted );
1710  $this->getHookRunner()->onNewRevisionFromEditComplete(
1711  $wikiPage,
1712  $nullRevision,
1713  $inserted->getParentId(),
1714  $user,
1715  $tags
1716  );
1717  }
1718 
1719  $wikiPage->updateRevisionOn( $dbw, $inserted );
1720  // Associate null revision id
1721  $logEntry->setAssociatedRevId( $inserted->getId() );
1722  }
1723  }
1724 
1725  $newPageContent = null;
1726  } else {
1727  // Make the description page and RC log entry post-commit
1728  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1729  }
1730 
1731  # Defer purges, page creation, and link updates in case they error out.
1732  # The most important thing is that files and the DB registry stay synced.
1733  $dbw->endAtomic( __METHOD__ );
1734  $fname = __METHOD__;
1735 
1736  # Do some cache purges after final commit so that:
1737  # a) Changes are more likely to be seen post-purge
1738  # b) They won't cause rollback of the log publish/update above
1740  new AutoCommitUpdate(
1741  $dbw,
1742  __METHOD__,
1744  function () use (
1745  $reupload, $wikiPage, $newPageContent, $comment, $user,
1746  $logEntry, $logId, $descId, $tags, $fname
1747  ) {
1748  # Update memcache after the commit
1749  $this->invalidateCache();
1750 
1751  $updateLogPage = false;
1752  if ( $newPageContent ) {
1753  # New file page; create the description page.
1754  # There's already a log entry, so don't make a second RC entry
1755  # CDN and file cache for the description page are purged by doEditContent.
1756  $status = $wikiPage->doEditContent(
1757  $newPageContent,
1758  $comment,
1760  false,
1761  $user
1762  );
1763 
1764  if ( isset( $status->value['revision-record'] ) ) {
1766  $revRecord = $status->value['revision-record'];
1767  // Associate new page revision id
1768  $logEntry->setAssociatedRevId( $revRecord->getId() );
1769  }
1770  // This relies on the resetArticleID() call in WikiPage::insertOn(),
1771  // which is triggered on $descTitle by doEditContent() above.
1772  if ( isset( $status->value['revision-record'] ) ) {
1774  $revRecord = $status->value['revision-record'];
1775  $updateLogPage = $revRecord->getPageId();
1776  }
1777  } else {
1778  # Existing file page: invalidate description page cache
1779  $title = $wikiPage->getTitle();
1781  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1782  $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1783  # Allow the new file version to be patrolled from the page footer
1785  }
1786 
1787  # Update associated rev id. This should be done by $logEntry->insert() earlier,
1788  # but setAssociatedRevId() wasn't called at that point yet...
1789  $logParams = $logEntry->getParameters();
1790  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1791  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1792  if ( $updateLogPage ) {
1793  # Also log page, in case where we just created it above
1794  $update['log_page'] = $updateLogPage;
1795  }
1796  $this->getRepo()->getMasterDB()->update(
1797  'logging',
1798  $update,
1799  [ 'log_id' => $logId ],
1800  $fname
1801  );
1802  $this->getRepo()->getMasterDB()->insert(
1803  'log_search',
1804  [
1805  'ls_field' => 'associated_rev_id',
1806  'ls_value' => (string)$logEntry->getAssociatedRevId(),
1807  'ls_log_id' => $logId,
1808  ],
1809  $fname
1810  );
1811 
1812  # Add change tags, if any
1813  if ( $tags ) {
1814  $logEntry->addTags( $tags );
1815  }
1816 
1817  # Uploads can be patrolled
1818  $logEntry->setIsPatrollable( true );
1819 
1820  # Now that the log entry is up-to-date, make an RC entry.
1821  $logEntry->publish( $logId );
1822 
1823  # Run hook for other updates (typically more cache purging)
1824  $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
1825 
1826  if ( $reupload ) {
1827  # Delete old thumbnails
1828  $this->purgeThumbnails();
1829  # Remove the old file from the CDN cache
1830  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1831  $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1832  } else {
1833  # Update backlink pages pointing to this title if created
1835  $this->getTitle(),
1836  'imagelinks',
1837  'upload-image',
1838  $user->getName()
1839  );
1840  }
1841 
1842  $this->prerenderThumbnails();
1843  }
1844  ),
1845  DeferredUpdates::PRESEND
1846  );
1847 
1848  if ( !$reupload ) {
1849  # This is a new file, so update the image count
1850  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1851  }
1852 
1853  # Invalidate cache for all pages using this file
1855  $this->getTitle(),
1856  'imagelinks',
1857  [ 'causeAction' => 'file-upload', 'causeAgent' => $user->getName() ]
1858  );
1859  JobQueueGroup::singleton()->lazyPush( $job );
1860 
1861  return Status::newGood();
1862  }
1863 
1880  public function publish( $src, $flags = 0, array $options = [] ) {
1881  return $this->publishTo( $src, $this->getRel(), $flags, $options );
1882  }
1883 
1900  protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1901  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1902 
1903  $repo = $this->getRepo();
1904  if ( $repo->getReadOnlyReason() !== false ) {
1905  return $this->readOnlyFatalStatus();
1906  }
1907 
1908  $this->lock();
1909 
1910  if ( $this->isOld() ) {
1911  $archiveRel = $dstRel;
1912  $archiveName = basename( $archiveRel );
1913  } else {
1914  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1915  $archiveRel = $this->getArchiveRel( $archiveName );
1916  }
1917 
1918  if ( $repo->hasSha1Storage() ) {
1919  $sha1 = FileRepo::isVirtualUrl( $srcPath )
1920  ? $repo->getFileSha1( $srcPath )
1921  : FSFile::getSha1Base36FromPath( $srcPath );
1923  $wrapperBackend = $repo->getBackend();
1924  '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
1925  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1926  $status = $repo->quickImport( $src, $dst );
1927  if ( $flags & File::DELETE_SOURCE ) {
1928  unlink( $srcPath );
1929  }
1930 
1931  if ( $this->exists() ) {
1932  $status->value = $archiveName;
1933  }
1934  } else {
1935  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1936  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1937 
1938  if ( $status->value == 'new' ) {
1939  $status->value = '';
1940  } else {
1941  $status->value = $archiveName;
1942  }
1943  }
1944 
1945  $this->unlock();
1946  return $status;
1947  }
1948 
1967  public function move( $target ) {
1968  $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
1969  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1970  return $this->readOnlyFatalStatus();
1971  }
1972 
1973  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1974  $batch = new LocalFileMoveBatch( $this, $target );
1975 
1976  $this->lock();
1977  $batch->addCurrent();
1978  $archiveNames = $batch->addOlds();
1979  $status = $batch->execute();
1980  $this->unlock();
1981 
1982  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1983 
1984  // Purge the source and target files outside the transaction...
1985  $oldTitleFile = $localRepo->newFile( $this->title );
1986  $newTitleFile = $localRepo->newFile( $target );
1988  new AutoCommitUpdate(
1989  $this->getRepo()->getMasterDB(),
1990  __METHOD__,
1991  static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1992  $oldTitleFile->purgeEverything();
1993  foreach ( $archiveNames as $archiveName ) {
1995  '@phan-var OldLocalFile $oldTitleFile';
1996  $oldTitleFile->purgeOldThumbnails( $archiveName );
1997  }
1998  $newTitleFile->purgeEverything();
1999  }
2000  ),
2001  DeferredUpdates::PRESEND
2002  );
2003 
2004  if ( $status->isOK() ) {
2005  // Now switch the object
2006  $this->title = $target;
2007  // Force regeneration of the name and hashpath
2008  $this->name = null;
2009  $this->hashPath = null;
2010  }
2011 
2012  return $status;
2013  }
2014 
2031  public function deleteFile( $reason, User $user, $suppress = false ) {
2032  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2033  return $this->readOnlyFatalStatus();
2034  }
2035 
2036  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2037 
2038  $this->lock();
2039  $batch->addCurrent();
2040  // Get old version relative paths
2041  $archiveNames = $batch->addOlds();
2042  $status = $batch->execute();
2043  $this->unlock();
2044 
2045  if ( $status->isOK() ) {
2046  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2047  }
2048 
2049  // To avoid slow purges in the transaction, move them outside...
2051  new AutoCommitUpdate(
2052  $this->getRepo()->getMasterDB(),
2053  __METHOD__,
2054  function () use ( $archiveNames ) {
2055  $this->purgeEverything();
2056  foreach ( $archiveNames as $archiveName ) {
2057  $this->purgeOldThumbnails( $archiveName );
2058  }
2059  }
2060  ),
2061  DeferredUpdates::PRESEND
2062  );
2063 
2064  // Purge the CDN
2065  $purgeUrls = [];
2066  foreach ( $archiveNames as $archiveName ) {
2067  $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2068  }
2069 
2070  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2071  $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2072 
2073  return $status;
2074  }
2075 
2094  public function deleteOldFile( $archiveName, $reason, User $user, $suppress = false ) {
2095  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2096  return $this->readOnlyFatalStatus();
2097  }
2098 
2099  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2100 
2101  $this->lock();
2102  $batch->addOld( $archiveName );
2103  $status = $batch->execute();
2104  $this->unlock();
2105 
2106  $this->purgeOldThumbnails( $archiveName );
2107  if ( $status->isOK() ) {
2108  $this->purgeDescription();
2109  }
2110 
2111  $url = $this->getArchiveUrl( $archiveName );
2112  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2113  $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2114 
2115  return $status;
2116  }
2117 
2130  public function restore( $versions = [], $unsuppress = false ) {
2131  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2132  return $this->readOnlyFatalStatus();
2133  }
2134 
2135  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2136 
2137  $this->lock();
2138  if ( !$versions ) {
2139  $batch->addAll();
2140  } else {
2141  $batch->addIds( $versions );
2142  }
2143  $status = $batch->execute();
2144  if ( $status->isGood() ) {
2145  $cleanupStatus = $batch->cleanup();
2146  $cleanupStatus->successCount = 0;
2147  $cleanupStatus->failCount = 0;
2148  $status->merge( $cleanupStatus );
2149  }
2150 
2151  $this->unlock();
2152  return $status;
2153  }
2154 
2165  public function getDescriptionUrl() {
2166  if ( !$this->title ) {
2167  return false; // Avoid hard failure when the file does not exist. T221812
2168  }
2169 
2170  return $this->title->getLocalURL();
2171  }
2172 
2182  public function getDescriptionText( Language $lang = null ) {
2183  if ( !$this->title ) {
2184  return false; // Avoid hard failure when the file does not exist. T221812
2185  }
2186 
2187  $store = MediaWikiServices::getInstance()->getRevisionStore();
2188  $revision = $store->getRevisionByTitle( $this->title, 0, RevisionStore::READ_NORMAL );
2189  if ( !$revision ) {
2190  return false;
2191  }
2192 
2193  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2194  $rendered = $renderer->getRenderedRevision(
2195  $revision,
2198  $lang
2199  )
2200  );
2201 
2202  if ( !$rendered ) {
2203  // audience check failed
2204  return false;
2205  }
2206 
2207  $pout = $rendered->getRevisionParserOutput();
2208  return $pout->getText();
2209  }
2210 
2217  public function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2218  $this->load();
2219  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2220  return '';
2221  } elseif ( $audience == self::FOR_THIS_USER
2222  && !$this->userCan( self::DELETED_COMMENT, $user )
2223  ) {
2224  return '';
2225  } else {
2226  return $this->description;
2227  }
2228  }
2229 
2234  public function getTimestamp() {
2235  $this->load();
2236 
2237  return $this->timestamp;
2238  }
2239 
2244  public function getDescriptionTouched() {
2245  if ( !$this->exists() ) {
2246  return false; // Avoid hard failure when the file does not exist. T221812
2247  }
2248 
2249  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2250  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2251  // need to differentiate between null (uninitialized) and false (failed to load).
2252  if ( $this->descriptionTouched === null ) {
2253  $cond = [
2254  'page_namespace' => $this->title->getNamespace(),
2255  'page_title' => $this->title->getDBkey()
2256  ];
2257  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2258  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2259  }
2260 
2262  }
2263 
2268  public function getSha1() {
2269  $this->load();
2270  // Initialise now if necessary
2271  if ( $this->sha1 == '' && $this->fileExists ) {
2272  $this->lock();
2273 
2274  $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2275  if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2276  $dbw = $this->repo->getMasterDB();
2277  $dbw->update( 'image',
2278  [ 'img_sha1' => $this->sha1 ],
2279  [ 'img_name' => $this->getName() ],
2280  __METHOD__ );
2281  $this->invalidateCache();
2282  }
2283 
2284  $this->unlock();
2285  }
2286 
2287  return $this->sha1;
2288  }
2289 
2293  public function isCacheable() {
2294  $this->load();
2295 
2296  // If extra data (metadata) was not loaded then it must have been large
2297  return $this->extraDataLoaded
2298  && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
2299  }
2300 
2305  public function acquireFileLock() {
2306  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2307  [ $this->getPath() ], LockManager::LOCK_EX, 10
2308  ) );
2309  }
2310 
2315  public function releaseFileLock() {
2316  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2317  [ $this->getPath() ], LockManager::LOCK_EX
2318  ) );
2319  }
2320 
2330  public function lock() {
2331  if ( !$this->locked ) {
2332  $logger = LoggerFactory::getInstance( 'LocalFile' );
2333 
2334  $dbw = $this->repo->getMasterDB();
2335  $makesTransaction = !$dbw->trxLevel();
2336  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2337  // T56736: use simple lock to handle when the file does not exist.
2338  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2339  // Also, that would cause contention on INSERT of similarly named rows.
2340  $status = $this->acquireFileLock(); // represents all versions of the file
2341  if ( !$status->isGood() ) {
2342  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2343  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2344 
2345  throw new LocalFileLockError( $status );
2346  }
2347  // Release the lock *after* commit to avoid row-level contention.
2348  // Make sure it triggers on rollback() as well as commit() (T132921).
2349  $dbw->onTransactionResolution(
2350  function () use ( $logger ) {
2351  $status = $this->releaseFileLock();
2352  if ( !$status->isGood() ) {
2353  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2354  }
2355  },
2356  __METHOD__
2357  );
2358  // Callers might care if the SELECT snapshot is safely fresh
2359  $this->lockedOwnTrx = $makesTransaction;
2360  }
2361 
2362  $this->locked++;
2363 
2364  return $this->lockedOwnTrx;
2365  }
2366 
2375  public function unlock() {
2376  if ( $this->locked ) {
2377  --$this->locked;
2378  if ( !$this->locked ) {
2379  $dbw = $this->repo->getMasterDB();
2380  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2381  $this->lockedOwnTrx = false;
2382  }
2383  }
2384  }
2385 
2389  protected function readOnlyFatalStatus() {
2390  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2391  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2392  }
2393 
2397  public function __destruct() {
2398  $this->unlock();
2399  }
2400 }
LocalFile\$media_type
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition: LocalFile.php:77
LocalFile\getSha1
getSha1()
Stable to override.
Definition: LocalFile.php:2268
LocalFile\ATOMIC_SECTION_LOCK
const ATOMIC_SECTION_LOCK
Definition: LocalFile.php:145
LocalFile\$fileExists
bool $fileExists
Does the file exist on disk? (loadFromXxx)
Definition: LocalFile.php:65
File\getPath
getPath()
Return the storage path to the file.
Definition: File.php:441
$wgUpdateCompatibleMetadata
$wgUpdateCompatibleMetadata
If to automatically update the img_metadata field if the metadata field is outdated but compatible wi...
Definition: DefaultSettings.php:932
LocalFile\maybeUpgradeRow
maybeUpgradeRow()
Upgrade a row if it needs it.
Definition: LocalFile.php:664
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:50
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:302
FileRepo\getReadOnlyReason
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition: FileRepo.php:257
LocalFile\unprefixRow
unprefixRow( $row, $prefix='img_')
Definition: LocalFile.php:556
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:364
File\$repo
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition: File.php:110
LocalFile\$width
int $width
Image width.
Definition: LocalFile.php:68
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:1728
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:47
LocalFile\deleteFile
deleteFile( $reason, User $user, $suppress=false)
Delete all versions of the file.
Definition: LocalFile.php:2031
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:267
LocalFile\unlock
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
Definition: LocalFile.php:2375
LocalFile\getTimestamp
getTimestamp()
Stable to override.
Definition: LocalFile.php:2234
File\userCan
userCan( $field, User $user)
Determine if the current user is allowed to view a particular field of this file, if it's marked as d...
Definition: File.php:2282
File\isMultipage
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition: File.php:2083
LocalFile\getUser
getUser( $type='text')
Returns user who uploaded the file @stable to override.
Definition: LocalFile.php:893
LocalFile\getRepo
getRepo()
Definition: LocalFile.php:283
LocalFile\loadFromDB
loadFromDB( $flags=0)
Load file metadata from the DB Stable to override.
Definition: LocalFile.php:445
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:172
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
LocalFile\purgeThumbList
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls Stable to override.
Definition: LocalFile.php:1184
File\getRel
getRel()
Get the path of the file relative to the public zone root.
Definition: File.php:1641
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:130
Revision\RevisionStore
Service for looking up page revisions.
Definition: RevisionStore.php:84
LocalFile\$missing
bool $missing
True if file is not present in file system.
Definition: LocalFile.php:140
LocalFileDeleteBatch
Helper class for file deletion.
Definition: LocalFileDeleteBatch.php:31
MediaHandler\filterThumbnailPurgeList
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
Definition: MediaHandler.php:810
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1832
FileBackendError
File backend exception for checked exceptions (e.g.
Definition: FileBackendError.php:10
LocalFile\upload
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, $user=null, $tags=[], $createNullRevision=true, $revert=false)
getHashPath inherited
Definition: LocalFile.php:1373
LocalFile\$upgraded
bool $upgraded
Whether the row was upgraded on load.
Definition: LocalFile.php:128
LocalFile\getDescriptionShortUrl
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
Definition: LocalFile.php:926
LocalFile\getCacheFields
getCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache.
Definition: LocalFile.php:407
Title\getPrefixedText
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1887
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
LocalFile\getHistory
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
Definition: LocalFile.php:1225
LocalFile\getMediaType
getMediaType()
Returns the type of the media in the file.
Definition: LocalFile.php:990
File\getUrl
getUrl()
Return the URL of the file Stable to override.
Definition: File.php:368
LocalFile\$dataLoaded
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
Definition: LocalFile.php:92
$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:2389
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:161
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1135
User\newFromName
static newFromName( $name, $validate='valid')
Definition: User.php:584
RequestContext\newExtraneousContext
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
Definition: RequestContext.php:646
LocalFile\$upgrading
bool $upgrading
Whether the row was scheduled to upgrade on load.
Definition: LocalFile.php:131
LocalFile\getSize
getSize()
Returns the size of the image file, in bytes @stable to override.
Definition: LocalFile.php:967
LocalFile\purgeOldThumbnails
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
Definition: LocalFile.php:1089
LocalFile\getThumbnails
getThumbnails( $archiveName=false)
getTransformScript inherited
Definition: LocalFile.php:1029
LocalFile\$sha1
string $sha1
SHA-1 base 36 content hash.
Definition: LocalFile.php:89
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:290
$res
$res
Definition: testCompression.php:57
serialize
serialize()
Definition: ApiMessageTrait.php:138
LocalFile\$minor_mime
string $minor_mime
Minor MIME type.
Definition: LocalFile.php:113
File\getArchiveRel
getArchiveRel( $suffix=false)
Get the path of an archived file relative to the public zone root Stable to override.
Definition: File.php:1653
File\isDeleted
isDeleted( $field)
Is this file a "deleted" file in a private archive? STUB.
Definition: File.php:1993
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:996
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:157
HTMLCacheUpdateJob\newForBacklinks
static newForBacklinks(Title $title, $table, $params=[])
Definition: HTMLCacheUpdateJob.php:59
LocalFile\acquireFileLock
acquireFileLock()
Definition: LocalFile.php:2305
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:2293
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:1260
Status
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:44
Revision
Definition: Revision.php:40
LocalFile\decodeRow
decodeRow( $row, $prefix='img_')
Decode a row from the database (either object or array) to an array with timestamps and MIME types de...
Definition: LocalFile.php:581
LocalFile\$bits
int $bits
Returned by getimagesize (loadFromXxx)
Definition: LocalFile.php:74
LocalFile\purgeThumbnails
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
Definition: LocalFile.php:1116
FileRepo\hasSha1Storage
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:2011
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:63
LocalFile\loadExtraFromDB
loadExtraFromDB()
Load lazy file metadata from the DB.
Definition: LocalFile.php:478
LocalFile\publishTo
publishTo( $src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
Definition: LocalFile.php:1900
File\$url
string $url
The URL corresponding to one of the four basic zones.
Definition: File.php:131
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:176
LocalFile\getDescriptionTouched
getDescriptionTouched()
Stable to override.
Definition: LocalFile.php:2244
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1034
LocalFile\purgeMetadataCache
purgeMetadataCache()
Refresh metadata in memcached, but don't touch thumbnails or CDN.
Definition: LocalFile.php:1054
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 Stable to overr...
Definition: File.php:1742
Wikimedia\Rdbms\IResultWrapper
Result wrapper for grabbing data queried from an IDatabase object.
Definition: IResultWrapper.php:24
ParserOptions\newFromUserAndLang
static newFromUserAndLang(User $user, Language $lang)
Get a ParserOptions object from a given user and language.
Definition: ParserOptions.php:1099
FileRepo\quickImport
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:1050
LocalFile\getUpgraded
getUpgraded()
Definition: LocalFile.php:703
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1528
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:62
LocalFile\loadFromRow
loadFromRow( $row, $prefix='img_')
Load file metadata from a DB result row Stable to override.
Definition: LocalFile.php:628
LocalFile\__destruct
__destruct()
Clean up any dangling locks.
Definition: LocalFile.php:2397
LocalFile\$deleted
int $deleted
Bitfield akin to rev_deleted.
Definition: LocalFile.php:98
$wgUploadThumbnailRenderMap
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
Definition: DefaultSettings.php:1658
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:107
EDIT_NEW
const EDIT_NEW
Definition: Defines.php:136
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:2182
SiteStatsUpdate\factory
static factory(array $deltas)
Definition: SiteStatsUpdate.php:71
MWFileProps
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
LocalFile\prerenderThumbnails
prerenderThumbnails()
Prerenders a configurable set of thumbnails Stable to override.
Definition: LocalFile.php:1156
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:627
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:293
MediaHandler\getPageDimensions
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
Definition: MediaHandler.php:447
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:682
$revStore
$revStore
Definition: testCompression.php:55
LocalFile\$mime
string $mime
MIME type, determined by MimeAnalyzer::guessMimeType.
Definition: LocalFile.php:80
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:915
LocalFile\setProps
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info.
Definition: LocalFile.php:767
FileRepo\getFileSha1
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1672
LocalFile
Class to represent a local file in the wiki's own database.
Definition: LocalFile.php:59
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:142
LocalFile\getMimeType
getMimeType()
Returns the MIME type of the file.
Definition: LocalFile.php:978
LocalFile\getDescription
getDescription( $audience=self::FOR_PUBLIC, User $user=null)
Stable to override.
Definition: LocalFile.php:2217
LocalFile\$extraDataLoaded
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
Definition: LocalFile.php:95
ThumbnailRenderJob
Job for asynchronous rendering of thumbnails.
Definition: ThumbnailRenderJob.php:31
LocalFile\$size
int $size
Size in bytes (loadFromXxx)
Definition: LocalFile.php:83
File\purgeDescription
purgeDescription()
Purge the file description page, but don't go after pages using the file.
Definition: File.php:1549
LocalFile\LOAD_ALL
const LOAD_ALL
Definition: LocalFile.php:143
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:2330
File\isOld
isOld()
Returns true if the image is an old version STUB.
Definition: File.php:1981
File\$handler
MediaHandler $handler
Definition: File.php:128
LocalFileLockError
@newable Stable to extend
Definition: LocalFileLockError.php:28
File\assertTitleDefined
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition: File.php:2406
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:104
LocalFile\releaseFileLock
releaseFileLock()
Definition: LocalFile.php:2315
LocalFile\upgradeRow
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file Stable to over...
Definition: LocalFile.php:711
LocalFile\load
load( $flags=0)
Load file metadata from cache or DB, unless already loaded Stable to override.
Definition: LocalFile.php:646
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:125
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:195
LocalFile\nextHistoryLine
nextHistoryLine()
Returns the history of this file, line by line.
Definition: LocalFile.php:1284
File\$title
Title string bool $title
Definition: File.php:113
LocalFile\$metadata
string $metadata
Handler-specific metadata.
Definition: LocalFile.php:86
LocalFile\getBitDepth
getBitDepth()
@stable to override
Definition: LocalFile.php:956
LocalFile\$height
int $height
Image height.
Definition: LocalFile.php:71
LocalFile\$user
User $user
Uploader.
Definition: LocalFile.php:119
File\getArchiveThumbUrl
getArchiveThumbUrl( $archiveName, $suffix=false)
Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified Stable to ov...
Definition: File.php:1788
EDIT_SUPPRESS_RC
const EDIT_SUPPRESS_RC
Definition: Defines.php:139
File\getName
getName()
Return the name of this file.
Definition: File.php:315
File\getArchiveUrl
getArchiveUrl( $suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified Stable to override...
Definition: File.php:1767
FSFile
Class representing a non-directory file on the file system.
Definition: FSFile.php:32
LocalFile\$timestamp
string $timestamp
Upload timestamp.
Definition: LocalFile.php:116
FileRepo\getBackend
getBackend()
Get the file backend instance.
Definition: FileRepo.php:247
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:476
LocalFile\$descriptionTouched
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
Definition: LocalFile.php:125
File\DELETE_SOURCE
const DELETE_SOURCE
Definition: File.php:80
LocalFile\$locked
bool $locked
True if the image row is locked.
Definition: LocalFile.php:134
LocalFile\$description
string $description
Description of current revision of the file.
Definition: LocalFile.php:122
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:429
File\getTitle
getTitle()
Return the associated title object.
Definition: File.php:345
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:227
LocalFile\getMetadata
getMetadata()
Get handler-specific metadata @stable to override.
Definition: LocalFile.php:947
LocalFile\deleteOldFile
deleteOldFile( $archiveName, $reason, User $user, $suppress=false)
Delete an old version of the file.
Definition: LocalFile.php:2094
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:70
MediaHandler\getContentHeaders
getContentHeaders( $metadata)
Get useful response headers for GET/HEAD requests for a file with the given metadata Stable to overri...
Definition: MediaHandler.php:1046
$cache
$cache
Definition: mcc.php:33
LocalFile\loadFromFile
loadFromFile()
Load metadata from the file itself.
Definition: LocalFile.php:395
File\assertRepoDefined
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition: File.php:2396
LocalFile\recordUpload3
recordUpload3(string $oldver, string $comment, string $pageText, User $user, $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:1503
LocalFile\recordUpload2
recordUpload2( $oldver, $comment, $pageText, $props=false, $timestamp=false, $user=null, $tags=[], $createNullRevision=true, $revert=false)
Record a file upload in the upload log and the image table.
Definition: LocalFile.php:1471
$job
if(count( $args)< 1) $job
Definition: recompressTracked.php:50
LocalFile\resetHistory
resetHistory()
Reset the history pointer to the first element of the history Stable to override.
Definition: LocalFile.php:1332
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
LinksUpdate\queueRecursiveJobsForTable
static queueRecursiveJobsForTable(Title $title, $table, $action='unknown', $userName='unknown')
Queue a RefreshLinks job for any table.
Definition: LinksUpdate.php:369
FileRepo\isVirtualUrl
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:286
LocalFile\loadExtraFieldsWithTimestamp
loadExtraFieldsWithTimestamp( $dbr, $fname)
Definition: LocalFile.php:507
LocalFileMoveBatch
Helper class for file movement.
Definition: LocalFileMoveBatch.php:33
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:42
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:137
LocalFile\publish
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
Definition: LocalFile.php:1880
Title\invalidateCache
invalidateCache( $purgeTime=null)
Updates page_touched for this page; called from LinksUpdate.php.
Definition: Title.php:4192
LocalFile\getWidth
getWidth( $page=1)
Return the width of the image @stable to override.
Definition: LocalFile.php:826
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 Stable to overri...
Definition: File.php:1825
LocalFile\$major_mime
string $major_mime
Major MIME type.
Definition: LocalFile.php:110
File\isVectorized
isVectorized()
Return true if the file is vectorized.
Definition: File.php:623
File\getHandler
getHandler()
Get a MediaHandler instance for this file.
Definition: File.php:1483
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:859
LocalFile\isMissing
isMissing()
splitMime inherited
Definition: LocalFile.php:810
LocalFile\invalidateCache
invalidateCache()
Purge the file object/metadata cache.
Definition: LocalFile.php:378
LocalFile\$lockedOwnTrx
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
Definition: LocalFile.php:137
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:66
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:60
LocalFile\getDescriptionUrl
getDescriptionUrl()
isMultipage inherited
Definition: LocalFile.php:2165
LocalFile\move
move( $target)
getLinksTo inherited
Definition: LocalFile.php:1967
LocalFile\$repoClass
string $repoClass
Definition: LocalFile.php:101
MediaHandler\isMetadataValid
isMetadataValid( $image, $metadata)
Check if the metadata string is valid for this handler.
Definition: MediaHandler.php:212
User\getName
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2107
LocalFile\restore
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition: LocalFile.php:2130
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:1562
LocalFile\exists
exists()
canRender inherited
Definition: LocalFile.php:1007
File\getThumbnails
getThumbnails()
Get all thumbnail names previously generated for this file STUB Overridden by LocalFile Stable to ove...
Definition: File.php:1529
LocalFile\loadFromCache
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
Definition: LocalFile.php:309
LocalFile\purgeCache
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
Definition: LocalFile.php:1066
File\getVirtualUrl
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file Stable to override.
Definition: File.php:1846
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:1344
$type
$type
Definition: testCompression.php:52