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