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