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