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