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