6 * Bump this number when serialized cache records may be incompatible.
8 define( 'MW_FILE_VERSION', 8 );
11 * Class to represent a local file in the wiki's own database
13 * Provides methods to retrieve paths (physical, logical, URL),
14 * to generate image thumbnails or for uploading.
16 * Note that only the repo object knows what its file class is called. You should
17 * never name a file class explictly outside of the repo class. Instead use the
18 * repo's factory functions to generate file objects, for example:
20 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
22 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
27 class LocalFile
extends File
{
31 var $fileExists, # does the file file exist on disk? (loadFromXxx)
32 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
33 $historyRes, # result of the query for the file's history (nextHistoryLine)
36 $bits, # --- returned by getimagesize (loadFromXxx)
38 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
39 $mime, # MIME type, determined by MimeMagic::guessMimeType
40 $major_mime, # Major mime type
41 $minor_mime, # Minor mime type
42 $size, # Size in bytes (loadFromXxx)
43 $metadata, # Handler-specific metadata
44 $timestamp, # Upload timestamp
45 $sha1, # SHA-1 base 36 content hash
46 $user, $user_text, # User, who uploaded the file
47 $description, # Description of current revision of the file
48 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
49 $upgraded, # Whether the row was upgraded on load
50 $locked, # True if the image row is locked
51 $missing, # True if file is not present in file system. Not to be cached in memcached
52 $deleted; # Bitfield akin to rev_deleted
57 * Create a LocalFile from a title
58 * Do not call this except from inside a repo class.
60 * Note: $unused param is only here to avoid an E_STRICT
62 static function newFromTitle( $title, $repo, $unused = null ) {
63 return new self( $title, $repo );
67 * Create a LocalFile from a title
68 * Do not call this except from inside a repo class.
70 static function newFromRow( $row, $repo ) {
71 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
72 $file = new self( $title, $repo );
73 $file->loadFromRow( $row );
78 * Create a LocalFile from a SHA-1 key
79 * Do not call this except from inside a repo class.
81 static function newFromKey( $sha1, $repo, $timestamp = false ) {
82 $conds = array( 'img_sha1' => $sha1 );
84 $conds['img_timestamp'] = $timestamp;
86 $dbr = $repo->getSlaveDB();
87 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
89 return self
::newFromRow( $row, $repo );
96 * Fields in the image table
98 static function selectFields() {
119 * Do not call this except from inside a repo class.
121 function __construct( $title, $repo ) {
122 if( !is_object( $title ) ) {
123 throw new MWException( __CLASS__
. ' constructor given bogus title.' );
125 parent
::__construct( $title, $repo );
126 $this->metadata
= '';
127 $this->historyLine
= 0;
128 $this->historyRes
= null;
129 $this->dataLoaded
= false;
133 * Get the memcached key for the main data for this file, or false if
134 * there is no access to the shared cache.
136 function getCacheKey() {
137 $hashedName = md5( $this->getName() );
138 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
142 * Try to load file metadata from memcached. Returns true on success.
144 function loadFromCache() {
146 wfProfileIn( __METHOD__
);
147 $this->dataLoaded
= false;
148 $key = $this->getCacheKey();
150 wfProfileOut( __METHOD__
);
153 $cachedValues = $wgMemc->get( $key );
155 // Check if the key existed and belongs to this version of MediaWiki
156 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
157 wfDebug( "Pulling file metadata from cache key $key\n" );
158 $this->fileExists
= $cachedValues['fileExists'];
159 if ( $this->fileExists
) {
160 $this->setProps( $cachedValues );
162 $this->dataLoaded
= true;
164 if ( $this->dataLoaded
) {
165 wfIncrStats( 'image_cache_hit' );
167 wfIncrStats( 'image_cache_miss' );
170 wfProfileOut( __METHOD__
);
171 return $this->dataLoaded
;
175 * Save the file metadata to memcached
177 function saveToCache() {
180 $key = $this->getCacheKey();
184 $fields = $this->getCacheFields( '' );
185 $cache = array( 'version' => MW_FILE_VERSION
);
186 $cache['fileExists'] = $this->fileExists
;
187 if ( $this->fileExists
) {
188 foreach ( $fields as $field ) {
189 $cache[$field] = $this->$field;
193 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
197 * Load metadata from the file itself
199 function loadFromFile() {
200 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
203 function getCacheFields( $prefix = 'img_' ) {
204 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
205 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
206 static $results = array();
207 if ( $prefix == '' ) {
210 if ( !isset( $results[$prefix] ) ) {
211 $prefixedFields = array();
212 foreach ( $fields as $field ) {
213 $prefixedFields[] = $prefix . $field;
215 $results[$prefix] = $prefixedFields;
217 return $results[$prefix];
221 * Load file metadata from the DB
223 function loadFromDB() {
224 # Polymorphic function name to distinguish foreign and local fetches
225 $fname = get_class( $this ) . '::' . __FUNCTION__
;
226 wfProfileIn( $fname );
228 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
229 $this->dataLoaded
= true;
231 $dbr = $this->repo
->getMasterDB();
233 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
234 array( 'img_name' => $this->getName() ), $fname );
236 $this->loadFromRow( $row );
238 $this->fileExists
= false;
241 wfProfileOut( $fname );
245 * Decode a row from the database (either object or array) to an array
246 * with timestamps and MIME types decoded, and the field prefix removed.
248 function decodeRow( $row, $prefix = 'img_' ) {
249 $array = (array)$row;
250 $prefixLength = strlen( $prefix );
251 // Sanity check prefix once
252 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
253 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
256 foreach ( $array as $name => $value ) {
257 $decoded[substr( $name, $prefixLength )] = $value;
259 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
260 if ( empty( $decoded['major_mime'] ) ) {
261 $decoded['mime'] = 'unknown/unknown';
263 if ( !$decoded['minor_mime'] ) {
264 $decoded['minor_mime'] = 'unknown';
266 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
268 # Trim zero padding from char/binary field
269 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
274 * Load file metadata from a DB result row
276 function loadFromRow( $row, $prefix = 'img_' ) {
277 $this->dataLoaded
= true;
278 $array = $this->decodeRow( $row, $prefix );
279 foreach ( $array as $name => $value ) {
280 $this->$name = $value;
282 $this->fileExists
= true;
283 $this->maybeUpgradeRow();
287 * Load file metadata from cache or DB, unless already loaded
290 if ( !$this->dataLoaded
) {
291 if ( !$this->loadFromCache() ) {
293 $this->saveToCache();
295 $this->dataLoaded
= true;
300 * Upgrade a row if it needs it
302 function maybeUpgradeRow() {
303 if ( wfReadOnly() ) {
306 if ( is_null( $this->media_type
) ||
307 $this->mime
== 'image/svg'
310 $this->upgraded
= true;
312 $handler = $this->getHandler();
313 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
315 $this->upgraded
= true;
320 function getUpgraded() {
321 return $this->upgraded
;
325 * Fix assorted version-related problems with the image row by reloading it from the file
327 function upgradeRow() {
328 wfProfileIn( __METHOD__
);
330 $this->loadFromFile();
332 # Don't destroy file info of missing files
333 if ( !$this->fileExists
) {
334 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
335 wfProfileOut( __METHOD__
);
338 $dbw = $this->repo
->getMasterDB();
339 list( $major, $minor ) = self
::splitMime( $this->mime
);
341 if ( wfReadOnly() ) {
342 wfProfileOut( __METHOD__
);
345 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
347 $dbw->update( 'image',
349 'img_width' => $this->width
,
350 'img_height' => $this->height
,
351 'img_bits' => $this->bits
,
352 'img_media_type' => $this->media_type
,
353 'img_major_mime' => $major,
354 'img_minor_mime' => $minor,
355 'img_metadata' => $this->metadata
,
356 'img_sha1' => $this->sha1
,
357 ), array( 'img_name' => $this->getName() ),
360 $this->saveToCache();
361 wfProfileOut( __METHOD__
);
365 * Set properties in this object to be equal to those given in the
366 * associative array $info. Only cacheable fields can be set.
368 * If 'mime' is given, it will be split into major_mime/minor_mime.
369 * If major_mime/minor_mime are given, $this->mime will also be set.
371 function setProps( $info ) {
372 $this->dataLoaded
= true;
373 $fields = $this->getCacheFields( '' );
374 $fields[] = 'fileExists';
375 foreach ( $fields as $field ) {
376 if ( isset( $info[$field] ) ) {
377 $this->$field = $info[$field];
380 // Fix up mime fields
381 if ( isset( $info['major_mime'] ) ) {
382 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
383 } elseif ( isset( $info['mime'] ) ) {
384 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
388 /** splitMime inherited */
389 /** getName inherited */
390 /** getTitle inherited */
391 /** getURL inherited */
392 /** getViewURL inherited */
393 /** getPath inherited */
394 /** isVisible inhereted */
396 function isMissing() {
397 if( $this->missing
=== null ) {
398 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
399 $this->missing
= !$fileExists;
401 return $this->missing
;
405 * Return the width of the image
407 * Returns false on error
409 public function getWidth( $page = 1 ) {
411 if ( $this->isMultipage() ) {
412 $dim = $this->getHandler()->getPageDimensions( $this, $page );
414 return $dim['width'];
424 * Return the height of the image
426 * Returns false on error
428 public function getHeight( $page = 1 ) {
430 if ( $this->isMultipage() ) {
431 $dim = $this->getHandler()->getPageDimensions( $this, $page );
433 return $dim['height'];
438 return $this->height
;
443 * Returns ID or name of user who uploaded the file
445 * @param $type string 'text' or 'id'
447 function getUser( $type = 'text' ) {
449 if( $type == 'text' ) {
450 return $this->user_text
;
451 } elseif( $type == 'id' ) {
457 * Get handler-specific metadata
459 function getMetadata() {
461 return $this->metadata
;
464 function getBitDepth() {
470 * Return the size of the image file, in bytes
472 public function getSize() {
478 * Returns the mime type of the file.
480 function getMimeType() {
486 * Return the type of the media in the file.
487 * Use the value returned by this function with the MEDIATYPE_xxx constants.
489 function getMediaType() {
491 return $this->media_type
;
494 /** canRender inherited */
495 /** mustRender inherited */
496 /** allowInlineDisplay inherited */
497 /** isSafeFile inherited */
498 /** isTrustedFile inherited */
501 * Returns true if the file file exists on disk.
502 * @return boolean Whether file file exist on disk.
504 public function exists() {
506 return $this->fileExists
;
509 /** getTransformScript inherited */
510 /** getUnscaledThumb inherited */
511 /** thumbName inherited */
512 /** createThumb inherited */
513 /** getThumbnail inherited */
514 /** transform inherited */
517 * Fix thumbnail files from 1.4 or before, with extreme prejudice
519 function migrateThumbFile( $thumbName ) {
520 $thumbDir = $this->getThumbPath();
521 $thumbPath = "$thumbDir/$thumbName";
522 if ( is_dir( $thumbPath ) ) {
523 // Directory where file should be
524 // This happened occasionally due to broken migration code in 1.5
525 // Rename to broken-*
526 for ( $i = 0; $i < 100 ; $i++
) {
527 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
528 if ( !file_exists( $broken ) ) {
529 rename( $thumbPath, $broken );
533 // Doesn't exist anymore
536 if ( is_file( $thumbDir ) ) {
537 // File where directory should be
539 // Doesn't exist anymore
544 /** getHandler inherited */
545 /** iconThumb inherited */
546 /** getLastError inherited */
549 * Get all thumbnail names previously generated for this file
551 function getThumbnails() {
554 $dir = $this->getThumbPath();
556 if ( is_dir( $dir ) ) {
557 $handle = opendir( $dir );
560 while ( false !== ( $file = readdir( $handle ) ) ) {
561 if ( $file{0} != '.' ) {
573 * Refresh metadata in memcached, but don't touch thumbnails or squid
575 function purgeMetadataCache() {
577 $this->saveToCache();
578 $this->purgeHistory();
582 * Purge the shared history (OldLocalFile) cache
584 function purgeHistory() {
586 $hashedName = md5( $this->getName() );
587 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
589 $wgMemc->delete( $oldKey );
594 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
596 function purgeCache() {
597 // Refresh metadata cache
598 $this->purgeMetadataCache();
601 $this->purgeThumbnails();
603 // Purge squid cache for this file
604 SquidUpdate
::purge( array( $this->getURL() ) );
608 * Delete cached transformed files
610 function purgeThumbnails() {
613 $files = $this->getThumbnails();
614 $dir = $this->getThumbPath();
616 foreach ( $files as $file ) {
617 # Check that the base file name is part of the thumb name
618 # This is a basic sanity check to avoid erasing unrelated directories
619 if ( strpos( $file, $this->getName() ) !== false ) {
620 $url = $this->getThumbUrl( $file );
622 @unlink
( "$dir/$file" );
628 SquidUpdate
::purge( $urls );
632 /** purgeDescription inherited */
633 /** purgeEverything inherited */
635 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
636 $dbr = $this->repo
->getSlaveDB();
637 $tables = array( 'oldimage' );
638 $fields = OldLocalFile
::selectFields();
639 $conds = $opts = $join_conds = array();
640 $eq = $inc ?
'=' : '';
641 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
643 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
646 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
649 $opts['LIMIT'] = $limit;
651 // Search backwards for time > x queries
652 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
653 $opts['ORDER BY'] = "oi_timestamp $order";
654 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
656 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
657 &$conds, &$opts, &$join_conds ) );
659 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
661 while( $row = $dbr->fetchObject( $res ) ) {
662 if ( $this->repo
->oldFileFromRowFactory
) {
663 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
665 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
668 if( $order == 'ASC' ) {
669 $r = array_reverse( $r ); // make sure it ends up descending
675 * Return the history of this file, line by line.
676 * starts with current version, then old versions.
677 * uses $this->historyLine to check which line to return:
678 * 0 return line for current version
679 * 1 query for old versions, return first one
680 * 2, ... return next old version from above query
682 public function nextHistoryLine() {
683 # Polymorphic function name to distinguish foreign and local fetches
684 $fname = get_class( $this ) . '::' . __FUNCTION__
;
686 $dbr = $this->repo
->getSlaveDB();
688 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
689 $this->historyRes
= $dbr->select( 'image',
692 "'' AS oi_archive_name",
696 array( 'img_name' => $this->title
->getDBkey() ),
699 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
700 $dbr->freeResult( $this->historyRes
);
701 $this->historyRes
= null;
704 } elseif ( $this->historyLine
== 1 ) {
705 $dbr->freeResult( $this->historyRes
);
706 $this->historyRes
= $dbr->select( 'oldimage', '*',
707 array( 'oi_name' => $this->title
->getDBkey() ),
709 array( 'ORDER BY' => 'oi_timestamp DESC' )
712 $this->historyLine ++
;
714 return $dbr->fetchObject( $this->historyRes
);
718 * Reset the history pointer to the first element of the history
720 public function resetHistory() {
721 $this->historyLine
= 0;
722 if ( !is_null( $this->historyRes
) ) {
723 $this->repo
->getSlaveDB()->freeResult( $this->historyRes
);
724 $this->historyRes
= null;
728 /** getFullPath inherited */
729 /** getHashPath inherited */
730 /** getRel inherited */
731 /** getUrlRel inherited */
732 /** getArchiveRel inherited */
733 /** getThumbRel inherited */
734 /** getArchivePath inherited */
735 /** getThumbPath inherited */
736 /** getArchiveUrl inherited */
737 /** getThumbUrl inherited */
738 /** getArchiveVirtualUrl inherited */
739 /** getThumbVirtualUrl inherited */
740 /** isHashed inherited */
743 * Upload a file and record it in the DB
744 * @param $srcPath String: source path or virtual URL
745 * @param $comment String: upload description
746 * @param $pageText String: text to use for the new description page,
747 * if a new description page is created
748 * @param $flags Integer: flags for publish()
749 * @param $props Array: File properties, if known. This can be used to reduce the
750 * upload time when uploading virtual URLs for which the file info
752 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
753 * @param $user Mixed: User object or null to use $wgUser
755 * @return FileRepoStatus object. On success, the value member contains the
756 * archive name, or an empty string if it was a new file.
758 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
760 $status = $this->publish( $srcPath, $flags );
762 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
763 $status->fatal( 'filenotfound', $srcPath );
771 * Record a file upload in the upload log and the image table
772 * @deprecated use upload()
774 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
775 $watch = false, $timestamp = false )
777 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
778 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
783 $wgUser->addWatch( $this->getTitle() );
790 * Record a file upload in the upload log and the image table
792 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
794 if( is_null( $user ) ) {
799 $dbw = $this->repo
->getMasterDB();
803 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
805 $props['description'] = $comment;
806 $props['user'] = $user->getId();
807 $props['user_text'] = $user->getName();
808 $props['timestamp'] = wfTimestamp( TS_MW
);
809 $this->setProps( $props );
811 // Delete thumbnails and refresh the metadata cache
812 $this->purgeThumbnails();
813 $this->saveToCache();
814 SquidUpdate
::purge( array( $this->getURL() ) );
816 // Fail now if the file isn't there
817 if ( !$this->fileExists
) {
818 wfDebug( __METHOD__
. ": File " . $this->getPath() . " went missing!\n" );
823 if ( $timestamp === false ) {
824 $timestamp = $dbw->timestamp();
827 # Test to see if the row exists using INSERT IGNORE
828 # This avoids race conditions by locking the row until the commit, and also
829 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
830 $dbw->insert( 'image',
832 'img_name' => $this->getName(),
833 'img_size'=> $this->size
,
834 'img_width' => intval( $this->width
),
835 'img_height' => intval( $this->height
),
836 'img_bits' => $this->bits
,
837 'img_media_type' => $this->media_type
,
838 'img_major_mime' => $this->major_mime
,
839 'img_minor_mime' => $this->minor_mime
,
840 'img_timestamp' => $timestamp,
841 'img_description' => $comment,
842 'img_user' => $user->getId(),
843 'img_user_text' => $user->getName(),
844 'img_metadata' => $this->metadata
,
845 'img_sha1' => $this->sha1
851 if( $dbw->affectedRows() == 0 ) {
854 # Collision, this is an update of a file
855 # Insert previous contents into oldimage
856 $dbw->insertSelect( 'oldimage', 'image',
858 'oi_name' => 'img_name',
859 'oi_archive_name' => $dbw->addQuotes( $oldver ),
860 'oi_size' => 'img_size',
861 'oi_width' => 'img_width',
862 'oi_height' => 'img_height',
863 'oi_bits' => 'img_bits',
864 'oi_timestamp' => 'img_timestamp',
865 'oi_description' => 'img_description',
866 'oi_user' => 'img_user',
867 'oi_user_text' => 'img_user_text',
868 'oi_metadata' => 'img_metadata',
869 'oi_media_type' => 'img_media_type',
870 'oi_major_mime' => 'img_major_mime',
871 'oi_minor_mime' => 'img_minor_mime',
872 'oi_sha1' => 'img_sha1'
873 ), array( 'img_name' => $this->getName() ), __METHOD__
876 # Update the current image row
877 $dbw->update( 'image',
879 'img_size' => $this->size
,
880 'img_width' => intval( $this->width
),
881 'img_height' => intval( $this->height
),
882 'img_bits' => $this->bits
,
883 'img_media_type' => $this->media_type
,
884 'img_major_mime' => $this->major_mime
,
885 'img_minor_mime' => $this->minor_mime
,
886 'img_timestamp' => $timestamp,
887 'img_description' => $comment,
888 'img_user' => $user->getId(),
889 'img_user_text' => $user->getName(),
890 'img_metadata' => $this->metadata
,
891 'img_sha1' => $this->sha1
892 ), array( /* WHERE */
893 'img_name' => $this->getName()
898 # Update the image count
899 $site_stats = $dbw->tableName( 'site_stats' );
900 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
903 $descTitle = $this->getTitle();
904 $article = new ImagePage( $descTitle );
905 $article->setFile( $this );
908 $log = new LogPage( 'upload' );
909 $action = $reupload ?
'overwrite' : 'upload';
910 $log->addEntry( $action, $descTitle, $comment, array(), $user );
912 if( $descTitle->exists() ) {
913 # Create a null revision
914 $latest = $descTitle->getLatestRevID();
915 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(),
916 $log->getRcComment(), false );
917 $nullRevision->insertOn( $dbw );
919 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
920 $article->updateRevisionOn( $dbw, $nullRevision );
922 # Invalidate the cache for the description page
923 $descTitle->invalidateCache();
924 $descTitle->purgeSquid();
926 // New file; create the description page.
927 // There's already a log entry, so don't make a second RC entry
928 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
931 # Hooks, hooks, the magic of hooks...
932 wfRunHooks( 'FileUpload', array( $this ) );
934 # Commit the transaction now, in case something goes wrong later
935 # The most important thing is that files don't get lost, especially archives
938 # Invalidate cache for all pages using this file
939 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
941 # Invalidate cache for all pages that redirects on this page
942 $redirs = $this->getTitle()->getRedirectsHere();
943 foreach( $redirs as $redir ) {
944 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
952 * Move or copy a file to its public location. If a file exists at the
953 * destination, move it to an archive. Returns a FileRepoStatus object with
954 * the archive name in the "value" member on success.
956 * The archive name should be passed through to recordUpload for database
959 * @param $srcPath String: local filesystem path to the source image
960 * @param $flags Integer: a bitwise combination of:
961 * File::DELETE_SOURCE Delete the source file, i.e. move
963 * @return FileRepoStatus object. On success, the value member contains the
964 * archive name, or an empty string if it was a new file.
966 function publish( $srcPath, $flags = 0 ) {
968 $dstRel = $this->getRel();
969 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
970 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
971 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
972 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
973 if ( $status->value
== 'new' ) {
976 $status->value
= $archiveName;
982 /** getLinksTo inherited */
983 /** getExifData inherited */
984 /** isLocal inherited */
985 /** wasDeleted inherited */
988 * Move file to the new title
990 * Move current, old version and all thumbnails
991 * to the new filename. Old file is deleted.
993 * Cache purging is done; checks for validity
994 * and logging are caller's responsibility
996 * @param $target Title New file name
997 * @return FileRepoStatus object.
999 function move( $target ) {
1000 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1002 $batch = new LocalFileMoveBatch( $this, $target );
1003 $batch->addCurrent();
1006 $status = $batch->execute();
1007 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1008 $this->purgeEverything();
1011 if ( $status->isOk() ) {
1012 // Now switch the object
1013 $this->title
= $target;
1014 // Force regeneration of the name and hashpath
1015 unset( $this->name
);
1016 unset( $this->hashPath
);
1017 // Purge the new image
1018 $this->purgeEverything();
1025 * Delete all versions of the file.
1027 * Moves the files into an archive directory (or deletes them)
1028 * and removes the database rows.
1030 * Cache purging is done; logging is caller's responsibility.
1034 * @return FileRepoStatus object.
1036 function delete( $reason, $suppress = false ) {
1038 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1039 $batch->addCurrent();
1041 # Get old version relative paths
1042 $dbw = $this->repo
->getMasterDB();
1043 $result = $dbw->select( 'oldimage',
1044 array( 'oi_archive_name' ),
1045 array( 'oi_name' => $this->getName() ) );
1046 while ( $row = $dbw->fetchObject( $result ) ) {
1047 $batch->addOld( $row->oi_archive_name
);
1049 $status = $batch->execute();
1051 if ( $status->ok
) {
1052 // Update site_stats
1053 $site_stats = $dbw->tableName( 'site_stats' );
1054 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1055 $this->purgeEverything();
1063 * Delete an old version of the file.
1065 * Moves the file into an archive directory (or deletes it)
1066 * and removes the database row.
1068 * Cache purging is done; logging is caller's responsibility.
1070 * @param $archiveName String
1071 * @param $reason String
1072 * @param $suppress Boolean
1073 * @throws MWException or FSException on database or file store failure
1074 * @return FileRepoStatus object.
1076 function deleteOld( $archiveName, $reason, $suppress=false ) {
1078 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1079 $batch->addOld( $archiveName );
1080 $status = $batch->execute();
1082 if ( $status->ok
) {
1083 $this->purgeDescription();
1084 $this->purgeHistory();
1090 * Restore all or specified deleted revisions to the given file.
1091 * Permissions and logging are left to the caller.
1093 * May throw database exceptions on error.
1095 * @param $versions set of record ids of deleted items to restore,
1096 * or empty to restore all revisions.
1097 * @param $unsuppress Boolean
1098 * @return FileRepoStatus
1100 function restore( $versions = array(), $unsuppress = false ) {
1101 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1105 $batch->addIds( $versions );
1107 $status = $batch->execute();
1108 if ( !$status->ok
) {
1112 $cleanupStatus = $batch->cleanup();
1113 $cleanupStatus->successCount
= 0;
1114 $cleanupStatus->failCount
= 0;
1115 $status->merge( $cleanupStatus );
1119 /** isMultipage inherited */
1120 /** pageCount inherited */
1121 /** scaleHeight inherited */
1122 /** getImageSize inherited */
1124 /** getDescriptionUrl inherited */
1125 /** getDescriptionText inherited */
1127 function getDescription() {
1129 return $this->description
;
1132 function getTimestamp() {
1134 return $this->timestamp
;
1137 function getSha1() {
1139 // Initialise now if necessary
1140 if ( $this->sha1
== '' && $this->fileExists
) {
1141 $this->sha1
= File
::sha1Base36( $this->getPath() );
1142 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1143 $dbw = $this->repo
->getMasterDB();
1144 $dbw->update( 'image',
1145 array( 'img_sha1' => $this->sha1
),
1146 array( 'img_name' => $this->getName() ),
1148 $this->saveToCache();
1156 * Start a transaction and lock the image for update
1157 * Increments a reference counter if the lock is already held
1158 * @return boolean True if the image exists, false otherwise
1161 $dbw = $this->repo
->getMasterDB();
1162 if ( !$this->locked
) {
1166 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1170 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1171 * the transaction and thereby releases the image lock.
1174 if ( $this->locked
) {
1176 if ( !$this->locked
) {
1177 $dbw = $this->repo
->getMasterDB();
1184 * Roll back the DB transaction and mark the image unlocked
1186 function unlockAndRollback() {
1187 $this->locked
= false;
1188 $dbw = $this->repo
->getMasterDB();
1191 } // LocalFile class
1193 #------------------------------------------------------------------------------
1196 * Helper class for file deletion
1199 class LocalFileDeleteBatch
{
1200 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1203 function __construct( File
$file, $reason = '', $suppress = false ) {
1204 $this->file
= $file;
1205 $this->reason
= $reason;
1206 $this->suppress
= $suppress;
1207 $this->status
= $file->repo
->newGood();
1210 function addCurrent() {
1211 $this->srcRels
['.'] = $this->file
->getRel();
1214 function addOld( $oldName ) {
1215 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1216 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1219 function getOldRels() {
1220 if ( !isset( $this->srcRels
['.'] ) ) {
1221 $oldRels =& $this->srcRels
;
1222 $deleteCurrent = false;
1224 $oldRels = $this->srcRels
;
1225 unset( $oldRels['.'] );
1226 $deleteCurrent = true;
1228 return array( $oldRels, $deleteCurrent );
1231 /*protected*/ function getHashes() {
1233 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1234 if ( $deleteCurrent ) {
1235 $hashes['.'] = $this->file
->getSha1();
1237 if ( count( $oldRels ) ) {
1238 $dbw = $this->file
->repo
->getMasterDB();
1239 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1240 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1242 while ( $row = $dbw->fetchObject( $res ) ) {
1243 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1244 // Get the hash from the file
1245 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1246 $props = $this->file
->repo
->getFileProps( $oldUrl );
1247 if ( $props['fileExists'] ) {
1248 // Upgrade the oldimage row
1249 $dbw->update( 'oldimage',
1250 array( 'oi_sha1' => $props['sha1'] ),
1251 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1253 $hashes[$row->oi_archive_name
] = $props['sha1'];
1255 $hashes[$row->oi_archive_name
] = false;
1258 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1262 $missing = array_diff_key( $this->srcRels
, $hashes );
1263 foreach ( $missing as $name => $rel ) {
1264 $this->status
->error( 'filedelete-old-unregistered', $name );
1266 foreach ( $hashes as $name => $hash ) {
1268 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1269 unset( $hashes[$name] );
1276 function doDBInserts() {
1278 $dbw = $this->file
->repo
->getMasterDB();
1279 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1280 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1281 $encReason = $dbw->addQuotes( $this->reason
);
1282 $encGroup = $dbw->addQuotes( 'deleted' );
1283 $ext = $this->file
->getExtension();
1284 $dotExt = $ext === '' ?
'' : ".$ext";
1285 $encExt = $dbw->addQuotes( $dotExt );
1286 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1288 // Bitfields to further suppress the content
1289 if ( $this->suppress
) {
1291 // This should be 15...
1292 $bitfield |
= Revision
::DELETED_TEXT
;
1293 $bitfield |
= Revision
::DELETED_COMMENT
;
1294 $bitfield |
= Revision
::DELETED_USER
;
1295 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1297 $bitfield = 'oi_deleted';
1300 if ( $deleteCurrent ) {
1301 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1302 $where = array( 'img_name' => $this->file
->getName() );
1303 $dbw->insertSelect( 'filearchive', 'image',
1305 'fa_storage_group' => $encGroup,
1306 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1307 'fa_deleted_user' => $encUserId,
1308 'fa_deleted_timestamp' => $encTimestamp,
1309 'fa_deleted_reason' => $encReason,
1310 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1312 'fa_name' => 'img_name',
1313 'fa_archive_name' => 'NULL',
1314 'fa_size' => 'img_size',
1315 'fa_width' => 'img_width',
1316 'fa_height' => 'img_height',
1317 'fa_metadata' => 'img_metadata',
1318 'fa_bits' => 'img_bits',
1319 'fa_media_type' => 'img_media_type',
1320 'fa_major_mime' => 'img_major_mime',
1321 'fa_minor_mime' => 'img_minor_mime',
1322 'fa_description' => 'img_description',
1323 'fa_user' => 'img_user',
1324 'fa_user_text' => 'img_user_text',
1325 'fa_timestamp' => 'img_timestamp'
1326 ), $where, __METHOD__
);
1329 if ( count( $oldRels ) ) {
1330 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1332 'oi_name' => $this->file
->getName(),
1333 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1334 $dbw->insertSelect( 'filearchive', 'oldimage',
1336 'fa_storage_group' => $encGroup,
1337 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1338 'fa_deleted_user' => $encUserId,
1339 'fa_deleted_timestamp' => $encTimestamp,
1340 'fa_deleted_reason' => $encReason,
1341 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1343 'fa_name' => 'oi_name',
1344 'fa_archive_name' => 'oi_archive_name',
1345 'fa_size' => 'oi_size',
1346 'fa_width' => 'oi_width',
1347 'fa_height' => 'oi_height',
1348 'fa_metadata' => 'oi_metadata',
1349 'fa_bits' => 'oi_bits',
1350 'fa_media_type' => 'oi_media_type',
1351 'fa_major_mime' => 'oi_major_mime',
1352 'fa_minor_mime' => 'oi_minor_mime',
1353 'fa_description' => 'oi_description',
1354 'fa_user' => 'oi_user',
1355 'fa_user_text' => 'oi_user_text',
1356 'fa_timestamp' => 'oi_timestamp',
1357 'fa_deleted' => $bitfield
1358 ), $where, __METHOD__
);
1362 function doDBDeletes() {
1363 $dbw = $this->file
->repo
->getMasterDB();
1364 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1365 if ( count( $oldRels ) ) {
1366 $dbw->delete( 'oldimage',
1368 'oi_name' => $this->file
->getName(),
1369 'oi_archive_name' => array_keys( $oldRels )
1372 if ( $deleteCurrent ) {
1373 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1378 * Run the transaction
1380 function execute() {
1382 wfProfileIn( __METHOD__
);
1384 $this->file
->lock();
1385 // Leave private files alone
1386 $privateFiles = array();
1387 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1388 $dbw = $this->file
->repo
->getMasterDB();
1389 if( !empty( $oldRels ) ) {
1390 $res = $dbw->select( 'oldimage',
1391 array( 'oi_archive_name' ),
1392 array( 'oi_name' => $this->file
->getName(),
1393 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1394 $dbw->bitAnd('oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1396 while( $row = $dbw->fetchObject( $res ) ) {
1397 $privateFiles[$row->oi_archive_name
] = 1;
1400 // Prepare deletion batch
1401 $hashes = $this->getHashes();
1402 $this->deletionBatch
= array();
1403 $ext = $this->file
->getExtension();
1404 $dotExt = $ext === '' ?
'' : ".$ext";
1405 foreach ( $this->srcRels
as $name => $srcRel ) {
1406 // Skip files that have no hash (missing source).
1407 // Keep private files where they are.
1408 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1409 $hash = $hashes[$name];
1410 $key = $hash . $dotExt;
1411 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1412 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1416 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1417 // We acquire this lock by running the inserts now, before the file operations.
1419 // This potentially has poor lock contention characteristics -- an alternative
1420 // scheme would be to insert stub filearchive entries with no fa_name and commit
1421 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1422 $this->doDBInserts();
1424 // Removes non-existent file from the batch, so we don't get errors.
1425 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1427 // Execute the file deletion batch
1428 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1429 if ( !$status->isGood() ) {
1430 $this->status
->merge( $status );
1433 if ( !$this->status
->ok
) {
1434 // Critical file deletion error
1435 // Roll back inserts, release lock and abort
1436 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1437 $this->file
->unlockAndRollback();
1438 wfProfileOut( __METHOD__
);
1439 return $this->status
;
1443 if ( $wgUseSquid ) {
1445 foreach ( $this->srcRels
as $srcRel ) {
1446 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1447 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1449 SquidUpdate
::purge( $urls );
1452 // Delete image/oldimage rows
1453 $this->doDBDeletes();
1455 // Commit and return
1456 $this->file
->unlock();
1457 wfProfileOut( __METHOD__
);
1458 return $this->status
;
1462 * Removes non-existent files from a deletion batch.
1464 function removeNonexistentFiles( $batch ) {
1465 $files = $newBatch = array();
1466 foreach( $batch as $batchItem ) {
1467 list( $src, $dest ) = $batchItem;
1468 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1470 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1471 foreach( $batch as $batchItem )
1472 if( $result[$batchItem[0]] )
1473 $newBatch[] = $batchItem;
1478 #------------------------------------------------------------------------------
1481 * Helper class for file undeletion
1484 class LocalFileRestoreBatch
{
1485 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1487 function __construct( File
$file, $unsuppress = false ) {
1488 $this->file
= $file;
1489 $this->cleanupBatch
= $this->ids
= array();
1490 $this->ids
= array();
1491 $this->unsuppress
= $unsuppress;
1497 function addId( $fa_id ) {
1498 $this->ids
[] = $fa_id;
1502 * Add a whole lot of files by ID
1504 function addIds( $ids ) {
1505 $this->ids
= array_merge( $this->ids
, $ids );
1509 * Add all revisions of the file
1516 * Run the transaction, except the cleanup batch.
1517 * The cleanup batch should be run in a separate transaction, because it locks different
1518 * rows and there's no need to keep the image row locked while it's acquiring those locks
1519 * The caller may have its own transaction open.
1520 * So we save the batch and let the caller call cleanup()
1522 function execute() {
1524 if ( !$this->all
&& !$this->ids
) {
1526 return $this->file
->repo
->newGood();
1529 $exists = $this->file
->lock();
1530 $dbw = $this->file
->repo
->getMasterDB();
1531 $status = $this->file
->repo
->newGood();
1533 // Fetch all or selected archived revisions for the file,
1534 // sorted from the most recent to the oldest.
1535 $conditions = array( 'fa_name' => $this->file
->getName() );
1537 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1540 $result = $dbw->select( 'filearchive', '*',
1543 array( 'ORDER BY' => 'fa_timestamp DESC' )
1546 $idsPresent = array();
1547 $storeBatch = array();
1548 $insertBatch = array();
1549 $insertCurrent = false;
1550 $deleteIds = array();
1552 $archiveNames = array();
1553 while( $row = $dbw->fetchObject( $result ) ) {
1554 $idsPresent[] = $row->fa_id
;
1556 if ( $row->fa_name
!= $this->file
->getName() ) {
1557 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1558 $status->failCount++
;
1561 if ( $row->fa_storage_key
== '' ) {
1562 // Revision was missing pre-deletion
1563 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1564 $status->failCount++
;
1568 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1569 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1571 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1573 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1574 $sha1 = substr( $sha1, 1 );
1577 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1578 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1579 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1580 ||
is_null( $row->fa_metadata
) ) {
1581 // Refresh our metadata
1582 // Required for a new current revision; nice for older ones too. :)
1583 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1586 'minor_mime' => $row->fa_minor_mime
,
1587 'major_mime' => $row->fa_major_mime
,
1588 'media_type' => $row->fa_media_type
,
1589 'metadata' => $row->fa_metadata
1593 if ( $first && !$exists ) {
1594 // This revision will be published as the new current version
1595 $destRel = $this->file
->getRel();
1596 $insertCurrent = array(
1597 'img_name' => $row->fa_name
,
1598 'img_size' => $row->fa_size
,
1599 'img_width' => $row->fa_width
,
1600 'img_height' => $row->fa_height
,
1601 'img_metadata' => $props['metadata'],
1602 'img_bits' => $row->fa_bits
,
1603 'img_media_type' => $props['media_type'],
1604 'img_major_mime' => $props['major_mime'],
1605 'img_minor_mime' => $props['minor_mime'],
1606 'img_description' => $row->fa_description
,
1607 'img_user' => $row->fa_user
,
1608 'img_user_text' => $row->fa_user_text
,
1609 'img_timestamp' => $row->fa_timestamp
,
1612 // The live (current) version cannot be hidden!
1613 if( !$this->unsuppress
&& $row->fa_deleted
) {
1614 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1615 $this->cleanupBatch
[] = $row->fa_storage_key
;
1618 $archiveName = $row->fa_archive_name
;
1619 if( $archiveName == '' ) {
1620 // This was originally a current version; we
1621 // have to devise a new archive name for it.
1622 // Format is <timestamp of archiving>!<name>
1623 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1625 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1627 } while ( isset( $archiveNames[$archiveName] ) );
1629 $archiveNames[$archiveName] = true;
1630 $destRel = $this->file
->getArchiveRel( $archiveName );
1631 $insertBatch[] = array(
1632 'oi_name' => $row->fa_name
,
1633 'oi_archive_name' => $archiveName,
1634 'oi_size' => $row->fa_size
,
1635 'oi_width' => $row->fa_width
,
1636 'oi_height' => $row->fa_height
,
1637 'oi_bits' => $row->fa_bits
,
1638 'oi_description' => $row->fa_description
,
1639 'oi_user' => $row->fa_user
,
1640 'oi_user_text' => $row->fa_user_text
,
1641 'oi_timestamp' => $row->fa_timestamp
,
1642 'oi_metadata' => $props['metadata'],
1643 'oi_media_type' => $props['media_type'],
1644 'oi_major_mime' => $props['major_mime'],
1645 'oi_minor_mime' => $props['minor_mime'],
1646 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1647 'oi_sha1' => $sha1 );
1650 $deleteIds[] = $row->fa_id
;
1651 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1652 // private files can stay where they are
1653 $status->successCount++
;
1655 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1656 $this->cleanupBatch
[] = $row->fa_storage_key
;
1662 // Add a warning to the status object for missing IDs
1663 $missingIds = array_diff( $this->ids
, $idsPresent );
1664 foreach ( $missingIds as $id ) {
1665 $status->error( 'undelete-missing-filearchive', $id );
1668 // Remove missing files from batch, so we don't get errors when undeleting them
1669 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1671 // Run the store batch
1672 // Use the OVERWRITE_SAME flag to smooth over a common error
1673 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1674 $status->merge( $storeStatus );
1676 if ( !$status->ok
) {
1677 // Store batch returned a critical error -- this usually means nothing was stored
1678 // Stop now and return an error
1679 $this->file
->unlock();
1683 // Run the DB updates
1684 // Because we have locked the image row, key conflicts should be rare.
1685 // If they do occur, we can roll back the transaction at this time with
1686 // no data loss, but leaving unregistered files scattered throughout the
1688 // This is not ideal, which is why it's important to lock the image row.
1689 if ( $insertCurrent ) {
1690 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1692 if ( $insertBatch ) {
1693 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1696 $dbw->delete( 'filearchive',
1697 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1701 // If store batch is empty (all files are missing), deletion is to be considered successful
1702 if( $status->successCount
> 0 ||
!$storeBatch ) {
1704 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1706 // Update site_stats
1707 $site_stats = $dbw->tableName( 'site_stats' );
1708 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1710 $this->file
->purgeEverything();
1712 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1713 $this->file
->purgeDescription();
1714 $this->file
->purgeHistory();
1717 $this->file
->unlock();
1722 * Removes non-existent files from a store batch.
1724 function removeNonexistentFiles( $triplets ) {
1725 $files = $filteredTriplets = array();
1726 foreach( $triplets as $file )
1727 $files[$file[0]] = $file[0];
1728 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1729 foreach( $triplets as $file )
1730 if( $result[$file[0]] )
1731 $filteredTriplets[] = $file;
1732 return $filteredTriplets;
1736 * Removes non-existent files from a cleanup batch.
1738 function removeNonexistentFromCleanup( $batch ) {
1739 $files = $newBatch = array();
1740 $repo = $this->file
->repo
;
1741 foreach( $batch as $file ) {
1742 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1743 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1746 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1747 foreach( $batch as $file )
1748 if( $result[$file] )
1749 $newBatch[] = $file;
1754 * Delete unused files in the deleted zone.
1755 * This should be called from outside the transaction in which execute() was called.
1757 function cleanup() {
1758 if ( !$this->cleanupBatch
) {
1759 return $this->file
->repo
->newGood();
1761 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1762 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1767 #------------------------------------------------------------------------------
1770 * Helper class for file movement
1773 class LocalFileMoveBatch
{
1774 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1776 function __construct( File
$file, Title
$target ) {
1777 $this->file
= $file;
1778 $this->target
= $target;
1779 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1780 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1781 $this->oldName
= $this->file
->getName();
1782 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1783 $this->oldRel
= $this->oldHash
. $this->oldName
;
1784 $this->newRel
= $this->newHash
. $this->newName
;
1785 $this->db
= $file->repo
->getMasterDb();
1789 * Add the current image to the batch
1791 function addCurrent() {
1792 $this->cur
= array( $this->oldRel
, $this->newRel
);
1796 * Add the old versions of the image to the batch
1798 function addOlds() {
1799 $archiveBase = 'archive';
1800 $this->olds
= array();
1801 $this->oldCount
= 0;
1803 $result = $this->db
->select( 'oldimage',
1804 array( 'oi_archive_name', 'oi_deleted' ),
1805 array( 'oi_name' => $this->oldName
),
1808 while( $row = $this->db
->fetchObject( $result ) ) {
1809 $oldName = $row->oi_archive_name
;
1810 $bits = explode( '!', $oldName, 2 );
1811 if( count( $bits ) != 2 ) {
1812 wfDebug( "Invalid old file name: $oldName \n" );
1815 list( $timestamp, $filename ) = $bits;
1816 if( $this->oldName
!= $filename ) {
1817 wfDebug( "Invalid old file name: $oldName \n" );
1821 // Do we want to add those to oldCount?
1822 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1825 $this->olds
[] = array(
1826 "{$archiveBase}/{$this->oldHash}{$oldName}",
1827 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1830 $this->db
->freeResult( $result );
1836 function execute() {
1837 $repo = $this->file
->repo
;
1838 $status = $repo->newGood();
1839 $triplets = $this->getMoveTriplets();
1841 $triplets = $this->removeNonexistentFiles( $triplets );
1842 $statusDb = $this->doDBUpdates();
1843 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1844 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1845 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1846 if( !$statusMove->isOk() ) {
1847 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1848 $this->db
->rollback();
1851 $status->merge( $statusDb );
1852 $status->merge( $statusMove );
1857 * Do the database updates and return a new FileRepoStatus indicating how
1858 * many rows where updated.
1860 * @return FileRepoStatus
1862 function doDBUpdates() {
1863 $repo = $this->file
->repo
;
1864 $status = $repo->newGood();
1867 // Update current image
1870 array( 'img_name' => $this->newName
),
1871 array( 'img_name' => $this->oldName
),
1874 if( $dbw->affectedRows() ) {
1875 $status->successCount++
;
1877 $status->failCount++
;
1880 // Update old images
1884 'oi_name' => $this->newName
,
1885 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1887 array( 'oi_name' => $this->oldName
),
1890 $affected = $dbw->affectedRows();
1891 $total = $this->oldCount
;
1892 $status->successCount +
= $affected;
1893 $status->failCount +
= $total - $affected;
1899 * Generate triplets for FSRepo::storeBatch().
1901 function getMoveTriplets() {
1902 $moves = array_merge( array( $this->cur
), $this->olds
);
1903 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1904 foreach( $moves as $move ) {
1905 // $move: (oldRelativePath, newRelativePath)
1906 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1907 $triplets[] = array( $srcUrl, 'public', $move[1] );
1908 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
1914 * Removes non-existent files from move batch.
1916 function removeNonexistentFiles( $triplets ) {
1918 foreach( $triplets as $file )
1919 $files[$file[0]] = $file[0];
1920 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1921 $filteredTriplets = array();
1922 foreach( $triplets as $file )
1923 if( $result[$file[0]] ) {
1924 $filteredTriplets[] = $file;
1926 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
1928 return $filteredTriplets;