3 * Local file in the wiki's own database
10 * Bump this number when serialized cache records may be incompatible.
12 define( 'MW_FILE_VERSION', 8 );
15 * Class to represent a local file in the wiki's own database
17 * Provides methods to retrieve paths (physical, logical, URL),
18 * to generate image thumbnails or for uploading.
20 * Note that only the repo object knows what its file class is called. You should
21 * never name a file class explictly outside of the repo class. Instead use the
22 * repo's factory functions to generate file objects, for example:
24 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
26 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
31 class LocalFile
extends File
{
36 $fileExists, # does the file exist on disk? (loadFromXxx)
37 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
38 $historyRes, # result of the query for the file's history (nextHistoryLine)
41 $bits, # --- returned by getimagesize (loadFromXxx)
43 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
44 $mime, # MIME type, determined by MimeMagic::guessMimeType
45 $major_mime, # Major mime type
46 $minor_mime, # Minor mime type
47 $size, # Size in bytes (loadFromXxx)
48 $metadata, # Handler-specific metadata
49 $timestamp, # Upload timestamp
50 $sha1, # SHA-1 base 36 content hash
51 $user, $user_text, # User, who uploaded the file
52 $description, # Description of current revision of the file
53 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
54 $upgraded, # Whether the row was upgraded on load
55 $locked, # True if the image row is locked
56 $missing, # True if file is not present in file system. Not to be cached in memcached
57 $deleted; # Bitfield akin to rev_deleted
62 * Create a LocalFile from a title
63 * Do not call this except from inside a repo class.
65 * Note: $unused param is only here to avoid an E_STRICT
67 static function newFromTitle( $title, $repo, $unused = null ) {
68 return new self( $title, $repo );
72 * Create a LocalFile from a title
73 * Do not call this except from inside a repo class.
75 static function newFromRow( $row, $repo ) {
76 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
77 $file = new self( $title, $repo );
78 $file->loadFromRow( $row );
84 * Create a LocalFile from a SHA-1 key
85 * Do not call this except from inside a repo class.
87 * @param $repo LocalRepo
90 static function newFromKey( $sha1, $repo, $timestamp = false ) {
91 $conds = array( 'img_sha1' => $sha1 );
94 $conds['img_timestamp'] = $timestamp;
97 $dbr = $repo->getSlaveDB();
98 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
101 return self
::newFromRow( $row, $repo );
108 * Fields in the image table
110 static function selectFields() {
131 * Do not call this except from inside a repo class.
133 function __construct( $title, $repo ) {
134 if ( !is_object( $title ) ) {
135 throw new MWException( __CLASS__
. ' constructor given bogus title.' );
138 parent
::__construct( $title, $repo );
140 $this->metadata
= '';
141 $this->historyLine
= 0;
142 $this->historyRes
= null;
143 $this->dataLoaded
= false;
147 * Get the memcached key for the main data for this file, or false if
148 * there is no access to the shared cache.
150 function getCacheKey() {
151 $hashedName = md5( $this->getName() );
153 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
157 * Try to load file metadata from memcached. Returns true on success.
159 function loadFromCache() {
162 wfProfileIn( __METHOD__
);
163 $this->dataLoaded
= false;
164 $key = $this->getCacheKey();
167 wfProfileOut( __METHOD__
);
171 $cachedValues = $wgMemc->get( $key );
173 // Check if the key existed and belongs to this version of MediaWiki
174 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
175 wfDebug( "Pulling file metadata from cache key $key\n" );
176 $this->fileExists
= $cachedValues['fileExists'];
177 if ( $this->fileExists
) {
178 $this->setProps( $cachedValues );
180 $this->dataLoaded
= true;
183 if ( $this->dataLoaded
) {
184 wfIncrStats( 'image_cache_hit' );
186 wfIncrStats( 'image_cache_miss' );
189 wfProfileOut( __METHOD__
);
190 return $this->dataLoaded
;
194 * Save the file metadata to memcached
196 function saveToCache() {
200 $key = $this->getCacheKey();
206 $fields = $this->getCacheFields( '' );
207 $cache = array( 'version' => MW_FILE_VERSION
);
208 $cache['fileExists'] = $this->fileExists
;
210 if ( $this->fileExists
) {
211 foreach ( $fields as $field ) {
212 $cache[$field] = $this->$field;
216 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
220 * Load metadata from the file itself
222 function loadFromFile() {
223 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
226 function getCacheFields( $prefix = 'img_' ) {
227 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
228 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
229 static $results = array();
231 if ( $prefix == '' ) {
235 if ( !isset( $results[$prefix] ) ) {
236 $prefixedFields = array();
237 foreach ( $fields as $field ) {
238 $prefixedFields[] = $prefix . $field;
240 $results[$prefix] = $prefixedFields;
243 return $results[$prefix];
247 * Load file metadata from the DB
249 function loadFromDB() {
250 # Polymorphic function name to distinguish foreign and local fetches
251 $fname = get_class( $this ) . '::' . __FUNCTION__
;
252 wfProfileIn( $fname );
254 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
255 $this->dataLoaded
= true;
257 $dbr = $this->repo
->getMasterDB();
259 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
260 array( 'img_name' => $this->getName() ), $fname );
263 $this->loadFromRow( $row );
265 $this->fileExists
= false;
268 wfProfileOut( $fname );
272 * Decode a row from the database (either object or array) to an array
273 * with timestamps and MIME types decoded, and the field prefix removed.
275 function decodeRow( $row, $prefix = 'img_' ) {
276 $array = (array)$row;
277 $prefixLength = strlen( $prefix );
279 // Sanity check prefix once
280 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
281 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
286 foreach ( $array as $name => $value ) {
287 $decoded[substr( $name, $prefixLength )] = $value;
290 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
292 if ( empty( $decoded['major_mime'] ) ) {
293 $decoded['mime'] = 'unknown/unknown';
295 if ( !$decoded['minor_mime'] ) {
296 $decoded['minor_mime'] = 'unknown';
298 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
301 # Trim zero padding from char/binary field
302 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
308 * Load file metadata from a DB result row
310 function loadFromRow( $row, $prefix = 'img_' ) {
311 $this->dataLoaded
= true;
312 $array = $this->decodeRow( $row, $prefix );
314 foreach ( $array as $name => $value ) {
315 $this->$name = $value;
318 $this->fileExists
= true;
319 $this->maybeUpgradeRow();
323 * Load file metadata from cache or DB, unless already loaded
326 if ( !$this->dataLoaded
) {
327 if ( !$this->loadFromCache() ) {
329 $this->saveToCache();
331 $this->dataLoaded
= true;
336 * Upgrade a row if it needs it
338 function maybeUpgradeRow() {
339 global $wgUpdateCompatibleMetadata;
340 if ( wfReadOnly() ) {
344 if ( is_null( $this->media_type
) ||
345 $this->mime
== 'image/svg'
348 $this->upgraded
= true;
350 $handler = $this->getHandler();
352 $validity = $handler->isMetadataValid( $this, $this->metadata
);
353 if ( $validity === MediaHandler
::METADATA_BAD
354 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
357 $this->upgraded
= true;
363 function getUpgraded() {
364 return $this->upgraded
;
368 * Fix assorted version-related problems with the image row by reloading it from the file
370 function upgradeRow() {
371 wfProfileIn( __METHOD__
);
373 $this->loadFromFile();
375 # Don't destroy file info of missing files
376 if ( !$this->fileExists
) {
377 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
378 wfProfileOut( __METHOD__
);
382 $dbw = $this->repo
->getMasterDB();
383 list( $major, $minor ) = self
::splitMime( $this->mime
);
385 if ( wfReadOnly() ) {
386 wfProfileOut( __METHOD__
);
389 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
391 $dbw->update( 'image',
393 'img_width' => $this->width
,
394 'img_height' => $this->height
,
395 'img_bits' => $this->bits
,
396 'img_media_type' => $this->media_type
,
397 'img_major_mime' => $major,
398 'img_minor_mime' => $minor,
399 'img_metadata' => $this->metadata
,
400 'img_sha1' => $this->sha1
,
401 ), array( 'img_name' => $this->getName() ),
405 $this->saveToCache();
406 wfProfileOut( __METHOD__
);
410 * Set properties in this object to be equal to those given in the
411 * associative array $info. Only cacheable fields can be set.
413 * If 'mime' is given, it will be split into major_mime/minor_mime.
414 * If major_mime/minor_mime are given, $this->mime will also be set.
416 function setProps( $info ) {
417 $this->dataLoaded
= true;
418 $fields = $this->getCacheFields( '' );
419 $fields[] = 'fileExists';
421 foreach ( $fields as $field ) {
422 if ( isset( $info[$field] ) ) {
423 $this->$field = $info[$field];
427 // Fix up mime fields
428 if ( isset( $info['major_mime'] ) ) {
429 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
430 } elseif ( isset( $info['mime'] ) ) {
431 $this->mime
= $info['mime'];
432 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
436 /** splitMime inherited */
437 /** getName inherited */
438 /** getTitle inherited */
439 /** getURL inherited */
440 /** getViewURL inherited */
441 /** getPath inherited */
442 /** isVisible inhereted */
444 function isMissing() {
445 if ( $this->missing
=== null ) {
446 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
447 $this->missing
= !$fileExists;
449 return $this->missing
;
453 * Return the width of the image
455 * Returns false on error
457 public function getWidth( $page = 1 ) {
460 if ( $this->isMultipage() ) {
461 $dim = $this->getHandler()->getPageDimensions( $this, $page );
463 return $dim['width'];
473 * Return the height of the image
475 * Returns false on error
477 public function getHeight( $page = 1 ) {
480 if ( $this->isMultipage() ) {
481 $dim = $this->getHandler()->getPageDimensions( $this, $page );
483 return $dim['height'];
488 return $this->height
;
493 * Returns ID or name of user who uploaded the file
495 * @param $type string 'text' or 'id'
497 function getUser( $type = 'text' ) {
500 if ( $type == 'text' ) {
501 return $this->user_text
;
502 } elseif ( $type == 'id' ) {
508 * Get handler-specific metadata
510 function getMetadata() {
512 return $this->metadata
;
515 function getBitDepth() {
521 * Return the size of the image file, in bytes
523 public function getSize() {
529 * Returns the mime type of the file.
531 function getMimeType() {
537 * Return the type of the media in the file.
538 * Use the value returned by this function with the MEDIATYPE_xxx constants.
540 function getMediaType() {
542 return $this->media_type
;
545 /** canRender inherited */
546 /** mustRender inherited */
547 /** allowInlineDisplay inherited */
548 /** isSafeFile inherited */
549 /** isTrustedFile inherited */
552 * Returns true if the file exists on disk.
553 * @return boolean Whether file exist on disk.
555 public function exists() {
557 return $this->fileExists
;
560 /** getTransformScript inherited */
561 /** getUnscaledThumb inherited */
562 /** thumbName inherited */
563 /** createThumb inherited */
564 /** transform inherited */
567 * Fix thumbnail files from 1.4 or before, with extreme prejudice
569 function migrateThumbFile( $thumbName ) {
570 $thumbDir = $this->getThumbPath();
571 $thumbPath = "$thumbDir/$thumbName";
573 if ( is_dir( $thumbPath ) ) {
574 // Directory where file should be
575 // This happened occasionally due to broken migration code in 1.5
576 // Rename to broken-*
577 for ( $i = 0; $i < 100 ; $i++
) {
578 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
579 if ( !file_exists( $broken ) ) {
580 rename( $thumbPath, $broken );
584 // Doesn't exist anymore
588 if ( is_file( $thumbDir ) ) {
589 // File where directory should be
591 // Doesn't exist anymore
596 /** getHandler inherited */
597 /** iconThumb inherited */
598 /** getLastError inherited */
601 * Get all thumbnail names previously generated for this file
603 function getThumbnails() {
607 $dir = $this->getThumbPath();
609 if ( is_dir( $dir ) ) {
610 $handle = opendir( $dir );
613 while ( false !== ( $file = readdir( $handle ) ) ) {
614 if ( $file { 0 } != '.' ) {
627 * Refresh metadata in memcached, but don't touch thumbnails or squid
629 function purgeMetadataCache() {
631 $this->saveToCache();
632 $this->purgeHistory();
636 * Purge the shared history (OldLocalFile) cache
638 function purgeHistory() {
641 $hashedName = md5( $this->getName() );
642 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
645 $wgMemc->delete( $oldKey );
650 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
652 function purgeCache() {
653 // Refresh metadata cache
654 $this->purgeMetadataCache();
657 $this->purgeThumbnails();
659 // Purge squid cache for this file
660 SquidUpdate
::purge( array( $this->getURL() ) );
664 * Delete cached transformed files
666 function purgeThumbnails() {
667 global $wgUseSquid, $wgExcludeFromThumbnailPurge;
670 $files = $this->getThumbnails();
671 $dir = $this->getThumbPath();
674 foreach ( $files as $file ) {
675 // Only remove files not in the $wgExcludeFromThumbnailPurge configuration variable
676 $ext = pathinfo( "$dir/$file", PATHINFO_EXTENSION
);
677 if ( in_array( $ext, $wgExcludeFromThumbnailPurge ) ) {
681 # Check that the base file name is part of the thumb name
682 # This is a basic sanity check to avoid erasing unrelated directories
683 if ( strpos( $file, $this->getName() ) !== false ) {
684 $url = $this->getThumbUrl( $file );
686 @unlink
( "$dir/$file" );
692 SquidUpdate
::purge( $urls );
696 /** purgeDescription inherited */
697 /** purgeEverything inherited */
699 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
700 $dbr = $this->repo
->getSlaveDB();
701 $tables = array( 'oldimage' );
702 $fields = OldLocalFile
::selectFields();
703 $conds = $opts = $join_conds = array();
704 $eq = $inc ?
'=' : '';
705 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
708 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
712 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
716 $opts['LIMIT'] = $limit;
719 // Search backwards for time > x queries
720 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
721 $opts['ORDER BY'] = "oi_timestamp $order";
722 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
724 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
725 &$conds, &$opts, &$join_conds ) );
727 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
730 foreach ( $res as $row ) {
731 if ( $this->repo
->oldFileFromRowFactory
) {
732 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
734 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
738 if ( $order == 'ASC' ) {
739 $r = array_reverse( $r ); // make sure it ends up descending
746 * Return the history of this file, line by line.
747 * starts with current version, then old versions.
748 * uses $this->historyLine to check which line to return:
749 * 0 return line for current version
750 * 1 query for old versions, return first one
751 * 2, ... return next old version from above query
753 public function nextHistoryLine() {
754 # Polymorphic function name to distinguish foreign and local fetches
755 $fname = get_class( $this ) . '::' . __FUNCTION__
;
757 $dbr = $this->repo
->getSlaveDB();
759 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
760 $this->historyRes
= $dbr->select( 'image',
763 "'' AS oi_archive_name",
767 array( 'img_name' => $this->title
->getDBkey() ),
771 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
772 $this->historyRes
= null;
775 } elseif ( $this->historyLine
== 1 ) {
776 $this->historyRes
= $dbr->select( 'oldimage', '*',
777 array( 'oi_name' => $this->title
->getDBkey() ),
779 array( 'ORDER BY' => 'oi_timestamp DESC' )
782 $this->historyLine ++
;
784 return $dbr->fetchObject( $this->historyRes
);
788 * Reset the history pointer to the first element of the history
790 public function resetHistory() {
791 $this->historyLine
= 0;
793 if ( !is_null( $this->historyRes
) ) {
794 $this->historyRes
= null;
798 /** getFullPath inherited */
799 /** getHashPath inherited */
800 /** getRel inherited */
801 /** getUrlRel inherited */
802 /** getArchiveRel inherited */
803 /** getThumbRel inherited */
804 /** getArchivePath inherited */
805 /** getThumbPath inherited */
806 /** getArchiveUrl inherited */
807 /** getThumbUrl inherited */
808 /** getArchiveVirtualUrl inherited */
809 /** getThumbVirtualUrl inherited */
810 /** isHashed inherited */
813 * Upload a file and record it in the DB
814 * @param $srcPath String: source path or virtual URL
815 * @param $comment String: upload description
816 * @param $pageText String: text to use for the new description page,
817 * if a new description page is created
818 * @param $flags Integer: flags for publish()
819 * @param $props Array: File properties, if known. This can be used to reduce the
820 * upload time when uploading virtual URLs for which the file info
822 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
823 * @param $user Mixed: User object or null to use $wgUser
825 * @return FileRepoStatus object. On success, the value member contains the
826 * archive name, or an empty string if it was a new file.
828 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
830 $status = $this->publish( $srcPath, $flags );
833 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
834 $status->fatal( 'filenotfound', $srcPath );
844 * Record a file upload in the upload log and the image table
846 function recordUpload2(
847 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
849 if ( is_null( $user ) ) {
854 $dbw = $this->repo
->getMasterDB();
858 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
861 if ( $timestamp === false ) {
862 $timestamp = $dbw->timestamp();
865 $props['description'] = $comment;
866 $props['user'] = $user->getId();
867 $props['user_text'] = $user->getName();
868 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
869 $this->setProps( $props );
872 $this->purgeThumbnails();
874 # The file is already on its final location, remove it from the squid cache
875 SquidUpdate
::purge( array( $this->getURL() ) );
877 # Fail now if the file isn't there
878 if ( !$this->fileExists
) {
879 wfDebug( __METHOD__
. ": File " . $this->getPath() . " went missing!\n" );
885 # Test to see if the row exists using INSERT IGNORE
886 # This avoids race conditions by locking the row until the commit, and also
887 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
888 $dbw->insert( 'image',
890 'img_name' => $this->getName(),
891 'img_size' => $this->size
,
892 'img_width' => intval( $this->width
),
893 'img_height' => intval( $this->height
),
894 'img_bits' => $this->bits
,
895 'img_media_type' => $this->media_type
,
896 'img_major_mime' => $this->major_mime
,
897 'img_minor_mime' => $this->minor_mime
,
898 'img_timestamp' => $timestamp,
899 'img_description' => $comment,
900 'img_user' => $user->getId(),
901 'img_user_text' => $user->getName(),
902 'img_metadata' => $this->metadata
,
903 'img_sha1' => $this->sha1
909 if ( $dbw->affectedRows() == 0 ) {
912 # Collision, this is an update of a file
913 # Insert previous contents into oldimage
914 $dbw->insertSelect( 'oldimage', 'image',
916 'oi_name' => 'img_name',
917 'oi_archive_name' => $dbw->addQuotes( $oldver ),
918 'oi_size' => 'img_size',
919 'oi_width' => 'img_width',
920 'oi_height' => 'img_height',
921 'oi_bits' => 'img_bits',
922 'oi_timestamp' => 'img_timestamp',
923 'oi_description' => 'img_description',
924 'oi_user' => 'img_user',
925 'oi_user_text' => 'img_user_text',
926 'oi_metadata' => 'img_metadata',
927 'oi_media_type' => 'img_media_type',
928 'oi_major_mime' => 'img_major_mime',
929 'oi_minor_mime' => 'img_minor_mime',
930 'oi_sha1' => 'img_sha1'
931 ), array( 'img_name' => $this->getName() ), __METHOD__
934 # Update the current image row
935 $dbw->update( 'image',
937 'img_size' => $this->size
,
938 'img_width' => intval( $this->width
),
939 'img_height' => intval( $this->height
),
940 'img_bits' => $this->bits
,
941 'img_media_type' => $this->media_type
,
942 'img_major_mime' => $this->major_mime
,
943 'img_minor_mime' => $this->minor_mime
,
944 'img_timestamp' => $timestamp,
945 'img_description' => $comment,
946 'img_user' => $user->getId(),
947 'img_user_text' => $user->getName(),
948 'img_metadata' => $this->metadata
,
949 'img_sha1' => $this->sha1
950 ), array( /* WHERE */
951 'img_name' => $this->getName()
956 # Update the image count
957 $site_stats = $dbw->tableName( 'site_stats' );
958 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
961 $descTitle = $this->getTitle();
962 $article = new ImagePage( $descTitle );
963 $article->setFile( $this );
966 $log = new LogPage( 'upload' );
967 $action = $reupload ?
'overwrite' : 'upload';
968 $log->addEntry( $action, $descTitle, $comment, array(), $user );
970 if ( $descTitle->exists() ) {
971 # Create a null revision
972 $latest = $descTitle->getLatestRevID();
973 $nullRevision = Revision
::newNullRevision(
975 $descTitle->getArticleId(),
976 $log->getRcComment(),
979 $nullRevision->insertOn( $dbw );
981 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
982 $article->updateRevisionOn( $dbw, $nullRevision );
984 # Invalidate the cache for the description page
985 $descTitle->invalidateCache();
986 $descTitle->purgeSquid();
988 # New file; create the description page.
989 # There's already a log entry, so don't make a second RC entry
990 # Squid and file cache for the description page are purged by doEdit.
991 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
994 # Commit the transaction now, in case something goes wrong later
995 # The most important thing is that files don't get lost, especially archives
998 # Save to cache and purge the squid
999 # We shall not saveToCache before the commit since otherwise
1000 # in case of a rollback there is an usable file from memcached
1001 # which in fact doesn't really exist (bug 24978)
1002 $this->saveToCache();
1004 # Hooks, hooks, the magic of hooks...
1005 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1007 # Invalidate cache for all pages using this file
1008 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1009 $update->doUpdate();
1011 # Invalidate cache for all pages that redirects on this page
1012 $redirs = $this->getTitle()->getRedirectsHere();
1014 foreach ( $redirs as $redir ) {
1015 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1016 $update->doUpdate();
1023 * Move or copy a file to its public location. If a file exists at the
1024 * destination, move it to an archive. Returns a FileRepoStatus object with
1025 * the archive name in the "value" member on success.
1027 * The archive name should be passed through to recordUpload for database
1030 * @param $srcPath String: local filesystem path to the source image
1031 * @param $flags Integer: a bitwise combination of:
1032 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1033 * @param $dstArchiveName string File name if the file is to be published
1035 * @return FileRepoStatus object. On success, the value member contains the
1036 * archive name, or an empty string if it was a new file.
1038 function publish( $srcPath, $flags = 0, $dstArchiveName = null ) {
1041 if ( $dstArchiveName ) {
1042 $dstRel = 'archive/' . $this->getHashPath() . $dstArchiveName;
1044 $dstRel = $this->getRel();
1047 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1048 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1049 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1050 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1052 if ( $status->value
== 'new' ) {
1053 $status->value
= '';
1055 $status->value
= $archiveName;
1063 /** getLinksTo inherited */
1064 /** getExifData inherited */
1065 /** isLocal inherited */
1066 /** wasDeleted inherited */
1069 * Move file to the new title
1071 * Move current, old version and all thumbnails
1072 * to the new filename. Old file is deleted.
1074 * Cache purging is done; checks for validity
1075 * and logging are caller's responsibility
1077 * @param $target Title New file name
1078 * @return FileRepoStatus object.
1080 function move( $target ) {
1081 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1084 $batch = new LocalFileMoveBatch( $this, $target );
1085 $batch->addCurrent();
1088 $status = $batch->execute();
1089 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1091 $this->purgeEverything();
1094 if ( $status->isOk() ) {
1095 // Now switch the object
1096 $this->title
= $target;
1097 // Force regeneration of the name and hashpath
1098 unset( $this->name
);
1099 unset( $this->hashPath
);
1100 // Purge the new image
1101 $this->purgeEverything();
1108 * Delete all versions of the file.
1110 * Moves the files into an archive directory (or deletes them)
1111 * and removes the database rows.
1113 * Cache purging is done; logging is caller's responsibility.
1117 * @return FileRepoStatus object.
1119 function delete( $reason, $suppress = false ) {
1122 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1123 $batch->addCurrent();
1125 # Get old version relative paths
1126 $dbw = $this->repo
->getMasterDB();
1127 $result = $dbw->select( 'oldimage',
1128 array( 'oi_archive_name' ),
1129 array( 'oi_name' => $this->getName() ) );
1130 foreach ( $result as $row ) {
1131 $batch->addOld( $row->oi_archive_name
);
1133 $status = $batch->execute();
1135 if ( $status->ok
) {
1136 // Update site_stats
1137 $site_stats = $dbw->tableName( 'site_stats' );
1138 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1139 $this->purgeEverything();
1148 * Delete an old version of the file.
1150 * Moves the file into an archive directory (or deletes it)
1151 * and removes the database row.
1153 * Cache purging is done; logging is caller's responsibility.
1155 * @param $archiveName String
1156 * @param $reason String
1157 * @param $suppress Boolean
1158 * @throws MWException or FSException on database or file store failure
1159 * @return FileRepoStatus object.
1161 function deleteOld( $archiveName, $reason, $suppress = false ) {
1164 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1165 $batch->addOld( $archiveName );
1166 $status = $batch->execute();
1170 if ( $status->ok
) {
1171 $this->purgeDescription();
1172 $this->purgeHistory();
1179 * Restore all or specified deleted revisions to the given file.
1180 * Permissions and logging are left to the caller.
1182 * May throw database exceptions on error.
1184 * @param $versions set of record ids of deleted items to restore,
1185 * or empty to restore all revisions.
1186 * @param $unsuppress Boolean
1187 * @return FileRepoStatus
1189 function restore( $versions = array(), $unsuppress = false ) {
1190 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1195 $batch->addIds( $versions );
1198 $status = $batch->execute();
1200 if ( !$status->isGood() ) {
1204 $cleanupStatus = $batch->cleanup();
1205 $cleanupStatus->successCount
= 0;
1206 $cleanupStatus->failCount
= 0;
1207 $status->merge( $cleanupStatus );
1212 /** isMultipage inherited */
1213 /** pageCount inherited */
1214 /** scaleHeight inherited */
1215 /** getImageSize inherited */
1218 * Get the URL of the file description page.
1220 function getDescriptionUrl() {
1221 return $this->title
->getLocalUrl();
1225 * Get the HTML text of the description page
1226 * This is not used by ImagePage for local files, since (among other things)
1227 * it skips the parser cache.
1229 function getDescriptionText() {
1231 $revision = Revision
::newFromTitle( $this->title
);
1232 if ( !$revision ) return false;
1233 $text = $revision->getText();
1234 if ( !$text ) return false;
1235 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1236 return $pout->getText();
1239 function getDescription() {
1241 return $this->description
;
1244 function getTimestamp() {
1246 return $this->timestamp
;
1249 function getSha1() {
1251 // Initialise now if necessary
1252 if ( $this->sha1
== '' && $this->fileExists
) {
1253 $this->sha1
= File
::sha1Base36( $this->getPath() );
1254 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1255 $dbw = $this->repo
->getMasterDB();
1256 $dbw->update( 'image',
1257 array( 'img_sha1' => $this->sha1
),
1258 array( 'img_name' => $this->getName() ),
1260 $this->saveToCache();
1268 * Start a transaction and lock the image for update
1269 * Increments a reference counter if the lock is already held
1270 * @return boolean True if the image exists, false otherwise
1273 $dbw = $this->repo
->getMasterDB();
1275 if ( !$this->locked
) {
1280 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1284 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1285 * the transaction and thereby releases the image lock.
1288 if ( $this->locked
) {
1290 if ( !$this->locked
) {
1291 $dbw = $this->repo
->getMasterDB();
1298 * Roll back the DB transaction and mark the image unlocked
1300 function unlockAndRollback() {
1301 $this->locked
= false;
1302 $dbw = $this->repo
->getMasterDB();
1305 } // LocalFile class
1307 # ------------------------------------------------------------------------------
1310 * Helper class for file deletion
1313 class LocalFileDeleteBatch
{
1320 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1323 function __construct( File
$file, $reason = '', $suppress = false ) {
1324 $this->file
= $file;
1325 $this->reason
= $reason;
1326 $this->suppress
= $suppress;
1327 $this->status
= $file->repo
->newGood();
1330 function addCurrent() {
1331 $this->srcRels
['.'] = $this->file
->getRel();
1334 function addOld( $oldName ) {
1335 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1336 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1339 function getOldRels() {
1340 if ( !isset( $this->srcRels
['.'] ) ) {
1341 $oldRels =& $this->srcRels
;
1342 $deleteCurrent = false;
1344 $oldRels = $this->srcRels
;
1345 unset( $oldRels['.'] );
1346 $deleteCurrent = true;
1349 return array( $oldRels, $deleteCurrent );
1352 protected function getHashes() {
1354 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1356 if ( $deleteCurrent ) {
1357 $hashes['.'] = $this->file
->getSha1();
1360 if ( count( $oldRels ) ) {
1361 $dbw = $this->file
->repo
->getMasterDB();
1362 $res = $dbw->select(
1364 array( 'oi_archive_name', 'oi_sha1' ),
1365 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1369 foreach ( $res as $row ) {
1370 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1371 // Get the hash from the file
1372 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1373 $props = $this->file
->repo
->getFileProps( $oldUrl );
1375 if ( $props['fileExists'] ) {
1376 // Upgrade the oldimage row
1377 $dbw->update( 'oldimage',
1378 array( 'oi_sha1' => $props['sha1'] ),
1379 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1381 $hashes[$row->oi_archive_name
] = $props['sha1'];
1383 $hashes[$row->oi_archive_name
] = false;
1386 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1391 $missing = array_diff_key( $this->srcRels
, $hashes );
1393 foreach ( $missing as $name => $rel ) {
1394 $this->status
->error( 'filedelete-old-unregistered', $name );
1397 foreach ( $hashes as $name => $hash ) {
1399 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1400 unset( $hashes[$name] );
1407 function doDBInserts() {
1410 $dbw = $this->file
->repo
->getMasterDB();
1411 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1412 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1413 $encReason = $dbw->addQuotes( $this->reason
);
1414 $encGroup = $dbw->addQuotes( 'deleted' );
1415 $ext = $this->file
->getExtension();
1416 $dotExt = $ext === '' ?
'' : ".$ext";
1417 $encExt = $dbw->addQuotes( $dotExt );
1418 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1420 // Bitfields to further suppress the content
1421 if ( $this->suppress
) {
1423 // This should be 15...
1424 $bitfield |
= Revision
::DELETED_TEXT
;
1425 $bitfield |
= Revision
::DELETED_COMMENT
;
1426 $bitfield |
= Revision
::DELETED_USER
;
1427 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1429 $bitfield = 'oi_deleted';
1432 if ( $deleteCurrent ) {
1433 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1434 $where = array( 'img_name' => $this->file
->getName() );
1435 $dbw->insertSelect( 'filearchive', 'image',
1437 'fa_storage_group' => $encGroup,
1438 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1439 'fa_deleted_user' => $encUserId,
1440 'fa_deleted_timestamp' => $encTimestamp,
1441 'fa_deleted_reason' => $encReason,
1442 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1444 'fa_name' => 'img_name',
1445 'fa_archive_name' => 'NULL',
1446 'fa_size' => 'img_size',
1447 'fa_width' => 'img_width',
1448 'fa_height' => 'img_height',
1449 'fa_metadata' => 'img_metadata',
1450 'fa_bits' => 'img_bits',
1451 'fa_media_type' => 'img_media_type',
1452 'fa_major_mime' => 'img_major_mime',
1453 'fa_minor_mime' => 'img_minor_mime',
1454 'fa_description' => 'img_description',
1455 'fa_user' => 'img_user',
1456 'fa_user_text' => 'img_user_text',
1457 'fa_timestamp' => 'img_timestamp'
1458 ), $where, __METHOD__
);
1461 if ( count( $oldRels ) ) {
1462 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1464 'oi_name' => $this->file
->getName(),
1465 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1466 $dbw->insertSelect( 'filearchive', 'oldimage',
1468 'fa_storage_group' => $encGroup,
1469 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1470 'fa_deleted_user' => $encUserId,
1471 'fa_deleted_timestamp' => $encTimestamp,
1472 'fa_deleted_reason' => $encReason,
1473 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1475 'fa_name' => 'oi_name',
1476 'fa_archive_name' => 'oi_archive_name',
1477 'fa_size' => 'oi_size',
1478 'fa_width' => 'oi_width',
1479 'fa_height' => 'oi_height',
1480 'fa_metadata' => 'oi_metadata',
1481 'fa_bits' => 'oi_bits',
1482 'fa_media_type' => 'oi_media_type',
1483 'fa_major_mime' => 'oi_major_mime',
1484 'fa_minor_mime' => 'oi_minor_mime',
1485 'fa_description' => 'oi_description',
1486 'fa_user' => 'oi_user',
1487 'fa_user_text' => 'oi_user_text',
1488 'fa_timestamp' => 'oi_timestamp',
1489 'fa_deleted' => $bitfield
1490 ), $where, __METHOD__
);
1494 function doDBDeletes() {
1495 $dbw = $this->file
->repo
->getMasterDB();
1496 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1498 if ( count( $oldRels ) ) {
1499 $dbw->delete( 'oldimage',
1501 'oi_name' => $this->file
->getName(),
1502 'oi_archive_name' => array_keys( $oldRels )
1506 if ( $deleteCurrent ) {
1507 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1512 * Run the transaction
1514 function execute() {
1516 wfProfileIn( __METHOD__
);
1518 $this->file
->lock();
1519 // Leave private files alone
1520 $privateFiles = array();
1521 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1522 $dbw = $this->file
->repo
->getMasterDB();
1524 if ( !empty( $oldRels ) ) {
1525 $res = $dbw->select( 'oldimage',
1526 array( 'oi_archive_name' ),
1527 array( 'oi_name' => $this->file
->getName(),
1528 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1529 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1532 foreach ( $res as $row ) {
1533 $privateFiles[$row->oi_archive_name
] = 1;
1536 // Prepare deletion batch
1537 $hashes = $this->getHashes();
1538 $this->deletionBatch
= array();
1539 $ext = $this->file
->getExtension();
1540 $dotExt = $ext === '' ?
'' : ".$ext";
1542 foreach ( $this->srcRels
as $name => $srcRel ) {
1543 // Skip files that have no hash (missing source).
1544 // Keep private files where they are.
1545 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1546 $hash = $hashes[$name];
1547 $key = $hash . $dotExt;
1548 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1549 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1553 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1554 // We acquire this lock by running the inserts now, before the file operations.
1556 // This potentially has poor lock contention characteristics -- an alternative
1557 // scheme would be to insert stub filearchive entries with no fa_name and commit
1558 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1559 $this->doDBInserts();
1561 // Removes non-existent file from the batch, so we don't get errors.
1562 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1564 // Execute the file deletion batch
1565 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1567 if ( !$status->isGood() ) {
1568 $this->status
->merge( $status );
1571 if ( !$this->status
->ok
) {
1572 // Critical file deletion error
1573 // Roll back inserts, release lock and abort
1574 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1575 $this->file
->unlockAndRollback();
1576 wfProfileOut( __METHOD__
);
1577 return $this->status
;
1581 if ( $wgUseSquid ) {
1584 foreach ( $this->srcRels
as $srcRel ) {
1585 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1586 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1588 SquidUpdate
::purge( $urls );
1591 // Delete image/oldimage rows
1592 $this->doDBDeletes();
1594 // Commit and return
1595 $this->file
->unlock();
1596 wfProfileOut( __METHOD__
);
1598 return $this->status
;
1602 * Removes non-existent files from a deletion batch.
1604 function removeNonexistentFiles( $batch ) {
1605 $files = $newBatch = array();
1607 foreach ( $batch as $batchItem ) {
1608 list( $src, $dest ) = $batchItem;
1609 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1612 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1614 foreach ( $batch as $batchItem ) {
1615 if ( $result[$batchItem[0]] ) {
1616 $newBatch[] = $batchItem;
1624 # ------------------------------------------------------------------------------
1627 * Helper class for file undeletion
1630 class LocalFileRestoreBatch
{
1636 var $cleanupBatch, $ids, $all, $unsuppress = false;
1638 function __construct( File
$file, $unsuppress = false ) {
1639 $this->file
= $file;
1640 $this->cleanupBatch
= $this->ids
= array();
1641 $this->ids
= array();
1642 $this->unsuppress
= $unsuppress;
1648 function addId( $fa_id ) {
1649 $this->ids
[] = $fa_id;
1653 * Add a whole lot of files by ID
1655 function addIds( $ids ) {
1656 $this->ids
= array_merge( $this->ids
, $ids );
1660 * Add all revisions of the file
1667 * Run the transaction, except the cleanup batch.
1668 * The cleanup batch should be run in a separate transaction, because it locks different
1669 * rows and there's no need to keep the image row locked while it's acquiring those locks
1670 * The caller may have its own transaction open.
1671 * So we save the batch and let the caller call cleanup()
1673 function execute() {
1676 if ( !$this->all
&& !$this->ids
) {
1678 return $this->file
->repo
->newGood();
1681 $exists = $this->file
->lock();
1682 $dbw = $this->file
->repo
->getMasterDB();
1683 $status = $this->file
->repo
->newGood();
1685 // Fetch all or selected archived revisions for the file,
1686 // sorted from the most recent to the oldest.
1687 $conditions = array( 'fa_name' => $this->file
->getName() );
1689 if ( !$this->all
) {
1690 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1693 $result = $dbw->select( 'filearchive', '*',
1696 array( 'ORDER BY' => 'fa_timestamp DESC' )
1699 $idsPresent = array();
1700 $storeBatch = array();
1701 $insertBatch = array();
1702 $insertCurrent = false;
1703 $deleteIds = array();
1705 $archiveNames = array();
1707 foreach ( $result as $row ) {
1708 $idsPresent[] = $row->fa_id
;
1710 if ( $row->fa_name
!= $this->file
->getName() ) {
1711 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1712 $status->failCount++
;
1716 if ( $row->fa_storage_key
== '' ) {
1717 // Revision was missing pre-deletion
1718 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1719 $status->failCount++
;
1723 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1724 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1726 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1729 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1730 $sha1 = substr( $sha1, 1 );
1733 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1734 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1735 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1736 ||
is_null( $row->fa_metadata
) ) {
1737 // Refresh our metadata
1738 // Required for a new current revision; nice for older ones too. :)
1739 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1742 'minor_mime' => $row->fa_minor_mime
,
1743 'major_mime' => $row->fa_major_mime
,
1744 'media_type' => $row->fa_media_type
,
1745 'metadata' => $row->fa_metadata
1749 if ( $first && !$exists ) {
1750 // This revision will be published as the new current version
1751 $destRel = $this->file
->getRel();
1752 $insertCurrent = array(
1753 'img_name' => $row->fa_name
,
1754 'img_size' => $row->fa_size
,
1755 'img_width' => $row->fa_width
,
1756 'img_height' => $row->fa_height
,
1757 'img_metadata' => $props['metadata'],
1758 'img_bits' => $row->fa_bits
,
1759 'img_media_type' => $props['media_type'],
1760 'img_major_mime' => $props['major_mime'],
1761 'img_minor_mime' => $props['minor_mime'],
1762 'img_description' => $row->fa_description
,
1763 'img_user' => $row->fa_user
,
1764 'img_user_text' => $row->fa_user_text
,
1765 'img_timestamp' => $row->fa_timestamp
,
1769 // The live (current) version cannot be hidden!
1770 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1771 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1772 $this->cleanupBatch
[] = $row->fa_storage_key
;
1775 $archiveName = $row->fa_archive_name
;
1777 if ( $archiveName == '' ) {
1778 // This was originally a current version; we
1779 // have to devise a new archive name for it.
1780 // Format is <timestamp of archiving>!<name>
1781 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1784 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1786 } while ( isset( $archiveNames[$archiveName] ) );
1789 $archiveNames[$archiveName] = true;
1790 $destRel = $this->file
->getArchiveRel( $archiveName );
1791 $insertBatch[] = array(
1792 'oi_name' => $row->fa_name
,
1793 'oi_archive_name' => $archiveName,
1794 'oi_size' => $row->fa_size
,
1795 'oi_width' => $row->fa_width
,
1796 'oi_height' => $row->fa_height
,
1797 'oi_bits' => $row->fa_bits
,
1798 'oi_description' => $row->fa_description
,
1799 'oi_user' => $row->fa_user
,
1800 'oi_user_text' => $row->fa_user_text
,
1801 'oi_timestamp' => $row->fa_timestamp
,
1802 'oi_metadata' => $props['metadata'],
1803 'oi_media_type' => $props['media_type'],
1804 'oi_major_mime' => $props['major_mime'],
1805 'oi_minor_mime' => $props['minor_mime'],
1806 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1807 'oi_sha1' => $sha1 );
1810 $deleteIds[] = $row->fa_id
;
1812 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1813 // private files can stay where they are
1814 $status->successCount++
;
1816 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1817 $this->cleanupBatch
[] = $row->fa_storage_key
;
1825 // Add a warning to the status object for missing IDs
1826 $missingIds = array_diff( $this->ids
, $idsPresent );
1828 foreach ( $missingIds as $id ) {
1829 $status->error( 'undelete-missing-filearchive', $id );
1832 // Remove missing files from batch, so we don't get errors when undeleting them
1833 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1835 // Run the store batch
1836 // Use the OVERWRITE_SAME flag to smooth over a common error
1837 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1838 $status->merge( $storeStatus );
1840 if ( !$status->isGood() ) {
1841 // Even if some files could be copied, fail entirely as that is the
1842 // easiest thing to do without data loss
1843 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1844 $status->ok
= false;
1845 $this->file
->unlock();
1850 // Run the DB updates
1851 // Because we have locked the image row, key conflicts should be rare.
1852 // If they do occur, we can roll back the transaction at this time with
1853 // no data loss, but leaving unregistered files scattered throughout the
1855 // This is not ideal, which is why it's important to lock the image row.
1856 if ( $insertCurrent ) {
1857 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1860 if ( $insertBatch ) {
1861 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1865 $dbw->delete( 'filearchive',
1866 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1870 // If store batch is empty (all files are missing), deletion is to be considered successful
1871 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1873 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1875 // Update site_stats
1876 $site_stats = $dbw->tableName( 'site_stats' );
1877 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1879 $this->file
->purgeEverything();
1881 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1882 $this->file
->purgeDescription();
1883 $this->file
->purgeHistory();
1887 $this->file
->unlock();
1893 * Removes non-existent files from a store batch.
1895 function removeNonexistentFiles( $triplets ) {
1896 $files = $filteredTriplets = array();
1897 foreach ( $triplets as $file )
1898 $files[$file[0]] = $file[0];
1900 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1902 foreach ( $triplets as $file ) {
1903 if ( $result[$file[0]] ) {
1904 $filteredTriplets[] = $file;
1908 return $filteredTriplets;
1912 * Removes non-existent files from a cleanup batch.
1914 function removeNonexistentFromCleanup( $batch ) {
1915 $files = $newBatch = array();
1916 $repo = $this->file
->repo
;
1918 foreach ( $batch as $file ) {
1919 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1920 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1923 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1925 foreach ( $batch as $file ) {
1926 if ( $result[$file] ) {
1927 $newBatch[] = $file;
1935 * Delete unused files in the deleted zone.
1936 * This should be called from outside the transaction in which execute() was called.
1938 function cleanup() {
1939 if ( !$this->cleanupBatch
) {
1940 return $this->file
->repo
->newGood();
1943 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1945 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1951 * Cleanup a failed batch. The batch was only partially successful, so
1952 * rollback by removing all items that were succesfully copied.
1954 * @param Status $storeStatus
1955 * @param array $storeBatch
1957 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
1958 $cleanupBatch = array();
1960 foreach ( $storeStatus->success
as $i => $success ) {
1962 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][1] );
1965 $this->file
->repo
->cleanupBatch( $cleanupBatch );
1969 # ------------------------------------------------------------------------------
1972 * Helper class for file movement
1975 class LocalFileMoveBatch
{
1976 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1978 function __construct( File
$file, Title
$target ) {
1979 $this->file
= $file;
1980 $this->target
= $target;
1981 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1982 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1983 $this->oldName
= $this->file
->getName();
1984 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1985 $this->oldRel
= $this->oldHash
. $this->oldName
;
1986 $this->newRel
= $this->newHash
. $this->newName
;
1987 $this->db
= $file->repo
->getMasterDb();
1991 * Add the current image to the batch
1993 function addCurrent() {
1994 $this->cur
= array( $this->oldRel
, $this->newRel
);
1998 * Add the old versions of the image to the batch
2000 function addOlds() {
2001 $archiveBase = 'archive';
2002 $this->olds
= array();
2003 $this->oldCount
= 0;
2005 $result = $this->db
->select( 'oldimage',
2006 array( 'oi_archive_name', 'oi_deleted' ),
2007 array( 'oi_name' => $this->oldName
),
2011 foreach ( $result as $row ) {
2012 $oldName = $row->oi_archive_name
;
2013 $bits = explode( '!', $oldName, 2 );
2015 if ( count( $bits ) != 2 ) {
2016 wfDebug( "Invalid old file name: $oldName \n" );
2020 list( $timestamp, $filename ) = $bits;
2022 if ( $this->oldName
!= $filename ) {
2023 wfDebug( "Invalid old file name: $oldName \n" );
2029 // Do we want to add those to oldCount?
2030 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2034 $this->olds
[] = array(
2035 "{$archiveBase}/{$this->oldHash}{$oldName}",
2036 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2044 function execute() {
2045 $repo = $this->file
->repo
;
2046 $status = $repo->newGood();
2047 $triplets = $this->getMoveTriplets();
2049 $triplets = $this->removeNonexistentFiles( $triplets );
2051 // Copy the files into their new location
2052 $statusMove = $repo->storeBatch( $triplets );
2053 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2054 if ( !$statusMove->isGood() ) {
2055 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2056 $this->cleanupTarget( $triplets );
2057 $statusMove->ok
= false;
2062 $statusDb = $this->doDBUpdates();
2063 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2064 if ( !$statusDb->isGood() ) {
2065 $this->db
->rollback();
2066 // Something went wrong with the DB updates, so remove the target files
2067 $this->cleanupTarget( $triplets );
2068 $statusDb->ok
= false;
2071 $this->db
->commit();
2073 // Everything went ok, remove the source files
2074 $this->cleanupSource( $triplets );
2076 $status->merge( $statusDb );
2077 $status->merge( $statusMove );
2083 * Do the database updates and return a new FileRepoStatus indicating how
2084 * many rows where updated.
2086 * @return FileRepoStatus
2088 function doDBUpdates() {
2089 $repo = $this->file
->repo
;
2090 $status = $repo->newGood();
2093 // Update current image
2096 array( 'img_name' => $this->newName
),
2097 array( 'img_name' => $this->oldName
),
2101 if ( $dbw->affectedRows() ) {
2102 $status->successCount++
;
2104 $status->failCount++
;
2105 $status->fatal( 'imageinvalidfilename' );
2109 // Update old images
2113 'oi_name' => $this->newName
,
2114 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2116 array( 'oi_name' => $this->oldName
),
2120 $affected = $dbw->affectedRows();
2121 $total = $this->oldCount
;
2122 $status->successCount +
= $affected;
2123 $status->failCount +
= $total - $affected;
2124 if ( $status->failCount
) {
2125 $status->error( 'imageinvalidfilename' );
2132 * Generate triplets for FSRepo::storeBatch().
2134 function getMoveTriplets() {
2135 $moves = array_merge( array( $this->cur
), $this->olds
);
2136 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2138 foreach ( $moves as $move ) {
2139 // $move: (oldRelativePath, newRelativePath)
2140 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2141 $triplets[] = array( $srcUrl, 'public', $move[1] );
2142 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2149 * Removes non-existent files from move batch.
2151 function removeNonexistentFiles( $triplets ) {
2154 foreach ( $triplets as $file ) {
2155 $files[$file[0]] = $file[0];
2158 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2159 $filteredTriplets = array();
2161 foreach ( $triplets as $file ) {
2162 if ( $result[$file[0]] ) {
2163 $filteredTriplets[] = $file;
2165 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2169 return $filteredTriplets;
2173 * Cleanup a partially moved array of triplets by deleting the target
2174 * files. Called if something went wrong half way.
2176 function cleanupTarget( $triplets ) {
2177 // Create dest pairs from the triplets
2179 foreach ( $triplets as $triplet ) {
2180 $pairs[] = array( $triplet[1], $triplet[2] );
2183 $this->file
->repo
->cleanupBatch( $pairs );
2187 * Cleanup a fully moved array of triplets by deleting the source files.
2188 * Called at the end of the move process if everything else went ok.
2190 function cleanupSource( $triplets ) {
2191 // Create source file names from the triplets
2193 foreach ( $triplets as $triplet ) {
2194 $files[] = $triplet[0];
2197 $this->file
->repo
->cleanupBatch( $files );