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