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 $this->historyRes
= null;
703 } elseif ( $this->historyLine
== 1 ) {
704 $this->historyRes
= $dbr->select( 'oldimage', '*',
705 array( 'oi_name' => $this->title
->getDBkey() ),
707 array( 'ORDER BY' => 'oi_timestamp DESC' )
710 $this->historyLine ++
;
712 return $dbr->fetchObject( $this->historyRes
);
716 * Reset the history pointer to the first element of the history
718 public function resetHistory() {
719 $this->historyLine
= 0;
720 if ( !is_null( $this->historyRes
) ) {
721 $this->historyRes
= null;
725 /** getFullPath inherited */
726 /** getHashPath inherited */
727 /** getRel inherited */
728 /** getUrlRel inherited */
729 /** getArchiveRel inherited */
730 /** getThumbRel inherited */
731 /** getArchivePath inherited */
732 /** getThumbPath inherited */
733 /** getArchiveUrl inherited */
734 /** getThumbUrl inherited */
735 /** getArchiveVirtualUrl inherited */
736 /** getThumbVirtualUrl inherited */
737 /** isHashed inherited */
740 * Upload a file and record it in the DB
741 * @param $srcPath String: source path or virtual URL
742 * @param $comment String: upload description
743 * @param $pageText String: text to use for the new description page,
744 * if a new description page is created
745 * @param $flags Integer: flags for publish()
746 * @param $props Array: File properties, if known. This can be used to reduce the
747 * upload time when uploading virtual URLs for which the file info
749 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
750 * @param $user Mixed: User object or null to use $wgUser
752 * @return FileRepoStatus object. On success, the value member contains the
753 * archive name, or an empty string if it was a new file.
755 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
757 $status = $this->publish( $srcPath, $flags );
759 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
760 $status->fatal( 'filenotfound', $srcPath );
768 * Record a file upload in the upload log and the image table
769 * @deprecated use upload()
771 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
772 $watch = false, $timestamp = false )
774 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
775 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
780 $wgUser->addWatch( $this->getTitle() );
787 * Record a file upload in the upload log and the image table
789 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
791 if( is_null( $user ) ) {
796 $dbw = $this->repo
->getMasterDB();
800 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
802 $props['description'] = $comment;
803 $props['user'] = $user->getId();
804 $props['user_text'] = $user->getName();
805 $props['timestamp'] = wfTimestamp( TS_MW
);
806 $this->setProps( $props );
808 // Delete thumbnails and refresh the metadata cache
809 $this->purgeThumbnails();
810 $this->saveToCache();
811 SquidUpdate
::purge( array( $this->getURL() ) );
813 // Fail now if the file isn't there
814 if ( !$this->fileExists
) {
815 wfDebug( __METHOD__
. ": File " . $this->getPath() . " went missing!\n" );
820 if ( $timestamp === false ) {
821 $timestamp = $dbw->timestamp();
824 # Test to see if the row exists using INSERT IGNORE
825 # This avoids race conditions by locking the row until the commit, and also
826 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
827 $dbw->insert( 'image',
829 'img_name' => $this->getName(),
830 'img_size'=> $this->size
,
831 'img_width' => intval( $this->width
),
832 'img_height' => intval( $this->height
),
833 'img_bits' => $this->bits
,
834 'img_media_type' => $this->media_type
,
835 'img_major_mime' => $this->major_mime
,
836 'img_minor_mime' => $this->minor_mime
,
837 'img_timestamp' => $timestamp,
838 'img_description' => $comment,
839 'img_user' => $user->getId(),
840 'img_user_text' => $user->getName(),
841 'img_metadata' => $this->metadata
,
842 'img_sha1' => $this->sha1
848 if( $dbw->affectedRows() == 0 ) {
851 # Collision, this is an update of a file
852 # Insert previous contents into oldimage
853 $dbw->insertSelect( 'oldimage', 'image',
855 'oi_name' => 'img_name',
856 'oi_archive_name' => $dbw->addQuotes( $oldver ),
857 'oi_size' => 'img_size',
858 'oi_width' => 'img_width',
859 'oi_height' => 'img_height',
860 'oi_bits' => 'img_bits',
861 'oi_timestamp' => 'img_timestamp',
862 'oi_description' => 'img_description',
863 'oi_user' => 'img_user',
864 'oi_user_text' => 'img_user_text',
865 'oi_metadata' => 'img_metadata',
866 'oi_media_type' => 'img_media_type',
867 'oi_major_mime' => 'img_major_mime',
868 'oi_minor_mime' => 'img_minor_mime',
869 'oi_sha1' => 'img_sha1'
870 ), array( 'img_name' => $this->getName() ), __METHOD__
873 # Update the current image row
874 $dbw->update( 'image',
876 'img_size' => $this->size
,
877 'img_width' => intval( $this->width
),
878 'img_height' => intval( $this->height
),
879 'img_bits' => $this->bits
,
880 'img_media_type' => $this->media_type
,
881 'img_major_mime' => $this->major_mime
,
882 'img_minor_mime' => $this->minor_mime
,
883 'img_timestamp' => $timestamp,
884 'img_description' => $comment,
885 'img_user' => $user->getId(),
886 'img_user_text' => $user->getName(),
887 'img_metadata' => $this->metadata
,
888 'img_sha1' => $this->sha1
889 ), array( /* WHERE */
890 'img_name' => $this->getName()
895 # Update the image count
896 $site_stats = $dbw->tableName( 'site_stats' );
897 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
900 $descTitle = $this->getTitle();
901 $article = new ImagePage( $descTitle );
902 $article->setFile( $this );
905 $log = new LogPage( 'upload' );
906 $action = $reupload ?
'overwrite' : 'upload';
907 $log->addEntry( $action, $descTitle, $comment, array(), $user );
909 if( $descTitle->exists() ) {
910 # Create a null revision
911 $latest = $descTitle->getLatestRevID();
912 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(),
913 $log->getRcComment(), false );
914 $nullRevision->insertOn( $dbw );
916 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
917 $article->updateRevisionOn( $dbw, $nullRevision );
919 # Invalidate the cache for the description page
920 $descTitle->invalidateCache();
921 $descTitle->purgeSquid();
923 // New file; create the description page.
924 // There's already a log entry, so don't make a second RC entry
925 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
928 # Hooks, hooks, the magic of hooks...
929 wfRunHooks( 'FileUpload', array( $this ) );
931 # Commit the transaction now, in case something goes wrong later
932 # The most important thing is that files don't get lost, especially archives
935 # Invalidate cache for all pages using this file
936 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
938 # Invalidate cache for all pages that redirects on this page
939 $redirs = $this->getTitle()->getRedirectsHere();
940 foreach( $redirs as $redir ) {
941 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
949 * Move or copy a file to its public location. If a file exists at the
950 * destination, move it to an archive. Returns a FileRepoStatus object with
951 * the archive name in the "value" member on success.
953 * The archive name should be passed through to recordUpload for database
956 * @param $srcPath String: local filesystem path to the source image
957 * @param $flags Integer: a bitwise combination of:
958 * File::DELETE_SOURCE Delete the source file, i.e. move
960 * @return FileRepoStatus object. On success, the value member contains the
961 * archive name, or an empty string if it was a new file.
963 function publish( $srcPath, $flags = 0 ) {
965 $dstRel = $this->getRel();
966 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
967 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
968 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
969 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
970 if ( $status->value
== 'new' ) {
973 $status->value
= $archiveName;
979 /** getLinksTo inherited */
980 /** getExifData inherited */
981 /** isLocal inherited */
982 /** wasDeleted inherited */
985 * Move file to the new title
987 * Move current, old version and all thumbnails
988 * to the new filename. Old file is deleted.
990 * Cache purging is done; checks for validity
991 * and logging are caller's responsibility
993 * @param $target Title New file name
994 * @return FileRepoStatus object.
996 function move( $target ) {
997 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
999 $batch = new LocalFileMoveBatch( $this, $target );
1000 $batch->addCurrent();
1003 $status = $batch->execute();
1004 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1005 $this->purgeEverything();
1008 if ( $status->isOk() ) {
1009 // Now switch the object
1010 $this->title
= $target;
1011 // Force regeneration of the name and hashpath
1012 unset( $this->name
);
1013 unset( $this->hashPath
);
1014 // Purge the new image
1015 $this->purgeEverything();
1022 * Delete all versions of the file.
1024 * Moves the files into an archive directory (or deletes them)
1025 * and removes the database rows.
1027 * Cache purging is done; logging is caller's responsibility.
1031 * @return FileRepoStatus object.
1033 function delete( $reason, $suppress = false ) {
1035 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1036 $batch->addCurrent();
1038 # Get old version relative paths
1039 $dbw = $this->repo
->getMasterDB();
1040 $result = $dbw->select( 'oldimage',
1041 array( 'oi_archive_name' ),
1042 array( 'oi_name' => $this->getName() ) );
1043 while ( $row = $dbw->fetchObject( $result ) ) {
1044 $batch->addOld( $row->oi_archive_name
);
1046 $status = $batch->execute();
1048 if ( $status->ok
) {
1049 // Update site_stats
1050 $site_stats = $dbw->tableName( 'site_stats' );
1051 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1052 $this->purgeEverything();
1060 * Delete an old version of the file.
1062 * Moves the file into an archive directory (or deletes it)
1063 * and removes the database row.
1065 * Cache purging is done; logging is caller's responsibility.
1067 * @param $archiveName String
1068 * @param $reason String
1069 * @param $suppress Boolean
1070 * @throws MWException or FSException on database or file store failure
1071 * @return FileRepoStatus object.
1073 function deleteOld( $archiveName, $reason, $suppress=false ) {
1075 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1076 $batch->addOld( $archiveName );
1077 $status = $batch->execute();
1079 if ( $status->ok
) {
1080 $this->purgeDescription();
1081 $this->purgeHistory();
1087 * Restore all or specified deleted revisions to the given file.
1088 * Permissions and logging are left to the caller.
1090 * May throw database exceptions on error.
1092 * @param $versions set of record ids of deleted items to restore,
1093 * or empty to restore all revisions.
1094 * @param $unsuppress Boolean
1095 * @return FileRepoStatus
1097 function restore( $versions = array(), $unsuppress = false ) {
1098 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1102 $batch->addIds( $versions );
1104 $status = $batch->execute();
1105 if ( !$status->ok
) {
1109 $cleanupStatus = $batch->cleanup();
1110 $cleanupStatus->successCount
= 0;
1111 $cleanupStatus->failCount
= 0;
1112 $status->merge( $cleanupStatus );
1116 /** isMultipage inherited */
1117 /** pageCount inherited */
1118 /** scaleHeight inherited */
1119 /** getImageSize inherited */
1121 /** getDescriptionUrl inherited */
1122 /** getDescriptionText inherited */
1124 function getDescription() {
1126 return $this->description
;
1129 function getTimestamp() {
1131 return $this->timestamp
;
1134 function getSha1() {
1136 // Initialise now if necessary
1137 if ( $this->sha1
== '' && $this->fileExists
) {
1138 $this->sha1
= File
::sha1Base36( $this->getPath() );
1139 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1140 $dbw = $this->repo
->getMasterDB();
1141 $dbw->update( 'image',
1142 array( 'img_sha1' => $this->sha1
),
1143 array( 'img_name' => $this->getName() ),
1145 $this->saveToCache();
1153 * Start a transaction and lock the image for update
1154 * Increments a reference counter if the lock is already held
1155 * @return boolean True if the image exists, false otherwise
1158 $dbw = $this->repo
->getMasterDB();
1159 if ( !$this->locked
) {
1163 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1167 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1168 * the transaction and thereby releases the image lock.
1171 if ( $this->locked
) {
1173 if ( !$this->locked
) {
1174 $dbw = $this->repo
->getMasterDB();
1181 * Roll back the DB transaction and mark the image unlocked
1183 function unlockAndRollback() {
1184 $this->locked
= false;
1185 $dbw = $this->repo
->getMasterDB();
1188 } // LocalFile class
1190 #------------------------------------------------------------------------------
1193 * Helper class for file deletion
1196 class LocalFileDeleteBatch
{
1197 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1200 function __construct( File
$file, $reason = '', $suppress = false ) {
1201 $this->file
= $file;
1202 $this->reason
= $reason;
1203 $this->suppress
= $suppress;
1204 $this->status
= $file->repo
->newGood();
1207 function addCurrent() {
1208 $this->srcRels
['.'] = $this->file
->getRel();
1211 function addOld( $oldName ) {
1212 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1213 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1216 function getOldRels() {
1217 if ( !isset( $this->srcRels
['.'] ) ) {
1218 $oldRels =& $this->srcRels
;
1219 $deleteCurrent = false;
1221 $oldRels = $this->srcRels
;
1222 unset( $oldRels['.'] );
1223 $deleteCurrent = true;
1225 return array( $oldRels, $deleteCurrent );
1228 /*protected*/ function getHashes() {
1230 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1231 if ( $deleteCurrent ) {
1232 $hashes['.'] = $this->file
->getSha1();
1234 if ( count( $oldRels ) ) {
1235 $dbw = $this->file
->repo
->getMasterDB();
1236 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1237 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1239 while ( $row = $dbw->fetchObject( $res ) ) {
1240 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1241 // Get the hash from the file
1242 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1243 $props = $this->file
->repo
->getFileProps( $oldUrl );
1244 if ( $props['fileExists'] ) {
1245 // Upgrade the oldimage row
1246 $dbw->update( 'oldimage',
1247 array( 'oi_sha1' => $props['sha1'] ),
1248 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1250 $hashes[$row->oi_archive_name
] = $props['sha1'];
1252 $hashes[$row->oi_archive_name
] = false;
1255 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1259 $missing = array_diff_key( $this->srcRels
, $hashes );
1260 foreach ( $missing as $name => $rel ) {
1261 $this->status
->error( 'filedelete-old-unregistered', $name );
1263 foreach ( $hashes as $name => $hash ) {
1265 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1266 unset( $hashes[$name] );
1273 function doDBInserts() {
1275 $dbw = $this->file
->repo
->getMasterDB();
1276 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1277 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1278 $encReason = $dbw->addQuotes( $this->reason
);
1279 $encGroup = $dbw->addQuotes( 'deleted' );
1280 $ext = $this->file
->getExtension();
1281 $dotExt = $ext === '' ?
'' : ".$ext";
1282 $encExt = $dbw->addQuotes( $dotExt );
1283 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1285 // Bitfields to further suppress the content
1286 if ( $this->suppress
) {
1288 // This should be 15...
1289 $bitfield |
= Revision
::DELETED_TEXT
;
1290 $bitfield |
= Revision
::DELETED_COMMENT
;
1291 $bitfield |
= Revision
::DELETED_USER
;
1292 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1294 $bitfield = 'oi_deleted';
1297 if ( $deleteCurrent ) {
1298 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1299 $where = array( 'img_name' => $this->file
->getName() );
1300 $dbw->insertSelect( 'filearchive', 'image',
1302 'fa_storage_group' => $encGroup,
1303 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1304 'fa_deleted_user' => $encUserId,
1305 'fa_deleted_timestamp' => $encTimestamp,
1306 'fa_deleted_reason' => $encReason,
1307 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1309 'fa_name' => 'img_name',
1310 'fa_archive_name' => 'NULL',
1311 'fa_size' => 'img_size',
1312 'fa_width' => 'img_width',
1313 'fa_height' => 'img_height',
1314 'fa_metadata' => 'img_metadata',
1315 'fa_bits' => 'img_bits',
1316 'fa_media_type' => 'img_media_type',
1317 'fa_major_mime' => 'img_major_mime',
1318 'fa_minor_mime' => 'img_minor_mime',
1319 'fa_description' => 'img_description',
1320 'fa_user' => 'img_user',
1321 'fa_user_text' => 'img_user_text',
1322 'fa_timestamp' => 'img_timestamp'
1323 ), $where, __METHOD__
);
1326 if ( count( $oldRels ) ) {
1327 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1329 'oi_name' => $this->file
->getName(),
1330 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1331 $dbw->insertSelect( 'filearchive', 'oldimage',
1333 'fa_storage_group' => $encGroup,
1334 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1335 'fa_deleted_user' => $encUserId,
1336 'fa_deleted_timestamp' => $encTimestamp,
1337 'fa_deleted_reason' => $encReason,
1338 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1340 'fa_name' => 'oi_name',
1341 'fa_archive_name' => 'oi_archive_name',
1342 'fa_size' => 'oi_size',
1343 'fa_width' => 'oi_width',
1344 'fa_height' => 'oi_height',
1345 'fa_metadata' => 'oi_metadata',
1346 'fa_bits' => 'oi_bits',
1347 'fa_media_type' => 'oi_media_type',
1348 'fa_major_mime' => 'oi_major_mime',
1349 'fa_minor_mime' => 'oi_minor_mime',
1350 'fa_description' => 'oi_description',
1351 'fa_user' => 'oi_user',
1352 'fa_user_text' => 'oi_user_text',
1353 'fa_timestamp' => 'oi_timestamp',
1354 'fa_deleted' => $bitfield
1355 ), $where, __METHOD__
);
1359 function doDBDeletes() {
1360 $dbw = $this->file
->repo
->getMasterDB();
1361 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1362 if ( count( $oldRels ) ) {
1363 $dbw->delete( 'oldimage',
1365 'oi_name' => $this->file
->getName(),
1366 'oi_archive_name' => array_keys( $oldRels )
1369 if ( $deleteCurrent ) {
1370 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1375 * Run the transaction
1377 function execute() {
1379 wfProfileIn( __METHOD__
);
1381 $this->file
->lock();
1382 // Leave private files alone
1383 $privateFiles = array();
1384 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1385 $dbw = $this->file
->repo
->getMasterDB();
1386 if( !empty( $oldRels ) ) {
1387 $res = $dbw->select( 'oldimage',
1388 array( 'oi_archive_name' ),
1389 array( 'oi_name' => $this->file
->getName(),
1390 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1391 $dbw->bitAnd('oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1393 while( $row = $dbw->fetchObject( $res ) ) {
1394 $privateFiles[$row->oi_archive_name
] = 1;
1397 // Prepare deletion batch
1398 $hashes = $this->getHashes();
1399 $this->deletionBatch
= array();
1400 $ext = $this->file
->getExtension();
1401 $dotExt = $ext === '' ?
'' : ".$ext";
1402 foreach ( $this->srcRels
as $name => $srcRel ) {
1403 // Skip files that have no hash (missing source).
1404 // Keep private files where they are.
1405 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1406 $hash = $hashes[$name];
1407 $key = $hash . $dotExt;
1408 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1409 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1413 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1414 // We acquire this lock by running the inserts now, before the file operations.
1416 // This potentially has poor lock contention characteristics -- an alternative
1417 // scheme would be to insert stub filearchive entries with no fa_name and commit
1418 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1419 $this->doDBInserts();
1421 // Removes non-existent file from the batch, so we don't get errors.
1422 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1424 // Execute the file deletion batch
1425 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1426 if ( !$status->isGood() ) {
1427 $this->status
->merge( $status );
1430 if ( !$this->status
->ok
) {
1431 // Critical file deletion error
1432 // Roll back inserts, release lock and abort
1433 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1434 $this->file
->unlockAndRollback();
1435 wfProfileOut( __METHOD__
);
1436 return $this->status
;
1440 if ( $wgUseSquid ) {
1442 foreach ( $this->srcRels
as $srcRel ) {
1443 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1444 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1446 SquidUpdate
::purge( $urls );
1449 // Delete image/oldimage rows
1450 $this->doDBDeletes();
1452 // Commit and return
1453 $this->file
->unlock();
1454 wfProfileOut( __METHOD__
);
1455 return $this->status
;
1459 * Removes non-existent files from a deletion batch.
1461 function removeNonexistentFiles( $batch ) {
1462 $files = $newBatch = array();
1463 foreach( $batch as $batchItem ) {
1464 list( $src, $dest ) = $batchItem;
1465 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1467 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1468 foreach( $batch as $batchItem )
1469 if( $result[$batchItem[0]] )
1470 $newBatch[] = $batchItem;
1475 #------------------------------------------------------------------------------
1478 * Helper class for file undeletion
1481 class LocalFileRestoreBatch
{
1482 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1484 function __construct( File
$file, $unsuppress = false ) {
1485 $this->file
= $file;
1486 $this->cleanupBatch
= $this->ids
= array();
1487 $this->ids
= array();
1488 $this->unsuppress
= $unsuppress;
1494 function addId( $fa_id ) {
1495 $this->ids
[] = $fa_id;
1499 * Add a whole lot of files by ID
1501 function addIds( $ids ) {
1502 $this->ids
= array_merge( $this->ids
, $ids );
1506 * Add all revisions of the file
1513 * Run the transaction, except the cleanup batch.
1514 * The cleanup batch should be run in a separate transaction, because it locks different
1515 * rows and there's no need to keep the image row locked while it's acquiring those locks
1516 * The caller may have its own transaction open.
1517 * So we save the batch and let the caller call cleanup()
1519 function execute() {
1521 if ( !$this->all
&& !$this->ids
) {
1523 return $this->file
->repo
->newGood();
1526 $exists = $this->file
->lock();
1527 $dbw = $this->file
->repo
->getMasterDB();
1528 $status = $this->file
->repo
->newGood();
1530 // Fetch all or selected archived revisions for the file,
1531 // sorted from the most recent to the oldest.
1532 $conditions = array( 'fa_name' => $this->file
->getName() );
1534 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1537 $result = $dbw->select( 'filearchive', '*',
1540 array( 'ORDER BY' => 'fa_timestamp DESC' )
1543 $idsPresent = array();
1544 $storeBatch = array();
1545 $insertBatch = array();
1546 $insertCurrent = false;
1547 $deleteIds = array();
1549 $archiveNames = array();
1550 while( $row = $dbw->fetchObject( $result ) ) {
1551 $idsPresent[] = $row->fa_id
;
1553 if ( $row->fa_name
!= $this->file
->getName() ) {
1554 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1555 $status->failCount++
;
1558 if ( $row->fa_storage_key
== '' ) {
1559 // Revision was missing pre-deletion
1560 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1561 $status->failCount++
;
1565 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1566 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1568 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1570 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1571 $sha1 = substr( $sha1, 1 );
1574 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1575 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1576 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1577 ||
is_null( $row->fa_metadata
) ) {
1578 // Refresh our metadata
1579 // Required for a new current revision; nice for older ones too. :)
1580 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1583 'minor_mime' => $row->fa_minor_mime
,
1584 'major_mime' => $row->fa_major_mime
,
1585 'media_type' => $row->fa_media_type
,
1586 'metadata' => $row->fa_metadata
1590 if ( $first && !$exists ) {
1591 // This revision will be published as the new current version
1592 $destRel = $this->file
->getRel();
1593 $insertCurrent = array(
1594 'img_name' => $row->fa_name
,
1595 'img_size' => $row->fa_size
,
1596 'img_width' => $row->fa_width
,
1597 'img_height' => $row->fa_height
,
1598 'img_metadata' => $props['metadata'],
1599 'img_bits' => $row->fa_bits
,
1600 'img_media_type' => $props['media_type'],
1601 'img_major_mime' => $props['major_mime'],
1602 'img_minor_mime' => $props['minor_mime'],
1603 'img_description' => $row->fa_description
,
1604 'img_user' => $row->fa_user
,
1605 'img_user_text' => $row->fa_user_text
,
1606 'img_timestamp' => $row->fa_timestamp
,
1609 // The live (current) version cannot be hidden!
1610 if( !$this->unsuppress
&& $row->fa_deleted
) {
1611 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1612 $this->cleanupBatch
[] = $row->fa_storage_key
;
1615 $archiveName = $row->fa_archive_name
;
1616 if( $archiveName == '' ) {
1617 // This was originally a current version; we
1618 // have to devise a new archive name for it.
1619 // Format is <timestamp of archiving>!<name>
1620 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1622 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1624 } while ( isset( $archiveNames[$archiveName] ) );
1626 $archiveNames[$archiveName] = true;
1627 $destRel = $this->file
->getArchiveRel( $archiveName );
1628 $insertBatch[] = array(
1629 'oi_name' => $row->fa_name
,
1630 'oi_archive_name' => $archiveName,
1631 'oi_size' => $row->fa_size
,
1632 'oi_width' => $row->fa_width
,
1633 'oi_height' => $row->fa_height
,
1634 'oi_bits' => $row->fa_bits
,
1635 'oi_description' => $row->fa_description
,
1636 'oi_user' => $row->fa_user
,
1637 'oi_user_text' => $row->fa_user_text
,
1638 'oi_timestamp' => $row->fa_timestamp
,
1639 'oi_metadata' => $props['metadata'],
1640 'oi_media_type' => $props['media_type'],
1641 'oi_major_mime' => $props['major_mime'],
1642 'oi_minor_mime' => $props['minor_mime'],
1643 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1644 'oi_sha1' => $sha1 );
1647 $deleteIds[] = $row->fa_id
;
1648 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1649 // private files can stay where they are
1650 $status->successCount++
;
1652 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1653 $this->cleanupBatch
[] = $row->fa_storage_key
;
1659 // Add a warning to the status object for missing IDs
1660 $missingIds = array_diff( $this->ids
, $idsPresent );
1661 foreach ( $missingIds as $id ) {
1662 $status->error( 'undelete-missing-filearchive', $id );
1665 // Remove missing files from batch, so we don't get errors when undeleting them
1666 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1668 // Run the store batch
1669 // Use the OVERWRITE_SAME flag to smooth over a common error
1670 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1671 $status->merge( $storeStatus );
1673 if ( !$status->ok
) {
1674 // Store batch returned a critical error -- this usually means nothing was stored
1675 // Stop now and return an error
1676 $this->file
->unlock();
1680 // Run the DB updates
1681 // Because we have locked the image row, key conflicts should be rare.
1682 // If they do occur, we can roll back the transaction at this time with
1683 // no data loss, but leaving unregistered files scattered throughout the
1685 // This is not ideal, which is why it's important to lock the image row.
1686 if ( $insertCurrent ) {
1687 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1689 if ( $insertBatch ) {
1690 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1693 $dbw->delete( 'filearchive',
1694 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1698 // If store batch is empty (all files are missing), deletion is to be considered successful
1699 if( $status->successCount
> 0 ||
!$storeBatch ) {
1701 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1703 // Update site_stats
1704 $site_stats = $dbw->tableName( 'site_stats' );
1705 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1707 $this->file
->purgeEverything();
1709 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1710 $this->file
->purgeDescription();
1711 $this->file
->purgeHistory();
1714 $this->file
->unlock();
1719 * Removes non-existent files from a store batch.
1721 function removeNonexistentFiles( $triplets ) {
1722 $files = $filteredTriplets = array();
1723 foreach( $triplets as $file )
1724 $files[$file[0]] = $file[0];
1725 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1726 foreach( $triplets as $file )
1727 if( $result[$file[0]] )
1728 $filteredTriplets[] = $file;
1729 return $filteredTriplets;
1733 * Removes non-existent files from a cleanup batch.
1735 function removeNonexistentFromCleanup( $batch ) {
1736 $files = $newBatch = array();
1737 $repo = $this->file
->repo
;
1738 foreach( $batch as $file ) {
1739 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1740 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1743 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1744 foreach( $batch as $file )
1745 if( $result[$file] )
1746 $newBatch[] = $file;
1751 * Delete unused files in the deleted zone.
1752 * This should be called from outside the transaction in which execute() was called.
1754 function cleanup() {
1755 if ( !$this->cleanupBatch
) {
1756 return $this->file
->repo
->newGood();
1758 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1759 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1764 #------------------------------------------------------------------------------
1767 * Helper class for file movement
1770 class LocalFileMoveBatch
{
1771 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1773 function __construct( File
$file, Title
$target ) {
1774 $this->file
= $file;
1775 $this->target
= $target;
1776 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1777 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1778 $this->oldName
= $this->file
->getName();
1779 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1780 $this->oldRel
= $this->oldHash
. $this->oldName
;
1781 $this->newRel
= $this->newHash
. $this->newName
;
1782 $this->db
= $file->repo
->getMasterDb();
1786 * Add the current image to the batch
1788 function addCurrent() {
1789 $this->cur
= array( $this->oldRel
, $this->newRel
);
1793 * Add the old versions of the image to the batch
1795 function addOlds() {
1796 $archiveBase = 'archive';
1797 $this->olds
= array();
1798 $this->oldCount
= 0;
1800 $result = $this->db
->select( 'oldimage',
1801 array( 'oi_archive_name', 'oi_deleted' ),
1802 array( 'oi_name' => $this->oldName
),
1805 while( $row = $this->db
->fetchObject( $result ) ) {
1806 $oldName = $row->oi_archive_name
;
1807 $bits = explode( '!', $oldName, 2 );
1808 if( count( $bits ) != 2 ) {
1809 wfDebug( "Invalid old file name: $oldName \n" );
1812 list( $timestamp, $filename ) = $bits;
1813 if( $this->oldName
!= $filename ) {
1814 wfDebug( "Invalid old file name: $oldName \n" );
1818 // Do we want to add those to oldCount?
1819 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1822 $this->olds
[] = array(
1823 "{$archiveBase}/{$this->oldHash}{$oldName}",
1824 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1832 function execute() {
1833 $repo = $this->file
->repo
;
1834 $status = $repo->newGood();
1835 $triplets = $this->getMoveTriplets();
1837 $triplets = $this->removeNonexistentFiles( $triplets );
1838 $statusDb = $this->doDBUpdates();
1839 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1840 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1841 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1842 if( !$statusMove->isOk() ) {
1843 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1844 $this->db
->rollback();
1847 $status->merge( $statusDb );
1848 $status->merge( $statusMove );
1853 * Do the database updates and return a new FileRepoStatus indicating how
1854 * many rows where updated.
1856 * @return FileRepoStatus
1858 function doDBUpdates() {
1859 $repo = $this->file
->repo
;
1860 $status = $repo->newGood();
1863 // Update current image
1866 array( 'img_name' => $this->newName
),
1867 array( 'img_name' => $this->oldName
),
1870 if( $dbw->affectedRows() ) {
1871 $status->successCount++
;
1873 $status->failCount++
;
1876 // Update old images
1880 'oi_name' => $this->newName
,
1881 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1883 array( 'oi_name' => $this->oldName
),
1886 $affected = $dbw->affectedRows();
1887 $total = $this->oldCount
;
1888 $status->successCount +
= $affected;
1889 $status->failCount +
= $total - $affected;
1895 * Generate triplets for FSRepo::storeBatch().
1897 function getMoveTriplets() {
1898 $moves = array_merge( array( $this->cur
), $this->olds
);
1899 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1900 foreach( $moves as $move ) {
1901 // $move: (oldRelativePath, newRelativePath)
1902 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1903 $triplets[] = array( $srcUrl, 'public', $move[1] );
1904 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
1910 * Removes non-existent files from move batch.
1912 function removeNonexistentFiles( $triplets ) {
1914 foreach( $triplets as $file )
1915 $files[$file[0]] = $file[0];
1916 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1917 $filteredTriplets = array();
1918 foreach( $triplets as $file )
1919 if( $result[$file[0]] ) {
1920 $filteredTriplets[] = $file;
1922 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
1924 return $filteredTriplets;