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