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