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 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 file exists on disk.
553 * @return boolean Whether file 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 /** getThumbnail inherited */
565 /** transform inherited */
568 * Fix thumbnail files from 1.4 or before, with extreme prejudice
570 function migrateThumbFile( $thumbName ) {
571 $thumbDir = $this->getThumbPath();
572 $thumbPath = "$thumbDir/$thumbName";
574 if ( is_dir( $thumbPath ) ) {
575 // Directory where file should be
576 // This happened occasionally due to broken migration code in 1.5
577 // Rename to broken-*
578 for ( $i = 0; $i < 100 ; $i++
) {
579 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
580 if ( !file_exists( $broken ) ) {
581 rename( $thumbPath, $broken );
585 // Doesn't exist anymore
589 if ( is_file( $thumbDir ) ) {
590 // File where directory should be
592 // Doesn't exist anymore
597 /** getHandler inherited */
598 /** iconThumb inherited */
599 /** getLastError inherited */
602 * Get all thumbnail names previously generated for this file
604 function getThumbnails() {
608 $dir = $this->getThumbPath();
610 if ( is_dir( $dir ) ) {
611 $handle = opendir( $dir );
614 while ( false !== ( $file = readdir( $handle ) ) ) {
615 if ( $file { 0 } != '.' ) {
628 * Refresh metadata in memcached, but don't touch thumbnails or squid
630 function purgeMetadataCache() {
632 $this->saveToCache();
633 $this->purgeHistory();
637 * Purge the shared history (OldLocalFile) cache
639 function purgeHistory() {
642 $hashedName = md5( $this->getName() );
643 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
646 $wgMemc->delete( $oldKey );
651 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
653 function purgeCache() {
654 // Refresh metadata cache
655 $this->purgeMetadataCache();
658 $this->purgeThumbnails();
660 // Purge squid cache for this file
661 SquidUpdate
::purge( array( $this->getURL() ) );
665 * Delete cached transformed files
667 function purgeThumbnails() {
668 global $wgUseSquid, $wgExcludeFromThumbnailPurge;
671 $files = $this->getThumbnails();
672 $dir = $this->getThumbPath();
675 foreach ( $files as $file ) {
676 // Only remove files not in the $wgExcludeFromThumbnailPurge configuration variable
677 $ext = pathinfo( "$dir/$file", PATHINFO_EXTENSION
);
678 if ( in_array( $ext, $wgExcludeFromThumbnailPurge ) ) {
682 # Check that the base file name is part of the thumb name
683 # This is a basic sanity check to avoid erasing unrelated directories
684 if ( strpos( $file, $this->getName() ) !== false ) {
685 $url = $this->getThumbUrl( $file );
687 @unlink
( "$dir/$file" );
693 SquidUpdate
::purge( $urls );
697 /** purgeDescription inherited */
698 /** purgeEverything inherited */
700 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
701 $dbr = $this->repo
->getSlaveDB();
702 $tables = array( 'oldimage' );
703 $fields = OldLocalFile
::selectFields();
704 $conds = $opts = $join_conds = array();
705 $eq = $inc ?
'=' : '';
706 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
709 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
713 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
717 $opts['LIMIT'] = $limit;
720 // Search backwards for time > x queries
721 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
722 $opts['ORDER BY'] = "oi_timestamp $order";
723 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
725 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
726 &$conds, &$opts, &$join_conds ) );
728 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
731 foreach ( $res as $row ) {
732 if ( $this->repo
->oldFileFromRowFactory
) {
733 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
735 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
739 if ( $order == 'ASC' ) {
740 $r = array_reverse( $r ); // make sure it ends up descending
747 * Return the history of this file, line by line.
748 * starts with current version, then old versions.
749 * uses $this->historyLine to check which line to return:
750 * 0 return line for current version
751 * 1 query for old versions, return first one
752 * 2, ... return next old version from above query
754 public function nextHistoryLine() {
755 # Polymorphic function name to distinguish foreign and local fetches
756 $fname = get_class( $this ) . '::' . __FUNCTION__
;
758 $dbr = $this->repo
->getSlaveDB();
760 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
761 $this->historyRes
= $dbr->select( 'image',
764 "'' AS oi_archive_name",
768 array( 'img_name' => $this->title
->getDBkey() ),
772 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
773 $this->historyRes
= null;
776 } elseif ( $this->historyLine
== 1 ) {
777 $this->historyRes
= $dbr->select( 'oldimage', '*',
778 array( 'oi_name' => $this->title
->getDBkey() ),
780 array( 'ORDER BY' => 'oi_timestamp DESC' )
783 $this->historyLine ++
;
785 return $dbr->fetchObject( $this->historyRes
);
789 * Reset the history pointer to the first element of the history
791 public function resetHistory() {
792 $this->historyLine
= 0;
794 if ( !is_null( $this->historyRes
) ) {
795 $this->historyRes
= null;
799 /** getFullPath inherited */
800 /** getHashPath inherited */
801 /** getRel inherited */
802 /** getUrlRel inherited */
803 /** getArchiveRel inherited */
804 /** getThumbRel inherited */
805 /** getArchivePath inherited */
806 /** getThumbPath inherited */
807 /** getArchiveUrl inherited */
808 /** getThumbUrl inherited */
809 /** getArchiveVirtualUrl inherited */
810 /** getThumbVirtualUrl inherited */
811 /** isHashed inherited */
814 * Upload a file and record it in the DB
815 * @param $srcPath String: source path or virtual URL
816 * @param $comment String: upload description
817 * @param $pageText String: text to use for the new description page,
818 * if a new description page is created
819 * @param $flags Integer: flags for publish()
820 * @param $props Array: File properties, if known. This can be used to reduce the
821 * upload time when uploading virtual URLs for which the file info
823 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
824 * @param $user Mixed: User object or null to use $wgUser
826 * @return FileRepoStatus object. On success, the value member contains the
827 * archive name, or an empty string if it was a new file.
829 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
831 $status = $this->publish( $srcPath, $flags );
834 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
835 $status->fatal( 'filenotfound', $srcPath );
845 * Record a file upload in the upload log and the image table
846 * @deprecated use upload()
848 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
849 $watch = false, $timestamp = false )
851 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
853 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
859 $wgUser->addWatch( $this->getTitle() );
866 * Record a file upload in the upload log and the image table
868 function recordUpload2(
869 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
871 if ( is_null( $user ) ) {
876 $dbw = $this->repo
->getMasterDB();
880 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
883 if ( $timestamp === false ) {
884 $timestamp = $dbw->timestamp();
887 $props['description'] = $comment;
888 $props['user'] = $user->getId();
889 $props['user_text'] = $user->getName();
890 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
891 $this->setProps( $props );
894 $this->purgeThumbnails();
896 # The file is already on its final location, remove it from the squid cache
897 SquidUpdate
::purge( array( $this->getURL() ) );
899 # Fail now if the file isn't there
900 if ( !$this->fileExists
) {
901 wfDebug( __METHOD__
. ": File " . $this->getPath() . " went missing!\n" );
907 # Test to see if the row exists using INSERT IGNORE
908 # This avoids race conditions by locking the row until the commit, and also
909 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
910 $dbw->insert( 'image',
912 'img_name' => $this->getName(),
913 'img_size' => $this->size
,
914 'img_width' => intval( $this->width
),
915 'img_height' => intval( $this->height
),
916 'img_bits' => $this->bits
,
917 'img_media_type' => $this->media_type
,
918 'img_major_mime' => $this->major_mime
,
919 'img_minor_mime' => $this->minor_mime
,
920 'img_timestamp' => $timestamp,
921 'img_description' => $comment,
922 'img_user' => $user->getId(),
923 'img_user_text' => $user->getName(),
924 'img_metadata' => $this->metadata
,
925 'img_sha1' => $this->sha1
931 if ( $dbw->affectedRows() == 0 ) {
934 # Collision, this is an update of a file
935 # Insert previous contents into oldimage
936 $dbw->insertSelect( 'oldimage', 'image',
938 'oi_name' => 'img_name',
939 'oi_archive_name' => $dbw->addQuotes( $oldver ),
940 'oi_size' => 'img_size',
941 'oi_width' => 'img_width',
942 'oi_height' => 'img_height',
943 'oi_bits' => 'img_bits',
944 'oi_timestamp' => 'img_timestamp',
945 'oi_description' => 'img_description',
946 'oi_user' => 'img_user',
947 'oi_user_text' => 'img_user_text',
948 'oi_metadata' => 'img_metadata',
949 'oi_media_type' => 'img_media_type',
950 'oi_major_mime' => 'img_major_mime',
951 'oi_minor_mime' => 'img_minor_mime',
952 'oi_sha1' => 'img_sha1'
953 ), array( 'img_name' => $this->getName() ), __METHOD__
956 # Update the current image row
957 $dbw->update( 'image',
959 'img_size' => $this->size
,
960 'img_width' => intval( $this->width
),
961 'img_height' => intval( $this->height
),
962 'img_bits' => $this->bits
,
963 'img_media_type' => $this->media_type
,
964 'img_major_mime' => $this->major_mime
,
965 'img_minor_mime' => $this->minor_mime
,
966 'img_timestamp' => $timestamp,
967 'img_description' => $comment,
968 'img_user' => $user->getId(),
969 'img_user_text' => $user->getName(),
970 'img_metadata' => $this->metadata
,
971 'img_sha1' => $this->sha1
972 ), array( /* WHERE */
973 'img_name' => $this->getName()
978 # Update the image count
979 $site_stats = $dbw->tableName( 'site_stats' );
980 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
983 $descTitle = $this->getTitle();
984 $article = new ImagePage( $descTitle );
985 $article->setFile( $this );
988 $log = new LogPage( 'upload' );
989 $action = $reupload ?
'overwrite' : 'upload';
990 $log->addEntry( $action, $descTitle, $comment, array(), $user );
992 if ( $descTitle->exists() ) {
993 # Create a null revision
994 $latest = $descTitle->getLatestRevID();
995 $nullRevision = Revision
::newNullRevision(
997 $descTitle->getArticleId(),
998 $log->getRcComment(),
1001 $nullRevision->insertOn( $dbw );
1003 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
1004 $article->updateRevisionOn( $dbw, $nullRevision );
1006 # Invalidate the cache for the description page
1007 $descTitle->invalidateCache();
1008 $descTitle->purgeSquid();
1010 # New file; create the description page.
1011 # There's already a log entry, so don't make a second RC entry
1012 # Squid and file cache for the description page are purged by doEdit.
1013 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
1016 # Commit the transaction now, in case something goes wrong later
1017 # The most important thing is that files don't get lost, especially archives
1020 # Save to cache and purge the squid
1021 # We shall not saveToCache before the commit since otherwise
1022 # in case of a rollback there is an usable file from memcached
1023 # which in fact doesn't really exist (bug 24978)
1024 $this->saveToCache();
1026 # Hooks, hooks, the magic of hooks...
1027 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1029 # Invalidate cache for all pages using this file
1030 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1031 $update->doUpdate();
1033 # Invalidate cache for all pages that redirects on this page
1034 $redirs = $this->getTitle()->getRedirectsHere();
1036 foreach ( $redirs as $redir ) {
1037 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1038 $update->doUpdate();
1045 * Move or copy a file to its public location. If a file exists at the
1046 * destination, move it to an archive. Returns a FileRepoStatus object with
1047 * the archive name in the "value" member on success.
1049 * The archive name should be passed through to recordUpload for database
1052 * @param $srcPath String: local filesystem path to the source image
1053 * @param $flags Integer: a bitwise combination of:
1054 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1055 * @param $dstArchiveName string File name if the file is to be published
1057 * @return FileRepoStatus object. On success, the value member contains the
1058 * archive name, or an empty string if it was a new file.
1060 function publish( $srcPath, $flags = 0, $dstArchiveName = null ) {
1063 if ( $dstArchiveName ) {
1064 $dstRel = 'archive/' . $this->getHashPath() . $dstArchiveName;
1066 $dstRel = $this->getRel();
1069 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1070 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1071 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1072 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1074 if ( $status->value
== 'new' ) {
1075 $status->value
= '';
1077 $status->value
= $archiveName;
1085 /** getLinksTo inherited */
1086 /** getExifData inherited */
1087 /** isLocal inherited */
1088 /** wasDeleted inherited */
1091 * Move file to the new title
1093 * Move current, old version and all thumbnails
1094 * to the new filename. Old file is deleted.
1096 * Cache purging is done; checks for validity
1097 * and logging are caller's responsibility
1099 * @param $target Title New file name
1100 * @return FileRepoStatus object.
1102 function move( $target ) {
1103 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1106 $batch = new LocalFileMoveBatch( $this, $target );
1107 $batch->addCurrent();
1110 $status = $batch->execute();
1111 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1113 $this->purgeEverything();
1116 if ( $status->isOk() ) {
1117 // Now switch the object
1118 $this->title
= $target;
1119 // Force regeneration of the name and hashpath
1120 unset( $this->name
);
1121 unset( $this->hashPath
);
1122 // Purge the new image
1123 $this->purgeEverything();
1130 * Delete all versions of the file.
1132 * Moves the files into an archive directory (or deletes them)
1133 * and removes the database rows.
1135 * Cache purging is done; logging is caller's responsibility.
1139 * @return FileRepoStatus object.
1141 function delete( $reason, $suppress = false ) {
1144 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1145 $batch->addCurrent();
1147 # Get old version relative paths
1148 $dbw = $this->repo
->getMasterDB();
1149 $result = $dbw->select( 'oldimage',
1150 array( 'oi_archive_name' ),
1151 array( 'oi_name' => $this->getName() ) );
1152 foreach ( $result as $row ) {
1153 $batch->addOld( $row->oi_archive_name
);
1155 $status = $batch->execute();
1157 if ( $status->ok
) {
1158 // Update site_stats
1159 $site_stats = $dbw->tableName( 'site_stats' );
1160 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1161 $this->purgeEverything();
1170 * Delete an old version of the file.
1172 * Moves the file into an archive directory (or deletes it)
1173 * and removes the database row.
1175 * Cache purging is done; logging is caller's responsibility.
1177 * @param $archiveName String
1178 * @param $reason String
1179 * @param $suppress Boolean
1180 * @throws MWException or FSException on database or file store failure
1181 * @return FileRepoStatus object.
1183 function deleteOld( $archiveName, $reason, $suppress = false ) {
1186 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1187 $batch->addOld( $archiveName );
1188 $status = $batch->execute();
1192 if ( $status->ok
) {
1193 $this->purgeDescription();
1194 $this->purgeHistory();
1201 * Restore all or specified deleted revisions to the given file.
1202 * Permissions and logging are left to the caller.
1204 * May throw database exceptions on error.
1206 * @param $versions set of record ids of deleted items to restore,
1207 * or empty to restore all revisions.
1208 * @param $unsuppress Boolean
1209 * @return FileRepoStatus
1211 function restore( $versions = array(), $unsuppress = false ) {
1212 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1217 $batch->addIds( $versions );
1220 $status = $batch->execute();
1222 if ( !$status->isGood() ) {
1226 $cleanupStatus = $batch->cleanup();
1227 $cleanupStatus->successCount
= 0;
1228 $cleanupStatus->failCount
= 0;
1229 $status->merge( $cleanupStatus );
1234 /** isMultipage inherited */
1235 /** pageCount inherited */
1236 /** scaleHeight inherited */
1237 /** getImageSize inherited */
1240 * Get the URL of the file description page.
1242 function getDescriptionUrl() {
1243 return $this->title
->getLocalUrl();
1247 * Get the HTML text of the description page
1248 * This is not used by ImagePage for local files, since (among other things)
1249 * it skips the parser cache.
1251 function getDescriptionText() {
1253 $revision = Revision
::newFromTitle( $this->title
);
1254 if ( !$revision ) return false;
1255 $text = $revision->getText();
1256 if ( !$text ) return false;
1257 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1258 return $pout->getText();
1261 function getDescription() {
1263 return $this->description
;
1266 function getTimestamp() {
1268 return $this->timestamp
;
1271 function getSha1() {
1273 // Initialise now if necessary
1274 if ( $this->sha1
== '' && $this->fileExists
) {
1275 $this->sha1
= File
::sha1Base36( $this->getPath() );
1276 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1277 $dbw = $this->repo
->getMasterDB();
1278 $dbw->update( 'image',
1279 array( 'img_sha1' => $this->sha1
),
1280 array( 'img_name' => $this->getName() ),
1282 $this->saveToCache();
1290 * Start a transaction and lock the image for update
1291 * Increments a reference counter if the lock is already held
1292 * @return boolean True if the image exists, false otherwise
1295 $dbw = $this->repo
->getMasterDB();
1297 if ( !$this->locked
) {
1302 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1306 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1307 * the transaction and thereby releases the image lock.
1310 if ( $this->locked
) {
1312 if ( !$this->locked
) {
1313 $dbw = $this->repo
->getMasterDB();
1320 * Roll back the DB transaction and mark the image unlocked
1322 function unlockAndRollback() {
1323 $this->locked
= false;
1324 $dbw = $this->repo
->getMasterDB();
1327 } // LocalFile class
1329 # ------------------------------------------------------------------------------
1332 * Helper class for file deletion
1335 class LocalFileDeleteBatch
{
1342 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1345 function __construct( File
$file, $reason = '', $suppress = false ) {
1346 $this->file
= $file;
1347 $this->reason
= $reason;
1348 $this->suppress
= $suppress;
1349 $this->status
= $file->repo
->newGood();
1352 function addCurrent() {
1353 $this->srcRels
['.'] = $this->file
->getRel();
1356 function addOld( $oldName ) {
1357 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1358 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1361 function getOldRels() {
1362 if ( !isset( $this->srcRels
['.'] ) ) {
1363 $oldRels =& $this->srcRels
;
1364 $deleteCurrent = false;
1366 $oldRels = $this->srcRels
;
1367 unset( $oldRels['.'] );
1368 $deleteCurrent = true;
1371 return array( $oldRels, $deleteCurrent );
1374 /*protected*/ function getHashes() {
1376 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1378 if ( $deleteCurrent ) {
1379 $hashes['.'] = $this->file
->getSha1();
1382 if ( count( $oldRels ) ) {
1383 $dbw = $this->file
->repo
->getMasterDB();
1384 $res = $dbw->select(
1386 array( 'oi_archive_name', 'oi_sha1' ),
1387 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1391 foreach ( $res as $row ) {
1392 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1393 // Get the hash from the file
1394 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1395 $props = $this->file
->repo
->getFileProps( $oldUrl );
1397 if ( $props['fileExists'] ) {
1398 // Upgrade the oldimage row
1399 $dbw->update( 'oldimage',
1400 array( 'oi_sha1' => $props['sha1'] ),
1401 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1403 $hashes[$row->oi_archive_name
] = $props['sha1'];
1405 $hashes[$row->oi_archive_name
] = false;
1408 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1413 $missing = array_diff_key( $this->srcRels
, $hashes );
1415 foreach ( $missing as $name => $rel ) {
1416 $this->status
->error( 'filedelete-old-unregistered', $name );
1419 foreach ( $hashes as $name => $hash ) {
1421 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1422 unset( $hashes[$name] );
1429 function doDBInserts() {
1432 $dbw = $this->file
->repo
->getMasterDB();
1433 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1434 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1435 $encReason = $dbw->addQuotes( $this->reason
);
1436 $encGroup = $dbw->addQuotes( 'deleted' );
1437 $ext = $this->file
->getExtension();
1438 $dotExt = $ext === '' ?
'' : ".$ext";
1439 $encExt = $dbw->addQuotes( $dotExt );
1440 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1442 // Bitfields to further suppress the content
1443 if ( $this->suppress
) {
1445 // This should be 15...
1446 $bitfield |
= Revision
::DELETED_TEXT
;
1447 $bitfield |
= Revision
::DELETED_COMMENT
;
1448 $bitfield |
= Revision
::DELETED_USER
;
1449 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1451 $bitfield = 'oi_deleted';
1454 if ( $deleteCurrent ) {
1455 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1456 $where = array( 'img_name' => $this->file
->getName() );
1457 $dbw->insertSelect( 'filearchive', 'image',
1459 'fa_storage_group' => $encGroup,
1460 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1461 'fa_deleted_user' => $encUserId,
1462 'fa_deleted_timestamp' => $encTimestamp,
1463 'fa_deleted_reason' => $encReason,
1464 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1466 'fa_name' => 'img_name',
1467 'fa_archive_name' => 'NULL',
1468 'fa_size' => 'img_size',
1469 'fa_width' => 'img_width',
1470 'fa_height' => 'img_height',
1471 'fa_metadata' => 'img_metadata',
1472 'fa_bits' => 'img_bits',
1473 'fa_media_type' => 'img_media_type',
1474 'fa_major_mime' => 'img_major_mime',
1475 'fa_minor_mime' => 'img_minor_mime',
1476 'fa_description' => 'img_description',
1477 'fa_user' => 'img_user',
1478 'fa_user_text' => 'img_user_text',
1479 'fa_timestamp' => 'img_timestamp'
1480 ), $where, __METHOD__
);
1483 if ( count( $oldRels ) ) {
1484 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1486 'oi_name' => $this->file
->getName(),
1487 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1488 $dbw->insertSelect( 'filearchive', 'oldimage',
1490 'fa_storage_group' => $encGroup,
1491 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1492 'fa_deleted_user' => $encUserId,
1493 'fa_deleted_timestamp' => $encTimestamp,
1494 'fa_deleted_reason' => $encReason,
1495 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1497 'fa_name' => 'oi_name',
1498 'fa_archive_name' => 'oi_archive_name',
1499 'fa_size' => 'oi_size',
1500 'fa_width' => 'oi_width',
1501 'fa_height' => 'oi_height',
1502 'fa_metadata' => 'oi_metadata',
1503 'fa_bits' => 'oi_bits',
1504 'fa_media_type' => 'oi_media_type',
1505 'fa_major_mime' => 'oi_major_mime',
1506 'fa_minor_mime' => 'oi_minor_mime',
1507 'fa_description' => 'oi_description',
1508 'fa_user' => 'oi_user',
1509 'fa_user_text' => 'oi_user_text',
1510 'fa_timestamp' => 'oi_timestamp',
1511 'fa_deleted' => $bitfield
1512 ), $where, __METHOD__
);
1516 function doDBDeletes() {
1517 $dbw = $this->file
->repo
->getMasterDB();
1518 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1520 if ( count( $oldRels ) ) {
1521 $dbw->delete( 'oldimage',
1523 'oi_name' => $this->file
->getName(),
1524 'oi_archive_name' => array_keys( $oldRels )
1528 if ( $deleteCurrent ) {
1529 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1534 * Run the transaction
1536 function execute() {
1538 wfProfileIn( __METHOD__
);
1540 $this->file
->lock();
1541 // Leave private files alone
1542 $privateFiles = array();
1543 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1544 $dbw = $this->file
->repo
->getMasterDB();
1546 if ( !empty( $oldRels ) ) {
1547 $res = $dbw->select( 'oldimage',
1548 array( 'oi_archive_name' ),
1549 array( 'oi_name' => $this->file
->getName(),
1550 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1551 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1554 foreach ( $res as $row ) {
1555 $privateFiles[$row->oi_archive_name
] = 1;
1558 // Prepare deletion batch
1559 $hashes = $this->getHashes();
1560 $this->deletionBatch
= array();
1561 $ext = $this->file
->getExtension();
1562 $dotExt = $ext === '' ?
'' : ".$ext";
1564 foreach ( $this->srcRels
as $name => $srcRel ) {
1565 // Skip files that have no hash (missing source).
1566 // Keep private files where they are.
1567 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1568 $hash = $hashes[$name];
1569 $key = $hash . $dotExt;
1570 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1571 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1575 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1576 // We acquire this lock by running the inserts now, before the file operations.
1578 // This potentially has poor lock contention characteristics -- an alternative
1579 // scheme would be to insert stub filearchive entries with no fa_name and commit
1580 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1581 $this->doDBInserts();
1583 // Removes non-existent file from the batch, so we don't get errors.
1584 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1586 // Execute the file deletion batch
1587 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1589 if ( !$status->isGood() ) {
1590 $this->status
->merge( $status );
1593 if ( !$this->status
->ok
) {
1594 // Critical file deletion error
1595 // Roll back inserts, release lock and abort
1596 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1597 $this->file
->unlockAndRollback();
1598 wfProfileOut( __METHOD__
);
1599 return $this->status
;
1603 if ( $wgUseSquid ) {
1606 foreach ( $this->srcRels
as $srcRel ) {
1607 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1608 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1610 SquidUpdate
::purge( $urls );
1613 // Delete image/oldimage rows
1614 $this->doDBDeletes();
1616 // Commit and return
1617 $this->file
->unlock();
1618 wfProfileOut( __METHOD__
);
1620 return $this->status
;
1624 * Removes non-existent files from a deletion batch.
1626 function removeNonexistentFiles( $batch ) {
1627 $files = $newBatch = array();
1629 foreach ( $batch as $batchItem ) {
1630 list( $src, $dest ) = $batchItem;
1631 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1634 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1636 foreach ( $batch as $batchItem ) {
1637 if ( $result[$batchItem[0]] ) {
1638 $newBatch[] = $batchItem;
1646 # ------------------------------------------------------------------------------
1649 * Helper class for file undeletion
1652 class LocalFileRestoreBatch
{
1658 var $cleanupBatch, $ids, $all, $unsuppress = false;
1660 function __construct( File
$file, $unsuppress = false ) {
1661 $this->file
= $file;
1662 $this->cleanupBatch
= $this->ids
= array();
1663 $this->ids
= array();
1664 $this->unsuppress
= $unsuppress;
1670 function addId( $fa_id ) {
1671 $this->ids
[] = $fa_id;
1675 * Add a whole lot of files by ID
1677 function addIds( $ids ) {
1678 $this->ids
= array_merge( $this->ids
, $ids );
1682 * Add all revisions of the file
1689 * Run the transaction, except the cleanup batch.
1690 * The cleanup batch should be run in a separate transaction, because it locks different
1691 * rows and there's no need to keep the image row locked while it's acquiring those locks
1692 * The caller may have its own transaction open.
1693 * So we save the batch and let the caller call cleanup()
1695 function execute() {
1698 if ( !$this->all
&& !$this->ids
) {
1700 return $this->file
->repo
->newGood();
1703 $exists = $this->file
->lock();
1704 $dbw = $this->file
->repo
->getMasterDB();
1705 $status = $this->file
->repo
->newGood();
1707 // Fetch all or selected archived revisions for the file,
1708 // sorted from the most recent to the oldest.
1709 $conditions = array( 'fa_name' => $this->file
->getName() );
1711 if ( !$this->all
) {
1712 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1715 $result = $dbw->select( 'filearchive', '*',
1718 array( 'ORDER BY' => 'fa_timestamp DESC' )
1721 $idsPresent = array();
1722 $storeBatch = array();
1723 $insertBatch = array();
1724 $insertCurrent = false;
1725 $deleteIds = array();
1727 $archiveNames = array();
1729 foreach ( $result as $row ) {
1730 $idsPresent[] = $row->fa_id
;
1732 if ( $row->fa_name
!= $this->file
->getName() ) {
1733 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1734 $status->failCount++
;
1738 if ( $row->fa_storage_key
== '' ) {
1739 // Revision was missing pre-deletion
1740 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1741 $status->failCount++
;
1745 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1746 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1748 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1751 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1752 $sha1 = substr( $sha1, 1 );
1755 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1756 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1757 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1758 ||
is_null( $row->fa_metadata
) ) {
1759 // Refresh our metadata
1760 // Required for a new current revision; nice for older ones too. :)
1761 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1764 'minor_mime' => $row->fa_minor_mime
,
1765 'major_mime' => $row->fa_major_mime
,
1766 'media_type' => $row->fa_media_type
,
1767 'metadata' => $row->fa_metadata
1771 if ( $first && !$exists ) {
1772 // This revision will be published as the new current version
1773 $destRel = $this->file
->getRel();
1774 $insertCurrent = array(
1775 'img_name' => $row->fa_name
,
1776 'img_size' => $row->fa_size
,
1777 'img_width' => $row->fa_width
,
1778 'img_height' => $row->fa_height
,
1779 'img_metadata' => $props['metadata'],
1780 'img_bits' => $row->fa_bits
,
1781 'img_media_type' => $props['media_type'],
1782 'img_major_mime' => $props['major_mime'],
1783 'img_minor_mime' => $props['minor_mime'],
1784 'img_description' => $row->fa_description
,
1785 'img_user' => $row->fa_user
,
1786 'img_user_text' => $row->fa_user_text
,
1787 'img_timestamp' => $row->fa_timestamp
,
1791 // The live (current) version cannot be hidden!
1792 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1793 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1794 $this->cleanupBatch
[] = $row->fa_storage_key
;
1797 $archiveName = $row->fa_archive_name
;
1799 if ( $archiveName == '' ) {
1800 // This was originally a current version; we
1801 // have to devise a new archive name for it.
1802 // Format is <timestamp of archiving>!<name>
1803 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1806 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1808 } while ( isset( $archiveNames[$archiveName] ) );
1811 $archiveNames[$archiveName] = true;
1812 $destRel = $this->file
->getArchiveRel( $archiveName );
1813 $insertBatch[] = array(
1814 'oi_name' => $row->fa_name
,
1815 'oi_archive_name' => $archiveName,
1816 'oi_size' => $row->fa_size
,
1817 'oi_width' => $row->fa_width
,
1818 'oi_height' => $row->fa_height
,
1819 'oi_bits' => $row->fa_bits
,
1820 'oi_description' => $row->fa_description
,
1821 'oi_user' => $row->fa_user
,
1822 'oi_user_text' => $row->fa_user_text
,
1823 'oi_timestamp' => $row->fa_timestamp
,
1824 'oi_metadata' => $props['metadata'],
1825 'oi_media_type' => $props['media_type'],
1826 'oi_major_mime' => $props['major_mime'],
1827 'oi_minor_mime' => $props['minor_mime'],
1828 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1829 'oi_sha1' => $sha1 );
1832 $deleteIds[] = $row->fa_id
;
1834 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1835 // private files can stay where they are
1836 $status->successCount++
;
1838 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1839 $this->cleanupBatch
[] = $row->fa_storage_key
;
1847 // Add a warning to the status object for missing IDs
1848 $missingIds = array_diff( $this->ids
, $idsPresent );
1850 foreach ( $missingIds as $id ) {
1851 $status->error( 'undelete-missing-filearchive', $id );
1854 // Remove missing files from batch, so we don't get errors when undeleting them
1855 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1857 // Run the store batch
1858 // Use the OVERWRITE_SAME flag to smooth over a common error
1859 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1860 $status->merge( $storeStatus );
1862 if ( !$status->isGood() ) {
1863 // Even if some files could be copied, fail entirely as that is the
1864 // easiest thing to do without data loss
1865 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1866 $status->ok
= false;
1867 $this->file
->unlock();
1872 // Run the DB updates
1873 // Because we have locked the image row, key conflicts should be rare.
1874 // If they do occur, we can roll back the transaction at this time with
1875 // no data loss, but leaving unregistered files scattered throughout the
1877 // This is not ideal, which is why it's important to lock the image row.
1878 if ( $insertCurrent ) {
1879 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1882 if ( $insertBatch ) {
1883 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1887 $dbw->delete( 'filearchive',
1888 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1892 // If store batch is empty (all files are missing), deletion is to be considered successful
1893 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1895 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1897 // Update site_stats
1898 $site_stats = $dbw->tableName( 'site_stats' );
1899 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1901 $this->file
->purgeEverything();
1903 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1904 $this->file
->purgeDescription();
1905 $this->file
->purgeHistory();
1909 $this->file
->unlock();
1915 * Removes non-existent files from a store batch.
1917 function removeNonexistentFiles( $triplets ) {
1918 $files = $filteredTriplets = array();
1919 foreach ( $triplets as $file )
1920 $files[$file[0]] = $file[0];
1922 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1924 foreach ( $triplets as $file ) {
1925 if ( $result[$file[0]] ) {
1926 $filteredTriplets[] = $file;
1930 return $filteredTriplets;
1934 * Removes non-existent files from a cleanup batch.
1936 function removeNonexistentFromCleanup( $batch ) {
1937 $files = $newBatch = array();
1938 $repo = $this->file
->repo
;
1940 foreach ( $batch as $file ) {
1941 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1942 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1945 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1947 foreach ( $batch as $file ) {
1948 if ( $result[$file] ) {
1949 $newBatch[] = $file;
1957 * Delete unused files in the deleted zone.
1958 * This should be called from outside the transaction in which execute() was called.
1960 function cleanup() {
1961 if ( !$this->cleanupBatch
) {
1962 return $this->file
->repo
->newGood();
1965 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1967 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1972 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
1973 $cleanupBatch = array();
1975 foreach ( $storeStatus->success
as $i => $success ) {
1977 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][1] );
1980 $this->file
->repo
->cleanupBatch( $cleanupBatch );
1984 # ------------------------------------------------------------------------------
1987 * Helper class for file movement
1990 class LocalFileMoveBatch
{
1991 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1993 function __construct( File
$file, Title
$target ) {
1994 $this->file
= $file;
1995 $this->target
= $target;
1996 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1997 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1998 $this->oldName
= $this->file
->getName();
1999 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2000 $this->oldRel
= $this->oldHash
. $this->oldName
;
2001 $this->newRel
= $this->newHash
. $this->newName
;
2002 $this->db
= $file->repo
->getMasterDb();
2006 * Add the current image to the batch
2008 function addCurrent() {
2009 $this->cur
= array( $this->oldRel
, $this->newRel
);
2013 * Add the old versions of the image to the batch
2015 function addOlds() {
2016 $archiveBase = 'archive';
2017 $this->olds
= array();
2018 $this->oldCount
= 0;
2020 $result = $this->db
->select( 'oldimage',
2021 array( 'oi_archive_name', 'oi_deleted' ),
2022 array( 'oi_name' => $this->oldName
),
2026 foreach ( $result as $row ) {
2027 $oldName = $row->oi_archive_name
;
2028 $bits = explode( '!', $oldName, 2 );
2030 if ( count( $bits ) != 2 ) {
2031 wfDebug( "Invalid old file name: $oldName \n" );
2035 list( $timestamp, $filename ) = $bits;
2037 if ( $this->oldName
!= $filename ) {
2038 wfDebug( "Invalid old file name: $oldName \n" );
2044 // Do we want to add those to oldCount?
2045 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2049 $this->olds
[] = array(
2050 "{$archiveBase}/{$this->oldHash}{$oldName}",
2051 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2059 function execute() {
2060 $repo = $this->file
->repo
;
2061 $status = $repo->newGood();
2062 $triplets = $this->getMoveTriplets();
2064 $triplets = $this->removeNonexistentFiles( $triplets );
2066 // Copy the files into their new location
2067 $statusMove = $repo->storeBatch( $triplets );
2068 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2069 if ( !$statusMove->isGood() ) {
2070 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2071 $this->cleanupTarget( $triplets );
2072 $statusMove->ok
= false;
2077 $statusDb = $this->doDBUpdates();
2078 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2079 if ( !$statusDb->isGood() ) {
2080 $this->db
->rollback();
2081 // Something went wrong with the DB updates, so remove the target files
2082 $this->cleanupTarget( $triplets );
2083 $statusDb->ok
= false;
2086 $this->db
->commit();
2088 // Everything went ok, remove the source files
2089 $this->cleanupSource( $triplets );
2091 $status->merge( $statusDb );
2092 $status->merge( $statusMove );
2098 * Do the database updates and return a new FileRepoStatus indicating how
2099 * many rows where updated.
2101 * @return FileRepoStatus
2103 function doDBUpdates() {
2104 $repo = $this->file
->repo
;
2105 $status = $repo->newGood();
2108 // Update current image
2111 array( 'img_name' => $this->newName
),
2112 array( 'img_name' => $this->oldName
),
2116 if ( $dbw->affectedRows() ) {
2117 $status->successCount++
;
2119 $status->failCount++
;
2120 $status->fatal( 'imageinvalidfilename' );
2124 // Update old images
2128 'oi_name' => $this->newName
,
2129 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2131 array( 'oi_name' => $this->oldName
),
2135 $affected = $dbw->affectedRows();
2136 $total = $this->oldCount
;
2137 $status->successCount +
= $affected;
2138 $status->failCount +
= $total - $affected;
2139 if ( $status->failCount
) {
2140 $status->error( 'imageinvalidfilename' );
2147 * Generate triplets for FSRepo::storeBatch().
2149 function getMoveTriplets() {
2150 $moves = array_merge( array( $this->cur
), $this->olds
);
2151 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2153 foreach ( $moves as $move ) {
2154 // $move: (oldRelativePath, newRelativePath)
2155 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2156 $triplets[] = array( $srcUrl, 'public', $move[1] );
2157 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2164 * Removes non-existent files from move batch.
2166 function removeNonexistentFiles( $triplets ) {
2169 foreach ( $triplets as $file ) {
2170 $files[$file[0]] = $file[0];
2173 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2174 $filteredTriplets = array();
2176 foreach ( $triplets as $file ) {
2177 if ( $result[$file[0]] ) {
2178 $filteredTriplets[] = $file;
2180 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2184 return $filteredTriplets;
2188 * Cleanup a partially moved array of triplets by deleting the target
2189 * files. Called if something went wrong half way.
2191 function cleanupTarget( $triplets ) {
2192 // Create dest pairs from the triplets
2194 foreach ( $triplets as $triplet ) {
2195 $pairs[] = array( $triplet[1], $triplet[2] );
2198 $this->file
->repo
->cleanupBatch( $pairs );
2202 * Cleanup a fully moved array of triplets by deleting the source files.
2203 * Called at the end of the move process if everything else went ok.
2205 function cleanupSource( $triplets ) {
2206 // Create source file names from the triplets
2208 foreach ( $triplets as $triplet ) {
2209 $files[] = $triplet[0];
2212 $this->file
->repo
->cleanupBatch( $files );