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