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