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