Drop the image_comment_temp table
[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 self
145 */
146 static function newFromTitle( $title, $repo, $unused = null ) {
147 return new self( $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 self
158 */
159 static function newFromRow( $row, $repo ) {
160 $title = Title::makeTitle( NS_FILE, $row->img_name );
161 $file = new self( $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 = self::getQueryInfo();
185 $row = $dbr->selectRow(
186 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__, [], $fileQuery['joins']
187 );
188 if ( $row ) {
189 return self::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 $this->maybeUpgradeRow();
638 }
639
640 /**
641 * Load file metadata from cache or DB, unless already loaded
642 * @param int $flags
643 */
644 function load( $flags = 0 ) {
645 if ( !$this->dataLoaded ) {
646 if ( $flags & self::READ_LATEST ) {
647 $this->loadFromDB( $flags );
648 } else {
649 $this->loadFromCache();
650 }
651 }
652
653 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
654 // @note: loads on name/timestamp to reduce race condition problems
655 $this->loadExtraFromDB();
656 }
657 }
658
659 /**
660 * Upgrade a row if it needs it
661 */
662 function maybeUpgradeRow() {
663 global $wgUpdateCompatibleMetadata;
664
665 if ( wfReadOnly() || $this->upgrading ) {
666 return;
667 }
668
669 $upgrade = false;
670 if ( is_null( $this->media_type ) || $this->mime == 'image/svg' ) {
671 $upgrade = true;
672 } else {
673 $handler = $this->getHandler();
674 if ( $handler ) {
675 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
676 if ( $validity === MediaHandler::METADATA_BAD ) {
677 $upgrade = true;
678 } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE ) {
679 $upgrade = $wgUpdateCompatibleMetadata;
680 }
681 }
682 }
683
684 if ( $upgrade ) {
685 $this->upgrading = true;
686 // Defer updates unless in auto-commit CLI mode
687 DeferredUpdates::addCallableUpdate( function () {
688 $this->upgrading = false; // avoid duplicate updates
689 try {
690 $this->upgradeRow();
691 } catch ( LocalFileLockError $e ) {
692 // let the other process handle it (or do it next time)
693 }
694 } );
695 }
696 }
697
698 /**
699 * @return bool Whether upgradeRow() ran for this object
700 */
701 function getUpgraded() {
702 return $this->upgraded;
703 }
704
705 /**
706 * Fix assorted version-related problems with the image row by reloading it from the file
707 */
708 function upgradeRow() {
709 $this->lock(); // begin
710
711 $this->loadFromFile();
712
713 # Don't destroy file info of missing files
714 if ( !$this->fileExists ) {
715 $this->unlock();
716 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
717
718 return;
719 }
720
721 $dbw = $this->repo->getMasterDB();
722 list( $major, $minor ) = self::splitMime( $this->mime );
723
724 if ( wfReadOnly() ) {
725 $this->unlock();
726
727 return;
728 }
729 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
730
731 $dbw->update( 'image',
732 [
733 'img_size' => $this->size, // sanity
734 'img_width' => $this->width,
735 'img_height' => $this->height,
736 'img_bits' => $this->bits,
737 'img_media_type' => $this->media_type,
738 'img_major_mime' => $major,
739 'img_minor_mime' => $minor,
740 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
741 'img_sha1' => $this->sha1,
742 ],
743 [ 'img_name' => $this->getName() ],
744 __METHOD__
745 );
746
747 $this->invalidateCache();
748
749 $this->unlock(); // done
750 $this->upgraded = true; // avoid rework/retries
751 }
752
753 /**
754 * Set properties in this object to be equal to those given in the
755 * associative array $info. Only cacheable fields can be set.
756 * All fields *must* be set in $info except for getLazyCacheFields().
757 *
758 * If 'mime' is given, it will be split into major_mime/minor_mime.
759 * If major_mime/minor_mime are given, $this->mime will also be set.
760 *
761 * @param array $info
762 */
763 function setProps( $info ) {
764 $this->dataLoaded = true;
765 $fields = $this->getCacheFields( '' );
766 $fields[] = 'fileExists';
767
768 foreach ( $fields as $field ) {
769 if ( isset( $info[$field] ) ) {
770 $this->$field = $info[$field];
771 }
772 }
773
774 if ( isset( $info['user'] ) || isset( $info['user_text'] ) || isset( $info['actor'] ) ) {
775 $this->user = User::newFromAnyId(
776 $info['user'] ?? null,
777 $info['user_text'] ?? null,
778 $info['actor'] ?? null
779 );
780 }
781
782 // Fix up mime fields
783 if ( isset( $info['major_mime'] ) ) {
784 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
785 } elseif ( isset( $info['mime'] ) ) {
786 $this->mime = $info['mime'];
787 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
788 }
789 }
790
791 /** splitMime inherited */
792 /** getName inherited */
793 /** getTitle inherited */
794 /** getURL inherited */
795 /** getViewURL inherited */
796 /** getPath inherited */
797 /** isVisible inherited */
798
799 /**
800 * @return bool
801 */
802 function isMissing() {
803 if ( $this->missing === null ) {
804 list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
805 $this->missing = !$fileExists;
806 }
807
808 return $this->missing;
809 }
810
811 /**
812 * Return the width of the image
813 *
814 * @param int $page
815 * @return int
816 */
817 public function getWidth( $page = 1 ) {
818 $page = (int)$page;
819 if ( $page < 1 ) {
820 $page = 1;
821 }
822
823 $this->load();
824
825 if ( $this->isMultipage() ) {
826 $handler = $this->getHandler();
827 if ( !$handler ) {
828 return 0;
829 }
830 $dim = $handler->getPageDimensions( $this, $page );
831 if ( $dim ) {
832 return $dim['width'];
833 } else {
834 // For non-paged media, the false goes through an
835 // intval, turning failure into 0, so do same here.
836 return 0;
837 }
838 } else {
839 return $this->width;
840 }
841 }
842
843 /**
844 * Return the height of the image
845 *
846 * @param int $page
847 * @return int
848 */
849 public function getHeight( $page = 1 ) {
850 $page = (int)$page;
851 if ( $page < 1 ) {
852 $page = 1;
853 }
854
855 $this->load();
856
857 if ( $this->isMultipage() ) {
858 $handler = $this->getHandler();
859 if ( !$handler ) {
860 return 0;
861 }
862 $dim = $handler->getPageDimensions( $this, $page );
863 if ( $dim ) {
864 return $dim['height'];
865 } else {
866 // For non-paged media, the false goes through an
867 // intval, turning failure into 0, so do same here.
868 return 0;
869 }
870 } else {
871 return $this->height;
872 }
873 }
874
875 /**
876 * Returns user who uploaded the file
877 *
878 * @param string $type 'text', 'id', or 'object'
879 * @return int|string|User
880 * @since 1.31 Added 'object'
881 */
882 function getUser( $type = 'text' ) {
883 $this->load();
884
885 if ( $type === 'object' ) {
886 return $this->user;
887 } elseif ( $type === 'text' ) {
888 return $this->user->getName();
889 } elseif ( $type === 'id' ) {
890 return $this->user->getId();
891 }
892
893 throw new MWException( "Unknown type '$type'." );
894 }
895
896 /**
897 * Get short description URL for a file based on the page ID.
898 *
899 * @return string|null
900 * @throws MWException
901 * @since 1.27
902 */
903 public function getDescriptionShortUrl() {
904 $pageId = $this->title->getArticleID();
905
906 if ( $pageId !== null ) {
907 $url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
908 if ( $url !== false ) {
909 return $url;
910 }
911 }
912 return null;
913 }
914
915 /**
916 * Get handler-specific metadata
917 * @return string
918 */
919 function getMetadata() {
920 $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
921 return $this->metadata;
922 }
923
924 /**
925 * @return int
926 */
927 function getBitDepth() {
928 $this->load();
929
930 return (int)$this->bits;
931 }
932
933 /**
934 * Returns the size of the image file, in bytes
935 * @return int
936 */
937 public function getSize() {
938 $this->load();
939
940 return $this->size;
941 }
942
943 /**
944 * Returns the MIME type of the file.
945 * @return string
946 */
947 function getMimeType() {
948 $this->load();
949
950 return $this->mime;
951 }
952
953 /**
954 * Returns the type of the media in the file.
955 * Use the value returned by this function with the MEDIATYPE_xxx constants.
956 * @return string
957 */
958 function getMediaType() {
959 $this->load();
960
961 return $this->media_type;
962 }
963
964 /** canRender inherited */
965 /** mustRender inherited */
966 /** allowInlineDisplay inherited */
967 /** isSafeFile inherited */
968 /** isTrustedFile inherited */
969
970 /**
971 * Returns true if the file exists on disk.
972 * @return bool Whether file exist on disk.
973 */
974 public function exists() {
975 $this->load();
976
977 return $this->fileExists;
978 }
979
980 /** getTransformScript inherited */
981 /** getUnscaledThumb inherited */
982 /** thumbName inherited */
983 /** createThumb inherited */
984 /** transform inherited */
985
986 /** getHandler inherited */
987 /** iconThumb inherited */
988 /** getLastError inherited */
989
990 /**
991 * Get all thumbnail names previously generated for this file
992 * @param string|bool $archiveName Name of an archive file, default false
993 * @return array First element is the base dir, then files in that base dir.
994 */
995 function getThumbnails( $archiveName = false ) {
996 if ( $archiveName ) {
997 $dir = $this->getArchiveThumbPath( $archiveName );
998 } else {
999 $dir = $this->getThumbPath();
1000 }
1001
1002 $backend = $this->repo->getBackend();
1003 $files = [ $dir ];
1004 try {
1005 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
1006 foreach ( $iterator as $file ) {
1007 $files[] = $file;
1008 }
1009 } catch ( FileBackendError $e ) {
1010 } // suppress (T56674)
1011
1012 return $files;
1013 }
1014
1015 /**
1016 * Refresh metadata in memcached, but don't touch thumbnails or CDN
1017 */
1018 function purgeMetadataCache() {
1019 $this->invalidateCache();
1020 }
1021
1022 /**
1023 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
1024 *
1025 * @param array $options An array potentially with the key forThumbRefresh.
1026 *
1027 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
1028 */
1029 function purgeCache( $options = [] ) {
1030 // Refresh metadata cache
1031 $this->purgeMetadataCache();
1032
1033 // Delete thumbnails
1034 $this->purgeThumbnails( $options );
1035
1036 // Purge CDN cache for this file
1037 DeferredUpdates::addUpdate(
1038 new CdnCacheUpdate( [ $this->getUrl() ] ),
1039 DeferredUpdates::PRESEND
1040 );
1041 }
1042
1043 /**
1044 * Delete cached transformed files for an archived version only.
1045 * @param string $archiveName Name of the archived file
1046 */
1047 function purgeOldThumbnails( $archiveName ) {
1048 // Get a list of old thumbnails and URLs
1049 $files = $this->getThumbnails( $archiveName );
1050
1051 // Purge any custom thumbnail caches
1052 Hooks::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
1053
1054 // Delete thumbnails
1055 $dir = array_shift( $files );
1056 $this->purgeThumbList( $dir, $files );
1057
1058 // Purge the CDN
1059 $urls = [];
1060 foreach ( $files as $file ) {
1061 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
1062 }
1063 DeferredUpdates::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates::PRESEND );
1064 }
1065
1066 /**
1067 * Delete cached transformed files for the current version only.
1068 * @param array $options
1069 */
1070 public function purgeThumbnails( $options = [] ) {
1071 $files = $this->getThumbnails();
1072 // Always purge all files from CDN regardless of handler filters
1073 $urls = [];
1074 foreach ( $files as $file ) {
1075 $urls[] = $this->getThumbUrl( $file );
1076 }
1077 array_shift( $urls ); // don't purge directory
1078
1079 // Give media handler a chance to filter the file purge list
1080 if ( !empty( $options['forThumbRefresh'] ) ) {
1081 $handler = $this->getHandler();
1082 if ( $handler ) {
1083 $handler->filterThumbnailPurgeList( $files, $options );
1084 }
1085 }
1086
1087 // Purge any custom thumbnail caches
1088 Hooks::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
1089
1090 // Delete thumbnails
1091 $dir = array_shift( $files );
1092 $this->purgeThumbList( $dir, $files );
1093
1094 // Purge the CDN
1095 DeferredUpdates::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates::PRESEND );
1096 }
1097
1098 /**
1099 * Prerenders a configurable set of thumbnails
1100 *
1101 * @since 1.28
1102 */
1103 public function prerenderThumbnails() {
1104 global $wgUploadThumbnailRenderMap;
1105
1106 $jobs = [];
1107
1108 $sizes = $wgUploadThumbnailRenderMap;
1109 rsort( $sizes );
1110
1111 foreach ( $sizes as $size ) {
1112 if ( $this->isVectorized() || $this->getWidth() > $size ) {
1113 $jobs[] = new ThumbnailRenderJob(
1114 $this->getTitle(),
1115 [ 'transformParams' => [ 'width' => $size ] ]
1116 );
1117 }
1118 }
1119
1120 if ( $jobs ) {
1121 JobQueueGroup::singleton()->lazyPush( $jobs );
1122 }
1123 }
1124
1125 /**
1126 * Delete a list of thumbnails visible at urls
1127 * @param string $dir Base dir of the files.
1128 * @param array $files Array of strings: relative filenames (to $dir)
1129 */
1130 protected function purgeThumbList( $dir, $files ) {
1131 $fileListDebug = strtr(
1132 var_export( $files, true ),
1133 [ "\n" => '' ]
1134 );
1135 wfDebug( __METHOD__ . ": $fileListDebug\n" );
1136
1137 $purgeList = [];
1138 foreach ( $files as $file ) {
1139 if ( $this->repo->supportsSha1URLs() ) {
1140 $reference = $this->getSha1();
1141 } else {
1142 $reference = $this->getName();
1143 }
1144
1145 # Check that the reference (filename or sha1) is part of the thumb name
1146 # This is a basic sanity check to avoid erasing unrelated directories
1147 if ( strpos( $file, $reference ) !== false
1148 || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1149 ) {
1150 $purgeList[] = "{$dir}/{$file}";
1151 }
1152 }
1153
1154 # Delete the thumbnails
1155 $this->repo->quickPurgeBatch( $purgeList );
1156 # Clear out the thumbnail directory if empty
1157 $this->repo->quickCleanDir( $dir );
1158 }
1159
1160 /** purgeDescription inherited */
1161 /** purgeEverything inherited */
1162
1163 /**
1164 * @param int|null $limit Optional: Limit to number of results
1165 * @param string|int|null $start Optional: Timestamp, start from
1166 * @param string|int|null $end Optional: Timestamp, end at
1167 * @param bool $inc
1168 * @return OldLocalFile[]
1169 */
1170 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1171 $dbr = $this->repo->getReplicaDB();
1172 $oldFileQuery = OldLocalFile::getQueryInfo();
1173
1174 $tables = $oldFileQuery['tables'];
1175 $fields = $oldFileQuery['fields'];
1176 $join_conds = $oldFileQuery['joins'];
1177 $conds = $opts = [];
1178 $eq = $inc ? '=' : '';
1179 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1180
1181 if ( $start ) {
1182 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1183 }
1184
1185 if ( $end ) {
1186 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1187 }
1188
1189 if ( $limit ) {
1190 $opts['LIMIT'] = $limit;
1191 }
1192
1193 // Search backwards for time > x queries
1194 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1195 $opts['ORDER BY'] = "oi_timestamp $order";
1196 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1197
1198 // Avoid PHP 7.1 warning from passing $this by reference
1199 $localFile = $this;
1200 Hooks::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1201 &$conds, &$opts, &$join_conds ] );
1202
1203 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1204 $r = [];
1205
1206 foreach ( $res as $row ) {
1207 $r[] = $this->repo->newFileFromRow( $row );
1208 }
1209
1210 if ( $order == 'ASC' ) {
1211 $r = array_reverse( $r ); // make sure it ends up descending
1212 }
1213
1214 return $r;
1215 }
1216
1217 /**
1218 * Returns the history of this file, line by line.
1219 * starts with current version, then old versions.
1220 * uses $this->historyLine to check which line to return:
1221 * 0 return line for current version
1222 * 1 query for old versions, return first one
1223 * 2, ... return next old version from above query
1224 * @return bool
1225 */
1226 public function nextHistoryLine() {
1227 # Polymorphic function name to distinguish foreign and local fetches
1228 $fname = static::class . '::' . __FUNCTION__;
1229
1230 $dbr = $this->repo->getReplicaDB();
1231
1232 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1233 $fileQuery = self::getQueryInfo();
1234 $this->historyRes = $dbr->select( $fileQuery['tables'],
1235 $fileQuery['fields'] + [
1236 'oi_archive_name' => $dbr->addQuotes( '' ),
1237 'oi_deleted' => 0,
1238 ],
1239 [ 'img_name' => $this->title->getDBkey() ],
1240 $fname,
1241 [],
1242 $fileQuery['joins']
1243 );
1244
1245 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1246 $this->historyRes = null;
1247
1248 return false;
1249 }
1250 } elseif ( $this->historyLine == 1 ) {
1251 $fileQuery = OldLocalFile::getQueryInfo();
1252 $this->historyRes = $dbr->select(
1253 $fileQuery['tables'],
1254 $fileQuery['fields'],
1255 [ 'oi_name' => $this->title->getDBkey() ],
1256 $fname,
1257 [ 'ORDER BY' => 'oi_timestamp DESC' ],
1258 $fileQuery['joins']
1259 );
1260 }
1261 $this->historyLine++;
1262
1263 return $dbr->fetchObject( $this->historyRes );
1264 }
1265
1266 /**
1267 * Reset the history pointer to the first element of the history
1268 */
1269 public function resetHistory() {
1270 $this->historyLine = 0;
1271
1272 if ( !is_null( $this->historyRes ) ) {
1273 $this->historyRes = null;
1274 }
1275 }
1276
1277 /** getHashPath inherited */
1278 /** getRel inherited */
1279 /** getUrlRel inherited */
1280 /** getArchiveRel inherited */
1281 /** getArchivePath inherited */
1282 /** getThumbPath inherited */
1283 /** getArchiveUrl inherited */
1284 /** getThumbUrl inherited */
1285 /** getArchiveVirtualUrl inherited */
1286 /** getThumbVirtualUrl inherited */
1287 /** isHashed inherited */
1288
1289 /**
1290 * Upload a file and record it in the DB
1291 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1292 * @param string $comment Upload description
1293 * @param string $pageText Text to use for the new description page,
1294 * if a new description page is created
1295 * @param int|bool $flags Flags for publish()
1296 * @param array|bool $props File properties, if known. This can be used to
1297 * reduce the upload time when uploading virtual URLs for which the file
1298 * info is already known
1299 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1300 * current time
1301 * @param User|null $user User object or null to use $wgUser
1302 * @param string[] $tags Change tags to add to the log entry and page revision.
1303 * (This doesn't check $user's permissions.)
1304 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1305 * upload, see T193621
1306 * @return Status On success, the value member contains the
1307 * archive name, or an empty string if it was a new file.
1308 */
1309 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1310 $timestamp = false, $user = null, $tags = [],
1311 $createNullRevision = true
1312 ) {
1313 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1314 return $this->readOnlyFatalStatus();
1315 } elseif ( MediaWikiServices::getInstance()->getRevisionStore()->isReadOnly() ) {
1316 // Check this in advance to avoid writing to FileBackend and the file tables,
1317 // only to fail on insert the revision due to the text store being unavailable.
1318 return $this->readOnlyFatalStatus();
1319 }
1320
1321 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1322 if ( !$props ) {
1323 if ( $this->repo->isVirtualUrl( $srcPath )
1324 || FileBackend::isStoragePath( $srcPath )
1325 ) {
1326 $props = $this->repo->getFileProps( $srcPath );
1327 } else {
1328 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
1329 $props = $mwProps->getPropsFromPath( $srcPath, true );
1330 }
1331 }
1332
1333 $options = [];
1334 $handler = MediaHandler::getHandler( $props['mime'] );
1335 if ( $handler ) {
1336 $metadata = Wikimedia\quietCall( 'unserialize', $props['metadata'] );
1337
1338 if ( !is_array( $metadata ) ) {
1339 $metadata = [];
1340 }
1341
1342 $options['headers'] = $handler->getContentHeaders( $metadata );
1343 } else {
1344 $options['headers'] = [];
1345 }
1346
1347 // Trim spaces on user supplied text
1348 $comment = trim( $comment );
1349
1350 $this->lock(); // begin
1351 $status = $this->publish( $src, $flags, $options );
1352
1353 if ( $status->successCount >= 2 ) {
1354 // There will be a copy+(one of move,copy,store).
1355 // The first succeeding does not commit us to updating the DB
1356 // since it simply copied the current version to a timestamped file name.
1357 // It is only *preferable* to avoid leaving such files orphaned.
1358 // Once the second operation goes through, then the current version was
1359 // updated and we must therefore update the DB too.
1360 $oldver = $status->value;
1361 $uploadStatus = $this->recordUpload2(
1362 $oldver,
1363 $comment,
1364 $pageText,
1365 $props,
1366 $timestamp,
1367 $user,
1368 $tags,
1369 $createNullRevision
1370 );
1371 if ( !$uploadStatus->isOK() ) {
1372 if ( $uploadStatus->hasMessage( 'filenotfound' ) ) {
1373 // update filenotfound error with more specific path
1374 $status->fatal( 'filenotfound', $srcPath );
1375 } else {
1376 $status->merge( $uploadStatus );
1377 }
1378 }
1379 }
1380
1381 $this->unlock(); // done
1382
1383 return $status;
1384 }
1385
1386 /**
1387 * Record a file upload in the upload log and the image table
1388 * @param string $oldver
1389 * @param string $desc
1390 * @param string $license
1391 * @param string $copyStatus
1392 * @param string $source
1393 * @param bool $watch
1394 * @param string|bool $timestamp
1395 * @param User|null $user User object or null to use $wgUser
1396 * @return bool
1397 */
1398 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1399 $watch = false, $timestamp = false, User $user = null ) {
1400 if ( !$user ) {
1401 global $wgUser;
1402 $user = $wgUser;
1403 }
1404
1405 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1406
1407 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user )->isOK() ) {
1408 return false;
1409 }
1410
1411 if ( $watch ) {
1412 $user->addWatch( $this->getTitle() );
1413 }
1414
1415 return true;
1416 }
1417
1418 /**
1419 * Record a file upload in the upload log and the image table
1420 * @param string $oldver
1421 * @param string $comment
1422 * @param string $pageText
1423 * @param bool|array $props
1424 * @param string|bool $timestamp
1425 * @param null|User $user
1426 * @param string[] $tags
1427 * @param bool $createNullRevision Set to false to avoid creation of a null revision on file
1428 * upload, see T193621
1429 * @return Status
1430 */
1431 function recordUpload2(
1432 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [],
1433 $createNullRevision = true
1434 ) {
1435 global $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage;
1436
1437 if ( is_null( $user ) ) {
1438 global $wgUser;
1439 $user = $wgUser;
1440 }
1441
1442 $dbw = $this->repo->getMasterDB();
1443
1444 # Imports or such might force a certain timestamp; otherwise we generate
1445 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1446 if ( $timestamp === false ) {
1447 $timestamp = $dbw->timestamp();
1448 $allowTimeKludge = true;
1449 } else {
1450 $allowTimeKludge = false;
1451 }
1452
1453 $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() );
1454 $props['description'] = $comment;
1455 $props['user'] = $user->getId();
1456 $props['user_text'] = $user->getName();
1457 $props['actor'] = $user->getActorId( $dbw );
1458 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1459 $this->setProps( $props );
1460
1461 # Fail now if the file isn't there
1462 if ( !$this->fileExists ) {
1463 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
1464
1465 return Status::newFatal( 'filenotfound', $this->getRel() );
1466 }
1467
1468 $dbw->startAtomic( __METHOD__ );
1469
1470 # Test to see if the row exists using INSERT IGNORE
1471 # This avoids race conditions by locking the row until the commit, and also
1472 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1473 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
1474 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
1475 $actorMigration = ActorMigration::newMigration();
1476 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
1477 $dbw->insert( 'image',
1478 [
1479 'img_name' => $this->getName(),
1480 'img_size' => $this->size,
1481 'img_width' => intval( $this->width ),
1482 'img_height' => intval( $this->height ),
1483 'img_bits' => $this->bits,
1484 'img_media_type' => $this->media_type,
1485 'img_major_mime' => $this->major_mime,
1486 'img_minor_mime' => $this->minor_mime,
1487 'img_timestamp' => $timestamp,
1488 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1489 'img_sha1' => $this->sha1
1490 ] + $commentFields + $actorFields,
1491 __METHOD__,
1492 'IGNORE'
1493 );
1494 $reupload = ( $dbw->affectedRows() == 0 );
1495
1496 if ( $reupload ) {
1497 $row = $dbw->selectRow(
1498 'image',
1499 [ 'img_timestamp', 'img_sha1' ],
1500 [ 'img_name' => $this->getName() ],
1501 __METHOD__,
1502 [ 'LOCK IN SHARE MODE' ]
1503 );
1504
1505 if ( $row && $row->img_sha1 === $this->sha1 ) {
1506 $dbw->endAtomic( __METHOD__ );
1507 wfDebug( __METHOD__ . ": File " . $this->getRel() . " already exists!\n" );
1508 $title = Title::newFromText( $this->getName(), NS_FILE );
1509 return Status::newFatal( 'fileexists-no-change', $title->getPrefixedText() );
1510 }
1511
1512 if ( $allowTimeKludge ) {
1513 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1514 $lUnixtime = $row ? wfTimestamp( TS_UNIX, $row->img_timestamp ) : false;
1515 # Avoid a timestamp that is not newer than the last version
1516 # TODO: the image/oldimage tables should be like page/revision with an ID field
1517 if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1518 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1519 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1520 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1521 }
1522 }
1523
1524 $tables = [ 'image' ];
1525 $fields = [
1526 'oi_name' => 'img_name',
1527 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1528 'oi_size' => 'img_size',
1529 'oi_width' => 'img_width',
1530 'oi_height' => 'img_height',
1531 'oi_bits' => 'img_bits',
1532 'oi_timestamp' => 'img_timestamp',
1533 'oi_metadata' => 'img_metadata',
1534 'oi_media_type' => 'img_media_type',
1535 'oi_major_mime' => 'img_major_mime',
1536 'oi_minor_mime' => 'img_minor_mime',
1537 'oi_sha1' => 'img_sha1',
1538 ];
1539 $joins = [];
1540
1541 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH ) {
1542 $fields['oi_description'] = 'img_description';
1543 }
1544 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH ) {
1545 $fields['oi_description_id'] = 'img_description_id';
1546 }
1547
1548 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD &&
1549 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
1550 ) {
1551 // Upgrade any rows that are still old-style. Otherwise an upgrade
1552 // might be missed if a deletion happens while the migration script
1553 // is running.
1554 $res = $dbw->select(
1555 [ 'image' ],
1556 [ 'img_name', 'img_description' ],
1557 [
1558 'img_name' => $this->getName(),
1559 'img_description_id' => 0,
1560 ],
1561 __METHOD__
1562 );
1563 foreach ( $res as $row ) {
1564 $imgFields = $commentStore->insert( $dbw, 'img_description', $row->img_description );
1565 $dbw->update(
1566 'image',
1567 $imgFields,
1568 [ 'img_name' => $row->img_name ],
1569 __METHOD__
1570 );
1571 }
1572 }
1573
1574 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
1575 $fields['oi_user'] = 'img_user';
1576 $fields['oi_user_text'] = 'img_user_text';
1577 }
1578 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
1579 $fields['oi_actor'] = 'img_actor';
1580 }
1581
1582 if (
1583 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH ) === SCHEMA_COMPAT_WRITE_BOTH
1584 ) {
1585 // Upgrade any rows that are still old-style. Otherwise an upgrade
1586 // might be missed if a deletion happens while the migration script
1587 // is running.
1588 $res = $dbw->select(
1589 [ 'image' ],
1590 [ 'img_name', 'img_user', 'img_user_text' ],
1591 [ 'img_name' => $this->getName(), 'img_actor' => 0 ],
1592 __METHOD__
1593 );
1594 foreach ( $res as $row ) {
1595 $actorId = User::newFromAnyId( $row->img_user, $row->img_user_text, null )->getActorId( $dbw );
1596 $dbw->update(
1597 'image',
1598 [ 'img_actor' => $actorId ],
1599 [ 'img_name' => $row->img_name, 'img_actor' => 0 ],
1600 __METHOD__
1601 );
1602 }
1603 }
1604
1605 # (T36993) Note: $oldver can be empty here, if the previous
1606 # version of the file was broken. Allow registration of the new
1607 # version to continue anyway, because that's better than having
1608 # an image that's not fixable by user operations.
1609 # Collision, this is an update of a file
1610 # Insert previous contents into oldimage
1611 $dbw->insertSelect( 'oldimage', $tables, $fields,
1612 [ 'img_name' => $this->getName() ], __METHOD__, [], [], $joins );
1613
1614 # Update the current image row
1615 $dbw->update( 'image',
1616 [
1617 'img_size' => $this->size,
1618 'img_width' => intval( $this->width ),
1619 'img_height' => intval( $this->height ),
1620 'img_bits' => $this->bits,
1621 'img_media_type' => $this->media_type,
1622 'img_major_mime' => $this->major_mime,
1623 'img_minor_mime' => $this->minor_mime,
1624 'img_timestamp' => $timestamp,
1625 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1626 'img_sha1' => $this->sha1
1627 ] + $commentFields + $actorFields,
1628 [ 'img_name' => $this->getName() ],
1629 __METHOD__
1630 );
1631 }
1632
1633 $descTitle = $this->getTitle();
1634 $descId = $descTitle->getArticleID();
1635 $wikiPage = new WikiFilePage( $descTitle );
1636 $wikiPage->setFile( $this );
1637
1638 // Add the log entry...
1639 $logEntry = new ManualLogEntry( 'upload', $reupload ? 'overwrite' : 'upload' );
1640 $logEntry->setTimestamp( $this->timestamp );
1641 $logEntry->setPerformer( $user );
1642 $logEntry->setComment( $comment );
1643 $logEntry->setTarget( $descTitle );
1644 // Allow people using the api to associate log entries with the upload.
1645 // Log has a timestamp, but sometimes different from upload timestamp.
1646 $logEntry->setParameters(
1647 [
1648 'img_sha1' => $this->sha1,
1649 'img_timestamp' => $timestamp,
1650 ]
1651 );
1652 // Note we keep $logId around since during new image
1653 // creation, page doesn't exist yet, so log_page = 0
1654 // but we want it to point to the page we're making,
1655 // so we later modify the log entry.
1656 // For a similar reason, we avoid making an RC entry
1657 // now and wait until the page exists.
1658 $logId = $logEntry->insert();
1659
1660 if ( $descTitle->exists() ) {
1661 // Use own context to get the action text in content language
1662 $formatter = LogFormatter::newFromEntry( $logEntry );
1663 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1664 $editSummary = $formatter->getPlainActionText();
1665
1666 $nullRevision = $createNullRevision === false ? null : Revision::newNullRevision(
1667 $dbw,
1668 $descId,
1669 $editSummary,
1670 false,
1671 $user
1672 );
1673 if ( $nullRevision ) {
1674 $nullRevision->insertOn( $dbw );
1675 Hooks::run(
1676 'NewRevisionFromEditComplete',
1677 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1678 );
1679 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1680 // Associate null revision id
1681 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1682 }
1683
1684 $newPageContent = null;
1685 } else {
1686 // Make the description page and RC log entry post-commit
1687 $newPageContent = ContentHandler::makeContent( $pageText, $descTitle );
1688 }
1689
1690 # Defer purges, page creation, and link updates in case they error out.
1691 # The most important thing is that files and the DB registry stay synced.
1692 $dbw->endAtomic( __METHOD__ );
1693 $fname = __METHOD__;
1694
1695 # Do some cache purges after final commit so that:
1696 # a) Changes are more likely to be seen post-purge
1697 # b) They won't cause rollback of the log publish/update above
1698 DeferredUpdates::addUpdate(
1699 new AutoCommitUpdate(
1700 $dbw,
1701 __METHOD__,
1702 function () use (
1703 $reupload, $wikiPage, $newPageContent, $comment, $user,
1704 $logEntry, $logId, $descId, $tags, $fname
1705 ) {
1706 # Update memcache after the commit
1707 $this->invalidateCache();
1708
1709 $updateLogPage = false;
1710 if ( $newPageContent ) {
1711 # New file page; create the description page.
1712 # There's already a log entry, so don't make a second RC entry
1713 # CDN and file cache for the description page are purged by doEditContent.
1714 $status = $wikiPage->doEditContent(
1715 $newPageContent,
1716 $comment,
1717 EDIT_NEW | EDIT_SUPPRESS_RC,
1718 false,
1719 $user
1720 );
1721
1722 if ( isset( $status->value['revision'] ) ) {
1723 /** @var Revision $rev */
1724 $rev = $status->value['revision'];
1725 // Associate new page revision id
1726 $logEntry->setAssociatedRevId( $rev->getId() );
1727 }
1728 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1729 // which is triggered on $descTitle by doEditContent() above.
1730 if ( isset( $status->value['revision'] ) ) {
1731 /** @var Revision $rev */
1732 $rev = $status->value['revision'];
1733 $updateLogPage = $rev->getPage();
1734 }
1735 } else {
1736 # Existing file page: invalidate description page cache
1737 $wikiPage->getTitle()->invalidateCache();
1738 $wikiPage->getTitle()->purgeSquid();
1739 # Allow the new file version to be patrolled from the page footer
1740 Article::purgePatrolFooterCache( $descId );
1741 }
1742
1743 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1744 # but setAssociatedRevId() wasn't called at that point yet...
1745 $logParams = $logEntry->getParameters();
1746 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1747 $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1748 if ( $updateLogPage ) {
1749 # Also log page, in case where we just created it above
1750 $update['log_page'] = $updateLogPage;
1751 }
1752 $this->getRepo()->getMasterDB()->update(
1753 'logging',
1754 $update,
1755 [ 'log_id' => $logId ],
1756 $fname
1757 );
1758 $this->getRepo()->getMasterDB()->insert(
1759 'log_search',
1760 [
1761 'ls_field' => 'associated_rev_id',
1762 'ls_value' => $logEntry->getAssociatedRevId(),
1763 'ls_log_id' => $logId,
1764 ],
1765 $fname
1766 );
1767
1768 # Add change tags, if any
1769 if ( $tags ) {
1770 $logEntry->setTags( $tags );
1771 }
1772
1773 # Uploads can be patrolled
1774 $logEntry->setIsPatrollable( true );
1775
1776 # Now that the log entry is up-to-date, make an RC entry.
1777 $logEntry->publish( $logId );
1778
1779 # Run hook for other updates (typically more cache purging)
1780 Hooks::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1781
1782 if ( $reupload ) {
1783 # Delete old thumbnails
1784 $this->purgeThumbnails();
1785 # Remove the old file from the CDN cache
1786 DeferredUpdates::addUpdate(
1787 new CdnCacheUpdate( [ $this->getUrl() ] ),
1788 DeferredUpdates::PRESEND
1789 );
1790 } else {
1791 # Update backlink pages pointing to this title if created
1792 LinksUpdate::queueRecursiveJobsForTable(
1793 $this->getTitle(),
1794 'imagelinks',
1795 'upload-image',
1796 $user->getName()
1797 );
1798 }
1799
1800 $this->prerenderThumbnails();
1801 }
1802 ),
1803 DeferredUpdates::PRESEND
1804 );
1805
1806 if ( !$reupload ) {
1807 # This is a new file, so update the image count
1808 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1809 }
1810
1811 # Invalidate cache for all pages using this file
1812 DeferredUpdates::addUpdate(
1813 new HTMLCacheUpdate( $this->getTitle(), 'imagelinks', 'file-upload' )
1814 );
1815
1816 return Status::newGood();
1817 }
1818
1819 /**
1820 * Move or copy a file to its public location. If a file exists at the
1821 * destination, move it to an archive. Returns a Status object with
1822 * the archive name in the "value" member on success.
1823 *
1824 * The archive name should be passed through to recordUpload for database
1825 * registration.
1826 *
1827 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1828 * @param 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 publish( $src, $flags = 0, array $options = [] ) {
1835 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1836 }
1837
1838 /**
1839 * Move or copy a file to a specified location. Returns a Status
1840 * object with the archive name in the "value" member on success.
1841 *
1842 * The archive name should be passed through to recordUpload for database
1843 * registration.
1844 *
1845 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1846 * @param string $dstRel Target relative path
1847 * @param int $flags A bitwise combination of:
1848 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1849 * @param array $options Optional additional parameters
1850 * @return Status On success, the value member contains the
1851 * archive name, or an empty string if it was a new file.
1852 */
1853 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1854 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1855
1856 $repo = $this->getRepo();
1857 if ( $repo->getReadOnlyReason() !== false ) {
1858 return $this->readOnlyFatalStatus();
1859 }
1860
1861 $this->lock(); // begin
1862
1863 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1864 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1865
1866 if ( $repo->hasSha1Storage() ) {
1867 $sha1 = $repo->isVirtualUrl( $srcPath )
1868 ? $repo->getFileSha1( $srcPath )
1869 : FSFile::getSha1Base36FromPath( $srcPath );
1870 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1871 $wrapperBackend = $repo->getBackend();
1872 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1873 $status = $repo->quickImport( $src, $dst );
1874 if ( $flags & File::DELETE_SOURCE ) {
1875 unlink( $srcPath );
1876 }
1877
1878 if ( $this->exists() ) {
1879 $status->value = $archiveName;
1880 }
1881 } else {
1882 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1883 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1884
1885 if ( $status->value == 'new' ) {
1886 $status->value = '';
1887 } else {
1888 $status->value = $archiveName;
1889 }
1890 }
1891
1892 $this->unlock(); // done
1893
1894 return $status;
1895 }
1896
1897 /** getLinksTo inherited */
1898 /** getExifData inherited */
1899 /** isLocal inherited */
1900 /** wasDeleted inherited */
1901
1902 /**
1903 * Move file to the new title
1904 *
1905 * Move current, old version and all thumbnails
1906 * to the new filename. Old file is deleted.
1907 *
1908 * Cache purging is done; checks for validity
1909 * and logging are caller's responsibility
1910 *
1911 * @param Title $target New file name
1912 * @return Status
1913 */
1914 function move( $target ) {
1915 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1916 return $this->readOnlyFatalStatus();
1917 }
1918
1919 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1920 $batch = new LocalFileMoveBatch( $this, $target );
1921
1922 $this->lock(); // begin
1923 $batch->addCurrent();
1924 $archiveNames = $batch->addOlds();
1925 $status = $batch->execute();
1926 $this->unlock(); // done
1927
1928 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1929
1930 // Purge the source and target files...
1931 $oldTitleFile = wfLocalFile( $this->title );
1932 $newTitleFile = wfLocalFile( $target );
1933 // To avoid slow purges in the transaction, move them outside...
1934 DeferredUpdates::addUpdate(
1935 new AutoCommitUpdate(
1936 $this->getRepo()->getMasterDB(),
1937 __METHOD__,
1938 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1939 $oldTitleFile->purgeEverything();
1940 foreach ( $archiveNames as $archiveName ) {
1941 $oldTitleFile->purgeOldThumbnails( $archiveName );
1942 }
1943 $newTitleFile->purgeEverything();
1944 }
1945 ),
1946 DeferredUpdates::PRESEND
1947 );
1948
1949 if ( $status->isOK() ) {
1950 // Now switch the object
1951 $this->title = $target;
1952 // Force regeneration of the name and hashpath
1953 unset( $this->name );
1954 unset( $this->hashPath );
1955 }
1956
1957 return $status;
1958 }
1959
1960 /**
1961 * Delete all versions of the file.
1962 *
1963 * Moves the files into an archive directory (or deletes them)
1964 * and removes the database rows.
1965 *
1966 * Cache purging is done; logging is caller's responsibility.
1967 *
1968 * @param string $reason
1969 * @param bool $suppress
1970 * @param User|null $user
1971 * @return Status
1972 */
1973 function delete( $reason, $suppress = false, $user = null ) {
1974 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1975 return $this->readOnlyFatalStatus();
1976 }
1977
1978 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1979
1980 $this->lock(); // begin
1981 $batch->addCurrent();
1982 // Get old version relative paths
1983 $archiveNames = $batch->addOlds();
1984 $status = $batch->execute();
1985 $this->unlock(); // done
1986
1987 if ( $status->isOK() ) {
1988 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
1989 }
1990
1991 // To avoid slow purges in the transaction, move them outside...
1992 DeferredUpdates::addUpdate(
1993 new AutoCommitUpdate(
1994 $this->getRepo()->getMasterDB(),
1995 __METHOD__,
1996 function () use ( $archiveNames ) {
1997 $this->purgeEverything();
1998 foreach ( $archiveNames as $archiveName ) {
1999 $this->purgeOldThumbnails( $archiveName );
2000 }
2001 }
2002 ),
2003 DeferredUpdates::PRESEND
2004 );
2005
2006 // Purge the CDN
2007 $purgeUrls = [];
2008 foreach ( $archiveNames as $archiveName ) {
2009 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
2010 }
2011 DeferredUpdates::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates::PRESEND );
2012
2013 return $status;
2014 }
2015
2016 /**
2017 * Delete an old version of the file.
2018 *
2019 * Moves the file into an archive directory (or deletes it)
2020 * and removes the database row.
2021 *
2022 * Cache purging is done; logging is caller's responsibility.
2023 *
2024 * @param string $archiveName
2025 * @param string $reason
2026 * @param bool $suppress
2027 * @param User|null $user
2028 * @throws MWException Exception on database or file store failure
2029 * @return Status
2030 */
2031 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
2032 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2033 return $this->readOnlyFatalStatus();
2034 }
2035
2036 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
2037
2038 $this->lock(); // begin
2039 $batch->addOld( $archiveName );
2040 $status = $batch->execute();
2041 $this->unlock(); // done
2042
2043 $this->purgeOldThumbnails( $archiveName );
2044 if ( $status->isOK() ) {
2045 $this->purgeDescription();
2046 }
2047
2048 DeferredUpdates::addUpdate(
2049 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
2050 DeferredUpdates::PRESEND
2051 );
2052
2053 return $status;
2054 }
2055
2056 /**
2057 * Restore all or specified deleted revisions to the given file.
2058 * Permissions and logging are left to the caller.
2059 *
2060 * May throw database exceptions on error.
2061 *
2062 * @param array $versions Set of record ids of deleted items to restore,
2063 * or empty to restore all revisions.
2064 * @param bool $unsuppress
2065 * @return Status
2066 */
2067 function restore( $versions = [], $unsuppress = false ) {
2068 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
2069 return $this->readOnlyFatalStatus();
2070 }
2071
2072 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
2073
2074 $this->lock(); // begin
2075 if ( !$versions ) {
2076 $batch->addAll();
2077 } else {
2078 $batch->addIds( $versions );
2079 }
2080 $status = $batch->execute();
2081 if ( $status->isGood() ) {
2082 $cleanupStatus = $batch->cleanup();
2083 $cleanupStatus->successCount = 0;
2084 $cleanupStatus->failCount = 0;
2085 $status->merge( $cleanupStatus );
2086 }
2087 $this->unlock(); // done
2088
2089 return $status;
2090 }
2091
2092 /** isMultipage inherited */
2093 /** pageCount inherited */
2094 /** scaleHeight inherited */
2095 /** getImageSize inherited */
2096
2097 /**
2098 * Get the URL of the file description page.
2099 * @return string
2100 */
2101 function getDescriptionUrl() {
2102 return $this->title->getLocalURL();
2103 }
2104
2105 /**
2106 * Get the HTML text of the description page
2107 * This is not used by ImagePage for local files, since (among other things)
2108 * it skips the parser cache.
2109 *
2110 * @param Language|null $lang What language to get description in (Optional)
2111 * @return string|false
2112 */
2113 function getDescriptionText( Language $lang = null ) {
2114 $store = MediaWikiServices::getInstance()->getRevisionStore();
2115 $revision = $store->getRevisionByTitle( $this->title, 0, Revision::READ_NORMAL );
2116 if ( !$revision ) {
2117 return false;
2118 }
2119
2120 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
2121 $rendered = $renderer->getRenderedRevision( $revision, new ParserOptions( null, $lang ) );
2122
2123 if ( !$rendered ) {
2124 // audience check failed
2125 return false;
2126 }
2127
2128 $pout = $rendered->getRevisionParserOutput();
2129 return $pout->getText();
2130 }
2131
2132 /**
2133 * @param int $audience
2134 * @param User|null $user
2135 * @return string
2136 */
2137 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2138 $this->load();
2139 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
2140 return '';
2141 } elseif ( $audience == self::FOR_THIS_USER
2142 && !$this->userCan( self::DELETED_COMMENT, $user )
2143 ) {
2144 return '';
2145 } else {
2146 return $this->description;
2147 }
2148 }
2149
2150 /**
2151 * @return bool|string
2152 */
2153 function getTimestamp() {
2154 $this->load();
2155
2156 return $this->timestamp;
2157 }
2158
2159 /**
2160 * @return bool|string
2161 */
2162 public function getDescriptionTouched() {
2163 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
2164 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
2165 // need to differentiate between null (uninitialized) and false (failed to load).
2166 if ( $this->descriptionTouched === null ) {
2167 $cond = [
2168 'page_namespace' => $this->title->getNamespace(),
2169 'page_title' => $this->title->getDBkey()
2170 ];
2171 $touched = $this->repo->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
2172 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
2173 }
2174
2175 return $this->descriptionTouched;
2176 }
2177
2178 /**
2179 * @return string
2180 */
2181 function getSha1() {
2182 $this->load();
2183 // Initialise now if necessary
2184 if ( $this->sha1 == '' && $this->fileExists ) {
2185 $this->lock(); // begin
2186
2187 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
2188 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
2189 $dbw = $this->repo->getMasterDB();
2190 $dbw->update( 'image',
2191 [ 'img_sha1' => $this->sha1 ],
2192 [ 'img_name' => $this->getName() ],
2193 __METHOD__ );
2194 $this->invalidateCache();
2195 }
2196
2197 $this->unlock(); // done
2198 }
2199
2200 return $this->sha1;
2201 }
2202
2203 /**
2204 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
2205 */
2206 function isCacheable() {
2207 $this->load();
2208
2209 // If extra data (metadata) was not loaded then it must have been large
2210 return $this->extraDataLoaded
2211 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
2212 }
2213
2214 /**
2215 * @return Status
2216 * @since 1.28
2217 */
2218 public function acquireFileLock() {
2219 return Status::wrap( $this->getRepo()->getBackend()->lockFiles(
2220 [ $this->getPath() ], LockManager::LOCK_EX, 10
2221 ) );
2222 }
2223
2224 /**
2225 * @return Status
2226 * @since 1.28
2227 */
2228 public function releaseFileLock() {
2229 return Status::wrap( $this->getRepo()->getBackend()->unlockFiles(
2230 [ $this->getPath() ], LockManager::LOCK_EX
2231 ) );
2232 }
2233
2234 /**
2235 * Start an atomic DB section and lock the image for update
2236 * or increments a reference counter if the lock is already held
2237 *
2238 * This method should not be used outside of LocalFile/LocalFile*Batch
2239 *
2240 * @throws LocalFileLockError Throws an error if the lock was not acquired
2241 * @return bool Whether the file lock owns/spawned the DB transaction
2242 */
2243 public function lock() {
2244 if ( !$this->locked ) {
2245 $logger = LoggerFactory::getInstance( 'LocalFile' );
2246
2247 $dbw = $this->repo->getMasterDB();
2248 $makesTransaction = !$dbw->trxLevel();
2249 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
2250 // T56736: use simple lock to handle when the file does not exist.
2251 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2252 // Also, that would cause contention on INSERT of similarly named rows.
2253 $status = $this->acquireFileLock(); // represents all versions of the file
2254 if ( !$status->isGood() ) {
2255 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2256 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2257
2258 throw new LocalFileLockError( $status );
2259 }
2260 // Release the lock *after* commit to avoid row-level contention.
2261 // Make sure it triggers on rollback() as well as commit() (T132921).
2262 $dbw->onTransactionResolution(
2263 function () use ( $logger ) {
2264 $status = $this->releaseFileLock();
2265 if ( !$status->isGood() ) {
2266 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2267 }
2268 },
2269 __METHOD__
2270 );
2271 // Callers might care if the SELECT snapshot is safely fresh
2272 $this->lockedOwnTrx = $makesTransaction;
2273 }
2274
2275 $this->locked++;
2276
2277 return $this->lockedOwnTrx;
2278 }
2279
2280 /**
2281 * Decrement the lock reference count and end the atomic section if it reaches zero
2282 *
2283 * This method should not be used outside of LocalFile/LocalFile*Batch
2284 *
2285 * The commit and loc release will happen when no atomic sections are active, which
2286 * may happen immediately or at some point after calling this
2287 */
2288 public function unlock() {
2289 if ( $this->locked ) {
2290 --$this->locked;
2291 if ( !$this->locked ) {
2292 $dbw = $this->repo->getMasterDB();
2293 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2294 $this->lockedOwnTrx = false;
2295 }
2296 }
2297 }
2298
2299 /**
2300 * @return Status
2301 */
2302 protected function readOnlyFatalStatus() {
2303 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2304 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2305 }
2306
2307 /**
2308 * Clean up any dangling locks
2309 */
2310 function __destruct() {
2311 $this->unlock();
2312 }
2313 } // LocalFile class
2314
2315 # ------------------------------------------------------------------------------
2316
2317 /**
2318 * Helper class for file deletion
2319 * @ingroup FileAbstraction
2320 */
2321 class LocalFileDeleteBatch {
2322 /** @var LocalFile */
2323 private $file;
2324
2325 /** @var string */
2326 private $reason;
2327
2328 /** @var array */
2329 private $srcRels = [];
2330
2331 /** @var array */
2332 private $archiveUrls = [];
2333
2334 /** @var array Items to be processed in the deletion batch */
2335 private $deletionBatch;
2336
2337 /** @var bool Whether to suppress all suppressable fields when deleting */
2338 private $suppress;
2339
2340 /** @var Status */
2341 private $status;
2342
2343 /** @var User */
2344 private $user;
2345
2346 /**
2347 * @param File $file
2348 * @param string $reason
2349 * @param bool $suppress
2350 * @param User|null $user
2351 */
2352 function __construct( File $file, $reason = '', $suppress = false, $user = null ) {
2353 $this->file = $file;
2354 $this->reason = $reason;
2355 $this->suppress = $suppress;
2356 if ( $user ) {
2357 $this->user = $user;
2358 } else {
2359 global $wgUser;
2360 $this->user = $wgUser;
2361 }
2362 $this->status = $file->repo->newGood();
2363 }
2364
2365 public function addCurrent() {
2366 $this->srcRels['.'] = $this->file->getRel();
2367 }
2368
2369 /**
2370 * @param string $oldName
2371 */
2372 public function addOld( $oldName ) {
2373 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
2374 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
2375 }
2376
2377 /**
2378 * Add the old versions of the image to the batch
2379 * @return string[] List of archive names from old versions
2380 */
2381 public function addOlds() {
2382 $archiveNames = [];
2383
2384 $dbw = $this->file->repo->getMasterDB();
2385 $result = $dbw->select( 'oldimage',
2386 [ 'oi_archive_name' ],
2387 [ 'oi_name' => $this->file->getName() ],
2388 __METHOD__
2389 );
2390
2391 foreach ( $result as $row ) {
2392 $this->addOld( $row->oi_archive_name );
2393 $archiveNames[] = $row->oi_archive_name;
2394 }
2395
2396 return $archiveNames;
2397 }
2398
2399 /**
2400 * @return array
2401 */
2402 protected function getOldRels() {
2403 if ( !isset( $this->srcRels['.'] ) ) {
2404 $oldRels =& $this->srcRels;
2405 $deleteCurrent = false;
2406 } else {
2407 $oldRels = $this->srcRels;
2408 unset( $oldRels['.'] );
2409 $deleteCurrent = true;
2410 }
2411
2412 return [ $oldRels, $deleteCurrent ];
2413 }
2414
2415 /**
2416 * @return array
2417 */
2418 protected function getHashes() {
2419 $hashes = [];
2420 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2421
2422 if ( $deleteCurrent ) {
2423 $hashes['.'] = $this->file->getSha1();
2424 }
2425
2426 if ( count( $oldRels ) ) {
2427 $dbw = $this->file->repo->getMasterDB();
2428 $res = $dbw->select(
2429 'oldimage',
2430 [ 'oi_archive_name', 'oi_sha1' ],
2431 [ 'oi_archive_name' => array_keys( $oldRels ),
2432 'oi_name' => $this->file->getName() ], // performance
2433 __METHOD__
2434 );
2435
2436 foreach ( $res as $row ) {
2437 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
2438 // Get the hash from the file
2439 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2440 $props = $this->file->repo->getFileProps( $oldUrl );
2441
2442 if ( $props['fileExists'] ) {
2443 // Upgrade the oldimage row
2444 $dbw->update( 'oldimage',
2445 [ 'oi_sha1' => $props['sha1'] ],
2446 [ 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ],
2447 __METHOD__ );
2448 $hashes[$row->oi_archive_name] = $props['sha1'];
2449 } else {
2450 $hashes[$row->oi_archive_name] = false;
2451 }
2452 } else {
2453 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2454 }
2455 }
2456 }
2457
2458 $missing = array_diff_key( $this->srcRels, $hashes );
2459
2460 foreach ( $missing as $name => $rel ) {
2461 $this->status->error( 'filedelete-old-unregistered', $name );
2462 }
2463
2464 foreach ( $hashes as $name => $hash ) {
2465 if ( !$hash ) {
2466 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2467 unset( $hashes[$name] );
2468 }
2469 }
2470
2471 return $hashes;
2472 }
2473
2474 protected function doDBInserts() {
2475 global $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage;
2476
2477 $now = time();
2478 $dbw = $this->file->repo->getMasterDB();
2479
2480 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
2481 $actorMigration = ActorMigration::newMigration();
2482
2483 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2484 $encUserId = $dbw->addQuotes( $this->user->getId() );
2485 $encGroup = $dbw->addQuotes( 'deleted' );
2486 $ext = $this->file->getExtension();
2487 $dotExt = $ext === '' ? '' : ".$ext";
2488 $encExt = $dbw->addQuotes( $dotExt );
2489 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2490
2491 // Bitfields to further suppress the content
2492 if ( $this->suppress ) {
2493 $bitfield = Revision::SUPPRESSED_ALL;
2494 } else {
2495 $bitfield = 'oi_deleted';
2496 }
2497
2498 if ( $deleteCurrent ) {
2499 $tables = [ 'image' ];
2500 $fields = [
2501 'fa_storage_group' => $encGroup,
2502 'fa_storage_key' => $dbw->conditional(
2503 [ 'img_sha1' => '' ],
2504 $dbw->addQuotes( '' ),
2505 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2506 ),
2507 'fa_deleted_user' => $encUserId,
2508 'fa_deleted_timestamp' => $encTimestamp,
2509 'fa_deleted' => $this->suppress ? $bitfield : 0,
2510 'fa_name' => 'img_name',
2511 'fa_archive_name' => 'NULL',
2512 'fa_size' => 'img_size',
2513 'fa_width' => 'img_width',
2514 'fa_height' => 'img_height',
2515 'fa_metadata' => 'img_metadata',
2516 'fa_bits' => 'img_bits',
2517 'fa_media_type' => 'img_media_type',
2518 'fa_major_mime' => 'img_major_mime',
2519 'fa_minor_mime' => 'img_minor_mime',
2520 'fa_timestamp' => 'img_timestamp',
2521 'fa_sha1' => 'img_sha1'
2522 ];
2523 $joins = [];
2524
2525 $fields += array_map(
2526 [ $dbw, 'addQuotes' ],
2527 $commentStore->insert( $dbw, 'fa_deleted_reason', $this->reason )
2528 );
2529
2530 if ( $wgCommentTableSchemaMigrationStage <= MIGRATION_WRITE_BOTH ) {
2531 $fields['fa_description'] = 'img_description';
2532 }
2533 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH ) {
2534 $fields['fa_description_id'] = 'img_description_id';
2535 }
2536
2537 if ( $wgCommentTableSchemaMigrationStage !== MIGRATION_OLD &&
2538 $wgCommentTableSchemaMigrationStage !== MIGRATION_NEW
2539 ) {
2540 // Upgrade any rows that are still old-style. Otherwise an upgrade
2541 // might be missed if a deletion happens while the migration script
2542 // is running.
2543 $res = $dbw->select(
2544 [ 'image' ],
2545 [ 'img_name', 'img_description' ],
2546 [
2547 'img_name' => $this->file->getName(),
2548 'img_description_id' => 0,
2549 ],
2550 __METHOD__
2551 );
2552 foreach ( $res as $row ) {
2553 $imgFields = $commentStore->insert( $dbw, 'img_description', $row->img_description );
2554 $dbw->update(
2555 'image',
2556 $imgFields,
2557 [ 'img_name' => $row->img_name ],
2558 __METHOD__
2559 );
2560 }
2561 }
2562
2563 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_OLD ) {
2564 $fields['fa_user'] = 'img_user';
2565 $fields['fa_user_text'] = 'img_user_text';
2566 }
2567 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
2568 $fields['fa_actor'] = 'img_actor';
2569 }
2570
2571 if (
2572 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_BOTH ) === SCHEMA_COMPAT_WRITE_BOTH
2573 ) {
2574 // Upgrade any rows that are still old-style. Otherwise an upgrade
2575 // might be missed if a deletion happens while the migration script
2576 // is running.
2577 $res = $dbw->select(
2578 [ 'image' ],
2579 [ 'img_name', 'img_user', 'img_user_text' ],
2580 [ 'img_name' => $this->file->getName(), 'img_actor' => 0 ],
2581 __METHOD__
2582 );
2583 foreach ( $res as $row ) {
2584 $actorId = User::newFromAnyId( $row->img_user, $row->img_user_text, null )->getActorId( $dbw );
2585 $dbw->update(
2586 'image',
2587 [ 'img_actor' => $actorId ],
2588 [ 'img_name' => $row->img_name, 'img_actor' => 0 ],
2589 __METHOD__
2590 );
2591 }
2592 }
2593
2594 $dbw->insertSelect( 'filearchive', $tables, $fields,
2595 [ 'img_name' => $this->file->getName() ], __METHOD__, [], [], $joins );
2596 }
2597
2598 if ( count( $oldRels ) ) {
2599 $fileQuery = OldLocalFile::getQueryInfo();
2600 $res = $dbw->select(
2601 $fileQuery['tables'],
2602 $fileQuery['fields'],
2603 [
2604 'oi_name' => $this->file->getName(),
2605 'oi_archive_name' => array_keys( $oldRels )
2606 ],
2607 __METHOD__,
2608 [ 'FOR UPDATE' ],
2609 $fileQuery['joins']
2610 );
2611 $rowsInsert = [];
2612 if ( $res->numRows() ) {
2613 $reason = $commentStore->createComment( $dbw, $this->reason );
2614 foreach ( $res as $row ) {
2615 $comment = $commentStore->getComment( 'oi_description', $row );
2616 $user = User::newFromAnyId( $row->oi_user, $row->oi_user_text, $row->oi_actor );
2617 $rowsInsert[] = [
2618 // Deletion-specific fields
2619 'fa_storage_group' => 'deleted',
2620 'fa_storage_key' => ( $row->oi_sha1 === '' )
2621 ? ''
2622 : "{$row->oi_sha1}{$dotExt}",
2623 'fa_deleted_user' => $this->user->getId(),
2624 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2625 // Counterpart fields
2626 'fa_deleted' => $this->suppress ? $bitfield : $row->oi_deleted,
2627 'fa_name' => $row->oi_name,
2628 'fa_archive_name' => $row->oi_archive_name,
2629 'fa_size' => $row->oi_size,
2630 'fa_width' => $row->oi_width,
2631 'fa_height' => $row->oi_height,
2632 'fa_metadata' => $row->oi_metadata,
2633 'fa_bits' => $row->oi_bits,
2634 'fa_media_type' => $row->oi_media_type,
2635 'fa_major_mime' => $row->oi_major_mime,
2636 'fa_minor_mime' => $row->oi_minor_mime,
2637 'fa_timestamp' => $row->oi_timestamp,
2638 'fa_sha1' => $row->oi_sha1
2639 ] + $commentStore->insert( $dbw, 'fa_deleted_reason', $reason )
2640 + $commentStore->insert( $dbw, 'fa_description', $comment )
2641 + $actorMigration->getInsertValues( $dbw, 'fa_user', $user );
2642 }
2643 }
2644
2645 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__ );
2646 }
2647 }
2648
2649 function doDBDeletes() {
2650 $dbw = $this->file->repo->getMasterDB();
2651 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2652
2653 if ( count( $oldRels ) ) {
2654 $dbw->delete( 'oldimage',
2655 [
2656 'oi_name' => $this->file->getName(),
2657 'oi_archive_name' => array_keys( $oldRels )
2658 ], __METHOD__ );
2659 }
2660
2661 if ( $deleteCurrent ) {
2662 $dbw->delete( 'image', [ 'img_name' => $this->file->getName() ], __METHOD__ );
2663 }
2664 }
2665
2666 /**
2667 * Run the transaction
2668 * @return Status
2669 */
2670 public function execute() {
2671 $repo = $this->file->getRepo();
2672 $this->file->lock();
2673
2674 // Prepare deletion batch
2675 $hashes = $this->getHashes();
2676 $this->deletionBatch = [];
2677 $ext = $this->file->getExtension();
2678 $dotExt = $ext === '' ? '' : ".$ext";
2679
2680 foreach ( $this->srcRels as $name => $srcRel ) {
2681 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2682 if ( isset( $hashes[$name] ) ) {
2683 $hash = $hashes[$name];
2684 $key = $hash . $dotExt;
2685 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2686 $this->deletionBatch[$name] = [ $srcRel, $dstRel ];
2687 }
2688 }
2689
2690 if ( !$repo->hasSha1Storage() ) {
2691 // Removes non-existent file from the batch, so we don't get errors.
2692 // This also handles files in the 'deleted' zone deleted via revision deletion.
2693 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch );
2694 if ( !$checkStatus->isGood() ) {
2695 $this->status->merge( $checkStatus );
2696 return $this->status;
2697 }
2698 $this->deletionBatch = $checkStatus->value;
2699
2700 // Execute the file deletion batch
2701 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2702 if ( !$status->isGood() ) {
2703 $this->status->merge( $status );
2704 }
2705 }
2706
2707 if ( !$this->status->isOK() ) {
2708 // Critical file deletion error; abort
2709 $this->file->unlock();
2710
2711 return $this->status;
2712 }
2713
2714 // Copy the image/oldimage rows to filearchive
2715 $this->doDBInserts();
2716 // Delete image/oldimage rows
2717 $this->doDBDeletes();
2718
2719 // Commit and return
2720 $this->file->unlock();
2721
2722 return $this->status;
2723 }
2724
2725 /**
2726 * Removes non-existent files from a deletion batch.
2727 * @param array $batch
2728 * @return Status
2729 */
2730 protected function removeNonexistentFiles( $batch ) {
2731 $files = $newBatch = [];
2732
2733 foreach ( $batch as $batchItem ) {
2734 list( $src, ) = $batchItem;
2735 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2736 }
2737
2738 $result = $this->file->repo->fileExistsBatch( $files );
2739 if ( in_array( null, $result, true ) ) {
2740 return Status::newFatal( 'backend-fail-internal',
2741 $this->file->repo->getBackend()->getName() );
2742 }
2743
2744 foreach ( $batch as $batchItem ) {
2745 if ( $result[$batchItem[0]] ) {
2746 $newBatch[] = $batchItem;
2747 }
2748 }
2749
2750 return Status::newGood( $newBatch );
2751 }
2752 }
2753
2754 # ------------------------------------------------------------------------------
2755
2756 /**
2757 * Helper class for file undeletion
2758 * @ingroup FileAbstraction
2759 */
2760 class LocalFileRestoreBatch {
2761 /** @var LocalFile */
2762 private $file;
2763
2764 /** @var string[] List of file IDs to restore */
2765 private $cleanupBatch;
2766
2767 /** @var string[] List of file IDs to restore */
2768 private $ids;
2769
2770 /** @var bool Add all revisions of the file */
2771 private $all;
2772
2773 /** @var bool Whether to remove all settings for suppressed fields */
2774 private $unsuppress = false;
2775
2776 /**
2777 * @param File $file
2778 * @param bool $unsuppress
2779 */
2780 function __construct( File $file, $unsuppress = false ) {
2781 $this->file = $file;
2782 $this->cleanupBatch = [];
2783 $this->ids = [];
2784 $this->unsuppress = $unsuppress;
2785 }
2786
2787 /**
2788 * Add a file by ID
2789 * @param int $fa_id
2790 */
2791 public function addId( $fa_id ) {
2792 $this->ids[] = $fa_id;
2793 }
2794
2795 /**
2796 * Add a whole lot of files by ID
2797 * @param int[] $ids
2798 */
2799 public function addIds( $ids ) {
2800 $this->ids = array_merge( $this->ids, $ids );
2801 }
2802
2803 /**
2804 * Add all revisions of the file
2805 */
2806 public function addAll() {
2807 $this->all = true;
2808 }
2809
2810 /**
2811 * Run the transaction, except the cleanup batch.
2812 * The cleanup batch should be run in a separate transaction, because it locks different
2813 * rows and there's no need to keep the image row locked while it's acquiring those locks
2814 * The caller may have its own transaction open.
2815 * So we save the batch and let the caller call cleanup()
2816 * @return Status
2817 */
2818 public function execute() {
2819 /** @var Language */
2820 global $wgLang;
2821
2822 $repo = $this->file->getRepo();
2823 if ( !$this->all && !$this->ids ) {
2824 // Do nothing
2825 return $repo->newGood();
2826 }
2827
2828 $lockOwnsTrx = $this->file->lock();
2829
2830 $dbw = $this->file->repo->getMasterDB();
2831
2832 $commentStore = MediaWikiServices::getInstance()->getCommentStore();
2833 $actorMigration = ActorMigration::newMigration();
2834
2835 $status = $this->file->repo->newGood();
2836
2837 $exists = (bool)$dbw->selectField( 'image', '1',
2838 [ 'img_name' => $this->file->getName() ],
2839 __METHOD__,
2840 // The lock() should already prevents changes, but this still may need
2841 // to bypass any transaction snapshot. However, if lock() started the
2842 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2843 $lockOwnsTrx ? [] : [ 'LOCK IN SHARE MODE' ]
2844 );
2845
2846 // Fetch all or selected archived revisions for the file,
2847 // sorted from the most recent to the oldest.
2848 $conditions = [ 'fa_name' => $this->file->getName() ];
2849
2850 if ( !$this->all ) {
2851 $conditions['fa_id'] = $this->ids;
2852 }
2853
2854 $arFileQuery = ArchivedFile::getQueryInfo();
2855 $result = $dbw->select(
2856 $arFileQuery['tables'],
2857 $arFileQuery['fields'],
2858 $conditions,
2859 __METHOD__,
2860 [ 'ORDER BY' => 'fa_timestamp DESC' ],
2861 $arFileQuery['joins']
2862 );
2863
2864 $idsPresent = [];
2865 $storeBatch = [];
2866 $insertBatch = [];
2867 $insertCurrent = false;
2868 $deleteIds = [];
2869 $first = true;
2870 $archiveNames = [];
2871
2872 foreach ( $result as $row ) {
2873 $idsPresent[] = $row->fa_id;
2874
2875 if ( $row->fa_name != $this->file->getName() ) {
2876 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2877 $status->failCount++;
2878 continue;
2879 }
2880
2881 if ( $row->fa_storage_key == '' ) {
2882 // Revision was missing pre-deletion
2883 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2884 $status->failCount++;
2885 continue;
2886 }
2887
2888 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2889 $row->fa_storage_key;
2890 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2891
2892 if ( isset( $row->fa_sha1 ) ) {
2893 $sha1 = $row->fa_sha1;
2894 } else {
2895 // old row, populate from key
2896 $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2897 }
2898
2899 # Fix leading zero
2900 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2901 $sha1 = substr( $sha1, 1 );
2902 }
2903
2904 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2905 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2906 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2907 || is_null( $row->fa_metadata )
2908 ) {
2909 // Refresh our metadata
2910 // Required for a new current revision; nice for older ones too. :)
2911 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2912 } else {
2913 $props = [
2914 'minor_mime' => $row->fa_minor_mime,
2915 'major_mime' => $row->fa_major_mime,
2916 'media_type' => $row->fa_media_type,
2917 'metadata' => $row->fa_metadata
2918 ];
2919 }
2920
2921 $comment = $commentStore->getComment( 'fa_description', $row );
2922 $user = User::newFromAnyId( $row->fa_user, $row->fa_user_text, $row->fa_actor );
2923 if ( $first && !$exists ) {
2924 // This revision will be published as the new current version
2925 $destRel = $this->file->getRel();
2926 $commentFields = $commentStore->insert( $dbw, 'img_description', $comment );
2927 $actorFields = $actorMigration->getInsertValues( $dbw, 'img_user', $user );
2928 $insertCurrent = [
2929 'img_name' => $row->fa_name,
2930 'img_size' => $row->fa_size,
2931 'img_width' => $row->fa_width,
2932 'img_height' => $row->fa_height,
2933 'img_metadata' => $props['metadata'],
2934 'img_bits' => $row->fa_bits,
2935 'img_media_type' => $props['media_type'],
2936 'img_major_mime' => $props['major_mime'],
2937 'img_minor_mime' => $props['minor_mime'],
2938 'img_timestamp' => $row->fa_timestamp,
2939 'img_sha1' => $sha1
2940 ] + $commentFields + $actorFields;
2941
2942 // The live (current) version cannot be hidden!
2943 if ( !$this->unsuppress && $row->fa_deleted ) {
2944 $status->fatal( 'undeleterevdel' );
2945 $this->file->unlock();
2946 return $status;
2947 }
2948 } else {
2949 $archiveName = $row->fa_archive_name;
2950
2951 if ( $archiveName == '' ) {
2952 // This was originally a current version; we
2953 // have to devise a new archive name for it.
2954 // Format is <timestamp of archiving>!<name>
2955 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2956
2957 do {
2958 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2959 $timestamp++;
2960 } while ( isset( $archiveNames[$archiveName] ) );
2961 }
2962
2963 $archiveNames[$archiveName] = true;
2964 $destRel = $this->file->getArchiveRel( $archiveName );
2965 $insertBatch[] = [
2966 'oi_name' => $row->fa_name,
2967 'oi_archive_name' => $archiveName,
2968 'oi_size' => $row->fa_size,
2969 'oi_width' => $row->fa_width,
2970 'oi_height' => $row->fa_height,
2971 'oi_bits' => $row->fa_bits,
2972 'oi_timestamp' => $row->fa_timestamp,
2973 'oi_metadata' => $props['metadata'],
2974 'oi_media_type' => $props['media_type'],
2975 'oi_major_mime' => $props['major_mime'],
2976 'oi_minor_mime' => $props['minor_mime'],
2977 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2978 'oi_sha1' => $sha1
2979 ] + $commentStore->insert( $dbw, 'oi_description', $comment )
2980 + $actorMigration->getInsertValues( $dbw, 'oi_user', $user );
2981 }
2982
2983 $deleteIds[] = $row->fa_id;
2984
2985 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2986 // private files can stay where they are
2987 $status->successCount++;
2988 } else {
2989 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2990 $this->cleanupBatch[] = $row->fa_storage_key;
2991 }
2992
2993 $first = false;
2994 }
2995
2996 unset( $result );
2997
2998 // Add a warning to the status object for missing IDs
2999 $missingIds = array_diff( $this->ids, $idsPresent );
3000
3001 foreach ( $missingIds as $id ) {
3002 $status->error( 'undelete-missing-filearchive', $id );
3003 }
3004
3005 if ( !$repo->hasSha1Storage() ) {
3006 // Remove missing files from batch, so we don't get errors when undeleting them
3007 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
3008 if ( !$checkStatus->isGood() ) {
3009 $status->merge( $checkStatus );
3010 return $status;
3011 }
3012 $storeBatch = $checkStatus->value;
3013
3014 // Run the store batch
3015 // Use the OVERWRITE_SAME flag to smooth over a common error
3016 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
3017 $status->merge( $storeStatus );
3018
3019 if ( !$status->isGood() ) {
3020 // Even if some files could be copied, fail entirely as that is the
3021 // easiest thing to do without data loss
3022 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
3023 $status->setOK( false );
3024 $this->file->unlock();
3025
3026 return $status;
3027 }
3028 }
3029
3030 // Run the DB updates
3031 // Because we have locked the image row, key conflicts should be rare.
3032 // If they do occur, we can roll back the transaction at this time with
3033 // no data loss, but leaving unregistered files scattered throughout the
3034 // public zone.
3035 // This is not ideal, which is why it's important to lock the image row.
3036 if ( $insertCurrent ) {
3037 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
3038 }
3039
3040 if ( $insertBatch ) {
3041 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
3042 }
3043
3044 if ( $deleteIds ) {
3045 $dbw->delete( 'filearchive',
3046 [ 'fa_id' => $deleteIds ],
3047 __METHOD__ );
3048 }
3049
3050 // If store batch is empty (all files are missing), deletion is to be considered successful
3051 if ( $status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
3052 if ( !$exists ) {
3053 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
3054
3055 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
3056
3057 $this->file->purgeEverything();
3058 } else {
3059 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
3060 $this->file->purgeDescription();
3061 }
3062 }
3063
3064 $this->file->unlock();
3065
3066 return $status;
3067 }
3068
3069 /**
3070 * Removes non-existent files from a store batch.
3071 * @param array $triplets
3072 * @return Status
3073 */
3074 protected function removeNonexistentFiles( $triplets ) {
3075 $files = $filteredTriplets = [];
3076 foreach ( $triplets as $file ) {
3077 $files[$file[0]] = $file[0];
3078 }
3079
3080 $result = $this->file->repo->fileExistsBatch( $files );
3081 if ( in_array( null, $result, true ) ) {
3082 return Status::newFatal( 'backend-fail-internal',
3083 $this->file->repo->getBackend()->getName() );
3084 }
3085
3086 foreach ( $triplets as $file ) {
3087 if ( $result[$file[0]] ) {
3088 $filteredTriplets[] = $file;
3089 }
3090 }
3091
3092 return Status::newGood( $filteredTriplets );
3093 }
3094
3095 /**
3096 * Removes non-existent files from a cleanup batch.
3097 * @param string[] $batch
3098 * @return string[]
3099 */
3100 protected function removeNonexistentFromCleanup( $batch ) {
3101 $files = $newBatch = [];
3102 $repo = $this->file->repo;
3103
3104 foreach ( $batch as $file ) {
3105 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
3106 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
3107 }
3108
3109 $result = $repo->fileExistsBatch( $files );
3110
3111 foreach ( $batch as $file ) {
3112 if ( $result[$file] ) {
3113 $newBatch[] = $file;
3114 }
3115 }
3116
3117 return $newBatch;
3118 }
3119
3120 /**
3121 * Delete unused files in the deleted zone.
3122 * This should be called from outside the transaction in which execute() was called.
3123 * @return Status
3124 */
3125 public function cleanup() {
3126 if ( !$this->cleanupBatch ) {
3127 return $this->file->repo->newGood();
3128 }
3129
3130 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
3131
3132 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
3133
3134 return $status;
3135 }
3136
3137 /**
3138 * Cleanup a failed batch. The batch was only partially successful, so
3139 * rollback by removing all items that were successfully copied.
3140 *
3141 * @param Status $storeStatus
3142 * @param array[] $storeBatch
3143 */
3144 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
3145 $cleanupBatch = [];
3146
3147 foreach ( $storeStatus->success as $i => $success ) {
3148 // Check if this item of the batch was successfully copied
3149 if ( $success ) {
3150 // Item was successfully copied and needs to be removed again
3151 // Extract ($dstZone, $dstRel) from the batch
3152 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
3153 }
3154 }
3155 $this->file->repo->cleanupBatch( $cleanupBatch );
3156 }
3157 }
3158
3159 # ------------------------------------------------------------------------------
3160
3161 /**
3162 * Helper class for file movement
3163 * @ingroup FileAbstraction
3164 */
3165 class LocalFileMoveBatch {
3166 /** @var LocalFile */
3167 protected $file;
3168
3169 /** @var Title */
3170 protected $target;
3171
3172 protected $cur;
3173
3174 protected $olds;
3175
3176 protected $oldCount;
3177
3178 protected $archive;
3179
3180 /** @var IDatabase */
3181 protected $db;
3182
3183 /**
3184 * @param File $file
3185 * @param Title $target
3186 */
3187 function __construct( File $file, Title $target ) {
3188 $this->file = $file;
3189 $this->target = $target;
3190 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
3191 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
3192 $this->oldName = $this->file->getName();
3193 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
3194 $this->oldRel = $this->oldHash . $this->oldName;
3195 $this->newRel = $this->newHash . $this->newName;
3196 $this->db = $file->getRepo()->getMasterDB();
3197 }
3198
3199 /**
3200 * Add the current image to the batch
3201 */
3202 public function addCurrent() {
3203 $this->cur = [ $this->oldRel, $this->newRel ];
3204 }
3205
3206 /**
3207 * Add the old versions of the image to the batch
3208 * @return string[] List of archive names from old versions
3209 */
3210 public function addOlds() {
3211 $archiveBase = 'archive';
3212 $this->olds = [];
3213 $this->oldCount = 0;
3214 $archiveNames = [];
3215
3216 $result = $this->db->select( 'oldimage',
3217 [ 'oi_archive_name', 'oi_deleted' ],
3218 [ 'oi_name' => $this->oldName ],
3219 __METHOD__,
3220 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
3221 );
3222
3223 foreach ( $result as $row ) {
3224 $archiveNames[] = $row->oi_archive_name;
3225 $oldName = $row->oi_archive_name;
3226 $bits = explode( '!', $oldName, 2 );
3227
3228 if ( count( $bits ) != 2 ) {
3229 wfDebug( "Old file name missing !: '$oldName' \n" );
3230 continue;
3231 }
3232
3233 list( $timestamp, $filename ) = $bits;
3234
3235 if ( $this->oldName != $filename ) {
3236 wfDebug( "Old file name doesn't match: '$oldName' \n" );
3237 continue;
3238 }
3239
3240 $this->oldCount++;
3241
3242 // Do we want to add those to oldCount?
3243 if ( $row->oi_deleted & File::DELETED_FILE ) {
3244 continue;
3245 }
3246
3247 $this->olds[] = [
3248 "{$archiveBase}/{$this->oldHash}{$oldName}",
3249 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
3250 ];
3251 }
3252
3253 return $archiveNames;
3254 }
3255
3256 /**
3257 * Perform the move.
3258 * @return Status
3259 */
3260 public function execute() {
3261 $repo = $this->file->repo;
3262 $status = $repo->newGood();
3263 $destFile = wfLocalFile( $this->target );
3264
3265 $this->file->lock(); // begin
3266 $destFile->lock(); // quickly fail if destination is not available
3267
3268 $triplets = $this->getMoveTriplets();
3269 $checkStatus = $this->removeNonexistentFiles( $triplets );
3270 if ( !$checkStatus->isGood() ) {
3271 $destFile->unlock();
3272 $this->file->unlock();
3273 $status->merge( $checkStatus ); // couldn't talk to file backend
3274 return $status;
3275 }
3276 $triplets = $checkStatus->value;
3277
3278 // Verify the file versions metadata in the DB.
3279 $statusDb = $this->verifyDBUpdates();
3280 if ( !$statusDb->isGood() ) {
3281 $destFile->unlock();
3282 $this->file->unlock();
3283 $statusDb->setOK( false );
3284
3285 return $statusDb;
3286 }
3287
3288 if ( !$repo->hasSha1Storage() ) {
3289 // Copy the files into their new location.
3290 // If a prior process fataled copying or cleaning up files we tolerate any
3291 // of the existing files if they are identical to the ones being stored.
3292 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
3293 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
3294 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
3295 if ( !$statusMove->isGood() ) {
3296 // Delete any files copied over (while the destination is still locked)
3297 $this->cleanupTarget( $triplets );
3298 $destFile->unlock();
3299 $this->file->unlock();
3300 wfDebugLog( 'imagemove', "Error in moving files: "
3301 . $statusMove->getWikiText( false, false, 'en' ) );
3302 $statusMove->setOK( false );
3303
3304 return $statusMove;
3305 }
3306 $status->merge( $statusMove );
3307 }
3308
3309 // Rename the file versions metadata in the DB.
3310 $this->doDBUpdates();
3311
3312 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
3313 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
3314
3315 $destFile->unlock();
3316 $this->file->unlock(); // done
3317
3318 // Everything went ok, remove the source files
3319 $this->cleanupSource( $triplets );
3320
3321 $status->merge( $statusDb );
3322
3323 return $status;
3324 }
3325
3326 /**
3327 * Verify the database updates and return a new Status indicating how
3328 * many rows would be updated.
3329 *
3330 * @return Status
3331 */
3332 protected function verifyDBUpdates() {
3333 $repo = $this->file->repo;
3334 $status = $repo->newGood();
3335 $dbw = $this->db;
3336
3337 $hasCurrent = $dbw->lockForUpdate(
3338 'image',
3339 [ 'img_name' => $this->oldName ],
3340 __METHOD__
3341 );
3342 $oldRowCount = $dbw->lockForUpdate(
3343 'oldimage',
3344 [ 'oi_name' => $this->oldName ],
3345 __METHOD__
3346 );
3347
3348 if ( $hasCurrent ) {
3349 $status->successCount++;
3350 } else {
3351 $status->failCount++;
3352 }
3353 $status->successCount += $oldRowCount;
3354 // T36934: oldCount is based on files that actually exist.
3355 // There may be more DB rows than such files, in which case $affected
3356 // can be greater than $total. We use max() to avoid negatives here.
3357 $status->failCount += max( 0, $this->oldCount - $oldRowCount );
3358 if ( $status->failCount ) {
3359 $status->error( 'imageinvalidfilename' );
3360 }
3361
3362 return $status;
3363 }
3364
3365 /**
3366 * Do the database updates and return a new Status indicating how
3367 * many rows where updated.
3368 */
3369 protected function doDBUpdates() {
3370 $dbw = $this->db;
3371
3372 // Update current image
3373 $dbw->update(
3374 'image',
3375 [ 'img_name' => $this->newName ],
3376 [ 'img_name' => $this->oldName ],
3377 __METHOD__
3378 );
3379
3380 // Update old images
3381 $dbw->update(
3382 'oldimage',
3383 [
3384 'oi_name' => $this->newName,
3385 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3386 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3387 ],
3388 [ 'oi_name' => $this->oldName ],
3389 __METHOD__
3390 );
3391 }
3392
3393 /**
3394 * Generate triplets for FileRepo::storeBatch().
3395 * @return array[]
3396 */
3397 protected function getMoveTriplets() {
3398 $moves = array_merge( [ $this->cur ], $this->olds );
3399 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3400
3401 foreach ( $moves as $move ) {
3402 // $move: (oldRelativePath, newRelativePath)
3403 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3404 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3405 wfDebugLog(
3406 'imagemove',
3407 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3408 );
3409 }
3410
3411 return $triplets;
3412 }
3413
3414 /**
3415 * Removes non-existent files from move batch.
3416 * @param array $triplets
3417 * @return Status
3418 */
3419 protected function removeNonexistentFiles( $triplets ) {
3420 $files = [];
3421
3422 foreach ( $triplets as $file ) {
3423 $files[$file[0]] = $file[0];
3424 }
3425
3426 $result = $this->file->repo->fileExistsBatch( $files );
3427 if ( in_array( null, $result, true ) ) {
3428 return Status::newFatal( 'backend-fail-internal',
3429 $this->file->repo->getBackend()->getName() );
3430 }
3431
3432 $filteredTriplets = [];
3433 foreach ( $triplets as $file ) {
3434 if ( $result[$file[0]] ) {
3435 $filteredTriplets[] = $file;
3436 } else {
3437 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3438 }
3439 }
3440
3441 return Status::newGood( $filteredTriplets );
3442 }
3443
3444 /**
3445 * Cleanup a partially moved array of triplets by deleting the target
3446 * files. Called if something went wrong half way.
3447 * @param array[] $triplets
3448 */
3449 protected function cleanupTarget( $triplets ) {
3450 // Create dest pairs from the triplets
3451 $pairs = [];
3452 foreach ( $triplets as $triplet ) {
3453 // $triplet: (old source virtual URL, dst zone, dest rel)
3454 $pairs[] = [ $triplet[1], $triplet[2] ];
3455 }
3456
3457 $this->file->repo->cleanupBatch( $pairs );
3458 }
3459
3460 /**
3461 * Cleanup a fully moved array of triplets by deleting the source files.
3462 * Called at the end of the move process if everything else went ok.
3463 * @param array[] $triplets
3464 */
3465 protected function cleanupSource( $triplets ) {
3466 // Create source file names from the triplets
3467 $files = [];
3468 foreach ( $triplets as $triplet ) {
3469 $files[] = $triplet[0];
3470 }
3471
3472 $this->file->repo->cleanupBatch( $files );
3473 }
3474 }
3475
3476 class LocalFileLockError extends ErrorPageError {
3477 public function __construct( Status $status ) {
3478 parent::__construct(
3479 'actionfailed',
3480 $status->getMessage()
3481 );
3482 }
3483
3484 public function report() {
3485 global $wgOut;
3486 $wgOut->setStatusCode( 429 );
3487 parent::report();
3488 }
3489 }