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 );
810 // Delete thumbnails and refresh the metadata cache
811 $this->purgeThumbnails();
812 $this->saveToCache();
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 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
930 # Hooks, hooks, the magic of hooks...
931 wfRunHooks( 'FileUpload', array( $this ) );
933 # Commit the transaction now, in case something goes wrong later
934 # The most important thing is that files don't get lost, especially archives
937 # Invalidate cache for all pages using this file
938 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
940 # Invalidate cache for all pages that redirects on this page
941 $redirs = $this->getTitle()->getRedirectsHere();
942 foreach( $redirs as $redir ) {
943 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
951 * Move or copy a file to its public location. If a file exists at the
952 * destination, move it to an archive. Returns a FileRepoStatus object with
953 * the archive name in the "value" member on success.
955 * The archive name should be passed through to recordUpload for database
958 * @param $srcPath String: local filesystem path to the source image
959 * @param $flags Integer: a bitwise combination of:
960 * File::DELETE_SOURCE Delete the source file, i.e. move
962 * @return FileRepoStatus object. On success, the value member contains the
963 * archive name, or an empty string if it was a new file.
965 function publish( $srcPath, $flags = 0 ) {
967 $dstRel = $this->getRel();
968 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
969 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
970 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
971 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
972 if ( $status->value
== 'new' ) {
975 $status->value
= $archiveName;
981 /** getLinksTo inherited */
982 /** getExifData inherited */
983 /** isLocal inherited */
984 /** wasDeleted inherited */
987 * Move file to the new title
989 * Move current, old version and all thumbnails
990 * to the new filename. Old file is deleted.
992 * Cache purging is done; checks for validity
993 * and logging are caller's responsibility
995 * @param $target Title New file name
996 * @return FileRepoStatus object.
998 function move( $target ) {
999 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1001 $batch = new LocalFileMoveBatch( $this, $target );
1002 $batch->addCurrent();
1005 $status = $batch->execute();
1006 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1007 $this->purgeEverything();
1010 if ( $status->isOk() ) {
1011 // Now switch the object
1012 $this->title
= $target;
1013 // Force regeneration of the name and hashpath
1014 unset( $this->name
);
1015 unset( $this->hashPath
);
1016 // Purge the new image
1017 $this->purgeEverything();
1024 * Delete all versions of the file.
1026 * Moves the files into an archive directory (or deletes them)
1027 * and removes the database rows.
1029 * Cache purging is done; logging is caller's responsibility.
1033 * @return FileRepoStatus object.
1035 function delete( $reason, $suppress = false ) {
1037 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1038 $batch->addCurrent();
1040 # Get old version relative paths
1041 $dbw = $this->repo
->getMasterDB();
1042 $result = $dbw->select( 'oldimage',
1043 array( 'oi_archive_name' ),
1044 array( 'oi_name' => $this->getName() ) );
1045 while ( $row = $dbw->fetchObject( $result ) ) {
1046 $batch->addOld( $row->oi_archive_name
);
1048 $status = $batch->execute();
1050 if ( $status->ok
) {
1051 // Update site_stats
1052 $site_stats = $dbw->tableName( 'site_stats' );
1053 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1054 $this->purgeEverything();
1062 * Delete an old version of the file.
1064 * Moves the file into an archive directory (or deletes it)
1065 * and removes the database row.
1067 * Cache purging is done; logging is caller's responsibility.
1069 * @param $archiveName String
1070 * @param $reason String
1071 * @param $suppress Boolean
1072 * @throws MWException or FSException on database or file store failure
1073 * @return FileRepoStatus object.
1075 function deleteOld( $archiveName, $reason, $suppress=false ) {
1077 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1078 $batch->addOld( $archiveName );
1079 $status = $batch->execute();
1081 if ( $status->ok
) {
1082 $this->purgeDescription();
1083 $this->purgeHistory();
1089 * Restore all or specified deleted revisions to the given file.
1090 * Permissions and logging are left to the caller.
1092 * May throw database exceptions on error.
1094 * @param $versions set of record ids of deleted items to restore,
1095 * or empty to restore all revisions.
1096 * @param $unsuppress Boolean
1097 * @return FileRepoStatus
1099 function restore( $versions = array(), $unsuppress = false ) {
1100 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1104 $batch->addIds( $versions );
1106 $status = $batch->execute();
1107 if ( !$status->ok
) {
1111 $cleanupStatus = $batch->cleanup();
1112 $cleanupStatus->successCount
= 0;
1113 $cleanupStatus->failCount
= 0;
1114 $status->merge( $cleanupStatus );
1118 /** isMultipage inherited */
1119 /** pageCount inherited */
1120 /** scaleHeight inherited */
1121 /** getImageSize inherited */
1123 /** getDescriptionUrl inherited */
1124 /** getDescriptionText inherited */
1126 function getDescription() {
1128 return $this->description
;
1131 function getTimestamp() {
1133 return $this->timestamp
;
1136 function getSha1() {
1138 // Initialise now if necessary
1139 if ( $this->sha1
== '' && $this->fileExists
) {
1140 $this->sha1
= File
::sha1Base36( $this->getPath() );
1141 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1142 $dbw = $this->repo
->getMasterDB();
1143 $dbw->update( 'image',
1144 array( 'img_sha1' => $this->sha1
),
1145 array( 'img_name' => $this->getName() ),
1147 $this->saveToCache();
1155 * Start a transaction and lock the image for update
1156 * Increments a reference counter if the lock is already held
1157 * @return boolean True if the image exists, false otherwise
1160 $dbw = $this->repo
->getMasterDB();
1161 if ( !$this->locked
) {
1165 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1169 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1170 * the transaction and thereby releases the image lock.
1173 if ( $this->locked
) {
1175 if ( !$this->locked
) {
1176 $dbw = $this->repo
->getMasterDB();
1183 * Roll back the DB transaction and mark the image unlocked
1185 function unlockAndRollback() {
1186 $this->locked
= false;
1187 $dbw = $this->repo
->getMasterDB();
1190 } // LocalFile class
1192 #------------------------------------------------------------------------------
1195 * Helper class for file deletion
1198 class LocalFileDeleteBatch
{
1199 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1202 function __construct( File
$file, $reason = '', $suppress = false ) {
1203 $this->file
= $file;
1204 $this->reason
= $reason;
1205 $this->suppress
= $suppress;
1206 $this->status
= $file->repo
->newGood();
1209 function addCurrent() {
1210 $this->srcRels
['.'] = $this->file
->getRel();
1213 function addOld( $oldName ) {
1214 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1215 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1218 function getOldRels() {
1219 if ( !isset( $this->srcRels
['.'] ) ) {
1220 $oldRels =& $this->srcRels
;
1221 $deleteCurrent = false;
1223 $oldRels = $this->srcRels
;
1224 unset( $oldRels['.'] );
1225 $deleteCurrent = true;
1227 return array( $oldRels, $deleteCurrent );
1230 /*protected*/ function getHashes() {
1232 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1233 if ( $deleteCurrent ) {
1234 $hashes['.'] = $this->file
->getSha1();
1236 if ( count( $oldRels ) ) {
1237 $dbw = $this->file
->repo
->getMasterDB();
1238 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1239 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1241 while ( $row = $dbw->fetchObject( $res ) ) {
1242 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1243 // Get the hash from the file
1244 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1245 $props = $this->file
->repo
->getFileProps( $oldUrl );
1246 if ( $props['fileExists'] ) {
1247 // Upgrade the oldimage row
1248 $dbw->update( 'oldimage',
1249 array( 'oi_sha1' => $props['sha1'] ),
1250 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1252 $hashes[$row->oi_archive_name
] = $props['sha1'];
1254 $hashes[$row->oi_archive_name
] = false;
1257 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1261 $missing = array_diff_key( $this->srcRels
, $hashes );
1262 foreach ( $missing as $name => $rel ) {
1263 $this->status
->error( 'filedelete-old-unregistered', $name );
1265 foreach ( $hashes as $name => $hash ) {
1267 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1268 unset( $hashes[$name] );
1275 function doDBInserts() {
1277 $dbw = $this->file
->repo
->getMasterDB();
1278 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1279 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1280 $encReason = $dbw->addQuotes( $this->reason
);
1281 $encGroup = $dbw->addQuotes( 'deleted' );
1282 $ext = $this->file
->getExtension();
1283 $dotExt = $ext === '' ?
'' : ".$ext";
1284 $encExt = $dbw->addQuotes( $dotExt );
1285 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1287 // Bitfields to further suppress the content
1288 if ( $this->suppress
) {
1290 // This should be 15...
1291 $bitfield |
= Revision
::DELETED_TEXT
;
1292 $bitfield |
= Revision
::DELETED_COMMENT
;
1293 $bitfield |
= Revision
::DELETED_USER
;
1294 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1296 $bitfield = 'oi_deleted';
1299 if ( $deleteCurrent ) {
1300 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1301 $where = array( 'img_name' => $this->file
->getName() );
1302 $dbw->insertSelect( 'filearchive', 'image',
1304 'fa_storage_group' => $encGroup,
1305 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1306 'fa_deleted_user' => $encUserId,
1307 'fa_deleted_timestamp' => $encTimestamp,
1308 'fa_deleted_reason' => $encReason,
1309 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1311 'fa_name' => 'img_name',
1312 'fa_archive_name' => 'NULL',
1313 'fa_size' => 'img_size',
1314 'fa_width' => 'img_width',
1315 'fa_height' => 'img_height',
1316 'fa_metadata' => 'img_metadata',
1317 'fa_bits' => 'img_bits',
1318 'fa_media_type' => 'img_media_type',
1319 'fa_major_mime' => 'img_major_mime',
1320 'fa_minor_mime' => 'img_minor_mime',
1321 'fa_description' => 'img_description',
1322 'fa_user' => 'img_user',
1323 'fa_user_text' => 'img_user_text',
1324 'fa_timestamp' => 'img_timestamp'
1325 ), $where, __METHOD__
);
1328 if ( count( $oldRels ) ) {
1329 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1331 'oi_name' => $this->file
->getName(),
1332 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1333 $dbw->insertSelect( 'filearchive', 'oldimage',
1335 'fa_storage_group' => $encGroup,
1336 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1337 'fa_deleted_user' => $encUserId,
1338 'fa_deleted_timestamp' => $encTimestamp,
1339 'fa_deleted_reason' => $encReason,
1340 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1342 'fa_name' => 'oi_name',
1343 'fa_archive_name' => 'oi_archive_name',
1344 'fa_size' => 'oi_size',
1345 'fa_width' => 'oi_width',
1346 'fa_height' => 'oi_height',
1347 'fa_metadata' => 'oi_metadata',
1348 'fa_bits' => 'oi_bits',
1349 'fa_media_type' => 'oi_media_type',
1350 'fa_major_mime' => 'oi_major_mime',
1351 'fa_minor_mime' => 'oi_minor_mime',
1352 'fa_description' => 'oi_description',
1353 'fa_user' => 'oi_user',
1354 'fa_user_text' => 'oi_user_text',
1355 'fa_timestamp' => 'oi_timestamp',
1356 'fa_deleted' => $bitfield
1357 ), $where, __METHOD__
);
1361 function doDBDeletes() {
1362 $dbw = $this->file
->repo
->getMasterDB();
1363 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1364 if ( count( $oldRels ) ) {
1365 $dbw->delete( 'oldimage',
1367 'oi_name' => $this->file
->getName(),
1368 'oi_archive_name' => array_keys( $oldRels )
1371 if ( $deleteCurrent ) {
1372 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1377 * Run the transaction
1379 function execute() {
1381 wfProfileIn( __METHOD__
);
1383 $this->file
->lock();
1384 // Leave private files alone
1385 $privateFiles = array();
1386 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1387 $dbw = $this->file
->repo
->getMasterDB();
1388 if( !empty( $oldRels ) ) {
1389 $res = $dbw->select( 'oldimage',
1390 array( 'oi_archive_name' ),
1391 array( 'oi_name' => $this->file
->getName(),
1392 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1393 $dbw->bitAnd('oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1395 while( $row = $dbw->fetchObject( $res ) ) {
1396 $privateFiles[$row->oi_archive_name
] = 1;
1399 // Prepare deletion batch
1400 $hashes = $this->getHashes();
1401 $this->deletionBatch
= array();
1402 $ext = $this->file
->getExtension();
1403 $dotExt = $ext === '' ?
'' : ".$ext";
1404 foreach ( $this->srcRels
as $name => $srcRel ) {
1405 // Skip files that have no hash (missing source).
1406 // Keep private files where they are.
1407 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1408 $hash = $hashes[$name];
1409 $key = $hash . $dotExt;
1410 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1411 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1415 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1416 // We acquire this lock by running the inserts now, before the file operations.
1418 // This potentially has poor lock contention characteristics -- an alternative
1419 // scheme would be to insert stub filearchive entries with no fa_name and commit
1420 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1421 $this->doDBInserts();
1423 // Removes non-existent file from the batch, so we don't get errors.
1424 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1426 // Execute the file deletion batch
1427 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1428 if ( !$status->isGood() ) {
1429 $this->status
->merge( $status );
1432 if ( !$this->status
->ok
) {
1433 // Critical file deletion error
1434 // Roll back inserts, release lock and abort
1435 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1436 $this->file
->unlockAndRollback();
1437 wfProfileOut( __METHOD__
);
1438 return $this->status
;
1442 if ( $wgUseSquid ) {
1444 foreach ( $this->srcRels
as $srcRel ) {
1445 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1446 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1448 SquidUpdate
::purge( $urls );
1451 // Delete image/oldimage rows
1452 $this->doDBDeletes();
1454 // Commit and return
1455 $this->file
->unlock();
1456 wfProfileOut( __METHOD__
);
1457 return $this->status
;
1461 * Removes non-existent files from a deletion batch.
1463 function removeNonexistentFiles( $batch ) {
1464 $files = $newBatch = array();
1465 foreach( $batch as $batchItem ) {
1466 list( $src, $dest ) = $batchItem;
1467 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1469 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1470 foreach( $batch as $batchItem )
1471 if( $result[$batchItem[0]] )
1472 $newBatch[] = $batchItem;
1477 #------------------------------------------------------------------------------
1480 * Helper class for file undeletion
1483 class LocalFileRestoreBatch
{
1484 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1486 function __construct( File
$file, $unsuppress = false ) {
1487 $this->file
= $file;
1488 $this->cleanupBatch
= $this->ids
= array();
1489 $this->ids
= array();
1490 $this->unsuppress
= $unsuppress;
1496 function addId( $fa_id ) {
1497 $this->ids
[] = $fa_id;
1501 * Add a whole lot of files by ID
1503 function addIds( $ids ) {
1504 $this->ids
= array_merge( $this->ids
, $ids );
1508 * Add all revisions of the file
1515 * Run the transaction, except the cleanup batch.
1516 * The cleanup batch should be run in a separate transaction, because it locks different
1517 * rows and there's no need to keep the image row locked while it's acquiring those locks
1518 * The caller may have its own transaction open.
1519 * So we save the batch and let the caller call cleanup()
1521 function execute() {
1523 if ( !$this->all
&& !$this->ids
) {
1525 return $this->file
->repo
->newGood();
1528 $exists = $this->file
->lock();
1529 $dbw = $this->file
->repo
->getMasterDB();
1530 $status = $this->file
->repo
->newGood();
1532 // Fetch all or selected archived revisions for the file,
1533 // sorted from the most recent to the oldest.
1534 $conditions = array( 'fa_name' => $this->file
->getName() );
1536 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1539 $result = $dbw->select( 'filearchive', '*',
1542 array( 'ORDER BY' => 'fa_timestamp DESC' )
1545 $idsPresent = array();
1546 $storeBatch = array();
1547 $insertBatch = array();
1548 $insertCurrent = false;
1549 $deleteIds = array();
1551 $archiveNames = array();
1552 while( $row = $dbw->fetchObject( $result ) ) {
1553 $idsPresent[] = $row->fa_id
;
1555 if ( $row->fa_name
!= $this->file
->getName() ) {
1556 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1557 $status->failCount++
;
1560 if ( $row->fa_storage_key
== '' ) {
1561 // Revision was missing pre-deletion
1562 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1563 $status->failCount++
;
1567 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1568 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1570 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1572 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1573 $sha1 = substr( $sha1, 1 );
1576 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1577 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1578 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1579 ||
is_null( $row->fa_metadata
) ) {
1580 // Refresh our metadata
1581 // Required for a new current revision; nice for older ones too. :)
1582 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1585 'minor_mime' => $row->fa_minor_mime
,
1586 'major_mime' => $row->fa_major_mime
,
1587 'media_type' => $row->fa_media_type
,
1588 'metadata' => $row->fa_metadata
1592 if ( $first && !$exists ) {
1593 // This revision will be published as the new current version
1594 $destRel = $this->file
->getRel();
1595 $insertCurrent = array(
1596 'img_name' => $row->fa_name
,
1597 'img_size' => $row->fa_size
,
1598 'img_width' => $row->fa_width
,
1599 'img_height' => $row->fa_height
,
1600 'img_metadata' => $props['metadata'],
1601 'img_bits' => $row->fa_bits
,
1602 'img_media_type' => $props['media_type'],
1603 'img_major_mime' => $props['major_mime'],
1604 'img_minor_mime' => $props['minor_mime'],
1605 'img_description' => $row->fa_description
,
1606 'img_user' => $row->fa_user
,
1607 'img_user_text' => $row->fa_user_text
,
1608 'img_timestamp' => $row->fa_timestamp
,
1611 // The live (current) version cannot be hidden!
1612 if( !$this->unsuppress
&& $row->fa_deleted
) {
1613 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1614 $this->cleanupBatch
[] = $row->fa_storage_key
;
1617 $archiveName = $row->fa_archive_name
;
1618 if( $archiveName == '' ) {
1619 // This was originally a current version; we
1620 // have to devise a new archive name for it.
1621 // Format is <timestamp of archiving>!<name>
1622 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1624 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1626 } while ( isset( $archiveNames[$archiveName] ) );
1628 $archiveNames[$archiveName] = true;
1629 $destRel = $this->file
->getArchiveRel( $archiveName );
1630 $insertBatch[] = array(
1631 'oi_name' => $row->fa_name
,
1632 'oi_archive_name' => $archiveName,
1633 'oi_size' => $row->fa_size
,
1634 'oi_width' => $row->fa_width
,
1635 'oi_height' => $row->fa_height
,
1636 'oi_bits' => $row->fa_bits
,
1637 'oi_description' => $row->fa_description
,
1638 'oi_user' => $row->fa_user
,
1639 'oi_user_text' => $row->fa_user_text
,
1640 'oi_timestamp' => $row->fa_timestamp
,
1641 'oi_metadata' => $props['metadata'],
1642 'oi_media_type' => $props['media_type'],
1643 'oi_major_mime' => $props['major_mime'],
1644 'oi_minor_mime' => $props['minor_mime'],
1645 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1646 'oi_sha1' => $sha1 );
1649 $deleteIds[] = $row->fa_id
;
1650 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1651 // private files can stay where they are
1652 $status->successCount++
;
1654 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1655 $this->cleanupBatch
[] = $row->fa_storage_key
;
1661 // Add a warning to the status object for missing IDs
1662 $missingIds = array_diff( $this->ids
, $idsPresent );
1663 foreach ( $missingIds as $id ) {
1664 $status->error( 'undelete-missing-filearchive', $id );
1667 // Remove missing files from batch, so we don't get errors when undeleting them
1668 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1670 // Run the store batch
1671 // Use the OVERWRITE_SAME flag to smooth over a common error
1672 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1673 $status->merge( $storeStatus );
1675 if ( !$status->ok
) {
1676 // Store batch returned a critical error -- this usually means nothing was stored
1677 // Stop now and return an error
1678 $this->file
->unlock();
1682 // Run the DB updates
1683 // Because we have locked the image row, key conflicts should be rare.
1684 // If they do occur, we can roll back the transaction at this time with
1685 // no data loss, but leaving unregistered files scattered throughout the
1687 // This is not ideal, which is why it's important to lock the image row.
1688 if ( $insertCurrent ) {
1689 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1691 if ( $insertBatch ) {
1692 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1695 $dbw->delete( 'filearchive',
1696 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1700 // If store batch is empty (all files are missing), deletion is to be considered successful
1701 if( $status->successCount
> 0 ||
!$storeBatch ) {
1703 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1705 // Update site_stats
1706 $site_stats = $dbw->tableName( 'site_stats' );
1707 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1709 $this->file
->purgeEverything();
1711 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1712 $this->file
->purgeDescription();
1713 $this->file
->purgeHistory();
1716 $this->file
->unlock();
1721 * Removes non-existent files from a store batch.
1723 function removeNonexistentFiles( $triplets ) {
1724 $files = $filteredTriplets = array();
1725 foreach( $triplets as $file )
1726 $files[$file[0]] = $file[0];
1727 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1728 foreach( $triplets as $file )
1729 if( $result[$file[0]] )
1730 $filteredTriplets[] = $file;
1731 return $filteredTriplets;
1735 * Removes non-existent files from a cleanup batch.
1737 function removeNonexistentFromCleanup( $batch ) {
1738 $files = $newBatch = array();
1739 $repo = $this->file
->repo
;
1740 foreach( $batch as $file ) {
1741 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1742 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1745 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1746 foreach( $batch as $file )
1747 if( $result[$file] )
1748 $newBatch[] = $file;
1753 * Delete unused files in the deleted zone.
1754 * This should be called from outside the transaction in which execute() was called.
1756 function cleanup() {
1757 if ( !$this->cleanupBatch
) {
1758 return $this->file
->repo
->newGood();
1760 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1761 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1766 #------------------------------------------------------------------------------
1769 * Helper class for file movement
1772 class LocalFileMoveBatch
{
1773 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1775 function __construct( File
$file, Title
$target ) {
1776 $this->file
= $file;
1777 $this->target
= $target;
1778 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1779 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1780 $this->oldName
= $this->file
->getName();
1781 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1782 $this->oldRel
= $this->oldHash
. $this->oldName
;
1783 $this->newRel
= $this->newHash
. $this->newName
;
1784 $this->db
= $file->repo
->getMasterDb();
1788 * Add the current image to the batch
1790 function addCurrent() {
1791 $this->cur
= array( $this->oldRel
, $this->newRel
);
1795 * Add the old versions of the image to the batch
1797 function addOlds() {
1798 $archiveBase = 'archive';
1799 $this->olds
= array();
1800 $this->oldCount
= 0;
1802 $result = $this->db
->select( 'oldimage',
1803 array( 'oi_archive_name', 'oi_deleted' ),
1804 array( 'oi_name' => $this->oldName
),
1807 while( $row = $this->db
->fetchObject( $result ) ) {
1808 $oldName = $row->oi_archive_name
;
1809 $bits = explode( '!', $oldName, 2 );
1810 if( count( $bits ) != 2 ) {
1811 wfDebug( "Invalid old file name: $oldName \n" );
1814 list( $timestamp, $filename ) = $bits;
1815 if( $this->oldName
!= $filename ) {
1816 wfDebug( "Invalid old file name: $oldName \n" );
1820 // Do we want to add those to oldCount?
1821 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1824 $this->olds
[] = array(
1825 "{$archiveBase}/{$this->oldHash}{$oldName}",
1826 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1834 function execute() {
1835 $repo = $this->file
->repo
;
1836 $status = $repo->newGood();
1837 $triplets = $this->getMoveTriplets();
1839 $triplets = $this->removeNonexistentFiles( $triplets );
1840 $statusDb = $this->doDBUpdates();
1841 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1842 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1843 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1844 if( !$statusMove->isOk() ) {
1845 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1846 $this->db
->rollback();
1849 $status->merge( $statusDb );
1850 $status->merge( $statusMove );
1855 * Do the database updates and return a new FileRepoStatus indicating how
1856 * many rows where updated.
1858 * @return FileRepoStatus
1860 function doDBUpdates() {
1861 $repo = $this->file
->repo
;
1862 $status = $repo->newGood();
1865 // Update current image
1868 array( 'img_name' => $this->newName
),
1869 array( 'img_name' => $this->oldName
),
1872 if( $dbw->affectedRows() ) {
1873 $status->successCount++
;
1875 $status->failCount++
;
1878 // Update old images
1882 'oi_name' => $this->newName
,
1883 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1885 array( 'oi_name' => $this->oldName
),
1888 $affected = $dbw->affectedRows();
1889 $total = $this->oldCount
;
1890 $status->successCount +
= $affected;
1891 $status->failCount +
= $total - $affected;
1897 * Generate triplets for FSRepo::storeBatch().
1899 function getMoveTriplets() {
1900 $moves = array_merge( array( $this->cur
), $this->olds
);
1901 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1902 foreach( $moves as $move ) {
1903 // $move: (oldRelativePath, newRelativePath)
1904 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1905 $triplets[] = array( $srcUrl, 'public', $move[1] );
1906 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
1912 * Removes non-existent files from move batch.
1914 function removeNonexistentFiles( $triplets ) {
1916 foreach( $triplets as $file )
1917 $files[$file[0]] = $file[0];
1918 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1919 $filteredTriplets = array();
1920 foreach( $triplets as $file )
1921 if( $result[$file[0]] ) {
1922 $filteredTriplets[] = $file;
1924 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
1926 return $filteredTriplets;