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