3 * Local file in the wiki's own database
6 * @ingroup FileAbstraction
10 * Bump this number when serialized cache records may be incompatible.
12 define( 'MW_FILE_VERSION', 8 );
15 * Class to represent a local file in the wiki's own database
17 * Provides methods to retrieve paths (physical, logical, URL),
18 * to generate image thumbnails or for uploading.
20 * Note that only the repo object knows what its file class is called. You should
21 * never name a file class explictly outside of the repo class. Instead use the
22 * repo's factory functions to generate file objects, for example:
24 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
26 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
29 * @ingroup FileAbstraction
31 class LocalFile
extends File
{
36 $fileExists, # does the file exist on disk? (loadFromXxx)
37 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
38 $historyRes, # result of the query for the file's history (nextHistoryLine)
41 $bits, # --- returned by getimagesize (loadFromXxx)
43 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
44 $mime, # MIME type, determined by MimeMagic::guessMimeType
45 $major_mime, # Major mime type
46 $minor_mime, # Minor mime type
47 $size, # Size in bytes (loadFromXxx)
48 $metadata, # Handler-specific metadata
49 $timestamp, # Upload timestamp
50 $sha1, # SHA-1 base 36 content hash
51 $user, $user_text, # User, who uploaded the file
52 $description, # Description of current revision of the file
53 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
54 $upgraded, # Whether the row was upgraded on load
55 $locked, # True if the image row is locked
56 $missing, # True if file is not present in file system. Not to be cached in memcached
57 $deleted; # Bitfield akin to rev_deleted
61 protected $repoClass = 'LocalRepo';
64 * Create a LocalFile from a title
65 * Do not call this except from inside a repo class.
67 * Note: $unused param is only here to avoid an E_STRICT
75 static function newFromTitle( $title, $repo, $unused = null ) {
76 return new self( $title, $repo );
80 * Create a LocalFile from a title
81 * Do not call this except from inside a repo class.
88 static function newFromRow( $row, $repo ) {
89 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
90 $file = new self( $title, $repo );
91 $file->loadFromRow( $row );
97 * Create a LocalFile from a SHA-1 key
98 * Do not call this except from inside a repo class.
100 * @param $sha1 string base-36 SHA-1
101 * @param $repo LocalRepo
102 * @param string|bool $timestamp MW_timestamp (optional)
104 * @return bool|LocalFile
106 static function newFromKey( $sha1, $repo, $timestamp = false ) {
107 $dbr = $repo->getSlaveDB();
109 $conds = array( 'img_sha1' => $sha1 );
111 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
114 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
116 return self
::newFromRow( $row, $repo );
123 * Fields in the image table
126 static function selectFields() {
147 * Do not call this except from inside a repo class.
149 function __construct( $title, $repo ) {
150 parent
::__construct( $title, $repo );
152 $this->metadata
= '';
153 $this->historyLine
= 0;
154 $this->historyRes
= null;
155 $this->dataLoaded
= false;
157 $this->assertRepoDefined();
158 $this->assertTitleDefined();
162 * Get the memcached key for the main data for this file, or false if
163 * there is no access to the shared cache.
166 function getCacheKey() {
167 $hashedName = md5( $this->getName() );
169 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
173 * Try to load file metadata from memcached. Returns true on success.
176 function loadFromCache() {
179 wfProfileIn( __METHOD__
);
180 $this->dataLoaded
= false;
181 $key = $this->getCacheKey();
184 wfProfileOut( __METHOD__
);
188 $cachedValues = $wgMemc->get( $key );
190 // Check if the key existed and belongs to this version of MediaWiki
191 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
192 wfDebug( "Pulling file metadata from cache key $key\n" );
193 $this->fileExists
= $cachedValues['fileExists'];
194 if ( $this->fileExists
) {
195 $this->setProps( $cachedValues );
197 $this->dataLoaded
= true;
200 if ( $this->dataLoaded
) {
201 wfIncrStats( 'image_cache_hit' );
203 wfIncrStats( 'image_cache_miss' );
206 wfProfileOut( __METHOD__
);
207 return $this->dataLoaded
;
211 * Save the file metadata to memcached
213 function saveToCache() {
217 $key = $this->getCacheKey();
223 $fields = $this->getCacheFields( '' );
224 $cache = array( 'version' => MW_FILE_VERSION
);
225 $cache['fileExists'] = $this->fileExists
;
227 if ( $this->fileExists
) {
228 foreach ( $fields as $field ) {
229 $cache[$field] = $this->$field;
233 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
237 * Load metadata from the file itself
239 function loadFromFile() {
240 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
241 $this->setProps( $props );
244 function getCacheFields( $prefix = 'img_' ) {
245 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
246 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
247 static $results = array();
249 if ( $prefix == '' ) {
253 if ( !isset( $results[$prefix] ) ) {
254 $prefixedFields = array();
255 foreach ( $fields as $field ) {
256 $prefixedFields[] = $prefix . $field;
258 $results[$prefix] = $prefixedFields;
261 return $results[$prefix];
265 * Load file metadata from the DB
267 function loadFromDB() {
268 # Polymorphic function name to distinguish foreign and local fetches
269 $fname = get_class( $this ) . '::' . __FUNCTION__
;
270 wfProfileIn( $fname );
272 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
273 $this->dataLoaded
= true;
275 $dbr = $this->repo
->getMasterDB();
277 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
278 array( 'img_name' => $this->getName() ), $fname );
281 $this->loadFromRow( $row );
283 $this->fileExists
= false;
286 wfProfileOut( $fname );
290 * Decode a row from the database (either object or array) to an array
291 * with timestamps and MIME types decoded, and the field prefix removed.
294 function decodeRow( $row, $prefix = 'img_' ) {
295 $array = (array)$row;
296 $prefixLength = strlen( $prefix );
298 // Sanity check prefix once
299 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
300 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
305 foreach ( $array as $name => $value ) {
306 $decoded[substr( $name, $prefixLength )] = $value;
309 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
311 if ( empty( $decoded['major_mime'] ) ) {
312 $decoded['mime'] = 'unknown/unknown';
314 if ( !$decoded['minor_mime'] ) {
315 $decoded['minor_mime'] = 'unknown';
317 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
320 # Trim zero padding from char/binary field
321 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
327 * Load file metadata from a DB result row
329 function loadFromRow( $row, $prefix = 'img_' ) {
330 $this->dataLoaded
= true;
331 $array = $this->decodeRow( $row, $prefix );
333 foreach ( $array as $name => $value ) {
334 $this->$name = $value;
337 $this->fileExists
= true;
338 $this->maybeUpgradeRow();
342 * Load file metadata from cache or DB, unless already loaded
345 if ( !$this->dataLoaded
) {
346 if ( !$this->loadFromCache() ) {
348 $this->saveToCache();
350 $this->dataLoaded
= true;
355 * Upgrade a row if it needs it
357 function maybeUpgradeRow() {
358 global $wgUpdateCompatibleMetadata;
359 if ( wfReadOnly() ) {
363 if ( is_null( $this->media_type
) ||
364 $this->mime
== 'image/svg'
367 $this->upgraded
= true;
369 $handler = $this->getHandler();
371 $validity = $handler->isMetadataValid( $this, $this->metadata
);
372 if ( $validity === MediaHandler
::METADATA_BAD
373 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
376 $this->upgraded
= true;
382 function getUpgraded() {
383 return $this->upgraded
;
387 * Fix assorted version-related problems with the image row by reloading it from the file
389 function upgradeRow() {
390 wfProfileIn( __METHOD__
);
392 $this->lock(); // begin
394 $this->loadFromFile();
396 # Don't destroy file info of missing files
397 if ( !$this->fileExists
) {
398 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
399 wfProfileOut( __METHOD__
);
403 $dbw = $this->repo
->getMasterDB();
404 list( $major, $minor ) = self
::splitMime( $this->mime
);
406 if ( wfReadOnly() ) {
407 wfProfileOut( __METHOD__
);
410 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
412 $dbw->update( 'image',
414 'img_width' => $this->width
,
415 'img_height' => $this->height
,
416 'img_bits' => $this->bits
,
417 'img_media_type' => $this->media_type
,
418 'img_major_mime' => $major,
419 'img_minor_mime' => $minor,
420 'img_metadata' => $this->metadata
,
421 'img_sha1' => $this->sha1
,
423 array( 'img_name' => $this->getName() ),
427 $this->saveToCache();
429 $this->unlock(); // done
431 wfProfileOut( __METHOD__
);
435 * Set properties in this object to be equal to those given in the
436 * associative array $info. Only cacheable fields can be set.
438 * If 'mime' is given, it will be split into major_mime/minor_mime.
439 * If major_mime/minor_mime are given, $this->mime will also be set.
441 function setProps( $info ) {
442 $this->dataLoaded
= true;
443 $fields = $this->getCacheFields( '' );
444 $fields[] = 'fileExists';
446 foreach ( $fields as $field ) {
447 if ( isset( $info[$field] ) ) {
448 $this->$field = $info[$field];
452 // Fix up mime fields
453 if ( isset( $info['major_mime'] ) ) {
454 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
455 } elseif ( isset( $info['mime'] ) ) {
456 $this->mime
= $info['mime'];
457 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
461 /** splitMime inherited */
462 /** getName inherited */
463 /** getTitle inherited */
464 /** getURL inherited */
465 /** getViewURL inherited */
466 /** getPath inherited */
467 /** isVisible inhereted */
469 function isMissing() {
470 if ( $this->missing
=== null ) {
471 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl(), FileRepo
::FILES_ONLY
);
472 $this->missing
= !$fileExists;
474 return $this->missing
;
478 * Return the width of the image
480 * Returns false on error
483 public function getWidth( $page = 1 ) {
486 if ( $this->isMultipage() ) {
487 $dim = $this->getHandler()->getPageDimensions( $this, $page );
489 return $dim['width'];
499 * Return the height of the image
501 * Returns false on error
504 public function getHeight( $page = 1 ) {
507 if ( $this->isMultipage() ) {
508 $dim = $this->getHandler()->getPageDimensions( $this, $page );
510 return $dim['height'];
515 return $this->height
;
520 * Returns ID or name of user who uploaded the file
522 * @param $type string 'text' or 'id'
524 function getUser( $type = 'text' ) {
527 if ( $type == 'text' ) {
528 return $this->user_text
;
529 } elseif ( $type == 'id' ) {
535 * Get handler-specific metadata
538 function getMetadata() {
540 return $this->metadata
;
543 function getBitDepth() {
549 * Return the size of the image file, in bytes
551 public function getSize() {
557 * Returns the mime type of the file.
559 function getMimeType() {
565 * Return the type of the media in the file.
566 * Use the value returned by this function with the MEDIATYPE_xxx constants.
568 function getMediaType() {
570 return $this->media_type
;
573 /** canRender inherited */
574 /** mustRender inherited */
575 /** allowInlineDisplay inherited */
576 /** isSafeFile inherited */
577 /** isTrustedFile inherited */
580 * Returns true if the file exists on disk.
581 * @return boolean Whether file exist on disk.
583 public function exists() {
585 return $this->fileExists
;
588 /** getTransformScript inherited */
589 /** getUnscaledThumb inherited */
590 /** thumbName inherited */
591 /** createThumb inherited */
592 /** transform inherited */
595 * Fix thumbnail files from 1.4 or before, with extreme prejudice
597 function migrateThumbFile( $thumbName ) {
598 $thumbDir = $this->getThumbPath();
600 /* Old code for bug 2532
601 $thumbPath = "$thumbDir/$thumbName";
602 if ( is_dir( $thumbPath ) ) {
603 // Directory where file should be
604 // This happened occasionally due to broken migration code in 1.5
605 // Rename to broken-*
606 for ( $i = 0; $i < 100 ; $i++ ) {
607 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
608 if ( !file_exists( $broken ) ) {
609 rename( $thumbPath, $broken );
613 // Doesn't exist anymore
618 if ( $this->repo
->fileExists( $thumbDir, FileRepo
::FILES_ONLY
) ) {
619 // Delete file where directory should be
620 $this->repo
->cleanupBatch( array( $thumbDir ) );
624 /** getHandler inherited */
625 /** iconThumb inherited */
626 /** getLastError inherited */
629 * Get all thumbnail names previously generated for this file
630 * @param $archiveName string|bool Name of an archive file, default false
631 * @return array first element is the base dir, then files in that base dir.
633 function getThumbnails( $archiveName = false ) {
636 if ( $archiveName ) {
637 $dir = $this->getArchiveThumbPath( $archiveName );
639 $dir = $this->getThumbPath();
642 $backend = $this->repo
->getBackend();
643 $files = array( $dir );
644 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
645 foreach ( $iterator as $file ) {
653 * Refresh metadata in memcached, but don't touch thumbnails or squid
655 function purgeMetadataCache() {
657 $this->saveToCache();
658 $this->purgeHistory();
662 * Purge the shared history (OldLocalFile) cache
664 function purgeHistory() {
667 $hashedName = md5( $this->getName() );
668 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
670 // Must purge thumbnails for old versions too! bug 30192
671 foreach( $this->getHistory() as $oldFile ) {
672 $oldFile->purgeThumbnails();
676 $wgMemc->delete( $oldKey );
681 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
683 function purgeCache( $options = array() ) {
684 // Refresh metadata cache
685 $this->purgeMetadataCache();
688 $this->purgeThumbnails( $options );
690 // Purge squid cache for this file
691 SquidUpdate
::purge( array( $this->getURL() ) );
695 * Delete cached transformed files for an archived version only.
696 * @param $archiveName string name of the archived file
698 function purgeOldThumbnails( $archiveName ) {
700 // Get a list of old thumbnails and URLs
701 $files = $this->getThumbnails( $archiveName );
702 $dir = array_shift( $files );
703 $this->purgeThumbList( $dir, $files );
705 // Purge any custom thumbnail caches
706 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
711 foreach( $files as $file ) {
712 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
714 SquidUpdate
::purge( $urls );
719 * Delete cached transformed files for the current version only.
721 function purgeThumbnails( $options = array() ) {
725 $files = $this->getThumbnails();
727 // Give media handler a chance to filter the purge list
728 if ( !empty( $options['forThumbRefresh'] ) ) {
729 $handler = $this->getHandler();
731 $handler->filterThumbnailPurgeList( $files, $options );
735 $dir = array_shift( $files );
736 $this->purgeThumbList( $dir, $files );
738 // Purge any custom thumbnail caches
739 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
744 foreach( $files as $file ) {
745 $urls[] = $this->getThumbUrl( $file );
747 SquidUpdate
::purge( $urls );
752 * Delete a list of thumbnails visible at urls
753 * @param $dir string base dir of the files.
754 * @param $files array of strings: relative filenames (to $dir)
756 protected function purgeThumbList( $dir, $files ) {
757 $fileListDebug = strtr(
758 var_export( $files, true ),
761 wfDebug( __METHOD__
. ": $fileListDebug\n" );
763 $purgeList = array();
764 foreach ( $files as $file ) {
765 # Check that the base file name is part of the thumb name
766 # This is a basic sanity check to avoid erasing unrelated directories
767 if ( strpos( $file, $this->getName() ) !== false ) {
768 $purgeList[] = "{$dir}/{$file}";
772 # Delete the thumbnails
773 $this->repo
->cleanupBatch( $purgeList, FileRepo
::SKIP_LOCKING
);
774 # Clear out the thumbnail directory if empty
775 $this->repo
->getBackend()->clean( array( 'dir' => $dir ) );
778 /** purgeDescription inherited */
779 /** purgeEverything inherited */
781 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
782 $dbr = $this->repo
->getSlaveDB();
783 $tables = array( 'oldimage' );
784 $fields = OldLocalFile
::selectFields();
785 $conds = $opts = $join_conds = array();
786 $eq = $inc ?
'=' : '';
787 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
790 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
794 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
798 $opts['LIMIT'] = $limit;
801 // Search backwards for time > x queries
802 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
803 $opts['ORDER BY'] = "oi_timestamp $order";
804 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
806 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
807 &$conds, &$opts, &$join_conds ) );
809 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
812 foreach ( $res as $row ) {
813 if ( $this->repo
->oldFileFromRowFactory
) {
814 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
816 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
820 if ( $order == 'ASC' ) {
821 $r = array_reverse( $r ); // make sure it ends up descending
828 * Return the history of this file, line by line.
829 * starts with current version, then old versions.
830 * uses $this->historyLine to check which line to return:
831 * 0 return line for current version
832 * 1 query for old versions, return first one
833 * 2, ... return next old version from above query
836 public function nextHistoryLine() {
837 # Polymorphic function name to distinguish foreign and local fetches
838 $fname = get_class( $this ) . '::' . __FUNCTION__
;
840 $dbr = $this->repo
->getSlaveDB();
842 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
843 $this->historyRes
= $dbr->select( 'image',
846 "'' AS oi_archive_name",
850 array( 'img_name' => $this->title
->getDBkey() ),
854 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
855 $this->historyRes
= null;
858 } elseif ( $this->historyLine
== 1 ) {
859 $this->historyRes
= $dbr->select( 'oldimage', '*',
860 array( 'oi_name' => $this->title
->getDBkey() ),
862 array( 'ORDER BY' => 'oi_timestamp DESC' )
865 $this->historyLine ++
;
867 return $dbr->fetchObject( $this->historyRes
);
871 * Reset the history pointer to the first element of the history
873 public function resetHistory() {
874 $this->historyLine
= 0;
876 if ( !is_null( $this->historyRes
) ) {
877 $this->historyRes
= null;
881 /** getHashPath inherited */
882 /** getRel inherited */
883 /** getUrlRel inherited */
884 /** getArchiveRel inherited */
885 /** getArchivePath inherited */
886 /** getThumbPath inherited */
887 /** getArchiveUrl inherited */
888 /** getThumbUrl inherited */
889 /** getArchiveVirtualUrl inherited */
890 /** getThumbVirtualUrl inherited */
891 /** isHashed inherited */
894 * Upload a file and record it in the DB
895 * @param $srcPath String: source storage path or virtual URL
896 * @param $comment String: upload description
897 * @param $pageText String: text to use for the new description page,
898 * if a new description page is created
899 * @param $flags Integer: flags for publish()
900 * @param $props Array: File properties, if known. This can be used to reduce the
901 * upload time when uploading virtual URLs for which the file info
903 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
904 * @param $user Mixed: User object or null to use $wgUser
906 * @return FileRepoStatus object. On success, the value member contains the
907 * archive name, or an empty string if it was a new file.
909 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
912 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
913 return $this->readOnlyFatalStatus();
916 // truncate nicely or the DB will do it for us
917 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
918 $comment = $wgContLang->truncate( $comment, 255 );
919 $this->lock(); // begin
920 $status = $this->publish( $srcPath, $flags );
922 if ( $status->successCount
> 0 ) {
923 # Essentially we are displacing any existing current file and saving
924 # a new current file at the old location. If just the first succeeded,
925 # we still need to displace the current DB entry and put in a new one.
926 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
927 $status->fatal( 'filenotfound', $srcPath );
931 $this->unlock(); // done
937 * Record a file upload in the upload log and the image table
940 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
941 $watch = false, $timestamp = false )
943 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
945 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
951 $wgUser->addWatch( $this->getTitle() );
957 * Record a file upload in the upload log and the image table
960 function recordUpload2(
961 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
963 if ( is_null( $user ) ) {
968 $dbw = $this->repo
->getMasterDB();
969 $dbw->begin( __METHOD__
);
972 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
975 if ( $timestamp === false ) {
976 $timestamp = $dbw->timestamp();
979 $props['description'] = $comment;
980 $props['user'] = $user->getId();
981 $props['user_text'] = $user->getName();
982 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
983 $this->setProps( $props );
986 $this->purgeThumbnails();
988 # The file is already on its final location, remove it from the squid cache
989 SquidUpdate
::purge( array( $this->getURL() ) );
991 # Fail now if the file isn't there
992 if ( !$this->fileExists
) {
993 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
999 # Test to see if the row exists using INSERT IGNORE
1000 # This avoids race conditions by locking the row until the commit, and also
1001 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1002 $dbw->insert( 'image',
1004 'img_name' => $this->getName(),
1005 'img_size' => $this->size
,
1006 'img_width' => intval( $this->width
),
1007 'img_height' => intval( $this->height
),
1008 'img_bits' => $this->bits
,
1009 'img_media_type' => $this->media_type
,
1010 'img_major_mime' => $this->major_mime
,
1011 'img_minor_mime' => $this->minor_mime
,
1012 'img_timestamp' => $timestamp,
1013 'img_description' => $comment,
1014 'img_user' => $user->getId(),
1015 'img_user_text' => $user->getName(),
1016 'img_metadata' => $this->metadata
,
1017 'img_sha1' => $this->sha1
1023 if ( $dbw->affectedRows() == 0 ) {
1024 # (bug 34993) Note: $oldver can be empty here, if the previous
1025 # version of the file was broken. Allow registration of the new
1026 # version to continue anyway, because that's better than having
1027 # an image that's not fixable by user operations.
1030 # Collision, this is an update of a file
1031 # Insert previous contents into oldimage
1032 $dbw->insertSelect( 'oldimage', 'image',
1034 'oi_name' => 'img_name',
1035 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1036 'oi_size' => 'img_size',
1037 'oi_width' => 'img_width',
1038 'oi_height' => 'img_height',
1039 'oi_bits' => 'img_bits',
1040 'oi_timestamp' => 'img_timestamp',
1041 'oi_description' => 'img_description',
1042 'oi_user' => 'img_user',
1043 'oi_user_text' => 'img_user_text',
1044 'oi_metadata' => 'img_metadata',
1045 'oi_media_type' => 'img_media_type',
1046 'oi_major_mime' => 'img_major_mime',
1047 'oi_minor_mime' => 'img_minor_mime',
1048 'oi_sha1' => 'img_sha1'
1050 array( 'img_name' => $this->getName() ),
1054 # Update the current image row
1055 $dbw->update( 'image',
1057 'img_size' => $this->size
,
1058 'img_width' => intval( $this->width
),
1059 'img_height' => intval( $this->height
),
1060 'img_bits' => $this->bits
,
1061 'img_media_type' => $this->media_type
,
1062 'img_major_mime' => $this->major_mime
,
1063 'img_minor_mime' => $this->minor_mime
,
1064 'img_timestamp' => $timestamp,
1065 'img_description' => $comment,
1066 'img_user' => $user->getId(),
1067 'img_user_text' => $user->getName(),
1068 'img_metadata' => $this->metadata
,
1069 'img_sha1' => $this->sha1
1071 array( 'img_name' => $this->getName() ),
1075 # This is a new file
1076 # Update the image count
1077 $dbw->begin( __METHOD__
);
1080 array( 'ss_images = ss_images+1' ),
1084 $dbw->commit( __METHOD__
);
1087 $descTitle = $this->getTitle();
1088 $wikiPage = new WikiFilePage( $descTitle );
1089 $wikiPage->setFile( $this );
1092 $log = new LogPage( 'upload' );
1093 $action = $reupload ?
'overwrite' : 'upload';
1094 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1096 if ( $descTitle->exists() ) {
1097 # Create a null revision
1098 $latest = $descTitle->getLatestRevID();
1099 $nullRevision = Revision
::newNullRevision(
1101 $descTitle->getArticleID(),
1102 $log->getRcComment(),
1105 if (!is_null($nullRevision)) {
1106 $nullRevision->insertOn( $dbw );
1108 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1109 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1111 # Invalidate the cache for the description page
1112 $descTitle->invalidateCache();
1113 $descTitle->purgeSquid();
1115 # New file; create the description page.
1116 # There's already a log entry, so don't make a second RC entry
1117 # Squid and file cache for the description page are purged by doEdit.
1118 $wikiPage->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
, false, $user );
1121 # Commit the transaction now, in case something goes wrong later
1122 # The most important thing is that files don't get lost, especially archives
1123 $dbw->commit( __METHOD__
);
1125 # Save to cache and purge the squid
1126 # We shall not saveToCache before the commit since otherwise
1127 # in case of a rollback there is an usable file from memcached
1128 # which in fact doesn't really exist (bug 24978)
1129 $this->saveToCache();
1131 # Hooks, hooks, the magic of hooks...
1132 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1134 # Invalidate cache for all pages using this file
1135 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1136 $update->doUpdate();
1138 # Invalidate cache for all pages that redirects on this page
1139 $redirs = $this->getTitle()->getRedirectsHere();
1141 foreach ( $redirs as $redir ) {
1142 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1143 $update->doUpdate();
1150 * Move or copy a file to its public location. If a file exists at the
1151 * destination, move it to an archive. Returns a FileRepoStatus object with
1152 * the archive name in the "value" member on success.
1154 * The archive name should be passed through to recordUpload for database
1157 * @param $srcPath String: local filesystem path to the source image
1158 * @param $flags Integer: a bitwise combination of:
1159 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1160 * @return FileRepoStatus object. On success, the value member contains the
1161 * archive name, or an empty string if it was a new file.
1163 function publish( $srcPath, $flags = 0 ) {
1164 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1168 * Move or copy a file to a specified location. Returns a FileRepoStatus
1169 * object with the archive name in the "value" member on success.
1171 * The archive name should be passed through to recordUpload for database
1174 * @param $srcPath String: local filesystem path to the source image
1175 * @param $dstRel String: target relative path
1176 * @param $flags Integer: a bitwise combination of:
1177 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1178 * @return FileRepoStatus object. On success, the value member contains the
1179 * archive name, or an empty string if it was a new file.
1181 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1182 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1183 return $this->readOnlyFatalStatus();
1186 $this->lock(); // begin
1188 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1189 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1190 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1191 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1193 if ( $status->value
== 'new' ) {
1194 $status->value
= '';
1196 $status->value
= $archiveName;
1199 $this->unlock(); // done
1204 /** getLinksTo inherited */
1205 /** getExifData inherited */
1206 /** isLocal inherited */
1207 /** wasDeleted inherited */
1210 * Move file to the new title
1212 * Move current, old version and all thumbnails
1213 * to the new filename. Old file is deleted.
1215 * Cache purging is done; checks for validity
1216 * and logging are caller's responsibility
1218 * @param $target Title New file name
1219 * @return FileRepoStatus object.
1221 function move( $target ) {
1222 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1223 return $this->readOnlyFatalStatus();
1226 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1227 $this->lock(); // begin
1229 $batch = new LocalFileMoveBatch( $this, $target );
1230 $batch->addCurrent();
1233 $status = $batch->execute();
1234 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1236 $this->purgeEverything();
1237 $this->unlock(); // done
1239 if ( $status->isOk() ) {
1240 // Now switch the object
1241 $this->title
= $target;
1242 // Force regeneration of the name and hashpath
1243 unset( $this->name
);
1244 unset( $this->hashPath
);
1245 // Purge the new image
1246 $this->purgeEverything();
1253 * Delete all versions of the file.
1255 * Moves the files into an archive directory (or deletes them)
1256 * and removes the database rows.
1258 * Cache purging is done; logging is caller's responsibility.
1262 * @return FileRepoStatus object.
1264 function delete( $reason, $suppress = false ) {
1265 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1266 return $this->readOnlyFatalStatus();
1269 $this->lock(); // begin
1271 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1272 $batch->addCurrent();
1274 # Get old version relative paths
1275 $dbw = $this->repo
->getMasterDB();
1276 $result = $dbw->select( 'oldimage',
1277 array( 'oi_archive_name' ),
1278 array( 'oi_name' => $this->getName() ) );
1279 foreach ( $result as $row ) {
1280 $batch->addOld( $row->oi_archive_name
);
1281 $this->purgeOldThumbnails( $row->oi_archive_name
);
1283 $status = $batch->execute();
1285 if ( $status->isOK() ) {
1286 // Update site_stats
1287 $site_stats = $dbw->tableName( 'site_stats' );
1288 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1289 $this->purgeEverything();
1292 $this->unlock(); // done
1298 * Delete an old version of the file.
1300 * Moves the file into an archive directory (or deletes it)
1301 * and removes the database row.
1303 * Cache purging is done; logging is caller's responsibility.
1305 * @param $archiveName String
1306 * @param $reason String
1307 * @param $suppress Boolean
1308 * @throws MWException or FSException on database or file store failure
1309 * @return FileRepoStatus object.
1311 function deleteOld( $archiveName, $reason, $suppress = false ) {
1312 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1313 return $this->readOnlyFatalStatus();
1316 $this->lock(); // begin
1318 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1319 $batch->addOld( $archiveName );
1320 $this->purgeOldThumbnails( $archiveName );
1321 $status = $batch->execute();
1323 $this->unlock(); // done
1325 if ( $status->isOK() ) {
1326 $this->purgeDescription();
1327 $this->purgeHistory();
1334 * Restore all or specified deleted revisions to the given file.
1335 * Permissions and logging are left to the caller.
1337 * May throw database exceptions on error.
1339 * @param $versions array set of record ids of deleted items to restore,
1340 * or empty to restore all revisions.
1341 * @param $unsuppress Boolean
1342 * @return FileRepoStatus
1344 function restore( $versions = array(), $unsuppress = false ) {
1345 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1346 return $this->readOnlyFatalStatus();
1349 $this->lock(); // begin
1351 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1356 $batch->addIds( $versions );
1359 $status = $batch->execute();
1361 if ( $status->isGood() ) {
1362 $cleanupStatus = $batch->cleanup();
1363 $cleanupStatus->successCount
= 0;
1364 $cleanupStatus->failCount
= 0;
1365 $status->merge( $cleanupStatus );
1368 $this->unlock(); // done
1373 /** isMultipage inherited */
1374 /** pageCount inherited */
1375 /** scaleHeight inherited */
1376 /** getImageSize inherited */
1379 * Get the URL of the file description page.
1382 function getDescriptionUrl() {
1383 return $this->title
->getLocalUrl();
1387 * Get the HTML text of the description page
1388 * This is not used by ImagePage for local files, since (among other things)
1389 * it skips the parser cache.
1390 * @return bool|mixed
1392 function getDescriptionText() {
1394 $revision = Revision
::newFromTitle( $this->title
);
1395 if ( !$revision ) return false;
1396 $text = $revision->getText();
1397 if ( !$text ) return false;
1398 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1399 return $pout->getText();
1402 function getDescription() {
1404 return $this->description
;
1407 function getTimestamp() {
1409 return $this->timestamp
;
1412 function getSha1() {
1414 // Initialise now if necessary
1415 if ( $this->sha1
== '' && $this->fileExists
) {
1416 $this->lock(); // begin
1418 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1419 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1420 $dbw = $this->repo
->getMasterDB();
1421 $dbw->update( 'image',
1422 array( 'img_sha1' => $this->sha1
),
1423 array( 'img_name' => $this->getName() ),
1425 $this->saveToCache();
1428 $this->unlock(); // done
1435 * Start a transaction and lock the image for update
1436 * Increments a reference counter if the lock is already held
1437 * @return boolean True if the image exists, false otherwise
1440 $dbw = $this->repo
->getMasterDB();
1442 if ( !$this->locked
) {
1443 $dbw->begin( __METHOD__
);
1447 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1451 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1452 * the transaction and thereby releases the image lock.
1455 if ( $this->locked
) {
1457 if ( !$this->locked
) {
1458 $dbw = $this->repo
->getMasterDB();
1459 $dbw->commit( __METHOD__
);
1465 * Roll back the DB transaction and mark the image unlocked
1467 function unlockAndRollback() {
1468 $this->locked
= false;
1469 $dbw = $this->repo
->getMasterDB();
1470 $dbw->rollback( __METHOD__
);
1476 protected function readOnlyFatalStatus() {
1477 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1478 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1480 } // LocalFile class
1482 # ------------------------------------------------------------------------------
1485 * Helper class for file deletion
1486 * @ingroup FileAbstraction
1488 class LocalFileDeleteBatch
{
1495 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1498 function __construct( File
$file, $reason = '', $suppress = false ) {
1499 $this->file
= $file;
1500 $this->reason
= $reason;
1501 $this->suppress
= $suppress;
1502 $this->status
= $file->repo
->newGood();
1505 function addCurrent() {
1506 $this->srcRels
['.'] = $this->file
->getRel();
1509 function addOld( $oldName ) {
1510 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1511 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1514 function getOldRels() {
1515 if ( !isset( $this->srcRels
['.'] ) ) {
1516 $oldRels =& $this->srcRels
;
1517 $deleteCurrent = false;
1519 $oldRels = $this->srcRels
;
1520 unset( $oldRels['.'] );
1521 $deleteCurrent = true;
1524 return array( $oldRels, $deleteCurrent );
1527 protected function getHashes() {
1529 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1531 if ( $deleteCurrent ) {
1532 $hashes['.'] = $this->file
->getSha1();
1535 if ( count( $oldRels ) ) {
1536 $dbw = $this->file
->repo
->getMasterDB();
1537 $res = $dbw->select(
1539 array( 'oi_archive_name', 'oi_sha1' ),
1540 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1544 foreach ( $res as $row ) {
1545 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1546 // Get the hash from the file
1547 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1548 $props = $this->file
->repo
->getFileProps( $oldUrl );
1550 if ( $props['fileExists'] ) {
1551 // Upgrade the oldimage row
1552 $dbw->update( 'oldimage',
1553 array( 'oi_sha1' => $props['sha1'] ),
1554 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1556 $hashes[$row->oi_archive_name
] = $props['sha1'];
1558 $hashes[$row->oi_archive_name
] = false;
1561 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1566 $missing = array_diff_key( $this->srcRels
, $hashes );
1568 foreach ( $missing as $name => $rel ) {
1569 $this->status
->error( 'filedelete-old-unregistered', $name );
1572 foreach ( $hashes as $name => $hash ) {
1574 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1575 unset( $hashes[$name] );
1582 function doDBInserts() {
1585 $dbw = $this->file
->repo
->getMasterDB();
1586 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1587 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1588 $encReason = $dbw->addQuotes( $this->reason
);
1589 $encGroup = $dbw->addQuotes( 'deleted' );
1590 $ext = $this->file
->getExtension();
1591 $dotExt = $ext === '' ?
'' : ".$ext";
1592 $encExt = $dbw->addQuotes( $dotExt );
1593 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1595 // Bitfields to further suppress the content
1596 if ( $this->suppress
) {
1598 // This should be 15...
1599 $bitfield |
= Revision
::DELETED_TEXT
;
1600 $bitfield |
= Revision
::DELETED_COMMENT
;
1601 $bitfield |
= Revision
::DELETED_USER
;
1602 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1604 $bitfield = 'oi_deleted';
1607 if ( $deleteCurrent ) {
1608 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1609 $where = array( 'img_name' => $this->file
->getName() );
1610 $dbw->insertSelect( 'filearchive', 'image',
1612 'fa_storage_group' => $encGroup,
1613 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1614 'fa_deleted_user' => $encUserId,
1615 'fa_deleted_timestamp' => $encTimestamp,
1616 'fa_deleted_reason' => $encReason,
1617 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1619 'fa_name' => 'img_name',
1620 'fa_archive_name' => 'NULL',
1621 'fa_size' => 'img_size',
1622 'fa_width' => 'img_width',
1623 'fa_height' => 'img_height',
1624 'fa_metadata' => 'img_metadata',
1625 'fa_bits' => 'img_bits',
1626 'fa_media_type' => 'img_media_type',
1627 'fa_major_mime' => 'img_major_mime',
1628 'fa_minor_mime' => 'img_minor_mime',
1629 'fa_description' => 'img_description',
1630 'fa_user' => 'img_user',
1631 'fa_user_text' => 'img_user_text',
1632 'fa_timestamp' => 'img_timestamp'
1633 ), $where, __METHOD__
);
1636 if ( count( $oldRels ) ) {
1637 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1639 'oi_name' => $this->file
->getName(),
1640 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1641 $dbw->insertSelect( 'filearchive', 'oldimage',
1643 'fa_storage_group' => $encGroup,
1644 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1645 'fa_deleted_user' => $encUserId,
1646 'fa_deleted_timestamp' => $encTimestamp,
1647 'fa_deleted_reason' => $encReason,
1648 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1650 'fa_name' => 'oi_name',
1651 'fa_archive_name' => 'oi_archive_name',
1652 'fa_size' => 'oi_size',
1653 'fa_width' => 'oi_width',
1654 'fa_height' => 'oi_height',
1655 'fa_metadata' => 'oi_metadata',
1656 'fa_bits' => 'oi_bits',
1657 'fa_media_type' => 'oi_media_type',
1658 'fa_major_mime' => 'oi_major_mime',
1659 'fa_minor_mime' => 'oi_minor_mime',
1660 'fa_description' => 'oi_description',
1661 'fa_user' => 'oi_user',
1662 'fa_user_text' => 'oi_user_text',
1663 'fa_timestamp' => 'oi_timestamp',
1664 'fa_deleted' => $bitfield
1665 ), $where, __METHOD__
);
1669 function doDBDeletes() {
1670 $dbw = $this->file
->repo
->getMasterDB();
1671 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1673 if ( count( $oldRels ) ) {
1674 $dbw->delete( 'oldimage',
1676 'oi_name' => $this->file
->getName(),
1677 'oi_archive_name' => array_keys( $oldRels )
1681 if ( $deleteCurrent ) {
1682 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1687 * Run the transaction
1688 * @return FileRepoStatus
1690 function execute() {
1692 wfProfileIn( __METHOD__
);
1694 $this->file
->lock();
1695 // Leave private files alone
1696 $privateFiles = array();
1697 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1698 $dbw = $this->file
->repo
->getMasterDB();
1700 if ( !empty( $oldRels ) ) {
1701 $res = $dbw->select( 'oldimage',
1702 array( 'oi_archive_name' ),
1703 array( 'oi_name' => $this->file
->getName(),
1704 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1705 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1708 foreach ( $res as $row ) {
1709 $privateFiles[$row->oi_archive_name
] = 1;
1712 // Prepare deletion batch
1713 $hashes = $this->getHashes();
1714 $this->deletionBatch
= array();
1715 $ext = $this->file
->getExtension();
1716 $dotExt = $ext === '' ?
'' : ".$ext";
1718 foreach ( $this->srcRels
as $name => $srcRel ) {
1719 // Skip files that have no hash (missing source).
1720 // Keep private files where they are.
1721 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1722 $hash = $hashes[$name];
1723 $key = $hash . $dotExt;
1724 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1725 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1729 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1730 // We acquire this lock by running the inserts now, before the file operations.
1732 // This potentially has poor lock contention characteristics -- an alternative
1733 // scheme would be to insert stub filearchive entries with no fa_name and commit
1734 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1735 $this->doDBInserts();
1737 // Removes non-existent file from the batch, so we don't get errors.
1738 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1740 // Execute the file deletion batch
1741 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1743 if ( !$status->isGood() ) {
1744 $this->status
->merge( $status );
1747 if ( !$this->status
->isOK() ) {
1748 // Critical file deletion error
1749 // Roll back inserts, release lock and abort
1750 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1751 $this->file
->unlockAndRollback();
1752 wfProfileOut( __METHOD__
);
1753 return $this->status
;
1757 if ( $wgUseSquid ) {
1760 foreach ( $this->srcRels
as $srcRel ) {
1761 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1762 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1764 SquidUpdate
::purge( $urls );
1767 // Delete image/oldimage rows
1768 $this->doDBDeletes();
1770 // Commit and return
1771 $this->file
->unlock();
1772 wfProfileOut( __METHOD__
);
1774 return $this->status
;
1778 * Removes non-existent files from a deletion batch.
1781 function removeNonexistentFiles( $batch ) {
1782 $files = $newBatch = array();
1784 foreach ( $batch as $batchItem ) {
1785 list( $src, $dest ) = $batchItem;
1786 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1789 $result = $this->file
->repo
->fileExistsBatch( $files, FileRepo
::FILES_ONLY
);
1791 foreach ( $batch as $batchItem ) {
1792 if ( $result[$batchItem[0]] ) {
1793 $newBatch[] = $batchItem;
1801 # ------------------------------------------------------------------------------
1804 * Helper class for file undeletion
1805 * @ingroup FileAbstraction
1807 class LocalFileRestoreBatch
{
1813 var $cleanupBatch, $ids, $all, $unsuppress = false;
1815 function __construct( File
$file, $unsuppress = false ) {
1816 $this->file
= $file;
1817 $this->cleanupBatch
= $this->ids
= array();
1818 $this->ids
= array();
1819 $this->unsuppress
= $unsuppress;
1825 function addId( $fa_id ) {
1826 $this->ids
[] = $fa_id;
1830 * Add a whole lot of files by ID
1832 function addIds( $ids ) {
1833 $this->ids
= array_merge( $this->ids
, $ids );
1837 * Add all revisions of the file
1844 * Run the transaction, except the cleanup batch.
1845 * The cleanup batch should be run in a separate transaction, because it locks different
1846 * rows and there's no need to keep the image row locked while it's acquiring those locks
1847 * The caller may have its own transaction open.
1848 * So we save the batch and let the caller call cleanup()
1849 * @return FileRepoStatus
1851 function execute() {
1854 if ( !$this->all
&& !$this->ids
) {
1856 return $this->file
->repo
->newGood();
1859 $exists = $this->file
->lock();
1860 $dbw = $this->file
->repo
->getMasterDB();
1861 $status = $this->file
->repo
->newGood();
1863 // Fetch all or selected archived revisions for the file,
1864 // sorted from the most recent to the oldest.
1865 $conditions = array( 'fa_name' => $this->file
->getName() );
1867 if ( !$this->all
) {
1868 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1871 $result = $dbw->select( 'filearchive', '*',
1874 array( 'ORDER BY' => 'fa_timestamp DESC' )
1877 $idsPresent = array();
1878 $storeBatch = array();
1879 $insertBatch = array();
1880 $insertCurrent = false;
1881 $deleteIds = array();
1883 $archiveNames = array();
1885 foreach ( $result as $row ) {
1886 $idsPresent[] = $row->fa_id
;
1888 if ( $row->fa_name
!= $this->file
->getName() ) {
1889 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1890 $status->failCount++
;
1894 if ( $row->fa_storage_key
== '' ) {
1895 // Revision was missing pre-deletion
1896 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1897 $status->failCount++
;
1901 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1902 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1904 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1907 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1908 $sha1 = substr( $sha1, 1 );
1911 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1912 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1913 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1914 ||
is_null( $row->fa_metadata
) ) {
1915 // Refresh our metadata
1916 // Required for a new current revision; nice for older ones too. :)
1917 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1920 'minor_mime' => $row->fa_minor_mime
,
1921 'major_mime' => $row->fa_major_mime
,
1922 'media_type' => $row->fa_media_type
,
1923 'metadata' => $row->fa_metadata
1927 if ( $first && !$exists ) {
1928 // This revision will be published as the new current version
1929 $destRel = $this->file
->getRel();
1930 $insertCurrent = array(
1931 'img_name' => $row->fa_name
,
1932 'img_size' => $row->fa_size
,
1933 'img_width' => $row->fa_width
,
1934 'img_height' => $row->fa_height
,
1935 'img_metadata' => $props['metadata'],
1936 'img_bits' => $row->fa_bits
,
1937 'img_media_type' => $props['media_type'],
1938 'img_major_mime' => $props['major_mime'],
1939 'img_minor_mime' => $props['minor_mime'],
1940 'img_description' => $row->fa_description
,
1941 'img_user' => $row->fa_user
,
1942 'img_user_text' => $row->fa_user_text
,
1943 'img_timestamp' => $row->fa_timestamp
,
1947 // The live (current) version cannot be hidden!
1948 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1949 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1950 $this->cleanupBatch
[] = $row->fa_storage_key
;
1953 $archiveName = $row->fa_archive_name
;
1955 if ( $archiveName == '' ) {
1956 // This was originally a current version; we
1957 // have to devise a new archive name for it.
1958 // Format is <timestamp of archiving>!<name>
1959 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1962 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1964 } while ( isset( $archiveNames[$archiveName] ) );
1967 $archiveNames[$archiveName] = true;
1968 $destRel = $this->file
->getArchiveRel( $archiveName );
1969 $insertBatch[] = array(
1970 'oi_name' => $row->fa_name
,
1971 'oi_archive_name' => $archiveName,
1972 'oi_size' => $row->fa_size
,
1973 'oi_width' => $row->fa_width
,
1974 'oi_height' => $row->fa_height
,
1975 'oi_bits' => $row->fa_bits
,
1976 'oi_description' => $row->fa_description
,
1977 'oi_user' => $row->fa_user
,
1978 'oi_user_text' => $row->fa_user_text
,
1979 'oi_timestamp' => $row->fa_timestamp
,
1980 'oi_metadata' => $props['metadata'],
1981 'oi_media_type' => $props['media_type'],
1982 'oi_major_mime' => $props['major_mime'],
1983 'oi_minor_mime' => $props['minor_mime'],
1984 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1985 'oi_sha1' => $sha1 );
1988 $deleteIds[] = $row->fa_id
;
1990 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1991 // private files can stay where they are
1992 $status->successCount++
;
1994 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1995 $this->cleanupBatch
[] = $row->fa_storage_key
;
2003 // Add a warning to the status object for missing IDs
2004 $missingIds = array_diff( $this->ids
, $idsPresent );
2006 foreach ( $missingIds as $id ) {
2007 $status->error( 'undelete-missing-filearchive', $id );
2010 // Remove missing files from batch, so we don't get errors when undeleting them
2011 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2013 // Run the store batch
2014 // Use the OVERWRITE_SAME flag to smooth over a common error
2015 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2016 $status->merge( $storeStatus );
2018 if ( !$status->isGood() ) {
2019 // Even if some files could be copied, fail entirely as that is the
2020 // easiest thing to do without data loss
2021 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2022 $status->ok
= false;
2023 $this->file
->unlock();
2028 // Run the DB updates
2029 // Because we have locked the image row, key conflicts should be rare.
2030 // If they do occur, we can roll back the transaction at this time with
2031 // no data loss, but leaving unregistered files scattered throughout the
2033 // This is not ideal, which is why it's important to lock the image row.
2034 if ( $insertCurrent ) {
2035 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2038 if ( $insertBatch ) {
2039 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2043 $dbw->delete( 'filearchive',
2044 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2048 // If store batch is empty (all files are missing), deletion is to be considered successful
2049 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2051 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2053 // Update site_stats
2054 $site_stats = $dbw->tableName( 'site_stats' );
2055 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2057 $this->file
->purgeEverything();
2059 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2060 $this->file
->purgeDescription();
2061 $this->file
->purgeHistory();
2065 $this->file
->unlock();
2071 * Removes non-existent files from a store batch.
2074 function removeNonexistentFiles( $triplets ) {
2075 $files = $filteredTriplets = array();
2076 foreach ( $triplets as $file )
2077 $files[$file[0]] = $file[0];
2079 $result = $this->file
->repo
->fileExistsBatch( $files, FileRepo
::FILES_ONLY
);
2081 foreach ( $triplets as $file ) {
2082 if ( $result[$file[0]] ) {
2083 $filteredTriplets[] = $file;
2087 return $filteredTriplets;
2091 * Removes non-existent files from a cleanup batch.
2094 function removeNonexistentFromCleanup( $batch ) {
2095 $files = $newBatch = array();
2096 $repo = $this->file
->repo
;
2098 foreach ( $batch as $file ) {
2099 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2100 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2103 $result = $repo->fileExistsBatch( $files, FileRepo
::FILES_ONLY
);
2105 foreach ( $batch as $file ) {
2106 if ( $result[$file] ) {
2107 $newBatch[] = $file;
2115 * Delete unused files in the deleted zone.
2116 * This should be called from outside the transaction in which execute() was called.
2117 * @return FileRepoStatus|void
2119 function cleanup() {
2120 if ( !$this->cleanupBatch
) {
2121 return $this->file
->repo
->newGood();
2124 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2126 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2132 * Cleanup a failed batch. The batch was only partially successful, so
2133 * rollback by removing all items that were succesfully copied.
2135 * @param Status $storeStatus
2136 * @param array $storeBatch
2138 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2139 $cleanupBatch = array();
2141 foreach ( $storeStatus->success
as $i => $success ) {
2142 // Check if this item of the batch was successfully copied
2144 // Item was successfully copied and needs to be removed again
2145 // Extract ($dstZone, $dstRel) from the batch
2146 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2149 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2153 # ------------------------------------------------------------------------------
2156 * Helper class for file movement
2157 * @ingroup FileAbstraction
2159 class LocalFileMoveBatch
{
2171 var $cur, $olds, $oldCount, $archive, $db;
2173 function __construct( File
$file, Title
$target ) {
2174 $this->file
= $file;
2175 $this->target
= $target;
2176 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2177 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2178 $this->oldName
= $this->file
->getName();
2179 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2180 $this->oldRel
= $this->oldHash
. $this->oldName
;
2181 $this->newRel
= $this->newHash
. $this->newName
;
2182 $this->db
= $file->repo
->getMasterDb();
2186 * Add the current image to the batch
2188 function addCurrent() {
2189 $this->cur
= array( $this->oldRel
, $this->newRel
);
2193 * Add the old versions of the image to the batch
2195 function addOlds() {
2196 $archiveBase = 'archive';
2197 $this->olds
= array();
2198 $this->oldCount
= 0;
2200 $result = $this->db
->select( 'oldimage',
2201 array( 'oi_archive_name', 'oi_deleted' ),
2202 array( 'oi_name' => $this->oldName
),
2206 foreach ( $result as $row ) {
2207 $oldName = $row->oi_archive_name
;
2208 $bits = explode( '!', $oldName, 2 );
2210 if ( count( $bits ) != 2 ) {
2211 wfDebug( "Old file name missing !: '$oldName' \n" );
2215 list( $timestamp, $filename ) = $bits;
2217 if ( $this->oldName
!= $filename ) {
2218 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2224 // Do we want to add those to oldCount?
2225 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2229 $this->olds
[] = array(
2230 "{$archiveBase}/{$this->oldHash}{$oldName}",
2231 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2238 * @return FileRepoStatus
2240 function execute() {
2241 $repo = $this->file
->repo
;
2242 $status = $repo->newGood();
2243 $triplets = $this->getMoveTriplets();
2245 $triplets = $this->removeNonexistentFiles( $triplets );
2247 // Copy the files into their new location
2248 $statusMove = $repo->storeBatch( $triplets );
2249 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2250 if ( !$statusMove->isGood() ) {
2251 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2252 $this->cleanupTarget( $triplets );
2253 $statusMove->ok
= false;
2257 $this->db
->begin( __METHOD__
);
2258 $statusDb = $this->doDBUpdates();
2259 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2260 if ( !$statusDb->isGood() ) {
2261 $this->db
->rollback( __METHOD__
);
2262 // Something went wrong with the DB updates, so remove the target files
2263 $this->cleanupTarget( $triplets );
2264 $statusDb->ok
= false;
2267 $this->db
->commit( __METHOD__
);
2269 // Everything went ok, remove the source files
2270 $this->cleanupSource( $triplets );
2272 $status->merge( $statusDb );
2273 $status->merge( $statusMove );
2279 * Do the database updates and return a new FileRepoStatus indicating how
2280 * many rows where updated.
2282 * @return FileRepoStatus
2284 function doDBUpdates() {
2285 $repo = $this->file
->repo
;
2286 $status = $repo->newGood();
2289 // Update current image
2292 array( 'img_name' => $this->newName
),
2293 array( 'img_name' => $this->oldName
),
2297 if ( $dbw->affectedRows() ) {
2298 $status->successCount++
;
2300 $status->failCount++
;
2301 $status->fatal( 'imageinvalidfilename' );
2305 // Update old images
2309 'oi_name' => $this->newName
,
2310 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2312 array( 'oi_name' => $this->oldName
),
2316 $affected = $dbw->affectedRows();
2317 $total = $this->oldCount
;
2318 $status->successCount +
= $affected;
2319 $status->failCount +
= $total - $affected;
2320 if ( $status->failCount
) {
2321 $status->error( 'imageinvalidfilename' );
2328 * Generate triplets for FileRepo::storeBatch().
2331 function getMoveTriplets() {
2332 $moves = array_merge( array( $this->cur
), $this->olds
);
2333 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2335 foreach ( $moves as $move ) {
2336 // $move: (oldRelativePath, newRelativePath)
2337 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2338 $triplets[] = array( $srcUrl, 'public', $move[1] );
2339 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2346 * Removes non-existent files from move batch.
2349 function removeNonexistentFiles( $triplets ) {
2352 foreach ( $triplets as $file ) {
2353 $files[$file[0]] = $file[0];
2356 $result = $this->file
->repo
->fileExistsBatch( $files, FileRepo
::FILES_ONLY
);
2357 $filteredTriplets = array();
2359 foreach ( $triplets as $file ) {
2360 if ( $result[$file[0]] ) {
2361 $filteredTriplets[] = $file;
2363 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2367 return $filteredTriplets;
2371 * Cleanup a partially moved array of triplets by deleting the target
2372 * files. Called if something went wrong half way.
2374 function cleanupTarget( $triplets ) {
2375 // Create dest pairs from the triplets
2377 foreach ( $triplets as $triplet ) {
2378 $pairs[] = array( $triplet[1], $triplet[2] );
2381 $this->file
->repo
->cleanupBatch( $pairs );
2385 * Cleanup a fully moved array of triplets by deleting the source files.
2386 * Called at the end of the move process if everything else went ok.
2388 function cleanupSource( $triplets ) {
2389 // Create source file names from the triplets
2391 foreach ( $triplets as $triplet ) {
2392 $files[] = $triplet[0];
2395 $this->file
->repo
->cleanupBatch( $files );