Unsuppress phan issues part 6
[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 // @phan-suppress-next-line PhanTypeInvalidDimOffset
1096 if ( !empty( $options['forThumbRefresh'] ) ) {
1097 $handler = $this->getHandler();
1098 if ( $handler ) {
1099 $handler->filterThumbnailPurgeList( $files, $options );
1100 }
1101 }
1102
1103 // Purge any custom thumbnail caches
1104 Hooks::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1105
1106 // Delete thumbnails
1107 $dir = array_shift( $files );
1108 $this->purgeThumbList( $dir, $files );
1109
1110 // Purge the CDN
1111 DeferredUpdates::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates::PRESEND );
1112 }
1113
1114 /**
1115 * Prerenders a configurable set of thumbnails
1116 *
1117 * @since 1.28
1118 */
1119 public function prerenderThumbnails() {
1120 global $wgUploadThumbnailRenderMap;
1121
1122 $jobs = [];
1123
1124 $sizes = $wgUploadThumbnailRenderMap;
1125 rsort( $sizes );
1126
1127 foreach ( $sizes as $size ) {
1128 if ( $this->isVectorized() || $this->getWidth() > $size ) {
1129 $jobs[] = new ThumbnailRenderJob(
1130 $this->getTitle(),
1131 [ 'transformParams' => [ 'width' => $size ] ]
1132 );
1133 }
1134 }
1135
1136 if ( $jobs ) {
1137 JobQueueGroup::singleton()->lazyPush( $jobs );
1138 }
1139 }
1140
1141 /**
1142 * Delete a list of thumbnails visible at urls
1143 * @param string $dir Base dir of the files.
1144 * @param array $files Array of strings: relative filenames (to $dir)
1145 */
1146 protected function purgeThumbList( $dir, $files ) {
1147 $fileListDebug = strtr(
1148 var_export( $files, true ),
1149 [ "\n" => '' ]
1150 );
1151 wfDebug( __METHOD__ . ": $fileListDebug\n" );
1152
1153 $purgeList = [];
1154 foreach ( $files as $file ) {
1155 if ( $this->repo->supportsSha1URLs() ) {
1156 $reference = $this->getSha1();
1157 } else {
1158 $reference = $this->getName();
1159 }
1160
1161 # Check that the reference (filename or sha1) is part of the thumb name
1162 # This is a basic sanity check to avoid erasing unrelated directories
1163 if ( strpos( $file, $reference ) !== false
1164 || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1165 ) {
1166 $purgeList[] = "{$dir}/{$file}";
1167 }
1168 }
1169
1170 # Delete the thumbnails
1171 $this->repo->quickPurgeBatch( $purgeList );
1172 # Clear out the thumbnail directory if empty
1173 $this->repo->quickCleanDir( $dir );
1174 }
1175
1176 /** purgeDescription inherited */
1177 /** purgeEverything inherited */
1178
1179 /**
1180 * @param int|null $limit Optional: Limit to number of results
1181 * @param string|int|null $start Optional: Timestamp, start from
1182 * @param string|int|null $end Optional: Timestamp, end at
1183 * @param bool $inc
1184 * @return OldLocalFile[]
1185 */
1186 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1187 $dbr = $this->repo->getReplicaDB();
1188 $oldFileQuery = OldLocalFile::getQueryInfo();
1189
1190 $tables = $oldFileQuery['tables'];
1191 $fields = $oldFileQuery['fields'];
1192 $join_conds = $oldFileQuery['joins'];
1193 $conds = $opts = [];
1194 $eq = $inc ? '=' : '';
1195 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1196
1197 if ( $start ) {
1198 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1199 }
1200
1201 if ( $end ) {
1202 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1203 }
1204
1205 if ( $limit ) {
1206 $opts['LIMIT'] = $limit;
1207 }
1208
1209 // Search backwards for time > x queries
1210 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1211 $opts['ORDER BY'] = "oi_timestamp $order";
1212 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1213
1214 // Avoid PHP 7.1 warning from passing $this by reference
1215 $localFile = $this;
1216 Hooks::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1217 &$conds, &$opts, &$join_conds ] );
1218
1219 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1220 $r = [];
1221
1222 foreach ( $res as $row ) {
1223 $r[] = $this->repo->newFileFromRow( $row );
1224 }
1225
1226 if ( $order == 'ASC' ) {
1227 $r = array_reverse( $r ); // make sure it ends up descending
1228 }
1229
1230 return $r;
1231 }
1232
1233 /**
1234 * Returns the history of this file, line by line.
1235 * starts with current version, then old versions.
1236 * uses $this->historyLine to check which line to return:
1237 * 0 return line for current version
1238 * 1 query for old versions, return first one
1239 * 2, ... return next old version from above query
1240 * @return bool
1241 */
1242 public function nextHistoryLine() {
1243 # Polymorphic function name to distinguish foreign and local fetches
1244 $fname = static::class . '::' . __FUNCTION__;
1245
1246 $dbr = $this->repo->getReplicaDB();
1247
1248 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1249 $fileQuery = self::getQueryInfo();
1250 $this->historyRes = $dbr->select( $fileQuery['tables'],
1251 $fileQuery['fields'] + [
1252 'oi_archive_name' => $dbr->addQuotes( '' ),
1253 'oi_deleted' => 0,
1254 ],
1255 [ 'img_name' => $this->title->getDBkey() ],
1256 $fname,
1257 [],
1258 $fileQuery['joins']
1259 );
1260
1261 if ( $dbr->numRows( $this->historyRes ) == 0 ) {
1262 $this->historyRes = null;
1263
1264 return false;
1265 }
1266 } elseif ( $this->historyLine == 1 ) {
1267 $fileQuery = OldLocalFile::getQueryInfo();
1268 $this->historyRes = $dbr->select(
1269 $fileQuery['tables'],
1270 $fileQuery['fields'],
1271 [ 'oi_name' => $this->title->getDBkey() ],
1272 $fname,
1273 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1274 $fileQuery['joins']
1275 );
1276 }
1277 $this->historyLine++;
1278
1279 return $dbr->fetchObject( $this->historyRes );
1280 }
1281
1282 /**
1283 * Reset the history pointer to the first element of the history
1284 */
1285 public function resetHistory() {
1286 $this->historyLine = 0;
1287
1288 if ( !is_null( $this->historyRes ) ) {
1289 $this->historyRes = null;
1290 }
1291 }
1292
1293 /** getHashPath inherited */
1294 /** getRel inherited */
1295 /** getUrlRel inherited */
1296 /** getArchiveRel inherited */
1297 /** getArchivePath inherited */
1298 /** getThumbPath inherited */
1299 /** getArchiveUrl inherited */
1300 /** getThumbUrl inherited */
1301 /** getArchiveVirtualUrl inherited */
1302 /** getThumbVirtualUrl inherited */
1303 /** isHashed inherited */
1304
1305 /**
1306 * Upload a file and record it in the DB
1307 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1308 * @param string $comment Upload description
1309 * @param string $pageText Text to use for the new description page,
1310 * if a new description page is created
1311 * @param int|bool $flags Flags for publish()
1312 * @param array|bool $props File properties, if known. This can be used to
1313 * reduce the upload time when uploading virtual URLs for which the file
1314 * info is already known
1315 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1316 * current time
1317 * @param User|null $user User object or null to use $wgUser
1318 * @param string[] $tags Change tags to add to the log entry and page revision.
1319 * (This doesn't check $user's permissions.)
1320 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1321 * upload, see T193621
1322 * @param bool $revert If this file upload is a revert
1323 * @return Status On success, the value member contains the
1324 * archive name, or an empty string if it was a new file.
1325 */
1326 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1327 $timestamp = false, $user = null, $tags = [],
1328 $createNullRevision = true, $revert = false
1329 ) {
1330 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1331 return $this->readOnlyFatalStatus();
1332 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1333 // Check this in advance to avoid writing to FileBackend and the file tables,
1334 // only to fail on insert the revision due to the text store being unavailable.
1335 return $this->readOnlyFatalStatus();
1336 }
1337
1338 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1339 if ( !$props ) {
1340 if ( FileRepo::isVirtualUrl( $srcPath )
1341 || FileBackend::isStoragePath( $srcPath )
1342 ) {
1343 $props = $this->repo->getFileProps( $srcPath );
1344 } else {
1345 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1346 $props = $mwProps->getPropsFromPath( $srcPath, true );
1347 }
1348 }
1349
1350 $options = [];
1351 $handler = MediaHandler::getHandler( $props['mime'] );
1352 if ( $handler ) {
1353 $metadata = AtEase::quietCall( 'unserialize', $props['metadata'] );
1354
1355 if ( !is_array( $metadata ) ) {
1356 $metadata = [];
1357 }
1358
1359 $options['headers'] = $handler->getContentHeaders( $metadata );
1360 } else {
1361 $options['headers'] = [];
1362 }
1363
1364 // Trim spaces on user supplied text
1365 $comment = trim( $comment );
1366
1367 $this->lock();
1368 $status = $this->publish( $src, $flags, $options );
1369
1370 if ( $status->successCount >= 2 ) {
1371 // There will be a copy+(one of move,copy,store).
1372 // The first succeeding does not commit us to updating the DB
1373 // since it simply copied the current version to a timestamped file name.
1374 // It is only *preferable* to avoid leaving such files orphaned.
1375 // Once the second operation goes through, then the current version was
1376 // updated and we must therefore update the DB too.
1377 $oldver = $status->value;
1378 $uploadStatus = $this->recordUpload2(
1379 $oldver,
1380 $comment,
1381 $pageText,
1382 $props,
1383 $timestamp,
1384 $user,
1385 $tags,
1386 $createNullRevision,
1387 $revert
1388 );
1389 if ( !$uploadStatus->isOK() ) {
1390 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1391 // update filenotfound error with more specific path
1392 $status->fatal( 'filenotfound', $srcPath );
1393 } else {
1394 $status->merge( $uploadStatus );
1395 }
1396 }
1397 }
1398
1399 $this->unlock();
1400 return $status;
1401 }
1402
1403 /**
1404 * Record a file upload in the upload log and the image table
1405 * @param string $oldver
1406 * @param string $desc
1407 * @param string $license
1408 * @param string $copyStatus
1409 * @param string $source
1410 * @param bool $watch
1411 * @param string|bool $timestamp
1412 * @param User|null $user User object or null to use $wgUser
1413 * @return bool
1414 */
1415 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1416 $watch = false, $timestamp = false, User $user = null ) {
1417 if ( !$user ) {
1418 global $wgUser;
1419 $user = $wgUser;
1420 }
1421
1422 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1423
1424 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1425 return false;
1426 }
1427
1428 if ( $watch ) {
1429 $user->addWatch( $this->getTitle() );
1430 }
1431
1432 return true;
1433 }
1434
1435 /**
1436 * Record a file upload in the upload log and the image table
1437 * @param string $oldver
1438 * @param string $comment
1439 * @param string $pageText
1440 * @param bool|array $props
1441 * @param string|bool $timestamp
1442 * @param null|User $user
1443 * @param string[] $tags
1444 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1445 * upload, see T193621
1446 * @param bool $revert If this file upload is a revert
1447 * @return Status
1448 */
1449 function recordUpload2(
1450 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1451 $createNullRevision = true, $revert = false
1452 ) {
1453 global $wgActorTableSchemaMigrationStage;
1454
1455 if ( is_null( $user ) ) {
1456 global $wgUser;
1457 $user = $wgUser;
1458 }
1459
1460 $dbw = $this->repo->getMasterDB();
1461
1462 # Imports or such might force a certain timestamp; otherwise we generate
1463 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1464 if ( $timestamp === false ) {
1465 $timestamp = $dbw->timestamp();
1466 $allowTimeKludge = true;
1467 } else {
1468 $allowTimeKludge = false;
1469 }
1470
1471 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1472 $props['description'] = $comment;
1473 $props['user'] = $user->getId();
1474 $props['user_text'] = $user->getName();
1475 $props['actor'] = $user->getActorId( $dbw );
1476 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1477 $this->setProps( $props );
1478
1479 # Fail now if the file isn't there
1480 if ( !$this->fileExists ) {
1481 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
1482
1483 return Status::newFatal( 'filenotfound', $this->getRel() );
1484 }
1485
1486 $dbw->startAtomic( __METHOD__ );
1487
1488 # Test to see if the row exists using INSERT IGNORE
1489 # This avoids race conditions by locking the row until the commit, and also
1490 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1491 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1492 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1493 $actorMigration = ActorMigration::newMigration();
1494 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1495 $dbw->insert( 'image',
1496 [
1497 'img_name' => $this->getName(),
1498 'img_size' => $this->size,
1499 'img_width' => intval( $this->width ),
1500 'img_height' => intval( $this->height ),
1501 'img_bits' => $this->bits,
1502 'img_media_type' => $this->media_type,
1503 'img_major_mime' => $this->major_mime,
1504 'img_minor_mime' => $this->minor_mime,
1505 'img_timestamp' => $timestamp,
1506 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1507 'img_sha1' => $this->sha1
1508 ] + $commentFields + $actorFields,
1509 __METHOD__,
1510 [ 'IGNORE' ]
1511 );
1512 $reupload = ( $dbw->affectedRows() == 0 );
1513
1514 if ( $reupload ) {
1515 $row = $dbw->selectRow(
1516 'image',
1517 [ 'img_timestamp', 'img_sha1' ],
1518 [ 'img_name' => $this->getName() ],
1519 __METHOD__,
1520 [ 'LOCK IN SHARE MODE' ]
1521 );
1522
1523 if ( $row && $row->img_sha1 === $this->sha1 ) {
1524 $dbw->endAtomic( __METHOD__ );
1525 wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!\n" );
1526 $title = Title::newFromText( $this->getName(), NS_FILE );
1527 return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1528 }
1529
1530 if ( $allowTimeKludge ) {
1531 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1532 $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1533 # Avoid a timestamp that is not newer than the last version
1534 # TODO: the image/oldimage tables should be like page/revision with an ID field
1535 if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1536 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1537 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1538 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1539 }
1540 }
1541
1542 $tables = [ 'image' ];
1543 $fields = [
1544 'oi_name' => 'img_name',
1545 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1546 'oi_size' => 'img_size',
1547 'oi_width' => 'img_width',
1548 'oi_height' => 'img_height',
1549 'oi_bits' => 'img_bits',
1550 'oi_description_id' => 'img_description_id',
1551 'oi_timestamp' => 'img_timestamp',
1552 'oi_metadata' => 'img_metadata',
1553 'oi_media_type' => 'img_media_type',
1554 'oi_major_mime' => 'img_major_mime',
1555 'oi_minor_mime' => 'img_minor_mime',
1556 'oi_sha1' => 'img_sha1',
1557 ];
1558 $joins = [];
1559
1560 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
1561 $fields['oi_user'] = 'img_user';
1562 $fields['oi_user_text'] = 'img_user_text';
1563 }
1564 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
1565 $fields['oi_actor'] = 'img_actor';
1566 }
1567
1568 if (
1569 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH ) === SCHEMA_COMPAT_WRITE_BOTH
1570 ) {
1571 // Upgrade any rows that are still old-style. Otherwise an upgrade
1572 // might be missed if a deletion happens while the migration script
1573 // is running.
1574 $res = $dbw->select(
1575 [ 'image' ],
1576 [ 'img_name', 'img_user', 'img_user_text' ],
1577 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1578 __METHOD__
1579 );
1580 foreach ( $res as $row ) {
1581 $actorId = User::newFromAnyId( $row->img_user, $row->img_user_text, null )->getActorId( $dbw );
1582 $dbw->update(
1583 'image',
1584 [ 'img_actor' => $actorId ],
1585 [ 'img_name' => $row->img_name, 'img_actor' => 0 ],
1586 __METHOD__
1587 );
1588 }
1589 }
1590
1591 # (T36993) Note: $oldver can be empty here, if the previous
1592 # version of the file was broken. Allow registration of the new
1593 # version to continue anyway, because that's better than having
1594 # an image that's not fixable by user operations.
1595 # Collision, this is an update of a file
1596 # Insert previous contents into oldimage
1597 $dbw->insertSelect( 'oldimage', $tables, $fields,
1598 [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1599
1600 # Update the current image row
1601 $dbw->update( 'image',
1602 [
1603 'img_size' => $this->size,
1604 'img_width' => intval( $this->width ),
1605 'img_height' => intval( $this->height ),
1606 'img_bits' => $this->bits,
1607 'img_media_type' => $this->media_type,
1608 'img_major_mime' => $this->major_mime,
1609 'img_minor_mime' => $this->minor_mime,
1610 'img_timestamp' => $timestamp,
1611 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1612 'img_sha1' => $this->sha1
1613 ] + $commentFields + $actorFields,
1614 [ 'img_name' => $this->getName() ],
1615 __METHOD__
1616 );
1617 }
1618
1619 $descTitle = $this->getTitle();
1620 $descId = $descTitle->getArticleID();
1621 $wikiPage = new WikiFilePage( $descTitle );
1622 $wikiPage->setFile( $this );
1623
1624 // Determine log action. If reupload is done by reverting, use a special log_action.
1625 if ( $revert === true ) {
1626 $logAction = 'revert';
1627 } elseif ( $reupload === true ) {
1628 $logAction = 'overwrite';
1629 } else {
1630 $logAction = 'upload';
1631 }
1632 // Add the log entry...
1633 $logEntry = new ManualLogEntry( 'upload', $logAction );
1634 $logEntry->setTimestamp( $this->timestamp );
1635 $logEntry->setPerformer( $user );
1636 $logEntry->setComment( $comment );
1637 $logEntry->setTarget( $descTitle );
1638 // Allow people using the api to associate log entries with the upload.
1639 // Log has a timestamp, but sometimes different from upload timestamp.
1640 $logEntry->setParameters(
1641 [
1642 'img_sha1' => $this->sha1,
1643 'img_timestamp' => $timestamp,
1644 ]
1645 );
1646 // Note we keep $logId around since during new image
1647 // creation, page doesn't exist yet, so log_page = 0
1648 // but we want it to point to the page we're making,
1649 // so we later modify the log entry.
1650 // For a similar reason, we avoid making an RC entry
1651 // now and wait until the page exists.
1652 $logId = $logEntry->insert();
1653
1654 if ( $descTitle->exists() ) {
1655 // Use own context to get the action text in content language
1656 $formatter = LogFormatter::newFromEntry( $logEntry );
1657 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1658 $editSummary = $formatter->getPlainActionText();
1659
1660 $nullRevision = $createNullRevision === false ? null : Revision::newNullRevision(
1661 $dbw,
1662 $descId,
1663 $editSummary,
1664 false,
1665 $user
1666 );
1667 if ( $nullRevision ) {
1668 $nullRevision->insertOn( $dbw );
1669 Hooks::run(
1670 'NewRevisionFromEditComplete',
1671 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1672 );
1673 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1674 // Associate null revision id
1675 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1676 }
1677
1678 $newPageContent = null;
1679 } else {
1680 // Make the description page and RC log entry post-commit
1681 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1682 }
1683
1684 # Defer purges, page creation, and link updates in case they error out.
1685 # The most important thing is that files and the DB registry stay synced.
1686 $dbw->endAtomic( __METHOD__ );
1687 $fname = __METHOD__;
1688
1689 # Do some cache purges after final commit so that:
1690 # a) Changes are more likely to be seen post-purge
1691 # b) They won't cause rollback of the log publish/update above
1692 DeferredUpdates::addUpdate(
1693 new AutoCommitUpdate(
1694 $dbw,
1695 __METHOD__,
1696 function () use (
1697 $reupload, $wikiPage, $newPageContent, $comment, $user,
1698 $logEntry, $logId, $descId, $tags, $fname
1699 ) {
1700 # Update memcache after the commit
1701 $this->invalidateCache();
1702
1703 $updateLogPage = false;
1704 if ( $newPageContent ) {
1705 # New file page; create the description page.
1706 # There's already a log entry, so don't make a second RC entry
1707 # CDN and file cache for the description page are purged by doEditContent.
1708 $status = $wikiPage->doEditContent(
1709 $newPageContent,
1710 $comment,
1711 EDIT_NEW | EDIT_SUPPRESS_RC,
1712 false,
1713 $user
1714 );
1715
1716 if ( isset( $status->value['revision'] ) ) {
1717 /** @var Revision $rev */
1718 $rev = $status->value['revision'];
1719 // Associate new page revision id
1720 $logEntry->setAssociatedRevId( $rev->getId() );
1721 }
1722 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1723 // which is triggered on $descTitle by doEditContent() above.
1724 if ( isset( $status->value['revision'] ) ) {
1725 /** @var Revision $rev */
1726 $rev = $status->value['revision'];
1727 $updateLogPage = $rev->getPage();
1728 }
1729 } else {
1730 # Existing file page: invalidate description page cache
1731 $wikiPage->getTitle()->invalidateCache();
1732 $wikiPage->getTitle()->purgeSquid();
1733 # Allow the new file version to be patrolled from the page footer
1734 Article::purgePatrolFooterCache( $descId );
1735 }
1736
1737 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1738 # but setAssociatedRevId() wasn't called at that point yet...
1739 $logParams = $logEntry->getParameters();
1740 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1741 $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1742 if ( $updateLogPage ) {
1743 # Also log page, in case where we just created it above
1744 $update['log_page'] = $updateLogPage;
1745 }
1746 $this->getRepo()->getMasterDB()->update(
1747 'logging',
1748 $update,
1749 [ 'log_id' => $logId ],
1750 $fname
1751 );
1752 $this->getRepo()->getMasterDB()->insert(
1753 'log_search',
1754 [
1755 'ls_field' => 'associated_rev_id',
1756 'ls_value' => $logEntry->getAssociatedRevId(),
1757 'ls_log_id' => $logId,
1758 ],
1759 $fname
1760 );
1761
1762 # Add change tags, if any
1763 if ( $tags ) {
1764 $logEntry->setTags( $tags );
1765 }
1766
1767 # Uploads can be patrolled
1768 $logEntry->setIsPatrollable( true );
1769
1770 # Now that the log entry is up-to-date, make an RC entry.
1771 $logEntry->publish( $logId );
1772
1773 # Run hook for other updates (typically more cache purging)
1774 Hooks::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1775
1776 if ( $reupload ) {
1777 # Delete old thumbnails
1778 $this->purgeThumbnails();
1779 # Remove the old file from the CDN cache
1780 DeferredUpdates::addUpdate(
1781 new CdnCacheUpdate( [ $this->getUrl() ] ),
1782 DeferredUpdates::PRESEND
1783 );
1784 } else {
1785 # Update backlink pages pointing to this title if created
1786 LinksUpdate::queueRecursiveJobsForTable(
1787 $this->getTitle(),
1788 'imagelinks',
1789 'upload-image',
1790 $user->getName()
1791 );
1792 }
1793
1794 $this->prerenderThumbnails();
1795 }
1796 ),
1797 DeferredUpdates::PRESEND
1798 );
1799
1800 if ( !$reupload ) {
1801 # This is a new file, so update the image count
1802 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1803 }
1804
1805 # Invalidate cache for all pages using this file
1806 DeferredUpdates::addUpdate(
1807 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1808 );
1809
1810 return Status::newGood();
1811 }
1812
1813 /**
1814 * Move or copy a file to its public location. If a file exists at the
1815 * destination, move it to an archive. Returns a Status object with
1816 * the archive name in the "value" member on success.
1817 *
1818 * The archive name should be passed through to recordUpload for database
1819 * registration.
1820 *
1821 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1822 * @param int $flags A bitwise combination of:
1823 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1824 * @param array $options Optional additional parameters
1825 * @return Status On success, the value member contains the
1826 * archive name, or an empty string if it was a new file.
1827 */
1828 function publish( $src, $flags = 0, array $options = [] ) {
1829 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1830 }
1831
1832 /**
1833 * Move or copy a file to a specified location. Returns a Status
1834 * object with the archive name in the "value" member on success.
1835 *
1836 * The archive name should be passed through to recordUpload for database
1837 * registration.
1838 *
1839 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1840 * @param string $dstRel Target relative path
1841 * @param int $flags A bitwise combination of:
1842 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1843 * @param array $options Optional additional parameters
1844 * @return Status On success, the value member contains the
1845 * archive name, or an empty string if it was a new file.
1846 */
1847 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1848 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1849
1850 $repo = $this->getRepo();
1851 if ( $repo->getReadOnlyReason() !== false ) {
1852 return $this->readOnlyFatalStatus();
1853 }
1854
1855 $this->lock();
1856
1857 if ( $this->isOld() ) {
1858 $archiveRel = $dstRel;
1859 $archiveName = basename( $archiveRel );
1860 } else {
1861 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1862 $archiveRel = $this->getArchiveRel( $archiveName );
1863 }
1864
1865 if ( $repo->hasSha1Storage() ) {
1866 $sha1 = FileRepo::isVirtualUrl( $srcPath )
1867 ? $repo->getFileSha1( $srcPath )
1868 : FSFile::getSha1Base36FromPath( $srcPath );
1869 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1870 $wrapperBackend = $repo->getBackend();
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 $oldTitleFile->purgeOldThumbnails( $archiveName );
1941 }
1942 $newTitleFile->purgeEverything();
1943 }
1944 ),
1945 DeferredUpdates::PRESEND
1946 );
1947
1948 if ( $status->isOK() ) {
1949 // Now switch the object
1950 $this->title = $target;
1951 // Force regeneration of the name and hashpath
1952 $this->name = null;
1953 $this->hashPath = null;
1954 }
1955
1956 return $status;
1957 }
1958
1959 /**
1960 * Delete all versions of the file.
1961 *
1962 * Moves the files into an archive directory (or deletes them)
1963 * and removes the database rows.
1964 *
1965 * Cache purging is done; logging is caller's responsibility.
1966 *
1967 * @param string $reason
1968 * @param bool $suppress
1969 * @param User|null $user
1970 * @return Status
1971 */
1972 function delete( $reason, $suppress = false, $user = null ) {
1973 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1974 return $this->readOnlyFatalStatus();
1975 }
1976
1977 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1978
1979 $this->lock();
1980 $batch->addCurrent();
1981 // Get old version relative paths
1982 $archiveNames = $batch->addOlds();
1983 $status = $batch->execute();
1984 $this->unlock();
1985
1986 if ( $status->isOK() ) {
1987 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
1988 }
1989
1990 // To avoid slow purges in the transaction, move them outside...
1991 DeferredUpdates::addUpdate(
1992 new AutoCommitUpdate(
1993 $this->getRepo()->getMasterDB(),
1994 __METHOD__,
1995 function () use ( $archiveNames ) {
1996 $this->purgeEverything();
1997 foreach ( $archiveNames as $archiveName ) {
1998 $this->purgeOldThumbnails( $archiveName );
1999 }
2000 }
2001 ),
2002 DeferredUpdates::PRESEND
2003 );
2004
2005 // Purge the CDN
2006 $purgeUrls = [];
2007 foreach ( $archiveNames as $archiveName ) {
2008 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2009 }
2010 DeferredUpdates::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates::PRESEND );
2011
2012 return $status;
2013 }
2014
2015 /**
2016 * Delete an old version of the file.
2017 *
2018 * Moves the file into an archive directory (or deletes it)
2019 * and removes the database row.
2020 *
2021 * Cache purging is done; logging is caller's responsibility.
2022 *
2023 * @param string $archiveName
2024 * @param string $reason
2025 * @param bool $suppress
2026 * @param User|null $user
2027 * @throws MWException Exception on database or file store failure
2028 * @return Status
2029 */
2030 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2031 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2032 return $this->readOnlyFatalStatus();
2033 }
2034
2035 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2036
2037 $this->lock();
2038 $batch->addOld( $archiveName );
2039 $status = $batch->execute();
2040 $this->unlock();
2041
2042 $this->purgeOldThumbnails( $archiveName );
2043 if ( $status->isOK() ) {
2044 $this->purgeDescription();
2045 }
2046
2047 DeferredUpdates::addUpdate(
2048 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2049 DeferredUpdates::PRESEND
2050 );
2051
2052 return $status;
2053 }
2054
2055 /**
2056 * Restore all or specified deleted revisions to the given file.
2057 * Permissions and logging are left to the caller.
2058 *
2059 * May throw database exceptions on error.
2060 *
2061 * @param array $versions Set of record ids of deleted items to restore,
2062 * or empty to restore all revisions.
2063 * @param bool $unsuppress
2064 * @return Status
2065 */
2066 function restore( $versions = [], $unsuppress = false ) {
2067 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2068 return $this->readOnlyFatalStatus();
2069 }
2070
2071 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2072
2073 $this->lock();
2074 if ( !$versions ) {
2075 $batch->addAll();
2076 } else {
2077 $batch->addIds( $versions );
2078 }
2079 $status = $batch->execute();
2080 if ( $status->isGood() ) {
2081 $cleanupStatus = $batch->cleanup();
2082 $cleanupStatus->successCount = 0;
2083 $cleanupStatus->failCount = 0;
2084 $status->merge( $cleanupStatus );
2085 }
2086
2087 $this->unlock();
2088 return $status;
2089 }
2090
2091 /** isMultipage inherited */
2092 /** pageCount inherited */
2093 /** scaleHeight inherited */
2094 /** getImageSize inherited */
2095
2096 /**
2097 * Get the URL of the file description page.
2098 * @return string
2099 */
2100 function getDescriptionUrl() {
2101 return $this->title->getLocalURL();
2102 }
2103
2104 /**
2105 * Get the HTML text of the description page
2106 * This is not used by ImagePage for local files, since (among other things)
2107 * it skips the parser cache.
2108 *
2109 * @param Language|null $lang What language to get description in (Optional)
2110 * @return string|false
2111 */
2112 function getDescriptionText( Language $lang = null ) {
2113 $store = MediaWikiServices::getInstance()->getRevisionStore();
2114 $revision = $store->getRevisionByTitle( $this->title, 0, Revision::READ_NORMAL );
2115 if ( !$revision ) {
2116 return false;
2117 }
2118
2119 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2120 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2121
2122 if ( !$rendered ) {
2123 // audience check failed
2124 return false;
2125 }
2126
2127 $pout = $rendered->getRevisionParserOutput();
2128 return $pout->getText();
2129 }
2130
2131 /**
2132 * @param int $audience
2133 * @param User|null $user
2134 * @return string
2135 */
2136 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2137 $this->load();
2138 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2139 return '';
2140 } elseif ( $audience == self::FOR_THIS_USER
2141 && !$this->userCan( self::DELETED_COMMENT, $user )
2142 ) {
2143 return '';
2144 } else {
2145 return $this->description;
2146 }
2147 }
2148
2149 /**
2150 * @return bool|string
2151 */
2152 function getTimestamp() {
2153 $this->load();
2154
2155 return $this->timestamp;
2156 }
2157
2158 /**
2159 * @return bool|string
2160 */
2161 public function getDescriptionTouched() {
2162 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2163 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2164 // need to differentiate between null (uninitialized) and false (failed to load).
2165 if ( $this->descriptionTouched === null ) {
2166 $cond = [
2167 'page_namespace' => $this->title->getNamespace(),
2168 'page_title' => $this->title->getDBkey()
2169 ];
2170 $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2171 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2172 }
2173
2174 return $this->descriptionTouched;
2175 }
2176
2177 /**
2178 * @return string
2179 */
2180 function getSha1() {
2181 $this->load();
2182 // Initialise now if necessary
2183 if ( $this->sha1 == '' && $this->fileExists ) {
2184 $this->lock();
2185
2186 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2187 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2188 $dbw = $this->repo->getMasterDB();
2189 $dbw->update( 'image',
2190 [ 'img_sha1' => $this->sha1 ],
2191 [ 'img_name' => $this->getName() ],
2192 __METHOD__ );
2193 $this->invalidateCache();
2194 }
2195
2196 $this->unlock();
2197 }
2198
2199 return $this->sha1;
2200 }
2201
2202 /**
2203 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2204 */
2205 function isCacheable() {
2206 $this->load();
2207
2208 // If extra data (metadata) was not loaded then it must have been large
2209 return $this->extraDataLoaded
2210 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
2211 }
2212
2213 /**
2214 * @return Status
2215 * @since 1.28
2216 */
2217 public function acquireFileLock() {
2218 return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2219 [ $this->getPath() ], LockManager::LOCK_EX, 10
2220 ) );
2221 }
2222
2223 /**
2224 * @return Status
2225 * @since 1.28
2226 */
2227 public function releaseFileLock() {
2228 return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2229 [ $this->getPath() ], LockManager::LOCK_EX
2230 ) );
2231 }
2232
2233 /**
2234 * Start an atomic DB section and lock the image for update
2235 * or increments a reference counter if the lock is already held
2236 *
2237 * This method should not be used outside of LocalFile/LocalFile*Batch
2238 *
2239 * @throws LocalFileLockError Throws an error if the lock was not acquired
2240 * @return bool Whether the file lock owns/spawned the DB transaction
2241 */
2242 public function lock() {
2243 if ( !$this->locked ) {
2244 $logger = LoggerFactory::getInstance( 'LocalFile' );
2245
2246 $dbw = $this->repo->getMasterDB();
2247 $makesTransaction = !$dbw->trxLevel();
2248 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2249 // T56736: use simple lock to handle when the file does not exist.
2250 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2251 // Also, that would cause contention on INSERT of similarly named rows.
2252 $status = $this->acquireFileLock(); // represents all versions of the file
2253 if ( !$status->isGood() ) {
2254 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2255 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2256
2257 throw new LocalFileLockError( $status );
2258 }
2259 // Release the lock *after* commit to avoid row-level contention.
2260 // Make sure it triggers on rollback() as well as commit() (T132921).
2261 $dbw->onTransactionResolution(
2262 function () use ( $logger ) {
2263 $status = $this->releaseFileLock();
2264 if ( !$status->isGood() ) {
2265 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2266 }
2267 },
2268 __METHOD__
2269 );
2270 // Callers might care if the SELECT snapshot is safely fresh
2271 $this->lockedOwnTrx = $makesTransaction;
2272 }
2273
2274 $this->locked++;
2275
2276 return $this->lockedOwnTrx;
2277 }
2278
2279 /**
2280 * Decrement the lock reference count and end the atomic section if it reaches zero
2281 *
2282 * This method should not be used outside of LocalFile/LocalFile*Batch
2283 *
2284 * The commit and loc release will happen when no atomic sections are active, which
2285 * may happen immediately or at some point after calling this
2286 */
2287 public function unlock() {
2288 if ( $this->locked ) {
2289 --$this->locked;
2290 if ( !$this->locked ) {
2291 $dbw = $this->repo->getMasterDB();
2292 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2293 $this->lockedOwnTrx = false;
2294 }
2295 }
2296 }
2297
2298 /**
2299 * @return Status
2300 */
2301 protected function readOnlyFatalStatus() {
2302 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2303 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2304 }
2305
2306 /**
2307 * Clean up any dangling locks
2308 */
2309 function __destruct() {
2310 $this->unlock();
2311 }
2312 }