Force LocalFile::purgeMetadataCache use the master DB
[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( File::READ_LATEST );
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(
1788 'page_namespace' => $this->title->getNamespace(),
1789 'page_title' => $this->title->getDBkey()
1790 );
1791 $touched = $this->repo->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
1792 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
1793 }
1794
1795 return $this->descriptionTouched;
1796 }
1797
1798 /**
1799 * @return string
1800 */
1801 function getSha1() {
1802 $this->load();
1803 // Initialise now if necessary
1804 if ( $this->sha1 == '' && $this->fileExists ) {
1805 $this->lock(); // begin
1806
1807 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
1808 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1809 $dbw = $this->repo->getMasterDB();
1810 $dbw->update( 'image',
1811 array( 'img_sha1' => $this->sha1 ),
1812 array( 'img_name' => $this->getName() ),
1813 __METHOD__ );
1814 $this->saveToCache();
1815 }
1816
1817 $this->unlock(); // done
1818 }
1819
1820 return $this->sha1;
1821 }
1822
1823 /**
1824 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1825 */
1826 function isCacheable() {
1827 $this->load();
1828
1829 // If extra data (metadata) was not loaded then it must have been large
1830 return $this->extraDataLoaded
1831 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
1832 }
1833
1834 /**
1835 * Start a transaction and lock the image for update
1836 * Increments a reference counter if the lock is already held
1837 * @throws MWException Throws an error if the lock was not acquired
1838 * @return bool Whether the file lock owns/spawned the DB transaction
1839 */
1840 function lock() {
1841 $dbw = $this->repo->getMasterDB();
1842
1843 if ( !$this->locked ) {
1844 if ( !$dbw->trxLevel() ) {
1845 $dbw->begin( __METHOD__ );
1846 $this->lockedOwnTrx = true;
1847 }
1848 $this->locked++;
1849 // Bug 54736: use simple lock to handle when the file does not exist.
1850 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1851 // Also, that would cause contention on INSERT of similarly named rows.
1852 $backend = $this->getRepo()->getBackend();
1853 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1854 $status = $backend->lockFiles( $lockPaths, LockManager::LOCK_EX, 5 );
1855 if ( !$status->isGood() ) {
1856 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1857 }
1858 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1859 $backend->unlockFiles( $lockPaths, LockManager::LOCK_EX ); // release on commit
1860 } );
1861 }
1862
1863 return $this->lockedOwnTrx;
1864 }
1865
1866 /**
1867 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1868 * the transaction and thereby releases the image lock.
1869 */
1870 function unlock() {
1871 if ( $this->locked ) {
1872 --$this->locked;
1873 if ( !$this->locked && $this->lockedOwnTrx ) {
1874 $dbw = $this->repo->getMasterDB();
1875 $dbw->commit( __METHOD__ );
1876 $this->lockedOwnTrx = false;
1877 }
1878 }
1879 }
1880
1881 /**
1882 * Roll back the DB transaction and mark the image unlocked
1883 */
1884 function unlockAndRollback() {
1885 $this->locked = false;
1886 $dbw = $this->repo->getMasterDB();
1887 $dbw->rollback( __METHOD__ );
1888 $this->lockedOwnTrx = false;
1889 }
1890
1891 /**
1892 * @return Status
1893 */
1894 protected function readOnlyFatalStatus() {
1895 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1896 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1897 }
1898
1899 /**
1900 * Clean up any dangling locks
1901 */
1902 function __destruct() {
1903 $this->unlock();
1904 }
1905 } // LocalFile class
1906
1907 # ------------------------------------------------------------------------------
1908
1909 /**
1910 * Helper class for file deletion
1911 * @ingroup FileAbstraction
1912 */
1913 class LocalFileDeleteBatch {
1914 /** @var LocalFile */
1915 private $file;
1916
1917 /** @var string */
1918 private $reason;
1919
1920 /** @var array */
1921 private $srcRels = array();
1922
1923 /** @var array */
1924 private $archiveUrls = array();
1925
1926 /** @var array Items to be processed in the deletion batch */
1927 private $deletionBatch;
1928
1929 /** @var bool Whether to suppress all suppressable fields when deleting */
1930 private $suppress;
1931
1932 /** @var FileRepoStatus */
1933 private $status;
1934
1935 /** @var User */
1936 private $user;
1937
1938 /**
1939 * @param File $file
1940 * @param string $reason
1941 * @param bool $suppress
1942 * @param User|null $user
1943 */
1944 function __construct( File $file, $reason = '', $suppress = false, $user = null ) {
1945 $this->file = $file;
1946 $this->reason = $reason;
1947 $this->suppress = $suppress;
1948 if ( $user ) {
1949 $this->user = $user;
1950 } else {
1951 global $wgUser;
1952 $this->user = $wgUser;
1953 }
1954 $this->status = $file->repo->newGood();
1955 }
1956
1957 function addCurrent() {
1958 $this->srcRels['.'] = $this->file->getRel();
1959 }
1960
1961 /**
1962 * @param string $oldName
1963 */
1964 function addOld( $oldName ) {
1965 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1966 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1967 }
1968
1969 /**
1970 * Add the old versions of the image to the batch
1971 * @return array List of archive names from old versions
1972 */
1973 function addOlds() {
1974 $archiveNames = array();
1975
1976 $dbw = $this->file->repo->getMasterDB();
1977 $result = $dbw->select( 'oldimage',
1978 array( 'oi_archive_name' ),
1979 array( 'oi_name' => $this->file->getName() ),
1980 __METHOD__
1981 );
1982
1983 foreach ( $result as $row ) {
1984 $this->addOld( $row->oi_archive_name );
1985 $archiveNames[] = $row->oi_archive_name;
1986 }
1987
1988 return $archiveNames;
1989 }
1990
1991 /**
1992 * @return array
1993 */
1994 function getOldRels() {
1995 if ( !isset( $this->srcRels['.'] ) ) {
1996 $oldRels =& $this->srcRels;
1997 $deleteCurrent = false;
1998 } else {
1999 $oldRels = $this->srcRels;
2000 unset( $oldRels['.'] );
2001 $deleteCurrent = true;
2002 }
2003
2004 return array( $oldRels, $deleteCurrent );
2005 }
2006
2007 /**
2008 * @return array
2009 */
2010 protected function getHashes() {
2011 $hashes = array();
2012 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2013
2014 if ( $deleteCurrent ) {
2015 $hashes['.'] = $this->file->getSha1();
2016 }
2017
2018 if ( count( $oldRels ) ) {
2019 $dbw = $this->file->repo->getMasterDB();
2020 $res = $dbw->select(
2021 'oldimage',
2022 array( 'oi_archive_name', 'oi_sha1' ),
2023 array( 'oi_archive_name' => array_keys( $oldRels ),
2024 'oi_name' => $this->file->getName() ), // performance
2025 __METHOD__
2026 );
2027
2028 foreach ( $res as $row ) {
2029 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
2030 // Get the hash from the file
2031 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2032 $props = $this->file->repo->getFileProps( $oldUrl );
2033
2034 if ( $props['fileExists'] ) {
2035 // Upgrade the oldimage row
2036 $dbw->update( 'oldimage',
2037 array( 'oi_sha1' => $props['sha1'] ),
2038 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
2039 __METHOD__ );
2040 $hashes[$row->oi_archive_name] = $props['sha1'];
2041 } else {
2042 $hashes[$row->oi_archive_name] = false;
2043 }
2044 } else {
2045 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2046 }
2047 }
2048 }
2049
2050 $missing = array_diff_key( $this->srcRels, $hashes );
2051
2052 foreach ( $missing as $name => $rel ) {
2053 $this->status->error( 'filedelete-old-unregistered', $name );
2054 }
2055
2056 foreach ( $hashes as $name => $hash ) {
2057 if ( !$hash ) {
2058 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2059 unset( $hashes[$name] );
2060 }
2061 }
2062
2063 return $hashes;
2064 }
2065
2066 function doDBInserts() {
2067 $dbw = $this->file->repo->getMasterDB();
2068 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2069 $encUserId = $dbw->addQuotes( $this->user->getId() );
2070 $encReason = $dbw->addQuotes( $this->reason );
2071 $encGroup = $dbw->addQuotes( 'deleted' );
2072 $ext = $this->file->getExtension();
2073 $dotExt = $ext === '' ? '' : ".$ext";
2074 $encExt = $dbw->addQuotes( $dotExt );
2075 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2076
2077 // Bitfields to further suppress the content
2078 if ( $this->suppress ) {
2079 $bitfield = 0;
2080 // This should be 15...
2081 $bitfield |= Revision::DELETED_TEXT;
2082 $bitfield |= Revision::DELETED_COMMENT;
2083 $bitfield |= Revision::DELETED_USER;
2084 $bitfield |= Revision::DELETED_RESTRICTED;
2085 } else {
2086 $bitfield = 'oi_deleted';
2087 }
2088
2089 if ( $deleteCurrent ) {
2090 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2091 $where = array( 'img_name' => $this->file->getName() );
2092 $dbw->insertSelect( 'filearchive', 'image',
2093 array(
2094 'fa_storage_group' => $encGroup,
2095 'fa_storage_key' => $dbw->conditional(
2096 array( 'img_sha1' => '' ),
2097 $dbw->addQuotes( '' ),
2098 $concat
2099 ),
2100 'fa_deleted_user' => $encUserId,
2101 'fa_deleted_timestamp' => $encTimestamp,
2102 'fa_deleted_reason' => $encReason,
2103 'fa_deleted' => $this->suppress ? $bitfield : 0,
2104
2105 'fa_name' => 'img_name',
2106 'fa_archive_name' => 'NULL',
2107 'fa_size' => 'img_size',
2108 'fa_width' => 'img_width',
2109 'fa_height' => 'img_height',
2110 'fa_metadata' => 'img_metadata',
2111 'fa_bits' => 'img_bits',
2112 'fa_media_type' => 'img_media_type',
2113 'fa_major_mime' => 'img_major_mime',
2114 'fa_minor_mime' => 'img_minor_mime',
2115 'fa_description' => 'img_description',
2116 'fa_user' => 'img_user',
2117 'fa_user_text' => 'img_user_text',
2118 'fa_timestamp' => 'img_timestamp',
2119 'fa_sha1' => 'img_sha1',
2120 ), $where, __METHOD__ );
2121 }
2122
2123 if ( count( $oldRels ) ) {
2124 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2125 $where = array(
2126 'oi_name' => $this->file->getName(),
2127 'oi_archive_name' => array_keys( $oldRels ) );
2128 $dbw->insertSelect( 'filearchive', 'oldimage',
2129 array(
2130 'fa_storage_group' => $encGroup,
2131 'fa_storage_key' => $dbw->conditional(
2132 array( 'oi_sha1' => '' ),
2133 $dbw->addQuotes( '' ),
2134 $concat
2135 ),
2136 'fa_deleted_user' => $encUserId,
2137 'fa_deleted_timestamp' => $encTimestamp,
2138 'fa_deleted_reason' => $encReason,
2139 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
2140
2141 'fa_name' => 'oi_name',
2142 'fa_archive_name' => 'oi_archive_name',
2143 'fa_size' => 'oi_size',
2144 'fa_width' => 'oi_width',
2145 'fa_height' => 'oi_height',
2146 'fa_metadata' => 'oi_metadata',
2147 'fa_bits' => 'oi_bits',
2148 'fa_media_type' => 'oi_media_type',
2149 'fa_major_mime' => 'oi_major_mime',
2150 'fa_minor_mime' => 'oi_minor_mime',
2151 'fa_description' => 'oi_description',
2152 'fa_user' => 'oi_user',
2153 'fa_user_text' => 'oi_user_text',
2154 'fa_timestamp' => 'oi_timestamp',
2155 'fa_sha1' => 'oi_sha1',
2156 ), $where, __METHOD__ );
2157 }
2158 }
2159
2160 function doDBDeletes() {
2161 $dbw = $this->file->repo->getMasterDB();
2162 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2163
2164 if ( count( $oldRels ) ) {
2165 $dbw->delete( 'oldimage',
2166 array(
2167 'oi_name' => $this->file->getName(),
2168 'oi_archive_name' => array_keys( $oldRels )
2169 ), __METHOD__ );
2170 }
2171
2172 if ( $deleteCurrent ) {
2173 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
2174 }
2175 }
2176
2177 /**
2178 * Run the transaction
2179 * @return FileRepoStatus
2180 */
2181 function execute() {
2182
2183 $this->file->lock();
2184
2185 // Prepare deletion batch
2186 $hashes = $this->getHashes();
2187 $this->deletionBatch = array();
2188 $ext = $this->file->getExtension();
2189 $dotExt = $ext === '' ? '' : ".$ext";
2190
2191 foreach ( $this->srcRels as $name => $srcRel ) {
2192 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2193 if ( isset( $hashes[$name] ) ) {
2194 $hash = $hashes[$name];
2195 $key = $hash . $dotExt;
2196 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
2197 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
2198 }
2199 }
2200
2201 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2202 // We acquire this lock by running the inserts now, before the file operations.
2203 //
2204 // This potentially has poor lock contention characteristics -- an alternative
2205 // scheme would be to insert stub filearchive entries with no fa_name and commit
2206 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2207 $this->doDBInserts();
2208
2209 // Removes non-existent file from the batch, so we don't get errors.
2210 // This also handles files in the 'deleted' zone deleted via revision deletion.
2211 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch );
2212 if ( !$checkStatus->isGood() ) {
2213 $this->status->merge( $checkStatus );
2214 return $this->status;
2215 }
2216 $this->deletionBatch = $checkStatus->value;
2217
2218 // Execute the file deletion batch
2219 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2220
2221 if ( !$status->isGood() ) {
2222 $this->status->merge( $status );
2223 }
2224
2225 if ( !$this->status->isOK() ) {
2226 // Critical file deletion error
2227 // Roll back inserts, release lock and abort
2228 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2229 $this->file->unlockAndRollback();
2230
2231 return $this->status;
2232 }
2233
2234 // Delete image/oldimage rows
2235 $this->doDBDeletes();
2236
2237 // Commit and return
2238 $this->file->unlock();
2239
2240 return $this->status;
2241 }
2242
2243 /**
2244 * Removes non-existent files from a deletion batch.
2245 * @param array $batch
2246 * @return Status
2247 */
2248 function removeNonexistentFiles( $batch ) {
2249 $files = $newBatch = array();
2250
2251 foreach ( $batch as $batchItem ) {
2252 list( $src, ) = $batchItem;
2253 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2254 }
2255
2256 $result = $this->file->repo->fileExistsBatch( $files );
2257 if ( in_array( null, $result, true ) ) {
2258 return Status::newFatal( 'backend-fail-internal',
2259 $this->file->repo->getBackend()->getName() );
2260 }
2261
2262 foreach ( $batch as $batchItem ) {
2263 if ( $result[$batchItem[0]] ) {
2264 $newBatch[] = $batchItem;
2265 }
2266 }
2267
2268 return Status::newGood( $newBatch );
2269 }
2270 }
2271
2272 # ------------------------------------------------------------------------------
2273
2274 /**
2275 * Helper class for file undeletion
2276 * @ingroup FileAbstraction
2277 */
2278 class LocalFileRestoreBatch {
2279 /** @var LocalFile */
2280 private $file;
2281
2282 /** @var array List of file IDs to restore */
2283 private $cleanupBatch;
2284
2285 /** @var array List of file IDs to restore */
2286 private $ids;
2287
2288 /** @var bool Add all revisions of the file */
2289 private $all;
2290
2291 /** @var bool Whether to remove all settings for suppressed fields */
2292 private $unsuppress = false;
2293
2294 /**
2295 * @param File $file
2296 * @param bool $unsuppress
2297 */
2298 function __construct( File $file, $unsuppress = false ) {
2299 $this->file = $file;
2300 $this->cleanupBatch = $this->ids = array();
2301 $this->ids = array();
2302 $this->unsuppress = $unsuppress;
2303 }
2304
2305 /**
2306 * Add a file by ID
2307 * @param int $fa_id
2308 */
2309 function addId( $fa_id ) {
2310 $this->ids[] = $fa_id;
2311 }
2312
2313 /**
2314 * Add a whole lot of files by ID
2315 * @param int[] $ids
2316 */
2317 function addIds( $ids ) {
2318 $this->ids = array_merge( $this->ids, $ids );
2319 }
2320
2321 /**
2322 * Add all revisions of the file
2323 */
2324 function addAll() {
2325 $this->all = true;
2326 }
2327
2328 /**
2329 * Run the transaction, except the cleanup batch.
2330 * The cleanup batch should be run in a separate transaction, because it locks different
2331 * rows and there's no need to keep the image row locked while it's acquiring those locks
2332 * The caller may have its own transaction open.
2333 * So we save the batch and let the caller call cleanup()
2334 * @return FileRepoStatus
2335 */
2336 function execute() {
2337 global $wgLang;
2338
2339 if ( !$this->all && !$this->ids ) {
2340 // Do nothing
2341 return $this->file->repo->newGood();
2342 }
2343
2344 $lockOwnsTrx = $this->file->lock();
2345
2346 $dbw = $this->file->repo->getMasterDB();
2347 $status = $this->file->repo->newGood();
2348
2349 $exists = (bool)$dbw->selectField( 'image', '1',
2350 array( 'img_name' => $this->file->getName() ),
2351 __METHOD__,
2352 // The lock() should already prevents changes, but this still may need
2353 // to bypass any transaction snapshot. However, if lock() started the
2354 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2355 $lockOwnsTrx ? array() : array( 'LOCK IN SHARE MODE' )
2356 );
2357
2358 // Fetch all or selected archived revisions for the file,
2359 // sorted from the most recent to the oldest.
2360 $conditions = array( 'fa_name' => $this->file->getName() );
2361
2362 if ( !$this->all ) {
2363 $conditions['fa_id'] = $this->ids;
2364 }
2365
2366 $result = $dbw->select(
2367 'filearchive',
2368 ArchivedFile::selectFields(),
2369 $conditions,
2370 __METHOD__,
2371 array( 'ORDER BY' => 'fa_timestamp DESC' )
2372 );
2373
2374 $idsPresent = array();
2375 $storeBatch = array();
2376 $insertBatch = array();
2377 $insertCurrent = false;
2378 $deleteIds = array();
2379 $first = true;
2380 $archiveNames = array();
2381
2382 foreach ( $result as $row ) {
2383 $idsPresent[] = $row->fa_id;
2384
2385 if ( $row->fa_name != $this->file->getName() ) {
2386 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2387 $status->failCount++;
2388 continue;
2389 }
2390
2391 if ( $row->fa_storage_key == '' ) {
2392 // Revision was missing pre-deletion
2393 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2394 $status->failCount++;
2395 continue;
2396 }
2397
2398 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) .
2399 $row->fa_storage_key;
2400 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2401
2402 if ( isset( $row->fa_sha1 ) ) {
2403 $sha1 = $row->fa_sha1;
2404 } else {
2405 // old row, populate from key
2406 $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2407 }
2408
2409 # Fix leading zero
2410 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2411 $sha1 = substr( $sha1, 1 );
2412 }
2413
2414 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2415 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2416 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2417 || is_null( $row->fa_metadata )
2418 ) {
2419 // Refresh our metadata
2420 // Required for a new current revision; nice for older ones too. :)
2421 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2422 } else {
2423 $props = array(
2424 'minor_mime' => $row->fa_minor_mime,
2425 'major_mime' => $row->fa_major_mime,
2426 'media_type' => $row->fa_media_type,
2427 'metadata' => $row->fa_metadata
2428 );
2429 }
2430
2431 if ( $first && !$exists ) {
2432 // This revision will be published as the new current version
2433 $destRel = $this->file->getRel();
2434 $insertCurrent = array(
2435 'img_name' => $row->fa_name,
2436 'img_size' => $row->fa_size,
2437 'img_width' => $row->fa_width,
2438 'img_height' => $row->fa_height,
2439 'img_metadata' => $props['metadata'],
2440 'img_bits' => $row->fa_bits,
2441 'img_media_type' => $props['media_type'],
2442 'img_major_mime' => $props['major_mime'],
2443 'img_minor_mime' => $props['minor_mime'],
2444 'img_description' => $row->fa_description,
2445 'img_user' => $row->fa_user,
2446 'img_user_text' => $row->fa_user_text,
2447 'img_timestamp' => $row->fa_timestamp,
2448 'img_sha1' => $sha1
2449 );
2450
2451 // The live (current) version cannot be hidden!
2452 if ( !$this->unsuppress && $row->fa_deleted ) {
2453 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2454 $this->cleanupBatch[] = $row->fa_storage_key;
2455 }
2456 } else {
2457 $archiveName = $row->fa_archive_name;
2458
2459 if ( $archiveName == '' ) {
2460 // This was originally a current version; we
2461 // have to devise a new archive name for it.
2462 // Format is <timestamp of archiving>!<name>
2463 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2464
2465 do {
2466 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2467 $timestamp++;
2468 } while ( isset( $archiveNames[$archiveName] ) );
2469 }
2470
2471 $archiveNames[$archiveName] = true;
2472 $destRel = $this->file->getArchiveRel( $archiveName );
2473 $insertBatch[] = array(
2474 'oi_name' => $row->fa_name,
2475 'oi_archive_name' => $archiveName,
2476 'oi_size' => $row->fa_size,
2477 'oi_width' => $row->fa_width,
2478 'oi_height' => $row->fa_height,
2479 'oi_bits' => $row->fa_bits,
2480 'oi_description' => $row->fa_description,
2481 'oi_user' => $row->fa_user,
2482 'oi_user_text' => $row->fa_user_text,
2483 'oi_timestamp' => $row->fa_timestamp,
2484 'oi_metadata' => $props['metadata'],
2485 'oi_media_type' => $props['media_type'],
2486 'oi_major_mime' => $props['major_mime'],
2487 'oi_minor_mime' => $props['minor_mime'],
2488 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2489 'oi_sha1' => $sha1 );
2490 }
2491
2492 $deleteIds[] = $row->fa_id;
2493
2494 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2495 // private files can stay where they are
2496 $status->successCount++;
2497 } else {
2498 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2499 $this->cleanupBatch[] = $row->fa_storage_key;
2500 }
2501
2502 $first = false;
2503 }
2504
2505 unset( $result );
2506
2507 // Add a warning to the status object for missing IDs
2508 $missingIds = array_diff( $this->ids, $idsPresent );
2509
2510 foreach ( $missingIds as $id ) {
2511 $status->error( 'undelete-missing-filearchive', $id );
2512 }
2513
2514 // Remove missing files from batch, so we don't get errors when undeleting them
2515 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2516 if ( !$checkStatus->isGood() ) {
2517 $status->merge( $checkStatus );
2518 return $status;
2519 }
2520 $storeBatch = $checkStatus->value;
2521
2522 // Run the store batch
2523 // Use the OVERWRITE_SAME flag to smooth over a common error
2524 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2525 $status->merge( $storeStatus );
2526
2527 if ( !$status->isGood() ) {
2528 // Even if some files could be copied, fail entirely as that is the
2529 // easiest thing to do without data loss
2530 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2531 $status->ok = false;
2532 $this->file->unlock();
2533
2534 return $status;
2535 }
2536
2537 // Run the DB updates
2538 // Because we have locked the image row, key conflicts should be rare.
2539 // If they do occur, we can roll back the transaction at this time with
2540 // no data loss, but leaving unregistered files scattered throughout the
2541 // public zone.
2542 // This is not ideal, which is why it's important to lock the image row.
2543 if ( $insertCurrent ) {
2544 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2545 }
2546
2547 if ( $insertBatch ) {
2548 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2549 }
2550
2551 if ( $deleteIds ) {
2552 $dbw->delete( 'filearchive',
2553 array( 'fa_id' => $deleteIds ),
2554 __METHOD__ );
2555 }
2556
2557 // If store batch is empty (all files are missing), deletion is to be considered successful
2558 if ( $status->successCount > 0 || !$storeBatch ) {
2559 if ( !$exists ) {
2560 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2561
2562 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
2563
2564 $this->file->purgeEverything();
2565 } else {
2566 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2567 $this->file->purgeDescription();
2568 $this->file->purgeHistory();
2569 }
2570 }
2571
2572 $this->file->unlock();
2573
2574 return $status;
2575 }
2576
2577 /**
2578 * Removes non-existent files from a store batch.
2579 * @param array $triplets
2580 * @return Status
2581 */
2582 function removeNonexistentFiles( $triplets ) {
2583 $files = $filteredTriplets = array();
2584 foreach ( $triplets as $file ) {
2585 $files[$file[0]] = $file[0];
2586 }
2587
2588 $result = $this->file->repo->fileExistsBatch( $files );
2589 if ( in_array( null, $result, true ) ) {
2590 return Status::newFatal( 'backend-fail-internal',
2591 $this->file->repo->getBackend()->getName() );
2592 }
2593
2594 foreach ( $triplets as $file ) {
2595 if ( $result[$file[0]] ) {
2596 $filteredTriplets[] = $file;
2597 }
2598 }
2599
2600 return Status::newGood( $filteredTriplets );
2601 }
2602
2603 /**
2604 * Removes non-existent files from a cleanup batch.
2605 * @param array $batch
2606 * @return array
2607 */
2608 function removeNonexistentFromCleanup( $batch ) {
2609 $files = $newBatch = array();
2610 $repo = $this->file->repo;
2611
2612 foreach ( $batch as $file ) {
2613 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2614 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2615 }
2616
2617 $result = $repo->fileExistsBatch( $files );
2618
2619 foreach ( $batch as $file ) {
2620 if ( $result[$file] ) {
2621 $newBatch[] = $file;
2622 }
2623 }
2624
2625 return $newBatch;
2626 }
2627
2628 /**
2629 * Delete unused files in the deleted zone.
2630 * This should be called from outside the transaction in which execute() was called.
2631 * @return FileRepoStatus
2632 */
2633 function cleanup() {
2634 if ( !$this->cleanupBatch ) {
2635 return $this->file->repo->newGood();
2636 }
2637
2638 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2639
2640 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2641
2642 return $status;
2643 }
2644
2645 /**
2646 * Cleanup a failed batch. The batch was only partially successful, so
2647 * rollback by removing all items that were succesfully copied.
2648 *
2649 * @param Status $storeStatus
2650 * @param array $storeBatch
2651 */
2652 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2653 $cleanupBatch = array();
2654
2655 foreach ( $storeStatus->success as $i => $success ) {
2656 // Check if this item of the batch was successfully copied
2657 if ( $success ) {
2658 // Item was successfully copied and needs to be removed again
2659 // Extract ($dstZone, $dstRel) from the batch
2660 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2661 }
2662 }
2663 $this->file->repo->cleanupBatch( $cleanupBatch );
2664 }
2665 }
2666
2667 # ------------------------------------------------------------------------------
2668
2669 /**
2670 * Helper class for file movement
2671 * @ingroup FileAbstraction
2672 */
2673 class LocalFileMoveBatch {
2674 /** @var LocalFile */
2675 protected $file;
2676
2677 /** @var Title */
2678 protected $target;
2679
2680 protected $cur;
2681
2682 protected $olds;
2683
2684 protected $oldCount;
2685
2686 protected $archive;
2687
2688 /** @var DatabaseBase */
2689 protected $db;
2690
2691 /**
2692 * @param File $file
2693 * @param Title $target
2694 */
2695 function __construct( File $file, Title $target ) {
2696 $this->file = $file;
2697 $this->target = $target;
2698 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2699 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2700 $this->oldName = $this->file->getName();
2701 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2702 $this->oldRel = $this->oldHash . $this->oldName;
2703 $this->newRel = $this->newHash . $this->newName;
2704 $this->db = $file->getRepo()->getMasterDb();
2705 }
2706
2707 /**
2708 * Add the current image to the batch
2709 */
2710 function addCurrent() {
2711 $this->cur = array( $this->oldRel, $this->newRel );
2712 }
2713
2714 /**
2715 * Add the old versions of the image to the batch
2716 * @return array List of archive names from old versions
2717 */
2718 function addOlds() {
2719 $archiveBase = 'archive';
2720 $this->olds = array();
2721 $this->oldCount = 0;
2722 $archiveNames = array();
2723
2724 $result = $this->db->select( 'oldimage',
2725 array( 'oi_archive_name', 'oi_deleted' ),
2726 array( 'oi_name' => $this->oldName ),
2727 __METHOD__,
2728 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2729 );
2730
2731 foreach ( $result as $row ) {
2732 $archiveNames[] = $row->oi_archive_name;
2733 $oldName = $row->oi_archive_name;
2734 $bits = explode( '!', $oldName, 2 );
2735
2736 if ( count( $bits ) != 2 ) {
2737 wfDebug( "Old file name missing !: '$oldName' \n" );
2738 continue;
2739 }
2740
2741 list( $timestamp, $filename ) = $bits;
2742
2743 if ( $this->oldName != $filename ) {
2744 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2745 continue;
2746 }
2747
2748 $this->oldCount++;
2749
2750 // Do we want to add those to oldCount?
2751 if ( $row->oi_deleted & File::DELETED_FILE ) {
2752 continue;
2753 }
2754
2755 $this->olds[] = array(
2756 "{$archiveBase}/{$this->oldHash}{$oldName}",
2757 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2758 );
2759 }
2760
2761 return $archiveNames;
2762 }
2763
2764 /**
2765 * Perform the move.
2766 * @return FileRepoStatus
2767 */
2768 function execute() {
2769 $repo = $this->file->repo;
2770 $status = $repo->newGood();
2771
2772 $triplets = $this->getMoveTriplets();
2773 $checkStatus = $this->removeNonexistentFiles( $triplets );
2774 if ( !$checkStatus->isGood() ) {
2775 $status->merge( $checkStatus );
2776 return $status;
2777 }
2778 $triplets = $checkStatus->value;
2779 $destFile = wfLocalFile( $this->target );
2780
2781 $this->file->lock(); // begin
2782 $destFile->lock(); // quickly fail if destination is not available
2783 // Rename the file versions metadata in the DB.
2784 // This implicitly locks the destination file, which avoids race conditions.
2785 // If we moved the files from A -> C before DB updates, another process could
2786 // move files from B -> C at this point, causing storeBatch() to fail and thus
2787 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2788 $statusDb = $this->doDBUpdates();
2789 if ( !$statusDb->isGood() ) {
2790 $destFile->unlock();
2791 $this->file->unlockAndRollback();
2792 $statusDb->ok = false;
2793
2794 return $statusDb;
2795 }
2796 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2797 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2798
2799 // Copy the files into their new location.
2800 // If a prior process fataled copying or cleaning up files we tolerate any
2801 // of the existing files if they are identical to the ones being stored.
2802 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
2803 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2804 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2805 if ( !$statusMove->isGood() ) {
2806 // Delete any files copied over (while the destination is still locked)
2807 $this->cleanupTarget( $triplets );
2808 $destFile->unlock();
2809 $this->file->unlockAndRollback(); // unlocks the destination
2810 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2811 $statusMove->ok = false;
2812
2813 return $statusMove;
2814 }
2815 $destFile->unlock();
2816 $this->file->unlock(); // done
2817
2818 // Everything went ok, remove the source files
2819 $this->cleanupSource( $triplets );
2820
2821 $status->merge( $statusDb );
2822 $status->merge( $statusMove );
2823
2824 return $status;
2825 }
2826
2827 /**
2828 * Do the database updates and return a new FileRepoStatus indicating how
2829 * many rows where updated.
2830 *
2831 * @return FileRepoStatus
2832 */
2833 function doDBUpdates() {
2834 $repo = $this->file->repo;
2835 $status = $repo->newGood();
2836 $dbw = $this->db;
2837
2838 // Update current image
2839 $dbw->update(
2840 'image',
2841 array( 'img_name' => $this->newName ),
2842 array( 'img_name' => $this->oldName ),
2843 __METHOD__
2844 );
2845
2846 if ( $dbw->affectedRows() ) {
2847 $status->successCount++;
2848 } else {
2849 $status->failCount++;
2850 $status->fatal( 'imageinvalidfilename' );
2851
2852 return $status;
2853 }
2854
2855 // Update old images
2856 $dbw->update(
2857 'oldimage',
2858 array(
2859 'oi_name' => $this->newName,
2860 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2861 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2862 ),
2863 array( 'oi_name' => $this->oldName ),
2864 __METHOD__
2865 );
2866
2867 $affected = $dbw->affectedRows();
2868 $total = $this->oldCount;
2869 $status->successCount += $affected;
2870 // Bug 34934: $total is based on files that actually exist.
2871 // There may be more DB rows than such files, in which case $affected
2872 // can be greater than $total. We use max() to avoid negatives here.
2873 $status->failCount += max( 0, $total - $affected );
2874 if ( $status->failCount ) {
2875 $status->error( 'imageinvalidfilename' );
2876 }
2877
2878 return $status;
2879 }
2880
2881 /**
2882 * Generate triplets for FileRepo::storeBatch().
2883 * @return array
2884 */
2885 function getMoveTriplets() {
2886 $moves = array_merge( array( $this->cur ), $this->olds );
2887 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2888
2889 foreach ( $moves as $move ) {
2890 // $move: (oldRelativePath, newRelativePath)
2891 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2892 $triplets[] = array( $srcUrl, 'public', $move[1] );
2893 wfDebugLog(
2894 'imagemove',
2895 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2896 );
2897 }
2898
2899 return $triplets;
2900 }
2901
2902 /**
2903 * Removes non-existent files from move batch.
2904 * @param array $triplets
2905 * @return Status
2906 */
2907 function removeNonexistentFiles( $triplets ) {
2908 $files = array();
2909
2910 foreach ( $triplets as $file ) {
2911 $files[$file[0]] = $file[0];
2912 }
2913
2914 $result = $this->file->repo->fileExistsBatch( $files );
2915 if ( in_array( null, $result, true ) ) {
2916 return Status::newFatal( 'backend-fail-internal',
2917 $this->file->repo->getBackend()->getName() );
2918 }
2919
2920 $filteredTriplets = array();
2921 foreach ( $triplets as $file ) {
2922 if ( $result[$file[0]] ) {
2923 $filteredTriplets[] = $file;
2924 } else {
2925 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2926 }
2927 }
2928
2929 return Status::newGood( $filteredTriplets );
2930 }
2931
2932 /**
2933 * Cleanup a partially moved array of triplets by deleting the target
2934 * files. Called if something went wrong half way.
2935 * @param array $triplets
2936 */
2937 function cleanupTarget( $triplets ) {
2938 // Create dest pairs from the triplets
2939 $pairs = array();
2940 foreach ( $triplets as $triplet ) {
2941 // $triplet: (old source virtual URL, dst zone, dest rel)
2942 $pairs[] = array( $triplet[1], $triplet[2] );
2943 }
2944
2945 $this->file->repo->cleanupBatch( $pairs );
2946 }
2947
2948 /**
2949 * Cleanup a fully moved array of triplets by deleting the source files.
2950 * Called at the end of the move process if everything else went ok.
2951 * @param array $triplets
2952 */
2953 function cleanupSource( $triplets ) {
2954 // Create source file names from the triplets
2955 $files = array();
2956 foreach ( $triplets as $triplet ) {
2957 $files[] = $triplet[0];
2958 }
2959
2960 $this->file->repo->cleanupBatch( $files );
2961 }
2962 }