6 * Bump this number when serialized cache records may be incompatible.
8 define( 'MW_FILE_VERSION', 8 );
11 * Class to represent a local file in the wiki's own database
13 * Provides methods to retrieve paths (physical, logical, URL),
14 * to generate image thumbnails or for uploading.
16 * Note that only the repo object knows what its file class is called. You should
17 * never name a file class explictly outside of the repo class. Instead use the
18 * repo's factory functions to generate file objects, for example:
20 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
22 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
27 class LocalFile
extends File
{
31 var $fileExists, # does the file file exist on disk? (loadFromXxx)
32 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
33 $historyRes, # result of the query for the file's history (nextHistoryLine)
36 $bits, # --- returned by getimagesize (loadFromXxx)
38 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
39 $mime, # MIME type, determined by MimeMagic::guessMimeType
40 $major_mime, # Major mime type
41 $minor_mime, # Minor mime type
42 $size, # Size in bytes (loadFromXxx)
43 $metadata, # Handler-specific metadata
44 $timestamp, # Upload timestamp
45 $sha1, # SHA-1 base 36 content hash
46 $user, $user_text, # User, who uploaded the file
47 $description, # Description of current revision of the file
48 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
49 $upgraded, # Whether the row was upgraded on load
50 $locked, # True if the image row is locked
51 $missing, # True if file is not present in file system. Not to be cached in memcached
52 $deleted; # Bitfield akin to rev_deleted
57 * Create a LocalFile from a title
58 * Do not call this except from inside a repo class.
60 * Note: $unused param is only here to avoid an E_STRICT
62 static function newFromTitle( $title, $repo, $unused = null ) {
63 return new self( $title, $repo );
67 * Create a LocalFile from a title
68 * Do not call this except from inside a repo class.
70 static function newFromRow( $row, $repo ) {
71 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
72 $file = new self( $title, $repo );
73 $file->loadFromRow( $row );
79 * Create a LocalFile from a SHA-1 key
80 * Do not call this except from inside a repo class.
82 static function newFromKey( $sha1, $repo, $timestamp = false ) {
83 $conds = array( 'img_sha1' => $sha1 );
86 $conds['img_timestamp'] = $timestamp;
89 $dbr = $repo->getSlaveDB();
90 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
93 return self
::newFromRow( $row, $repo );
100 * Fields in the image table
102 static function selectFields() {
123 * Do not call this except from inside a repo class.
125 function __construct( $title, $repo ) {
126 if ( !is_object( $title ) ) {
127 throw new MWException( __CLASS__
. ' constructor given bogus title.' );
130 parent
::__construct( $title, $repo );
132 $this->metadata
= '';
133 $this->historyLine
= 0;
134 $this->historyRes
= null;
135 $this->dataLoaded
= false;
139 * Get the memcached key for the main data for this file, or false if
140 * there is no access to the shared cache.
142 function getCacheKey() {
143 $hashedName = md5( $this->getName() );
145 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
149 * Try to load file metadata from memcached. Returns true on success.
151 function loadFromCache() {
154 wfProfileIn( __METHOD__
);
155 $this->dataLoaded
= false;
156 $key = $this->getCacheKey();
159 wfProfileOut( __METHOD__
);
163 $cachedValues = $wgMemc->get( $key );
165 // Check if the key existed and belongs to this version of MediaWiki
166 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
167 wfDebug( "Pulling file metadata from cache key $key\n" );
168 $this->fileExists
= $cachedValues['fileExists'];
169 if ( $this->fileExists
) {
170 $this->setProps( $cachedValues );
172 $this->dataLoaded
= true;
175 if ( $this->dataLoaded
) {
176 wfIncrStats( 'image_cache_hit' );
178 wfIncrStats( 'image_cache_miss' );
181 wfProfileOut( __METHOD__
);
182 return $this->dataLoaded
;
186 * Save the file metadata to memcached
188 function saveToCache() {
192 $key = $this->getCacheKey();
198 $fields = $this->getCacheFields( '' );
199 $cache = array( 'version' => MW_FILE_VERSION
);
200 $cache['fileExists'] = $this->fileExists
;
202 if ( $this->fileExists
) {
203 foreach ( $fields as $field ) {
204 $cache[$field] = $this->$field;
208 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
212 * Load metadata from the file itself
214 function loadFromFile() {
215 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
218 function getCacheFields( $prefix = 'img_' ) {
219 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
220 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
221 static $results = array();
223 if ( $prefix == '' ) {
227 if ( !isset( $results[$prefix] ) ) {
228 $prefixedFields = array();
229 foreach ( $fields as $field ) {
230 $prefixedFields[] = $prefix . $field;
232 $results[$prefix] = $prefixedFields;
235 return $results[$prefix];
239 * Load file metadata from the DB
241 function loadFromDB() {
242 # Polymorphic function name to distinguish foreign and local fetches
243 $fname = get_class( $this ) . '::' . __FUNCTION__
;
244 wfProfileIn( $fname );
246 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
247 $this->dataLoaded
= true;
249 $dbr = $this->repo
->getMasterDB();
251 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
252 array( 'img_name' => $this->getName() ), $fname );
255 $this->loadFromRow( $row );
257 $this->fileExists
= false;
260 wfProfileOut( $fname );
264 * Decode a row from the database (either object or array) to an array
265 * with timestamps and MIME types decoded, and the field prefix removed.
267 function decodeRow( $row, $prefix = 'img_' ) {
268 $array = (array)$row;
269 $prefixLength = strlen( $prefix );
271 // Sanity check prefix once
272 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
273 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
278 foreach ( $array as $name => $value ) {
279 $decoded[substr( $name, $prefixLength )] = $value;
282 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
284 if ( empty( $decoded['major_mime'] ) ) {
285 $decoded['mime'] = 'unknown/unknown';
287 if ( !$decoded['minor_mime'] ) {
288 $decoded['minor_mime'] = 'unknown';
290 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
293 # Trim zero padding from char/binary field
294 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
300 * Load file metadata from a DB result row
302 function loadFromRow( $row, $prefix = 'img_' ) {
303 $this->dataLoaded
= true;
304 $array = $this->decodeRow( $row, $prefix );
306 foreach ( $array as $name => $value ) {
307 $this->$name = $value;
310 $this->fileExists
= true;
311 $this->maybeUpgradeRow();
315 * Load file metadata from cache or DB, unless already loaded
318 if ( !$this->dataLoaded
) {
319 if ( !$this->loadFromCache() ) {
321 $this->saveToCache();
323 $this->dataLoaded
= true;
328 * Upgrade a row if it needs it
330 function maybeUpgradeRow() {
331 if ( wfReadOnly() ) {
335 if ( is_null( $this->media_type
) ||
336 $this->mime
== 'image/svg'
339 $this->upgraded
= true;
341 $handler = $this->getHandler();
342 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
344 $this->upgraded
= true;
349 function getUpgraded() {
350 return $this->upgraded
;
354 * Fix assorted version-related problems with the image row by reloading it from the file
356 function upgradeRow() {
357 wfProfileIn( __METHOD__
);
359 $this->loadFromFile();
361 # Don't destroy file info of missing files
362 if ( !$this->fileExists
) {
363 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
364 wfProfileOut( __METHOD__
);
368 $dbw = $this->repo
->getMasterDB();
369 list( $major, $minor ) = self
::splitMime( $this->mime
);
371 if ( wfReadOnly() ) {
372 wfProfileOut( __METHOD__
);
375 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
377 $dbw->update( 'image',
379 'img_width' => $this->width
,
380 'img_height' => $this->height
,
381 'img_bits' => $this->bits
,
382 'img_media_type' => $this->media_type
,
383 'img_major_mime' => $major,
384 'img_minor_mime' => $minor,
385 'img_metadata' => $this->metadata
,
386 'img_sha1' => $this->sha1
,
387 ), array( 'img_name' => $this->getName() ),
391 $this->saveToCache();
392 wfProfileOut( __METHOD__
);
396 * Set properties in this object to be equal to those given in the
397 * associative array $info. Only cacheable fields can be set.
399 * If 'mime' is given, it will be split into major_mime/minor_mime.
400 * If major_mime/minor_mime are given, $this->mime will also be set.
402 function setProps( $info ) {
403 $this->dataLoaded
= true;
404 $fields = $this->getCacheFields( '' );
405 $fields[] = 'fileExists';
407 foreach ( $fields as $field ) {
408 if ( isset( $info[$field] ) ) {
409 $this->$field = $info[$field];
413 // Fix up mime fields
414 if ( isset( $info['major_mime'] ) ) {
415 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
416 } elseif ( isset( $info['mime'] ) ) {
417 $this->mime
= $info['mime'];
418 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
422 /** splitMime inherited */
423 /** getName inherited */
424 /** getTitle inherited */
425 /** getURL inherited */
426 /** getViewURL inherited */
427 /** getPath inherited */
428 /** isVisible inhereted */
430 function isMissing() {
431 if ( $this->missing
=== null ) {
432 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
433 $this->missing
= !$fileExists;
435 return $this->missing
;
439 * Return the width of the image
441 * Returns false on error
443 public function getWidth( $page = 1 ) {
446 if ( $this->isMultipage() ) {
447 $dim = $this->getHandler()->getPageDimensions( $this, $page );
449 return $dim['width'];
459 * Return the height of the image
461 * Returns false on error
463 public function getHeight( $page = 1 ) {
466 if ( $this->isMultipage() ) {
467 $dim = $this->getHandler()->getPageDimensions( $this, $page );
469 return $dim['height'];
474 return $this->height
;
479 * Returns ID or name of user who uploaded the file
481 * @param $type string 'text' or 'id'
483 function getUser( $type = 'text' ) {
486 if ( $type == 'text' ) {
487 return $this->user_text
;
488 } elseif ( $type == 'id' ) {
494 * Get handler-specific metadata
496 function getMetadata() {
498 return $this->metadata
;
501 function getBitDepth() {
507 * Return the size of the image file, in bytes
509 public function getSize() {
515 * Returns the mime type of the file.
517 function getMimeType() {
523 * Return the type of the media in the file.
524 * Use the value returned by this function with the MEDIATYPE_xxx constants.
526 function getMediaType() {
528 return $this->media_type
;
531 /** canRender inherited */
532 /** mustRender inherited */
533 /** allowInlineDisplay inherited */
534 /** isSafeFile inherited */
535 /** isTrustedFile inherited */
538 * Returns true if the file file exists on disk.
539 * @return boolean Whether file file exist on disk.
541 public function exists() {
543 return $this->fileExists
;
546 /** getTransformScript inherited */
547 /** getUnscaledThumb inherited */
548 /** thumbName inherited */
549 /** createThumb inherited */
550 /** getThumbnail inherited */
551 /** transform inherited */
554 * Fix thumbnail files from 1.4 or before, with extreme prejudice
556 function migrateThumbFile( $thumbName ) {
557 $thumbDir = $this->getThumbPath();
558 $thumbPath = "$thumbDir/$thumbName";
560 if ( is_dir( $thumbPath ) ) {
561 // Directory where file should be
562 // This happened occasionally due to broken migration code in 1.5
563 // Rename to broken-*
564 for ( $i = 0; $i < 100 ; $i++
) {
565 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
566 if ( !file_exists( $broken ) ) {
567 rename( $thumbPath, $broken );
571 // Doesn't exist anymore
575 if ( is_file( $thumbDir ) ) {
576 // File where directory should be
578 // Doesn't exist anymore
583 /** getHandler inherited */
584 /** iconThumb inherited */
585 /** getLastError inherited */
588 * Get all thumbnail names previously generated for this file
590 function getThumbnails() {
594 $dir = $this->getThumbPath();
596 if ( is_dir( $dir ) ) {
597 $handle = opendir( $dir );
600 while ( false !== ( $file = readdir( $handle ) ) ) {
601 if ( $file { 0 } != '.' ) {
614 * Refresh metadata in memcached, but don't touch thumbnails or squid
616 function purgeMetadataCache() {
618 $this->saveToCache();
619 $this->purgeHistory();
623 * Purge the shared history (OldLocalFile) cache
625 function purgeHistory() {
628 $hashedName = md5( $this->getName() );
629 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
632 $wgMemc->delete( $oldKey );
637 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
639 function purgeCache() {
640 // Refresh metadata cache
641 $this->purgeMetadataCache();
644 $this->purgeThumbnails();
646 // Purge squid cache for this file
647 SquidUpdate
::purge( array( $this->getURL() ) );
651 * Delete cached transformed files
653 function purgeThumbnails() {
657 $files = $this->getThumbnails();
658 $dir = $this->getThumbPath();
661 foreach ( $files as $file ) {
662 # Check that the base file name is part of the thumb name
663 # This is a basic sanity check to avoid erasing unrelated directories
664 if ( strpos( $file, $this->getName() ) !== false ) {
665 $url = $this->getThumbUrl( $file );
667 @unlink
( "$dir/$file" );
673 SquidUpdate
::purge( $urls );
677 /** purgeDescription inherited */
678 /** purgeEverything inherited */
680 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
681 $dbr = $this->repo
->getSlaveDB();
682 $tables = array( 'oldimage' );
683 $fields = OldLocalFile
::selectFields();
684 $conds = $opts = $join_conds = array();
685 $eq = $inc ?
'=' : '';
686 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
689 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
693 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
697 $opts['LIMIT'] = $limit;
700 // Search backwards for time > x queries
701 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
702 $opts['ORDER BY'] = "oi_timestamp $order";
703 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
705 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
706 &$conds, &$opts, &$join_conds ) );
708 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
711 while ( $row = $dbr->fetchObject( $res ) ) {
712 if ( $this->repo
->oldFileFromRowFactory
) {
713 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
715 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
719 if ( $order == 'ASC' ) {
720 $r = array_reverse( $r ); // make sure it ends up descending
727 * Return the history of this file, line by line.
728 * starts with current version, then old versions.
729 * uses $this->historyLine to check which line to return:
730 * 0 return line for current version
731 * 1 query for old versions, return first one
732 * 2, ... return next old version from above query
734 public function nextHistoryLine() {
735 # Polymorphic function name to distinguish foreign and local fetches
736 $fname = get_class( $this ) . '::' . __FUNCTION__
;
738 $dbr = $this->repo
->getSlaveDB();
740 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
741 $this->historyRes
= $dbr->select( 'image',
744 "'' AS oi_archive_name",
748 array( 'img_name' => $this->title
->getDBkey() ),
752 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
753 $this->historyRes
= null;
756 } elseif ( $this->historyLine
== 1 ) {
757 $this->historyRes
= $dbr->select( 'oldimage', '*',
758 array( 'oi_name' => $this->title
->getDBkey() ),
760 array( 'ORDER BY' => 'oi_timestamp DESC' )
763 $this->historyLine ++
;
765 return $dbr->fetchObject( $this->historyRes
);
769 * Reset the history pointer to the first element of the history
771 public function resetHistory() {
772 $this->historyLine
= 0;
774 if ( !is_null( $this->historyRes
) ) {
775 $this->historyRes
= null;
779 /** getFullPath inherited */
780 /** getHashPath inherited */
781 /** getRel inherited */
782 /** getUrlRel inherited */
783 /** getArchiveRel inherited */
784 /** getThumbRel inherited */
785 /** getArchivePath inherited */
786 /** getThumbPath inherited */
787 /** getArchiveUrl inherited */
788 /** getThumbUrl inherited */
789 /** getArchiveVirtualUrl inherited */
790 /** getThumbVirtualUrl inherited */
791 /** isHashed inherited */
794 * Upload a file and record it in the DB
795 * @param $srcPath String: source path or virtual URL
796 * @param $comment String: upload description
797 * @param $pageText String: text to use for the new description page,
798 * if a new description page is created
799 * @param $flags Integer: flags for publish()
800 * @param $props Array: File properties, if known. This can be used to reduce the
801 * upload time when uploading virtual URLs for which the file info
803 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
804 * @param $user Mixed: User object or null to use $wgUser
806 * @return FileRepoStatus object. On success, the value member contains the
807 * archive name, or an empty string if it was a new file.
809 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
811 $status = $this->publish( $srcPath, $flags );
814 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
815 $status->fatal( 'filenotfound', $srcPath );
825 * Record a file upload in the upload log and the image table
826 * @deprecated use upload()
828 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
829 $watch = false, $timestamp = false )
831 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
833 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
839 $wgUser->addWatch( $this->getTitle() );
846 * Record a file upload in the upload log and the image table
848 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
850 if ( is_null( $user ) ) {
855 $dbw = $this->repo
->getMasterDB();
859 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
862 $props['description'] = $comment;
863 $props['user'] = $user->getId();
864 $props['user_text'] = $user->getName();
865 $props['timestamp'] = wfTimestamp( TS_MW
);
866 $this->setProps( $props );
869 $this->purgeThumbnails();
871 # The file is already on its final location, remove it from the squid cache
872 SquidUpdate
::purge( array( $this->getURL() ) );
874 # Fail now if the file isn't there
875 if ( !$this->fileExists
) {
876 wfDebug( __METHOD__
. ": File " . $this->getPath() . " went missing!\n" );
882 if ( $timestamp === false ) {
883 $timestamp = $dbw->timestamp();
886 # Test to see if the row exists using INSERT IGNORE
887 # This avoids race conditions by locking the row until the commit, and also
888 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
889 $dbw->insert( 'image',
891 'img_name' => $this->getName(),
892 'img_size' => $this->size
,
893 'img_width' => intval( $this->width
),
894 'img_height' => intval( $this->height
),
895 'img_bits' => $this->bits
,
896 'img_media_type' => $this->media_type
,
897 'img_major_mime' => $this->major_mime
,
898 'img_minor_mime' => $this->minor_mime
,
899 'img_timestamp' => $timestamp,
900 'img_description' => $comment,
901 'img_user' => $user->getId(),
902 'img_user_text' => $user->getName(),
903 'img_metadata' => $this->metadata
,
904 'img_sha1' => $this->sha1
910 if ( $dbw->affectedRows() == 0 ) {
913 # Collision, this is an update of a file
914 # Insert previous contents into oldimage
915 $dbw->insertSelect( 'oldimage', 'image',
917 'oi_name' => 'img_name',
918 'oi_archive_name' => $dbw->addQuotes( $oldver ),
919 'oi_size' => 'img_size',
920 'oi_width' => 'img_width',
921 'oi_height' => 'img_height',
922 'oi_bits' => 'img_bits',
923 'oi_timestamp' => 'img_timestamp',
924 'oi_description' => 'img_description',
925 'oi_user' => 'img_user',
926 'oi_user_text' => 'img_user_text',
927 'oi_metadata' => 'img_metadata',
928 'oi_media_type' => 'img_media_type',
929 'oi_major_mime' => 'img_major_mime',
930 'oi_minor_mime' => 'img_minor_mime',
931 'oi_sha1' => 'img_sha1'
932 ), array( 'img_name' => $this->getName() ), __METHOD__
935 # Update the current image row
936 $dbw->update( 'image',
938 'img_size' => $this->size
,
939 'img_width' => intval( $this->width
),
940 'img_height' => intval( $this->height
),
941 'img_bits' => $this->bits
,
942 'img_media_type' => $this->media_type
,
943 'img_major_mime' => $this->major_mime
,
944 'img_minor_mime' => $this->minor_mime
,
945 'img_timestamp' => $timestamp,
946 'img_description' => $comment,
947 'img_user' => $user->getId(),
948 'img_user_text' => $user->getName(),
949 'img_metadata' => $this->metadata
,
950 'img_sha1' => $this->sha1
951 ), array( /* WHERE */
952 'img_name' => $this->getName()
957 # Update the image count
958 $site_stats = $dbw->tableName( 'site_stats' );
959 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
962 $descTitle = $this->getTitle();
963 $article = new ImagePage( $descTitle );
964 $article->setFile( $this );
967 $log = new LogPage( 'upload' );
968 $action = $reupload ?
'overwrite' : 'upload';
969 $log->addEntry( $action, $descTitle, $comment, array(), $user );
971 if ( $descTitle->exists() ) {
972 # Create a null revision
973 $latest = $descTitle->getLatestRevID();
974 $nullRevision = Revision
::newNullRevision(
976 $descTitle->getArticleId(),
977 $log->getRcComment(),
980 $nullRevision->insertOn( $dbw );
982 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
983 $article->updateRevisionOn( $dbw, $nullRevision );
985 # Invalidate the cache for the description page
986 $descTitle->invalidateCache();
987 $descTitle->purgeSquid();
989 # New file; create the description page.
990 # There's already a log entry, so don't make a second RC entry
991 # Squid and file cache for the description page are purged by doEdit.
992 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
995 # Commit the transaction now, in case something goes wrong later
996 # The most important thing is that files don't get lost, especially archives
999 # Save to cache and purge the squid
1000 # We shall not saveToCache before the commit since otherwise
1001 # in case of a rollback there is an usable file from memcached
1002 # which in fact doesn't really exist (bug 24978)
1003 $this->saveToCache();
1005 # Hooks, hooks, the magic of hooks...
1006 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1008 # Invalidate cache for all pages using this file
1009 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1010 $update->doUpdate();
1012 # Invalidate cache for all pages that redirects on this page
1013 $redirs = $this->getTitle()->getRedirectsHere();
1015 foreach ( $redirs as $redir ) {
1016 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1017 $update->doUpdate();
1024 * Move or copy a file to its public location. If a file exists at the
1025 * destination, move it to an archive. Returns a FileRepoStatus object with
1026 * the archive name in the "value" member on success.
1028 * The archive name should be passed through to recordUpload for database
1031 * @param $srcPath String: local filesystem path to the source image
1032 * @param $flags Integer: a bitwise combination of:
1033 * File::DELETE_SOURCE Delete the source file, i.e. move
1035 * @return FileRepoStatus object. On success, the value member contains the
1036 * archive name, or an empty string if it was a new file.
1038 function publish( $srcPath, $flags = 0 ) {
1041 $dstRel = $this->getRel();
1042 $archiveName = gmdate( 'YmdHis' ) . '!' . $this->getName();
1043 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1044 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1045 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1047 if ( $status->value
== 'new' ) {
1048 $status->value
= '';
1050 $status->value
= $archiveName;
1058 /** getLinksTo inherited */
1059 /** getExifData inherited */
1060 /** isLocal inherited */
1061 /** wasDeleted inherited */
1064 * Move file to the new title
1066 * Move current, old version and all thumbnails
1067 * to the new filename. Old file is deleted.
1069 * Cache purging is done; checks for validity
1070 * and logging are caller's responsibility
1072 * @param $target Title New file name
1073 * @return FileRepoStatus object.
1075 function move( $target ) {
1076 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1079 $batch = new LocalFileMoveBatch( $this, $target );
1080 $batch->addCurrent();
1083 $status = $batch->execute();
1084 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1086 $this->purgeEverything();
1089 if ( $status->isOk() ) {
1090 // Now switch the object
1091 $this->title
= $target;
1092 // Force regeneration of the name and hashpath
1093 unset( $this->name
);
1094 unset( $this->hashPath
);
1095 // Purge the new image
1096 $this->purgeEverything();
1103 * Delete all versions of the file.
1105 * Moves the files into an archive directory (or deletes them)
1106 * and removes the database rows.
1108 * Cache purging is done; logging is caller's responsibility.
1112 * @return FileRepoStatus object.
1114 function delete( $reason, $suppress = false ) {
1117 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1118 $batch->addCurrent();
1120 # Get old version relative paths
1121 $dbw = $this->repo
->getMasterDB();
1122 $result = $dbw->select( 'oldimage',
1123 array( 'oi_archive_name' ),
1124 array( 'oi_name' => $this->getName() ) );
1125 while ( $row = $dbw->fetchObject( $result ) ) {
1126 $batch->addOld( $row->oi_archive_name
);
1128 $status = $batch->execute();
1130 if ( $status->ok
) {
1131 // Update site_stats
1132 $site_stats = $dbw->tableName( 'site_stats' );
1133 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1134 $this->purgeEverything();
1143 * Delete an old version of the file.
1145 * Moves the file into an archive directory (or deletes it)
1146 * and removes the database row.
1148 * Cache purging is done; logging is caller's responsibility.
1150 * @param $archiveName String
1151 * @param $reason String
1152 * @param $suppress Boolean
1153 * @throws MWException or FSException on database or file store failure
1154 * @return FileRepoStatus object.
1156 function deleteOld( $archiveName, $reason, $suppress = false ) {
1159 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1160 $batch->addOld( $archiveName );
1161 $status = $batch->execute();
1165 if ( $status->ok
) {
1166 $this->purgeDescription();
1167 $this->purgeHistory();
1174 * Restore all or specified deleted revisions to the given file.
1175 * Permissions and logging are left to the caller.
1177 * May throw database exceptions on error.
1179 * @param $versions set of record ids of deleted items to restore,
1180 * or empty to restore all revisions.
1181 * @param $unsuppress Boolean
1182 * @return FileRepoStatus
1184 function restore( $versions = array(), $unsuppress = false ) {
1185 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1190 $batch->addIds( $versions );
1193 $status = $batch->execute();
1195 if ( !$status->ok
) {
1199 $cleanupStatus = $batch->cleanup();
1200 $cleanupStatus->successCount
= 0;
1201 $cleanupStatus->failCount
= 0;
1202 $status->merge( $cleanupStatus );
1207 /** isMultipage inherited */
1208 /** pageCount inherited */
1209 /** scaleHeight inherited */
1210 /** getImageSize inherited */
1212 /** getDescriptionUrl inherited */
1213 /** getDescriptionText inherited */
1215 function getDescription() {
1217 return $this->description
;
1220 function getTimestamp() {
1222 return $this->timestamp
;
1225 function getSha1() {
1227 // Initialise now if necessary
1228 if ( $this->sha1
== '' && $this->fileExists
) {
1229 $this->sha1
= File
::sha1Base36( $this->getPath() );
1230 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1231 $dbw = $this->repo
->getMasterDB();
1232 $dbw->update( 'image',
1233 array( 'img_sha1' => $this->sha1
),
1234 array( 'img_name' => $this->getName() ),
1236 $this->saveToCache();
1244 * Start a transaction and lock the image for update
1245 * Increments a reference counter if the lock is already held
1246 * @return boolean True if the image exists, false otherwise
1249 $dbw = $this->repo
->getMasterDB();
1251 if ( !$this->locked
) {
1256 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1260 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1261 * the transaction and thereby releases the image lock.
1264 if ( $this->locked
) {
1266 if ( !$this->locked
) {
1267 $dbw = $this->repo
->getMasterDB();
1274 * Roll back the DB transaction and mark the image unlocked
1276 function unlockAndRollback() {
1277 $this->locked
= false;
1278 $dbw = $this->repo
->getMasterDB();
1281 } // LocalFile class
1283 # ------------------------------------------------------------------------------
1286 * Helper class for file deletion
1289 class LocalFileDeleteBatch
{
1290 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1293 function __construct( File
$file, $reason = '', $suppress = false ) {
1294 $this->file
= $file;
1295 $this->reason
= $reason;
1296 $this->suppress
= $suppress;
1297 $this->status
= $file->repo
->newGood();
1300 function addCurrent() {
1301 $this->srcRels
['.'] = $this->file
->getRel();
1304 function addOld( $oldName ) {
1305 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1306 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1309 function getOldRels() {
1310 if ( !isset( $this->srcRels
['.'] ) ) {
1311 $oldRels =& $this->srcRels
;
1312 $deleteCurrent = false;
1314 $oldRels = $this->srcRels
;
1315 unset( $oldRels['.'] );
1316 $deleteCurrent = true;
1319 return array( $oldRels, $deleteCurrent );
1322 /*protected*/ function getHashes() {
1324 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1326 if ( $deleteCurrent ) {
1327 $hashes['.'] = $this->file
->getSha1();
1330 if ( count( $oldRels ) ) {
1331 $dbw = $this->file
->repo
->getMasterDB();
1332 $res = $dbw->select(
1334 array( 'oi_archive_name', 'oi_sha1' ),
1335 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1339 while ( $row = $dbw->fetchObject( $res ) ) {
1340 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1341 // Get the hash from the file
1342 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1343 $props = $this->file
->repo
->getFileProps( $oldUrl );
1345 if ( $props['fileExists'] ) {
1346 // Upgrade the oldimage row
1347 $dbw->update( 'oldimage',
1348 array( 'oi_sha1' => $props['sha1'] ),
1349 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1351 $hashes[$row->oi_archive_name
] = $props['sha1'];
1353 $hashes[$row->oi_archive_name
] = false;
1356 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1361 $missing = array_diff_key( $this->srcRels
, $hashes );
1363 foreach ( $missing as $name => $rel ) {
1364 $this->status
->error( 'filedelete-old-unregistered', $name );
1367 foreach ( $hashes as $name => $hash ) {
1369 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1370 unset( $hashes[$name] );
1377 function doDBInserts() {
1380 $dbw = $this->file
->repo
->getMasterDB();
1381 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1382 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1383 $encReason = $dbw->addQuotes( $this->reason
);
1384 $encGroup = $dbw->addQuotes( 'deleted' );
1385 $ext = $this->file
->getExtension();
1386 $dotExt = $ext === '' ?
'' : ".$ext";
1387 $encExt = $dbw->addQuotes( $dotExt );
1388 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1390 // Bitfields to further suppress the content
1391 if ( $this->suppress
) {
1393 // This should be 15...
1394 $bitfield |
= Revision
::DELETED_TEXT
;
1395 $bitfield |
= Revision
::DELETED_COMMENT
;
1396 $bitfield |
= Revision
::DELETED_USER
;
1397 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1399 $bitfield = 'oi_deleted';
1402 if ( $deleteCurrent ) {
1403 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1404 $where = array( 'img_name' => $this->file
->getName() );
1405 $dbw->insertSelect( 'filearchive', 'image',
1407 'fa_storage_group' => $encGroup,
1408 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1409 'fa_deleted_user' => $encUserId,
1410 'fa_deleted_timestamp' => $encTimestamp,
1411 'fa_deleted_reason' => $encReason,
1412 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1414 'fa_name' => 'img_name',
1415 'fa_archive_name' => 'NULL',
1416 'fa_size' => 'img_size',
1417 'fa_width' => 'img_width',
1418 'fa_height' => 'img_height',
1419 'fa_metadata' => 'img_metadata',
1420 'fa_bits' => 'img_bits',
1421 'fa_media_type' => 'img_media_type',
1422 'fa_major_mime' => 'img_major_mime',
1423 'fa_minor_mime' => 'img_minor_mime',
1424 'fa_description' => 'img_description',
1425 'fa_user' => 'img_user',
1426 'fa_user_text' => 'img_user_text',
1427 'fa_timestamp' => 'img_timestamp'
1428 ), $where, __METHOD__
);
1431 if ( count( $oldRels ) ) {
1432 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1434 'oi_name' => $this->file
->getName(),
1435 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1436 $dbw->insertSelect( 'filearchive', 'oldimage',
1438 'fa_storage_group' => $encGroup,
1439 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1440 'fa_deleted_user' => $encUserId,
1441 'fa_deleted_timestamp' => $encTimestamp,
1442 'fa_deleted_reason' => $encReason,
1443 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1445 'fa_name' => 'oi_name',
1446 'fa_archive_name' => 'oi_archive_name',
1447 'fa_size' => 'oi_size',
1448 'fa_width' => 'oi_width',
1449 'fa_height' => 'oi_height',
1450 'fa_metadata' => 'oi_metadata',
1451 'fa_bits' => 'oi_bits',
1452 'fa_media_type' => 'oi_media_type',
1453 'fa_major_mime' => 'oi_major_mime',
1454 'fa_minor_mime' => 'oi_minor_mime',
1455 'fa_description' => 'oi_description',
1456 'fa_user' => 'oi_user',
1457 'fa_user_text' => 'oi_user_text',
1458 'fa_timestamp' => 'oi_timestamp',
1459 'fa_deleted' => $bitfield
1460 ), $where, __METHOD__
);
1464 function doDBDeletes() {
1465 $dbw = $this->file
->repo
->getMasterDB();
1466 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1468 if ( count( $oldRels ) ) {
1469 $dbw->delete( 'oldimage',
1471 'oi_name' => $this->file
->getName(),
1472 'oi_archive_name' => array_keys( $oldRels )
1476 if ( $deleteCurrent ) {
1477 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1482 * Run the transaction
1484 function execute() {
1486 wfProfileIn( __METHOD__
);
1488 $this->file
->lock();
1489 // Leave private files alone
1490 $privateFiles = array();
1491 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1492 $dbw = $this->file
->repo
->getMasterDB();
1494 if ( !empty( $oldRels ) ) {
1495 $res = $dbw->select( 'oldimage',
1496 array( 'oi_archive_name' ),
1497 array( 'oi_name' => $this->file
->getName(),
1498 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1499 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1502 while ( $row = $dbw->fetchObject( $res ) ) {
1503 $privateFiles[$row->oi_archive_name
] = 1;
1506 // Prepare deletion batch
1507 $hashes = $this->getHashes();
1508 $this->deletionBatch
= array();
1509 $ext = $this->file
->getExtension();
1510 $dotExt = $ext === '' ?
'' : ".$ext";
1512 foreach ( $this->srcRels
as $name => $srcRel ) {
1513 // Skip files that have no hash (missing source).
1514 // Keep private files where they are.
1515 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1516 $hash = $hashes[$name];
1517 $key = $hash . $dotExt;
1518 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1519 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1523 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1524 // We acquire this lock by running the inserts now, before the file operations.
1526 // This potentially has poor lock contention characteristics -- an alternative
1527 // scheme would be to insert stub filearchive entries with no fa_name and commit
1528 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1529 $this->doDBInserts();
1531 // Removes non-existent file from the batch, so we don't get errors.
1532 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1534 // Execute the file deletion batch
1535 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1537 if ( !$status->isGood() ) {
1538 $this->status
->merge( $status );
1541 if ( !$this->status
->ok
) {
1542 // Critical file deletion error
1543 // Roll back inserts, release lock and abort
1544 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1545 $this->file
->unlockAndRollback();
1546 wfProfileOut( __METHOD__
);
1547 return $this->status
;
1551 if ( $wgUseSquid ) {
1554 foreach ( $this->srcRels
as $srcRel ) {
1555 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1556 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1558 SquidUpdate
::purge( $urls );
1561 // Delete image/oldimage rows
1562 $this->doDBDeletes();
1564 // Commit and return
1565 $this->file
->unlock();
1566 wfProfileOut( __METHOD__
);
1568 return $this->status
;
1572 * Removes non-existent files from a deletion batch.
1574 function removeNonexistentFiles( $batch ) {
1575 $files = $newBatch = array();
1577 foreach ( $batch as $batchItem ) {
1578 list( $src, $dest ) = $batchItem;
1579 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1582 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1584 foreach ( $batch as $batchItem ) {
1585 if ( $result[$batchItem[0]] ) {
1586 $newBatch[] = $batchItem;
1594 # ------------------------------------------------------------------------------
1597 * Helper class for file undeletion
1600 class LocalFileRestoreBatch
{
1601 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1603 function __construct( File
$file, $unsuppress = false ) {
1604 $this->file
= $file;
1605 $this->cleanupBatch
= $this->ids
= array();
1606 $this->ids
= array();
1607 $this->unsuppress
= $unsuppress;
1613 function addId( $fa_id ) {
1614 $this->ids
[] = $fa_id;
1618 * Add a whole lot of files by ID
1620 function addIds( $ids ) {
1621 $this->ids
= array_merge( $this->ids
, $ids );
1625 * Add all revisions of the file
1632 * Run the transaction, except the cleanup batch.
1633 * The cleanup batch should be run in a separate transaction, because it locks different
1634 * rows and there's no need to keep the image row locked while it's acquiring those locks
1635 * The caller may have its own transaction open.
1636 * So we save the batch and let the caller call cleanup()
1638 function execute() {
1641 if ( !$this->all
&& !$this->ids
) {
1643 return $this->file
->repo
->newGood();
1646 $exists = $this->file
->lock();
1647 $dbw = $this->file
->repo
->getMasterDB();
1648 $status = $this->file
->repo
->newGood();
1650 // Fetch all or selected archived revisions for the file,
1651 // sorted from the most recent to the oldest.
1652 $conditions = array( 'fa_name' => $this->file
->getName() );
1654 if ( !$this->all
) {
1655 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1658 $result = $dbw->select( 'filearchive', '*',
1661 array( 'ORDER BY' => 'fa_timestamp DESC' )
1664 $idsPresent = array();
1665 $storeBatch = array();
1666 $insertBatch = array();
1667 $insertCurrent = false;
1668 $deleteIds = array();
1670 $archiveNames = array();
1672 while ( $row = $dbw->fetchObject( $result ) ) {
1673 $idsPresent[] = $row->fa_id
;
1675 if ( $row->fa_name
!= $this->file
->getName() ) {
1676 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1677 $status->failCount++
;
1681 if ( $row->fa_storage_key
== '' ) {
1682 // Revision was missing pre-deletion
1683 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1684 $status->failCount++
;
1688 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1689 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1691 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1694 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1695 $sha1 = substr( $sha1, 1 );
1698 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1699 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1700 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1701 ||
is_null( $row->fa_metadata
) ) {
1702 // Refresh our metadata
1703 // Required for a new current revision; nice for older ones too. :)
1704 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1707 'minor_mime' => $row->fa_minor_mime
,
1708 'major_mime' => $row->fa_major_mime
,
1709 'media_type' => $row->fa_media_type
,
1710 'metadata' => $row->fa_metadata
1714 if ( $first && !$exists ) {
1715 // This revision will be published as the new current version
1716 $destRel = $this->file
->getRel();
1717 $insertCurrent = array(
1718 'img_name' => $row->fa_name
,
1719 'img_size' => $row->fa_size
,
1720 'img_width' => $row->fa_width
,
1721 'img_height' => $row->fa_height
,
1722 'img_metadata' => $props['metadata'],
1723 'img_bits' => $row->fa_bits
,
1724 'img_media_type' => $props['media_type'],
1725 'img_major_mime' => $props['major_mime'],
1726 'img_minor_mime' => $props['minor_mime'],
1727 'img_description' => $row->fa_description
,
1728 'img_user' => $row->fa_user
,
1729 'img_user_text' => $row->fa_user_text
,
1730 'img_timestamp' => $row->fa_timestamp
,
1734 // The live (current) version cannot be hidden!
1735 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1736 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1737 $this->cleanupBatch
[] = $row->fa_storage_key
;
1740 $archiveName = $row->fa_archive_name
;
1742 if ( $archiveName == '' ) {
1743 // This was originally a current version; we
1744 // have to devise a new archive name for it.
1745 // Format is <timestamp of archiving>!<name>
1746 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1749 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1751 } while ( isset( $archiveNames[$archiveName] ) );
1754 $archiveNames[$archiveName] = true;
1755 $destRel = $this->file
->getArchiveRel( $archiveName );
1756 $insertBatch[] = array(
1757 'oi_name' => $row->fa_name
,
1758 'oi_archive_name' => $archiveName,
1759 'oi_size' => $row->fa_size
,
1760 'oi_width' => $row->fa_width
,
1761 'oi_height' => $row->fa_height
,
1762 'oi_bits' => $row->fa_bits
,
1763 'oi_description' => $row->fa_description
,
1764 'oi_user' => $row->fa_user
,
1765 'oi_user_text' => $row->fa_user_text
,
1766 'oi_timestamp' => $row->fa_timestamp
,
1767 'oi_metadata' => $props['metadata'],
1768 'oi_media_type' => $props['media_type'],
1769 'oi_major_mime' => $props['major_mime'],
1770 'oi_minor_mime' => $props['minor_mime'],
1771 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1772 'oi_sha1' => $sha1 );
1775 $deleteIds[] = $row->fa_id
;
1777 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1778 // private files can stay where they are
1779 $status->successCount++
;
1781 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1782 $this->cleanupBatch
[] = $row->fa_storage_key
;
1790 // Add a warning to the status object for missing IDs
1791 $missingIds = array_diff( $this->ids
, $idsPresent );
1793 foreach ( $missingIds as $id ) {
1794 $status->error( 'undelete-missing-filearchive', $id );
1797 // Remove missing files from batch, so we don't get errors when undeleting them
1798 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1800 // Run the store batch
1801 // Use the OVERWRITE_SAME flag to smooth over a common error
1802 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1803 $status->merge( $storeStatus );
1805 if ( !$status->ok
) {
1806 // Store batch returned a critical error -- this usually means nothing was stored
1807 // Stop now and return an error
1808 $this->file
->unlock();
1813 // Run the DB updates
1814 // Because we have locked the image row, key conflicts should be rare.
1815 // If they do occur, we can roll back the transaction at this time with
1816 // no data loss, but leaving unregistered files scattered throughout the
1818 // This is not ideal, which is why it's important to lock the image row.
1819 if ( $insertCurrent ) {
1820 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1823 if ( $insertBatch ) {
1824 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1828 $dbw->delete( 'filearchive',
1829 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1833 // If store batch is empty (all files are missing), deletion is to be considered successful
1834 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1836 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1838 // Update site_stats
1839 $site_stats = $dbw->tableName( 'site_stats' );
1840 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1842 $this->file
->purgeEverything();
1844 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1845 $this->file
->purgeDescription();
1846 $this->file
->purgeHistory();
1850 $this->file
->unlock();
1856 * Removes non-existent files from a store batch.
1858 function removeNonexistentFiles( $triplets ) {
1859 $files = $filteredTriplets = array();
1860 foreach ( $triplets as $file )
1861 $files[$file[0]] = $file[0];
1863 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1865 foreach ( $triplets as $file ) {
1866 if ( $result[$file[0]] ) {
1867 $filteredTriplets[] = $file;
1871 return $filteredTriplets;
1875 * Removes non-existent files from a cleanup batch.
1877 function removeNonexistentFromCleanup( $batch ) {
1878 $files = $newBatch = array();
1879 $repo = $this->file
->repo
;
1881 foreach ( $batch as $file ) {
1882 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1883 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1886 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1888 foreach ( $batch as $file ) {
1889 if ( $result[$file] ) {
1890 $newBatch[] = $file;
1898 * Delete unused files in the deleted zone.
1899 * This should be called from outside the transaction in which execute() was called.
1901 function cleanup() {
1902 if ( !$this->cleanupBatch
) {
1903 return $this->file
->repo
->newGood();
1906 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1908 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1914 # ------------------------------------------------------------------------------
1917 * Helper class for file movement
1920 class LocalFileMoveBatch
{
1921 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1923 function __construct( File
$file, Title
$target ) {
1924 $this->file
= $file;
1925 $this->target
= $target;
1926 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1927 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1928 $this->oldName
= $this->file
->getName();
1929 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1930 $this->oldRel
= $this->oldHash
. $this->oldName
;
1931 $this->newRel
= $this->newHash
. $this->newName
;
1932 $this->db
= $file->repo
->getMasterDb();
1936 * Add the current image to the batch
1938 function addCurrent() {
1939 $this->cur
= array( $this->oldRel
, $this->newRel
);
1943 * Add the old versions of the image to the batch
1945 function addOlds() {
1946 $archiveBase = 'archive';
1947 $this->olds
= array();
1948 $this->oldCount
= 0;
1950 $result = $this->db
->select( 'oldimage',
1951 array( 'oi_archive_name', 'oi_deleted' ),
1952 array( 'oi_name' => $this->oldName
),
1956 while ( $row = $this->db
->fetchObject( $result ) ) {
1957 $oldName = $row->oi_archive_name
;
1958 $bits = explode( '!', $oldName, 2 );
1960 if ( count( $bits ) != 2 ) {
1961 wfDebug( "Invalid old file name: $oldName \n" );
1965 list( $timestamp, $filename ) = $bits;
1967 if ( $this->oldName
!= $filename ) {
1968 wfDebug( "Invalid old file name: $oldName \n" );
1974 // Do we want to add those to oldCount?
1975 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
1979 $this->olds
[] = array(
1980 "{$archiveBase}/{$this->oldHash}{$oldName}",
1981 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1989 function execute() {
1990 $repo = $this->file
->repo
;
1991 $status = $repo->newGood();
1992 $triplets = $this->getMoveTriplets();
1994 $triplets = $this->removeNonexistentFiles( $triplets );
1995 $statusDb = $this->doDBUpdates();
1996 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1997 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1998 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2000 if ( !$statusMove->isOk() ) {
2001 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2002 $this->db
->rollback();
2005 $status->merge( $statusDb );
2006 $status->merge( $statusMove );
2012 * Do the database updates and return a new FileRepoStatus indicating how
2013 * many rows where updated.
2015 * @return FileRepoStatus
2017 function doDBUpdates() {
2018 $repo = $this->file
->repo
;
2019 $status = $repo->newGood();
2022 // Update current image
2025 array( 'img_name' => $this->newName
),
2026 array( 'img_name' => $this->oldName
),
2030 if ( $dbw->affectedRows() ) {
2031 $status->successCount++
;
2033 $status->failCount++
;
2036 // Update old images
2040 'oi_name' => $this->newName
,
2041 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2043 array( 'oi_name' => $this->oldName
),
2047 $affected = $dbw->affectedRows();
2048 $total = $this->oldCount
;
2049 $status->successCount +
= $affected;
2050 $status->failCount +
= $total - $affected;
2056 * Generate triplets for FSRepo::storeBatch().
2058 function getMoveTriplets() {
2059 $moves = array_merge( array( $this->cur
), $this->olds
);
2060 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2062 foreach ( $moves as $move ) {
2063 // $move: (oldRelativePath, newRelativePath)
2064 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2065 $triplets[] = array( $srcUrl, 'public', $move[1] );
2066 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2073 * Removes non-existent files from move batch.
2075 function removeNonexistentFiles( $triplets ) {
2078 foreach ( $triplets as $file ) {
2079 $files[$file[0]] = $file[0];
2082 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2083 $filteredTriplets = array();
2085 foreach ( $triplets as $file ) {
2086 if ( $result[$file[0]] ) {
2087 $filteredTriplets[] = $file;
2089 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2093 return $filteredTriplets;