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