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