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