Remove silly 'm' prefix from StubObject/DeprecatedGlobal members
[mediawiki.git] / includes / filerepo / file / LocalFile.php
bloba8fa8bd67b518b1d682daa0a42c54db76671b570
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 bool Whether the row was upgraded on load */
113 private $upgraded;
115 /** @var bool True if the image row is locked */
116 private $locked;
118 /** @var bool True if the image row is locked with a lock initiated transaction */
119 private $lockedOwnTrx;
121 /** @var bool True if file is not present in file system. Not to be cached in memcached */
122 private $missing;
124 /** @var int UNIX timestamp of last markVolatile() call */
125 private $lastMarkedVolatile = 0;
127 const LOAD_ALL = 1; // integer; load all the lazy fields too (like metadata)
128 const LOAD_VIA_SLAVE = 2; // integer; use a slave to load the data
130 const VOLATILE_TTL = 300; // integer; seconds
133 * Create a LocalFile from a title
134 * Do not call this except from inside a repo class.
136 * Note: $unused param is only here to avoid an E_STRICT
138 * @param Title $title
139 * @param FileRepo $repo
140 * @param null $unused
142 * @return LocalFile
144 static function newFromTitle( $title, $repo, $unused = null ) {
145 return new self( $title, $repo );
149 * Create a LocalFile from a title
150 * Do not call this except from inside a repo class.
152 * @param stdClass $row
153 * @param FileRepo $repo
155 * @return LocalFile
157 static function newFromRow( $row, $repo ) {
158 $title = Title::makeTitle( NS_FILE, $row->img_name );
159 $file = new self( $title, $repo );
160 $file->loadFromRow( $row );
162 return $file;
166 * Create a LocalFile from a SHA-1 key
167 * Do not call this except from inside a repo class.
169 * @param string $sha1 base-36 SHA-1
170 * @param LocalRepo $repo
171 * @param string|bool $timestamp MW_timestamp (optional)
172 * @return bool|LocalFile
174 static function newFromKey( $sha1, $repo, $timestamp = false ) {
175 $dbr = $repo->getSlaveDB();
177 $conds = array( 'img_sha1' => $sha1 );
178 if ( $timestamp ) {
179 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
182 $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
183 if ( $row ) {
184 return self::newFromRow( $row, $repo );
185 } else {
186 return false;
191 * Fields in the image table
192 * @return array
194 static function selectFields() {
195 return array(
196 'img_name',
197 'img_size',
198 'img_width',
199 'img_height',
200 'img_metadata',
201 'img_bits',
202 'img_media_type',
203 'img_major_mime',
204 'img_minor_mime',
205 'img_description',
206 'img_user',
207 'img_user_text',
208 'img_timestamp',
209 'img_sha1',
214 * Constructor.
215 * Do not call this except from inside a repo class.
216 * @param Title $title
217 * @param FileRepo $repo
219 function __construct( $title, $repo ) {
220 parent::__construct( $title, $repo );
222 $this->metadata = '';
223 $this->historyLine = 0;
224 $this->historyRes = null;
225 $this->dataLoaded = false;
226 $this->extraDataLoaded = false;
228 $this->assertRepoDefined();
229 $this->assertTitleDefined();
233 * Get the memcached key for the main data for this file, or false if
234 * there is no access to the shared cache.
235 * @return string|bool
237 function getCacheKey() {
238 $hashedName = md5( $this->getName() );
240 return $this->repo->getSharedCacheKey( 'file', $hashedName );
244 * Try to load file metadata from memcached. Returns true on success.
245 * @return bool
247 function loadFromCache() {
248 global $wgMemc;
250 wfProfileIn( __METHOD__ );
251 $this->dataLoaded = false;
252 $this->extraDataLoaded = false;
253 $key = $this->getCacheKey();
255 if ( !$key ) {
256 wfProfileOut( __METHOD__ );
258 return false;
261 $cachedValues = $wgMemc->get( $key );
263 // Check if the key existed and belongs to this version of MediaWiki
264 if ( isset( $cachedValues['version'] ) && $cachedValues['version'] == MW_FILE_VERSION ) {
265 wfDebug( "Pulling file metadata from cache key $key\n" );
266 $this->fileExists = $cachedValues['fileExists'];
267 if ( $this->fileExists ) {
268 $this->setProps( $cachedValues );
270 $this->dataLoaded = true;
271 $this->extraDataLoaded = true;
272 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
273 $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] );
277 if ( $this->dataLoaded ) {
278 wfIncrStats( 'image_cache_hit' );
279 } else {
280 wfIncrStats( 'image_cache_miss' );
283 wfProfileOut( __METHOD__ );
285 return $this->dataLoaded;
289 * Save the file metadata to memcached
291 function saveToCache() {
292 global $wgMemc;
294 $this->load();
295 $key = $this->getCacheKey();
297 if ( !$key ) {
298 return;
301 $fields = $this->getCacheFields( '' );
302 $cache = array( 'version' => MW_FILE_VERSION );
303 $cache['fileExists'] = $this->fileExists;
305 if ( $this->fileExists ) {
306 foreach ( $fields as $field ) {
307 $cache[$field] = $this->$field;
311 // Strip off excessive entries from the subset of fields that can become large.
312 // If the cache value gets to large it will not fit in memcached and nothing will
313 // get cached at all, causing master queries for any file access.
314 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
315 if ( isset( $cache[$field] ) && strlen( $cache[$field] ) > 100 * 1024 ) {
316 unset( $cache[$field] ); // don't let the value get too big
320 // Cache presence for 1 week and negatives for 1 day
321 $wgMemc->set( $key, $cache, $this->fileExists ? 86400 * 7 : 86400 );
325 * Load metadata from the file itself
327 function loadFromFile() {
328 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
329 $this->setProps( $props );
333 * @param string $prefix
334 * @return array
336 function getCacheFields( $prefix = 'img_' ) {
337 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
338 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
339 'user_text', 'description' );
340 static $results = array();
342 if ( $prefix == '' ) {
343 return $fields;
346 if ( !isset( $results[$prefix] ) ) {
347 $prefixedFields = array();
348 foreach ( $fields as $field ) {
349 $prefixedFields[] = $prefix . $field;
351 $results[$prefix] = $prefixedFields;
354 return $results[$prefix];
358 * @param string $prefix
359 * @return array
361 function getLazyCacheFields( $prefix = 'img_' ) {
362 static $fields = array( 'metadata' );
363 static $results = array();
365 if ( $prefix == '' ) {
366 return $fields;
369 if ( !isset( $results[$prefix] ) ) {
370 $prefixedFields = array();
371 foreach ( $fields as $field ) {
372 $prefixedFields[] = $prefix . $field;
374 $results[$prefix] = $prefixedFields;
377 return $results[$prefix];
381 * Load file metadata from the DB
383 function loadFromDB( $flags = 0 ) {
384 # Polymorphic function name to distinguish foreign and local fetches
385 $fname = get_class( $this ) . '::' . __FUNCTION__;
386 wfProfileIn( $fname );
388 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
389 $this->dataLoaded = true;
390 $this->extraDataLoaded = true;
392 $dbr = ( $flags & self::LOAD_VIA_SLAVE )
393 ? $this->repo->getSlaveDB()
394 : $this->repo->getMasterDB();
396 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
397 array( 'img_name' => $this->getName() ), $fname );
399 if ( $row ) {
400 $this->loadFromRow( $row );
401 } else {
402 $this->fileExists = false;
405 wfProfileOut( $fname );
409 * Load lazy file metadata from the DB.
410 * This covers fields that are sometimes not cached.
412 protected function loadExtraFromDB() {
413 # Polymorphic function name to distinguish foreign and local fetches
414 $fname = get_class( $this ) . '::' . __FUNCTION__;
415 wfProfileIn( $fname );
417 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
418 $this->extraDataLoaded = true;
420 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo->getSlaveDB(), $fname );
421 if ( !$fieldMap ) {
422 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo->getMasterDB(), $fname );
425 if ( $fieldMap ) {
426 foreach ( $fieldMap as $name => $value ) {
427 $this->$name = $value;
429 } else {
430 wfProfileOut( $fname );
431 throw new MWException( "Could not find data for image '{$this->getName()}'." );
434 wfProfileOut( $fname );
438 * @param DatabaseBase $dbr
439 * @param string $fname
440 * @return array|false
442 private function loadFieldsWithTimestamp( $dbr, $fname ) {
443 $fieldMap = false;
445 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ),
446 array( 'img_name' => $this->getName(), 'img_timestamp' => $this->getTimestamp() ),
447 $fname );
448 if ( $row ) {
449 $fieldMap = $this->unprefixRow( $row, 'img_' );
450 } else {
451 # File may have been uploaded over in the meantime; check the old versions
452 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ),
453 array( 'oi_name' => $this->getName(), 'oi_timestamp' => $this->getTimestamp() ),
454 $fname );
455 if ( $row ) {
456 $fieldMap = $this->unprefixRow( $row, 'oi_' );
460 return $fieldMap;
464 * @param array $row Row
465 * @param string $prefix
466 * @throws MWException
467 * @return array
469 protected function unprefixRow( $row, $prefix = 'img_' ) {
470 $array = (array)$row;
471 $prefixLength = strlen( $prefix );
473 // Sanity check prefix once
474 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
475 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
478 $decoded = array();
479 foreach ( $array as $name => $value ) {
480 $decoded[substr( $name, $prefixLength )] = $value;
483 return $decoded;
487 * Decode a row from the database (either object or array) to an array
488 * with timestamps and MIME types decoded, and the field prefix removed.
489 * @param object $row
490 * @param string $prefix
491 * @throws MWException
492 * @return array
494 function decodeRow( $row, $prefix = 'img_' ) {
495 $decoded = $this->unprefixRow( $row, $prefix );
497 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
499 $decoded['metadata'] = $this->repo->getSlaveDB()->decodeBlob( $decoded['metadata'] );
501 if ( empty( $decoded['major_mime'] ) ) {
502 $decoded['mime'] = 'unknown/unknown';
503 } else {
504 if ( !$decoded['minor_mime'] ) {
505 $decoded['minor_mime'] = 'unknown';
507 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
510 # Trim zero padding from char/binary field
511 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
513 return $decoded;
517 * Load file metadata from a DB result row
519 * @param object $row
520 * @param string $prefix
522 function loadFromRow( $row, $prefix = 'img_' ) {
523 $this->dataLoaded = true;
524 $this->extraDataLoaded = true;
526 $array = $this->decodeRow( $row, $prefix );
528 foreach ( $array as $name => $value ) {
529 $this->$name = $value;
532 $this->fileExists = true;
533 $this->maybeUpgradeRow();
537 * Load file metadata from cache or DB, unless already loaded
538 * @param int $flags
540 function load( $flags = 0 ) {
541 if ( !$this->dataLoaded ) {
542 if ( !$this->loadFromCache() ) {
543 $this->loadFromDB( $this->isVolatile() ? 0 : self::LOAD_VIA_SLAVE );
544 $this->saveToCache();
546 $this->dataLoaded = true;
548 if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) {
549 $this->loadExtraFromDB();
554 * Upgrade a row if it needs it
556 function maybeUpgradeRow() {
557 global $wgUpdateCompatibleMetadata;
558 if ( wfReadOnly() ) {
559 return;
562 if ( is_null( $this->media_type ) ||
563 $this->mime == 'image/svg'
565 $this->upgradeRow();
566 $this->upgraded = true;
567 } else {
568 $handler = $this->getHandler();
569 if ( $handler ) {
570 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
571 if ( $validity === MediaHandler::METADATA_BAD
572 || ( $validity === MediaHandler::METADATA_COMPATIBLE && $wgUpdateCompatibleMetadata )
574 $this->upgradeRow();
575 $this->upgraded = true;
581 function getUpgraded() {
582 return $this->upgraded;
586 * Fix assorted version-related problems with the image row by reloading it from the file
588 function upgradeRow() {
589 wfProfileIn( __METHOD__ );
591 $this->lock(); // begin
593 $this->loadFromFile();
595 # Don't destroy file info of missing files
596 if ( !$this->fileExists ) {
597 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
598 wfProfileOut( __METHOD__ );
600 return;
603 $dbw = $this->repo->getMasterDB();
604 list( $major, $minor ) = self::splitMime( $this->mime );
606 if ( wfReadOnly() ) {
607 wfProfileOut( __METHOD__ );
609 return;
611 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
613 $dbw->update( 'image',
614 array(
615 'img_size' => $this->size, // sanity
616 'img_width' => $this->width,
617 'img_height' => $this->height,
618 'img_bits' => $this->bits,
619 'img_media_type' => $this->media_type,
620 'img_major_mime' => $major,
621 'img_minor_mime' => $minor,
622 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
623 'img_sha1' => $this->sha1,
625 array( 'img_name' => $this->getName() ),
626 __METHOD__
629 $this->saveToCache();
631 $this->unlock(); // done
633 wfProfileOut( __METHOD__ );
637 * Set properties in this object to be equal to those given in the
638 * associative array $info. Only cacheable fields can be set.
639 * All fields *must* be set in $info except for getLazyCacheFields().
641 * If 'mime' is given, it will be split into major_mime/minor_mime.
642 * If major_mime/minor_mime are given, $this->mime will also be set.
644 * @param array $info
646 function setProps( $info ) {
647 $this->dataLoaded = true;
648 $fields = $this->getCacheFields( '' );
649 $fields[] = 'fileExists';
651 foreach ( $fields as $field ) {
652 if ( isset( $info[$field] ) ) {
653 $this->$field = $info[$field];
657 // Fix up mime fields
658 if ( isset( $info['major_mime'] ) ) {
659 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
660 } elseif ( isset( $info['mime'] ) ) {
661 $this->mime = $info['mime'];
662 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
666 /** splitMime inherited */
667 /** getName inherited */
668 /** getTitle inherited */
669 /** getURL inherited */
670 /** getViewURL inherited */
671 /** getPath inherited */
672 /** isVisible inhereted */
675 * @return bool
677 function isMissing() {
678 if ( $this->missing === null ) {
679 list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() );
680 $this->missing = !$fileExists;
683 return $this->missing;
687 * Return the width of the image
689 * @param int $page
690 * @return int
692 public function getWidth( $page = 1 ) {
693 $this->load();
695 if ( $this->isMultipage() ) {
696 $handler = $this->getHandler();
697 if ( !$handler ) {
698 return 0;
700 $dim = $handler->getPageDimensions( $this, $page );
701 if ( $dim ) {
702 return $dim['width'];
703 } else {
704 // For non-paged media, the false goes through an
705 // intval, turning failure into 0, so do same here.
706 return 0;
708 } else {
709 return $this->width;
714 * Return the height of the image
716 * @param int $page
717 * @return int
719 public function getHeight( $page = 1 ) {
720 $this->load();
722 if ( $this->isMultipage() ) {
723 $handler = $this->getHandler();
724 if ( !$handler ) {
725 return 0;
727 $dim = $handler->getPageDimensions( $this, $page );
728 if ( $dim ) {
729 return $dim['height'];
730 } else {
731 // For non-paged media, the false goes through an
732 // intval, turning failure into 0, so do same here.
733 return 0;
735 } else {
736 return $this->height;
741 * Returns ID or name of user who uploaded the file
743 * @param string $type 'text' or 'id'
744 * @return int|string
746 function getUser( $type = 'text' ) {
747 $this->load();
749 if ( $type == 'text' ) {
750 return $this->user_text;
751 } elseif ( $type == 'id' ) {
752 return $this->user;
757 * Get handler-specific metadata
758 * @return string
760 function getMetadata() {
761 $this->load( self::LOAD_ALL ); // large metadata is loaded in another step
762 return $this->metadata;
766 * @return int
768 function getBitDepth() {
769 $this->load();
771 return $this->bits;
775 * Returns the size of the image file, in bytes
776 * @return int
778 public function getSize() {
779 $this->load();
781 return $this->size;
785 * Returns the mime type of the file.
786 * @return string
788 function getMimeType() {
789 $this->load();
791 return $this->mime;
795 * Returns the type of the media in the file.
796 * Use the value returned by this function with the MEDIATYPE_xxx constants.
797 * @return string
799 function getMediaType() {
800 $this->load();
802 return $this->media_type;
805 /** canRender inherited */
806 /** mustRender inherited */
807 /** allowInlineDisplay inherited */
808 /** isSafeFile inherited */
809 /** isTrustedFile inherited */
812 * Returns true if the file exists on disk.
813 * @return bool Whether file exist on disk.
815 public function exists() {
816 $this->load();
818 return $this->fileExists;
821 /** getTransformScript inherited */
822 /** getUnscaledThumb inherited */
823 /** thumbName inherited */
824 /** createThumb inherited */
825 /** transform inherited */
827 /** getHandler inherited */
828 /** iconThumb inherited */
829 /** getLastError inherited */
832 * Get all thumbnail names previously generated for this file
833 * @param string|bool $archiveName Name of an archive file, default false
834 * @return array first element is the base dir, then files in that base dir.
836 function getThumbnails( $archiveName = false ) {
837 if ( $archiveName ) {
838 $dir = $this->getArchiveThumbPath( $archiveName );
839 } else {
840 $dir = $this->getThumbPath();
843 $backend = $this->repo->getBackend();
844 $files = array( $dir );
845 try {
846 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
847 foreach ( $iterator as $file ) {
848 $files[] = $file;
850 } catch ( FileBackendError $e ) {
851 } // suppress (bug 54674)
853 return $files;
857 * Refresh metadata in memcached, but don't touch thumbnails or squid
859 function purgeMetadataCache() {
860 $this->loadFromDB();
861 $this->saveToCache();
862 $this->purgeHistory();
866 * Purge the shared history (OldLocalFile) cache.
868 * @note This used to purge old thumbnails as well.
870 function purgeHistory() {
871 global $wgMemc;
873 $hashedName = md5( $this->getName() );
874 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
876 if ( $oldKey ) {
877 $wgMemc->delete( $oldKey );
882 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid.
884 * @param array $options An array potentially with the key forThumbRefresh.
886 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
888 function purgeCache( $options = array() ) {
889 wfProfileIn( __METHOD__ );
890 // Refresh metadata cache
891 $this->purgeMetadataCache();
893 // Delete thumbnails
894 $this->purgeThumbnails( $options );
896 // Purge squid cache for this file
897 SquidUpdate::purge( array( $this->getURL() ) );
898 wfProfileOut( __METHOD__ );
902 * Delete cached transformed files for an archived version only.
903 * @param string $archiveName Name of the archived file
905 function purgeOldThumbnails( $archiveName ) {
906 global $wgUseSquid;
907 wfProfileIn( __METHOD__ );
909 // Get a list of old thumbnails and URLs
910 $files = $this->getThumbnails( $archiveName );
912 // Purge any custom thumbnail caches
913 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
915 $dir = array_shift( $files );
916 $this->purgeThumbList( $dir, $files );
918 // Purge the squid
919 if ( $wgUseSquid ) {
920 $urls = array();
921 foreach ( $files as $file ) {
922 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
924 SquidUpdate::purge( $urls );
927 wfProfileOut( __METHOD__ );
931 * Delete cached transformed files for the current version only.
933 function purgeThumbnails( $options = array() ) {
934 global $wgUseSquid;
935 wfProfileIn( __METHOD__ );
937 // Delete thumbnails
938 $files = $this->getThumbnails();
939 // Always purge all files from squid regardless of handler filters
940 $urls = array();
941 if ( $wgUseSquid ) {
942 foreach ( $files as $file ) {
943 $urls[] = $this->getThumbUrl( $file );
945 array_shift( $urls ); // don't purge directory
948 // Give media handler a chance to filter the file purge list
949 if ( !empty( $options['forThumbRefresh'] ) ) {
950 $handler = $this->getHandler();
951 if ( $handler ) {
952 $handler->filterThumbnailPurgeList( $files, $options );
956 // Purge any custom thumbnail caches
957 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
959 $dir = array_shift( $files );
960 $this->purgeThumbList( $dir, $files );
962 // Purge the squid
963 if ( $wgUseSquid ) {
964 SquidUpdate::purge( $urls );
967 wfProfileOut( __METHOD__ );
971 * Delete a list of thumbnails visible at urls
972 * @param string $dir Base dir of the files.
973 * @param array $files Array of strings: relative filenames (to $dir)
975 protected function purgeThumbList( $dir, $files ) {
976 $fileListDebug = strtr(
977 var_export( $files, true ),
978 array( "\n" => '' )
980 wfDebug( __METHOD__ . ": $fileListDebug\n" );
982 $purgeList = array();
983 foreach ( $files as $file ) {
984 # Check that the base file name is part of the thumb name
985 # This is a basic sanity check to avoid erasing unrelated directories
986 if ( strpos( $file, $this->getName() ) !== false
987 || strpos( $file, "-thumbnail" ) !== false // "short" thumb name
989 $purgeList[] = "{$dir}/{$file}";
993 # Delete the thumbnails
994 $this->repo->quickPurgeBatch( $purgeList );
995 # Clear out the thumbnail directory if empty
996 $this->repo->quickCleanDir( $dir );
999 /** purgeDescription inherited */
1000 /** purgeEverything inherited */
1003 * @param int $limit Optional: Limit to number of results
1004 * @param int $start Optional: Timestamp, start from
1005 * @param int $end Optional: Timestamp, end at
1006 * @param bool $inc
1007 * @return array
1009 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1010 $dbr = $this->repo->getSlaveDB();
1011 $tables = array( 'oldimage' );
1012 $fields = OldLocalFile::selectFields();
1013 $conds = $opts = $join_conds = array();
1014 $eq = $inc ? '=' : '';
1015 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
1017 if ( $start ) {
1018 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1021 if ( $end ) {
1022 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1025 if ( $limit ) {
1026 $opts['LIMIT'] = $limit;
1029 // Search backwards for time > x queries
1030 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
1031 $opts['ORDER BY'] = "oi_timestamp $order";
1032 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
1034 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
1035 &$conds, &$opts, &$join_conds ) );
1037 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
1038 $r = array();
1040 foreach ( $res as $row ) {
1041 $r[] = $this->repo->newFileFromRow( $row );
1044 if ( $order == 'ASC' ) {
1045 $r = array_reverse( $r ); // make sure it ends up descending
1048 return $r;
1052 * Returns the history of this file, line by line.
1053 * starts with current version, then old versions.
1054 * uses $this->historyLine to check which line to return:
1055 * 0 return line for current version
1056 * 1 query for old versions, return first one
1057 * 2, ... return next old version from above query
1058 * @return bool
1060 public function nextHistoryLine() {
1061 # Polymorphic function name to distinguish foreign and local fetches
1062 $fname = get_class( $this ) . '::' . __FUNCTION__;
1064 $dbr = $this->repo->getSlaveDB();
1066 if ( $this->historyLine == 0 ) { // called for the first time, return line from cur
1067 $this->historyRes = $dbr->select( 'image',
1068 array(
1069 '*',
1070 "'' AS oi_archive_name",
1071 '0 as oi_deleted',
1072 'img_sha1'
1074 array( 'img_name' => $this->title->getDBkey() ),
1075 $fname
1078 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1079 $this->historyRes = null;
1081 return false;
1083 } elseif ( $this->historyLine == 1 ) {
1084 $this->historyRes = $dbr->select( 'oldimage', '*',
1085 array( 'oi_name' => $this->title->getDBkey() ),
1086 $fname,
1087 array( 'ORDER BY' => 'oi_timestamp DESC' )
1090 $this->historyLine++;
1092 return $dbr->fetchObject( $this->historyRes );
1096 * Reset the history pointer to the first element of the history
1098 public function resetHistory() {
1099 $this->historyLine = 0;
1101 if ( !is_null( $this->historyRes ) ) {
1102 $this->historyRes = null;
1106 /** getHashPath inherited */
1107 /** getRel inherited */
1108 /** getUrlRel inherited */
1109 /** getArchiveRel inherited */
1110 /** getArchivePath inherited */
1111 /** getThumbPath inherited */
1112 /** getArchiveUrl inherited */
1113 /** getThumbUrl inherited */
1114 /** getArchiveVirtualUrl inherited */
1115 /** getThumbVirtualUrl inherited */
1116 /** isHashed inherited */
1119 * Upload a file and record it in the DB
1120 * @param string $srcPath Source storage path, virtual URL, or filesystem path
1121 * @param string $comment Upload description
1122 * @param string $pageText Text to use for the new description page,
1123 * if a new description page is created
1124 * @param int|bool $flags Flags for publish()
1125 * @param array|bool $props File properties, if known. This can be used to
1126 * reduce the upload time when uploading virtual URLs for which the file
1127 * info is already known
1128 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1129 * current time
1130 * @param User|null $user User object or null to use $wgUser
1132 * @return FileRepoStatus On success, the value member contains the
1133 * archive name, or an empty string if it was a new file.
1135 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false,
1136 $timestamp = false, $user = null
1138 global $wgContLang;
1140 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1141 return $this->readOnlyFatalStatus();
1144 if ( !$props ) {
1145 wfProfileIn( __METHOD__ . '-getProps' );
1146 if ( $this->repo->isVirtualUrl( $srcPath )
1147 || FileBackend::isStoragePath( $srcPath )
1149 $props = $this->repo->getFileProps( $srcPath );
1150 } else {
1151 $props = FSFile::getPropsFromPath( $srcPath );
1153 wfProfileOut( __METHOD__ . '-getProps' );
1156 $options = array();
1157 $handler = MediaHandler::getHandler( $props['mime'] );
1158 if ( $handler ) {
1159 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1160 } else {
1161 $options['headers'] = array();
1164 // Trim spaces on user supplied text
1165 $comment = trim( $comment );
1167 // Truncate nicely or the DB will do it for us
1168 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1169 $comment = $wgContLang->truncate( $comment, 255 );
1170 $this->lock(); // begin
1171 $status = $this->publish( $srcPath, $flags, $options );
1173 if ( $status->successCount >= 2 ) {
1174 // There will be a copy+(one of move,copy,store).
1175 // The first succeeding does not commit us to updating the DB
1176 // since it simply copied the current version to a timestamped file name.
1177 // It is only *preferable* to avoid leaving such files orphaned.
1178 // Once the second operation goes through, then the current version was
1179 // updated and we must therefore update the DB too.
1180 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
1181 $status->fatal( 'filenotfound', $srcPath );
1185 $this->unlock(); // done
1187 return $status;
1191 * Record a file upload in the upload log and the image table
1192 * @param string $oldver
1193 * @param string $desc
1194 * @param string $license
1195 * @param string $copyStatus
1196 * @param string $source
1197 * @param bool $watch
1198 * @param string|bool $timestamp
1199 * @param User|null $user User object or null to use $wgUser
1200 * @return bool
1202 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1203 $watch = false, $timestamp = false, User $user = null ) {
1204 if ( !$user ) {
1205 global $wgUser;
1206 $user = $wgUser;
1209 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
1211 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1212 return false;
1215 if ( $watch ) {
1216 $user->addWatch( $this->getTitle() );
1219 return true;
1223 * Record a file upload in the upload log and the image table
1224 * @param string $oldver
1225 * @param string $comment
1226 * @param string $pageText
1227 * @param bool|array $props
1228 * @param string|bool $timestamp
1229 * @param null|User $user
1230 * @return bool
1232 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false,
1233 $user = null
1235 wfProfileIn( __METHOD__ );
1237 if ( is_null( $user ) ) {
1238 global $wgUser;
1239 $user = $wgUser;
1242 $dbw = $this->repo->getMasterDB();
1243 $dbw->begin( __METHOD__ );
1245 if ( !$props ) {
1246 wfProfileIn( __METHOD__ . '-getProps' );
1247 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
1248 wfProfileOut( __METHOD__ . '-getProps' );
1251 if ( $timestamp === false ) {
1252 // Use FOR UPDATE in case lock()/unlock() did not start the transaction
1253 $ltimestamp = $dbw->selectField( 'image', 'img_timestamp',
1254 array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
1255 $ltime = $ltimestamp ? wfTimestamp( TS_UNIX, $ltimestamp ) : false;
1256 $ctime = time();
1257 // Avoid a timestamp that is not newer than the last version
1258 if ( $ctime > $ltime ) {
1259 $timestamp = $dbw->timestamp( $ctime );
1260 } else {
1261 sleep( 1 ); // fast enough uploads will go in to the future otherwise
1262 $timestamp = $dbw->timestamp( $ltime + 1 );
1266 $props['description'] = $comment;
1267 $props['user'] = $user->getId();
1268 $props['user_text'] = $user->getName();
1269 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
1270 $this->setProps( $props );
1272 # Fail now if the file isn't there
1273 if ( !$this->fileExists ) {
1274 wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" );
1275 wfProfileOut( __METHOD__ );
1277 return false;
1280 $reupload = false;
1282 # Test to see if the row exists using INSERT IGNORE
1283 # This avoids race conditions by locking the row until the commit, and also
1284 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1285 $dbw->insert( 'image',
1286 array(
1287 'img_name' => $this->getName(),
1288 'img_size' => $this->size,
1289 'img_width' => intval( $this->width ),
1290 'img_height' => intval( $this->height ),
1291 'img_bits' => $this->bits,
1292 'img_media_type' => $this->media_type,
1293 'img_major_mime' => $this->major_mime,
1294 'img_minor_mime' => $this->minor_mime,
1295 'img_timestamp' => $timestamp,
1296 'img_description' => $comment,
1297 'img_user' => $user->getId(),
1298 'img_user_text' => $user->getName(),
1299 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1300 'img_sha1' => $this->sha1
1302 __METHOD__,
1303 'IGNORE'
1305 if ( $dbw->affectedRows() == 0 ) {
1306 # (bug 34993) Note: $oldver can be empty here, if the previous
1307 # version of the file was broken. Allow registration of the new
1308 # version to continue anyway, because that's better than having
1309 # an image that's not fixable by user operations.
1311 $reupload = true;
1312 # Collision, this is an update of a file
1313 # Insert previous contents into oldimage
1314 $dbw->insertSelect( 'oldimage', 'image',
1315 array(
1316 'oi_name' => 'img_name',
1317 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1318 'oi_size' => 'img_size',
1319 'oi_width' => 'img_width',
1320 'oi_height' => 'img_height',
1321 'oi_bits' => 'img_bits',
1322 'oi_timestamp' => 'img_timestamp',
1323 'oi_description' => 'img_description',
1324 'oi_user' => 'img_user',
1325 'oi_user_text' => 'img_user_text',
1326 'oi_metadata' => 'img_metadata',
1327 'oi_media_type' => 'img_media_type',
1328 'oi_major_mime' => 'img_major_mime',
1329 'oi_minor_mime' => 'img_minor_mime',
1330 'oi_sha1' => 'img_sha1'
1332 array( 'img_name' => $this->getName() ),
1333 __METHOD__
1336 # Update the current image row
1337 $dbw->update( 'image',
1338 array( /* SET */
1339 'img_size' => $this->size,
1340 'img_width' => intval( $this->width ),
1341 'img_height' => intval( $this->height ),
1342 'img_bits' => $this->bits,
1343 'img_media_type' => $this->media_type,
1344 'img_major_mime' => $this->major_mime,
1345 'img_minor_mime' => $this->minor_mime,
1346 'img_timestamp' => $timestamp,
1347 'img_description' => $comment,
1348 'img_user' => $user->getId(),
1349 'img_user_text' => $user->getName(),
1350 'img_metadata' => $dbw->encodeBlob( $this->metadata ),
1351 'img_sha1' => $this->sha1
1353 array( 'img_name' => $this->getName() ),
1354 __METHOD__
1356 } else {
1357 # This is a new file, so update the image count
1358 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
1361 $descTitle = $this->getTitle();
1362 $wikiPage = new WikiFilePage( $descTitle );
1363 $wikiPage->setFile( $this );
1365 # Add the log entry
1366 $action = $reupload ? 'overwrite' : 'upload';
1368 $logEntry = new ManualLogEntry( 'upload', $action );
1369 $logEntry->setPerformer( $user );
1370 $logEntry->setComment( $comment );
1371 $logEntry->setTarget( $descTitle );
1373 // Allow people using the api to associate log entries with the upload.
1374 // Log has a timestamp, but sometimes different from upload timestamp.
1375 $logEntry->setParameters(
1376 array(
1377 'img_sha1' => $this->sha1,
1378 'img_timestamp' => $timestamp,
1381 // Note we keep $logId around since during new image
1382 // creation, page doesn't exist yet, so log_page = 0
1383 // but we want it to point to the page we're making,
1384 // so we later modify the log entry.
1385 // For a similar reason, we avoid making an RC entry
1386 // now and wait until the page exists.
1387 $logId = $logEntry->insert();
1389 $exists = $descTitle->exists();
1390 if ( $exists ) {
1391 // Page exists, do RC entry now (otherwise we wait for later).
1392 $logEntry->publish( $logId );
1394 wfProfileIn( __METHOD__ . '-edit' );
1396 if ( $exists ) {
1397 # Create a null revision
1398 $latest = $descTitle->getLatestRevID();
1399 $editSummary = LogFormatter::newFromEntry( $logEntry )->getPlainActionText();
1401 $nullRevision = Revision::newNullRevision(
1402 $dbw,
1403 $descTitle->getArticleID(),
1404 $editSummary,
1405 false,
1406 $user
1408 if ( !is_null( $nullRevision ) ) {
1409 $nullRevision->insertOn( $dbw );
1411 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1412 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1416 # Commit the transaction now, in case something goes wrong later
1417 # The most important thing is that files don't get lost, especially archives
1418 # NOTE: once we have support for nested transactions, the commit may be moved
1419 # to after $wikiPage->doEdit has been called.
1420 $dbw->commit( __METHOD__ );
1422 # Save to memcache.
1423 # We shall not saveToCache before the commit since otherwise
1424 # in case of a rollback there is an usable file from memcached
1425 # which in fact doesn't really exist (bug 24978)
1426 $this->saveToCache();
1428 if ( $exists ) {
1429 # Invalidate the cache for the description page
1430 $descTitle->invalidateCache();
1431 $descTitle->purgeSquid();
1432 } else {
1433 # New file; create the description page.
1434 # There's already a log entry, so don't make a second RC entry
1435 # Squid and file cache for the description page are purged by doEditContent.
1436 $content = ContentHandler::makeContent( $pageText, $descTitle );
1437 $status = $wikiPage->doEditContent(
1438 $content,
1439 $comment,
1440 EDIT_NEW | EDIT_SUPPRESS_RC,
1441 false,
1442 $user
1445 $dbw->begin( __METHOD__ ); // XXX; doEdit() uses a transaction
1446 // Now that the page exists, make an RC entry.
1447 $logEntry->publish( $logId );
1448 if ( isset( $status->value['revision'] ) ) {
1449 $dbw->update( 'logging',
1450 array( 'log_page' => $status->value['revision']->getPage() ),
1451 array( 'log_id' => $logId ),
1452 __METHOD__
1455 $dbw->commit( __METHOD__ ); // commit before anything bad can happen
1458 wfProfileOut( __METHOD__ . '-edit' );
1460 if ( $reupload ) {
1461 # Delete old thumbnails
1462 wfProfileIn( __METHOD__ . '-purge' );
1463 $this->purgeThumbnails();
1464 wfProfileOut( __METHOD__ . '-purge' );
1466 # Remove the old file from the squid cache
1467 SquidUpdate::purge( array( $this->getURL() ) );
1470 # Hooks, hooks, the magic of hooks...
1471 wfProfileIn( __METHOD__ . '-hooks' );
1472 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1473 wfProfileOut( __METHOD__ . '-hooks' );
1475 # Invalidate cache for all pages using this file
1476 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1477 $update->doUpdate();
1478 if ( !$reupload ) {
1479 LinksUpdate::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1482 wfProfileOut( __METHOD__ );
1484 return true;
1488 * Move or copy a file to its public location. If a file exists at the
1489 * destination, move it to an archive. Returns a FileRepoStatus object with
1490 * the archive name in the "value" member on success.
1492 * The archive name should be passed through to recordUpload for database
1493 * registration.
1495 * @param string $srcPath Local filesystem path to the source image
1496 * @param int $flags A bitwise combination of:
1497 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1498 * @param array $options Optional additional parameters
1499 * @return FileRepoStatus On success, the value member contains the
1500 * archive name, or an empty string if it was a new file.
1502 function publish( $srcPath, $flags = 0, array $options = array() ) {
1503 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1507 * Move or copy a file to a specified location. Returns a FileRepoStatus
1508 * object with the archive name in the "value" member on success.
1510 * The archive name should be passed through to recordUpload for database
1511 * registration.
1513 * @param string $srcPath Local filesystem path to the source image
1514 * @param string $dstRel Target relative path
1515 * @param int $flags A bitwise combination of:
1516 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1517 * @param array $options Optional additional parameters
1518 * @return FileRepoStatus On success, the value member contains the
1519 * archive name, or an empty string if it was a new file.
1521 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1522 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1523 return $this->readOnlyFatalStatus();
1526 $this->lock(); // begin
1528 $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName();
1529 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1530 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1531 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1533 if ( $status->value == 'new' ) {
1534 $status->value = '';
1535 } else {
1536 $status->value = $archiveName;
1539 $this->unlock(); // done
1541 return $status;
1544 /** getLinksTo inherited */
1545 /** getExifData inherited */
1546 /** isLocal inherited */
1547 /** wasDeleted inherited */
1550 * Move file to the new title
1552 * Move current, old version and all thumbnails
1553 * to the new filename. Old file is deleted.
1555 * Cache purging is done; checks for validity
1556 * and logging are caller's responsibility
1558 * @param Title $target New file name
1559 * @return FileRepoStatus
1561 function move( $target ) {
1562 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1563 return $this->readOnlyFatalStatus();
1566 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1567 $batch = new LocalFileMoveBatch( $this, $target );
1569 $this->lock(); // begin
1570 $batch->addCurrent();
1571 $archiveNames = $batch->addOlds();
1572 $status = $batch->execute();
1573 $this->unlock(); // done
1575 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1577 // Purge the source and target files...
1578 $oldTitleFile = wfLocalFile( $this->title );
1579 $newTitleFile = wfLocalFile( $target );
1580 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1581 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1582 $this->getRepo()->getMasterDB()->onTransactionIdle(
1583 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1584 $oldTitleFile->purgeEverything();
1585 foreach ( $archiveNames as $archiveName ) {
1586 $oldTitleFile->purgeOldThumbnails( $archiveName );
1588 $newTitleFile->purgeEverything();
1592 if ( $status->isOK() ) {
1593 // Now switch the object
1594 $this->title = $target;
1595 // Force regeneration of the name and hashpath
1596 unset( $this->name );
1597 unset( $this->hashPath );
1600 return $status;
1604 * Delete all versions of the file.
1606 * Moves the files into an archive directory (or deletes them)
1607 * and removes the database rows.
1609 * Cache purging is done; logging is caller's responsibility.
1611 * @param string $reason
1612 * @param bool $suppress
1613 * @param User|null $user
1614 * @return FileRepoStatus
1616 function delete( $reason, $suppress = false, $user = null ) {
1617 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1618 return $this->readOnlyFatalStatus();
1621 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1623 $this->lock(); // begin
1624 $batch->addCurrent();
1625 # Get old version relative paths
1626 $archiveNames = $batch->addOlds();
1627 $status = $batch->execute();
1628 $this->unlock(); // done
1630 if ( $status->isOK() ) {
1631 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => -1 ) ) );
1634 // Hack: the lock()/unlock() pair is nested in a transaction so the locking is not
1635 // tied to BEGIN/COMMIT. To avoid slow purges in the transaction, move them outside.
1636 $file = $this;
1637 $this->getRepo()->getMasterDB()->onTransactionIdle(
1638 function () use ( $file, $archiveNames ) {
1639 global $wgUseSquid;
1641 $file->purgeEverything();
1642 foreach ( $archiveNames as $archiveName ) {
1643 $file->purgeOldThumbnails( $archiveName );
1646 if ( $wgUseSquid ) {
1647 // Purge the squid
1648 $purgeUrls = array();
1649 foreach ( $archiveNames as $archiveName ) {
1650 $purgeUrls[] = $file->getArchiveUrl( $archiveName );
1652 SquidUpdate::purge( $purgeUrls );
1657 return $status;
1661 * Delete an old version of the file.
1663 * Moves the file into an archive directory (or deletes it)
1664 * and removes the database row.
1666 * Cache purging is done; logging is caller's responsibility.
1668 * @param string $archiveName
1669 * @param string $reason
1670 * @param bool $suppress
1671 * @param User|null $user
1672 * @throws MWException Exception on database or file store failure
1673 * @return FileRepoStatus
1675 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1676 global $wgUseSquid;
1677 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1678 return $this->readOnlyFatalStatus();
1681 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1683 $this->lock(); // begin
1684 $batch->addOld( $archiveName );
1685 $status = $batch->execute();
1686 $this->unlock(); // done
1688 $this->purgeOldThumbnails( $archiveName );
1689 if ( $status->isOK() ) {
1690 $this->purgeDescription();
1691 $this->purgeHistory();
1694 if ( $wgUseSquid ) {
1695 // Purge the squid
1696 SquidUpdate::purge( array( $this->getArchiveUrl( $archiveName ) ) );
1699 return $status;
1703 * Restore all or specified deleted revisions to the given file.
1704 * Permissions and logging are left to the caller.
1706 * May throw database exceptions on error.
1708 * @param array $versions Set of record ids of deleted items to restore,
1709 * or empty to restore all revisions.
1710 * @param bool $unsuppress
1711 * @return FileRepoStatus
1713 function restore( $versions = array(), $unsuppress = false ) {
1714 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1715 return $this->readOnlyFatalStatus();
1718 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1720 $this->lock(); // begin
1721 if ( !$versions ) {
1722 $batch->addAll();
1723 } else {
1724 $batch->addIds( $versions );
1726 $status = $batch->execute();
1727 if ( $status->isGood() ) {
1728 $cleanupStatus = $batch->cleanup();
1729 $cleanupStatus->successCount = 0;
1730 $cleanupStatus->failCount = 0;
1731 $status->merge( $cleanupStatus );
1733 $this->unlock(); // done
1735 return $status;
1738 /** isMultipage inherited */
1739 /** pageCount inherited */
1740 /** scaleHeight inherited */
1741 /** getImageSize inherited */
1744 * Get the URL of the file description page.
1745 * @return string
1747 function getDescriptionUrl() {
1748 return $this->title->getLocalURL();
1752 * Get the HTML text of the description page
1753 * This is not used by ImagePage for local files, since (among other things)
1754 * it skips the parser cache.
1756 * @param Language $lang What language to get description in (Optional)
1757 * @return bool|mixed
1759 function getDescriptionText( $lang = null ) {
1760 $revision = Revision::newFromTitle( $this->title, false, Revision::READ_NORMAL );
1761 if ( !$revision ) {
1762 return false;
1764 $content = $revision->getContent();
1765 if ( !$content ) {
1766 return false;
1768 $pout = $content->getParserOutput( $this->title, null, new ParserOptions( null, $lang ) );
1770 return $pout->getText();
1774 * @param int $audience
1775 * @param User $user
1776 * @return string
1778 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1779 $this->load();
1780 if ( $audience == self::FOR_PUBLIC && $this->isDeleted( self::DELETED_COMMENT ) ) {
1781 return '';
1782 } elseif ( $audience == self::FOR_THIS_USER
1783 && !$this->userCan( self::DELETED_COMMENT, $user )
1785 return '';
1786 } else {
1787 return $this->description;
1792 * @return bool|string
1794 function getTimestamp() {
1795 $this->load();
1797 return $this->timestamp;
1801 * @return string
1803 function getSha1() {
1804 $this->load();
1805 // Initialise now if necessary
1806 if ( $this->sha1 == '' && $this->fileExists ) {
1807 $this->lock(); // begin
1809 $this->sha1 = $this->repo->getFileSha1( $this->getPath() );
1810 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1811 $dbw = $this->repo->getMasterDB();
1812 $dbw->update( 'image',
1813 array( 'img_sha1' => $this->sha1 ),
1814 array( 'img_name' => $this->getName() ),
1815 __METHOD__ );
1816 $this->saveToCache();
1819 $this->unlock(); // done
1822 return $this->sha1;
1826 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1828 function isCacheable() {
1829 $this->load();
1831 // If extra data (metadata) was not loaded then it must have been large
1832 return $this->extraDataLoaded
1833 && strlen( serialize( $this->metadata ) ) <= self::CACHE_FIELD_MAX_LEN;
1837 * Start a transaction and lock the image for update
1838 * Increments a reference counter if the lock is already held
1839 * @throws MWException
1840 * @return bool True if the image exists, false otherwise
1842 function lock() {
1843 $dbw = $this->repo->getMasterDB();
1845 if ( !$this->locked ) {
1846 if ( !$dbw->trxLevel() ) {
1847 $dbw->begin( __METHOD__ );
1848 $this->lockedOwnTrx = true;
1850 $this->locked++;
1851 // Bug 54736: use simple lock to handle when the file does not exist.
1852 // SELECT FOR UPDATE only locks records not the gaps where there are none.
1853 $cache = wfGetMainCache();
1854 $key = $this->getCacheKey();
1855 if ( !$cache->lock( $key, 5 ) ) {
1856 throw new MWException( "Could not acquire lock for '{$this->getName()}.'" );
1858 $dbw->onTransactionIdle( function () use ( $cache, $key ) {
1859 $cache->unlock( $key ); // release on commit
1860 } );
1863 $this->markVolatile(); // file may change soon
1865 return $dbw->selectField( 'image', '1',
1866 array( 'img_name' => $this->getName() ), __METHOD__, array( 'FOR UPDATE' ) );
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 Wether 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() {
2227 wfProfileIn( __METHOD__ );
2229 $this->file->lock();
2230 // Leave private files alone
2231 $privateFiles = array();
2232 list( $oldRels, ) = $this->getOldRels();
2233 $dbw = $this->file->repo->getMasterDB();
2235 if ( !empty( $oldRels ) ) {
2236 $res = $dbw->select( 'oldimage',
2237 array( 'oi_archive_name' ),
2238 array( 'oi_name' => $this->file->getName(),
2239 'oi_archive_name' => array_keys( $oldRels ),
2240 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
2241 __METHOD__ );
2243 foreach ( $res as $row ) {
2244 $privateFiles[$row->oi_archive_name] = 1;
2247 // Prepare deletion batch
2248 $hashes = $this->getHashes();
2249 $this->deletionBatch = array();
2250 $ext = $this->file->getExtension();
2251 $dotExt = $ext === '' ? '' : ".$ext";
2253 foreach ( $this->srcRels as $name => $srcRel ) {
2254 // Skip files that have no hash (missing source).
2255 // Keep private files where they are.
2256 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
2257 $hash = $hashes[$name];
2258 $key = $hash . $dotExt;
2259 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
2260 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
2264 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
2265 // We acquire this lock by running the inserts now, before the file operations.
2267 // This potentially has poor lock contention characteristics -- an alternative
2268 // scheme would be to insert stub filearchive entries with no fa_name and commit
2269 // them in a separate transaction, then run the file ops, then update the fa_name fields.
2270 $this->doDBInserts();
2272 // Removes non-existent file from the batch, so we don't get errors.
2273 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
2275 // Execute the file deletion batch
2276 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
2278 if ( !$status->isGood() ) {
2279 $this->status->merge( $status );
2282 if ( !$this->status->isOK() ) {
2283 // Critical file deletion error
2284 // Roll back inserts, release lock and abort
2285 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
2286 $this->file->unlockAndRollback();
2287 wfProfileOut( __METHOD__ );
2289 return $this->status;
2292 // Delete image/oldimage rows
2293 $this->doDBDeletes();
2295 // Commit and return
2296 $this->file->unlock();
2297 wfProfileOut( __METHOD__ );
2299 return $this->status;
2303 * Removes non-existent files from a deletion batch.
2304 * @param array $batch
2305 * @return array
2307 function removeNonexistentFiles( $batch ) {
2308 $files = $newBatch = array();
2310 foreach ( $batch as $batchItem ) {
2311 list( $src, ) = $batchItem;
2312 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2315 $result = $this->file->repo->fileExistsBatch( $files );
2317 foreach ( $batch as $batchItem ) {
2318 if ( $result[$batchItem[0]] ) {
2319 $newBatch[] = $batchItem;
2323 return $newBatch;
2327 # ------------------------------------------------------------------------------
2330 * Helper class for file undeletion
2331 * @ingroup FileAbstraction
2333 class LocalFileRestoreBatch {
2334 /** @var LocalFile */
2335 private $file;
2337 /** @var array List of file IDs to restore */
2338 private $cleanupBatch;
2340 /** @var array List of file IDs to restore */
2341 private $ids;
2343 /** @var bool Add all revisions of the file */
2344 private $all;
2346 /** @var bool Wether to remove all settings for suppressed fields */
2347 private $unsuppress = false;
2350 * @param File $file
2351 * @param bool $unsuppress
2353 function __construct( File $file, $unsuppress = false ) {
2354 $this->file = $file;
2355 $this->cleanupBatch = $this->ids = array();
2356 $this->ids = array();
2357 $this->unsuppress = $unsuppress;
2361 * Add a file by ID
2363 function addId( $fa_id ) {
2364 $this->ids[] = $fa_id;
2368 * Add a whole lot of files by ID
2370 function addIds( $ids ) {
2371 $this->ids = array_merge( $this->ids, $ids );
2375 * Add all revisions of the file
2377 function addAll() {
2378 $this->all = true;
2382 * Run the transaction, except the cleanup batch.
2383 * The cleanup batch should be run in a separate transaction, because it locks different
2384 * rows and there's no need to keep the image row locked while it's acquiring those locks
2385 * The caller may have its own transaction open.
2386 * So we save the batch and let the caller call cleanup()
2387 * @return FileRepoStatus
2389 function execute() {
2390 global $wgLang;
2392 if ( !$this->all && !$this->ids ) {
2393 // Do nothing
2394 return $this->file->repo->newGood();
2397 $exists = $this->file->lock();
2398 $dbw = $this->file->repo->getMasterDB();
2399 $status = $this->file->repo->newGood();
2401 // Fetch all or selected archived revisions for the file,
2402 // sorted from the most recent to the oldest.
2403 $conditions = array( 'fa_name' => $this->file->getName() );
2405 if ( !$this->all ) {
2406 $conditions['fa_id'] = $this->ids;
2409 $result = $dbw->select(
2410 'filearchive',
2411 ArchivedFile::selectFields(),
2412 $conditions,
2413 __METHOD__,
2414 array( 'ORDER BY' => 'fa_timestamp DESC' )
2417 $idsPresent = array();
2418 $storeBatch = array();
2419 $insertBatch = array();
2420 $insertCurrent = false;
2421 $deleteIds = array();
2422 $first = true;
2423 $archiveNames = array();
2425 foreach ( $result as $row ) {
2426 $idsPresent[] = $row->fa_id;
2428 if ( $row->fa_name != $this->file->getName() ) {
2429 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
2430 $status->failCount++;
2431 continue;
2434 if ( $row->fa_storage_key == '' ) {
2435 // Revision was missing pre-deletion
2436 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
2437 $status->failCount++;
2438 continue;
2441 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) .
2442 $row->fa_storage_key;
2443 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2445 if ( isset( $row->fa_sha1 ) ) {
2446 $sha1 = $row->fa_sha1;
2447 } else {
2448 // old row, populate from key
2449 $sha1 = LocalRepo::getHashFromKey( $row->fa_storage_key );
2452 # Fix leading zero
2453 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2454 $sha1 = substr( $sha1, 1 );
2457 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
2458 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
2459 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
2460 || is_null( $row->fa_metadata )
2462 // Refresh our metadata
2463 // Required for a new current revision; nice for older ones too. :)
2464 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
2465 } else {
2466 $props = array(
2467 'minor_mime' => $row->fa_minor_mime,
2468 'major_mime' => $row->fa_major_mime,
2469 'media_type' => $row->fa_media_type,
2470 'metadata' => $row->fa_metadata
2474 if ( $first && !$exists ) {
2475 // This revision will be published as the new current version
2476 $destRel = $this->file->getRel();
2477 $insertCurrent = array(
2478 'img_name' => $row->fa_name,
2479 'img_size' => $row->fa_size,
2480 'img_width' => $row->fa_width,
2481 'img_height' => $row->fa_height,
2482 'img_metadata' => $props['metadata'],
2483 'img_bits' => $row->fa_bits,
2484 'img_media_type' => $props['media_type'],
2485 'img_major_mime' => $props['major_mime'],
2486 'img_minor_mime' => $props['minor_mime'],
2487 'img_description' => $row->fa_description,
2488 'img_user' => $row->fa_user,
2489 'img_user_text' => $row->fa_user_text,
2490 'img_timestamp' => $row->fa_timestamp,
2491 'img_sha1' => $sha1
2494 // The live (current) version cannot be hidden!
2495 if ( !$this->unsuppress && $row->fa_deleted ) {
2496 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2497 $this->cleanupBatch[] = $row->fa_storage_key;
2499 } else {
2500 $archiveName = $row->fa_archive_name;
2502 if ( $archiveName == '' ) {
2503 // This was originally a current version; we
2504 // have to devise a new archive name for it.
2505 // Format is <timestamp of archiving>!<name>
2506 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
2508 do {
2509 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
2510 $timestamp++;
2511 } while ( isset( $archiveNames[$archiveName] ) );
2514 $archiveNames[$archiveName] = true;
2515 $destRel = $this->file->getArchiveRel( $archiveName );
2516 $insertBatch[] = array(
2517 'oi_name' => $row->fa_name,
2518 'oi_archive_name' => $archiveName,
2519 'oi_size' => $row->fa_size,
2520 'oi_width' => $row->fa_width,
2521 'oi_height' => $row->fa_height,
2522 'oi_bits' => $row->fa_bits,
2523 'oi_description' => $row->fa_description,
2524 'oi_user' => $row->fa_user,
2525 'oi_user_text' => $row->fa_user_text,
2526 'oi_timestamp' => $row->fa_timestamp,
2527 'oi_metadata' => $props['metadata'],
2528 'oi_media_type' => $props['media_type'],
2529 'oi_major_mime' => $props['major_mime'],
2530 'oi_minor_mime' => $props['minor_mime'],
2531 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
2532 'oi_sha1' => $sha1 );
2535 $deleteIds[] = $row->fa_id;
2537 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
2538 // private files can stay where they are
2539 $status->successCount++;
2540 } else {
2541 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2542 $this->cleanupBatch[] = $row->fa_storage_key;
2545 $first = false;
2548 unset( $result );
2550 // Add a warning to the status object for missing IDs
2551 $missingIds = array_diff( $this->ids, $idsPresent );
2553 foreach ( $missingIds as $id ) {
2554 $status->error( 'undelete-missing-filearchive', $id );
2557 // Remove missing files from batch, so we don't get errors when undeleting them
2558 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2560 // Run the store batch
2561 // Use the OVERWRITE_SAME flag to smooth over a common error
2562 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
2563 $status->merge( $storeStatus );
2565 if ( !$status->isGood() ) {
2566 // Even if some files could be copied, fail entirely as that is the
2567 // easiest thing to do without data loss
2568 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2569 $status->ok = false;
2570 $this->file->unlock();
2572 return $status;
2575 // Run the DB updates
2576 // Because we have locked the image row, key conflicts should be rare.
2577 // If they do occur, we can roll back the transaction at this time with
2578 // no data loss, but leaving unregistered files scattered throughout the
2579 // public zone.
2580 // This is not ideal, which is why it's important to lock the image row.
2581 if ( $insertCurrent ) {
2582 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
2585 if ( $insertBatch ) {
2586 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
2589 if ( $deleteIds ) {
2590 $dbw->delete( 'filearchive',
2591 array( 'fa_id' => $deleteIds ),
2592 __METHOD__ );
2595 // If store batch is empty (all files are missing), deletion is to be considered successful
2596 if ( $status->successCount > 0 || !$storeBatch ) {
2597 if ( !$exists ) {
2598 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
2600 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array( 'images' => 1 ) ) );
2602 $this->file->purgeEverything();
2603 } else {
2604 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
2605 $this->file->purgeDescription();
2606 $this->file->purgeHistory();
2610 $this->file->unlock();
2612 return $status;
2616 * Removes non-existent files from a store batch.
2617 * @param array $triplets
2618 * @return array
2620 function removeNonexistentFiles( $triplets ) {
2621 $files = $filteredTriplets = array();
2622 foreach ( $triplets as $file ) {
2623 $files[$file[0]] = $file[0];
2626 $result = $this->file->repo->fileExistsBatch( $files );
2628 foreach ( $triplets as $file ) {
2629 if ( $result[$file[0]] ) {
2630 $filteredTriplets[] = $file;
2634 return $filteredTriplets;
2638 * Removes non-existent files from a cleanup batch.
2639 * @param array $batch
2640 * @return array
2642 function removeNonexistentFromCleanup( $batch ) {
2643 $files = $newBatch = array();
2644 $repo = $this->file->repo;
2646 foreach ( $batch as $file ) {
2647 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2648 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2651 $result = $repo->fileExistsBatch( $files );
2653 foreach ( $batch as $file ) {
2654 if ( $result[$file] ) {
2655 $newBatch[] = $file;
2659 return $newBatch;
2663 * Delete unused files in the deleted zone.
2664 * This should be called from outside the transaction in which execute() was called.
2665 * @return FileRepoStatus
2667 function cleanup() {
2668 if ( !$this->cleanupBatch ) {
2669 return $this->file->repo->newGood();
2672 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
2674 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
2676 return $status;
2680 * Cleanup a failed batch. The batch was only partially successful, so
2681 * rollback by removing all items that were succesfully copied.
2683 * @param Status $storeStatus
2684 * @param array $storeBatch
2686 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2687 $cleanupBatch = array();
2689 foreach ( $storeStatus->success as $i => $success ) {
2690 // Check if this item of the batch was successfully copied
2691 if ( $success ) {
2692 // Item was successfully copied and needs to be removed again
2693 // Extract ($dstZone, $dstRel) from the batch
2694 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2697 $this->file->repo->cleanupBatch( $cleanupBatch );
2701 # ------------------------------------------------------------------------------
2704 * Helper class for file movement
2705 * @ingroup FileAbstraction
2707 class LocalFileMoveBatch {
2708 /** @var LocalFile */
2709 protected $file;
2711 /** @var Title */
2712 protected $target;
2714 protected $cur;
2716 protected $olds;
2718 protected $oldCount;
2720 protected $archive;
2722 /** @var DatabaseBase */
2723 protected $db;
2726 * @param File $file
2727 * @param Title $target
2729 function __construct( File $file, Title $target ) {
2730 $this->file = $file;
2731 $this->target = $target;
2732 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
2733 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
2734 $this->oldName = $this->file->getName();
2735 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
2736 $this->oldRel = $this->oldHash . $this->oldName;
2737 $this->newRel = $this->newHash . $this->newName;
2738 $this->db = $file->getRepo()->getMasterDb();
2742 * Add the current image to the batch
2744 function addCurrent() {
2745 $this->cur = array( $this->oldRel, $this->newRel );
2749 * Add the old versions of the image to the batch
2750 * @return array List of archive names from old versions
2752 function addOlds() {
2753 $archiveBase = 'archive';
2754 $this->olds = array();
2755 $this->oldCount = 0;
2756 $archiveNames = array();
2758 $result = $this->db->select( 'oldimage',
2759 array( 'oi_archive_name', 'oi_deleted' ),
2760 array( 'oi_name' => $this->oldName ),
2761 __METHOD__
2764 foreach ( $result as $row ) {
2765 $archiveNames[] = $row->oi_archive_name;
2766 $oldName = $row->oi_archive_name;
2767 $bits = explode( '!', $oldName, 2 );
2769 if ( count( $bits ) != 2 ) {
2770 wfDebug( "Old file name missing !: '$oldName' \n" );
2771 continue;
2774 list( $timestamp, $filename ) = $bits;
2776 if ( $this->oldName != $filename ) {
2777 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2778 continue;
2781 $this->oldCount++;
2783 // Do we want to add those to oldCount?
2784 if ( $row->oi_deleted & File::DELETED_FILE ) {
2785 continue;
2788 $this->olds[] = array(
2789 "{$archiveBase}/{$this->oldHash}{$oldName}",
2790 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2794 return $archiveNames;
2798 * Perform the move.
2799 * @return FileRepoStatus
2801 function execute() {
2802 $repo = $this->file->repo;
2803 $status = $repo->newGood();
2805 $triplets = $this->getMoveTriplets();
2806 $triplets = $this->removeNonexistentFiles( $triplets );
2807 $destFile = wfLocalFile( $this->target );
2809 $this->file->lock(); // begin
2810 $destFile->lock(); // quickly fail if destination is not available
2811 // Rename the file versions metadata in the DB.
2812 // This implicitly locks the destination file, which avoids race conditions.
2813 // If we moved the files from A -> C before DB updates, another process could
2814 // move files from B -> C at this point, causing storeBatch() to fail and thus
2815 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2816 $statusDb = $this->doDBUpdates();
2817 if ( !$statusDb->isGood() ) {
2818 $this->file->unlockAndRollback();
2819 $statusDb->ok = false;
2821 return $statusDb;
2823 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2824 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2826 // Copy the files into their new location.
2827 // If a prior process fataled copying or cleaning up files we tolerate any
2828 // of the existing files if they are identical to the ones being stored.
2829 $statusMove = $repo->storeBatch( $triplets, FileRepo::OVERWRITE_SAME );
2830 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2831 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2832 if ( !$statusMove->isGood() ) {
2833 // Delete any files copied over (while the destination is still locked)
2834 $this->cleanupTarget( $triplets );
2835 $this->file->unlockAndRollback(); // unlocks the destination
2836 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2837 $statusMove->ok = false;
2839 return $statusMove;
2841 $destFile->unlock();
2842 $this->file->unlock(); // done
2844 // Everything went ok, remove the source files
2845 $this->cleanupSource( $triplets );
2847 $status->merge( $statusDb );
2848 $status->merge( $statusMove );
2850 return $status;
2854 * Do the database updates and return a new FileRepoStatus indicating how
2855 * many rows where updated.
2857 * @return FileRepoStatus
2859 function doDBUpdates() {
2860 $repo = $this->file->repo;
2861 $status = $repo->newGood();
2862 $dbw = $this->db;
2864 // Update current image
2865 $dbw->update(
2866 'image',
2867 array( 'img_name' => $this->newName ),
2868 array( 'img_name' => $this->oldName ),
2869 __METHOD__
2872 if ( $dbw->affectedRows() ) {
2873 $status->successCount++;
2874 } else {
2875 $status->failCount++;
2876 $status->fatal( 'imageinvalidfilename' );
2878 return $status;
2881 // Update old images
2882 $dbw->update(
2883 'oldimage',
2884 array(
2885 'oi_name' => $this->newName,
2886 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2887 $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2889 array( 'oi_name' => $this->oldName ),
2890 __METHOD__
2893 $affected = $dbw->affectedRows();
2894 $total = $this->oldCount;
2895 $status->successCount += $affected;
2896 // Bug 34934: $total is based on files that actually exist.
2897 // There may be more DB rows than such files, in which case $affected
2898 // can be greater than $total. We use max() to avoid negatives here.
2899 $status->failCount += max( 0, $total - $affected );
2900 if ( $status->failCount ) {
2901 $status->error( 'imageinvalidfilename' );
2904 return $status;
2908 * Generate triplets for FileRepo::storeBatch().
2909 * @return array
2911 function getMoveTriplets() {
2912 $moves = array_merge( array( $this->cur ), $this->olds );
2913 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2915 foreach ( $moves as $move ) {
2916 // $move: (oldRelativePath, newRelativePath)
2917 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2918 $triplets[] = array( $srcUrl, 'public', $move[1] );
2919 wfDebugLog(
2920 'imagemove',
2921 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
2925 return $triplets;
2929 * Removes non-existent files from move batch.
2930 * @param array $triplets
2931 * @return array
2933 function removeNonexistentFiles( $triplets ) {
2934 $files = array();
2936 foreach ( $triplets as $file ) {
2937 $files[$file[0]] = $file[0];
2940 $result = $this->file->repo->fileExistsBatch( $files );
2941 $filteredTriplets = array();
2943 foreach ( $triplets as $file ) {
2944 if ( $result[$file[0]] ) {
2945 $filteredTriplets[] = $file;
2946 } else {
2947 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2951 return $filteredTriplets;
2955 * Cleanup a partially moved array of triplets by deleting the target
2956 * files. Called if something went wrong half way.
2958 function cleanupTarget( $triplets ) {
2959 // Create dest pairs from the triplets
2960 $pairs = array();
2961 foreach ( $triplets as $triplet ) {
2962 // $triplet: (old source virtual URL, dst zone, dest rel)
2963 $pairs[] = array( $triplet[1], $triplet[2] );
2966 $this->file->repo->cleanupBatch( $pairs );
2970 * Cleanup a fully moved array of triplets by deleting the source files.
2971 * Called at the end of the move process if everything else went ok.
2973 function cleanupSource( $triplets ) {
2974 // Create source file names from the triplets
2975 $files = array();
2976 foreach ( $triplets as $triplet ) {
2977 $files[] = $triplet[0];
2980 $this->file->repo->cleanupBatch( $files );