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