Merge "Remove wfSetBit()/wfSetVar() calls in DatabaseBase"
[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 // Associate new page revision id
1484 $logEntry->setAssociatedRevId( $status->value['revision']->getId() );
1485 }
1486 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1487 // which is triggered on $descTitle by doEditContent() above.
1488 if ( isset( $status->value['revision'] ) ) {
1489 /** @var $rev Revision */
1490 $rev = $status->value['revision'];
1491 $updateLogPage = $rev->getPage();
1492 }
1493 } else {
1494 # Existing file page: invalidate description page cache
1495 $wikiPage->getTitle()->invalidateCache();
1496 $wikiPage->getTitle()->purgeSquid();
1497 # Allow the new file version to be patrolled from the page footer
1498 Article::purgePatrolFooterCache( $descId );
1499 }
1500
1501 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1502 # but setAssociatedRevId() wasn't called at that point yet...
1503 $logParams = $logEntry->getParameters();
1504 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1505 $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ];
1506 if ( $updateLogPage ) {
1507 # Also log page, in case where we just created it above
1508 $update['log_page'] = $updateLogPage;
1509 }
1510 $this->getRepo()->getMasterDB()->update(
1511 'logging',
1512 $update,
1513 [ 'log_id' => $logId ],
1514 __METHOD__
1515 );
1516 $this->getRepo()->getMasterDB()->insert(
1517 'log_search',
1518 [
1519 'ls_field' => 'associated_rev_id',
1520 'ls_value' => $logEntry->getAssociatedRevId(),
1521 'ls_log_id' => $logId,
1522 ],
1523 __METHOD__
1524 );
1525
1526 # Add change tags, if any
1527 if ( $tags ) {
1528 $logEntry->setTags( $tags );
1529 }
1530
1531 # Uploads can be patrolled
1532 $logEntry->setIsPatrollable( true );
1533
1534 # Now that the log entry is up-to-date, make an RC entry.
1535 $logEntry->publish( $logId );
1536
1537 # Run hook for other updates (typically more cache purging)
1538 Hooks::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1539
1540 if ( $reupload ) {
1541 # Delete old thumbnails
1542 $this->purgeThumbnails();
1543 # Remove the old file from the CDN cache
1544 DeferredUpdates::addUpdate(
1545 new CdnCacheUpdate( [ $this->getUrl() ] ),
1546 DeferredUpdates::PRESEND
1547 );
1548 } else {
1549 # Update backlink pages pointing to this title if created
1550 LinksUpdate::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1551 }
1552
1553 $this->prerenderThumbnails();
1554 }
1555 ),
1556 DeferredUpdates::PRESEND
1557 );
1558
1559 if ( !$reupload ) {
1560 # This is a new file, so update the image count
1561 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
1562 }
1563
1564 # Invalidate cache for all pages using this file
1565 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1566
1567 return true;
1568 }
1569
1570 /**
1571 * Move or copy a file to its public location. If a file exists at the
1572 * destination, move it to an archive. Returns a FileRepoStatus object with
1573 * the archive name in the "value" member on success.
1574 *
1575 * The archive name should be passed through to recordUpload for database
1576 * registration.
1577 *
1578 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1579 * @param int $flags A bitwise combination of:
1580 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1581 * @param array $options Optional additional parameters
1582 * @return FileRepoStatus On success, the value member contains the
1583 * archive name, or an empty string if it was a new file.
1584 */
1585 function publish( $src, $flags = 0, array $options = [] ) {
1586 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1587 }
1588
1589 /**
1590 * Move or copy a file to a specified location. Returns a FileRepoStatus
1591 * object with the archive name in the "value" member on success.
1592 *
1593 * The archive name should be passed through to recordUpload for database
1594 * registration.
1595 *
1596 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1597 * @param string $dstRel Target relative path
1598 * @param int $flags A bitwise combination of:
1599 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1600 * @param array $options Optional additional parameters
1601 * @return FileRepoStatus On success, the value member contains the
1602 * archive name, or an empty string if it was a new file.
1603 */
1604 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1605 $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src;
1606
1607 $repo = $this->getRepo();
1608 if ( $repo->getReadOnlyReason() !== false ) {
1609 return $this->readOnlyFatalStatus();
1610 }
1611
1612 $this->lock(); // begin
1613
1614 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1615 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1616
1617 if ( $repo->hasSha1Storage() ) {
1618 $sha1 = $repo->isVirtualUrl( $srcPath )
1619 ? $repo->getFileSha1( $srcPath )
1620 : FSFile::getSha1Base36FromPath( $srcPath );
1621 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1622 $wrapperBackend = $repo->getBackend();
1623 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1624 $status = $repo->quickImport( $src, $dst );
1625 if ( $flags & File::DELETE_SOURCE ) {
1626 unlink( $srcPath );
1627 }
1628
1629 if ( $this->exists() ) {
1630 $status->value = $archiveName;
1631 }
1632 } else {
1633 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1634 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1635
1636 if ( $status->value == 'new' ) {
1637 $status->value = '';
1638 } else {
1639 $status->value = $archiveName;
1640 }
1641 }
1642
1643 $this->unlock(); // done
1644
1645 return $status;
1646 }
1647
1648 /** getLinksTo inherited */
1649 /** getExifData inherited */
1650 /** isLocal inherited */
1651 /** wasDeleted inherited */
1652
1653 /**
1654 * Move file to the new title
1655 *
1656 * Move current, old version and all thumbnails
1657 * to the new filename. Old file is deleted.
1658 *
1659 * Cache purging is done; checks for validity
1660 * and logging are caller's responsibility
1661 *
1662 * @param Title $target New file name
1663 * @return FileRepoStatus
1664 */
1665 function move( $target ) {
1666 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1667 return $this->readOnlyFatalStatus();
1668 }
1669
1670 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1671 $batch = new LocalFileMoveBatch( $this, $target );
1672
1673 $this->lock(); // begin
1674 $batch->addCurrent();
1675 $archiveNames = $batch->addOlds();
1676 $status = $batch->execute();
1677 $this->unlock(); // done
1678
1679 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1680
1681 // Purge the source and target files...
1682 $oldTitleFile = wfLocalFile( $this->title );
1683 $newTitleFile = wfLocalFile( $target );
1684 // To avoid slow purges in the transaction, move them outside...
1685 DeferredUpdates::addUpdate(
1686 new AutoCommitUpdate(
1687 $this->getRepo()->getMasterDB(),
1688 __METHOD__,
1689 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1690 $oldTitleFile->purgeEverything();
1691 foreach ( $archiveNames as $archiveName ) {
1692 $oldTitleFile->purgeOldThumbnails( $archiveName );
1693 }
1694 $newTitleFile->purgeEverything();
1695 }
1696 ),
1697 DeferredUpdates::PRESEND
1698 );
1699
1700 if ( $status->isOK() ) {
1701 // Now switch the object
1702 $this->title = $target;
1703 // Force regeneration of the name and hashpath
1704 unset( $this->name );
1705 unset( $this->hashPath );
1706 }
1707
1708 return $status;
1709 }
1710
1711 /**
1712 * Delete all versions of the file.
1713 *
1714 * Moves the files into an archive directory (or deletes them)
1715 * and removes the database rows.
1716 *
1717 * Cache purging is done; logging is caller's responsibility.
1718 *
1719 * @param string $reason
1720 * @param bool $suppress
1721 * @param User|null $user
1722 * @return FileRepoStatus
1723 */
1724 function delete( $reason, $suppress = false, $user = null ) {
1725 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1726 return $this->readOnlyFatalStatus();
1727 }
1728
1729 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1730
1731 $this->lock(); // begin
1732 $batch->addCurrent();
1733 // Get old version relative paths
1734 $archiveNames = $batch->addOlds();
1735 $status = $batch->execute();
1736 $this->unlock(); // done
1737
1738 if ( $status->isOK() ) {
1739 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => -1 ] ) );
1740 }
1741
1742 // To avoid slow purges in the transaction, move them outside...
1743 DeferredUpdates::addUpdate(
1744 new AutoCommitUpdate(
1745 $this->getRepo()->getMasterDB(),
1746 __METHOD__,
1747 function () use ( $archiveNames ) {
1748 $this->purgeEverything();
1749 foreach ( $archiveNames as $archiveName ) {
1750 $this->purgeOldThumbnails( $archiveName );
1751 }
1752 }
1753 ),
1754 DeferredUpdates::PRESEND
1755 );
1756
1757 // Purge the CDN
1758 $purgeUrls = [];
1759 foreach ( $archiveNames as $archiveName ) {
1760 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1761 }
1762 DeferredUpdates::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates::PRESEND );
1763
1764 return $status;
1765 }
1766
1767 /**
1768 * Delete an old version of the file.
1769 *
1770 * Moves the file into an archive directory (or deletes it)
1771 * and removes the database row.
1772 *
1773 * Cache purging is done; logging is caller's responsibility.
1774 *
1775 * @param string $archiveName
1776 * @param string $reason
1777 * @param bool $suppress
1778 * @param User|null $user
1779 * @throws MWException Exception on database or file store failure
1780 * @return FileRepoStatus
1781 */
1782 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1783 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1784 return $this->readOnlyFatalStatus();
1785 }
1786
1787 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1788
1789 $this->lock(); // begin
1790 $batch->addOld( $archiveName );
1791 $status = $batch->execute();
1792 $this->unlock(); // done
1793
1794 $this->purgeOldThumbnails( $archiveName );
1795 if ( $status->isOK() ) {
1796 $this->purgeDescription();
1797 }
1798
1799 DeferredUpdates::addUpdate(
1800 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1801 DeferredUpdates::PRESEND
1802 );
1803
1804 return $status;
1805 }
1806
1807 /**
1808 * Restore all or specified deleted revisions to the given file.
1809 * Permissions and logging are left to the caller.
1810 *
1811 * May throw database exceptions on error.
1812 *
1813 * @param array $versions Set of record ids of deleted items to restore,
1814 * or empty to restore all revisions.
1815 * @param bool $unsuppress
1816 * @return FileRepoStatus
1817 */
1818 function restore( $versions = [], $unsuppress = false ) {
1819 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1820 return $this->readOnlyFatalStatus();
1821 }
1822
1823 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1824
1825 $this->lock(); // begin
1826 if ( !$versions ) {
1827 $batch->addAll();
1828 } else {
1829 $batch->addIds( $versions );
1830 }
1831 $status = $batch->execute();
1832 if ( $status->isGood() ) {
1833 $cleanupStatus = $batch->cleanup();
1834 $cleanupStatus->successCount = 0;
1835 $cleanupStatus->failCount = 0;
1836 $status->merge( $cleanupStatus );
1837 }
1838 $this->unlock(); // done
1839
1840 return $status;
1841 }
1842
1843 /** isMultipage inherited */
1844 /** pageCount inherited */
1845 /** scaleHeight inherited */
1846 /** getImageSize inherited */
1847
1848 /**
1849 * Get the URL of the file description page.
1850 * @return string
1851 */
1852 function getDescriptionUrl() {
1853 return $this->title->getLocalURL();
1854 }
1855
1856 /**
1857 * Get the HTML text of the description page
1858 * This is not used by ImagePage for local files, since (among other things)
1859 * it skips the parser cache.
1860 *
1861 * @param Language $lang What language to get description in (Optional)
1862 * @return bool|mixed
1863 */
1864 function getDescriptionText( $lang = null ) {
1865 $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
1866 if ( !$revision ) {
1867 return false;
1868 }
1869 $content = $revision->getContent();
1870 if ( !$content ) {
1871 return false;
1872 }
1873 $pout = $content->getParserOutput( $this->title, null, new ParserOptions( null, $lang ) );
1874
1875 return $pout->getText();
1876 }
1877
1878 /**
1879 * @param int $audience
1880 * @param User $user
1881 * @return string
1882 */
1883 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1884 $this->load();
1885 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
1886 return '';
1887 } elseif ( $audience == self::FOR_THIS_USER
1888 && !$this->userCan( self::DELETED_COMMENT, $user )
1889 ) {
1890 return '';
1891 } else {
1892 return $this->description;
1893 }
1894 }
1895
1896 /**
1897 * @return bool|string
1898 */
1899 function getTimestamp() {
1900 $this->load();
1901
1902 return $this->timestamp;
1903 }
1904
1905 /**
1906 * @return bool|string
1907 */
1908 public function getDescriptionTouched() {
1909 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1910 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1911 // need to differentiate between null (uninitialized) and false (failed to load).
1912 if ( $this->descriptionTouched === null ) {
1913 $cond = [
1914 'page_namespace' => $this->title->getNamespace(),
1915 'page_title' => $this->title->getDBkey()
1916 ];
1917 $touched = $this->repo->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
1918 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
1919 }
1920
1921 return $this->descriptionTouched;
1922 }
1923
1924 /**
1925 * @return string
1926 */
1927 function getSha1() {
1928 $this->load();
1929 // Initialise now if necessary
1930 if ( $this->sha1 == '' && $this->fileExists ) {
1931 $this->lock(); // begin
1932
1933 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
1934 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1935 $dbw = $this->repo->getMasterDB();
1936 $dbw->update( 'image',
1937 [ 'img_sha1' => $this->sha1 ],
1938 [ 'img_name' => $this->getName() ],
1939 __METHOD__ );
1940 $this->invalidateCache();
1941 }
1942
1943 $this->unlock(); // done
1944 }
1945
1946 return $this->sha1;
1947 }
1948
1949 /**
1950 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1951 */
1952 function isCacheable() {
1953 $this->load();
1954
1955 // If extra data (metadata) was not loaded then it must have been large
1956 return $this->extraDataLoaded
1957 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
1958 }
1959
1960 /**
1961 * @return Status
1962 * @since 1.28
1963 */
1964 public function acquireFileLock() {
1965 return $this->getRepo()->getBackend()->lockFiles(
1966 [ $this->getPath() ], LockManager::LOCK_EX, 10
1967 );
1968 }
1969
1970 /**
1971 * @return Status
1972 * @since 1.28
1973 */
1974 public function releaseFileLock() {
1975 return $this->getRepo()->getBackend()->unlockFiles(
1976 [ $this->getPath() ], LockManager::LOCK_EX
1977 );
1978 }
1979
1980 /**
1981 * Start an atomic DB section and lock the image for update
1982 * or increments a reference counter if the lock is already held
1983 *
1984 * This method should not be used outside of LocalFile/LocalFile*Batch
1985 *
1986 * @throws LocalFileLockError Throws an error if the lock was not acquired
1987 * @return bool Whether the file lock owns/spawned the DB transaction
1988 */
1989 public function lock() {
1990 if ( !$this->locked ) {
1991 $logger = LoggerFactory::getInstance( 'LocalFile' );
1992
1993 $dbw = $this->repo->getMasterDB();
1994 $makesTransaction = !$dbw->trxLevel();
1995 $dbw->startAtomic( self::ATOMIC_SECTION_LOCK );
1996 // Bug 54736: use simple lock to handle when the file does not exist.
1997 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1998 // Also, that would cause contention on INSERT of similarly named rows.
1999 $status = $this->acquireFileLock(); // represents all versions of the file
2000 if ( !$status->isGood() ) {
2001 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2002 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name ] );
2003
2004 throw new LocalFileLockError( $status );
2005 }
2006 // Release the lock *after* commit to avoid row-level contention.
2007 // Make sure it triggers on rollback() as well as commit() (T132921).
2008 $dbw->onTransactionResolution(
2009 function () use ( $logger ) {
2010 $status = $this->releaseFileLock();
2011 if ( !$status->isGood() ) {
2012 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name ] );
2013 }
2014 },
2015 __METHOD__
2016 );
2017 // Callers might care if the SELECT snapshot is safely fresh
2018 $this->lockedOwnTrx = $makesTransaction;
2019 }
2020
2021 $this->locked++;
2022
2023 return $this->lockedOwnTrx;
2024 }
2025
2026 /**
2027 * Decrement the lock reference count and end the atomic section if it reaches zero
2028 *
2029 * This method should not be used outside of LocalFile/LocalFile*Batch
2030 *
2031 * The commit and loc release will happen when no atomic sections are active, which
2032 * may happen immediately or at some point after calling this
2033 */
2034 public function unlock() {
2035 if ( $this->locked ) {
2036 --$this->locked;
2037 if ( !$this->locked ) {
2038 $dbw = $this->repo->getMasterDB();
2039 $dbw->endAtomic( self::ATOMIC_SECTION_LOCK );
2040 $this->lockedOwnTrx = false;
2041 }
2042 }
2043 }
2044
2045 /**
2046 * @return Status
2047 */
2048 protected function readOnlyFatalStatus() {
2049 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2050 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2051 }
2052
2053 /**
2054 * Clean up any dangling locks
2055 */
2056 function __destruct() {
2057 $this->unlock();
2058 }
2059 } // LocalFile class
2060
2061 # ------------------------------------------------------------------------------
2062
2063 /**
2064 * Helper class for file deletion
2065 * @ingroup FileAbstraction
2066 */
2067 class LocalFileDeleteBatch {
2068 /** @var LocalFile */
2069 private $file;
2070
2071 /** @var string */
2072 private $reason;
2073
2074 /** @var array */
2075 private $srcRels = [];
2076
2077 /** @var array */
2078 private $archiveUrls = [];
2079
2080 /** @var array Items to be processed in the deletion batch */
2081 private $deletionBatch;
2082
2083 /** @var bool Whether to suppress all suppressable fields when deleting */
2084 private $suppress;
2085
2086 /** @var FileRepoStatus */
2087 private $status;
2088
2089 /** @var User */
2090 private $user;
2091
2092 /**
2093 * @param File $file
2094 * @param string $reason
2095 * @param bool $suppress
2096 * @param User|null $user
2097 */
2098 function __construct( File $file, $reason = '', $suppress = false, $user = null ) {
2099 $this->file = $file;
2100 $this->reason = $reason;
2101 $this->suppress = $suppress;
2102 if ( $user ) {
2103 $this->user = $user;
2104 } else {
2105 global $wgUser;
2106 $this->user = $wgUser;
2107 }
2108 $this->status = $file->repo->newGood();
2109 }
2110
2111 public function addCurrent() {
2112 $this->srcRels['.'] = $this->file->getRel();
2113 }
2114
2115 /**
2116 * @param string $oldName
2117 */
2118 public function addOld( $oldName ) {
2119 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
2120 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
2121 }
2122
2123 /**
2124 * Add the old versions of the image to the batch
2125 * @return array List of archive names from old versions
2126 */
2127 public function addOlds() {
2128 $archiveNames = [];
2129
2130 $dbw = $this->file->repo->getMasterDB();
2131 $result = $dbw->select( 'oldimage',
2132 [ 'oi_archive_name' ],
2133 [ 'oi_name' => $this->file->getName() ],
2134 __METHOD__
2135 );
2136
2137 foreach ( $result as $row ) {
2138 $this->addOld( $row->oi_archive_name );
2139 $archiveNames[] = $row->oi_archive_name;
2140 }
2141
2142 return $archiveNames;
2143 }
2144
2145 /**
2146 * @return array
2147 */
2148 protected function getOldRels() {
2149 if ( !isset( $this->srcRels['.'] ) ) {
2150 $oldRels =& $this->srcRels;
2151 $deleteCurrent = false;
2152 } else {
2153 $oldRels = $this->srcRels;
2154 unset( $oldRels['.'] );
2155 $deleteCurrent = true;
2156 }
2157
2158 return [ $oldRels, $deleteCurrent ];
2159 }
2160
2161 /**
2162 * @return array
2163 */
2164 protected function getHashes() {
2165 $hashes = [];
2166 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2167
2168 if ( $deleteCurrent ) {
2169 $hashes['.'] = $this->file->getSha1();
2170 }
2171
2172 if ( count( $oldRels ) ) {
2173 $dbw = $this->file->repo->getMasterDB();
2174 $res = $dbw->select(
2175 'oldimage',
2176 [ 'oi_archive_name', 'oi_sha1' ],
2177 [ 'oi_archive_name' => array_keys( $oldRels ),
2178 'oi_name' => $this->file->getName() ], // performance
2179 __METHOD__
2180 );
2181
2182 foreach ( $res as $row ) {
2183 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
2184 // Get the hash from the file
2185 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2186 $props = $this->file->repo->getFileProps( $oldUrl );
2187
2188 if ( $props['fileExists'] ) {
2189 // Upgrade the oldimage row
2190 $dbw->update( 'oldimage',
2191 [ 'oi_sha1' => $props['sha1'] ],
2192 [ 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ],
2193 __METHOD__ );
2194 $hashes[$row->oi_archive_name] = $props['sha1'];
2195 } else {
2196 $hashes[$row->oi_archive_name] = false;
2197 }
2198 } else {
2199 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2200 }
2201 }
2202 }
2203
2204 $missing = array_diff_key( $this->srcRels, $hashes );
2205
2206 foreach ( $missing as $name => $rel ) {
2207 $this->status->error( 'filedelete-old-unregistered', $name );
2208 }
2209
2210 foreach ( $hashes as $name => $hash ) {
2211 if ( !$hash ) {
2212 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2213 unset( $hashes[$name] );
2214 }
2215 }
2216
2217 return $hashes;
2218 }
2219
2220 protected function doDBInserts() {
2221 $now = time();
2222 $dbw = $this->file->repo->getMasterDB();
2223 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2224 $encUserId = $dbw->addQuotes( $this->user->getId() );
2225 $encReason = $dbw->addQuotes( $this->reason );
2226 $encGroup = $dbw->addQuotes( 'deleted' );
2227 $ext = $this->file->getExtension();
2228 $dotExt = $ext === '' ? '' : ".$ext";
2229 $encExt = $dbw->addQuotes( $dotExt );
2230 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2231
2232 // Bitfields to further suppress the content
2233 if ( $this->suppress ) {
2234 $bitfield = 0;
2235 // This should be 15...
2236 $bitfield |= Revision::DELETED_TEXT;
2237 $bitfield |= Revision::DELETED_COMMENT;
2238 $bitfield |= Revision::DELETED_USER;
2239 $bitfield |= Revision::DELETED_RESTRICTED;
2240 } else {
2241 $bitfield = 'oi_deleted';
2242 }
2243
2244 if ( $deleteCurrent ) {
2245 $dbw->insertSelect(
2246 'filearchive',
2247 'image',
2248 [
2249 'fa_storage_group' => $encGroup,
2250 'fa_storage_key' => $dbw->conditional(
2251 [ 'img_sha1' => '' ],
2252 $dbw->addQuotes( '' ),
2253 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2254 ),
2255 'fa_deleted_user' => $encUserId,
2256 'fa_deleted_timestamp' => $encTimestamp,
2257 'fa_deleted_reason' => $encReason,
2258 'fa_deleted' => $this->suppress ? $bitfield : 0,
2259
2260 'fa_name' => 'img_name',
2261 'fa_archive_name' => 'NULL',
2262 'fa_size' => 'img_size',
2263 'fa_width' => 'img_width',
2264 'fa_height' => 'img_height',
2265 'fa_metadata' => 'img_metadata',
2266 'fa_bits' => 'img_bits',
2267 'fa_media_type' => 'img_media_type',
2268 'fa_major_mime' => 'img_major_mime',
2269 'fa_minor_mime' => 'img_minor_mime',
2270 'fa_description' => 'img_description',
2271 'fa_user' => 'img_user',
2272 'fa_user_text' => 'img_user_text',
2273 'fa_timestamp' => 'img_timestamp',
2274 'fa_sha1' => 'img_sha1'
2275 ],
2276 [ 'img_name' => $this->file->getName() ],
2277 __METHOD__
2278 );
2279 }
2280
2281 if ( count( $oldRels ) ) {
2282 $res = $dbw->select(
2283 'oldimage',
2284 OldLocalFile::selectFields(),
2285 [
2286 'oi_name' => $this->file->getName(),
2287 'oi_archive_name' => array_keys( $oldRels )
2288 ],
2289 __METHOD__,
2290 [ 'FOR UPDATE' ]
2291 );
2292 $rowsInsert = [];
2293 foreach ( $res as $row ) {
2294 $rowsInsert[] = [
2295 // Deletion-specific fields
2296 'fa_storage_group' => 'deleted',
2297 'fa_storage_key' => ( $row->oi_sha1 === '' )
2298 ? ''
2299 : "{$row->oi_sha1}{$dotExt}",
2300 'fa_deleted_user' => $this->user->getId(),
2301 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2302 'fa_deleted_reason' => $this->reason,
2303 // Counterpart fields
2304 'fa_deleted' => $this->suppress ? $bitfield : $row->oi_deleted,
2305 'fa_name' => $row->oi_name,
2306 'fa_archive_name' => $row->oi_archive_name,
2307 'fa_size' => $row->oi_size,
2308 'fa_width' => $row->oi_width,
2309 'fa_height' => $row->oi_height,
2310 'fa_metadata' => $row->oi_metadata,
2311 'fa_bits' => $row->oi_bits,
2312 'fa_media_type' => $row->oi_media_type,
2313 'fa_major_mime' => $row->oi_major_mime,
2314 'fa_minor_mime' => $row->oi_minor_mime,
2315 'fa_description' => $row->oi_description,
2316 'fa_user' => $row->oi_user,
2317 'fa_user_text' => $row->oi_user_text,
2318 'fa_timestamp' => $row->oi_timestamp,
2319 'fa_sha1' => $row->oi_sha1
2320 ];
2321 }
2322
2323 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__ );
2324 }
2325 }
2326
2327 function doDBDeletes() {
2328 $dbw = $this->file->repo->getMasterDB();
2329 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2330
2331 if ( count( $oldRels ) ) {
2332 $dbw->delete( 'oldimage',
2333 [
2334 'oi_name' => $this->file->getName(),
2335 'oi_archive_name' => array_keys( $oldRels )
2336 ], __METHOD__ );
2337 }
2338
2339 if ( $deleteCurrent ) {
2340 $dbw->delete( 'image', [ 'img_name' => $this->file->getName() ], __METHOD__ );
2341 }
2342 }
2343
2344 /**
2345 * Run the transaction
2346 * @return FileRepoStatus
2347 */
2348 public function execute() {
2349 $repo = $this->file->getRepo();
2350 $this->file->lock();
2351
2352 // Prepare deletion batch
2353 $hashes = $this->getHashes();
2354 $this->deletionBatch = [];
2355 $ext = $this->file->getExtension();
2356 $dotExt = $ext === '' ? '' : ".$ext";
2357
2358 foreach ( $this->srcRels as $name => $srcRel ) {
2359 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2360 if ( isset( $hashes[$name] ) ) {
2361 $hash = $hashes[$name];
2362 $key = $hash . $dotExt;
2363 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2364 $this->deletionBatch[$name] = [ $srcRel, $dstRel ];
2365 }
2366 }
2367
2368 if ( !$repo->hasSha1Storage() ) {
2369 // Removes non-existent file from the batch, so we don't get errors.
2370 // This also handles files in the 'deleted' zone deleted via revision deletion.
2371 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch );
2372 if ( !$checkStatus->isGood() ) {
2373 $this->status->merge( $checkStatus );
2374 return $this->status;
2375 }
2376 $this->deletionBatch = $checkStatus->value;
2377
2378 // Execute the file deletion batch
2379 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2380 if ( !$status->isGood() ) {
2381 $this->status->merge( $status );
2382 }
2383 }
2384
2385 if ( !$this->status->isOK() ) {
2386 // Critical file deletion error; abort
2387 $this->file->unlock();
2388
2389 return $this->status;
2390 }
2391
2392 // Copy the image/oldimage rows to filearchive
2393 $this->doDBInserts();
2394 // Delete image/oldimage rows
2395 $this->doDBDeletes();
2396
2397 // Commit and return
2398 $this->file->unlock();
2399
2400 return $this->status;
2401 }
2402
2403 /**
2404 * Removes non-existent files from a deletion batch.
2405 * @param array $batch
2406 * @return Status
2407 */
2408 protected function removeNonexistentFiles( $batch ) {
2409 $files = $newBatch = [];
2410
2411 foreach ( $batch as $batchItem ) {
2412 list( $src, ) = $batchItem;
2413 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2414 }
2415
2416 $result = $this->file->repo->fileExistsBatch( $files );
2417 if ( in_array( null, $result, true ) ) {
2418 return Status::newFatal( 'backend-fail-internal',
2419 $this->file->repo->getBackend()->getName() );
2420 }
2421
2422 foreach ( $batch as $batchItem ) {
2423 if ( $result[$batchItem[0]] ) {
2424 $newBatch[] = $batchItem;
2425 }
2426 }
2427
2428 return Status::newGood( $newBatch );
2429 }
2430 }
2431
2432 # ------------------------------------------------------------------------------
2433
2434 /**
2435 * Helper class for file undeletion
2436 * @ingroup FileAbstraction
2437 */
2438 class LocalFileRestoreBatch {
2439 /** @var LocalFile */
2440 private $file;
2441
2442 /** @var array List of file IDs to restore */
2443 private $cleanupBatch;
2444
2445 /** @var array List of file IDs to restore */
2446 private $ids;
2447
2448 /** @var bool Add all revisions of the file */
2449 private $all;
2450
2451 /** @var bool Whether to remove all settings for suppressed fields */
2452 private $unsuppress = false;
2453
2454 /**
2455 * @param File $file
2456 * @param bool $unsuppress
2457 */
2458 function __construct( File $file, $unsuppress = false ) {
2459 $this->file = $file;
2460 $this->cleanupBatch = $this->ids = [];
2461 $this->ids = [];
2462 $this->unsuppress = $unsuppress;
2463 }
2464
2465 /**
2466 * Add a file by ID
2467 * @param int $fa_id
2468 */
2469 public function addId( $fa_id ) {
2470 $this->ids[] = $fa_id;
2471 }
2472
2473 /**
2474 * Add a whole lot of files by ID
2475 * @param int[] $ids
2476 */
2477 public function addIds( $ids ) {
2478 $this->ids = array_merge( $this->ids, $ids );
2479 }
2480
2481 /**
2482 * Add all revisions of the file
2483 */
2484 public function addAll() {
2485 $this->all = true;
2486 }
2487
2488 /**
2489 * Run the transaction, except the cleanup batch.
2490 * The cleanup batch should be run in a separate transaction, because it locks different
2491 * rows and there's no need to keep the image row locked while it's acquiring those locks
2492 * The caller may have its own transaction open.
2493 * So we save the batch and let the caller call cleanup()
2494 * @return FileRepoStatus
2495 */
2496 public function execute() {
2497 /** @var Language */
2498 global $wgLang;
2499
2500 $repo = $this->file->getRepo();
2501 if ( !$this->all && !$this->ids ) {
2502 // Do nothing
2503 return $repo->newGood();
2504 }
2505
2506 $lockOwnsTrx = $this->file->lock();
2507
2508 $dbw = $this->file->repo->getMasterDB();
2509 $status = $this->file->repo->newGood();
2510
2511 $exists = (bool)$dbw->selectField( 'image', '1',
2512 [ 'img_name' => $this->file->getName() ],
2513 __METHOD__,
2514 // The lock() should already prevents changes, but this still may need
2515 // to bypass any transaction snapshot. However, if lock() started the
2516 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2517 $lockOwnsTrx ? [] : [ 'LOCK IN SHARE MODE' ]
2518 );
2519
2520 // Fetch all or selected archived revisions for the file,
2521 // sorted from the most recent to the oldest.
2522 $conditions = [ 'fa_name' => $this->file->getName() ];
2523
2524 if ( !$this->all ) {
2525 $conditions['fa_id'] = $this->ids;
2526 }
2527
2528 $result = $dbw->select(
2529 'filearchive',
2530 ArchivedFile::selectFields(),
2531 $conditions,
2532 __METHOD__,
2533 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2534 );
2535
2536 $idsPresent = [];
2537 $storeBatch = [];
2538 $insertBatch = [];
2539 $insertCurrent = false;
2540 $deleteIds = [];
2541 $first = true;
2542 $archiveNames = [];
2543
2544 foreach ( $result as $row ) {
2545 $idsPresent[] = $row->fa_id;
2546
2547 if ( $row->fa_name != $this->file->getName() ) {
2548 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2549 $status->failCount++;
2550 continue;
2551 }
2552
2553 if ( $row->fa_storage_key == '' ) {
2554 // Revision was missing pre-deletion
2555 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2556 $status->failCount++;
2557 continue;
2558 }
2559
2560 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key ) .
2561 $row->fa_storage_key;
2562 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2563
2564 if ( isset( $row->fa_sha1 ) ) {
2565 $sha1 = $row->fa_sha1;
2566 } else {
2567 // old row, populate from key
2568 $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2569 }
2570
2571 # Fix leading zero
2572 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2573 $sha1 = substr( $sha1, 1 );
2574 }
2575
2576 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2577 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2578 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2579 || is_null( $row->fa_metadata )
2580 ) {
2581 // Refresh our metadata
2582 // Required for a new current revision; nice for older ones too. :)
2583 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2584 } else {
2585 $props = [
2586 'minor_mime' => $row->fa_minor_mime,
2587 'major_mime' => $row->fa_major_mime,
2588 'media_type' => $row->fa_media_type,
2589 'metadata' => $row->fa_metadata
2590 ];
2591 }
2592
2593 if ( $first && !$exists ) {
2594 // This revision will be published as the new current version
2595 $destRel = $this->file->getRel();
2596 $insertCurrent = [
2597 'img_name' => $row->fa_name,
2598 'img_size' => $row->fa_size,
2599 'img_width' => $row->fa_width,
2600 'img_height' => $row->fa_height,
2601 'img_metadata' => $props['metadata'],
2602 'img_bits' => $row->fa_bits,
2603 'img_media_type' => $props['media_type'],
2604 'img_major_mime' => $props['major_mime'],
2605 'img_minor_mime' => $props['minor_mime'],
2606 'img_description' => $row->fa_description,
2607 'img_user' => $row->fa_user,
2608 'img_user_text' => $row->fa_user_text,
2609 'img_timestamp' => $row->fa_timestamp,
2610 'img_sha1' => $sha1
2611 ];
2612
2613 // The live (current) version cannot be hidden!
2614 if ( !$this->unsuppress && $row->fa_deleted ) {
2615 $status->fatal( 'undeleterevdel' );
2616 $this->file->unlock();
2617 return $status;
2618 }
2619 } else {
2620 $archiveName = $row->fa_archive_name;
2621
2622 if ( $archiveName == '' ) {
2623 // This was originally a current version; we
2624 // have to devise a new archive name for it.
2625 // Format is <timestamp of archiving>!<name>
2626 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2627
2628 do {
2629 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2630 $timestamp++;
2631 } while ( isset( $archiveNames[$archiveName] ) );
2632 }
2633
2634 $archiveNames[$archiveName] = true;
2635 $destRel = $this->file->getArchiveRel( $archiveName );
2636 $insertBatch[] = [
2637 'oi_name' => $row->fa_name,
2638 'oi_archive_name' => $archiveName,
2639 'oi_size' => $row->fa_size,
2640 'oi_width' => $row->fa_width,
2641 'oi_height' => $row->fa_height,
2642 'oi_bits' => $row->fa_bits,
2643 'oi_description' => $row->fa_description,
2644 'oi_user' => $row->fa_user,
2645 'oi_user_text' => $row->fa_user_text,
2646 'oi_timestamp' => $row->fa_timestamp,
2647 'oi_metadata' => $props['metadata'],
2648 'oi_media_type' => $props['media_type'],
2649 'oi_major_mime' => $props['major_mime'],
2650 'oi_minor_mime' => $props['minor_mime'],
2651 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2652 'oi_sha1' => $sha1 ];
2653 }
2654
2655 $deleteIds[] = $row->fa_id;
2656
2657 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2658 // private files can stay where they are
2659 $status->successCount++;
2660 } else {
2661 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2662 $this->cleanupBatch[] = $row->fa_storage_key;
2663 }
2664
2665 $first = false;
2666 }
2667
2668 unset( $result );
2669
2670 // Add a warning to the status object for missing IDs
2671 $missingIds = array_diff( $this->ids, $idsPresent );
2672
2673 foreach ( $missingIds as $id ) {
2674 $status->error( 'undelete-missing-filearchive', $id );
2675 }
2676
2677 if ( !$repo->hasSha1Storage() ) {
2678 // Remove missing files from batch, so we don't get errors when undeleting them
2679 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2680 if ( !$checkStatus->isGood() ) {
2681 $status->merge( $checkStatus );
2682 return $status;
2683 }
2684 $storeBatch = $checkStatus->value;
2685
2686 // Run the store batch
2687 // Use the OVERWRITE_SAME flag to smooth over a common error
2688 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2689 $status->merge( $storeStatus );
2690
2691 if ( !$status->isGood() ) {
2692 // Even if some files could be copied, fail entirely as that is the
2693 // easiest thing to do without data loss
2694 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2695 $status->ok = false;
2696 $this->file->unlock();
2697
2698 return $status;
2699 }
2700 }
2701
2702 // Run the DB updates
2703 // Because we have locked the image row, key conflicts should be rare.
2704 // If they do occur, we can roll back the transaction at this time with
2705 // no data loss, but leaving unregistered files scattered throughout the
2706 // public zone.
2707 // This is not ideal, which is why it's important to lock the image row.
2708 if ( $insertCurrent ) {
2709 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2710 }
2711
2712 if ( $insertBatch ) {
2713 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2714 }
2715
2716 if ( $deleteIds ) {
2717 $dbw->delete( 'filearchive',
2718 [ 'fa_id' => $deleteIds ],
2719 __METHOD__ );
2720 }
2721
2722 // If store batch is empty (all files are missing), deletion is to be considered successful
2723 if ( $status->successCount > 0 || !$storeBatch || $repo->hasSha1Storage() ) {
2724 if ( !$exists ) {
2725 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2726
2727 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) );
2728
2729 $this->file->purgeEverything();
2730 } else {
2731 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2732 $this->file->purgeDescription();
2733 }
2734 }
2735
2736 $this->file->unlock();
2737
2738 return $status;
2739 }
2740
2741 /**
2742 * Removes non-existent files from a store batch.
2743 * @param array $triplets
2744 * @return Status
2745 */
2746 protected function removeNonexistentFiles( $triplets ) {
2747 $files = $filteredTriplets = [];
2748 foreach ( $triplets as $file ) {
2749 $files[$file[0]] = $file[0];
2750 }
2751
2752 $result = $this->file->repo->fileExistsBatch( $files );
2753 if ( in_array( null, $result, true ) ) {
2754 return Status::newFatal( 'backend-fail-internal',
2755 $this->file->repo->getBackend()->getName() );
2756 }
2757
2758 foreach ( $triplets as $file ) {
2759 if ( $result[$file[0]] ) {
2760 $filteredTriplets[] = $file;
2761 }
2762 }
2763
2764 return Status::newGood( $filteredTriplets );
2765 }
2766
2767 /**
2768 * Removes non-existent files from a cleanup batch.
2769 * @param array $batch
2770 * @return array
2771 */
2772 protected function removeNonexistentFromCleanup( $batch ) {
2773 $files = $newBatch = [];
2774 $repo = $this->file->repo;
2775
2776 foreach ( $batch as $file ) {
2777 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2778 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2779 }
2780
2781 $result = $repo->fileExistsBatch( $files );
2782
2783 foreach ( $batch as $file ) {
2784 if ( $result[$file] ) {
2785 $newBatch[] = $file;
2786 }
2787 }
2788
2789 return $newBatch;
2790 }
2791
2792 /**
2793 * Delete unused files in the deleted zone.
2794 * This should be called from outside the transaction in which execute() was called.
2795 * @return FileRepoStatus
2796 */
2797 public function cleanup() {
2798 if ( !$this->cleanupBatch ) {
2799 return $this->file->repo->newGood();
2800 }
2801
2802 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2803
2804 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2805
2806 return $status;
2807 }
2808
2809 /**
2810 * Cleanup a failed batch. The batch was only partially successful, so
2811 * rollback by removing all items that were succesfully copied.
2812 *
2813 * @param Status $storeStatus
2814 * @param array $storeBatch
2815 */
2816 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2817 $cleanupBatch = [];
2818
2819 foreach ( $storeStatus->success as $i => $success ) {
2820 // Check if this item of the batch was successfully copied
2821 if ( $success ) {
2822 // Item was successfully copied and needs to be removed again
2823 // Extract ($dstZone, $dstRel) from the batch
2824 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2825 }
2826 }
2827 $this->file->repo->cleanupBatch( $cleanupBatch );
2828 }
2829 }
2830
2831 # ------------------------------------------------------------------------------
2832
2833 /**
2834 * Helper class for file movement
2835 * @ingroup FileAbstraction
2836 */
2837 class LocalFileMoveBatch {
2838 /** @var LocalFile */
2839 protected $file;
2840
2841 /** @var Title */
2842 protected $target;
2843
2844 protected $cur;
2845
2846 protected $olds;
2847
2848 protected $oldCount;
2849
2850 protected $archive;
2851
2852 /** @var DatabaseBase */
2853 protected $db;
2854
2855 /**
2856 * @param File $file
2857 * @param Title $target
2858 */
2859 function __construct( File $file, Title $target ) {
2860 $this->file = $file;
2861 $this->target = $target;
2862 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2863 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2864 $this->oldName = $this->file->getName();
2865 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2866 $this->oldRel = $this->oldHash . $this->oldName;
2867 $this->newRel = $this->newHash . $this->newName;
2868 $this->db = $file->getRepo()->getMasterDB();
2869 }
2870
2871 /**
2872 * Add the current image to the batch
2873 */
2874 public function addCurrent() {
2875 $this->cur = [ $this->oldRel, $this->newRel ];
2876 }
2877
2878 /**
2879 * Add the old versions of the image to the batch
2880 * @return array List of archive names from old versions
2881 */
2882 public function addOlds() {
2883 $archiveBase = 'archive';
2884 $this->olds = [];
2885 $this->oldCount = 0;
2886 $archiveNames = [];
2887
2888 $result = $this->db->select( 'oldimage',
2889 [ 'oi_archive_name', 'oi_deleted' ],
2890 [ 'oi_name' => $this->oldName ],
2891 __METHOD__,
2892 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2893 );
2894
2895 foreach ( $result as $row ) {
2896 $archiveNames[] = $row->oi_archive_name;
2897 $oldName = $row->oi_archive_name;
2898 $bits = explode( '!', $oldName, 2 );
2899
2900 if ( count( $bits ) != 2 ) {
2901 wfDebug( "Old file name missing !: '$oldName' \n" );
2902 continue;
2903 }
2904
2905 list( $timestamp, $filename ) = $bits;
2906
2907 if ( $this->oldName != $filename ) {
2908 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2909 continue;
2910 }
2911
2912 $this->oldCount++;
2913
2914 // Do we want to add those to oldCount?
2915 if ( $row->oi_deleted & File::DELETED_FILE ) {
2916 continue;
2917 }
2918
2919 $this->olds[] = [
2920 "{$archiveBase}/{$this->oldHash}{$oldName}",
2921 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2922 ];
2923 }
2924
2925 return $archiveNames;
2926 }
2927
2928 /**
2929 * Perform the move.
2930 * @return FileRepoStatus
2931 */
2932 public function execute() {
2933 $repo = $this->file->repo;
2934 $status = $repo->newGood();
2935 $destFile = wfLocalFile( $this->target );
2936
2937 $this->file->lock(); // begin
2938 $destFile->lock(); // quickly fail if destination is not available
2939
2940 $triplets = $this->getMoveTriplets();
2941 $checkStatus = $this->removeNonexistentFiles( $triplets );
2942 if ( !$checkStatus->isGood() ) {
2943 $destFile->unlock();
2944 $this->file->unlock();
2945 $status->merge( $checkStatus ); // couldn't talk to file backend
2946 return $status;
2947 }
2948 $triplets = $checkStatus->value;
2949
2950 // Verify the file versions metadata in the DB.
2951 $statusDb = $this->verifyDBUpdates();
2952 if ( !$statusDb->isGood() ) {
2953 $destFile->unlock();
2954 $this->file->unlock();
2955 $statusDb->ok = false;
2956
2957 return $statusDb;
2958 }
2959
2960 if ( !$repo->hasSha1Storage() ) {
2961 // Copy the files into their new location.
2962 // If a prior process fataled copying or cleaning up files we tolerate any
2963 // of the existing files if they are identical to the ones being stored.
2964 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
2965 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2966 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2967 if ( !$statusMove->isGood() ) {
2968 // Delete any files copied over (while the destination is still locked)
2969 $this->cleanupTarget( $triplets );
2970 $destFile->unlock();
2971 $this->file->unlock();
2972 wfDebugLog( 'imagemove', "Error in moving files: "
2973 . $statusMove->getWikiText( false, false, 'en' ) );
2974 $statusMove->ok = false;
2975
2976 return $statusMove;
2977 }
2978 $status->merge( $statusMove );
2979 }
2980
2981 // Rename the file versions metadata in the DB.
2982 $this->doDBUpdates();
2983
2984 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2985 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2986
2987 $destFile->unlock();
2988 $this->file->unlock(); // done
2989
2990 // Everything went ok, remove the source files
2991 $this->cleanupSource( $triplets );
2992
2993 $status->merge( $statusDb );
2994
2995 return $status;
2996 }
2997
2998 /**
2999 * Verify the database updates and return a new FileRepoStatus indicating how
3000 * many rows would be updated.
3001 *
3002 * @return FileRepoStatus
3003 */
3004 protected function verifyDBUpdates() {
3005 $repo = $this->file->repo;
3006 $status = $repo->newGood();
3007 $dbw = $this->db;
3008
3009 $hasCurrent = $dbw->selectField(
3010 'image',
3011 '1',
3012 [ 'img_name' => $this->oldName ],
3013 __METHOD__,
3014 [ 'FOR UPDATE' ]
3015 );
3016 $oldRowCount = $dbw->selectField(
3017 'oldimage',
3018 'COUNT(*)',
3019 [ 'oi_name' => $this->oldName ],
3020 __METHOD__,
3021 [ 'FOR UPDATE' ]
3022 );
3023
3024 if ( $hasCurrent ) {
3025 $status->successCount++;
3026 } else {
3027 $status->failCount++;
3028 }
3029 $status->successCount += $oldRowCount;
3030 // Bug 34934: oldCount is based on files that actually exist.
3031 // There may be more DB rows than such files, in which case $affected
3032 // can be greater than $total. We use max() to avoid negatives here.
3033 $status->failCount += max( 0, $this->oldCount - $oldRowCount );
3034 if ( $status->failCount ) {
3035 $status->error( 'imageinvalidfilename' );
3036 }
3037
3038 return $status;
3039 }
3040
3041 /**
3042 * Do the database updates and return a new FileRepoStatus indicating how
3043 * many rows where updated.
3044 */
3045 protected function doDBUpdates() {
3046 $dbw = $this->db;
3047
3048 // Update current image
3049 $dbw->update(
3050 'image',
3051 [ 'img_name' => $this->newName ],
3052 [ 'img_name' => $this->oldName ],
3053 __METHOD__
3054 );
3055 // Update old images
3056 $dbw->update(
3057 'oldimage',
3058 [
3059 'oi_name' => $this->newName,
3060 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3061 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
3062 ],
3063 [ 'oi_name' => $this->oldName ],
3064 __METHOD__
3065 );
3066 }
3067
3068 /**
3069 * Generate triplets for FileRepo::storeBatch().
3070 * @return array
3071 */
3072 protected function getMoveTriplets() {
3073 $moves = array_merge( [ $this->cur ], $this->olds );
3074 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3075
3076 foreach ( $moves as $move ) {
3077 // $move: (oldRelativePath, newRelativePath)
3078 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3079 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3080 wfDebugLog(
3081 'imagemove',
3082 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3083 );
3084 }
3085
3086 return $triplets;
3087 }
3088
3089 /**
3090 * Removes non-existent files from move batch.
3091 * @param array $triplets
3092 * @return Status
3093 */
3094 protected function removeNonexistentFiles( $triplets ) {
3095 $files = [];
3096
3097 foreach ( $triplets as $file ) {
3098 $files[$file[0]] = $file[0];
3099 }
3100
3101 $result = $this->file->repo->fileExistsBatch( $files );
3102 if ( in_array( null, $result, true ) ) {
3103 return Status::newFatal( 'backend-fail-internal',
3104 $this->file->repo->getBackend()->getName() );
3105 }
3106
3107 $filteredTriplets = [];
3108 foreach ( $triplets as $file ) {
3109 if ( $result[$file[0]] ) {
3110 $filteredTriplets[] = $file;
3111 } else {
3112 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3113 }
3114 }
3115
3116 return Status::newGood( $filteredTriplets );
3117 }
3118
3119 /**
3120 * Cleanup a partially moved array of triplets by deleting the target
3121 * files. Called if something went wrong half way.
3122 * @param array $triplets
3123 */
3124 protected function cleanupTarget( $triplets ) {
3125 // Create dest pairs from the triplets
3126 $pairs = [];
3127 foreach ( $triplets as $triplet ) {
3128 // $triplet: (old source virtual URL, dst zone, dest rel)
3129 $pairs[] = [ $triplet[1], $triplet[2] ];
3130 }
3131
3132 $this->file->repo->cleanupBatch( $pairs );
3133 }
3134
3135 /**
3136 * Cleanup a fully moved array of triplets by deleting the source files.
3137 * Called at the end of the move process if everything else went ok.
3138 * @param array $triplets
3139 */
3140 protected function cleanupSource( $triplets ) {
3141 // Create source file names from the triplets
3142 $files = [];
3143 foreach ( $triplets as $triplet ) {
3144 $files[] = $triplet[0];
3145 }
3146
3147 $this->file->repo->cleanupBatch( $files );
3148 }
3149 }
3150
3151 class LocalFileLockError extends ErrorPageError {
3152 public function __construct( Status $status ) {
3153 parent::__construct(
3154 'actionfailed',
3155 $status->getMessage()
3156 );
3157 }
3158
3159 public function report() {
3160 global $wgOut;
3161 $wgOut->setStatusCode( 429 );
3162 parent::report();
3163 }
3164 }