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