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