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  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  $uploadStatus = $this->recordUpload2(
1426  $oldver,
1427  $comment,
1428  $pageText,
1429  $props,
1430  $timestamp,
1431  $user,
1432  $tags,
1433  $createNullRevision,
1434  $revert
1435  );
1436  if ( !$uploadStatus->isOK() ) {
1437  if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1438  // update filenotfound error with more specific path
1439  $status->fatal( 'filenotfound', $srcPath );
1440  } else {
1441  $status->merge( $uploadStatus );
1442  }
1443  }
1444  }
1445 
1446  $this->unlock();
1447  return $status;
1448  }
1449 
1463  public function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1464  $watch = false, $timestamp = false, User $user = null ) {
1465  wfDeprecated( __METHOD__, '1.35' );
1466  if ( !$user ) {
1467  global $wgUser;
1468  $user = $wgUser;
1469  }
1470 
1471  $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1472 
1473  if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1474  return false;
1475  }
1476 
1477  if ( $watch ) {
1478  $user->addWatch( $this->getTitle() );
1479  }
1480 
1481  return true;
1482  }
1483 
1499  public function recordUpload2(
1500  $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1501  $createNullRevision = true, $revert = false
1502  ) {
1503  // TODO check all callers and hard deprecate
1504  if ( $user === null ) {
1505  global $wgUser;
1506  $user = $wgUser;
1507  }
1508  return $this->recordUpload3(
1509  $oldver, $comment, $pageText,
1510  $user, $props, $timestamp, $tags,
1511  $createNullRevision, $revert
1512  );
1513  }
1514 
1531  public function recordUpload3(
1532  string $oldver,
1533  string $comment,
1534  string $pageText,
1535  User $user,
1536  $props = false,
1537  $timestamp = false,
1538  $tags = [],
1539  bool $createNullRevision = true,
1540  bool $revert = false
1541  ) : Status {
1542  $dbw = $this->repo->getMasterDB();
1543 
1544  # Imports or such might force a certain timestamp; otherwise we generate
1545  # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1546  if ( $timestamp === false ) {
1547  $timestamp = $dbw->timestamp();
1548  $allowTimeKludge = true;
1549  } else {
1550  $allowTimeKludge = false;
1551  }
1552 
1553  $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1554  $props['description'] = $comment;
1555  $props['user'] = $user->getId();
1556  $props['user_text'] = $user->getName();
1557  $props['actor'] = $user->getActorId( $dbw );
1558  $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1559  $this->setProps( $props );
1560 
1561  # Fail now if the file isn't there
1562  if ( !$this->fileExists ) {
1563  wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1564 
1565  return Status::newFatal( 'filenotfound', $this->getRel() );
1566  }
1567 
1568  $dbw->startAtomic( __METHOD__ );
1569 
1570  # Test to see if the row exists using INSERT IGNORE
1571  # This avoids race conditions by locking the row until the commit, and also
1572  # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1573  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1574  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1575  $actorMigration = ActorMigration::newMigration();
1576  $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1577  $dbw->insert( 'image',
1578  [
1579  'img_name' => $this->getName(),
1580  'img_size' => $this->size,
1581  'img_width' => intval( $this->width ),
1582  'img_height' => intval( $this->height ),
1583  'img_bits' => $this->bits,
1584  'img_media_type' => $this->media_type,
1585  'img_major_mime' => $this->major_mime,
1586  'img_minor_mime' => $this->minor_mime,
1587  'img_timestamp' => $timestamp,
1588  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1589  'img_sha1' => $this->sha1
1590  ] + $commentFields + $actorFields,
1591  __METHOD__,
1592  [ 'IGNORE' ]
1593  );
1594  $reupload = ( $dbw->affectedRows() == 0 );
1595 
1596  if ( $reupload ) {
1597  $row = $dbw->selectRow(
1598  'image',
1599  [ 'img_timestamp', 'img_sha1' ],
1600  [ 'img_name' => $this->getName() ],
1601  __METHOD__,
1602  [ 'LOCK IN SHARE MODE' ]
1603  );
1604 
1605  if ( $row && $row->img_sha1 === $this->sha1 ) {
1606  $dbw->endAtomic( __METHOD__ );
1607  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1608  $title = Title::newFromText( $this->getName(), NS_FILE );
1609  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1610  }
1611 
1612  if ( $allowTimeKludge ) {
1613  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1614  $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1615  # Avoid a timestamp that is not newer than the last version
1616  # TODO: the image/oldimage tables should be like page/revision with an ID field
1617  if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1618  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1619  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1620  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1621  }
1622  }
1623 
1624  $tables = [ 'image' ];
1625  $fields = [
1626  'oi_name' => 'img_name',
1627  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1628  'oi_size' => 'img_size',
1629  'oi_width' => 'img_width',
1630  'oi_height' => 'img_height',
1631  'oi_bits' => 'img_bits',
1632  'oi_description_id' => 'img_description_id',
1633  'oi_timestamp' => 'img_timestamp',
1634  'oi_metadata' => 'img_metadata',
1635  'oi_media_type' => 'img_media_type',
1636  'oi_major_mime' => 'img_major_mime',
1637  'oi_minor_mime' => 'img_minor_mime',
1638  'oi_sha1' => 'img_sha1',
1639  'oi_actor' => 'img_actor',
1640  ];
1641  $joins = [];
1642 
1643  # (T36993) Note: $oldver can be empty here, if the previous
1644  # version of the file was broken. Allow registration of the new
1645  # version to continue anyway, because that's better than having
1646  # an image that's not fixable by user operations.
1647  # Collision, this is an update of a file
1648  # Insert previous contents into oldimage
1649  $dbw->insertSelect( 'oldimage', $tables, $fields,
1650  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1651 
1652  # Update the current image row
1653  $dbw->update( 'image',
1654  [
1655  'img_size' => $this->size,
1656  'img_width' => intval( $this->width ),
1657  'img_height' => intval( $this->height ),
1658  'img_bits' => $this->bits,
1659  'img_media_type' => $this->media_type,
1660  'img_major_mime' => $this->major_mime,
1661  'img_minor_mime' => $this->minor_mime,
1662  'img_timestamp' => $timestamp,
1663  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1664  'img_sha1' => $this->sha1
1665  ] + $commentFields + $actorFields,
1666  [ 'img_name' => $this->getName() ],
1667  __METHOD__
1668  );
1669  }
1670 
1671  $descTitle = $this->getTitle();
1672  $descId = $descTitle->getArticleID();
1673  $wikiPage = new WikiFilePage( $descTitle );
1674  $wikiPage->setFile( $this );
1675 
1676  // Determine log action. If reupload is done by reverting, use a special log_action.
1677  if ( $revert === true ) {
1678  $logAction = 'revert';
1679  } elseif ( $reupload === true ) {
1680  $logAction = 'overwrite';
1681  } else {
1682  $logAction = 'upload';
1683  }
1684  // Add the log entry...
1685  $logEntry = new ManualLogEntry( 'upload', $logAction );
1686  $logEntry->setTimestamp( $this->timestamp );
1687  $logEntry->setPerformer( $user );
1688  $logEntry->setComment( $comment );
1689  $logEntry->setTarget( $descTitle );
1690  // Allow people using the api to associate log entries with the upload.
1691  // Log has a timestamp, but sometimes different from upload timestamp.
1692  $logEntry->setParameters(
1693  [
1694  'img_sha1' => $this->sha1,
1695  'img_timestamp' => $timestamp,
1696  ]
1697  );
1698  // Note we keep $logId around since during new image
1699  // creation, page doesn't exist yet, so log_page = 0
1700  // but we want it to point to the page we're making,
1701  // so we later modify the log entry.
1702  // For a similar reason, we avoid making an RC entry
1703  // now and wait until the page exists.
1704  $logId = $logEntry->insert();
1705 
1706  if ( $descTitle->exists() ) {
1707  if ( $createNullRevision !== false ) {
1708  $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1709  // Use own context to get the action text in content language
1710  $formatter = LogFormatter::newFromEntry( $logEntry );
1711  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1712  $editSummary = $formatter->getPlainActionText();
1713  $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1714  $nullRevRecord = $revStore->newNullRevision(
1715  $dbw,
1716  $descTitle,
1717  $summary,
1718  false,
1719  $user
1720  );
1721 
1722  if ( $nullRevRecord ) {
1723  $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1724 
1725  $this->getHookRunner()->onRevisionFromEditComplete(
1726  $wikiPage,
1727  $inserted,
1728  $inserted->getParentId(),
1729  $user,
1730  $tags
1731  );
1732 
1733  // Hook is hard deprecated since 1.35
1734  if ( $this->getHookContainer()->isRegistered( 'NewRevisionFromEditComplete' ) ) {
1735  // Only create the Revision object if needed
1736  $nullRevision = new Revision( $inserted );
1737  $this->getHookRunner()->onNewRevisionFromEditComplete(
1738  $wikiPage,
1739  $nullRevision,
1740  $inserted->getParentId(),
1741  $user,
1742  $tags
1743  );
1744  }
1745 
1746  $wikiPage->updateRevisionOn( $dbw, $inserted );
1747  // Associate null revision id
1748  $logEntry->setAssociatedRevId( $inserted->getId() );
1749  }
1750  }
1751 
1752  $newPageContent = null;
1753  } else {
1754  // Make the description page and RC log entry post-commit
1755  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1756  }
1757 
1758  # Defer purges, page creation, and link updates in case they error out.
1759  # The most important thing is that files and the DB registry stay synced.
1760  $dbw->endAtomic( __METHOD__ );
1761  $fname = __METHOD__;
1762 
1763  # Do some cache purges after final commit so that:
1764  # a) Changes are more likely to be seen post-purge
1765  # b) They won't cause rollback of the log publish/update above
1767  new AutoCommitUpdate(
1768  $dbw,
1769  __METHOD__,
1771  function () use (
1772  $reupload, $wikiPage, $newPageContent, $comment, $user,
1773  $logEntry, $logId, $descId, $tags, $fname
1774  ) {
1775  # Update memcache after the commit
1776  $this->invalidateCache();
1777 
1778  $updateLogPage = false;
1779  if ( $newPageContent ) {
1780  # New file page; create the description page.
1781  # There's already a log entry, so don't make a second RC entry
1782  # CDN and file cache for the description page are purged by doEditContent.
1783  $status = $wikiPage->doEditContent(
1784  $newPageContent,
1785  $comment,
1787  false,
1788  $user
1789  );
1790 
1791  if ( isset( $status->value['revision-record'] ) ) {
1793  $revRecord = $status->value['revision-record'];
1794  // Associate new page revision id
1795  $logEntry->setAssociatedRevId( $revRecord->getId() );
1796  }
1797  // This relies on the resetArticleID() call in WikiPage::insertOn(),
1798  // which is triggered on $descTitle by doEditContent() above.
1799  if ( isset( $status->value['revision-record'] ) ) {
1801  $revRecord = $status->value['revision-record'];
1802  $updateLogPage = $revRecord->getPageId();
1803  }
1804  } else {
1805  # Existing file page: invalidate description page cache
1806  $title = $wikiPage->getTitle();
1808  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1809  $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1810  # Allow the new file version to be patrolled from the page footer
1812  }
1813 
1814  # Update associated rev id. This should be done by $logEntry->insert() earlier,
1815  # but setAssociatedRevId() wasn't called at that point yet...
1816  $logParams = $logEntry->getParameters();
1817  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1818  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1819  if ( $updateLogPage ) {
1820  # Also log page, in case where we just created it above
1821  $update['log_page'] = $updateLogPage;
1822  }
1823  $this->getRepo()->getMasterDB()->update(
1824  'logging',
1825  $update,
1826  [ 'log_id' => $logId ],
1827  $fname
1828  );
1829  $this->getRepo()->getMasterDB()->insert(
1830  'log_search',
1831  [
1832  'ls_field' => 'associated_rev_id',
1833  'ls_value' => (string)$logEntry->getAssociatedRevId(),
1834  'ls_log_id' => $logId,
1835  ],
1836  $fname
1837  );
1838 
1839  # Add change tags, if any
1840  if ( $tags ) {
1841  $logEntry->addTags( $tags );
1842  }
1843 
1844  # Uploads can be patrolled
1845  $logEntry->setIsPatrollable( true );
1846 
1847  # Now that the log entry is up-to-date, make an RC entry.
1848  $logEntry->publish( $logId );
1849 
1850  # Run hook for other updates (typically more cache purging)
1851  $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
1852 
1853  if ( $reupload ) {
1854  # Delete old thumbnails
1855  $this->purgeThumbnails();
1856  # Remove the old file from the CDN cache
1857  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1858  $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1859  } else {
1860  # Update backlink pages pointing to this title if created
1862  $this->getTitle(),
1863  'imagelinks',
1864  'upload-image',
1865  $user->getName()
1866  );
1867  }
1868 
1869  $this->prerenderThumbnails();
1870  }
1871  ),
1873  );
1874 
1875  if ( !$reupload ) {
1876  # This is a new file, so update the image count
1877  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1878  }
1879 
1880  # Invalidate cache for all pages using this file
1882  $this->getTitle(),
1883  'imagelinks',
1884  [ 'causeAction' => 'file-upload', 'causeAgent' => $user->getName() ]
1885  );
1886  JobQueueGroup::singleton()->lazyPush( $job );
1887 
1888  return Status::newGood();
1889  }
1890 
1907  public function publish( $src, $flags = 0, array $options = [] ) {
1908  return $this->publishTo( $src, $this->getRel(), $flags, $options );
1909  }
1910 
1927  protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1928  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1929 
1930  $repo = $this->getRepo();
1931  if ( $repo->getReadOnlyReason() !== false ) {
1932  return $this->readOnlyFatalStatus();
1933  }
1934 
1935  $this->lock();
1936 
1937  if ( $this->isOld() ) {
1938  $archiveRel = $dstRel;
1939  $archiveName = basename( $archiveRel );
1940  } else {
1941  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1942  $archiveRel = $this->getArchiveRel( $archiveName );
1943  }
1944 
1945  if ( $repo->hasSha1Storage() ) {
1946  $sha1 = FileRepo::isVirtualUrl( $srcPath )
1947  ? $repo->getFileSha1( $srcPath )
1948  : FSFile::getSha1Base36FromPath( $srcPath );
1950  $wrapperBackend = $repo->getBackend();
1951  '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
1952  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1953  $status = $repo->quickImport( $src, $dst );
1954  if ( $flags & File::DELETE_SOURCE ) {
1955  unlink( $srcPath );
1956  }
1957 
1958  if ( $this->exists() ) {
1959  $status->value = $archiveName;
1960  }
1961  } else {
1962  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1963  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1964 
1965  if ( $status->value == 'new' ) {
1966  $status->value = '';
1967  } else {
1968  $status->value = $archiveName;
1969  }
1970  }
1971 
1972  $this->unlock();
1973  return $status;
1974  }
1975 
1994  public function move( $target ) {
1995  $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
1996  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1997  return $this->readOnlyFatalStatus();
1998  }
1999 
2000  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2001  $batch = new LocalFileMoveBatch( $this, $target );
2002 
2003  $this->lock();
2004  $batch->addCurrent();
2005  $archiveNames = $batch->addOlds();
2006  $status = $batch->execute();
2007  $this->unlock();
2008 
2009  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2010 
2011  // Purge the source and target files outside the transaction...
2012  $oldTitleFile = $localRepo->newFile( $this->title );
2013  $newTitleFile = $localRepo->newFile( $target );
2015  new AutoCommitUpdate(
2016  $this->getRepo()->getMasterDB(),
2017  __METHOD__,
2018  function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2019  $oldTitleFile->purgeEverything();
2020  foreach ( $archiveNames as $archiveName ) {
2022  '@phan-var OldLocalFile $oldTitleFile';
2023  $oldTitleFile->purgeOldThumbnails( $archiveName );
2024  }
2025  $newTitleFile->purgeEverything();
2026  }
2027  ),
2029  );
2030 
2031  if ( $status->isOK() ) {
2032  // Now switch the object
2033  $this->title = $target;
2034  // Force regeneration of the name and hashpath
2035  $this->name = null;
2036  $this->hashPath = null;
2037  }
2038 
2039  return $status;
2040  }
2041 
2057  public function delete( $reason, $suppress = false, $user = null ) {
2058  wfDeprecated( __METHOD__, '1.35' );
2059  if ( $user === null ) {
2060  global $wgUser;
2061  $user = $wgUser;
2062  }
2063  return $this->deleteFile( $reason, $user, $suppress );
2064  }
2065 
2082  public function deleteFile( $reason, User $user, $suppress = false ) {
2083  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2084  return $this->readOnlyFatalStatus();
2085  }
2086 
2087  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2088 
2089  $this->lock();
2090  $batch->addCurrent();
2091  // Get old version relative paths
2092  $archiveNames = $batch->addOlds();
2093  $status = $batch->execute();
2094  $this->unlock();
2095 
2096  if ( $status->isOK() ) {
2097  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2098  }
2099 
2100  // To avoid slow purges in the transaction, move them outside...
2102  new AutoCommitUpdate(
2103  $this->getRepo()->getMasterDB(),
2104  __METHOD__,
2105  function () use ( $archiveNames ) {
2106  $this->purgeEverything();
2107  foreach ( $archiveNames as $archiveName ) {
2108  $this->purgeOldThumbnails( $archiveName );
2109  }
2110  }
2111  ),
2113  );
2114 
2115  // Purge the CDN
2116  $purgeUrls = [];
2117  foreach ( $archiveNames as $archiveName ) {
2118  $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2119  }
2120 
2121  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2122  $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2123 
2124  return $status;
2125  }
2126 
2144  public function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2145  wfDeprecated( __METHOD__, '1.35' );
2146  if ( $user === null ) {
2147  global $wgUser;
2148  $user = $wgUser;
2149  }
2150  return $this->deleteOldFile( $archiveName, $reason, $user, $suppress );
2151  }
2152 
2171  public function deleteOldFile( $archiveName, $reason, User $user, $suppress = false ) {
2172  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2173  return $this->readOnlyFatalStatus();
2174  }
2175 
2176  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2177 
2178  $this->lock();
2179  $batch->addOld( $archiveName );
2180  $status = $batch->execute();
2181  $this->unlock();
2182 
2183  $this->purgeOldThumbnails( $archiveName );
2184  if ( $status->isOK() ) {
2185  $this->purgeDescription();
2186  }
2187 
2188  $url = $this->getArchiveUrl( $archiveName );
2189  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2190  $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2191 
2192  return $status;
2193  }
2194 
2207  public function restore( $versions = [], $unsuppress = false ) {
2208  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2209  return $this->readOnlyFatalStatus();
2210  }
2211 
2212  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2213 
2214  $this->lock();
2215  if ( !$versions ) {
2216  $batch->addAll();
2217  } else {
2218  $batch->addIds( $versions );
2219  }
2220  $status = $batch->execute();
2221  if ( $status->isGood() ) {
2222  $cleanupStatus = $batch->cleanup();
2223  $cleanupStatus->successCount = 0;
2224  $cleanupStatus->failCount = 0;
2225  $status->merge( $cleanupStatus );
2226  }
2227 
2228  $this->unlock();
2229  return $status;
2230  }
2231 
2242  public function getDescriptionUrl() {
2243  if ( !$this->title ) {
2244  return false; // Avoid hard failure when the file does not exist. T221812
2245  }
2246 
2247  return $this->title->getLocalURL();
2248  }
2249 
2259  public function getDescriptionText( Language $lang = null ) {
2260  if ( !$this->title ) {
2261  return false; // Avoid hard failure when the file does not exist. T221812
2262  }
2263 
2264  $store = MediaWikiServices::getInstance()->getRevisionStore();
2265  $revision = $store->getRevisionByTitle( $this->title, 0, RevisionStore::READ_NORMAL );
2266  if ( !$revision ) {
2267  return false;
2268  }
2269 
2270  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2271  $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2272 
2273  if ( !$rendered ) {
2274  // audience check failed
2275  return false;
2276  }
2277 
2278  $pout = $rendered->getRevisionParserOutput();
2279  return $pout->getText();
2280  }
2281 
2288  public function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2289  $this->load();
2290  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2291  return '';
2292  } elseif ( $audience == self::FOR_THIS_USER
2293  && !$this->userCan( self::DELETED_COMMENT, $user )
2294  ) {
2295  return '';
2296  } else {
2297  return $this->description;
2298  }
2299  }
2300 
2305  public function getTimestamp() {
2306  $this->load();
2307 
2308  return $this->timestamp;
2309  }
2310 
2315  public function getDescriptionTouched() {
2316  if ( !$this->exists() ) {
2317  return false; // Avoid hard failure when the file does not exist. T221812
2318  }
2319 
2320  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2321  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2322  // need to differentiate between null (uninitialized) and false (failed to load).
2323  if ( $this->descriptionTouched === null ) {
2324  $cond = [
2325  'page_namespace' => $this->title->getNamespace(),
2326  'page_title' => $this->title->getDBkey()
2327  ];
2328  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2329  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2330  }
2331 
2333  }
2334 
2339  public function getSha1() {
2340  $this->load();
2341  // Initialise now if necessary
2342  if ( $this->sha1 == '' && $this->fileExists ) {
2343  $this->lock();
2344 
2345  $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2346  if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2347  $dbw = $this->repo->getMasterDB();
2348  $dbw->update( 'image',
2349  [ 'img_sha1' => $this->sha1 ],
2350  [ 'img_name' => $this->getName() ],
2351  __METHOD__ );
2352  $this->invalidateCache();
2353  }
2354 
2355  $this->unlock();
2356  }
2357 
2358  return $this->sha1;
2359  }
2360 
2364  public function isCacheable() {
2365  $this->load();
2366 
2367  // If extra data (metadata) was not loaded then it must have been large
2368  return $this->extraDataLoaded
2369  && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
2370  }
2371 
2376  public function acquireFileLock() {
2377  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2378  [ $this->getPath() ], LockManager::LOCK_EX, 10
2379  ) );
2380  }
2381 
2386  public function releaseFileLock() {
2387  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2388  [ $this->getPath() ], LockManager::LOCK_EX
2389  ) );
2390  }
2391 
2401  public function lock() {
2402  if ( !$this->locked ) {
2403  $logger = LoggerFactory::getInstance( 'LocalFile' );
2404 
2405  $dbw = $this->repo->getMasterDB();
2406  $makesTransaction = !$dbw->trxLevel();
2407  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2408  // T56736: use simple lock to handle when the file does not exist.
2409  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2410  // Also, that would cause contention on INSERT of similarly named rows.
2411  $status = $this->acquireFileLock(); // represents all versions of the file
2412  if ( !$status->isGood() ) {
2413  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2414  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2415 
2416  throw new LocalFileLockError( $status );
2417  }
2418  // Release the lock *after* commit to avoid row-level contention.
2419  // Make sure it triggers on rollback() as well as commit() (T132921).
2420  $dbw->onTransactionResolution(
2421  function () use ( $logger ) {
2422  $status = $this->releaseFileLock();
2423  if ( !$status->isGood() ) {
2424  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2425  }
2426  },
2427  __METHOD__
2428  );
2429  // Callers might care if the SELECT snapshot is safely fresh
2430  $this->lockedOwnTrx = $makesTransaction;
2431  }
2432 
2433  $this->locked++;
2434 
2435  return $this->lockedOwnTrx;
2436  }
2437 
2446  public function unlock() {
2447  if ( $this->locked ) {
2448  --$this->locked;
2449  if ( !$this->locked ) {
2450  $dbw = $this->repo->getMasterDB();
2451  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2452  $this->lockedOwnTrx = false;
2453  }
2454  }
2455  }
2456 
2460  protected function readOnlyFatalStatus() {
2461  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2462  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2463  }
2464 
2468  public function __destruct() {
2469  $this->unlock();
2470  }
2471 }
LocalFile\$media_type
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition: LocalFile.php:77
LocalFile\getSha1
getSha1()
Stable to override.
Definition: LocalFile.php:2339
ParserOptions
Set options of the Parser.
Definition: ParserOptions.php:44
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:891
SpecialUpload\getInitialPageText
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
Definition: SpecialUpload.php:611
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:254
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:329
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:1704
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:46
LocalFile\deleteFile
deleteFile( $reason, User $user, $suppress=false)
Delete all versions of the file.
Definition: LocalFile.php:2082
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:2446
User\getId
getId()
Get the user's ID.
Definition: User.php:1925
LocalFile\getTimestamp
getTimestamp()
Stable to override.
Definition: LocalFile.php:2305
File\isMultipage
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition: File.php:2106
LocalFile\getUser
getUser( $type='text')
Returns user who uploaded the file @stable to override.
Definition: LocalFile.php:893
User\getActorId
getActorId(IDatabase $dbw=null)
Get the user's actor ID.
Definition: User.php:1993
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:154
$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:1617
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:81
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:775
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1808
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:1850
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:106
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
NS_FILE
const NS_FILE
Definition: Defines.php:75
$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:2460
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:1125
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:538
RequestContext\newExtraneousContext
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
Definition: RequestContext.php:623
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:1629
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:988
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:140
HTMLCacheUpdateJob\newForBacklinks
static newForBacklinks(Title $title, $table, $params=[])
Definition: HTMLCacheUpdateJob.php:59
LocalFile\acquireFileLock
acquireFileLock()
Definition: LocalFile.php:2376
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:2364
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:1224
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:1969
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:1927
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:2315
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1026
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:1718
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:1014
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
LocalFile\deleteOld
deleteOld( $archiveName, $reason, $suppress=false, $user=null)
Delete an old version of the file.
Definition: LocalFile.php:2144
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:2468
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:1617
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
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:2259
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:592
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:613
$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:909
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:1637
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:2288
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:1525
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:2401
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:2428
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:2386
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
User\addWatch
addWatch( $title, $checkRights=self::CHECK_USER_RIGHTS, ?string $expiry=null)
Watch an article.
Definition: User.php:3091
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:1764
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:1743
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:244
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\recordUpload
recordUpload( $oldver, $desc, $license='', $copyStatus='', $source='', $watch=false, $timestamp=false, User $user=null)
Record a file upload in the upload log and the image table.
Definition: LocalFile.php:1463
EDIT_NEW
const EDIT_NEW
Definition: Defines.php:141
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:2171
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:1011
$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:2418
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:1531
DeferredUpdates\PRESEND
const PRESEND
Definition: DeferredUpdates.php:84
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:1499
$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:283
LocalFile\loadExtraFieldsWithTimestamp
loadExtraFieldsWithTimestamp( $dbr, $fname)
Definition: LocalFile.php:507
LocalFileMoveBatch
Helper class for file movement.
Definition: LocalFileMoveBatch.php:31
MediaHandler\METADATA_BAD
const METADATA_BAD
Definition: MediaHandler.php:40
$source
$source
Definition: mwdoc-filter.php:34
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: ManualLogEntry.php:42
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:1907
EDIT_SUPPRESS_RC
const EDIT_SUPPRESS_RC
Definition: Defines.php:144
Title\invalidateCache
invalidateCache( $purgeTime=null)
Updates page_touched for this page; called from LinksUpdate.php.
Definition: Title.php:4170
LocalFile\getWidth
getWidth( $page=1)
Return the width of the image @stable to override.
Definition: LocalFile.php:826
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:1801
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:1459
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
File\userCan
userCan( $field, User $user=null)
Determine if the current user is allowed to view a particular field of this file, if it's marked as d...
Definition: File.php:2304
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:55
DeferredUpdates\addCallableUpdate
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add a callable update.
Definition: DeferredUpdates.php:145
LocalFile\VERSION
const VERSION
Definition: LocalFile.php:60
LocalFile\getDescriptionUrl
getDescriptionUrl()
isMultipage inherited
Definition: LocalFile.php:2242
LocalFile\move
move( $target)
getLinksTo inherited
Definition: LocalFile.php:1994
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:1954
LocalFile\restore
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition: LocalFile.php:2207
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:41
File\purgeEverything
purgeEverything()
Purge metadata and all affected pages when the file is created, deleted, or majorly updated.
Definition: File.php:1538
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:1505
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:1822
LogFormatter\newFromEntry
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
Definition: LogFormatter.php:52
Article\purgePatrolFooterCache
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Definition: Article.php:1385
$type
$type
Definition: testCompression.php:52