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