6abe00cb7fd556c3cd5592164aff8e02dcdf9094
[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 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 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 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1490 return $this->readOnlyFatalStatus();
1491 }
1492
1493 $this->lock(); // begin
1494
1495 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1496 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1497 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1498 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1499
1500 if ( $status->value == 'new' ) {
1501 $status->value = '';
1502 } else {
1503 $status->value = $archiveName;
1504 }
1505
1506 $this->unlock(); // done
1507
1508 return $status;
1509 }
1510
1511 /** getLinksTo inherited */
1512 /** getExifData inherited */
1513 /** isLocal inherited */
1514 /** wasDeleted inherited */
1515
1516 /**
1517 * Move file to the new title
1518 *
1519 * Move current, old version and all thumbnails
1520 * to the new filename. Old file is deleted.
1521 *
1522 * Cache purging is done; checks for validity
1523 * and logging are caller's responsibility
1524 *
1525 * @param Title $target New file name
1526 * @return FileRepoStatus
1527 */
1528 function move( $target ) {
1529 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1530 return $this->readOnlyFatalStatus();
1531 }
1532
1533 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1534 $batch = new LocalFileMoveBatch( $this, $target );
1535
1536 $this->lock(); // begin
1537 $batch->addCurrent();
1538 $archiveNames = $batch->addOlds();
1539 $status = $batch->execute();
1540 $this->unlock(); // done
1541
1542 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1543
1544 // Purge the source and target files...
1545 $oldTitleFile = wfLocalFile( $this->title );
1546 $newTitleFile = wfLocalFile( $target );
1547 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1548 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1549 $this->getRepo()->getMasterDB()->onTransactionIdle(
1550 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1551 $oldTitleFile->purgeEverything();
1552 foreach ( $archiveNames as $archiveName ) {
1553 $oldTitleFile->purgeOldThumbnails( $archiveName );
1554 }
1555 $newTitleFile->purgeEverything();
1556 }
1557 );
1558
1559 if ( $status->isOK() ) {
1560 // Now switch the object
1561 $this->title = $target;
1562 // Force regeneration of the name and hashpath
1563 unset( $this->name );
1564 unset( $this->hashPath );
1565 }
1566
1567 return $status;
1568 }
1569
1570 /**
1571 * Delete all versions of the file.
1572 *
1573 * Moves the files into an archive directory (or deletes them)
1574 * and removes the database rows.
1575 *
1576 * Cache purging is done; logging is caller's responsibility.
1577 *
1578 * @param string $reason
1579 * @param bool $suppress
1580 * @param User|null $user
1581 * @return FileRepoStatus
1582 */
1583 function delete( $reason, $suppress = false, $user = null ) {
1584 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1585 return $this->readOnlyFatalStatus();
1586 }
1587
1588 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1589
1590 $this->lock(); // begin
1591 $batch->addCurrent();
1592 # Get old version relative paths
1593 $archiveNames = $batch->addOlds();
1594 $status = $batch->execute();
1595 $this->unlock(); // done
1596
1597 if ( $status->isOK() ) {
1598 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => -1 ) ) );
1599 }
1600
1601 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1602 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1603 $that = $this;
1604 $this->getRepo()->getMasterDB()->onTransactionIdle(
1605 function () use ( $that, $archiveNames ) {
1606 global $wgUseSquid;
1607
1608 $that->purgeEverything();
1609 foreach ( $archiveNames as $archiveName ) {
1610 $that->purgeOldThumbnails( $archiveName );
1611 }
1612
1613 if ( $wgUseSquid ) {
1614 // Purge the squid
1615 $purgeUrls = array();
1616 foreach ( $archiveNames as $archiveName ) {
1617 $purgeUrls[] = $that->getArchiveUrl( $archiveName );
1618 }
1619 SquidUpdate::purge( $purgeUrls );
1620 }
1621 }
1622 );
1623
1624 return $status;
1625 }
1626
1627 /**
1628 * Delete an old version of the file.
1629 *
1630 * Moves the file into an archive directory (or deletes it)
1631 * and removes the database row.
1632 *
1633 * Cache purging is done; logging is caller's responsibility.
1634 *
1635 * @param string $archiveName
1636 * @param string $reason
1637 * @param bool $suppress
1638 * @param User|null $user
1639 * @throws MWException Exception on database or file store failure
1640 * @return FileRepoStatus
1641 */
1642 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1643 global $wgUseSquid;
1644 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1645 return $this->readOnlyFatalStatus();
1646 }
1647
1648 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1649
1650 $this->lock(); // begin
1651 $batch->addOld( $archiveName );
1652 $status = $batch->execute();
1653 $this->unlock(); // done
1654
1655 $this->purgeOldThumbnails( $archiveName );
1656 if ( $status->isOK() ) {
1657 $this->purgeDescription();
1658 }
1659
1660 if ( $wgUseSquid ) {
1661 // Purge the squid
1662 SquidUpdate::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1663 }
1664
1665 return $status;
1666 }
1667
1668 /**
1669 * Restore all or specified deleted revisions to the given file.
1670 * Permissions and logging are left to the caller.
1671 *
1672 * May throw database exceptions on error.
1673 *
1674 * @param array $versions Set of record ids of deleted items to restore,
1675 * or empty to restore all revisions.
1676 * @param bool $unsuppress
1677 * @return FileRepoStatus
1678 */
1679 function restore( $versions = array(), $unsuppress = false ) {
1680 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1681 return $this->readOnlyFatalStatus();
1682 }
1683
1684 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1685
1686 $this->lock(); // begin
1687 if ( !$versions ) {
1688 $batch->addAll();
1689 } else {
1690 $batch->addIds( $versions );
1691 }
1692 $status = $batch->execute();
1693 if ( $status->isGood() ) {
1694 $cleanupStatus = $batch->cleanup();
1695 $cleanupStatus->successCount = 0;
1696 $cleanupStatus->failCount = 0;
1697 $status->merge( $cleanupStatus );
1698 }
1699 $this->unlock(); // done
1700
1701 return $status;
1702 }
1703
1704 /** isMultipage inherited */
1705 /** pageCount inherited */
1706 /** scaleHeight inherited */
1707 /** getImageSize inherited */
1708
1709 /**
1710 * Get the URL of the file description page.
1711 * @return string
1712 */
1713 function getDescriptionUrl() {
1714 return $this->title->getLocalURL();
1715 }
1716
1717 /**
1718 * Get the HTML text of the description page
1719 * This is not used by ImagePage for local files, since (among other things)
1720 * it skips the parser cache.
1721 *
1722 * @param Language $lang What language to get description in (Optional)
1723 * @return bool|mixed
1724 */
1725 function getDescriptionText( $lang = null ) {
1726 $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
1727 if ( !$revision ) {
1728 return false;
1729 }
1730 $content = $revision->getContent();
1731 if ( !$content ) {
1732 return false;
1733 }
1734 $pout = $content->getParserOutput( $this->title, null, new ParserOptions( null, $lang ) );
1735
1736 return $pout->getText();
1737 }
1738
1739 /**
1740 * @param int $audience
1741 * @param User $user
1742 * @return string
1743 */
1744 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1745 $this->load();
1746 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
1747 return '';
1748 } elseif ( $audience == self::FOR_THIS_USER
1749 && !$this->userCan( self::DELETED_COMMENT, $user )
1750 ) {
1751 return '';
1752 } else {
1753 return $this->description;
1754 }
1755 }
1756
1757 /**
1758 * @return bool|string
1759 */
1760 function getTimestamp() {
1761 $this->load();
1762
1763 return $this->timestamp;
1764 }
1765
1766 /**
1767 * @return bool|string
1768 */
1769 public function getDescriptionTouched() {
1770 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1771 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1772 // need to differentiate between null (uninitialized) and false (failed to load).
1773 if ( $this->descriptionTouched === null ) {
1774 $cond = array(
1775 'page_namespace' => $this->title->getNamespace(),
1776 'page_title' => $this->title->getDBkey()
1777 );
1778 $touched = $this->repo->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
1779 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
1780 }
1781
1782 return $this->descriptionTouched;
1783 }
1784
1785 /**
1786 * @return string
1787 */
1788 function getSha1() {
1789 $this->load();
1790 // Initialise now if necessary
1791 if ( $this->sha1 == '' && $this->fileExists ) {
1792 $this->lock(); // begin
1793
1794 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
1795 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1796 $dbw = $this->repo->getMasterDB();
1797 $dbw->update( 'image',
1798 array( 'img_sha1' => $this->sha1 ),
1799 array( 'img_name' => $this->getName() ),
1800 __METHOD__ );
1801 $this->invalidateCache();
1802 }
1803
1804 $this->unlock(); // done
1805 }
1806
1807 return $this->sha1;
1808 }
1809
1810 /**
1811 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1812 */
1813 function isCacheable() {
1814 $this->load();
1815
1816 // If extra data (metadata) was not loaded then it must have been large
1817 return $this->extraDataLoaded
1818 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
1819 }
1820
1821 /**
1822 * Start a transaction and lock the image for update
1823 * Increments a reference counter if the lock is already held
1824 * @throws MWException Throws an error if the lock was not acquired
1825 * @return bool Whether the file lock owns/spawned the DB transaction
1826 */
1827 function lock() {
1828 $dbw = $this->repo->getMasterDB();
1829
1830 if ( !$this->locked ) {
1831 if ( !$dbw->trxLevel() ) {
1832 $dbw->begin( __METHOD__ );
1833 $this->lockedOwnTrx = true;
1834 }
1835 $this->locked++;
1836 // Bug 54736: use simple lock to handle when the file does not exist.
1837 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1838 // Also, that would cause contention on INSERT of similarly named rows.
1839 $backend = $this->getRepo()->getBackend();
1840 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1841 $status = $backend->lockFiles( $lockPaths, LockManager::LOCK_EX, 5 );
1842 if ( !$status->isGood() ) {
1843 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1844 }
1845 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1846 $backend->unlockFiles( $lockPaths, LockManager::LOCK_EX ); // release on commit
1847 } );
1848 }
1849
1850 return $this->lockedOwnTrx;
1851 }
1852
1853 /**
1854 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1855 * the transaction and thereby releases the image lock.
1856 */
1857 function unlock() {
1858 if ( $this->locked ) {
1859 --$this->locked;
1860 if ( !$this->locked && $this->lockedOwnTrx ) {
1861 $dbw = $this->repo->getMasterDB();
1862 $dbw->commit( __METHOD__ );
1863 $this->lockedOwnTrx = false;
1864 }
1865 }
1866 }
1867
1868 /**
1869 * Roll back the DB transaction and mark the image unlocked
1870 */
1871 function unlockAndRollback() {
1872 $this->locked = false;
1873 $dbw = $this->repo->getMasterDB();
1874 $dbw->rollback( __METHOD__ );
1875 $this->lockedOwnTrx = false;
1876 }
1877
1878 /**
1879 * @return Status
1880 */
1881 protected function readOnlyFatalStatus() {
1882 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1883 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1884 }
1885
1886 /**
1887 * Clean up any dangling locks
1888 */
1889 function __destruct() {
1890 $this->unlock();
1891 }
1892 } // LocalFile class
1893
1894 # ------------------------------------------------------------------------------
1895
1896 /**
1897 * Helper class for file deletion
1898 * @ingroup FileAbstraction
1899 */
1900 class LocalFileDeleteBatch {
1901 /** @var LocalFile */
1902 private $file;
1903
1904 /** @var string */
1905 private $reason;
1906
1907 /** @var array */
1908 private $srcRels = array();
1909
1910 /** @var array */
1911 private $archiveUrls = array();
1912
1913 /** @var array Items to be processed in the deletion batch */
1914 private $deletionBatch;
1915
1916 /** @var bool Whether to suppress all suppressable fields when deleting */
1917 private $suppress;
1918
1919 /** @var FileRepoStatus */
1920 private $status;
1921
1922 /** @var User */
1923 private $user;
1924
1925 /**
1926 * @param File $file
1927 * @param string $reason
1928 * @param bool $suppress
1929 * @param User|null $user
1930 */
1931 function __construct( File $file, $reason = '', $suppress = false, $user = null ) {
1932 $this->file = $file;
1933 $this->reason = $reason;
1934 $this->suppress = $suppress;
1935 if ( $user ) {
1936 $this->user = $user;
1937 } else {
1938 global $wgUser;
1939 $this->user = $wgUser;
1940 }
1941 $this->status = $file->repo->newGood();
1942 }
1943
1944 function addCurrent() {
1945 $this->srcRels['.'] = $this->file->getRel();
1946 }
1947
1948 /**
1949 * @param string $oldName
1950 */
1951 function addOld( $oldName ) {
1952 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1953 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1954 }
1955
1956 /**
1957 * Add the old versions of the image to the batch
1958 * @return array List of archive names from old versions
1959 */
1960 function addOlds() {
1961 $archiveNames = array();
1962
1963 $dbw = $this->file->repo->getMasterDB();
1964 $result = $dbw->select( 'oldimage',
1965 array( 'oi_archive_name' ),
1966 array( 'oi_name' => $this->file->getName() ),
1967 __METHOD__
1968 );
1969
1970 foreach ( $result as $row ) {
1971 $this->addOld( $row->oi_archive_name );
1972 $archiveNames[] = $row->oi_archive_name;
1973 }
1974
1975 return $archiveNames;
1976 }
1977
1978 /**
1979 * @return array
1980 */
1981 function getOldRels() {
1982 if ( !isset( $this->srcRels['.'] ) ) {
1983 $oldRels =& $this->srcRels;
1984 $deleteCurrent = false;
1985 } else {
1986 $oldRels = $this->srcRels;
1987 unset( $oldRels['.'] );
1988 $deleteCurrent = true;
1989 }
1990
1991 return array( $oldRels, $deleteCurrent );
1992 }
1993
1994 /**
1995 * @return array
1996 */
1997 protected function getHashes() {
1998 $hashes = array();
1999 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2000
2001 if ( $deleteCurrent ) {
2002 $hashes['.'] = $this->file->getSha1();
2003 }
2004
2005 if ( count( $oldRels ) ) {
2006 $dbw = $this->file->repo->getMasterDB();
2007 $res = $dbw->select(
2008 'oldimage',
2009 array( 'oi_archive_name', 'oi_sha1' ),
2010 array( 'oi_archive_name' => array_keys( $oldRels ),
2011 'oi_name' => $this->file->getName() ), // performance
2012 __METHOD__
2013 );
2014
2015 foreach ( $res as $row ) {
2016 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
2017 // Get the hash from the file
2018 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2019 $props = $this->file->repo->getFileProps( $oldUrl );
2020
2021 if ( $props['fileExists'] ) {
2022 // Upgrade the oldimage row
2023 $dbw->update( 'oldimage',
2024 array( 'oi_sha1' => $props['sha1'] ),
2025 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
2026 __METHOD__ );
2027 $hashes[$row->oi_archive_name] = $props['sha1'];
2028 } else {
2029 $hashes[$row->oi_archive_name] = false;
2030 }
2031 } else {
2032 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2033 }
2034 }
2035 }
2036
2037 $missing = array_diff_key( $this->srcRels, $hashes );
2038
2039 foreach ( $missing as $name => $rel ) {
2040 $this->status->error( 'filedelete-old-unregistered', $name );
2041 }
2042
2043 foreach ( $hashes as $name => $hash ) {
2044 if ( !$hash ) {
2045 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2046 unset( $hashes[$name] );
2047 }
2048 }
2049
2050 return $hashes;
2051 }
2052
2053 function doDBInserts() {
2054 $dbw = $this->file->repo->getMasterDB();
2055 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2056 $encUserId = $dbw->addQuotes( $this->user->getId() );
2057 $encReason = $dbw->addQuotes( $this->reason );
2058 $encGroup = $dbw->addQuotes( 'deleted' );
2059 $ext = $this->file->getExtension();
2060 $dotExt = $ext === '' ? '' : ".$ext";
2061 $encExt = $dbw->addQuotes( $dotExt );
2062 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2063
2064 // Bitfields to further suppress the content
2065 if ( $this->suppress ) {
2066 $bitfield = 0;
2067 // This should be 15...
2068 $bitfield |= Revision::DELETED_TEXT;
2069 $bitfield |= Revision::DELETED_COMMENT;
2070 $bitfield |= Revision::DELETED_USER;
2071 $bitfield |= Revision::DELETED_RESTRICTED;
2072 } else {
2073 $bitfield = 'oi_deleted';
2074 }
2075
2076 if ( $deleteCurrent ) {
2077 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2078 $where = array( 'img_name' => $this->file->getName() );
2079 $dbw->insertSelect( 'filearchive', 'image',
2080 array(
2081 'fa_storage_group' => $encGroup,
2082 'fa_storage_key' => $dbw->conditional(
2083 array( 'img_sha1' => '' ),
2084 $dbw->addQuotes( '' ),
2085 $concat
2086 ),
2087 'fa_deleted_user' => $encUserId,
2088 'fa_deleted_timestamp' => $encTimestamp,
2089 'fa_deleted_reason' => $encReason,
2090 'fa_deleted' => $this->suppress ? $bitfield : 0,
2091
2092 'fa_name' => 'img_name',
2093 'fa_archive_name' => 'NULL',
2094 'fa_size' => 'img_size',
2095 'fa_width' => 'img_width',
2096 'fa_height' => 'img_height',
2097 'fa_metadata' => 'img_metadata',
2098 'fa_bits' => 'img_bits',
2099 'fa_media_type' => 'img_media_type',
2100 'fa_major_mime' => 'img_major_mime',
2101 'fa_minor_mime' => 'img_minor_mime',
2102 'fa_description' => 'img_description',
2103 'fa_user' => 'img_user',
2104 'fa_user_text' => 'img_user_text',
2105 'fa_timestamp' => 'img_timestamp',
2106 'fa_sha1' => 'img_sha1',
2107 ), $where, __METHOD__ );
2108 }
2109
2110 if ( count( $oldRels ) ) {
2111 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2112 $where = array(
2113 'oi_name' => $this->file->getName(),
2114 'oi_archive_name' => array_keys( $oldRels ) );
2115 $dbw->insertSelect( 'filearchive', 'oldimage',
2116 array(
2117 'fa_storage_group' => $encGroup,
2118 'fa_storage_key' => $dbw->conditional(
2119 array( 'oi_sha1' => '' ),
2120 $dbw->addQuotes( '' ),
2121 $concat
2122 ),
2123 'fa_deleted_user' => $encUserId,
2124 'fa_deleted_timestamp' => $encTimestamp,
2125 'fa_deleted_reason' => $encReason,
2126 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
2127
2128 'fa_name' => 'oi_name',
2129 'fa_archive_name' => 'oi_archive_name',
2130 'fa_size' => 'oi_size',
2131 'fa_width' => 'oi_width',
2132 'fa_height' => 'oi_height',
2133 'fa_metadata' => 'oi_metadata',
2134 'fa_bits' => 'oi_bits',
2135 'fa_media_type' => 'oi_media_type',
2136 'fa_major_mime' => 'oi_major_mime',
2137 'fa_minor_mime' => 'oi_minor_mime',
2138 'fa_description' => 'oi_description',
2139 'fa_user' => 'oi_user',
2140 'fa_user_text' => 'oi_user_text',
2141 'fa_timestamp' => 'oi_timestamp',
2142 'fa_sha1' => 'oi_sha1',
2143 ), $where, __METHOD__ );
2144 }
2145 }
2146
2147 function doDBDeletes() {
2148 $dbw = $this->file->repo->getMasterDB();
2149 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2150
2151 if ( count( $oldRels ) ) {
2152 $dbw->delete( 'oldimage',
2153 array(
2154 'oi_name' => $this->file->getName(),
2155 'oi_archive_name' => array_keys( $oldRels )
2156 ), __METHOD__ );
2157 }
2158
2159 if ( $deleteCurrent ) {
2160 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
2161 }
2162 }
2163
2164 /**
2165 * Run the transaction
2166 * @return FileRepoStatus
2167 */
2168 function execute() {
2169
2170 $this->file->lock();
2171
2172 // Prepare deletion batch
2173 $hashes = $this->getHashes();
2174 $this->deletionBatch = array();
2175 $ext = $this->file->getExtension();
2176 $dotExt = $ext === '' ? '' : ".$ext";
2177
2178 foreach ( $this->srcRels as $name => $srcRel ) {
2179 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2180 if ( isset( $hashes[$name] ) ) {
2181 $hash = $hashes[$name];
2182 $key = $hash . $dotExt;
2183 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
2184 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
2185 }
2186 }
2187
2188 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2189 // We acquire this lock by running the inserts now, before the file operations.
2190 //
2191 // This potentially has poor lock contention characteristics -- an alternative
2192 // scheme would be to insert stub filearchive entries with no fa_name and commit
2193 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2194 $this->doDBInserts();
2195
2196 // Removes non-existent file from the batch, so we don't get errors.
2197 // This also handles files in the 'deleted' zone deleted via revision deletion.
2198 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch );
2199 if ( !$checkStatus->isGood() ) {
2200 $this->status->merge( $checkStatus );
2201 return $this->status;
2202 }
2203 $this->deletionBatch = $checkStatus->value;
2204
2205 // Execute the file deletion batch
2206 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2207
2208 if ( !$status->isGood() ) {
2209 $this->status->merge( $status );
2210 }
2211
2212 if ( !$this->status->isOK() ) {
2213 // Critical file deletion error
2214 // Roll back inserts, release lock and abort
2215 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2216 $this->file->unlockAndRollback();
2217
2218 return $this->status;
2219 }
2220
2221 // Delete image/oldimage rows
2222 $this->doDBDeletes();
2223
2224 // Commit and return
2225 $this->file->unlock();
2226
2227 return $this->status;
2228 }
2229
2230 /**
2231 * Removes non-existent files from a deletion batch.
2232 * @param array $batch
2233 * @return Status
2234 */
2235 function removeNonexistentFiles( $batch ) {
2236 $files = $newBatch = array();
2237
2238 foreach ( $batch as $batchItem ) {
2239 list( $src, ) = $batchItem;
2240 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2241 }
2242
2243 $result = $this->file->repo->fileExistsBatch( $files );
2244 if ( in_array( null, $result, true ) ) {
2245 return Status::newFatal( 'backend-fail-internal',
2246 $this->file->repo->getBackend()->getName() );
2247 }
2248
2249 foreach ( $batch as $batchItem ) {
2250 if ( $result[$batchItem[0]] ) {
2251 $newBatch[] = $batchItem;
2252 }
2253 }
2254
2255 return Status::newGood( $newBatch );
2256 }
2257 }
2258
2259 # ------------------------------------------------------------------------------
2260
2261 /**
2262 * Helper class for file undeletion
2263 * @ingroup FileAbstraction
2264 */
2265 class LocalFileRestoreBatch {
2266 /** @var LocalFile */
2267 private $file;
2268
2269 /** @var array List of file IDs to restore */
2270 private $cleanupBatch;
2271
2272 /** @var array List of file IDs to restore */
2273 private $ids;
2274
2275 /** @var bool Add all revisions of the file */
2276 private $all;
2277
2278 /** @var bool Whether to remove all settings for suppressed fields */
2279 private $unsuppress = false;
2280
2281 /**
2282 * @param File $file
2283 * @param bool $unsuppress
2284 */
2285 function __construct( File $file, $unsuppress = false ) {
2286 $this->file = $file;
2287 $this->cleanupBatch = $this->ids = array();
2288 $this->ids = array();
2289 $this->unsuppress = $unsuppress;
2290 }
2291
2292 /**
2293 * Add a file by ID
2294 * @param int $fa_id
2295 */
2296 function addId( $fa_id ) {
2297 $this->ids[] = $fa_id;
2298 }
2299
2300 /**
2301 * Add a whole lot of files by ID
2302 * @param int[] $ids
2303 */
2304 function addIds( $ids ) {
2305 $this->ids = array_merge( $this->ids, $ids );
2306 }
2307
2308 /**
2309 * Add all revisions of the file
2310 */
2311 function addAll() {
2312 $this->all = true;
2313 }
2314
2315 /**
2316 * Run the transaction, except the cleanup batch.
2317 * The cleanup batch should be run in a separate transaction, because it locks different
2318 * rows and there's no need to keep the image row locked while it's acquiring those locks
2319 * The caller may have its own transaction open.
2320 * So we save the batch and let the caller call cleanup()
2321 * @return FileRepoStatus
2322 */
2323 function execute() {
2324 global $wgLang;
2325
2326 if ( !$this->all && !$this->ids ) {
2327 // Do nothing
2328 return $this->file->repo->newGood();
2329 }
2330
2331 $lockOwnsTrx = $this->file->lock();
2332
2333 $dbw = $this->file->repo->getMasterDB();
2334 $status = $this->file->repo->newGood();
2335
2336 $exists = (bool)$dbw->selectField( 'image', '1',
2337 array( 'img_name' => $this->file->getName() ),
2338 __METHOD__,
2339 // The lock() should already prevents changes, but this still may need
2340 // to bypass any transaction snapshot. However, if lock() started the
2341 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2342 $lockOwnsTrx ? array() : array( 'LOCK IN SHARE MODE' )
2343 );
2344
2345 // Fetch all or selected archived revisions for the file,
2346 // sorted from the most recent to the oldest.
2347 $conditions = array( 'fa_name' => $this->file->getName() );
2348
2349 if ( !$this->all ) {
2350 $conditions['fa_id'] = $this->ids;
2351 }
2352
2353 $result = $dbw->select(
2354 'filearchive',
2355 ArchivedFile::selectFields(),
2356 $conditions,
2357 __METHOD__,
2358 array( 'ORDER BY' => 'fa_timestamp DESC' )
2359 );
2360
2361 $idsPresent = array();
2362 $storeBatch = array();
2363 $insertBatch = array();
2364 $insertCurrent = false;
2365 $deleteIds = array();
2366 $first = true;
2367 $archiveNames = array();
2368
2369 foreach ( $result as $row ) {
2370 $idsPresent[] = $row->fa_id;
2371
2372 if ( $row->fa_name != $this->file->getName() ) {
2373 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2374 $status->failCount++;
2375 continue;
2376 }
2377
2378 if ( $row->fa_storage_key == '' ) {
2379 // Revision was missing pre-deletion
2380 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2381 $status->failCount++;
2382 continue;
2383 }
2384
2385 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) .
2386 $row->fa_storage_key;
2387 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2388
2389 if ( isset( $row->fa_sha1 ) ) {
2390 $sha1 = $row->fa_sha1;
2391 } else {
2392 // old row, populate from key
2393 $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2394 }
2395
2396 # Fix leading zero
2397 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2398 $sha1 = substr( $sha1, 1 );
2399 }
2400
2401 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2402 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2403 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2404 || is_null( $row->fa_metadata )
2405 ) {
2406 // Refresh our metadata
2407 // Required for a new current revision; nice for older ones too. :)
2408 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2409 } else {
2410 $props = array(
2411 'minor_mime' => $row->fa_minor_mime,
2412 'major_mime' => $row->fa_major_mime,
2413 'media_type' => $row->fa_media_type,
2414 'metadata' => $row->fa_metadata
2415 );
2416 }
2417
2418 if ( $first && !$exists ) {
2419 // This revision will be published as the new current version
2420 $destRel = $this->file->getRel();
2421 $insertCurrent = array(
2422 'img_name' => $row->fa_name,
2423 'img_size' => $row->fa_size,
2424 'img_width' => $row->fa_width,
2425 'img_height' => $row->fa_height,
2426 'img_metadata' => $props['metadata'],
2427 'img_bits' => $row->fa_bits,
2428 'img_media_type' => $props['media_type'],
2429 'img_major_mime' => $props['major_mime'],
2430 'img_minor_mime' => $props['minor_mime'],
2431 'img_description' => $row->fa_description,
2432 'img_user' => $row->fa_user,
2433 'img_user_text' => $row->fa_user_text,
2434 'img_timestamp' => $row->fa_timestamp,
2435 'img_sha1' => $sha1
2436 );
2437
2438 // The live (current) version cannot be hidden!
2439 if ( !$this->unsuppress && $row->fa_deleted ) {
2440 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2441 $this->cleanupBatch[] = $row->fa_storage_key;
2442 }
2443 } else {
2444 $archiveName = $row->fa_archive_name;
2445
2446 if ( $archiveName == '' ) {
2447 // This was originally a current version; we
2448 // have to devise a new archive name for it.
2449 // Format is <timestamp of archiving>!<name>
2450 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2451
2452 do {
2453 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2454 $timestamp++;
2455 } while ( isset( $archiveNames[$archiveName] ) );
2456 }
2457
2458 $archiveNames[$archiveName] = true;
2459 $destRel = $this->file->getArchiveRel( $archiveName );
2460 $insertBatch[] = array(
2461 'oi_name' => $row->fa_name,
2462 'oi_archive_name' => $archiveName,
2463 'oi_size' => $row->fa_size,
2464 'oi_width' => $row->fa_width,
2465 'oi_height' => $row->fa_height,
2466 'oi_bits' => $row->fa_bits,
2467 'oi_description' => $row->fa_description,
2468 'oi_user' => $row->fa_user,
2469 'oi_user_text' => $row->fa_user_text,
2470 'oi_timestamp' => $row->fa_timestamp,
2471 'oi_metadata' => $props['metadata'],
2472 'oi_media_type' => $props['media_type'],
2473 'oi_major_mime' => $props['major_mime'],
2474 'oi_minor_mime' => $props['minor_mime'],
2475 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2476 'oi_sha1' => $sha1 );
2477 }
2478
2479 $deleteIds[] = $row->fa_id;
2480
2481 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2482 // private files can stay where they are
2483 $status->successCount++;
2484 } else {
2485 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2486 $this->cleanupBatch[] = $row->fa_storage_key;
2487 }
2488
2489 $first = false;
2490 }
2491
2492 unset( $result );
2493
2494 // Add a warning to the status object for missing IDs
2495 $missingIds = array_diff( $this->ids, $idsPresent );
2496
2497 foreach ( $missingIds as $id ) {
2498 $status->error( 'undelete-missing-filearchive', $id );
2499 }
2500
2501 // Remove missing files from batch, so we don't get errors when undeleting them
2502 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2503 if ( !$checkStatus->isGood() ) {
2504 $status->merge( $checkStatus );
2505 return $status;
2506 }
2507 $storeBatch = $checkStatus->value;
2508
2509 // Run the store batch
2510 // Use the OVERWRITE_SAME flag to smooth over a common error
2511 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2512 $status->merge( $storeStatus );
2513
2514 if ( !$status->isGood() ) {
2515 // Even if some files could be copied, fail entirely as that is the
2516 // easiest thing to do without data loss
2517 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2518 $status->ok = false;
2519 $this->file->unlock();
2520
2521 return $status;
2522 }
2523
2524 // Run the DB updates
2525 // Because we have locked the image row, key conflicts should be rare.
2526 // If they do occur, we can roll back the transaction at this time with
2527 // no data loss, but leaving unregistered files scattered throughout the
2528 // public zone.
2529 // This is not ideal, which is why it's important to lock the image row.
2530 if ( $insertCurrent ) {
2531 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2532 }
2533
2534 if ( $insertBatch ) {
2535 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2536 }
2537
2538 if ( $deleteIds ) {
2539 $dbw->delete( 'filearchive',
2540 array( 'fa_id' => $deleteIds ),
2541 __METHOD__ );
2542 }
2543
2544 // If store batch is empty (all files are missing), deletion is to be considered successful
2545 if ( $status->successCount > 0 || !$storeBatch ) {
2546 if ( !$exists ) {
2547 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2548
2549 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
2550
2551 $this->file->purgeEverything();
2552 } else {
2553 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2554 $this->file->purgeDescription();
2555 }
2556 }
2557
2558 $this->file->unlock();
2559
2560 return $status;
2561 }
2562
2563 /**
2564 * Removes non-existent files from a store batch.
2565 * @param array $triplets
2566 * @return Status
2567 */
2568 function removeNonexistentFiles( $triplets ) {
2569 $files = $filteredTriplets = array();
2570 foreach ( $triplets as $file ) {
2571 $files[$file[0]] = $file[0];
2572 }
2573
2574 $result = $this->file->repo->fileExistsBatch( $files );
2575 if ( in_array( null, $result, true ) ) {
2576 return Status::newFatal( 'backend-fail-internal',
2577 $this->file->repo->getBackend()->getName() );
2578 }
2579
2580 foreach ( $triplets as $file ) {
2581 if ( $result[$file[0]] ) {
2582 $filteredTriplets[] = $file;
2583 }
2584 }
2585
2586 return Status::newGood( $filteredTriplets );
2587 }
2588
2589 /**
2590 * Removes non-existent files from a cleanup batch.
2591 * @param array $batch
2592 * @return array
2593 */
2594 function removeNonexistentFromCleanup( $batch ) {
2595 $files = $newBatch = array();
2596 $repo = $this->file->repo;
2597
2598 foreach ( $batch as $file ) {
2599 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2600 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2601 }
2602
2603 $result = $repo->fileExistsBatch( $files );
2604
2605 foreach ( $batch as $file ) {
2606 if ( $result[$file] ) {
2607 $newBatch[] = $file;
2608 }
2609 }
2610
2611 return $newBatch;
2612 }
2613
2614 /**
2615 * Delete unused files in the deleted zone.
2616 * This should be called from outside the transaction in which execute() was called.
2617 * @return FileRepoStatus
2618 */
2619 function cleanup() {
2620 if ( !$this->cleanupBatch ) {
2621 return $this->file->repo->newGood();
2622 }
2623
2624 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2625
2626 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2627
2628 return $status;
2629 }
2630
2631 /**
2632 * Cleanup a failed batch. The batch was only partially successful, so
2633 * rollback by removing all items that were succesfully copied.
2634 *
2635 * @param Status $storeStatus
2636 * @param array $storeBatch
2637 */
2638 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2639 $cleanupBatch = array();
2640
2641 foreach ( $storeStatus->success as $i => $success ) {
2642 // Check if this item of the batch was successfully copied
2643 if ( $success ) {
2644 // Item was successfully copied and needs to be removed again
2645 // Extract ($dstZone, $dstRel) from the batch
2646 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2647 }
2648 }
2649 $this->file->repo->cleanupBatch( $cleanupBatch );
2650 }
2651 }
2652
2653 # ------------------------------------------------------------------------------
2654
2655 /**
2656 * Helper class for file movement
2657 * @ingroup FileAbstraction
2658 */
2659 class LocalFileMoveBatch {
2660 /** @var LocalFile */
2661 protected $file;
2662
2663 /** @var Title */
2664 protected $target;
2665
2666 protected $cur;
2667
2668 protected $olds;
2669
2670 protected $oldCount;
2671
2672 protected $archive;
2673
2674 /** @var DatabaseBase */
2675 protected $db;
2676
2677 /**
2678 * @param File $file
2679 * @param Title $target
2680 */
2681 function __construct( File $file, Title $target ) {
2682 $this->file = $file;
2683 $this->target = $target;
2684 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2685 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2686 $this->oldName = $this->file->getName();
2687 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2688 $this->oldRel = $this->oldHash . $this->oldName;
2689 $this->newRel = $this->newHash . $this->newName;
2690 $this->db = $file->getRepo()->getMasterDb();
2691 }
2692
2693 /**
2694 * Add the current image to the batch
2695 */
2696 function addCurrent() {
2697 $this->cur = array( $this->oldRel, $this->newRel );
2698 }
2699
2700 /**
2701 * Add the old versions of the image to the batch
2702 * @return array List of archive names from old versions
2703 */
2704 function addOlds() {
2705 $archiveBase = 'archive';
2706 $this->olds = array();
2707 $this->oldCount = 0;
2708 $archiveNames = array();
2709
2710 $result = $this->db->select( 'oldimage',
2711 array( 'oi_archive_name', 'oi_deleted' ),
2712 array( 'oi_name' => $this->oldName ),
2713 __METHOD__,
2714 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2715 );
2716
2717 foreach ( $result as $row ) {
2718 $archiveNames[] = $row->oi_archive_name;
2719 $oldName = $row->oi_archive_name;
2720 $bits = explode( '!', $oldName, 2 );
2721
2722 if ( count( $bits ) != 2 ) {
2723 wfDebug( "Old file name missing !: '$oldName' \n" );
2724 continue;
2725 }
2726
2727 list( $timestamp, $filename ) = $bits;
2728
2729 if ( $this->oldName != $filename ) {
2730 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2731 continue;
2732 }
2733
2734 $this->oldCount++;
2735
2736 // Do we want to add those to oldCount?
2737 if ( $row->oi_deleted & File::DELETED_FILE ) {
2738 continue;
2739 }
2740
2741 $this->olds[] = array(
2742 "{$archiveBase}/{$this->oldHash}{$oldName}",
2743 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2744 );
2745 }
2746
2747 return $archiveNames;
2748 }
2749
2750 /**
2751 * Perform the move.
2752 * @return FileRepoStatus
2753 */
2754 function execute() {
2755 $repo = $this->file->repo;
2756 $status = $repo->newGood();
2757
2758 $triplets = $this->getMoveTriplets();
2759 $checkStatus = $this->removeNonexistentFiles( $triplets );
2760 if ( !$checkStatus->isGood() ) {
2761 $status->merge( $checkStatus );
2762 return $status;
2763 }
2764 $triplets = $checkStatus->value;
2765 $destFile = wfLocalFile( $this->target );
2766
2767 $this->file->lock(); // begin
2768 $destFile->lock(); // quickly fail if destination is not available
2769 // Rename the file versions metadata in the DB.
2770 // This implicitly locks the destination file, which avoids race conditions.
2771 // If we moved the files from A -> C before DB updates, another process could
2772 // move files from B -> C at this point, causing storeBatch() to fail and thus
2773 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2774 $statusDb = $this->doDBUpdates();
2775 if ( !$statusDb->isGood() ) {
2776 $destFile->unlock();
2777 $this->file->unlockAndRollback();
2778 $statusDb->ok = false;
2779
2780 return $statusDb;
2781 }
2782 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2783 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2784
2785 // Copy the files into their new location.
2786 // If a prior process fataled copying or cleaning up files we tolerate any
2787 // of the existing files if they are identical to the ones being stored.
2788 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
2789 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2790 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2791 if ( !$statusMove->isGood() ) {
2792 // Delete any files copied over (while the destination is still locked)
2793 $this->cleanupTarget( $triplets );
2794 $destFile->unlock();
2795 $this->file->unlockAndRollback(); // unlocks the destination
2796 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2797 $statusMove->ok = false;
2798
2799 return $statusMove;
2800 }
2801 $destFile->unlock();
2802 $this->file->unlock(); // done
2803
2804 // Everything went ok, remove the source files
2805 $this->cleanupSource( $triplets );
2806
2807 $status->merge( $statusDb );
2808 $status->merge( $statusMove );
2809
2810 return $status;
2811 }
2812
2813 /**
2814 * Do the database updates and return a new FileRepoStatus indicating how
2815 * many rows where updated.
2816 *
2817 * @return FileRepoStatus
2818 */
2819 function doDBUpdates() {
2820 $repo = $this->file->repo;
2821 $status = $repo->newGood();
2822 $dbw = $this->db;
2823
2824 // Update current image
2825 $dbw->update(
2826 'image',
2827 array( 'img_name' => $this->newName ),
2828 array( 'img_name' => $this->oldName ),
2829 __METHOD__
2830 );
2831
2832 if ( $dbw->affectedRows() ) {
2833 $status->successCount++;
2834 } else {
2835 $status->failCount++;
2836 $status->fatal( 'imageinvalidfilename' );
2837
2838 return $status;
2839 }
2840
2841 // Update old images
2842 $dbw->update(
2843 'oldimage',
2844 array(
2845 'oi_name' => $this->newName,
2846 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2847 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2848 ),
2849 array( 'oi_name' => $this->oldName ),
2850 __METHOD__
2851 );
2852
2853 $affected = $dbw->affectedRows();
2854 $total = $this->oldCount;
2855 $status->successCount += $affected;
2856 // Bug 34934: $total is based on files that actually exist.
2857 // There may be more DB rows than such files, in which case $affected
2858 // can be greater than $total. We use max() to avoid negatives here.
2859 $status->failCount += max( 0, $total - $affected );
2860 if ( $status->failCount ) {
2861 $status->error( 'imageinvalidfilename' );
2862 }
2863
2864 return $status;
2865 }
2866
2867 /**
2868 * Generate triplets for FileRepo::storeBatch().
2869 * @return array
2870 */
2871 function getMoveTriplets() {
2872 $moves = array_merge( array( $this->cur ), $this->olds );
2873 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2874
2875 foreach ( $moves as $move ) {
2876 // $move: (oldRelativePath, newRelativePath)
2877 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2878 $triplets[] = array( $srcUrl, 'public', $move[1] );
2879 wfDebugLog(
2880 'imagemove',
2881 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2882 );
2883 }
2884
2885 return $triplets;
2886 }
2887
2888 /**
2889 * Removes non-existent files from move batch.
2890 * @param array $triplets
2891 * @return Status
2892 */
2893 function removeNonexistentFiles( $triplets ) {
2894 $files = array();
2895
2896 foreach ( $triplets as $file ) {
2897 $files[$file[0]] = $file[0];
2898 }
2899
2900 $result = $this->file->repo->fileExistsBatch( $files );
2901 if ( in_array( null, $result, true ) ) {
2902 return Status::newFatal( 'backend-fail-internal',
2903 $this->file->repo->getBackend()->getName() );
2904 }
2905
2906 $filteredTriplets = array();
2907 foreach ( $triplets as $file ) {
2908 if ( $result[$file[0]] ) {
2909 $filteredTriplets[] = $file;
2910 } else {
2911 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2912 }
2913 }
2914
2915 return Status::newGood( $filteredTriplets );
2916 }
2917
2918 /**
2919 * Cleanup a partially moved array of triplets by deleting the target
2920 * files. Called if something went wrong half way.
2921 * @param array $triplets
2922 */
2923 function cleanupTarget( $triplets ) {
2924 // Create dest pairs from the triplets
2925 $pairs = array();
2926 foreach ( $triplets as $triplet ) {
2927 // $triplet: (old source virtual URL, dst zone, dest rel)
2928 $pairs[] = array( $triplet[1], $triplet[2] );
2929 }
2930
2931 $this->file->repo->cleanupBatch( $pairs );
2932 }
2933
2934 /**
2935 * Cleanup a fully moved array of triplets by deleting the source files.
2936 * Called at the end of the move process if everything else went ok.
2937 * @param array $triplets
2938 */
2939 function cleanupSource( $triplets ) {
2940 // Create source file names from the triplets
2941 $files = array();
2942 foreach ( $triplets as $triplet ) {
2943 $files[] = $triplet[0];
2944 }
2945
2946 $this->file->repo->cleanupBatch( $files );
2947 }
2948 }