6 * Bump this number when serialized cache records may be incompatible.
8 define( 'MW_FILE_VERSION', 4 );
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
25 * @addtogroup FileRepo
27 class LocalFile
extends File
32 var $fileExists, # does the file file exist on disk? (loadFromXxx)
33 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
34 $historyRes, # result of the query for the file's history (nextHistoryLine)
37 $bits, # --- returned by getimagesize (loadFromXxx)
39 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
40 $mime, # MIME type, determined by MimeMagic::guessMimeType
41 $major_mime, # Major mime type
42 $minor_mime, # Minor mime type
43 $size, # Size in bytes (loadFromXxx)
44 $metadata, # Handler-specific metadata
45 $timestamp, # Upload timestamp
46 $sha1, # SHA-1 base 36 content hash
47 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
48 $upgraded, # Whether the row was upgraded on load
49 $locked; # True if the image row is locked
54 * Create a LocalFile from a title
55 * Do not call this except from inside a repo class.
57 static function newFromTitle( $title, $repo ) {
58 return new self( $title, $repo );
62 * Create a LocalFile from a title
63 * Do not call this except from inside a repo class.
65 static function newFromRow( $row, $repo ) {
66 $title = Title
::makeTitle( NS_IMAGE
, $row->img_name
);
67 $file = new self( $title, $repo );
68 $file->loadFromRow( $row );
74 * Do not call this except from inside a repo class.
76 function __construct( $title, $repo ) {
77 if( !is_object( $title ) ) {
78 throw new MWException( __CLASS__
.' constructor given bogus title.' );
80 parent
::__construct( $title, $repo );
82 $this->historyLine
= 0;
83 $this->historyRes
= null;
84 $this->dataLoaded
= false;
88 * Get the memcached key
90 function getCacheKey() {
91 $hashedName = md5($this->getName());
92 return wfMemcKey( 'file', $hashedName );
96 * Try to load file metadata from memcached. Returns true on success.
98 function loadFromCache() {
100 wfProfileIn( __METHOD__
);
101 $this->dataLoaded
= false;
102 $key = $this->getCacheKey();
106 $cachedValues = $wgMemc->get( $key );
108 // Check if the key existed and belongs to this version of MediaWiki
109 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
110 wfDebug( "Pulling file metadata from cache key $key\n" );
111 $this->fileExists
= $cachedValues['fileExists'];
112 if ( $this->fileExists
) {
113 unset( $cachedValues['version'] );
114 unset( $cachedValues['fileExists'] );
115 foreach ( $cachedValues as $name => $value ) {
116 $this->$name = $value;
120 if ( $this->dataLoaded
) {
121 wfIncrStats( 'image_cache_hit' );
123 wfIncrStats( 'image_cache_miss' );
126 wfProfileOut( __METHOD__
);
127 return $this->dataLoaded
;
131 * Save the file metadata to memcached
133 function saveToCache() {
136 $key = $this->getCacheKey();
140 $fields = $this->getCacheFields( '' );
141 $cache = array( 'version' => MW_FILE_VERSION
);
142 $cache['fileExists'] = $this->fileExists
;
143 if ( $this->fileExists
) {
144 foreach ( $fields as $field ) {
145 $cache[$field] = $this->$field;
149 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
153 * Load metadata from the file itself
155 function loadFromFile() {
156 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
159 function getCacheFields( $prefix = 'img_' ) {
160 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
161 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1' );
162 static $results = array();
163 if ( $prefix == '' ) {
166 if ( !isset( $results[$prefix] ) ) {
167 $prefixedFields = array();
168 foreach ( $fields as $field ) {
169 $prefixedFields[] = $prefix . $field;
171 $results[$prefix] = $prefixedFields;
173 return $results[$prefix];
177 * Load file metadata from the DB
179 function loadFromDB() {
180 # Polymorphic function name to distinguish foreign and local fetches
181 $fname = get_class( $this ) . '::' . __FUNCTION__
;
182 wfProfileIn( $fname );
184 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
185 $this->dataLoaded
= true;
187 $dbr = $this->repo
->getSlaveDB();
189 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
190 array( 'img_name' => $this->getName() ), $fname );
192 $this->loadFromRow( $row );
194 $this->fileExists
= false;
197 wfProfileOut( $fname );
201 * Decode a row from the database (either object or array) to an array
202 * with timestamps and MIME types decoded, and the field prefix removed.
204 function decodeRow( $row, $prefix = 'img_' ) {
205 $array = (array)$row;
206 $prefixLength = strlen( $prefix );
207 // Sanity check prefix once
208 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
209 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
212 foreach ( $array as $name => $value ) {
213 $deprefixedName = substr( $name, $prefixLength );
214 $decoded[substr( $name, $prefixLength )] = $value;
216 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
217 if ( empty( $decoded['major_mime'] ) ) {
218 $decoded['mime'] = "unknown/unknown";
220 if (!$decoded['minor_mime']) {
221 $decoded['minor_mime'] = "unknown";
223 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
225 # Trim zero padding from char/binary field
226 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
231 * Load file metadata from a DB result row
233 function loadFromRow( $row, $prefix = 'img_' ) {
234 $this->dataLoaded
= true;
235 $array = $this->decodeRow( $row, $prefix );
236 foreach ( $array as $name => $value ) {
237 $this->$name = $value;
239 $this->fileExists
= true;
240 // Check for rows from a previous schema, quietly upgrade them
241 $this->maybeUpgradeRow();
245 * Load file metadata from cache or DB, unless already loaded
248 if ( !$this->dataLoaded
) {
249 if ( !$this->loadFromCache() ) {
251 $this->saveToCache();
253 $this->dataLoaded
= true;
258 * Upgrade a row if it needs it
260 function maybeUpgradeRow() {
261 if ( wfReadOnly() ) {
264 if ( is_null($this->media_type
) ||
265 $this->mime
== 'image/svg' ||
269 $this->upgraded
= true;
271 $handler = $this->getHandler();
272 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
274 $this->upgraded
= true;
279 function getUpgraded() {
280 return $this->upgraded
;
284 * Fix assorted version-related problems with the image row by reloading it from the file
286 function upgradeRow() {
287 wfProfileIn( __METHOD__
);
289 $this->loadFromFile();
291 # Don't destroy file info of missing files
292 if ( !$this->fileExists
) {
293 wfDebug( __METHOD__
.": file does not exist, aborting\n" );
296 $dbw = $this->repo
->getMasterDB();
297 list( $major, $minor ) = self
::splitMime( $this->mime
);
299 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
301 $dbw->update( 'image',
303 'img_width' => $this->width
,
304 'img_height' => $this->height
,
305 'img_bits' => $this->bits
,
306 'img_media_type' => $this->media_type
,
307 'img_major_mime' => $major,
308 'img_minor_mime' => $minor,
309 'img_metadata' => $this->metadata
,
310 'img_sha1' => $this->sha1
,
311 ), array( 'img_name' => $this->getName() ),
314 $this->saveToCache();
315 wfProfileOut( __METHOD__
);
318 function setProps( $info ) {
319 $this->dataLoaded
= true;
320 $fields = $this->getCacheFields( '' );
321 $fields[] = 'fileExists';
322 foreach ( $fields as $field ) {
323 if ( isset( $info[$field] ) ) {
324 $this->$field = $info[$field];
327 // Fix up mime fields
328 if ( isset( $info['major_mime'] ) ) {
329 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
330 } elseif ( isset( $info['mime'] ) ) {
331 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
335 /** splitMime inherited */
336 /** getName inherited */
337 /** getTitle inherited */
338 /** getURL inherited */
339 /** getViewURL inherited */
340 /** getPath inherited */
343 * Return the width of the image
345 * Returns false on error
348 function getWidth( $page = 1 ) {
350 if ( $this->isMultipage() ) {
351 $dim = $this->getHandler()->getPageDimensions( $this, $page );
353 return $dim['width'];
363 * Return the height of the image
365 * Returns false on error
368 function getHeight( $page = 1 ) {
370 if ( $this->isMultipage() ) {
371 $dim = $this->getHandler()->getPageDimensions( $this, $page );
373 return $dim['height'];
378 return $this->height
;
383 * Get handler-specific metadata
385 function getMetadata() {
387 return $this->metadata
;
391 * Return the size of the image file, in bytes
400 * Returns the mime type of the file.
402 function getMimeType() {
408 * Return the type of the media in the file.
409 * Use the value returned by this function with the MEDIATYPE_xxx constants.
411 function getMediaType() {
413 return $this->media_type
;
416 /** canRender inherited */
417 /** mustRender inherited */
418 /** allowInlineDisplay inherited */
419 /** isSafeFile inherited */
420 /** isTrustedFile inherited */
423 * Returns true if the file file exists on disk.
424 * @return boolean Whether file file exist on disk.
429 return $this->fileExists
;
432 /** getTransformScript inherited */
433 /** getUnscaledThumb inherited */
434 /** thumbName inherited */
435 /** createThumb inherited */
436 /** getThumbnail inherited */
437 /** transform inherited */
440 * Fix thumbnail files from 1.4 or before, with extreme prejudice
442 function migrateThumbFile( $thumbName ) {
443 $thumbDir = $this->getThumbPath();
444 $thumbPath = "$thumbDir/$thumbName";
445 if ( is_dir( $thumbPath ) ) {
446 // Directory where file should be
447 // This happened occasionally due to broken migration code in 1.5
448 // Rename to broken-*
449 for ( $i = 0; $i < 100 ; $i++
) {
450 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
451 if ( !file_exists( $broken ) ) {
452 rename( $thumbPath, $broken );
456 // Doesn't exist anymore
459 if ( is_file( $thumbDir ) ) {
460 // File where directory should be
462 // Doesn't exist anymore
467 /** getHandler inherited */
468 /** iconThumb inherited */
469 /** getLastError inherited */
472 * Get all thumbnail names previously generated for this file
474 function getThumbnails() {
475 if ( $this->isHashed() ) {
478 $dir = $this->getThumbPath();
480 if ( is_dir( $dir ) ) {
481 $handle = opendir( $dir );
484 while ( false !== ( $file = readdir($handle) ) ) {
485 if ( $file{0} != '.' ) {
500 * Refresh metadata in memcached, but don't touch thumbnails or squid
502 function purgeMetadataCache() {
504 $this->saveToCache();
505 $this->purgeHistory();
509 * Purge the shared history (OldLocalFile) cache
511 function purgeHistory() {
513 $hashedName = md5($this->getName());
514 $oldKey = wfMemcKey( 'oldfile', $hashedName );
515 $wgMemc->delete( $oldKey );
519 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
521 function purgeCache() {
522 // Refresh metadata cache
523 $this->purgeMetadataCache();
526 $this->purgeThumbnails();
528 // Purge squid cache for this file
529 wfPurgeSquidServers( array( $this->getURL() ) );
533 * Delete cached transformed files
535 function purgeThumbnails() {
538 $files = $this->getThumbnails();
539 $dir = $this->getThumbPath();
541 foreach ( $files as $file ) {
543 # Check that the base file name is part of the thumb name
544 # This is a basic sanity check to avoid erasing unrelated directories
545 if ( strpos( $file, $this->getName() ) !== false ) {
546 $url = $this->getThumbUrl( $file );
548 @unlink
( "$dir/$file" );
554 wfPurgeSquidServers( $urls );
558 /** purgeDescription inherited */
559 /** purgeEverything inherited */
562 * Return the history of this file, line by line.
563 * starts with current version, then old versions.
564 * uses $this->historyLine to check which line to return:
565 * 0 return line for current version
566 * 1 query for old versions, return first one
567 * 2, ... return next old version from above query
571 function nextHistoryLine() {
572 $dbr = $this->repo
->getSlaveDB();
574 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
575 $this->historyRes
= $dbr->select( 'image',
578 "'' AS oi_archive_name"
580 array( 'img_name' => $this->title
->getDBkey() ),
583 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
584 $dbr->freeResult($this->historyRes
);
585 $this->historyRes
= null;
588 } else if ( $this->historyLine
== 1 ) {
589 $dbr->freeResult($this->historyRes
);
590 $this->historyRes
= $dbr->select( 'oldimage', '*',
591 array( 'oi_name' => $this->title
->getDBkey() ),
593 array( 'ORDER BY' => 'oi_timestamp DESC' )
596 $this->historyLine ++
;
598 return $dbr->fetchObject( $this->historyRes
);
602 * Reset the history pointer to the first element of the history
605 function resetHistory() {
606 $this->historyLine
= 0;
607 if (!is_null($this->historyRes
)) {
608 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
609 $this->historyRes
= null;
613 /** getFullPath inherited */
614 /** getHashPath inherited */
615 /** getRel inherited */
616 /** getUrlRel inherited */
617 /** getArchiveRel inherited */
618 /** getThumbRel inherited */
619 /** getArchivePath inherited */
620 /** getThumbPath inherited */
621 /** getArchiveUrl inherited */
622 /** getThumbUrl inherited */
623 /** getArchiveVirtualUrl inherited */
624 /** getThumbVirtualUrl inherited */
625 /** isHashed inherited */
628 * Upload a file and record it in the DB
629 * @param string $srcPath Source path or virtual URL
630 * @param string $comment Upload description
631 * @param string $pageText Text to use for the new description page, if a new description page is created
632 * @param integer $flags Flags for publish()
633 * @param array $props File properties, if known. This can be used to reduce the
634 * upload time when uploading virtual URLs for which the file info
636 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
638 * @return FileRepoStatus object. On success, the value member contains the
639 * archive name, or an empty string if it was a new file.
641 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
643 $status = $this->publish( $srcPath, $flags );
645 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
646 $status->fatal( 'filenotfound', $srcPath );
654 * Record a file upload in the upload log and the image table
655 * @deprecated use upload()
657 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
658 $watch = false, $timestamp = false )
660 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
661 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
666 $wgUser->addWatch( $this->getTitle() );
673 * Record a file upload in the upload log and the image table
675 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
679 $dbw = $this->repo
->getMasterDB();
682 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
684 $this->setProps( $props );
686 // Delete thumbnails and refresh the metadata cache
687 $this->purgeThumbnails();
688 $this->saveToCache();
689 wfPurgeSquidServers( array( $this->getURL() ) );
691 // Fail now if the file isn't there
692 if ( !$this->fileExists
) {
693 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
697 if ( $timestamp === false ) {
698 $timestamp = $dbw->timestamp();
701 # Test to see if the row exists using INSERT IGNORE
702 # This avoids race conditions by locking the row until the commit, and also
703 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
704 $dbw->insert( 'image',
706 'img_name' => $this->getName(),
707 'img_size'=> $this->size
,
708 'img_width' => intval( $this->width
),
709 'img_height' => intval( $this->height
),
710 'img_bits' => $this->bits
,
711 'img_media_type' => $this->media_type
,
712 'img_major_mime' => $this->major_mime
,
713 'img_minor_mime' => $this->minor_mime
,
714 'img_timestamp' => $timestamp,
715 'img_description' => $comment,
716 'img_user' => $wgUser->getID(),
717 'img_user_text' => $wgUser->getName(),
718 'img_metadata' => $this->metadata
,
719 'img_sha1' => $this->sha1
725 if( $dbw->affectedRows() == 0 ) {
726 # Collision, this is an update of a file
727 # Insert previous contents into oldimage
728 $dbw->insertSelect( 'oldimage', 'image',
730 'oi_name' => 'img_name',
731 'oi_archive_name' => $dbw->addQuotes( $oldver ),
732 'oi_size' => 'img_size',
733 'oi_width' => 'img_width',
734 'oi_height' => 'img_height',
735 'oi_bits' => 'img_bits',
736 'oi_timestamp' => 'img_timestamp',
737 'oi_description' => 'img_description',
738 'oi_user' => 'img_user',
739 'oi_user_text' => 'img_user_text',
740 'oi_metadata' => 'img_metadata',
741 'oi_media_type' => 'img_media_type',
742 'oi_major_mime' => 'img_major_mime',
743 'oi_minor_mime' => 'img_minor_mime',
744 'oi_sha1' => 'img_sha1',
745 ), array( 'img_name' => $this->getName() ), __METHOD__
748 # Update the current image row
749 $dbw->update( 'image',
751 'img_size' => $this->size
,
752 'img_width' => intval( $this->width
),
753 'img_height' => intval( $this->height
),
754 'img_bits' => $this->bits
,
755 'img_media_type' => $this->media_type
,
756 'img_major_mime' => $this->major_mime
,
757 'img_minor_mime' => $this->minor_mime
,
758 'img_timestamp' => $timestamp,
759 'img_description' => $comment,
760 'img_user' => $wgUser->getID(),
761 'img_user_text' => $wgUser->getName(),
762 'img_metadata' => $this->metadata
,
763 'img_sha1' => $this->sha1
764 ), array( /* WHERE */
765 'img_name' => $this->getName()
770 # Update the image count
771 $site_stats = $dbw->tableName( 'site_stats' );
772 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
775 $descTitle = $this->getTitle();
776 $article = new Article( $descTitle );
779 $log = new LogPage( 'upload' );
780 $log->addEntry( 'upload', $descTitle, $comment );
782 if( $descTitle->exists() ) {
783 # Create a null revision
784 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
785 $nullRevision->insertOn( $dbw );
787 # Invalidate the cache for the description page
788 $descTitle->invalidateCache();
789 $descTitle->purgeSquid();
791 // New file; create the description page.
792 // There's already a log entry, so don't make a second RC entry
793 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
796 # Hooks, hooks, the magic of hooks...
797 wfRunHooks( 'FileUpload', array( $this ) );
799 # Commit the transaction now, in case something goes wrong later
800 # The most important thing is that files don't get lost, especially archives
801 $dbw->immediateCommit();
803 # Invalidate cache for all pages using this file
804 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
811 * Move or copy a file to its public location. If a file exists at the
812 * destination, move it to an archive. Returns the archive name on success
813 * or an empty string if it was a new file, and a wikitext-formatted
814 * WikiError object on failure.
816 * The archive name should be passed through to recordUpload for database
819 * @param string $sourcePath Local filesystem path to the source image
820 * @param integer $flags A bitwise combination of:
821 * File::DELETE_SOURCE Delete the source file, i.e. move
823 * @return FileRepoStatus object. On success, the value member contains the
824 * archive name, or an empty string if it was a new file.
826 function publish( $srcPath, $flags = 0 ) {
828 $dstRel = $this->getRel();
829 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
830 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
831 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
832 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
833 if ( $status->value
== 'new' ) {
836 $status->value
= $archiveName;
842 /** getLinksTo inherited */
843 /** getExifData inherited */
844 /** isLocal inherited */
845 /** wasDeleted inherited */
848 * Delete all versions of the file.
850 * Moves the files into an archive directory (or deletes them)
851 * and removes the database rows.
853 * Cache purging is done; logging is caller's responsibility.
856 * @return FileRepoStatus object.
858 function delete( $reason ) {
860 $batch = new LocalFileDeleteBatch( $this, $reason );
861 $batch->addCurrent();
863 # Get old version relative paths
864 $dbw = $this->repo
->getMasterDB();
865 $result = $dbw->select( 'oldimage',
866 array( 'oi_archive_name' ),
867 array( 'oi_name' => $this->getName() ) );
868 while ( $row = $dbw->fetchObject( $result ) ) {
869 $batch->addOld( $row->oi_archive_name
);
871 $status = $batch->execute();
875 $site_stats = $dbw->tableName( 'site_stats' );
876 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
877 $this->purgeEverything();
885 * Delete an old version of the file.
887 * Moves the file into an archive directory (or deletes it)
888 * and removes the database row.
890 * Cache purging is done; logging is caller's responsibility.
893 * @throws MWException or FSException on database or filestore failure
894 * @return FileRepoStatus object.
896 function deleteOld( $archiveName, $reason ) {
898 $batch = new LocalFileDeleteBatch( $this, $reason );
899 $batch->addOld( $archiveName );
900 $status = $batch->execute();
903 $this->purgeDescription();
904 $this->purgeHistory();
910 * Restore all or specified deleted revisions to the given file.
911 * Permissions and logging are left to the caller.
913 * May throw database exceptions on error.
915 * @param $versions set of record ids of deleted items to restore,
916 * or empty to restore all revisions.
917 * @return FileRepoStatus
919 function restore( $versions = array(), $unsuppress = false ) {
920 $batch = new LocalFileRestoreBatch( $this );
924 $batch->addIds( $versions );
926 $status = $batch->execute();
927 if ( !$status->ok
) {
931 $cleanupStatus = $batch->cleanup();
932 $cleanupStatus->successCount
= 0;
933 $cleanupStatus->failCount
= 0;
934 $status->merge( $cleanupStatus );
938 /** isMultipage inherited */
939 /** pageCount inherited */
940 /** scaleHeight inherited */
941 /** getImageSize inherited */
944 * Get the URL of the file description page.
946 function getDescriptionUrl() {
947 return $this->title
->getLocalUrl();
951 * Get the HTML text of the description page
952 * This is not used by ImagePage for local files, since (among other things)
953 * it skips the parser cache.
955 function getDescriptionText() {
957 $revision = Revision
::newFromTitle( $this->title
);
958 if ( !$revision ) return false;
959 $text = $revision->getText();
960 if ( !$text ) return false;
961 $html = $wgParser->parse( $text, new ParserOptions
);
965 function getTimestamp() {
967 return $this->timestamp
;
976 * Start a transaction and lock the image for update
977 * Increments a reference counter if the lock is already held
978 * @return boolean True if the image exists, false otherwise
981 $dbw = $this->repo
->getMasterDB();
982 if ( !$this->locked
) {
986 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
990 * Decrement the lock reference count. If the reference count is reduced to zero, commits
991 * the transaction and thereby releases the image lock.
994 if ( $this->locked
) {
996 if ( !$this->locked
) {
997 $dbw = $this->repo
->getMasterDB();
1004 * Roll back the DB transaction and mark the image unlocked
1006 function unlockAndRollback() {
1007 $this->locked
= false;
1008 $dbw = $this->repo
->getMasterDB();
1011 } // LocalFile class
1013 #------------------------------------------------------------------------------
1016 * Backwards compatibility class
1018 class Image
extends LocalFile
{
1019 function __construct( $title ) {
1020 $repo = RepoGroup
::singleton()->getLocalRepo();
1021 parent
::__construct( $title, $repo );
1025 * Wrapper for wfFindFile(), for backwards-compatibility only
1026 * Do not use in core code.
1029 static function newFromTitle( $title, $time = false ) {
1030 $img = wfFindFile( $title, $time );
1032 $img = wfLocalFile( $title );
1038 * Wrapper for wfFindFile(), for backwards-compatibility only.
1039 * Do not use in core code.
1041 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
1042 * @return image object or null if invalid title
1045 static function newFromName( $name ) {
1046 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
1047 if ( is_object( $title ) ) {
1048 $img = wfFindFile( $title );
1050 $img = wfLocalFile( $title );
1059 * Return the URL of an image, provided its name.
1061 * Backwards-compatibility for extensions.
1062 * Note that fromSharedDirectory will only use the shared path for files
1063 * that actually exist there now, and will return local paths otherwise.
1065 * @param string $name Name of the image, without the leading "Image:"
1066 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
1067 * @return string URL of $name image
1070 static function imageUrl( $name, $fromSharedDirectory = false ) {
1072 if( $fromSharedDirectory ) {
1073 $image = wfFindFile( $name );
1076 $image = wfLocalFile( $name );
1078 return $image->getUrl();
1082 #------------------------------------------------------------------------------
1085 * Helper class for file deletion
1087 class LocalFileDeleteBatch
{
1088 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch;
1091 function __construct( File
$file, $reason = '' ) {
1092 $this->file
= $file;
1093 $this->reason
= $reason;
1094 $this->status
= $file->repo
->newGood();
1097 function addCurrent() {
1098 $this->srcRels
['.'] = $this->file
->getRel();
1101 function addOld( $oldName ) {
1102 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1103 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1106 function getOldRels() {
1107 if ( !isset( $this->srcRels
['.'] ) ) {
1108 $oldRels =& $this->srcRels
;
1109 $deleteCurrent = false;
1111 $oldRels = $this->srcRels
;
1112 unset( $oldRels['.'] );
1113 $deleteCurrent = true;
1115 return array( $oldRels, $deleteCurrent );
1118 /*protected*/ function getHashes() {
1120 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1121 if ( $deleteCurrent ) {
1122 $hashes['.'] = $this->file
->getSha1();
1124 if ( count( $oldRels ) ) {
1125 $dbw = $this->file
->repo
->getMasterDB();
1126 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1127 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1129 while ( $row = $dbw->fetchObject( $res ) ) {
1130 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1131 // Get the hash from the file
1132 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1133 $props = $this->file
->repo
->getFileProps( $oldUrl );
1134 if ( $props['fileExists'] ) {
1135 // Upgrade the oldimage row
1136 $dbw->update( 'oldimage',
1137 array( 'oi_sha1' => $props['sha1'] ),
1138 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1140 $hashes[$row->oi_archive_name
] = $props['sha1'];
1142 $hashes[$row->oi_archive_name
] = false;
1145 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1149 $missing = array_diff_key( $this->srcRels
, $hashes );
1150 foreach ( $missing as $name => $rel ) {
1151 $this->status
->error( 'filedelete-old-unregistered', $name );
1153 foreach ( $hashes as $name => $hash ) {
1155 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1156 unset( $hashes[$name] );
1163 function doDBInserts() {
1165 $dbw = $this->file
->repo
->getMasterDB();
1166 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1167 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1168 $encReason = $dbw->addQuotes( $this->reason
);
1169 $encGroup = $dbw->addQuotes( 'deleted' );
1170 $ext = $this->file
->getExtension();
1171 $dotExt = $ext === '' ?
'' : ".$ext";
1172 $encExt = $dbw->addQuotes( $dotExt );
1173 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1175 if ( $deleteCurrent ) {
1176 $where = array( 'img_name' => $this->file
->getName() );
1177 $dbw->insertSelect( 'filearchive', 'image',
1179 'fa_storage_group' => $encGroup,
1180 'fa_storage_key' => "IF(img_sha1='', '', CONCAT(img_sha1,$encExt))",
1182 'fa_deleted_user' => $encUserId,
1183 'fa_deleted_timestamp' => $encTimestamp,
1184 'fa_deleted_reason' => $encReason,
1187 'fa_name' => 'img_name',
1188 'fa_archive_name' => 'NULL',
1189 'fa_size' => 'img_size',
1190 'fa_width' => 'img_width',
1191 'fa_height' => 'img_height',
1192 'fa_metadata' => 'img_metadata',
1193 'fa_bits' => 'img_bits',
1194 'fa_media_type' => 'img_media_type',
1195 'fa_major_mime' => 'img_major_mime',
1196 'fa_minor_mime' => 'img_minor_mime',
1197 'fa_description' => 'img_description',
1198 'fa_user' => 'img_user',
1199 'fa_user_text' => 'img_user_text',
1200 'fa_timestamp' => 'img_timestamp'
1201 ), $where, __METHOD__
);
1204 if ( count( $oldRels ) ) {
1206 'oi_name' => $this->file
->getName(),
1207 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1209 $dbw->insertSelect( 'filearchive', 'oldimage',
1211 'fa_storage_group' => $encGroup,
1212 'fa_storage_key' => "IF(oi_sha1='', '', CONCAT(oi_sha1,$encExt))",
1214 'fa_deleted_user' => $encUserId,
1215 'fa_deleted_timestamp' => $encTimestamp,
1216 'fa_deleted_reason' => $encReason,
1219 'fa_name' => 'oi_name',
1220 'fa_archive_name' => 'oi_archive_name',
1221 'fa_size' => 'oi_size',
1222 'fa_width' => 'oi_width',
1223 'fa_height' => 'oi_height',
1224 'fa_metadata' => 'oi_metadata',
1225 'fa_bits' => 'oi_bits',
1226 'fa_media_type' => 'oi_media_type',
1227 'fa_major_mime' => 'oi_major_mime',
1228 'fa_minor_mime' => 'oi_minor_mime',
1229 'fa_description' => 'oi_description',
1230 'fa_user' => 'oi_user',
1231 'fa_user_text' => 'oi_user_text',
1232 'fa_timestamp' => 'oi_timestamp'
1233 ), $where, __METHOD__
);
1237 function doDBDeletes() {
1238 $dbw = $this->file
->repo
->getMasterDB();
1239 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1240 if ( $deleteCurrent ) {
1241 $where = array( 'img_name' => $this->file
->getName() );
1242 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1244 if ( count( $oldRels ) ) {
1245 $dbw->delete( 'oldimage',
1247 'oi_name' => $this->file
->getName(),
1248 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1254 * Run the transaction
1256 function execute() {
1257 global $wgUser, $wgUseSquid;
1258 wfProfileIn( __METHOD__
);
1260 $this->file
->lock();
1262 // Prepare deletion batch
1263 $hashes = $this->getHashes();
1264 $this->deletionBatch
= array();
1265 $ext = $this->file
->getExtension();
1266 $dotExt = $ext === '' ?
'' : ".$ext";
1267 foreach ( $this->srcRels
as $name => $srcRel ) {
1268 // Skip files that have no hash (missing source)
1269 if ( isset( $hashes[$name] ) ) {
1270 $hash = $hashes[$name];
1271 $key = $hash . $dotExt;
1272 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1273 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1277 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1278 // We acquire this lock by running the inserts now, before the file operations.
1280 // This potentially has poor lock contention characteristics -- an alternative
1281 // scheme would be to insert stub filearchive entries with no fa_name and commit
1282 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1283 $this->doDBInserts();
1285 // Execute the file deletion batch
1286 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1287 if ( !$status->isGood() ) {
1288 $this->status
->merge( $status );
1291 if ( !$this->status
->ok
) {
1292 // Critical file deletion error
1293 // Roll back inserts, release lock and abort
1294 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1295 $this->file
->unlockAndRollback();
1296 return $this->status
;
1300 if ( $wgUseSquid ) {
1302 foreach ( $this->srcRels
as $srcRel ) {
1303 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1304 $urls[] = $this->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1306 SquidUpdate
::purge( $urls );
1309 // Delete image/oldimage rows
1310 $this->doDBDeletes();
1312 // Commit and return
1313 $this->file
->unlock();
1314 wfProfileOut( __METHOD__
);
1315 return $this->status
;
1319 #------------------------------------------------------------------------------
1322 * Helper class for file undeletion
1324 class LocalFileRestoreBatch
{
1325 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1327 function __construct( File
$file ) {
1328 $this->file
= $file;
1329 $this->cleanupBatch
= $this->ids
= array();
1330 $this->ids
= array();
1336 function addId( $fa_id ) {
1337 $this->ids
[] = $fa_id;
1341 * Add a whole lot of files by ID
1343 function addIds( $ids ) {
1344 $this->ids
= array_merge( $this->ids
, $ids );
1348 * Add all revisions of the file
1355 * Run the transaction, except the cleanup batch.
1356 * The cleanup batch should be run in a separate transaction, because it locks different
1357 * rows and there's no need to keep the image row locked while it's acquiring those locks
1358 * The caller may have its own transaction open.
1359 * So we save the batch and let the caller call cleanup()
1361 function execute() {
1362 global $wgUser, $wgLang;
1363 if ( !$this->all
&& !$this->ids
) {
1365 return $this->file
->repo
->newGood();
1368 $exists = $this->file
->lock();
1369 $dbw = $this->file
->repo
->getMasterDB();
1370 $status = $this->file
->repo
->newGood();
1372 // Fetch all or selected archived revisions for the file,
1373 // sorted from the most recent to the oldest.
1374 $conditions = array( 'fa_name' => $this->file
->getName() );
1376 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1379 $result = $dbw->select( 'filearchive', '*',
1382 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1384 $idsPresent = array();
1385 $storeBatch = array();
1386 $insertBatch = array();
1387 $insertCurrent = false;
1388 $deleteIds = array();
1390 $archiveNames = array();
1391 while( $row = $dbw->fetchObject( $result ) ) {
1392 $idsPresent[] = $row->fa_id
;
1393 if ( $this->unsuppress
) {
1394 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1395 } else if ( ($row->fa_deleted
& Revision
::DELETED_RESTRICTED
) && !$wgUser->isAllowed('hiderevision') ) {
1396 // Skip restoring file revisions that the user cannot restore
1399 if ( $row->fa_name
!= $this->file
->getName() ) {
1400 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1401 $status->failCount++
;
1404 if ( $row->fa_storage_key
== '' ) {
1405 // Revision was missing pre-deletion
1406 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1407 $status->failCount++
;
1411 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1412 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1414 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1416 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1417 $sha1 = substr( $sha1, 1 );
1420 if ( $first && !$exists ) {
1421 // This revision will be published as the new current version
1422 $destRel = $this->file
->getRel();
1423 $info = $this->file
->repo
->getFileProps( $deletedUrl );
1424 $insertCurrent = array(
1425 'img_name' => $row->fa_name
,
1426 'img_size' => $row->fa_size
,
1427 'img_width' => $row->fa_width
,
1428 'img_height' => $row->fa_height
,
1429 'img_metadata' => $row->fa_metadata
,
1430 'img_bits' => $row->fa_bits
,
1431 'img_media_type' => $row->fa_media_type
,
1432 'img_major_mime' => $row->fa_major_mime
,
1433 'img_minor_mime' => $row->fa_minor_mime
,
1434 'img_description' => $row->fa_description
,
1435 'img_user' => $row->fa_user
,
1436 'img_user_text' => $row->fa_user_text
,
1437 'img_timestamp' => $row->fa_timestamp
,
1438 'img_sha1' => $sha1);
1440 $archiveName = $row->fa_archive_name
;
1441 if( $archiveName == '' ) {
1442 // This was originally a current version; we
1443 // have to devise a new archive name for it.
1444 // Format is <timestamp of archiving>!<name>
1445 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1447 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1449 } while ( isset( $archiveNames[$archiveName] ) );
1451 $archiveNames[$archiveName] = true;
1452 $destRel = $this->file
->getArchiveRel( $archiveName );
1453 $insertBatch[] = array(
1454 'oi_name' => $row->fa_name
,
1455 'oi_archive_name' => $archiveName,
1456 'oi_size' => $row->fa_size
,
1457 'oi_width' => $row->fa_width
,
1458 'oi_height' => $row->fa_height
,
1459 'oi_bits' => $row->fa_bits
,
1460 'oi_description' => $row->fa_description
,
1461 'oi_user' => $row->fa_user
,
1462 'oi_user_text' => $row->fa_user_text
,
1463 'oi_timestamp' => $row->fa_timestamp
,
1464 'oi_metadata' => $row->fa_metadata
,
1465 'oi_media_type' => $row->fa_media_type
,
1466 'oi_major_mime' => $row->fa_major_mime
,
1467 'oi_minor_mime' => $row->fa_minor_mime
,
1468 'oi_deleted' => $row->fa_deleted
,
1469 'oi_sha1' => $sha1 );
1472 $deleteIds[] = $row->fa_id
;
1473 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1474 $this->cleanupBatch
[] = $row->fa_storage_key
;
1479 // Add a warning to the status object for missing IDs
1480 $missingIds = array_diff( $this->ids
, $idsPresent );
1481 foreach ( $missingIds as $id ) {
1482 $status->error( 'undelete-missing-filearchive', $id );
1485 // Run the store batch
1486 // Use the OVERWRITE_SAME flag to smooth over a common error
1487 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1488 $status->merge( $storeStatus );
1490 if ( !$status->ok
) {
1491 // Store batch returned a critical error -- this usually means nothing was stored
1492 // Stop now and return an error
1493 $this->file
->unlock();
1497 // Run the DB updates
1498 // Because we have locked the image row, key conflicts should be rare.
1499 // If they do occur, we can roll back the transaction at this time with
1500 // no data loss, but leaving unregistered files scattered throughout the
1502 // This is not ideal, which is why it's important to lock the image row.
1503 if ( $insertCurrent ) {
1504 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1506 if ( $insertBatch ) {
1507 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1510 $dbw->delete( 'filearchive',
1511 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1515 if( $status->successCount
> 0 ) {
1517 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1519 // Update site_stats
1520 $site_stats = $dbw->tableName( 'site_stats' );
1521 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1523 $this->file
->purgeEverything();
1525 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1526 $this->file
->purgeDescription();
1527 $this->file
->purgeHistory();
1530 $this->file
->unlock();
1535 * Delete unused files in the deleted zone.
1536 * This should be called from outside the transaction in which execute() was called.
1538 function cleanup() {
1539 if ( !$this->cleanupBatch
) {
1540 return $this->file
->repo
->newGood();
1542 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);