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