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