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