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