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