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 $decoded[substr( $name, $prefixLength )] = $value;
215 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
216 if ( empty( $decoded['major_mime'] ) ) {
217 $decoded['mime'] = "unknown/unknown";
219 if (!$decoded['minor_mime']) {
220 $decoded['minor_mime'] = "unknown";
222 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
224 # Trim zero padding from char/binary field
225 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
230 * Load file metadata from a DB result row
232 function loadFromRow( $row, $prefix = 'img_' ) {
233 $this->dataLoaded
= true;
234 $array = $this->decodeRow( $row, $prefix );
235 foreach ( $array as $name => $value ) {
236 $this->$name = $value;
238 $this->fileExists
= true;
239 // Check for rows from a previous schema, quietly upgrade them
240 $this->maybeUpgradeRow();
244 * Load file metadata from cache or DB, unless already loaded
247 if ( !$this->dataLoaded
) {
248 if ( !$this->loadFromCache() ) {
250 $this->saveToCache();
252 $this->dataLoaded
= true;
257 * Upgrade a row if it needs it
259 function maybeUpgradeRow() {
260 if ( wfReadOnly() ) {
263 if ( is_null($this->media_type
) ||
264 $this->mime
== 'image/svg'
267 $this->upgraded
= true;
269 $handler = $this->getHandler();
270 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
272 $this->upgraded
= true;
277 function getUpgraded() {
278 return $this->upgraded
;
282 * Fix assorted version-related problems with the image row by reloading it from the file
284 function upgradeRow() {
285 wfProfileIn( __METHOD__
);
287 $this->loadFromFile();
289 # Don't destroy file info of missing files
290 if ( !$this->fileExists
) {
291 wfDebug( __METHOD__
.": file does not exist, aborting\n" );
294 $dbw = $this->repo
->getMasterDB();
295 list( $major, $minor ) = self
::splitMime( $this->mime
);
297 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
299 $dbw->update( 'image',
301 'img_width' => $this->width
,
302 'img_height' => $this->height
,
303 'img_bits' => $this->bits
,
304 'img_media_type' => $this->media_type
,
305 'img_major_mime' => $major,
306 'img_minor_mime' => $minor,
307 'img_metadata' => $this->metadata
,
308 'img_sha1' => $this->sha1
,
309 ), array( 'img_name' => $this->getName() ),
312 $this->saveToCache();
313 wfProfileOut( __METHOD__
);
316 function setProps( $info ) {
317 $this->dataLoaded
= true;
318 $fields = $this->getCacheFields( '' );
319 $fields[] = 'fileExists';
320 foreach ( $fields as $field ) {
321 if ( isset( $info[$field] ) ) {
322 $this->$field = $info[$field];
325 // Fix up mime fields
326 if ( isset( $info['major_mime'] ) ) {
327 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
328 } elseif ( isset( $info['mime'] ) ) {
329 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
333 /** splitMime inherited */
334 /** getName inherited */
335 /** getTitle inherited */
336 /** getURL inherited */
337 /** getViewURL inherited */
338 /** getPath inherited */
341 * Return the width of the image
343 * Returns false on error
346 function getWidth( $page = 1 ) {
348 if ( $this->isMultipage() ) {
349 $dim = $this->getHandler()->getPageDimensions( $this, $page );
351 return $dim['width'];
361 * Return the height of the image
363 * Returns false on error
366 function getHeight( $page = 1 ) {
368 if ( $this->isMultipage() ) {
369 $dim = $this->getHandler()->getPageDimensions( $this, $page );
371 return $dim['height'];
376 return $this->height
;
381 * Get handler-specific metadata
383 function getMetadata() {
385 return $this->metadata
;
389 * Return the size of the image file, in bytes
398 * Returns the mime type of the file.
400 function getMimeType() {
406 * Return the type of the media in the file.
407 * Use the value returned by this function with the MEDIATYPE_xxx constants.
409 function getMediaType() {
411 return $this->media_type
;
414 /** canRender inherited */
415 /** mustRender inherited */
416 /** allowInlineDisplay inherited */
417 /** isSafeFile inherited */
418 /** isTrustedFile inherited */
421 * Returns true if the file file exists on disk.
422 * @return boolean Whether file file exist on disk.
427 return $this->fileExists
;
430 /** getTransformScript inherited */
431 /** getUnscaledThumb inherited */
432 /** thumbName inherited */
433 /** createThumb inherited */
434 /** getThumbnail inherited */
435 /** transform inherited */
438 * Fix thumbnail files from 1.4 or before, with extreme prejudice
440 function migrateThumbFile( $thumbName ) {
441 $thumbDir = $this->getThumbPath();
442 $thumbPath = "$thumbDir/$thumbName";
443 if ( is_dir( $thumbPath ) ) {
444 // Directory where file should be
445 // This happened occasionally due to broken migration code in 1.5
446 // Rename to broken-*
447 for ( $i = 0; $i < 100 ; $i++
) {
448 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
449 if ( !file_exists( $broken ) ) {
450 rename( $thumbPath, $broken );
454 // Doesn't exist anymore
457 if ( is_file( $thumbDir ) ) {
458 // File where directory should be
460 // Doesn't exist anymore
465 /** getHandler inherited */
466 /** iconThumb inherited */
467 /** getLastError inherited */
470 * Get all thumbnail names previously generated for this file
472 function getThumbnails() {
473 if ( $this->isHashed() ) {
476 $dir = $this->getThumbPath();
478 if ( is_dir( $dir ) ) {
479 $handle = opendir( $dir );
482 while ( false !== ( $file = readdir($handle) ) ) {
483 if ( $file{0} != '.' ) {
498 * Refresh metadata in memcached, but don't touch thumbnails or squid
500 function purgeMetadataCache() {
502 $this->saveToCache();
503 $this->purgeHistory();
507 * Purge the shared history (OldLocalFile) cache
509 function purgeHistory() {
511 $hashedName = md5($this->getName());
512 $oldKey = wfMemcKey( 'oldfile', $hashedName );
513 $wgMemc->delete( $oldKey );
517 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
519 function purgeCache() {
520 // Refresh metadata cache
521 $this->purgeMetadataCache();
524 $this->purgeThumbnails();
526 // Purge squid cache for this file
527 wfPurgeSquidServers( array( $this->getURL() ) );
531 * Delete cached transformed files
533 function purgeThumbnails() {
536 $files = $this->getThumbnails();
537 $dir = $this->getThumbPath();
539 foreach ( $files as $file ) {
540 # Check that the base file name is part of the thumb name
541 # This is a basic sanity check to avoid erasing unrelated directories
542 if ( strpos( $file, $this->getName() ) !== false ) {
543 $url = $this->getThumbUrl( $file );
545 @unlink
( "$dir/$file" );
551 wfPurgeSquidServers( $urls );
555 /** purgeDescription inherited */
556 /** purgeEverything inherited */
559 * Return the history of this file, line by line.
560 * starts with current version, then old versions.
561 * uses $this->historyLine to check which line to return:
562 * 0 return line for current version
563 * 1 query for old versions, return first one
564 * 2, ... return next old version from above query
568 function nextHistoryLine() {
569 $dbr = $this->repo
->getSlaveDB();
571 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
572 $this->historyRes
= $dbr->select( 'image',
575 "'' AS oi_archive_name"
577 array( 'img_name' => $this->title
->getDBkey() ),
580 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
581 $dbr->freeResult($this->historyRes
);
582 $this->historyRes
= null;
585 } else if ( $this->historyLine
== 1 ) {
586 $dbr->freeResult($this->historyRes
);
587 $this->historyRes
= $dbr->select( 'oldimage', '*',
588 array( 'oi_name' => $this->title
->getDBkey() ),
590 array( 'ORDER BY' => 'oi_timestamp DESC' )
593 $this->historyLine ++
;
595 return $dbr->fetchObject( $this->historyRes
);
599 * Reset the history pointer to the first element of the history
602 function resetHistory() {
603 $this->historyLine
= 0;
604 if (!is_null($this->historyRes
)) {
605 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
606 $this->historyRes
= null;
610 /** getFullPath inherited */
611 /** getHashPath inherited */
612 /** getRel inherited */
613 /** getUrlRel inherited */
614 /** getArchiveRel inherited */
615 /** getThumbRel inherited */
616 /** getArchivePath inherited */
617 /** getThumbPath inherited */
618 /** getArchiveUrl inherited */
619 /** getThumbUrl inherited */
620 /** getArchiveVirtualUrl inherited */
621 /** getThumbVirtualUrl inherited */
622 /** isHashed inherited */
625 * Upload a file and record it in the DB
626 * @param string $srcPath Source path or virtual URL
627 * @param string $comment Upload description
628 * @param string $pageText Text to use for the new description page, if a new description page is created
629 * @param integer $flags Flags for publish()
630 * @param array $props File properties, if known. This can be used to reduce the
631 * upload time when uploading virtual URLs for which the file info
633 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
635 * @return FileRepoStatus object. On success, the value member contains the
636 * archive name, or an empty string if it was a new file.
638 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
640 $status = $this->publish( $srcPath, $flags );
642 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
643 $status->fatal( 'filenotfound', $srcPath );
651 * Record a file upload in the upload log and the image table
652 * @deprecated use upload()
654 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
655 $watch = false, $timestamp = false )
657 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
658 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
663 $wgUser->addWatch( $this->getTitle() );
670 * Record a file upload in the upload log and the image table
672 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
676 $dbw = $this->repo
->getMasterDB();
679 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
681 $this->setProps( $props );
683 // Delete thumbnails and refresh the metadata cache
684 $this->purgeThumbnails();
685 $this->saveToCache();
686 wfPurgeSquidServers( array( $this->getURL() ) );
688 // Fail now if the file isn't there
689 if ( !$this->fileExists
) {
690 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
695 if ( $timestamp === false ) {
696 $timestamp = $dbw->timestamp();
699 # Test to see if the row exists using INSERT IGNORE
700 # This avoids race conditions by locking the row until the commit, and also
701 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
702 $dbw->insert( 'image',
704 'img_name' => $this->getName(),
705 'img_size'=> $this->size
,
706 'img_width' => intval( $this->width
),
707 'img_height' => intval( $this->height
),
708 'img_bits' => $this->bits
,
709 'img_media_type' => $this->media_type
,
710 'img_major_mime' => $this->major_mime
,
711 'img_minor_mime' => $this->minor_mime
,
712 'img_timestamp' => $timestamp,
713 'img_description' => $comment,
714 'img_user' => $wgUser->getID(),
715 'img_user_text' => $wgUser->getName(),
716 'img_metadata' => $this->metadata
,
717 'img_sha1' => $this->sha1
723 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 $action = $reupload ?
'overwrite' : 'upload';
781 $log->addEntry( $action, $descTitle, $comment );
783 if( $descTitle->exists() ) {
784 # Create a null revision
785 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
786 $nullRevision->insertOn( $dbw );
787 $article->updateRevisionOn( $dbw, $nullRevision );
789 # Invalidate the cache for the description page
790 $descTitle->invalidateCache();
791 $descTitle->purgeSquid();
793 // New file; create the description page.
794 // There's already a log entry, so don't make a second RC entry
795 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
798 # Hooks, hooks, the magic of hooks...
799 wfRunHooks( 'FileUpload', array( $this ) );
801 # Commit the transaction now, in case something goes wrong later
802 # The most important thing is that files don't get lost, especially archives
803 $dbw->immediateCommit();
805 # Invalidate cache for all pages using this file
806 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
813 * Move or copy a file to its public location. If a file exists at the
814 * destination, move it to an archive. Returns the archive name on success
815 * or an empty string if it was a new file, and a wikitext-formatted
816 * WikiError object on failure.
818 * The archive name should be passed through to recordUpload for database
821 * @param string $sourcePath Local filesystem path to the source image
822 * @param integer $flags A bitwise combination of:
823 * File::DELETE_SOURCE Delete the source file, i.e. move
825 * @return FileRepoStatus object. On success, the value member contains the
826 * archive name, or an empty string if it was a new file.
828 function publish( $srcPath, $flags = 0 ) {
830 $dstRel = $this->getRel();
831 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
832 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
833 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
834 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
835 if ( $status->value
== 'new' ) {
838 $status->value
= $archiveName;
844 /** getLinksTo inherited */
845 /** getExifData inherited */
846 /** isLocal inherited */
847 /** wasDeleted inherited */
850 * Delete all versions of the file.
852 * Moves the files into an archive directory (or deletes them)
853 * and removes the database rows.
855 * Cache purging is done; logging is caller's responsibility.
858 * @return FileRepoStatus object.
860 function delete( $reason ) {
862 $batch = new LocalFileDeleteBatch( $this, $reason );
863 $batch->addCurrent();
865 # Get old version relative paths
866 $dbw = $this->repo
->getMasterDB();
867 $result = $dbw->select( 'oldimage',
868 array( 'oi_archive_name' ),
869 array( 'oi_name' => $this->getName() ) );
870 while ( $row = $dbw->fetchObject( $result ) ) {
871 $batch->addOld( $row->oi_archive_name
);
873 $status = $batch->execute();
877 $site_stats = $dbw->tableName( 'site_stats' );
878 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
879 $this->purgeEverything();
887 * Delete an old version of the file.
889 * Moves the file into an archive directory (or deletes it)
890 * and removes the database row.
892 * Cache purging is done; logging is caller's responsibility.
895 * @throws MWException or FSException on database or filestore failure
896 * @return FileRepoStatus object.
898 function deleteOld( $archiveName, $reason ) {
900 $batch = new LocalFileDeleteBatch( $this, $reason );
901 $batch->addOld( $archiveName );
902 $status = $batch->execute();
905 $this->purgeDescription();
906 $this->purgeHistory();
912 * Restore all or specified deleted revisions to the given file.
913 * Permissions and logging are left to the caller.
915 * May throw database exceptions on error.
917 * @param $versions set of record ids of deleted items to restore,
918 * or empty to restore all revisions.
919 * @return FileRepoStatus
921 function restore( $versions = array(), $unsuppress = false ) {
922 $batch = new LocalFileRestoreBatch( $this );
926 $batch->addIds( $versions );
928 $status = $batch->execute();
929 if ( !$status->ok
) {
933 $cleanupStatus = $batch->cleanup();
934 $cleanupStatus->successCount
= 0;
935 $cleanupStatus->failCount
= 0;
936 $status->merge( $cleanupStatus );
940 /** isMultipage inherited */
941 /** pageCount inherited */
942 /** scaleHeight inherited */
943 /** getImageSize inherited */
946 * Get the URL of the file description page.
948 function getDescriptionUrl() {
949 return $this->title
->getLocalUrl();
953 * Get the HTML text of the description page
954 * This is not used by ImagePage for local files, since (among other things)
955 * it skips the parser cache.
957 function getDescriptionText() {
959 $revision = Revision
::newFromTitle( $this->title
);
960 if ( !$revision ) return false;
961 $text = $revision->getText();
962 if ( !$text ) return false;
963 $html = $wgParser->parse( $text, new ParserOptions
);
967 function getTimestamp() {
969 return $this->timestamp
;
974 // Initialise now if necessary
975 if ( $this->sha1
== '' && $this->fileExists
) {
976 $this->sha1
= File
::sha1Base36( $this->getPath() );
977 if ( strval( $this->sha1
) != '' ) {
978 $dbw = $this->repo
->getMasterDB();
979 $dbw->update( 'image',
980 array( 'img_sha1' => $this->sha1
),
981 array( 'img_name' => $this->getName() ),
983 $this->saveToCache();
991 * Start a transaction and lock the image for update
992 * Increments a reference counter if the lock is already held
993 * @return boolean True if the image exists, false otherwise
996 $dbw = $this->repo
->getMasterDB();
997 if ( !$this->locked
) {
1001 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1005 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1006 * the transaction and thereby releases the image lock.
1009 if ( $this->locked
) {
1011 if ( !$this->locked
) {
1012 $dbw = $this->repo
->getMasterDB();
1019 * Roll back the DB transaction and mark the image unlocked
1021 function unlockAndRollback() {
1022 $this->locked
= false;
1023 $dbw = $this->repo
->getMasterDB();
1026 } // LocalFile class
1028 #------------------------------------------------------------------------------
1031 * Backwards compatibility class
1033 class Image
extends LocalFile
{
1034 function __construct( $title ) {
1035 $repo = RepoGroup
::singleton()->getLocalRepo();
1036 parent
::__construct( $title, $repo );
1040 * Wrapper for wfFindFile(), for backwards-compatibility only
1041 * Do not use in core code.
1044 static function newFromTitle( $title, $time = false ) {
1045 $img = wfFindFile( $title, $time );
1047 $img = wfLocalFile( $title );
1053 * Wrapper for wfFindFile(), for backwards-compatibility only.
1054 * Do not use in core code.
1056 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
1057 * @return image object or null if invalid title
1060 static function newFromName( $name ) {
1061 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
1062 if ( is_object( $title ) ) {
1063 $img = wfFindFile( $title );
1065 $img = wfLocalFile( $title );
1074 * Return the URL of an image, provided its name.
1076 * Backwards-compatibility for extensions.
1077 * Note that fromSharedDirectory will only use the shared path for files
1078 * that actually exist there now, and will return local paths otherwise.
1080 * @param string $name Name of the image, without the leading "Image:"
1081 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
1082 * @return string URL of $name image
1085 static function imageUrl( $name, $fromSharedDirectory = false ) {
1087 if( $fromSharedDirectory ) {
1088 $image = wfFindFile( $name );
1091 $image = wfLocalFile( $name );
1093 return $image->getUrl();
1097 #------------------------------------------------------------------------------
1100 * Helper class for file deletion
1102 class LocalFileDeleteBatch
{
1103 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch;
1106 function __construct( File
$file, $reason = '' ) {
1107 $this->file
= $file;
1108 $this->reason
= $reason;
1109 $this->status
= $file->repo
->newGood();
1112 function addCurrent() {
1113 $this->srcRels
['.'] = $this->file
->getRel();
1116 function addOld( $oldName ) {
1117 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1118 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1121 function getOldRels() {
1122 if ( !isset( $this->srcRels
['.'] ) ) {
1123 $oldRels =& $this->srcRels
;
1124 $deleteCurrent = false;
1126 $oldRels = $this->srcRels
;
1127 unset( $oldRels['.'] );
1128 $deleteCurrent = true;
1130 return array( $oldRels, $deleteCurrent );
1133 /*protected*/ function getHashes() {
1135 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1136 if ( $deleteCurrent ) {
1137 $hashes['.'] = $this->file
->getSha1();
1139 if ( count( $oldRels ) ) {
1140 $dbw = $this->file
->repo
->getMasterDB();
1141 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1142 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1144 while ( $row = $dbw->fetchObject( $res ) ) {
1145 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1146 // Get the hash from the file
1147 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1148 $props = $this->file
->repo
->getFileProps( $oldUrl );
1149 if ( $props['fileExists'] ) {
1150 // Upgrade the oldimage row
1151 $dbw->update( 'oldimage',
1152 array( 'oi_sha1' => $props['sha1'] ),
1153 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1155 $hashes[$row->oi_archive_name
] = $props['sha1'];
1157 $hashes[$row->oi_archive_name
] = false;
1160 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1164 $missing = array_diff_key( $this->srcRels
, $hashes );
1165 foreach ( $missing as $name => $rel ) {
1166 $this->status
->error( 'filedelete-old-unregistered', $name );
1168 foreach ( $hashes as $name => $hash ) {
1170 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1171 unset( $hashes[$name] );
1178 function doDBInserts() {
1180 $dbw = $this->file
->repo
->getMasterDB();
1181 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1182 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1183 $encReason = $dbw->addQuotes( $this->reason
);
1184 $encGroup = $dbw->addQuotes( 'deleted' );
1185 $ext = $this->file
->getExtension();
1186 $dotExt = $ext === '' ?
'' : ".$ext";
1187 $encExt = $dbw->addQuotes( $dotExt );
1188 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1190 if ( $deleteCurrent ) {
1191 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1192 $where = array( 'img_name' => $this->file
->getName() );
1193 $dbw->insertSelect( 'filearchive', 'image',
1195 'fa_storage_group' => $encGroup,
1196 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1197 'fa_deleted_user' => $encUserId,
1198 'fa_deleted_timestamp' => $encTimestamp,
1199 'fa_deleted_reason' => $encReason,
1202 'fa_name' => 'img_name',
1203 'fa_archive_name' => 'NULL',
1204 'fa_size' => 'img_size',
1205 'fa_width' => 'img_width',
1206 'fa_height' => 'img_height',
1207 'fa_metadata' => 'img_metadata',
1208 'fa_bits' => 'img_bits',
1209 'fa_media_type' => 'img_media_type',
1210 'fa_major_mime' => 'img_major_mime',
1211 'fa_minor_mime' => 'img_minor_mime',
1212 'fa_description' => 'img_description',
1213 'fa_user' => 'img_user',
1214 'fa_user_text' => 'img_user_text',
1215 'fa_timestamp' => 'img_timestamp'
1216 ), $where, __METHOD__
);
1219 if ( count( $oldRels ) ) {
1220 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1222 'oi_name' => $this->file
->getName(),
1223 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1224 $dbw->insertSelect( 'filearchive', 'oldimage',
1226 'fa_storage_group' => $encGroup,
1227 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1228 'fa_deleted_user' => $encUserId,
1229 'fa_deleted_timestamp' => $encTimestamp,
1230 'fa_deleted_reason' => $encReason,
1233 'fa_name' => 'oi_name',
1234 'fa_archive_name' => 'oi_archive_name',
1235 'fa_size' => 'oi_size',
1236 'fa_width' => 'oi_width',
1237 'fa_height' => 'oi_height',
1238 'fa_metadata' => 'oi_metadata',
1239 'fa_bits' => 'oi_bits',
1240 'fa_media_type' => 'oi_media_type',
1241 'fa_major_mime' => 'oi_major_mime',
1242 'fa_minor_mime' => 'oi_minor_mime',
1243 'fa_description' => 'oi_description',
1244 'fa_user' => 'oi_user',
1245 'fa_user_text' => 'oi_user_text',
1246 'fa_timestamp' => 'oi_timestamp'
1247 ), $where, __METHOD__
);
1251 function doDBDeletes() {
1252 $dbw = $this->file
->repo
->getMasterDB();
1253 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1254 if ( $deleteCurrent ) {
1255 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1257 if ( count( $oldRels ) ) {
1258 $dbw->delete( 'oldimage',
1260 'oi_name' => $this->file
->getName(),
1261 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1267 * Run the transaction
1269 function execute() {
1270 global $wgUser, $wgUseSquid;
1271 wfProfileIn( __METHOD__
);
1273 $this->file
->lock();
1275 // Prepare deletion batch
1276 $hashes = $this->getHashes();
1277 $this->deletionBatch
= array();
1278 $ext = $this->file
->getExtension();
1279 $dotExt = $ext === '' ?
'' : ".$ext";
1280 foreach ( $this->srcRels
as $name => $srcRel ) {
1281 // Skip files that have no hash (missing source)
1282 if ( isset( $hashes[$name] ) ) {
1283 $hash = $hashes[$name];
1284 $key = $hash . $dotExt;
1285 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1286 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1290 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1291 // We acquire this lock by running the inserts now, before the file operations.
1293 // This potentially has poor lock contention characteristics -- an alternative
1294 // scheme would be to insert stub filearchive entries with no fa_name and commit
1295 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1296 $this->doDBInserts();
1298 // Execute the file deletion batch
1299 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1300 if ( !$status->isGood() ) {
1301 $this->status
->merge( $status );
1304 if ( !$this->status
->ok
) {
1305 // Critical file deletion error
1306 // Roll back inserts, release lock and abort
1307 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1308 $this->file
->unlockAndRollback();
1309 return $this->status
;
1313 if ( $wgUseSquid ) {
1315 foreach ( $this->srcRels
as $srcRel ) {
1316 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1317 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1319 SquidUpdate
::purge( $urls );
1322 // Delete image/oldimage rows
1323 $this->doDBDeletes();
1325 // Commit and return
1326 $this->file
->unlock();
1327 wfProfileOut( __METHOD__
);
1328 return $this->status
;
1332 #------------------------------------------------------------------------------
1335 * Helper class for file undeletion
1337 class LocalFileRestoreBatch
{
1338 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1340 function __construct( File
$file ) {
1341 $this->file
= $file;
1342 $this->cleanupBatch
= $this->ids
= array();
1343 $this->ids
= array();
1349 function addId( $fa_id ) {
1350 $this->ids
[] = $fa_id;
1354 * Add a whole lot of files by ID
1356 function addIds( $ids ) {
1357 $this->ids
= array_merge( $this->ids
, $ids );
1361 * Add all revisions of the file
1368 * Run the transaction, except the cleanup batch.
1369 * The cleanup batch should be run in a separate transaction, because it locks different
1370 * rows and there's no need to keep the image row locked while it's acquiring those locks
1371 * The caller may have its own transaction open.
1372 * So we save the batch and let the caller call cleanup()
1374 function execute() {
1375 global $wgUser, $wgLang;
1376 if ( !$this->all
&& !$this->ids
) {
1378 return $this->file
->repo
->newGood();
1381 $exists = $this->file
->lock();
1382 $dbw = $this->file
->repo
->getMasterDB();
1383 $status = $this->file
->repo
->newGood();
1385 // Fetch all or selected archived revisions for the file,
1386 // sorted from the most recent to the oldest.
1387 $conditions = array( 'fa_name' => $this->file
->getName() );
1389 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1392 $result = $dbw->select( 'filearchive', '*',
1395 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1397 $idsPresent = array();
1398 $storeBatch = array();
1399 $insertBatch = array();
1400 $insertCurrent = false;
1401 $deleteIds = array();
1403 $archiveNames = array();
1404 while( $row = $dbw->fetchObject( $result ) ) {
1405 $idsPresent[] = $row->fa_id
;
1406 if ( $this->unsuppress
) {
1407 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1408 } else if ( ($row->fa_deleted
& Revision
::DELETED_RESTRICTED
) && !$wgUser->isAllowed('hiderevision') ) {
1409 // Skip restoring file revisions that the user cannot restore
1412 if ( $row->fa_name
!= $this->file
->getName() ) {
1413 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1414 $status->failCount++
;
1417 if ( $row->fa_storage_key
== '' ) {
1418 // Revision was missing pre-deletion
1419 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1420 $status->failCount++
;
1424 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1425 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1427 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1429 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1430 $sha1 = substr( $sha1, 1 );
1433 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1434 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1435 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1436 ||
is_null( $row->fa_metadata
) ) {
1437 // Refresh our metadata
1438 // Required for a new current revision; nice for older ones too. :)
1439 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1442 'minor_mime' => $row->fa_minor_mime
,
1443 'major_mime' => $row->fa_major_mime
,
1444 'media_type' => $row->fa_media_type
,
1445 'metadata' => $row->fa_metadata
);
1448 if ( $first && !$exists ) {
1449 // This revision will be published as the new current version
1450 $destRel = $this->file
->getRel();
1451 $insertCurrent = array(
1452 'img_name' => $row->fa_name
,
1453 'img_size' => $row->fa_size
,
1454 'img_width' => $row->fa_width
,
1455 'img_height' => $row->fa_height
,
1456 'img_metadata' => $props['metadata'],
1457 'img_bits' => $row->fa_bits
,
1458 'img_media_type' => $props['media_type'],
1459 'img_major_mime' => $props['major_mime'],
1460 'img_minor_mime' => $props['minor_mime'],
1461 'img_description' => $row->fa_description
,
1462 'img_user' => $row->fa_user
,
1463 'img_user_text' => $row->fa_user_text
,
1464 'img_timestamp' => $row->fa_timestamp
,
1465 'img_sha1' => $sha1);
1467 $archiveName = $row->fa_archive_name
;
1468 if( $archiveName == '' ) {
1469 // This was originally a current version; we
1470 // have to devise a new archive name for it.
1471 // Format is <timestamp of archiving>!<name>
1472 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1474 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1476 } while ( isset( $archiveNames[$archiveName] ) );
1478 $archiveNames[$archiveName] = true;
1479 $destRel = $this->file
->getArchiveRel( $archiveName );
1480 $insertBatch[] = array(
1481 'oi_name' => $row->fa_name
,
1482 'oi_archive_name' => $archiveName,
1483 'oi_size' => $row->fa_size
,
1484 'oi_width' => $row->fa_width
,
1485 'oi_height' => $row->fa_height
,
1486 'oi_bits' => $row->fa_bits
,
1487 'oi_description' => $row->fa_description
,
1488 'oi_user' => $row->fa_user
,
1489 'oi_user_text' => $row->fa_user_text
,
1490 'oi_timestamp' => $row->fa_timestamp
,
1491 'oi_metadata' => $props['metadata'],
1492 'oi_media_type' => $props['media_type'],
1493 'oi_major_mime' => $props['major_mime'],
1494 'oi_minor_mime' => $props['minor_mime'],
1495 'oi_deleted' => $row->fa_deleted
,
1496 'oi_sha1' => $sha1 );
1499 $deleteIds[] = $row->fa_id
;
1500 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1501 $this->cleanupBatch
[] = $row->fa_storage_key
;
1506 // Add a warning to the status object for missing IDs
1507 $missingIds = array_diff( $this->ids
, $idsPresent );
1508 foreach ( $missingIds as $id ) {
1509 $status->error( 'undelete-missing-filearchive', $id );
1512 // Run the store batch
1513 // Use the OVERWRITE_SAME flag to smooth over a common error
1514 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1515 $status->merge( $storeStatus );
1517 if ( !$status->ok
) {
1518 // Store batch returned a critical error -- this usually means nothing was stored
1519 // Stop now and return an error
1520 $this->file
->unlock();
1524 // Run the DB updates
1525 // Because we have locked the image row, key conflicts should be rare.
1526 // If they do occur, we can roll back the transaction at this time with
1527 // no data loss, but leaving unregistered files scattered throughout the
1529 // This is not ideal, which is why it's important to lock the image row.
1530 if ( $insertCurrent ) {
1531 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1533 if ( $insertBatch ) {
1534 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1537 $dbw->delete( 'filearchive',
1538 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1542 if( $status->successCount
> 0 ) {
1544 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1546 // Update site_stats
1547 $site_stats = $dbw->tableName( 'site_stats' );
1548 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1550 $this->file
->purgeEverything();
1552 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1553 $this->file
->purgeDescription();
1554 $this->file
->purgeHistory();
1557 $this->file
->unlock();
1562 * Delete unused files in the deleted zone.
1563 * This should be called from outside the transaction in which execute() was called.
1565 function cleanup() {
1566 if ( !$this->cleanupBatch
) {
1567 return $this->file
->repo
->newGood();
1569 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);