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