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