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