* (bug 13921) deadlocks mass-deleting media files in categories
[lhc/web/wiklou.git] / includes / filerepo / LocalFile.php
1 <?php
2 /**
3 * Local file in the wiki's own database
4 *
5 * @file
6 * @ingroup FileRepo
7 */
8
9 /**
10 * Bump this number when serialized cache records may be incompatible.
11 */
12 define( 'MW_FILE_VERSION', 8 );
13
14 /**
15 * Class to represent a local file in the wiki's own database
16 *
17 * Provides methods to retrieve paths (physical, logical, URL),
18 * to generate image thumbnails or for uploading.
19 *
20 * Note that only the repo object knows what its file class is called. You should
21 * never name a file class explictly outside of the repo class. Instead use the
22 * repo's factory functions to generate file objects, for example:
23 *
24 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
25 *
26 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
27 * in most cases.
28 *
29 * @ingroup FileRepo
30 */
31 class LocalFile extends File {
32 /**#@+
33 * @private
34 */
35 var
36 $fileExists, # does the file file exist on disk? (loadFromXxx)
37 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
38 $historyRes, # result of the query for the file's history (nextHistoryLine)
39 $width, # \
40 $height, # |
41 $bits, # --- returned by getimagesize (loadFromXxx)
42 $attr, # /
43 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
44 $mime, # MIME type, determined by MimeMagic::guessMimeType
45 $major_mime, # Major mime type
46 $minor_mime, # Minor mime type
47 $size, # Size in bytes (loadFromXxx)
48 $metadata, # Handler-specific metadata
49 $timestamp, # Upload timestamp
50 $sha1, # SHA-1 base 36 content hash
51 $user, $user_text, # User, who uploaded the file
52 $description, # Description of current revision of the file
53 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
54 $upgraded, # Whether the row was upgraded on load
55 $locked, # True if the image row is locked
56 $missing, # True if file is not present in file system. Not to be cached in memcached
57 $deleted; # Bitfield akin to rev_deleted
58
59 /**#@-*/
60
61 /**
62 * Create a LocalFile from a title
63 * Do not call this except from inside a repo class.
64 *
65 * Note: $unused param is only here to avoid an E_STRICT
66 */
67 static function newFromTitle( $title, $repo, $unused = null ) {
68 return new self( $title, $repo );
69 }
70
71 /**
72 * Create a LocalFile from a title
73 * Do not call this except from inside a repo class.
74 */
75 static function newFromRow( $row, $repo ) {
76 $title = Title::makeTitle( NS_FILE, $row->img_name );
77 $file = new self( $title, $repo );
78 $file->loadFromRow( $row );
79
80 return $file;
81 }
82
83 /**
84 * Create a LocalFile from a SHA-1 key
85 * Do not call this except from inside a repo class.
86 * @param $sha1
87 * @param $repo LocalRepo
88 * @param $timestamp
89 */
90 static function newFromKey( $sha1, $repo, $timestamp = false ) {
91 $conds = array( 'img_sha1' => $sha1 );
92
93 if ( $timestamp ) {
94 $conds['img_timestamp'] = $timestamp;
95 }
96
97 $dbr = $repo->getSlaveDB();
98 $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
99
100 if ( $row ) {
101 return self::newFromRow( $row, $repo );
102 } else {
103 return false;
104 }
105 }
106
107 /**
108 * Fields in the image table
109 */
110 static function selectFields() {
111 return array(
112 'img_name',
113 'img_size',
114 'img_width',
115 'img_height',
116 'img_metadata',
117 'img_bits',
118 'img_media_type',
119 'img_major_mime',
120 'img_minor_mime',
121 'img_description',
122 'img_user',
123 'img_user_text',
124 'img_timestamp',
125 'img_sha1',
126 );
127 }
128
129 /**
130 * Constructor.
131 * Do not call this except from inside a repo class.
132 */
133 function __construct( $title, $repo ) {
134 if ( !is_object( $title ) ) {
135 throw new MWException( __CLASS__ . ' constructor given bogus title.' );
136 }
137
138 parent::__construct( $title, $repo );
139
140 $this->metadata = '';
141 $this->historyLine = 0;
142 $this->historyRes = null;
143 $this->dataLoaded = false;
144 }
145
146 /**
147 * Get the memcached key for the main data for this file, or false if
148 * there is no access to the shared cache.
149 */
150 function getCacheKey() {
151 $hashedName = md5( $this->getName() );
152
153 return $this->repo->getSharedCacheKey( 'file', $hashedName );
154 }
155
156 /**
157 * Try to load file metadata from memcached. Returns true on success.
158 */
159 function loadFromCache() {
160 global $wgMemc;
161
162 wfProfileIn( __METHOD__ );
163 $this->dataLoaded = false;
164 $key = $this->getCacheKey();
165
166 if ( !$key ) {
167 wfProfileOut( __METHOD__ );
168 return false;
169 }
170
171 $cachedValues = $wgMemc->get( $key );
172
173 // Check if the key existed and belongs to this version of MediaWiki
174 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
175 wfDebug( "Pulling file metadata from cache key $key\n" );
176 $this->fileExists = $cachedValues['fileExists'];
177 if ( $this->fileExists ) {
178 $this->setProps( $cachedValues );
179 }
180 $this->dataLoaded = true;
181 }
182
183 if ( $this->dataLoaded ) {
184 wfIncrStats( 'image_cache_hit' );
185 } else {
186 wfIncrStats( 'image_cache_miss' );
187 }
188
189 wfProfileOut( __METHOD__ );
190 return $this->dataLoaded;
191 }
192
193 /**
194 * Save the file metadata to memcached
195 */
196 function saveToCache() {
197 global $wgMemc;
198
199 $this->load();
200 $key = $this->getCacheKey();
201
202 if ( !$key ) {
203 return;
204 }
205
206 $fields = $this->getCacheFields( '' );
207 $cache = array( 'version' => MW_FILE_VERSION );
208 $cache['fileExists'] = $this->fileExists;
209
210 if ( $this->fileExists ) {
211 foreach ( $fields as $field ) {
212 $cache[$field] = $this->$field;
213 }
214 }
215
216 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
217 }
218
219 /**
220 * Load metadata from the file itself
221 */
222 function loadFromFile() {
223 $this->setProps( self::getPropsFromPath( $this->getPath() ) );
224 }
225
226 function getCacheFields( $prefix = 'img_' ) {
227 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
228 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
229 static $results = array();
230
231 if ( $prefix == '' ) {
232 return $fields;
233 }
234
235 if ( !isset( $results[$prefix] ) ) {
236 $prefixedFields = array();
237 foreach ( $fields as $field ) {
238 $prefixedFields[] = $prefix . $field;
239 }
240 $results[$prefix] = $prefixedFields;
241 }
242
243 return $results[$prefix];
244 }
245
246 /**
247 * Load file metadata from the DB
248 */
249 function loadFromDB() {
250 # Polymorphic function name to distinguish foreign and local fetches
251 $fname = get_class( $this ) . '::' . __FUNCTION__;
252 wfProfileIn( $fname );
253
254 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
255 $this->dataLoaded = true;
256
257 $dbr = $this->repo->getMasterDB();
258
259 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
260 array( 'img_name' => $this->getName() ), $fname );
261
262 if ( $row ) {
263 $this->loadFromRow( $row );
264 } else {
265 $this->fileExists = false;
266 }
267
268 wfProfileOut( $fname );
269 }
270
271 /**
272 * Decode a row from the database (either object or array) to an array
273 * with timestamps and MIME types decoded, and the field prefix removed.
274 */
275 function decodeRow( $row, $prefix = 'img_' ) {
276 $array = (array)$row;
277 $prefixLength = strlen( $prefix );
278
279 // Sanity check prefix once
280 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
281 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
282 }
283
284 $decoded = array();
285
286 foreach ( $array as $name => $value ) {
287 $decoded[substr( $name, $prefixLength )] = $value;
288 }
289
290 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
291
292 if ( empty( $decoded['major_mime'] ) ) {
293 $decoded['mime'] = 'unknown/unknown';
294 } else {
295 if ( !$decoded['minor_mime'] ) {
296 $decoded['minor_mime'] = 'unknown';
297 }
298 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
299 }
300
301 # Trim zero padding from char/binary field
302 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
303
304 return $decoded;
305 }
306
307 /**
308 * Load file metadata from a DB result row
309 */
310 function loadFromRow( $row, $prefix = 'img_' ) {
311 $this->dataLoaded = true;
312 $array = $this->decodeRow( $row, $prefix );
313
314 foreach ( $array as $name => $value ) {
315 $this->$name = $value;
316 }
317
318 $this->fileExists = true;
319 $this->maybeUpgradeRow();
320 }
321
322 /**
323 * Load file metadata from cache or DB, unless already loaded
324 */
325 function load() {
326 if ( !$this->dataLoaded ) {
327 if ( !$this->loadFromCache() ) {
328 $this->loadFromDB();
329 $this->saveToCache();
330 }
331 $this->dataLoaded = true;
332 }
333 }
334
335 /**
336 * Upgrade a row if it needs it
337 */
338 function maybeUpgradeRow() {
339 if ( wfReadOnly() ) {
340 return;
341 }
342
343 if ( is_null( $this->media_type ) ||
344 $this->mime == 'image/svg'
345 ) {
346 $this->upgradeRow();
347 $this->upgraded = true;
348 } else {
349 $handler = $this->getHandler();
350 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata ) ) {
351 $this->upgradeRow();
352 $this->upgraded = true;
353 }
354 }
355 }
356
357 function getUpgraded() {
358 return $this->upgraded;
359 }
360
361 /**
362 * Fix assorted version-related problems with the image row by reloading it from the file
363 */
364 function upgradeRow() {
365 wfProfileIn( __METHOD__ );
366
367 $this->loadFromFile();
368
369 # Don't destroy file info of missing files
370 if ( !$this->fileExists ) {
371 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
372 wfProfileOut( __METHOD__ );
373 return;
374 }
375
376 $dbw = $this->repo->getMasterDB();
377 list( $major, $minor ) = self::splitMime( $this->mime );
378
379 if ( wfReadOnly() ) {
380 wfProfileOut( __METHOD__ );
381 return;
382 }
383 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
384
385 $dbw->update( 'image',
386 array(
387 'img_width' => $this->width,
388 'img_height' => $this->height,
389 'img_bits' => $this->bits,
390 'img_media_type' => $this->media_type,
391 'img_major_mime' => $major,
392 'img_minor_mime' => $minor,
393 'img_metadata' => $this->metadata,
394 'img_sha1' => $this->sha1,
395 ), array( 'img_name' => $this->getName() ),
396 __METHOD__
397 );
398
399 $this->saveToCache();
400 wfProfileOut( __METHOD__ );
401 }
402
403 /**
404 * Set properties in this object to be equal to those given in the
405 * associative array $info. Only cacheable fields can be set.
406 *
407 * If 'mime' is given, it will be split into major_mime/minor_mime.
408 * If major_mime/minor_mime are given, $this->mime will also be set.
409 */
410 function setProps( $info ) {
411 $this->dataLoaded = true;
412 $fields = $this->getCacheFields( '' );
413 $fields[] = 'fileExists';
414
415 foreach ( $fields as $field ) {
416 if ( isset( $info[$field] ) ) {
417 $this->$field = $info[$field];
418 }
419 }
420
421 // Fix up mime fields
422 if ( isset( $info['major_mime'] ) ) {
423 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
424 } elseif ( isset( $info['mime'] ) ) {
425 $this->mime = $info['mime'];
426 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
427 }
428 }
429
430 /** splitMime inherited */
431 /** getName inherited */
432 /** getTitle inherited */
433 /** getURL inherited */
434 /** getViewURL inherited */
435 /** getPath inherited */
436 /** isVisible inhereted */
437
438 function isMissing() {
439 if ( $this->missing === null ) {
440 list( $fileExists ) = $this->repo->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo::FILES_ONLY );
441 $this->missing = !$fileExists;
442 }
443 return $this->missing;
444 }
445
446 /**
447 * Return the width of the image
448 *
449 * Returns false on error
450 */
451 public function getWidth( $page = 1 ) {
452 $this->load();
453
454 if ( $this->isMultipage() ) {
455 $dim = $this->getHandler()->getPageDimensions( $this, $page );
456 if ( $dim ) {
457 return $dim['width'];
458 } else {
459 return false;
460 }
461 } else {
462 return $this->width;
463 }
464 }
465
466 /**
467 * Return the height of the image
468 *
469 * Returns false on error
470 */
471 public function getHeight( $page = 1 ) {
472 $this->load();
473
474 if ( $this->isMultipage() ) {
475 $dim = $this->getHandler()->getPageDimensions( $this, $page );
476 if ( $dim ) {
477 return $dim['height'];
478 } else {
479 return false;
480 }
481 } else {
482 return $this->height;
483 }
484 }
485
486 /**
487 * Returns ID or name of user who uploaded the file
488 *
489 * @param $type string 'text' or 'id'
490 */
491 function getUser( $type = 'text' ) {
492 $this->load();
493
494 if ( $type == 'text' ) {
495 return $this->user_text;
496 } elseif ( $type == 'id' ) {
497 return $this->user;
498 }
499 }
500
501 /**
502 * Get handler-specific metadata
503 */
504 function getMetadata() {
505 $this->load();
506 return $this->metadata;
507 }
508
509 function getBitDepth() {
510 $this->load();
511 return $this->bits;
512 }
513
514 /**
515 * Return the size of the image file, in bytes
516 */
517 public function getSize() {
518 $this->load();
519 return $this->size;
520 }
521
522 /**
523 * Returns the mime type of the file.
524 */
525 function getMimeType() {
526 $this->load();
527 return $this->mime;
528 }
529
530 /**
531 * Return the type of the media in the file.
532 * Use the value returned by this function with the MEDIATYPE_xxx constants.
533 */
534 function getMediaType() {
535 $this->load();
536 return $this->media_type;
537 }
538
539 /** canRender inherited */
540 /** mustRender inherited */
541 /** allowInlineDisplay inherited */
542 /** isSafeFile inherited */
543 /** isTrustedFile inherited */
544
545 /**
546 * Returns true if the file file exists on disk.
547 * @return boolean Whether file file exist on disk.
548 */
549 public function exists() {
550 $this->load();
551 return $this->fileExists;
552 }
553
554 /** getTransformScript inherited */
555 /** getUnscaledThumb inherited */
556 /** thumbName inherited */
557 /** createThumb inherited */
558 /** getThumbnail inherited */
559 /** transform inherited */
560
561 /**
562 * Fix thumbnail files from 1.4 or before, with extreme prejudice
563 */
564 function migrateThumbFile( $thumbName ) {
565 $thumbDir = $this->getThumbPath();
566 $thumbPath = "$thumbDir/$thumbName";
567
568 if ( is_dir( $thumbPath ) ) {
569 // Directory where file should be
570 // This happened occasionally due to broken migration code in 1.5
571 // Rename to broken-*
572 for ( $i = 0; $i < 100 ; $i++ ) {
573 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
574 if ( !file_exists( $broken ) ) {
575 rename( $thumbPath, $broken );
576 break;
577 }
578 }
579 // Doesn't exist anymore
580 clearstatcache();
581 }
582
583 if ( is_file( $thumbDir ) ) {
584 // File where directory should be
585 unlink( $thumbDir );
586 // Doesn't exist anymore
587 clearstatcache();
588 }
589 }
590
591 /** getHandler inherited */
592 /** iconThumb inherited */
593 /** getLastError inherited */
594
595 /**
596 * Get all thumbnail names previously generated for this file
597 */
598 function getThumbnails() {
599 $this->load();
600
601 $files = array();
602 $dir = $this->getThumbPath();
603
604 if ( is_dir( $dir ) ) {
605 $handle = opendir( $dir );
606
607 if ( $handle ) {
608 while ( false !== ( $file = readdir( $handle ) ) ) {
609 if ( $file { 0 } != '.' ) {
610 $files[] = $file;
611 }
612 }
613
614 closedir( $handle );
615 }
616 }
617
618 return $files;
619 }
620
621 /**
622 * Refresh metadata in memcached, but don't touch thumbnails or squid
623 */
624 function purgeMetadataCache() {
625 $this->loadFromDB();
626 $this->saveToCache();
627 $this->purgeHistory();
628 }
629
630 /**
631 * Purge the shared history (OldLocalFile) cache
632 */
633 function purgeHistory() {
634 global $wgMemc;
635
636 $hashedName = md5( $this->getName() );
637 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
638
639 if ( $oldKey ) {
640 $wgMemc->delete( $oldKey );
641 }
642 }
643
644 /**
645 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
646 */
647 function purgeCache() {
648 // Refresh metadata cache
649 $this->purgeMetadataCache();
650
651 // Delete thumbnails
652 $this->purgeThumbnails();
653
654 // Purge squid cache for this file
655 SquidUpdate::purge( array( $this->getURL() ) );
656 }
657
658 /**
659 * Delete cached transformed files
660 */
661 function purgeThumbnails() {
662 global $wgUseSquid, $wgExcludeFromThumbnailPurge;
663
664 // Delete thumbnails
665 $files = $this->getThumbnails();
666 $dir = $this->getThumbPath();
667 $urls = array();
668
669 foreach ( $files as $file ) {
670 // Only remove files not in the $wgExcludeFromThumbnailPurge configuration variable
671 $ext = pathinfo( "$dir/$file", PATHINFO_EXTENSION );
672 if ( in_array( $ext, $wgExcludeFromThumbnailPurge ) ) {
673 continue;
674 }
675
676 # Check that the base file name is part of the thumb name
677 # This is a basic sanity check to avoid erasing unrelated directories
678 if ( strpos( $file, $this->getName() ) !== false ) {
679 $url = $this->getThumbUrl( $file );
680 $urls[] = $url;
681 @unlink( "$dir/$file" );
682 }
683 }
684
685 // Purge the squid
686 if ( $wgUseSquid ) {
687 SquidUpdate::purge( $urls );
688 }
689 }
690
691 /** purgeDescription inherited */
692 /** purgeEverything inherited */
693
694 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
695 $dbr = $this->repo->getSlaveDB();
696 $tables = array( 'oldimage' );
697 $fields = OldLocalFile::selectFields();
698 $conds = $opts = $join_conds = array();
699 $eq = $inc ? '=' : '';
700 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
701
702 if ( $start ) {
703 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
704 }
705
706 if ( $end ) {
707 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
708 }
709
710 if ( $limit ) {
711 $opts['LIMIT'] = $limit;
712 }
713
714 // Search backwards for time > x queries
715 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
716 $opts['ORDER BY'] = "oi_timestamp $order";
717 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
718
719 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
720 &$conds, &$opts, &$join_conds ) );
721
722 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
723 $r = array();
724
725 foreach ( $res as $row ) {
726 if ( $this->repo->oldFileFromRowFactory ) {
727 $r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
728 } else {
729 $r[] = OldLocalFile::newFromRow( $row, $this->repo );
730 }
731 }
732
733 if ( $order == 'ASC' ) {
734 $r = array_reverse( $r ); // make sure it ends up descending
735 }
736
737 return $r;
738 }
739
740 /**
741 * Return the history of this file, line by line.
742 * starts with current version, then old versions.
743 * uses $this->historyLine to check which line to return:
744 * 0 return line for current version
745 * 1 query for old versions, return first one
746 * 2, ... return next old version from above query
747 */
748 public function nextHistoryLine() {
749 # Polymorphic function name to distinguish foreign and local fetches
750 $fname = get_class( $this ) . '::' . __FUNCTION__;
751
752 $dbr = $this->repo->getSlaveDB();
753
754 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
755 $this->historyRes = $dbr->select( 'image',
756 array(
757 '*',
758 "'' AS oi_archive_name",
759 '0 as oi_deleted',
760 'img_sha1'
761 ),
762 array( 'img_name' => $this->title->getDBkey() ),
763 $fname
764 );
765
766 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
767 $this->historyRes = null;
768 return false;
769 }
770 } elseif ( $this->historyLine == 1 ) {
771 $this->historyRes = $dbr->select( 'oldimage', '*',
772 array( 'oi_name' => $this->title->getDBkey() ),
773 $fname,
774 array( 'ORDER BY' => 'oi_timestamp DESC' )
775 );
776 }
777 $this->historyLine ++;
778
779 return $dbr->fetchObject( $this->historyRes );
780 }
781
782 /**
783 * Reset the history pointer to the first element of the history
784 */
785 public function resetHistory() {
786 $this->historyLine = 0;
787
788 if ( !is_null( $this->historyRes ) ) {
789 $this->historyRes = null;
790 }
791 }
792
793 /** getFullPath inherited */
794 /** getHashPath inherited */
795 /** getRel inherited */
796 /** getUrlRel inherited */
797 /** getArchiveRel inherited */
798 /** getThumbRel inherited */
799 /** getArchivePath inherited */
800 /** getThumbPath inherited */
801 /** getArchiveUrl inherited */
802 /** getThumbUrl inherited */
803 /** getArchiveVirtualUrl inherited */
804 /** getThumbVirtualUrl inherited */
805 /** isHashed inherited */
806
807 /**
808 * Upload a file and record it in the DB
809 * @param $srcPath String: source path or virtual URL
810 * @param $comment String: upload description
811 * @param $pageText String: text to use for the new description page,
812 * if a new description page is created
813 * @param $flags Integer: flags for publish()
814 * @param $props Array: File properties, if known. This can be used to reduce the
815 * upload time when uploading virtual URLs for which the file info
816 * is already known
817 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
818 * @param $user Mixed: User object or null to use $wgUser
819 *
820 * @return FileRepoStatus object. On success, the value member contains the
821 * archive name, or an empty string if it was a new file.
822 */
823 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
824 $this->lock();
825 $status = $this->publish( $srcPath, $flags );
826
827 if ( $status->ok ) {
828 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
829 $status->fatal( 'filenotfound', $srcPath );
830 }
831 }
832
833 $this->unlock();
834
835 return $status;
836 }
837
838 /**
839 * Record a file upload in the upload log and the image table
840 * @deprecated use upload()
841 */
842 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
843 $watch = false, $timestamp = false )
844 {
845 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
846
847 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
848 return false;
849 }
850
851 if ( $watch ) {
852 global $wgUser;
853 $wgUser->addWatch( $this->getTitle() );
854 }
855 return true;
856
857 }
858
859 /**
860 * Record a file upload in the upload log and the image table
861 */
862 function recordUpload2(
863 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
864 ) {
865 if ( is_null( $user ) ) {
866 global $wgUser;
867 $user = $wgUser;
868 }
869
870 $dbw = $this->repo->getMasterDB();
871 $dbw->begin();
872
873 if ( !$props ) {
874 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
875 }
876
877 if ( $timestamp === false ) {
878 $timestamp = $dbw->timestamp();
879 }
880
881 $props['description'] = $comment;
882 $props['user'] = $user->getId();
883 $props['user_text'] = $user->getName();
884 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
885 $this->setProps( $props );
886
887 # Delete thumbnails
888 $this->purgeThumbnails();
889
890 # The file is already on its final location, remove it from the squid cache
891 SquidUpdate::purge( array( $this->getURL() ) );
892
893 # Fail now if the file isn't there
894 if ( !$this->fileExists ) {
895 wfDebug( __METHOD__ . ": File " . $this->getPath() . " went missing!\n" );
896 return false;
897 }
898
899 $reupload = false;
900
901 # Test to see if the row exists using INSERT IGNORE
902 # This avoids race conditions by locking the row until the commit, and also
903 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
904 $dbw->insert( 'image',
905 array(
906 'img_name' => $this->getName(),
907 'img_size' => $this->size,
908 'img_width' => intval( $this->width ),
909 'img_height' => intval( $this->height ),
910 'img_bits' => $this->bits,
911 'img_media_type' => $this->media_type,
912 'img_major_mime' => $this->major_mime,
913 'img_minor_mime' => $this->minor_mime,
914 'img_timestamp' => $timestamp,
915 'img_description' => $comment,
916 'img_user' => $user->getId(),
917 'img_user_text' => $user->getName(),
918 'img_metadata' => $this->metadata,
919 'img_sha1' => $this->sha1
920 ),
921 __METHOD__,
922 'IGNORE'
923 );
924
925 if ( $dbw->affectedRows() == 0 ) {
926 $reupload = true;
927
928 # Collision, this is an update of a file
929 # Insert previous contents into oldimage
930 $dbw->insertSelect( 'oldimage', 'image',
931 array(
932 'oi_name' => 'img_name',
933 'oi_archive_name' => $dbw->addQuotes( $oldver ),
934 'oi_size' => 'img_size',
935 'oi_width' => 'img_width',
936 'oi_height' => 'img_height',
937 'oi_bits' => 'img_bits',
938 'oi_timestamp' => 'img_timestamp',
939 'oi_description' => 'img_description',
940 'oi_user' => 'img_user',
941 'oi_user_text' => 'img_user_text',
942 'oi_metadata' => 'img_metadata',
943 'oi_media_type' => 'img_media_type',
944 'oi_major_mime' => 'img_major_mime',
945 'oi_minor_mime' => 'img_minor_mime',
946 'oi_sha1' => 'img_sha1'
947 ), array( 'img_name' => $this->getName() ), __METHOD__
948 );
949
950 # Update the current image row
951 $dbw->update( 'image',
952 array( /* SET */
953 'img_size' => $this->size,
954 'img_width' => intval( $this->width ),
955 'img_height' => intval( $this->height ),
956 'img_bits' => $this->bits,
957 'img_media_type' => $this->media_type,
958 'img_major_mime' => $this->major_mime,
959 'img_minor_mime' => $this->minor_mime,
960 'img_timestamp' => $timestamp,
961 'img_description' => $comment,
962 'img_user' => $user->getId(),
963 'img_user_text' => $user->getName(),
964 'img_metadata' => $this->metadata,
965 'img_sha1' => $this->sha1
966 ), array( /* WHERE */
967 'img_name' => $this->getName()
968 ), __METHOD__
969 );
970 } else {
971 # This is a new file
972 # Update the image count
973 $site_stats = $dbw->tableName( 'site_stats' );
974 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
975 }
976
977 $descTitle = $this->getTitle();
978 $article = new ImagePage( $descTitle );
979 $article->setFile( $this );
980
981 # Add the log entry
982 $log = new LogPage( 'upload' );
983 $action = $reupload ? 'overwrite' : 'upload';
984 $log->addEntry( $action, $descTitle, $comment, array(), $user );
985
986 if ( $descTitle->exists() ) {
987 # Create a null revision
988 $latest = $descTitle->getLatestRevID();
989 $nullRevision = Revision::newNullRevision(
990 $dbw,
991 $descTitle->getArticleId(),
992 $log->getRcComment(),
993 false
994 );
995 $nullRevision->insertOn( $dbw );
996
997 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
998 $article->updateRevisionOn( $dbw, $nullRevision );
999
1000 # Invalidate the cache for the description page
1001 $descTitle->invalidateCache();
1002 $descTitle->purgeSquid();
1003 } else {
1004 # New file; create the description page.
1005 # There's already a log entry, so don't make a second RC entry
1006 # Squid and file cache for the description page are purged by doEdit.
1007 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
1008 }
1009
1010 # Commit the transaction now, in case something goes wrong later
1011 # The most important thing is that files don't get lost, especially archives
1012 $dbw->commit();
1013
1014 # Save to cache and purge the squid
1015 # We shall not saveToCache before the commit since otherwise
1016 # in case of a rollback there is an usable file from memcached
1017 # which in fact doesn't really exist (bug 24978)
1018 $this->saveToCache();
1019
1020 # Hooks, hooks, the magic of hooks...
1021 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1022
1023 # Invalidate cache for all pages using this file
1024 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1025 $update->doUpdate();
1026
1027 # Invalidate cache for all pages that redirects on this page
1028 $redirs = $this->getTitle()->getRedirectsHere();
1029
1030 foreach ( $redirs as $redir ) {
1031 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1032 $update->doUpdate();
1033 }
1034
1035 return true;
1036 }
1037
1038 /**
1039 * Move or copy a file to its public location. If a file exists at the
1040 * destination, move it to an archive. Returns a FileRepoStatus object with
1041 * the archive name in the "value" member on success.
1042 *
1043 * The archive name should be passed through to recordUpload for database
1044 * registration.
1045 *
1046 * @param $srcPath String: local filesystem path to the source image
1047 * @param $flags Integer: a bitwise combination of:
1048 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1049 * @param $dstArchiveName string File name if the file is to be published
1050 * into the archive
1051 * @return FileRepoStatus object. On success, the value member contains the
1052 * archive name, or an empty string if it was a new file.
1053 */
1054 function publish( $srcPath, $flags = 0, $dstArchiveName = null ) {
1055 $this->lock();
1056
1057 if ( $dstArchiveName ) {
1058 $dstRel = 'archive/' . $this->getHashPath() . $dstArchiveName;
1059 } else {
1060 $dstRel = $this->getRel();
1061 }
1062
1063 $archiveName = wfTimestamp( TS_MW ) . '!'. $this->getName();
1064 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1065 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1066 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
1067
1068 if ( $status->value == 'new' ) {
1069 $status->value = '';
1070 } else {
1071 $status->value = $archiveName;
1072 }
1073
1074 $this->unlock();
1075
1076 return $status;
1077 }
1078
1079 /** getLinksTo inherited */
1080 /** getExifData inherited */
1081 /** isLocal inherited */
1082 /** wasDeleted inherited */
1083
1084 /**
1085 * Move file to the new title
1086 *
1087 * Move current, old version and all thumbnails
1088 * to the new filename. Old file is deleted.
1089 *
1090 * Cache purging is done; checks for validity
1091 * and logging are caller's responsibility
1092 *
1093 * @param $target Title New file name
1094 * @return FileRepoStatus object.
1095 */
1096 function move( $target ) {
1097 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1098 $this->lock();
1099
1100 $batch = new LocalFileMoveBatch( $this, $target );
1101 $batch->addCurrent();
1102 $batch->addOlds();
1103
1104 $status = $batch->execute();
1105 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1106
1107 $this->purgeEverything();
1108 $this->unlock();
1109
1110 if ( $status->isOk() ) {
1111 // Now switch the object
1112 $this->title = $target;
1113 // Force regeneration of the name and hashpath
1114 unset( $this->name );
1115 unset( $this->hashPath );
1116 // Purge the new image
1117 $this->purgeEverything();
1118 }
1119
1120 return $status;
1121 }
1122
1123 /**
1124 * Delete all versions of the file.
1125 *
1126 * Moves the files into an archive directory (or deletes them)
1127 * and removes the database rows.
1128 *
1129 * Cache purging is done; logging is caller's responsibility.
1130 *
1131 * @param $reason
1132 * @param $suppress
1133 * @return FileRepoStatus object.
1134 */
1135 function delete( $reason, $suppress = false ) {
1136 $this->lock();
1137
1138 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1139 $batch->addCurrent();
1140
1141 # Get old version relative paths
1142 $dbw = $this->repo->getMasterDB();
1143 $result = $dbw->select( 'oldimage',
1144 array( 'oi_archive_name' ),
1145 array( 'oi_name' => $this->getName() ) );
1146 foreach ( $result as $row ) {
1147 $batch->addOld( $row->oi_archive_name );
1148 }
1149 $status = $batch->execute();
1150
1151 if ( $status->ok ) {
1152 // Update site_stats
1153 $site_stats = $dbw->tableName( 'site_stats' );
1154 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1155 $this->purgeEverything();
1156 }
1157
1158 $this->unlock();
1159
1160 return $status;
1161 }
1162
1163 /**
1164 * Delete an old version of the file.
1165 *
1166 * Moves the file into an archive directory (or deletes it)
1167 * and removes the database row.
1168 *
1169 * Cache purging is done; logging is caller's responsibility.
1170 *
1171 * @param $archiveName String
1172 * @param $reason String
1173 * @param $suppress Boolean
1174 * @throws MWException or FSException on database or file store failure
1175 * @return FileRepoStatus object.
1176 */
1177 function deleteOld( $archiveName, $reason, $suppress = false ) {
1178 $this->lock();
1179
1180 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1181 $batch->addOld( $archiveName );
1182 $status = $batch->execute();
1183
1184 $this->unlock();
1185
1186 if ( $status->ok ) {
1187 $this->purgeDescription();
1188 $this->purgeHistory();
1189 }
1190
1191 return $status;
1192 }
1193
1194 /**
1195 * Restore all or specified deleted revisions to the given file.
1196 * Permissions and logging are left to the caller.
1197 *
1198 * May throw database exceptions on error.
1199 *
1200 * @param $versions set of record ids of deleted items to restore,
1201 * or empty to restore all revisions.
1202 * @param $unsuppress Boolean
1203 * @return FileRepoStatus
1204 */
1205 function restore( $versions = array(), $unsuppress = false ) {
1206 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1207
1208 if ( !$versions ) {
1209 $batch->addAll();
1210 } else {
1211 $batch->addIds( $versions );
1212 }
1213
1214 $status = $batch->execute();
1215
1216 if ( !$status->isGood() ) {
1217 return $status;
1218 }
1219
1220 $cleanupStatus = $batch->cleanup();
1221 $cleanupStatus->successCount = 0;
1222 $cleanupStatus->failCount = 0;
1223 $status->merge( $cleanupStatus );
1224
1225 return $status;
1226 }
1227
1228 /** isMultipage inherited */
1229 /** pageCount inherited */
1230 /** scaleHeight inherited */
1231 /** getImageSize inherited */
1232
1233 /**
1234 * Get the URL of the file description page.
1235 */
1236 function getDescriptionUrl() {
1237 return $this->title->getLocalUrl();
1238 }
1239
1240 /**
1241 * Get the HTML text of the description page
1242 * This is not used by ImagePage for local files, since (among other things)
1243 * it skips the parser cache.
1244 */
1245 function getDescriptionText() {
1246 global $wgParser;
1247 $revision = Revision::newFromTitle( $this->title );
1248 if ( !$revision ) return false;
1249 $text = $revision->getText();
1250 if ( !$text ) return false;
1251 $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
1252 return $pout->getText();
1253 }
1254
1255 function getDescription() {
1256 $this->load();
1257 return $this->description;
1258 }
1259
1260 function getTimestamp() {
1261 $this->load();
1262 return $this->timestamp;
1263 }
1264
1265 function getSha1() {
1266 $this->load();
1267 // Initialise now if necessary
1268 if ( $this->sha1 == '' && $this->fileExists ) {
1269 $this->sha1 = File::sha1Base36( $this->getPath() );
1270 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1271 $dbw = $this->repo->getMasterDB();
1272 $dbw->update( 'image',
1273 array( 'img_sha1' => $this->sha1 ),
1274 array( 'img_name' => $this->getName() ),
1275 __METHOD__ );
1276 $this->saveToCache();
1277 }
1278 }
1279
1280 return $this->sha1;
1281 }
1282
1283 /**
1284 * Start a transaction and lock the image for update
1285 * Increments a reference counter if the lock is already held
1286 * @return boolean True if the image exists, false otherwise
1287 */
1288 function lock() {
1289 $dbw = $this->repo->getMasterDB();
1290
1291 if ( !$this->locked ) {
1292 $dbw->begin();
1293 $this->locked++;
1294 }
1295
1296 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1297 }
1298
1299 /**
1300 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1301 * the transaction and thereby releases the image lock.
1302 */
1303 function unlock() {
1304 if ( $this->locked ) {
1305 --$this->locked;
1306 if ( !$this->locked ) {
1307 $dbw = $this->repo->getMasterDB();
1308 $dbw->commit();
1309 }
1310 }
1311 }
1312
1313 /**
1314 * Roll back the DB transaction and mark the image unlocked
1315 */
1316 function unlockAndRollback() {
1317 $this->locked = false;
1318 $dbw = $this->repo->getMasterDB();
1319 $dbw->rollback();
1320 }
1321 } // LocalFile class
1322
1323 # ------------------------------------------------------------------------------
1324
1325 /**
1326 * Helper class for file deletion
1327 * @ingroup FileRepo
1328 */
1329 class LocalFileDeleteBatch {
1330
1331 /**
1332 * @var LocalFile
1333 */
1334 var $file;
1335
1336 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1337 var $status;
1338
1339 function __construct( File $file, $reason = '', $suppress = false ) {
1340 $this->file = $file;
1341 $this->reason = $reason;
1342 $this->suppress = $suppress;
1343 $this->status = $file->repo->newGood();
1344 }
1345
1346 function addCurrent() {
1347 $this->srcRels['.'] = $this->file->getRel();
1348 }
1349
1350 function addOld( $oldName ) {
1351 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1352 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1353 }
1354
1355 function getOldRels() {
1356 if ( !isset( $this->srcRels['.'] ) ) {
1357 $oldRels =& $this->srcRels;
1358 $deleteCurrent = false;
1359 } else {
1360 $oldRels = $this->srcRels;
1361 unset( $oldRels['.'] );
1362 $deleteCurrent = true;
1363 }
1364
1365 return array( $oldRels, $deleteCurrent );
1366 }
1367
1368 /*protected*/ function getHashes() {
1369 $hashes = array();
1370 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1371
1372 if ( $deleteCurrent ) {
1373 $hashes['.'] = $this->file->getSha1();
1374 }
1375
1376 if ( count( $oldRels ) ) {
1377 $dbw = $this->file->repo->getMasterDB();
1378 $res = $dbw->select(
1379 'oldimage',
1380 array( 'oi_archive_name', 'oi_sha1' ),
1381 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1382 __METHOD__
1383 );
1384
1385 foreach ( $res as $row ) {
1386 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1387 // Get the hash from the file
1388 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1389 $props = $this->file->repo->getFileProps( $oldUrl );
1390
1391 if ( $props['fileExists'] ) {
1392 // Upgrade the oldimage row
1393 $dbw->update( 'oldimage',
1394 array( 'oi_sha1' => $props['sha1'] ),
1395 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1396 __METHOD__ );
1397 $hashes[$row->oi_archive_name] = $props['sha1'];
1398 } else {
1399 $hashes[$row->oi_archive_name] = false;
1400 }
1401 } else {
1402 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1403 }
1404 }
1405 }
1406
1407 $missing = array_diff_key( $this->srcRels, $hashes );
1408
1409 foreach ( $missing as $name => $rel ) {
1410 $this->status->error( 'filedelete-old-unregistered', $name );
1411 }
1412
1413 foreach ( $hashes as $name => $hash ) {
1414 if ( !$hash ) {
1415 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1416 unset( $hashes[$name] );
1417 }
1418 }
1419
1420 return $hashes;
1421 }
1422
1423 function doDBInserts() {
1424 global $wgUser;
1425
1426 $dbw = $this->file->repo->getMasterDB();
1427 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1428 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1429 $encReason = $dbw->addQuotes( $this->reason );
1430 $encGroup = $dbw->addQuotes( 'deleted' );
1431 $ext = $this->file->getExtension();
1432 $dotExt = $ext === '' ? '' : ".$ext";
1433 $encExt = $dbw->addQuotes( $dotExt );
1434 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1435
1436 // Bitfields to further suppress the content
1437 if ( $this->suppress ) {
1438 $bitfield = 0;
1439 // This should be 15...
1440 $bitfield |= Revision::DELETED_TEXT;
1441 $bitfield |= Revision::DELETED_COMMENT;
1442 $bitfield |= Revision::DELETED_USER;
1443 $bitfield |= Revision::DELETED_RESTRICTED;
1444 } else {
1445 $bitfield = 'oi_deleted';
1446 }
1447
1448 if ( $deleteCurrent ) {
1449 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1450 $where = array( 'img_name' => $this->file->getName() );
1451 $dbw->insertSelect( 'filearchive', 'image',
1452 array(
1453 'fa_storage_group' => $encGroup,
1454 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1455 'fa_deleted_user' => $encUserId,
1456 'fa_deleted_timestamp' => $encTimestamp,
1457 'fa_deleted_reason' => $encReason,
1458 'fa_deleted' => $this->suppress ? $bitfield : 0,
1459
1460 'fa_name' => 'img_name',
1461 'fa_archive_name' => 'NULL',
1462 'fa_size' => 'img_size',
1463 'fa_width' => 'img_width',
1464 'fa_height' => 'img_height',
1465 'fa_metadata' => 'img_metadata',
1466 'fa_bits' => 'img_bits',
1467 'fa_media_type' => 'img_media_type',
1468 'fa_major_mime' => 'img_major_mime',
1469 'fa_minor_mime' => 'img_minor_mime',
1470 'fa_description' => 'img_description',
1471 'fa_user' => 'img_user',
1472 'fa_user_text' => 'img_user_text',
1473 'fa_timestamp' => 'img_timestamp'
1474 ), $where, __METHOD__ );
1475 }
1476
1477 if ( count( $oldRels ) ) {
1478 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1479 $where = array(
1480 'oi_name' => $this->file->getName(),
1481 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1482 $dbw->insertSelect( 'filearchive', 'oldimage',
1483 array(
1484 'fa_storage_group' => $encGroup,
1485 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1486 'fa_deleted_user' => $encUserId,
1487 'fa_deleted_timestamp' => $encTimestamp,
1488 'fa_deleted_reason' => $encReason,
1489 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1490
1491 'fa_name' => 'oi_name',
1492 'fa_archive_name' => 'oi_archive_name',
1493 'fa_size' => 'oi_size',
1494 'fa_width' => 'oi_width',
1495 'fa_height' => 'oi_height',
1496 'fa_metadata' => 'oi_metadata',
1497 'fa_bits' => 'oi_bits',
1498 'fa_media_type' => 'oi_media_type',
1499 'fa_major_mime' => 'oi_major_mime',
1500 'fa_minor_mime' => 'oi_minor_mime',
1501 'fa_description' => 'oi_description',
1502 'fa_user' => 'oi_user',
1503 'fa_user_text' => 'oi_user_text',
1504 'fa_timestamp' => 'oi_timestamp',
1505 'fa_deleted' => $bitfield
1506 ), $where, __METHOD__ );
1507 }
1508 }
1509
1510 function doDBDeletes() {
1511 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1512
1513 // https://bugzilla.wikimedia.org/show_bug.cgi?id=13921
1514 // Create and use a new loadBalancer object, to prevent "1205: Lock wait timeout exceeded;"
1515 $lb = wfGetLBFactory()->newMainLB();
1516 $dbw = $lb->getConnection( DB_MASTER );
1517
1518 if ( count( $oldRels ) ) {
1519 $dbw->delete( 'oldimage',
1520 array(
1521 'oi_name' => $this->file->getName(),
1522 'oi_archive_name' => array_keys( $oldRels )
1523 ), __METHOD__ );
1524 }
1525
1526 if ( $deleteCurrent ) {
1527 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1528 }
1529
1530 $lb->commitMasterChanges();
1531 $lb->closeAll();
1532 }
1533
1534 /**
1535 * Run the transaction
1536 */
1537 function execute() {
1538 global $wgUseSquid;
1539 wfProfileIn( __METHOD__ );
1540
1541 $this->file->lock();
1542 // Leave private files alone
1543 $privateFiles = array();
1544 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1545 $dbw = $this->file->repo->getMasterDB();
1546
1547 if ( !empty( $oldRels ) ) {
1548 $res = $dbw->select( 'oldimage',
1549 array( 'oi_archive_name' ),
1550 array( 'oi_name' => $this->file->getName(),
1551 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1552 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
1553 __METHOD__ );
1554
1555 foreach ( $res as $row ) {
1556 $privateFiles[$row->oi_archive_name] = 1;
1557 }
1558 }
1559 // Prepare deletion batch
1560 $hashes = $this->getHashes();
1561 $this->deletionBatch = array();
1562 $ext = $this->file->getExtension();
1563 $dotExt = $ext === '' ? '' : ".$ext";
1564
1565 foreach ( $this->srcRels as $name => $srcRel ) {
1566 // Skip files that have no hash (missing source).
1567 // Keep private files where they are.
1568 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1569 $hash = $hashes[$name];
1570 $key = $hash . $dotExt;
1571 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1572 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1573 }
1574 }
1575
1576 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1577 // We acquire this lock by running the inserts now, before the file operations.
1578 //
1579 // This potentially has poor lock contention characteristics -- an alternative
1580 // scheme would be to insert stub filearchive entries with no fa_name and commit
1581 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1582 $this->doDBInserts();
1583
1584 // Removes non-existent file from the batch, so we don't get errors.
1585 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
1586
1587 // Execute the file deletion batch
1588 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1589
1590 if ( !$status->isGood() ) {
1591 $this->status->merge( $status );
1592 }
1593
1594 if ( !$this->status->ok ) {
1595 // Critical file deletion error
1596 // Roll back inserts, release lock and abort
1597 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1598 $this->file->unlockAndRollback();
1599 wfProfileOut( __METHOD__ );
1600 return $this->status;
1601 }
1602
1603 // Purge squid
1604 if ( $wgUseSquid ) {
1605 $urls = array();
1606
1607 foreach ( $this->srcRels as $srcRel ) {
1608 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1609 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1610 }
1611 SquidUpdate::purge( $urls );
1612 }
1613
1614 // Delete image/oldimage rows
1615 $this->doDBDeletes();
1616
1617 // Commit and return
1618 $this->file->unlock();
1619 wfProfileOut( __METHOD__ );
1620
1621 return $this->status;
1622 }
1623
1624 /**
1625 * Removes non-existent files from a deletion batch.
1626 */
1627 function removeNonexistentFiles( $batch ) {
1628 $files = $newBatch = array();
1629
1630 foreach ( $batch as $batchItem ) {
1631 list( $src, $dest ) = $batchItem;
1632 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1633 }
1634
1635 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1636
1637 foreach ( $batch as $batchItem ) {
1638 if ( $result[$batchItem[0]] ) {
1639 $newBatch[] = $batchItem;
1640 }
1641 }
1642
1643 return $newBatch;
1644 }
1645 }
1646
1647 # ------------------------------------------------------------------------------
1648
1649 /**
1650 * Helper class for file undeletion
1651 * @ingroup FileRepo
1652 */
1653 class LocalFileRestoreBatch {
1654 /**
1655 * @var LocalFile
1656 */
1657 var $file;
1658
1659 var $cleanupBatch, $ids, $all, $unsuppress = false;
1660
1661 function __construct( File $file, $unsuppress = false ) {
1662 $this->file = $file;
1663 $this->cleanupBatch = $this->ids = array();
1664 $this->ids = array();
1665 $this->unsuppress = $unsuppress;
1666 }
1667
1668 /**
1669 * Add a file by ID
1670 */
1671 function addId( $fa_id ) {
1672 $this->ids[] = $fa_id;
1673 }
1674
1675 /**
1676 * Add a whole lot of files by ID
1677 */
1678 function addIds( $ids ) {
1679 $this->ids = array_merge( $this->ids, $ids );
1680 }
1681
1682 /**
1683 * Add all revisions of the file
1684 */
1685 function addAll() {
1686 $this->all = true;
1687 }
1688
1689 /**
1690 * Run the transaction, except the cleanup batch.
1691 * The cleanup batch should be run in a separate transaction, because it locks different
1692 * rows and there's no need to keep the image row locked while it's acquiring those locks
1693 * The caller may have its own transaction open.
1694 * So we save the batch and let the caller call cleanup()
1695 */
1696 function execute() {
1697 global $wgLang;
1698
1699 if ( !$this->all && !$this->ids ) {
1700 // Do nothing
1701 return $this->file->repo->newGood();
1702 }
1703
1704 $exists = $this->file->lock();
1705 $dbw = $this->file->repo->getMasterDB();
1706 $status = $this->file->repo->newGood();
1707
1708 // Fetch all or selected archived revisions for the file,
1709 // sorted from the most recent to the oldest.
1710 $conditions = array( 'fa_name' => $this->file->getName() );
1711
1712 if ( !$this->all ) {
1713 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1714 }
1715
1716 $result = $dbw->select( 'filearchive', '*',
1717 $conditions,
1718 __METHOD__,
1719 array( 'ORDER BY' => 'fa_timestamp DESC' )
1720 );
1721
1722 $idsPresent = array();
1723 $storeBatch = array();
1724 $insertBatch = array();
1725 $insertCurrent = false;
1726 $deleteIds = array();
1727 $first = true;
1728 $archiveNames = array();
1729
1730 foreach ( $result as $row ) {
1731 $idsPresent[] = $row->fa_id;
1732
1733 if ( $row->fa_name != $this->file->getName() ) {
1734 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1735 $status->failCount++;
1736 continue;
1737 }
1738
1739 if ( $row->fa_storage_key == '' ) {
1740 // Revision was missing pre-deletion
1741 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1742 $status->failCount++;
1743 continue;
1744 }
1745
1746 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1747 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1748
1749 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1750
1751 # Fix leading zero
1752 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1753 $sha1 = substr( $sha1, 1 );
1754 }
1755
1756 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1757 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1758 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1759 || is_null( $row->fa_metadata ) ) {
1760 // Refresh our metadata
1761 // Required for a new current revision; nice for older ones too. :)
1762 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1763 } else {
1764 $props = array(
1765 'minor_mime' => $row->fa_minor_mime,
1766 'major_mime' => $row->fa_major_mime,
1767 'media_type' => $row->fa_media_type,
1768 'metadata' => $row->fa_metadata
1769 );
1770 }
1771
1772 if ( $first && !$exists ) {
1773 // This revision will be published as the new current version
1774 $destRel = $this->file->getRel();
1775 $insertCurrent = array(
1776 'img_name' => $row->fa_name,
1777 'img_size' => $row->fa_size,
1778 'img_width' => $row->fa_width,
1779 'img_height' => $row->fa_height,
1780 'img_metadata' => $props['metadata'],
1781 'img_bits' => $row->fa_bits,
1782 'img_media_type' => $props['media_type'],
1783 'img_major_mime' => $props['major_mime'],
1784 'img_minor_mime' => $props['minor_mime'],
1785 'img_description' => $row->fa_description,
1786 'img_user' => $row->fa_user,
1787 'img_user_text' => $row->fa_user_text,
1788 'img_timestamp' => $row->fa_timestamp,
1789 'img_sha1' => $sha1
1790 );
1791
1792 // The live (current) version cannot be hidden!
1793 if ( !$this->unsuppress && $row->fa_deleted ) {
1794 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1795 $this->cleanupBatch[] = $row->fa_storage_key;
1796 }
1797 } else {
1798 $archiveName = $row->fa_archive_name;
1799
1800 if ( $archiveName == '' ) {
1801 // This was originally a current version; we
1802 // have to devise a new archive name for it.
1803 // Format is <timestamp of archiving>!<name>
1804 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1805
1806 do {
1807 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1808 $timestamp++;
1809 } while ( isset( $archiveNames[$archiveName] ) );
1810 }
1811
1812 $archiveNames[$archiveName] = true;
1813 $destRel = $this->file->getArchiveRel( $archiveName );
1814 $insertBatch[] = array(
1815 'oi_name' => $row->fa_name,
1816 'oi_archive_name' => $archiveName,
1817 'oi_size' => $row->fa_size,
1818 'oi_width' => $row->fa_width,
1819 'oi_height' => $row->fa_height,
1820 'oi_bits' => $row->fa_bits,
1821 'oi_description' => $row->fa_description,
1822 'oi_user' => $row->fa_user,
1823 'oi_user_text' => $row->fa_user_text,
1824 'oi_timestamp' => $row->fa_timestamp,
1825 'oi_metadata' => $props['metadata'],
1826 'oi_media_type' => $props['media_type'],
1827 'oi_major_mime' => $props['major_mime'],
1828 'oi_minor_mime' => $props['minor_mime'],
1829 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
1830 'oi_sha1' => $sha1 );
1831 }
1832
1833 $deleteIds[] = $row->fa_id;
1834
1835 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
1836 // private files can stay where they are
1837 $status->successCount++;
1838 } else {
1839 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1840 $this->cleanupBatch[] = $row->fa_storage_key;
1841 }
1842
1843 $first = false;
1844 }
1845
1846 unset( $result );
1847
1848 // Add a warning to the status object for missing IDs
1849 $missingIds = array_diff( $this->ids, $idsPresent );
1850
1851 foreach ( $missingIds as $id ) {
1852 $status->error( 'undelete-missing-filearchive', $id );
1853 }
1854
1855 // Remove missing files from batch, so we don't get errors when undeleting them
1856 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1857
1858 // Run the store batch
1859 // Use the OVERWRITE_SAME flag to smooth over a common error
1860 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1861 $status->merge( $storeStatus );
1862
1863 if ( !$status->isGood() ) {
1864 // Even if some files could be copied, fail entirely as that is the
1865 // easiest thing to do without data loss
1866 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1867 $status->ok = false;
1868 $this->file->unlock();
1869
1870 return $status;
1871 }
1872
1873 // Run the DB updates
1874 // Because we have locked the image row, key conflicts should be rare.
1875 // If they do occur, we can roll back the transaction at this time with
1876 // no data loss, but leaving unregistered files scattered throughout the
1877 // public zone.
1878 // This is not ideal, which is why it's important to lock the image row.
1879 if ( $insertCurrent ) {
1880 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1881 }
1882
1883 if ( $insertBatch ) {
1884 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1885 }
1886
1887 if ( $deleteIds ) {
1888 $dbw->delete( 'filearchive',
1889 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1890 __METHOD__ );
1891 }
1892
1893 // If store batch is empty (all files are missing), deletion is to be considered successful
1894 if ( $status->successCount > 0 || !$storeBatch ) {
1895 if ( !$exists ) {
1896 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
1897
1898 // Update site_stats
1899 $site_stats = $dbw->tableName( 'site_stats' );
1900 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1901
1902 $this->file->purgeEverything();
1903 } else {
1904 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
1905 $this->file->purgeDescription();
1906 $this->file->purgeHistory();
1907 }
1908 }
1909
1910 $this->file->unlock();
1911
1912 return $status;
1913 }
1914
1915 /**
1916 * Removes non-existent files from a store batch.
1917 */
1918 function removeNonexistentFiles( $triplets ) {
1919 $files = $filteredTriplets = array();
1920 foreach ( $triplets as $file )
1921 $files[$file[0]] = $file[0];
1922
1923 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1924
1925 foreach ( $triplets as $file ) {
1926 if ( $result[$file[0]] ) {
1927 $filteredTriplets[] = $file;
1928 }
1929 }
1930
1931 return $filteredTriplets;
1932 }
1933
1934 /**
1935 * Removes non-existent files from a cleanup batch.
1936 */
1937 function removeNonexistentFromCleanup( $batch ) {
1938 $files = $newBatch = array();
1939 $repo = $this->file->repo;
1940
1941 foreach ( $batch as $file ) {
1942 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1943 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1944 }
1945
1946 $result = $repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1947
1948 foreach ( $batch as $file ) {
1949 if ( $result[$file] ) {
1950 $newBatch[] = $file;
1951 }
1952 }
1953
1954 return $newBatch;
1955 }
1956
1957 /**
1958 * Delete unused files in the deleted zone.
1959 * This should be called from outside the transaction in which execute() was called.
1960 */
1961 function cleanup() {
1962 if ( !$this->cleanupBatch ) {
1963 return $this->file->repo->newGood();
1964 }
1965
1966 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
1967
1968 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
1969
1970 return $status;
1971 }
1972
1973 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
1974 $cleanupBatch = array();
1975
1976 foreach ( $storeStatus->success as $i => $success ) {
1977 if ( $success ) {
1978 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][1] );
1979 }
1980 }
1981 $this->file->repo->cleanupBatch( $cleanupBatch );
1982 }
1983 }
1984
1985 # ------------------------------------------------------------------------------
1986
1987 /**
1988 * Helper class for file movement
1989 * @ingroup FileRepo
1990 */
1991 class LocalFileMoveBatch {
1992 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1993
1994 function __construct( File $file, Title $target ) {
1995 $this->file = $file;
1996 $this->target = $target;
1997 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
1998 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
1999 $this->oldName = $this->file->getName();
2000 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2001 $this->oldRel = $this->oldHash . $this->oldName;
2002 $this->newRel = $this->newHash . $this->newName;
2003 $this->db = $file->repo->getMasterDb();
2004 }
2005
2006 /**
2007 * Add the current image to the batch
2008 */
2009 function addCurrent() {
2010 $this->cur = array( $this->oldRel, $this->newRel );
2011 }
2012
2013 /**
2014 * Add the old versions of the image to the batch
2015 */
2016 function addOlds() {
2017 $archiveBase = 'archive';
2018 $this->olds = array();
2019 $this->oldCount = 0;
2020
2021 $result = $this->db->select( 'oldimage',
2022 array( 'oi_archive_name', 'oi_deleted' ),
2023 array( 'oi_name' => $this->oldName ),
2024 __METHOD__
2025 );
2026
2027 foreach ( $result as $row ) {
2028 $oldName = $row->oi_archive_name;
2029 $bits = explode( '!', $oldName, 2 );
2030
2031 if ( count( $bits ) != 2 ) {
2032 wfDebug( "Invalid old file name: $oldName \n" );
2033 continue;
2034 }
2035
2036 list( $timestamp, $filename ) = $bits;
2037
2038 if ( $this->oldName != $filename ) {
2039 wfDebug( "Invalid old file name: $oldName \n" );
2040 continue;
2041 }
2042
2043 $this->oldCount++;
2044
2045 // Do we want to add those to oldCount?
2046 if ( $row->oi_deleted & File::DELETED_FILE ) {
2047 continue;
2048 }
2049
2050 $this->olds[] = array(
2051 "{$archiveBase}/{$this->oldHash}{$oldName}",
2052 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2053 );
2054 }
2055 }
2056
2057 /**
2058 * Perform the move.
2059 */
2060 function execute() {
2061 $repo = $this->file->repo;
2062 $status = $repo->newGood();
2063 $triplets = $this->getMoveTriplets();
2064
2065 $triplets = $this->removeNonexistentFiles( $triplets );
2066
2067 // Copy the files into their new location
2068 $statusMove = $repo->storeBatch( $triplets );
2069 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2070 if ( !$statusMove->isGood() ) {
2071 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2072 $this->cleanupTarget( $triplets );
2073 $statusMove->ok = false;
2074 return $statusMove;
2075 }
2076
2077 $this->db->begin();
2078 $statusDb = $this->doDBUpdates();
2079 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2080 if ( !$statusDb->isGood() ) {
2081 $this->db->rollback();
2082 // Something went wrong with the DB updates, so remove the target files
2083 $this->cleanupTarget( $triplets );
2084 $statusDb->ok = false;
2085 return $statusDb;
2086 }
2087 $this->db->commit();
2088
2089 // Everything went ok, remove the source files
2090 $this->cleanupSource( $triplets );
2091
2092 $status->merge( $statusDb );
2093 $status->merge( $statusMove );
2094
2095 return $status;
2096 }
2097
2098 /**
2099 * Do the database updates and return a new FileRepoStatus indicating how
2100 * many rows where updated.
2101 *
2102 * @return FileRepoStatus
2103 */
2104 function doDBUpdates() {
2105 $repo = $this->file->repo;
2106 $status = $repo->newGood();
2107 $dbw = $this->db;
2108
2109 // Update current image
2110 $dbw->update(
2111 'image',
2112 array( 'img_name' => $this->newName ),
2113 array( 'img_name' => $this->oldName ),
2114 __METHOD__
2115 );
2116
2117 if ( $dbw->affectedRows() ) {
2118 $status->successCount++;
2119 } else {
2120 $status->failCount++;
2121 $status->fatal( 'imageinvalidfilename' );
2122 return $status;
2123 }
2124
2125 // Update old images
2126 $dbw->update(
2127 'oldimage',
2128 array(
2129 'oi_name' => $this->newName,
2130 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2131 ),
2132 array( 'oi_name' => $this->oldName ),
2133 __METHOD__
2134 );
2135
2136 $affected = $dbw->affectedRows();
2137 $total = $this->oldCount;
2138 $status->successCount += $affected;
2139 $status->failCount += $total - $affected;
2140 if ( $status->failCount ) {
2141 $status->error( 'imageinvalidfilename' );
2142 }
2143
2144 return $status;
2145 }
2146
2147 /**
2148 * Generate triplets for FSRepo::storeBatch().
2149 */
2150 function getMoveTriplets() {
2151 $moves = array_merge( array( $this->cur ), $this->olds );
2152 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2153
2154 foreach ( $moves as $move ) {
2155 // $move: (oldRelativePath, newRelativePath)
2156 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2157 $triplets[] = array( $srcUrl, 'public', $move[1] );
2158 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2159 }
2160
2161 return $triplets;
2162 }
2163
2164 /**
2165 * Removes non-existent files from move batch.
2166 */
2167 function removeNonexistentFiles( $triplets ) {
2168 $files = array();
2169
2170 foreach ( $triplets as $file ) {
2171 $files[$file[0]] = $file[0];
2172 }
2173
2174 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
2175 $filteredTriplets = array();
2176
2177 foreach ( $triplets as $file ) {
2178 if ( $result[$file[0]] ) {
2179 $filteredTriplets[] = $file;
2180 } else {
2181 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2182 }
2183 }
2184
2185 return $filteredTriplets;
2186 }
2187
2188 /**
2189 * Cleanup a partially moved array of triplets by deleting the target
2190 * files. Called if something went wrong half way.
2191 */
2192 function cleanupTarget( $triplets ) {
2193 // Create dest pairs from the triplets
2194 $pairs = array();
2195 foreach ( $triplets as $triplet ) {
2196 $pairs[] = array( $triplet[1], $triplet[2] );
2197 }
2198
2199 $this->file->repo->cleanupBatch( $pairs );
2200 }
2201
2202 /**
2203 * Cleanup a fully moved array of triplets by deleting the source files.
2204 * Called at the end of the move process if everything else went ok.
2205 */
2206 function cleanupSource( $triplets ) {
2207 // Create source file names from the triplets
2208 $files = array();
2209 foreach ( $triplets as $triplet ) {
2210 $files[] = $triplet[0];
2211 }
2212
2213 $this->file->repo->cleanupBatch( $files );
2214 }
2215 }