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