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