6 * Bump this number when serialized cache records may be incompatible.
8 define( 'MW_FILE_VERSION', 6 );
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
56 * Create a LocalFile from a title
57 * Do not call this except from inside a repo class.
59 static function newFromTitle( $title, $repo ) {
60 return new self( $title, $repo );
64 * Create a LocalFile from a title
65 * Do not call this except from inside a repo class.
67 static function newFromRow( $row, $repo ) {
68 $title = Title
::makeTitle( NS_IMAGE
, $row->img_name
);
69 $file = new self( $title, $repo );
70 $file->loadFromRow( $row );
76 * Do not call this except from inside a repo class.
78 function __construct( $title, $repo ) {
79 if( !is_object( $title ) ) {
80 throw new MWException( __CLASS__
.' constructor given bogus title.' );
82 parent
::__construct( $title, $repo );
84 $this->historyLine
= 0;
85 $this->historyRes
= null;
86 $this->dataLoaded
= false;
90 * Get the memcached key
92 function getCacheKey() {
93 $hashedName = md5($this->getName());
94 return wfMemcKey( 'file', $hashedName );
98 * Try to load file metadata from memcached. Returns true on success.
100 function loadFromCache() {
102 wfProfileIn( __METHOD__
);
103 $this->dataLoaded
= false;
104 $key = $this->getCacheKey();
108 $cachedValues = $wgMemc->get( $key );
110 // Check if the key existed and belongs to this version of MediaWiki
111 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
112 wfDebug( "Pulling file metadata from cache key $key\n" );
113 $this->fileExists
= $cachedValues['fileExists'];
114 if ( $this->fileExists
) {
115 $this->setProps( $cachedValues );
117 $this->dataLoaded
= true;
119 if ( $this->dataLoaded
) {
120 wfIncrStats( 'image_cache_hit' );
122 wfIncrStats( 'image_cache_miss' );
125 wfProfileOut( __METHOD__
);
126 return $this->dataLoaded
;
130 * Save the file metadata to memcached
132 function saveToCache() {
135 $key = $this->getCacheKey();
139 $fields = $this->getCacheFields( '' );
140 $cache = array( 'version' => MW_FILE_VERSION
);
141 $cache['fileExists'] = $this->fileExists
;
142 if ( $this->fileExists
) {
143 foreach ( $fields as $field ) {
144 $cache[$field] = $this->$field;
148 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
152 * Load metadata from the file itself
154 function loadFromFile() {
155 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
158 function getCacheFields( $prefix = 'img_' ) {
159 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
160 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
161 static $results = array();
162 if ( $prefix == '' ) {
165 if ( !isset( $results[$prefix] ) ) {
166 $prefixedFields = array();
167 foreach ( $fields as $field ) {
168 $prefixedFields[] = $prefix . $field;
170 $results[$prefix] = $prefixedFields;
172 return $results[$prefix];
176 * Load file metadata from the DB
178 function loadFromDB() {
179 # Polymorphic function name to distinguish foreign and local fetches
180 $fname = get_class( $this ) . '::' . __FUNCTION__
;
181 wfProfileIn( $fname );
183 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
184 $this->dataLoaded
= true;
186 $dbr = $this->repo
->getSlaveDB();
188 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
189 array( 'img_name' => $this->getName() ), $fname );
191 $this->loadFromRow( $row );
193 $this->fileExists
= false;
196 wfProfileOut( $fname );
200 * Decode a row from the database (either object or array) to an array
201 * with timestamps and MIME types decoded, and the field prefix removed.
203 function decodeRow( $row, $prefix = 'img_' ) {
204 $array = (array)$row;
205 $prefixLength = strlen( $prefix );
206 // Sanity check prefix once
207 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
208 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
211 foreach ( $array as $name => $value ) {
212 $decoded[substr( $name, $prefixLength )] = $value;
214 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
215 if ( empty( $decoded['major_mime'] ) ) {
216 $decoded['mime'] = "unknown/unknown";
218 if (!$decoded['minor_mime']) {
219 $decoded['minor_mime'] = "unknown";
221 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
223 # Trim zero padding from char/binary field
224 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
229 * Load file metadata from a DB result row
231 function loadFromRow( $row, $prefix = 'img_' ) {
232 $this->dataLoaded
= true;
233 $array = $this->decodeRow( $row, $prefix );
234 foreach ( $array as $name => $value ) {
235 $this->$name = $value;
237 $this->fileExists
= true;
238 // Check for rows from a previous schema, quietly upgrade them
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 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
298 $dbw->update( 'image',
300 'img_width' => $this->width
,
301 'img_height' => $this->height
,
302 'img_bits' => $this->bits
,
303 'img_media_type' => $this->media_type
,
304 'img_major_mime' => $major,
305 'img_minor_mime' => $minor,
306 'img_metadata' => $this->metadata
,
307 'img_sha1' => $this->sha1
,
308 ), array( 'img_name' => $this->getName() ),
311 $this->saveToCache();
312 wfProfileOut( __METHOD__
);
316 * Set properties in this object to be equal to those given in the
317 * associative array $info. Only cacheable fields can be set.
319 * If 'mime' is given, it will be split into major_mime/minor_mime.
320 * If major_mime/minor_mime are given, $this->mime will also be set.
322 function setProps( $info ) {
323 $this->dataLoaded
= true;
324 $fields = $this->getCacheFields( '' );
325 $fields[] = 'fileExists';
326 foreach ( $fields as $field ) {
327 if ( isset( $info[$field] ) ) {
328 $this->$field = $info[$field];
331 // Fix up mime fields
332 if ( isset( $info['major_mime'] ) ) {
333 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
334 } elseif ( isset( $info['mime'] ) ) {
335 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
339 /** splitMime inherited */
340 /** getName inherited */
341 /** getTitle inherited */
342 /** getURL inherited */
343 /** getViewURL inherited */
344 /** getPath inherited */
347 * Return the width of the image
349 * Returns false on error
352 function getWidth( $page = 1 ) {
354 if ( $this->isMultipage() ) {
355 $dim = $this->getHandler()->getPageDimensions( $this, $page );
357 return $dim['width'];
367 * Return the height of the image
369 * Returns false on error
372 function getHeight( $page = 1 ) {
374 if ( $this->isMultipage() ) {
375 $dim = $this->getHandler()->getPageDimensions( $this, $page );
377 return $dim['height'];
382 return $this->height
;
387 * Returns ID or name of user who uploaded the file
389 * @param $type string 'text' or 'id'
391 function getUser($type='text') {
393 if( $type == 'text' ) {
394 return $this->user_text
;
395 } elseif( $type == 'id' ) {
401 * Get handler-specific metadata
403 function getMetadata() {
405 return $this->metadata
;
409 * Return the size of the image file, in bytes
418 * Returns the mime type of the file.
420 function getMimeType() {
426 * Return the type of the media in the file.
427 * Use the value returned by this function with the MEDIATYPE_xxx constants.
429 function getMediaType() {
431 return $this->media_type
;
434 /** canRender inherited */
435 /** mustRender inherited */
436 /** allowInlineDisplay inherited */
437 /** isSafeFile inherited */
438 /** isTrustedFile inherited */
441 * Returns true if the file file exists on disk.
442 * @return boolean Whether file file exist on disk.
447 return $this->fileExists
;
450 /** getTransformScript inherited */
451 /** getUnscaledThumb inherited */
452 /** thumbName inherited */
453 /** createThumb inherited */
454 /** getThumbnail inherited */
455 /** transform inherited */
458 * Fix thumbnail files from 1.4 or before, with extreme prejudice
460 function migrateThumbFile( $thumbName ) {
461 $thumbDir = $this->getThumbPath();
462 $thumbPath = "$thumbDir/$thumbName";
463 if ( is_dir( $thumbPath ) ) {
464 // Directory where file should be
465 // This happened occasionally due to broken migration code in 1.5
466 // Rename to broken-*
467 for ( $i = 0; $i < 100 ; $i++
) {
468 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
469 if ( !file_exists( $broken ) ) {
470 rename( $thumbPath, $broken );
474 // Doesn't exist anymore
477 if ( is_file( $thumbDir ) ) {
478 // File where directory should be
480 // Doesn't exist anymore
485 /** getHandler inherited */
486 /** iconThumb inherited */
487 /** getLastError inherited */
490 * Get all thumbnail names previously generated for this file
492 function getThumbnails() {
493 if ( $this->isHashed() ) {
496 $dir = $this->getThumbPath();
498 if ( is_dir( $dir ) ) {
499 $handle = opendir( $dir );
502 while ( false !== ( $file = readdir($handle) ) ) {
503 if ( $file{0} != '.' ) {
518 * Refresh metadata in memcached, but don't touch thumbnails or squid
520 function purgeMetadataCache() {
522 $this->saveToCache();
523 $this->purgeHistory();
527 * Purge the shared history (OldLocalFile) cache
529 function purgeHistory() {
531 $hashedName = md5($this->getName());
532 $oldKey = wfMemcKey( 'oldfile', $hashedName );
533 $wgMemc->delete( $oldKey );
537 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
539 function purgeCache() {
540 // Refresh metadata cache
541 $this->purgeMetadataCache();
544 $this->purgeThumbnails();
546 // Purge squid cache for this file
547 wfPurgeSquidServers( array( $this->getURL() ) );
551 * Delete cached transformed files
553 function purgeThumbnails() {
556 $files = $this->getThumbnails();
557 $dir = $this->getThumbPath();
559 foreach ( $files as $file ) {
560 # Check that the base file name is part of the thumb name
561 # This is a basic sanity check to avoid erasing unrelated directories
562 if ( strpos( $file, $this->getName() ) !== false ) {
563 $url = $this->getThumbUrl( $file );
565 @unlink
( "$dir/$file" );
571 wfPurgeSquidServers( $urls );
575 /** purgeDescription inherited */
576 /** purgeEverything inherited */
578 function getHistory($limit = null, $start = null, $end = null) {
579 $dbr = $this->repo
->getSlaveDB();
580 $conds = $opts = array();
581 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBKey() );
582 if( $start !== null ) {
583 $conds[] = "oi_timestamp < '" . $dbr->timestamp( $start ) . "'";
585 if( $end !== null ) {
586 $conds[] = "oi_timestamp > '" . $dbr->timestamp( $end ). "'";
589 $opts['LIMIT'] = $limit;
591 $opts['ORDER BY'] = 'oi_timestamp DESC';
592 $res = $dbr->select('oldimage', '*', $conds, __METHOD__
, $opts);
594 while( $row = $dbr->fetchObject($res) ) {
595 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
601 * Return the history of this file, line by line.
602 * starts with current version, then old versions.
603 * uses $this->historyLine to check which line to return:
604 * 0 return line for current version
605 * 1 query for old versions, return first one
606 * 2, ... return next old version from above query
610 function nextHistoryLine() {
611 $dbr = $this->repo
->getSlaveDB();
613 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
614 $this->historyRes
= $dbr->select( 'image',
617 "'' AS oi_archive_name"
619 array( 'img_name' => $this->title
->getDBkey() ),
622 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
623 $dbr->freeResult($this->historyRes
);
624 $this->historyRes
= null;
627 } else if ( $this->historyLine
== 1 ) {
628 $dbr->freeResult($this->historyRes
);
629 $this->historyRes
= $dbr->select( 'oldimage', '*',
630 array( 'oi_name' => $this->title
->getDBkey() ),
632 array( 'ORDER BY' => 'oi_timestamp DESC' )
635 $this->historyLine ++
;
637 return $dbr->fetchObject( $this->historyRes
);
641 * Reset the history pointer to the first element of the history
644 function resetHistory() {
645 $this->historyLine
= 0;
646 if (!is_null($this->historyRes
)) {
647 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
648 $this->historyRes
= null;
652 /** getFullPath inherited */
653 /** getHashPath inherited */
654 /** getRel inherited */
655 /** getUrlRel inherited */
656 /** getArchiveRel inherited */
657 /** getThumbRel inherited */
658 /** getArchivePath inherited */
659 /** getThumbPath inherited */
660 /** getArchiveUrl inherited */
661 /** getThumbUrl inherited */
662 /** getArchiveVirtualUrl inherited */
663 /** getThumbVirtualUrl inherited */
664 /** isHashed inherited */
667 * Upload a file and record it in the DB
668 * @param string $srcPath Source path or virtual URL
669 * @param string $comment Upload description
670 * @param string $pageText Text to use for the new description page, if a new description page is created
671 * @param integer $flags Flags for publish()
672 * @param array $props File properties, if known. This can be used to reduce the
673 * upload time when uploading virtual URLs for which the file info
675 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
677 * @return FileRepoStatus object. On success, the value member contains the
678 * archive name, or an empty string if it was a new file.
680 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
682 $status = $this->publish( $srcPath, $flags );
684 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
685 $status->fatal( 'filenotfound', $srcPath );
693 * Record a file upload in the upload log and the image table
694 * @deprecated use upload()
696 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
697 $watch = false, $timestamp = false )
699 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
700 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
705 $wgUser->addWatch( $this->getTitle() );
712 * Record a file upload in the upload log and the image table
714 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
718 $dbw = $this->repo
->getMasterDB();
721 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
723 $props['description'] = $comment;
724 $props['user'] = $wgUser->getID();
725 $props['user_text'] = $wgUser->getName();
726 $this->setProps( $props );
728 // Delete thumbnails and refresh the metadata cache
729 $this->purgeThumbnails();
730 $this->saveToCache();
731 wfPurgeSquidServers( array( $this->getURL() ) );
733 // Fail now if the file isn't there
734 if ( !$this->fileExists
) {
735 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
740 if ( $timestamp === false ) {
741 $timestamp = $dbw->timestamp();
744 # Test to see if the row exists using INSERT IGNORE
745 # This avoids race conditions by locking the row until the commit, and also
746 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
747 $dbw->insert( 'image',
749 'img_name' => $this->getName(),
750 'img_size'=> $this->size
,
751 'img_width' => intval( $this->width
),
752 'img_height' => intval( $this->height
),
753 'img_bits' => $this->bits
,
754 'img_media_type' => $this->media_type
,
755 'img_major_mime' => $this->major_mime
,
756 'img_minor_mime' => $this->minor_mime
,
757 'img_timestamp' => $timestamp,
758 'img_description' => $comment,
759 'img_user' => $wgUser->getID(),
760 'img_user_text' => $wgUser->getName(),
761 'img_metadata' => $this->metadata
,
762 'img_sha1' => $this->sha1
768 if( $dbw->affectedRows() == 0 ) {
771 # Collision, this is an update of a file
772 # Insert previous contents into oldimage
773 $dbw->insertSelect( 'oldimage', 'image',
775 'oi_name' => 'img_name',
776 'oi_archive_name' => $dbw->addQuotes( $oldver ),
777 'oi_size' => 'img_size',
778 'oi_width' => 'img_width',
779 'oi_height' => 'img_height',
780 'oi_bits' => 'img_bits',
781 'oi_timestamp' => 'img_timestamp',
782 'oi_description' => 'img_description',
783 'oi_user' => 'img_user',
784 'oi_user_text' => 'img_user_text',
785 'oi_metadata' => 'img_metadata',
786 'oi_media_type' => 'img_media_type',
787 'oi_major_mime' => 'img_major_mime',
788 'oi_minor_mime' => 'img_minor_mime',
789 'oi_sha1' => 'img_sha1',
790 ), array( 'img_name' => $this->getName() ), __METHOD__
793 # Update the current image row
794 $dbw->update( 'image',
796 'img_size' => $this->size
,
797 'img_width' => intval( $this->width
),
798 'img_height' => intval( $this->height
),
799 'img_bits' => $this->bits
,
800 'img_media_type' => $this->media_type
,
801 'img_major_mime' => $this->major_mime
,
802 'img_minor_mime' => $this->minor_mime
,
803 'img_timestamp' => $timestamp,
804 'img_description' => $comment,
805 'img_user' => $wgUser->getID(),
806 'img_user_text' => $wgUser->getName(),
807 'img_metadata' => $this->metadata
,
808 'img_sha1' => $this->sha1
809 ), array( /* WHERE */
810 'img_name' => $this->getName()
815 # Update the image count
816 $site_stats = $dbw->tableName( 'site_stats' );
817 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
820 $descTitle = $this->getTitle();
821 $article = new Article( $descTitle );
824 $log = new LogPage( 'upload' );
825 $action = $reupload ?
'overwrite' : 'upload';
826 $log->addEntry( $action, $descTitle, $comment );
828 if( $descTitle->exists() ) {
829 # Create a null revision
830 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
831 $nullRevision->insertOn( $dbw );
832 $article->updateRevisionOn( $dbw, $nullRevision );
834 # Invalidate the cache for the description page
835 $descTitle->invalidateCache();
836 $descTitle->purgeSquid();
838 // New file; create the description page.
839 // There's already a log entry, so don't make a second RC entry
840 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
843 # Hooks, hooks, the magic of hooks...
844 wfRunHooks( 'FileUpload', array( $this ) );
846 # Commit the transaction now, in case something goes wrong later
847 # The most important thing is that files don't get lost, especially archives
848 $dbw->immediateCommit();
850 # Invalidate cache for all pages using this file
851 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
858 * Move or copy a file to its public location. If a file exists at the
859 * destination, move it to an archive. Returns the archive name on success
860 * or an empty string if it was a new file, and a wikitext-formatted
861 * WikiError object on failure.
863 * The archive name should be passed through to recordUpload for database
866 * @param string $sourcePath Local filesystem path to the source image
867 * @param integer $flags A bitwise combination of:
868 * File::DELETE_SOURCE Delete the source file, i.e. move
870 * @return FileRepoStatus object. On success, the value member contains the
871 * archive name, or an empty string if it was a new file.
873 function publish( $srcPath, $flags = 0 ) {
875 $dstRel = $this->getRel();
876 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
877 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
878 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
879 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
880 if ( $status->value
== 'new' ) {
883 $status->value
= $archiveName;
889 /** getLinksTo inherited */
890 /** getExifData inherited */
891 /** isLocal inherited */
892 /** wasDeleted inherited */
895 * Delete all versions of the file.
897 * Moves the files into an archive directory (or deletes them)
898 * and removes the database rows.
900 * Cache purging is done; logging is caller's responsibility.
903 * @return FileRepoStatus object.
905 function delete( $reason ) {
907 $batch = new LocalFileDeleteBatch( $this, $reason );
908 $batch->addCurrent();
910 # Get old version relative paths
911 $dbw = $this->repo
->getMasterDB();
912 $result = $dbw->select( 'oldimage',
913 array( 'oi_archive_name' ),
914 array( 'oi_name' => $this->getName() ) );
915 while ( $row = $dbw->fetchObject( $result ) ) {
916 $batch->addOld( $row->oi_archive_name
);
918 $status = $batch->execute();
922 $site_stats = $dbw->tableName( 'site_stats' );
923 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
924 $this->purgeEverything();
932 * Delete an old version of the file.
934 * Moves the file into an archive directory (or deletes it)
935 * and removes the database row.
937 * Cache purging is done; logging is caller's responsibility.
940 * @throws MWException or FSException on database or filestore failure
941 * @return FileRepoStatus object.
943 function deleteOld( $archiveName, $reason ) {
945 $batch = new LocalFileDeleteBatch( $this, $reason );
946 $batch->addOld( $archiveName );
947 $status = $batch->execute();
950 $this->purgeDescription();
951 $this->purgeHistory();
957 * Restore all or specified deleted revisions to the given file.
958 * Permissions and logging are left to the caller.
960 * May throw database exceptions on error.
962 * @param $versions set of record ids of deleted items to restore,
963 * or empty to restore all revisions.
964 * @return FileRepoStatus
966 function restore( $versions = array(), $unsuppress = false ) {
967 $batch = new LocalFileRestoreBatch( $this );
971 $batch->addIds( $versions );
973 $status = $batch->execute();
974 if ( !$status->ok
) {
978 $cleanupStatus = $batch->cleanup();
979 $cleanupStatus->successCount
= 0;
980 $cleanupStatus->failCount
= 0;
981 $status->merge( $cleanupStatus );
985 /** isMultipage inherited */
986 /** pageCount inherited */
987 /** scaleHeight inherited */
988 /** getImageSize inherited */
991 * Get the URL of the file description page.
993 function getDescriptionUrl() {
994 return $this->title
->getLocalUrl();
998 * Get the HTML text of the description page
999 * This is not used by ImagePage for local files, since (among other things)
1000 * it skips the parser cache.
1002 function getDescriptionText() {
1004 $revision = Revision
::newFromTitle( $this->title
);
1005 if ( !$revision ) return false;
1006 $text = $revision->getText();
1007 if ( !$text ) return false;
1008 $html = $wgParser->parse( $text, new ParserOptions
);
1012 function getDescription() {
1014 return $this->description
;
1017 function getTimestamp() {
1019 return $this->timestamp
;
1022 function getSha1() {
1024 // Initialise now if necessary
1025 if ( $this->sha1
== '' && $this->fileExists
) {
1026 $this->sha1
= File
::sha1Base36( $this->getPath() );
1027 if ( strval( $this->sha1
) != '' ) {
1028 $dbw = $this->repo
->getMasterDB();
1029 $dbw->update( 'image',
1030 array( 'img_sha1' => $this->sha1
),
1031 array( 'img_name' => $this->getName() ),
1033 $this->saveToCache();
1041 * Start a transaction and lock the image for update
1042 * Increments a reference counter if the lock is already held
1043 * @return boolean True if the image exists, false otherwise
1046 $dbw = $this->repo
->getMasterDB();
1047 if ( !$this->locked
) {
1051 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1055 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1056 * the transaction and thereby releases the image lock.
1059 if ( $this->locked
) {
1061 if ( !$this->locked
) {
1062 $dbw = $this->repo
->getMasterDB();
1069 * Roll back the DB transaction and mark the image unlocked
1071 function unlockAndRollback() {
1072 $this->locked
= false;
1073 $dbw = $this->repo
->getMasterDB();
1076 } // LocalFile class
1078 #------------------------------------------------------------------------------
1081 * Backwards compatibility class
1083 class Image
extends LocalFile
{
1084 function __construct( $title ) {
1085 $repo = RepoGroup
::singleton()->getLocalRepo();
1086 parent
::__construct( $title, $repo );
1090 * Wrapper for wfFindFile(), for backwards-compatibility only
1091 * Do not use in core code.
1094 static function newFromTitle( $title, $time = false ) {
1095 $img = wfFindFile( $title, $time );
1097 $img = wfLocalFile( $title );
1103 * Wrapper for wfFindFile(), for backwards-compatibility only.
1104 * Do not use in core code.
1106 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
1107 * @return image object or null if invalid title
1110 static function newFromName( $name ) {
1111 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
1112 if ( is_object( $title ) ) {
1113 $img = wfFindFile( $title );
1115 $img = wfLocalFile( $title );
1124 * Return the URL of an image, provided its name.
1126 * Backwards-compatibility for extensions.
1127 * Note that fromSharedDirectory will only use the shared path for files
1128 * that actually exist there now, and will return local paths otherwise.
1130 * @param string $name Name of the image, without the leading "Image:"
1131 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
1132 * @return string URL of $name image
1135 static function imageUrl( $name, $fromSharedDirectory = false ) {
1137 if( $fromSharedDirectory ) {
1138 $image = wfFindFile( $name );
1141 $image = wfLocalFile( $name );
1143 return $image->getUrl();
1147 #------------------------------------------------------------------------------
1150 * Helper class for file deletion
1152 class LocalFileDeleteBatch
{
1153 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch;
1156 function __construct( File
$file, $reason = '' ) {
1157 $this->file
= $file;
1158 $this->reason
= $reason;
1159 $this->status
= $file->repo
->newGood();
1162 function addCurrent() {
1163 $this->srcRels
['.'] = $this->file
->getRel();
1166 function addOld( $oldName ) {
1167 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1168 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1171 function getOldRels() {
1172 if ( !isset( $this->srcRels
['.'] ) ) {
1173 $oldRels =& $this->srcRels
;
1174 $deleteCurrent = false;
1176 $oldRels = $this->srcRels
;
1177 unset( $oldRels['.'] );
1178 $deleteCurrent = true;
1180 return array( $oldRels, $deleteCurrent );
1183 /*protected*/ function getHashes() {
1185 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1186 if ( $deleteCurrent ) {
1187 $hashes['.'] = $this->file
->getSha1();
1189 if ( count( $oldRels ) ) {
1190 $dbw = $this->file
->repo
->getMasterDB();
1191 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1192 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1194 while ( $row = $dbw->fetchObject( $res ) ) {
1195 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1196 // Get the hash from the file
1197 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1198 $props = $this->file
->repo
->getFileProps( $oldUrl );
1199 if ( $props['fileExists'] ) {
1200 // Upgrade the oldimage row
1201 $dbw->update( 'oldimage',
1202 array( 'oi_sha1' => $props['sha1'] ),
1203 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1205 $hashes[$row->oi_archive_name
] = $props['sha1'];
1207 $hashes[$row->oi_archive_name
] = false;
1210 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1214 $missing = array_diff_key( $this->srcRels
, $hashes );
1215 foreach ( $missing as $name => $rel ) {
1216 $this->status
->error( 'filedelete-old-unregistered', $name );
1218 foreach ( $hashes as $name => $hash ) {
1220 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1221 unset( $hashes[$name] );
1228 function doDBInserts() {
1230 $dbw = $this->file
->repo
->getMasterDB();
1231 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1232 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1233 $encReason = $dbw->addQuotes( $this->reason
);
1234 $encGroup = $dbw->addQuotes( 'deleted' );
1235 $ext = $this->file
->getExtension();
1236 $dotExt = $ext === '' ?
'' : ".$ext";
1237 $encExt = $dbw->addQuotes( $dotExt );
1238 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1240 if ( $deleteCurrent ) {
1241 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1242 $where = array( 'img_name' => $this->file
->getName() );
1243 $dbw->insertSelect( 'filearchive', 'image',
1245 'fa_storage_group' => $encGroup,
1246 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1247 'fa_deleted_user' => $encUserId,
1248 'fa_deleted_timestamp' => $encTimestamp,
1249 'fa_deleted_reason' => $encReason,
1252 'fa_name' => 'img_name',
1253 'fa_archive_name' => 'NULL',
1254 'fa_size' => 'img_size',
1255 'fa_width' => 'img_width',
1256 'fa_height' => 'img_height',
1257 'fa_metadata' => 'img_metadata',
1258 'fa_bits' => 'img_bits',
1259 'fa_media_type' => 'img_media_type',
1260 'fa_major_mime' => 'img_major_mime',
1261 'fa_minor_mime' => 'img_minor_mime',
1262 'fa_description' => 'img_description',
1263 'fa_user' => 'img_user',
1264 'fa_user_text' => 'img_user_text',
1265 'fa_timestamp' => 'img_timestamp'
1266 ), $where, __METHOD__
);
1269 if ( count( $oldRels ) ) {
1270 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1272 'oi_name' => $this->file
->getName(),
1273 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1274 $dbw->insertSelect( 'filearchive', 'oldimage',
1276 'fa_storage_group' => $encGroup,
1277 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1278 'fa_deleted_user' => $encUserId,
1279 'fa_deleted_timestamp' => $encTimestamp,
1280 'fa_deleted_reason' => $encReason,
1283 'fa_name' => 'oi_name',
1284 'fa_archive_name' => 'oi_archive_name',
1285 'fa_size' => 'oi_size',
1286 'fa_width' => 'oi_width',
1287 'fa_height' => 'oi_height',
1288 'fa_metadata' => 'oi_metadata',
1289 'fa_bits' => 'oi_bits',
1290 'fa_media_type' => 'oi_media_type',
1291 'fa_major_mime' => 'oi_major_mime',
1292 'fa_minor_mime' => 'oi_minor_mime',
1293 'fa_description' => 'oi_description',
1294 'fa_user' => 'oi_user',
1295 'fa_user_text' => 'oi_user_text',
1296 'fa_timestamp' => 'oi_timestamp'
1297 ), $where, __METHOD__
);
1301 function doDBDeletes() {
1302 $dbw = $this->file
->repo
->getMasterDB();
1303 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1304 if ( $deleteCurrent ) {
1305 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1307 if ( count( $oldRels ) ) {
1308 $dbw->delete( 'oldimage',
1310 'oi_name' => $this->file
->getName(),
1311 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1317 * Run the transaction
1319 function execute() {
1320 global $wgUser, $wgUseSquid;
1321 wfProfileIn( __METHOD__
);
1323 $this->file
->lock();
1325 // Prepare deletion batch
1326 $hashes = $this->getHashes();
1327 $this->deletionBatch
= array();
1328 $ext = $this->file
->getExtension();
1329 $dotExt = $ext === '' ?
'' : ".$ext";
1330 foreach ( $this->srcRels
as $name => $srcRel ) {
1331 // Skip files that have no hash (missing source)
1332 if ( isset( $hashes[$name] ) ) {
1333 $hash = $hashes[$name];
1334 $key = $hash . $dotExt;
1335 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1336 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1340 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1341 // We acquire this lock by running the inserts now, before the file operations.
1343 // This potentially has poor lock contention characteristics -- an alternative
1344 // scheme would be to insert stub filearchive entries with no fa_name and commit
1345 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1346 $this->doDBInserts();
1348 // Execute the file deletion batch
1349 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1350 if ( !$status->isGood() ) {
1351 $this->status
->merge( $status );
1354 if ( !$this->status
->ok
) {
1355 // Critical file deletion error
1356 // Roll back inserts, release lock and abort
1357 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1358 $this->file
->unlockAndRollback();
1359 return $this->status
;
1363 if ( $wgUseSquid ) {
1365 foreach ( $this->srcRels
as $srcRel ) {
1366 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1367 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1369 SquidUpdate
::purge( $urls );
1372 // Delete image/oldimage rows
1373 $this->doDBDeletes();
1375 // Commit and return
1376 $this->file
->unlock();
1377 wfProfileOut( __METHOD__
);
1378 return $this->status
;
1382 #------------------------------------------------------------------------------
1385 * Helper class for file undeletion
1387 class LocalFileRestoreBatch
{
1388 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1390 function __construct( File
$file ) {
1391 $this->file
= $file;
1392 $this->cleanupBatch
= $this->ids
= array();
1393 $this->ids
= array();
1399 function addId( $fa_id ) {
1400 $this->ids
[] = $fa_id;
1404 * Add a whole lot of files by ID
1406 function addIds( $ids ) {
1407 $this->ids
= array_merge( $this->ids
, $ids );
1411 * Add all revisions of the file
1418 * Run the transaction, except the cleanup batch.
1419 * The cleanup batch should be run in a separate transaction, because it locks different
1420 * rows and there's no need to keep the image row locked while it's acquiring those locks
1421 * The caller may have its own transaction open.
1422 * So we save the batch and let the caller call cleanup()
1424 function execute() {
1425 global $wgUser, $wgLang;
1426 if ( !$this->all
&& !$this->ids
) {
1428 return $this->file
->repo
->newGood();
1431 $exists = $this->file
->lock();
1432 $dbw = $this->file
->repo
->getMasterDB();
1433 $status = $this->file
->repo
->newGood();
1435 // Fetch all or selected archived revisions for the file,
1436 // sorted from the most recent to the oldest.
1437 $conditions = array( 'fa_name' => $this->file
->getName() );
1439 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1442 $result = $dbw->select( 'filearchive', '*',
1445 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1447 $idsPresent = array();
1448 $storeBatch = array();
1449 $insertBatch = array();
1450 $insertCurrent = false;
1451 $deleteIds = array();
1453 $archiveNames = array();
1454 while( $row = $dbw->fetchObject( $result ) ) {
1455 $idsPresent[] = $row->fa_id
;
1456 if ( $this->unsuppress
) {
1457 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1458 } else if ( ($row->fa_deleted
& Revision
::DELETED_RESTRICTED
) && !$wgUser->isAllowed('hiderevision') ) {
1459 // Skip restoring file revisions that the user cannot restore
1462 if ( $row->fa_name
!= $this->file
->getName() ) {
1463 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1464 $status->failCount++
;
1467 if ( $row->fa_storage_key
== '' ) {
1468 // Revision was missing pre-deletion
1469 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1470 $status->failCount++
;
1474 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1475 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1477 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1479 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1480 $sha1 = substr( $sha1, 1 );
1483 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1484 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1485 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1486 ||
is_null( $row->fa_metadata
) ) {
1487 // Refresh our metadata
1488 // Required for a new current revision; nice for older ones too. :)
1489 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1492 'minor_mime' => $row->fa_minor_mime
,
1493 'major_mime' => $row->fa_major_mime
,
1494 'media_type' => $row->fa_media_type
,
1495 'metadata' => $row->fa_metadata
);
1498 if ( $first && !$exists ) {
1499 // This revision will be published as the new current version
1500 $destRel = $this->file
->getRel();
1501 $insertCurrent = array(
1502 'img_name' => $row->fa_name
,
1503 'img_size' => $row->fa_size
,
1504 'img_width' => $row->fa_width
,
1505 'img_height' => $row->fa_height
,
1506 'img_metadata' => $props['metadata'],
1507 'img_bits' => $row->fa_bits
,
1508 'img_media_type' => $props['media_type'],
1509 'img_major_mime' => $props['major_mime'],
1510 'img_minor_mime' => $props['minor_mime'],
1511 'img_description' => $row->fa_description
,
1512 'img_user' => $row->fa_user
,
1513 'img_user_text' => $row->fa_user_text
,
1514 'img_timestamp' => $row->fa_timestamp
,
1515 'img_sha1' => $sha1);
1517 $archiveName = $row->fa_archive_name
;
1518 if( $archiveName == '' ) {
1519 // This was originally a current version; we
1520 // have to devise a new archive name for it.
1521 // Format is <timestamp of archiving>!<name>
1522 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1524 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1526 } while ( isset( $archiveNames[$archiveName] ) );
1528 $archiveNames[$archiveName] = true;
1529 $destRel = $this->file
->getArchiveRel( $archiveName );
1530 $insertBatch[] = array(
1531 'oi_name' => $row->fa_name
,
1532 'oi_archive_name' => $archiveName,
1533 'oi_size' => $row->fa_size
,
1534 'oi_width' => $row->fa_width
,
1535 'oi_height' => $row->fa_height
,
1536 'oi_bits' => $row->fa_bits
,
1537 'oi_description' => $row->fa_description
,
1538 'oi_user' => $row->fa_user
,
1539 'oi_user_text' => $row->fa_user_text
,
1540 'oi_timestamp' => $row->fa_timestamp
,
1541 'oi_metadata' => $props['metadata'],
1542 'oi_media_type' => $props['media_type'],
1543 'oi_major_mime' => $props['major_mime'],
1544 'oi_minor_mime' => $props['minor_mime'],
1545 'oi_deleted' => $row->fa_deleted
,
1546 'oi_sha1' => $sha1 );
1549 $deleteIds[] = $row->fa_id
;
1550 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1551 $this->cleanupBatch
[] = $row->fa_storage_key
;
1556 // Add a warning to the status object for missing IDs
1557 $missingIds = array_diff( $this->ids
, $idsPresent );
1558 foreach ( $missingIds as $id ) {
1559 $status->error( 'undelete-missing-filearchive', $id );
1562 // Run the store batch
1563 // Use the OVERWRITE_SAME flag to smooth over a common error
1564 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1565 $status->merge( $storeStatus );
1567 if ( !$status->ok
) {
1568 // Store batch returned a critical error -- this usually means nothing was stored
1569 // Stop now and return an error
1570 $this->file
->unlock();
1574 // Run the DB updates
1575 // Because we have locked the image row, key conflicts should be rare.
1576 // If they do occur, we can roll back the transaction at this time with
1577 // no data loss, but leaving unregistered files scattered throughout the
1579 // This is not ideal, which is why it's important to lock the image row.
1580 if ( $insertCurrent ) {
1581 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1583 if ( $insertBatch ) {
1584 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1587 $dbw->delete( 'filearchive',
1588 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1592 if( $status->successCount
> 0 ) {
1594 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1596 // Update site_stats
1597 $site_stats = $dbw->tableName( 'site_stats' );
1598 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1600 $this->file
->purgeEverything();
1602 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1603 $this->file
->purgeDescription();
1604 $this->file
->purgeHistory();
1607 $this->file
->unlock();
1612 * Delete unused files in the deleted zone.
1613 * This should be called from outside the transaction in which execute() was called.
1615 function cleanup() {
1616 if ( !$this->cleanupBatch
) {
1617 return $this->file
->repo
->newGood();
1619 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);