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 
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['user'] = $user->getId();
1528  $props['user_text'] = $user->getName();
1529  $props['actor'] = $user->getActorId( $dbw );
1530  $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1531  $this->setProps( $props );
1532 
1533  # Fail now if the file isn't there
1534  if ( !$this->fileExists ) {
1535  wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1536 
1537  return Status::newFatal( 'filenotfound', $this->getRel() );
1538  }
1539 
1540  $dbw->startAtomic( __METHOD__ );
1541 
1542  # Test to see if the row exists using INSERT IGNORE
1543  # This avoids race conditions by locking the row until the commit, and also
1544  # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1545  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1546  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1547  $actorMigration = ActorMigration::newMigration();
1548  $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1549  $dbw->insert( 'image',
1550  [
1551  'img_name' => $this->getName(),
1552  'img_size' => $this->size,
1553  'img_width' => intval( $this->width ),
1554  'img_height' => intval( $this->height ),
1555  'img_bits' => $this->bits,
1556  'img_media_type' => $this->media_type,
1557  'img_major_mime' => $this->major_mime,
1558  'img_minor_mime' => $this->minor_mime,
1559  'img_timestamp' => $timestamp,
1560  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1561  'img_sha1' => $this->sha1
1562  ] + $commentFields + $actorFields,
1563  __METHOD__,
1564  [ 'IGNORE' ]
1565  );
1566  $reupload = ( $dbw->affectedRows() == 0 );
1567 
1568  if ( $reupload ) {
1569  $row = $dbw->selectRow(
1570  'image',
1571  [ 'img_timestamp', 'img_sha1' ],
1572  [ 'img_name' => $this->getName() ],
1573  __METHOD__,
1574  [ 'LOCK IN SHARE MODE' ]
1575  );
1576 
1577  if ( $row && $row->img_sha1 === $this->sha1 ) {
1578  $dbw->endAtomic( __METHOD__ );
1579  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1580  $title = Title::newFromText( $this->getName(), NS_FILE );
1581  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1582  }
1583 
1584  if ( $allowTimeKludge ) {
1585  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1586  $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1587  # Avoid a timestamp that is not newer than the last version
1588  # TODO: the image/oldimage tables should be like page/revision with an ID field
1589  if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1590  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1591  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1592  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1593  }
1594  }
1595 
1596  $tables = [ 'image' ];
1597  $fields = [
1598  'oi_name' => 'img_name',
1599  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1600  'oi_size' => 'img_size',
1601  'oi_width' => 'img_width',
1602  'oi_height' => 'img_height',
1603  'oi_bits' => 'img_bits',
1604  'oi_description_id' => 'img_description_id',
1605  'oi_timestamp' => 'img_timestamp',
1606  'oi_metadata' => 'img_metadata',
1607  'oi_media_type' => 'img_media_type',
1608  'oi_major_mime' => 'img_major_mime',
1609  'oi_minor_mime' => 'img_minor_mime',
1610  'oi_sha1' => 'img_sha1',
1611  'oi_actor' => 'img_actor',
1612  ];
1613  $joins = [];
1614 
1615  # (T36993) Note: $oldver can be empty here, if the previous
1616  # version of the file was broken. Allow registration of the new
1617  # version to continue anyway, because that's better than having
1618  # an image that's not fixable by user operations.
1619  # Collision, this is an update of a file
1620  # Insert previous contents into oldimage
1621  $dbw->insertSelect( 'oldimage', $tables, $fields,
1622  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1623 
1624  # Update the current image row
1625  $dbw->update( 'image',
1626  [
1627  'img_size' => $this->size,
1628  'img_width' => intval( $this->width ),
1629  'img_height' => intval( $this->height ),
1630  'img_bits' => $this->bits,
1631  'img_media_type' => $this->media_type,
1632  'img_major_mime' => $this->major_mime,
1633  'img_minor_mime' => $this->minor_mime,
1634  'img_timestamp' => $timestamp,
1635  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1636  'img_sha1' => $this->sha1
1637  ] + $commentFields + $actorFields,
1638  [ 'img_name' => $this->getName() ],
1639  __METHOD__
1640  );
1641  }
1642 
1643  $descTitle = $this->getTitle();
1644  $descId = $descTitle->getArticleID();
1645  $wikiPage = new WikiFilePage( $descTitle );
1646  $wikiPage->setFile( $this );
1647 
1648  // Determine log action. If reupload is done by reverting, use a special log_action.
1649  if ( $revert === true ) {
1650  $logAction = 'revert';
1651  } elseif ( $reupload === true ) {
1652  $logAction = 'overwrite';
1653  } else {
1654  $logAction = 'upload';
1655  }
1656  // Add the log entry...
1657  $logEntry = new ManualLogEntry( 'upload', $logAction );
1658  $logEntry->setTimestamp( $this->timestamp );
1659  $logEntry->setPerformer( $user );
1660  $logEntry->setComment( $comment );
1661  $logEntry->setTarget( $descTitle );
1662  // Allow people using the api to associate log entries with the upload.
1663  // Log has a timestamp, but sometimes different from upload timestamp.
1664  $logEntry->setParameters(
1665  [
1666  'img_sha1' => $this->sha1,
1667  'img_timestamp' => $timestamp,
1668  ]
1669  );
1670  // Note we keep $logId around since during new image
1671  // creation, page doesn't exist yet, so log_page = 0
1672  // but we want it to point to the page we're making,
1673  // so we later modify the log entry.
1674  // For a similar reason, we avoid making an RC entry
1675  // now and wait until the page exists.
1676  $logId = $logEntry->insert();
1677 
1678  if ( $descTitle->exists() ) {
1679  if ( $createNullRevision !== false ) {
1680  $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1681  // Use own context to get the action text in content language
1682  $formatter = LogFormatter::newFromEntry( $logEntry );
1683  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1684  $editSummary = $formatter->getPlainActionText();
1685  $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1686  $nullRevRecord = $revStore->newNullRevision(
1687  $dbw,
1688  $descTitle,
1689  $summary,
1690  false,
1691  $user
1692  );
1693 
1694  if ( $nullRevRecord ) {
1695  $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1696 
1697  $this->getHookRunner()->onRevisionFromEditComplete(
1698  $wikiPage,
1699  $inserted,
1700  $inserted->getParentId(),
1701  $user,
1702  $tags
1703  );
1704 
1705  // Hook is hard deprecated since 1.35
1706  if ( $this->getHookContainer()->isRegistered( 'NewRevisionFromEditComplete' ) ) {
1707  // Only create the Revision object if needed
1708  $nullRevision = new Revision( $inserted );
1709  $this->getHookRunner()->onNewRevisionFromEditComplete(
1710  $wikiPage,
1711  $nullRevision,
1712  $inserted->getParentId(),
1713  $user,
1714  $tags
1715  );
1716  }
1717 
1718  $wikiPage->updateRevisionOn( $dbw, $inserted );
1719  // Associate null revision id
1720  $logEntry->setAssociatedRevId( $inserted->getId() );
1721  }
1722  }
1723 
1724  $newPageContent = null;
1725  } else {
1726  // Make the description page and RC log entry post-commit
1727  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1728  }
1729 
1730  # Defer purges, page creation, and link updates in case they error out.
1731  # The most important thing is that files and the DB registry stay synced.
1732  $dbw->endAtomic( __METHOD__ );
1733  $fname = __METHOD__;
1734 
1735  # Do some cache purges after final commit so that:
1736  # a) Changes are more likely to be seen post-purge
1737  # b) They won't cause rollback of the log publish/update above
1739  new AutoCommitUpdate(
1740  $dbw,
1741  __METHOD__,
1743  function () use (
1744  $reupload, $wikiPage, $newPageContent, $comment, $user,
1745  $logEntry, $logId, $descId, $tags, $fname
1746  ) {
1747  # Update memcache after the commit
1748  $this->invalidateCache();
1749 
1750  $updateLogPage = false;
1751  if ( $newPageContent ) {
1752  # New file page; create the description page.
1753  # There's already a log entry, so don't make a second RC entry
1754  # CDN and file cache for the description page are purged by doEditContent.
1755  $status = $wikiPage->doEditContent(
1756  $newPageContent,
1757  $comment,
1759  false,
1760  $user
1761  );
1762 
1763  if ( isset( $status->value['revision-record'] ) ) {
1765  $revRecord = $status->value['revision-record'];
1766  // Associate new page revision id
1767  $logEntry->setAssociatedRevId( $revRecord->getId() );
1768  }
1769  // This relies on the resetArticleID() call in WikiPage::insertOn(),
1770  // which is triggered on $descTitle by doEditContent() above.
1771  if ( isset( $status->value['revision-record'] ) ) {
1773  $revRecord = $status->value['revision-record'];
1774  $updateLogPage = $revRecord->getPageId();
1775  }
1776  } else {
1777  # Existing file page: invalidate description page cache
1778  $title = $wikiPage->getTitle();
1780  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1781  $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1782  # Allow the new file version to be patrolled from the page footer
1784  }
1785 
1786  # Update associated rev id. This should be done by $logEntry->insert() earlier,
1787  # but setAssociatedRevId() wasn't called at that point yet...
1788  $logParams = $logEntry->getParameters();
1789  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1790  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1791  if ( $updateLogPage ) {
1792  # Also log page, in case where we just created it above
1793  $update['log_page'] = $updateLogPage;
1794  }
1795  $this->getRepo()->getMasterDB()->update(
1796  'logging',
1797  $update,
1798  [ 'log_id' => $logId ],
1799  $fname
1800  );
1801  $this->getRepo()->getMasterDB()->insert(
1802  'log_search',
1803  [
1804  'ls_field' => 'associated_rev_id',
1805  'ls_value' => (string)$logEntry->getAssociatedRevId(),
1806  'ls_log_id' => $logId,
1807  ],
1808  $fname
1809  );
1810 
1811  # Add change tags, if any
1812  if ( $tags ) {
1813  $logEntry->addTags( $tags );
1814  }
1815 
1816  # Uploads can be patrolled
1817  $logEntry->setIsPatrollable( true );
1818 
1819  # Now that the log entry is up-to-date, make an RC entry.
1820  $logEntry->publish( $logId );
1821 
1822  # Run hook for other updates (typically more cache purging)
1823  $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
1824 
1825  if ( $reupload ) {
1826  # Delete old thumbnails
1827  $this->purgeThumbnails();
1828  # Remove the old file from the CDN cache
1829  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1830  $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1831  } else {
1832  # Update backlink pages pointing to this title if created
1834  $this->getTitle(),
1835  'imagelinks',
1836  'upload-image',
1837  $user->getName()
1838  );
1839  }
1840 
1841  $this->prerenderThumbnails();
1842  }
1843  ),
1845  );
1846 
1847  if ( !$reupload ) {
1848  # This is a new file, so update the image count
1849  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1850  }
1851 
1852  # Invalidate cache for all pages using this file
1854  $this->getTitle(),
1855  'imagelinks',
1856  [ 'causeAction' => 'file-upload', 'causeAgent' => $user->getName() ]
1857  );
1858  JobQueueGroup::singleton()->lazyPush( $job );
1859 
1860  return Status::newGood();
1861  }
1862 
1879  public function publish( $src, $flags = 0, array $options = [] ) {
1880  return $this->publishTo( $src, $this->getRel(), $flags, $options );
1881  }
1882 
1899  protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1900  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1901 
1902  $repo = $this->getRepo();
1903  if ( $repo->getReadOnlyReason() !== false ) {
1904  return $this->readOnlyFatalStatus();
1905  }
1906 
1907  $this->lock();
1908 
1909  if ( $this->isOld() ) {
1910  $archiveRel = $dstRel;
1911  $archiveName = basename( $archiveRel );
1912  } else {
1913  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1914  $archiveRel = $this->getArchiveRel( $archiveName );
1915  }
1916 
1917  if ( $repo->hasSha1Storage() ) {
1918  $sha1 = FileRepo::isVirtualUrl( $srcPath )
1919  ? $repo->getFileSha1( $srcPath )
1920  : FSFile::getSha1Base36FromPath( $srcPath );
1922  $wrapperBackend = $repo->getBackend();
1923  '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
1924  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1925  $status = $repo->quickImport( $src, $dst );
1926  if ( $flags & File::DELETE_SOURCE ) {
1927  unlink( $srcPath );
1928  }
1929 
1930  if ( $this->exists() ) {
1931  $status->value = $archiveName;
1932  }
1933  } else {
1934  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1935  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1936 
1937  if ( $status->value == 'new' ) {
1938  $status->value = '';
1939  } else {
1940  $status->value = $archiveName;
1941  }
1942  }
1943 
1944  $this->unlock();
1945  return $status;
1946  }
1947 
1966  public function move( $target ) {
1967  $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
1968  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1969  return $this->readOnlyFatalStatus();
1970  }
1971 
1972  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1973  $batch = new LocalFileMoveBatch( $this, $target );
1974 
1975  $this->lock();
1976  $batch->addCurrent();
1977  $archiveNames = $batch->addOlds();
1978  $status = $batch->execute();
1979  $this->unlock();
1980 
1981  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1982 
1983  // Purge the source and target files outside the transaction...
1984  $oldTitleFile = $localRepo->newFile( $this->title );
1985  $newTitleFile = $localRepo->newFile( $target );
1987  new AutoCommitUpdate(
1988  $this->getRepo()->getMasterDB(),
1989  __METHOD__,
1990  function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1991  $oldTitleFile->purgeEverything();
1992  foreach ( $archiveNames as $archiveName ) {
1994  '@phan-var OldLocalFile $oldTitleFile';
1995  $oldTitleFile->purgeOldThumbnails( $archiveName );
1996  }
1997  $newTitleFile->purgeEverything();
1998  }
1999  ),
2001  );
2002 
2003  if ( $status->isOK() ) {
2004  // Now switch the object
2005  $this->title = $target;
2006  // Force regeneration of the name and hashpath
2007  $this->name = null;
2008  $this->hashPath = null;
2009  }
2010 
2011  return $status;
2012  }
2013 
2030  public function deleteFile( $reason, User $user, $suppress = false ) {
2031  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2032  return $this->readOnlyFatalStatus();
2033  }
2034 
2035  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2036 
2037  $this->lock();
2038  $batch->addCurrent();
2039  // Get old version relative paths
2040  $archiveNames = $batch->addOlds();
2041  $status = $batch->execute();
2042  $this->unlock();
2043 
2044  if ( $status->isOK() ) {
2045  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2046  }
2047 
2048  // To avoid slow purges in the transaction, move them outside...
2050  new AutoCommitUpdate(
2051  $this->getRepo()->getMasterDB(),
2052  __METHOD__,
2053  function () use ( $archiveNames ) {
2054  $this->purgeEverything();
2055  foreach ( $archiveNames as $archiveName ) {
2056  $this->purgeOldThumbnails( $archiveName );
2057  }
2058  }
2059  ),
2061  );
2062 
2063  // Purge the CDN
2064  $purgeUrls = [];
2065  foreach ( $archiveNames as $archiveName ) {
2066  $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2067  }
2068 
2069  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2070  $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2071 
2072  return $status;
2073  }
2074 
2093  public function deleteOldFile( $archiveName, $reason, User $user, $suppress = false ) {
2094  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2095  return $this->readOnlyFatalStatus();
2096  }
2097 
2098  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2099 
2100  $this->lock();
2101  $batch->addOld( $archiveName );
2102  $status = $batch->execute();
2103  $this->unlock();
2104 
2105  $this->purgeOldThumbnails( $archiveName );
2106  if ( $status->isOK() ) {
2107  $this->purgeDescription();
2108  }
2109 
2110  $url = $this->getArchiveUrl( $archiveName );
2111  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2112  $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2113 
2114  return $status;
2115  }
2116 
2129  public function restore( $versions = [], $unsuppress = false ) {
2130  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2131  return $this->readOnlyFatalStatus();
2132  }
2133 
2134  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2135 
2136  $this->lock();
2137  if ( !$versions ) {
2138  $batch->addAll();
2139  } else {
2140  $batch->addIds( $versions );
2141  }
2142  $status = $batch->execute();
2143  if ( $status->isGood() ) {
2144  $cleanupStatus = $batch->cleanup();
2145  $cleanupStatus->successCount = 0;
2146  $cleanupStatus->failCount = 0;
2147  $status->merge( $cleanupStatus );
2148  }
2149 
2150  $this->unlock();
2151  return $status;
2152  }
2153 
2164  public function getDescriptionUrl() {
2165  if ( !$this->title ) {
2166  return false; // Avoid hard failure when the file does not exist. T221812
2167  }
2168 
2169  return $this->title->getLocalURL();
2170  }
2171 
2181  public function getDescriptionText( Language $lang = null ) {
2182  if ( !$this->title ) {
2183  return false; // Avoid hard failure when the file does not exist. T221812
2184  }
2185 
2186  $store = MediaWikiServices::getInstance()->getRevisionStore();
2187  $revision = $store->getRevisionByTitle( $this->title, 0, RevisionStore::READ_NORMAL );
2188  if ( !$revision ) {
2189  return false;
2190  }
2191 
2192  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2193  $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2194 
2195  if ( !$rendered ) {
2196  // audience check failed
2197  return false;
2198  }
2199 
2200  $pout = $rendered->getRevisionParserOutput();
2201  return $pout->getText();
2202  }
2203 
2210  public function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2211  $this->load();
2212  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2213  return '';
2214  } elseif ( $audience == self::FOR_THIS_USER
2215  && !$this->userCan( self::DELETED_COMMENT, $user )
2216  ) {
2217  return '';
2218  } else {
2219  return $this->description;
2220  }
2221  }
2222 
2227  public function getTimestamp() {
2228  $this->load();
2229 
2230  return $this->timestamp;
2231  }
2232 
2237  public function getDescriptionTouched() {
2238  if ( !$this->exists() ) {
2239  return false; // Avoid hard failure when the file does not exist. T221812
2240  }
2241 
2242  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2243  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2244  // need to differentiate between null (uninitialized) and false (failed to load).
2245  if ( $this->descriptionTouched === null ) {
2246  $cond = [
2247  'page_namespace' => $this->title->getNamespace(),
2248  'page_title' => $this->title->getDBkey()
2249  ];
2250  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2251  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2252  }
2253 
2255  }
2256 
2261  public function getSha1() {
2262  $this->load();
2263  // Initialise now if necessary
2264  if ( $this->sha1 == '' && $this->fileExists ) {
2265  $this->lock();
2266 
2267  $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2268  if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2269  $dbw = $this->repo->getMasterDB();
2270  $dbw->update( 'image',
2271  [ 'img_sha1' => $this->sha1 ],
2272  [ 'img_name' => $this->getName() ],
2273  __METHOD__ );
2274  $this->invalidateCache();
2275  }
2276 
2277  $this->unlock();
2278  }
2279 
2280  return $this->sha1;
2281  }
2282 
2286  public function isCacheable() {
2287  $this->load();
2288 
2289  // If extra data (metadata) was not loaded then it must have been large
2290  return $this->extraDataLoaded
2291  && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
2292  }
2293 
2298  public function acquireFileLock() {
2299  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2300  [ $this->getPath() ], LockManager::LOCK_EX, 10
2301  ) );
2302  }
2303 
2308  public function releaseFileLock() {
2309  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2310  [ $this->getPath() ], LockManager::LOCK_EX
2311  ) );
2312  }
2313 
2323  public function lock() {
2324  if ( !$this->locked ) {
2325  $logger = LoggerFactory::getInstance( 'LocalFile' );
2326 
2327  $dbw = $this->repo->getMasterDB();
2328  $makesTransaction = !$dbw->trxLevel();
2329  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2330  // T56736: use simple lock to handle when the file does not exist.
2331  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2332  // Also, that would cause contention on INSERT of similarly named rows.
2333  $status = $this->acquireFileLock(); // represents all versions of the file
2334  if ( !$status->isGood() ) {
2335  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2336  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2337 
2338  throw new LocalFileLockError( $status );
2339  }
2340  // Release the lock *after* commit to avoid row-level contention.
2341  // Make sure it triggers on rollback() as well as commit() (T132921).
2342  $dbw->onTransactionResolution(
2343  function () use ( $logger ) {
2344  $status = $this->releaseFileLock();
2345  if ( !$status->isGood() ) {
2346  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2347  }
2348  },
2349  __METHOD__
2350  );
2351  // Callers might care if the SELECT snapshot is safely fresh
2352  $this->lockedOwnTrx = $makesTransaction;
2353  }
2354 
2355  $this->locked++;
2356 
2357  return $this->lockedOwnTrx;
2358  }
2359 
2368  public function unlock() {
2369  if ( $this->locked ) {
2370  --$this->locked;
2371  if ( !$this->locked ) {
2372  $dbw = $this->repo->getMasterDB();
2373  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2374  $this->lockedOwnTrx = false;
2375  }
2376  }
2377  }
2378 
2382  protected function readOnlyFatalStatus() {
2383  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2384  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2385  }
2386 
2390  public function __destruct() {
2391  $this->unlock();
2392  }
2393 }
LocalFile\$media_type
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition: LocalFile.php:77
LocalFile\getSha1
getSha1()
Stable to override.
Definition: LocalFile.php:2261
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:890
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:328
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:2030
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:2368
User\getId
getId()
Get the user's ID.
Definition: User.php:2024
LocalFile\getTimestamp
getTimestamp()
Stable to override.
Definition: LocalFile.php:2227
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:2257
File\isMultipage
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition: File.php:2059
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:2092
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:165
$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:80
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:1815
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:1852
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:2382
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:1126
User\newFromName
static newFromName( $name, $validate='valid')
Definition: User.php:545
RequestContext\newExtraneousContext
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
Definition: RequestContext.php:624
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:1969
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:989
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:156
HTMLCacheUpdateJob\newForBacklinks
static newForBacklinks(Title $title, $table, $params=[])
Definition: HTMLCacheUpdateJob.php:59
LocalFile\acquireFileLock
acquireFileLock()
Definition: LocalFile.php:2298
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:2286
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:1247
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:1998
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:1899
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:2237
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
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:1037
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:2390
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:1615
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:2181
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:591
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:643
$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:910
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:1659
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:2210
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:2323
File\isOld
isOld()
Returns true if the image is an old version STUB.
Definition: File.php:1957
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:2381
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:2308
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: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
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:454
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
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:2093
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:2371
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
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: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: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
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:1879
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:4094
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
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:56
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:2164
LocalFile\move
move( $target)
getLinksTo inherited
Definition: LocalFile.php:1966
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:2053
LocalFile\restore
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition: LocalFile.php:2129
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: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:53
Article\purgePatrolFooterCache
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Definition: Article.php:1338
$type
$type
Definition: testCompression.php:52