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