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