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 & SCHEMA_COMPAT_READ_NEW ) {
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 used anymore.
209  throw new BadMethodCallException(
210  'Cannot use ' . __METHOD__
211  . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
212  );
213  }
214 
215  return [
216  'img_name',
217  'img_size',
218  'img_width',
219  'img_height',
220  'img_metadata',
221  'img_bits',
222  'img_media_type',
223  'img_major_mime',
224  'img_minor_mime',
225  'img_user',
226  'img_user_text',
227  'img_actor' => 'NULL',
228  'img_timestamp',
229  'img_sha1',
230  ] + MediaWikiServices::getInstance()->getCommentStore()->getFields( 'img_description' );
231  }
232 
244  public static function getQueryInfo( array $options = [] ) {
245  $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'img_description' );
246  $actorQuery = ActorMigration::newMigration()->getJoin( 'img_user' );
247  $ret = [
248  'tables' => [ 'image' ] + $commentQuery['tables'] + $actorQuery['tables'],
249  'fields' => [
250  'img_name',
251  'img_size',
252  'img_width',
253  'img_height',
254  'img_metadata',
255  'img_bits',
256  'img_media_type',
257  'img_major_mime',
258  'img_minor_mime',
259  'img_timestamp',
260  'img_sha1',
261  ] + $commentQuery['fields'] + $actorQuery['fields'],
262  'joins' => $commentQuery['joins'] + $actorQuery['joins'],
263  ];
264 
265  if ( in_array( 'omit-nonlazy', $options, true ) ) {
266  // Internal use only for getting only the lazy fields
267  $ret['fields'] = [];
268  }
269  if ( !in_array( 'omit-lazy', $options, true ) ) {
270  // Note: Keep this in sync with self::getLazyCacheFields()
271  $ret['fields'][] = 'img_metadata';
272  }
273 
274  return $ret;
275  }
276 
282  function __construct( $title, $repo ) {
283  parent::__construct( $title, $repo );
284 
285  $this->metadata = '';
286  $this->historyLine = 0;
287  $this->historyRes = null;
288  $this->dataLoaded = false;
289  $this->extraDataLoaded = false;
290 
291  $this->assertRepoDefined();
292  $this->assertTitleDefined();
293  }
294 
300  function getCacheKey() {
301  return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
302  }
303 
310  return [ $this->getCacheKey() ];
311  }
312 
316  private function loadFromCache() {
317  $this->dataLoaded = false;
318  $this->extraDataLoaded = false;
319 
320  $key = $this->getCacheKey();
321  if ( !$key ) {
322  $this->loadFromDB( self::READ_NORMAL );
323 
324  return;
325  }
326 
327  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
328  $cachedValues = $cache->getWithSetCallback(
329  $key,
330  $cache::TTL_WEEK,
331  function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
332  $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
333 
334  $this->loadFromDB( self::READ_NORMAL );
335 
336  $fields = $this->getCacheFields( '' );
337  $cacheVal['fileExists'] = $this->fileExists;
338  if ( $this->fileExists ) {
339  foreach ( $fields as $field ) {
340  $cacheVal[$field] = $this->$field;
341  }
342  }
343  $cacheVal['user'] = $this->user ? $this->user->getId() : 0;
344  $cacheVal['user_text'] = $this->user ? $this->user->getName() : '';
345  $cacheVal['actor'] = $this->user ? $this->user->getActorId() : null;
346 
347  // Strip off excessive entries from the subset of fields that can become large.
348  // If the cache value gets to large it will not fit in memcached and nothing will
349  // get cached at all, causing master queries for any file access.
350  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
351  if ( isset( $cacheVal[$field] )
352  && strlen( $cacheVal[$field] ) > 100 * 1024
353  ) {
354  unset( $cacheVal[$field] ); // don't let the value get too big
355  }
356  }
357 
358  if ( $this->fileExists ) {
359  $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
360  } else {
361  $ttl = $cache::TTL_DAY;
362  }
363 
364  return $cacheVal;
365  },
366  [ 'version' => self::VERSION ]
367  );
368 
369  $this->fileExists = $cachedValues['fileExists'];
370  if ( $this->fileExists ) {
371  $this->setProps( $cachedValues );
372  }
373 
374  $this->dataLoaded = true;
375  $this->extraDataLoaded = true;
376  foreach ( $this->getLazyCacheFields( '' ) as $field ) {
377  $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
378  }
379  }
380 
384  public function invalidateCache() {
385  $key = $this->getCacheKey();
386  if ( !$key ) {
387  return;
388  }
389 
390  $this->repo->getMasterDB()->onTransactionPreCommitOrIdle(
391  function () use ( $key ) {
392  MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
393  },
394  __METHOD__
395  );
396  }
397 
401  function loadFromFile() {
402  $props = $this->repo->getFileProps( $this->getVirtualUrl() );
403  $this->setProps( $props );
404  }
405 
412  protected function getCacheFields( $prefix = 'img_' ) {
413  if ( $prefix !== '' ) {
414  throw new InvalidArgumentException(
415  __METHOD__ . ' with a non-empty prefix is no longer supported.'
416  );
417  }
418 
419  // See self::getQueryInfo() for the fetching of the data from the DB,
420  // self::loadFromRow() for the loading of the object from the DB row,
421  // and self::loadFromCache() for the caching, and self::setProps() for
422  // populating the object from an array of data.
423  return [ 'size', 'width', 'height', 'bits', 'media_type',
424  'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'description' ];
425  }
426 
434  protected function getLazyCacheFields( $prefix = 'img_' ) {
435  if ( $prefix !== '' ) {
436  throw new InvalidArgumentException(
437  __METHOD__ . ' with a non-empty prefix is no longer supported.'
438  );
439  }
440 
441  // Keep this in sync with the omit-lazy option in self::getQueryInfo().
442  return [ 'metadata' ];
443  }
444 
449  function loadFromDB( $flags = 0 ) {
450  $fname = static::class . '::' . __FUNCTION__;
451 
452  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
453  $this->dataLoaded = true;
454  $this->extraDataLoaded = true;
455 
456  $dbr = ( $flags & self::READ_LATEST )
457  ? $this->repo->getMasterDB()
458  : $this->repo->getReplicaDB();
459 
460  $fileQuery = static::getQueryInfo();
461  $row = $dbr->selectRow(
462  $fileQuery['tables'],
463  $fileQuery['fields'],
464  [ 'img_name' => $this->getName() ],
465  $fname,
466  [],
467  $fileQuery['joins']
468  );
469 
470  if ( $row ) {
471  $this->loadFromRow( $row );
472  } else {
473  $this->fileExists = false;
474  }
475  }
476 
481  protected function loadExtraFromDB() {
482  $fname = static::class . '::' . __FUNCTION__;
483 
484  # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
485  $this->extraDataLoaded = true;
486 
487  $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo->getReplicaDB(), $fname );
488  if ( !$fieldMap ) {
489  $fieldMap = $this->loadExtraFieldsWithTimestamp( $this->repo->getMasterDB(), $fname );
490  }
491 
492  if ( $fieldMap ) {
493  foreach ( $fieldMap as $name => $value ) {
494  $this->$name = $value;
495  }
496  } else {
497  throw new MWException( "Could not find data for image '{$this->getName()}'." );
498  }
499  }
500 
506  private function loadExtraFieldsWithTimestamp( $dbr, $fname ) {
507  $fieldMap = false;
508 
509  $fileQuery = self::getQueryInfo( [ 'omit-nonlazy' ] );
510  $row = $dbr->selectRow(
511  $fileQuery['tables'],
512  $fileQuery['fields'],
513  [
514  'img_name' => $this->getName(),
515  'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
516  ],
517  $fname,
518  [],
519  $fileQuery['joins']
520  );
521  if ( $row ) {
522  $fieldMap = $this->unprefixRow( $row, 'img_' );
523  } else {
524  # File may have been uploaded over in the meantime; check the old versions
525  $fileQuery = OldLocalFile::getQueryInfo( [ 'omit-nonlazy' ] );
526  $row = $dbr->selectRow(
527  $fileQuery['tables'],
528  $fileQuery['fields'],
529  [
530  'oi_name' => $this->getName(),
531  'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ),
532  ],
533  $fname,
534  [],
535  $fileQuery['joins']
536  );
537  if ( $row ) {
538  $fieldMap = $this->unprefixRow( $row, 'oi_' );
539  }
540  }
541 
542  if ( isset( $fieldMap['metadata'] ) ) {
543  $fieldMap['metadata'] = $this->repo->getReplicaDB()->decodeBlob( $fieldMap['metadata'] );
544  }
545 
546  return $fieldMap;
547  }
548 
555  protected function unprefixRow( $row, $prefix = 'img_' ) {
556  $array = (array)$row;
557  $prefixLength = strlen( $prefix );
558 
559  // Sanity check prefix once
560  if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
561  throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
562  }
563 
564  $decoded = [];
565  foreach ( $array as $name => $value ) {
566  $decoded[substr( $name, $prefixLength )] = $value;
567  }
568 
569  return $decoded;
570  }
571 
580  function decodeRow( $row, $prefix = 'img_' ) {
581  $decoded = $this->unprefixRow( $row, $prefix );
582 
583  $decoded['description'] = MediaWikiServices::getInstance()->getCommentStore()
584  ->getComment( 'description', (object)$decoded )->text;
585 
586  $decoded['user'] = User::newFromAnyId(
587  $decoded['user'] ?? null,
588  $decoded['user_text'] ?? null,
589  $decoded['actor'] ?? null
590  );
591  unset( $decoded['user_text'], $decoded['actor'] );
592 
593  $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
594 
595  $decoded['metadata'] = $this->repo->getReplicaDB()->decodeBlob( $decoded['metadata'] );
596 
597  if ( empty( $decoded['major_mime'] ) ) {
598  $decoded['mime'] = 'unknown/unknown';
599  } else {
600  if ( !$decoded['minor_mime'] ) {
601  $decoded['minor_mime'] = 'unknown';
602  }
603  $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
604  }
605 
606  // Trim zero padding from char/binary field
607  $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
608 
609  // Normalize some fields to integer type, per their database definition.
610  // Use unary + so that overflows will be upgraded to double instead of
611  // being trucated as with intval(). This is important to allow >2GB
612  // files on 32-bit systems.
613  foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
614  $decoded[$field] = +$decoded[$field];
615  }
616 
617  return $decoded;
618  }
619 
626  function loadFromRow( $row, $prefix = 'img_' ) {
627  $this->dataLoaded = true;
628  $this->extraDataLoaded = true;
629 
630  $array = $this->decodeRow( $row, $prefix );
631 
632  foreach ( $array as $name => $value ) {
633  $this->$name = $value;
634  }
635 
636  $this->fileExists = true;
637  $this->maybeUpgradeRow();
638  }
639 
644  function load( $flags = 0 ) {
645  if ( !$this->dataLoaded ) {
646  if ( $flags & self::READ_LATEST ) {
647  $this->loadFromDB( $flags );
648  } else {
649  $this->loadFromCache();
650  }
651  }
652 
653  if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
654  // @note: loads on name/timestamp to reduce race condition problems
655  $this->loadExtraFromDB();
656  }
657  }
658 
662  function maybeUpgradeRow() {
664 
665  if ( wfReadOnly() || $this->upgrading ) {
666  return;
667  }
668 
669  $upgrade = false;
670  if ( is_null( $this->media_type ) || $this->mime == 'image/svg' ) {
671  $upgrade = true;
672  } else {
673  $handler = $this->getHandler();
674  if ( $handler ) {
675  $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
676  if ( $validity === MediaHandler::METADATA_BAD ) {
677  $upgrade = true;
678  } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE ) {
679  $upgrade = $wgUpdateCompatibleMetadata;
680  }
681  }
682  }
683 
684  if ( $upgrade ) {
685  $this->upgrading = true;
686  // Defer updates unless in auto-commit CLI mode
688  $this->upgrading = false; // avoid duplicate updates
689  try {
690  $this->upgradeRow();
691  } catch ( LocalFileLockError $e ) {
692  // let the other process handle it (or do it next time)
693  }
694  } );
695  }
696  }
697 
701  function getUpgraded() {
702  return $this->upgraded;
703  }
704 
708  function upgradeRow() {
709  $this->lock();
710 
711  $this->loadFromFile();
712 
713  # Don't destroy file info of missing files
714  if ( !$this->fileExists ) {
715  $this->unlock();
716  wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
717 
718  return;
719  }
720 
721  $dbw = $this->repo->getMasterDB();
722  list( $major, $minor ) = self::splitMime( $this->mime );
723 
724  if ( wfReadOnly() ) {
725  $this->unlock();
726 
727  return;
728  }
729  wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
730 
731  $dbw->update( 'image',
732  [
733  'img_size' => $this->size, // sanity
734  'img_width' => $this->width,
735  'img_height' => $this->height,
736  'img_bits' => $this->bits,
737  'img_media_type' => $this->media_type,
738  'img_major_mime' => $major,
739  'img_minor_mime' => $minor,
740  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
741  'img_sha1' => $this->sha1,
742  ],
743  [ 'img_name' => $this->getName() ],
744  __METHOD__
745  );
746 
747  $this->invalidateCache();
748 
749  $this->unlock();
750  $this->upgraded = true; // avoid rework/retries
751  }
752 
763  function setProps( $info ) {
764  $this->dataLoaded = true;
765  $fields = $this->getCacheFields( '' );
766  $fields[] = 'fileExists';
767 
768  foreach ( $fields as $field ) {
769  if ( isset( $info[$field] ) ) {
770  $this->$field = $info[$field];
771  }
772  }
773 
774  if ( isset( $info['user'] ) || isset( $info['user_text'] ) || isset( $info['actor'] ) ) {
775  $this->user = User::newFromAnyId(
776  $info['user'] ?? null,
777  $info['user_text'] ?? null,
778  $info['actor'] ?? null
779  );
780  }
781 
782  // Fix up mime fields
783  if ( isset( $info['major_mime'] ) ) {
784  $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
785  } elseif ( isset( $info['mime'] ) ) {
786  $this->mime = $info['mime'];
787  list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
788  }
789  }
790 
802  function isMissing() {
803  if ( $this->missing === null ) {
804  list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
805  $this->missing = !$fileExists;
806  }
807 
808  return $this->missing;
809  }
810 
817  public function getWidth( $page = 1 ) {
818  $page = (int)$page;
819  if ( $page < 1 ) {
820  $page = 1;
821  }
822 
823  $this->load();
824 
825  if ( $this->isMultipage() ) {
826  $handler = $this->getHandler();
827  if ( !$handler ) {
828  return 0;
829  }
830  $dim = $handler->getPageDimensions( $this, $page );
831  if ( $dim ) {
832  return $dim['width'];
833  } else {
834  // For non-paged media, the false goes through an
835  // intval, turning failure into 0, so do same here.
836  return 0;
837  }
838  } else {
839  return $this->width;
840  }
841  }
842 
849  public function getHeight( $page = 1 ) {
850  $page = (int)$page;
851  if ( $page < 1 ) {
852  $page = 1;
853  }
854 
855  $this->load();
856 
857  if ( $this->isMultipage() ) {
858  $handler = $this->getHandler();
859  if ( !$handler ) {
860  return 0;
861  }
862  $dim = $handler->getPageDimensions( $this, $page );
863  if ( $dim ) {
864  return $dim['height'];
865  } else {
866  // For non-paged media, the false goes through an
867  // intval, turning failure into 0, so do same here.
868  return 0;
869  }
870  } else {
871  return $this->height;
872  }
873  }
874 
882  function getUser( $type = 'text' ) {
883  $this->load();
884 
885  if ( $type === 'object' ) {
886  return $this->user;
887  } elseif ( $type === 'text' ) {
888  return $this->user->getName();
889  } elseif ( $type === 'id' ) {
890  return $this->user->getId();
891  }
892 
893  throw new MWException( "Unknown type '$type'." );
894  }
895 
903  public function getDescriptionShortUrl() {
904  $pageId = $this->title->getArticleID();
905 
906  if ( $pageId !== null ) {
907  $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
908  if ( $url !== false ) {
909  return $url;
910  }
911  }
912  return null;
913  }
914 
919  function getMetadata() {
920  $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
921  return $this->metadata;
922  }
923 
927  function getBitDepth() {
928  $this->load();
929 
930  return (int)$this->bits;
931  }
932 
937  public function getSize() {
938  $this->load();
939 
940  return $this->size;
941  }
942 
947  function getMimeType() {
948  $this->load();
949 
950  return $this->mime;
951  }
952 
958  function getMediaType() {
959  $this->load();
960 
961  return $this->media_type;
962  }
963 
974  public function exists() {
975  $this->load();
976 
977  return $this->fileExists;
978  }
979 
995  function getThumbnails( $archiveName = false ) {
996  if ( $archiveName ) {
997  $dir = $this->getArchiveThumbPath( $archiveName );
998  } else {
999  $dir = $this->getThumbPath();
1000  }
1001 
1002  $backend = $this->repo->getBackend();
1003  $files = [ $dir ];
1004  try {
1005  $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1006  foreach ( $iterator as $file ) {
1007  $files[] = $file;
1008  }
1009  } catch ( FileBackendError $e ) {
1010  } // suppress (T56674)
1011 
1012  return $files;
1013  }
1014 
1018  function purgeMetadataCache() {
1019  $this->invalidateCache();
1020  }
1021 
1029  function purgeCache( $options = [] ) {
1030  // Refresh metadata cache
1031  $this->purgeMetadataCache();
1032 
1033  // Delete thumbnails
1034  $this->purgeThumbnails( $options );
1035 
1036  // Purge CDN cache for this file
1038  new CdnCacheUpdate( [ $this->getUrl() ] ),
1040  );
1041  }
1042 
1047  function purgeOldThumbnails( $archiveName ) {
1048  // Get a list of old thumbnails and URLs
1049  $files = $this->getThumbnails( $archiveName );
1050 
1051  // Purge any custom thumbnail caches
1052  Hooks::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1053 
1054  // Delete thumbnails
1055  $dir = array_shift( $files );
1056  $this->purgeThumbList( $dir, $files );
1057 
1058  // Purge the CDN
1059  $urls = [];
1060  foreach ( $files as $file ) {
1061  $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1062  }
1064  }
1065 
1070  public function purgeThumbnails( $options = [] ) {
1071  $files = $this->getThumbnails();
1072  // Always purge all files from CDN regardless of handler filters
1073  $urls = [];
1074  foreach ( $files as $file ) {
1075  $urls[] = $this->getThumbUrl( $file );
1076  }
1077  array_shift( $urls ); // don't purge directory
1078 
1079  // Give media handler a chance to filter the file purge list
1080  if ( !empty( $options['forThumbRefresh'] ) ) {
1081  $handler = $this->getHandler();
1082  if ( $handler ) {
1084  }
1085  }
1086 
1087  // Purge any custom thumbnail caches
1088  Hooks::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1089 
1090  // Delete thumbnails
1091  $dir = array_shift( $files );
1092  $this->purgeThumbList( $dir, $files );
1093 
1094  // Purge the CDN
1096  }
1097 
1103  public function prerenderThumbnails() {
1105 
1106  $jobs = [];
1107 
1108  $sizes = $wgUploadThumbnailRenderMap;
1109  rsort( $sizes );
1110 
1111  foreach ( $sizes as $size ) {
1112  if ( $this->isVectorized() || $this->getWidth() > $size ) {
1113  $jobs[] = new ThumbnailRenderJob(
1114  $this->getTitle(),
1115  [ 'transformParams' => [ 'width' => $size ] ]
1116  );
1117  }
1118  }
1119 
1120  if ( $jobs ) {
1121  JobQueueGroup::singleton()->lazyPush( $jobs );
1122  }
1123  }
1124 
1130  protected function purgeThumbList( $dir, $files ) {
1131  $fileListDebug = strtr(
1132  var_export( $files, true ),
1133  [ "\n" => '' ]
1134  );
1135  wfDebug( __METHOD__ . ": $fileListDebug\n" );
1136 
1137  $purgeList = [];
1138  foreach ( $files as $file ) {
1139  if ( $this->repo->supportsSha1URLs() ) {
1140  $reference = $this->getSha1();
1141  } else {
1142  $reference = $this->getName();
1143  }
1144 
1145  # Check that the reference (filename or sha1) is part of the thumb name
1146  # This is a basic sanity check to avoid erasing unrelated directories
1147  if ( strpos( $file, $reference ) !== false
1148  || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1149  ) {
1150  $purgeList[] = "{$dir}/{$file}";
1151  }
1152  }
1153 
1154  # Delete the thumbnails
1155  $this->repo->quickPurgeBatch( $purgeList );
1156  # Clear out the thumbnail directory if empty
1157  $this->repo->quickCleanDir( $dir );
1158  }
1159 
1170  function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1171  $dbr = $this->repo->getReplicaDB();
1172  $oldFileQuery = OldLocalFile::getQueryInfo();
1173 
1174  $tables = $oldFileQuery['tables'];
1175  $fields = $oldFileQuery['fields'];
1176  $join_conds = $oldFileQuery['joins'];
1177  $conds = $opts = [];
1178  $eq = $inc ? '=' : '';
1179  $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1180 
1181  if ( $start ) {
1182  $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1183  }
1184 
1185  if ( $end ) {
1186  $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1187  }
1188 
1189  if ( $limit ) {
1190  $opts['LIMIT'] = $limit;
1191  }
1192 
1193  // Search backwards for time > x queries
1194  $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1195  $opts['ORDER BY'] = "oi_timestamp $order";
1196  $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1197 
1198  // Avoid PHP 7.1 warning from passing $this by reference
1199  $localFile = $this;
1200  Hooks::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1201  &$conds, &$opts, &$join_conds ] );
1202 
1203  $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1204  $r = [];
1205 
1206  foreach ( $res as $row ) {
1207  $r[] = $this->repo->newFileFromRow( $row );
1208  }
1209 
1210  if ( $order == 'ASC' ) {
1211  $r = array_reverse( $r ); // make sure it ends up descending
1212  }
1213 
1214  return $r;
1215  }
1216 
1226  public function nextHistoryLine() {
1227  # Polymorphic function name to distinguish foreign and local fetches
1228  $fname = static::class . '::' . __FUNCTION__;
1229 
1230  $dbr = $this->repo->getReplicaDB();
1231 
1232  if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1233  $fileQuery = self::getQueryInfo();
1234  $this->historyRes = $dbr->select( $fileQuery['tables'],
1235  $fileQuery['fields'] + [
1236  'oi_archive_name' => $dbr->addQuotes( '' ),
1237  'oi_deleted' => 0,
1238  ],
1239  [ 'img_name' => $this->title->getDBkey() ],
1240  $fname,
1241  [],
1242  $fileQuery['joins']
1243  );
1244 
1245  if ( $dbr->numRows( $this->historyRes ) == 0 ) {
1246  $this->historyRes = null;
1247 
1248  return false;
1249  }
1250  } elseif ( $this->historyLine == 1 ) {
1251  $fileQuery = OldLocalFile::getQueryInfo();
1252  $this->historyRes = $dbr->select(
1253  $fileQuery['tables'],
1254  $fileQuery['fields'],
1255  [ 'oi_name' => $this->title->getDBkey() ],
1256  $fname,
1257  [ 'ORDER BY' => 'oi_timestamp DESC' ],
1258  $fileQuery['joins']
1259  );
1260  }
1261  $this->historyLine++;
1262 
1263  return $dbr->fetchObject( $this->historyRes );
1264  }
1265 
1269  public function resetHistory() {
1270  $this->historyLine = 0;
1271 
1272  if ( !is_null( $this->historyRes ) ) {
1273  $this->historyRes = null;
1274  }
1275  }
1276 
1309  function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1310  $timestamp = false, $user = null, $tags = [],
1311  $createNullRevision = true
1312  ) {
1313  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1314  return $this->readOnlyFatalStatus();
1315  } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1316  // Check this in advance to avoid writing to FileBackend and the file tables,
1317  // only to fail on insert the revision due to the text store being unavailable.
1318  return $this->readOnlyFatalStatus();
1319  }
1320 
1321  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1322  if ( !$props ) {
1323  if ( FileRepo::isVirtualUrl( $srcPath )
1324  || FileBackend::isStoragePath( $srcPath )
1325  ) {
1326  $props = $this->repo->getFileProps( $srcPath );
1327  } else {
1328  $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1329  $props = $mwProps->getPropsFromPath( $srcPath, true );
1330  }
1331  }
1332 
1333  $options = [];
1334  $handler = MediaHandler::getHandler( $props['mime'] );
1335  if ( $handler ) {
1336  $metadata = Wikimedia\quietCall( 'unserialize', $props['metadata'] );
1337 
1338  if ( !is_array( $metadata ) ) {
1339  $metadata = [];
1340  }
1341 
1342  $options['headers'] = $handler->getContentHeaders( $metadata );
1343  } else {
1344  $options['headers'] = [];
1345  }
1346 
1347  // Trim spaces on user supplied text
1348  $comment = trim( $comment );
1349 
1350  $this->lock();
1351  $status = $this->publish( $src, $flags, $options );
1352 
1353  if ( $status->successCount >= 2 ) {
1354  // There will be a copy+(one of move,copy,store).
1355  // The first succeeding does not commit us to updating the DB
1356  // since it simply copied the current version to a timestamped file name.
1357  // It is only *preferable* to avoid leaving such files orphaned.
1358  // Once the second operation goes through, then the current version was
1359  // updated and we must therefore update the DB too.
1360  $oldver = $status->value;
1361  $uploadStatus = $this->recordUpload2(
1362  $oldver,
1363  $comment,
1364  $pageText,
1365  $props,
1366  $timestamp,
1367  $user,
1368  $tags,
1369  $createNullRevision
1370  );
1371  if ( !$uploadStatus->isOK() ) {
1372  if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1373  // update filenotfound error with more specific path
1374  $status->fatal( 'filenotfound', $srcPath );
1375  } else {
1376  $status->merge( $uploadStatus );
1377  }
1378  }
1379  }
1380 
1381  $this->unlock();
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  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1474  $actorMigration = ActorMigration::newMigration();
1475  $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1476  $dbw->insert( 'image',
1477  [
1478  'img_name' => $this->getName(),
1479  'img_size' => $this->size,
1480  'img_width' => intval( $this->width ),
1481  'img_height' => intval( $this->height ),
1482  'img_bits' => $this->bits,
1483  'img_media_type' => $this->media_type,
1484  'img_major_mime' => $this->major_mime,
1485  'img_minor_mime' => $this->minor_mime,
1486  'img_timestamp' => $timestamp,
1487  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1488  'img_sha1' => $this->sha1
1489  ] + $commentFields + $actorFields,
1490  __METHOD__,
1491  'IGNORE'
1492  );
1493  $reupload = ( $dbw->affectedRows() == 0 );
1494 
1495  if ( $reupload ) {
1496  $row = $dbw->selectRow(
1497  'image',
1498  [ 'img_timestamp', 'img_sha1' ],
1499  [ 'img_name' => $this->getName() ],
1500  __METHOD__,
1501  [ 'LOCK IN SHARE MODE' ]
1502  );
1503 
1504  if ( $row && $row->img_sha1 === $this->sha1 ) {
1505  $dbw->endAtomic( __METHOD__ );
1506  wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!\n" );
1507  $title = Title::newFromText( $this->getName(), NS_FILE );
1508  return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1509  }
1510 
1511  if ( $allowTimeKludge ) {
1512  # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1513  $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1514  # Avoid a timestamp that is not newer than the last version
1515  # TODO: the image/oldimage tables should be like page/revision with an ID field
1516  if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1517  sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1518  $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1519  $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1520  }
1521  }
1522 
1523  $tables = [ 'image' ];
1524  $fields = [
1525  'oi_name' => 'img_name',
1526  'oi_archive_name' => $dbw->addQuotes( $oldver ),
1527  'oi_size' => 'img_size',
1528  'oi_width' => 'img_width',
1529  'oi_height' => 'img_height',
1530  'oi_bits' => 'img_bits',
1531  'oi_description_id' => 'img_description_id',
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 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
1542  $fields['oi_user'] = 'img_user';
1543  $fields['oi_user_text'] = 'img_user_text';
1544  }
1545  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
1546  $fields['oi_actor'] = 'img_actor';
1547  }
1548 
1549  if (
1550  ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH ) === SCHEMA_COMPAT_WRITE_BOTH
1551  ) {
1552  // Upgrade any rows that are still old-style. Otherwise an upgrade
1553  // might be missed if a deletion happens while the migration script
1554  // is running.
1555  $res = $dbw->select(
1556  [ 'image' ],
1557  [ 'img_name', 'img_user', 'img_user_text' ],
1558  [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1559  __METHOD__
1560  );
1561  foreach ( $res as $row ) {
1562  $actorId = User::newFromAnyId( $row->img_user, $row->img_user_text, null )->getActorId( $dbw );
1563  $dbw->update(
1564  'image',
1565  [ 'img_actor' => $actorId ],
1566  [ 'img_name' => $row->img_name, 'img_actor' => 0 ],
1567  __METHOD__
1568  );
1569  }
1570  }
1571 
1572  # (T36993) Note: $oldver can be empty here, if the previous
1573  # version of the file was broken. Allow registration of the new
1574  # version to continue anyway, because that's better than having
1575  # an image that's not fixable by user operations.
1576  # Collision, this is an update of a file
1577  # Insert previous contents into oldimage
1578  $dbw->insertSelect( 'oldimage', $tables, $fields,
1579  [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1580 
1581  # Update the current image row
1582  $dbw->update( 'image',
1583  [
1584  'img_size' => $this->size,
1585  'img_width' => intval( $this->width ),
1586  'img_height' => intval( $this->height ),
1587  'img_bits' => $this->bits,
1588  'img_media_type' => $this->media_type,
1589  'img_major_mime' => $this->major_mime,
1590  'img_minor_mime' => $this->minor_mime,
1591  'img_timestamp' => $timestamp,
1592  'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1593  'img_sha1' => $this->sha1
1594  ] + $commentFields + $actorFields,
1595  [ 'img_name' => $this->getName() ],
1596  __METHOD__
1597  );
1598  }
1599 
1600  $descTitle = $this->getTitle();
1601  $descId = $descTitle->getArticleID();
1602  $wikiPage = new WikiFilePage( $descTitle );
1603  $wikiPage->setFile( $this );
1604 
1605  // Add the log entry...
1606  $logEntry = new ManualLogEntry( 'upload', $reupload ? 'overwrite' : 'upload' );
1607  $logEntry->setTimestamp( $this->timestamp );
1608  $logEntry->setPerformer( $user );
1609  $logEntry->setComment( $comment );
1610  $logEntry->setTarget( $descTitle );
1611  // Allow people using the api to associate log entries with the upload.
1612  // Log has a timestamp, but sometimes different from upload timestamp.
1613  $logEntry->setParameters(
1614  [
1615  'img_sha1' => $this->sha1,
1616  'img_timestamp' => $timestamp,
1617  ]
1618  );
1619  // Note we keep $logId around since during new image
1620  // creation, page doesn't exist yet, so log_page = 0
1621  // but we want it to point to the page we're making,
1622  // so we later modify the log entry.
1623  // For a similar reason, we avoid making an RC entry
1624  // now and wait until the page exists.
1625  $logId = $logEntry->insert();
1626 
1627  if ( $descTitle->exists() ) {
1628  // Use own context to get the action text in content language
1629  $formatter = LogFormatter::newFromEntry( $logEntry );
1630  $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1631  $editSummary = $formatter->getPlainActionText();
1632 
1633  $nullRevision = $createNullRevision === false ? null : Revision::newNullRevision(
1634  $dbw,
1635  $descId,
1636  $editSummary,
1637  false,
1638  $user
1639  );
1640  if ( $nullRevision ) {
1641  $nullRevision->insertOn( $dbw );
1642  Hooks::run(
1643  'NewRevisionFromEditComplete',
1644  [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1645  );
1646  $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1647  // Associate null revision id
1648  $logEntry->setAssociatedRevId( $nullRevision->getId() );
1649  }
1650 
1651  $newPageContent = null;
1652  } else {
1653  // Make the description page and RC log entry post-commit
1654  $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1655  }
1656 
1657  # Defer purges, page creation, and link updates in case they error out.
1658  # The most important thing is that files and the DB registry stay synced.
1659  $dbw->endAtomic( __METHOD__ );
1660  $fname = __METHOD__;
1661 
1662  # Do some cache purges after final commit so that:
1663  # a) Changes are more likely to be seen post-purge
1664  # b) They won't cause rollback of the log publish/update above
1666  new AutoCommitUpdate(
1667  $dbw,
1668  __METHOD__,
1669  function () use (
1670  $reupload, $wikiPage, $newPageContent, $comment, $user,
1671  $logEntry, $logId, $descId, $tags, $fname
1672  ) {
1673  # Update memcache after the commit
1674  $this->invalidateCache();
1675 
1676  $updateLogPage = false;
1677  if ( $newPageContent ) {
1678  # New file page; create the description page.
1679  # There's already a log entry, so don't make a second RC entry
1680  # CDN and file cache for the description page are purged by doEditContent.
1681  $status = $wikiPage->doEditContent(
1682  $newPageContent,
1683  $comment,
1685  false,
1686  $user
1687  );
1688 
1689  if ( isset( $status->value['revision'] ) ) {
1691  $rev = $status->value['revision'];
1692  // Associate new page revision id
1693  $logEntry->setAssociatedRevId( $rev->getId() );
1694  }
1695  // This relies on the resetArticleID() call in WikiPage::insertOn(),
1696  // which is triggered on $descTitle by doEditContent() above.
1697  if ( isset( $status->value['revision'] ) ) {
1699  $rev = $status->value['revision'];
1700  $updateLogPage = $rev->getPage();
1701  }
1702  } else {
1703  # Existing file page: invalidate description page cache
1704  $wikiPage->getTitle()->invalidateCache();
1705  $wikiPage->getTitle()->purgeSquid();
1706  # Allow the new file version to be patrolled from the page footer
1708  }
1709 
1710  # Update associated rev id. This should be done by $logEntry->insert() earlier,
1711  # but setAssociatedRevId() wasn't called at that point yet...
1712  $logParams = $logEntry->getParameters();
1713  $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1714  $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1715  if ( $updateLogPage ) {
1716  # Also log page, in case where we just created it above
1717  $update['log_page'] = $updateLogPage;
1718  }
1719  $this->getRepo()->getMasterDB()->update(
1720  'logging',
1721  $update,
1722  [ 'log_id' => $logId ],
1723  $fname
1724  );
1725  $this->getRepo()->getMasterDB()->insert(
1726  'log_search',
1727  [
1728  'ls_field' => 'associated_rev_id',
1729  'ls_value' => $logEntry->getAssociatedRevId(),
1730  'ls_log_id' => $logId,
1731  ],
1732  $fname
1733  );
1734 
1735  # Add change tags, if any
1736  if ( $tags ) {
1737  $logEntry->setTags( $tags );
1738  }
1739 
1740  # Uploads can be patrolled
1741  $logEntry->setIsPatrollable( true );
1742 
1743  # Now that the log entry is up-to-date, make an RC entry.
1744  $logEntry->publish( $logId );
1745 
1746  # Run hook for other updates (typically more cache purging)
1747  Hooks::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1748 
1749  if ( $reupload ) {
1750  # Delete old thumbnails
1751  $this->purgeThumbnails();
1752  # Remove the old file from the CDN cache
1754  new CdnCacheUpdate( [ $this->getUrl() ] ),
1756  );
1757  } else {
1758  # Update backlink pages pointing to this title if created
1760  $this->getTitle(),
1761  'imagelinks',
1762  'upload-image',
1763  $user->getName()
1764  );
1765  }
1766 
1767  $this->prerenderThumbnails();
1768  }
1769  ),
1771  );
1772 
1773  if ( !$reupload ) {
1774  # This is a new file, so update the image count
1775  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1776  }
1777 
1778  # Invalidate cache for all pages using this file
1780  new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1781  );
1782 
1783  return Status::newGood();
1784  }
1785 
1801  function publish( $src, $flags = 0, array $options = [] ) {
1802  return $this->publishTo( $src, $this->getRel(), $flags, $options );
1803  }
1804 
1820  function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1821  $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1822 
1823  $repo = $this->getRepo();
1824  if ( $repo->getReadOnlyReason() !== false ) {
1825  return $this->readOnlyFatalStatus();
1826  }
1827 
1828  $this->lock();
1829 
1830  $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1831  $archiveRel = $this->getArchiveRel( $archiveName );
1832 
1833  if ( $repo->hasSha1Storage() ) {
1834  $sha1 = FileRepo::isVirtualUrl( $srcPath )
1835  ? $repo->getFileSha1( $srcPath )
1836  : FSFile::getSha1Base36FromPath( $srcPath );
1838  $wrapperBackend = $repo->getBackend();
1839  $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1840  $status = $repo->quickImport( $src, $dst );
1841  if ( $flags & File::DELETE_SOURCE ) {
1842  unlink( $srcPath );
1843  }
1844 
1845  if ( $this->exists() ) {
1846  $status->value = $archiveName;
1847  }
1848  } else {
1849  $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1850  $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1851 
1852  if ( $status->value == 'new' ) {
1853  $status->value = '';
1854  } else {
1855  $status->value = $archiveName;
1856  }
1857  }
1858 
1859  $this->unlock();
1860  return $status;
1861  }
1862 
1880  function move( $target ) {
1881  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1882  return $this->readOnlyFatalStatus();
1883  }
1884 
1885  wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1886  $batch = new LocalFileMoveBatch( $this, $target );
1887 
1888  $this->lock();
1889  $batch->addCurrent();
1890  $archiveNames = $batch->addOlds();
1891  $status = $batch->execute();
1892  $this->unlock();
1893 
1894  wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1895 
1896  // Purge the source and target files...
1897  $oldTitleFile = wfLocalFile( $this->title );
1898  $newTitleFile = wfLocalFile( $target );
1899  // To avoid slow purges in the transaction, move them outside...
1901  new AutoCommitUpdate(
1902  $this->getRepo()->getMasterDB(),
1903  __METHOD__,
1904  function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1905  $oldTitleFile->purgeEverything();
1906  foreach ( $archiveNames as $archiveName ) {
1907  $oldTitleFile->purgeOldThumbnails( $archiveName );
1908  }
1909  $newTitleFile->purgeEverything();
1910  }
1911  ),
1913  );
1914 
1915  if ( $status->isOK() ) {
1916  // Now switch the object
1917  $this->title = $target;
1918  // Force regeneration of the name and hashpath
1919  unset( $this->name );
1920  unset( $this->hashPath );
1921  }
1922 
1923  return $status;
1924  }
1925 
1939  function delete( $reason, $suppress = false, $user = null ) {
1940  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1941  return $this->readOnlyFatalStatus();
1942  }
1943 
1944  $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1945 
1946  $this->lock();
1947  $batch->addCurrent();
1948  // Get old version relative paths
1949  $archiveNames = $batch->addOlds();
1950  $status = $batch->execute();
1951  $this->unlock();
1952 
1953  if ( $status->isOK() ) {
1954  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
1955  }
1956 
1957  // To avoid slow purges in the transaction, move them outside...
1959  new AutoCommitUpdate(
1960  $this->getRepo()->getMasterDB(),
1961  __METHOD__,
1962  function () use ( $archiveNames ) {
1963  $this->purgeEverything();
1964  foreach ( $archiveNames as $archiveName ) {
1965  $this->purgeOldThumbnails( $archiveName );
1966  }
1967  }
1968  ),
1970  );
1971 
1972  // Purge the CDN
1973  $purgeUrls = [];
1974  foreach ( $archiveNames as $archiveName ) {
1975  $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1976  }
1978 
1979  return $status;
1980  }
1981 
1997  function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1998  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1999  return $this->readOnlyFatalStatus();
2000  }
2001 
2002  $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2003 
2004  $this->lock();
2005  $batch->addOld( $archiveName );
2006  $status = $batch->execute();
2007  $this->unlock();
2008 
2009  $this->purgeOldThumbnails( $archiveName );
2010  if ( $status->isOK() ) {
2011  $this->purgeDescription();
2012  }
2013 
2015  new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2017  );
2018 
2019  return $status;
2020  }
2021 
2033  function restore( $versions = [], $unsuppress = false ) {
2034  if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2035  return $this->readOnlyFatalStatus();
2036  }
2037 
2038  $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2039 
2040  $this->lock();
2041  if ( !$versions ) {
2042  $batch->addAll();
2043  } else {
2044  $batch->addIds( $versions );
2045  }
2046  $status = $batch->execute();
2047  if ( $status->isGood() ) {
2048  $cleanupStatus = $batch->cleanup();
2049  $cleanupStatus->successCount = 0;
2050  $cleanupStatus->failCount = 0;
2051  $status->merge( $cleanupStatus );
2052  }
2053 
2054  $this->unlock();
2055  return $status;
2056  }
2057 
2067  function getDescriptionUrl() {
2068  return $this->title->getLocalURL();
2069  }
2070 
2080  $store = MediaWikiServices::getInstance()->getRevisionStore();
2081  $revision = $store->getRevisionByTitle( $this->title, 0, Revision::READ_NORMAL );
2082  if ( !$revision ) {
2083  return false;
2084  }
2085 
2086  $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2087  $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2088 
2089  if ( !$rendered ) {
2090  // audience check failed
2091  return false;
2092  }
2093 
2094  $pout = $rendered->getRevisionParserOutput();
2095  return $pout->getText();
2096  }
2097 
2103  function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2104  $this->load();
2105  if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2106  return '';
2107  } elseif ( $audience == self::FOR_THIS_USER
2108  && !$this->userCan( self::DELETED_COMMENT, $user )
2109  ) {
2110  return '';
2111  } else {
2112  return $this->description;
2113  }
2114  }
2115 
2119  function getTimestamp() {
2120  $this->load();
2121 
2122  return $this->timestamp;
2123  }
2124 
2128  public function getDescriptionTouched() {
2129  // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2130  // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2131  // need to differentiate between null (uninitialized) and false (failed to load).
2132  if ( $this->descriptionTouched === null ) {
2133  $cond = [
2134  'page_namespace' => $this->title->getNamespace(),
2135  'page_title' => $this->title->getDBkey()
2136  ];
2137  $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2138  $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2139  }
2140 
2142  }
2143 
2147  function getSha1() {
2148  $this->load();
2149  // Initialise now if necessary
2150  if ( $this->sha1 == '' && $this->fileExists ) {
2151  $this->lock();
2152 
2153  $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2154  if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2155  $dbw = $this->repo->getMasterDB();
2156  $dbw->update( 'image',
2157  [ 'img_sha1' => $this->sha1 ],
2158  [ 'img_name' => $this->getName() ],
2159  __METHOD__ );
2160  $this->invalidateCache();
2161  }
2162 
2163  $this->unlock();
2164  }
2165 
2166  return $this->sha1;
2167  }
2168 
2172  function isCacheable() {
2173  $this->load();
2174 
2175  // If extra data (metadata) was not loaded then it must have been large
2176  return $this->extraDataLoaded
2177  && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
2178  }
2179 
2184  public function acquireFileLock() {
2185  return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2186  [ $this->getPath() ], LockManager::LOCK_EX, 10
2187  ) );
2188  }
2189 
2194  public function releaseFileLock() {
2195  return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2196  [ $this->getPath() ], LockManager::LOCK_EX
2197  ) );
2198  }
2199 
2209  public function lock() {
2210  if ( !$this->locked ) {
2211  $logger = LoggerFactory::getInstance( 'LocalFile' );
2212 
2213  $dbw = $this->repo->getMasterDB();
2214  $makesTransaction = !$dbw->trxLevel();
2215  $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2216  // T56736: use simple lock to handle when the file does not exist.
2217  // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2218  // Also, that would cause contention on INSERT of similarly named rows.
2219  $status = $this->acquireFileLock(); // represents all versions of the file
2220  if ( !$status->isGood() ) {
2221  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2222  $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2223 
2224  throw new LocalFileLockError( $status );
2225  }
2226  // Release the lock *after* commit to avoid row-level contention.
2227  // Make sure it triggers on rollback() as well as commit() (T132921).
2228  $dbw->onTransactionResolution(
2229  function () use ( $logger ) {
2230  $status = $this->releaseFileLock();
2231  if ( !$status->isGood() ) {
2232  $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2233  }
2234  },
2235  __METHOD__
2236  );
2237  // Callers might care if the SELECT snapshot is safely fresh
2238  $this->lockedOwnTrx = $makesTransaction;
2239  }
2240 
2241  $this->locked++;
2242 
2243  return $this->lockedOwnTrx;
2244  }
2245 
2254  public function unlock() {
2255  if ( $this->locked ) {
2256  --$this->locked;
2257  if ( !$this->locked ) {
2258  $dbw = $this->repo->getMasterDB();
2259  $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2260  $this->lockedOwnTrx = false;
2261  }
2262  }
2263  }
2264 
2268  protected function readOnlyFatalStatus() {
2269  return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2270  $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2271  }
2272 
2276  function __destruct() {
2277  $this->unlock();
2278  }
2279 } // LocalFile class
2280 
2281 # ------------------------------------------------------------------------------
2282 
2289  private $file;
2290 
2292  private $reason;
2293 
2295  private $srcRels = [];
2296 
2298  private $archiveUrls = [];
2299 
2302 
2304  private $suppress;
2305 
2307  private $status;
2308 
2310  private $user;
2311 
2318  function __construct( File $file, $reason = '', $suppress = false, $user = null ) {
2319  $this->file = $file;
2320  $this->reason = $reason;
2321  $this->suppress = $suppress;
2322  if ( $user ) {
2323  $this->user = $user;
2324  } else {
2325  global $wgUser;
2326  $this->user = $wgUser;
2327  }
2328  $this->status = $file->repo->newGood();
2329  }
2330 
2331  public function addCurrent() {
2332  $this->srcRels['.'] = $this->file->getRel();
2333  }
2334 
2338  public function addOld( $oldName ) {
2339  $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
2340  $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
2341  }
2342 
2347  public function addOlds() {
2348  $archiveNames = [];
2349 
2350  $dbw = $this->file->repo->getMasterDB();
2351  $result = $dbw->select( 'oldimage',
2352  [ 'oi_archive_name' ],
2353  [ 'oi_name' => $this->file->getName() ],
2354  __METHOD__
2355  );
2356 
2357  foreach ( $result as $row ) {
2358  $this->addOld( $row->oi_archive_name );
2359  $archiveNames[] = $row->oi_archive_name;
2360  }
2361 
2362  return $archiveNames;
2363  }
2364 
2368  protected function getOldRels() {
2369  if ( !isset( $this->srcRels['.'] ) ) {
2370  $oldRels =& $this->srcRels;
2371  $deleteCurrent = false;
2372  } else {
2373  $oldRels = $this->srcRels;
2374  unset( $oldRels['.'] );
2375  $deleteCurrent = true;
2376  }
2377 
2378  return [ $oldRels, $deleteCurrent ];
2379  }
2380 
2384  protected function getHashes() {
2385  $hashes = [];
2386  list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2387 
2388  if ( $deleteCurrent ) {
2389  $hashes['.'] = $this->file->getSha1();
2390  }
2391 
2392  if ( count( $oldRels ) ) {
2393  $dbw = $this->file->repo->getMasterDB();
2394  $res = $dbw->select(
2395  'oldimage',
2396  [ 'oi_archive_name', 'oi_sha1' ],
2397  [ 'oi_archive_name' => array_keys( $oldRels ),
2398  'oi_name' => $this->file->getName() ], // performance
2399  __METHOD__
2400  );
2401 
2402  foreach ( $res as $row ) {
2403  if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
2404  // Get the hash from the file
2405  $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2406  $props = $this->file->repo->getFileProps( $oldUrl );
2407 
2408  if ( $props['fileExists'] ) {
2409  // Upgrade the oldimage row
2410  $dbw->update( 'oldimage',
2411  [ 'oi_sha1' => $props['sha1'] ],
2412  [ 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ],
2413  __METHOD__ );
2414  $hashes[$row->oi_archive_name] = $props['sha1'];
2415  } else {
2416  $hashes[$row->oi_archive_name] = false;
2417  }
2418  } else {
2419  $hashes[$row->oi_archive_name] = $row->oi_sha1;
2420  }
2421  }
2422  }
2423 
2424  $missing = array_diff_key( $this->srcRels, $hashes );
2425 
2426  foreach ( $missing as $name => $rel ) {
2427  $this->status->error( 'filedelete-old-unregistered', $name );
2428  }
2429 
2430  foreach ( $hashes as $name => $hash ) {
2431  if ( !$hash ) {
2432  $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2433  unset( $hashes[$name] );
2434  }
2435  }
2436 
2437  return $hashes;
2438  }
2439 
2440  protected function doDBInserts() {
2442 
2443  $now = time();
2444  $dbw = $this->file->repo->getMasterDB();
2445 
2446  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
2447  $actorMigration = ActorMigration::newMigration();
2448 
2449  $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2450  $encUserId = $dbw->addQuotes( $this->user->getId() );
2451  $encGroup = $dbw->addQuotes( 'deleted' );
2452  $ext = $this->file->getExtension();
2453  $dotExt = $ext === '' ? '' : ".$ext";
2454  $encExt = $dbw->addQuotes( $dotExt );
2455  list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2456 
2457  // Bitfields to further suppress the content
2458  if ( $this->suppress ) {
2459  $bitfield = Revision::SUPPRESSED_ALL;
2460  } else {
2461  $bitfield = 'oi_deleted';
2462  }
2463 
2464  if ( $deleteCurrent ) {
2465  $tables = [ 'image' ];
2466  $fields = [
2467  'fa_storage_group' => $encGroup,
2468  'fa_storage_key' => $dbw->conditional(
2469  [ 'img_sha1' => '' ],
2470  $dbw->addQuotes( '' ),
2471  $dbw->buildConcat( [ "img_sha1", $encExt ] )
2472  ),
2473  'fa_deleted_user' => $encUserId,
2474  'fa_deleted_timestamp' => $encTimestamp,
2475  'fa_deleted' => $this->suppress ? $bitfield : 0,
2476  'fa_name' => 'img_name',
2477  'fa_archive_name' => 'NULL',
2478  'fa_size' => 'img_size',
2479  'fa_width' => 'img_width',
2480  'fa_height' => 'img_height',
2481  'fa_metadata' => 'img_metadata',
2482  'fa_bits' => 'img_bits',
2483  'fa_media_type' => 'img_media_type',
2484  'fa_major_mime' => 'img_major_mime',
2485  'fa_minor_mime' => 'img_minor_mime',
2486  'fa_description_id' => 'img_description_id',
2487  'fa_timestamp' => 'img_timestamp',
2488  'fa_sha1' => 'img_sha1'
2489  ];
2490  $joins = [];
2491 
2492  $fields += array_map(
2493  [ $dbw, 'addQuotes' ],
2494  $commentStore->insert( $dbw, 'fa_deleted_reason', $this->reason )
2495  );
2496 
2497  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
2498  $fields['fa_user'] = 'img_user';
2499  $fields['fa_user_text'] = 'img_user_text';
2500  }
2501  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
2502  $fields['fa_actor'] = 'img_actor';
2503  }
2504 
2505  if (
2506  ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH ) === SCHEMA_COMPAT_WRITE_BOTH
2507  ) {
2508  // Upgrade any rows that are still old-style. Otherwise an upgrade
2509  // might be missed if a deletion happens while the migration script
2510  // is running.
2511  $res = $dbw->select(
2512  [ 'image' ],
2513  [ 'img_name', 'img_user', 'img_user_text' ],
2514  [ 'img_name' => $this->file->getName(), 'img_actor' => 0 ],
2515  __METHOD__
2516  );
2517  foreach ( $res as $row ) {
2518  $actorId = User::newFromAnyId( $row->img_user, $row->img_user_text, null )->getActorId( $dbw );
2519  $dbw->update(
2520  'image',
2521  [ 'img_actor' => $actorId ],
2522  [ 'img_name' => $row->img_name, 'img_actor' => 0 ],
2523  __METHOD__
2524  );
2525  }
2526  }
2527 
2528  $dbw->insertSelect( 'filearchive', $tables, $fields,
2529  [ 'img_name' => $this->file->getName() ], __METHOD__, [], [], $joins );
2530  }
2531 
2532  if ( count( $oldRels ) ) {
2533  $fileQuery = OldLocalFile::getQueryInfo();
2534  $res = $dbw->select(
2535  $fileQuery['tables'],
2536  $fileQuery['fields'],
2537  [
2538  'oi_name' => $this->file->getName(),
2539  'oi_archive_name' => array_keys( $oldRels )
2540  ],
2541  __METHOD__,
2542  [ 'FOR UPDATE' ],
2543  $fileQuery['joins']
2544  );
2545  $rowsInsert = [];
2546  if ( $res->numRows() ) {
2547  $reason = $commentStore->createComment( $dbw, $this->reason );
2548  foreach ( $res as $row ) {
2549  $comment = $commentStore->getComment( 'oi_description', $row );
2550  $user = User::newFromAnyId( $row->oi_user, $row->oi_user_text, $row->oi_actor );
2551  $rowsInsert[] = [
2552  // Deletion-specific fields
2553  'fa_storage_group' => 'deleted',
2554  'fa_storage_key' => ( $row->oi_sha1 === '' )
2555  ? ''
2556  : "{$row->oi_sha1}{$dotExt}",
2557  'fa_deleted_user' => $this->user->getId(),
2558  'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2559  // Counterpart fields
2560  'fa_deleted' => $this->suppress ? $bitfield : $row->oi_deleted,
2561  'fa_name' => $row->oi_name,
2562  'fa_archive_name' => $row->oi_archive_name,
2563  'fa_size' => $row->oi_size,
2564  'fa_width' => $row->oi_width,
2565  'fa_height' => $row->oi_height,
2566  'fa_metadata' => $row->oi_metadata,
2567  'fa_bits' => $row->oi_bits,
2568  'fa_media_type' => $row->oi_media_type,
2569  'fa_major_mime' => $row->oi_major_mime,
2570  'fa_minor_mime' => $row->oi_minor_mime,
2571  'fa_timestamp' => $row->oi_timestamp,
2572  'fa_sha1' => $row->oi_sha1
2573  ] + $commentStore->insert( $dbw, 'fa_deleted_reason', $reason )
2574  + $commentStore->insert( $dbw, 'fa_description', $comment )
2575  + $actorMigration->getInsertValues( $dbw, 'fa_user', $user );
2576  }
2577  }
2578 
2579  $dbw->insert( 'filearchive', $rowsInsert, __METHOD__ );
2580  }
2581  }
2582 
2583  function doDBDeletes() {
2584  $dbw = $this->file->repo->getMasterDB();
2585  list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2586 
2587  if ( count( $oldRels ) ) {
2588  $dbw->delete( 'oldimage',
2589  [
2590  'oi_name' => $this->file->getName(),
2591  'oi_archive_name' => array_keys( $oldRels )
2592  ], __METHOD__ );
2593  }
2594 
2595  if ( $deleteCurrent ) {
2596  $dbw->delete( 'image', [ 'img_name' => $this->file->getName() ], __METHOD__ );
2597  }
2598  }
2599 
2604  public function execute() {
2605  $repo = $this->file->getRepo();
2606  $this->file->lock();
2607 
2608  // Prepare deletion batch
2609  $hashes = $this->getHashes();
2610  $this->deletionBatch = [];
2611  $ext = $this->file->getExtension();
2612  $dotExt = $ext === '' ? '' : ".$ext";
2613 
2614  foreach ( $this->srcRels as $name => $srcRel ) {
2615  // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2616  if ( isset( $hashes[$name] ) ) {
2617  $hash = $hashes[$name];
2618  $key = $hash . $dotExt;
2619  $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2620  $this->deletionBatch[$name] = [ $srcRel, $dstRel ];
2621  }
2622  }
2623 
2624  if ( !$repo->hasSha1Storage() ) {
2625  // Removes non-existent file from the batch, so we don't get errors.
2626  // This also handles files in the 'deleted' zone deleted via revision deletion.
2627  $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch );
2628  if ( !$checkStatus->isGood() ) {
2629  $this->status->merge( $checkStatus );
2630  return $this->status;
2631  }
2632  $this->deletionBatch = $checkStatus->value;
2633 
2634  // Execute the file deletion batch
2635  $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2636  if ( !$status->isGood() ) {
2637  $this->status->merge( $status );
2638  }
2639  }
2640 
2641  if ( !$this->status->isOK() ) {
2642  // Critical file deletion error; abort
2643  $this->file->unlock();
2644 
2645  return $this->status;
2646  }
2647 
2648  // Copy the image/oldimage rows to filearchive
2649  $this->doDBInserts();
2650  // Delete image/oldimage rows
2651  $this->doDBDeletes();
2652 
2653  // Commit and return
2654  $this->file->unlock();
2655 
2656  return $this->status;
2657  }
2658 
2664  protected function removeNonexistentFiles( $batch ) {
2665  $files = $newBatch = [];
2666 
2667  foreach ( $batch as $batchItem ) {
2668  list( $src, ) = $batchItem;
2669  $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2670  }
2671 
2672  $result = $this->file->repo->fileExistsBatch( $files );
2673  if ( in_array( null, $result, true ) ) {
2674  return Status::newFatal( 'backend-fail-internal',
2675  $this->file->repo->getBackend()->getName() );
2676  }
2677 
2678  foreach ( $batch as $batchItem ) {
2679  if ( $result[$batchItem[0]] ) {
2680  $newBatch[] = $batchItem;
2681  }
2682  }
2683 
2684  return Status::newGood( $newBatch );
2685  }
2686 }
2687 
2688 # ------------------------------------------------------------------------------
2689 
2696  private $file;
2697 
2699  private $cleanupBatch;
2700 
2702  private $ids;
2703 
2705  private $all;
2706 
2708  private $unsuppress = false;
2709 
2714  function __construct( File $file, $unsuppress = false ) {
2715  $this->file = $file;
2716  $this->cleanupBatch = [];
2717  $this->ids = [];
2718  $this->unsuppress = $unsuppress;
2719  }
2720 
2725  public function addId( $fa_id ) {
2726  $this->ids[] = $fa_id;
2727  }
2728 
2733  public function addIds( $ids ) {
2734  $this->ids = array_merge( $this->ids, $ids );
2735  }
2736 
2740  public function addAll() {
2741  $this->all = true;
2742  }
2743 
2752  public function execute() {
2754  global $wgLang;
2755 
2756  $repo = $this->file->getRepo();
2757  if ( !$this->all && !$this->ids ) {
2758  // Do nothing
2759  return $repo->newGood();
2760  }
2761 
2762  $lockOwnsTrx = $this->file->lock();
2763 
2764  $dbw = $this->file->repo->getMasterDB();
2765 
2766  $commentStore = MediaWikiServices::getInstance()->getCommentStore();
2767  $actorMigration = ActorMigration::newMigration();
2768 
2769  $status = $this->file->repo->newGood();
2770 
2771  $exists = (bool)$dbw->selectField( 'image', '1',
2772  [ 'img_name' => $this->file->getName() ],
2773  __METHOD__,
2774  // The lock() should already prevents changes, but this still may need
2775  // to bypass any transaction snapshot. However, if lock() started the
2776  // trx (which it probably did) then snapshot is post-lock and up-to-date.
2777  $lockOwnsTrx ? [] : [ 'LOCK IN SHARE MODE' ]
2778  );
2779 
2780  // Fetch all or selected archived revisions for the file,
2781  // sorted from the most recent to the oldest.
2782  $conditions = [ 'fa_name' => $this->file->getName() ];
2783 
2784  if ( !$this->all ) {
2785  $conditions['fa_id'] = $this->ids;
2786  }
2787 
2788  $arFileQuery = ArchivedFile::getQueryInfo();
2789  $result = $dbw->select(
2790  $arFileQuery['tables'],
2791  $arFileQuery['fields'],
2792  $conditions,
2793  __METHOD__,
2794  [ 'ORDER BY' => 'fa_timestamp DESC' ],
2795  $arFileQuery['joins']
2796  );
2797 
2798  $idsPresent = [];
2799  $storeBatch = [];
2800  $insertBatch = [];
2801  $insertCurrent = false;
2802  $deleteIds = [];
2803  $first = true;
2804  $archiveNames = [];
2805 
2806  foreach ( $result as $row ) {
2807  $idsPresent[] = $row->fa_id;
2808 
2809  if ( $row->fa_name != $this->file->getName() ) {
2810  $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2811  $status->failCount++;
2812  continue;
2813  }
2814 
2815  if ( $row->fa_storage_key == '' ) {
2816  // Revision was missing pre-deletion
2817  $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2818  $status->failCount++;
2819  continue;
2820  }
2821 
2822  $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2823  $row->fa_storage_key;
2824  $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2825 
2826  if ( isset( $row->fa_sha1 ) ) {
2827  $sha1 = $row->fa_sha1;
2828  } else {
2829  // old row, populate from key
2830  $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2831  }
2832 
2833  # Fix leading zero
2834  if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2835  $sha1 = substr( $sha1, 1 );
2836  }
2837 
2838  if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2839  || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2840  || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2841  || is_null( $row->fa_metadata )
2842  ) {
2843  // Refresh our metadata
2844  // Required for a new current revision; nice for older ones too. :)
2845  $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2846  } else {
2847  $props = [
2848  'minor_mime' => $row->fa_minor_mime,
2849  'major_mime' => $row->fa_major_mime,
2850  'media_type' => $row->fa_media_type,
2851  'metadata' => $row->fa_metadata
2852  ];
2853  }
2854 
2855  $comment = $commentStore->getComment( 'fa_description', $row );
2856  $user = User::newFromAnyId( $row->fa_user, $row->fa_user_text, $row->fa_actor );
2857  if ( $first && !$exists ) {
2858  // This revision will be published as the new current version
2859  $destRel = $this->file->getRel();
2860  $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
2861  $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
2862  $insertCurrent = [
2863  'img_name' => $row->fa_name,
2864  'img_size' => $row->fa_size,
2865  'img_width' => $row->fa_width,
2866  'img_height' => $row->fa_height,
2867  'img_metadata' => $props['metadata'],
2868  'img_bits' => $row->fa_bits,
2869  'img_media_type' => $props['media_type'],
2870  'img_major_mime' => $props['major_mime'],
2871  'img_minor_mime' => $props['minor_mime'],
2872  'img_timestamp' => $row->fa_timestamp,
2873  'img_sha1' => $sha1
2874  ] + $commentFields + $actorFields;
2875 
2876  // The live (current) version cannot be hidden!
2877  if ( !$this->unsuppress && $row->fa_deleted ) {
2878  $status->fatal( 'undeleterevdel' );
2879  $this->file->unlock();
2880  return $status;
2881  }
2882  } else {
2883  $archiveName = $row->fa_archive_name;
2884 
2885  if ( $archiveName == '' ) {
2886  // This was originally a current version; we
2887  // have to devise a new archive name for it.
2888  // Format is <timestamp of archiving>!<name>
2889  $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2890 
2891  do {
2892  $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2893  $timestamp++;
2894  } while ( isset( $archiveNames[$archiveName] ) );
2895  }
2896 
2897  $archiveNames[$archiveName] = true;
2898  $destRel = $this->file->getArchiveRel( $archiveName );
2899  $insertBatch[] = [
2900  'oi_name' => $row->fa_name,
2901  'oi_archive_name' => $archiveName,
2902  'oi_size' => $row->fa_size,
2903  'oi_width' => $row->fa_width,
2904  'oi_height' => $row->fa_height,
2905  'oi_bits' => $row->fa_bits,
2906  'oi_timestamp' => $row->fa_timestamp,
2907  'oi_metadata' => $props['metadata'],
2908  'oi_media_type' => $props['media_type'],
2909  'oi_major_mime' => $props['major_mime'],
2910  'oi_minor_mime' => $props['minor_mime'],
2911  'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2912  'oi_sha1' => $sha1
2913  ] + $commentStore->insert( $dbw, 'oi_description', $comment )
2914  + $actorMigration->getInsertValues( $dbw, 'oi_user', $user );
2915  }
2916 
2917  $deleteIds[] = $row->fa_id;
2918 
2919  if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2920  // private files can stay where they are
2921  $status->successCount++;
2922  } else {
2923  $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2924  $this->cleanupBatch[] = $row->fa_storage_key;
2925  }
2926 
2927  $first = false;
2928  }
2929 
2930  unset( $result );
2931 
2932  // Add a warning to the status object for missing IDs
2933  $missingIds = array_diff( $this->ids, $idsPresent );
2934 
2935  foreach ( $missingIds as $id ) {
2936  $status->error( 'undelete-missing-filearchive', $id );
2937  }
2938 
2939  if ( !$repo->hasSha1Storage() ) {
2940  // Remove missing files from batch, so we don't get errors when undeleting them
2941  $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2942  if ( !$checkStatus->isGood() ) {
2943  $status->merge( $checkStatus );
2944  return $status;
2945  }
2946  $storeBatch = $checkStatus->value;
2947 
2948  // Run the store batch
2949  // Use the OVERWRITE_SAME flag to smooth over a common error
2950  $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2951  $status->merge( $storeStatus );
2952 
2953  if ( !$status->isGood() ) {
2954  // Even if some files could be copied, fail entirely as that is the
2955  // easiest thing to do without data loss
2956  $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2957  $status->setOK( false );
2958  $this->file->unlock();
2959 
2960  return $status;
2961  }
2962  }
2963 
2964  // Run the DB updates
2965  // Because we have locked the image row, key conflicts should be rare.
2966  // If they do occur, we can roll back the transaction at this time with
2967  // no data loss, but leaving unregistered files scattered throughout the
2968  // public zone.
2969  // This is not ideal, which is why it's important to lock the image row.
2970  if ( $insertCurrent ) {
2971  $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2972  }
2973 
2974  if ( $insertBatch ) {
2975  $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2976  }
2977 
2978  if ( $deleteIds ) {
2979  $dbw->delete( 'filearchive',
2980  [ 'fa_id' => $deleteIds ],
2981  __METHOD__ );
2982  }
2983 
2984  // If store batch is empty (all files are missing), deletion is to be considered successful
2985  if ( $status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
2986  if ( !$exists ) {
2987  wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2988 
2989  DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2990 
2991  $this->file->purgeEverything();
2992  } else {
2993  wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2994  $this->file->purgeDescription();
2995  }
2996  }
2997 
2998  $this->file->unlock();
2999 
3000  return $status;
3001  }
3002 
3008  protected function removeNonexistentFiles( $triplets ) {
3009  $files = $filteredTriplets = [];
3010  foreach ( $triplets as $file ) {
3011  $files[$file[0]] = $file[0];
3012  }
3013 
3014  $result = $this->file->repo->fileExistsBatch( $files );
3015  if ( in_array( null, $result, true ) ) {
3016  return Status::newFatal( 'backend-fail-internal',
3017  $this->file->repo->getBackend()->getName() );
3018  }
3019 
3020  foreach ( $triplets as $file ) {
3021  if ( $result[$file[0]] ) {
3022  $filteredTriplets[] = $file;
3023  }
3024  }
3025 
3026  return Status::newGood( $filteredTriplets );
3027  }
3028 
3034  protected function removeNonexistentFromCleanup( $batch ) {
3035  $files = $newBatch = [];
3036  $repo = $this->file->repo;
3037 
3038  foreach ( $batch as $file ) {
3039  $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
3040  rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3041  }
3042 
3043  $result = $repo->fileExistsBatch( $files );
3044 
3045  foreach ( $batch as $file ) {
3046  if ( $result[$file] ) {
3047  $newBatch[] = $file;
3048  }
3049  }
3050 
3051  return $newBatch;
3052  }
3053 
3059  public function cleanup() {
3060  if ( !$this->cleanupBatch ) {
3061  return $this->file->repo->newGood();
3062  }
3063 
3064  $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
3065 
3066  $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
3067 
3068  return $status;
3069  }
3070 
3078  protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
3079  $cleanupBatch = [];
3080 
3081  foreach ( $storeStatus->success as $i => $success ) {
3082  // Check if this item of the batch was successfully copied
3083  if ( $success ) {
3084  // Item was successfully copied and needs to be removed again
3085  // Extract ($dstZone, $dstRel) from the batch
3086  $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3087  }
3088  }
3089  $this->file->repo->cleanupBatch( $cleanupBatch );
3090  }
3091 }
3092 
3093 # ------------------------------------------------------------------------------
3094 
3101  protected $file;
3102 
3104  protected $target;
3105 
3106  protected $cur;
3107 
3108  protected $olds;
3109 
3110  protected $oldCount;
3111 
3112  protected $archive;
3113 
3115  protected $db;
3116 
3121  function __construct( File $file, Title $target ) {
3122  $this->file = $file;
3123  $this->target = $target;
3124  $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
3125  $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
3126  $this->oldName = $this->file->getName();
3127  $this->newName = $this->file->repo->getNameFromTitle( $this->target );
3128  $this->oldRel = $this->oldHash . $this->oldName;
3129  $this->newRel = $this->newHash . $this->newName;
3130  $this->db = $file->getRepo()->getMasterDB();
3131  }
3132 
3136  public function addCurrent() {
3137  $this->cur = [ $this->oldRel, $this->newRel ];
3138  }
3139 
3144  public function addOlds() {
3145  $archiveBase = 'archive';
3146  $this->olds = [];
3147  $this->oldCount = 0;
3148  $archiveNames = [];
3149 
3150  $result = $this->db->select( 'oldimage',
3151  [ 'oi_archive_name', 'oi_deleted' ],
3152  [ 'oi_name' => $this->oldName ],
3153  __METHOD__,
3154  [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3155  );
3156 
3157  foreach ( $result as $row ) {
3158  $archiveNames[] = $row->oi_archive_name;
3159  $oldName = $row->oi_archive_name;
3160  $bits = explode( '!', $oldName, 2 );
3161 
3162  if ( count( $bits ) != 2 ) {
3163  wfDebug( "Old file name missing !: '$oldName' \n" );
3164  continue;
3165  }
3166 
3167  list( $timestamp, $filename ) = $bits;
3168 
3169  if ( $this->oldName != $filename ) {
3170  wfDebug( "Old file name doesn't match: '$oldName' \n" );
3171  continue;
3172  }
3173 
3174  $this->oldCount++;
3175 
3176  // Do we want to add those to oldCount?
3177  if ( $row->oi_deleted & File::DELETED_FILE ) {
3178  continue;
3179  }
3180 
3181  $this->olds[] = [
3182  "{$archiveBase}/{$this->oldHash}{$oldName}",
3183  "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3184  ];
3185  }
3186 
3187  return $archiveNames;
3188  }
3189 
3194  public function execute() {
3195  $repo = $this->file->repo;
3196  $status = $repo->newGood();
3197  $destFile = wfLocalFile( $this->target );
3198 
3199  $this->file->lock();
3200  $destFile->lock(); // quickly fail if destination is not available
3201 
3202  $triplets = $this->getMoveTriplets();
3203  $checkStatus = $this->removeNonexistentFiles( $triplets );
3204  if ( !$checkStatus->isGood() ) {
3205  $destFile->unlock();
3206  $this->file->unlock();
3207  $status->merge( $checkStatus ); // couldn't talk to file backend
3208  return $status;
3209  }
3210  $triplets = $checkStatus->value;
3211 
3212  // Verify the file versions metadata in the DB.
3213  $statusDb = $this->verifyDBUpdates();
3214  if ( !$statusDb->isGood() ) {
3215  $destFile->unlock();
3216  $this->file->unlock();
3217  $statusDb->setOK( false );
3218 
3219  return $statusDb;
3220  }
3221 
3222  if ( !$repo->hasSha1Storage() ) {
3223  // Copy the files into their new location.
3224  // If a prior process fataled copying or cleaning up files we tolerate any
3225  // of the existing files if they are identical to the ones being stored.
3226  $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
3227  wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3228  "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3229  if ( !$statusMove->isGood() ) {
3230  // Delete any files copied over (while the destination is still locked)
3231  $this->cleanupTarget( $triplets );
3232  $destFile->unlock();
3233  $this->file->unlock();
3234  wfDebugLog( 'imagemove', "Error in moving files: "
3235  . $statusMove->getWikiText( false, false, 'en' ) );
3236  $statusMove->setOK( false );
3237 
3238  return $statusMove;
3239  }
3240  $status->merge( $statusMove );
3241  }
3242 
3243  // Rename the file versions metadata in the DB.
3244  $this->doDBUpdates();
3245 
3246  wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3247  "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3248 
3249  $destFile->unlock();
3250  $this->file->unlock();
3251 
3252  // Everything went ok, remove the source files
3253  $this->cleanupSource( $triplets );
3254 
3255  $status->merge( $statusDb );
3256 
3257  return $status;
3258  }
3259 
3266  protected function verifyDBUpdates() {
3267  $repo = $this->file->repo;
3268  $status = $repo->newGood();
3269  $dbw = $this->db;
3270 
3271  $hasCurrent = $dbw->lockForUpdate(
3272  'image',
3273  [ 'img_name' => $this->oldName ],
3274  __METHOD__
3275  );
3276  $oldRowCount = $dbw->lockForUpdate(
3277  'oldimage',
3278  [ 'oi_name' => $this->oldName ],
3279  __METHOD__
3280  );
3281 
3282  if ( $hasCurrent ) {
3283  $status->successCount++;
3284  } else {
3285  $status->failCount++;
3286  }
3287  $status->successCount += $oldRowCount;
3288  // T36934: oldCount is based on files that actually exist.
3289  // There may be more DB rows than such files, in which case $affected
3290  // can be greater than $total. We use max() to avoid negatives here.
3291  $status->failCount += max( 0, $this->oldCount - $oldRowCount );
3292  if ( $status->failCount ) {
3293  $status->error( 'imageinvalidfilename' );
3294  }
3295 
3296  return $status;
3297  }
3298 
3303  protected function doDBUpdates() {
3304  $dbw = $this->db;
3305 
3306  // Update current image
3307  $dbw->update(
3308  'image',
3309  [ 'img_name' => $this->newName ],
3310  [ 'img_name' => $this->oldName ],
3311  __METHOD__
3312  );
3313 
3314  // Update old images
3315  $dbw->update(
3316  'oldimage',
3317  [
3318  'oi_name' => $this->newName,
3319  'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3320  $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3321  ],
3322  [ 'oi_name' => $this->oldName ],
3323  __METHOD__
3324  );
3325  }
3326 
3331  protected function getMoveTriplets() {
3332  $moves = array_merge( [ $this->cur ], $this->olds );
3333  $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3334 
3335  foreach ( $moves as $move ) {
3336  // $move: (oldRelativePath, newRelativePath)
3337  $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3338  $triplets[] = [ $srcUrl, 'public', $move[1] ];
3339  wfDebugLog(
3340  'imagemove',
3341  "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3342  );
3343  }
3344 
3345  return $triplets;
3346  }
3347 
3353  protected function removeNonexistentFiles( $triplets ) {
3354  $files = [];
3355 
3356  foreach ( $triplets as $file ) {
3357  $files[$file[0]] = $file[0];
3358  }
3359 
3360  $result = $this->file->repo->fileExistsBatch( $files );
3361  if ( in_array( null, $result, true ) ) {
3362  return Status::newFatal( 'backend-fail-internal',
3363  $this->file->repo->getBackend()->getName() );
3364  }
3365 
3366  $filteredTriplets = [];
3367  foreach ( $triplets as $file ) {
3368  if ( $result[$file[0]] ) {
3369  $filteredTriplets[] = $file;
3370  } else {
3371  wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3372  }
3373  }
3374 
3375  return Status::newGood( $filteredTriplets );
3376  }
3377 
3383  protected function cleanupTarget( $triplets ) {
3384  // Create dest pairs from the triplets
3385  $pairs = [];
3386  foreach ( $triplets as $triplet ) {
3387  // $triplet: (old source virtual URL, dst zone, dest rel)
3388  $pairs[] = [ $triplet[1], $triplet[2] ];
3389  }
3390 
3391  $this->file->repo->cleanupBatch( $pairs );
3392  }
3393 
3399  protected function cleanupSource( $triplets ) {
3400  // Create source file names from the triplets
3401  $files = [];
3402  foreach ( $triplets as $triplet ) {
3403  $files[] = $triplet[0];
3404  }
3405 
3406  $this->file->repo->cleanupBatch( $files );
3407  }
3408 }
3409 
3411  public function __construct( Status $status ) {
3412  parent::__construct(
3413  'actionfailed',
3414  $status->getMessage()
3415  );
3416  }
3417 
3418  public function report() {
3419  global $wgOut;
3420  $wgOut->setStatusCode( 429 );
3421  parent::report();
3422  }
3423 }
const SCHEMA_COMPAT_WRITE_OLD
Definition: Defines.php:284
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))
exists()
canRender inherited
Definition: LocalFile.php:974
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:384
getCacheFields( $prefix='img_')
Returns the list of object properties that are included as-is in the cache.
Definition: LocalFile.php:412
MediaHandler $handler
Definition: File.php:114
addWatch( $title, $checkRights=self::CHECK_USER_RIGHTS)
Watch an article.
Definition: User.php:3973
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:266
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:2285
const VERSION
Definition: LocalFile.php:47
$success
addAll()
Add all revisions of the file.
Definition: LocalFile.php:2740
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:555
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:1995
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:2172
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:1673
purgeMetadataCache()
Refresh metadata in memcached, but don&#39;t touch thumbnails or CDN.
Definition: LocalFile.php:1018
releaseFileLock()
Definition: LocalFile.php:2194
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:3059
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:1276
width
addCurrent()
Add the current image to the batch.
Definition: LocalFile.php:3136
const DELETE_SOURCE
Definition: FileRepo.php:40
getSize()
Returns the size of the image file, in bytes.
Definition: LocalFile.php:937
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:3266
setProps( $info)
Set properties in this object to be equal to those given in the associative array $info...
Definition: LocalFile.php:763
getThumbnails( $archiveName=false)
getTransformScript inherited
Definition: LocalFile.php:995
Helper class for file undeletion.
Definition: LocalFile.php:2694
unlock()
Decrement the lock reference count and end the atomic section if it reaches zero. ...
Definition: LocalFile.php:2254
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:3034
$source
$value
const SCHEMA_COMPAT_READ_NEW
Definition: Defines.php:287
isMissing()
splitMime inherited
Definition: LocalFile.php:802
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:2164
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:2275
move( $target)
getLinksTo inherited
Definition: LocalFile.php:1880
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:1870
purgeThumbnails( $options=[])
Delete cached transformed files for the current version only.
Definition: LocalFile.php:1070
string [] $ids
List of file IDs to restore.
Definition: LocalFile.php:2702
getArchiveUrl( $suffix=false)
Get the URL of the archive directory, or a particular file if $suffix is specified.
Definition: File.php:1653
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1624
removeNonexistentFiles( $batch)
Removes non-existent files from a deletion batch.
Definition: LocalFile.php:2664
quickImport( $src, $dst, $options=null)
Import a file from the local file system into the repo.
Definition: FileRepo.php:973
const METADATA_BAD
cleanupSource( $triplets)
Cleanup a fully moved array of triplets by deleting the source files.
Definition: LocalFile.php:3399
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:1177
loadFromDB( $flags=0)
Load file metadata from the DB.
Definition: LocalFile.php:449
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:3303
getTitle()
Return the associated title object.
Definition: File.php:326
Title string bool $title
Definition: File.php:99
this hook is for auditing only 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:989
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2487
restore( $versions=[], $unsuppress=false)
Restore all or specified deleted revisions to the given file.
Definition: LocalFile.php:2033
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:2276
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:215
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. '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 '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:1993
__construct(File $file, $reason='', $suppress=false, $user=null)
Definition: LocalFile.php:2318
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:1729
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:903
nextHistoryLine()
Returns the history of this file, line by line.
Definition: LocalFile.php:1226
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:47
addIds( $ids)
Add a whole lot of files by ID.
Definition: LocalFile.php:2733
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
__construct(File $file, Title $target)
Definition: LocalFile.php:3121
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:1801
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:1170
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:225
__construct(File $file, $unsuppress=false)
Definition: LocalFile.php:2714
wfReadOnly()
Check whether the wiki is in read-only mode.
string $metadata
Handler-specific metadata.
Definition: LocalFile.php:73
$wgLang
Definition: Setup.php:891
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:580
string $repoClass
Definition: LocalFile.php:88
cleanupTarget( $triplets)
Cleanup a partially moved array of triplets by deleting the target files.
Definition: LocalFile.php:3383
getThumbUrl( $suffix=false)
Get the URL of the thumbnail directory, or a particular file if $suffix is specified.
Definition: File.php:1709
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:1975
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:434
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:300
static factory(array $deltas)
getDescriptionTouched()
Definition: LocalFile.php:2128
const LOCK_EX
Definition: LockManager.php:69
const SCHEMA_COMPAT_WRITE_NEW
Definition: Defines.php:286
getFileSha1( $virtualUrl)
Get the sha1 (base 36) of a file with a given virtual URL/storage path.
Definition: FileRepo.php:1598
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:61
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:2163
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:1029
$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:2184
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:1340
const CACHE_FIELD_MAX_LEN
Definition: LocalFile.php:49
__construct(Status $status)
Definition: LocalFile.php:3411
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:626
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:254
loadExtraFromDB()
Load lazy file metadata from the DB.
Definition: LocalFile.php:481
$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:1995
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:662
readOnlyFatalStatus()
Definition: LocalFile.php:2268
Helper class for file movement.
Definition: LocalFile.php:3099
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:2604
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
bool $all
Add all revisions of the file.
Definition: LocalFile.php:2705
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:1103
getMetadata()
Get handler-specific metadata.
Definition: LocalFile.php:919
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:1779
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:1047
string $mime
MIME type, determined by MimeAnalyzer::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:3194
Helper class for file deletion.
Definition: LocalFile.php:2287
static getHashFromKey( $key)
Gets the SHA1 hash from a storage key.
Definition: LocalRepo.php:182
const SCHEMA_COMPAT_WRITE_BOTH
Definition: Defines.php:288
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
array $deletionBatch
Items to be processed in the deletion batch.
Definition: LocalFile.php:2301
purgeThumbList( $dir, $files)
Delete a list of thumbnails visible at urls.
Definition: LocalFile.php:1130
getDescription( $audience=self::FOR_PUBLIC, User $user=null)
Definition: LocalFile.php:2103
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:1309
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new oldlocalfile object...
getArchiveRel( $suffix=false)
Get the path of an archived file relative to the public zone root.
Definition: File.php:1543
removeNonexistentFiles( $triplets)
Removes non-existent files from a store batch.
Definition: LocalFile.php:3008
getDescriptionText(Language $lang=null)
Get the HTML text of the description page This is not used by ImagePage for local files...
Definition: LocalFile.php:2079
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:3353
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:1616
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:708
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:2460
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:1997
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:2526
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:2209
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:506
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:2067
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:3144
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
static singleton( $domain=false)
storeBatch(array $triplets, $flags=0)
Store a batch of files.
Definition: FileRepo.php:862
getMoveTriplets()
Generate triplets for FileRepo::storeBatch().
Definition: LocalFile.php:3331
string $timestamp
Upload timestamp.
Definition: LocalFile.php:103
getHeight( $page=1)
Return the height of the image.
Definition: LocalFile.php:849
int $height
Image height.
Definition: LocalFile.php:58
loadFromFile()
Load metadata from the file itself.
Definition: LocalFile.php:401
$wgOut
Definition: Setup.php:896
fileExistsBatch(array $files)
Checks existence of an array of files.
Definition: FileRepo.php:1377
getDeletedHashPath( $key)
Get a relative path for a deletion archive key, e.g.
Definition: FileRepo.php:1494
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:1820
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object...
Definition: LocalFile.php:244
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:2304
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:958
loadFromCache()
Try to load file metadata from memcached, falling back to the database.
Definition: LocalFile.php:316
string [] $cleanupBatch
List of file IDs to restore.
Definition: LocalFile.php:2699
getMutableCacheKeys(WANObjectCache $cache)
Definition: LocalFile.php:309
int $width
Image width.
Definition: LocalFile.php:55
cleanupFailedBatch( $storeStatus, $storeBatch)
Cleanup a failed batch.
Definition: LocalFile.php:3078
getMimeType()
Returns the MIME type of the file.
Definition: LocalFile.php:947
resetHistory()
Reset the history pointer to the first element of the history.
Definition: LocalFile.php:1269
static newNullRevision( $dbw, $pageId, $summary, $minor, $user=null)
Create a new null-revision for insertion into a page&#39;s history.
Definition: Revision.php:1198
int $size
Size in bytes (loadFromXxx)
Definition: LocalFile.php:70
hasSha1Storage()
Returns whether or not storage is SHA-1 based.
Definition: FileRepo.php:1937
addOlds()
Add the old versions of the image to the batch.
Definition: LocalFile.php:2347
isDeleted( $field)
Is this file a "deleted" file in a private archive? STUB.
Definition: File.php:1891
getWidth( $page=1)
Return the width of the image.
Definition: LocalFile.php:817
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
Definition: LocalFile.php:644
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:1629
$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:882
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:51
newGood( $value=null)
Create a new good result.
Definition: FileRepo.php:1753
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:2752
__construct( $title, $repo)
Do not call this except from inside a repo class.
Definition: LocalFile.php:282
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:2725
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