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