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