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];
381 // Fix up mime fields
382 if ( isset( $info['major_mime'] ) ) {
383 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
384 } elseif ( isset( $info['mime'] ) ) {
385 $this->mime
= $info['mime'];
386 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
390 /** splitMime inherited */
391 /** getName inherited */
392 /** getTitle inherited */
393 /** getURL inherited */
394 /** getViewURL inherited */
395 /** getPath inherited */
396 /** isVisible inhereted */
398 function isMissing() {
399 if( $this->missing
=== null ) {
400 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
401 $this->missing
= !$fileExists;
403 return $this->missing
;
407 * Return the width of the image
409 * Returns false on error
411 public function getWidth( $page = 1 ) {
413 if ( $this->isMultipage() ) {
414 $dim = $this->getHandler()->getPageDimensions( $this, $page );
416 return $dim['width'];
426 * Return the height of the image
428 * Returns false on error
430 public function getHeight( $page = 1 ) {
432 if ( $this->isMultipage() ) {
433 $dim = $this->getHandler()->getPageDimensions( $this, $page );
435 return $dim['height'];
440 return $this->height
;
445 * Returns ID or name of user who uploaded the file
447 * @param $type string 'text' or 'id'
449 function getUser( $type = 'text' ) {
451 if( $type == 'text' ) {
452 return $this->user_text
;
453 } elseif( $type == 'id' ) {
459 * Get handler-specific metadata
461 function getMetadata() {
463 return $this->metadata
;
466 function getBitDepth() {
472 * Return the size of the image file, in bytes
474 public function getSize() {
480 * Returns the mime type of the file.
482 function getMimeType() {
488 * Return the type of the media in the file.
489 * Use the value returned by this function with the MEDIATYPE_xxx constants.
491 function getMediaType() {
493 return $this->media_type
;
496 /** canRender inherited */
497 /** mustRender inherited */
498 /** allowInlineDisplay inherited */
499 /** isSafeFile inherited */
500 /** isTrustedFile inherited */
503 * Returns true if the file file exists on disk.
504 * @return boolean Whether file file exist on disk.
506 public function exists() {
508 return $this->fileExists
;
511 /** getTransformScript inherited */
512 /** getUnscaledThumb inherited */
513 /** thumbName inherited */
514 /** createThumb inherited */
515 /** getThumbnail inherited */
516 /** transform inherited */
519 * Fix thumbnail files from 1.4 or before, with extreme prejudice
521 function migrateThumbFile( $thumbName ) {
522 $thumbDir = $this->getThumbPath();
523 $thumbPath = "$thumbDir/$thumbName";
524 if ( is_dir( $thumbPath ) ) {
525 // Directory where file should be
526 // This happened occasionally due to broken migration code in 1.5
527 // Rename to broken-*
528 for ( $i = 0; $i < 100 ; $i++
) {
529 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
530 if ( !file_exists( $broken ) ) {
531 rename( $thumbPath, $broken );
535 // Doesn't exist anymore
538 if ( is_file( $thumbDir ) ) {
539 // File where directory should be
541 // Doesn't exist anymore
546 /** getHandler inherited */
547 /** iconThumb inherited */
548 /** getLastError inherited */
551 * Get all thumbnail names previously generated for this file
553 function getThumbnails() {
556 $dir = $this->getThumbPath();
558 if ( is_dir( $dir ) ) {
559 $handle = opendir( $dir );
562 while ( false !== ( $file = readdir( $handle ) ) ) {
563 if ( $file{0} != '.' ) {
575 * Refresh metadata in memcached, but don't touch thumbnails or squid
577 function purgeMetadataCache() {
579 $this->saveToCache();
580 $this->purgeHistory();
584 * Purge the shared history (OldLocalFile) cache
586 function purgeHistory() {
588 $hashedName = md5( $this->getName() );
589 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
591 $wgMemc->delete( $oldKey );
596 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
598 function purgeCache() {
599 // Refresh metadata cache
600 $this->purgeMetadataCache();
603 $this->purgeThumbnails();
605 // Purge squid cache for this file
606 SquidUpdate
::purge( array( $this->getURL() ) );
610 * Delete cached transformed files
612 function purgeThumbnails() {
615 $files = $this->getThumbnails();
616 $dir = $this->getThumbPath();
618 foreach ( $files as $file ) {
619 # Check that the base file name is part of the thumb name
620 # This is a basic sanity check to avoid erasing unrelated directories
621 if ( strpos( $file, $this->getName() ) !== false ) {
622 $url = $this->getThumbUrl( $file );
624 @unlink
( "$dir/$file" );
630 SquidUpdate
::purge( $urls );
634 /** purgeDescription inherited */
635 /** purgeEverything inherited */
637 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
638 $dbr = $this->repo
->getSlaveDB();
639 $tables = array( 'oldimage' );
640 $fields = OldLocalFile
::selectFields();
641 $conds = $opts = $join_conds = array();
642 $eq = $inc ?
'=' : '';
643 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
645 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
648 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
651 $opts['LIMIT'] = $limit;
653 // Search backwards for time > x queries
654 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
655 $opts['ORDER BY'] = "oi_timestamp $order";
656 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
658 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
659 &$conds, &$opts, &$join_conds ) );
661 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
663 while( $row = $dbr->fetchObject( $res ) ) {
664 if ( $this->repo
->oldFileFromRowFactory
) {
665 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
667 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
670 if( $order == 'ASC' ) {
671 $r = array_reverse( $r ); // make sure it ends up descending
677 * Return the history of this file, line by line.
678 * starts with current version, then old versions.
679 * uses $this->historyLine to check which line to return:
680 * 0 return line for current version
681 * 1 query for old versions, return first one
682 * 2, ... return next old version from above query
684 public function nextHistoryLine() {
685 # Polymorphic function name to distinguish foreign and local fetches
686 $fname = get_class( $this ) . '::' . __FUNCTION__
;
688 $dbr = $this->repo
->getSlaveDB();
690 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
691 $this->historyRes
= $dbr->select( 'image',
694 "'' AS oi_archive_name",
698 array( 'img_name' => $this->title
->getDBkey() ),
701 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
702 $this->historyRes
= null;
705 } elseif ( $this->historyLine
== 1 ) {
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->historyRes
= null;
727 /** getFullPath inherited */
728 /** getHashPath inherited */
729 /** getRel inherited */
730 /** getUrlRel inherited */
731 /** getArchiveRel inherited */
732 /** getThumbRel inherited */
733 /** getArchivePath inherited */
734 /** getThumbPath inherited */
735 /** getArchiveUrl inherited */
736 /** getThumbUrl inherited */
737 /** getArchiveVirtualUrl inherited */
738 /** getThumbVirtualUrl inherited */
739 /** isHashed inherited */
742 * Upload a file and record it in the DB
743 * @param $srcPath String: source path or virtual URL
744 * @param $comment String: upload description
745 * @param $pageText String: text to use for the new description page,
746 * if a new description page is created
747 * @param $flags Integer: flags for publish()
748 * @param $props Array: File properties, if known. This can be used to reduce the
749 * upload time when uploading virtual URLs for which the file info
751 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
752 * @param $user Mixed: User object or null to use $wgUser
754 * @return FileRepoStatus object. On success, the value member contains the
755 * archive name, or an empty string if it was a new file.
757 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
759 $status = $this->publish( $srcPath, $flags );
761 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
762 $status->fatal( 'filenotfound', $srcPath );
770 * Record a file upload in the upload log and the image table
771 * @deprecated use upload()
773 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
774 $watch = false, $timestamp = false )
776 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
777 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
782 $wgUser->addWatch( $this->getTitle() );
789 * Record a file upload in the upload log and the image table
791 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
793 if( is_null( $user ) ) {
798 $dbw = $this->repo
->getMasterDB();
802 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
804 $props['description'] = $comment;
805 $props['user'] = $user->getId();
806 $props['user_text'] = $user->getName();
807 $props['timestamp'] = wfTimestamp( TS_MW
);
808 $this->setProps( $props );
811 $this->purgeThumbnails();
812 # The file is already on its final location, remove it from the squid cache
813 SquidUpdate
::purge( array( $this->getURL() ) );
815 # Fail now if the file isn't there
816 if ( !$this->fileExists
) {
817 wfDebug( __METHOD__
. ": File " . $this->getPath() . " went missing!\n" );
822 if ( $timestamp === false ) {
823 $timestamp = $dbw->timestamp();
826 # Test to see if the row exists using INSERT IGNORE
827 # This avoids race conditions by locking the row until the commit, and also
828 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
829 $dbw->insert( 'image',
831 'img_name' => $this->getName(),
832 'img_size'=> $this->size
,
833 'img_width' => intval( $this->width
),
834 'img_height' => intval( $this->height
),
835 'img_bits' => $this->bits
,
836 'img_media_type' => $this->media_type
,
837 'img_major_mime' => $this->major_mime
,
838 'img_minor_mime' => $this->minor_mime
,
839 'img_timestamp' => $timestamp,
840 'img_description' => $comment,
841 'img_user' => $user->getId(),
842 'img_user_text' => $user->getName(),
843 'img_metadata' => $this->metadata
,
844 'img_sha1' => $this->sha1
850 if( $dbw->affectedRows() == 0 ) {
853 # Collision, this is an update of a file
854 # Insert previous contents into oldimage
855 $dbw->insertSelect( 'oldimage', 'image',
857 'oi_name' => 'img_name',
858 'oi_archive_name' => $dbw->addQuotes( $oldver ),
859 'oi_size' => 'img_size',
860 'oi_width' => 'img_width',
861 'oi_height' => 'img_height',
862 'oi_bits' => 'img_bits',
863 'oi_timestamp' => 'img_timestamp',
864 'oi_description' => 'img_description',
865 'oi_user' => 'img_user',
866 'oi_user_text' => 'img_user_text',
867 'oi_metadata' => 'img_metadata',
868 'oi_media_type' => 'img_media_type',
869 'oi_major_mime' => 'img_major_mime',
870 'oi_minor_mime' => 'img_minor_mime',
871 'oi_sha1' => 'img_sha1'
872 ), array( 'img_name' => $this->getName() ), __METHOD__
875 # Update the current image row
876 $dbw->update( 'image',
878 'img_size' => $this->size
,
879 'img_width' => intval( $this->width
),
880 'img_height' => intval( $this->height
),
881 'img_bits' => $this->bits
,
882 'img_media_type' => $this->media_type
,
883 'img_major_mime' => $this->major_mime
,
884 'img_minor_mime' => $this->minor_mime
,
885 'img_timestamp' => $timestamp,
886 'img_description' => $comment,
887 'img_user' => $user->getId(),
888 'img_user_text' => $user->getName(),
889 'img_metadata' => $this->metadata
,
890 'img_sha1' => $this->sha1
891 ), array( /* WHERE */
892 'img_name' => $this->getName()
897 # Update the image count
898 $site_stats = $dbw->tableName( 'site_stats' );
899 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
902 $descTitle = $this->getTitle();
903 $article = new ImagePage( $descTitle );
904 $article->setFile( $this );
907 $log = new LogPage( 'upload' );
908 $action = $reupload ?
'overwrite' : 'upload';
909 $log->addEntry( $action, $descTitle, $comment, array(), $user );
911 if( $descTitle->exists() ) {
912 # Create a null revision
913 $latest = $descTitle->getLatestRevID();
914 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(),
915 $log->getRcComment(), false );
916 $nullRevision->insertOn( $dbw );
918 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
919 $article->updateRevisionOn( $dbw, $nullRevision );
921 # Invalidate the cache for the description page
922 $descTitle->invalidateCache();
923 $descTitle->purgeSquid();
925 # New file; create the description page.
926 # There's already a log entry, so don't make a second RC entry
927 # Squid and file cache for the description page are purged by doEdit.
928 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
931 # Commit the transaction now, in case something goes wrong later
932 # The most important thing is that files don't get lost, especially archives
935 # Save to cache and purge the squid
936 # We shall not saveToCache before the commit since otherwise
937 # in case of a rollback there is an usable file from memcached
938 # which in fact doesn't really exist (bug 24978)
939 $this->saveToCache();
941 # Hooks, hooks, the magic of hooks...
942 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
944 # Invalidate cache for all pages using this file
945 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
947 # Invalidate cache for all pages that redirects on this page
948 $redirs = $this->getTitle()->getRedirectsHere();
949 foreach( $redirs as $redir ) {
950 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
958 * Move or copy a file to its public location. If a file exists at the
959 * destination, move it to an archive. Returns a FileRepoStatus object with
960 * the archive name in the "value" member on success.
962 * The archive name should be passed through to recordUpload for database
965 * @param $srcPath String: local filesystem path to the source image
966 * @param $flags Integer: a bitwise combination of:
967 * File::DELETE_SOURCE Delete the source file, i.e. move
969 * @return FileRepoStatus object. On success, the value member contains the
970 * archive name, or an empty string if it was a new file.
972 function publish( $srcPath, $flags = 0 ) {
974 $dstRel = $this->getRel();
975 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
976 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
977 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
978 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
979 if ( $status->value
== 'new' ) {
982 $status->value
= $archiveName;
988 /** getLinksTo inherited */
989 /** getExifData inherited */
990 /** isLocal inherited */
991 /** wasDeleted inherited */
994 * Move file to the new title
996 * Move current, old version and all thumbnails
997 * to the new filename. Old file is deleted.
999 * Cache purging is done; checks for validity
1000 * and logging are caller's responsibility
1002 * @param $target Title New file name
1003 * @return FileRepoStatus object.
1005 function move( $target ) {
1006 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1008 $batch = new LocalFileMoveBatch( $this, $target );
1009 $batch->addCurrent();
1012 $status = $batch->execute();
1013 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1014 $this->purgeEverything();
1017 if ( $status->isOk() ) {
1018 // Now switch the object
1019 $this->title
= $target;
1020 // Force regeneration of the name and hashpath
1021 unset( $this->name
);
1022 unset( $this->hashPath
);
1023 // Purge the new image
1024 $this->purgeEverything();
1031 * Delete all versions of the file.
1033 * Moves the files into an archive directory (or deletes them)
1034 * and removes the database rows.
1036 * Cache purging is done; logging is caller's responsibility.
1040 * @return FileRepoStatus object.
1042 function delete( $reason, $suppress = false ) {
1044 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1045 $batch->addCurrent();
1047 # Get old version relative paths
1048 $dbw = $this->repo
->getMasterDB();
1049 $result = $dbw->select( 'oldimage',
1050 array( 'oi_archive_name' ),
1051 array( 'oi_name' => $this->getName() ) );
1052 while ( $row = $dbw->fetchObject( $result ) ) {
1053 $batch->addOld( $row->oi_archive_name
);
1055 $status = $batch->execute();
1057 if ( $status->ok
) {
1058 // Update site_stats
1059 $site_stats = $dbw->tableName( 'site_stats' );
1060 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1061 $this->purgeEverything();
1069 * Delete an old version of the file.
1071 * Moves the file into an archive directory (or deletes it)
1072 * and removes the database row.
1074 * Cache purging is done; logging is caller's responsibility.
1076 * @param $archiveName String
1077 * @param $reason String
1078 * @param $suppress Boolean
1079 * @throws MWException or FSException on database or file store failure
1080 * @return FileRepoStatus object.
1082 function deleteOld( $archiveName, $reason, $suppress=false ) {
1084 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1085 $batch->addOld( $archiveName );
1086 $status = $batch->execute();
1088 if ( $status->ok
) {
1089 $this->purgeDescription();
1090 $this->purgeHistory();
1096 * Restore all or specified deleted revisions to the given file.
1097 * Permissions and logging are left to the caller.
1099 * May throw database exceptions on error.
1101 * @param $versions set of record ids of deleted items to restore,
1102 * or empty to restore all revisions.
1103 * @param $unsuppress Boolean
1104 * @return FileRepoStatus
1106 function restore( $versions = array(), $unsuppress = false ) {
1107 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1111 $batch->addIds( $versions );
1113 $status = $batch->execute();
1114 if ( !$status->ok
) {
1118 $cleanupStatus = $batch->cleanup();
1119 $cleanupStatus->successCount
= 0;
1120 $cleanupStatus->failCount
= 0;
1121 $status->merge( $cleanupStatus );
1125 /** isMultipage inherited */
1126 /** pageCount inherited */
1127 /** scaleHeight inherited */
1128 /** getImageSize inherited */
1130 /** getDescriptionUrl inherited */
1131 /** getDescriptionText inherited */
1133 function getDescription() {
1135 return $this->description
;
1138 function getTimestamp() {
1140 return $this->timestamp
;
1143 function getSha1() {
1145 // Initialise now if necessary
1146 if ( $this->sha1
== '' && $this->fileExists
) {
1147 $this->sha1
= File
::sha1Base36( $this->getPath() );
1148 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1149 $dbw = $this->repo
->getMasterDB();
1150 $dbw->update( 'image',
1151 array( 'img_sha1' => $this->sha1
),
1152 array( 'img_name' => $this->getName() ),
1154 $this->saveToCache();
1162 * Start a transaction and lock the image for update
1163 * Increments a reference counter if the lock is already held
1164 * @return boolean True if the image exists, false otherwise
1167 $dbw = $this->repo
->getMasterDB();
1168 if ( !$this->locked
) {
1172 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1176 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1177 * the transaction and thereby releases the image lock.
1180 if ( $this->locked
) {
1182 if ( !$this->locked
) {
1183 $dbw = $this->repo
->getMasterDB();
1190 * Roll back the DB transaction and mark the image unlocked
1192 function unlockAndRollback() {
1193 $this->locked
= false;
1194 $dbw = $this->repo
->getMasterDB();
1197 } // LocalFile class
1199 #------------------------------------------------------------------------------
1202 * Helper class for file deletion
1205 class LocalFileDeleteBatch
{
1206 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1209 function __construct( File
$file, $reason = '', $suppress = false ) {
1210 $this->file
= $file;
1211 $this->reason
= $reason;
1212 $this->suppress
= $suppress;
1213 $this->status
= $file->repo
->newGood();
1216 function addCurrent() {
1217 $this->srcRels
['.'] = $this->file
->getRel();
1220 function addOld( $oldName ) {
1221 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1222 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1225 function getOldRels() {
1226 if ( !isset( $this->srcRels
['.'] ) ) {
1227 $oldRels =& $this->srcRels
;
1228 $deleteCurrent = false;
1230 $oldRels = $this->srcRels
;
1231 unset( $oldRels['.'] );
1232 $deleteCurrent = true;
1234 return array( $oldRels, $deleteCurrent );
1237 /*protected*/ function getHashes() {
1239 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1240 if ( $deleteCurrent ) {
1241 $hashes['.'] = $this->file
->getSha1();
1243 if ( count( $oldRels ) ) {
1244 $dbw = $this->file
->repo
->getMasterDB();
1245 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1246 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1248 while ( $row = $dbw->fetchObject( $res ) ) {
1249 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1250 // Get the hash from the file
1251 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1252 $props = $this->file
->repo
->getFileProps( $oldUrl );
1253 if ( $props['fileExists'] ) {
1254 // Upgrade the oldimage row
1255 $dbw->update( 'oldimage',
1256 array( 'oi_sha1' => $props['sha1'] ),
1257 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1259 $hashes[$row->oi_archive_name
] = $props['sha1'];
1261 $hashes[$row->oi_archive_name
] = false;
1264 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1268 $missing = array_diff_key( $this->srcRels
, $hashes );
1269 foreach ( $missing as $name => $rel ) {
1270 $this->status
->error( 'filedelete-old-unregistered', $name );
1272 foreach ( $hashes as $name => $hash ) {
1274 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1275 unset( $hashes[$name] );
1282 function doDBInserts() {
1284 $dbw = $this->file
->repo
->getMasterDB();
1285 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1286 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1287 $encReason = $dbw->addQuotes( $this->reason
);
1288 $encGroup = $dbw->addQuotes( 'deleted' );
1289 $ext = $this->file
->getExtension();
1290 $dotExt = $ext === '' ?
'' : ".$ext";
1291 $encExt = $dbw->addQuotes( $dotExt );
1292 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1294 // Bitfields to further suppress the content
1295 if ( $this->suppress
) {
1297 // This should be 15...
1298 $bitfield |
= Revision
::DELETED_TEXT
;
1299 $bitfield |
= Revision
::DELETED_COMMENT
;
1300 $bitfield |
= Revision
::DELETED_USER
;
1301 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1303 $bitfield = 'oi_deleted';
1306 if ( $deleteCurrent ) {
1307 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1308 $where = array( 'img_name' => $this->file
->getName() );
1309 $dbw->insertSelect( 'filearchive', 'image',
1311 'fa_storage_group' => $encGroup,
1312 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1313 'fa_deleted_user' => $encUserId,
1314 'fa_deleted_timestamp' => $encTimestamp,
1315 'fa_deleted_reason' => $encReason,
1316 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1318 'fa_name' => 'img_name',
1319 'fa_archive_name' => 'NULL',
1320 'fa_size' => 'img_size',
1321 'fa_width' => 'img_width',
1322 'fa_height' => 'img_height',
1323 'fa_metadata' => 'img_metadata',
1324 'fa_bits' => 'img_bits',
1325 'fa_media_type' => 'img_media_type',
1326 'fa_major_mime' => 'img_major_mime',
1327 'fa_minor_mime' => 'img_minor_mime',
1328 'fa_description' => 'img_description',
1329 'fa_user' => 'img_user',
1330 'fa_user_text' => 'img_user_text',
1331 'fa_timestamp' => 'img_timestamp'
1332 ), $where, __METHOD__
);
1335 if ( count( $oldRels ) ) {
1336 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1338 'oi_name' => $this->file
->getName(),
1339 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1340 $dbw->insertSelect( 'filearchive', 'oldimage',
1342 'fa_storage_group' => $encGroup,
1343 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1344 'fa_deleted_user' => $encUserId,
1345 'fa_deleted_timestamp' => $encTimestamp,
1346 'fa_deleted_reason' => $encReason,
1347 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1349 'fa_name' => 'oi_name',
1350 'fa_archive_name' => 'oi_archive_name',
1351 'fa_size' => 'oi_size',
1352 'fa_width' => 'oi_width',
1353 'fa_height' => 'oi_height',
1354 'fa_metadata' => 'oi_metadata',
1355 'fa_bits' => 'oi_bits',
1356 'fa_media_type' => 'oi_media_type',
1357 'fa_major_mime' => 'oi_major_mime',
1358 'fa_minor_mime' => 'oi_minor_mime',
1359 'fa_description' => 'oi_description',
1360 'fa_user' => 'oi_user',
1361 'fa_user_text' => 'oi_user_text',
1362 'fa_timestamp' => 'oi_timestamp',
1363 'fa_deleted' => $bitfield
1364 ), $where, __METHOD__
);
1368 function doDBDeletes() {
1369 $dbw = $this->file
->repo
->getMasterDB();
1370 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1371 if ( count( $oldRels ) ) {
1372 $dbw->delete( 'oldimage',
1374 'oi_name' => $this->file
->getName(),
1375 'oi_archive_name' => array_keys( $oldRels )
1378 if ( $deleteCurrent ) {
1379 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1384 * Run the transaction
1386 function execute() {
1388 wfProfileIn( __METHOD__
);
1390 $this->file
->lock();
1391 // Leave private files alone
1392 $privateFiles = array();
1393 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1394 $dbw = $this->file
->repo
->getMasterDB();
1395 if( !empty( $oldRels ) ) {
1396 $res = $dbw->select( 'oldimage',
1397 array( 'oi_archive_name' ),
1398 array( 'oi_name' => $this->file
->getName(),
1399 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1400 $dbw->bitAnd('oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1402 while( $row = $dbw->fetchObject( $res ) ) {
1403 $privateFiles[$row->oi_archive_name
] = 1;
1406 // Prepare deletion batch
1407 $hashes = $this->getHashes();
1408 $this->deletionBatch
= array();
1409 $ext = $this->file
->getExtension();
1410 $dotExt = $ext === '' ?
'' : ".$ext";
1411 foreach ( $this->srcRels
as $name => $srcRel ) {
1412 // Skip files that have no hash (missing source).
1413 // Keep private files where they are.
1414 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1415 $hash = $hashes[$name];
1416 $key = $hash . $dotExt;
1417 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1418 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1422 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1423 // We acquire this lock by running the inserts now, before the file operations.
1425 // This potentially has poor lock contention characteristics -- an alternative
1426 // scheme would be to insert stub filearchive entries with no fa_name and commit
1427 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1428 $this->doDBInserts();
1430 // Removes non-existent file from the batch, so we don't get errors.
1431 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1433 // Execute the file deletion batch
1434 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1435 if ( !$status->isGood() ) {
1436 $this->status
->merge( $status );
1439 if ( !$this->status
->ok
) {
1440 // Critical file deletion error
1441 // Roll back inserts, release lock and abort
1442 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1443 $this->file
->unlockAndRollback();
1444 wfProfileOut( __METHOD__
);
1445 return $this->status
;
1449 if ( $wgUseSquid ) {
1451 foreach ( $this->srcRels
as $srcRel ) {
1452 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1453 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1455 SquidUpdate
::purge( $urls );
1458 // Delete image/oldimage rows
1459 $this->doDBDeletes();
1461 // Commit and return
1462 $this->file
->unlock();
1463 wfProfileOut( __METHOD__
);
1464 return $this->status
;
1468 * Removes non-existent files from a deletion batch.
1470 function removeNonexistentFiles( $batch ) {
1471 $files = $newBatch = array();
1472 foreach( $batch as $batchItem ) {
1473 list( $src, $dest ) = $batchItem;
1474 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1476 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1477 foreach( $batch as $batchItem )
1478 if( $result[$batchItem[0]] )
1479 $newBatch[] = $batchItem;
1484 #------------------------------------------------------------------------------
1487 * Helper class for file undeletion
1490 class LocalFileRestoreBatch
{
1491 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1493 function __construct( File
$file, $unsuppress = false ) {
1494 $this->file
= $file;
1495 $this->cleanupBatch
= $this->ids
= array();
1496 $this->ids
= array();
1497 $this->unsuppress
= $unsuppress;
1503 function addId( $fa_id ) {
1504 $this->ids
[] = $fa_id;
1508 * Add a whole lot of files by ID
1510 function addIds( $ids ) {
1511 $this->ids
= array_merge( $this->ids
, $ids );
1515 * Add all revisions of the file
1522 * Run the transaction, except the cleanup batch.
1523 * The cleanup batch should be run in a separate transaction, because it locks different
1524 * rows and there's no need to keep the image row locked while it's acquiring those locks
1525 * The caller may have its own transaction open.
1526 * So we save the batch and let the caller call cleanup()
1528 function execute() {
1530 if ( !$this->all
&& !$this->ids
) {
1532 return $this->file
->repo
->newGood();
1535 $exists = $this->file
->lock();
1536 $dbw = $this->file
->repo
->getMasterDB();
1537 $status = $this->file
->repo
->newGood();
1539 // Fetch all or selected archived revisions for the file,
1540 // sorted from the most recent to the oldest.
1541 $conditions = array( 'fa_name' => $this->file
->getName() );
1543 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1546 $result = $dbw->select( 'filearchive', '*',
1549 array( 'ORDER BY' => 'fa_timestamp DESC' )
1552 $idsPresent = array();
1553 $storeBatch = array();
1554 $insertBatch = array();
1555 $insertCurrent = false;
1556 $deleteIds = array();
1558 $archiveNames = array();
1559 while( $row = $dbw->fetchObject( $result ) ) {
1560 $idsPresent[] = $row->fa_id
;
1562 if ( $row->fa_name
!= $this->file
->getName() ) {
1563 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1564 $status->failCount++
;
1567 if ( $row->fa_storage_key
== '' ) {
1568 // Revision was missing pre-deletion
1569 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1570 $status->failCount++
;
1574 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1575 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1577 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1579 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1580 $sha1 = substr( $sha1, 1 );
1583 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1584 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1585 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1586 ||
is_null( $row->fa_metadata
) ) {
1587 // Refresh our metadata
1588 // Required for a new current revision; nice for older ones too. :)
1589 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1592 'minor_mime' => $row->fa_minor_mime
,
1593 'major_mime' => $row->fa_major_mime
,
1594 'media_type' => $row->fa_media_type
,
1595 'metadata' => $row->fa_metadata
1599 if ( $first && !$exists ) {
1600 // This revision will be published as the new current version
1601 $destRel = $this->file
->getRel();
1602 $insertCurrent = array(
1603 'img_name' => $row->fa_name
,
1604 'img_size' => $row->fa_size
,
1605 'img_width' => $row->fa_width
,
1606 'img_height' => $row->fa_height
,
1607 'img_metadata' => $props['metadata'],
1608 'img_bits' => $row->fa_bits
,
1609 'img_media_type' => $props['media_type'],
1610 'img_major_mime' => $props['major_mime'],
1611 'img_minor_mime' => $props['minor_mime'],
1612 'img_description' => $row->fa_description
,
1613 'img_user' => $row->fa_user
,
1614 'img_user_text' => $row->fa_user_text
,
1615 'img_timestamp' => $row->fa_timestamp
,
1618 // The live (current) version cannot be hidden!
1619 if( !$this->unsuppress
&& $row->fa_deleted
) {
1620 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1621 $this->cleanupBatch
[] = $row->fa_storage_key
;
1624 $archiveName = $row->fa_archive_name
;
1625 if( $archiveName == '' ) {
1626 // This was originally a current version; we
1627 // have to devise a new archive name for it.
1628 // Format is <timestamp of archiving>!<name>
1629 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1631 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1633 } while ( isset( $archiveNames[$archiveName] ) );
1635 $archiveNames[$archiveName] = true;
1636 $destRel = $this->file
->getArchiveRel( $archiveName );
1637 $insertBatch[] = array(
1638 'oi_name' => $row->fa_name
,
1639 'oi_archive_name' => $archiveName,
1640 'oi_size' => $row->fa_size
,
1641 'oi_width' => $row->fa_width
,
1642 'oi_height' => $row->fa_height
,
1643 'oi_bits' => $row->fa_bits
,
1644 'oi_description' => $row->fa_description
,
1645 'oi_user' => $row->fa_user
,
1646 'oi_user_text' => $row->fa_user_text
,
1647 'oi_timestamp' => $row->fa_timestamp
,
1648 'oi_metadata' => $props['metadata'],
1649 'oi_media_type' => $props['media_type'],
1650 'oi_major_mime' => $props['major_mime'],
1651 'oi_minor_mime' => $props['minor_mime'],
1652 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1653 'oi_sha1' => $sha1 );
1656 $deleteIds[] = $row->fa_id
;
1657 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1658 // private files can stay where they are
1659 $status->successCount++
;
1661 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1662 $this->cleanupBatch
[] = $row->fa_storage_key
;
1668 // Add a warning to the status object for missing IDs
1669 $missingIds = array_diff( $this->ids
, $idsPresent );
1670 foreach ( $missingIds as $id ) {
1671 $status->error( 'undelete-missing-filearchive', $id );
1674 // Remove missing files from batch, so we don't get errors when undeleting them
1675 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1677 // Run the store batch
1678 // Use the OVERWRITE_SAME flag to smooth over a common error
1679 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1680 $status->merge( $storeStatus );
1682 if ( !$status->ok
) {
1683 // Store batch returned a critical error -- this usually means nothing was stored
1684 // Stop now and return an error
1685 $this->file
->unlock();
1689 // Run the DB updates
1690 // Because we have locked the image row, key conflicts should be rare.
1691 // If they do occur, we can roll back the transaction at this time with
1692 // no data loss, but leaving unregistered files scattered throughout the
1694 // This is not ideal, which is why it's important to lock the image row.
1695 if ( $insertCurrent ) {
1696 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1698 if ( $insertBatch ) {
1699 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1702 $dbw->delete( 'filearchive',
1703 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1707 // If store batch is empty (all files are missing), deletion is to be considered successful
1708 if( $status->successCount
> 0 ||
!$storeBatch ) {
1710 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1712 // Update site_stats
1713 $site_stats = $dbw->tableName( 'site_stats' );
1714 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1716 $this->file
->purgeEverything();
1718 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1719 $this->file
->purgeDescription();
1720 $this->file
->purgeHistory();
1723 $this->file
->unlock();
1728 * Removes non-existent files from a store batch.
1730 function removeNonexistentFiles( $triplets ) {
1731 $files = $filteredTriplets = array();
1732 foreach( $triplets as $file )
1733 $files[$file[0]] = $file[0];
1734 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1735 foreach( $triplets as $file )
1736 if( $result[$file[0]] )
1737 $filteredTriplets[] = $file;
1738 return $filteredTriplets;
1742 * Removes non-existent files from a cleanup batch.
1744 function removeNonexistentFromCleanup( $batch ) {
1745 $files = $newBatch = array();
1746 $repo = $this->file
->repo
;
1747 foreach( $batch as $file ) {
1748 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1749 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1752 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1753 foreach( $batch as $file )
1754 if( $result[$file] )
1755 $newBatch[] = $file;
1760 * Delete unused files in the deleted zone.
1761 * This should be called from outside the transaction in which execute() was called.
1763 function cleanup() {
1764 if ( !$this->cleanupBatch
) {
1765 return $this->file
->repo
->newGood();
1767 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1768 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1773 #------------------------------------------------------------------------------
1776 * Helper class for file movement
1779 class LocalFileMoveBatch
{
1780 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1782 function __construct( File
$file, Title
$target ) {
1783 $this->file
= $file;
1784 $this->target
= $target;
1785 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1786 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1787 $this->oldName
= $this->file
->getName();
1788 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1789 $this->oldRel
= $this->oldHash
. $this->oldName
;
1790 $this->newRel
= $this->newHash
. $this->newName
;
1791 $this->db
= $file->repo
->getMasterDb();
1795 * Add the current image to the batch
1797 function addCurrent() {
1798 $this->cur
= array( $this->oldRel
, $this->newRel
);
1802 * Add the old versions of the image to the batch
1804 function addOlds() {
1805 $archiveBase = 'archive';
1806 $this->olds
= array();
1807 $this->oldCount
= 0;
1809 $result = $this->db
->select( 'oldimage',
1810 array( 'oi_archive_name', 'oi_deleted' ),
1811 array( 'oi_name' => $this->oldName
),
1814 while( $row = $this->db
->fetchObject( $result ) ) {
1815 $oldName = $row->oi_archive_name
;
1816 $bits = explode( '!', $oldName, 2 );
1817 if( count( $bits ) != 2 ) {
1818 wfDebug( "Invalid old file name: $oldName \n" );
1821 list( $timestamp, $filename ) = $bits;
1822 if( $this->oldName
!= $filename ) {
1823 wfDebug( "Invalid old file name: $oldName \n" );
1827 // Do we want to add those to oldCount?
1828 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1831 $this->olds
[] = array(
1832 "{$archiveBase}/{$this->oldHash}{$oldName}",
1833 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1841 function execute() {
1842 $repo = $this->file
->repo
;
1843 $status = $repo->newGood();
1844 $triplets = $this->getMoveTriplets();
1846 $triplets = $this->removeNonexistentFiles( $triplets );
1847 $statusDb = $this->doDBUpdates();
1848 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1849 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1850 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1851 if( !$statusMove->isOk() ) {
1852 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1853 $this->db
->rollback();
1856 $status->merge( $statusDb );
1857 $status->merge( $statusMove );
1862 * Do the database updates and return a new FileRepoStatus indicating how
1863 * many rows where updated.
1865 * @return FileRepoStatus
1867 function doDBUpdates() {
1868 $repo = $this->file
->repo
;
1869 $status = $repo->newGood();
1872 // Update current image
1875 array( 'img_name' => $this->newName
),
1876 array( 'img_name' => $this->oldName
),
1879 if( $dbw->affectedRows() ) {
1880 $status->successCount++
;
1882 $status->failCount++
;
1885 // Update old images
1889 'oi_name' => $this->newName
,
1890 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1892 array( 'oi_name' => $this->oldName
),
1895 $affected = $dbw->affectedRows();
1896 $total = $this->oldCount
;
1897 $status->successCount +
= $affected;
1898 $status->failCount +
= $total - $affected;
1904 * Generate triplets for FSRepo::storeBatch().
1906 function getMoveTriplets() {
1907 $moves = array_merge( array( $this->cur
), $this->olds
);
1908 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1909 foreach( $moves as $move ) {
1910 // $move: (oldRelativePath, newRelativePath)
1911 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1912 $triplets[] = array( $srcUrl, 'public', $move[1] );
1913 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
1919 * Removes non-existent files from move batch.
1921 function removeNonexistentFiles( $triplets ) {
1923 foreach( $triplets as $file )
1924 $files[$file[0]] = $file[0];
1925 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1926 $filteredTriplets = array();
1927 foreach( $triplets as $file )
1928 if( $result[$file[0]] ) {
1929 $filteredTriplets[] = $file;
1931 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
1933 return $filteredTriplets;