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
73 static function newFromTitle( $title, $repo, $unused = null ) {
74 return new self( $title, $repo );
78 * Create a LocalFile from a title
79 * Do not call this except from inside a repo class.
86 static function newFromRow( $row, $repo ) {
87 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
88 $file = new self( $title, $repo );
89 $file->loadFromRow( $row );
95 * Create a LocalFile from a SHA-1 key
96 * Do not call this except from inside a repo class.
99 * @param $repo LocalRepo
100 * @param $timestamp string
104 static function newFromKey( $sha1, $repo, $timestamp = false ) {
105 $conds = array( 'img_sha1' => $sha1 );
108 $conds['img_timestamp'] = $timestamp;
111 $dbr = $repo->getSlaveDB();
112 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
115 return self
::newFromRow( $row, $repo );
122 * Fields in the image table
124 static function selectFields() {
145 * Do not call this except from inside a repo class.
147 function __construct( $title, $repo ) {
148 if ( !is_object( $title ) ) {
149 throw new MWException( __CLASS__
. ' constructor given bogus title.' );
152 parent
::__construct( $title, $repo );
154 $this->metadata
= '';
155 $this->historyLine
= 0;
156 $this->historyRes
= null;
157 $this->dataLoaded
= false;
161 * Get the memcached key for the main data for this file, or false if
162 * there is no access to the shared cache.
164 function getCacheKey() {
165 $hashedName = md5( $this->getName() );
167 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
171 * Try to load file metadata from memcached. Returns true on success.
173 function loadFromCache() {
176 wfProfileIn( __METHOD__
);
177 $this->dataLoaded
= false;
178 $key = $this->getCacheKey();
181 wfProfileOut( __METHOD__
);
185 $cachedValues = $wgMemc->get( $key );
187 // Check if the key existed and belongs to this version of MediaWiki
188 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
189 wfDebug( "Pulling file metadata from cache key $key\n" );
190 $this->fileExists
= $cachedValues['fileExists'];
191 if ( $this->fileExists
) {
192 $this->setProps( $cachedValues );
194 $this->dataLoaded
= true;
197 if ( $this->dataLoaded
) {
198 wfIncrStats( 'image_cache_hit' );
200 wfIncrStats( 'image_cache_miss' );
203 wfProfileOut( __METHOD__
);
204 return $this->dataLoaded
;
208 * Save the file metadata to memcached
210 function saveToCache() {
214 $key = $this->getCacheKey();
220 $fields = $this->getCacheFields( '' );
221 $cache = array( 'version' => MW_FILE_VERSION
);
222 $cache['fileExists'] = $this->fileExists
;
224 if ( $this->fileExists
) {
225 foreach ( $fields as $field ) {
226 $cache[$field] = $this->$field;
230 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
234 * Load metadata from the file itself
236 function loadFromFile() {
237 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
240 function getCacheFields( $prefix = 'img_' ) {
241 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
242 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
243 static $results = array();
245 if ( $prefix == '' ) {
249 if ( !isset( $results[$prefix] ) ) {
250 $prefixedFields = array();
251 foreach ( $fields as $field ) {
252 $prefixedFields[] = $prefix . $field;
254 $results[$prefix] = $prefixedFields;
257 return $results[$prefix];
261 * Load file metadata from the DB
263 function loadFromDB() {
264 # Polymorphic function name to distinguish foreign and local fetches
265 $fname = get_class( $this ) . '::' . __FUNCTION__
;
266 wfProfileIn( $fname );
268 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
269 $this->dataLoaded
= true;
271 $dbr = $this->repo
->getMasterDB();
273 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
274 array( 'img_name' => $this->getName() ), $fname );
277 $this->loadFromRow( $row );
279 $this->fileExists
= false;
282 wfProfileOut( $fname );
286 * Decode a row from the database (either object or array) to an array
287 * with timestamps and MIME types decoded, and the field prefix removed.
289 function decodeRow( $row, $prefix = 'img_' ) {
290 $array = (array)$row;
291 $prefixLength = strlen( $prefix );
293 // Sanity check prefix once
294 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
295 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
300 foreach ( $array as $name => $value ) {
301 $decoded[substr( $name, $prefixLength )] = $value;
304 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
306 if ( empty( $decoded['major_mime'] ) ) {
307 $decoded['mime'] = 'unknown/unknown';
309 if ( !$decoded['minor_mime'] ) {
310 $decoded['minor_mime'] = 'unknown';
312 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
315 # Trim zero padding from char/binary field
316 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
322 * Load file metadata from a DB result row
324 function loadFromRow( $row, $prefix = 'img_' ) {
325 $this->dataLoaded
= true;
326 $array = $this->decodeRow( $row, $prefix );
328 foreach ( $array as $name => $value ) {
329 $this->$name = $value;
332 $this->fileExists
= true;
333 $this->maybeUpgradeRow();
337 * Load file metadata from cache or DB, unless already loaded
340 if ( !$this->dataLoaded
) {
341 if ( !$this->loadFromCache() ) {
343 $this->saveToCache();
345 $this->dataLoaded
= true;
350 * Upgrade a row if it needs it
352 function maybeUpgradeRow() {
353 global $wgUpdateCompatibleMetadata;
354 if ( wfReadOnly() ) {
358 if ( is_null( $this->media_type
) ||
359 $this->mime
== 'image/svg'
362 $this->upgraded
= true;
364 $handler = $this->getHandler();
366 $validity = $handler->isMetadataValid( $this, $this->metadata
);
367 if ( $validity === MediaHandler
::METADATA_BAD
368 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
371 $this->upgraded
= true;
377 function getUpgraded() {
378 return $this->upgraded
;
382 * Fix assorted version-related problems with the image row by reloading it from the file
384 function upgradeRow() {
385 wfProfileIn( __METHOD__
);
387 $this->loadFromFile();
389 # Don't destroy file info of missing files
390 if ( !$this->fileExists
) {
391 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
392 wfProfileOut( __METHOD__
);
396 $dbw = $this->repo
->getMasterDB();
397 list( $major, $minor ) = self
::splitMime( $this->mime
);
399 if ( wfReadOnly() ) {
400 wfProfileOut( __METHOD__
);
403 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
405 $dbw->update( 'image',
407 'img_width' => $this->width
,
408 'img_height' => $this->height
,
409 'img_bits' => $this->bits
,
410 'img_media_type' => $this->media_type
,
411 'img_major_mime' => $major,
412 'img_minor_mime' => $minor,
413 'img_metadata' => $this->metadata
,
414 'img_sha1' => $this->sha1
,
415 ), array( 'img_name' => $this->getName() ),
419 $this->saveToCache();
420 wfProfileOut( __METHOD__
);
424 * Set properties in this object to be equal to those given in the
425 * associative array $info. Only cacheable fields can be set.
427 * If 'mime' is given, it will be split into major_mime/minor_mime.
428 * If major_mime/minor_mime are given, $this->mime will also be set.
430 function setProps( $info ) {
431 $this->dataLoaded
= true;
432 $fields = $this->getCacheFields( '' );
433 $fields[] = 'fileExists';
435 foreach ( $fields as $field ) {
436 if ( isset( $info[$field] ) ) {
437 $this->$field = $info[$field];
441 // Fix up mime fields
442 if ( isset( $info['major_mime'] ) ) {
443 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
444 } elseif ( isset( $info['mime'] ) ) {
445 $this->mime
= $info['mime'];
446 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
450 /** splitMime inherited */
451 /** getName inherited */
452 /** getTitle inherited */
453 /** getURL inherited */
454 /** getViewURL inherited */
455 /** getPath inherited */
456 /** isVisible inhereted */
458 function isMissing() {
459 if ( $this->missing
=== null ) {
460 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
461 $this->missing
= !$fileExists;
463 return $this->missing
;
467 * Return the width of the image
469 * Returns false on error
471 public function getWidth( $page = 1 ) {
474 if ( $this->isMultipage() ) {
475 $dim = $this->getHandler()->getPageDimensions( $this, $page );
477 return $dim['width'];
487 * Return the height of the image
489 * Returns false on error
491 public function getHeight( $page = 1 ) {
494 if ( $this->isMultipage() ) {
495 $dim = $this->getHandler()->getPageDimensions( $this, $page );
497 return $dim['height'];
502 return $this->height
;
507 * Returns ID or name of user who uploaded the file
509 * @param $type string 'text' or 'id'
511 function getUser( $type = 'text' ) {
514 if ( $type == 'text' ) {
515 return $this->user_text
;
516 } elseif ( $type == 'id' ) {
522 * Get handler-specific metadata
524 function getMetadata() {
526 return $this->metadata
;
529 function getBitDepth() {
535 * Return the size of the image file, in bytes
537 public function getSize() {
543 * Returns the mime type of the file.
545 function getMimeType() {
551 * Return the type of the media in the file.
552 * Use the value returned by this function with the MEDIATYPE_xxx constants.
554 function getMediaType() {
556 return $this->media_type
;
559 /** canRender inherited */
560 /** mustRender inherited */
561 /** allowInlineDisplay inherited */
562 /** isSafeFile inherited */
563 /** isTrustedFile inherited */
566 * Returns true if the file exists on disk.
567 * @return boolean Whether file exist on disk.
569 public function exists() {
571 return $this->fileExists
;
574 /** getTransformScript inherited */
575 /** getUnscaledThumb inherited */
576 /** thumbName inherited */
577 /** createThumb inherited */
578 /** transform inherited */
581 * Fix thumbnail files from 1.4 or before, with extreme prejudice
583 function migrateThumbFile( $thumbName ) {
584 $thumbDir = $this->getThumbPath();
585 $thumbPath = "$thumbDir/$thumbName";
587 if ( is_dir( $thumbPath ) ) {
588 // Directory where file should be
589 // This happened occasionally due to broken migration code in 1.5
590 // Rename to broken-*
591 for ( $i = 0; $i < 100 ; $i++
) {
592 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
593 if ( !file_exists( $broken ) ) {
594 rename( $thumbPath, $broken );
598 // Doesn't exist anymore
602 if ( is_file( $thumbDir ) ) {
603 // File where directory should be
605 // Doesn't exist anymore
610 /** getHandler inherited */
611 /** iconThumb inherited */
612 /** getLastError inherited */
615 * Get all thumbnail names previously generated for this file
617 function getThumbnails() {
621 $dir = $this->getThumbPath();
623 if ( is_dir( $dir ) ) {
624 $handle = opendir( $dir );
627 while ( false !== ( $file = readdir( $handle ) ) ) {
628 if ( $file { 0 } != '.' ) {
641 * Refresh metadata in memcached, but don't touch thumbnails or squid
643 function purgeMetadataCache() {
645 $this->saveToCache();
646 $this->purgeHistory();
650 * Purge the shared history (OldLocalFile) cache
652 function purgeHistory() {
655 $hashedName = md5( $this->getName() );
656 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
658 // Must purge thumbnails for old versions too! bug 30192
659 foreach( $this->getHistory() as $oldFile ) {
660 $oldFile->purgeThumbnails();
664 $wgMemc->delete( $oldKey );
669 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
671 function purgeCache() {
672 // Refresh metadata cache
673 $this->purgeMetadataCache();
676 $this->purgeThumbnails();
678 // Purge squid cache for this file
679 SquidUpdate
::purge( array( $this->getURL() ) );
683 * Delete cached transformed files
685 function purgeThumbnails() {
686 global $wgUseSquid, $wgExcludeFromThumbnailPurge;
689 $files = $this->getThumbnails();
690 $dir = $this->getThumbPath();
693 foreach ( $files as $file ) {
694 // Only remove files not in the $wgExcludeFromThumbnailPurge configuration variable
695 $ext = pathinfo( "$dir/$file", PATHINFO_EXTENSION
);
696 if ( in_array( $ext, $wgExcludeFromThumbnailPurge ) ) {
700 # Check that the base file name is part of the thumb name
701 # This is a basic sanity check to avoid erasing unrelated directories
702 if ( strpos( $file, $this->getName() ) !== false ) {
703 $url = $this->getThumbUrl( $file );
705 wfSuppressWarnings();
706 unlink( "$dir/$file" );
713 SquidUpdate
::purge( $urls );
717 /** purgeDescription inherited */
718 /** purgeEverything inherited */
720 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
721 $dbr = $this->repo
->getSlaveDB();
722 $tables = array( 'oldimage' );
723 $fields = OldLocalFile
::selectFields();
724 $conds = $opts = $join_conds = array();
725 $eq = $inc ?
'=' : '';
726 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
729 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
733 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
737 $opts['LIMIT'] = $limit;
740 // Search backwards for time > x queries
741 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
742 $opts['ORDER BY'] = "oi_timestamp $order";
743 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
745 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
746 &$conds, &$opts, &$join_conds ) );
748 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
751 foreach ( $res as $row ) {
752 if ( $this->repo
->oldFileFromRowFactory
) {
753 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
755 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
759 if ( $order == 'ASC' ) {
760 $r = array_reverse( $r ); // make sure it ends up descending
767 * Return the history of this file, line by line.
768 * starts with current version, then old versions.
769 * uses $this->historyLine to check which line to return:
770 * 0 return line for current version
771 * 1 query for old versions, return first one
772 * 2, ... return next old version from above query
774 public function nextHistoryLine() {
775 # Polymorphic function name to distinguish foreign and local fetches
776 $fname = get_class( $this ) . '::' . __FUNCTION__
;
778 $dbr = $this->repo
->getSlaveDB();
780 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
781 $this->historyRes
= $dbr->select( 'image',
784 "'' AS oi_archive_name",
788 array( 'img_name' => $this->title
->getDBkey() ),
792 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
793 $this->historyRes
= null;
796 } elseif ( $this->historyLine
== 1 ) {
797 $this->historyRes
= $dbr->select( 'oldimage', '*',
798 array( 'oi_name' => $this->title
->getDBkey() ),
800 array( 'ORDER BY' => 'oi_timestamp DESC' )
803 $this->historyLine ++
;
805 return $dbr->fetchObject( $this->historyRes
);
809 * Reset the history pointer to the first element of the history
811 public function resetHistory() {
812 $this->historyLine
= 0;
814 if ( !is_null( $this->historyRes
) ) {
815 $this->historyRes
= null;
819 /** getFullPath inherited */
820 /** getHashPath inherited */
821 /** getRel inherited */
822 /** getUrlRel inherited */
823 /** getArchiveRel inherited */
824 /** getArchivePath inherited */
825 /** getThumbPath inherited */
826 /** getArchiveUrl inherited */
827 /** getThumbUrl inherited */
828 /** getArchiveVirtualUrl inherited */
829 /** getThumbVirtualUrl inherited */
830 /** isHashed inherited */
833 * Upload a file and record it in the DB
834 * @param $srcPath String: source path or virtual URL
835 * @param $comment String: upload description
836 * @param $pageText String: text to use for the new description page,
837 * if a new description page is created
838 * @param $flags Integer: flags for publish()
839 * @param $props Array: File properties, if known. This can be used to reduce the
840 * upload time when uploading virtual URLs for which the file info
842 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
843 * @param $user Mixed: User object or null to use $wgUser
845 * @return FileRepoStatus object. On success, the value member contains the
846 * archive name, or an empty string if it was a new file.
848 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
850 $status = $this->publish( $srcPath, $flags );
853 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
854 $status->fatal( 'filenotfound', $srcPath );
864 * Record a file upload in the upload log and the image table
866 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
867 $watch = false, $timestamp = false )
869 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
871 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
877 $wgUser->addWatch( $this->getTitle() );
883 * Record a file upload in the upload log and the image table
885 function recordUpload2(
886 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
888 if ( is_null( $user ) ) {
893 $dbw = $this->repo
->getMasterDB();
897 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
900 if ( $timestamp === false ) {
901 $timestamp = $dbw->timestamp();
904 $props['description'] = $comment;
905 $props['user'] = $user->getId();
906 $props['user_text'] = $user->getName();
907 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
908 $this->setProps( $props );
911 $this->purgeThumbnails();
913 # The file is already on its final location, remove it from the squid cache
914 SquidUpdate
::purge( array( $this->getURL() ) );
916 # Fail now if the file isn't there
917 if ( !$this->fileExists
) {
918 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
924 # Test to see if the row exists using INSERT IGNORE
925 # This avoids race conditions by locking the row until the commit, and also
926 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
927 $dbw->insert( 'image',
929 'img_name' => $this->getName(),
930 'img_size' => $this->size
,
931 'img_width' => intval( $this->width
),
932 'img_height' => intval( $this->height
),
933 'img_bits' => $this->bits
,
934 'img_media_type' => $this->media_type
,
935 'img_major_mime' => $this->major_mime
,
936 'img_minor_mime' => $this->minor_mime
,
937 'img_timestamp' => $timestamp,
938 'img_description' => $comment,
939 'img_user' => $user->getId(),
940 'img_user_text' => $user->getName(),
941 'img_metadata' => $this->metadata
,
942 'img_sha1' => $this->sha1
948 if ( $dbw->affectedRows() == 0 ) {
951 # Collision, this is an update of a file
952 # Insert previous contents into oldimage
953 $dbw->insertSelect( 'oldimage', 'image',
955 'oi_name' => 'img_name',
956 'oi_archive_name' => $dbw->addQuotes( $oldver ),
957 'oi_size' => 'img_size',
958 'oi_width' => 'img_width',
959 'oi_height' => 'img_height',
960 'oi_bits' => 'img_bits',
961 'oi_timestamp' => 'img_timestamp',
962 'oi_description' => 'img_description',
963 'oi_user' => 'img_user',
964 'oi_user_text' => 'img_user_text',
965 'oi_metadata' => 'img_metadata',
966 'oi_media_type' => 'img_media_type',
967 'oi_major_mime' => 'img_major_mime',
968 'oi_minor_mime' => 'img_minor_mime',
969 'oi_sha1' => 'img_sha1'
970 ), array( 'img_name' => $this->getName() ), __METHOD__
973 # Update the current image row
974 $dbw->update( 'image',
976 'img_size' => $this->size
,
977 'img_width' => intval( $this->width
),
978 'img_height' => intval( $this->height
),
979 'img_bits' => $this->bits
,
980 'img_media_type' => $this->media_type
,
981 'img_major_mime' => $this->major_mime
,
982 'img_minor_mime' => $this->minor_mime
,
983 'img_timestamp' => $timestamp,
984 'img_description' => $comment,
985 'img_user' => $user->getId(),
986 'img_user_text' => $user->getName(),
987 'img_metadata' => $this->metadata
,
988 'img_sha1' => $this->sha1
989 ), array( /* WHERE */
990 'img_name' => $this->getName()
995 # Update the image count
996 $site_stats = $dbw->tableName( 'site_stats' );
997 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1000 $descTitle = $this->getTitle();
1001 $article = new ImagePage( $descTitle );
1002 $article->setFile( $this );
1005 $log = new LogPage( 'upload' );
1006 $action = $reupload ?
'overwrite' : 'upload';
1007 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1009 if ( $descTitle->exists() ) {
1010 # Create a null revision
1011 $latest = $descTitle->getLatestRevID();
1012 $nullRevision = Revision
::newNullRevision(
1014 $descTitle->getArticleId(),
1015 $log->getRcComment(),
1018 if (!is_null($nullRevision)) {
1019 $nullRevision->insertOn( $dbw );
1021 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
1022 $article->updateRevisionOn( $dbw, $nullRevision );
1024 # Invalidate the cache for the description page
1025 $descTitle->invalidateCache();
1026 $descTitle->purgeSquid();
1028 # New file; create the description page.
1029 # There's already a log entry, so don't make a second RC entry
1030 # Squid and file cache for the description page are purged by doEdit.
1031 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
1034 # Commit the transaction now, in case something goes wrong later
1035 # The most important thing is that files don't get lost, especially archives
1038 # Save to cache and purge the squid
1039 # We shall not saveToCache before the commit since otherwise
1040 # in case of a rollback there is an usable file from memcached
1041 # which in fact doesn't really exist (bug 24978)
1042 $this->saveToCache();
1044 # Hooks, hooks, the magic of hooks...
1045 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1047 # Invalidate cache for all pages using this file
1048 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1049 $update->doUpdate();
1051 # Invalidate cache for all pages that redirects on this page
1052 $redirs = $this->getTitle()->getRedirectsHere();
1054 foreach ( $redirs as $redir ) {
1055 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1056 $update->doUpdate();
1063 * Move or copy a file to its public location. If a file exists at the
1064 * destination, move it to an archive. Returns a FileRepoStatus object with
1065 * the archive name in the "value" member on success.
1067 * The archive name should be passed through to recordUpload for database
1070 * @param $srcPath String: local filesystem path to the source image
1071 * @param $flags Integer: a bitwise combination of:
1072 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1073 * @return FileRepoStatus object. On success, the value member contains the
1074 * archive name, or an empty string if it was a new file.
1076 function publish( $srcPath, $flags = 0 ) {
1077 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1081 * Move or copy a file to a specified location. Returns a FileRepoStatus
1082 * object with the archive name in the "value" member on success.
1084 * The archive name should be passed through to recordUpload for database
1087 * @param $srcPath String: local filesystem path to the source image
1088 * @param $dstRel String: target relative path
1089 * @param $flags Integer: a bitwise combination of:
1090 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1091 * @return FileRepoStatus object. On success, the value member contains the
1092 * archive name, or an empty string if it was a new file.
1094 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1097 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1098 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1099 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1100 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1102 if ( $status->value
== 'new' ) {
1103 $status->value
= '';
1105 $status->value
= $archiveName;
1113 /** getLinksTo inherited */
1114 /** getExifData inherited */
1115 /** isLocal inherited */
1116 /** wasDeleted inherited */
1119 * Move file to the new title
1121 * Move current, old version and all thumbnails
1122 * to the new filename. Old file is deleted.
1124 * Cache purging is done; checks for validity
1125 * and logging are caller's responsibility
1127 * @param $target Title New file name
1128 * @return FileRepoStatus object.
1130 function move( $target ) {
1131 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1134 $batch = new LocalFileMoveBatch( $this, $target );
1135 $batch->addCurrent();
1138 $status = $batch->execute();
1139 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1141 $this->purgeEverything();
1144 if ( $status->isOk() ) {
1145 // Now switch the object
1146 $this->title
= $target;
1147 // Force regeneration of the name and hashpath
1148 unset( $this->name
);
1149 unset( $this->hashPath
);
1150 // Purge the new image
1151 $this->purgeEverything();
1158 * Delete all versions of the file.
1160 * Moves the files into an archive directory (or deletes them)
1161 * and removes the database rows.
1163 * Cache purging is done; logging is caller's responsibility.
1167 * @return FileRepoStatus object.
1169 function delete( $reason, $suppress = false ) {
1172 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1173 $batch->addCurrent();
1175 # Get old version relative paths
1176 $dbw = $this->repo
->getMasterDB();
1177 $result = $dbw->select( 'oldimage',
1178 array( 'oi_archive_name' ),
1179 array( 'oi_name' => $this->getName() ) );
1180 foreach ( $result as $row ) {
1181 $batch->addOld( $row->oi_archive_name
);
1183 $status = $batch->execute();
1185 if ( $status->ok
) {
1186 // Update site_stats
1187 $site_stats = $dbw->tableName( 'site_stats' );
1188 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1189 $this->purgeEverything();
1198 * Delete an old version of the file.
1200 * Moves the file into an archive directory (or deletes it)
1201 * and removes the database row.
1203 * Cache purging is done; logging is caller's responsibility.
1205 * @param $archiveName String
1206 * @param $reason String
1207 * @param $suppress Boolean
1208 * @throws MWException or FSException on database or file store failure
1209 * @return FileRepoStatus object.
1211 function deleteOld( $archiveName, $reason, $suppress = false ) {
1214 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1215 $batch->addOld( $archiveName );
1216 $status = $batch->execute();
1220 if ( $status->ok
) {
1221 $this->purgeDescription();
1222 $this->purgeHistory();
1229 * Restore all or specified deleted revisions to the given file.
1230 * Permissions and logging are left to the caller.
1232 * May throw database exceptions on error.
1234 * @param $versions set of record ids of deleted items to restore,
1235 * or empty to restore all revisions.
1236 * @param $unsuppress Boolean
1237 * @return FileRepoStatus
1239 function restore( $versions = array(), $unsuppress = false ) {
1240 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1245 $batch->addIds( $versions );
1248 $status = $batch->execute();
1250 if ( !$status->isGood() ) {
1254 $cleanupStatus = $batch->cleanup();
1255 $cleanupStatus->successCount
= 0;
1256 $cleanupStatus->failCount
= 0;
1257 $status->merge( $cleanupStatus );
1262 /** isMultipage inherited */
1263 /** pageCount inherited */
1264 /** scaleHeight inherited */
1265 /** getImageSize inherited */
1268 * Get the URL of the file description page.
1270 function getDescriptionUrl() {
1271 return $this->title
->getLocalUrl();
1275 * Get the HTML text of the description page
1276 * This is not used by ImagePage for local files, since (among other things)
1277 * it skips the parser cache.
1279 function getDescriptionText() {
1281 $revision = Revision
::newFromTitle( $this->title
);
1282 if ( !$revision ) return false;
1283 $text = $revision->getText();
1284 if ( !$text ) return false;
1285 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1286 return $pout->getText();
1289 function getDescription() {
1291 return $this->description
;
1294 function getTimestamp() {
1296 return $this->timestamp
;
1299 function getSha1() {
1301 // Initialise now if necessary
1302 if ( $this->sha1
== '' && $this->fileExists
) {
1303 $this->sha1
= File
::sha1Base36( $this->getPath() );
1304 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1305 $dbw = $this->repo
->getMasterDB();
1306 $dbw->update( 'image',
1307 array( 'img_sha1' => $this->sha1
),
1308 array( 'img_name' => $this->getName() ),
1310 $this->saveToCache();
1318 * Start a transaction and lock the image for update
1319 * Increments a reference counter if the lock is already held
1320 * @return boolean True if the image exists, false otherwise
1323 $dbw = $this->repo
->getMasterDB();
1325 if ( !$this->locked
) {
1330 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1334 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1335 * the transaction and thereby releases the image lock.
1338 if ( $this->locked
) {
1340 if ( !$this->locked
) {
1341 $dbw = $this->repo
->getMasterDB();
1348 * Roll back the DB transaction and mark the image unlocked
1350 function unlockAndRollback() {
1351 $this->locked
= false;
1352 $dbw = $this->repo
->getMasterDB();
1355 } // LocalFile class
1357 # ------------------------------------------------------------------------------
1360 * Helper class for file deletion
1363 class LocalFileDeleteBatch
{
1370 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1373 function __construct( File
$file, $reason = '', $suppress = false ) {
1374 $this->file
= $file;
1375 $this->reason
= $reason;
1376 $this->suppress
= $suppress;
1377 $this->status
= $file->repo
->newGood();
1380 function addCurrent() {
1381 $this->srcRels
['.'] = $this->file
->getRel();
1384 function addOld( $oldName ) {
1385 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1386 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1389 function getOldRels() {
1390 if ( !isset( $this->srcRels
['.'] ) ) {
1391 $oldRels =& $this->srcRels
;
1392 $deleteCurrent = false;
1394 $oldRels = $this->srcRels
;
1395 unset( $oldRels['.'] );
1396 $deleteCurrent = true;
1399 return array( $oldRels, $deleteCurrent );
1402 protected function getHashes() {
1404 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1406 if ( $deleteCurrent ) {
1407 $hashes['.'] = $this->file
->getSha1();
1410 if ( count( $oldRels ) ) {
1411 $dbw = $this->file
->repo
->getMasterDB();
1412 $res = $dbw->select(
1414 array( 'oi_archive_name', 'oi_sha1' ),
1415 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1419 foreach ( $res as $row ) {
1420 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1421 // Get the hash from the file
1422 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1423 $props = $this->file
->repo
->getFileProps( $oldUrl );
1425 if ( $props['fileExists'] ) {
1426 // Upgrade the oldimage row
1427 $dbw->update( 'oldimage',
1428 array( 'oi_sha1' => $props['sha1'] ),
1429 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1431 $hashes[$row->oi_archive_name
] = $props['sha1'];
1433 $hashes[$row->oi_archive_name
] = false;
1436 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1441 $missing = array_diff_key( $this->srcRels
, $hashes );
1443 foreach ( $missing as $name => $rel ) {
1444 $this->status
->error( 'filedelete-old-unregistered', $name );
1447 foreach ( $hashes as $name => $hash ) {
1449 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1450 unset( $hashes[$name] );
1457 function doDBInserts() {
1460 $dbw = $this->file
->repo
->getMasterDB();
1461 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1462 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1463 $encReason = $dbw->addQuotes( $this->reason
);
1464 $encGroup = $dbw->addQuotes( 'deleted' );
1465 $ext = $this->file
->getExtension();
1466 $dotExt = $ext === '' ?
'' : ".$ext";
1467 $encExt = $dbw->addQuotes( $dotExt );
1468 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1470 // Bitfields to further suppress the content
1471 if ( $this->suppress
) {
1473 // This should be 15...
1474 $bitfield |
= Revision
::DELETED_TEXT
;
1475 $bitfield |
= Revision
::DELETED_COMMENT
;
1476 $bitfield |
= Revision
::DELETED_USER
;
1477 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1479 $bitfield = 'oi_deleted';
1482 if ( $deleteCurrent ) {
1483 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1484 $where = array( 'img_name' => $this->file
->getName() );
1485 $dbw->insertSelect( 'filearchive', 'image',
1487 'fa_storage_group' => $encGroup,
1488 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1489 'fa_deleted_user' => $encUserId,
1490 'fa_deleted_timestamp' => $encTimestamp,
1491 'fa_deleted_reason' => $encReason,
1492 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1494 'fa_name' => 'img_name',
1495 'fa_archive_name' => 'NULL',
1496 'fa_size' => 'img_size',
1497 'fa_width' => 'img_width',
1498 'fa_height' => 'img_height',
1499 'fa_metadata' => 'img_metadata',
1500 'fa_bits' => 'img_bits',
1501 'fa_media_type' => 'img_media_type',
1502 'fa_major_mime' => 'img_major_mime',
1503 'fa_minor_mime' => 'img_minor_mime',
1504 'fa_description' => 'img_description',
1505 'fa_user' => 'img_user',
1506 'fa_user_text' => 'img_user_text',
1507 'fa_timestamp' => 'img_timestamp'
1508 ), $where, __METHOD__
);
1511 if ( count( $oldRels ) ) {
1512 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1514 'oi_name' => $this->file
->getName(),
1515 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1516 $dbw->insertSelect( 'filearchive', 'oldimage',
1518 'fa_storage_group' => $encGroup,
1519 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1520 'fa_deleted_user' => $encUserId,
1521 'fa_deleted_timestamp' => $encTimestamp,
1522 'fa_deleted_reason' => $encReason,
1523 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1525 'fa_name' => 'oi_name',
1526 'fa_archive_name' => 'oi_archive_name',
1527 'fa_size' => 'oi_size',
1528 'fa_width' => 'oi_width',
1529 'fa_height' => 'oi_height',
1530 'fa_metadata' => 'oi_metadata',
1531 'fa_bits' => 'oi_bits',
1532 'fa_media_type' => 'oi_media_type',
1533 'fa_major_mime' => 'oi_major_mime',
1534 'fa_minor_mime' => 'oi_minor_mime',
1535 'fa_description' => 'oi_description',
1536 'fa_user' => 'oi_user',
1537 'fa_user_text' => 'oi_user_text',
1538 'fa_timestamp' => 'oi_timestamp',
1539 'fa_deleted' => $bitfield
1540 ), $where, __METHOD__
);
1544 function doDBDeletes() {
1545 $dbw = $this->file
->repo
->getMasterDB();
1546 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1548 if ( count( $oldRels ) ) {
1549 $dbw->delete( 'oldimage',
1551 'oi_name' => $this->file
->getName(),
1552 'oi_archive_name' => array_keys( $oldRels )
1556 if ( $deleteCurrent ) {
1557 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1562 * Run the transaction
1564 function execute() {
1566 wfProfileIn( __METHOD__
);
1568 $this->file
->lock();
1569 // Leave private files alone
1570 $privateFiles = array();
1571 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1572 $dbw = $this->file
->repo
->getMasterDB();
1574 if ( !empty( $oldRels ) ) {
1575 $res = $dbw->select( 'oldimage',
1576 array( 'oi_archive_name' ),
1577 array( 'oi_name' => $this->file
->getName(),
1578 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1579 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1582 foreach ( $res as $row ) {
1583 $privateFiles[$row->oi_archive_name
] = 1;
1586 // Prepare deletion batch
1587 $hashes = $this->getHashes();
1588 $this->deletionBatch
= array();
1589 $ext = $this->file
->getExtension();
1590 $dotExt = $ext === '' ?
'' : ".$ext";
1592 foreach ( $this->srcRels
as $name => $srcRel ) {
1593 // Skip files that have no hash (missing source).
1594 // Keep private files where they are.
1595 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1596 $hash = $hashes[$name];
1597 $key = $hash . $dotExt;
1598 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1599 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1603 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1604 // We acquire this lock by running the inserts now, before the file operations.
1606 // This potentially has poor lock contention characteristics -- an alternative
1607 // scheme would be to insert stub filearchive entries with no fa_name and commit
1608 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1609 $this->doDBInserts();
1611 // Removes non-existent file from the batch, so we don't get errors.
1612 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1614 // Execute the file deletion batch
1615 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1617 if ( !$status->isGood() ) {
1618 $this->status
->merge( $status );
1621 if ( !$this->status
->ok
) {
1622 // Critical file deletion error
1623 // Roll back inserts, release lock and abort
1624 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1625 $this->file
->unlockAndRollback();
1626 wfProfileOut( __METHOD__
);
1627 return $this->status
;
1631 if ( $wgUseSquid ) {
1634 foreach ( $this->srcRels
as $srcRel ) {
1635 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1636 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1638 SquidUpdate
::purge( $urls );
1641 // Delete image/oldimage rows
1642 $this->doDBDeletes();
1644 // Commit and return
1645 $this->file
->unlock();
1646 wfProfileOut( __METHOD__
);
1648 return $this->status
;
1652 * Removes non-existent files from a deletion batch.
1654 function removeNonexistentFiles( $batch ) {
1655 $files = $newBatch = array();
1657 foreach ( $batch as $batchItem ) {
1658 list( $src, $dest ) = $batchItem;
1659 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1662 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1664 foreach ( $batch as $batchItem ) {
1665 if ( $result[$batchItem[0]] ) {
1666 $newBatch[] = $batchItem;
1674 # ------------------------------------------------------------------------------
1677 * Helper class for file undeletion
1680 class LocalFileRestoreBatch
{
1686 var $cleanupBatch, $ids, $all, $unsuppress = false;
1688 function __construct( File
$file, $unsuppress = false ) {
1689 $this->file
= $file;
1690 $this->cleanupBatch
= $this->ids
= array();
1691 $this->ids
= array();
1692 $this->unsuppress
= $unsuppress;
1698 function addId( $fa_id ) {
1699 $this->ids
[] = $fa_id;
1703 * Add a whole lot of files by ID
1705 function addIds( $ids ) {
1706 $this->ids
= array_merge( $this->ids
, $ids );
1710 * Add all revisions of the file
1717 * Run the transaction, except the cleanup batch.
1718 * The cleanup batch should be run in a separate transaction, because it locks different
1719 * rows and there's no need to keep the image row locked while it's acquiring those locks
1720 * The caller may have its own transaction open.
1721 * So we save the batch and let the caller call cleanup()
1723 function execute() {
1726 if ( !$this->all
&& !$this->ids
) {
1728 return $this->file
->repo
->newGood();
1731 $exists = $this->file
->lock();
1732 $dbw = $this->file
->repo
->getMasterDB();
1733 $status = $this->file
->repo
->newGood();
1735 // Fetch all or selected archived revisions for the file,
1736 // sorted from the most recent to the oldest.
1737 $conditions = array( 'fa_name' => $this->file
->getName() );
1739 if ( !$this->all
) {
1740 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1743 $result = $dbw->select( 'filearchive', '*',
1746 array( 'ORDER BY' => 'fa_timestamp DESC' )
1749 $idsPresent = array();
1750 $storeBatch = array();
1751 $insertBatch = array();
1752 $insertCurrent = false;
1753 $deleteIds = array();
1755 $archiveNames = array();
1757 foreach ( $result as $row ) {
1758 $idsPresent[] = $row->fa_id
;
1760 if ( $row->fa_name
!= $this->file
->getName() ) {
1761 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1762 $status->failCount++
;
1766 if ( $row->fa_storage_key
== '' ) {
1767 // Revision was missing pre-deletion
1768 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1769 $status->failCount++
;
1773 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1774 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1776 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1779 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1780 $sha1 = substr( $sha1, 1 );
1783 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1784 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1785 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1786 ||
is_null( $row->fa_metadata
) ) {
1787 // Refresh our metadata
1788 // Required for a new current revision; nice for older ones too. :)
1789 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1792 'minor_mime' => $row->fa_minor_mime
,
1793 'major_mime' => $row->fa_major_mime
,
1794 'media_type' => $row->fa_media_type
,
1795 'metadata' => $row->fa_metadata
1799 if ( $first && !$exists ) {
1800 // This revision will be published as the new current version
1801 $destRel = $this->file
->getRel();
1802 $insertCurrent = array(
1803 'img_name' => $row->fa_name
,
1804 'img_size' => $row->fa_size
,
1805 'img_width' => $row->fa_width
,
1806 'img_height' => $row->fa_height
,
1807 'img_metadata' => $props['metadata'],
1808 'img_bits' => $row->fa_bits
,
1809 'img_media_type' => $props['media_type'],
1810 'img_major_mime' => $props['major_mime'],
1811 'img_minor_mime' => $props['minor_mime'],
1812 'img_description' => $row->fa_description
,
1813 'img_user' => $row->fa_user
,
1814 'img_user_text' => $row->fa_user_text
,
1815 'img_timestamp' => $row->fa_timestamp
,
1819 // The live (current) version cannot be hidden!
1820 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1821 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1822 $this->cleanupBatch
[] = $row->fa_storage_key
;
1825 $archiveName = $row->fa_archive_name
;
1827 if ( $archiveName == '' ) {
1828 // This was originally a current version; we
1829 // have to devise a new archive name for it.
1830 // Format is <timestamp of archiving>!<name>
1831 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1834 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1836 } while ( isset( $archiveNames[$archiveName] ) );
1839 $archiveNames[$archiveName] = true;
1840 $destRel = $this->file
->getArchiveRel( $archiveName );
1841 $insertBatch[] = array(
1842 'oi_name' => $row->fa_name
,
1843 'oi_archive_name' => $archiveName,
1844 'oi_size' => $row->fa_size
,
1845 'oi_width' => $row->fa_width
,
1846 'oi_height' => $row->fa_height
,
1847 'oi_bits' => $row->fa_bits
,
1848 'oi_description' => $row->fa_description
,
1849 'oi_user' => $row->fa_user
,
1850 'oi_user_text' => $row->fa_user_text
,
1851 'oi_timestamp' => $row->fa_timestamp
,
1852 'oi_metadata' => $props['metadata'],
1853 'oi_media_type' => $props['media_type'],
1854 'oi_major_mime' => $props['major_mime'],
1855 'oi_minor_mime' => $props['minor_mime'],
1856 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1857 'oi_sha1' => $sha1 );
1860 $deleteIds[] = $row->fa_id
;
1862 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1863 // private files can stay where they are
1864 $status->successCount++
;
1866 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1867 $this->cleanupBatch
[] = $row->fa_storage_key
;
1875 // Add a warning to the status object for missing IDs
1876 $missingIds = array_diff( $this->ids
, $idsPresent );
1878 foreach ( $missingIds as $id ) {
1879 $status->error( 'undelete-missing-filearchive', $id );
1882 // Remove missing files from batch, so we don't get errors when undeleting them
1883 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1885 // Run the store batch
1886 // Use the OVERWRITE_SAME flag to smooth over a common error
1887 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1888 $status->merge( $storeStatus );
1890 if ( !$status->isGood() ) {
1891 // Even if some files could be copied, fail entirely as that is the
1892 // easiest thing to do without data loss
1893 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1894 $status->ok
= false;
1895 $this->file
->unlock();
1900 // Run the DB updates
1901 // Because we have locked the image row, key conflicts should be rare.
1902 // If they do occur, we can roll back the transaction at this time with
1903 // no data loss, but leaving unregistered files scattered throughout the
1905 // This is not ideal, which is why it's important to lock the image row.
1906 if ( $insertCurrent ) {
1907 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1910 if ( $insertBatch ) {
1911 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1915 $dbw->delete( 'filearchive',
1916 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1920 // If store batch is empty (all files are missing), deletion is to be considered successful
1921 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1923 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1925 // Update site_stats
1926 $site_stats = $dbw->tableName( 'site_stats' );
1927 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1929 $this->file
->purgeEverything();
1931 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1932 $this->file
->purgeDescription();
1933 $this->file
->purgeHistory();
1937 $this->file
->unlock();
1943 * Removes non-existent files from a store batch.
1945 function removeNonexistentFiles( $triplets ) {
1946 $files = $filteredTriplets = array();
1947 foreach ( $triplets as $file )
1948 $files[$file[0]] = $file[0];
1950 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1952 foreach ( $triplets as $file ) {
1953 if ( $result[$file[0]] ) {
1954 $filteredTriplets[] = $file;
1958 return $filteredTriplets;
1962 * Removes non-existent files from a cleanup batch.
1964 function removeNonexistentFromCleanup( $batch ) {
1965 $files = $newBatch = array();
1966 $repo = $this->file
->repo
;
1968 foreach ( $batch as $file ) {
1969 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1970 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1973 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1975 foreach ( $batch as $file ) {
1976 if ( $result[$file] ) {
1977 $newBatch[] = $file;
1985 * Delete unused files in the deleted zone.
1986 * This should be called from outside the transaction in which execute() was called.
1988 function cleanup() {
1989 if ( !$this->cleanupBatch
) {
1990 return $this->file
->repo
->newGood();
1993 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1995 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2001 * Cleanup a failed batch. The batch was only partially successful, so
2002 * rollback by removing all items that were succesfully copied.
2004 * @param Status $storeStatus
2005 * @param array $storeBatch
2007 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2008 $cleanupBatch = array();
2010 foreach ( $storeStatus->success
as $i => $success ) {
2011 // Check if this item of the batch was successfully copied
2013 // Item was successfully copied and needs to be removed again
2014 // Extract ($dstZone, $dstRel) from the batch
2015 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2018 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2022 # ------------------------------------------------------------------------------
2025 * Helper class for file movement
2028 class LocalFileMoveBatch
{
2029 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
2031 function __construct( File
$file, Title
$target ) {
2032 $this->file
= $file;
2033 $this->target
= $target;
2034 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2035 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2036 $this->oldName
= $this->file
->getName();
2037 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2038 $this->oldRel
= $this->oldHash
. $this->oldName
;
2039 $this->newRel
= $this->newHash
. $this->newName
;
2040 $this->db
= $file->repo
->getMasterDb();
2044 * Add the current image to the batch
2046 function addCurrent() {
2047 $this->cur
= array( $this->oldRel
, $this->newRel
);
2051 * Add the old versions of the image to the batch
2053 function addOlds() {
2054 $archiveBase = 'archive';
2055 $this->olds
= array();
2056 $this->oldCount
= 0;
2058 $result = $this->db
->select( 'oldimage',
2059 array( 'oi_archive_name', 'oi_deleted' ),
2060 array( 'oi_name' => $this->oldName
),
2064 foreach ( $result as $row ) {
2065 $oldName = $row->oi_archive_name
;
2066 $bits = explode( '!', $oldName, 2 );
2068 if ( count( $bits ) != 2 ) {
2069 wfDebug( "Old file name missing !: '$oldName' \n" );
2073 list( $timestamp, $filename ) = $bits;
2075 if ( $this->oldName
!= $filename ) {
2076 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2082 // Do we want to add those to oldCount?
2083 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2087 $this->olds
[] = array(
2088 "{$archiveBase}/{$this->oldHash}{$oldName}",
2089 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2097 function execute() {
2098 $repo = $this->file
->repo
;
2099 $status = $repo->newGood();
2100 $triplets = $this->getMoveTriplets();
2102 $triplets = $this->removeNonexistentFiles( $triplets );
2104 // Copy the files into their new location
2105 $statusMove = $repo->storeBatch( $triplets );
2106 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2107 if ( !$statusMove->isGood() ) {
2108 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2109 $this->cleanupTarget( $triplets );
2110 $statusMove->ok
= false;
2115 $statusDb = $this->doDBUpdates();
2116 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2117 if ( !$statusDb->isGood() ) {
2118 $this->db
->rollback();
2119 // Something went wrong with the DB updates, so remove the target files
2120 $this->cleanupTarget( $triplets );
2121 $statusDb->ok
= false;
2124 $this->db
->commit();
2126 // Everything went ok, remove the source files
2127 $this->cleanupSource( $triplets );
2129 $status->merge( $statusDb );
2130 $status->merge( $statusMove );
2136 * Do the database updates and return a new FileRepoStatus indicating how
2137 * many rows where updated.
2139 * @return FileRepoStatus
2141 function doDBUpdates() {
2142 $repo = $this->file
->repo
;
2143 $status = $repo->newGood();
2146 // Update current image
2149 array( 'img_name' => $this->newName
),
2150 array( 'img_name' => $this->oldName
),
2154 if ( $dbw->affectedRows() ) {
2155 $status->successCount++
;
2157 $status->failCount++
;
2158 $status->fatal( 'imageinvalidfilename' );
2162 // Update old images
2166 'oi_name' => $this->newName
,
2167 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2169 array( 'oi_name' => $this->oldName
),
2173 $affected = $dbw->affectedRows();
2174 $total = $this->oldCount
;
2175 $status->successCount +
= $affected;
2176 $status->failCount +
= $total - $affected;
2177 if ( $status->failCount
) {
2178 $status->error( 'imageinvalidfilename' );
2185 * Generate triplets for FSRepo::storeBatch().
2187 function getMoveTriplets() {
2188 $moves = array_merge( array( $this->cur
), $this->olds
);
2189 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2191 foreach ( $moves as $move ) {
2192 // $move: (oldRelativePath, newRelativePath)
2193 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2194 $triplets[] = array( $srcUrl, 'public', $move[1] );
2195 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2202 * Removes non-existent files from move batch.
2204 function removeNonexistentFiles( $triplets ) {
2207 foreach ( $triplets as $file ) {
2208 $files[$file[0]] = $file[0];
2211 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2212 $filteredTriplets = array();
2214 foreach ( $triplets as $file ) {
2215 if ( $result[$file[0]] ) {
2216 $filteredTriplets[] = $file;
2218 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2222 return $filteredTriplets;
2226 * Cleanup a partially moved array of triplets by deleting the target
2227 * files. Called if something went wrong half way.
2229 function cleanupTarget( $triplets ) {
2230 // Create dest pairs from the triplets
2232 foreach ( $triplets as $triplet ) {
2233 $pairs[] = array( $triplet[1], $triplet[2] );
2236 $this->file
->repo
->cleanupBatch( $pairs );
2240 * Cleanup a fully moved array of triplets by deleting the source files.
2241 * Called at the end of the move process if everything else went ok.
2243 function cleanupSource( $triplets ) {
2244 // Create source file names from the triplets
2246 foreach ( $triplets as $triplet ) {
2247 $files[] = $triplet[0];
2250 $this->file
->repo
->cleanupBatch( $files );