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