Debian Codegraph @

includes/filerepo/file/LocalFile.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\CommentStore\CommentStoreComment;
22 use MediaWiki\Content\ContentHandler;
23 use MediaWiki\Context\RequestContext;
24 use MediaWiki\Deferred\AutoCommitUpdate;
25 use MediaWiki\Deferred\DeferredUpdates;
26 use MediaWiki\Deferred\LinksUpdate\LinksUpdate;
27 use MediaWiki\Deferred\SiteStatsUpdate;
28 use MediaWiki\FileRepo\File\FileSelectQueryBuilder;
29 use MediaWiki\Language\Language;
30 use MediaWiki\Logger\LoggerFactory;
31 use MediaWiki\MainConfigNames;
32 use MediaWiki\MediaWikiServices;
33 use MediaWiki\Parser\ParserOptions;
34 use MediaWiki\Permissions\Authority;
35 use MediaWiki\Status\Status;
36 use MediaWiki\Title\Title;
37 use MediaWiki\User\UserIdentity;
38 use MediaWiki\User\UserIdentityValue;
39 use Wikimedia\FileBackend\FileBackend;
40 use Wikimedia\FileBackend\FileBackendError;
41 use Wikimedia\FileBackend\FSFile\FSFile;
42 use Wikimedia\Rdbms\Blob;
43 use Wikimedia\Rdbms\Database;
44 use Wikimedia\Rdbms\IDBAccessObject;
45 use Wikimedia\Rdbms\IReadableDatabase;
46 use Wikimedia\Rdbms\IResultWrapper;
47 use Wikimedia\Rdbms\SelectQueryBuilder;
48
49 /**
50 * Local file in the wiki's own database.
51 *
52 * Provides methods to retrieve paths (physical, logical, URL),
53 * to generate image thumbnails or for uploading.
54 *
55 * Note that only the repo object knows what its file class is called. You should
56 * never name a file class explicitly outside of the repo class. Instead use the
57 * repo's factory functions to generate file objects, for example:
58 *
59 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
60 *
61 * Consider the services container below;
62 *
63 * $services = MediaWikiServices::getInstance();
64 *
65 * The convenience services $services->getRepoGroup()->getLocalRepo()->newFile()
66 * and $services->getRepoGroup()->findFile() should be sufficient in most cases.
67 *
68 * @TODO: DI - Instead of using MediaWikiServices::getInstance(), a service should
69 * ideally accept a RepoGroup in its constructor and then, use $this->repoGroup->findFile()
70 * and $this->repoGroup->getLocalRepo()->newFile().
71 *
72 * @stable to extend
73 * @ingroup FileAbstraction
74 */
75 class LocalFile extends File {
76 private const VERSION = 13; // cache version
77
78 private const CACHE_FIELD_MAX_LEN = 1000;
79
80 /** @var string Metadata serialization: empty string. This is a compact non-legacy format. */
81 private const MDS_EMPTY = 'empty';
82
83 /** @var string Metadata serialization: some other string */
84 private const MDS_LEGACY = 'legacy';
85
86 /** @var string Metadata serialization: PHP serialize() */
87 private const MDS_PHP = 'php';
88
89 /** @var string Metadata serialization: JSON */
90 private const MDS_JSON = 'json';
91
92 /** @var int Maximum number of pages for which to trigger render jobs */
93 private const MAX_PAGE_RENDER_JOBS = 50;
94
95 /** @var bool Does the file exist on disk? (loadFromXxx) */
96 protected $fileExists;
97
98 /** @var int Image width */
99 protected $width;
100
101 /** @var int Image height */
102 protected $height;
103
104 /** @var int Returned by getimagesize (loadFromXxx) */
105 protected $bits;
106
107 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
108 protected $media_type;
109
110 /** @var string MIME type, determined by MimeAnalyzer::guessMimeType */
111 protected $mime;
112
113 /** @var int Size in bytes (loadFromXxx) */
114 protected $size;
115
116 /** @var array Unserialized metadata */
117 protected $metadataArray = [];
118
119 /**
120 * One of the MDS_* constants, giving the format of the metadata as stored
121 * in the DB, or null if the data was not loaded from the DB.
122 *
123 * @var string|null
124 */
125 protected $metadataSerializationFormat;
126
127 /** @var string[] Map of metadata item name to blob address */
128 protected $metadataBlobs = [];
129
130 /**
131 * Map of metadata item name to blob address for items that exist but
132 * have not yet been loaded into $this->metadataArray
133 *
134 * @var string[]
135 */
136 protected $unloadedMetadataBlobs = [];
137
138 /** @var string SHA-1 base 36 content hash */
139 protected $sha1;
140
141 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
142 protected $dataLoaded = false;
143
144 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
145 protected $extraDataLoaded = false;
146
147 /** @var int Bitfield akin to rev_deleted */
148 protected $deleted;
149
150 /** @var string */
151 protected $repoClass = LocalRepo::class;
152
153 /** @var int Number of line to return by nextHistoryLine() (constructor) */
154 private $historyLine = 0;
155
156 /** @var IResultWrapper|null Result of the query for the file's history (nextHistoryLine) */
157 private $historyRes = null;
158
159 /** @var string Major MIME type */
160 private $major_mime;
161
162 /** @var string Minor MIME type */
163 private $minor_mime;
164
165 /** @var string Upload timestamp */
166 private $timestamp;
167
168 /** @var UserIdentity|null Uploader */
169 private $user;
170
171 /** @var string Description of current revision of the file */
172 private $description;
173
174 /** @var string TS_MW timestamp of the last change of the file description */
175 private $descriptionTouched;
176
177 /** @var bool Whether the row was upgraded on load */
178 private $upgraded;
179
180 /** @var bool Whether the row was scheduled to upgrade on load */
181 private $upgrading;
182
183 /** @var int If >= 1 the image row is locked */
184 private $locked;
185
186 /** @var bool True if the image row is locked with a lock initiated transaction */
187 private $lockedOwnTrx;
188
189 /** @var bool True if file is not present in file system. Not to be cached in memcached */
190 private $missing;
191
192 /** @var MetadataStorageHelper */
193 private $metadataStorageHelper;
194
195 // @note: higher than IDBAccessObject constants
196 private const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata)
197
198 private const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction';
199
200 /**
201 * Create a LocalFile from a title
202 * Do not call this except from inside a repo class.
203 *
204 * Note: $unused param is only here to avoid an E_STRICT
205 *
206 * @stable to override
207 *
208 * @param Title $title
209 * @param LocalRepo $repo
210 * @param null $unused
211 *
212 * @return static
213 */
214 public static function newFromTitle( $title, $repo, $unused = null ) {
215 return new static( $title, $repo );
216 }
217
218 /**
219 * Create a LocalFile from a title
220 * Do not call this except from inside a repo class.
221 *
222 * @stable to override
223 *
224 * @param stdClass $row
225 * @param LocalRepo $repo
226 *
227 * @return static
228 */
229 public static function newFromRow( $row, $repo ) {
230 $title = Title::makeTitle( NS_FILE, $row->img_name );
231 $file = new static( $title, $repo );
232 $file->loadFromRow( $row );
233
234 return $file;
235 }
236
237 /**
238 * Create a LocalFile from a SHA-1 key
239 * Do not call this except from inside a repo class.
240 *
241 * @stable to override
242 *
243 * @param string $sha1 Base-36 SHA-1
244 * @param LocalRepo $repo
245 * @param string|false $timestamp MW_timestamp (optional)
246 * @return static|false
247 */
248 public static function newFromKey( $sha1, $repo, $timestamp = false ) {
249 $dbr = $repo->getReplicaDB();
250 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
251
252 $queryBuilder->where( [ 'img_sha1' => $sha1 ] );
253
254 if ( $timestamp ) {
255 $queryBuilder->andWhere( [ 'img_timestamp' => $dbr->timestamp( $timestamp ) ] );
256 }
257
258 $row = $queryBuilder->caller( __METHOD__ )->fetchRow();
259 if ( $row ) {
260 return static::newFromRow( $row, $repo );
261 } else {
262 return false;
263 }
264 }
265
266 /**
267 * Return the tables, fields, and join conditions to be selected to create
268 * a new localfile object.
269 *
270 * Since 1.34, img_user and img_user_text have not been present in the
271 * database, but they continue to be available in query results as
272 * aliases.
273 *
274 * @since 1.31
275 * @stable to override
276 *
277 * @deprecated since 1.41 use FileSelectQueryBuilder instead
278 * @param string[] $options
279 * - omit-lazy: Omit fields that are lazily cached.
280 * @return array[] With three keys:
281 * - tables: (string[]) to include in the `$table` to `IDatabase->select()` or `SelectQueryBuilder::tables`
282 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()` or `SelectQueryBuilder::fields`
283 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()` or `SelectQueryBuilder::joinConds`
284 * @phan-return array{tables:string[],fields:string[],joins:array}
285 */
286 public static function getQueryInfo( array $options = [] ) {
287 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
288 $queryInfo = FileSelectQueryBuilder::newForFile( $dbr, $options )->getQueryInfo();
289 // needs remapping...
290 return [
291 'tables' => $queryInfo['tables'],
292 'fields' => $queryInfo['fields'],
293 'joins' => $queryInfo['join_conds'],
294 ];
295 }
296
297 /**
298 * Do not call this except from inside a repo class.
299 * @stable to call
300 *
301 * @param Title $title
302 * @param LocalRepo $repo
303 */
304 public function __construct( $title, $repo ) {
305 parent::__construct( $title, $repo );
306 $this->metadataStorageHelper = new MetadataStorageHelper( $repo );
307
308 $this->assertRepoDefined();
309 $this->assertTitleDefined();
310 }
311
312 /**
313 * @return LocalRepo|false
314 */
315 public function getRepo() {
316 return $this->repo;
317 }
318
319 /**
320 * Get the memcached key for the main data for this file, or false if
321 * there is no access to the shared cache.
322 * @stable to override
323 * @return string|false
324 */
325 protected function getCacheKey() {
326 return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) );
327 }
328
329 /**
330 * Try to load file metadata from memcached, falling back to the database
331 */
332 private function loadFromCache() {
333 $this->dataLoaded = false;
334 $this->extraDataLoaded = false;
335
336 $key = $this->getCacheKey();
337 if ( !$key ) {
338 $this->loadFromDB( IDBAccessObject::READ_NORMAL );
339
340 return;
341 }
342
343 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
344 $cachedValues = $cache->getWithSetCallback(
345 $key,
346 $cache::TTL_WEEK,
347 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
348 $setOpts += Database::getCacheSetOptions( $this->repo->getReplicaDB() );
349
350 $this->loadFromDB( IDBAccessObject::READ_NORMAL );
351
352 $fields = $this->getCacheFields( '' );
353 $cacheVal = [];
354 $cacheVal['fileExists'] = $this->fileExists;
355 if ( $this->fileExists ) {
356 foreach ( $fields as $field ) {
357 $cacheVal[$field] = $this->$field;
358 }
359 }
360 if ( $this->user ) {
361 $cacheVal['user'] = $this->user->getId();
362 $cacheVal['user_text'] = $this->user->getName();
363 }
364
365 // Don't cache metadata items stored as blobs, since they tend to be large
366 if ( $this->metadataBlobs ) {
367 $cacheVal['metadata'] = array_diff_key(
368 $this->metadataArray, $this->metadataBlobs );
369 // Save the blob addresses
370 $cacheVal['metadataBlobs'] = $this->metadataBlobs;
371 } else {
372 $cacheVal['metadata'] = $this->metadataArray;
373 }
374
375 // Strip off excessive entries from the subset of fields that can become large.
376 // If the cache value gets too large and might not fit in the cache,
377 // causing repeat database queries for each access to the file.
378 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
379 if ( isset( $cacheVal[$field] )
380 && strlen( serialize( $cacheVal[$field] ) ) > 100 * 1024
381 ) {
382 unset( $cacheVal[$field] ); // don't let the value get too big
383 if ( $field === 'metadata' ) {
384 unset( $cacheVal['metadataBlobs'] );
385 }
386 }
387 }
388
389 if ( $this->fileExists ) {
390 $ttl = $cache->adaptiveTTL( (int)wfTimestamp( TS_UNIX, $this->timestamp ), $ttl );
391 } else {
392 $ttl = $cache::TTL_DAY;
393 }
394
395 return $cacheVal;
396 },
397 [ 'version' => self::VERSION ]
398 );
399
400 $this->fileExists = $cachedValues['fileExists'];
401 if ( $this->fileExists ) {
402 $this->setProps( $cachedValues );
403 }
404
405 $this->dataLoaded = true;
406 $this->extraDataLoaded = true;
407 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
408 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
409 }
410 }
411
412 /**
413 * Purge the file object/metadata cache
414 */
415 public function invalidateCache() {
416 $key = $this->getCacheKey();
417 if ( !$key ) {
418 return;
419 }
420
421 $this->repo->getPrimaryDB()->onTransactionPreCommitOrIdle(
422 static function () use ( $key ) {
423 MediaWikiServices::getInstance()->getMainWANObjectCache()->delete( $key );
424 },
425 __METHOD__
426 );
427 }
428
429 /**
430 * Load metadata from the file itself
431 *
432 * @internal
433 * @param string|null $path The path or virtual URL to load from, or null
434 * to use the previously stored file.
435 */
436 public function loadFromFile( $path = null ) {
437 $props = $this->repo->getFileProps( $path ?? $this->getVirtualUrl() );
438 $this->setProps( $props );
439 }
440
441 /**
442 * Returns the list of object properties that are included as-is in the cache.
443 * @stable to override
444 * @param string $prefix Must be the empty string
445 * @return string[]
446 * @since 1.31 No longer accepts a non-empty $prefix
447 */
448 protected function getCacheFields( $prefix = 'img_' ) {
449 if ( $prefix !== '' ) {
450 throw new InvalidArgumentException(
451 __METHOD__ . ' with a non-empty prefix is no longer supported.'
452 );
453 }
454
455 // See self::getQueryInfo() for the fetching of the data from the DB,
456 // self::loadFromRow() for the loading of the object from the DB row,
457 // and self::loadFromCache() for the caching, and self::setProps() for
458 // populating the object from an array of data.
459 return [ 'size', 'width', 'height', 'bits', 'media_type',
460 'major_mime', 'minor_mime', 'timestamp', 'sha1', 'description' ];
461 }
462
463 /**
464 * Returns the list of object properties that are included as-is in the
465 * cache, only when they're not too big, and are lazily loaded by self::loadExtraFromDB().
466 * @param string $prefix Must be the empty string
467 * @return string[]
468 * @since 1.31 No longer accepts a non-empty $prefix
469 */
470 protected function getLazyCacheFields( $prefix = 'img_' ) {
471 if ( $prefix !== '' ) {
472 throw new InvalidArgumentException(
473 __METHOD__ . ' with a non-empty prefix is no longer supported.'
474 );
475 }
476
477 // Keep this in sync with the omit-lazy option in self::getQueryInfo().
478 return [ 'metadata' ];
479 }
480
481 /**
482 * Load file metadata from the DB
483 * @stable to override
484 * @param int $flags
485 */
486 protected function loadFromDB( $flags = 0 ) {
487 $fname = static::class . '::' . __FUNCTION__;
488
489 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
490 $this->dataLoaded = true;
491 $this->extraDataLoaded = true;
492
493 $dbr = ( $flags & IDBAccessObject::READ_LATEST )
494 ? $this->repo->getPrimaryDB()
495 : $this->repo->getReplicaDB();
496 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
497
498 $queryBuilder->where( [ 'img_name' => $this->getName() ] );
499 $row = $queryBuilder->caller( $fname )->fetchRow();
500
501 if ( $row ) {
502 $this->loadFromRow( $row );
503 } else {
504 $this->fileExists = false;
505 $this->mime = 'unknown/unknown';
506 }
507 }
508
509 /**
510 * Load lazy file metadata from the DB.
511 * This covers fields that are sometimes not cached.
512 * @stable to override
513 */
514 protected function loadExtraFromDB() {
515 if ( !$this->title ) {
516 return; // Avoid hard failure when the file does not exist. T221812
517 }
518
519 $fname = static::class . '::' . __FUNCTION__;
520
521 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
522 $this->extraDataLoaded = true;
523
524 $db = $this->repo->getReplicaDB();
525 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
526 if ( !$fieldMap ) {
527 $db = $this->repo->getPrimaryDB();
528 $fieldMap = $this->loadExtraFieldsWithTimestamp( $db, $fname );
529 }
530
531 if ( $fieldMap ) {
532 if ( isset( $fieldMap['metadata'] ) ) {
533 $this->loadMetadataFromDbFieldValue( $db, $fieldMap['metadata'] );
534 }
535 } else {
536 throw new RuntimeException( "Could not find data for image '{$this->getName()}'." );
537 }
538 }
539
540 /**
541 * @param IReadableDatabase $dbr
542 * @param string $fname
543 * @return string[]|false
544 */
545 private function loadExtraFieldsWithTimestamp( IReadableDatabase $dbr, $fname ) {
546 $fieldMap = false;
547
548 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr, [ 'omit-nonlazy' ] );
549 $queryBuilder->where( [ 'img_name' => $this->getName() ] )
550 ->andWhere( [ 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] );
551 $row = $queryBuilder->caller( $fname )->fetchRow();
552 if ( $row ) {
553 $fieldMap = $this->unprefixRow( $row, 'img_' );
554 } else {
555 # File may have been uploaded over in the meantime; check the old versions
556 $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr, [ 'omit-nonlazy' ] );
557 $row = $queryBuilder->where( [ 'oi_name' => $this->getName() ] )
558 ->andWhere( [ 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ) ] )
559 ->caller( __METHOD__ )->fetchRow();
560 if ( $row ) {
561 $fieldMap = $this->unprefixRow( $row, 'oi_' );
562 }
563 }
564
565 return $fieldMap;
566 }
567
568 /**
569 * @param array|stdClass $row
570 * @param string $prefix
571 * @return array
572 */
573 protected function unprefixRow( $row, $prefix = 'img_' ) {
574 $array = (array)$row;
575 $prefixLength = strlen( $prefix );
576
577 // Double check prefix once
578 if ( substr( array_key_first( $array ), 0, $prefixLength ) !== $prefix ) {
579 throw new InvalidArgumentException( __METHOD__ . ': incorrect $prefix parameter' );
580 }
581
582 $decoded = [];
583 foreach ( $array as $name => $value ) {
584 $decoded[substr( $name, $prefixLength )] = $value;
585 }
586
587 return $decoded;
588 }
589
590 /**
591 * Load file metadata from a DB result row
592 * @stable to override
593 *
594 * Passing arbitrary fields in the row and expecting them to be translated
595 * to property names on $this is deprecated since 1.37. Instead, override
596 * loadFromRow(), and clone and unset the extra fields before passing them
597 * to the parent.
598 *
599 * After the deprecation period has passed, extra fields will be ignored,
600 * and the deprecation warning will be removed.
601 *
602 * @param stdClass $row
603 * @param string $prefix
604 */
605 public function loadFromRow( $row, $prefix = 'img_' ) {
606 $this->dataLoaded = true;
607
608 $unprefixed = $this->unprefixRow( $row, $prefix );
609
610 $this->name = $unprefixed['name'];
611 $this->media_type = $unprefixed['media_type'];
612
613 $services = MediaWikiServices::getInstance();
614 $this->description = $services->getCommentStore()
615 ->getComment( "{$prefix}description", $row )->text;
616
617 $this->user = $services->getUserFactory()->newFromAnyId(
618 $unprefixed['user'] ?? null,
619 $unprefixed['user_text'] ?? null,
620 $unprefixed['actor'] ?? null
621 );
622
623 $this->timestamp = wfTimestamp( TS_MW, $unprefixed['timestamp'] );
624
625 $this->loadMetadataFromDbFieldValue(
626 $this->repo->getReplicaDB(), $unprefixed['metadata'] );
627
628 if ( empty( $unprefixed['major_mime'] ) ) {
629 $this->major_mime = 'unknown';
630 $this->minor_mime = 'unknown';
631 $this->mime = 'unknown/unknown';
632 } else {
633 if ( !$unprefixed['minor_mime'] ) {
634 $unprefixed['minor_mime'] = 'unknown';
635 }
636 $this->major_mime = $unprefixed['major_mime'];
637 $this->minor_mime = $unprefixed['minor_mime'];
638 $this->mime = $unprefixed['major_mime'] . '/' . $unprefixed['minor_mime'];
639 }
640
641 // Trim zero padding from char/binary field
642 $this->sha1 = rtrim( $unprefixed['sha1'], "\0" );
643
644 // Normalize some fields to integer type, per their database definition.
645 // Use unary + so that overflows will be upgraded to double instead of
646 // being truncated as with intval(). This is important to allow > 2 GiB
647 // files on 32-bit systems.
648 $this->size = +$unprefixed['size'];
649 $this->width = +$unprefixed['width'];
650 $this->height = +$unprefixed['height'];
651 $this->bits = +$unprefixed['bits'];
652
653 // Check for extra fields (deprecated since MW 1.37)
654 $extraFields = array_diff(
655 array_keys( $unprefixed ),
656 [
657 'name', 'media_type', 'description_text', 'description_data',
658 'description_cid', 'user', 'user_text', 'actor', 'timestamp',
659 'metadata', 'major_mime', 'minor_mime', 'sha1', 'size', 'width',
660 'height', 'bits'
661 ]
662 );
663 if ( $extraFields ) {
664 wfDeprecatedMsg(
665 'Passing extra fields (' .
666 implode( ', ', $extraFields )
667 . ') to ' . __METHOD__ . ' was deprecated in MediaWiki 1.37. ' .
668 'Property assignment will be removed in a later version.',
669 '1.37' );
670 foreach ( $extraFields as $field ) {
671 $this->$field = $unprefixed[$field];
672 }
673 }
674
675 $this->fileExists = true;
676 }
677
678 /**
679 * Load file metadata from cache or DB, unless already loaded
680 * @stable to override
681 * @param int $flags
682 */
683 public function load( $flags = 0 ) {
684 if ( !$this->dataLoaded ) {
685 if ( $flags & IDBAccessObject::READ_LATEST ) {
686 $this->loadFromDB( $flags );
687 } else {
688 $this->loadFromCache();
689 }
690 }
691
692 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
693 // @note: loads on name/timestamp to reduce race condition problems
694 $this->loadExtraFromDB();
695 }
696 }
697
698 /**
699 * Upgrade a row if it needs it
700 * @internal
701 */
702 public function maybeUpgradeRow() {
703 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() || $this->upgrading ) {
704 return;
705 }
706
707 $upgrade = false;
708 $reserialize = false;
709 if ( $this->media_type === null || $this->mime == 'image/svg' ) {
710 $upgrade = true;
711 } else {
712 $handler = $this->getHandler();
713 if ( $handler ) {
714 $validity = $handler->isFileMetadataValid( $this );
715 if ( $validity === MediaHandler::METADATA_BAD ) {
716 $upgrade = true;
717 } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE
718 && $this->repo->isMetadataUpdateEnabled()
719 ) {
720 $upgrade = true;
721 } elseif ( $this->repo->isJsonMetadataEnabled()
722 && $this->repo->isMetadataReserializeEnabled()
723 ) {
724 if ( $this->repo->isSplitMetadataEnabled() && $this->isMetadataOversize() ) {
725 $reserialize = true;
726 } elseif ( $this->metadataSerializationFormat !== self::MDS_EMPTY &&
727 $this->metadataSerializationFormat !== self::MDS_JSON ) {
728 $reserialize = true;
729 }
730 }
731 }
732 }
733
734 if ( $upgrade || $reserialize ) {
735 $this->upgrading = true;
736 // Defer updates unless in auto-commit CLI mode
737 DeferredUpdates::addCallableUpdate( function () use ( $upgrade ) {
738 $this->upgrading = false; // avoid duplicate updates
739 try {
740 if ( $upgrade ) {
741 $this->upgradeRow();
742 } else {
743 $this->reserializeMetadata();
744 }
745 } catch ( LocalFileLockError $e ) {
746 // let the other process handle it (or do it next time)
747 }
748 } );
749 }
750 }
751
752 /**
753 * @return bool Whether upgradeRow() ran for this object
754 */
755 public function getUpgraded() {
756 return $this->upgraded;
757 }
758
759 /**
760 * Fix assorted version-related problems with the image row by reloading it from the file
761 * @stable to override
762 */
763 public function upgradeRow() {
764 $dbw = $this->repo->getPrimaryDB();
765
766 // Make a DB query condition that will fail to match the image row if the
767 // image was reuploaded while the upgrade was in process.
768 $freshnessCondition = [ 'img_timestamp' => $dbw->timestamp( $this->getTimestamp() ) ];
769
770 $this->loadFromFile();
771
772 # Don't destroy file info of missing files
773 if ( !$this->fileExists ) {
774 wfDebug( __METHOD__ . ": file does not exist, aborting" );
775
776 return;
777 }
778
779 [ $major, $minor ] = self::splitMime( $this->mime );
780
781 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema" );
782
783 $dbw->newUpdateQueryBuilder()
784 ->update( 'image' )
785 ->set( [
786 'img_size' => $this->size,
787 'img_width' => $this->width,
788 'img_height' => $this->height,
789 'img_bits' => $this->bits,
790 'img_media_type' => $this->media_type,
791 'img_major_mime' => $major,
792 'img_minor_mime' => $minor,
793 'img_metadata' => $this->getMetadataForDb( $dbw ),
794 'img_sha1' => $this->sha1,
795 ] )
796 ->where( [ 'img_name' => $this->getName() ] )
797 ->andWhere( $freshnessCondition )
798 ->caller( __METHOD__ )->execute();
799
800 $this->invalidateCache();
801
802 $this->upgraded = true; // avoid rework/retries
803 }
804
805 /**
806 * Write the metadata back to the database with the current serialization
807 * format.
808 */
809 protected function reserializeMetadata() {
810 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
811 return;
812 }
813 $dbw = $this->repo->getPrimaryDB();
814 $dbw->newUpdateQueryBuilder()
815 ->update( 'image' )
816 ->set( [ 'img_metadata' => $this->getMetadataForDb( $dbw ) ] )
817 ->where( [
818 'img_name' => $this->name,
819 'img_timestamp' => $dbw->timestamp( $this->timestamp ),
820 ] )
821 ->caller( __METHOD__ )->execute();
822 $this->upgraded = true;
823 }
824
825 /**
826 * Set properties in this object to be equal to those given in the
827 * associative array $info. Only cacheable fields can be set.
828 * All fields *must* be set in $info except for getLazyCacheFields().
829 *
830 * If 'mime' is given, it will be split into major_mime/minor_mime.
831 * If major_mime/minor_mime are given, $this->mime will also be set.
832 *
833 * @stable to override
834 * @param array $info
835 */
836 protected function setProps( $info ) {
837 $this->dataLoaded = true;
838 $fields = $this->getCacheFields( '' );
839 $fields[] = 'fileExists';
840
841 foreach ( $fields as $field ) {
842 if ( isset( $info[$field] ) ) {
843 $this->$field = $info[$field];
844 }
845 }
846
847 // Only our own cache sets these properties, so they both should be present.
848 if ( isset( $info['user'] ) &&
849 isset( $info['user_text'] ) &&
850 $info['user_text'] !== ''
851 ) {
852 $this->user = new UserIdentityValue( $info['user'], $info['user_text'] );
853 }
854
855 // Fix up mime fields
856 if ( isset( $info['major_mime'] ) ) {
857 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
858 } elseif ( isset( $info['mime'] ) ) {
859 $this->mime = $info['mime'];
860 [ $this->major_mime, $this->minor_mime ] = self::splitMime( $this->mime );
861 }
862
863 if ( isset( $info['metadata'] ) ) {
864 if ( is_string( $info['metadata'] ) ) {
865 $this->loadMetadataFromString( $info['metadata'] );
866 } elseif ( is_array( $info['metadata'] ) ) {
867 $this->metadataArray = $info['metadata'];
868 if ( isset( $info['metadataBlobs'] ) ) {
869 $this->metadataBlobs = $info['metadataBlobs'];
870 $this->unloadedMetadataBlobs = array_diff_key(
871 $this->metadataBlobs,
872 $this->metadataArray
873 );
874 } else {
875 $this->metadataBlobs = [];
876 $this->unloadedMetadataBlobs = [];
877 }
878 } else {
879 $logger = LoggerFactory::getInstance( 'LocalFile' );
880 $logger->warning( __METHOD__ . ' given invalid metadata of type ' .
881 get_debug_type( $info['metadata'] ) );
882 $this->metadataArray = [];
883 }
884 $this->extraDataLoaded = true;
885 }
886 }
887
888 /** splitMime inherited */
889 /** getName inherited */
890 /** getTitle inherited */
891 /** getURL inherited */
892 /** getViewURL inherited */
893 /** getPath inherited */
894 /** isVisible inherited */
895
896 /**
897 * Checks if this file exists in its parent repo, as referenced by its
898 * virtual URL.
899 * @stable to override
900 *
901 * @return bool
902 */
903 public function isMissing() {
904 if ( $this->missing === null ) {
905 $fileExists = $this->repo->fileExists( $this->getVirtualUrl() );
906 $this->missing = !$fileExists;
907 }
908
909 return $this->missing;
910 }
911
912 /**
913 * Return the width of the image
914 * @stable to override
915 *
916 * @param int $page
917 * @return int
918 */
919 public function getWidth( $page = 1 ) {
920 $page = (int)$page;
921 if ( $page < 1 ) {
922 $page = 1;
923 }
924
925 $this->load();
926
927 if ( $this->isMultipage() ) {
928 $handler = $this->getHandler();
929 if ( !$handler ) {
930 return 0;
931 }
932 $dim = $handler->getPageDimensions( $this, $page );
933 if ( $dim ) {
934 return $dim['width'];
935 } else {
936 // For non-paged media, the false goes through an
937 // intval, turning failure into 0, so do same here.
938 return 0;
939 }
940 } else {
941 return $this->width;
942 }
943 }
944
945 /**
946 * Return the height of the image
947 * @stable to override
948 *
949 * @param int $page
950 * @return int
951 */
952 public function getHeight( $page = 1 ) {
953 $page = (int)$page;
954 if ( $page < 1 ) {
955 $page = 1;
956 }
957
958 $this->load();
959
960 if ( $this->isMultipage() ) {
961 $handler = $this->getHandler();
962 if ( !$handler ) {
963 return 0;
964 }
965 $dim = $handler->getPageDimensions( $this, $page );
966 if ( $dim ) {
967 return $dim['height'];
968 } else {
969 // For non-paged media, the false goes through an
970 // intval, turning failure into 0, so do same here.
971 return 0;
972 }
973 } else {
974 return $this->height;
975 }
976 }
977
978 /**
979 * Get short description URL for a file based on the page ID.
980 * @stable to override
981 *
982 * @return string|null
983 * @since 1.27
984 */
985 public function getDescriptionShortUrl() {
986 if ( !$this->title ) {
987 return null; // Avoid hard failure when the file does not exist. T221812
988 }
989
990 $pageId = $this->title->getArticleID();
991
992 if ( $pageId ) {
993 $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
994 if ( $url !== false ) {
995 return $url;
996 }
997 }
998 return null;
999 }
1000
1001 /**
1002 * Get handler-specific metadata as a serialized string
1003 *
1004 * @deprecated since 1.37 use getMetadataArray() or getMetadataItem()
1005 * @return string
1006 */
1007 public function getMetadata() {
1008 $data = $this->getMetadataArray();
1009 if ( !$data ) {
1010 return '';
1011 } elseif ( array_keys( $data ) === [ '_error' ] ) {
1012 // Legacy error encoding
1013 return $data['_error'];
1014 } else {
1015 return serialize( $this->getMetadataArray() );
1016 }
1017 }
1018
1019 /**
1020 * Get unserialized handler-specific metadata
1021 *
1022 * @since 1.37
1023 * @return array
1024 */
1025 public function getMetadataArray(): array {
1026 $this->load( self::LOAD_ALL );
1027 if ( $this->unloadedMetadataBlobs ) {
1028 return $this->getMetadataItems(
1029 array_unique( array_merge(
1030 array_keys( $this->metadataArray ),
1031 array_keys( $this->unloadedMetadataBlobs )
1032 ) )
1033 );
1034 }
1035 return $this->metadataArray;
1036 }
1037
1038 public function getMetadataItems( array $itemNames ): array {
1039 $this->load( self::LOAD_ALL );
1040 $result = [];
1041 $addresses = [];
1042 foreach ( $itemNames as $itemName ) {
1043 if ( array_key_exists( $itemName, $this->metadataArray ) ) {
1044 $result[$itemName] = $this->metadataArray[$itemName];
1045 } elseif ( isset( $this->unloadedMetadataBlobs[$itemName] ) ) {
1046 $addresses[$itemName] = $this->unloadedMetadataBlobs[$itemName];
1047 }
1048 }
1049
1050 if ( $addresses ) {
1051 $resultFromBlob = $this->metadataStorageHelper->getMetadataFromBlobStore( $addresses );
1052 foreach ( $addresses as $itemName => $address ) {
1053 unset( $this->unloadedMetadataBlobs[$itemName] );
1054 $value = $resultFromBlob[$itemName] ?? null;
1055 if ( $value !== null ) {
1056 $result[$itemName] = $value;
1057 $this->metadataArray[$itemName] = $value;
1058 }
1059 }
1060 }
1061 return $result;
1062 }
1063
1064 /**
1065 * Serialize the metadata array for insertion into img_metadata, oi_metadata
1066 * or fa_metadata.
1067 *
1068 * If metadata splitting is enabled, this may write blobs to the database,
1069 * returning their addresses.
1070 *
1071 * @internal
1072 * @param IReadableDatabase $db
1073 * @return string|Blob
1074 */
1075 public function getMetadataForDb( IReadableDatabase $db ) {
1076 $this->load( self::LOAD_ALL );
1077 if ( !$this->metadataArray && !$this->metadataBlobs ) {
1078 $s = '';
1079 } elseif ( $this->repo->isJsonMetadataEnabled() ) {
1080 $s = $this->getJsonMetadata();
1081 } else {
1082 $s = serialize( $this->getMetadataArray() );
1083 }
1084 if ( !is_string( $s ) ) {
1085 throw new RuntimeException( 'Could not serialize image metadata value for DB' );
1086 }
1087 return $db->encodeBlob( $s );
1088 }
1089
1090 /**
1091 * Get metadata in JSON format ready for DB insertion, optionally splitting
1092 * items out to BlobStore.
1093 *
1094 * @return string
1095 */
1096 private function getJsonMetadata() {
1097 // Directly store data that is not already in BlobStore
1098 $envelope = [
1099 'data' => array_diff_key( $this->metadataArray, $this->metadataBlobs )
1100 ];
1101
1102 // Also store the blob addresses
1103 if ( $this->metadataBlobs ) {
1104 $envelope['blobs'] = $this->metadataBlobs;
1105 }
1106
1107 [ $s, $blobAddresses ] = $this->metadataStorageHelper->getJsonMetadata( $this, $envelope );
1108
1109 // Repeated calls to this function should not keep inserting more blobs
1110 $this->metadataBlobs += $blobAddresses;
1111
1112 return $s;
1113 }
1114
1115 /**
1116 * Determine whether the loaded metadata may be a candidate for splitting, by measuring its
1117 * serialized size. Helper for maybeUpgradeRow().
1118 *
1119 * @return bool
1120 */
1121 private function isMetadataOversize() {
1122 if ( !$this->repo->isSplitMetadataEnabled() ) {
1123 return false;
1124 }
1125 $threshold = $this->repo->getSplitMetadataThreshold();
1126 $directItems = array_diff_key( $this->metadataArray, $this->metadataBlobs );
1127 foreach ( $directItems as $value ) {
1128 if ( strlen( $this->metadataStorageHelper->jsonEncode( $value ) ) > $threshold ) {
1129 return true;
1130 }
1131 }
1132 return false;
1133 }
1134
1135 /**
1136 * Unserialize a metadata blob which came from the database and store it
1137 * in $this.
1138 *
1139 * @since 1.37
1140 * @param IReadableDatabase $db
1141 * @param string|Blob $metadataBlob
1142 */
1143 protected function loadMetadataFromDbFieldValue( IReadableDatabase $db, $metadataBlob ) {
1144 $this->loadMetadataFromString( $db->decodeBlob( $metadataBlob ) );
1145 }
1146
1147 /**
1148 * Unserialize a metadata string which came from some non-DB source, or is
1149 * the return value of IReadableDatabase::decodeBlob().
1150 *
1151 * @since 1.37
1152 * @param string $metadataString
1153 */
1154 protected function loadMetadataFromString( $metadataString ) {
1155 $this->extraDataLoaded = true;
1156 $this->metadataArray = [];
1157 $this->metadataBlobs = [];
1158 $this->unloadedMetadataBlobs = [];
1159 $metadataString = (string)$metadataString;
1160 if ( $metadataString === '' ) {
1161 $this->metadataSerializationFormat = self::MDS_EMPTY;
1162 return;
1163 }
1164 if ( $metadataString[0] === '{' ) {
1165 $envelope = $this->metadataStorageHelper->jsonDecode( $metadataString );
1166 if ( !$envelope ) {
1167 // Legacy error encoding
1168 $this->metadataArray = [ '_error' => $metadataString ];
1169 $this->metadataSerializationFormat = self::MDS_LEGACY;
1170 } else {
1171 $this->metadataSerializationFormat = self::MDS_JSON;
1172 if ( isset( $envelope['data'] ) ) {
1173 $this->metadataArray = $envelope['data'];
1174 }
1175 if ( isset( $envelope['blobs'] ) ) {
1176 $this->metadataBlobs = $this->unloadedMetadataBlobs = $envelope['blobs'];
1177 }
1178 }
1179 } else {
1180 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1181 $data = @unserialize( $metadataString );
1182 if ( !is_array( $data ) ) {
1183 // Legacy error encoding
1184 $data = [ '_error' => $metadataString ];
1185 $this->metadataSerializationFormat = self::MDS_LEGACY;
1186 } else {
1187 $this->metadataSerializationFormat = self::MDS_PHP;
1188 }
1189 $this->metadataArray = $data;
1190 }
1191 }
1192
1193 /**
1194 * @stable to override
1195 * @return int
1196 */
1197 public function getBitDepth() {
1198 $this->load();
1199
1200 return (int)$this->bits;
1201 }
1202
1203 /**
1204 * Returns the size of the image file, in bytes
1205 * @stable to override
1206 * @return int
1207 */
1208 public function getSize() {
1209 $this->load();
1210
1211 return $this->size;
1212 }
1213
1214 /**
1215 * Returns the MIME type of the file.
1216 * @stable to override
1217 * @return string
1218 */
1219 public function getMimeType() {
1220 $this->load();
1221
1222 return $this->mime;
1223 }
1224
1225 /**
1226 * Returns the type of the media in the file.
1227 * Use the value returned by this function with the MEDIATYPE_xxx constants.
1228 * @stable to override
1229 * @return string
1230 */
1231 public function getMediaType() {
1232 $this->load();
1233
1234 return $this->media_type;
1235 }
1236
1237 /** canRender inherited */
1238 /** mustRender inherited */
1239 /** allowInlineDisplay inherited */
1240 /** isSafeFile inherited */
1241 /** isTrustedFile inherited */
1242
1243 /**
1244 * Returns true if the file exists on disk.
1245 * @stable to override
1246 * @return bool Whether file exist on disk.
1247 */
1248 public function exists() {
1249 $this->load();
1250
1251 return $this->fileExists;
1252 }
1253
1254 /** getTransformScript inherited */
1255 /** getUnscaledThumb inherited */
1256 /** thumbName inherited */
1257 /** createThumb inherited */
1258 /** transform inherited */
1259
1260 /** getHandler inherited */
1261 /** iconThumb inherited */
1262 /** getLastError inherited */
1263
1264 /**
1265 * Get all thumbnail names previously generated for this file.
1266 *
1267 * This should be called during POST requests only (and other db-writing
1268 * contexts) as it may involve connections across multiple data centers
1269 * (e.g. both backends of a FileBackendMultiWrite setup).
1270 *
1271 * @stable to override
1272 * @param string|false $archiveName Name of an archive file, default false
1273 * @return array First element is the base dir, then files in that base dir.
1274 */
1275 protected function getThumbnails( $archiveName = false ) {
1276 if ( $archiveName ) {
1277 $dir = $this->getArchiveThumbPath( $archiveName );
1278 } else {
1279 $dir = $this->getThumbPath();
1280 }
1281
1282 $backend = $this->repo->getBackend();
1283 $files = [ $dir ];
1284 try {
1285 $iterator = $backend->getFileList( [ 'dir' => $dir, 'forWrite' => true ] );
1286 if ( $iterator !== null ) {
1287 foreach ( $iterator as $file ) {
1288 $files[] = $file;
1289 }
1290 }
1291 } catch ( FileBackendError $e ) {
1292 } // suppress (T56674)
1293
1294 return $files;
1295 }
1296
1297 /**
1298 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1299 * @stable to override
1300 *
1301 * @param array $options An array potentially with the key forThumbRefresh.
1302 *
1303 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1304 */
1305 public function purgeCache( $options = [] ) {
1306 // Refresh metadata in memcached, but don't touch thumbnails or CDN
1307 $this->maybeUpgradeRow();
1308 $this->invalidateCache();
1309
1310 // Delete thumbnails
1311 $this->purgeThumbnails( $options );
1312
1313 // Purge CDN cache for this file
1314 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1315 $hcu->purgeUrls(
1316 $this->getUrl(),
1317 !empty( $options['forThumbRefresh'] )
1318 ? $hcu::PURGE_PRESEND // just a manual purge
1319 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1320 );
1321 }
1322
1323 /**
1324 * Delete cached transformed files for an archived version only.
1325 * @stable to override
1326 * @param string $archiveName Name of the archived file
1327 */
1328 public function purgeOldThumbnails( $archiveName ) {
1329 // Get a list of old thumbnails
1330 $thumbs = $this->getThumbnails( $archiveName );
1331
1332 // Delete thumbnails from storage, and prevent the directory itself from being purged
1333 $dir = array_shift( $thumbs );
1334 $this->purgeThumbList( $dir, $thumbs );
1335
1336 $urls = [];
1337 foreach ( $thumbs as $thumb ) {
1338 $urls[] = $this->getArchiveThumbUrl( $archiveName, $thumb );
1339 }
1340
1341 // Purge any custom thumbnail caches
1342 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, $archiveName, $urls );
1343
1344 // Purge the CDN
1345 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1346 $hcu->purgeUrls( $urls, $hcu::PURGE_PRESEND );
1347 }
1348
1349 /**
1350 * Delete cached transformed files for the current version only.
1351 * @stable to override
1352 * @param array $options
1353 * @phan-param array{forThumbRefresh?:bool} $options
1354 */
1355 public function purgeThumbnails( $options = [] ) {
1356 $thumbs = $this->getThumbnails();
1357
1358 // Delete thumbnails from storage, and prevent the directory itself from being purged
1359 $dir = array_shift( $thumbs );
1360 $this->purgeThumbList( $dir, $thumbs );
1361
1362 // Always purge all files from CDN regardless of handler filters
1363 $urls = [];
1364 foreach ( $thumbs as $thumb ) {
1365 $urls[] = $this->getThumbUrl( $thumb );
1366 }
1367
1368 // Give the media handler a chance to filter the file purge list
1369 if ( !empty( $options['forThumbRefresh'] ) ) {
1370 $handler = $this->getHandler();
1371 if ( $handler ) {
1372 $handler->filterThumbnailPurgeList( $thumbs, $options );
1373 }
1374 }
1375
1376 // Purge any custom thumbnail caches
1377 $this->getHookRunner()->onLocalFilePurgeThumbnails( $this, false, $urls );
1378
1379 // Purge the CDN
1380 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1381 $hcu->purgeUrls(
1382 $urls,
1383 !empty( $options['forThumbRefresh'] )
1384 ? $hcu::PURGE_PRESEND // just a manual purge
1385 : $hcu::PURGE_INTENT_TXROUND_REFLECTED
1386 );
1387 }
1388
1389 /**
1390 * Prerenders a configurable set of thumbnails
1391 * @stable to override
1392 *
1393 * @since 1.28
1394 */
1395 public function prerenderThumbnails() {
1396 $uploadThumbnailRenderMap = MediaWikiServices::getInstance()
1397 ->getMainConfig()->get( MainConfigNames::UploadThumbnailRenderMap );
1398
1399 $jobs = [];
1400
1401 $sizes = $uploadThumbnailRenderMap;
1402 rsort( $sizes );
1403
1404 foreach ( $sizes as $size ) {
1405 if ( $this->isMultipage() ) {
1406 // (T309114) Only trigger render jobs up to MAX_PAGE_RENDER_JOBS to avoid
1407 // a flood of jobs for huge files.
1408 $pageLimit = min( $this->pageCount(), self::MAX_PAGE_RENDER_JOBS );
1409
1410 $jobs[] = new ThumbnailRenderJob(
1411 $this->getTitle(),
1412 [
1413 'transformParams' => [ 'width' => $size, 'page' => 1 ],
1414 'enqueueNextPage' => true,
1415 'pageLimit' => $pageLimit
1416 ]
1417 );
1418 } elseif ( $this->isVectorized() || $this->getWidth() > $size ) {
1419 $jobs[] = new ThumbnailRenderJob(
1420 $this->getTitle(),
1421 [ 'transformParams' => [ 'width' => $size ] ]
1422 );
1423 }
1424 }
1425
1426 if ( $jobs ) {
1427 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $jobs );
1428 }
1429 }
1430
1431 /**
1432 * Delete a list of thumbnails visible at urls
1433 * @stable to override
1434 * @param string $dir Base dir of the files.
1435 * @param array $files Array of strings: relative filenames (to $dir)
1436 */
1437 protected function purgeThumbList( $dir, $files ) {
1438 $fileListDebug = strtr(
1439 var_export( $files, true ),
1440 [ "\n" => '' ]
1441 );
1442 wfDebug( __METHOD__ . ": $fileListDebug" );
1443
1444 if ( $this->repo->supportsSha1URLs() ) {
1445 $reference = $this->getSha1();
1446 } else {
1447 $reference = $this->getName();
1448 }
1449
1450 $purgeList = [];
1451 foreach ( $files as $file ) {
1452 # Check that the reference (filename or sha1) is part of the thumb name
1453 # This is a basic check to avoid erasing unrelated directories
1454 if ( str_contains( $file, $reference )
1455 || str_contains( $file, "-thumbnail" ) // "short" thumb name
1456 ) {
1457 $purgeList[] = "{$dir}/{$file}";
1458 }
1459 }
1460
1461 # Delete the thumbnails
1462 $this->repo->quickPurgeBatch( $purgeList );
1463 # Clear out the thumbnail directory if empty
1464 $this->repo->quickCleanDir( $dir );
1465 }
1466
1467 /** purgeDescription inherited */
1468 /** purgeEverything inherited */
1469
1470 /**
1471 * @stable to override
1472 * @param int|null $limit Optional: Limit to number of results
1473 * @param string|int|null $start Optional: Timestamp, start from
1474 * @param string|int|null $end Optional: Timestamp, end at
1475 * @param bool $inc
1476 * @return OldLocalFile[] Guaranteed to be in descending order
1477 */
1478 public function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1479 if ( !$this->exists() ) {
1480 return []; // Avoid hard failure when the file does not exist. T221812
1481 }
1482
1483 $dbr = $this->repo->getReplicaDB();
1484 $oldFileQuery = OldLocalFile::getQueryInfo();
1485
1486 $tables = $oldFileQuery['tables'];
1487 $fields = $oldFileQuery['fields'];
1488 $join_conds = $oldFileQuery['joins'];
1489 $conds = $opts = [];
1490 $eq = $inc ? '=' : '';
1491 $conds[] = $dbr->expr( 'oi_name', '=', $this->title->getDBkey() );
1492
1493 if ( $start ) {
1494 $conds[] = $dbr->expr( 'oi_timestamp', "<$eq", $dbr->timestamp( $start ) );
1495 }
1496
1497 if ( $end ) {
1498 $conds[] = $dbr->expr( 'oi_timestamp', ">$eq", $dbr->timestamp( $end ) );
1499 }
1500
1501 if ( $limit ) {
1502 $opts['LIMIT'] = $limit;
1503 }
1504
1505 // Search backwards for time > x queries
1506 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1507 $opts['ORDER BY'] = "oi_timestamp $order";
1508 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1509
1510 $this->getHookRunner()->onLocalFile__getHistory( $this, $tables, $fields,
1511 $conds, $opts, $join_conds );
1512
1513 $res = $dbr->newSelectQueryBuilder()
1514 ->tables( $tables )
1515 ->fields( $fields )
1516 ->conds( $conds )
1517 ->caller( __METHOD__ )
1518 ->options( $opts )
1519 ->joinConds( $join_conds )
1520 ->fetchResultSet();
1521 $r = [];
1522
1523 foreach ( $res as $row ) {
1524 $r[] = $this->repo->newFileFromRow( $row );
1525 }
1526
1527 if ( $order == 'ASC' ) {
1528 $r = array_reverse( $r ); // make sure it ends up descending
1529 }
1530
1531 return $r;
1532 }
1533
1534 /**
1535 * Returns the history of this file, line by line.
1536 * starts with current version, then old versions.
1537 * uses $this->historyLine to check which line to return:
1538 * 0 return line for current version
1539 * 1 query for old versions, return first one
1540 * 2, ... return next old version from above query
1541 * @stable to override
1542 * @return stdClass|false
1543 */
1544 public function nextHistoryLine() {
1545 if ( !$this->exists() ) {
1546 return false; // Avoid hard failure when the file does not exist. T221812
1547 }
1548
1549 # Polymorphic function name to distinguish foreign and local fetches
1550 $fname = static::class . '::' . __FUNCTION__;
1551
1552 $dbr = $this->repo->getReplicaDB();
1553
1554 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1555 $queryBuilder = FileSelectQueryBuilder::newForFile( $dbr );
1556
1557 $queryBuilder->fields( [ 'oi_archive_name' => $dbr->addQuotes( '' ), 'oi_deleted' => '0' ] )
1558 ->where( [ 'img_name' => $this->title->getDBkey() ] );
1559 $this->historyRes = $queryBuilder->caller( $fname )->fetchResultSet();
1560
1561 if ( $this->historyRes->numRows() == 0 ) {
1562 $this->historyRes = null;
1563
1564 return false;
1565 }
1566 } elseif ( $this->historyLine == 1 ) {
1567 $queryBuilder = FileSelectQueryBuilder::newForOldFile( $dbr );
1568
1569 $this->historyRes = $queryBuilder->where( [ 'oi_name' => $this->title->getDBkey() ] )
1570 ->orderBy( 'oi_timestamp', SelectQueryBuilder::SORT_DESC )
1571 ->caller( $fname )->fetchResultSet();
1572 }
1573 $this->historyLine++;
1574
1575 return $this->historyRes->fetchObject();
1576 }
1577
1578 /**
1579 * Reset the history pointer to the first element of the history
1580 * @stable to override
1581 */
1582 public function resetHistory() {
1583 $this->historyLine = 0;
1584
1585 if ( $this->historyRes !== null ) {
1586 $this->historyRes = null;
1587 }
1588 }
1589
1590 /** getHashPath inherited */
1591 /** getRel inherited */
1592 /** getUrlRel inherited */
1593 /** getArchiveRel inherited */
1594 /** getArchivePath inherited */
1595 /** getThumbPath inherited */
1596 /** getArchiveUrl inherited */
1597 /** getThumbUrl inherited */
1598 /** getArchiveVirtualUrl inherited */
1599 /** getThumbVirtualUrl inherited */
1600 /** isHashed inherited */
1601
1602 /**
1603 * Upload a file and record it in the DB
1604 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1605 * @param string $comment Upload description
1606 * @param string $pageText Text to use for the new description page,
1607 * if a new description page is created
1608 * @param int $flags Flags for publish()
1609 * @param array|false $props File properties, if known. This can be used to
1610 * reduce the upload time when uploading virtual URLs for which the file
1611 * info is already known
1612 * @param string|false $timestamp Timestamp for img_timestamp, or false to use the
1613 * current time. Can be in any format accepted by ConvertibleTimestamp.
1614 * @param Authority|null $uploader object or null to use the context authority
1615 * @param string[] $tags Change tags to add to the log entry and page revision.
1616 * (This doesn't check $uploader's permissions.)
1617 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1618 * upload, see T193621
1619 * @param bool $revert If this file upload is a revert
1620 * @return Status On success, the value member contains the
1621 * archive name, or an empty string if it was a new file.
1622 */
1623 public function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1624 $timestamp = false, ?Authority $uploader = null, $tags = [],
1625 $createNullRevision = true, $revert = false
1626 ) {
1627 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1628 return $this->readOnlyFatalStatus();
1629 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1630 // Check this in advance to avoid writing to FileBackend and the file tables,
1631 // only to fail on insert the revision due to the text store being unavailable.
1632 return $this->readOnlyFatalStatus();
1633 }
1634
1635 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1636 if ( !$props ) {
1637 if ( FileRepo::isVirtualUrl( $srcPath )
1638 || FileBackend::isStoragePath( $srcPath )
1639 ) {
1640 $props = $this->repo->getFileProps( $srcPath );
1641 } else {
1642 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1643 $props = $mwProps->getPropsFromPath( $srcPath, true );
1644 }
1645 }
1646
1647 $options = [];
1648 $handler = MediaHandler::getHandler( $props['mime'] );
1649 if ( $handler ) {
1650 if ( is_string( $props['metadata'] ) ) {
1651 // This supports callers directly fabricating a metadata
1652 // property using serialize(). Normally the metadata property
1653 // comes from MWFileProps, in which case it won't be a string.
1654 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1655 $metadata = @unserialize( $props['metadata'] );
1656 } else {
1657 $metadata = $props['metadata'];
1658 }
1659
1660 if ( is_array( $metadata ) ) {
1661 $options['headers'] = $handler->getContentHeaders( $metadata );
1662 }
1663 } else {
1664 $options['headers'] = [];
1665 }
1666
1667 // Trim spaces on user supplied text
1668 $comment = trim( $comment );
1669
1670 $status = $this->publish( $src, $flags, $options );
1671
1672 if ( $status->successCount >= 2 ) {
1673 // There will be a copy+(one of move,copy,store).
1674 // The first succeeding does not commit us to updating the DB
1675 // since it simply copied the current version to a timestamped file name.
1676 // It is only *preferable* to avoid leaving such files orphaned.
1677 // Once the second operation goes through, then the current version was
1678 // updated and we must therefore update the DB too.
1679 $oldver = $status->value;
1680
1681 $uploadStatus = $this->recordUpload3(
1682 $oldver,
1683 $comment,
1684 $pageText,
1685 $uploader ?? RequestContext::getMain()->getAuthority(),
1686 $props,
1687 $timestamp,
1688 $tags,
1689 $createNullRevision,
1690 $revert
1691 );
1692 if ( !$uploadStatus->isOK() ) {
1693 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1694 // update filenotfound error with more specific path
1695 $status->fatal( 'filenotfound', $srcPath );
1696 } else {
1697 $status->merge( $uploadStatus );
1698 }
1699 }
1700 }
1701
1702 return $status;
1703 }
1704
1705 /**
1706 * Record a file upload in the upload log and the image table (version 3)
1707 * @since 1.35
1708 * @stable to override
1709 * @param string $oldver
1710 * @param string $comment
1711 * @param string $pageText File description page text (only used for new uploads)
1712 * @param Authority $performer
1713 * @param array|false $props
1714 * @param string|false $timestamp Can be in any format accepted by ConvertibleTimestamp
1715 * @param string[] $tags
1716 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1717 * upload, see T193621
1718 * @param bool $revert If this file upload is a revert
1719 * @return Status
1720 */
1721 public function recordUpload3(
1722 string $oldver,
1723 string $comment,
1724 string $pageText,
1725 Authority $performer,
1726 $props = false,
1727 $timestamp = false,
1728 $tags = [],
1729 bool $createNullRevision = true,
1730 bool $revert = false
1731 ): Status {
1732 $dbw = $this->repo->getPrimaryDB();
1733
1734 # Imports or such might force a certain timestamp; otherwise we generate
1735 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1736 if ( $timestamp === false ) {
1737 $timestamp = $dbw->timestamp();
1738 $allowTimeKludge = true;
1739 } else {
1740 $allowTimeKludge = false;
1741 }
1742
1743 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1744 $props['description'] = $comment;
1745 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1746 $this->setProps( $props );
1747
1748 # Fail now if the file isn't there
1749 if ( !$this->fileExists ) {
1750 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!" );
1751
1752 return Status::newFatal( 'filenotfound', $this->getRel() );
1753 }
1754
1755 $mimeAnalyzer = MediaWikiServices::getInstance()->getMimeAnalyzer();
1756 if ( !$mimeAnalyzer->isValidMajorMimeType( $this->major_mime ) ) {
1757 $this->major_mime = 'unknown';
1758 }
1759
1760 $actorNormalizaton = MediaWikiServices::getInstance()->getActorNormalization();
1761
1762 $dbw->startAtomic( __METHOD__ );
1763
1764 $actorId = $actorNormalizaton->acquireActorId( $performer->getUser(), $dbw );
1765 $this->user = $performer->getUser();
1766
1767 # Test to see if the row exists using INSERT IGNORE
1768 # This avoids race conditions by locking the row until the commit, and also
1769 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1770 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1771 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1772 $actorFields = [ 'img_actor' => $actorId ];
1773 $dbw->newInsertQueryBuilder()
1774 ->insertInto( 'image' )
1775 ->ignore()
1776 ->row( [
1777 'img_name' => $this->getName(),
1778 'img_size' => $this->size,
1779 'img_width' => intval( $this->width ),
1780 'img_height' => intval( $this->height ),
1781 'img_bits' => $this->bits,
1782 'img_media_type' => $this->media_type,
1783 'img_major_mime' => $this->major_mime,
1784 'img_minor_mime' => $this->minor_mime,
1785 'img_timestamp' => $dbw->timestamp( $timestamp ),
1786 'img_metadata' => $this->getMetadataForDb( $dbw ),
1787 'img_sha1' => $this->sha1
1788 ] + $commentFields + $actorFields )
1789 ->caller( __METHOD__ )->execute();
1790 $reupload = ( $dbw->affectedRows() == 0 );
1791
1792 if ( $reupload ) {
1793 $row = $dbw->newSelectQueryBuilder()
1794 ->select( [ 'img_timestamp', 'img_sha1' ] )
1795 ->from( 'image' )
1796 ->where( [ 'img_name' => $this->getName() ] )
1797 ->caller( __METHOD__ )->fetchRow();
1798
1799 if ( $row && $row->img_sha1 === $this->sha1 ) {
1800 $dbw->endAtomic( __METHOD__ );
1801 wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!" );
1802 $title = Title::newFromText( $this->getName(), NS_FILE );
1803 return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1804 }
1805
1806 if ( $allowTimeKludge ) {
1807 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1808 $lUnixtime = $row ? (int)wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1809 # Avoid a timestamp that is not newer than the last version
1810 # TODO: the image/oldimage tables should be like page/revision with an ID field
1811 if ( $lUnixtime && (int)wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1812 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1813 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1814 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1815 }
1816 }
1817
1818 $tables = [ 'image' ];
1819 $fields = [
1820 'oi_name' => 'img_name',
1821 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1822 'oi_size' => 'img_size',
1823 'oi_width' => 'img_width',
1824 'oi_height' => 'img_height',
1825 'oi_bits' => 'img_bits',
1826 'oi_description_id' => 'img_description_id',
1827 'oi_timestamp' => 'img_timestamp',
1828 'oi_metadata' => 'img_metadata',
1829 'oi_media_type' => 'img_media_type',
1830 'oi_major_mime' => 'img_major_mime',
1831 'oi_minor_mime' => 'img_minor_mime',
1832 'oi_sha1' => 'img_sha1',
1833 'oi_actor' => 'img_actor',
1834 ];
1835 $joins = [];
1836
1837 # (T36993) Note: $oldver can be empty here, if the previous
1838 # version of the file was broken. Allow registration of the new
1839 # version to continue anyway, because that's better than having
1840 # an image that's not fixable by user operations.
1841 # Collision, this is an update of a file
1842 # Insert previous contents into oldimage
1843 $dbw->insertSelect( 'oldimage', $tables, $fields,
1844 [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1845
1846 # Update the current image row
1847 $dbw->newUpdateQueryBuilder()
1848 ->update( 'image' )
1849 ->set( [
1850 'img_size' => $this->size,
1851 'img_width' => intval( $this->width ),
1852 'img_height' => intval( $this->height ),
1853 'img_bits' => $this->bits,
1854 'img_media_type' => $this->media_type,
1855 'img_major_mime' => $this->major_mime,
1856 'img_minor_mime' => $this->minor_mime,
1857 'img_timestamp' => $dbw->timestamp( $timestamp ),
1858 'img_metadata' => $this->getMetadataForDb( $dbw ),
1859 'img_sha1' => $this->sha1
1860 ] + $commentFields + $actorFields )
1861 ->where( [ 'img_name' => $this->getName() ] )
1862 ->caller( __METHOD__ )->execute();
1863 }
1864
1865 $descTitle = $this->getTitle();
1866 $descId = $descTitle->getArticleID();
1867 $wikiPage = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $descTitle );
1868 if ( !$wikiPage instanceof WikiFilePage ) {
1869 throw new UnexpectedValueException( 'Cannot obtain instance of WikiFilePage for ' . $this->getName()
1870 . ', got instance of ' . get_class( $wikiPage ) );
1871 }
1872 $wikiPage->setFile( $this );
1873
1874 // Determine log action. If reupload is done by reverting, use a special log_action.
1875 if ( $revert ) {
1876 $logAction = 'revert';
1877 } elseif ( $reupload ) {
1878 $logAction = 'overwrite';
1879 } else {
1880 $logAction = 'upload';
1881 }
1882 // Add the log entry...
1883 $logEntry = new ManualLogEntry( 'upload', $logAction );
1884 $logEntry->setTimestamp( $this->timestamp );
1885 $logEntry->setPerformer( $performer->getUser() );
1886 $logEntry->setComment( $comment );
1887 $logEntry->setTarget( $descTitle );
1888 // Allow people using the api to associate log entries with the upload.
1889 // Log has a timestamp, but sometimes different from upload timestamp.
1890 $logEntry->setParameters(
1891 [
1892 'img_sha1' => $this->sha1,
1893 'img_timestamp' => $timestamp,
1894 ]
1895 );
1896 // Note we keep $logId around since during new image
1897 // creation, page doesn't exist yet, so log_page = 0
1898 // but we want it to point to the page we're making,
1899 // so we later modify the log entry.
1900 // For a similar reason, we avoid making an RC entry
1901 // now and wait until the page exists.
1902 $logId = $logEntry->insert();
1903
1904 if ( $descTitle->exists() ) {
1905 if ( $createNullRevision ) {
1906 $services = MediaWikiServices::getInstance();
1907 $revStore = $services->getRevisionStore();
1908 // Use own context to get the action text in content language
1909 $formatter = $services->getLogFormatterFactory()->newFromEntry( $logEntry );
1910 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1911 $editSummary = $formatter->getPlainActionText();
1912 $summary = CommentStoreComment::newUnsavedComment( $editSummary );
1913 $nullRevRecord = $revStore->newNullRevision(
1914 $dbw,
1915 $descTitle,
1916 $summary,
1917 false,
1918 $performer->getUser()
1919 );
1920
1921 if ( $nullRevRecord ) {
1922 $inserted = $revStore->insertRevisionOn( $nullRevRecord, $dbw );
1923
1924 $this->getHookRunner()->onRevisionFromEditComplete(
1925 $wikiPage,
1926 $inserted,
1927 $inserted->getParentId(),
1928 $performer->getUser(),
1929 $tags
1930 );
1931
1932 $wikiPage->updateRevisionOn( $dbw, $inserted );
1933 // Associate null revision id
1934 $logEntry->setAssociatedRevId( $inserted->getId() );
1935 }
1936 }
1937
1938 $newPageContent = null;
1939 } else {
1940 // Make the description page and RC log entry post-commit
1941 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1942 }
1943
1944 // NOTE: Even after ending this atomic section, we are probably still in the implicit
1945 // transaction started by any prior master query in the request. We cannot yet safely
1946 // schedule jobs, see T263301.
1947 $dbw->endAtomic( __METHOD__ );
1948 $fname = __METHOD__;
1949
1950 # Do some cache purges after final commit so that:
1951 # a) Changes are more likely to be seen post-purge
1952 # b) They won't cause rollback of the log publish/update above
1953 $purgeUpdate = new AutoCommitUpdate(
1954 $dbw,
1955 __METHOD__,
1956 function () use (
1957 $reupload, $wikiPage, $newPageContent, $comment, $performer,
1958 $logEntry, $logId, $descId, $tags, $fname
1959 ) {
1960 # Update memcache after the commit
1961 $this->invalidateCache();
1962
1963 $updateLogPage = false;
1964 if ( $newPageContent ) {
1965 # New file page; create the description page.
1966 # There's already a log entry, so don't make a second RC entry
1967 # CDN and file cache for the description page are purged by doUserEditContent.
1968 $status = $wikiPage->doUserEditContent(
1969 $newPageContent,
1970 $performer,
1971 $comment,
1972 EDIT_NEW | EDIT_SUPPRESS_RC
1973 );
1974
1975 $revRecord = $status->getNewRevision();
1976 if ( $revRecord ) {
1977 // Associate new page revision id
1978 $logEntry->setAssociatedRevId( $revRecord->getId() );
1979
1980 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1981 // which is triggered on $descTitle by doUserEditContent() above.
1982 $updateLogPage = $revRecord->getPageId();
1983 }
1984 } else {
1985 # Existing file page: invalidate description page cache
1986 $title = $wikiPage->getTitle();
1987 $title->invalidateCache();
1988 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
1989 $hcu->purgeTitleUrls( $title, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
1990 # Allow the new file version to be patrolled from the page footer
1991 Article::purgePatrolFooterCache( $descId );
1992 }
1993
1994 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1995 # but setAssociatedRevId() wasn't called at that point yet...
1996 $logParams = $logEntry->getParameters();
1997 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1998 $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1999 if ( $updateLogPage ) {
2000 # Also log page, in case where we just created it above
2001 $update['log_page'] = $updateLogPage;
2002 }
2003 $this->getRepo()->getPrimaryDB()->newUpdateQueryBuilder()
2004 ->update( 'logging' )
2005 ->set( $update )
2006 ->where( [ 'log_id' => $logId ] )
2007 ->caller( $fname )->execute();
2008
2009 $this->getRepo()->getPrimaryDB()->newInsertQueryBuilder()
2010 ->insertInto( 'log_search' )
2011 ->row( [
2012 'ls_field' => 'associated_rev_id',
2013 'ls_value' => (string)$logEntry->getAssociatedRevId(),
2014 'ls_log_id' => $logId,
2015 ] )
2016 ->caller( $fname )->execute();
2017
2018 # Add change tags, if any
2019 if ( $tags ) {
2020 $logEntry->addTags( $tags );
2021 }
2022
2023 # Uploads can be patrolled
2024 $logEntry->setIsPatrollable( true );
2025
2026 # Now that the log entry is up-to-date, make an RC entry.
2027 $logEntry->publish( $logId );
2028
2029 # Run hook for other updates (typically more cache purging)
2030 $this->getHookRunner()->onFileUpload( $this, $reupload, !$newPageContent );
2031
2032 if ( $reupload ) {
2033 # Delete old thumbnails
2034 $this->purgeThumbnails();
2035 # Remove the old file from the CDN cache
2036 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2037 $hcu->purgeUrls( $this->getUrl(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2038 } else {
2039 # Update backlink pages pointing to this title if created
2040 $blcFactory = MediaWikiServices::getInstance()->getBacklinkCacheFactory();
2041 LinksUpdate::queueRecursiveJobsForTable(
2042 $this->getTitle(),
2043 'imagelinks',
2044 'upload-image',
2045 $performer->getUser()->getName(),
2046 $blcFactory->getBacklinkCache( $this->getTitle() )
2047 );
2048 }
2049
2050 $this->prerenderThumbnails();
2051 }
2052 );
2053
2054 # Invalidate cache for all pages using this file
2055 $cacheUpdateJob = HTMLCacheUpdateJob::newForBacklinks(
2056 $this->getTitle(),
2057 'imagelinks',
2058 [ 'causeAction' => 'file-upload', 'causeAgent' => $performer->getUser()->getName() ]
2059 );
2060
2061 // NOTE: We are probably still in the implicit transaction started by DBO_TRX. We should
2062 // only schedule jobs after that transaction was committed, so a job queue failure
2063 // doesn't cause the upload to fail (T263301). Also, we should generally not schedule any
2064 // Jobs or the DeferredUpdates that assume the update is complete until after the
2065 // transaction has been committed and we are sure that the upload was indeed successful.
2066 $dbw->onTransactionCommitOrIdle( static function () use ( $reupload, $purgeUpdate, $cacheUpdateJob ) {
2067 DeferredUpdates::addUpdate( $purgeUpdate, DeferredUpdates::PRESEND );
2068
2069 if ( !$reupload ) {
2070 // This is a new file, so update the image count
2071 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2072 }
2073
2074 MediaWikiServices::getInstance()->getJobQueueGroup()->lazyPush( $cacheUpdateJob );
2075 }, __METHOD__ );
2076
2077 return Status::newGood();
2078 }
2079
2080 /**
2081 * Move or copy a file to its public location. If a file exists at the
2082 * destination, move it to an archive. Returns a Status object with
2083 * the archive name in the "value" member on success.
2084 *
2085 * The archive name should be passed through to recordUpload for database
2086 * registration.
2087 *
2088 * @stable to override
2089 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
2090 * @param int $flags A bitwise combination of:
2091 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
2092 * @param array $options Optional additional parameters
2093 * @return Status On success, the value member contains the
2094 * archive name, or an empty string if it was a new file.
2095 */
2096 public function publish( $src, $flags = 0, array $options = [] ) {
2097 return $this->publishTo( $src, $this->getRel(), $flags, $options );
2098 }
2099
2100 /**
2101 * Move or copy a file to a specified location. Returns a Status
2102 * object with the archive name in the "value" member on success.
2103 *
2104 * The archive name should be passed through to recordUpload for database
2105 * registration.
2106 *
2107 * @stable to override
2108 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
2109 * @param string $dstRel Target relative path
2110 * @param int $flags A bitwise combination of:
2111 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
2112 * @param array $options Optional additional parameters
2113 * @return Status On success, the value member contains the
2114 * archive name, or an empty string if it was a new file.
2115 */
2116 protected function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
2117 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
2118
2119 $repo = $this->getRepo();
2120 if ( $repo->getReadOnlyReason() !== false ) {
2121 return $this->readOnlyFatalStatus();
2122 }
2123
2124 $status = $this->acquireFileLock();
2125 if ( !$status->isOK() ) {
2126 return $status;
2127 }
2128
2129 if ( $this->isOld() ) {
2130 $archiveRel = $dstRel;
2131 $archiveName = basename( $archiveRel );
2132 } else {
2133 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
2134 $archiveRel = $this->getArchiveRel( $archiveName );
2135 }
2136
2137 if ( $repo->hasSha1Storage() ) {
2138 $sha1 = FileRepo::isVirtualUrl( $srcPath )
2139 ? $repo->getFileSha1( $srcPath )
2140 : FSFile::getSha1Base36FromPath( $srcPath );
2141 /** @var FileBackendDBRepoWrapper $wrapperBackend */
2142 $wrapperBackend = $repo->getBackend();
2143 '@phan-var FileBackendDBRepoWrapper $wrapperBackend';
2144 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
2145 $status = $repo->quickImport( $src, $dst );
2146 if ( $flags & File::DELETE_SOURCE ) {
2147 unlink( $srcPath );
2148 }
2149
2150 if ( $this->exists() ) {
2151 $status->value = $archiveName;
2152 }
2153 } else {
2154 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
2155 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
2156
2157 if ( $status->value == 'new' ) {
2158 $status->value = '';
2159 } else {
2160 $status->value = $archiveName;
2161 }
2162 }
2163
2164 $this->releaseFileLock();
2165 return $status;
2166 }
2167
2168 /** getLinksTo inherited */
2169 /** getExifData inherited */
2170 /** isLocal inherited */
2171 /** wasDeleted inherited */
2172
2173 /**
2174 * Move file to the new title
2175 *
2176 * Move current, old version and all thumbnails
2177 * to the new filename. Old file is deleted.
2178 *
2179 * Cache purging is done; checks for validity
2180 * and logging are caller's responsibility
2181 *
2182 * @stable to override
2183 * @param Title $target New file name
2184 * @return Status
2185 */
2186 public function move( $target ) {
2187 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2188 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2189 return $this->readOnlyFatalStatus();
2190 }
2191
2192 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
2193 $batch = new LocalFileMoveBatch( $this, $target );
2194
2195 $status = $batch->addCurrent();
2196 if ( !$status->isOK() ) {
2197 return $status;
2198 }
2199 $archiveNames = $batch->addOlds();
2200 $status = $batch->execute();
2201
2202 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
2203
2204 // Purge the source and target files outside the transaction...
2205 $oldTitleFile = $localRepo->newFile( $this->title );
2206 $newTitleFile = $localRepo->newFile( $target );
2207 DeferredUpdates::addUpdate(
2208 new AutoCommitUpdate(
2209 $this->getRepo()->getPrimaryDB(),
2210 __METHOD__,
2211 static function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
2212 $oldTitleFile->purgeEverything();
2213 foreach ( $archiveNames as $archiveName ) {
2214 /** @var OldLocalFile $oldTitleFile */
2215 '@phan-var OldLocalFile $oldTitleFile';
2216 $oldTitleFile->purgeOldThumbnails( $archiveName );
2217 }
2218 $newTitleFile->purgeEverything();
2219 }
2220 ),
2221 DeferredUpdates::PRESEND
2222 );
2223
2224 if ( $status->isOK() ) {
2225 // Now switch the object
2226 $this->title = $target;
2227 // Force regeneration of the name and hashpath
2228 $this->name = null;
2229 $this->hashPath = null;
2230 }
2231
2232 return $status;
2233 }
2234
2235 /**
2236 * Delete all versions of the file.
2237 *
2238 * @since 1.35
2239 *
2240 * Moves the files into an archive directory (or deletes them)
2241 * and removes the database rows.
2242 *
2243 * Cache purging is done; logging is caller's responsibility.
2244 * @stable to override
2245 *
2246 * @param string $reason
2247 * @param UserIdentity $user
2248 * @param bool $suppress
2249 * @return Status
2250 */
2251 public function deleteFile( $reason, UserIdentity $user, $suppress = false ) {
2252 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2253 return $this->readOnlyFatalStatus();
2254 }
2255
2256 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2257
2258 $batch->addCurrent();
2259 // Get old version relative paths
2260 $archiveNames = $batch->addOlds();
2261 $status = $batch->execute();
2262
2263 if ( $status->isOK() ) {
2264 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
2265 }
2266
2267 // To avoid slow purges in the transaction, move them outside...
2268 DeferredUpdates::addUpdate(
2269 new AutoCommitUpdate(
2270 $this->getRepo()->getPrimaryDB(),
2271 __METHOD__,
2272 function () use ( $archiveNames ) {
2273 $this->purgeEverything();
2274 foreach ( $archiveNames as $archiveName ) {
2275 $this->purgeOldThumbnails( $archiveName );
2276 }
2277 }
2278 ),
2279 DeferredUpdates::PRESEND
2280 );
2281
2282 // Purge the CDN
2283 $purgeUrls = [];
2284 foreach ( $archiveNames as $archiveName ) {
2285 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2286 }
2287
2288 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2289 $hcu->purgeUrls( $purgeUrls, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2290
2291 return $status;
2292 }
2293
2294 /**
2295 * Delete an old version of the file.
2296 *
2297 * @since 1.35
2298 * @stable to override
2299 *
2300 * Moves the file into an archive directory (or deletes it)
2301 * and removes the database row.
2302 *
2303 * Cache purging is done; logging is caller's responsibility.
2304 *
2305 * @param string $archiveName
2306 * @param string $reason
2307 * @param UserIdentity $user
2308 * @param bool $suppress
2309 * @return Status
2310 */
2311 public function deleteOldFile( $archiveName, $reason, UserIdentity $user, $suppress = false ) {
2312 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2313 return $this->readOnlyFatalStatus();
2314 }
2315
2316 $batch = new LocalFileDeleteBatch( $this, $user, $reason, $suppress );
2317
2318 $batch->addOld( $archiveName );
2319 $status = $batch->execute();
2320
2321 $this->purgeOldThumbnails( $archiveName );
2322 if ( $status->isOK() ) {
2323 $this->purgeDescription();
2324 }
2325
2326 $url = $this->getArchiveUrl( $archiveName );
2327 $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
2328 $hcu->purgeUrls( $url, $hcu::PURGE_INTENT_TXROUND_REFLECTED );
2329
2330 return $status;
2331 }
2332
2333 /**
2334 * Restore all or specified deleted revisions to the given file.
2335 * Permissions and logging are left to the caller.
2336 *
2337 * May throw database exceptions on error.
2338 * @stable to override
2339 *
2340 * @param int[] $versions Set of record ids of deleted items to restore,
2341 * or empty to restore all revisions.
2342 * @param bool $unsuppress
2343 * @return Status
2344 */
2345 public function restore( $versions = [], $unsuppress = false ) {
2346 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2347 return $this->readOnlyFatalStatus();
2348 }
2349
2350 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2351
2352 if ( !$versions ) {
2353 $batch->addAll();
2354 } else {
2355 $batch->addIds( $versions );
2356 }
2357 $status = $batch->execute();
2358 if ( $status->isGood() ) {
2359 $cleanupStatus = $batch->cleanup();
2360 $cleanupStatus->successCount = 0;
2361 $cleanupStatus->failCount = 0;
2362 $status->merge( $cleanupStatus );
2363 }
2364
2365 return $status;
2366 }
2367
2368 /** isMultipage inherited */
2369 /** pageCount inherited */
2370 /** scaleHeight inherited */
2371 /** getImageSize inherited */
2372
2373 /**
2374 * Get the URL of the file description page.
2375 * @stable to override
2376 * @return string|false
2377 */
2378 public function getDescriptionUrl() {
2379 // Avoid hard failure when the file does not exist. T221812
2380 return $this->title ? $this->title->getLocalURL() : false;
2381 }
2382
2383 /**
2384 * Get the HTML text of the description page
2385 * This is not used by ImagePage for local files, since (among other things)
2386 * it skips the parser cache.
2387 * @stable to override
2388 *
2389 * @param Language|null $lang What language to get description in (Optional)
2390 * @return string|false
2391 */
2392 public function getDescriptionText( ?Language $lang = null ) {
2393 if ( !$this->title ) {
2394 return false; // Avoid hard failure when the file does not exist. T221812
2395 }
2396
2397 $services = MediaWikiServices::getInstance();
2398 $page = $services->getPageStore()->getPageByReference( $this->getTitle() );
2399 if ( !$page ) {
2400 return false;
2401 }
2402
2403 if ( $lang ) {
2404 $parserOptions = ParserOptions::newFromUserAndLang(
2405 RequestContext::getMain()->getUser(),
2406 $lang
2407 );
2408 } else {
2409 $parserOptions = ParserOptions::newFromContext( RequestContext::getMain() );
2410 }
2411
2412 $parseStatus = $services->getParserOutputAccess()
2413 ->getParserOutput( $page, $parserOptions );
2414
2415 if ( !$parseStatus->isGood() ) {
2416 // Rendering failed.
2417 return false;
2418 }
2419 return $parseStatus->getValue()->getText();
2420 }
2421
2422 /**
2423 * @since 1.37
2424 * @stable to override
2425 * @param int $audience
2426 * @param Authority|null $performer
2427 * @return UserIdentity|null
2428 */
2429 public function getUploader( int $audience = self::FOR_PUBLIC, ?Authority $performer = null ): ?UserIdentity {
2430 $this->load();
2431 if ( $audience === self::FOR_PUBLIC && $this->isDeleted( self::DELETED_USER ) ) {
2432 return null;
2433 } elseif ( $audience === self::FOR_THIS_USER && !$this->userCan( self::DELETED_USER, $performer ) ) {
2434 return null;
2435 } else {
2436 return $this->user;
2437 }
2438 }
2439
2440 /**
2441 * @stable to override
2442 * @param int $audience
2443 * @param Authority|null $performer
2444 * @return string
2445 */
2446 public function getDescription( $audience = self::FOR_PUBLIC, ?Authority $performer = null ) {
2447 $this->load();
2448 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2449 return '';
2450 } elseif ( $audience == self::FOR_THIS_USER && !$this->userCan( self::DELETED_COMMENT, $performer ) ) {
2451 return '';
2452 } else {
2453 return $this->description;
2454 }
2455 }
2456
2457 /**
2458 * @stable to override
2459 * @return string|false TS_MW timestamp, a string with 14 digits
2460 */
2461 public function getTimestamp() {
2462 $this->load();
2463
2464 return $this->timestamp;
2465 }
2466
2467 /**
2468 * @stable to override
2469 * @return string|false
2470 */
2471 public function getDescriptionTouched() {
2472 if ( !$this->exists() ) {
2473 return false; // Avoid hard failure when the file does not exist. T221812
2474 }
2475
2476 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2477 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2478 // need to differentiate between null (uninitialized) and false (failed to load).
2479 if ( $this->descriptionTouched === null ) {
2480 $touched = $this->repo->getReplicaDB()->newSelectQueryBuilder()
2481 ->select( 'page_touched' )
2482 ->from( 'page' )
2483 ->where( [ 'page_namespace' => $this->title->getNamespace() ] )
2484 ->andWhere( [ 'page_title' => $this->title->getDBkey() ] )
2485 ->caller( __METHOD__ )->fetchField();
2486 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2487 }
2488
2489 return $this->descriptionTouched;
2490 }
2491
2492 /**
2493 * @stable to override
2494 * @return string|false
2495 */
2496 public function getSha1() {
2497 $this->load();
2498 return $this->sha1;
2499 }
2500
2501 /**
2502 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2503 */
2504 public function isCacheable() {
2505 $this->load();
2506
2507 // If extra data (metadata) was not loaded then it must have been large
2508 return $this->extraDataLoaded
2509 && strlen( serialize( $this->metadataArray ) ) <= self::CACHE_FIELD_MAX_LEN;
2510 }
2511
2512 /**
2513 * Acquire an exclusive lock on the file, indicating an intention to write
2514 * to the file backend.
2515 *
2516 * @param float|int $timeout The timeout in seconds
2517 * @return Status
2518 * @since 1.28
2519 */
2520 public function acquireFileLock( $timeout = 0 ) {
2521 return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2522 [ $this->getPath() ], LockManager::LOCK_EX, $timeout
2523 ) );
2524 }
2525
2526 /**
2527 * Release a lock acquired with acquireFileLock().
2528 *
2529 * @return Status
2530 * @since 1.28
2531 */
2532 public function releaseFileLock() {
2533 return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2534 [ $this->getPath() ], LockManager::LOCK_EX
2535 ) );
2536 }
2537
2538 /**
2539 * Start an atomic DB section and lock the image for update
2540 * or increments a reference counter if the lock is already held
2541 *
2542 * This method should not be used outside of LocalFile/LocalFile*Batch
2543 *
2544 * @deprecated since 1.38 Use acquireFileLock()
2545 * @throws LocalFileLockError Throws an error if the lock was not acquired
2546 * @return bool Whether the file lock owns/spawned the DB transaction
2547 */
2548 public function lock() {
2549 if ( !$this->locked ) {
2550 $logger = LoggerFactory::getInstance( 'LocalFile' );
2551
2552 $dbw = $this->repo->getPrimaryDB();
2553 $makesTransaction = !$dbw->trxLevel();
2554 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2555 // T56736: use simple lock to handle when the file does not exist.
2556 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2557 // Also, that would cause contention on INSERT of similarly named rows.
2558 $status = $this->acquireFileLock( 10 ); // represents all versions of the file
2559 if ( !$status->isGood() ) {
2560 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2561 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2562
2563 throw new LocalFileLockError( $status );
2564 }
2565 // Release the lock *after* commit to avoid row-level contention.
2566 // Make sure it triggers on rollback() as well as commit() (T132921).
2567 $dbw->onTransactionResolution(
2568 function () use ( $logger ) {
2569 $status = $this->releaseFileLock();
2570 if ( !$status->isGood() ) {
2571 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2572 }
2573 },
2574 __METHOD__
2575 );
2576 // Callers might care if the SELECT snapshot is safely fresh
2577 $this->lockedOwnTrx = $makesTransaction;
2578 }
2579
2580 $this->locked++;
2581
2582 return $this->lockedOwnTrx;
2583 }
2584
2585 /**
2586 * Decrement the lock reference count and end the atomic section if it reaches zero
2587 *
2588 * This method should not be used outside of LocalFile/LocalFile*Batch
2589 *
2590 * The commit and lock release will happen when no atomic sections are active, which
2591 * may happen immediately or at some point after calling this
2592 *
2593 * @deprecated since 1.38 Use releaseFileLock()
2594 */
2595 public function unlock() {
2596 if ( $this->locked ) {
2597 --$this->locked;
2598 if ( !$this->locked ) {
2599 $dbw = $this->repo->getPrimaryDB();
2600 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2601 $this->lockedOwnTrx = false;
2602 }
2603 }
2604 }
2605
2606 /**
2607 * @return Status
2608 */
2609 protected function readOnlyFatalStatus() {
2610 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2611 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2612 }
2613
2614 /**
2615 * Clean up any dangling locks
2616 */
2617 public function __destruct() {
2618 $this->unlock();
2619 }
2620 }