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