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