Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / filerepo / file / LocalFile.php
blob699c9154a2d9bf5c664934c28bdceef5b7100b0a
1 <?php
2 /**
3 * Local file in the wiki's own database.
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.
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.
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
20 * @file
21 * @ingroup FileAbstraction
24 /**
25 * Bump this number when serialized cache records may be incompatible.
27 define( 'MW_FILE_VERSION', 9 );
29 /**
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
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:
39 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
42 * in most cases.
44 * @ingroup FileAbstraction
46 class LocalFile extends File {
47 const CACHE_FIELD_MAX_LEN = 1000;
49 /** @var bool Does the file exist on disk? (loadFromXxx) */
50 protected $fileExists;
52 /** @var int Image width */
53 protected $width;
55 /** @var int Image height */
56 protected $height;
58 /** @var int Returned by getimagesize (loadFromXxx) */
59 protected $bits;
61 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
62 protected $media_type;
64 /** @var string MIME type, determined by MimeMagic::guessMimeType */
65 protected $mime;
67 /** @var int Size in bytes (loadFromXxx) */
68 protected $size;
70 /** @var string Handler-specific metadata */
71 protected $metadata;
73 /** @var string SHA-1 base 36 content hash */
74 protected $sha1;
76 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
77 protected $dataLoaded;
79 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
80 protected $extraDataLoaded;
82 /** @var int Bitfield akin to rev_deleted */
83 protected $deleted;
85 /** @var string */
86 protected $repoClass = 'LocalRepo';
88 /** @var int Number of line to return by nextHistoryLine() (constructor) */
89 private $historyLine;
91 /** @var int Result of the query for the file's history (nextHistoryLine) */
92 private $historyRes;
94 /** @var string Major MIME type */
95 private $major_mime;
97 /** @var string Minor MIME type */
98 private $minor_mime;
100 /** @var string Upload timestamp */
101 private $timestamp;
103 /** @var int User ID of uploader */
104 private $user;
106 /** @var string User name of uploader */
107 private $user_text;
109 /** @var string Description of current revision of the file */
110 private $description;
112 /** @var string TS_MW timestamp of the last change of the file description */
113 private $descriptionTouched;
115 /** @var bool Whether the row was upgraded on load */
116 private $upgraded;
118 /** @var bool True if the image row is locked */
119 private $locked;
121 /** @var bool True if the image row is locked with a lock initiated transaction */
122 private $lockedOwnTrx;
124 /** @var bool True if file is not present in file system. Not to be cached in memcached */
125 private $missing;
127 /** @var int UNIX timestamp of last markVolatile() call */
128 private $lastMarkedVolatile = 0;
130 const LOAD_ALL = 1; // integer; load all the lazy fields too (like metadata)
131 const LOAD_VIA_SLAVE = 2; // integer; use a slave to load the data
133 const VOLATILE_TTL = 300; // integer; seconds
136 * Create a LocalFile from a title
137 * Do not call this except from inside a repo class.
139 * Note: $unused param is only here to avoid an E_STRICT
141 * @param Title $title
142 * @param FileRepo $repo
143 * @param null $unused
145 * @return LocalFile
147 static function newFromTitle( $title, $repo, $unused = null ) {
148 return new self( $title, $repo );
152 * Create a LocalFile from a title
153 * Do not call this except from inside a repo class.
155 * @param stdClass $row
156 * @param FileRepo $repo
158 * @return LocalFile
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 );
165 return $file;
169 * Create a LocalFile from a SHA-1 key
170 * Do not call this except from inside a repo class.
172 * @param string $sha1 Base-36 SHA-1
173 * @param LocalRepo $repo
174 * @param string|bool $timestamp MW_timestamp (optional)
175 * @return bool|LocalFile
177 static function newFromKey( $sha1, $repo, $timestamp = false ) {
178 $dbr = $repo->getSlaveDB();
180 $conds = array( 'img_sha1' => $sha1 );
181 if ( $timestamp ) {
182 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
185 $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
186 if ( $row ) {
187 return self::newFromRow( $row, $repo );
188 } else {
189 return false;
194 * Fields in the image table
195 * @return array
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',
217 * Constructor.
218 * Do not call this except from inside a repo class.
219 * @param Title $title
220 * @param FileRepo $repo
222 function __construct( $title, $repo ) {
223 parent::__construct( $title, $repo );
225 $this->metadata = '';
226 $this->historyLine = 0;
227 $this->historyRes = null;
228 $this->dataLoaded = false;
229 $this->extraDataLoaded = false;
231 $this->assertRepoDefined();
232 $this->assertTitleDefined();
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
240 function getCacheKey() {
241 $hashedName = md5( $this->getName() );
243 return $this->repo->getSharedCacheKey( 'file', $hashedName );
247 * Try to load file metadata from memcached. Returns true on success.
248 * @return bool
250 function loadFromCache() {
251 global $wgMemc;
253 $this->dataLoaded = false;
254 $this->extraDataLoaded = false;
255 $key = $this->getCacheKey();
257 if ( !$key ) {
259 return false;
262 $cachedValues = $wgMemc->get( $key );
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 );
271 $this->dataLoaded = true;
272 $this->extraDataLoaded = true;
273 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
274 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
278 if ( $this->dataLoaded ) {
279 wfIncrStats( 'image_cache_hit' );
280 } else {
281 wfIncrStats( 'image_cache_miss' );
284 return $this->dataLoaded;
288 * Save the file metadata to memcached
290 function saveToCache() {
291 global $wgMemc;
293 $this->load();
294 $key = $this->getCacheKey();
296 if ( !$key ) {
297 return;
300 $fields = $this->getCacheFields( '' );
301 $cache = array( 'version' => MW_FILE_VERSION );
302 $cache['fileExists'] = $this->fileExists;
304 if ( $this->fileExists ) {
305 foreach ( $fields as $field ) {
306 $cache[$field] = $this->$field;
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
319 // Cache presence for 1 week and negatives for 1 day
320 $wgMemc->set( $key, $cache, $this->fileExists ? 86400 * 7 : 86400 );
324 * Load metadata from the file itself
326 function loadFromFile() {
327 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
328 $this->setProps( $props );
332 * @param string $prefix
333 * @return array
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();
341 if ( $prefix == '' ) {
342 return $fields;
345 if ( !isset( $results[$prefix] ) ) {
346 $prefixedFields = array();
347 foreach ( $fields as $field ) {
348 $prefixedFields[] = $prefix . $field;
350 $results[$prefix] = $prefixedFields;
353 return $results[$prefix];
357 * @param string $prefix
358 * @return array
360 function getLazyCacheFields( $prefix = 'img_' ) {
361 static $fields = array( 'metadata' );
362 static $results = array();
364 if ( $prefix == '' ) {
365 return $fields;
368 if ( !isset( $results[$prefix] ) ) {
369 $prefixedFields = array();
370 foreach ( $fields as $field ) {
371 $prefixedFields[] = $prefix . $field;
373 $results[$prefix] = $prefixedFields;
376 return $results[$prefix];
380 * Load file metadata from the DB
381 * @param int $flags
383 function loadFromDB( $flags = 0 ) {
384 $fname = get_class( $this ) . '::' . __FUNCTION__;
386 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
387 $this->dataLoaded = true;
388 $this->extraDataLoaded = true;
390 $dbr = ( $flags & self::LOAD_VIA_SLAVE )
391 ? $this->repo->getSlaveDB()
392 : $this->repo->getMasterDB();
394 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
395 array( 'img_name' => $this->getName() ), $fname );
397 if ( $row ) {
398 $this->loadFromRow( $row );
399 } else {
400 $this->fileExists = false;
405 * Load lazy file metadata from the DB.
406 * This covers fields that are sometimes not cached.
408 protected function loadExtraFromDB() {
409 $fname = get_class( $this ) . '::' . __FUNCTION__;
411 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
412 $this->extraDataLoaded = true;
414 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo->getSlaveDB(), $fname );
415 if ( !$fieldMap ) {
416 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo->getMasterDB(), $fname );
419 if ( $fieldMap ) {
420 foreach ( $fieldMap as $name => $value ) {
421 $this->$name = $value;
423 } else {
424 throw new MWException( "Could not find data for image '{$this->getName()}'." );
429 * @param DatabaseBase $dbr
430 * @param string $fname
431 * @return array|bool
433 private function loadFieldsWithTimestamp( $dbr, $fname ) {
434 $fieldMap = false;
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_' );
451 return $fieldMap;
455 * @param array $row Row
456 * @param string $prefix
457 * @throws MWException
458 * @return array
460 protected function unprefixRow( $row, $prefix = 'img_' ) {
461 $array = (array)$row;
462 $prefixLength = strlen( $prefix );
464 // Sanity check prefix once
465 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
466 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
469 $decoded = array();
470 foreach ( $array as $name => $value ) {
471 $decoded[substr( $name, $prefixLength )] = $value;
474 return $decoded;
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
485 function decodeRow( $row, $prefix = 'img_' ) {
486 $decoded = $this->unprefixRow( $row, $prefix );
488 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
490 $decoded['metadata'] = $this->repo->getSlaveDB()->decodeBlob( $decoded['metadata'] );
492 if ( empty( $decoded['major_mime'] ) ) {
493 $decoded['mime'] = 'unknown/unknown';
494 } else {
495 if ( !$decoded['minor_mime'] ) {
496 $decoded['minor_mime'] = 'unknown';
498 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
501 # Trim zero padding from char/binary field
502 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
504 return $decoded;
508 * Load file metadata from a DB result row
510 * @param object $row
511 * @param string $prefix
513 function loadFromRow( $row, $prefix = 'img_' ) {
514 $this->dataLoaded = true;
515 $this->extraDataLoaded = true;
517 $array = $this->decodeRow( $row, $prefix );
519 foreach ( $array as $name => $value ) {
520 $this->$name = $value;
523 $this->fileExists = true;
524 $this->maybeUpgradeRow();
528 * Load file metadata from cache or DB, unless already loaded
529 * @param int $flags
531 function load( $flags = 0 ) {
532 if ( !$this->dataLoaded ) {
533 if ( !$this->loadFromCache() ) {
534 $this->loadFromDB( $this->isVolatile() ? 0 : self::LOAD_VIA_SLAVE );
535 $this->saveToCache();
537 $this->dataLoaded = true;
539 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
540 $this->loadExtraFromDB();
545 * Upgrade a row if it needs it
547 function maybeUpgradeRow() {
548 global $wgUpdateCompatibleMetadata;
549 if ( wfReadOnly() ) {
550 return;
553 if ( is_null( $this->media_type ) ||
554 $this->mime == 'image/svg'
556 $this->upgradeRow();
557 $this->upgraded = true;
558 } else {
559 $handler = $this->getHandler();
560 if ( $handler ) {
561 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
562 if ( $validity === MediaHandler::METADATA_BAD
563 || ( $validity === MediaHandler::METADATA_COMPATIBLE && $wgUpdateCompatibleMetadata )
565 $this->upgradeRow();
566 $this->upgraded = true;
572 function getUpgraded() {
573 return $this->upgraded;
577 * Fix assorted version-related problems with the image row by reloading it from the file
579 function upgradeRow() {
581 $this->lock(); // begin
583 $this->loadFromFile();
585 # Don't destroy file info of missing files
586 if ( !$this->fileExists ) {
587 $this->unlock();
588 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
590 return;
593 $dbw = $this->repo->getMasterDB();
594 list( $major, $minor ) = self::splitMime( $this->mime );
596 if ( wfReadOnly() ) {
597 $this->unlock();
599 return;
601 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
603 $dbw->update( 'image',
604 array(
605 'img_size' => $this->size, // sanity
606 'img_width' => $this->width,
607 'img_height' => $this->height,
608 'img_bits' => $this->bits,
609 'img_media_type' => $this->media_type,
610 'img_major_mime' => $major,
611 'img_minor_mime' => $minor,
612 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
613 'img_sha1' => $this->sha1,
615 array( 'img_name' => $this->getName() ),
616 __METHOD__
619 $this->saveToCache();
621 $this->unlock(); // done
626 * Set properties in this object to be equal to those given in the
627 * associative array $info. Only cacheable fields can be set.
628 * All fields *must* be set in $info except for getLazyCacheFields().
630 * If 'mime' is given, it will be split into major_mime/minor_mime.
631 * If major_mime/minor_mime are given, $this->mime will also be set.
633 * @param array $info
635 function setProps( $info ) {
636 $this->dataLoaded = true;
637 $fields = $this->getCacheFields( '' );
638 $fields[] = 'fileExists';
640 foreach ( $fields as $field ) {
641 if ( isset( $info[$field] ) ) {
642 $this->$field = $info[$field];
646 // Fix up mime fields
647 if ( isset( $info['major_mime'] ) ) {
648 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
649 } elseif ( isset( $info['mime'] ) ) {
650 $this->mime = $info['mime'];
651 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
655 /** splitMime inherited */
656 /** getName inherited */
657 /** getTitle inherited */
658 /** getURL inherited */
659 /** getViewURL inherited */
660 /** getPath inherited */
661 /** isVisible inherited */
664 * @return bool
666 function isMissing() {
667 if ( $this->missing === null ) {
668 list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
669 $this->missing = !$fileExists;
672 return $this->missing;
676 * Return the width of the image
678 * @param int $page
679 * @return int
681 public function getWidth( $page = 1 ) {
682 $this->load();
684 if ( $this->isMultipage() ) {
685 $handler = $this->getHandler();
686 if ( !$handler ) {
687 return 0;
689 $dim = $handler->getPageDimensions( $this, $page );
690 if ( $dim ) {
691 return $dim['width'];
692 } else {
693 // For non-paged media, the false goes through an
694 // intval, turning failure into 0, so do same here.
695 return 0;
697 } else {
698 return $this->width;
703 * Return the height of the image
705 * @param int $page
706 * @return int
708 public function getHeight( $page = 1 ) {
709 $this->load();
711 if ( $this->isMultipage() ) {
712 $handler = $this->getHandler();
713 if ( !$handler ) {
714 return 0;
716 $dim = $handler->getPageDimensions( $this, $page );
717 if ( $dim ) {
718 return $dim['height'];
719 } else {
720 // For non-paged media, the false goes through an
721 // intval, turning failure into 0, so do same here.
722 return 0;
724 } else {
725 return $this->height;
730 * Returns ID or name of user who uploaded the file
732 * @param string $type 'text' or 'id'
733 * @return int|string
735 function getUser( $type = 'text' ) {
736 $this->load();
738 if ( $type == 'text' ) {
739 return $this->user_text;
740 } elseif ( $type == 'id' ) {
741 return $this->user;
746 * Get handler-specific metadata
747 * @return string
749 function getMetadata() {
750 $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
751 return $this->metadata;
755 * @return int
757 function getBitDepth() {
758 $this->load();
760 return $this->bits;
764 * Returns the size of the image file, in bytes
765 * @return int
767 public function getSize() {
768 $this->load();
770 return $this->size;
774 * Returns the MIME type of the file.
775 * @return string
777 function getMimeType() {
778 $this->load();
780 return $this->mime;
784 * Returns the type of the media in the file.
785 * Use the value returned by this function with the MEDIATYPE_xxx constants.
786 * @return string
788 function getMediaType() {
789 $this->load();
791 return $this->media_type;
794 /** canRender inherited */
795 /** mustRender inherited */
796 /** allowInlineDisplay inherited */
797 /** isSafeFile inherited */
798 /** isTrustedFile inherited */
801 * Returns true if the file exists on disk.
802 * @return bool Whether file exist on disk.
804 public function exists() {
805 $this->load();
807 return $this->fileExists;
810 /** getTransformScript inherited */
811 /** getUnscaledThumb inherited */
812 /** thumbName inherited */
813 /** createThumb inherited */
814 /** transform inherited */
816 /** getHandler inherited */
817 /** iconThumb inherited */
818 /** getLastError inherited */
821 * Get all thumbnail names previously generated for this file
822 * @param string|bool $archiveName Name of an archive file, default false
823 * @return array First element is the base dir, then files in that base dir.
825 function getThumbnails( $archiveName = false ) {
826 if ( $archiveName ) {
827 $dir = $this->getArchiveThumbPath( $archiveName );
828 } else {
829 $dir = $this->getThumbPath();
832 $backend = $this->repo->getBackend();
833 $files = array( $dir );
834 try {
835 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
836 foreach ( $iterator as $file ) {
837 $files[] = $file;
839 } catch ( FileBackendError $e ) {
840 } // suppress (bug 54674)
842 return $files;
846 * Refresh metadata in memcached, but don't touch thumbnails or squid
848 function purgeMetadataCache() {
849 $this->loadFromDB();
850 $this->saveToCache();
851 $this->purgeHistory();
855 * Purge the shared history (OldLocalFile) cache.
857 * @note This used to purge old thumbnails as well.
859 function purgeHistory() {
860 global $wgMemc;
862 $hashedName = md5( $this->getName() );
863 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
865 if ( $oldKey ) {
866 $wgMemc->delete( $oldKey );
871 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
873 * @param array $options An array potentially with the key forThumbRefresh.
875 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
877 function purgeCache( $options = array() ) {
878 // Refresh metadata cache
879 $this->purgeMetadataCache();
881 // Delete thumbnails
882 $this->purgeThumbnails( $options );
884 // Purge squid cache for this file
885 SquidUpdate::purge( array( $this->getURL() ) );
889 * Delete cached transformed files for an archived version only.
890 * @param string $archiveName Name of the archived file
892 function purgeOldThumbnails( $archiveName ) {
893 global $wgUseSquid;
895 // Get a list of old thumbnails and URLs
896 $files = $this->getThumbnails( $archiveName );
898 // Purge any custom thumbnail caches
899 Hooks::run( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
901 $dir = array_shift( $files );
902 $this->purgeThumbList( $dir, $files );
904 // Purge the squid
905 if ( $wgUseSquid ) {
906 $urls = array();
907 foreach ( $files as $file ) {
908 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
910 SquidUpdate::purge( $urls );
916 * Delete cached transformed files for the current version only.
917 * @param array $options
919 function purgeThumbnails( $options = array() ) {
920 global $wgUseSquid;
922 // Delete thumbnails
923 $files = $this->getThumbnails();
924 // Always purge all files from squid regardless of handler filters
925 $urls = array();
926 if ( $wgUseSquid ) {
927 foreach ( $files as $file ) {
928 $urls[] = $this->getThumbUrl( $file );
930 array_shift( $urls ); // don't purge directory
933 // Give media handler a chance to filter the file purge list
934 if ( !empty( $options['forThumbRefresh'] ) ) {
935 $handler = $this->getHandler();
936 if ( $handler ) {
937 $handler->filterThumbnailPurgeList( $files, $options );
941 // Purge any custom thumbnail caches
942 Hooks::run( 'LocalFilePurgeThumbnails', array( $this, false ) );
944 $dir = array_shift( $files );
945 $this->purgeThumbList( $dir, $files );
947 // Purge the squid
948 if ( $wgUseSquid ) {
949 SquidUpdate::purge( $urls );
955 * Delete a list of thumbnails visible at urls
956 * @param string $dir Base dir of the files.
957 * @param array $files Array of strings: relative filenames (to $dir)
959 protected function purgeThumbList( $dir, $files ) {
960 $fileListDebug = strtr(
961 var_export( $files, true ),
962 array( "\n" => '' )
964 wfDebug( __METHOD__ . ": $fileListDebug\n" );
966 $purgeList = array();
967 foreach ( $files as $file ) {
968 # Check that the base file name is part of the thumb name
969 # This is a basic sanity check to avoid erasing unrelated directories
970 if ( strpos( $file, $this->getName() ) !== false
971 || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
973 $purgeList[] = "{$dir}/{$file}";
977 # Delete the thumbnails
978 $this->repo->quickPurgeBatch( $purgeList );
979 # Clear out the thumbnail directory if empty
980 $this->repo->quickCleanDir( $dir );
983 /** purgeDescription inherited */
984 /** purgeEverything inherited */
987 * @param int $limit Optional: Limit to number of results
988 * @param int $start Optional: Timestamp, start from
989 * @param int $end Optional: Timestamp, end at
990 * @param bool $inc
991 * @return array
993 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
994 $dbr = $this->repo->getSlaveDB();
995 $tables = array( 'oldimage' );
996 $fields = OldLocalFile::selectFields();
997 $conds = $opts = $join_conds = array();
998 $eq = $inc ? '=' : '';
999 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1001 if ( $start ) {
1002 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1005 if ( $end ) {
1006 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1009 if ( $limit ) {
1010 $opts['LIMIT'] = $limit;
1013 // Search backwards for time > x queries
1014 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1015 $opts['ORDER BY'] = "oi_timestamp $order";
1016 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1018 Hooks::run( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1019 &$conds, &$opts, &$join_conds ) );
1021 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1022 $r = array();
1024 foreach ( $res as $row ) {
1025 $r[] = $this->repo->newFileFromRow( $row );
1028 if ( $order == 'ASC' ) {
1029 $r = array_reverse( $r ); // make sure it ends up descending
1032 return $r;
1036 * Returns the history of this file, line by line.
1037 * starts with current version, then old versions.
1038 * uses $this->historyLine to check which line to return:
1039 * 0 return line for current version
1040 * 1 query for old versions, return first one
1041 * 2, ... return next old version from above query
1042 * @return bool
1044 public function nextHistoryLine() {
1045 # Polymorphic function name to distinguish foreign and local fetches
1046 $fname = get_class( $this ) . '::' . __FUNCTION__;
1048 $dbr = $this->repo->getSlaveDB();
1050 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1051 $this->historyRes = $dbr->select( 'image',
1052 array(
1053 '*',
1054 "'' AS oi_archive_name",
1055 '0 as oi_deleted',
1056 'img_sha1'
1058 array( 'img_name' => $this->title->getDBkey() ),
1059 $fname
1062 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1063 $this->historyRes = null;
1065 return false;
1067 } elseif ( $this->historyLine == 1 ) {
1068 $this->historyRes = $dbr->select( 'oldimage', '*',
1069 array( 'oi_name' => $this->title->getDBkey() ),
1070 $fname,
1071 array( 'ORDER BY' => 'oi_timestamp DESC' )
1074 $this->historyLine++;
1076 return $dbr->fetchObject( $this->historyRes );
1080 * Reset the history pointer to the first element of the history
1082 public function resetHistory() {
1083 $this->historyLine = 0;
1085 if ( !is_null( $this->historyRes ) ) {
1086 $this->historyRes = null;
1090 /** getHashPath inherited */
1091 /** getRel inherited */
1092 /** getUrlRel inherited */
1093 /** getArchiveRel inherited */
1094 /** getArchivePath inherited */
1095 /** getThumbPath inherited */
1096 /** getArchiveUrl inherited */
1097 /** getThumbUrl inherited */
1098 /** getArchiveVirtualUrl inherited */
1099 /** getThumbVirtualUrl inherited */
1100 /** isHashed inherited */
1103 * Upload a file and record it in the DB
1104 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1105 * @param string $comment Upload description
1106 * @param string $pageText Text to use for the new description page,
1107 * if a new description page is created
1108 * @param int|bool $flags Flags for publish()
1109 * @param array|bool $props File properties, if known. This can be used to
1110 * reduce the upload time when uploading virtual URLs for which the file
1111 * info is already known
1112 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1113 * current time
1114 * @param User|null $user User object or null to use $wgUser
1116 * @return FileRepoStatus On success, the value member contains the
1117 * archive name, or an empty string if it was a new file.
1119 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1120 $timestamp = false, $user = null
1122 global $wgContLang;
1124 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1125 return $this->readOnlyFatalStatus();
1128 if ( !$props ) {
1129 if ( $this->repo->isVirtualUrl( $srcPath )
1130 || FileBackend::isStoragePath( $srcPath )
1132 $props = $this->repo->getFileProps( $srcPath );
1133 } else {
1134 $props = FSFile::getPropsFromPath( $srcPath );
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();
1146 // Trim spaces on user supplied text
1147 $comment = trim( $comment );
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 );
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 );
1167 $this->unlock(); // done
1169 return $status;
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
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;
1191 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1193 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1194 return false;
1197 if ( $watch ) {
1198 $user->addWatch( $this->getTitle() );
1201 return true;
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
1214 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1215 $user = null
1218 if ( is_null( $user ) ) {
1219 global $wgUser;
1220 $user = $wgUser;
1223 $dbw = $this->repo->getMasterDB();
1224 $dbw->begin( __METHOD__ );
1226 if ( !$props ) {
1227 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
1230 # Imports or such might force a certain timestamp; otherwise we generate
1231 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1232 if ( $timestamp === false ) {
1233 $timestamp = $dbw->timestamp();
1234 $allowTimeKludge = true;
1235 } else {
1236 $allowTimeKludge = false;
1239 $props['description'] = $comment;
1240 $props['user'] = $user->getId();
1241 $props['user_text'] = $user->getName();
1242 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1243 $this->setProps( $props );
1245 # Fail now if the file isn't there
1246 if ( !$this->fileExists ) {
1247 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
1248 $dbw->rollback( __METHOD__ );
1250 return false;
1253 $reupload = false;
1255 # Test to see if the row exists using INSERT IGNORE
1256 # This avoids race conditions by locking the row until the commit, and also
1257 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1258 $dbw->insert( 'image',
1259 array(
1260 'img_name' => $this->getName(),
1261 'img_size' => $this->size,
1262 'img_width' => intval( $this->width ),
1263 'img_height' => intval( $this->height ),
1264 'img_bits' => $this->bits,
1265 'img_media_type' => $this->media_type,
1266 'img_major_mime' => $this->major_mime,
1267 'img_minor_mime' => $this->minor_mime,
1268 'img_timestamp' => $timestamp,
1269 'img_description' => $comment,
1270 'img_user' => $user->getId(),
1271 'img_user_text' => $user->getName(),
1272 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1273 'img_sha1' => $this->sha1
1275 __METHOD__,
1276 'IGNORE'
1278 if ( $dbw->affectedRows() == 0 ) {
1279 if ( $allowTimeKludge ) {
1280 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1281 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1282 array( 'img_name' => $this->getName() ),
1283 __METHOD__,
1284 array( 'LOCK IN SHARE MODE' ) );
1285 $lUnixtime = $ltimestamp ? wfTimestamp( TS_UNIX, $ltimestamp ) : false;
1286 # Avoid a timestamp that is not newer than the last version
1287 # TODO: the image/oldimage tables should be like page/revision with an ID field
1288 if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) {
1289 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1290 $timestamp = $dbw->timestamp( $lUnixtime + 1 );
1291 $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1295 # (bug 34993) Note: $oldver can be empty here, if the previous
1296 # version of the file was broken. Allow registration of the new
1297 # version to continue anyway, because that's better than having
1298 # an image that's not fixable by user operations.
1300 $reupload = true;
1301 # Collision, this is an update of a file
1302 # Insert previous contents into oldimage
1303 $dbw->insertSelect( 'oldimage', 'image',
1304 array(
1305 'oi_name' => 'img_name',
1306 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1307 'oi_size' => 'img_size',
1308 'oi_width' => 'img_width',
1309 'oi_height' => 'img_height',
1310 'oi_bits' => 'img_bits',
1311 'oi_timestamp' => 'img_timestamp',
1312 'oi_description' => 'img_description',
1313 'oi_user' => 'img_user',
1314 'oi_user_text' => 'img_user_text',
1315 'oi_metadata' => 'img_metadata',
1316 'oi_media_type' => 'img_media_type',
1317 'oi_major_mime' => 'img_major_mime',
1318 'oi_minor_mime' => 'img_minor_mime',
1319 'oi_sha1' => 'img_sha1'
1321 array( 'img_name' => $this->getName() ),
1322 __METHOD__
1325 # Update the current image row
1326 $dbw->update( 'image',
1327 array( /* SET */
1328 'img_size' => $this->size,
1329 'img_width' => intval( $this->width ),
1330 'img_height' => intval( $this->height ),
1331 'img_bits' => $this->bits,
1332 'img_media_type' => $this->media_type,
1333 'img_major_mime' => $this->major_mime,
1334 'img_minor_mime' => $this->minor_mime,
1335 'img_timestamp' => $timestamp,
1336 'img_description' => $comment,
1337 'img_user' => $user->getId(),
1338 'img_user_text' => $user->getName(),
1339 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1340 'img_sha1' => $this->sha1
1342 array( 'img_name' => $this->getName() ),
1343 __METHOD__
1345 } else {
1346 # This is a new file, so update the image count
1347 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
1350 $descTitle = $this->getTitle();
1351 $wikiPage = new WikiFilePage( $descTitle );
1352 $wikiPage->setFile( $this );
1354 # Add the log entry
1355 $action = $reupload ? 'overwrite' : 'upload';
1357 $logEntry = new ManualLogEntry( 'upload', $action );
1358 $logEntry->setPerformer( $user );
1359 $logEntry->setComment( $comment );
1360 $logEntry->setTarget( $descTitle );
1362 // Allow people using the api to associate log entries with the upload.
1363 // Log has a timestamp, but sometimes different from upload timestamp.
1364 $logEntry->setParameters(
1365 array(
1366 'img_sha1' => $this->sha1,
1367 'img_timestamp' => $timestamp,
1370 // Note we keep $logId around since during new image
1371 // creation, page doesn't exist yet, so log_page = 0
1372 // but we want it to point to the page we're making,
1373 // so we later modify the log entry.
1374 // For a similar reason, we avoid making an RC entry
1375 // now and wait until the page exists.
1376 $logId = $logEntry->insert();
1378 $exists = $descTitle->exists();
1379 if ( $exists ) {
1380 // Page exists, do RC entry now (otherwise we wait for later).
1381 $logEntry->publish( $logId );
1384 if ( $exists ) {
1385 # Create a null revision
1386 $latest = $descTitle->getLatestRevID();
1387 // Use own context to get the action text in content language
1388 $formatter = LogFormatter::newFromEntry( $logEntry );
1389 $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) );
1390 $editSummary = $formatter->getPlainActionText();
1392 $nullRevision = Revision::newNullRevision(
1393 $dbw,
1394 $descTitle->getArticleID(),
1395 $editSummary,
1396 false,
1397 $user
1399 if ( !is_null( $nullRevision ) ) {
1400 $nullRevision->insertOn( $dbw );
1402 Hooks::run( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1403 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1407 # Commit the transaction now, in case something goes wrong later
1408 # The most important thing is that files don't get lost, especially archives
1409 # NOTE: once we have support for nested transactions, the commit may be moved
1410 # to after $wikiPage->doEdit has been called.
1411 $dbw->commit( __METHOD__ );
1413 # Save to memcache.
1414 # We shall not saveToCache before the commit since otherwise
1415 # in case of a rollback there is an usable file from memcached
1416 # which in fact doesn't really exist (bug 24978)
1417 $this->saveToCache();
1419 if ( $exists ) {
1420 # Invalidate the cache for the description page
1421 $descTitle->invalidateCache();
1422 $descTitle->purgeSquid();
1423 } else {
1424 # New file; create the description page.
1425 # There's already a log entry, so don't make a second RC entry
1426 # Squid and file cache for the description page are purged by doEditContent.
1427 $content = ContentHandler::makeContent( $pageText, $descTitle );
1428 $status = $wikiPage->doEditContent(
1429 $content,
1430 $comment,
1431 EDIT_NEW | EDIT_SUPPRESS_RC,
1432 false,
1433 $user
1436 $dbw->begin( __METHOD__ ); // XXX; doEdit() uses a transaction
1437 // Now that the page exists, make an RC entry.
1438 $logEntry->publish( $logId );
1439 if ( isset( $status->value['revision'] ) ) {
1440 $dbw->update( 'logging',
1441 array( 'log_page' => $status->value['revision']->getPage() ),
1442 array( 'log_id' => $logId ),
1443 __METHOD__
1446 $dbw->commit( __METHOD__ ); // commit before anything bad can happen
1449 if ( $reupload ) {
1450 # Delete old thumbnails
1451 $this->purgeThumbnails();
1453 # Remove the old file from the squid cache
1454 SquidUpdate::purge( array( $this->getURL() ) );
1457 # Hooks, hooks, the magic of hooks...
1458 Hooks::run( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1460 # Invalidate cache for all pages using this file
1461 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1462 $update->doUpdate();
1463 if ( !$reupload ) {
1464 LinksUpdate::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1467 return true;
1471 * Move or copy a file to its public location. If a file exists at the
1472 * destination, move it to an archive. Returns a FileRepoStatus object with
1473 * the archive name in the "value" member on success.
1475 * The archive name should be passed through to recordUpload for database
1476 * registration.
1478 * @param string $srcPath Local filesystem path to the source image
1479 * @param int $flags A bitwise combination of:
1480 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1481 * @param array $options Optional additional parameters
1482 * @return FileRepoStatus On success, the value member contains the
1483 * archive name, or an empty string if it was a new file.
1485 function publish( $srcPath, $flags = 0, array $options = array() ) {
1486 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1490 * Move or copy a file to a specified location. Returns a FileRepoStatus
1491 * object with the archive name in the "value" member on success.
1493 * The archive name should be passed through to recordUpload for database
1494 * registration.
1496 * @param string $srcPath Local filesystem path to the source image
1497 * @param string $dstRel Target relative path
1498 * @param int $flags A bitwise combination of:
1499 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1500 * @param array $options Optional additional parameters
1501 * @return FileRepoStatus On success, the value member contains the
1502 * archive name, or an empty string if it was a new file.
1504 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1505 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1506 return $this->readOnlyFatalStatus();
1509 $this->lock(); // begin
1511 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1512 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1513 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1514 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1516 if ( $status->value == 'new' ) {
1517 $status->value = '';
1518 } else {
1519 $status->value = $archiveName;
1522 $this->unlock(); // done
1524 return $status;
1527 /** getLinksTo inherited */
1528 /** getExifData inherited */
1529 /** isLocal inherited */
1530 /** wasDeleted inherited */
1533 * Move file to the new title
1535 * Move current, old version and all thumbnails
1536 * to the new filename. Old file is deleted.
1538 * Cache purging is done; checks for validity
1539 * and logging are caller's responsibility
1541 * @param Title $target New file name
1542 * @return FileRepoStatus
1544 function move( $target ) {
1545 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1546 return $this->readOnlyFatalStatus();
1549 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1550 $batch = new LocalFileMoveBatch( $this, $target );
1552 $this->lock(); // begin
1553 $batch->addCurrent();
1554 $archiveNames = $batch->addOlds();
1555 $status = $batch->execute();
1556 $this->unlock(); // done
1558 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1560 // Purge the source and target files...
1561 $oldTitleFile = wfLocalFile( $this->title );
1562 $newTitleFile = wfLocalFile( $target );
1563 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1564 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1565 $this->getRepo()->getMasterDB()->onTransactionIdle(
1566 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1567 $oldTitleFile->purgeEverything();
1568 foreach ( $archiveNames as $archiveName ) {
1569 $oldTitleFile->purgeOldThumbnails( $archiveName );
1571 $newTitleFile->purgeEverything();
1575 if ( $status->isOK() ) {
1576 // Now switch the object
1577 $this->title = $target;
1578 // Force regeneration of the name and hashpath
1579 unset( $this->name );
1580 unset( $this->hashPath );
1583 return $status;
1587 * Delete all versions of the file.
1589 * Moves the files into an archive directory (or deletes them)
1590 * and removes the database rows.
1592 * Cache purging is done; logging is caller's responsibility.
1594 * @param string $reason
1595 * @param bool $suppress
1596 * @param User|null $user
1597 * @return FileRepoStatus
1599 function delete( $reason, $suppress = false, $user = null ) {
1600 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1601 return $this->readOnlyFatalStatus();
1604 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1606 $this->lock(); // begin
1607 $batch->addCurrent();
1608 # Get old version relative paths
1609 $archiveNames = $batch->addOlds();
1610 $status = $batch->execute();
1611 $this->unlock(); // done
1613 if ( $status->isOK() ) {
1614 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => -1 ) ) );
1617 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1618 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1619 $file = $this;
1620 $this->getRepo()->getMasterDB()->onTransactionIdle(
1621 function () use ( $file, $archiveNames ) {
1622 global $wgUseSquid;
1624 $file->purgeEverything();
1625 foreach ( $archiveNames as $archiveName ) {
1626 $file->purgeOldThumbnails( $archiveName );
1629 if ( $wgUseSquid ) {
1630 // Purge the squid
1631 $purgeUrls = array();
1632 foreach ( $archiveNames as $archiveName ) {
1633 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1635 SquidUpdate::purge( $purgeUrls );
1640 return $status;
1644 * Delete an old version of the file.
1646 * Moves the file into an archive directory (or deletes it)
1647 * and removes the database row.
1649 * Cache purging is done; logging is caller's responsibility.
1651 * @param string $archiveName
1652 * @param string $reason
1653 * @param bool $suppress
1654 * @param User|null $user
1655 * @throws MWException Exception on database or file store failure
1656 * @return FileRepoStatus
1658 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1659 global $wgUseSquid;
1660 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1661 return $this->readOnlyFatalStatus();
1664 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1666 $this->lock(); // begin
1667 $batch->addOld( $archiveName );
1668 $status = $batch->execute();
1669 $this->unlock(); // done
1671 $this->purgeOldThumbnails( $archiveName );
1672 if ( $status->isOK() ) {
1673 $this->purgeDescription();
1674 $this->purgeHistory();
1677 if ( $wgUseSquid ) {
1678 // Purge the squid
1679 SquidUpdate::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1682 return $status;
1686 * Restore all or specified deleted revisions to the given file.
1687 * Permissions and logging are left to the caller.
1689 * May throw database exceptions on error.
1691 * @param array $versions Set of record ids of deleted items to restore,
1692 * or empty to restore all revisions.
1693 * @param bool $unsuppress
1694 * @return FileRepoStatus
1696 function restore( $versions = array(), $unsuppress = false ) {
1697 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1698 return $this->readOnlyFatalStatus();
1701 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1703 $this->lock(); // begin
1704 if ( !$versions ) {
1705 $batch->addAll();
1706 } else {
1707 $batch->addIds( $versions );
1709 $status = $batch->execute();
1710 if ( $status->isGood() ) {
1711 $cleanupStatus = $batch->cleanup();
1712 $cleanupStatus->successCount = 0;
1713 $cleanupStatus->failCount = 0;
1714 $status->merge( $cleanupStatus );
1716 $this->unlock(); // done
1718 return $status;
1721 /** isMultipage inherited */
1722 /** pageCount inherited */
1723 /** scaleHeight inherited */
1724 /** getImageSize inherited */
1727 * Get the URL of the file description page.
1728 * @return string
1730 function getDescriptionUrl() {
1731 return $this->title->getLocalURL();
1735 * Get the HTML text of the description page
1736 * This is not used by ImagePage for local files, since (among other things)
1737 * it skips the parser cache.
1739 * @param Language $lang What language to get description in (Optional)
1740 * @return bool|mixed
1742 function getDescriptionText( $lang = null ) {
1743 $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
1744 if ( !$revision ) {
1745 return false;
1747 $content = $revision->getContent();
1748 if ( !$content ) {
1749 return false;
1751 $pout = $content->getParserOutput( $this->title, null, new ParserOptions( null, $lang ) );
1753 return $pout->getText();
1757 * @param int $audience
1758 * @param User $user
1759 * @return string
1761 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1762 $this->load();
1763 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
1764 return '';
1765 } elseif ( $audience == self::FOR_THIS_USER
1766 && !$this->userCan( self::DELETED_COMMENT, $user )
1768 return '';
1769 } else {
1770 return $this->description;
1775 * @return bool|string
1777 function getTimestamp() {
1778 $this->load();
1780 return $this->timestamp;
1784 * @return bool|string
1786 public function getDescriptionTouched() {
1787 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1788 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1789 // need to differentiate between null (uninitialized) and false (failed to load).
1790 if ( $this->descriptionTouched === null ) {
1791 $cond = array( 'page_namespace' => $this->title->getNamespace(), 'page_title' => $this->title->getDBkey() );
1792 $touched = $this->repo->getSlaveDB()->selectField( 'page', 'page_touched', $cond, __METHOD__ );
1793 $this->descriptionTouched = $touched ? wfTimestamp( TS_MW, $touched ) : false;
1796 return $this->descriptionTouched;
1800 * @return string
1802 function getSha1() {
1803 $this->load();
1804 // Initialise now if necessary
1805 if ( $this->sha1 == '' && $this->fileExists ) {
1806 $this->lock(); // begin
1808 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
1809 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1810 $dbw = $this->repo->getMasterDB();
1811 $dbw->update( 'image',
1812 array( 'img_sha1' => $this->sha1 ),
1813 array( 'img_name' => $this->getName() ),
1814 __METHOD__ );
1815 $this->saveToCache();
1818 $this->unlock(); // done
1821 return $this->sha1;
1825 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1827 function isCacheable() {
1828 $this->load();
1830 // If extra data (metadata) was not loaded then it must have been large
1831 return $this->extraDataLoaded
1832 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
1836 * Start a transaction and lock the image for update
1837 * Increments a reference counter if the lock is already held
1838 * @throws MWException Throws an error if the lock was not acquired
1839 * @return bool Whether the file lock owns/spawned the DB transaction
1841 function lock() {
1842 $dbw = $this->repo->getMasterDB();
1844 if ( !$this->locked ) {
1845 if ( !$dbw->trxLevel() ) {
1846 $dbw->begin( __METHOD__ );
1847 $this->lockedOwnTrx = true;
1849 $this->locked++;
1850 // Bug 54736: use simple lock to handle when the file does not exist.
1851 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
1852 // Also, that would cause contention on INSERT of similarly named rows.
1853 $backend = $this->getRepo()->getBackend();
1854 $lockPaths = array( $this->getPath() ); // represents all versions of the file
1855 $status = $backend->lockFiles( $lockPaths, LockManager::LOCK_EX, 5 );
1856 if ( !$status->isGood() ) {
1857 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1859 $dbw->onTransactionIdle( function () use ( $backend, $lockPaths ) {
1860 $backend->unlockFiles( $lockPaths, LockManager::LOCK_EX ); // release on commit
1861 } );
1864 $this->markVolatile(); // file may change soon
1866 return $this->lockedOwnTrx;
1870 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1871 * the transaction and thereby releases the image lock.
1873 function unlock() {
1874 if ( $this->locked ) {
1875 --$this->locked;
1876 if ( !$this->locked && $this->lockedOwnTrx ) {
1877 $dbw = $this->repo->getMasterDB();
1878 $dbw->commit( __METHOD__ );
1879 $this->lockedOwnTrx = false;
1885 * Mark a file as about to be changed
1887 * This sets a cache key that alters master/slave DB loading behavior
1889 * @return bool Success
1891 protected function markVolatile() {
1892 global $wgMemc;
1894 $key = $this->repo->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1895 if ( $key ) {
1896 $this->lastMarkedVolatile = time();
1897 return $wgMemc->set( $key, $this->lastMarkedVolatile, self::VOLATILE_TTL );
1900 return true;
1904 * Check if a file is about to be changed or has been changed recently
1906 * @see LocalFile::isVolatile()
1907 * @return bool Whether the file is volatile
1909 protected function isVolatile() {
1910 global $wgMemc;
1912 $key = $this->repo->getSharedCacheKey( 'file-volatile', md5( $this->getName() ) );
1913 if ( !$key ) {
1914 // repo unavailable; bail.
1915 return false;
1918 if ( $this->lastMarkedVolatile === 0 ) {
1919 $this->lastMarkedVolatile = $wgMemc->get( $key ) ?: 0;
1922 $volatileDuration = time() - $this->lastMarkedVolatile;
1923 return $volatileDuration <= self::VOLATILE_TTL;
1927 * Roll back the DB transaction and mark the image unlocked
1929 function unlockAndRollback() {
1930 $this->locked = false;
1931 $dbw = $this->repo->getMasterDB();
1932 $dbw->rollback( __METHOD__ );
1933 $this->lockedOwnTrx = false;
1937 * @return Status
1939 protected function readOnlyFatalStatus() {
1940 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1941 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1945 * Clean up any dangling locks
1947 function __destruct() {
1948 $this->unlock();
1950 } // LocalFile class
1952 # ------------------------------------------------------------------------------
1955 * Helper class for file deletion
1956 * @ingroup FileAbstraction
1958 class LocalFileDeleteBatch {
1959 /** @var LocalFile */
1960 private $file;
1962 /** @var string */
1963 private $reason;
1965 /** @var array */
1966 private $srcRels = array();
1968 /** @var array */
1969 private $archiveUrls = array();
1971 /** @var array Items to be processed in the deletion batch */
1972 private $deletionBatch;
1974 /** @var bool Whether to suppress all suppressable fields when deleting */
1975 private $suppress;
1977 /** @var FileRepoStatus */
1978 private $status;
1980 /** @var User */
1981 private $user;
1984 * @param File $file
1985 * @param string $reason
1986 * @param bool $suppress
1987 * @param User|null $user
1989 function __construct( File $file, $reason = '', $suppress = false, $user = null ) {
1990 $this->file = $file;
1991 $this->reason = $reason;
1992 $this->suppress = $suppress;
1993 if ( $user ) {
1994 $this->user = $user;
1995 } else {
1996 global $wgUser;
1997 $this->user = $wgUser;
1999 $this->status = $file->repo->newGood();
2002 function addCurrent() {
2003 $this->srcRels['.'] = $this->file->getRel();
2007 * @param string $oldName
2009 function addOld( $oldName ) {
2010 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
2011 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
2015 * Add the old versions of the image to the batch
2016 * @return array List of archive names from old versions
2018 function addOlds() {
2019 $archiveNames = array();
2021 $dbw = $this->file->repo->getMasterDB();
2022 $result = $dbw->select( 'oldimage',
2023 array( 'oi_archive_name' ),
2024 array( 'oi_name' => $this->file->getName() ),
2025 __METHOD__
2028 foreach ( $result as $row ) {
2029 $this->addOld( $row->oi_archive_name );
2030 $archiveNames[] = $row->oi_archive_name;
2033 return $archiveNames;
2037 * @return array
2039 function getOldRels() {
2040 if ( !isset( $this->srcRels['.'] ) ) {
2041 $oldRels =& $this->srcRels;
2042 $deleteCurrent = false;
2043 } else {
2044 $oldRels = $this->srcRels;
2045 unset( $oldRels['.'] );
2046 $deleteCurrent = true;
2049 return array( $oldRels, $deleteCurrent );
2053 * @return array
2055 protected function getHashes() {
2056 $hashes = array();
2057 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2059 if ( $deleteCurrent ) {
2060 $hashes['.'] = $this->file->getSha1();
2063 if ( count( $oldRels ) ) {
2064 $dbw = $this->file->repo->getMasterDB();
2065 $res = $dbw->select(
2066 'oldimage',
2067 array( 'oi_archive_name', 'oi_sha1' ),
2068 array( 'oi_archive_name' => array_keys( $oldRels ),
2069 'oi_name' => $this->file->getName() ), // performance
2070 __METHOD__
2073 foreach ( $res as $row ) {
2074 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
2075 // Get the hash from the file
2076 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
2077 $props = $this->file->repo->getFileProps( $oldUrl );
2079 if ( $props['fileExists'] ) {
2080 // Upgrade the oldimage row
2081 $dbw->update( 'oldimage',
2082 array( 'oi_sha1' => $props['sha1'] ),
2083 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
2084 __METHOD__ );
2085 $hashes[$row->oi_archive_name] = $props['sha1'];
2086 } else {
2087 $hashes[$row->oi_archive_name] = false;
2089 } else {
2090 $hashes[$row->oi_archive_name] = $row->oi_sha1;
2095 $missing = array_diff_key( $this->srcRels, $hashes );
2097 foreach ( $missing as $name => $rel ) {
2098 $this->status->error( 'filedelete-old-unregistered', $name );
2101 foreach ( $hashes as $name => $hash ) {
2102 if ( !$hash ) {
2103 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
2104 unset( $hashes[$name] );
2108 return $hashes;
2111 function doDBInserts() {
2112 $dbw = $this->file->repo->getMasterDB();
2113 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
2114 $encUserId = $dbw->addQuotes( $this->user->getId() );
2115 $encReason = $dbw->addQuotes( $this->reason );
2116 $encGroup = $dbw->addQuotes( 'deleted' );
2117 $ext = $this->file->getExtension();
2118 $dotExt = $ext === '' ? '' : ".$ext";
2119 $encExt = $dbw->addQuotes( $dotExt );
2120 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2122 // Bitfields to further suppress the content
2123 if ( $this->suppress ) {
2124 $bitfield = 0;
2125 // This should be 15...
2126 $bitfield |= Revision::DELETED_TEXT;
2127 $bitfield |= Revision::DELETED_COMMENT;
2128 $bitfield |= Revision::DELETED_USER;
2129 $bitfield |= Revision::DELETED_RESTRICTED;
2130 } else {
2131 $bitfield = 'oi_deleted';
2134 if ( $deleteCurrent ) {
2135 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
2136 $where = array( 'img_name' => $this->file->getName() );
2137 $dbw->insertSelect( 'filearchive', 'image',
2138 array(
2139 'fa_storage_group' => $encGroup,
2140 'fa_storage_key' => $dbw->conditional(
2141 array( 'img_sha1' => '' ),
2142 $dbw->addQuotes( '' ),
2143 $concat
2145 'fa_deleted_user' => $encUserId,
2146 'fa_deleted_timestamp' => $encTimestamp,
2147 'fa_deleted_reason' => $encReason,
2148 'fa_deleted' => $this->suppress ? $bitfield : 0,
2150 'fa_name' => 'img_name',
2151 'fa_archive_name' => 'NULL',
2152 'fa_size' => 'img_size',
2153 'fa_width' => 'img_width',
2154 'fa_height' => 'img_height',
2155 'fa_metadata' => 'img_metadata',
2156 'fa_bits' => 'img_bits',
2157 'fa_media_type' => 'img_media_type',
2158 'fa_major_mime' => 'img_major_mime',
2159 'fa_minor_mime' => 'img_minor_mime',
2160 'fa_description' => 'img_description',
2161 'fa_user' => 'img_user',
2162 'fa_user_text' => 'img_user_text',
2163 'fa_timestamp' => 'img_timestamp',
2164 'fa_sha1' => 'img_sha1',
2165 ), $where, __METHOD__ );
2168 if ( count( $oldRels ) ) {
2169 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
2170 $where = array(
2171 'oi_name' => $this->file->getName(),
2172 'oi_archive_name' => array_keys( $oldRels ) );
2173 $dbw->insertSelect( 'filearchive', 'oldimage',
2174 array(
2175 'fa_storage_group' => $encGroup,
2176 'fa_storage_key' => $dbw->conditional(
2177 array( 'oi_sha1' => '' ),
2178 $dbw->addQuotes( '' ),
2179 $concat
2181 'fa_deleted_user' => $encUserId,
2182 'fa_deleted_timestamp' => $encTimestamp,
2183 'fa_deleted_reason' => $encReason,
2184 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
2186 'fa_name' => 'oi_name',
2187 'fa_archive_name' => 'oi_archive_name',
2188 'fa_size' => 'oi_size',
2189 'fa_width' => 'oi_width',
2190 'fa_height' => 'oi_height',
2191 'fa_metadata' => 'oi_metadata',
2192 'fa_bits' => 'oi_bits',
2193 'fa_media_type' => 'oi_media_type',
2194 'fa_major_mime' => 'oi_major_mime',
2195 'fa_minor_mime' => 'oi_minor_mime',
2196 'fa_description' => 'oi_description',
2197 'fa_user' => 'oi_user',
2198 'fa_user_text' => 'oi_user_text',
2199 'fa_timestamp' => 'oi_timestamp',
2200 'fa_sha1' => 'oi_sha1',
2201 ), $where, __METHOD__ );
2205 function doDBDeletes() {
2206 $dbw = $this->file->repo->getMasterDB();
2207 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2209 if ( count( $oldRels ) ) {
2210 $dbw->delete( 'oldimage',
2211 array(
2212 'oi_name' => $this->file->getName(),
2213 'oi_archive_name' => array_keys( $oldRels )
2214 ), __METHOD__ );
2217 if ( $deleteCurrent ) {
2218 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
2223 * Run the transaction
2224 * @return FileRepoStatus
2226 function execute() {
2228 $this->file->lock();
2230 // Prepare deletion batch
2231 $hashes = $this->getHashes();
2232 $this->deletionBatch = array();
2233 $ext = $this->file->getExtension();
2234 $dotExt = $ext === '' ? '' : ".$ext";
2236 foreach ( $this->srcRels as $name => $srcRel ) {
2237 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2238 if ( isset( $hashes[$name] ) ) {
2239 $hash = $hashes[$name];
2240 $key = $hash . $dotExt;
2241 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
2242 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
2246 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2247 // We acquire this lock by running the inserts now, before the file operations.
2249 // This potentially has poor lock contention characteristics -- an alternative
2250 // scheme would be to insert stub filearchive entries with no fa_name and commit
2251 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2252 $this->doDBInserts();
2254 // Removes non-existent file from the batch, so we don't get errors.
2255 // This also handles files in the 'deleted' zone deleted via revision deletion.
2256 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch );
2257 if ( !$checkStatus->isGood() ) {
2258 $this->status->merge( $checkStatus );
2259 return $this->status;
2261 $this->deletionBatch = $checkStatus->value;
2263 // Execute the file deletion batch
2264 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2266 if ( !$status->isGood() ) {
2267 $this->status->merge( $status );
2270 if ( !$this->status->isOK() ) {
2271 // Critical file deletion error
2272 // Roll back inserts, release lock and abort
2273 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2274 $this->file->unlockAndRollback();
2276 return $this->status;
2279 // Delete image/oldimage rows
2280 $this->doDBDeletes();
2282 // Commit and return
2283 $this->file->unlock();
2285 return $this->status;
2289 * Removes non-existent files from a deletion batch.
2290 * @param array $batch
2291 * @return Status
2293 function removeNonexistentFiles( $batch ) {
2294 $files = $newBatch = array();
2296 foreach ( $batch as $batchItem ) {
2297 list( $src, ) = $batchItem;
2298 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2301 $result = $this->file->repo->fileExistsBatch( $files );
2302 if ( in_array( null, $result, true ) ) {
2303 return Status::newFatal( 'backend-fail-internal',
2304 $this->file->repo->getBackend()->getName() );
2307 foreach ( $batch as $batchItem ) {
2308 if ( $result[$batchItem[0]] ) {
2309 $newBatch[] = $batchItem;
2313 return Status::newGood( $newBatch );
2317 # ------------------------------------------------------------------------------
2320 * Helper class for file undeletion
2321 * @ingroup FileAbstraction
2323 class LocalFileRestoreBatch {
2324 /** @var LocalFile */
2325 private $file;
2327 /** @var array List of file IDs to restore */
2328 private $cleanupBatch;
2330 /** @var array List of file IDs to restore */
2331 private $ids;
2333 /** @var bool Add all revisions of the file */
2334 private $all;
2336 /** @var bool Whether to remove all settings for suppressed fields */
2337 private $unsuppress = false;
2340 * @param File $file
2341 * @param bool $unsuppress
2343 function __construct( File $file, $unsuppress = false ) {
2344 $this->file = $file;
2345 $this->cleanupBatch = $this->ids = array();
2346 $this->ids = array();
2347 $this->unsuppress = $unsuppress;
2351 * Add a file by ID
2352 * @param int $fa_id
2354 function addId( $fa_id ) {
2355 $this->ids[] = $fa_id;
2359 * Add a whole lot of files by ID
2360 * @param int[] $ids
2362 function addIds( $ids ) {
2363 $this->ids = array_merge( $this->ids, $ids );
2367 * Add all revisions of the file
2369 function addAll() {
2370 $this->all = true;
2374 * Run the transaction, except the cleanup batch.
2375 * The cleanup batch should be run in a separate transaction, because it locks different
2376 * rows and there's no need to keep the image row locked while it's acquiring those locks
2377 * The caller may have its own transaction open.
2378 * So we save the batch and let the caller call cleanup()
2379 * @return FileRepoStatus
2381 function execute() {
2382 global $wgLang;
2384 if ( !$this->all && !$this->ids ) {
2385 // Do nothing
2386 return $this->file->repo->newGood();
2389 $lockOwnsTrx = $this->file->lock();
2391 $dbw = $this->file->repo->getMasterDB();
2392 $status = $this->file->repo->newGood();
2394 $exists = (bool)$dbw->selectField( 'image', '1',
2395 array( 'img_name' => $this->file->getName() ),
2396 __METHOD__,
2397 // The lock() should already prevents changes, but this still may need
2398 // to bypass any transaction snapshot. However, if lock() started the
2399 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2400 $lockOwnsTrx ? array() : array( 'LOCK IN SHARE MODE' )
2403 // Fetch all or selected archived revisions for the file,
2404 // sorted from the most recent to the oldest.
2405 $conditions = array( 'fa_name' => $this->file->getName() );
2407 if ( !$this->all ) {
2408 $conditions['fa_id'] = $this->ids;
2411 $result = $dbw->select(
2412 'filearchive',
2413 ArchivedFile::selectFields(),
2414 $conditions,
2415 __METHOD__,
2416 array( 'ORDER BY' => 'fa_timestamp DESC' )
2419 $idsPresent = array();
2420 $storeBatch = array();
2421 $insertBatch = array();
2422 $insertCurrent = false;
2423 $deleteIds = array();
2424 $first = true;
2425 $archiveNames = array();
2427 foreach ( $result as $row ) {
2428 $idsPresent[] = $row->fa_id;
2430 if ( $row->fa_name != $this->file->getName() ) {
2431 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2432 $status->failCount++;
2433 continue;
2436 if ( $row->fa_storage_key == '' ) {
2437 // Revision was missing pre-deletion
2438 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2439 $status->failCount++;
2440 continue;
2443 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) .
2444 $row->fa_storage_key;
2445 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2447 if ( isset( $row->fa_sha1 ) ) {
2448 $sha1 = $row->fa_sha1;
2449 } else {
2450 // old row, populate from key
2451 $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2454 # Fix leading zero
2455 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2456 $sha1 = substr( $sha1, 1 );
2459 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2460 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2461 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2462 || is_null( $row->fa_metadata )
2464 // Refresh our metadata
2465 // Required for a new current revision; nice for older ones too. :)
2466 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2467 } else {
2468 $props = array(
2469 'minor_mime' => $row->fa_minor_mime,
2470 'major_mime' => $row->fa_major_mime,
2471 'media_type' => $row->fa_media_type,
2472 'metadata' => $row->fa_metadata
2476 if ( $first && !$exists ) {
2477 // This revision will be published as the new current version
2478 $destRel = $this->file->getRel();
2479 $insertCurrent = array(
2480 'img_name' => $row->fa_name,
2481 'img_size' => $row->fa_size,
2482 'img_width' => $row->fa_width,
2483 'img_height' => $row->fa_height,
2484 'img_metadata' => $props['metadata'],
2485 'img_bits' => $row->fa_bits,
2486 'img_media_type' => $props['media_type'],
2487 'img_major_mime' => $props['major_mime'],
2488 'img_minor_mime' => $props['minor_mime'],
2489 'img_description' => $row->fa_description,
2490 'img_user' => $row->fa_user,
2491 'img_user_text' => $row->fa_user_text,
2492 'img_timestamp' => $row->fa_timestamp,
2493 'img_sha1' => $sha1
2496 // The live (current) version cannot be hidden!
2497 if ( !$this->unsuppress && $row->fa_deleted ) {
2498 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2499 $this->cleanupBatch[] = $row->fa_storage_key;
2501 } else {
2502 $archiveName = $row->fa_archive_name;
2504 if ( $archiveName == '' ) {
2505 // This was originally a current version; we
2506 // have to devise a new archive name for it.
2507 // Format is <timestamp of archiving>!<name>
2508 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2510 do {
2511 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2512 $timestamp++;
2513 } while ( isset( $archiveNames[$archiveName] ) );
2516 $archiveNames[$archiveName] = true;
2517 $destRel = $this->file->getArchiveRel( $archiveName );
2518 $insertBatch[] = array(
2519 'oi_name' => $row->fa_name,
2520 'oi_archive_name' => $archiveName,
2521 'oi_size' => $row->fa_size,
2522 'oi_width' => $row->fa_width,
2523 'oi_height' => $row->fa_height,
2524 'oi_bits' => $row->fa_bits,
2525 'oi_description' => $row->fa_description,
2526 'oi_user' => $row->fa_user,
2527 'oi_user_text' => $row->fa_user_text,
2528 'oi_timestamp' => $row->fa_timestamp,
2529 'oi_metadata' => $props['metadata'],
2530 'oi_media_type' => $props['media_type'],
2531 'oi_major_mime' => $props['major_mime'],
2532 'oi_minor_mime' => $props['minor_mime'],
2533 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2534 'oi_sha1' => $sha1 );
2537 $deleteIds[] = $row->fa_id;
2539 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2540 // private files can stay where they are
2541 $status->successCount++;
2542 } else {
2543 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2544 $this->cleanupBatch[] = $row->fa_storage_key;
2547 $first = false;
2550 unset( $result );
2552 // Add a warning to the status object for missing IDs
2553 $missingIds = array_diff( $this->ids, $idsPresent );
2555 foreach ( $missingIds as $id ) {
2556 $status->error( 'undelete-missing-filearchive', $id );
2559 // Remove missing files from batch, so we don't get errors when undeleting them
2560 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2561 if ( !$checkStatus->isGood() ) {
2562 $status->merge( $checkStatus );
2563 return $status;
2565 $storeBatch = $checkStatus->value;
2567 // Run the store batch
2568 // Use the OVERWRITE_SAME flag to smooth over a common error
2569 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2570 $status->merge( $storeStatus );
2572 if ( !$status->isGood() ) {
2573 // Even if some files could be copied, fail entirely as that is the
2574 // easiest thing to do without data loss
2575 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2576 $status->ok = false;
2577 $this->file->unlock();
2579 return $status;
2582 // Run the DB updates
2583 // Because we have locked the image row, key conflicts should be rare.
2584 // If they do occur, we can roll back the transaction at this time with
2585 // no data loss, but leaving unregistered files scattered throughout the
2586 // public zone.
2587 // This is not ideal, which is why it's important to lock the image row.
2588 if ( $insertCurrent ) {
2589 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2592 if ( $insertBatch ) {
2593 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2596 if ( $deleteIds ) {
2597 $dbw->delete( 'filearchive',
2598 array( 'fa_id' => $deleteIds ),
2599 __METHOD__ );
2602 // If store batch is empty (all files are missing), deletion is to be considered successful
2603 if ( $status->successCount > 0 || !$storeBatch ) {
2604 if ( !$exists ) {
2605 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2607 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
2609 $this->file->purgeEverything();
2610 } else {
2611 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2612 $this->file->purgeDescription();
2613 $this->file->purgeHistory();
2617 $this->file->unlock();
2619 return $status;
2623 * Removes non-existent files from a store batch.
2624 * @param array $triplets
2625 * @return Status
2627 function removeNonexistentFiles( $triplets ) {
2628 $files = $filteredTriplets = array();
2629 foreach ( $triplets as $file ) {
2630 $files[$file[0]] = $file[0];
2633 $result = $this->file->repo->fileExistsBatch( $files );
2634 if ( in_array( null, $result, true ) ) {
2635 return Status::newFatal( 'backend-fail-internal',
2636 $this->file->repo->getBackend()->getName() );
2639 foreach ( $triplets as $file ) {
2640 if ( $result[$file[0]] ) {
2641 $filteredTriplets[] = $file;
2645 return Status::newGood( $filteredTriplets );
2649 * Removes non-existent files from a cleanup batch.
2650 * @param array $batch
2651 * @return array
2653 function removeNonexistentFromCleanup( $batch ) {
2654 $files = $newBatch = array();
2655 $repo = $this->file->repo;
2657 foreach ( $batch as $file ) {
2658 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2659 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2662 $result = $repo->fileExistsBatch( $files );
2664 foreach ( $batch as $file ) {
2665 if ( $result[$file] ) {
2666 $newBatch[] = $file;
2670 return $newBatch;
2674 * Delete unused files in the deleted zone.
2675 * This should be called from outside the transaction in which execute() was called.
2676 * @return FileRepoStatus
2678 function cleanup() {
2679 if ( !$this->cleanupBatch ) {
2680 return $this->file->repo->newGood();
2683 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2685 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2687 return $status;
2691 * Cleanup a failed batch. The batch was only partially successful, so
2692 * rollback by removing all items that were succesfully copied.
2694 * @param Status $storeStatus
2695 * @param array $storeBatch
2697 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2698 $cleanupBatch = array();
2700 foreach ( $storeStatus->success as $i => $success ) {
2701 // Check if this item of the batch was successfully copied
2702 if ( $success ) {
2703 // Item was successfully copied and needs to be removed again
2704 // Extract ($dstZone, $dstRel) from the batch
2705 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2708 $this->file->repo->cleanupBatch( $cleanupBatch );
2712 # ------------------------------------------------------------------------------
2715 * Helper class for file movement
2716 * @ingroup FileAbstraction
2718 class LocalFileMoveBatch {
2719 /** @var LocalFile */
2720 protected $file;
2722 /** @var Title */
2723 protected $target;
2725 protected $cur;
2727 protected $olds;
2729 protected $oldCount;
2731 protected $archive;
2733 /** @var DatabaseBase */
2734 protected $db;
2737 * @param File $file
2738 * @param Title $target
2740 function __construct( File $file, Title $target ) {
2741 $this->file = $file;
2742 $this->target = $target;
2743 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2744 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2745 $this->oldName = $this->file->getName();
2746 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2747 $this->oldRel = $this->oldHash . $this->oldName;
2748 $this->newRel = $this->newHash . $this->newName;
2749 $this->db = $file->getRepo()->getMasterDb();
2753 * Add the current image to the batch
2755 function addCurrent() {
2756 $this->cur = array( $this->oldRel, $this->newRel );
2760 * Add the old versions of the image to the batch
2761 * @return array List of archive names from old versions
2763 function addOlds() {
2764 $archiveBase = 'archive';
2765 $this->olds = array();
2766 $this->oldCount = 0;
2767 $archiveNames = array();
2769 $result = $this->db->select( 'oldimage',
2770 array( 'oi_archive_name', 'oi_deleted' ),
2771 array( 'oi_name' => $this->oldName ),
2772 __METHOD__,
2773 array( 'LOCK IN SHARE MODE' ) // ignore snapshot
2776 foreach ( $result as $row ) {
2777 $archiveNames[] = $row->oi_archive_name;
2778 $oldName = $row->oi_archive_name;
2779 $bits = explode( '!', $oldName, 2 );
2781 if ( count( $bits ) != 2 ) {
2782 wfDebug( "Old file name missing !: '$oldName' \n" );
2783 continue;
2786 list( $timestamp, $filename ) = $bits;
2788 if ( $this->oldName != $filename ) {
2789 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2790 continue;
2793 $this->oldCount++;
2795 // Do we want to add those to oldCount?
2796 if ( $row->oi_deleted & File::DELETED_FILE ) {
2797 continue;
2800 $this->olds[] = array(
2801 "{$archiveBase}/{$this->oldHash}{$oldName}",
2802 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2806 return $archiveNames;
2810 * Perform the move.
2811 * @return FileRepoStatus
2813 function execute() {
2814 $repo = $this->file->repo;
2815 $status = $repo->newGood();
2817 $triplets = $this->getMoveTriplets();
2818 $checkStatus = $this->removeNonexistentFiles( $triplets );
2819 if ( !$checkStatus->isGood() ) {
2820 $status->merge( $checkStatus );
2821 return $status;
2823 $triplets = $checkStatus->value;
2824 $destFile = wfLocalFile( $this->target );
2826 $this->file->lock(); // begin
2827 $destFile->lock(); // quickly fail if destination is not available
2828 // Rename the file versions metadata in the DB.
2829 // This implicitly locks the destination file, which avoids race conditions.
2830 // If we moved the files from A -> C before DB updates, another process could
2831 // move files from B -> C at this point, causing storeBatch() to fail and thus
2832 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2833 $statusDb = $this->doDBUpdates();
2834 if ( !$statusDb->isGood() ) {
2835 $destFile->unlock();
2836 $this->file->unlockAndRollback();
2837 $statusDb->ok = false;
2839 return $statusDb;
2841 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2842 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2844 // Copy the files into their new location.
2845 // If a prior process fataled copying or cleaning up files we tolerate any
2846 // of the existing files if they are identical to the ones being stored.
2847 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
2848 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2849 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2850 if ( !$statusMove->isGood() ) {
2851 // Delete any files copied over (while the destination is still locked)
2852 $this->cleanupTarget( $triplets );
2853 $destFile->unlock();
2854 $this->file->unlockAndRollback(); // unlocks the destination
2855 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2856 $statusMove->ok = false;
2858 return $statusMove;
2860 $destFile->unlock();
2861 $this->file->unlock(); // done
2863 // Everything went ok, remove the source files
2864 $this->cleanupSource( $triplets );
2866 $status->merge( $statusDb );
2867 $status->merge( $statusMove );
2869 return $status;
2873 * Do the database updates and return a new FileRepoStatus indicating how
2874 * many rows where updated.
2876 * @return FileRepoStatus
2878 function doDBUpdates() {
2879 $repo = $this->file->repo;
2880 $status = $repo->newGood();
2881 $dbw = $this->db;
2883 // Update current image
2884 $dbw->update(
2885 'image',
2886 array( 'img_name' => $this->newName ),
2887 array( 'img_name' => $this->oldName ),
2888 __METHOD__
2891 if ( $dbw->affectedRows() ) {
2892 $status->successCount++;
2893 } else {
2894 $status->failCount++;
2895 $status->fatal( 'imageinvalidfilename' );
2897 return $status;
2900 // Update old images
2901 $dbw->update(
2902 'oldimage',
2903 array(
2904 'oi_name' => $this->newName,
2905 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2906 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2908 array( 'oi_name' => $this->oldName ),
2909 __METHOD__
2912 $affected = $dbw->affectedRows();
2913 $total = $this->oldCount;
2914 $status->successCount += $affected;
2915 // Bug 34934: $total is based on files that actually exist.
2916 // There may be more DB rows than such files, in which case $affected
2917 // can be greater than $total. We use max() to avoid negatives here.
2918 $status->failCount += max( 0, $total - $affected );
2919 if ( $status->failCount ) {
2920 $status->error( 'imageinvalidfilename' );
2923 return $status;
2927 * Generate triplets for FileRepo::storeBatch().
2928 * @return array
2930 function getMoveTriplets() {
2931 $moves = array_merge( array( $this->cur ), $this->olds );
2932 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2934 foreach ( $moves as $move ) {
2935 // $move: (oldRelativePath, newRelativePath)
2936 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2937 $triplets[] = array( $srcUrl, 'public', $move[1] );
2938 wfDebugLog(
2939 'imagemove',
2940 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2944 return $triplets;
2948 * Removes non-existent files from move batch.
2949 * @param array $triplets
2950 * @return Status
2952 function removeNonexistentFiles( $triplets ) {
2953 $files = array();
2955 foreach ( $triplets as $file ) {
2956 $files[$file[0]] = $file[0];
2959 $result = $this->file->repo->fileExistsBatch( $files );
2960 if ( in_array( null, $result, true ) ) {
2961 return Status::newFatal( 'backend-fail-internal',
2962 $this->file->repo->getBackend()->getName() );
2965 $filteredTriplets = array();
2966 foreach ( $triplets as $file ) {
2967 if ( $result[$file[0]] ) {
2968 $filteredTriplets[] = $file;
2969 } else {
2970 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2974 return Status::newGood( $filteredTriplets );
2978 * Cleanup a partially moved array of triplets by deleting the target
2979 * files. Called if something went wrong half way.
2980 * @param array $triplets
2982 function cleanupTarget( $triplets ) {
2983 // Create dest pairs from the triplets
2984 $pairs = array();
2985 foreach ( $triplets as $triplet ) {
2986 // $triplet: (old source virtual URL, dst zone, dest rel)
2987 $pairs[] = array( $triplet[1], $triplet[2] );
2990 $this->file->repo->cleanupBatch( $pairs );
2994 * Cleanup a fully moved array of triplets by deleting the source files.
2995 * Called at the end of the move process if everything else went ok.
2996 * @param array $triplets
2998 function cleanupSource( $triplets ) {
2999 // Create source file names from the triplets
3000 $files = array();
3001 foreach ( $triplets as $triplet ) {
3002 $files[] = $triplet[0];
3005 $this->file->repo->cleanupBatch( $files );