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