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