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