MediaWiki  master
LocalFile.php
Go to the documentation of this file.
1 <?php
26 use Wikimedia\AtEase\AtEase;
30 
56 class LocalFile extends File {
57  private const VERSION = 12; // cache version
58 
59  private const CACHE_FIELD_MAX_LEN = 1000;
60 
62  protected $fileExists;
63 
65  protected $width;
66 
68  protected $height;
69 
71  protected $bits;
72 
74  protected $media_type;
75 
77  protected $mime;
78 
80  protected $size;
81 
83  protected $metadata;
84 
86  protected $sha1;
87 
89  protected $dataLoaded;
90 
92  protected $extraDataLoaded;
93 
95  protected $deleted;
96 
98  protected $repoClass = LocalRepo::class;
99 
101  private $historyLine;
102 
104  private $historyRes;
105 
107  private $major_mime;
108 
110  private $minor_mime;
111 
113  private $timestamp;
114 
116  private $user;
117 
119  private $description;
120 
123 
125  private $upgraded;
126 
128  private $upgrading;
129 
131  private $locked;
132 
134  private $lockedOwnTrx;
135 
137  private $missing;
138 
139  // @note: higher than IDBAccessObject constants
140  private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
141 
142  private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
143 
156  public static function newFromTitle( $title, $repo, $unused = null ) {
157  return new static( $title, $repo );
158  }
159 
169  public static function newFromRow( $row, $repo ) {
170  $title = Title::makeTitle( NS_FILE, $row->img_name );
171  $file = new static( $title, $repo );
172  $file->loadFromRow( $row );
173 
174  return $file;
175  }
176 
186  public static function newFromKey( $sha1, $repo, $timestamp = false ) {
187  $dbr = $repo->getReplicaDB();
188 
189  $conds = [ 'img_sha1' => $sha1 ];
190  if ( $timestamp ) {
191  $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
192  }
193 
194  $fileQuery = static::getQueryInfo();
195  $row = $dbr->selectRow(
196  $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__, [], $fileQuery['joins']
197  );
198  if ( $row ) {
199  return static::newFromRow( $row, $repo );
200  } else {
201  return false;
202  }
203  }
204 
216  public static function getQueryInfo( array $options = [] ) {
217  $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'img_description' );
218  $actorQuery = ActorMigration::newMigration()->getJoin( 'img_user' );
219  $ret = [
220  'tables' => [ 'image' ] + $commentQuery['tables'] + $actorQuery['tables'],
221  'fields' => [
222  'img_name',
223  'img_size',
224  'img_width',
225  'img_height',
226  'img_metadata',
227  'img_bits',
228  'img_media_type',
229  'img_major_mime',
230  'img_minor_mime',
231  'img_timestamp',
232  'img_sha1',
233  ] + $commentQuery['fields'] + $actorQuery['fields'],
234  'joins' => $commentQuery['joins'] + $actorQuery['joins'],
235  ];
236 
237  if ( in_array( 'omit-nonlazy', $options, true ) ) {
238  // Internal use only for getting only the lazy fields
239  $ret['fields'] = [];
240  }
241  if ( !in_array( 'omit-lazy', $options, true ) ) {
242  // Note: Keep this in sync with self::getLazyCacheFields()
243  $ret['fields'][] = 'img_metadata';
244  }
245 
246  return $ret;
247  }
248 
254  public function __construct( $title, $repo ) {
255  parent::__construct( $title, $repo );
256 
257  $this->metadata = '';
258  $this->historyLine = 0;
259  $this->historyRes = null;
260  $this->dataLoaded = false;
261  $this->extraDataLoaded = false;
262 
263  $this->assertRepoDefined();
264  $this->assertTitleDefined();
265  }
266 
270  public function getRepo() {
271  return $this->repo;
272  }
273 
279  protected function getCacheKey() {
280  return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
281  }
282 
289  return [ $this->getCacheKey() ];
290  }
291 
295  private function loadFromCache() {
296  $this->dataLoaded = false;
297  $this->extraDataLoaded = false;
298 
299  $key = $this->getCacheKey();
300  if ( !$key ) {
301  $this->loadFromDB( self::READ_NORMAL );
302 
303  return;
304  }
305 
306  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
307  $cachedValues = $cache->getWithSetCallback(
308  $key,
309  $cache::TTL_WEEK,
310  function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
311  $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
312 
313  $this->loadFromDB( self::READ_NORMAL );
314 
315  $fields = $this->getCacheFields( '' );
316  $cacheVal = [];
317  $cacheVal['fileExists'] = $this->fileExists;
318  if ( $this->fileExists ) {
319  foreach ( $fields as $field ) {
320  $cacheVal[$field] = $this->$field;
321  }
322  }
323  $cacheVal['user'] = $this->user ? $this->user->getId() : 0;
324  $cacheVal['user_text'] = $this->user ? $this->user->getName() : '';
325  $cacheVal['actor'] = $this->user ? $this->user->getActorId() : null;
326 
327  // Strip off excessive entries from the subset of fields that can become large.
328  // If the cache value gets to large it will not fit in memcached and nothing will
329  // get cached at all, causing master queries for any file access.
330  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
331  if ( isset( $cacheVal[$field] )
332  && strlen( $cacheVal[$field] ) > 100 * 1024
333  ) {
334  unset( $cacheVal[$field] ); // don't let the value get too big
335  }
336  }
337 
338  if ( $this->fileExists ) {
339  $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
340  } else {
341  $ttl = $cache::TTL_DAY;
342  }
343 
344  return $cacheVal;
345  },
346  [ 'version' => self::VERSION ]
347  );
348 
349  $this->fileExists = $cachedValues['fileExists'];
350  if ( $this->fileExists ) {
351  $this->setProps( $cachedValues );
352  }
353 
354  $this->dataLoaded = true;
355  $this->extraDataLoaded = true;
356  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
357  $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
358  }
359  }
360 
364  public function invalidateCache() {
365  $key = $this->getCacheKey();
366  if ( !$key ) {
367  return;
368  }
369 
370  $this->repo->getMasterDB()->onTransactionPreCommitOrIdle(
371  function () use ( $key ) {
372  MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
373  },
374  __METHOD__
375  );
376  }
377 
381  protected function loadFromFile() {
382  $props = $this->repo->getFileProps( $this->getVirtualUrl() );
383  $this->setProps( $props );
384  }
385 
392  protected function getCacheFields( $prefix = 'img_' ) {
393  if ( $prefix !== '' ) {
394  throw new InvalidArgumentException(
395  __METHOD__ . ' with a non-empty prefix is no longer supported.'
396  );
397  }
398 
399  // See self::getQueryInfo() for the fetching of the data from the DB,
400  // self::loadFromRow() for the loading of the object from the DB row,
401  // and self::loadFromCache() for the caching, and self::setProps() for
402  // populating the object from an array of data.
403  return [ 'size', 'width', 'height', 'bits', 'media_type',
404  'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
405  }
406 
414  protected function getLazyCacheFields( $prefix = 'img_' ) {
415  if ( $prefix !== '' ) {
416  throw new InvalidArgumentException(
417  __METHOD__ . ' with a non-empty prefix is no longer supported.'
418  );
419  }
420 
421  // Keep this in sync with the omit-lazy option in self::getQueryInfo().
422  return [ 'metadata' ];
423  }
424 
429  protected function loadFromDB( $flags = 0 ) {
430  $fname = static::class . '::' . __FUNCTION__;
431 
432  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
433  $this->dataLoaded = true;
434  $this->extraDataLoaded = true;
435 
436  $dbr = ( $flags & self::READ_LATEST )
437  ? $this->repo->getMasterDB()
438  : $this->repo->getReplicaDB();
439 
440  $fileQuery = static::getQueryInfo();
441  $row = $dbr->selectRow(
442  $fileQuery['tables'],
443  $fileQuery['fields'],
444  [ 'img_name' => $this->getName() ],
445  $fname,
446  [],
447  $fileQuery['joins']
448  );
449 
450  if ( $row ) {
451  $this->loadFromRow( $row );
452  } else {
453  $this->fileExists = false;
454  }
455  }
456 
461  protected function loadExtraFromDB() {
462  if ( !$this->title ) {
463  return; // Avoid hard failure when the file does not exist. T221812
464  }
465 
466  $fname = static::class . '::' . __FUNCTION__;
467 
468  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
469  $this->extraDataLoaded = true;
470 
471  $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo->getReplicaDB(), $fname );
472  if ( !$fieldMap ) {
473  $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo->getMasterDB(), $fname );
474  }
475 
476  if ( $fieldMap ) {
477  foreach ( $fieldMap as $name => $value ) {
478  $this->$name = $value;
479  }
480  } else {
481  throw new MWException( "Could not find data for image '{$this->getName()}'." );
482  }
483  }
484 
490  private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
491  $fieldMap = false;
492 
493  $fileQuery = self::getQueryInfo( [ 'omit-nonlazy' ] );
494  $row = $dbr->selectRow(
495  $fileQuery['tables'],
496  $fileQuery['fields'],
497  [
498  'img_name' => $this->getName(),
499  'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
500  ],
501  $fname,
502  [],
503  $fileQuery['joins']
504  );
505  if ( $row ) {
506  $fieldMap = $this->unprefixRow( $row, 'img_' );
507  } else {
508  # File may have been uploaded over in the meantime; check the old versions
509  $fileQuery = OldLocalFile::getQueryInfo( [ 'omit-nonlazy' ] );
510  $row = $dbr->selectRow(
511  $fileQuery['tables'],
512  $fileQuery['fields'],
513  [
514  'oi_name' => $this->getName(),
515  'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
516  ],
517  $fname,
518  [],
519  $fileQuery['joins']
520  );
521  if ( $row ) {
522  $fieldMap = $this->unprefixRow( $row, 'oi_' );
523  }
524  }
525 
526  if ( isset( $fieldMap['metadata'] ) ) {
527  $fieldMap['metadata'] = $this->repo->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
528  }
529 
530  return $fieldMap;
531  }
532 
539  protected function unprefixRow( $row, $prefix = 'img_' ) {
540  $array = (array)$row;
541  $prefixLength = strlen( $prefix );
542 
543  // Sanity check prefix once
544  if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
545  throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
546  }
547 
548  $decoded = [];
549  foreach ( $array as $name => $value ) {
550  $decoded[substr( $name, $prefixLength )] = $value;
551  }
552 
553  return $decoded;
554  }
555 
564  private function decodeRow( $row, $prefix = 'img_' ) {
565  $decoded = $this->unprefixRow( $row, $prefix );
566 
567  $decoded['description'] = MediaWikiServices::getInstance()->getCommentStore()
568  ->getComment( 'description', (object)$decoded )->text;
569 
570  $decoded['user'] = User::newFromAnyId(
571  $decoded['user'] ?? null,
572  $decoded['user_text'] ?? null,
573  $decoded['actor'] ?? null
574  );
575  unset( $decoded['user_text'], $decoded['actor'] );
576 
577  $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
578 
579  $decoded['metadata'] = $this->repo->getReplicaDB()->decodeBlob( $decoded['metadata'] );
580 
581  if ( empty( $decoded['major_mime'] ) ) {
582  $decoded['mime'] = 'unknown/unknown';
583  } else {
584  if ( !$decoded['minor_mime'] ) {
585  $decoded['minor_mime'] = 'unknown';
586  }
587  $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
588  }
589 
590  // Trim zero padding from char/binary field
591  $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
592 
593  // Normalize some fields to integer type, per their database definition.
594  // Use unary + so that overflows will be upgraded to double instead of
595  // being trucated as with intval(). This is important to allow >2GB
596  // files on 32-bit systems.
597  foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
598  $decoded[$field] = +$decoded[$field];
599  }
600 
601  return $decoded;
602  }
603 
610  public function loadFromRow( $row, $prefix = 'img_' ) {
611  $this->dataLoaded = true;
612  $this->extraDataLoaded = true;
613 
614  $array = $this->decodeRow( $row, $prefix );
615 
616  foreach ( $array as $name => $value ) {
617  $this->$name = $value;
618  }
619 
620  $this->fileExists = true;
621  }
622 
627  public function load( $flags = 0 ) {
628  if ( !$this->dataLoaded ) {
629  if ( $flags & self::READ_LATEST ) {
630  $this->loadFromDB( $flags );
631  } else {
632  $this->loadFromCache();
633  }
634  }
635 
636  if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
637  // @note: loads on name/timestamp to reduce race condition problems
638  $this->loadExtraFromDB();
639  }
640  }
641 
645  protected function maybeUpgradeRow() {
647 
648  if ( wfReadOnly() || $this->upgrading ) {
649  return;
650  }
651 
652  $upgrade = false;
653  if ( $this->media_type === null || $this->mime == 'image/svg' ) {
654  $upgrade = true;
655  } else {
656  $handler = $this->getHandler();
657  if ( $handler ) {
658  $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
659  if ( $validity === MediaHandler::METADATA_BAD ) {
660  $upgrade = true;
661  } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE ) {
662  $upgrade = $wgUpdateCompatibleMetadata;
663  }
664  }
665  }
666 
667  if ( $upgrade ) {
668  $this->upgrading = true;
669  // Defer updates unless in auto-commit CLI mode
671  $this->upgrading = false; // avoid duplicate updates
672  try {
673  $this->upgradeRow();
674  } catch ( LocalFileLockError $e ) {
675  // let the other process handle it (or do it next time)
676  }
677  } );
678  }
679  }
680 
684  public function getUpgraded() {
685  return $this->upgraded;
686  }
687 
691  public function upgradeRow() {
692  $this->lock();
693 
694  $this->loadFromFile();
695 
696  # Don't destroy file info of missing files
697  if ( !$this->fileExists ) {
698  $this->unlock();
699  wfDebug( __METHOD__ . ": file does not exist, aborting" );
700 
701  return;
702  }
703 
704  $dbw = $this->repo->getMasterDB();
705  list( $major, $minor ) = self::splitMime( $this->mime );
706 
707  if ( wfReadOnly() ) {
708  $this->unlock();
709 
710  return;
711  }
712  wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
713 
714  $dbw->update( 'image',
715  [
716  'img_size' => $this->size, // sanity
717  'img_width' => $this->width,
718  'img_height' => $this->height,
719  'img_bits' => $this->bits,
720  'img_media_type' => $this->media_type,
721  'img_major_mime' => $major,
722  'img_minor_mime' => $minor,
723  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
724  'img_sha1' => $this->sha1,
725  ],
726  [ 'img_name' => $this->getName() ],
727  __METHOD__
728  );
729 
730  $this->invalidateCache();
731 
732  $this->unlock();
733  $this->upgraded = true; // avoid rework/retries
734  }
735 
746  protected function setProps( $info ) {
747  $this->dataLoaded = true;
748  $fields = $this->getCacheFields( '' );
749  $fields[] = 'fileExists';
750 
751  foreach ( $fields as $field ) {
752  if ( isset( $info[$field] ) ) {
753  $this->$field = $info[$field];
754  }
755  }
756 
757  if ( isset( $info['user'] ) || isset( $info['user_text'] ) || isset( $info['actor'] ) ) {
758  $this->user = User::newFromAnyId(
759  $info['user'] ?? null,
760  $info['user_text'] ?? null,
761  $info['actor'] ?? null
762  );
763  }
764 
765  // Fix up mime fields
766  if ( isset( $info['major_mime'] ) ) {
767  $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
768  } elseif ( isset( $info['mime'] ) ) {
769  $this->mime = $info['mime'];
770  list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
771  }
772  }
773 
788  public function isMissing() {
789  if ( $this->missing === null ) {
790  $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
791  $this->missing = !$fileExists;
792  }
793 
794  return $this->missing;
795  }
796 
803  public function getWidth( $page = 1 ) {
804  $page = (int)$page;
805  if ( $page < 1 ) {
806  $page = 1;
807  }
808 
809  $this->load();
810 
811  if ( $this->isMultipage() ) {
812  $handler = $this->getHandler();
813  if ( !$handler ) {
814  return 0;
815  }
816  $dim = $handler->getPageDimensions( $this, $page );
817  if ( $dim ) {
818  return $dim['width'];
819  } else {
820  // For non-paged media, the false goes through an
821  // intval, turning failure into 0, so do same here.
822  return 0;
823  }
824  } else {
825  return $this->width;
826  }
827  }
828 
835  public function getHeight( $page = 1 ) {
836  $page = (int)$page;
837  if ( $page < 1 ) {
838  $page = 1;
839  }
840 
841  $this->load();
842 
843  if ( $this->isMultipage() ) {
844  $handler = $this->getHandler();
845  if ( !$handler ) {
846  return 0;
847  }
848  $dim = $handler->getPageDimensions( $this, $page );
849  if ( $dim ) {
850  return $dim['height'];
851  } else {
852  // For non-paged media, the false goes through an
853  // intval, turning failure into 0, so do same here.
854  return 0;
855  }
856  } else {
857  return $this->height;
858  }
859  }
860 
868  public function getUser( $type = 'text' ) {
869  $this->load();
870 
871  if ( !$this->user ) {
872  // If the file does not exist, $this->user will be null, see T221812.
873  // Note: 'Unknown user' this is a reserved user name.
874  if ( $type === 'object' ) {
875  return User::newFromName( 'Unknown user', false );
876  } elseif ( $type === 'text' ) {
877  return 'Unknown user';
878  } elseif ( $type === 'id' ) {
879  return 0;
880  }
881  } else {
882  if ( $type === 'object' ) {
883  return $this->user;
884  } elseif ( $type === 'text' ) {
885  return $this->user->getName();
886  } elseif ( $type === 'id' ) {
887  return $this->user->getId();
888  }
889  }
890 
891  throw new MWException( "Unknown type '$type'." );
892  }
893 
900  public function getDescriptionShortUrl() {
901  if ( !$this->title ) {
902  return null; // Avoid hard failure when the file does not exist. T221812
903  }
904 
905  $pageId = $this->title->getArticleID();
906 
907  if ( $pageId ) {
908  $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
909  if ( $url !== false ) {
910  return $url;
911  }
912  }
913  return null;
914  }
915 
920  public function getMetadata() {
921  $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
922  return $this->metadata;
923  }
924 
928  public function getBitDepth() {
929  $this->load();
930 
931  return (int)$this->bits;
932  }
933 
938  public function getSize() {
939  $this->load();
940 
941  return $this->size;
942  }
943 
948  public function getMimeType() {
949  $this->load();
950 
951  return $this->mime;
952  }
953 
959  public function getMediaType() {
960  $this->load();
961 
962  return $this->media_type;
963  }
964 
975  public function exists() {
976  $this->load();
977 
978  return $this->fileExists;
979  }
980 
996  protected function getThumbnails( $archiveName = false ) {
997  if ( $archiveName ) {
998  $dir = $this->getArchiveThumbPath( $archiveName );
999  } else {
1000  $dir = $this->getThumbPath();
1001  }
1002 
1003  $backend = $this->repo->getBackend();
1004  $files = [ $dir ];
1005  try {
1006  $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1007  if ( $iterator !== null ) {
1008  foreach ( $iterator as $file ) {
1009  $files[] = $file;
1010  }
1011  }
1012  } catch ( FileBackendError $e ) {
1013  } // suppress (T56674)
1014 
1015  return $files;
1016  }
1017 
1021  private function purgeMetadataCache() {
1022  $this->invalidateCache();
1023  }
1024 
1032  public function purgeCache( $options = [] ) {
1033  // Refresh metadata cache
1034  $this->maybeUpgradeRow();
1035  $this->purgeMetadataCache();
1036 
1037  // Delete thumbnails
1038  $this->purgeThumbnails( $options );
1039 
1040  // Purge CDN cache for this file
1041  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1042  $hcu->purgeUrls(
1043  $this->getUrl(),
1044  !empty( $options['forThumbRefresh'] )
1045  ? $hcu::PURGE_PRESEND // just a manual purge
1046  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1047  );
1048  }
1049 
1054  public function purgeOldThumbnails( $archiveName ) {
1055  // Get a list of old thumbnails and URLs
1056  $files = $this->getThumbnails( $archiveName );
1057 
1058  // Purge any custom thumbnail caches
1059  $this->hookRunner->onLocalFilePurgeThumbnails( $this, $archiveName );
1060 
1061  // Delete thumbnails
1062  $dir = array_shift( $files );
1063  $this->purgeThumbList( $dir, $files );
1064 
1065  // Purge the CDN
1066  $urls = [];
1067  foreach ( $files as $file ) {
1068  $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1069  }
1070 
1071  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1072  $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1073  }
1074 
1080  public function purgeThumbnails( $options = [] ) {
1081  $files = $this->getThumbnails();
1082  // Always purge all files from CDN regardless of handler filters
1083  $urls = [];
1084  foreach ( $files as $file ) {
1085  $urls[] = $this->getThumbUrl( $file );
1086  }
1087  array_shift( $urls ); // don't purge directory
1088 
1089  // Give media handler a chance to filter the file purge list
1090  if ( !empty( $options['forThumbRefresh'] ) ) {
1091  $handler = $this->getHandler();
1092  if ( $handler ) {
1093  $handler->filterThumbnailPurgeList( $files, $options );
1094  }
1095  }
1096 
1097  // Purge any custom thumbnail caches
1098  $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false );
1099 
1100  // Delete thumbnails
1101  $dir = array_shift( $files );
1102  $this->purgeThumbList( $dir, $files );
1103 
1104  // Purge the CDN
1105  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1106  $hcu->purgeUrls(
1107  $urls,
1108  !empty( $options['forThumbRefresh'] )
1109  ? $hcu::PURGE_PRESEND // just a manual purge
1110  : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1111  );
1112  }
1113 
1119  public function prerenderThumbnails() {
1121 
1122  $jobs = [];
1123 
1124  $sizes = $wgUploadThumbnailRenderMap;
1125  rsort( $sizes );
1126 
1127  foreach ( $sizes as $size ) {
1128  if ( $this->isVectorized() || $this->getWidth() > $size ) {
1129  $jobs[] = new ThumbnailRenderJob(
1130  $this->getTitle(),
1131  [ 'transformParams' => [ 'width' => $size ] ]
1132  );
1133  }
1134  }
1135 
1136  if ( $jobs ) {
1137  JobQueueGroup::singleton()->lazyPush( $jobs );
1138  }
1139  }
1140 
1146  protected function purgeThumbList( $dir, $files ) {
1147  $fileListDebug = strtr(
1148  var_export( $files, true ),
1149  [ "\n" => '' ]
1150  );
1151  wfDebug( __METHOD__ . ": $fileListDebug" );
1152 
1153  $purgeList = [];
1154  foreach ( $files as $file ) {
1155  if ( $this->repo->supportsSha1URLs() ) {
1156  $reference = $this->getSha1();
1157  } else {
1158  $reference = $this->getName();
1159  }
1160 
1161  # Check that the reference (filename or sha1) is part of the thumb name
1162  # This is a basic sanity check to avoid erasing unrelated directories
1163  if ( strpos( $file, $reference ) !== false
1164  || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1165  ) {
1166  $purgeList[] = "{$dir}/{$file}";
1167  }
1168  }
1169 
1170  # Delete the thumbnails
1171  $this->repo->quickPurgeBatch( $purgeList );
1172  # Clear out the thumbnail directory if empty
1173  $this->repo->quickCleanDir( $dir );
1174  }
1175 
1186  public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1187  if ( !$this->exists() ) {
1188  return []; // Avoid hard failure when the file does not exist. T221812
1189  }
1190 
1191  $dbr = $this->repo->getReplicaDB();
1192  $oldFileQuery = OldLocalFile::getQueryInfo();
1193 
1194  $tables = $oldFileQuery['tables'];
1195  $fields = $oldFileQuery['fields'];
1196  $join_conds = $oldFileQuery['joins'];
1197  $conds = $opts = [];
1198  $eq = $inc ? '=' : '';
1199  $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1200 
1201  if ( $start ) {
1202  $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1203  }
1204 
1205  if ( $end ) {
1206  $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1207  }
1208 
1209  if ( $limit ) {
1210  $opts['LIMIT'] = $limit;
1211  }
1212 
1213  // Search backwards for time > x queries
1214  $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1215  $opts['ORDER BY'] = "oi_timestamp $order";
1216  $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1217 
1218  $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1219  $conds, $opts, $join_conds );
1220 
1221  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1222  $r = [];
1223 
1224  foreach ( $res as $row ) {
1225  $r[] = $this->repo->newFileFromRow( $row );
1226  }
1227 
1228  if ( $order == 'ASC' ) {
1229  $r = array_reverse( $r ); // make sure it ends up descending
1230  }
1231 
1232  return $r;
1233  }
1234 
1244  public function nextHistoryLine() {
1245  if ( !$this->exists() ) {
1246  return false; // Avoid hard failure when the file does not exist. T221812
1247  }
1248 
1249  # Polymorphic function name to distinguish foreign and local fetches
1250  $fname = static::class . '::' . __FUNCTION__;
1251 
1252  $dbr = $this->repo->getReplicaDB();
1253 
1254  if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1255  $fileQuery = self::getQueryInfo();
1256  $this->historyRes = $dbr->select( $fileQuery['tables'],
1257  $fileQuery['fields'] + [
1258  'oi_archive_name' => $dbr->addQuotes( '' ),
1259  'oi_deleted' => 0,
1260  ],
1261  [ 'img_name' => $this->title->getDBkey() ],
1262  $fname,
1263  [],
1264  $fileQuery['joins']
1265  );
1266 
1267  if ( $dbr->numRows( $this->historyRes ) == 0 ) {
1268  $this->historyRes = null;
1269 
1270  return false;
1271  }
1272  } elseif ( $this->historyLine == 1 ) {
1273  $fileQuery = OldLocalFile::getQueryInfo();
1274  $this->historyRes = $dbr->select(
1275  $fileQuery['tables'],
1276  $fileQuery['fields'],
1277  [ 'oi_name' => $this->title->getDBkey() ],
1278  $fname,
1279  [ 'ORDER BY' => 'oi_timestamp DESC' ],
1280  $fileQuery['joins']
1281  );
1282  }
1283  $this->historyLine++;
1284 
1285  return $dbr->fetchObject( $this->historyRes );
1286  }
1287 
1291  public function resetHistory() {
1292  $this->historyLine = 0;
1293 
1294  if ( $this->historyRes !== null ) {
1295  $this->historyRes = null;
1296  }
1297  }
1298 
1332  public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1333  $timestamp = false, $user = null, $tags = [],
1334  $createNullRevision = true, $revert = false
1335  ) {
1336  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1337  return $this->readOnlyFatalStatus();
1338  } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1339  // Check this in advance to avoid writing to FileBackend and the file tables,
1340  // only to fail on insert the revision due to the text store being unavailable.
1341  return $this->readOnlyFatalStatus();
1342  }
1343 
1344  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1345  if ( !$props ) {
1346  if ( FileRepo::isVirtualUrl( $srcPath )
1347  || FileBackend::isStoragePath( $srcPath )
1348  ) {
1349  $props = $this->repo->getFileProps( $srcPath );
1350  } else {
1351  $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1352  $props = $mwProps->getPropsFromPath( $srcPath, true );
1353  }
1354  }
1355 
1356  $options = [];
1357  $handler = MediaHandler::getHandler( $props['mime'] );
1358  if ( $handler ) {
1359  $metadata = AtEase::quietCall( 'unserialize', $props['metadata'] );
1360 
1361  if ( !is_array( $metadata ) ) {
1362  $metadata = [];
1363  }
1364 
1365  $options['headers'] = $handler->getContentHeaders( $metadata );
1366  } else {
1367  $options['headers'] = [];
1368  }
1369 
1370  // Trim spaces on user supplied text
1371  $comment = trim( $comment );
1372 
1373  $this->lock();
1374  $status = $this->publish( $src, $flags, $options );
1375 
1376  if ( $status->successCount >= 2 ) {
1377  // There will be a copy+(one of move,copy,store).
1378  // The first succeeding does not commit us to updating the DB
1379  // since it simply copied the current version to a timestamped file name.
1380  // It is only *preferable* to avoid leaving such files orphaned.
1381  // Once the second operation goes through, then the current version was
1382  // updated and we must therefore update the DB too.
1383  $oldver = $status->value;
1384  $uploadStatus = $this->recordUpload2(
1385  $oldver,
1386  $comment,
1387  $pageText,
1388  $props,
1389  $timestamp,
1390  $user,
1391  $tags,
1392  $createNullRevision,
1393  $revert
1394  );
1395  if ( !$uploadStatus->isOK() ) {
1396  if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1397  // update filenotfound error with more specific path
1398  $status->fatal( 'filenotfound', $srcPath );
1399  } else {
1400  $status->merge( $uploadStatus );
1401  }
1402  }
1403  }
1404 
1405  $this->unlock();
1406  return $status;
1407  }
1408 
1421  public function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1422  $watch = false, $timestamp = false, User $user = null ) {
1423  if ( !$user ) {
1424  global $wgUser;
1425  $user = $wgUser;
1426  }
1427 
1428  $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1429 
1430  if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1431  return false;
1432  }
1433 
1434  if ( $watch ) {
1435  $user->addWatch( $this->getTitle() );
1436  }
1437 
1438  return true;
1439  }
1440 
1455  public function recordUpload2(
1456  $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1457  $createNullRevision = true, $revert = false
1458  ) {
1459  if ( $user === null ) {
1460  global $wgUser;
1461  $user = $wgUser;
1462  }
1463 
1464  $dbw = $this->repo->getMasterDB();
1465 
1466  # Imports or such might force a certain timestamp; otherwise we generate
1467  # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1468  if ( $timestamp === false ) {
1469  $timestamp = $dbw->timestamp();
1470  $allowTimeKludge = true;
1471  } else {
1472  $allowTimeKludge = false;
1473  }
1474 
1475  $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1476  $props['description'] = $comment;
1477  $props['user'] = $user->getId();
1478  $props['user_text'] = $user->getName();
1479  $props['actor'] = $user->getActorId( $dbw );
1480  $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1481  $this->setProps( $props );
1482 
1483  # Fail now if the file isn't there
1484  if ( !$this->fileExists ) {
1485  wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1486 
1487  return Status::newFatal( 'filenotfound', $this->getRel() );
1488  }
1489 
1490  $dbw->startAtomic( __METHOD__ );
1491 
1492  # Test to see if the row exists using INSERT IGNORE
1493  # This avoids race conditions by locking the row until the commit, and also
1494  # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1495  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1496  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1497  $actorMigration = ActorMigration::newMigration();
1498  $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1499  $dbw->insert( 'image',
1500  [
1501  'img_name' => $this->getName(),
1502  'img_size' => $this->size,
1503  'img_width' => intval( $this->width ),
1504  'img_height' => intval( $this->height ),
1505  'img_bits' => $this->bits,
1506  'img_media_type' => $this->media_type,
1507  'img_major_mime' => $this->major_mime,
1508  'img_minor_mime' => $this->minor_mime,
1509  'img_timestamp' => $timestamp,
1510  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1511  'img_sha1' => $this->sha1
1512  ] + $commentFields + $actorFields,
1513  __METHOD__,
1514  [ 'IGNORE' ]
1515  );
1516  $reupload = ( $dbw->affectedRows() == 0 );
1517 
1518  if ( $reupload ) {
1519  $row = $dbw->selectRow(
1520  'image',
1521  [ 'img_timestamp', 'img_sha1' ],
1522  [ 'img_name' => $this->getName() ],
1523  __METHOD__,
1524  [ 'LOCK IN SHARE MODE' ]
1525  );
1526 
1527  if ( $row && $row->img_sha1 === $this->sha1 ) {
1528  $dbw->endAtomic( __METHOD__ );
1529  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1530  $title = Title::newFromText( $this->getName(), NS_FILE );
1531  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1532  }
1533 
1534  if ( $allowTimeKludge ) {
1535  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1536  $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1537  # Avoid a timestamp that is not newer than the last version
1538  # TODO: the image/oldimage tables should be like page/revision with an ID field
1539  if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1540  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1541  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1542  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1543  }
1544  }
1545 
1546  $tables = [ 'image' ];
1547  $fields = [
1548  'oi_name' => 'img_name',
1549  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1550  'oi_size' => 'img_size',
1551  'oi_width' => 'img_width',
1552  'oi_height' => 'img_height',
1553  'oi_bits' => 'img_bits',
1554  'oi_description_id' => 'img_description_id',
1555  'oi_timestamp' => 'img_timestamp',
1556  'oi_metadata' => 'img_metadata',
1557  'oi_media_type' => 'img_media_type',
1558  'oi_major_mime' => 'img_major_mime',
1559  'oi_minor_mime' => 'img_minor_mime',
1560  'oi_sha1' => 'img_sha1',
1561  'oi_actor' => 'img_actor',
1562  ];
1563  $joins = [];
1564 
1565  # (T36993) Note: $oldver can be empty here, if the previous
1566  # version of the file was broken. Allow registration of the new
1567  # version to continue anyway, because that's better than having
1568  # an image that's not fixable by user operations.
1569  # Collision, this is an update of a file
1570  # Insert previous contents into oldimage
1571  $dbw->insertSelect( 'oldimage', $tables, $fields,
1572  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1573 
1574  # Update the current image row
1575  $dbw->update( 'image',
1576  [
1577  'img_size' => $this->size,
1578  'img_width' => intval( $this->width ),
1579  'img_height' => intval( $this->height ),
1580  'img_bits' => $this->bits,
1581  'img_media_type' => $this->media_type,
1582  'img_major_mime' => $this->major_mime,
1583  'img_minor_mime' => $this->minor_mime,
1584  'img_timestamp' => $timestamp,
1585  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1586  'img_sha1' => $this->sha1
1587  ] + $commentFields + $actorFields,
1588  [ 'img_name' => $this->getName() ],
1589  __METHOD__
1590  );
1591  }
1592 
1593  $descTitle = $this->getTitle();
1594  $descId = $descTitle->getArticleID();
1595  $wikiPage = new WikiFilePage( $descTitle );
1596  $wikiPage->setFile( $this );
1597 
1598  // Determine log action. If reupload is done by reverting, use a special log_action.
1599  if ( $revert === true ) {
1600  $logAction = 'revert';
1601  } elseif ( $reupload === true ) {
1602  $logAction = 'overwrite';
1603  } else {
1604  $logAction = 'upload';
1605  }
1606  // Add the log entry...
1607  $logEntry = new ManualLogEntry( 'upload', $logAction );
1608  $logEntry->setTimestamp( $this->timestamp );
1609  $logEntry->setPerformer( $user );
1610  $logEntry->setComment( $comment );
1611  $logEntry->setTarget( $descTitle );
1612  // Allow people using the api to associate log entries with the upload.
1613  // Log has a timestamp, but sometimes different from upload timestamp.
1614  $logEntry->setParameters(
1615  [
1616  'img_sha1' => $this->sha1,
1617  'img_timestamp' => $timestamp,
1618  ]
1619  );
1620  // Note we keep $logId around since during new image
1621  // creation, page doesn't exist yet, so log_page = 0
1622  // but we want it to point to the page we're making,
1623  // so we later modify the log entry.
1624  // For a similar reason, we avoid making an RC entry
1625  // now and wait until the page exists.
1626  $logId = $logEntry->insert();
1627 
1628  if ( $descTitle->exists() ) {
1629  if ( $createNullRevision !== false ) {
1630  $revStore = MediaWikiServices::getInstance()->getRevisionStore();
1631  // Use own context to get the action text in content language
1632  $formatter = LogFormatter::newFromEntry( $logEntry );
1633  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1634  $editSummary = $formatter->getPlainActionText();
1635  $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1636  $nullRevRecord = $revStore->newNullRevision(
1637  $dbw,
1638  $descTitle,
1639  $summary,
1640  false,
1641  $user
1642  );
1643 
1644  if ( $nullRevRecord ) {
1645  $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1646 
1647  $this->getHookRunner()->onRevisionFromEditComplete(
1648  $wikiPage,
1649  $inserted,
1650  $inserted->getParentId(),
1651  $user,
1652  $tags
1653  );
1654 
1655  // TODO hard deprecate
1656  $nullRevision = new Revision( $inserted );
1657  $this->getHookRunner()->onNewRevisionFromEditComplete(
1658  $wikiPage,
1659  $nullRevision,
1660  $inserted->getParentId(),
1661  $user,
1662  $tags
1663  );
1664  $wikiPage->updateRevisionOn( $dbw, $inserted );
1665  // Associate null revision id
1666  $logEntry->setAssociatedRevId( $inserted->getId() );
1667  }
1668  }
1669 
1670  $newPageContent = null;
1671  } else {
1672  // Make the description page and RC log entry post-commit
1673  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1674  }
1675 
1676  # Defer purges, page creation, and link updates in case they error out.
1677  # The most important thing is that files and the DB registry stay synced.
1678  $dbw->endAtomic( __METHOD__ );
1679  $fname = __METHOD__;
1680 
1681  # Do some cache purges after final commit so that:
1682  # a) Changes are more likely to be seen post-purge
1683  # b) They won't cause rollback of the log publish/update above
1685  new AutoCommitUpdate(
1686  $dbw,
1687  __METHOD__,
1689  function () use (
1690  $reupload, $wikiPage, $newPageContent, $comment, $user,
1691  $logEntry, $logId, $descId, $tags, $fname
1692  ) {
1693  # Update memcache after the commit
1694  $this->invalidateCache();
1695 
1696  $updateLogPage = false;
1697  if ( $newPageContent ) {
1698  # New file page; create the description page.
1699  # There's already a log entry, so don't make a second RC entry
1700  # CDN and file cache for the description page are purged by doEditContent.
1701  $status = $wikiPage->doEditContent(
1702  $newPageContent,
1703  $comment,
1705  false,
1706  $user
1707  );
1708 
1709  if ( isset( $status->value['revision'] ) ) {
1711  $rev = $status->value['revision'];
1712  // Associate new page revision id
1713  $logEntry->setAssociatedRevId( $rev->getId() );
1714  }
1715  // This relies on the resetArticleID() call in WikiPage::insertOn(),
1716  // which is triggered on $descTitle by doEditContent() above.
1717  if ( isset( $status->value['revision'] ) ) {
1719  $rev = $status->value['revision'];
1720  $updateLogPage = $rev->getPage();
1721  }
1722  } else {
1723  # Existing file page: invalidate description page cache
1724  $title = $wikiPage->getTitle();
1726  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1727  $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1728  # Allow the new file version to be patrolled from the page footer
1730  }
1731 
1732  # Update associated rev id. This should be done by $logEntry->insert() earlier,
1733  # but setAssociatedRevId() wasn't called at that point yet...
1734  $logParams = $logEntry->getParameters();
1735  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1736  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1737  if ( $updateLogPage ) {
1738  # Also log page, in case where we just created it above
1739  $update['log_page'] = $updateLogPage;
1740  }
1741  $this->getRepo()->getMasterDB()->update(
1742  'logging',
1743  $update,
1744  [ 'log_id' => $logId ],
1745  $fname
1746  );
1747  $this->getRepo()->getMasterDB()->insert(
1748  'log_search',
1749  [
1750  'ls_field' => 'associated_rev_id',
1751  'ls_value' => (string)$logEntry->getAssociatedRevId(),
1752  'ls_log_id' => $logId,
1753  ],
1754  $fname
1755  );
1756 
1757  # Add change tags, if any
1758  if ( $tags ) {
1759  $logEntry->addTags( $tags );
1760  }
1761 
1762  # Uploads can be patrolled
1763  $logEntry->setIsPatrollable( true );
1764 
1765  # Now that the log entry is up-to-date, make an RC entry.
1766  $logEntry->publish( $logId );
1767 
1768  # Run hook for other updates (typically more cache purging)
1769  $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
1770 
1771  if ( $reupload ) {
1772  # Delete old thumbnails
1773  $this->purgeThumbnails();
1774  # Remove the old file from the CDN cache
1775  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1776  $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1777  } else {
1778  # Update backlink pages pointing to this title if created
1780  $this->getTitle(),
1781  'imagelinks',
1782  'upload-image',
1783  $user->getName()
1784  );
1785  }
1786 
1787  $this->prerenderThumbnails();
1788  }
1789  ),
1791  );
1792 
1793  if ( !$reupload ) {
1794  # This is a new file, so update the image count
1795  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1796  }
1797 
1798  # Invalidate cache for all pages using this file
1800  $this->getTitle(),
1801  'imagelinks',
1802  [ 'causeAction' => 'file-upload', 'causeAgent' => $user->getName() ]
1803  );
1804  JobQueueGroup::singleton()->lazyPush( $job );
1805 
1806  return Status::newGood();
1807  }
1808 
1824  public function publish( $src, $flags = 0, array $options = [] ) {
1825  return $this->publishTo( $src, $this->getRel(), $flags, $options );
1826  }
1827 
1843  protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1844  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1845 
1846  $repo = $this->getRepo();
1847  if ( $repo->getReadOnlyReason() !== false ) {
1848  return $this->readOnlyFatalStatus();
1849  }
1850 
1851  $this->lock();
1852 
1853  if ( $this->isOld() ) {
1854  $archiveRel = $dstRel;
1855  $archiveName = basename( $archiveRel );
1856  } else {
1857  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1858  $archiveRel = $this->getArchiveRel( $archiveName );
1859  }
1860 
1861  if ( $repo->hasSha1Storage() ) {
1862  $sha1 = FileRepo::isVirtualUrl( $srcPath )
1863  ? $repo->getFileSha1( $srcPath )
1864  : FSFile::getSha1Base36FromPath( $srcPath );
1866  $wrapperBackend = $repo->getBackend();
1867  '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
1868  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1869  $status = $repo->quickImport( $src, $dst );
1870  if ( $flags & File::DELETE_SOURCE ) {
1871  unlink( $srcPath );
1872  }
1873 
1874  if ( $this->exists() ) {
1875  $status->value = $archiveName;
1876  }
1877  } else {
1878  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1879  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1880 
1881  if ( $status->value == 'new' ) {
1882  $status->value = '';
1883  } else {
1884  $status->value = $archiveName;
1885  }
1886  }
1887 
1888  $this->unlock();
1889  return $status;
1890  }
1891 
1909  public function move( $target ) {
1910  $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
1911  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1912  return $this->readOnlyFatalStatus();
1913  }
1914 
1915  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1916  $batch = new LocalFileMoveBatch( $this, $target );
1917 
1918  $this->lock();
1919  $batch->addCurrent();
1920  $archiveNames = $batch->addOlds();
1921  $status = $batch->execute();
1922  $this->unlock();
1923 
1924  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1925 
1926  // Purge the source and target files outside the transaction...
1927  $oldTitleFile = $localRepo->newFile( $this->title );
1928  $newTitleFile = $localRepo->newFile( $target );
1930  new AutoCommitUpdate(
1931  $this->getRepo()->getMasterDB(),
1932  __METHOD__,
1933  function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1934  $oldTitleFile->purgeEverything();
1935  foreach ( $archiveNames as $archiveName ) {
1937  '@phan-var OldLocalFile $oldTitleFile';
1938  $oldTitleFile->purgeOldThumbnails( $archiveName );
1939  }
1940  $newTitleFile->purgeEverything();
1941  }
1942  ),
1944  );
1945 
1946  if ( $status->isOK() ) {
1947  // Now switch the object
1948  $this->title = $target;
1949  // Force regeneration of the name and hashpath
1950  $this->name = null;
1951  $this->hashPath = null;
1952  }
1953 
1954  return $status;
1955  }
1956 
1972  public function delete( $reason, $suppress = false, $user = null ) {
1973  wfDeprecated( __METHOD__, '1.35' );
1974  if ( $user === null ) {
1975  global $wgUser;
1976  $user = $wgUser;
1977  }
1978  return $this->deleteFile( $reason, $user, $suppress );
1979  }
1980 
1996  public function deleteFile( $reason, User $user, $suppress = false ) {
1997  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1998  return $this->readOnlyFatalStatus();
1999  }
2000 
2001  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2002 
2003  $this->lock();
2004  $batch->addCurrent();
2005  // Get old version relative paths
2006  $archiveNames = $batch->addOlds();
2007  $status = $batch->execute();
2008  $this->unlock();
2009 
2010  if ( $status->isOK() ) {
2011  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2012  }
2013 
2014  // To avoid slow purges in the transaction, move them outside...
2016  new AutoCommitUpdate(
2017  $this->getRepo()->getMasterDB(),
2018  __METHOD__,
2019  function () use ( $archiveNames ) {
2020  $this->purgeEverything();
2021  foreach ( $archiveNames as $archiveName ) {
2022  $this->purgeOldThumbnails( $archiveName );
2023  }
2024  }
2025  ),
2027  );
2028 
2029  // Purge the CDN
2030  $purgeUrls = [];
2031  foreach ( $archiveNames as $archiveName ) {
2032  $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2033  }
2034 
2035  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2036  $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2037 
2038  return $status;
2039  }
2040 
2058  public function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2059  wfDeprecated( __METHOD__, '1.35' );
2060  if ( $user === null ) {
2061  global $wgUser;
2062  $user = $wgUser;
2063  }
2064  return $this->deleteOldFile( $archiveName, $reason, $user, $suppress );
2065  }
2066 
2084  public function deleteOldFile( $archiveName, $reason, User $user, $suppress = false ) {
2085  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2086  return $this->readOnlyFatalStatus();
2087  }
2088 
2089  $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2090 
2091  $this->lock();
2092  $batch->addOld( $archiveName );
2093  $status = $batch->execute();
2094  $this->unlock();
2095 
2096  $this->purgeOldThumbnails( $archiveName );
2097  if ( $status->isOK() ) {
2098  $this->purgeDescription();
2099  }
2100 
2101  $url = $this->getArchiveUrl( $archiveName );
2102  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2103  $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2104 
2105  return $status;
2106  }
2107 
2119  public function restore( $versions = [], $unsuppress = false ) {
2120  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2121  return $this->readOnlyFatalStatus();
2122  }
2123 
2124  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2125 
2126  $this->lock();
2127  if ( !$versions ) {
2128  $batch->addAll();
2129  } else {
2130  $batch->addIds( $versions );
2131  }
2132  $status = $batch->execute();
2133  if ( $status->isGood() ) {
2134  $cleanupStatus = $batch->cleanup();
2135  $cleanupStatus->successCount = 0;
2136  $cleanupStatus->failCount = 0;
2137  $status->merge( $cleanupStatus );
2138  }
2139 
2140  $this->unlock();
2141  return $status;
2142  }
2143 
2153  public function getDescriptionUrl() {
2154  if ( !$this->title ) {
2155  return false; // Avoid hard failure when the file does not exist. T221812
2156  }
2157 
2158  return $this->title->getLocalURL();
2159  }
2160 
2169  public function getDescriptionText( Language $lang = null ) {
2170  if ( !$this->title ) {
2171  return false; // Avoid hard failure when the file does not exist. T221812
2172  }
2173 
2174  $store = MediaWikiServices::getInstance()->getRevisionStore();
2175  $revision = $store->getRevisionByTitle( $this->title, 0, Revision::READ_NORMAL );
2176  if ( !$revision ) {
2177  return false;
2178  }
2179 
2180  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2181  $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2182 
2183  if ( !$rendered ) {
2184  // audience check failed
2185  return false;
2186  }
2187 
2188  $pout = $rendered->getRevisionParserOutput();
2189  return $pout->getText();
2190  }
2191 
2197  public function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2198  $this->load();
2199  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2200  return '';
2201  } elseif ( $audience == self::FOR_THIS_USER
2202  && !$this->userCan( self::DELETED_COMMENT, $user )
2203  ) {
2204  return '';
2205  } else {
2206  return $this->description;
2207  }
2208  }
2209 
2213  public function getTimestamp() {
2214  $this->load();
2215 
2216  return $this->timestamp;
2217  }
2218 
2222  public function getDescriptionTouched() {
2223  if ( !$this->exists() ) {
2224  return false; // Avoid hard failure when the file does not exist. T221812
2225  }
2226 
2227  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2228  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2229  // need to differentiate between null (uninitialized) and false (failed to load).
2230  if ( $this->descriptionTouched === null ) {
2231  $cond = [
2232  'page_namespace' => $this->title->getNamespace(),
2233  'page_title' => $this->title->getDBkey()
2234  ];
2235  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2236  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2237  }
2238 
2240  }
2241 
2245  public function getSha1() {
2246  $this->load();
2247  // Initialise now if necessary
2248  if ( $this->sha1 == '' && $this->fileExists ) {
2249  $this->lock();
2250 
2251  $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2252  if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2253  $dbw = $this->repo->getMasterDB();
2254  $dbw->update( 'image',
2255  [ 'img_sha1' => $this->sha1 ],
2256  [ 'img_name' => $this->getName() ],
2257  __METHOD__ );
2258  $this->invalidateCache();
2259  }
2260 
2261  $this->unlock();
2262  }
2263 
2264  return $this->sha1;
2265  }
2266 
2270  public function isCacheable() {
2271  $this->load();
2272 
2273  // If extra data (metadata) was not loaded then it must have been large
2274  return $this->extraDataLoaded
2275  && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
2276  }
2277 
2282  public function acquireFileLock() {
2283  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2284  [ $this->getPath() ], LockManager::LOCK_EX, 10
2285  ) );
2286  }
2287 
2292  public function releaseFileLock() {
2293  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2294  [ $this->getPath() ], LockManager::LOCK_EX
2295  ) );
2296  }
2297 
2307  public function lock() {
2308  if ( !$this->locked ) {
2309  $logger = LoggerFactory::getInstance( 'LocalFile' );
2310 
2311  $dbw = $this->repo->getMasterDB();
2312  $makesTransaction = !$dbw->trxLevel();
2313  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2314  // T56736: use simple lock to handle when the file does not exist.
2315  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2316  // Also, that would cause contention on INSERT of similarly named rows.
2317  $status = $this->acquireFileLock(); // represents all versions of the file
2318  if ( !$status->isGood() ) {
2319  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2320  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2321 
2322  throw new LocalFileLockError( $status );
2323  }
2324  // Release the lock *after* commit to avoid row-level contention.
2325  // Make sure it triggers on rollback() as well as commit() (T132921).
2326  $dbw->onTransactionResolution(
2327  function () use ( $logger ) {
2328  $status = $this->releaseFileLock();
2329  if ( !$status->isGood() ) {
2330  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2331  }
2332  },
2333  __METHOD__
2334  );
2335  // Callers might care if the SELECT snapshot is safely fresh
2336  $this->lockedOwnTrx = $makesTransaction;
2337  }
2338 
2339  $this->locked++;
2340 
2341  return $this->lockedOwnTrx;
2342  }
2343 
2352  public function unlock() {
2353  if ( $this->locked ) {
2354  --$this->locked;
2355  if ( !$this->locked ) {
2356  $dbw = $this->repo->getMasterDB();
2357  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2358  $this->lockedOwnTrx = false;
2359  }
2360  }
2361  }
2362 
2366  protected function readOnlyFatalStatus() {
2367  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2368  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2369  }
2370 
2374  public function __destruct() {
2375  $this->unlock();
2376  }
2377 }
LocalFile\$media_type
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition: LocalFile.php:74
LocalFile\getSha1
getSha1()
Definition: LocalFile.php:2245
ParserOptions
Set options of the Parser.
Definition: ParserOptions.php:42
LocalFile\ATOMIC_SECTION_LOCK
const ATOMIC_SECTION_LOCK
Definition: LocalFile.php:142
LocalFile\$fileExists
bool $fileExists
Does the file exist on disk? (loadFromXxx)
Definition: LocalFile.php:62
File\getPath
getPath()
Return the storage path to the file.
Definition: File.php:430
$wgUpdateCompatibleMetadata
$wgUpdateCompatibleMetadata
If to automatically update the img_metadata field if the metadata field is outdated but compatible wi...
Definition: DefaultSettings.php:865
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:645
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:49
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:66
LocalFile\getMutableCacheKeys
getMutableCacheKeys(WANObjectCache $cache)
Definition: LocalFile.php:288
FileRepo\getReadOnlyReason
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition: FileRepo.php:253
LocalFile\unprefixRow
unprefixRow( $row, $prefix='img_')
Definition: LocalFile.php:539
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:332
File\$repo
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition: File.php:109
LocalFile\$width
int $width
Image width.
Definition: LocalFile.php:65
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:1667
LocalFile\deleteFile
deleteFile( $reason, User $user, $suppress=false)
Delete all versions of the file.
Definition: LocalFile.php:1996
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:69
LocalFile\__construct
__construct( $title, $repo)
Do not call this except from inside a repo class.
Definition: LocalFile.php:254
LocalFile\unlock
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero.
Definition: LocalFile.php:2352
User\getId
getId()
Get the user's ID.
Definition: User.php:2108
LocalFile\getTimestamp
getTimestamp()
Definition: LocalFile.php:2213
File\isMultipage
isMultipage()
Returns 'true' if this file is a type which supports multiple pages, e.g.
Definition: File.php:2049
LocalFile\getUser
getUser( $type='text')
Returns user who uploaded the file.
Definition: LocalFile.php:868
User\getActorId
getActorId(IDatabase $dbw=null)
Get the user's actor ID.
Definition: User.php:2176
LocalFile\getRepo
getRepo()
Definition: LocalFile.php:270
LocalFile\loadFromDB
loadFromDB( $flags=0)
Load file metadata from the DB.
Definition: LocalFile.php:429
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:146
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
LocalFile\purgeThumbList
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
Definition: LocalFile.php:1146
File\getRel
getRel()
Get the path of the file relative to the public zone root.
Definition: File.php:1583
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:120
LocalFile\$missing
bool $missing
True if file is not present in file system.
Definition: LocalFile.php:137
LocalFileDeleteBatch
Helper class for file deletion.
Definition: LocalFileDeleteBatch.php:31
MediaHandler\filterThumbnailPurgeList
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
Definition: MediaHandler.php:716
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1806
FileBackendError
File backend exception for checked exceptions (e.g.
Definition: FileBackendError.php:8
LocalFile\upload
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, $user=null, $tags=[], $createNullRevision=true, $revert=false)
getHashPath inherited
Definition: LocalFile.php:1332
LocalFile\$upgraded
bool $upgraded
Whether the row was upgraded on load.
Definition: LocalFile.php:125
LocalFile\getDescriptionShortUrl
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
Definition: LocalFile.php:900
LocalFile\getCacheFields
getCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache.
Definition: LocalFile.php:392
Title\getPrefixedText
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1854
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:1186
LocalFile\getMediaType
getMediaType()
Returns the type of the media in the file.
Definition: LocalFile.php:959
File\getUrl
getUrl()
Return the URL of the file.
Definition: File.php:361
LocalFile\$dataLoaded
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
Definition: LocalFile.php:89
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:2366
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:156
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1104
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
RequestContext\newExtraneousContext
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
Definition: RequestContext.php:621
LocalFile\$upgrading
bool $upgrading
Whether the row was scheduled to upgrade on load.
Definition: LocalFile.php:128
LocalFile\getSize
getSize()
Returns the size of the image file, in bytes.
Definition: LocalFile.php:938
LocalFile\purgeOldThumbnails
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
Definition: LocalFile.php:1054
LocalFile\getThumbnails
getThumbnails( $archiveName=false)
getTransformScript inherited
Definition: LocalFile.php:996
LocalFile\$sha1
string $sha1
SHA-1 base 36 content hash.
Definition: LocalFile.php:86
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:286
$res
$res
Definition: testCompression.php:57
serialize
serialize()
Definition: ApiMessageTrait.php:138
LocalFile\$minor_mime
string $minor_mime
Minor MIME type.
Definition: LocalFile.php:110
File\getArchiveRel
getArchiveRel( $suffix=false)
Get the path of an archived file relative to the public zone root.
Definition: File.php:1594
File\isDeleted
isDeleted( $field)
Is this file a "deleted" file in a private archive? STUB.
Definition: File.php:1942
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:992
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:139
HTMLCacheUpdateJob\newForBacklinks
static newForBacklinks(Title $title, $table, $params=[])
Definition: HTMLCacheUpdateJob.php:59
LocalFile\acquireFileLock
acquireFileLock()
Definition: LocalFile.php:2282
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:2270
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:1223
Revision
Definition: Revision.php:39
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:564
LocalFile\$bits
int $bits
Returned by getimagesize (loadFromXxx)
Definition: LocalFile.php:71
LocalFile\purgeThumbnails
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
Definition: LocalFile.php:1080
FileRepo\hasSha1Storage
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:1968
MediaHandler\METADATA_COMPATIBLE
const METADATA_COMPATIBLE
Definition: MediaHandler.php:39
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:62
LocalFile\loadExtraFromDB
loadExtraFromDB()
Load lazy file metadata from the DB.
Definition: LocalFile.php:461
LocalFile\publishTo
publishTo( $src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
Definition: LocalFile.php:1843
File\$url
string $url
The URL corresponding to one of the four basic zones.
Definition: File.php:130
MWException
MediaWiki exception.
Definition: MWException.php:26
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:169
LocalFile\getDescriptionTouched
getDescriptionTouched()
Definition: LocalFile.php:2222
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1030
LocalFile\purgeMetadataCache
purgeMetadataCache()
Refresh metadata in memcached, but don't touch thumbnails or CDN.
Definition: LocalFile.php:1021
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
File\getThumbPath
getThumbPath( $suffix=false)
Get the path of the thumbnail directory, or a particular file if $suffix is specified.
Definition: File.php:1680
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:1013
LocalFile\getUpgraded
getUpgraded()
Definition: LocalFile.php:684
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1524
LocalFile\deleteOld
deleteOld( $archiveName, $reason, $suppress=false, $user=null)
Delete an old version of the file.
Definition: LocalFile.php:2058
Status\wrap
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:60
LocalFile\CACHE_FIELD_MAX_LEN
const CACHE_FIELD_MAX_LEN
Definition: LocalFile.php:59
LocalFile\loadFromRow
loadFromRow( $row, $prefix='img_')
Load file metadata from a DB result row.
Definition: LocalFile.php:610
LocalFile\__destruct
__destruct()
Clean up any dangling locks.
Definition: LocalFile.php:2374
LocalFile\$deleted
int $deleted
Bitfield akin to rev_deleted.
Definition: LocalFile.php:95
$wgUploadThumbnailRenderMap
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
Definition: DefaultSettings.php:1589
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:104
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:2169
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.
Definition: LocalFile.php:1119
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:595
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:279
MediaHandler\getPageDimensions
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood,...
Definition: MediaHandler.php:409
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:616
$revStore
$revStore
Definition: testCompression.php:55
LocalFile\$mime
string $mime
MIME type, determined by MimeAnalyzer::guessMimeType.
Definition: LocalFile.php:77
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:913
LocalFile\setProps
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info.
Definition: LocalFile.php:746
FileRepo\getFileSha1
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1636
LocalFile
Class to represent a local file in the wiki's own database.
Definition: LocalFile.php:56
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:140
LocalFile\getMimeType
getMimeType()
Returns the MIME type of the file.
Definition: LocalFile.php:948
LocalFile\getDescription
getDescription( $audience=self::FOR_PUBLIC, User $user=null)
Definition: LocalFile.php:2197
$urls
$urls
Definition: opensearch_desc.php:82
LocalFile\$extraDataLoaded
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
Definition: LocalFile.php:92
ThumbnailRenderJob
Job for asynchronous rendering of thumbnails.
Definition: ThumbnailRenderJob.php:31
LocalFile\$size
int $size
Size in bytes (loadFromXxx)
Definition: LocalFile.php:80
File\purgeDescription
purgeDescription()
Purge the file description page, but don't go after pages using the file.
Definition: File.php:1495
LocalFile\LOAD_ALL
const LOAD_ALL
Definition: LocalFile.php:140
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:2307
File\isOld
isOld()
Returns true if the image is an old version STUB.
Definition: File.php:1931
File\$handler
MediaHandler $handler
Definition: File.php:127
LocalFileLockError
Definition: LocalFileLockError.php:24
File\assertTitleDefined
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition: File.php:2360
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
LocalFile\$historyLine
int $historyLine
Number of line to return by nextHistoryLine() (constructor)
Definition: LocalFile.php:101
LocalFile\releaseFileLock
releaseFileLock()
Definition: LocalFile.php:2292
LocalFile\upgradeRow
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file.
Definition: LocalFile.php:691
LocalFile\load
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
Definition: LocalFile.php:627
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:120
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:186
LocalFile\nextHistoryLine
nextHistoryLine()
Returns the history of this file, line by line.
Definition: LocalFile.php:1244
File\$title
Title string bool $title
Definition: File.php:112
User\addWatch
addWatch( $title, $checkRights=self::CHECK_USER_RIGHTS, ?string $expiry=null)
Watch an article.
Definition: User.php:3394
LocalFile\$metadata
string $metadata
Handler-specific metadata.
Definition: LocalFile.php:83
LocalFile\getBitDepth
getBitDepth()
Definition: LocalFile.php:928
LocalFile\$height
int $height
Image height.
Definition: LocalFile.php:68
LocalFile\$user
User $user
Uploader.
Definition: LocalFile.php:116
File\getArchiveThumbUrl
getArchiveThumbUrl( $archiveName, $suffix=false)
Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified.
Definition: File.php:1724
File\getName
getName()
Return the name of this file.
Definition: File.php:310
File\getArchiveUrl
getArchiveUrl( $suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified.
Definition: File.php:1704
FSFile
Class representing a non-directory file on the file system.
Definition: FSFile.php:32
LocalFile\$timestamp
string $timestamp
Upload timestamp.
Definition: LocalFile.php:113
FileRepo\getBackend
getBackend()
Get the file backend instance.
Definition: FileRepo.php:243
LocalFile\$descriptionTouched
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
Definition: LocalFile.php:122
File\DELETE_SOURCE
const DELETE_SOURCE
Definition: File.php:79
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:1421
EDIT_NEW
const EDIT_NEW
Definition: Defines.php:141
LocalFile\$locked
bool $locked
True if the image row is locked.
Definition: LocalFile.php:131
LocalFile\$description
string $description
Description of current revision of the file.
Definition: LocalFile.php:119
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:414
File\getTitle
getTitle()
Return the associated title object.
Definition: File.php:339
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:216
LocalFile\getMetadata
getMetadata()
Get handler-specific metadata.
Definition: LocalFile.php:920
LocalFile\deleteOldFile
deleteOldFile( $archiveName, $reason, User $user, $suppress=false)
Delete an old version of the file.
Definition: LocalFile.php:2084
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.
Definition: MediaHandler.php:931
$cache
$cache
Definition: mcc.php:33
LocalFile\loadFromFile
loadFromFile()
Load metadata from the file itself.
Definition: LocalFile.php:381
File\assertRepoDefined
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition: File.php:2350
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:1455
$job
if(count( $args)< 1) $job
Definition: recompressTracked.php:50
LocalFile\resetHistory
resetHistory()
Reset the history pointer to the first element of the history.
Definition: LocalFile.php:1291
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:51
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:282
LocalFile\loadExtraFieldsWithTimestamp
loadExtraFieldsWithTimestamp( $dbr, $fname)
Definition: LocalFile.php:490
LocalFileMoveBatch
Helper class for file movement.
Definition: LocalFileMoveBatch.php:31
MediaHandler\METADATA_BAD
const METADATA_BAD
Definition: MediaHandler.php:38
$source
$source
Definition: mwdoc-filter.php:34
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: ManualLogEntry.php:38
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:136
LocalFile\publish
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
Definition: LocalFile.php:1824
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:4111
LocalFile\getWidth
getWidth( $page=1)
Return the width of the image.
Definition: LocalFile.php:803
File\getThumbUrl
getThumbUrl( $suffix=false)
Get the URL of the thumbnail directory, or a particular file if $suffix is specified.
Definition: File.php:1760
LocalFile\$major_mime
string $major_mime
Major MIME type.
Definition: LocalFile.php:107
File\isVectorized
isVectorized()
Return true if the file is vectorized.
Definition: File.php:608
File\getHandler
getHandler()
Get a MediaHandler instance for this file.
Definition: File.php:1431
LockManager\LOCK_EX
const LOCK_EX
Definition: LockManager.php:70
LocalFile\getHeight
getHeight( $page=1)
Return the height of the image.
Definition: LocalFile.php:835
LocalFile\isMissing
isMissing()
splitMime inherited
Definition: LocalFile.php:788
LocalFile\invalidateCache
invalidateCache()
Purge the file object/metadata cache.
Definition: LocalFile.php:364
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:2238
LocalFile\$lockedOwnTrx
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
Definition: LocalFile.php:134
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:57
LocalFile\getDescriptionUrl
getDescriptionUrl()
isMultipage inherited
Definition: LocalFile.php:2153
LocalFile\move
move( $target)
getLinksTo inherited
Definition: LocalFile.php:1909
LocalFile\$repoClass
string $repoClass
Definition: LocalFile.php:98
MediaHandler\isMetadataValid
isMetadataValid( $image, $metadata)
Check if the metadata string is valid for this handler.
Definition: MediaHandler.php:203
User\getName
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2137
LocalFile\restore
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition: LocalFile.php:2119
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:1508
LocalFile\exists
exists()
canRender inherited
Definition: LocalFile.php:975
File\getThumbnails
getThumbnails()
Get all thumbnail names previously generated for this file STUB Overridden by LocalFile.
Definition: File.php:1476
LocalFile\loadFromCache
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
Definition: LocalFile.php:295
LocalFile\purgeCache
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
Definition: LocalFile.php:1032
File\getVirtualUrl
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
Definition: File.php:1780
LogFormatter\newFromEntry
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
Definition: LogFormatter.php:50
Article\purgePatrolFooterCache
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Definition: Article.php:1377
$type
$type
Definition: testCompression.php:52