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