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