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