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