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