getPath() does the wrong thing under SwiftMedia, but getRel() works for everything.
[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 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 * @param $title
68 * @param $repo
69 * @param $unused
70 *
71 * @return LocalFile
72 */
73 static function newFromTitle( $title, $repo, $unused = null ) {
74 return new self( $title, $repo );
75 }
76
77 /**
78 * Create a LocalFile from a title
79 * Do not call this except from inside a repo class.
80 *
81 * @param $row
82 * @param $repo
83 *
84 * @return LocalFile
85 */
86 static function newFromRow( $row, $repo ) {
87 $title = Title::makeTitle( NS_FILE, $row->img_name );
88 $file = new self( $title, $repo );
89 $file->loadFromRow( $row );
90
91 return $file;
92 }
93
94 /**
95 * Create a LocalFile from a SHA-1 key
96 * Do not call this except from inside a repo class.
97 *
98 * @param $sha1 string
99 * @param $repo LocalRepo
100 * @param $timestamp string
101 *
102 * @return LocalFile
103 */
104 static function newFromKey( $sha1, $repo, $timestamp = false ) {
105 $conds = array( 'img_sha1' => $sha1 );
106
107 if ( $timestamp ) {
108 $conds['img_timestamp'] = $timestamp;
109 }
110
111 $dbr = $repo->getSlaveDB();
112 $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
113
114 if ( $row ) {
115 return self::newFromRow( $row, $repo );
116 } else {
117 return false;
118 }
119 }
120
121 /**
122 * Fields in the image table
123 */
124 static function selectFields() {
125 return array(
126 'img_name',
127 'img_size',
128 'img_width',
129 'img_height',
130 'img_metadata',
131 'img_bits',
132 'img_media_type',
133 'img_major_mime',
134 'img_minor_mime',
135 'img_description',
136 'img_user',
137 'img_user_text',
138 'img_timestamp',
139 'img_sha1',
140 );
141 }
142
143 /**
144 * Constructor.
145 * Do not call this except from inside a repo class.
146 */
147 function __construct( $title, $repo ) {
148 if ( !is_object( $title ) ) {
149 throw new MWException( __CLASS__ . ' constructor given bogus title.' );
150 }
151
152 parent::__construct( $title, $repo );
153
154 $this->metadata = '';
155 $this->historyLine = 0;
156 $this->historyRes = null;
157 $this->dataLoaded = false;
158 }
159
160 /**
161 * Get the memcached key for the main data for this file, or false if
162 * there is no access to the shared cache.
163 */
164 function getCacheKey() {
165 $hashedName = md5( $this->getName() );
166
167 return $this->repo->getSharedCacheKey( 'file', $hashedName );
168 }
169
170 /**
171 * Try to load file metadata from memcached. Returns true on success.
172 */
173 function loadFromCache() {
174 global $wgMemc;
175
176 wfProfileIn( __METHOD__ );
177 $this->dataLoaded = false;
178 $key = $this->getCacheKey();
179
180 if ( !$key ) {
181 wfProfileOut( __METHOD__ );
182 return false;
183 }
184
185 $cachedValues = $wgMemc->get( $key );
186
187 // Check if the key existed and belongs to this version of MediaWiki
188 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
189 wfDebug( "Pulling file metadata from cache key $key\n" );
190 $this->fileExists = $cachedValues['fileExists'];
191 if ( $this->fileExists ) {
192 $this->setProps( $cachedValues );
193 }
194 $this->dataLoaded = true;
195 }
196
197 if ( $this->dataLoaded ) {
198 wfIncrStats( 'image_cache_hit' );
199 } else {
200 wfIncrStats( 'image_cache_miss' );
201 }
202
203 wfProfileOut( __METHOD__ );
204 return $this->dataLoaded;
205 }
206
207 /**
208 * Save the file metadata to memcached
209 */
210 function saveToCache() {
211 global $wgMemc;
212
213 $this->load();
214 $key = $this->getCacheKey();
215
216 if ( !$key ) {
217 return;
218 }
219
220 $fields = $this->getCacheFields( '' );
221 $cache = array( 'version' => MW_FILE_VERSION );
222 $cache['fileExists'] = $this->fileExists;
223
224 if ( $this->fileExists ) {
225 foreach ( $fields as $field ) {
226 $cache[$field] = $this->$field;
227 }
228 }
229
230 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
231 }
232
233 /**
234 * Load metadata from the file itself
235 */
236 function loadFromFile() {
237 $this->setProps( self::getPropsFromPath( $this->getPath() ) );
238 }
239
240 function getCacheFields( $prefix = 'img_' ) {
241 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
242 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
243 static $results = array();
244
245 if ( $prefix == '' ) {
246 return $fields;
247 }
248
249 if ( !isset( $results[$prefix] ) ) {
250 $prefixedFields = array();
251 foreach ( $fields as $field ) {
252 $prefixedFields[] = $prefix . $field;
253 }
254 $results[$prefix] = $prefixedFields;
255 }
256
257 return $results[$prefix];
258 }
259
260 /**
261 * Load file metadata from the DB
262 */
263 function loadFromDB() {
264 # Polymorphic function name to distinguish foreign and local fetches
265 $fname = get_class( $this ) . '::' . __FUNCTION__;
266 wfProfileIn( $fname );
267
268 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
269 $this->dataLoaded = true;
270
271 $dbr = $this->repo->getMasterDB();
272
273 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
274 array( 'img_name' => $this->getName() ), $fname );
275
276 if ( $row ) {
277 $this->loadFromRow( $row );
278 } else {
279 $this->fileExists = false;
280 }
281
282 wfProfileOut( $fname );
283 }
284
285 /**
286 * Decode a row from the database (either object or array) to an array
287 * with timestamps and MIME types decoded, and the field prefix removed.
288 */
289 function decodeRow( $row, $prefix = 'img_' ) {
290 $array = (array)$row;
291 $prefixLength = strlen( $prefix );
292
293 // Sanity check prefix once
294 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
295 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
296 }
297
298 $decoded = array();
299
300 foreach ( $array as $name => $value ) {
301 $decoded[substr( $name, $prefixLength )] = $value;
302 }
303
304 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
305
306 if ( empty( $decoded['major_mime'] ) ) {
307 $decoded['mime'] = 'unknown/unknown';
308 } else {
309 if ( !$decoded['minor_mime'] ) {
310 $decoded['minor_mime'] = 'unknown';
311 }
312 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
313 }
314
315 # Trim zero padding from char/binary field
316 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
317
318 return $decoded;
319 }
320
321 /**
322 * Load file metadata from a DB result row
323 */
324 function loadFromRow( $row, $prefix = 'img_' ) {
325 $this->dataLoaded = true;
326 $array = $this->decodeRow( $row, $prefix );
327
328 foreach ( $array as $name => $value ) {
329 $this->$name = $value;
330 }
331
332 $this->fileExists = true;
333 $this->maybeUpgradeRow();
334 }
335
336 /**
337 * Load file metadata from cache or DB, unless already loaded
338 */
339 function load() {
340 if ( !$this->dataLoaded ) {
341 if ( !$this->loadFromCache() ) {
342 $this->loadFromDB();
343 $this->saveToCache();
344 }
345 $this->dataLoaded = true;
346 }
347 }
348
349 /**
350 * Upgrade a row if it needs it
351 */
352 function maybeUpgradeRow() {
353 global $wgUpdateCompatibleMetadata;
354 if ( wfReadOnly() ) {
355 return;
356 }
357
358 if ( is_null( $this->media_type ) ||
359 $this->mime == 'image/svg'
360 ) {
361 $this->upgradeRow();
362 $this->upgraded = true;
363 } else {
364 $handler = $this->getHandler();
365 if ( $handler ) {
366 $validity = $handler->isMetadataValid( $this, $this->metadata );
367 if ( $validity === MediaHandler::METADATA_BAD
368 || ( $validity === MediaHandler::METADATA_COMPATIBLE && $wgUpdateCompatibleMetadata )
369 ) {
370 $this->upgradeRow();
371 $this->upgraded = true;
372 }
373 }
374 }
375 }
376
377 function getUpgraded() {
378 return $this->upgraded;
379 }
380
381 /**
382 * Fix assorted version-related problems with the image row by reloading it from the file
383 */
384 function upgradeRow() {
385 wfProfileIn( __METHOD__ );
386
387 $this->loadFromFile();
388
389 # Don't destroy file info of missing files
390 if ( !$this->fileExists ) {
391 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
392 wfProfileOut( __METHOD__ );
393 return;
394 }
395
396 $dbw = $this->repo->getMasterDB();
397 list( $major, $minor ) = self::splitMime( $this->mime );
398
399 if ( wfReadOnly() ) {
400 wfProfileOut( __METHOD__ );
401 return;
402 }
403 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
404
405 $dbw->update( 'image',
406 array(
407 'img_width' => $this->width,
408 'img_height' => $this->height,
409 'img_bits' => $this->bits,
410 'img_media_type' => $this->media_type,
411 'img_major_mime' => $major,
412 'img_minor_mime' => $minor,
413 'img_metadata' => $this->metadata,
414 'img_sha1' => $this->sha1,
415 ), array( 'img_name' => $this->getName() ),
416 __METHOD__
417 );
418
419 $this->saveToCache();
420 wfProfileOut( __METHOD__ );
421 }
422
423 /**
424 * Set properties in this object to be equal to those given in the
425 * associative array $info. Only cacheable fields can be set.
426 *
427 * If 'mime' is given, it will be split into major_mime/minor_mime.
428 * If major_mime/minor_mime are given, $this->mime will also be set.
429 */
430 function setProps( $info ) {
431 $this->dataLoaded = true;
432 $fields = $this->getCacheFields( '' );
433 $fields[] = 'fileExists';
434
435 foreach ( $fields as $field ) {
436 if ( isset( $info[$field] ) ) {
437 $this->$field = $info[$field];
438 }
439 }
440
441 // Fix up mime fields
442 if ( isset( $info['major_mime'] ) ) {
443 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
444 } elseif ( isset( $info['mime'] ) ) {
445 $this->mime = $info['mime'];
446 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
447 }
448 }
449
450 /** splitMime inherited */
451 /** getName inherited */
452 /** getTitle inherited */
453 /** getURL inherited */
454 /** getViewURL inherited */
455 /** getPath inherited */
456 /** isVisible inhereted */
457
458 function isMissing() {
459 if ( $this->missing === null ) {
460 list( $fileExists ) = $this->repo->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo::FILES_ONLY );
461 $this->missing = !$fileExists;
462 }
463 return $this->missing;
464 }
465
466 /**
467 * Return the width of the image
468 *
469 * Returns false on error
470 */
471 public function getWidth( $page = 1 ) {
472 $this->load();
473
474 if ( $this->isMultipage() ) {
475 $dim = $this->getHandler()->getPageDimensions( $this, $page );
476 if ( $dim ) {
477 return $dim['width'];
478 } else {
479 return false;
480 }
481 } else {
482 return $this->width;
483 }
484 }
485
486 /**
487 * Return the height of the image
488 *
489 * Returns false on error
490 */
491 public function getHeight( $page = 1 ) {
492 $this->load();
493
494 if ( $this->isMultipage() ) {
495 $dim = $this->getHandler()->getPageDimensions( $this, $page );
496 if ( $dim ) {
497 return $dim['height'];
498 } else {
499 return false;
500 }
501 } else {
502 return $this->height;
503 }
504 }
505
506 /**
507 * Returns ID or name of user who uploaded the file
508 *
509 * @param $type string 'text' or 'id'
510 */
511 function getUser( $type = 'text' ) {
512 $this->load();
513
514 if ( $type == 'text' ) {
515 return $this->user_text;
516 } elseif ( $type == 'id' ) {
517 return $this->user;
518 }
519 }
520
521 /**
522 * Get handler-specific metadata
523 */
524 function getMetadata() {
525 $this->load();
526 return $this->metadata;
527 }
528
529 function getBitDepth() {
530 $this->load();
531 return $this->bits;
532 }
533
534 /**
535 * Return the size of the image file, in bytes
536 */
537 public function getSize() {
538 $this->load();
539 return $this->size;
540 }
541
542 /**
543 * Returns the mime type of the file.
544 */
545 function getMimeType() {
546 $this->load();
547 return $this->mime;
548 }
549
550 /**
551 * Return the type of the media in the file.
552 * Use the value returned by this function with the MEDIATYPE_xxx constants.
553 */
554 function getMediaType() {
555 $this->load();
556 return $this->media_type;
557 }
558
559 /** canRender inherited */
560 /** mustRender inherited */
561 /** allowInlineDisplay inherited */
562 /** isSafeFile inherited */
563 /** isTrustedFile inherited */
564
565 /**
566 * Returns true if the file exists on disk.
567 * @return boolean Whether file exist on disk.
568 */
569 public function exists() {
570 $this->load();
571 return $this->fileExists;
572 }
573
574 /** getTransformScript inherited */
575 /** getUnscaledThumb inherited */
576 /** thumbName inherited */
577 /** createThumb inherited */
578 /** transform inherited */
579
580 /**
581 * Fix thumbnail files from 1.4 or before, with extreme prejudice
582 */
583 function migrateThumbFile( $thumbName ) {
584 $thumbDir = $this->getThumbPath();
585 $thumbPath = "$thumbDir/$thumbName";
586
587 if ( is_dir( $thumbPath ) ) {
588 // Directory where file should be
589 // This happened occasionally due to broken migration code in 1.5
590 // Rename to broken-*
591 for ( $i = 0; $i < 100 ; $i++ ) {
592 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
593 if ( !file_exists( $broken ) ) {
594 rename( $thumbPath, $broken );
595 break;
596 }
597 }
598 // Doesn't exist anymore
599 clearstatcache();
600 }
601
602 if ( is_file( $thumbDir ) ) {
603 // File where directory should be
604 unlink( $thumbDir );
605 // Doesn't exist anymore
606 clearstatcache();
607 }
608 }
609
610 /** getHandler inherited */
611 /** iconThumb inherited */
612 /** getLastError inherited */
613
614 /**
615 * Get all thumbnail names previously generated for this file
616 */
617 function getThumbnails() {
618 $this->load();
619
620 $files = array();
621 $dir = $this->getThumbPath();
622
623 if ( is_dir( $dir ) ) {
624 $handle = opendir( $dir );
625
626 if ( $handle ) {
627 while ( false !== ( $file = readdir( $handle ) ) ) {
628 if ( $file { 0 } != '.' ) {
629 $files[] = $file;
630 }
631 }
632
633 closedir( $handle );
634 }
635 }
636
637 return $files;
638 }
639
640 /**
641 * Refresh metadata in memcached, but don't touch thumbnails or squid
642 */
643 function purgeMetadataCache() {
644 $this->loadFromDB();
645 $this->saveToCache();
646 $this->purgeHistory();
647 }
648
649 /**
650 * Purge the shared history (OldLocalFile) cache
651 */
652 function purgeHistory() {
653 global $wgMemc;
654
655 $hashedName = md5( $this->getName() );
656 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
657
658 if ( $oldKey ) {
659 $wgMemc->delete( $oldKey );
660 }
661 }
662
663 /**
664 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
665 */
666 function purgeCache() {
667 // Refresh metadata cache
668 $this->purgeMetadataCache();
669
670 // Delete thumbnails
671 $this->purgeThumbnails();
672
673 // Purge squid cache for this file
674 SquidUpdate::purge( array( $this->getURL() ) );
675 }
676
677 /**
678 * Delete cached transformed files
679 */
680 function purgeThumbnails() {
681 global $wgUseSquid, $wgExcludeFromThumbnailPurge;
682
683 // Delete thumbnails
684 $files = $this->getThumbnails();
685 $dir = $this->getThumbPath();
686 $urls = array();
687
688 foreach ( $files as $file ) {
689 // Only remove files not in the $wgExcludeFromThumbnailPurge configuration variable
690 $ext = pathinfo( "$dir/$file", PATHINFO_EXTENSION );
691 if ( in_array( $ext, $wgExcludeFromThumbnailPurge ) ) {
692 continue;
693 }
694
695 # Check that the base file name is part of the thumb name
696 # This is a basic sanity check to avoid erasing unrelated directories
697 if ( strpos( $file, $this->getName() ) !== false ) {
698 $url = $this->getThumbUrl( $file );
699 $urls[] = $url;
700 @unlink( "$dir/$file" );
701 }
702 }
703
704 // Purge the squid
705 if ( $wgUseSquid ) {
706 SquidUpdate::purge( $urls );
707 }
708 }
709
710 /** purgeDescription inherited */
711 /** purgeEverything inherited */
712
713 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
714 $dbr = $this->repo->getSlaveDB();
715 $tables = array( 'oldimage' );
716 $fields = OldLocalFile::selectFields();
717 $conds = $opts = $join_conds = array();
718 $eq = $inc ? '=' : '';
719 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
720
721 if ( $start ) {
722 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
723 }
724
725 if ( $end ) {
726 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
727 }
728
729 if ( $limit ) {
730 $opts['LIMIT'] = $limit;
731 }
732
733 // Search backwards for time > x queries
734 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
735 $opts['ORDER BY'] = "oi_timestamp $order";
736 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
737
738 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
739 &$conds, &$opts, &$join_conds ) );
740
741 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
742 $r = array();
743
744 foreach ( $res as $row ) {
745 if ( $this->repo->oldFileFromRowFactory ) {
746 $r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
747 } else {
748 $r[] = OldLocalFile::newFromRow( $row, $this->repo );
749 }
750 }
751
752 if ( $order == 'ASC' ) {
753 $r = array_reverse( $r ); // make sure it ends up descending
754 }
755
756 return $r;
757 }
758
759 /**
760 * Return the history of this file, line by line.
761 * starts with current version, then old versions.
762 * uses $this->historyLine to check which line to return:
763 * 0 return line for current version
764 * 1 query for old versions, return first one
765 * 2, ... return next old version from above query
766 */
767 public function nextHistoryLine() {
768 # Polymorphic function name to distinguish foreign and local fetches
769 $fname = get_class( $this ) . '::' . __FUNCTION__;
770
771 $dbr = $this->repo->getSlaveDB();
772
773 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
774 $this->historyRes = $dbr->select( 'image',
775 array(
776 '*',
777 "'' AS oi_archive_name",
778 '0 as oi_deleted',
779 'img_sha1'
780 ),
781 array( 'img_name' => $this->title->getDBkey() ),
782 $fname
783 );
784
785 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
786 $this->historyRes = null;
787 return false;
788 }
789 } elseif ( $this->historyLine == 1 ) {
790 $this->historyRes = $dbr->select( 'oldimage', '*',
791 array( 'oi_name' => $this->title->getDBkey() ),
792 $fname,
793 array( 'ORDER BY' => 'oi_timestamp DESC' )
794 );
795 }
796 $this->historyLine ++;
797
798 return $dbr->fetchObject( $this->historyRes );
799 }
800
801 /**
802 * Reset the history pointer to the first element of the history
803 */
804 public function resetHistory() {
805 $this->historyLine = 0;
806
807 if ( !is_null( $this->historyRes ) ) {
808 $this->historyRes = null;
809 }
810 }
811
812 /** getFullPath inherited */
813 /** getHashPath inherited */
814 /** getRel inherited */
815 /** getUrlRel inherited */
816 /** getArchiveRel inherited */
817 /** getArchivePath inherited */
818 /** getThumbPath inherited */
819 /** getArchiveUrl inherited */
820 /** getThumbUrl inherited */
821 /** getArchiveVirtualUrl inherited */
822 /** getThumbVirtualUrl inherited */
823 /** isHashed inherited */
824
825 /**
826 * Upload a file and record it in the DB
827 * @param $srcPath String: source path or virtual URL
828 * @param $comment String: upload description
829 * @param $pageText String: text to use for the new description page,
830 * if a new description page is created
831 * @param $flags Integer: flags for publish()
832 * @param $props Array: File properties, if known. This can be used to reduce the
833 * upload time when uploading virtual URLs for which the file info
834 * is already known
835 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
836 * @param $user Mixed: User object or null to use $wgUser
837 *
838 * @return FileRepoStatus object. On success, the value member contains the
839 * archive name, or an empty string if it was a new file.
840 */
841 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
842 $this->lock();
843 $status = $this->publish( $srcPath, $flags );
844
845 if ( $status->ok ) {
846 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
847 $status->fatal( 'filenotfound', $srcPath );
848 }
849 }
850
851 $this->unlock();
852
853 return $status;
854 }
855
856 /**
857 * Record a file upload in the upload log and the image table
858 */
859 function recordUpload2(
860 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
861 ) {
862 if ( is_null( $user ) ) {
863 global $wgUser;
864 $user = $wgUser;
865 }
866
867 $dbw = $this->repo->getMasterDB();
868 $dbw->begin();
869
870 if ( !$props ) {
871 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
872 }
873
874 if ( $timestamp === false ) {
875 $timestamp = $dbw->timestamp();
876 }
877
878 $props['description'] = $comment;
879 $props['user'] = $user->getId();
880 $props['user_text'] = $user->getName();
881 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
882 $this->setProps( $props );
883
884 # Delete thumbnails
885 $this->purgeThumbnails();
886
887 # The file is already on its final location, remove it from the squid cache
888 SquidUpdate::purge( array( $this->getURL() ) );
889
890 # Fail now if the file isn't there
891 if ( !$this->fileExists ) {
892 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
893 return false;
894 }
895
896 $reupload = false;
897
898 # Test to see if the row exists using INSERT IGNORE
899 # This avoids race conditions by locking the row until the commit, and also
900 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
901 $dbw->insert( 'image',
902 array(
903 'img_name' => $this->getName(),
904 'img_size' => $this->size,
905 'img_width' => intval( $this->width ),
906 'img_height' => intval( $this->height ),
907 'img_bits' => $this->bits,
908 'img_media_type' => $this->media_type,
909 'img_major_mime' => $this->major_mime,
910 'img_minor_mime' => $this->minor_mime,
911 'img_timestamp' => $timestamp,
912 'img_description' => $comment,
913 'img_user' => $user->getId(),
914 'img_user_text' => $user->getName(),
915 'img_metadata' => $this->metadata,
916 'img_sha1' => $this->sha1
917 ),
918 __METHOD__,
919 'IGNORE'
920 );
921
922 if ( $dbw->affectedRows() == 0 ) {
923 $reupload = true;
924
925 # Collision, this is an update of a file
926 # Insert previous contents into oldimage
927 $dbw->insertSelect( 'oldimage', 'image',
928 array(
929 'oi_name' => 'img_name',
930 'oi_archive_name' => $dbw->addQuotes( $oldver ),
931 'oi_size' => 'img_size',
932 'oi_width' => 'img_width',
933 'oi_height' => 'img_height',
934 'oi_bits' => 'img_bits',
935 'oi_timestamp' => 'img_timestamp',
936 'oi_description' => 'img_description',
937 'oi_user' => 'img_user',
938 'oi_user_text' => 'img_user_text',
939 'oi_metadata' => 'img_metadata',
940 'oi_media_type' => 'img_media_type',
941 'oi_major_mime' => 'img_major_mime',
942 'oi_minor_mime' => 'img_minor_mime',
943 'oi_sha1' => 'img_sha1'
944 ), array( 'img_name' => $this->getName() ), __METHOD__
945 );
946
947 # Update the current image row
948 $dbw->update( 'image',
949 array( /* SET */
950 'img_size' => $this->size,
951 'img_width' => intval( $this->width ),
952 'img_height' => intval( $this->height ),
953 'img_bits' => $this->bits,
954 'img_media_type' => $this->media_type,
955 'img_major_mime' => $this->major_mime,
956 'img_minor_mime' => $this->minor_mime,
957 'img_timestamp' => $timestamp,
958 'img_description' => $comment,
959 'img_user' => $user->getId(),
960 'img_user_text' => $user->getName(),
961 'img_metadata' => $this->metadata,
962 'img_sha1' => $this->sha1
963 ), array( /* WHERE */
964 'img_name' => $this->getName()
965 ), __METHOD__
966 );
967 } else {
968 # This is a new file
969 # Update the image count
970 $site_stats = $dbw->tableName( 'site_stats' );
971 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
972 }
973
974 $descTitle = $this->getTitle();
975 $article = new ImagePage( $descTitle );
976 $article->setFile( $this );
977
978 # Add the log entry
979 $log = new LogPage( 'upload' );
980 $action = $reupload ? 'overwrite' : 'upload';
981 $log->addEntry( $action, $descTitle, $comment, array(), $user );
982
983 if ( $descTitle->exists() ) {
984 # Create a null revision
985 $latest = $descTitle->getLatestRevID();
986 $nullRevision = Revision::newNullRevision(
987 $dbw,
988 $descTitle->getArticleId(),
989 $log->getRcComment(),
990 false
991 );
992 $nullRevision->insertOn( $dbw );
993
994 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
995 $article->updateRevisionOn( $dbw, $nullRevision );
996
997 # Invalidate the cache for the description page
998 $descTitle->invalidateCache();
999 $descTitle->purgeSquid();
1000 } else {
1001 # New file; create the description page.
1002 # There's already a log entry, so don't make a second RC entry
1003 # Squid and file cache for the description page are purged by doEdit.
1004 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
1005 }
1006
1007 # Commit the transaction now, in case something goes wrong later
1008 # The most important thing is that files don't get lost, especially archives
1009 $dbw->commit();
1010
1011 # Save to cache and purge the squid
1012 # We shall not saveToCache before the commit since otherwise
1013 # in case of a rollback there is an usable file from memcached
1014 # which in fact doesn't really exist (bug 24978)
1015 $this->saveToCache();
1016
1017 # Hooks, hooks, the magic of hooks...
1018 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1019
1020 # Invalidate cache for all pages using this file
1021 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1022 $update->doUpdate();
1023
1024 # Invalidate cache for all pages that redirects on this page
1025 $redirs = $this->getTitle()->getRedirectsHere();
1026
1027 foreach ( $redirs as $redir ) {
1028 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1029 $update->doUpdate();
1030 }
1031
1032 return true;
1033 }
1034
1035 /**
1036 * Move or copy a file to its public location. If a file exists at the
1037 * destination, move it to an archive. Returns a FileRepoStatus object with
1038 * the archive name in the "value" member on success.
1039 *
1040 * The archive name should be passed through to recordUpload for database
1041 * registration.
1042 *
1043 * @param $srcPath String: local filesystem path to the source image
1044 * @param $flags Integer: a bitwise combination of:
1045 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1046 * @return FileRepoStatus object. On success, the value member contains the
1047 * archive name, or an empty string if it was a new file.
1048 */
1049 function publish( $srcPath, $flags = 0 ) {
1050 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1051 }
1052
1053 /**
1054 * Move or copy a file to a specified location. Returns a FileRepoStatus
1055 * object with the archive name in the "value" member on success.
1056 *
1057 * The archive name should be passed through to recordUpload for database
1058 * registration.
1059 *
1060 * @param $srcPath String: local filesystem path to the source image
1061 * @param $dstRel String: target relative path
1062 * @param $flags Integer: a bitwise combination of:
1063 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1064 * @return FileRepoStatus object. On success, the value member contains the
1065 * archive name, or an empty string if it was a new file.
1066 */
1067 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1068 $this->lock();
1069
1070 $archiveName = wfTimestamp( TS_MW ) . '!'. $this->getName();
1071 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1072 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1073 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
1074
1075 if ( $status->value == 'new' ) {
1076 $status->value = '';
1077 } else {
1078 $status->value = $archiveName;
1079 }
1080
1081 $this->unlock();
1082
1083 return $status;
1084 }
1085
1086 /** getLinksTo inherited */
1087 /** getExifData inherited */
1088 /** isLocal inherited */
1089 /** wasDeleted inherited */
1090
1091 /**
1092 * Move file to the new title
1093 *
1094 * Move current, old version and all thumbnails
1095 * to the new filename. Old file is deleted.
1096 *
1097 * Cache purging is done; checks for validity
1098 * and logging are caller's responsibility
1099 *
1100 * @param $target Title New file name
1101 * @return FileRepoStatus object.
1102 */
1103 function move( $target ) {
1104 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1105 $this->lock();
1106
1107 $batch = new LocalFileMoveBatch( $this, $target );
1108 $batch->addCurrent();
1109 $batch->addOlds();
1110
1111 $status = $batch->execute();
1112 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1113
1114 $this->purgeEverything();
1115 $this->unlock();
1116
1117 if ( $status->isOk() ) {
1118 // Now switch the object
1119 $this->title = $target;
1120 // Force regeneration of the name and hashpath
1121 unset( $this->name );
1122 unset( $this->hashPath );
1123 // Purge the new image
1124 $this->purgeEverything();
1125 }
1126
1127 return $status;
1128 }
1129
1130 /**
1131 * Delete all versions of the file.
1132 *
1133 * Moves the files into an archive directory (or deletes them)
1134 * and removes the database rows.
1135 *
1136 * Cache purging is done; logging is caller's responsibility.
1137 *
1138 * @param $reason
1139 * @param $suppress
1140 * @return FileRepoStatus object.
1141 */
1142 function delete( $reason, $suppress = false ) {
1143 $this->lock();
1144
1145 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1146 $batch->addCurrent();
1147
1148 # Get old version relative paths
1149 $dbw = $this->repo->getMasterDB();
1150 $result = $dbw->select( 'oldimage',
1151 array( 'oi_archive_name' ),
1152 array( 'oi_name' => $this->getName() ) );
1153 foreach ( $result as $row ) {
1154 $batch->addOld( $row->oi_archive_name );
1155 }
1156 $status = $batch->execute();
1157
1158 if ( $status->ok ) {
1159 // Update site_stats
1160 $site_stats = $dbw->tableName( 'site_stats' );
1161 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1162 $this->purgeEverything();
1163 }
1164
1165 $this->unlock();
1166
1167 return $status;
1168 }
1169
1170 /**
1171 * Delete an old version of the file.
1172 *
1173 * Moves the file into an archive directory (or deletes it)
1174 * and removes the database row.
1175 *
1176 * Cache purging is done; logging is caller's responsibility.
1177 *
1178 * @param $archiveName String
1179 * @param $reason String
1180 * @param $suppress Boolean
1181 * @throws MWException or FSException on database or file store failure
1182 * @return FileRepoStatus object.
1183 */
1184 function deleteOld( $archiveName, $reason, $suppress = false ) {
1185 $this->lock();
1186
1187 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1188 $batch->addOld( $archiveName );
1189 $status = $batch->execute();
1190
1191 $this->unlock();
1192
1193 if ( $status->ok ) {
1194 $this->purgeDescription();
1195 $this->purgeHistory();
1196 }
1197
1198 return $status;
1199 }
1200
1201 /**
1202 * Restore all or specified deleted revisions to the given file.
1203 * Permissions and logging are left to the caller.
1204 *
1205 * May throw database exceptions on error.
1206 *
1207 * @param $versions set of record ids of deleted items to restore,
1208 * or empty to restore all revisions.
1209 * @param $unsuppress Boolean
1210 * @return FileRepoStatus
1211 */
1212 function restore( $versions = array(), $unsuppress = false ) {
1213 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1214
1215 if ( !$versions ) {
1216 $batch->addAll();
1217 } else {
1218 $batch->addIds( $versions );
1219 }
1220
1221 $status = $batch->execute();
1222
1223 if ( !$status->isGood() ) {
1224 return $status;
1225 }
1226
1227 $cleanupStatus = $batch->cleanup();
1228 $cleanupStatus->successCount = 0;
1229 $cleanupStatus->failCount = 0;
1230 $status->merge( $cleanupStatus );
1231
1232 return $status;
1233 }
1234
1235 /** isMultipage inherited */
1236 /** pageCount inherited */
1237 /** scaleHeight inherited */
1238 /** getImageSize inherited */
1239
1240 /**
1241 * Get the URL of the file description page.
1242 */
1243 function getDescriptionUrl() {
1244 return $this->title->getLocalUrl();
1245 }
1246
1247 /**
1248 * Get the HTML text of the description page
1249 * This is not used by ImagePage for local files, since (among other things)
1250 * it skips the parser cache.
1251 */
1252 function getDescriptionText() {
1253 global $wgParser;
1254 $revision = Revision::newFromTitle( $this->title );
1255 if ( !$revision ) return false;
1256 $text = $revision->getText();
1257 if ( !$text ) return false;
1258 $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
1259 return $pout->getText();
1260 }
1261
1262 function getDescription() {
1263 $this->load();
1264 return $this->description;
1265 }
1266
1267 function getTimestamp() {
1268 $this->load();
1269 return $this->timestamp;
1270 }
1271
1272 function getSha1() {
1273 $this->load();
1274 // Initialise now if necessary
1275 if ( $this->sha1 == '' && $this->fileExists ) {
1276 $this->sha1 = File::sha1Base36( $this->getPath() );
1277 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1278 $dbw = $this->repo->getMasterDB();
1279 $dbw->update( 'image',
1280 array( 'img_sha1' => $this->sha1 ),
1281 array( 'img_name' => $this->getName() ),
1282 __METHOD__ );
1283 $this->saveToCache();
1284 }
1285 }
1286
1287 return $this->sha1;
1288 }
1289
1290 /**
1291 * Start a transaction and lock the image for update
1292 * Increments a reference counter if the lock is already held
1293 * @return boolean True if the image exists, false otherwise
1294 */
1295 function lock() {
1296 $dbw = $this->repo->getMasterDB();
1297
1298 if ( !$this->locked ) {
1299 $dbw->begin();
1300 $this->locked++;
1301 }
1302
1303 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1304 }
1305
1306 /**
1307 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1308 * the transaction and thereby releases the image lock.
1309 */
1310 function unlock() {
1311 if ( $this->locked ) {
1312 --$this->locked;
1313 if ( !$this->locked ) {
1314 $dbw = $this->repo->getMasterDB();
1315 $dbw->commit();
1316 }
1317 }
1318 }
1319
1320 /**
1321 * Roll back the DB transaction and mark the image unlocked
1322 */
1323 function unlockAndRollback() {
1324 $this->locked = false;
1325 $dbw = $this->repo->getMasterDB();
1326 $dbw->rollback();
1327 }
1328 } // LocalFile class
1329
1330 # ------------------------------------------------------------------------------
1331
1332 /**
1333 * Helper class for file deletion
1334 * @ingroup FileRepo
1335 */
1336 class LocalFileDeleteBatch {
1337
1338 /**
1339 * @var LocalFile
1340 */
1341 var $file;
1342
1343 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1344 var $status;
1345
1346 function __construct( File $file, $reason = '', $suppress = false ) {
1347 $this->file = $file;
1348 $this->reason = $reason;
1349 $this->suppress = $suppress;
1350 $this->status = $file->repo->newGood();
1351 }
1352
1353 function addCurrent() {
1354 $this->srcRels['.'] = $this->file->getRel();
1355 }
1356
1357 function addOld( $oldName ) {
1358 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1359 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1360 }
1361
1362 function getOldRels() {
1363 if ( !isset( $this->srcRels['.'] ) ) {
1364 $oldRels =& $this->srcRels;
1365 $deleteCurrent = false;
1366 } else {
1367 $oldRels = $this->srcRels;
1368 unset( $oldRels['.'] );
1369 $deleteCurrent = true;
1370 }
1371
1372 return array( $oldRels, $deleteCurrent );
1373 }
1374
1375 protected function getHashes() {
1376 $hashes = array();
1377 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1378
1379 if ( $deleteCurrent ) {
1380 $hashes['.'] = $this->file->getSha1();
1381 }
1382
1383 if ( count( $oldRels ) ) {
1384 $dbw = $this->file->repo->getMasterDB();
1385 $res = $dbw->select(
1386 'oldimage',
1387 array( 'oi_archive_name', 'oi_sha1' ),
1388 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1389 __METHOD__
1390 );
1391
1392 foreach ( $res as $row ) {
1393 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1394 // Get the hash from the file
1395 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1396 $props = $this->file->repo->getFileProps( $oldUrl );
1397
1398 if ( $props['fileExists'] ) {
1399 // Upgrade the oldimage row
1400 $dbw->update( 'oldimage',
1401 array( 'oi_sha1' => $props['sha1'] ),
1402 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1403 __METHOD__ );
1404 $hashes[$row->oi_archive_name] = $props['sha1'];
1405 } else {
1406 $hashes[$row->oi_archive_name] = false;
1407 }
1408 } else {
1409 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1410 }
1411 }
1412 }
1413
1414 $missing = array_diff_key( $this->srcRels, $hashes );
1415
1416 foreach ( $missing as $name => $rel ) {
1417 $this->status->error( 'filedelete-old-unregistered', $name );
1418 }
1419
1420 foreach ( $hashes as $name => $hash ) {
1421 if ( !$hash ) {
1422 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1423 unset( $hashes[$name] );
1424 }
1425 }
1426
1427 return $hashes;
1428 }
1429
1430 function doDBInserts() {
1431 global $wgUser;
1432
1433 $dbw = $this->file->repo->getMasterDB();
1434 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1435 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1436 $encReason = $dbw->addQuotes( $this->reason );
1437 $encGroup = $dbw->addQuotes( 'deleted' );
1438 $ext = $this->file->getExtension();
1439 $dotExt = $ext === '' ? '' : ".$ext";
1440 $encExt = $dbw->addQuotes( $dotExt );
1441 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1442
1443 // Bitfields to further suppress the content
1444 if ( $this->suppress ) {
1445 $bitfield = 0;
1446 // This should be 15...
1447 $bitfield |= Revision::DELETED_TEXT;
1448 $bitfield |= Revision::DELETED_COMMENT;
1449 $bitfield |= Revision::DELETED_USER;
1450 $bitfield |= Revision::DELETED_RESTRICTED;
1451 } else {
1452 $bitfield = 'oi_deleted';
1453 }
1454
1455 if ( $deleteCurrent ) {
1456 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1457 $where = array( 'img_name' => $this->file->getName() );
1458 $dbw->insertSelect( 'filearchive', 'image',
1459 array(
1460 'fa_storage_group' => $encGroup,
1461 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1462 'fa_deleted_user' => $encUserId,
1463 'fa_deleted_timestamp' => $encTimestamp,
1464 'fa_deleted_reason' => $encReason,
1465 'fa_deleted' => $this->suppress ? $bitfield : 0,
1466
1467 'fa_name' => 'img_name',
1468 'fa_archive_name' => 'NULL',
1469 'fa_size' => 'img_size',
1470 'fa_width' => 'img_width',
1471 'fa_height' => 'img_height',
1472 'fa_metadata' => 'img_metadata',
1473 'fa_bits' => 'img_bits',
1474 'fa_media_type' => 'img_media_type',
1475 'fa_major_mime' => 'img_major_mime',
1476 'fa_minor_mime' => 'img_minor_mime',
1477 'fa_description' => 'img_description',
1478 'fa_user' => 'img_user',
1479 'fa_user_text' => 'img_user_text',
1480 'fa_timestamp' => 'img_timestamp'
1481 ), $where, __METHOD__ );
1482 }
1483
1484 if ( count( $oldRels ) ) {
1485 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1486 $where = array(
1487 'oi_name' => $this->file->getName(),
1488 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1489 $dbw->insertSelect( 'filearchive', 'oldimage',
1490 array(
1491 'fa_storage_group' => $encGroup,
1492 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1493 'fa_deleted_user' => $encUserId,
1494 'fa_deleted_timestamp' => $encTimestamp,
1495 'fa_deleted_reason' => $encReason,
1496 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1497
1498 'fa_name' => 'oi_name',
1499 'fa_archive_name' => 'oi_archive_name',
1500 'fa_size' => 'oi_size',
1501 'fa_width' => 'oi_width',
1502 'fa_height' => 'oi_height',
1503 'fa_metadata' => 'oi_metadata',
1504 'fa_bits' => 'oi_bits',
1505 'fa_media_type' => 'oi_media_type',
1506 'fa_major_mime' => 'oi_major_mime',
1507 'fa_minor_mime' => 'oi_minor_mime',
1508 'fa_description' => 'oi_description',
1509 'fa_user' => 'oi_user',
1510 'fa_user_text' => 'oi_user_text',
1511 'fa_timestamp' => 'oi_timestamp',
1512 'fa_deleted' => $bitfield
1513 ), $where, __METHOD__ );
1514 }
1515 }
1516
1517 function doDBDeletes() {
1518 $dbw = $this->file->repo->getMasterDB();
1519 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1520
1521 if ( count( $oldRels ) ) {
1522 $dbw->delete( 'oldimage',
1523 array(
1524 'oi_name' => $this->file->getName(),
1525 'oi_archive_name' => array_keys( $oldRels )
1526 ), __METHOD__ );
1527 }
1528
1529 if ( $deleteCurrent ) {
1530 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1531 }
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 /**
1974 * Cleanup a failed batch. The batch was only partially successful, so
1975 * rollback by removing all items that were succesfully copied.
1976 *
1977 * @param Status $storeStatus
1978 * @param array $storeBatch
1979 */
1980 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
1981 $cleanupBatch = array();
1982
1983 foreach ( $storeStatus->success as $i => $success ) {
1984 if ( $success ) {
1985 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][1] );
1986 }
1987 }
1988 $this->file->repo->cleanupBatch( $cleanupBatch );
1989 }
1990 }
1991
1992 # ------------------------------------------------------------------------------
1993
1994 /**
1995 * Helper class for file movement
1996 * @ingroup FileRepo
1997 */
1998 class LocalFileMoveBatch {
1999 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
2000
2001 function __construct( File $file, Title $target ) {
2002 $this->file = $file;
2003 $this->target = $target;
2004 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2005 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2006 $this->oldName = $this->file->getName();
2007 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2008 $this->oldRel = $this->oldHash . $this->oldName;
2009 $this->newRel = $this->newHash . $this->newName;
2010 $this->db = $file->repo->getMasterDb();
2011 }
2012
2013 /**
2014 * Add the current image to the batch
2015 */
2016 function addCurrent() {
2017 $this->cur = array( $this->oldRel, $this->newRel );
2018 }
2019
2020 /**
2021 * Add the old versions of the image to the batch
2022 */
2023 function addOlds() {
2024 $archiveBase = 'archive';
2025 $this->olds = array();
2026 $this->oldCount = 0;
2027
2028 $result = $this->db->select( 'oldimage',
2029 array( 'oi_archive_name', 'oi_deleted' ),
2030 array( 'oi_name' => $this->oldName ),
2031 __METHOD__
2032 );
2033
2034 foreach ( $result as $row ) {
2035 $oldName = $row->oi_archive_name;
2036 $bits = explode( '!', $oldName, 2 );
2037
2038 if ( count( $bits ) != 2 ) {
2039 wfDebug( "Old file name missing !: '$oldName' \n" );
2040 continue;
2041 }
2042
2043 list( $timestamp, $filename ) = $bits;
2044
2045 if ( $this->oldName != $filename ) {
2046 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2047 continue;
2048 }
2049
2050 $this->oldCount++;
2051
2052 // Do we want to add those to oldCount?
2053 if ( $row->oi_deleted & File::DELETED_FILE ) {
2054 continue;
2055 }
2056
2057 $this->olds[] = array(
2058 "{$archiveBase}/{$this->oldHash}{$oldName}",
2059 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2060 );
2061 }
2062 }
2063
2064 /**
2065 * Perform the move.
2066 */
2067 function execute() {
2068 $repo = $this->file->repo;
2069 $status = $repo->newGood();
2070 $triplets = $this->getMoveTriplets();
2071
2072 $triplets = $this->removeNonexistentFiles( $triplets );
2073
2074 // Copy the files into their new location
2075 $statusMove = $repo->storeBatch( $triplets );
2076 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2077 if ( !$statusMove->isGood() ) {
2078 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2079 $this->cleanupTarget( $triplets );
2080 $statusMove->ok = false;
2081 return $statusMove;
2082 }
2083
2084 $this->db->begin();
2085 $statusDb = $this->doDBUpdates();
2086 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2087 if ( !$statusDb->isGood() ) {
2088 $this->db->rollback();
2089 // Something went wrong with the DB updates, so remove the target files
2090 $this->cleanupTarget( $triplets );
2091 $statusDb->ok = false;
2092 return $statusDb;
2093 }
2094 $this->db->commit();
2095
2096 // Everything went ok, remove the source files
2097 $this->cleanupSource( $triplets );
2098
2099 $status->merge( $statusDb );
2100 $status->merge( $statusMove );
2101
2102 return $status;
2103 }
2104
2105 /**
2106 * Do the database updates and return a new FileRepoStatus indicating how
2107 * many rows where updated.
2108 *
2109 * @return FileRepoStatus
2110 */
2111 function doDBUpdates() {
2112 $repo = $this->file->repo;
2113 $status = $repo->newGood();
2114 $dbw = $this->db;
2115
2116 // Update current image
2117 $dbw->update(
2118 'image',
2119 array( 'img_name' => $this->newName ),
2120 array( 'img_name' => $this->oldName ),
2121 __METHOD__
2122 );
2123
2124 if ( $dbw->affectedRows() ) {
2125 $status->successCount++;
2126 } else {
2127 $status->failCount++;
2128 $status->fatal( 'imageinvalidfilename' );
2129 return $status;
2130 }
2131
2132 // Update old images
2133 $dbw->update(
2134 'oldimage',
2135 array(
2136 'oi_name' => $this->newName,
2137 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2138 ),
2139 array( 'oi_name' => $this->oldName ),
2140 __METHOD__
2141 );
2142
2143 $affected = $dbw->affectedRows();
2144 $total = $this->oldCount;
2145 $status->successCount += $affected;
2146 $status->failCount += $total - $affected;
2147 if ( $status->failCount ) {
2148 $status->error( 'imageinvalidfilename' );
2149 }
2150
2151 return $status;
2152 }
2153
2154 /**
2155 * Generate triplets for FSRepo::storeBatch().
2156 */
2157 function getMoveTriplets() {
2158 $moves = array_merge( array( $this->cur ), $this->olds );
2159 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2160
2161 foreach ( $moves as $move ) {
2162 // $move: (oldRelativePath, newRelativePath)
2163 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2164 $triplets[] = array( $srcUrl, 'public', $move[1] );
2165 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2166 }
2167
2168 return $triplets;
2169 }
2170
2171 /**
2172 * Removes non-existent files from move batch.
2173 */
2174 function removeNonexistentFiles( $triplets ) {
2175 $files = array();
2176
2177 foreach ( $triplets as $file ) {
2178 $files[$file[0]] = $file[0];
2179 }
2180
2181 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
2182 $filteredTriplets = array();
2183
2184 foreach ( $triplets as $file ) {
2185 if ( $result[$file[0]] ) {
2186 $filteredTriplets[] = $file;
2187 } else {
2188 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2189 }
2190 }
2191
2192 return $filteredTriplets;
2193 }
2194
2195 /**
2196 * Cleanup a partially moved array of triplets by deleting the target
2197 * files. Called if something went wrong half way.
2198 */
2199 function cleanupTarget( $triplets ) {
2200 // Create dest pairs from the triplets
2201 $pairs = array();
2202 foreach ( $triplets as $triplet ) {
2203 $pairs[] = array( $triplet[1], $triplet[2] );
2204 }
2205
2206 $this->file->repo->cleanupBatch( $pairs );
2207 }
2208
2209 /**
2210 * Cleanup a fully moved array of triplets by deleting the source files.
2211 * Called at the end of the move process if everything else went ok.
2212 */
2213 function cleanupSource( $triplets ) {
2214 // Create source file names from the triplets
2215 $files = array();
2216 foreach ( $triplets as $triplet ) {
2217 $files[] = $triplet[0];
2218 }
2219
2220 $this->file->repo->cleanupBatch( $files );
2221 }
2222 }