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_mine, # Minor mime type
43 $size, # Size in bytes (loadFromXxx)
44 $metadata, # Handler-specific metadata
45 $timestamp, # Upload timestamp
46 $sha1, # SHA-1 base 36 content hash
47 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
48 $upgraded, # Whether the row was upgraded on load
49 $locked; # True if the image row is locked
54 * Create a LocalFile from a title
55 * Do not call this except from inside a repo class.
57 static function newFromTitle( $title, $repo ) {
58 return new self( $title, $repo );
62 * Create a LocalFile from a title
63 * Do not call this except from inside a repo class.
65 static function newFromRow( $row, $repo ) {
66 $title = Title
::makeTitle( NS_IMAGE
, $row->img_name
);
67 $file = new self( $title, $repo );
68 $file->loadFromRow( $row );
74 * Do not call this except from inside a repo class.
76 function __construct( $title, $repo ) {
77 if( !is_object( $title ) ) {
78 throw new MWException( __CLASS__
.' constructor given bogus title.' );
80 parent
::__construct( $title, $repo );
82 $this->historyLine
= 0;
83 $this->historyRes
= null;
84 $this->dataLoaded
= false;
88 * Get the memcached key
90 function getCacheKey() {
91 $hashedName = md5($this->getName());
92 return wfMemcKey( 'file', $hashedName );
96 * Try to load file metadata from memcached. Returns true on success.
98 function loadFromCache() {
100 wfProfileIn( __METHOD__
);
101 $this->dataLoaded
= false;
102 $key = $this->getCacheKey();
106 $cachedValues = $wgMemc->get( $key );
108 // Check if the key existed and belongs to this version of MediaWiki
109 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
110 wfDebug( "Pulling file metadata from cache key $key\n" );
111 $this->fileExists
= $cachedValues['fileExists'];
112 if ( $this->fileExists
) {
113 unset( $cachedValues['version'] );
114 unset( $cachedValues['fileExists'] );
115 foreach ( $cachedValues as $name => $value ) {
116 $this->$name = $value;
120 if ( $this->dataLoaded
) {
121 wfIncrStats( 'image_cache_hit' );
123 wfIncrStats( 'image_cache_miss' );
126 wfProfileOut( __METHOD__
);
127 return $this->dataLoaded
;
131 * Save the file metadata to memcached
133 function saveToCache() {
136 $key = $this->getCacheKey();
140 $fields = $this->getCacheFields( '' );
141 $cache = array( 'version' => MW_FILE_VERSION
);
142 $cache['fileExists'] = $this->fileExists
;
143 if ( $this->fileExists
) {
144 foreach ( $fields as $field ) {
145 $cache[$field] = $this->$field;
149 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
153 * Load metadata from the file itself
155 function loadFromFile() {
156 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
159 function getCacheFields( $prefix = 'img_' ) {
160 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
161 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1' );
162 static $results = array();
163 if ( $prefix == '' ) {
166 if ( !isset( $results[$prefix] ) ) {
167 $prefixedFields = array();
168 foreach ( $fields as $field ) {
169 $prefixedFields[] = $prefix . $field;
171 $results[$prefix] = $prefixedFields;
173 return $results[$prefix];
177 * Load file metadata from the DB
179 function loadFromDB() {
180 # Polymorphic function name to distinguish foreign and local fetches
181 $fname = get_class( $this ) . '::' . __FUNCTION__
;
182 wfProfileIn( $fname );
184 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
185 $this->dataLoaded
= true;
187 $dbr = $this->repo
->getSlaveDB();
189 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
190 array( 'img_name' => $this->getName() ), $fname );
192 $this->loadFromRow( $row );
194 $this->fileExists
= false;
197 wfProfileOut( $fname );
201 * Decode a row from the database (either object or array) to an array
202 * with timestamps and MIME types decoded, and the field prefix removed.
204 function decodeRow( $row, $prefix = 'img_' ) {
205 $array = (array)$row;
206 $prefixLength = strlen( $prefix );
207 // Sanity check prefix once
208 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
209 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
212 foreach ( $array as $name => $value ) {
213 $deprefixedName = substr( $name, $prefixLength );
214 $decoded[substr( $name, $prefixLength )] = $value;
216 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
217 if ( empty( $decoded['major_mime'] ) ) {
218 $decoded['mime'] = "unknown/unknown";
220 if (!$decoded['minor_mime']) {
221 $decoded['minor_mime'] = "unknown";
223 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
225 # Trim zero padding from char/binary field
226 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
231 * Load file metadata from a DB result row
233 function loadFromRow( $row, $prefix = 'img_' ) {
234 $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' ||
268 $this->upgraded
= true;
270 $handler = $this->getHandler();
271 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
273 $this->upgraded
= true;
278 function getUpgraded() {
279 return $this->upgraded
;
283 * Fix assorted version-related problems with the image row by reloading it from the file
285 function upgradeRow() {
286 wfProfileIn( __METHOD__
);
288 $this->loadFromFile();
290 $dbw = $this->repo
->getMasterDB();
291 list( $major, $minor ) = self
::splitMime( $this->mime
);
293 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
295 $dbw->update( 'image',
297 'img_width' => $this->width
,
298 'img_height' => $this->height
,
299 'img_bits' => $this->bits
,
300 'img_media_type' => $this->media_type
,
301 'img_major_mime' => $major,
302 'img_minor_mime' => $minor,
303 'img_metadata' => $this->metadata
,
304 'img_sha1' => $this->sha1
,
305 ), array( 'img_name' => $this->getName() ),
308 $this->saveToCache();
309 wfProfileOut( __METHOD__
);
312 function setProps( $info ) {
313 $this->dataLoaded
= true;
314 $fields = $this->getCacheFields( '' );
315 $fields[] = 'fileExists';
316 foreach ( $fields as $field ) {
317 if ( isset( $info[$field] ) ) {
318 $this->$field = $info[$field];
323 /** splitMime inherited */
324 /** getName inherited */
325 /** getTitle inherited */
326 /** getURL inherited */
327 /** getViewURL inherited */
328 /** getPath inherited */
331 * Return the width of the image
333 * Returns false on error
336 function getWidth( $page = 1 ) {
338 if ( $this->isMultipage() ) {
339 $dim = $this->getHandler()->getPageDimensions( $this, $page );
341 return $dim['width'];
351 * Return the height of the image
353 * Returns false on error
356 function getHeight( $page = 1 ) {
358 if ( $this->isMultipage() ) {
359 $dim = $this->getHandler()->getPageDimensions( $this, $page );
361 return $dim['height'];
366 return $this->height
;
371 * Get handler-specific metadata
373 function getMetadata() {
375 return $this->metadata
;
379 * Return the size of the image file, in bytes
388 * Returns the mime type of the file.
390 function getMimeType() {
396 * Return the type of the media in the file.
397 * Use the value returned by this function with the MEDIATYPE_xxx constants.
399 function getMediaType() {
401 return $this->media_type
;
404 /** canRender inherited */
405 /** mustRender inherited */
406 /** allowInlineDisplay inherited */
407 /** isSafeFile inherited */
408 /** isTrustedFile inherited */
411 * Returns true if the file file exists on disk.
412 * @return boolean Whether file file exist on disk.
417 return $this->fileExists
;
420 /** getTransformScript inherited */
421 /** getUnscaledThumb inherited */
422 /** thumbName inherited */
423 /** createThumb inherited */
424 /** getThumbnail inherited */
425 /** transform inherited */
428 * Fix thumbnail files from 1.4 or before, with extreme prejudice
430 function migrateThumbFile( $thumbName ) {
431 $thumbDir = $this->getThumbPath();
432 $thumbPath = "$thumbDir/$thumbName";
433 if ( is_dir( $thumbPath ) ) {
434 // Directory where file should be
435 // This happened occasionally due to broken migration code in 1.5
436 // Rename to broken-*
437 for ( $i = 0; $i < 100 ; $i++
) {
438 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
439 if ( !file_exists( $broken ) ) {
440 rename( $thumbPath, $broken );
444 // Doesn't exist anymore
447 if ( is_file( $thumbDir ) ) {
448 // File where directory should be
450 // Doesn't exist anymore
455 /** getHandler inherited */
456 /** iconThumb inherited */
457 /** getLastError inherited */
460 * Get all thumbnail names previously generated for this file
462 function getThumbnails() {
463 if ( $this->isHashed() ) {
466 $dir = $this->getThumbPath();
468 if ( is_dir( $dir ) ) {
469 $handle = opendir( $dir );
472 while ( false !== ( $file = readdir($handle) ) ) {
473 if ( $file{0} != '.' ) {
488 * Refresh metadata in memcached, but don't touch thumbnails or squid
490 function purgeMetadataCache() {
492 $this->saveToCache();
493 $this->purgeHistory();
497 * Purge the shared history (OldLocalFile) cache
499 function purgeHistory() {
501 $hashedName = md5($this->getName());
502 $oldKey = wfMemcKey( 'oldfile', $hashedName );
503 $wgMemc->delete( $oldKey );
507 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
509 function purgeCache() {
510 // Refresh metadata cache
511 $this->purgeMetadataCache();
514 $this->purgeThumbnails();
516 // Purge squid cache for this file
517 wfPurgeSquidServers( array( $this->getURL() ) );
521 * Delete cached transformed files
523 function purgeThumbnails() {
526 $files = $this->getThumbnails();
527 $dir = $this->getThumbPath();
529 foreach ( $files as $file ) {
531 # Check that the base file name is part of the thumb name
532 # This is a basic sanity check to avoid erasing unrelated directories
533 if ( strpos( $file, $this->getName() ) !== false ) {
534 $url = $this->getThumbUrl( $file );
536 @unlink
( "$dir/$file" );
542 wfPurgeSquidServers( $urls );
546 /** purgeDescription inherited */
547 /** purgeEverything inherited */
550 * Return the history of this file, line by line.
551 * starts with current version, then old versions.
552 * uses $this->historyLine to check which line to return:
553 * 0 return line for current version
554 * 1 query for old versions, return first one
555 * 2, ... return next old version from above query
559 function nextHistoryLine() {
560 $dbr = $this->repo
->getSlaveDB();
562 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
563 $this->historyRes
= $dbr->select( 'image',
567 'img_user','img_user_text',
571 "'' AS oi_archive_name"
573 array( 'img_name' => $this->title
->getDBkey() ),
576 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
577 $dbr->freeResult($this->historyRes
);
578 $this->historyRes
= null;
581 } else if ( $this->historyLine
== 1 ) {
582 $dbr->freeResult($this->historyRes
);
583 $this->historyRes
= $dbr->select( 'oldimage',
585 'oi_size AS img_size',
586 'oi_description AS img_description',
587 'oi_user AS img_user',
588 'oi_user_text AS img_user_text',
589 'oi_timestamp AS img_timestamp',
590 'oi_width as img_width',
591 'oi_height as img_height',
594 array( 'oi_name' => $this->title
->getDBkey() ),
596 array( 'ORDER BY' => 'oi_timestamp DESC' )
599 $this->historyLine ++
;
601 return $dbr->fetchObject( $this->historyRes
);
605 * Reset the history pointer to the first element of the history
608 function resetHistory() {
609 $this->historyLine
= 0;
610 if (!is_null($this->historyRes
)) {
611 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
612 $this->historyRes
= null;
616 /** getFullPath inherited */
617 /** getHashPath inherited */
618 /** getRel inherited */
619 /** getUrlRel inherited */
620 /** getArchiveRel inherited */
621 /** getThumbRel inherited */
622 /** getArchivePath inherited */
623 /** getThumbPath inherited */
624 /** getArchiveUrl inherited */
625 /** getThumbUrl inherited */
626 /** getArchiveVirtualUrl inherited */
627 /** getThumbVirtualUrl inherited */
628 /** isHashed inherited */
631 * Upload a file and record it in the DB
632 * @param string $srcPath Source path or virtual URL
633 * @param string $comment Upload description
634 * @param string $pageText Text to use for the new description page, if a new description page is created
635 * @param integer $flags Flags for publish()
636 * @param array $props File properties, if known. This can be used to reduce the
637 * upload time when uploading virtual URLs for which the file info
639 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
641 * @return FileRepoStatus object. On success, the value member contains the
642 * archive name, or an empty string if it was a new file.
644 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false ) {
646 $status = $this->publish( $srcPath, $flags );
648 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp ) ) {
649 $status->fatal( 'filenotfound', $srcPath );
657 * Record a file upload in the upload log and the image table
658 * @deprecated use upload()
660 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
661 $watch = false, $timestamp = false )
663 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
664 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
669 $wgUser->addWatch( $this->getTitle() );
676 * Record a file upload in the upload log and the image table
678 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false )
682 $dbw = $this->repo
->getMasterDB();
685 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
687 $this->setProps( $props );
689 // Delete thumbnails and refresh the metadata cache
690 $this->purgeThumbnails();
691 $this->saveToCache();
692 wfPurgeSquidServers( array( $this->getURL() ) );
694 // Fail now if the file isn't there
695 if ( !$this->fileExists
) {
696 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
700 if ( $timestamp === false ) {
701 $timestamp = $dbw->timestamp();
704 # Test to see if the row exists using INSERT IGNORE
705 # This avoids race conditions by locking the row until the commit, and also
706 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
707 $dbw->insert( 'image',
709 'img_name' => $this->getName(),
710 'img_size'=> $this->size
,
711 'img_width' => intval( $this->width
),
712 'img_height' => intval( $this->height
),
713 'img_bits' => $this->bits
,
714 'img_media_type' => $this->media_type
,
715 'img_major_mime' => $this->major_mime
,
716 'img_minor_mime' => $this->minor_mime
,
717 'img_timestamp' => $timestamp,
718 'img_description' => $comment,
719 'img_user' => $wgUser->getID(),
720 'img_user_text' => $wgUser->getName(),
721 'img_metadata' => $this->metadata
,
722 'img_sha1' => $this->sha1
728 if( $dbw->affectedRows() == 0 ) {
729 # Collision, this is an update of a file
730 # Insert previous contents into oldimage
731 $dbw->insertSelect( 'oldimage', 'image',
733 'oi_name' => 'img_name',
734 'oi_archive_name' => $dbw->addQuotes( $oldver ),
735 'oi_size' => 'img_size',
736 'oi_width' => 'img_width',
737 'oi_height' => 'img_height',
738 'oi_bits' => 'img_bits',
739 'oi_timestamp' => 'img_timestamp',
740 'oi_description' => 'img_description',
741 'oi_user' => 'img_user',
742 'oi_user_text' => 'img_user_text',
743 'oi_metadata' => 'img_metadata',
744 'oi_media_type' => 'img_media_type',
745 'oi_major_mime' => 'img_major_mime',
746 'oi_minor_mime' => 'img_minor_mime',
747 'oi_sha1' => 'img_sha1',
748 ), array( 'img_name' => $this->getName() ), __METHOD__
751 # Update the current image row
752 $dbw->update( 'image',
754 'img_size' => $this->size
,
755 'img_width' => intval( $this->width
),
756 'img_height' => intval( $this->height
),
757 'img_bits' => $this->bits
,
758 'img_media_type' => $this->media_type
,
759 'img_major_mime' => $this->major_mime
,
760 'img_minor_mime' => $this->minor_mime
,
761 'img_timestamp' => $timestamp,
762 'img_description' => $comment,
763 'img_user' => $wgUser->getID(),
764 'img_user_text' => $wgUser->getName(),
765 'img_metadata' => $this->metadata
,
766 'img_sha1' => $this->sha1
767 ), array( /* WHERE */
768 'img_name' => $this->getName()
773 # Update the image count
774 $site_stats = $dbw->tableName( 'site_stats' );
775 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
778 $descTitle = $this->getTitle();
779 $article = new Article( $descTitle );
782 $log = new LogPage( 'upload' );
783 $log->addEntry( 'upload', $descTitle, $comment );
785 if( $descTitle->exists() ) {
786 # Create a null revision
787 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(), $log->getRcComment(), false );
788 $nullRevision->insertOn( $dbw );
790 # Invalidate the cache for the description page
791 $descTitle->invalidateCache();
792 $descTitle->purgeSquid();
794 // New file; create the description page.
795 // There's already a log entry, so don't make a second RC entry
796 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
799 # Hooks, hooks, the magic of hooks...
800 wfRunHooks( 'FileUpload', array( $this ) );
802 # Commit the transaction now, in case something goes wrong later
803 # The most important thing is that files don't get lost, especially archives
804 $dbw->immediateCommit();
806 # Invalidate cache for all pages using this file
807 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
814 * Move or copy a file to its public location. If a file exists at the
815 * destination, move it to an archive. Returns the archive name on success
816 * or an empty string if it was a new file, and a wikitext-formatted
817 * WikiError object on failure.
819 * The archive name should be passed through to recordUpload for database
822 * @param string $sourcePath Local filesystem path to the source image
823 * @param integer $flags A bitwise combination of:
824 * File::DELETE_SOURCE Delete the source file, i.e. move
826 * @return FileRepoStatus object. On success, the value member contains the
827 * archive name, or an empty string if it was a new file.
829 function publish( $srcPath, $flags = 0 ) {
831 $dstRel = $this->getRel();
832 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
833 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
834 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
835 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
836 if ( $status->value
== 'new' ) {
839 $status->value
= $archiveName;
845 /** getLinksTo inherited */
846 /** getExifData inherited */
847 /** isLocal inherited */
848 /** wasDeleted inherited */
851 * Delete all versions of the file.
853 * Moves the files into an archive directory (or deletes them)
854 * and removes the database rows.
856 * Cache purging is done; logging is caller's responsibility.
859 * @return FileRepoStatus object.
861 function delete( $reason ) {
863 $batch = new LocalFileDeleteBatch( $this, $reason );
864 $batch->addCurrent();
866 # Get old version relative paths
867 $dbw = $this->repo
->getMasterDB();
868 $result = $dbw->select( 'oldimage',
869 array( 'oi_archive_name' ),
870 array( 'oi_name' => $this->getName() ) );
871 while ( $row = $dbw->fetchObject( $result ) ) {
872 $batch->addOld( $row->oi_archive_name
);
874 $status = $batch->execute();
878 $site_stats = $dbw->tableName( 'site_stats' );
879 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
880 $this->purgeEverything();
888 * Delete an old version of the file.
890 * Moves the file into an archive directory (or deletes it)
891 * and removes the database row.
893 * Cache purging is done; logging is caller's responsibility.
896 * @throws MWException or FSException on database or filestore failure
897 * @return FileRepoStatus object.
899 function deleteOld( $archiveName, $reason ) {
901 $batch = new LocalFileDeleteBatch( $this, $reason );
902 $batch->addOld( $archiveName );
903 $status = $batch->execute();
906 $this->purgeDescription();
907 $this->purgeHistory();
913 * Restore all or specified deleted revisions to the given file.
914 * Permissions and logging are left to the caller.
916 * May throw database exceptions on error.
918 * @param $versions set of record ids of deleted items to restore,
919 * or empty to restore all revisions.
920 * @return FileRepoStatus
922 function restore( $versions = array(), $unsuppress = false ) {
923 $batch = new LocalFileRestoreBatch( $this );
927 $batch->addIds( $versions );
929 $status = $batch->execute();
930 if ( !$status->ok
) {
934 $cleanupStatus = $batch->cleanup();
935 $cleanupStatus->successCount
= 0;
936 $cleanupStatus->failCount
= 0;
937 $status->merge( $cleanupStatus );
941 /** isMultipage inherited */
942 /** pageCount inherited */
943 /** scaleHeight inherited */
944 /** getImageSize inherited */
947 * Get the URL of the file description page.
949 function getDescriptionUrl() {
950 return $this->title
->getLocalUrl();
954 * Get the HTML text of the description page
955 * This is not used by ImagePage for local files, since (among other things)
956 * it skips the parser cache.
958 function getDescriptionText() {
960 $revision = Revision
::newFromTitle( $this->title
);
961 if ( !$revision ) return false;
962 $text = $revision->getText();
963 if ( !$text ) return false;
964 $html = $wgParser->parse( $text, new ParserOptions
);
968 function getTimestamp() {
970 return $this->timestamp
;
979 * Start a transaction and lock the image for update
980 * Increments a reference counter if the lock is already held
981 * @return boolean True if the image exists, false otherwise
984 $dbw = $this->repo
->getMasterDB();
985 if ( !$this->locked
) {
989 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
993 * Decrement the lock reference count. If the reference count is reduced to zero, commits
994 * the transaction and thereby releases the image lock.
997 if ( $this->locked
) {
999 if ( !$this->locked
) {
1000 $dbw = $this->repo
->getMasterDB();
1007 * Roll back the DB transaction and mark the image unlocked
1009 function unlockAndRollback() {
1010 $this->locked
= false;
1011 $dbw = $this->repo
->getMasterDB();
1014 } // LocalFile class
1016 #------------------------------------------------------------------------------
1019 * Backwards compatibility class
1021 class Image
extends LocalFile
{
1022 function __construct( $title ) {
1023 $repo = RepoGroup
::singleton()->getLocalRepo();
1024 parent
::__construct( $title, $repo );
1028 * Wrapper for wfFindFile(), for backwards-compatibility only
1029 * Do not use in core code.
1032 static function newFromTitle( $title, $time = false ) {
1033 $img = wfFindFile( $title, $time );
1035 $img = wfLocalFile( $title );
1041 * Wrapper for wfFindFile(), for backwards-compatibility only.
1042 * Do not use in core code.
1044 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
1045 * @return image object or null if invalid title
1048 static function newFromName( $name ) {
1049 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
1050 if ( is_object( $title ) ) {
1051 $img = wfFindFile( $title );
1053 $img = wfLocalFile( $title );
1062 * Return the URL of an image, provided its name.
1064 * Backwards-compatibility for extensions.
1065 * Note that fromSharedDirectory will only use the shared path for files
1066 * that actually exist there now, and will return local paths otherwise.
1068 * @param string $name Name of the image, without the leading "Image:"
1069 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
1070 * @return string URL of $name image
1073 static function imageUrl( $name, $fromSharedDirectory = false ) {
1075 if( $fromSharedDirectory ) {
1076 $image = wfFindFile( $name );
1079 $image = wfLocalFile( $name );
1081 return $image->getUrl();
1085 #------------------------------------------------------------------------------
1088 * Helper class for file deletion
1090 class LocalFileDeleteBatch
{
1091 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch;
1094 function __construct( File
$file, $reason = '' ) {
1095 $this->file
= $file;
1096 $this->reason
= $reason;
1097 $this->status
= $file->repo
->newGood();
1100 function addCurrent() {
1101 $this->srcRels
['.'] = $this->file
->getRel();
1104 function addOld( $oldName ) {
1105 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1106 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1109 function getOldRels() {
1110 if ( !isset( $this->srcRels
['.'] ) ) {
1111 $oldRels =& $this->srcRels
;
1112 $deleteCurrent = false;
1114 $oldRels = $this->srcRels
;
1115 unset( $oldRels['.'] );
1116 $deleteCurrent = true;
1118 return array( $oldRels, $deleteCurrent );
1121 /*protected*/ function getHashes() {
1123 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1124 if ( $deleteCurrent ) {
1125 $hashes['.'] = $this->file
->getSha1();
1127 if ( count( $oldRels ) ) {
1128 $dbw = $this->file
->repo
->getMasterDB();
1129 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1130 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1132 while ( $row = $dbw->fetchObject( $res ) ) {
1133 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1134 // Get the hash from the file
1135 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1136 $props = $this->file
->repo
->getFileProps( $oldUrl );
1137 if ( $props['fileExists'] ) {
1138 // Upgrade the oldimage row
1139 $dbw->update( 'oldimage',
1140 array( 'oi_sha1' => $props['sha1'] ),
1141 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1143 $hashes[$row->oi_archive_name
] = $props['sha1'];
1145 $hashes[$row->oi_archive_name
] = false;
1148 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1152 $missing = array_diff_key( $this->srcRels
, $hashes );
1153 foreach ( $missing as $name => $rel ) {
1154 $this->status
->error( 'filedelete-old-unregistered', $name );
1156 foreach ( $hashes as $name => $hash ) {
1158 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1159 unset( $hashes[$name] );
1166 function doDBInserts() {
1168 $dbw = $this->file
->repo
->getMasterDB();
1169 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1170 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1171 $encReason = $dbw->addQuotes( $this->reason
);
1172 $encGroup = $dbw->addQuotes( 'deleted' );
1173 $ext = $this->file
->getExtension();
1174 $dotExt = $ext === '' ?
'' : ".$ext";
1175 $encExt = $dbw->addQuotes( $dotExt );
1176 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1178 if ( $deleteCurrent ) {
1179 $where = array( 'img_name' => $this->file
->getName() );
1180 $dbw->insertSelect( 'filearchive', 'image',
1182 'fa_storage_group' => $encGroup,
1183 'fa_storage_key' => "IF(img_sha1='', '', CONCAT(img_sha1,$encExt))",
1185 'fa_deleted_user' => $encUserId,
1186 'fa_deleted_timestamp' => $encTimestamp,
1187 'fa_deleted_reason' => $encReason,
1190 'fa_name' => 'img_name',
1191 'fa_archive_name' => 'NULL',
1192 'fa_size' => 'img_size',
1193 'fa_width' => 'img_width',
1194 'fa_height' => 'img_height',
1195 'fa_metadata' => 'img_metadata',
1196 'fa_bits' => 'img_bits',
1197 'fa_media_type' => 'img_media_type',
1198 'fa_major_mime' => 'img_major_mime',
1199 'fa_minor_mime' => 'img_minor_mime',
1200 'fa_description' => 'img_description',
1201 'fa_user' => 'img_user',
1202 'fa_user_text' => 'img_user_text',
1203 'fa_timestamp' => 'img_timestamp'
1204 ), $where, __METHOD__
);
1207 if ( count( $oldRels ) ) {
1209 'oi_name' => $this->file
->getName(),
1210 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1212 $dbw->insertSelect( 'filearchive', 'oldimage',
1214 'fa_storage_group' => $encGroup,
1215 'fa_storage_key' => "IF(oi_sha1='', '', CONCAT(oi_sha1,$encExt))",
1217 'fa_deleted_user' => $encUserId,
1218 'fa_deleted_timestamp' => $encTimestamp,
1219 'fa_deleted_reason' => $encReason,
1222 'fa_name' => 'oi_name',
1223 'fa_archive_name' => 'oi_archive_name',
1224 'fa_size' => 'oi_size',
1225 'fa_width' => 'oi_width',
1226 'fa_height' => 'oi_height',
1227 'fa_metadata' => 'oi_metadata',
1228 'fa_bits' => 'oi_bits',
1229 'fa_media_type' => 'oi_media_type',
1230 'fa_major_mime' => 'oi_major_mime',
1231 'fa_minor_mime' => 'oi_minor_mime',
1232 'fa_description' => 'oi_description',
1233 'fa_user' => 'oi_user',
1234 'fa_user_text' => 'oi_user_text',
1235 'fa_timestamp' => 'oi_timestamp'
1236 ), $where, __METHOD__
);
1240 function doDBDeletes() {
1241 $dbw = $this->file
->repo
->getMasterDB();
1242 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1243 if ( $deleteCurrent ) {
1244 $where = array( 'img_name' => $this->file
->getName() );
1245 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1247 if ( count( $oldRels ) ) {
1248 $dbw->delete( 'oldimage',
1250 'oi_name' => $this->file
->getName(),
1251 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')'
1257 * Run the transaction
1259 function execute() {
1260 global $wgUser, $wgUseSquid;
1261 wfProfileIn( __METHOD__
);
1263 $this->file
->lock();
1265 // Prepare deletion batch
1266 $hashes = $this->getHashes();
1267 $this->deletionBatch
= array();
1268 $ext = $this->file
->getExtension();
1269 $dotExt = $ext === '' ?
'' : ".$ext";
1270 foreach ( $this->srcRels
as $name => $srcRel ) {
1271 // Skip files that have no hash (missing source)
1272 if ( isset( $hashes[$name] ) ) {
1273 $hash = $hashes[$name];
1274 $key = $hash . $dotExt;
1275 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1276 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1280 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1281 // We acquire this lock by running the inserts now, before the file operations.
1283 // This potentially has poor lock contention characteristics -- an alternative
1284 // scheme would be to insert stub filearchive entries with no fa_name and commit
1285 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1286 $this->doDBInserts();
1288 // Execute the file deletion batch
1289 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1290 if ( !$status->isGood() ) {
1291 $this->status
->merge( $status );
1294 if ( !$this->status
->ok
) {
1295 // Critical file deletion error
1296 // Roll back inserts, release lock and abort
1297 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1298 $this->file
->unlockAndRollback();
1299 return $this->status
;
1303 if ( $wgUseSquid ) {
1305 foreach ( $this->srcRels
as $srcRel ) {
1306 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1307 $urls[] = $this->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1309 SquidUpdate
::purge( $urls );
1312 // Delete image/oldimage rows
1313 $this->doDBDeletes();
1315 // Commit and return
1316 $this->file
->unlock();
1317 wfProfileOut( __METHOD__
);
1318 return $this->status
;
1322 #------------------------------------------------------------------------------
1325 * Helper class for file undeletion
1327 class LocalFileRestoreBatch
{
1328 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1330 function __construct( File
$file ) {
1331 $this->file
= $file;
1332 $this->cleanupBatch
= $this->ids
= array();
1333 $this->ids
= array();
1339 function addId( $fa_id ) {
1340 $this->ids
[] = $fa_id;
1344 * Add a whole lot of files by ID
1346 function addIds( $ids ) {
1347 $this->ids
= array_merge( $this->ids
, $ids );
1351 * Add all revisions of the file
1358 * Run the transaction, except the cleanup batch.
1359 * The cleanup batch should be run in a separate transaction, because it locks different
1360 * rows and there's no need to keep the image row locked while it's acquiring those locks
1361 * The caller may have its own transaction open.
1362 * So we save the batch and let the caller call cleanup()
1364 function execute() {
1365 global $wgUser, $wgLang;
1366 if ( !$this->all
&& !$this->ids
) {
1368 return $this->file
->repo
->newGood();
1371 $exists = $this->file
->lock();
1372 $dbw = $this->file
->repo
->getMasterDB();
1373 $status = $this->file
->repo
->newGood();
1375 // Fetch all or selected archived revisions for the file,
1376 // sorted from the most recent to the oldest.
1377 $conditions = array( 'fa_name' => $this->file
->getName() );
1379 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1382 $result = $dbw->select( 'filearchive', '*',
1385 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1387 $idsPresent = array();
1388 $storeBatch = array();
1389 $insertBatch = array();
1390 $insertCurrent = false;
1391 $deleteIds = array();
1393 $archiveNames = array();
1394 while( $row = $dbw->fetchObject( $result ) ) {
1395 $idsPresent[] = $row->fa_id
;
1396 if ( $this->unsuppress
) {
1397 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1398 } else if ( ($row->fa_deleted
& Revision
::DELETED_RESTRICTED
) && !$wgUser->isAllowed('hiderevision') ) {
1399 // Skip restoring file revisions that the user cannot restore
1402 if ( $row->fa_name
!= $this->file
->getName() ) {
1403 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1404 $status->failCount++
;
1407 if ( $row->fa_storage_key
== '' ) {
1408 // Revision was missing pre-deletion
1409 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1410 $status->failCount++
;
1414 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1415 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1417 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1419 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1420 $sha1 = substr( $sha1, 1 );
1423 if ( $first && !$exists ) {
1424 // This revision will be published as the new current version
1425 $destRel = $this->file
->getRel();
1426 $info = $this->file
->repo
->getFileProps( $deletedUrl );
1427 $insertCurrent = array(
1428 'img_name' => $row->fa_name
,
1429 'img_size' => $row->fa_size
,
1430 'img_width' => $row->fa_width
,
1431 'img_height' => $row->fa_height
,
1432 'img_metadata' => $row->fa_metadata
,
1433 'img_bits' => $row->fa_bits
,
1434 'img_media_type' => $row->fa_media_type
,
1435 'img_major_mime' => $row->fa_major_mime
,
1436 'img_minor_mime' => $row->fa_minor_mime
,
1437 'img_description' => $row->fa_description
,
1438 'img_user' => $row->fa_user
,
1439 'img_user_text' => $row->fa_user_text
,
1440 'img_timestamp' => $row->fa_timestamp
,
1441 'img_sha1' => $sha1);
1443 $archiveName = $row->fa_archive_name
;
1444 if( $archiveName == '' ) {
1445 // This was originally a current version; we
1446 // have to devise a new archive name for it.
1447 // Format is <timestamp of archiving>!<name>
1448 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1450 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1452 } while ( isset( $archiveNames[$archiveName] ) );
1454 $archiveNames[$archiveName] = true;
1455 $destRel = $this->file
->getArchiveRel( $archiveName );
1456 $insertBatch[] = array(
1457 'oi_name' => $row->fa_name
,
1458 'oi_archive_name' => $archiveName,
1459 'oi_size' => $row->fa_size
,
1460 'oi_width' => $row->fa_width
,
1461 'oi_height' => $row->fa_height
,
1462 'oi_bits' => $row->fa_bits
,
1463 'oi_description' => $row->fa_description
,
1464 'oi_user' => $row->fa_user
,
1465 'oi_user_text' => $row->fa_user_text
,
1466 'oi_timestamp' => $row->fa_timestamp
,
1467 'oi_metadata' => $row->fa_metadata
,
1468 'oi_media_type' => $row->fa_media_type
,
1469 'oi_major_mime' => $row->fa_major_mime
,
1470 'oi_minor_mime' => $row->fa_minor_mime
,
1471 'oi_deleted' => $row->fa_deleted
,
1472 'oi_sha1' => $sha1 );
1475 $deleteIds[] = $row->fa_id
;
1476 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1477 $this->cleanupBatch
[] = $row->fa_storage_key
;
1482 // Add a warning to the status object for missing IDs
1483 $missingIds = array_diff( $this->ids
, $idsPresent );
1484 foreach ( $missingIds as $id ) {
1485 $status->error( 'undelete-missing-filearchive', $id );
1488 // Run the store batch
1489 // Use the OVERWRITE_SAME flag to smooth over a common error
1490 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1491 $status->merge( $storeStatus );
1493 if ( !$status->ok
) {
1494 // Store batch returned a critical error -- this usually means nothing was stored
1495 // Stop now and return an error
1496 $this->file
->unlock();
1500 // Run the DB updates
1501 // Because we have locked the image row, key conflicts should be rare.
1502 // If they do occur, we can roll back the transaction at this time with
1503 // no data loss, but leaving unregistered files scattered throughout the
1505 // This is not ideal, which is why it's important to lock the image row.
1506 if ( $insertCurrent ) {
1507 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1509 if ( $insertBatch ) {
1510 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1513 $dbw->delete( 'filearchive',
1514 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1518 if( $status->successCount
> 0 ) {
1520 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1522 // Update site_stats
1523 $site_stats = $dbw->tableName( 'site_stats' );
1524 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1526 $this->file
->purgeEverything();
1528 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1529 $this->file
->purgeDescription();
1530 $this->file
->purgeHistory();
1533 $this->file
->unlock();
1538 * Delete unused files in the deleted zone.
1539 * This should be called from outside the transaction in which execute() was called.
1541 function cleanup() {
1542 if ( !$this->cleanupBatch
) {
1543 return $this->file
->repo
->newGood();
1545 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);