6 * Bump this number when serialized cache records may be incompatible.
8 define( 'MW_FILE_VERSION', 7 );
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 $user, $user_text, # User, who uploaded the file
48 $description, # Description of current revision of the file
49 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
50 $upgraded, # Whether the row was upgraded on load
51 $locked, # True if the image row is locked
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 static function newFromTitle( $title, $repo ) {
61 return new self( $title, $repo );
65 * Create a LocalFile from a title
66 * Do not call this except from inside a repo class.
68 static function newFromRow( $row, $repo ) {
69 $title = Title
::makeTitle( NS_IMAGE
, $row->img_name
);
70 $file = new self( $title, $repo );
71 $file->loadFromRow( $row );
77 * Do not call this except from inside a repo class.
79 function __construct( $title, $repo ) {
80 if( !is_object( $title ) ) {
81 throw new MWException( __CLASS__
.' constructor given bogus title.' );
83 parent
::__construct( $title, $repo );
85 $this->historyLine
= 0;
86 $this->historyRes
= null;
87 $this->dataLoaded
= false;
91 * Get the memcached key
93 function getCacheKey() {
94 $hashedName = md5($this->getName());
95 return wfMemcKey( 'file', $hashedName );
99 * Try to load file metadata from memcached. Returns true on success.
101 function loadFromCache() {
103 wfProfileIn( __METHOD__
);
104 $this->dataLoaded
= false;
105 $key = $this->getCacheKey();
109 $cachedValues = $wgMemc->get( $key );
111 // Check if the key existed and belongs to this version of MediaWiki
112 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
113 wfDebug( "Pulling file metadata from cache key $key\n" );
114 $this->fileExists
= $cachedValues['fileExists'];
115 if ( $this->fileExists
) {
116 $this->setProps( $cachedValues );
118 $this->dataLoaded
= true;
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', 'user', 'user_text', 'description' );
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
->getMasterDB();
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 $this->maybeUpgradeRow();
243 * Load file metadata from cache or DB, unless already loaded
246 if ( !$this->dataLoaded
) {
247 if ( !$this->loadFromCache() ) {
249 $this->saveToCache();
251 $this->dataLoaded
= true;
256 * Upgrade a row if it needs it
258 function maybeUpgradeRow() {
259 if ( wfReadOnly() ) {
262 if ( is_null($this->media_type
) ||
263 $this->mime
== 'image/svg'
266 $this->upgraded
= true;
268 $handler = $this->getHandler();
269 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
271 $this->upgraded
= true;
276 function getUpgraded() {
277 return $this->upgraded
;
281 * Fix assorted version-related problems with the image row by reloading it from the file
283 function upgradeRow() {
284 wfProfileIn( __METHOD__
);
286 $this->loadFromFile();
288 # Don't destroy file info of missing files
289 if ( !$this->fileExists
) {
290 wfDebug( __METHOD__
.": file does not exist, aborting\n" );
293 $dbw = $this->repo
->getMasterDB();
294 list( $major, $minor ) = self
::splitMime( $this->mime
);
296 if ( wfReadOnly() ) {
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__
);
319 * Set properties in this object to be equal to those given in the
320 * associative array $info. Only cacheable fields can be set.
322 * If 'mime' is given, it will be split into major_mime/minor_mime.
323 * If major_mime/minor_mime are given, $this->mime will also be set.
325 function setProps( $info ) {
326 $this->dataLoaded
= true;
327 $fields = $this->getCacheFields( '' );
328 $fields[] = 'fileExists';
329 foreach ( $fields as $field ) {
330 if ( isset( $info[$field] ) ) {
331 $this->$field = $info[$field];
334 // Fix up mime fields
335 if ( isset( $info['major_mime'] ) ) {
336 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
337 } elseif ( isset( $info['mime'] ) ) {
338 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
342 /** splitMime inherited */
343 /** getName inherited */
344 /** getTitle inherited */
345 /** getURL inherited */
346 /** getViewURL inherited */
347 /** getPath inherited */
348 /** isVisible inhereted */
351 * Return the width of the image
353 * Returns false on error
356 function getWidth( $page = 1 ) {
358 if ( $this->isMultipage() ) {
359 $dim = $this->getHandler()->getPageDimensions( $this, $page );
361 return $dim['width'];
371 * Return the height of the image
373 * Returns false on error
376 function getHeight( $page = 1 ) {
378 if ( $this->isMultipage() ) {
379 $dim = $this->getHandler()->getPageDimensions( $this, $page );
381 return $dim['height'];
386 return $this->height
;
391 * Returns ID or name of user who uploaded the file
393 * @param $type string 'text' or 'id'
395 function getUser($type='text') {
397 if( $type == 'text' ) {
398 return $this->user_text
;
399 } elseif( $type == 'id' ) {
405 * Get handler-specific metadata
407 function getMetadata() {
409 return $this->metadata
;
413 * Return the size of the image file, in bytes
422 * Returns the mime type of the file.
424 function getMimeType() {
430 * Return the type of the media in the file.
431 * Use the value returned by this function with the MEDIATYPE_xxx constants.
433 function getMediaType() {
435 return $this->media_type
;
438 /** canRender inherited */
439 /** mustRender inherited */
440 /** allowInlineDisplay inherited */
441 /** isSafeFile inherited */
442 /** isTrustedFile inherited */
445 * Returns true if the file file exists on disk.
446 * @return boolean Whether file file exist on disk.
451 return $this->fileExists
;
454 /** getTransformScript inherited */
455 /** getUnscaledThumb inherited */
456 /** thumbName inherited */
457 /** createThumb inherited */
458 /** getThumbnail inherited */
459 /** transform inherited */
462 * Fix thumbnail files from 1.4 or before, with extreme prejudice
464 function migrateThumbFile( $thumbName ) {
465 $thumbDir = $this->getThumbPath();
466 $thumbPath = "$thumbDir/$thumbName";
467 if ( is_dir( $thumbPath ) ) {
468 // Directory where file should be
469 // This happened occasionally due to broken migration code in 1.5
470 // Rename to broken-*
471 for ( $i = 0; $i < 100 ; $i++
) {
472 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
473 if ( !file_exists( $broken ) ) {
474 rename( $thumbPath, $broken );
478 // Doesn't exist anymore
481 if ( is_file( $thumbDir ) ) {
482 // File where directory should be
484 // Doesn't exist anymore
489 /** getHandler inherited */
490 /** iconThumb inherited */
491 /** getLastError inherited */
494 * Get all thumbnail names previously generated for this file
496 function getThumbnails() {
497 if ( $this->isHashed() ) {
500 $dir = $this->getThumbPath();
502 if ( is_dir( $dir ) ) {
503 $handle = opendir( $dir );
506 while ( false !== ( $file = readdir($handle) ) ) {
507 if ( $file{0} != '.' ) {
522 * Refresh metadata in memcached, but don't touch thumbnails or squid
524 function purgeMetadataCache() {
526 $this->saveToCache();
527 $this->purgeHistory();
531 * Purge the shared history (OldLocalFile) cache
533 function purgeHistory() {
535 $hashedName = md5($this->getName());
536 $oldKey = wfMemcKey( 'oldfile', $hashedName );
537 $wgMemc->delete( $oldKey );
541 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
543 function purgeCache() {
544 // Refresh metadata cache
545 $this->purgeMetadataCache();
548 $this->purgeThumbnails();
550 // Purge squid cache for this file
551 SquidUpdate
::purge( array( $this->getURL() ) );
555 * Delete cached transformed files
557 function purgeThumbnails() {
560 $files = $this->getThumbnails();
561 $dir = $this->getThumbPath();
563 foreach ( $files as $file ) {
564 # Check that the base file name is part of the thumb name
565 # This is a basic sanity check to avoid erasing unrelated directories
566 if ( strpos( $file, $this->getName() ) !== false ) {
567 $url = $this->getThumbUrl( $file );
569 @unlink
( "$dir/$file" );
575 SquidUpdate
::purge( $urls );
579 /** purgeDescription inherited */
580 /** purgeEverything inherited */
582 function getHistory($limit = null, $start = null, $end = null) {
583 $dbr = $this->repo
->getSlaveDB();
584 $conds = $opts = array();
585 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBKey() );
586 if( $start !== null ) {
587 $conds[] = "oi_timestamp <= " . $dbr->addQuotes( $dbr->timestamp( $start ) );
589 if( $end !== null ) {
590 $conds[] = "oi_timestamp >= " . $dbr->addQuotes( $dbr->timestamp( $end ) );
593 $opts['LIMIT'] = $limit;
595 $opts['ORDER BY'] = 'oi_timestamp DESC';
596 $res = $dbr->select('oldimage', '*', $conds, __METHOD__
, $opts);
598 while( $row = $dbr->fetchObject($res) ) {
599 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
605 * Return the history of this file, line by line.
606 * starts with current version, then old versions.
607 * uses $this->historyLine to check which line to return:
608 * 0 return line for current version
609 * 1 query for old versions, return first one
610 * 2, ... return next old version from above query
614 function nextHistoryLine() {
615 # Polymorphic function name to distinguish foreign and local fetches
616 $fname = get_class( $this ) . '::' . __FUNCTION__
;
618 $dbr = $this->repo
->getSlaveDB();
620 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
621 $this->historyRes
= $dbr->select( 'image',
624 "'' AS oi_archive_name",
628 array( 'img_name' => $this->title
->getDBkey() ),
631 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
632 $dbr->freeResult($this->historyRes
);
633 $this->historyRes
= null;
636 } else if ( $this->historyLine
== 1 ) {
637 $dbr->freeResult($this->historyRes
);
638 $this->historyRes
= $dbr->select( 'oldimage', '*',
639 array( 'oi_name' => $this->title
->getDBkey() ),
641 array( 'ORDER BY' => 'oi_timestamp DESC' )
644 $this->historyLine ++
;
646 return $dbr->fetchObject( $this->historyRes
);
650 * Reset the history pointer to the first element of the history
653 function resetHistory() {
654 $this->historyLine
= 0;
655 if (!is_null($this->historyRes
)) {
656 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
657 $this->historyRes
= null;
661 /** getFullPath inherited */
662 /** getHashPath inherited */
663 /** getRel inherited */
664 /** getUrlRel inherited */
665 /** getArchiveRel inherited */
666 /** getThumbRel inherited */
667 /** getArchivePath inherited */
668 /** getThumbPath inherited */
669 /** getArchiveUrl inherited */
670 /** getThumbUrl inherited */
671 /** getArchiveVirtualUrl inherited */
672 /** getThumbVirtualUrl inherited */
673 /** isHashed inherited */
676 * Upload a file and record it in the DB
677 * @param string $srcPath Source path or virtual URL
678 * @param string $comment Upload description
679 * @param string $pageText Text to use for the new description page, if a new description page is created
680 * @param integer $flags Flags for publish()
681 * @param array $props File properties, if known. This can be used to reduce the
682 * upload time when uploading virtual URLs for which the file info
684 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
686 * @return FileRepoStatus object. On success, the value member contains the
687 * archive name, or an empty string if it was a new file.
689 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
691 $status = $this->publish( $srcPath, $flags );
693 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
694 $status->fatal( 'filenotfound', $srcPath );
702 * Record a file upload in the upload log and the image table
703 * @deprecated use upload()
705 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
706 $watch = false, $timestamp = false )
708 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
709 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
714 $wgUser->addWatch( $this->getTitle() );
721 * Record a file upload in the upload log and the image table
723 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
727 $dbw = $this->repo
->getMasterDB();
730 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
732 $props['description'] = $comment;
733 $props['user'] = $wgUser->getID();
734 $props['user_text'] = $wgUser->getName();
735 $props['timestamp'] = wfTimestamp( TS_MW
);
736 $this->setProps( $props );
738 // Delete thumbnails and refresh the metadata cache
739 $this->purgeThumbnails();
740 $this->saveToCache();
741 SquidUpdate
::purge( array( $this->getURL() ) );
743 // Fail now if the file isn't there
744 if ( !$this->fileExists
) {
745 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
750 if ( $timestamp === false ) {
751 $timestamp = $dbw->timestamp();
754 # Test to see if the row exists using INSERT IGNORE
755 # This avoids race conditions by locking the row until the commit, and also
756 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
757 $dbw->insert( 'image',
759 'img_name' => $this->getName(),
760 'img_size'=> $this->size
,
761 'img_width' => intval( $this->width
),
762 'img_height' => intval( $this->height
),
763 'img_bits' => $this->bits
,
764 'img_media_type' => $this->media_type
,
765 'img_major_mime' => $this->major_mime
,
766 'img_minor_mime' => $this->minor_mime
,
767 'img_timestamp' => $timestamp,
768 'img_description' => $comment,
769 'img_user' => $wgUser->getID(),
770 'img_user_text' => $wgUser->getName(),
771 'img_metadata' => $this->metadata
,
772 'img_sha1' => $this->sha1
778 if( $dbw->affectedRows() == 0 ) {
781 # Collision, this is an update of a file
782 # Insert previous contents into oldimage
783 $dbw->insertSelect( 'oldimage', 'image',
785 'oi_name' => 'img_name',
786 'oi_archive_name' => $dbw->addQuotes( $oldver ),
787 'oi_size' => 'img_size',
788 'oi_width' => 'img_width',
789 'oi_height' => 'img_height',
790 'oi_bits' => 'img_bits',
791 'oi_timestamp' => 'img_timestamp',
792 'oi_description' => 'img_description',
793 'oi_user' => 'img_user',
794 'oi_user_text' => 'img_user_text',
795 'oi_metadata' => 'img_metadata',
796 'oi_media_type' => 'img_media_type',
797 'oi_major_mime' => 'img_major_mime',
798 'oi_minor_mime' => 'img_minor_mime',
799 'oi_sha1' => 'img_sha1'
800 ), array( 'img_name' => $this->getName() ), __METHOD__
803 # Update the current image row
804 $dbw->update( 'image',
806 'img_size' => $this->size
,
807 'img_width' => intval( $this->width
),
808 'img_height' => intval( $this->height
),
809 'img_bits' => $this->bits
,
810 'img_media_type' => $this->media_type
,
811 'img_major_mime' => $this->major_mime
,
812 'img_minor_mime' => $this->minor_mime
,
813 'img_timestamp' => $timestamp,
814 'img_description' => $comment,
815 'img_user' => $wgUser->getID(),
816 'img_user_text' => $wgUser->getName(),
817 'img_metadata' => $this->metadata
,
818 'img_sha1' => $this->sha1
819 ), array( /* WHERE */
820 'img_name' => $this->getName()
825 # Update the image count
826 $site_stats = $dbw->tableName( 'site_stats' );
827 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
830 $descTitle = $this->getTitle();
831 $article = new Article( $descTitle );
834 $log = new LogPage( 'upload' );
835 $action = $reupload ?
'overwrite' : 'upload';
836 $log->addEntry( $action, $descTitle, $comment );
838 if( $descTitle->exists() ) {
839 # Create a null revision
840 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
841 $nullRevision->insertOn( $dbw );
842 $article->updateRevisionOn( $dbw, $nullRevision );
844 # Invalidate the cache for the description page
845 $descTitle->invalidateCache();
846 $descTitle->purgeSquid();
848 // New file; create the description page.
849 // There's already a log entry, so don't make a second RC entry
850 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
853 # Hooks, hooks, the magic of hooks...
854 wfRunHooks( 'FileUpload', array( $this ) );
856 # Commit the transaction now, in case something goes wrong later
857 # The most important thing is that files don't get lost, especially archives
858 $dbw->immediateCommit();
860 # Invalidate cache for all pages using this file
861 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
868 * Move or copy a file to its public location. If a file exists at the
869 * destination, move it to an archive. Returns the archive name on success
870 * or an empty string if it was a new file, and a wikitext-formatted
871 * WikiError object on failure.
873 * The archive name should be passed through to recordUpload for database
876 * @param string $sourcePath Local filesystem path to the source image
877 * @param integer $flags A bitwise combination of:
878 * File::DELETE_SOURCE Delete the source file, i.e. move
880 * @return FileRepoStatus object. On success, the value member contains the
881 * archive name, or an empty string if it was a new file.
883 function publish( $srcPath, $flags = 0 ) {
885 $dstRel = $this->getRel();
886 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
887 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
888 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
889 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
890 if ( $status->value
== 'new' ) {
893 $status->value
= $archiveName;
899 /** getLinksTo inherited */
900 /** getExifData inherited */
901 /** isLocal inherited */
902 /** wasDeleted inherited */
905 * Delete all versions of the file.
907 * Moves the files into an archive directory (or deletes them)
908 * and removes the database rows.
910 * Cache purging is done; logging is caller's responsibility.
914 * @return FileRepoStatus object.
916 function delete( $reason, $suppress = false ) {
918 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
919 $batch->addCurrent();
921 # Get old version relative paths
922 $dbw = $this->repo
->getMasterDB();
923 $result = $dbw->select( 'oldimage',
924 array( 'oi_archive_name' ),
925 array( 'oi_name' => $this->getName() ) );
926 while ( $row = $dbw->fetchObject( $result ) ) {
927 $batch->addOld( $row->oi_archive_name
);
929 $status = $batch->execute();
933 $site_stats = $dbw->tableName( 'site_stats' );
934 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
935 $this->purgeEverything();
943 * Delete an old version of the file.
945 * Moves the file into an archive directory (or deletes it)
946 * and removes the database row.
948 * Cache purging is done; logging is caller's responsibility.
952 * @throws MWException or FSException on database or filestore failure
953 * @return FileRepoStatus object.
955 function deleteOld( $archiveName, $reason, $suppress=false ) {
957 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
958 $batch->addOld( $archiveName );
959 $status = $batch->execute();
962 $this->purgeDescription();
963 $this->purgeHistory();
969 * Restore all or specified deleted revisions to the given file.
970 * Permissions and logging are left to the caller.
972 * May throw database exceptions on error.
974 * @param $versions set of record ids of deleted items to restore,
975 * or empty to restore all revisions.
977 * @return FileRepoStatus
979 function restore( $versions = array(), $unsuppress = false ) {
980 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
984 $batch->addIds( $versions );
986 $status = $batch->execute();
987 if ( !$status->ok
) {
991 $cleanupStatus = $batch->cleanup();
992 $cleanupStatus->successCount
= 0;
993 $cleanupStatus->failCount
= 0;
994 $status->merge( $cleanupStatus );
998 /** isMultipage inherited */
999 /** pageCount inherited */
1000 /** scaleHeight inherited */
1001 /** getImageSize inherited */
1004 * Get the URL of the file description page.
1006 function getDescriptionUrl() {
1007 return $this->title
->getLocalUrl();
1011 * Get the HTML text of the description page
1012 * This is not used by ImagePage for local files, since (among other things)
1013 * it skips the parser cache.
1015 function getDescriptionText() {
1017 $revision = Revision
::newFromTitle( $this->title
);
1018 if ( !$revision ) return false;
1019 $text = $revision->getText();
1020 if ( !$text ) return false;
1021 $html = $wgParser->parse( $text, new ParserOptions
);
1025 function getDescription() {
1027 return $this->description
;
1030 function getTimestamp() {
1032 return $this->timestamp
;
1035 function getSha1() {
1037 // Initialise now if necessary
1038 if ( $this->sha1
== '' && $this->fileExists
) {
1039 $this->sha1
= File
::sha1Base36( $this->getPath() );
1040 if ( strval( $this->sha1
) != '' ) {
1041 $dbw = $this->repo
->getMasterDB();
1042 $dbw->update( 'image',
1043 array( 'img_sha1' => $this->sha1
),
1044 array( 'img_name' => $this->getName() ),
1046 $this->saveToCache();
1054 * Start a transaction and lock the image for update
1055 * Increments a reference counter if the lock is already held
1056 * @return boolean True if the image exists, false otherwise
1059 $dbw = $this->repo
->getMasterDB();
1060 if ( !$this->locked
) {
1064 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1068 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1069 * the transaction and thereby releases the image lock.
1072 if ( $this->locked
) {
1074 if ( !$this->locked
) {
1075 $dbw = $this->repo
->getMasterDB();
1082 * Roll back the DB transaction and mark the image unlocked
1084 function unlockAndRollback() {
1085 $this->locked
= false;
1086 $dbw = $this->repo
->getMasterDB();
1089 } // LocalFile class
1091 #------------------------------------------------------------------------------
1094 * Backwards compatibility class
1096 class Image
extends LocalFile
{
1097 function __construct( $title ) {
1098 $repo = RepoGroup
::singleton()->getLocalRepo();
1099 parent
::__construct( $title, $repo );
1103 * Wrapper for wfFindFile(), for backwards-compatibility only
1104 * Do not use in core code.
1107 static function newFromTitle( $title, $time = false ) {
1108 $img = wfFindFile( $title, $time );
1110 $img = wfLocalFile( $title );
1116 * Wrapper for wfFindFile(), for backwards-compatibility only.
1117 * Do not use in core code.
1119 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
1120 * @return image object or null if invalid title
1123 static function newFromName( $name ) {
1124 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
1125 if ( is_object( $title ) ) {
1126 $img = wfFindFile( $title );
1128 $img = wfLocalFile( $title );
1137 * Return the URL of an image, provided its name.
1139 * Backwards-compatibility for extensions.
1140 * Note that fromSharedDirectory will only use the shared path for files
1141 * that actually exist there now, and will return local paths otherwise.
1143 * @param string $name Name of the image, without the leading "Image:"
1144 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
1145 * @return string URL of $name image
1148 static function imageUrl( $name, $fromSharedDirectory = false ) {
1150 if( $fromSharedDirectory ) {
1151 $image = wfFindFile( $name );
1154 $image = wfLocalFile( $name );
1156 return $image->getUrl();
1160 #------------------------------------------------------------------------------
1163 * Helper class for file deletion
1165 class LocalFileDeleteBatch
{
1166 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1169 function __construct( File
$file, $reason = '', $suppress = false ) {
1170 $this->file
= $file;
1171 $this->reason
= $reason;
1172 $this->suppress
= $suppress;
1173 $this->status
= $file->repo
->newGood();
1176 function addCurrent() {
1177 $this->srcRels
['.'] = $this->file
->getRel();
1180 function addOld( $oldName ) {
1181 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1182 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1185 function getOldRels() {
1186 if ( !isset( $this->srcRels
['.'] ) ) {
1187 $oldRels =& $this->srcRels
;
1188 $deleteCurrent = false;
1190 $oldRels = $this->srcRels
;
1191 unset( $oldRels['.'] );
1192 $deleteCurrent = true;
1194 return array( $oldRels, $deleteCurrent );
1197 /*protected*/ function getHashes() {
1199 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1200 if ( $deleteCurrent ) {
1201 $hashes['.'] = $this->file
->getSha1();
1203 if ( count( $oldRels ) ) {
1204 $dbw = $this->file
->repo
->getMasterDB();
1205 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1206 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1208 while ( $row = $dbw->fetchObject( $res ) ) {
1209 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1210 // Get the hash from the file
1211 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1212 $props = $this->file
->repo
->getFileProps( $oldUrl );
1213 if ( $props['fileExists'] ) {
1214 // Upgrade the oldimage row
1215 $dbw->update( 'oldimage',
1216 array( 'oi_sha1' => $props['sha1'] ),
1217 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1219 $hashes[$row->oi_archive_name
] = $props['sha1'];
1221 $hashes[$row->oi_archive_name
] = false;
1224 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1228 $missing = array_diff_key( $this->srcRels
, $hashes );
1229 foreach ( $missing as $name => $rel ) {
1230 $this->status
->error( 'filedelete-old-unregistered', $name );
1232 foreach ( $hashes as $name => $hash ) {
1234 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1235 unset( $hashes[$name] );
1242 function doDBInserts() {
1244 $dbw = $this->file
->repo
->getMasterDB();
1245 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1246 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1247 $encReason = $dbw->addQuotes( $this->reason
);
1248 $encGroup = $dbw->addQuotes( 'deleted' );
1249 $ext = $this->file
->getExtension();
1250 $dotExt = $ext === '' ?
'' : ".$ext";
1251 $encExt = $dbw->addQuotes( $dotExt );
1252 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1254 // Bitfields to further suppress the content
1255 if ( $this->suppress
) {
1257 // This should be 15...
1258 $bitfield |
= Revision
::DELETED_TEXT
;
1259 $bitfield |
= Revision
::DELETED_COMMENT
;
1260 $bitfield |
= Revision
::DELETED_USER
;
1261 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1263 $bitfield = 'oi_deleted';
1266 if ( $deleteCurrent ) {
1267 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1268 $where = array( 'img_name' => $this->file
->getName() );
1269 $dbw->insertSelect( 'filearchive', 'image',
1271 'fa_storage_group' => $encGroup,
1272 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1273 'fa_deleted_user' => $encUserId,
1274 'fa_deleted_timestamp' => $encTimestamp,
1275 'fa_deleted_reason' => $encReason,
1276 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1278 'fa_name' => 'img_name',
1279 'fa_archive_name' => 'NULL',
1280 'fa_size' => 'img_size',
1281 'fa_width' => 'img_width',
1282 'fa_height' => 'img_height',
1283 'fa_metadata' => 'img_metadata',
1284 'fa_bits' => 'img_bits',
1285 'fa_media_type' => 'img_media_type',
1286 'fa_major_mime' => 'img_major_mime',
1287 'fa_minor_mime' => 'img_minor_mime',
1288 'fa_description' => 'img_description',
1289 'fa_user' => 'img_user',
1290 'fa_user_text' => 'img_user_text',
1291 'fa_timestamp' => 'img_timestamp'
1292 ), $where, __METHOD__
);
1295 if ( count( $oldRels ) ) {
1296 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1298 'oi_name' => $this->file
->getName(),
1299 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1300 $dbw->insertSelect( 'filearchive', 'oldimage',
1302 'fa_storage_group' => $encGroup,
1303 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1304 'fa_deleted_user' => $encUserId,
1305 'fa_deleted_timestamp' => $encTimestamp,
1306 'fa_deleted_reason' => $encReason,
1307 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1309 'fa_name' => 'oi_name',
1310 'fa_archive_name' => 'oi_archive_name',
1311 'fa_size' => 'oi_size',
1312 'fa_width' => 'oi_width',
1313 'fa_height' => 'oi_height',
1314 'fa_metadata' => 'oi_metadata',
1315 'fa_bits' => 'oi_bits',
1316 'fa_media_type' => 'oi_media_type',
1317 'fa_major_mime' => 'oi_major_mime',
1318 'fa_minor_mime' => 'oi_minor_mime',
1319 'fa_description' => 'oi_description',
1320 'fa_user' => 'oi_user',
1321 'fa_user_text' => 'oi_user_text',
1322 'fa_timestamp' => 'oi_timestamp',
1323 'fa_deleted' => $bitfield
1324 ), $where, __METHOD__
);
1328 function doDBDeletes() {
1329 $dbw = $this->file
->repo
->getMasterDB();
1330 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1331 if ( count( $oldRels ) ) {
1332 $dbw->delete( 'oldimage',
1334 'oi_name' => $this->file
->getName(),
1335 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1338 if ( $deleteCurrent ) {
1339 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1344 * Run the transaction
1346 function execute() {
1347 global $wgUser, $wgUseSquid;
1348 wfProfileIn( __METHOD__
);
1350 $this->file
->lock();
1351 // Leave private files alone
1352 $privateFiles = array();
1353 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1354 $dbw = $this->file
->repo
->getMasterDB();
1355 if( !empty( $oldRels ) ) {
1356 $res = $dbw->select( 'oldimage',
1357 array( 'oi_archive_name' ),
1358 array( 'oi_name' => $this->file
->getName(),
1359 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1360 'oi_deleted & ' . File
::DELETED_FILE
=> File
::DELETED_FILE
),
1362 while( $row = $dbw->fetchObject( $res ) ) {
1363 $privateFiles[$row->oi_archive_name
] = 1;
1366 // Prepare deletion batch
1367 $hashes = $this->getHashes();
1368 $this->deletionBatch
= array();
1369 $ext = $this->file
->getExtension();
1370 $dotExt = $ext === '' ?
'' : ".$ext";
1371 foreach ( $this->srcRels
as $name => $srcRel ) {
1372 // Skip files that have no hash (missing source).
1373 // Keep private files where they are.
1374 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1375 $hash = $hashes[$name];
1376 $key = $hash . $dotExt;
1377 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1378 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1382 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1383 // We acquire this lock by running the inserts now, before the file operations.
1385 // This potentially has poor lock contention characteristics -- an alternative
1386 // scheme would be to insert stub filearchive entries with no fa_name and commit
1387 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1388 $this->doDBInserts();
1390 // Execute the file deletion batch
1391 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1392 if ( !$status->isGood() ) {
1393 $this->status
->merge( $status );
1396 if ( !$this->status
->ok
) {
1397 // Critical file deletion error
1398 // Roll back inserts, release lock and abort
1399 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1400 $this->file
->unlockAndRollback();
1401 return $this->status
;
1405 if ( $wgUseSquid ) {
1407 foreach ( $this->srcRels
as $srcRel ) {
1408 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1409 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1411 SquidUpdate
::purge( $urls );
1414 // Delete image/oldimage rows
1415 $this->doDBDeletes();
1417 // Commit and return
1418 $this->file
->unlock();
1419 wfProfileOut( __METHOD__
);
1420 return $this->status
;
1424 #------------------------------------------------------------------------------
1427 * Helper class for file undeletion
1429 class LocalFileRestoreBatch
{
1430 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1432 function __construct( File
$file, $unsuppress = false ) {
1433 $this->file
= $file;
1434 $this->cleanupBatch
= $this->ids
= array();
1435 $this->ids
= array();
1436 $this->unsuppress
= $unsuppress;
1442 function addId( $fa_id ) {
1443 $this->ids
[] = $fa_id;
1447 * Add a whole lot of files by ID
1449 function addIds( $ids ) {
1450 $this->ids
= array_merge( $this->ids
, $ids );
1454 * Add all revisions of the file
1461 * Run the transaction, except the cleanup batch.
1462 * The cleanup batch should be run in a separate transaction, because it locks different
1463 * rows and there's no need to keep the image row locked while it's acquiring those locks
1464 * The caller may have its own transaction open.
1465 * So we save the batch and let the caller call cleanup()
1467 function execute() {
1468 global $wgUser, $wgLang;
1469 if ( !$this->all
&& !$this->ids
) {
1471 return $this->file
->repo
->newGood();
1474 $exists = $this->file
->lock();
1475 $dbw = $this->file
->repo
->getMasterDB();
1476 $status = $this->file
->repo
->newGood();
1478 // Fetch all or selected archived revisions for the file,
1479 // sorted from the most recent to the oldest.
1480 $conditions = array( 'fa_name' => $this->file
->getName() );
1482 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1485 $result = $dbw->select( 'filearchive', '*',
1488 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1490 $idsPresent = array();
1491 $storeBatch = array();
1492 $insertBatch = array();
1493 $insertCurrent = false;
1494 $deleteIds = array();
1496 $archiveNames = array();
1497 while( $row = $dbw->fetchObject( $result ) ) {
1498 $idsPresent[] = $row->fa_id
;
1500 if ( $row->fa_name
!= $this->file
->getName() ) {
1501 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1502 $status->failCount++
;
1505 if ( $row->fa_storage_key
== '' ) {
1506 // Revision was missing pre-deletion
1507 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1508 $status->failCount++
;
1512 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1513 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1515 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1517 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1518 $sha1 = substr( $sha1, 1 );
1521 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1522 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1523 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1524 ||
is_null( $row->fa_metadata
) ) {
1525 // Refresh our metadata
1526 // Required for a new current revision; nice for older ones too. :)
1527 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1530 'minor_mime' => $row->fa_minor_mime
,
1531 'major_mime' => $row->fa_major_mime
,
1532 'media_type' => $row->fa_media_type
,
1533 'metadata' => $row->fa_metadata
);
1536 if ( $first && !$exists ) {
1537 // The live (current) version cannot be hidden!
1538 if( !$this->unsuppress
&& $row->fa_deleted
) {
1539 $this->file
->unlock();
1542 // This revision will be published as the new current version
1543 $destRel = $this->file
->getRel();
1544 $insertCurrent = array(
1545 'img_name' => $row->fa_name
,
1546 'img_size' => $row->fa_size
,
1547 'img_width' => $row->fa_width
,
1548 'img_height' => $row->fa_height
,
1549 'img_metadata' => $props['metadata'],
1550 'img_bits' => $row->fa_bits
,
1551 'img_media_type' => $props['media_type'],
1552 'img_major_mime' => $props['major_mime'],
1553 'img_minor_mime' => $props['minor_mime'],
1554 'img_description' => $row->fa_description
,
1555 'img_user' => $row->fa_user
,
1556 'img_user_text' => $row->fa_user_text
,
1557 'img_timestamp' => $row->fa_timestamp
,
1558 'img_sha1' => $sha1);
1560 $archiveName = $row->fa_archive_name
;
1561 if( $archiveName == '' ) {
1562 // This was originally a current version; we
1563 // have to devise a new archive name for it.
1564 // Format is <timestamp of archiving>!<name>
1565 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1567 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1569 } while ( isset( $archiveNames[$archiveName] ) );
1571 $archiveNames[$archiveName] = true;
1572 $destRel = $this->file
->getArchiveRel( $archiveName );
1573 $insertBatch[] = array(
1574 'oi_name' => $row->fa_name
,
1575 'oi_archive_name' => $archiveName,
1576 'oi_size' => $row->fa_size
,
1577 'oi_width' => $row->fa_width
,
1578 'oi_height' => $row->fa_height
,
1579 'oi_bits' => $row->fa_bits
,
1580 'oi_description' => $row->fa_description
,
1581 'oi_user' => $row->fa_user
,
1582 'oi_user_text' => $row->fa_user_text
,
1583 'oi_timestamp' => $row->fa_timestamp
,
1584 'oi_metadata' => $props['metadata'],
1585 'oi_media_type' => $props['media_type'],
1586 'oi_major_mime' => $props['major_mime'],
1587 'oi_minor_mime' => $props['minor_mime'],
1588 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1589 'oi_sha1' => $sha1 );
1592 $deleteIds[] = $row->fa_id
;
1593 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1594 // private files can stay where they are
1596 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1597 $this->cleanupBatch
[] = $row->fa_storage_key
;
1603 // Add a warning to the status object for missing IDs
1604 $missingIds = array_diff( $this->ids
, $idsPresent );
1605 foreach ( $missingIds as $id ) {
1606 $status->error( 'undelete-missing-filearchive', $id );
1609 // Run the store batch
1610 // Use the OVERWRITE_SAME flag to smooth over a common error
1611 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1612 $status->merge( $storeStatus );
1614 if ( !$status->ok
) {
1615 // Store batch returned a critical error -- this usually means nothing was stored
1616 // Stop now and return an error
1617 $this->file
->unlock();
1621 // Run the DB updates
1622 // Because we have locked the image row, key conflicts should be rare.
1623 // If they do occur, we can roll back the transaction at this time with
1624 // no data loss, but leaving unregistered files scattered throughout the
1626 // This is not ideal, which is why it's important to lock the image row.
1627 if ( $insertCurrent ) {
1628 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1630 if ( $insertBatch ) {
1631 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1634 $dbw->delete( 'filearchive',
1635 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1639 if( $status->successCount
> 0 ) {
1641 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1643 // Update site_stats
1644 $site_stats = $dbw->tableName( 'site_stats' );
1645 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1647 $this->file
->purgeEverything();
1649 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1650 $this->file
->purgeDescription();
1651 $this->file
->purgeHistory();
1654 $this->file
->unlock();
1659 * Delete unused files in the deleted zone.
1660 * This should be called from outside the transaction in which execute() was called.
1662 function cleanup() {
1663 if ( !$this->cleanupBatch
) {
1664 return $this->file
->repo
->newGood();
1666 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);