MediaWiki  master
LocalFile.php
Go to the documentation of this file.
1 <?php
28 
46 class LocalFile extends File {
47  const VERSION = 11; // cache version
48 
49  const CACHE_FIELD_MAX_LEN = 1000;
50 
52  protected $fileExists;
53 
55  protected $width;
56 
58  protected $height;
59 
61  protected $bits;
62 
64  protected $media_type;
65 
67  protected $mime;
68 
70  protected $size;
71 
73  protected $metadata;
74 
76  protected $sha1;
77 
79  protected $dataLoaded;
80 
82  protected $extraDataLoaded;
83 
85  protected $deleted;
86 
89 
91  private $historyLine;
92 
94  private $historyRes;
95 
97  private $major_mime;
98 
100  private $minor_mime;
101 
103  private $timestamp;
104 
106  private $user;
107 
109  private $description;
110 
113 
115  private $upgraded;
116 
118  private $upgrading;
119 
121  private $locked;
122 
124  private $lockedOwnTrx;
125 
127  private $missing;
128 
129  // @note: higher than IDBAccessObject constants
130  const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
131 
132  const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
133 
146  static function newFromTitle( $title, $repo, $unused = null ) {
147  return new self( $title, $repo );
148  }
149 
159  static function newFromRow( $row, $repo ) {
160  $title = Title::makeTitle( NS_FILE, $row->img_name );
161  $file = new self( $title, $repo );
162  $file->loadFromRow( $row );
163 
164  return $file;
165  }
166 
176  static function newFromKey( $sha1, $repo, $timestamp = false ) {
177  $dbr = $repo->getReplicaDB();
178 
179  $conds = [ 'img_sha1' => $sha1 ];
180  if ( $timestamp ) {
181  $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
182  }
183 
184  $fileQuery = self::getQueryInfo();
185  $row = $dbr->selectRow(
186  $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__, [], $fileQuery['joins']
187  );
188  if ( $row ) {
189  return self::newFromRow( $row, $repo );
190  } else {
191  return false;
192  }
193  }
194 
200  static function selectFields() {
202 
203  wfDeprecated( __METHOD__, '1.31' );
204  if ( $wgActorTableSchemaMigrationStage > MIGRATION_WRITE_BOTH ) {
205  // If code is using this instead of self::getQueryInfo(), there's a
206  // decent chance it's going to try to directly access
207  // $row->img_user or $row->img_user_text and we can't give it
208  // useful values here once those aren't being written anymore.
209  throw new BadMethodCallException(
210  'Cannot use ' . __METHOD__ . ' when $wgActorTableSchemaMigrationStage > MIGRATION_WRITE_BOTH'
211  );
212  }
213 
214  return [
215  'img_name',
216  'img_size',
217  'img_width',
218  'img_height',
219  'img_metadata',
220  'img_bits',
221  'img_media_type',
222  'img_major_mime',
223  'img_minor_mime',
224  'img_user',
225  'img_user_text',
226  'img_actor' => $wgActorTableSchemaMigrationStage > MIGRATION_OLD ? 'img_actor' : 'NULL',
227  'img_timestamp',
228  'img_sha1',
229  ] + MediaWikiServices::getInstance()->getCommentStore()->getFields( 'img_description' );
230  }
231 
243  public static function getQueryInfo( array $options = [] ) {
244  $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'img_description' );
245  $actorQuery = ActorMigration::newMigration()->getJoin( 'img_user' );
246  $ret = [
247  'tables' => [ 'image' ] + $commentQuery['tables'] + $actorQuery['tables'],
248  'fields' => [
249  'img_name',
250  'img_size',
251  'img_width',
252  'img_height',
253  'img_metadata',
254  'img_bits',
255  'img_media_type',
256  'img_major_mime',
257  'img_minor_mime',
258  'img_timestamp',
259  'img_sha1',
260  ] + $commentQuery['fields'] + $actorQuery['fields'],
261  'joins' => $commentQuery['joins'] + $actorQuery['joins'],
262  ];
263 
264  if ( in_array( 'omit-nonlazy', $options, true ) ) {
265  // Internal use only for getting only the lazy fields
266  $ret['fields'] = [];
267  }
268  if ( !in_array( 'omit-lazy', $options, true ) ) {
269  // Note: Keep this in sync with self::getLazyCacheFields()
270  $ret['fields'][] = 'img_metadata';
271  }
272 
273  return $ret;
274  }
275 
281  function __construct( $title, $repo ) {
282  parent::__construct( $title, $repo );
283 
284  $this->metadata = '';
285  $this->historyLine = 0;
286  $this->historyRes = null;
287  $this->dataLoaded = false;
288  $this->extraDataLoaded = false;
289 
290  $this->assertRepoDefined();
291  $this->assertTitleDefined();
292  }
293 
299  function getCacheKey() {
300  return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
301  }
302 
309  return [ $this->getCacheKey() ];
310  }
311 
315  private function loadFromCache() {
316  $this->dataLoaded = false;
317  $this->extraDataLoaded = false;
318 
319  $key = $this->getCacheKey();
320  if ( !$key ) {
321  $this->loadFromDB( self::READ_NORMAL );
322 
323  return;
324  }
325 
326  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
327  $cachedValues = $cache->getWithSetCallback(
328  $key,
329  $cache::TTL_WEEK,
330  function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
331  $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
332 
333  $this->loadFromDB( self::READ_NORMAL );
334 
335  $fields = $this->getCacheFields( '' );
336  $cacheVal['fileExists'] = $this->fileExists;
337  if ( $this->fileExists ) {
338  foreach ( $fields as $field ) {
339  $cacheVal[$field] = $this->$field;
340  }
341  }
342  $cacheVal['user'] = $this->user ? $this->user->getId() : 0;
343  $cacheVal['user_text'] = $this->user ? $this->user->getName() : '';
344  $cacheVal['actor'] = $this->user ? $this->user->getActorId() : null;
345 
346  // Strip off excessive entries from the subset of fields that can become large.
347  // If the cache value gets to large it will not fit in memcached and nothing will
348  // get cached at all, causing master queries for any file access.
349  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
350  if ( isset( $cacheVal[$field] )
351  && strlen( $cacheVal[$field] ) > 100 * 1024
352  ) {
353  unset( $cacheVal[$field] ); // don't let the value get too big
354  }
355  }
356 
357  if ( $this->fileExists ) {
358  $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
359  } else {
360  $ttl = $cache::TTL_DAY;
361  }
362 
363  return $cacheVal;
364  },
365  [ 'version' => self::VERSION ]
366  );
367 
368  $this->fileExists = $cachedValues['fileExists'];
369  if ( $this->fileExists ) {
370  $this->setProps( $cachedValues );
371  }
372 
373  $this->dataLoaded = true;
374  $this->extraDataLoaded = true;
375  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
376  $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
377  }
378  }
379 
383  public function invalidateCache() {
384  $key = $this->getCacheKey();
385  if ( !$key ) {
386  return;
387  }
388 
389  $this->repo->getMasterDB()->onTransactionPreCommitOrIdle(
390  function () use ( $key ) {
391  MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
392  },
393  __METHOD__
394  );
395  }
396 
400  function loadFromFile() {
401  $props = $this->repo->getFileProps( $this->getVirtualUrl() );
402  $this->setProps( $props );
403  }
404 
411  protected function getCacheFields( $prefix = 'img_' ) {
412  if ( $prefix !== '' ) {
413  throw new InvalidArgumentException(
414  __METHOD__ . ' with a non-empty prefix is no longer supported.'
415  );
416  }
417 
418  // See self::getQueryInfo() for the fetching of the data from the DB,
419  // self::loadFromRow() for the loading of the object from the DB row,
420  // and self::loadFromCache() for the caching, and self::setProps() for
421  // populating the object from an array of data.
422  return [ 'size', 'width', 'height', 'bits', 'media_type',
423  'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
424  }
425 
433  protected function getLazyCacheFields( $prefix = 'img_' ) {
434  if ( $prefix !== '' ) {
435  throw new InvalidArgumentException(
436  __METHOD__ . ' with a non-empty prefix is no longer supported.'
437  );
438  }
439 
440  // Keep this in sync with the omit-lazy option in self::getQueryInfo().
441  return [ 'metadata' ];
442  }
443 
448  function loadFromDB( $flags = 0 ) {
449  $fname = static::class . '::' . __FUNCTION__;
450 
451  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
452  $this->dataLoaded = true;
453  $this->extraDataLoaded = true;
454 
455  $dbr = ( $flags & self::READ_LATEST )
456  ? $this->repo->getMasterDB()
457  : $this->repo->getReplicaDB();
458 
459  $fileQuery = static::getQueryInfo();
460  $row = $dbr->selectRow(
461  $fileQuery['tables'],
462  $fileQuery['fields'],
463  [ 'img_name' => $this->getName() ],
464  $fname,
465  [],
466  $fileQuery['joins']
467  );
468 
469  if ( $row ) {
470  $this->loadFromRow( $row );
471  } else {
472  $this->fileExists = false;
473  }
474  }
475 
480  protected function loadExtraFromDB() {
481  $fname = static::class . '::' . __FUNCTION__;
482 
483  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
484  $this->extraDataLoaded = true;
485 
486  $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo->getReplicaDB(), $fname );
487  if ( !$fieldMap ) {
488  $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo->getMasterDB(), $fname );
489  }
490 
491  if ( $fieldMap ) {
492  foreach ( $fieldMap as $name => $value ) {
493  $this->$name = $value;
494  }
495  } else {
496  throw new MWException( "Could not find data for image '{$this->getName()}'." );
497  }
498  }
499 
505  private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
506  $fieldMap = false;
507 
508  $fileQuery = self::getQueryInfo( [ 'omit-nonlazy' ] );
509  $row = $dbr->selectRow(
510  $fileQuery['tables'],
511  $fileQuery['fields'],
512  [
513  'img_name' => $this->getName(),
514  'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
515  ],
516  $fname,
517  [],
518  $fileQuery['joins']
519  );
520  if ( $row ) {
521  $fieldMap = $this->unprefixRow( $row, 'img_' );
522  } else {
523  # File may have been uploaded over in the meantime; check the old versions
524  $fileQuery = OldLocalFile::getQueryInfo( [ 'omit-nonlazy' ] );
525  $row = $dbr->selectRow(
526  $fileQuery['tables'],
527  $fileQuery['fields'],
528  [
529  'oi_name' => $this->getName(),
530  'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
531  ],
532  $fname,
533  [],
534  $fileQuery['joins']
535  );
536  if ( $row ) {
537  $fieldMap = $this->unprefixRow( $row, 'oi_' );
538  }
539  }
540 
541  if ( isset( $fieldMap['metadata'] ) ) {
542  $fieldMap['metadata'] = $this->repo->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
543  }
544 
545  return $fieldMap;
546  }
547 
554  protected function unprefixRow( $row, $prefix = 'img_' ) {
555  $array = (array)$row;
556  $prefixLength = strlen( $prefix );
557 
558  // Sanity check prefix once
559  if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
560  throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
561  }
562 
563  $decoded = [];
564  foreach ( $array as $name => $value ) {
565  $decoded[substr( $name, $prefixLength )] = $value;
566  }
567 
568  return $decoded;
569  }
570 
579  function decodeRow( $row, $prefix = 'img_' ) {
580  $decoded = $this->unprefixRow( $row, $prefix );
581 
582  $decoded['description'] = MediaWikiServices::getInstance()->getCommentStore()
583  ->getComment( 'description', (object)$decoded )->text;
584 
585  $decoded['user'] = User::newFromAnyId(
586  $decoded['user'] ?? null,
587  $decoded['user_text'] ?? null,
588  $decoded['actor'] ?? null
589  );
590  unset( $decoded['user_text'], $decoded['actor'] );
591 
592  $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
593 
594  $decoded['metadata'] = $this->repo->getReplicaDB()->decodeBlob( $decoded['metadata'] );
595 
596  if ( empty( $decoded['major_mime'] ) ) {
597  $decoded['mime'] = 'unknown/unknown';
598  } else {
599  if ( !$decoded['minor_mime'] ) {
600  $decoded['minor_mime'] = 'unknown';
601  }
602  $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
603  }
604 
605  // Trim zero padding from char/binary field
606  $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
607 
608  // Normalize some fields to integer type, per their database definition.
609  // Use unary + so that overflows will be upgraded to double instead of
610  // being trucated as with intval(). This is important to allow >2GB
611  // files on 32-bit systems.
612  foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
613  $decoded[$field] = +$decoded[$field];
614  }
615 
616  return $decoded;
617  }
618 
625  function loadFromRow( $row, $prefix = 'img_' ) {
626  $this->dataLoaded = true;
627  $this->extraDataLoaded = true;
628 
629  $array = $this->decodeRow( $row, $prefix );
630 
631  foreach ( $array as $name => $value ) {
632  $this->$name = $value;
633  }
634 
635  $this->fileExists = true;
636  $this->maybeUpgradeRow();
637  }
638 
643  function load( $flags = 0 ) {
644  if ( !$this->dataLoaded ) {
645  if ( $flags & self::READ_LATEST ) {
646  $this->loadFromDB( $flags );
647  } else {
648  $this->loadFromCache();
649  }
650  }
651 
652  if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
653  // @note: loads on name/timestamp to reduce race condition problems
654  $this->loadExtraFromDB();
655  }
656  }
657 
661  function maybeUpgradeRow() {
663 
664  if ( wfReadOnly() || $this->upgrading ) {
665  return;
666  }
667 
668  $upgrade = false;
669  if ( is_null( $this->media_type ) || $this->mime == 'image/svg' ) {
670  $upgrade = true;
671  } else {
672  $handler = $this->getHandler();
673  if ( $handler ) {
674  $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
675  if ( $validity === MediaHandler::METADATA_BAD ) {
676  $upgrade = true;
677  } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE ) {
678  $upgrade = $wgUpdateCompatibleMetadata;
679  }
680  }
681  }
682 
683  if ( $upgrade ) {
684  $this->upgrading = true;
685  // Defer updates unless in auto-commit CLI mode
687  $this->upgrading = false; // avoid duplicate updates
688  try {
689  $this->upgradeRow();
690  } catch ( LocalFileLockError $e ) {
691  // let the other process handle it (or do it next time)
692  }
693  } );
694  }
695  }
696 
700  function getUpgraded() {
701  return $this->upgraded;
702  }
703 
707  function upgradeRow() {
708  $this->lock(); // begin
709 
710  $this->loadFromFile();
711 
712  # Don't destroy file info of missing files
713  if ( !$this->fileExists ) {
714  $this->unlock();
715  wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
716 
717  return;
718  }
719 
720  $dbw = $this->repo->getMasterDB();
721  list( $major, $minor ) = self::splitMime( $this->mime );
722 
723  if ( wfReadOnly() ) {
724  $this->unlock();
725 
726  return;
727  }
728  wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
729 
730  $dbw->update( 'image',
731  [
732  'img_size' => $this->size, // sanity
733  'img_width' => $this->width,
734  'img_height' => $this->height,
735  'img_bits' => $this->bits,
736  'img_media_type' => $this->media_type,
737  'img_major_mime' => $major,
738  'img_minor_mime' => $minor,
739  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
740  'img_sha1' => $this->sha1,
741  ],
742  [ 'img_name' => $this->getName() ],
743  __METHOD__
744  );
745 
746  $this->invalidateCache();
747 
748  $this->unlock(); // done
749  $this->upgraded = true; // avoid rework/retries
750  }
751 
762  function setProps( $info ) {
763  $this->dataLoaded = true;
764  $fields = $this->getCacheFields( '' );
765  $fields[] = 'fileExists';
766 
767  foreach ( $fields as $field ) {
768  if ( isset( $info[$field] ) ) {
769  $this->$field = $info[$field];
770  }
771  }
772 
773  if ( isset( $info['user'] ) || isset( $info['user_text'] ) || isset( $info['actor'] ) ) {
774  $this->user = User::newFromAnyId(
775  $info['user'] ?? null,
776  $info['user_text'] ?? null,
777  $info['actor'] ?? null
778  );
779  }
780 
781  // Fix up mime fields
782  if ( isset( $info['major_mime'] ) ) {
783  $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
784  } elseif ( isset( $info['mime'] ) ) {
785  $this->mime = $info['mime'];
786  list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
787  }
788  }
789 
801  function isMissing() {
802  if ( $this->missing === null ) {
803  list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
804  $this->missing = !$fileExists;
805  }
806 
807  return $this->missing;
808  }
809 
816  public function getWidth( $page = 1 ) {
817  $page = (int)$page;
818  if ( $page < 1 ) {
819  $page = 1;
820  }
821 
822  $this->load();
823 
824  if ( $this->isMultipage() ) {
825  $handler = $this->getHandler();
826  if ( !$handler ) {
827  return 0;
828  }
829  $dim = $handler->getPageDimensions( $this, $page );
830  if ( $dim ) {
831  return $dim['width'];
832  } else {
833  // For non-paged media, the false goes through an
834  // intval, turning failure into 0, so do same here.
835  return 0;
836  }
837  } else {
838  return $this->width;
839  }
840  }
841 
848  public function getHeight( $page = 1 ) {
849  $page = (int)$page;
850  if ( $page < 1 ) {
851  $page = 1;
852  }
853 
854  $this->load();
855 
856  if ( $this->isMultipage() ) {
857  $handler = $this->getHandler();
858  if ( !$handler ) {
859  return 0;
860  }
861  $dim = $handler->getPageDimensions( $this, $page );
862  if ( $dim ) {
863  return $dim['height'];
864  } else {
865  // For non-paged media, the false goes through an
866  // intval, turning failure into 0, so do same here.
867  return 0;
868  }
869  } else {
870  return $this->height;
871  }
872  }
873 
881  function getUser( $type = 'text' ) {
882  $this->load();
883 
884  if ( $type === 'object' ) {
885  return $this->user;
886  } elseif ( $type === 'text' ) {
887  return $this->user->getName();
888  } elseif ( $type === 'id' ) {
889  return $this->user->getId();
890  }
891 
892  throw new MWException( "Unknown type '$type'." );
893  }
894 
902  public function getDescriptionShortUrl() {
903  $pageId = $this->title->getArticleID();
904 
905  if ( $pageId !== null ) {
906  $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
907  if ( $url !== false ) {
908  return $url;
909  }
910  }
911  return null;
912  }
913 
918  function getMetadata() {
919  $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
920  return $this->metadata;
921  }
922 
926  function getBitDepth() {
927  $this->load();
928 
929  return (int)$this->bits;
930  }
931 
936  public function getSize() {
937  $this->load();
938 
939  return $this->size;
940  }
941 
946  function getMimeType() {
947  $this->load();
948 
949  return $this->mime;
950  }
951 
957  function getMediaType() {
958  $this->load();
959 
960  return $this->media_type;
961  }
962 
973  public function exists() {
974  $this->load();
975 
976  return $this->fileExists;
977  }
978 
994  function getThumbnails( $archiveName = false ) {
995  if ( $archiveName ) {
996  $dir = $this->getArchiveThumbPath( $archiveName );
997  } else {
998  $dir = $this->getThumbPath();
999  }
1000 
1001  $backend = $this->repo->getBackend();
1002  $files = [ $dir ];
1003  try {
1004  $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1005  foreach ( $iterator as $file ) {
1006  $files[] = $file;
1007  }
1008  } catch ( FileBackendError $e ) {
1009  } // suppress (T56674)
1010 
1011  return $files;
1012  }
1013 
1017  function purgeMetadataCache() {
1018  $this->invalidateCache();
1019  }
1020 
1028  function purgeCache( $options = [] ) {
1029  // Refresh metadata cache
1030  $this->purgeMetadataCache();
1031 
1032  // Delete thumbnails
1033  $this->purgeThumbnails( $options );
1034 
1035  // Purge CDN cache for this file
1037  new CdnCacheUpdate( [ $this->getUrl() ] ),
1039  );
1040  }
1041 
1046  function purgeOldThumbnails( $archiveName ) {
1047  // Get a list of old thumbnails and URLs
1048  $files = $this->getThumbnails( $archiveName );
1049 
1050  // Purge any custom thumbnail caches
1051  Hooks::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1052 
1053  // Delete thumbnails
1054  $dir = array_shift( $files );
1055  $this->purgeThumbList( $dir, $files );
1056 
1057  // Purge the CDN
1058  $urls = [];
1059  foreach ( $files as $file ) {
1060  $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1061  }
1063  }
1064 
1069  public function purgeThumbnails( $options = [] ) {
1070  $files = $this->getThumbnails();
1071  // Always purge all files from CDN regardless of handler filters
1072  $urls = [];
1073  foreach ( $files as $file ) {
1074  $urls[] = $this->getThumbUrl( $file );
1075  }
1076  array_shift( $urls ); // don't purge directory
1077 
1078  // Give media handler a chance to filter the file purge list
1079  if ( !empty( $options['forThumbRefresh'] ) ) {
1080  $handler = $this->getHandler();
1081  if ( $handler ) {
1083  }
1084  }
1085 
1086  // Purge any custom thumbnail caches
1087  Hooks::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1088 
1089  // Delete thumbnails
1090  $dir = array_shift( $files );
1091  $this->purgeThumbList( $dir, $files );
1092 
1093  // Purge the CDN
1095  }
1096 
1102  public function prerenderThumbnails() {
1104 
1105  $jobs = [];
1106 
1107  $sizes = $wgUploadThumbnailRenderMap;
1108  rsort( $sizes );
1109 
1110  foreach ( $sizes as $size ) {
1111  if ( $this->isVectorized() || $this->getWidth() > $size ) {
1112  $jobs[] = new ThumbnailRenderJob(
1113  $this->getTitle(),
1114  [ 'transformParams' => [ 'width' => $size ] ]
1115  );
1116  }
1117  }
1118 
1119  if ( $jobs ) {
1120  JobQueueGroup::singleton()->lazyPush( $jobs );
1121  }
1122  }
1123 
1129  protected function purgeThumbList( $dir, $files ) {
1130  $fileListDebug = strtr(
1131  var_export( $files, true ),
1132  [ "\n" => '' ]
1133  );
1134  wfDebug( __METHOD__ . ": $fileListDebug\n" );
1135 
1136  $purgeList = [];
1137  foreach ( $files as $file ) {
1138  if ( $this->repo->supportsSha1URLs() ) {
1139  $reference = $this->getSha1();
1140  } else {
1141  $reference = $this->getName();
1142  }
1143 
1144  # Check that the reference (filename or sha1) is part of the thumb name
1145  # This is a basic sanity check to avoid erasing unrelated directories
1146  if ( strpos( $file, $reference ) !== false
1147  || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1148  ) {
1149  $purgeList[] = "{$dir}/{$file}";
1150  }
1151  }
1152 
1153  # Delete the thumbnails
1154  $this->repo->quickPurgeBatch( $purgeList );
1155  # Clear out the thumbnail directory if empty
1156  $this->repo->quickCleanDir( $dir );
1157  }
1158 
1169  function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1170  $dbr = $this->repo->getReplicaDB();
1171  $oldFileQuery = OldLocalFile::getQueryInfo();
1172 
1173  $tables = $oldFileQuery['tables'];
1174  $fields = $oldFileQuery['fields'];
1175  $join_conds = $oldFileQuery['joins'];
1176  $conds = $opts = [];
1177  $eq = $inc ? '=' : '';
1178  $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1179 
1180  if ( $start ) {
1181  $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1182  }
1183 
1184  if ( $end ) {
1185  $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1186  }
1187 
1188  if ( $limit ) {
1189  $opts['LIMIT'] = $limit;
1190  }
1191 
1192  // Search backwards for time > x queries
1193  $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1194  $opts['ORDER BY'] = "oi_timestamp $order";
1195  $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1196 
1197  // Avoid PHP 7.1 warning from passing $this by reference
1198  $localFile = $this;
1199  Hooks::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1200  &$conds, &$opts, &$join_conds ] );
1201 
1202  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1203  $r = [];
1204 
1205  foreach ( $res as $row ) {
1206  $r[] = $this->repo->newFileFromRow( $row );
1207  }
1208 
1209  if ( $order == 'ASC' ) {
1210  $r = array_reverse( $r ); // make sure it ends up descending
1211  }
1212 
1213  return $r;
1214  }
1215 
1225  public function nextHistoryLine() {
1226  # Polymorphic function name to distinguish foreign and local fetches
1227  $fname = static::class . '::' . __FUNCTION__;
1228 
1229  $dbr = $this->repo->getReplicaDB();
1230 
1231  if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1232  $fileQuery = self::getQueryInfo();
1233  $this->historyRes = $dbr->select( $fileQuery['tables'],
1234  $fileQuery['fields'] + [
1235  'oi_archive_name' => $dbr->addQuotes( '' ),
1236  'oi_deleted' => 0,
1237  ],
1238  [ 'img_name' => $this->title->getDBkey() ],
1239  $fname,
1240  [],
1241  $fileQuery['joins']
1242  );
1243 
1244  if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1245  $this->historyRes = null;
1246 
1247  return false;
1248  }
1249  } elseif ( $this->historyLine == 1 ) {
1250  $fileQuery = OldLocalFile::getQueryInfo();
1251  $this->historyRes = $dbr->select(
1252  $fileQuery['tables'],
1253  $fileQuery['fields'],
1254  [ 'oi_name' => $this->title->getDBkey() ],
1255  $fname,
1256  [ 'ORDER BY' => 'oi_timestamp DESC' ],
1257  $fileQuery['joins']
1258  );
1259  }
1260  $this->historyLine++;
1261 
1262  return $dbr->fetchObject( $this->historyRes );
1263  }
1264 
1268  public function resetHistory() {
1269  $this->historyLine = 0;
1270 
1271  if ( !is_null( $this->historyRes ) ) {
1272  $this->historyRes = null;
1273  }
1274  }
1275 
1308  function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1309  $timestamp = false, $user = null, $tags = [],
1310  $createNullRevision = true
1311  ) {
1312  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1313  return $this->readOnlyFatalStatus();
1314  } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1315  // Check this in advance to avoid writing to FileBackend and the file tables,
1316  // only to fail on insert the revision due to the text store being unavailable.
1317  return $this->readOnlyFatalStatus();
1318  }
1319 
1320  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1321  if ( !$props ) {
1322  if ( $this->repo->isVirtualUrl( $srcPath )
1323  || FileBackend::isStoragePath( $srcPath )
1324  ) {
1325  $props = $this->repo->getFileProps( $srcPath );
1326  } else {
1327  $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1328  $props = $mwProps->getPropsFromPath( $srcPath, true );
1329  }
1330  }
1331 
1332  $options = [];
1333  $handler = MediaHandler::getHandler( $props['mime'] );
1334  if ( $handler ) {
1335  $metadata = Wikimedia\quietCall( 'unserialize', $props['metadata'] );
1336 
1337  if ( !is_array( $metadata ) ) {
1338  $metadata = [];
1339  }
1340 
1341  $options['headers'] = $handler->getContentHeaders( $metadata );
1342  } else {
1343  $options['headers'] = [];
1344  }
1345 
1346  // Trim spaces on user supplied text
1347  $comment = trim( $comment );
1348 
1349  $this->lock(); // begin
1350  $status = $this->publish( $src, $flags, $options );
1351 
1352  if ( $status->successCount >= 2 ) {
1353  // There will be a copy+(one of move,copy,store).
1354  // The first succeeding does not commit us to updating the DB
1355  // since it simply copied the current version to a timestamped file name.
1356  // It is only *preferable* to avoid leaving such files orphaned.
1357  // Once the second operation goes through, then the current version was
1358  // updated and we must therefore update the DB too.
1359  $oldver = $status->value;
1360  $uploadStatus = $this->recordUpload2(
1361  $oldver,
1362  $comment,
1363  $pageText,
1364  $props,
1365  $timestamp,
1366  $user,
1367  $tags,
1368  $createNullRevision
1369  );
1370  if ( !$uploadStatus->isOK() ) {
1371  if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1372  // update filenotfound error with more specific path
1373  $status->fatal( 'filenotfound', $srcPath );
1374  } else {
1375  $status->merge( $uploadStatus );
1376  }
1377  }
1378  }
1379 
1380  $this->unlock(); // done
1381 
1382  return $status;
1383  }
1384 
1397  function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1398  $watch = false, $timestamp = false, User $user = null ) {
1399  if ( !$user ) {
1400  global $wgUser;
1401  $user = $wgUser;
1402  }
1403 
1404  $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1405 
1406  if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1407  return false;
1408  }
1409 
1410  if ( $watch ) {
1411  $user->addWatch( $this->getTitle() );
1412  }
1413 
1414  return true;
1415  }
1416 
1430  function recordUpload2(
1431  $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1432  $createNullRevision = true
1433  ) {
1435 
1436  if ( is_null( $user ) ) {
1437  global $wgUser;
1438  $user = $wgUser;
1439  }
1440 
1441  $dbw = $this->repo->getMasterDB();
1442 
1443  # Imports or such might force a certain timestamp; otherwise we generate
1444  # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1445  if ( $timestamp === false ) {
1446  $timestamp = $dbw->timestamp();
1447  $allowTimeKludge = true;
1448  } else {
1449  $allowTimeKludge = false;
1450  }
1451 
1452  $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1453  $props['description'] = $comment;
1454  $props['user'] = $user->getId();
1455  $props['user_text'] = $user->getName();
1456  $props['actor'] = $user->getActorId( $dbw );
1457  $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1458  $this->setProps( $props );
1459 
1460  # Fail now if the file isn't there
1461  if ( !$this->fileExists ) {
1462  wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
1463 
1464  return Status::newFatal( 'filenotfound', $this->getRel() );
1465  }
1466 
1467  $dbw->startAtomic( __METHOD__ );
1468 
1469  # Test to see if the row exists using INSERT IGNORE
1470  # This avoids race conditions by locking the row until the commit, and also
1471  # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1472  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1473  list( $commentFields, $commentCallback ) =
1474  $commentStore->insertWithTempTable( $dbw, 'img_description', $comment );
1475  $actorMigration = ActorMigration::newMigration();
1476  $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1477  $dbw->insert( 'image',
1478  [
1479  'img_name' => $this->getName(),
1480  'img_size' => $this->size,
1481  'img_width' => intval( $this->width ),
1482  'img_height' => intval( $this->height ),
1483  'img_bits' => $this->bits,
1484  'img_media_type' => $this->media_type,
1485  'img_major_mime' => $this->major_mime,
1486  'img_minor_mime' => $this->minor_mime,
1487  'img_timestamp' => $timestamp,
1488  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1489  'img_sha1' => $this->sha1
1490  ] + $commentFields + $actorFields,
1491  __METHOD__,
1492  'IGNORE'
1493  );
1494  $reupload = ( $dbw->affectedRows() == 0 );
1495 
1496  if ( $reupload ) {
1497  $row = $dbw->selectRow(
1498  'image',
1499  [ 'img_timestamp', 'img_sha1' ],
1500  [ 'img_name' => $this->getName() ],
1501  __METHOD__,
1502  [ 'LOCK IN SHARE MODE' ]
1503  );
1504 
1505  if ( $row && $row->img_sha1 === $this->sha1 ) {
1506  $dbw->endAtomic( __METHOD__ );
1507  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!\n" );
1508  $title = Title::newFromText( $this->getName(), NS_FILE );
1509  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1510  }
1511 
1512  if ( $allowTimeKludge ) {
1513  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1514  $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1515  # Avoid a timestamp that is not newer than the last version
1516  # TODO: the image/oldimage tables should be like page/revision with an ID field
1517  if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1518  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1519  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1520  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1521  }
1522  }
1523 
1524  $tables = [ 'image' ];
1525  $fields = [
1526  'oi_name' => 'img_name',
1527  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1528  'oi_size' => 'img_size',
1529  'oi_width' => 'img_width',
1530  'oi_height' => 'img_height',
1531  'oi_bits' => 'img_bits',
1532  'oi_timestamp' => 'img_timestamp',
1533  'oi_metadata' => 'img_metadata',
1534  'oi_media_type' => 'img_media_type',
1535  'oi_major_mime' => 'img_major_mime',
1536  'oi_minor_mime' => 'img_minor_mime',
1537  'oi_sha1' => 'img_sha1',
1538  ];
1539  $joins = [];
1540 
1541  if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH ) {
1542  $fields['oi_description'] = 'img_description';
1543  }
1544  if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH ) {
1545  $tables[] = 'image_comment_temp';
1546  $fields['oi_description_id'] = 'imgcomment_description_id';
1547  $joins['image_comment_temp'] = [
1548  $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN',
1549  [ 'imgcomment_name = img_name' ]
1550  ];
1551  }
1552 
1553  if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD &&
1554  $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
1555  ) {
1556  // Upgrade any rows that are still old-style. Otherwise an upgrade
1557  // might be missed if a deletion happens while the migration script
1558  // is running.
1559  $res = $dbw->select(
1560  [ 'image', 'image_comment_temp' ],
1561  [ 'img_name', 'img_description' ],
1562  [ 'img_name' => $this->getName(), 'imgcomment_name' => null ],
1563  __METHOD__,
1564  [],
1565  [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
1566  );
1567  foreach ( $res as $row ) {
1568  list( , $callback ) = $commentStore->insertWithTempTable(
1569  $dbw, 'img_description', $row->img_description
1570  );
1571  $callback( $row->img_name );
1572  }
1573  }
1574 
1575  if ( $wgActorTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH ) {
1576  $fields['oi_user'] = 'img_user';
1577  $fields['oi_user_text'] = 'img_user_text';
1578  }
1579  if ( $wgActorTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH ) {
1580  $fields['oi_actor'] = 'img_actor';
1581  }
1582 
1583  if ( $wgActorTableSchemaMigrationStage !== MIGRATION_OLD &&
1584  $wgActorTableSchemaMigrationStage !== MIGRATION_NEW
1585  ) {
1586  // Upgrade any rows that are still old-style. Otherwise an upgrade
1587  // might be missed if a deletion happens while the migration script
1588  // is running.
1589  $res = $dbw->select(
1590  [ 'image' ],
1591  [ 'img_name', 'img_user', 'img_user_text' ],
1592  [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1593  __METHOD__
1594  );
1595  foreach ( $res as $row ) {
1596  $actorId = User::newFromAnyId( $row->img_user, $row->img_user_text, null )->getActorId( $dbw );
1597  $dbw->update(
1598  'image',
1599  [ 'img_actor' => $actorId ],
1600  [ 'img_name' => $row->img_name, 'img_actor' => 0 ],
1601  __METHOD__
1602  );
1603  }
1604  }
1605 
1606  # (T36993) Note: $oldver can be empty here, if the previous
1607  # version of the file was broken. Allow registration of the new
1608  # version to continue anyway, because that's better than having
1609  # an image that's not fixable by user operations.
1610  # Collision, this is an update of a file
1611  # Insert previous contents into oldimage
1612  $dbw->insertSelect( 'oldimage', $tables, $fields,
1613  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1614 
1615  # Update the current image row
1616  $dbw->update( 'image',
1617  [
1618  'img_size' => $this->size,
1619  'img_width' => intval( $this->width ),
1620  'img_height' => intval( $this->height ),
1621  'img_bits' => $this->bits,
1622  'img_media_type' => $this->media_type,
1623  'img_major_mime' => $this->major_mime,
1624  'img_minor_mime' => $this->minor_mime,
1625  'img_timestamp' => $timestamp,
1626  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1627  'img_sha1' => $this->sha1
1628  ] + $commentFields + $actorFields,
1629  [ 'img_name' => $this->getName() ],
1630  __METHOD__
1631  );
1632  if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD ) {
1633  // So $commentCallback can insert the new row
1634  $dbw->delete( 'image_comment_temp', [ 'imgcomment_name' => $this->getName() ], __METHOD__ );
1635  }
1636  }
1637  $commentCallback( $this->getName() );
1638 
1639  $descTitle = $this->getTitle();
1640  $descId = $descTitle->getArticleID();
1641  $wikiPage = new WikiFilePage( $descTitle );
1642  $wikiPage->setFile( $this );
1643 
1644  // Add the log entry...
1645  $logEntry = new ManualLogEntry( 'upload', $reupload ? 'overwrite' : 'upload' );
1646  $logEntry->setTimestamp( $this->timestamp );
1647  $logEntry->setPerformer( $user );
1648  $logEntry->setComment( $comment );
1649  $logEntry->setTarget( $descTitle );
1650  // Allow people using the api to associate log entries with the upload.
1651  // Log has a timestamp, but sometimes different from upload timestamp.
1652  $logEntry->setParameters(
1653  [
1654  'img_sha1' => $this->sha1,
1655  'img_timestamp' => $timestamp,
1656  ]
1657  );
1658  // Note we keep $logId around since during new image
1659  // creation, page doesn't exist yet, so log_page = 0
1660  // but we want it to point to the page we're making,
1661  // so we later modify the log entry.
1662  // For a similar reason, we avoid making an RC entry
1663  // now and wait until the page exists.
1664  $logId = $logEntry->insert();
1665 
1666  if ( $descTitle->exists() ) {
1667  // Use own context to get the action text in content language
1668  $formatter = LogFormatter::newFromEntry( $logEntry );
1669  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1670  $editSummary = $formatter->getPlainActionText();
1671 
1672  $nullRevision = $createNullRevision === false ? null : Revision::newNullRevision(
1673  $dbw,
1674  $descId,
1675  $editSummary,
1676  false,
1677  $user
1678  );
1679  if ( $nullRevision ) {
1680  $nullRevision->insertOn( $dbw );
1681  Hooks::run(
1682  'NewRevisionFromEditComplete',
1683  [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1684  );
1685  $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1686  // Associate null revision id
1687  $logEntry->setAssociatedRevId( $nullRevision->getId() );
1688  }
1689 
1690  $newPageContent = null;
1691  } else {
1692  // Make the description page and RC log entry post-commit
1693  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1694  }
1695 
1696  # Defer purges, page creation, and link updates in case they error out.
1697  # The most important thing is that files and the DB registry stay synced.
1698  $dbw->endAtomic( __METHOD__ );
1699 
1700  # Do some cache purges after final commit so that:
1701  # a) Changes are more likely to be seen post-purge
1702  # b) They won't cause rollback of the log publish/update above
1704  new AutoCommitUpdate(
1705  $dbw,
1706  __METHOD__,
1707  function () use (
1708  $reupload, $wikiPage, $newPageContent, $comment, $user,
1709  $logEntry, $logId, $descId, $tags
1710  ) {
1711  # Update memcache after the commit
1712  $this->invalidateCache();
1713 
1714  $updateLogPage = false;
1715  if ( $newPageContent ) {
1716  # New file page; create the description page.
1717  # There's already a log entry, so don't make a second RC entry
1718  # CDN and file cache for the description page are purged by doEditContent.
1719  $status = $wikiPage->doEditContent(
1720  $newPageContent,
1721  $comment,
1723  false,
1724  $user
1725  );
1726 
1727  if ( isset( $status->value['revision'] ) ) {
1729  $rev = $status->value['revision'];
1730  // Associate new page revision id
1731  $logEntry->setAssociatedRevId( $rev->getId() );
1732  }
1733  // This relies on the resetArticleID() call in WikiPage::insertOn(),
1734  // which is triggered on $descTitle by doEditContent() above.
1735  if ( isset( $status->value['revision'] ) ) {
1737  $rev = $status->value['revision'];
1738  $updateLogPage = $rev->getPage();
1739  }
1740  } else {
1741  # Existing file page: invalidate description page cache
1742  $wikiPage->getTitle()->invalidateCache();
1743  $wikiPage->getTitle()->purgeSquid();
1744  # Allow the new file version to be patrolled from the page footer
1746  }
1747 
1748  # Update associated rev id. This should be done by $logEntry->insert() earlier,
1749  # but setAssociatedRevId() wasn't called at that point yet...
1750  $logParams = $logEntry->getParameters();
1751  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1752  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1753  if ( $updateLogPage ) {
1754  # Also log page, in case where we just created it above
1755  $update['log_page'] = $updateLogPage;
1756  }
1757  $this->getRepo()->getMasterDB()->update(
1758  'logging',
1759  $update,
1760  [ 'log_id' => $logId ],
1761  __METHOD__
1762  );
1763  $this->getRepo()->getMasterDB()->insert(
1764  'log_search',
1765  [
1766  'ls_field' => 'associated_rev_id',
1767  'ls_value' => $logEntry->getAssociatedRevId(),
1768  'ls_log_id' => $logId,
1769  ],
1770  __METHOD__
1771  );
1772 
1773  # Add change tags, if any
1774  if ( $tags ) {
1775  $logEntry->setTags( $tags );
1776  }
1777 
1778  # Uploads can be patrolled
1779  $logEntry->setIsPatrollable( true );
1780 
1781  # Now that the log entry is up-to-date, make an RC entry.
1782  $logEntry->publish( $logId );
1783 
1784  # Run hook for other updates (typically more cache purging)
1785  Hooks::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1786 
1787  if ( $reupload ) {
1788  # Delete old thumbnails
1789  $this->purgeThumbnails();
1790  # Remove the old file from the CDN cache
1792  new CdnCacheUpdate( [ $this->getUrl() ] ),
1794  );
1795  } else {
1796  # Update backlink pages pointing to this title if created
1798  $this->getTitle(),
1799  'imagelinks',
1800  'upload-image',
1801  $user->getName()
1802  );
1803  }
1804 
1805  $this->prerenderThumbnails();
1806  }
1807  ),
1809  );
1810 
1811  if ( !$reupload ) {
1812  # This is a new file, so update the image count
1813  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1814  }
1815 
1816  # Invalidate cache for all pages using this file
1818  new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1819  );
1820 
1821  return Status::newGood();
1822  }
1823 
1839  function publish( $src, $flags = 0, array $options = [] ) {
1840  return $this->publishTo( $src, $this->getRel(), $flags, $options );
1841  }
1842 
1858  function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1859  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1860 
1861  $repo = $this->getRepo();
1862  if ( $repo->getReadOnlyReason() !== false ) {
1863  return $this->readOnlyFatalStatus();
1864  }
1865 
1866  $this->lock(); // begin
1867 
1868  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1869  $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1870 
1871  if ( $repo->hasSha1Storage() ) {
1872  $sha1 = $repo->isVirtualUrl( $srcPath )
1873  ? $repo->getFileSha1( $srcPath )
1874  : FSFile::getSha1Base36FromPath( $srcPath );
1876  $wrapperBackend = $repo->getBackend();
1877  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1878  $status = $repo->quickImport( $src, $dst );
1879  if ( $flags & File::DELETE_SOURCE ) {
1880  unlink( $srcPath );
1881  }
1882 
1883  if ( $this->exists() ) {
1884  $status->value = $archiveName;
1885  }
1886  } else {
1887  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1888  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1889 
1890  if ( $status->value == 'new' ) {
1891  $status->value = '';
1892  } else {
1893  $status->value = $archiveName;
1894  }
1895  }
1896 
1897  $this->unlock(); // done
1898 
1899  return $status;
1900  }
1901 
1919  function move( $target ) {
1920  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1921  return $this->readOnlyFatalStatus();
1922  }
1923 
1924  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1925  $batch = new LocalFileMoveBatch( $this, $target );
1926 
1927  $this->lock(); // begin
1928  $batch->addCurrent();
1929  $archiveNames = $batch->addOlds();
1930  $status = $batch->execute();
1931  $this->unlock(); // done
1932 
1933  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1934 
1935  // Purge the source and target files...
1936  $oldTitleFile = wfLocalFile( $this->title );
1937  $newTitleFile = wfLocalFile( $target );
1938  // To avoid slow purges in the transaction, move them outside...
1940  new AutoCommitUpdate(
1941  $this->getRepo()->getMasterDB(),
1942  __METHOD__,
1943  function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1944  $oldTitleFile->purgeEverything();
1945  foreach ( $archiveNames as $archiveName ) {
1946  $oldTitleFile->purgeOldThumbnails( $archiveName );
1947  }
1948  $newTitleFile->purgeEverything();
1949  }
1950  ),
1952  );
1953 
1954  if ( $status->isOK() ) {
1955  // Now switch the object
1956  $this->title = $target;
1957  // Force regeneration of the name and hashpath
1958  unset( $this->name );
1959  unset( $this->hashPath );
1960  }
1961 
1962  return $status;
1963  }
1964 
1978  function delete( $reason, $suppress = false, $user = null ) {
1979  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1980  return $this->readOnlyFatalStatus();
1981  }
1982 
1983  $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1984 
1985  $this->lock(); // begin
1986  $batch->addCurrent();
1987  // Get old version relative paths
1988  $archiveNames = $batch->addOlds();
1989  $status = $batch->execute();
1990  $this->unlock(); // done
1991 
1992  if ( $status->isOK() ) {
1993  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
1994  }
1995 
1996  // To avoid slow purges in the transaction, move them outside...
1998  new AutoCommitUpdate(
1999  $this->getRepo()->getMasterDB(),
2000  __METHOD__,
2001  function () use ( $archiveNames ) {
2002  $this->purgeEverything();
2003  foreach ( $archiveNames as $archiveName ) {
2004  $this->purgeOldThumbnails( $archiveName );
2005  }
2006  }
2007  ),
2009  );
2010 
2011  // Purge the CDN
2012  $purgeUrls = [];
2013  foreach ( $archiveNames as $archiveName ) {
2014  $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2015  }
2017 
2018  return $status;
2019  }
2020 
2036  function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2037  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2038  return $this->readOnlyFatalStatus();
2039  }
2040 
2041  $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2042 
2043  $this->lock(); // begin
2044  $batch->addOld( $archiveName );
2045  $status = $batch->execute();
2046  $this->unlock(); // done
2047 
2048  $this->purgeOldThumbnails( $archiveName );
2049  if ( $status->isOK() ) {
2050  $this->purgeDescription();
2051  }
2052 
2054  new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2056  );
2057 
2058  return $status;
2059  }
2060 
2072  function restore( $versions = [], $unsuppress = false ) {
2073  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2074  return $this->readOnlyFatalStatus();
2075  }
2076 
2077  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2078 
2079  $this->lock(); // begin
2080  if ( !$versions ) {
2081  $batch->addAll();
2082  } else {
2083  $batch->addIds( $versions );
2084  }
2085  $status = $batch->execute();
2086  if ( $status->isGood() ) {
2087  $cleanupStatus = $batch->cleanup();
2088  $cleanupStatus->successCount = 0;
2089  $cleanupStatus->failCount = 0;
2090  $status->merge( $cleanupStatus );
2091  }
2092  $this->unlock(); // done
2093 
2094  return $status;
2095  }
2096 
2106  function getDescriptionUrl() {
2107  return $this->title->getLocalURL();
2108  }
2109 
2118  function getDescriptionText( Language $lang = null ) {
2119  $store = MediaWikiServices::getInstance()->getRevisionStore();
2120  $revision = $store->getRevisionByTitle( $this->title, 0, Revision::READ_NORMAL );
2121  if ( !$revision ) {
2122  return false;
2123  }
2124 
2125  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2126  $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2127 
2128  if ( !$rendered ) {
2129  // audience check failed
2130  return false;
2131  }
2132 
2133  $pout = $rendered->getRevisionParserOutput();
2134  return $pout->getText();
2135  }
2136 
2142  function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2143  $this->load();
2144  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2145  return '';
2146  } elseif ( $audience == self::FOR_THIS_USER
2147  && !$this->userCan( self::DELETED_COMMENT, $user )
2148  ) {
2149  return '';
2150  } else {
2151  return $this->description;
2152  }
2153  }
2154 
2158  function getTimestamp() {
2159  $this->load();
2160 
2161  return $this->timestamp;
2162  }
2163 
2167  public function getDescriptionTouched() {
2168  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2169  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2170  // need to differentiate between null (uninitialized) and false (failed to load).
2171  if ( $this->descriptionTouched === null ) {
2172  $cond = [
2173  'page_namespace' => $this->title->getNamespace(),
2174  'page_title' => $this->title->getDBkey()
2175  ];
2176  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2177  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2178  }
2179 
2181  }
2182 
2186  function getSha1() {
2187  $this->load();
2188  // Initialise now if necessary
2189  if ( $this->sha1 == '' && $this->fileExists ) {
2190  $this->lock(); // begin
2191 
2192  $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2193  if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2194  $dbw = $this->repo->getMasterDB();
2195  $dbw->update( 'image',
2196  [ 'img_sha1' => $this->sha1 ],
2197  [ 'img_name' => $this->getName() ],
2198  __METHOD__ );
2199  $this->invalidateCache();
2200  }
2201 
2202  $this->unlock(); // done
2203  }
2204 
2205  return $this->sha1;
2206  }
2207 
2211  function isCacheable() {
2212  $this->load();
2213 
2214  // If extra data (metadata) was not loaded then it must have been large
2215  return $this->extraDataLoaded
2216  && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
2217  }
2218 
2223  public function acquireFileLock() {
2224  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2225  [ $this->getPath() ], LockManager::LOCK_EX, 10
2226  ) );
2227  }
2228 
2233  public function releaseFileLock() {
2234  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2235  [ $this->getPath() ], LockManager::LOCK_EX
2236  ) );
2237  }
2238 
2248  public function lock() {
2249  if ( !$this->locked ) {
2250  $logger = LoggerFactory::getInstance( 'LocalFile' );
2251 
2252  $dbw = $this->repo->getMasterDB();
2253  $makesTransaction = !$dbw->trxLevel();
2254  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2255  // T56736: use simple lock to handle when the file does not exist.
2256  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2257  // Also, that would cause contention on INSERT of similarly named rows.
2258  $status = $this->acquireFileLock(); // represents all versions of the file
2259  if ( !$status->isGood() ) {
2260  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2261  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2262 
2263  throw new LocalFileLockError( $status );
2264  }
2265  // Release the lock *after* commit to avoid row-level contention.
2266  // Make sure it triggers on rollback() as well as commit() (T132921).
2267  $dbw->onTransactionResolution(
2268  function () use ( $logger ) {
2269  $status = $this->releaseFileLock();
2270  if ( !$status->isGood() ) {
2271  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2272  }
2273  },
2274  __METHOD__
2275  );
2276  // Callers might care if the SELECT snapshot is safely fresh
2277  $this->lockedOwnTrx = $makesTransaction;
2278  }
2279 
2280  $this->locked++;
2281 
2282  return $this->lockedOwnTrx;
2283  }
2284 
2293  public function unlock() {
2294  if ( $this->locked ) {
2295  --$this->locked;
2296  if ( !$this->locked ) {
2297  $dbw = $this->repo->getMasterDB();
2298  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2299  $this->lockedOwnTrx = false;
2300  }
2301  }
2302  }
2303 
2307  protected function readOnlyFatalStatus() {
2308  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2309  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2310  }
2311 
2315  function __destruct() {
2316  $this->unlock();
2317  }
2318 } // LocalFile class
2319 
2320 # ------------------------------------------------------------------------------
2321 
2328  private $file;
2329 
2331  private $reason;
2332 
2334  private $srcRels = [];
2335 
2337  private $archiveUrls = [];
2338 
2341 
2343  private $suppress;
2344 
2346  private $status;
2347 
2349  private $user;
2350 
2357  function __construct( File $file, $reason = '', $suppress = false, $user = null ) {
2358  $this->file = $file;
2359  $this->reason = $reason;
2360  $this->suppress = $suppress;
2361  if ( $user ) {
2362  $this->user = $user;
2363  } else {
2364  global $wgUser;
2365  $this->user = $wgUser;
2366  }
2367  $this->status = $file->repo->newGood();
2368  }
2369 
2370  public function addCurrent() {
2371  $this->srcRels['.'] = $this->file->getRel();
2372  }
2373 
2377  public function addOld( $oldName ) {
2378  $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
2379  $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
2380  }
2381 
2386  public function addOlds() {
2387  $archiveNames = [];
2388 
2389  $dbw = $this->file->repo->getMasterDB();
2390  $result = $dbw->select( 'oldimage',
2391  [ 'oi_archive_name' ],
2392  [ 'oi_name' => $this->file->getName() ],
2393  __METHOD__
2394  );
2395 
2396  foreach ( $result as $row ) {
2397  $this->addOld( $row->oi_archive_name );
2398  $archiveNames[] = $row->oi_archive_name;
2399  }
2400 
2401  return $archiveNames;
2402  }
2403 
2407  protected function getOldRels() {
2408  if ( !isset( $this->srcRels['.'] ) ) {
2409  $oldRels =& $this->srcRels;
2410  $deleteCurrent = false;
2411  } else {
2412  $oldRels = $this->srcRels;
2413  unset( $oldRels['.'] );
2414  $deleteCurrent = true;
2415  }
2416 
2417  return [ $oldRels, $deleteCurrent ];
2418  }
2419 
2423  protected function getHashes() {
2424  $hashes = [];
2425  list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2426 
2427  if ( $deleteCurrent ) {
2428  $hashes['.'] = $this->file->getSha1();
2429  }
2430 
2431  if ( count( $oldRels ) ) {
2432  $dbw = $this->file->repo->getMasterDB();
2433  $res = $dbw->select(
2434  'oldimage',
2435  [ 'oi_archive_name', 'oi_sha1' ],
2436  [ 'oi_archive_name' => array_keys( $oldRels ),
2437  'oi_name' => $this->file->getName() ], // performance
2438  __METHOD__
2439  );
2440 
2441  foreach ( $res as $row ) {
2442  if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
2443  // Get the hash from the file
2444  $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2445  $props = $this->file->repo->getFileProps( $oldUrl );
2446 
2447  if ( $props['fileExists'] ) {
2448  // Upgrade the oldimage row
2449  $dbw->update( 'oldimage',
2450  [ 'oi_sha1' => $props['sha1'] ],
2451  [ 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ],
2452  __METHOD__ );
2453  $hashes[$row->oi_archive_name] = $props['sha1'];
2454  } else {
2455  $hashes[$row->oi_archive_name] = false;
2456  }
2457  } else {
2458  $hashes[$row->oi_archive_name] = $row->oi_sha1;
2459  }
2460  }
2461  }
2462 
2463  $missing = array_diff_key( $this->srcRels, $hashes );
2464 
2465  foreach ( $missing as $name => $rel ) {
2466  $this->status->error( 'filedelete-old-unregistered', $name );
2467  }
2468 
2469  foreach ( $hashes as $name => $hash ) {
2470  if ( !$hash ) {
2471  $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2472  unset( $hashes[$name] );
2473  }
2474  }
2475 
2476  return $hashes;
2477  }
2478 
2479  protected function doDBInserts() {
2481 
2482  $now = time();
2483  $dbw = $this->file->repo->getMasterDB();
2484 
2485  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
2486  $actorMigration = ActorMigration::newMigration();
2487 
2488  $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2489  $encUserId = $dbw->addQuotes( $this->user->getId() );
2490  $encGroup = $dbw->addQuotes( 'deleted' );
2491  $ext = $this->file->getExtension();
2492  $dotExt = $ext === '' ? '' : ".$ext";
2493  $encExt = $dbw->addQuotes( $dotExt );
2494  list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2495 
2496  // Bitfields to further suppress the content
2497  if ( $this->suppress ) {
2498  $bitfield = Revision::SUPPRESSED_ALL;
2499  } else {
2500  $bitfield = 'oi_deleted';
2501  }
2502 
2503  if ( $deleteCurrent ) {
2504  $tables = [ 'image' ];
2505  $fields = [
2506  'fa_storage_group' => $encGroup,
2507  'fa_storage_key' => $dbw->conditional(
2508  [ 'img_sha1' => '' ],
2509  $dbw->addQuotes( '' ),
2510  $dbw->buildConcat( [ "img_sha1", $encExt ] )
2511  ),
2512  'fa_deleted_user' => $encUserId,
2513  'fa_deleted_timestamp' => $encTimestamp,
2514  'fa_deleted' => $this->suppress ? $bitfield : 0,
2515  'fa_name' => 'img_name',
2516  'fa_archive_name' => 'NULL',
2517  'fa_size' => 'img_size',
2518  'fa_width' => 'img_width',
2519  'fa_height' => 'img_height',
2520  'fa_metadata' => 'img_metadata',
2521  'fa_bits' => 'img_bits',
2522  'fa_media_type' => 'img_media_type',
2523  'fa_major_mime' => 'img_major_mime',
2524  'fa_minor_mime' => 'img_minor_mime',
2525  'fa_timestamp' => 'img_timestamp',
2526  'fa_sha1' => 'img_sha1'
2527  ];
2528  $joins = [];
2529 
2530  $fields += array_map(
2531  [ $dbw, 'addQuotes' ],
2532  $commentStore->insert( $dbw, 'fa_deleted_reason', $this->reason )
2533  );
2534 
2535  if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH ) {
2536  $fields['fa_description'] = 'img_description';
2537  }
2538  if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH ) {
2539  $tables[] = 'image_comment_temp';
2540  $fields['fa_description_id'] = 'imgcomment_description_id';
2541  $joins['image_comment_temp'] = [
2542  $wgCommentTableSchemaMigrationStage === MIGRATION_NEW ? 'JOIN' : 'LEFT JOIN',
2543  [ 'imgcomment_name = img_name' ]
2544  ];
2545  }
2546 
2547  if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD &&
2548  $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
2549  ) {
2550  // Upgrade any rows that are still old-style. Otherwise an upgrade
2551  // might be missed if a deletion happens while the migration script
2552  // is running.
2553  $res = $dbw->select(
2554  [ 'image', 'image_comment_temp' ],
2555  [ 'img_name', 'img_description' ],
2556  [ 'img_name' => $this->file->getName(), 'imgcomment_name' => null ],
2557  __METHOD__,
2558  [],
2559  [ 'image_comment_temp' => [ 'LEFT JOIN', [ 'imgcomment_name = img_name' ] ] ]
2560  );
2561  foreach ( $res as $row ) {
2562  list( , $callback ) = $commentStore->insertWithTempTable(
2563  $dbw, 'img_description', $row->img_description
2564  );
2565  $callback( $row->img_name );
2566  }
2567  }
2568 
2569  if ( $wgActorTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH ) {
2570  $fields['fa_user'] = 'img_user';
2571  $fields['fa_user_text'] = 'img_user_text';
2572  }
2573  if ( $wgActorTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH ) {
2574  $fields['fa_actor'] = 'img_actor';
2575  }
2576 
2577  if ( $wgActorTableSchemaMigrationStage !== MIGRATION_OLD &&
2578  $wgActorTableSchemaMigrationStage !== MIGRATION_NEW
2579  ) {
2580  // Upgrade any rows that are still old-style. Otherwise an upgrade
2581  // might be missed if a deletion happens while the migration script
2582  // is running.
2583  $res = $dbw->select(
2584  [ 'image' ],
2585  [ 'img_name', 'img_user', 'img_user_text' ],
2586  [ 'img_name' => $this->file->getName(), 'img_actor' => 0 ],
2587  __METHOD__
2588  );
2589  foreach ( $res as $row ) {
2590  $actorId = User::newFromAnyId( $row->img_user, $row->img_user_text, null )->getActorId( $dbw );
2591  $dbw->update(
2592  'image',
2593  [ 'img_actor' => $actorId ],
2594  [ 'img_name' => $row->img_name, 'img_actor' => 0 ],
2595  __METHOD__
2596  );
2597  }
2598  }
2599 
2600  $dbw->insertSelect( 'filearchive', $tables, $fields,
2601  [ 'img_name' => $this->file->getName() ], __METHOD__, [], [], $joins );
2602  }
2603 
2604  if ( count( $oldRels ) ) {
2605  $fileQuery = OldLocalFile::getQueryInfo();
2606  $res = $dbw->select(
2607  $fileQuery['tables'],
2608  $fileQuery['fields'],
2609  [
2610  'oi_name' => $this->file->getName(),
2611  'oi_archive_name' => array_keys( $oldRels )
2612  ],
2613  __METHOD__,
2614  [ 'FOR UPDATE' ],
2615  $fileQuery['joins']
2616  );
2617  $rowsInsert = [];
2618  if ( $res->numRows() ) {
2619  $reason = $commentStore->createComment( $dbw, $this->reason );
2620  foreach ( $res as $row ) {
2621  $comment = $commentStore->getComment( 'oi_description', $row );
2622  $user = User::newFromAnyId( $row->oi_user, $row->oi_user_text, $row->oi_actor );
2623  $rowsInsert[] = [
2624  // Deletion-specific fields
2625  'fa_storage_group' => 'deleted',
2626  'fa_storage_key' => ( $row->oi_sha1 === '' )
2627  ? ''
2628  : "{$row->oi_sha1}{$dotExt}",
2629  'fa_deleted_user' => $this->user->getId(),
2630  'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2631  // Counterpart fields
2632  'fa_deleted' => $this->suppress ? $bitfield : $row->oi_deleted,
2633  'fa_name' => $row->oi_name,
2634  'fa_archive_name' => $row->oi_archive_name,
2635  'fa_size' => $row->oi_size,
2636  'fa_width' => $row->oi_width,
2637  'fa_height' => $row->oi_height,
2638  'fa_metadata' => $row->oi_metadata,
2639  'fa_bits' => $row->oi_bits,
2640  'fa_media_type' => $row->oi_media_type,
2641  'fa_major_mime' => $row->oi_major_mime,
2642  'fa_minor_mime' => $row->oi_minor_mime,
2643  'fa_timestamp' => $row->oi_timestamp,
2644  'fa_sha1' => $row->oi_sha1
2645  ] + $commentStore->insert( $dbw, 'fa_deleted_reason', $reason )
2646  + $commentStore->insert( $dbw, 'fa_description', $comment )
2647  + $actorMigration->getInsertValues( $dbw, 'fa_user', $user );
2648  }
2649  }
2650 
2651  $dbw->insert( 'filearchive', $rowsInsert, __METHOD__ );
2652  }
2653  }
2654 
2655  function doDBDeletes() {
2657 
2658  $dbw = $this->file->repo->getMasterDB();
2659  list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2660 
2661  if ( count( $oldRels ) ) {
2662  $dbw->delete( 'oldimage',
2663  [
2664  'oi_name' => $this->file->getName(),
2665  'oi_archive_name' => array_keys( $oldRels )
2666  ], __METHOD__ );
2667  }
2668 
2669  if ( $deleteCurrent ) {
2670  $dbw->delete( 'image', [ 'img_name' => $this->file->getName() ], __METHOD__ );
2671  if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD ) {
2672  $dbw->delete(
2673  'image_comment_temp', [ 'imgcomment_name' => $this->file->getName() ], __METHOD__
2674  );
2675  }
2676  }
2677  }
2678 
2683  public function execute() {
2684  $repo = $this->file->getRepo();
2685  $this->file->lock();
2686 
2687  // Prepare deletion batch
2688  $hashes = $this->getHashes();
2689  $this->deletionBatch = [];
2690  $ext = $this->file->getExtension();
2691  $dotExt = $ext === '' ? '' : ".$ext";
2692 
2693  foreach ( $this->srcRels as $name => $srcRel ) {
2694  // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2695  if ( isset( $hashes[$name] ) ) {
2696  $hash = $hashes[$name];
2697  $key = $hash . $dotExt;
2698  $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2699  $this->deletionBatch[$name] = [ $srcRel, $dstRel ];
2700  }
2701  }
2702 
2703  if ( !$repo->hasSha1Storage() ) {
2704  // Removes non-existent file from the batch, so we don't get errors.
2705  // This also handles files in the 'deleted' zone deleted via revision deletion.
2706  $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch );
2707  if ( !$checkStatus->isGood() ) {
2708  $this->status->merge( $checkStatus );
2709  return $this->status;
2710  }
2711  $this->deletionBatch = $checkStatus->value;
2712 
2713  // Execute the file deletion batch
2714  $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2715  if ( !$status->isGood() ) {
2716  $this->status->merge( $status );
2717  }
2718  }
2719 
2720  if ( !$this->status->isOK() ) {
2721  // Critical file deletion error; abort
2722  $this->file->unlock();
2723 
2724  return $this->status;
2725  }
2726 
2727  // Copy the image/oldimage rows to filearchive
2728  $this->doDBInserts();
2729  // Delete image/oldimage rows
2730  $this->doDBDeletes();
2731 
2732  // Commit and return
2733  $this->file->unlock();
2734 
2735  return $this->status;
2736  }
2737 
2743  protected function removeNonexistentFiles( $batch ) {
2744  $files = $newBatch = [];
2745 
2746  foreach ( $batch as $batchItem ) {
2747  list( $src, ) = $batchItem;
2748  $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2749  }
2750 
2751  $result = $this->file->repo->fileExistsBatch( $files );
2752  if ( in_array( null, $result, true ) ) {
2753  return Status::newFatal( 'backend-fail-internal',
2754  $this->file->repo->getBackend()->getName() );
2755  }
2756 
2757  foreach ( $batch as $batchItem ) {
2758  if ( $result[$batchItem[0]] ) {
2759  $newBatch[] = $batchItem;
2760  }
2761  }
2762 
2763  return Status::newGood( $newBatch );
2764  }
2765 }
2766 
2767 # ------------------------------------------------------------------------------
2768 
2775  private $file;
2776 
2778  private $cleanupBatch;
2779 
2781  private $ids;
2782 
2784  private $all;
2785 
2787  private $unsuppress = false;
2788 
2793  function __construct( File $file, $unsuppress = false ) {
2794  $this->file = $file;
2795  $this->cleanupBatch = [];
2796  $this->ids = [];
2797  $this->unsuppress = $unsuppress;
2798  }
2799 
2804  public function addId( $fa_id ) {
2805  $this->ids[] = $fa_id;
2806  }
2807 
2812  public function addIds( $ids ) {
2813  $this->ids = array_merge( $this->ids, $ids );
2814  }
2815 
2819  public function addAll() {
2820  $this->all = true;
2821  }
2822 
2831  public function execute() {
2833  global $wgLang;
2834 
2835  $repo = $this->file->getRepo();
2836  if ( !$this->all && !$this->ids ) {
2837  // Do nothing
2838  return $repo->newGood();
2839  }
2840 
2841  $lockOwnsTrx = $this->file->lock();
2842 
2843  $dbw = $this->file->repo->getMasterDB();
2844 
2845  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
2846  $actorMigration = ActorMigration::newMigration();
2847 
2848  $status = $this->file->repo->newGood();
2849 
2850  $exists = (bool)$dbw->selectField( 'image', '1',
2851  [ 'img_name' => $this->file->getName() ],
2852  __METHOD__,
2853  // The lock() should already prevents changes, but this still may need
2854  // to bypass any transaction snapshot. However, if lock() started the
2855  // trx (which it probably did) then snapshot is post-lock and up-to-date.
2856  $lockOwnsTrx ? [] : [ 'LOCK IN SHARE MODE' ]
2857  );
2858 
2859  // Fetch all or selected archived revisions for the file,
2860  // sorted from the most recent to the oldest.
2861  $conditions = [ 'fa_name' => $this->file->getName() ];
2862 
2863  if ( !$this->all ) {
2864  $conditions['fa_id'] = $this->ids;
2865  }
2866 
2867  $arFileQuery = ArchivedFile::getQueryInfo();
2868  $result = $dbw->select(
2869  $arFileQuery['tables'],
2870  $arFileQuery['fields'],
2871  $conditions,
2872  __METHOD__,
2873  [ 'ORDER BY' => 'fa_timestamp DESC' ],
2874  $arFileQuery['joins']
2875  );
2876 
2877  $idsPresent = [];
2878  $storeBatch = [];
2879  $insertBatch = [];
2880  $insertCurrent = false;
2881  $deleteIds = [];
2882  $first = true;
2883  $archiveNames = [];
2884 
2885  foreach ( $result as $row ) {
2886  $idsPresent[] = $row->fa_id;
2887 
2888  if ( $row->fa_name != $this->file->getName() ) {
2889  $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2890  $status->failCount++;
2891  continue;
2892  }
2893 
2894  if ( $row->fa_storage_key == '' ) {
2895  // Revision was missing pre-deletion
2896  $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2897  $status->failCount++;
2898  continue;
2899  }
2900 
2901  $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2902  $row->fa_storage_key;
2903  $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2904 
2905  if ( isset( $row->fa_sha1 ) ) {
2906  $sha1 = $row->fa_sha1;
2907  } else {
2908  // old row, populate from key
2909  $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2910  }
2911 
2912  # Fix leading zero
2913  if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2914  $sha1 = substr( $sha1, 1 );
2915  }
2916 
2917  if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2918  || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2919  || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2920  || is_null( $row->fa_metadata )
2921  ) {
2922  // Refresh our metadata
2923  // Required for a new current revision; nice for older ones too. :)
2924  $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2925  } else {
2926  $props = [
2927  'minor_mime' => $row->fa_minor_mime,
2928  'major_mime' => $row->fa_major_mime,
2929  'media_type' => $row->fa_media_type,
2930  'metadata' => $row->fa_metadata
2931  ];
2932  }
2933 
2934  $comment = $commentStore->getComment( 'fa_description', $row );
2935  $user = User::newFromAnyId( $row->fa_user, $row->fa_user_text, $row->fa_actor );
2936  if ( $first && !$exists ) {
2937  // This revision will be published as the new current version
2938  $destRel = $this->file->getRel();
2939  list( $commentFields, $commentCallback ) =
2940  $commentStore->insertWithTempTable( $dbw, 'img_description', $comment );
2941  $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
2942  $insertCurrent = [
2943  'img_name' => $row->fa_name,
2944  'img_size' => $row->fa_size,
2945  'img_width' => $row->fa_width,
2946  'img_height' => $row->fa_height,
2947  'img_metadata' => $props['metadata'],
2948  'img_bits' => $row->fa_bits,
2949  'img_media_type' => $props['media_type'],
2950  'img_major_mime' => $props['major_mime'],
2951  'img_minor_mime' => $props['minor_mime'],
2952  'img_timestamp' => $row->fa_timestamp,
2953  'img_sha1' => $sha1
2954  ] + $commentFields + $actorFields;
2955 
2956  // The live (current) version cannot be hidden!
2957  if ( !$this->unsuppress && $row->fa_deleted ) {
2958  $status->fatal( 'undeleterevdel' );
2959  $this->file->unlock();
2960  return $status;
2961  }
2962  } else {
2963  $archiveName = $row->fa_archive_name;
2964 
2965  if ( $archiveName == '' ) {
2966  // This was originally a current version; we
2967  // have to devise a new archive name for it.
2968  // Format is <timestamp of archiving>!<name>
2969  $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2970 
2971  do {
2972  $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2973  $timestamp++;
2974  } while ( isset( $archiveNames[$archiveName] ) );
2975  }
2976 
2977  $archiveNames[$archiveName] = true;
2978  $destRel = $this->file->getArchiveRel( $archiveName );
2979  $insertBatch[] = [
2980  'oi_name' => $row->fa_name,
2981  'oi_archive_name' => $archiveName,
2982  'oi_size' => $row->fa_size,
2983  'oi_width' => $row->fa_width,
2984  'oi_height' => $row->fa_height,
2985  'oi_bits' => $row->fa_bits,
2986  'oi_timestamp' => $row->fa_timestamp,
2987  'oi_metadata' => $props['metadata'],
2988  'oi_media_type' => $props['media_type'],
2989  'oi_major_mime' => $props['major_mime'],
2990  'oi_minor_mime' => $props['minor_mime'],
2991  'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2992  'oi_sha1' => $sha1
2993  ] + $commentStore->insert( $dbw, 'oi_description', $comment )
2994  + $actorMigration->getInsertValues( $dbw, 'oi_user', $user );
2995  }
2996 
2997  $deleteIds[] = $row->fa_id;
2998 
2999  if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
3000  // private files can stay where they are
3001  $status->successCount++;
3002  } else {
3003  $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
3004  $this->cleanupBatch[] = $row->fa_storage_key;
3005  }
3006 
3007  $first = false;
3008  }
3009 
3010  unset( $result );
3011 
3012  // Add a warning to the status object for missing IDs
3013  $missingIds = array_diff( $this->ids, $idsPresent );
3014 
3015  foreach ( $missingIds as $id ) {
3016  $status->error( 'undelete-missing-filearchive', $id );
3017  }
3018 
3019  if ( !$repo->hasSha1Storage() ) {
3020  // Remove missing files from batch, so we don't get errors when undeleting them
3021  $checkStatus = $this->removeNonexistentFiles( $storeBatch );
3022  if ( !$checkStatus->isGood() ) {
3023  $status->merge( $checkStatus );
3024  return $status;
3025  }
3026  $storeBatch = $checkStatus->value;
3027 
3028  // Run the store batch
3029  // Use the OVERWRITE_SAME flag to smooth over a common error
3030  $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
3031  $status->merge( $storeStatus );
3032 
3033  if ( !$status->isGood() ) {
3034  // Even if some files could be copied, fail entirely as that is the
3035  // easiest thing to do without data loss
3036  $this->cleanupFailedBatch( $storeStatus, $storeBatch );
3037  $status->setOK( false );
3038  $this->file->unlock();
3039 
3040  return $status;
3041  }
3042  }
3043 
3044  // Run the DB updates
3045  // Because we have locked the image row, key conflicts should be rare.
3046  // If they do occur, we can roll back the transaction at this time with
3047  // no data loss, but leaving unregistered files scattered throughout the
3048  // public zone.
3049  // This is not ideal, which is why it's important to lock the image row.
3050  if ( $insertCurrent ) {
3051  $dbw->insert( 'image', $insertCurrent, __METHOD__ );
3052  $commentCallback( $insertCurrent['img_name'] );
3053  }
3054 
3055  if ( $insertBatch ) {
3056  $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
3057  }
3058 
3059  if ( $deleteIds ) {
3060  $dbw->delete( 'filearchive',
3061  [ 'fa_id' => $deleteIds ],
3062  __METHOD__ );
3063  }
3064 
3065  // If store batch is empty (all files are missing), deletion is to be considered successful
3066  if ( $status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
3067  if ( !$exists ) {
3068  wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
3069 
3070  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
3071 
3072  $this->file->purgeEverything();
3073  } else {
3074  wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
3075  $this->file->purgeDescription();
3076  }
3077  }
3078 
3079  $this->file->unlock();
3080 
3081  return $status;
3082  }
3083 
3089  protected function removeNonexistentFiles( $triplets ) {
3090  $files = $filteredTriplets = [];
3091  foreach ( $triplets as $file ) {
3092  $files[$file[0]] = $file[0];
3093  }
3094 
3095  $result = $this->file->repo->fileExistsBatch( $files );
3096  if ( in_array( null, $result, true ) ) {
3097  return Status::newFatal( 'backend-fail-internal',
3098  $this->file->repo->getBackend()->getName() );
3099  }
3100 
3101  foreach ( $triplets as $file ) {
3102  if ( $result[$file[0]] ) {
3103  $filteredTriplets[] = $file;
3104  }
3105  }
3106 
3107  return Status::newGood( $filteredTriplets );
3108  }
3109 
3115  protected function removeNonexistentFromCleanup( $batch ) {
3116  $files = $newBatch = [];
3117  $repo = $this->file->repo;
3118 
3119  foreach ( $batch as $file ) {
3120  $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
3121  rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3122  }
3123 
3124  $result = $repo->fileExistsBatch( $files );
3125 
3126  foreach ( $batch as $file ) {
3127  if ( $result[$file] ) {
3128  $newBatch[] = $file;
3129  }
3130  }
3131 
3132  return $newBatch;
3133  }
3134 
3140  public function cleanup() {
3141  if ( !$this->cleanupBatch ) {
3142  return $this->file->repo->newGood();
3143  }
3144 
3145  $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
3146 
3147  $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
3148 
3149  return $status;
3150  }
3151 
3159  protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
3160  $cleanupBatch = [];
3161 
3162  foreach ( $storeStatus->success as $i => $success ) {
3163  // Check if this item of the batch was successfully copied
3164  if ( $success ) {
3165  // Item was successfully copied and needs to be removed again
3166  // Extract ($dstZone, $dstRel) from the batch
3167  $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3168  }
3169  }
3170  $this->file->repo->cleanupBatch( $cleanupBatch );
3171  }
3172 }
3173 
3174 # ------------------------------------------------------------------------------
3175 
3182  protected $file;
3183 
3185  protected $target;
3186 
3187  protected $cur;
3188 
3189  protected $olds;
3190 
3191  protected $oldCount;
3192 
3193  protected $archive;
3194 
3196  protected $db;
3197 
3202  function __construct( File $file, Title $target ) {
3203  $this->file = $file;
3204  $this->target = $target;
3205  $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
3206  $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
3207  $this->oldName = $this->file->getName();
3208  $this->newName = $this->file->repo->getNameFromTitle( $this->target );
3209  $this->oldRel = $this->oldHash . $this->oldName;
3210  $this->newRel = $this->newHash . $this->newName;
3211  $this->db = $file->getRepo()->getMasterDB();
3212  }
3213 
3217  public function addCurrent() {
3218  $this->cur = [ $this->oldRel, $this->newRel ];
3219  }
3220 
3225  public function addOlds() {
3226  $archiveBase = 'archive';
3227  $this->olds = [];
3228  $this->oldCount = 0;
3229  $archiveNames = [];
3230 
3231  $result = $this->db->select( 'oldimage',
3232  [ 'oi_archive_name', 'oi_deleted' ],
3233  [ 'oi_name' => $this->oldName ],
3234  __METHOD__,
3235  [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3236  );
3237 
3238  foreach ( $result as $row ) {
3239  $archiveNames[] = $row->oi_archive_name;
3240  $oldName = $row->oi_archive_name;
3241  $bits = explode( '!', $oldName, 2 );
3242 
3243  if ( count( $bits ) != 2 ) {
3244  wfDebug( "Old file name missing !: '$oldName' \n" );
3245  continue;
3246  }
3247 
3248  list( $timestamp, $filename ) = $bits;
3249 
3250  if ( $this->oldName != $filename ) {
3251  wfDebug( "Old file name doesn't match: '$oldName' \n" );
3252  continue;
3253  }
3254 
3255  $this->oldCount++;
3256 
3257  // Do we want to add those to oldCount?
3258  if ( $row->oi_deleted & File::DELETED_FILE ) {
3259  continue;
3260  }
3261 
3262  $this->olds[] = [
3263  "{$archiveBase}/{$this->oldHash}{$oldName}",
3264  "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3265  ];
3266  }
3267 
3268  return $archiveNames;
3269  }
3270 
3275  public function execute() {
3276  $repo = $this->file->repo;
3277  $status = $repo->newGood();
3278  $destFile = wfLocalFile( $this->target );
3279 
3280  $this->file->lock(); // begin
3281  $destFile->lock(); // quickly fail if destination is not available
3282 
3283  $triplets = $this->getMoveTriplets();
3284  $checkStatus = $this->removeNonexistentFiles( $triplets );
3285  if ( !$checkStatus->isGood() ) {
3286  $destFile->unlock();
3287  $this->file->unlock();
3288  $status->merge( $checkStatus ); // couldn't talk to file backend
3289  return $status;
3290  }
3291  $triplets = $checkStatus->value;
3292 
3293  // Verify the file versions metadata in the DB.
3294  $statusDb = $this->verifyDBUpdates();
3295  if ( !$statusDb->isGood() ) {
3296  $destFile->unlock();
3297  $this->file->unlock();
3298  $statusDb->setOK( false );
3299 
3300  return $statusDb;
3301  }
3302 
3303  if ( !$repo->hasSha1Storage() ) {
3304  // Copy the files into their new location.
3305  // If a prior process fataled copying or cleaning up files we tolerate any
3306  // of the existing files if they are identical to the ones being stored.
3307  $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
3308  wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3309  "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3310  if ( !$statusMove->isGood() ) {
3311  // Delete any files copied over (while the destination is still locked)
3312  $this->cleanupTarget( $triplets );
3313  $destFile->unlock();
3314  $this->file->unlock();
3315  wfDebugLog( 'imagemove', "Error in moving files: "
3316  . $statusMove->getWikiText( false, false, 'en' ) );
3317  $statusMove->setOK( false );
3318 
3319  return $statusMove;
3320  }
3321  $status->merge( $statusMove );
3322  }
3323 
3324  // Rename the file versions metadata in the DB.
3325  $this->doDBUpdates();
3326 
3327  wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3328  "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3329 
3330  $destFile->unlock();
3331  $this->file->unlock(); // done
3332 
3333  // Everything went ok, remove the source files
3334  $this->cleanupSource( $triplets );
3335 
3336  $status->merge( $statusDb );
3337 
3338  return $status;
3339  }
3340 
3347  protected function verifyDBUpdates() {
3348  $repo = $this->file->repo;
3349  $status = $repo->newGood();
3350  $dbw = $this->db;
3351 
3352  $hasCurrent = $dbw->lockForUpdate(
3353  'image',
3354  [ 'img_name' => $this->oldName ],
3355  __METHOD__
3356  );
3357  $oldRowCount = $dbw->lockForUpdate(
3358  'oldimage',
3359  [ 'oi_name' => $this->oldName ],
3360  __METHOD__
3361  );
3362 
3363  if ( $hasCurrent ) {
3364  $status->successCount++;
3365  } else {
3366  $status->failCount++;
3367  }
3368  $status->successCount += $oldRowCount;
3369  // T36934: oldCount is based on files that actually exist.
3370  // There may be more DB rows than such files, in which case $affected
3371  // can be greater than $total. We use max() to avoid negatives here.
3372  $status->failCount += max( 0, $this->oldCount - $oldRowCount );
3373  if ( $status->failCount ) {
3374  $status->error( 'imageinvalidfilename' );
3375  }
3376 
3377  return $status;
3378  }
3379 
3384  protected function doDBUpdates() {
3386 
3387  $dbw = $this->db;
3388 
3389  // Update current image
3390  $dbw->update(
3391  'image',
3392  [ 'img_name' => $this->newName ],
3393  [ 'img_name' => $this->oldName ],
3394  __METHOD__
3395  );
3396  if ( $wgCommentTableSchemaMigrationStage > MIGRATION_OLD ) {
3397  $dbw->update(
3398  'image_comment_temp',
3399  [ 'imgcomment_name' => $this->newName ],
3400  [ 'imgcomment_name' => $this->oldName ],
3401  __METHOD__
3402  );
3403  }
3404 
3405  // Update old images
3406  $dbw->update(
3407  'oldimage',
3408  [
3409  'oi_name' => $this->newName,
3410  'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3411  $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3412  ],
3413  [ 'oi_name' => $this->oldName ],
3414  __METHOD__
3415  );
3416  }
3417 
3422  protected function getMoveTriplets() {
3423  $moves = array_merge( [ $this->cur ], $this->olds );
3424  $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3425 
3426  foreach ( $moves as $move ) {
3427  // $move: (oldRelativePath, newRelativePath)
3428  $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3429  $triplets[] = [ $srcUrl, 'public', $move[1] ];
3430  wfDebugLog(
3431  'imagemove',
3432  "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3433  );
3434  }
3435 
3436  return $triplets;
3437  }
3438 
3444  protected function removeNonexistentFiles( $triplets ) {
3445  $files = [];
3446 
3447  foreach ( $triplets as $file ) {
3448  $files[$file[0]] = $file[0];
3449  }
3450 
3451  $result = $this->file->repo->fileExistsBatch( $files );
3452  if ( in_array( null, $result, true ) ) {
3453  return Status::newFatal( 'backend-fail-internal',
3454  $this->file->repo->getBackend()->getName() );
3455  }
3456 
3457  $filteredTriplets = [];
3458  foreach ( $triplets as $file ) {
3459  if ( $result[$file[0]] ) {
3460  $filteredTriplets[] = $file;
3461  } else {
3462  wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3463  }
3464  }
3465 
3466  return Status::newGood( $filteredTriplets );
3467  }
3468 
3474  protected function cleanupTarget( $triplets ) {
3475  // Create dest pairs from the triplets
3476  $pairs = [];
3477  foreach ( $triplets as $triplet ) {
3478  // $triplet: (old source virtual URL, dst zone, dest rel)
3479  $pairs[] = [ $triplet[1], $triplet[2] ];
3480  }
3481 
3482  $this->file->repo->cleanupBatch( $pairs );
3483  }
3484 
3490  protected function cleanupSource( $triplets ) {
3491  // Create source file names from the triplets
3492  $files = [];
3493  foreach ( $triplets as $triplet ) {
3494  $files[] = $triplet[0];
3495  }
3496 
3497  $this->file->repo->cleanupBatch( $files );
3498  }
3499 }
3500 
3502  public function __construct( Status $status ) {
3503  parent::__construct(
3504  'actionfailed',
3505  $status->getMessage()
3506  );
3507  }
3508 
3509  public function report() {
3510  global $wgOut;
3511  $wgOut->setStatusCode( 429 );
3512  parent::report();
3513  }
3514 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
int $wgCommentTableSchemaMigrationStage
Comment table schema migration stage.
exists()
canRender inherited
Definition: LocalFile.php:973
User $user
Uploader.
Definition: LocalFile.php:106
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
invalidateCache()
Purge the file object/metadata cache.
Definition: LocalFile.php:383
static singleton( $wiki=false)
getCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache.
Definition: LocalFile.php:411
MediaHandler $handler
Definition: File.php:114
addWatch( $title, $checkRights=self::CHECK_USER_RIGHTS)
Watch an article.
Definition: User.php:3912
string $media_type
MEDIATYPE_xxx (bitmap, drawing, audio...)
Definition: LocalFile.php:64
getVirtualUrl( $suffix=false)
Get a URL referring to this repository, with the private mwrepo protocol.
Definition: FileRepo.php:261
bool $extraDataLoaded
Whether or not lazy-loaded data has been loaded from the database.
Definition: LocalFile.php:82
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
assertTitleDefined()
Assert that $this->title is set to a Title.
Definition: File.php:2296
const VERSION
Definition: LocalFile.php:47
$success
addAll()
Add all revisions of the file.
Definition: LocalFile.php:2819
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
serialize()
unprefixRow( $row, $prefix='img_')
Definition: LocalFile.php:554
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new archivedfile object...
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:2060
string $minor_mime
Minor MIME type.
Definition: LocalFile.php:100
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2237
getArchiveThumbUrl( $archiveName, $suffix=false)
Get the URL of the archived file&#39;s thumbs, or a particular thumb if $suffix is specified.
Definition: File.php:1675
purgeMetadataCache()
Refresh metadata in memcached, but don&#39;t touch thumbnails or CDN.
Definition: LocalFile.php:1017
releaseFileLock()
Definition: LocalFile.php:2233
const DELETE_SOURCE
Definition: File.php:66
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
if(!isset( $args[0])) $lang
static newFromEntry(LogEntry $entry)
Constructs a new formatter suitable for given entry.
cleanup()
Delete unused files in the deleted zone.
Definition: LocalFile.php:3140
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1315
width
addCurrent()
Add the current image to the batch.
Definition: LocalFile.php:3217
const DELETE_SOURCE
Definition: FileRepo.php:40
getSize()
Returns the size of the image file, in bytes.
Definition: LocalFile.php:936
Handles purging appropriate CDN URLs given a title (or titles)
verifyDBUpdates()
Verify the database updates and return a new Status indicating how many rows would be updated...
Definition: LocalFile.php:3347
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info...
Definition: LocalFile.php:762
getThumbnails( $archiveName=false)
getTransformScript inherited
Definition: LocalFile.php:994
Helper class for file undeletion.
Definition: LocalFile.php:2773
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero. ...
Definition: LocalFile.php:2293
string $major_mime
Major MIME type.
Definition: LocalFile.php:97
string $sha1
SHA-1 base 36 content hash.
Definition: LocalFile.php:76
removeNonexistentFromCleanup( $batch)
Removes non-existent files from a cleanup batch.
Definition: LocalFile.php:3115
$source
$value
isMissing()
splitMime inherited
Definition: LocalFile.php:801
const MIGRATION_WRITE_BOTH
Definition: Defines.php:316
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
Definition: hooks.txt:2229
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
assertRepoDefined()
Assert that $this->repo is set to a valid FileRepo instance.
Definition: File.php:2286
move( $target)
getLinksTo inherited
Definition: LocalFile.php:1919
getName()
Return the name of this file.
Definition: File.php:297
string $name
The name of a file from its title object.
Definition: File.php:123
getRepo()
Returns the repository.
Definition: File.php:1874
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
Definition: LocalFile.php:1069
string [] $ids
List of file IDs to restore.
Definition: LocalFile.php:2781
getArchiveUrl( $suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified.
Definition: File.php:1655
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1694
removeNonexistentFiles( $batch)
Removes non-existent files from a deletion batch.
Definition: LocalFile.php:2743
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:967
const METADATA_BAD
cleanupSource( $triplets)
Cleanup a fully moved array of triplets by deleting the source files.
Definition: LocalFile.php:3490
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
int $bits
Returned by getimagesize (loadFromXxx)
Definition: LocalFile.php:61
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:1171
loadFromDB( $flags=0)
Load file metadata from the DB.
Definition: LocalFile.php:448
title
wfLocalFile( $title)
Get an object referring to a locally registered file.
const ATOMIC_SECTION_LOCK
Definition: LocalFile.php:132
bool $fileExists
Does the file exist on disk? (loadFromXxx)
Definition: LocalFile.php:52
doDBUpdates()
Do the database updates and return a new Status indicating how many rows where updated.
Definition: LocalFile.php:3384
getTitle()
Return the associated title object.
Definition: File.php:326
Title string bool $title
Definition: File.php:99
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2451
getHashPath()
Get the filename hash component of the directory including trailing slash, e.g.
Definition: File.php:1517
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition: LocalFile.php:2072
purgeEverything()
Purge metadata and all affected pages when the file is created, deleted, or majorly updated...
Definition: File.php:1459
__destruct()
Clean up any dangling locks.
Definition: LocalFile.php:2315
getMessage( $shortContext=false, $longContext=false, $lang=null)
Get a bullet list of the errors as a Message object.
Definition: Status.php:233
const DELETED_FILE
Definition: File.php:53
getBackend()
Get the file backend instance.
Definition: FileRepo.php:210
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:2058
__construct(File $file, $reason='', $suppress=false, $user=null)
Definition: LocalFile.php:2357
static newFromRow( $row, $repo)
Create a LocalFile from a title Do not call this except from inside a repo class. ...
Definition: LocalFile.php:159
and how to run hooks for an and one after Each event has a name
Definition: hooks.txt:6
getThumbnails()
Get all thumbnail names previously generated for this file STUB Overridden by LocalFile.
Definition: File.php:1428
$batch
Definition: linkcache.txt:23
getVirtualUrl( $suffix=false)
Get the public zone virtual URL for a current version source file.
Definition: File.php:1733
Deferrable Update for closure/callback updates that should use auto-commit mode.
getDescriptionShortUrl()
Get short description URL for a file based on the page ID.
Definition: LocalFile.php:902
nextHistoryLine()
Returns the history of this file, line by line.
Definition: LocalFile.php:1225
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:46
addIds( $ids)
Add a whole lot of files by ID.
Definition: LocalFile.php:2812
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
__construct(File $file, Title $target)
Definition: LocalFile.php:3202
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
publish( $src, $flags=0, array $options=[])
Move or copy a file to its public location.
Definition: LocalFile.php:1839
getPath()
Return the storage path to the file.
Definition: File.php:417
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
Definition: LocalFile.php:1169
int $historyRes
Result of the query for the file&#39;s history (nextHistoryLine)
Definition: LocalFile.php:94
bool $locked
True if the image row is locked.
Definition: LocalFile.php:121
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add a callable update.
getReadOnlyReason()
Get an explanatory message if this repo is read-only.
Definition: FileRepo.php:220
__construct(File $file, $unsuppress=false)
Definition: LocalFile.php:2793
wfReadOnly()
Check whether the wiki is in read-only mode.
string $metadata
Handler-specific metadata.
Definition: LocalFile.php:73
$wgLang
Definition: Setup.php:887
string $descriptionTouched
TS_MW timestamp of the last change of the file description.
Definition: LocalFile.php:112
static newMigration()
Static constructor.
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
Definition: hooks.txt:91
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:579
string $repoClass
Definition: LocalFile.php:88
cleanupTarget( $triplets)
Cleanup a partially moved array of triplets by deleting the target files.
Definition: LocalFile.php:3474
getThumbUrl( $suffix=false)
Get the URL of the thumbnail directory, or a particular file if $suffix is specified.
Definition: File.php:1713
File backend exception for checked exceptions (e.g.
An error page which can definitely be safely rendered using the OutputPage.
isVectorized()
Return true if the file is vectorized.
Definition: File.php:555
Class to invalidate the HTML cache of all the pages linking to a given title.
isMultipage()
Returns &#39;true&#39; if this file is a type which supports multiple pages, e.g.
Definition: File.php:1979
getLazyCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache, only when they&#39;re not too...
Definition: LocalFile.php:433
const LOAD_ALL
Definition: LocalFile.php:130
getHandler()
Get a MediaHandler instance for this file.
Definition: File.php:1383
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:299
static factory(array $deltas)
getDescriptionTouched()
Definition: LocalFile.php:2167
const LOCK_EX
Definition: LockManager.php:69
const MIGRATION_OLD
Definition: Defines.php:315
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1592
getRel()
Get the path of the file relative to the public zone root.
Definition: File.php:1532
$res
Definition: database.txt:21
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
userCan( $field, User $user=null)
Determine if the current user is allowed to view a particular field of this file, if it&#39;s marked as d...
Definition: File.php:2166
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
purgeCache( $options=[])
Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN...
Definition: LocalFile.php:1028
$wgUploadThumbnailRenderMap
When defined, is an array of thumbnail widths to be rendered at upload time.
static selectFields()
Fields in the image table.
Definition: LocalFile.php:200
acquireFileLock()
Definition: LocalFile.php:2223
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example, it is done during re-uploads when file patrol is used.
Definition: Article.php:1338
const CACHE_FIELD_MAX_LEN
Definition: LocalFile.php:49
__construct(Status $status)
Definition: LocalFile.php:3502
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
Definition: distributors.txt:9
loadFromRow( $row, $prefix='img_')
Load file metadata from a DB result row.
Definition: LocalFile.php:625
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:249
loadExtraFromDB()
Load lazy file metadata from the DB.
Definition: LocalFile.php:480
$cache
Definition: mcc.php:33
const EDIT_SUPPRESS_RC
Definition: Defines.php:155
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:2060
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:176
maybeUpgradeRow()
Upgrade a row if it needs it.
Definition: LocalFile.php:661
readOnlyFatalStatus()
Definition: LocalFile.php:2307
Helper class for file movement.
Definition: LocalFile.php:3180
bool $upgraded
Whether the row was upgraded on load.
Definition: LocalFile.php:115
static newExtraneousContext(Title $title, $request=[])
Create a new extraneous context.
execute()
Run the transaction.
Definition: LocalFile.php:2683
bool $all
Add all revisions of the file.
Definition: LocalFile.php:2784
bool $lockedOwnTrx
True if the image row is locked with a lock initiated transaction.
Definition: LocalFile.php:124
bool $dataLoaded
Whether or not core data has been loaded from the database (loadFromXxx)
Definition: LocalFile.php:79
const NS_FILE
Definition: Defines.php:70
FileRepo LocalRepo ForeignAPIRepo bool $repo
Some member variables can be lazy-initialised using __get().
Definition: File.php:96
prerenderThumbnails()
Prerenders a configurable set of thumbnails.
Definition: LocalFile.php:1102
getMetadata()
Get handler-specific metadata.
Definition: LocalFile.php:918
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1832
recordUpload2( $oldver, $comment, $pageText, $props=false, $timestamp=false, $user=null, $tags=[], $createNullRevision=true)
Record a file upload in the upload log and the image table.
Definition: LocalFile.php:1430
purgeOldThumbnails( $archiveName)
Delete cached transformed files for an archived version only.
Definition: LocalFile.php:1046
string $mime
MIME type, determined by MimeMagic::guessMimeType.
Definition: LocalFile.php:67
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding, zero padded to 31 digits.
Definition: FSFile.php:218
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Special handling for file pages.
execute()
Perform the move.
Definition: LocalFile.php:3275
Helper class for file deletion.
Definition: LocalFile.php:2326
static getHashFromKey( $key)
Gets the SHA1 hash from a storage key.
Definition: LocalRepo.php:182
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:113
array $deletionBatch
Items to be processed in the deletion batch.
Definition: LocalFile.php:2340
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
Definition: LocalFile.php:1129
getDescription( $audience=self::FOR_PUBLIC, User $user=null)
Definition: LocalFile.php:2142
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:55
upload( $src, $comment, $pageText, $flags=0, $props=false, $timestamp=false, $user=null, $tags=[], $createNullRevision=true)
getHashPath inherited
Definition: LocalFile.php:1308
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new oldlocalfile object...
removeNonexistentFiles( $triplets)
Removes non-existent files from a store batch.
Definition: LocalFile.php:3089
getDescriptionText(Language $lang=null)
Get the HTML text of the description page This is not used by ImagePage for local files...
Definition: LocalFile.php:2118
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:545
static queueRecursiveJobsForTable(Title $title, $table, $action='unknown', $userName='unknown')
Queue a RefreshLinks job for any table.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
removeNonexistentFiles( $triplets)
Removes non-existent files from move batch.
Definition: LocalFile.php:3444
getArchiveThumbPath( $archiveName, $suffix=false)
Get the path of an archived file&#39;s thumbs, or a particular thumb if $suffix is specified.
Definition: File.php:1618
isMetadataValid( $image, $metadata)
Check if the metadata string is valid for this handler.
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
Definition: User.php:675
upgradeRow()
Fix assorted version-related problems with the image row by reloading it from the file...
Definition: LocalFile.php:707
getContentHeaders( $metadata)
Get useful response headers for GET/HEAD requests for a file with the given metadata.
getId()
Get the user&#39;s ID.
Definition: User.php:2426
Class representing a non-directory file on the file system.
Definition: FSFile.php:29
const OVERWRITE_SAME
Definition: FileRepo.php:42
deleteOld( $archiveName, $reason, $suppress=false, $user=null)
Delete an old version of the file.
Definition: LocalFile.php:2036
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
getActorId(IDatabase $dbw=null)
Get the user&#39;s actor ID.
Definition: User.php:2489
const EDIT_NEW
Definition: Defines.php:152
Job for asynchronous rendering of thumbnails.
bool $upgrading
Whether the row was scheduled to upgrade on load.
Definition: LocalFile.php:118
lock()
Start an atomic DB section and lock the image for update or increments a reference counter if the loc...
Definition: LocalFile.php:2248
string $url
The URL corresponding to one of the four basic zones.
Definition: File.php:117
int $deleted
Bitfield akin to rev_deleted.
Definition: LocalFile.php:85
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
loadExtraFieldsWithTimestamp( $dbr, $fname)
Definition: LocalFile.php:505
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
filterThumbnailPurgeList(&$files, $options)
Remove files from the purge list.
getUrl()
Return the URL of the file.
Definition: File.php:348
bool $missing
True if file is not present in file system.
Definition: LocalFile.php:127
const METADATA_COMPATIBLE
getDescriptionUrl()
isMultipage inherited
Definition: LocalFile.php:2106
getPageDimensions(File $image, $page)
Get an associative array of page dimensions Currently "width" and "height" are understood, but this might be expanded in the future.
Class to represent a local file in the wiki&#39;s own database.
Definition: LocalFile.php:46
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
addOlds()
Add the old versions of the image to the batch.
Definition: LocalFile.php:3225
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition: FileRepo.php:856
getMoveTriplets()
Generate triplets for FileRepo::storeBatch().
Definition: LocalFile.php:3422
string $timestamp
Upload timestamp.
Definition: LocalFile.php:103
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition: hooks.txt:1020
getHeight( $page=1)
Return the height of the image.
Definition: LocalFile.php:848
int $height
Image height.
Definition: LocalFile.php:58
loadFromFile()
Load metadata from the file itself.
Definition: LocalFile.php:400
$wgOut
Definition: Setup.php:892
fileExistsBatch(array $files)
Checks existence of an array of files.
Definition: FileRepo.php:1371
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
Definition: FileRepo.php:1488
string $description
Description of current revision of the file.
Definition: LocalFile.php:109
publishTo( $src, $dstRel, $flags=0, array $options=[])
Move or copy a file to a specified location.
Definition: LocalFile.php:1858
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object...
Definition: LocalFile.php:243
const MIGRATION_NEW
Definition: Defines.php:318
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:51
bool $suppress
Whether to suppress all suppressable fields when deleting.
Definition: LocalFile.php:2343
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
$ext
Definition: router.php:55
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
getMediaType()
Returns the type of the media in the file.
Definition: LocalFile.php:957
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
Definition: LocalFile.php:315
string [] $cleanupBatch
List of file IDs to restore.
Definition: LocalFile.php:2778
getMutableCacheKeys(WANObjectCache $cache)
Definition: LocalFile.php:308
int $width
Image width.
Definition: LocalFile.php:55
cleanupFailedBatch( $storeStatus, $storeBatch)
Cleanup a failed batch.
Definition: LocalFile.php:3159
getMimeType()
Returns the MIME type of the file.
Definition: LocalFile.php:946
resetHistory()
Reset the history pointer to the first element of the history.
Definition: LocalFile.php:1268
static newNullRevision( $dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page&#39;s history.
Definition: Revision.php:1167
int $size
Size in bytes (loadFromXxx)
Definition: LocalFile.php:70
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:1931
addOlds()
Add the old versions of the image to the batch.
Definition: LocalFile.php:2386
isDeleted( $field)
Is this file a "deleted" file in a private archive? STUB.
Definition: File.php:1895
getWidth( $page=1)
Return the width of the image.
Definition: LocalFile.php:816
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
Definition: LocalFile.php:643
purgeDescription()
Purge the file description page, but don&#39;t go after pages using the file.
Definition: File.php:1447
getThumbPath( $suffix=false)
Get the path of the thumbnail directory, or a particular file if $suffix is specified.
Definition: File.php:1631
$wgUpdateCompatibleMetadata
If to automatically update the img_metadata field if the metadata field is outdated but compatible wi...
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:146
getUser( $type='text')
Returns user who uploaded the file.
Definition: LocalFile.php:881
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
const SUPPRESSED_ALL
Definition: Revision.php:52
newGood( $value=null)
Create a new good result.
Definition: FileRepo.php:1747
int $historyLine
Number of line to return by nextHistoryLine() (constructor)
Definition: LocalFile.php:91
execute()
Run the transaction, except the cleanup batch.
Definition: LocalFile.php:2831
__construct( $title, $repo)
Do not call this except from inside a repo class.
Definition: LocalFile.php:281
static makeParamBlob( $params)
Create a blob from a parameter array.
Definition: LogEntry.php:142
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:1397
addId( $fa_id)
Add a file by ID.
Definition: LocalFile.php:2804
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:280