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