6 * Bump this number when serialized cache records may be incompatible.
8 define( 'MW_FILE_VERSION', 8 );
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
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 $missing, # True if file is not present in file system. Not to be cached in memcached
53 $deleted; # Bitfield akin to rev_deleted
58 * Create a LocalFile from a title
59 * Do not call this except from inside a repo class.
61 * Note: $unused param is only here to avoid an E_STRICT
63 static function newFromTitle( $title, $repo, $unused = null ) {
64 return new self( $title, $repo );
68 * Create a LocalFile from a title
69 * Do not call this except from inside a repo class.
71 static function newFromRow( $row, $repo ) {
72 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
73 $file = new self( $title, $repo );
74 $file->loadFromRow( $row );
79 * Create a LocalFile from a SHA-1 key
80 * Do not call this except from inside a repo class.
82 static function newFromKey( $sha1, $repo, $timestamp = false ) {
83 # Polymorphic function name to distinguish foreign and local fetches
84 $fname = get_class( $this ) . '::' . __FUNCTION__
;
86 $conds = array( 'img_sha1' => $sha1 );
88 $conds['img_timestamp'] = $timestamp;
90 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ), $conds, $fname );
92 return self
::newFromRow( $row, $repo );
99 * Fields in the image table
101 static function selectFields() {
122 * Do not call this except from inside a repo class.
124 function __construct( $title, $repo ) {
125 if( !is_object( $title ) ) {
126 throw new MWException( __CLASS__
.' constructor given bogus title.' );
128 parent
::__construct( $title, $repo );
129 $this->metadata
= '';
130 $this->historyLine
= 0;
131 $this->historyRes
= null;
132 $this->dataLoaded
= false;
136 * Get the memcached key
138 function getCacheKey() {
139 $hashedName = md5($this->getName());
140 return wfMemcKey( 'file', $hashedName );
144 * Try to load file metadata from memcached. Returns true on success.
146 function loadFromCache() {
148 wfProfileIn( __METHOD__
);
149 $this->dataLoaded
= false;
150 $key = $this->getCacheKey();
152 wfProfileOut( __METHOD__
);
155 $cachedValues = $wgMemc->get( $key );
157 // Check if the key existed and belongs to this version of MediaWiki
158 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
159 wfDebug( "Pulling file metadata from cache key $key\n" );
160 $this->fileExists
= $cachedValues['fileExists'];
161 if ( $this->fileExists
) {
162 $this->setProps( $cachedValues );
164 $this->dataLoaded
= true;
166 if ( $this->dataLoaded
) {
167 wfIncrStats( 'image_cache_hit' );
169 wfIncrStats( 'image_cache_miss' );
172 wfProfileOut( __METHOD__
);
173 return $this->dataLoaded
;
177 * Save the file metadata to memcached
179 function saveToCache() {
182 $key = $this->getCacheKey();
186 $fields = $this->getCacheFields( '' );
187 $cache = array( 'version' => MW_FILE_VERSION
);
188 $cache['fileExists'] = $this->fileExists
;
189 if ( $this->fileExists
) {
190 foreach ( $fields as $field ) {
191 $cache[$field] = $this->$field;
195 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
199 * Load metadata from the file itself
201 function loadFromFile() {
202 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
205 function getCacheFields( $prefix = 'img_' ) {
206 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
207 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
208 static $results = array();
209 if ( $prefix == '' ) {
212 if ( !isset( $results[$prefix] ) ) {
213 $prefixedFields = array();
214 foreach ( $fields as $field ) {
215 $prefixedFields[] = $prefix . $field;
217 $results[$prefix] = $prefixedFields;
219 return $results[$prefix];
223 * Load file metadata from the DB
225 function loadFromDB() {
226 # Polymorphic function name to distinguish foreign and local fetches
227 $fname = get_class( $this ) . '::' . __FUNCTION__
;
228 wfProfileIn( $fname );
230 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
231 $this->dataLoaded
= true;
233 $dbr = $this->repo
->getMasterDB();
235 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
236 array( 'img_name' => $this->getName() ), $fname );
238 $this->loadFromRow( $row );
240 $this->fileExists
= false;
243 wfProfileOut( $fname );
247 * Decode a row from the database (either object or array) to an array
248 * with timestamps and MIME types decoded, and the field prefix removed.
250 function decodeRow( $row, $prefix = 'img_' ) {
251 $array = (array)$row;
252 $prefixLength = strlen( $prefix );
253 // Sanity check prefix once
254 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
255 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
258 foreach ( $array as $name => $value ) {
259 $decoded[substr( $name, $prefixLength )] = $value;
261 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
262 if ( empty( $decoded['major_mime'] ) ) {
263 $decoded['mime'] = "unknown/unknown";
265 if (!$decoded['minor_mime']) {
266 $decoded['minor_mime'] = "unknown";
268 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
270 # Trim zero padding from char/binary field
271 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
276 * Load file metadata from a DB result row
278 function loadFromRow( $row, $prefix = 'img_' ) {
279 $this->dataLoaded
= true;
280 $array = $this->decodeRow( $row, $prefix );
281 foreach ( $array as $name => $value ) {
282 $this->$name = $value;
284 $this->fileExists
= true;
285 $this->maybeUpgradeRow();
289 * Load file metadata from cache or DB, unless already loaded
292 if ( !$this->dataLoaded
) {
293 if ( !$this->loadFromCache() ) {
295 $this->saveToCache();
297 $this->dataLoaded
= true;
302 * Upgrade a row if it needs it
304 function maybeUpgradeRow() {
305 if ( wfReadOnly() ) {
308 if ( is_null($this->media_type
) ||
309 $this->mime
== 'image/svg'
312 $this->upgraded
= true;
314 $handler = $this->getHandler();
315 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
317 $this->upgraded
= true;
322 function getUpgraded() {
323 return $this->upgraded
;
327 * Fix assorted version-related problems with the image row by reloading it from the file
329 function upgradeRow() {
330 wfProfileIn( __METHOD__
);
332 $this->loadFromFile();
334 # Don't destroy file info of missing files
335 if ( !$this->fileExists
) {
336 wfDebug( __METHOD__
.": file does not exist, aborting\n" );
337 wfProfileOut( __METHOD__
);
340 $dbw = $this->repo
->getMasterDB();
341 list( $major, $minor ) = self
::splitMime( $this->mime
);
343 if ( wfReadOnly() ) {
344 wfProfileOut( __METHOD__
);
347 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
349 $dbw->update( 'image',
351 'img_width' => $this->width
,
352 'img_height' => $this->height
,
353 'img_bits' => $this->bits
,
354 'img_media_type' => $this->media_type
,
355 'img_major_mime' => $major,
356 'img_minor_mime' => $minor,
357 'img_metadata' => $this->metadata
,
358 'img_sha1' => $this->sha1
,
359 ), array( 'img_name' => $this->getName() ),
362 $this->saveToCache();
363 wfProfileOut( __METHOD__
);
367 * Set properties in this object to be equal to those given in the
368 * associative array $info. Only cacheable fields can be set.
370 * If 'mime' is given, it will be split into major_mime/minor_mime.
371 * If major_mime/minor_mime are given, $this->mime will also be set.
373 function setProps( $info ) {
374 $this->dataLoaded
= true;
375 $fields = $this->getCacheFields( '' );
376 $fields[] = 'fileExists';
377 foreach ( $fields as $field ) {
378 if ( isset( $info[$field] ) ) {
379 $this->$field = $info[$field];
382 // Fix up mime fields
383 if ( isset( $info['major_mime'] ) ) {
384 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
385 } elseif ( isset( $info['mime'] ) ) {
386 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
390 /** splitMime inherited */
391 /** getName inherited */
392 /** getTitle inherited */
393 /** getURL inherited */
394 /** getViewURL inherited */
395 /** getPath inherited */
396 /** isVisible inhereted */
398 function isMissing() {
399 if( $this->missing
=== null ) {
400 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
401 $this->missing
= !$fileExists;
403 return $this->missing
;
407 * Return the width of the image
409 * Returns false on error
412 function getWidth( $page = 1 ) {
414 if ( $this->isMultipage() ) {
415 $dim = $this->getHandler()->getPageDimensions( $this, $page );
417 return $dim['width'];
427 * Return the height of the image
429 * Returns false on error
432 function getHeight( $page = 1 ) {
434 if ( $this->isMultipage() ) {
435 $dim = $this->getHandler()->getPageDimensions( $this, $page );
437 return $dim['height'];
442 return $this->height
;
447 * Returns ID or name of user who uploaded the file
449 * @param $type string 'text' or 'id'
451 function getUser($type='text') {
453 if( $type == 'text' ) {
454 return $this->user_text
;
455 } elseif( $type == 'id' ) {
461 * Get handler-specific metadata
463 function getMetadata() {
465 return $this->metadata
;
468 function getBitDepth() {
474 * Return the size of the image file, in bytes
483 * Returns the mime type of the file.
485 function getMimeType() {
491 * Return the type of the media in the file.
492 * Use the value returned by this function with the MEDIATYPE_xxx constants.
494 function getMediaType() {
496 return $this->media_type
;
499 /** canRender inherited */
500 /** mustRender inherited */
501 /** allowInlineDisplay inherited */
502 /** isSafeFile inherited */
503 /** isTrustedFile inherited */
506 * Returns true if the file file exists on disk.
507 * @return boolean Whether file file exist on disk.
512 return $this->fileExists
;
515 /** getTransformScript inherited */
516 /** getUnscaledThumb inherited */
517 /** thumbName inherited */
518 /** createThumb inherited */
519 /** getThumbnail inherited */
520 /** transform inherited */
523 * Fix thumbnail files from 1.4 or before, with extreme prejudice
525 function migrateThumbFile( $thumbName ) {
526 $thumbDir = $this->getThumbPath();
527 $thumbPath = "$thumbDir/$thumbName";
528 if ( is_dir( $thumbPath ) ) {
529 // Directory where file should be
530 // This happened occasionally due to broken migration code in 1.5
531 // Rename to broken-*
532 for ( $i = 0; $i < 100 ; $i++
) {
533 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
534 if ( !file_exists( $broken ) ) {
535 rename( $thumbPath, $broken );
539 // Doesn't exist anymore
542 if ( is_file( $thumbDir ) ) {
543 // File where directory should be
545 // Doesn't exist anymore
550 /** getHandler inherited */
551 /** iconThumb inherited */
552 /** getLastError inherited */
555 * Get all thumbnail names previously generated for this file
557 function getThumbnails() {
560 $dir = $this->getThumbPath();
562 if ( is_dir( $dir ) ) {
563 $handle = opendir( $dir );
566 while ( false !== ( $file = readdir($handle) ) ) {
567 if ( $file{0} != '.' ) {
579 * Refresh metadata in memcached, but don't touch thumbnails or squid
581 function purgeMetadataCache() {
583 $this->saveToCache();
584 $this->purgeHistory();
588 * Purge the shared history (OldLocalFile) cache
590 function purgeHistory() {
592 $hashedName = md5($this->getName());
593 $oldKey = wfMemcKey( 'oldfile', $hashedName );
594 $wgMemc->delete( $oldKey );
598 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
600 function purgeCache() {
601 // Refresh metadata cache
602 $this->purgeMetadataCache();
605 $this->purgeThumbnails();
607 // Purge squid cache for this file
608 SquidUpdate
::purge( array( $this->getURL() ) );
612 * Delete cached transformed files
614 function purgeThumbnails() {
617 $files = $this->getThumbnails();
618 $dir = $this->getThumbPath();
620 foreach ( $files as $file ) {
621 # Check that the base file name is part of the thumb name
622 # This is a basic sanity check to avoid erasing unrelated directories
623 if ( strpos( $file, $this->getName() ) !== false ) {
624 $url = $this->getThumbUrl( $file );
626 @unlink
( "$dir/$file" );
632 SquidUpdate
::purge( $urls );
636 /** purgeDescription inherited */
637 /** purgeEverything inherited */
639 function getHistory($limit = null, $start = null, $end = null, $inc = true) {
640 $dbr = $this->repo
->getSlaveDB();
641 $tables = array('oldimage');
642 $fields = OldLocalFile
::selectFields();
643 $conds = $opts = $join_conds = array();
644 $eq = $inc ?
"=" : "";
645 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBKey() );
647 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
650 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
653 $opts['LIMIT'] = $limit;
655 // Search backwards for time > x queries
656 $order = (!$start && $end !== null) ?
"ASC" : "DESC";
657 $opts['ORDER BY'] = "oi_timestamp $order";
658 $opts['USE INDEX'] = array('oldimage' => 'oi_name_timestamp');
660 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
661 &$conds, &$opts, &$join_conds ) );
663 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
665 while( $row = $dbr->fetchObject($res) ) {
666 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
668 if( $order == "ASC" ) {
669 $r = array_reverse( $r ); // make sure it ends up descending
675 * Return the history of this file, line by line.
676 * starts with current version, then old versions.
677 * uses $this->historyLine to check which line to return:
678 * 0 return line for current version
679 * 1 query for old versions, return first one
680 * 2, ... return next old version from above query
684 function nextHistoryLine() {
685 # Polymorphic function name to distinguish foreign and local fetches
686 $fname = get_class( $this ) . '::' . __FUNCTION__
;
688 $dbr = $this->repo
->getSlaveDB();
690 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
691 $this->historyRes
= $dbr->select( 'image',
694 "'' AS oi_archive_name",
698 array( 'img_name' => $this->title
->getDBkey() ),
701 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
702 $dbr->freeResult($this->historyRes
);
703 $this->historyRes
= null;
706 } else if ( $this->historyLine
== 1 ) {
707 $dbr->freeResult($this->historyRes
);
708 $this->historyRes
= $dbr->select( 'oldimage', '*',
709 array( 'oi_name' => $this->title
->getDBkey() ),
711 array( 'ORDER BY' => 'oi_timestamp DESC' )
714 $this->historyLine ++
;
716 return $dbr->fetchObject( $this->historyRes
);
720 * Reset the history pointer to the first element of the history
723 function resetHistory() {
724 $this->historyLine
= 0;
725 if (!is_null($this->historyRes
)) {
726 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
727 $this->historyRes
= null;
731 /** getFullPath inherited */
732 /** getHashPath inherited */
733 /** getRel inherited */
734 /** getUrlRel inherited */
735 /** getArchiveRel inherited */
736 /** getThumbRel inherited */
737 /** getArchivePath inherited */
738 /** getThumbPath inherited */
739 /** getArchiveUrl inherited */
740 /** getThumbUrl inherited */
741 /** getArchiveVirtualUrl inherited */
742 /** getThumbVirtualUrl inherited */
743 /** isHashed inherited */
746 * Upload a file and record it in the DB
747 * @param string $srcPath Source path or virtual URL
748 * @param string $comment Upload description
749 * @param string $pageText Text to use for the new description page, if a new description page is created
750 * @param integer $flags Flags for publish()
751 * @param array $props File properties, if known. This can be used to reduce the
752 * upload time when uploading virtual URLs for which the file info
754 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
756 * @return FileRepoStatus object. On success, the value member contains the
757 * archive name, or an empty string if it was a new file.
759 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
761 $status = $this->publish( $srcPath, $flags );
763 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
764 $status->fatal( 'filenotfound', $srcPath );
772 * Record a file upload in the upload log and the image table
773 * @deprecated use upload()
775 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
776 $watch = false, $timestamp = false )
778 $pageText = UploadForm
::getInitialPageText( $desc, $license, $copyStatus, $source );
779 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
784 $wgUser->addWatch( $this->getTitle() );
791 * Record a file upload in the upload log and the image table
793 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
795 if( is_null( $user ) ) {
800 $dbw = $this->repo
->getMasterDB();
804 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
806 $props['description'] = $comment;
807 $props['user'] = $user->getId();
808 $props['user_text'] = $user->getName();
809 $props['timestamp'] = wfTimestamp( TS_MW
);
810 $this->setProps( $props );
812 // Delete thumbnails and refresh the metadata cache
813 $this->purgeThumbnails();
814 $this->saveToCache();
815 SquidUpdate
::purge( array( $this->getURL() ) );
817 // Fail now if the file isn't there
818 if ( !$this->fileExists
) {
819 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
824 if ( $timestamp === false ) {
825 $timestamp = $dbw->timestamp();
828 # Test to see if the row exists using INSERT IGNORE
829 # This avoids race conditions by locking the row until the commit, and also
830 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
831 $dbw->insert( 'image',
833 'img_name' => $this->getName(),
834 'img_size'=> $this->size
,
835 'img_width' => intval( $this->width
),
836 'img_height' => intval( $this->height
),
837 'img_bits' => $this->bits
,
838 'img_media_type' => $this->media_type
,
839 'img_major_mime' => $this->major_mime
,
840 'img_minor_mime' => $this->minor_mime
,
841 'img_timestamp' => $timestamp,
842 'img_description' => $comment,
843 'img_user' => $user->getId(),
844 'img_user_text' => $user->getName(),
845 'img_metadata' => $this->metadata
,
846 'img_sha1' => $this->sha1
852 if( $dbw->affectedRows() == 0 ) {
855 # Collision, this is an update of a file
856 # Insert previous contents into oldimage
857 $dbw->insertSelect( 'oldimage', 'image',
859 'oi_name' => 'img_name',
860 'oi_archive_name' => $dbw->addQuotes( $oldver ),
861 'oi_size' => 'img_size',
862 'oi_width' => 'img_width',
863 'oi_height' => 'img_height',
864 'oi_bits' => 'img_bits',
865 'oi_timestamp' => 'img_timestamp',
866 'oi_description' => 'img_description',
867 'oi_user' => 'img_user',
868 'oi_user_text' => 'img_user_text',
869 'oi_metadata' => 'img_metadata',
870 'oi_media_type' => 'img_media_type',
871 'oi_major_mime' => 'img_major_mime',
872 'oi_minor_mime' => 'img_minor_mime',
873 'oi_sha1' => 'img_sha1'
874 ), array( 'img_name' => $this->getName() ), __METHOD__
877 # Update the current image row
878 $dbw->update( 'image',
880 'img_size' => $this->size
,
881 'img_width' => intval( $this->width
),
882 'img_height' => intval( $this->height
),
883 'img_bits' => $this->bits
,
884 'img_media_type' => $this->media_type
,
885 'img_major_mime' => $this->major_mime
,
886 'img_minor_mime' => $this->minor_mime
,
887 'img_timestamp' => $timestamp,
888 'img_description' => $comment,
889 'img_user' => $user->getId(),
890 'img_user_text' => $user->getName(),
891 'img_metadata' => $this->metadata
,
892 'img_sha1' => $this->sha1
893 ), array( /* WHERE */
894 'img_name' => $this->getName()
899 # Update the image count
900 $site_stats = $dbw->tableName( 'site_stats' );
901 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
904 $descTitle = $this->getTitle();
905 $article = new ImagePage( $descTitle );
906 $article->setFile( $this );
909 $log = new LogPage( 'upload' );
910 $action = $reupload ?
'overwrite' : 'upload';
911 $log->addEntry( $action, $descTitle, $comment, array(), $user );
913 if( $descTitle->exists() ) {
914 # Create a null revision
915 $latest = $descTitle->getLatestRevID();
916 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(),
917 $log->getRcComment(), false );
918 $nullRevision->insertOn( $dbw );
920 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $user) );
921 $article->updateRevisionOn( $dbw, $nullRevision );
923 # Invalidate the cache for the description page
924 $descTitle->invalidateCache();
925 $descTitle->purgeSquid();
927 // New file; create the description page.
928 // There's already a log entry, so don't make a second RC entry
929 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
932 # Hooks, hooks, the magic of hooks...
933 wfRunHooks( 'FileUpload', array( $this ) );
935 # Commit the transaction now, in case something goes wrong later
936 # The most important thing is that files don't get lost, especially archives
937 $dbw->immediateCommit();
939 # Invalidate cache for all pages using this file
940 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
942 # Invalidate cache for all pages that redirects on this page
943 $redirs = $this->getTitle()->getRedirectsHere();
944 foreach( $redirs as $redir ) {
945 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
953 * Move or copy a file to its public location. If a file exists at the
954 * destination, move it to an archive. Returns the archive name on success
955 * or an empty string if it was a new file, and a wikitext-formatted
956 * WikiError object on failure.
958 * The archive name should be passed through to recordUpload for database
961 * @param string $sourcePath Local filesystem path to the source image
962 * @param integer $flags A bitwise combination of:
963 * File::DELETE_SOURCE Delete the source file, i.e. move
965 * @return FileRepoStatus object. On success, the value member contains the
966 * archive name, or an empty string if it was a new file.
968 function publish( $srcPath, $flags = 0 ) {
970 $dstRel = $this->getRel();
971 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
972 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
973 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
974 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
975 if ( $status->value
== 'new' ) {
978 $status->value
= $archiveName;
984 /** getLinksTo inherited */
985 /** getExifData inherited */
986 /** isLocal inherited */
987 /** wasDeleted inherited */
990 * Move file to the new title
992 * Move current, old version and all thumbnails
993 * to the new filename. Old file is deleted.
995 * Cache purging is done; checks for validity
996 * and logging are caller's responsibility
998 * @param $target Title New file name
999 * @return FileRepoStatus object.
1001 function move( $target ) {
1002 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1004 $batch = new LocalFileMoveBatch( $this, $target );
1005 $batch->addCurrent();
1008 $status = $batch->execute();
1009 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1010 $this->purgeEverything();
1013 if ( $status->isOk() ) {
1014 // Now switch the object
1015 $this->title
= $target;
1016 // Force regeneration of the name and hashpath
1017 unset( $this->name
);
1018 unset( $this->hashPath
);
1019 // Purge the new image
1020 $this->purgeEverything();
1027 * Delete all versions of the file.
1029 * Moves the files into an archive directory (or deletes them)
1030 * and removes the database rows.
1032 * Cache purging is done; logging is caller's responsibility.
1036 * @return FileRepoStatus object.
1038 function delete( $reason, $suppress = false ) {
1040 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1041 $batch->addCurrent();
1043 # Get old version relative paths
1044 $dbw = $this->repo
->getMasterDB();
1045 $result = $dbw->select( 'oldimage',
1046 array( 'oi_archive_name' ),
1047 array( 'oi_name' => $this->getName() ) );
1048 while ( $row = $dbw->fetchObject( $result ) ) {
1049 $batch->addOld( $row->oi_archive_name
);
1051 $status = $batch->execute();
1053 if ( $status->ok
) {
1054 // Update site_stats
1055 $site_stats = $dbw->tableName( 'site_stats' );
1056 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1057 $this->purgeEverything();
1065 * Delete an old version of the file.
1067 * Moves the file into an archive directory (or deletes it)
1068 * and removes the database row.
1070 * Cache purging is done; logging is caller's responsibility.
1074 * @throws MWException or FSException on database or filestore failure
1075 * @return FileRepoStatus object.
1077 function deleteOld( $archiveName, $reason, $suppress=false ) {
1079 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1080 $batch->addOld( $archiveName );
1081 $status = $batch->execute();
1083 if ( $status->ok
) {
1084 $this->purgeDescription();
1085 $this->purgeHistory();
1091 * Restore all or specified deleted revisions to the given file.
1092 * Permissions and logging are left to the caller.
1094 * May throw database exceptions on error.
1096 * @param $versions set of record ids of deleted items to restore,
1097 * or empty to restore all revisions.
1099 * @return FileRepoStatus
1101 function restore( $versions = array(), $unsuppress = false ) {
1102 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1106 $batch->addIds( $versions );
1108 $status = $batch->execute();
1109 if ( !$status->ok
) {
1113 $cleanupStatus = $batch->cleanup();
1114 $cleanupStatus->successCount
= 0;
1115 $cleanupStatus->failCount
= 0;
1116 $status->merge( $cleanupStatus );
1120 /** isMultipage inherited */
1121 /** pageCount inherited */
1122 /** scaleHeight inherited */
1123 /** getImageSize inherited */
1126 * Get the URL of the file description page.
1128 function getDescriptionUrl() {
1129 return $this->title
->getLocalUrl();
1133 * Get the HTML text of the description page
1134 * This is not used by ImagePage for local files, since (among other things)
1135 * it skips the parser cache.
1137 function getDescriptionText() {
1139 $revision = Revision
::newFromTitle( $this->title
);
1140 if ( !$revision ) return false;
1141 $text = $revision->getText();
1142 if ( !$text ) return false;
1143 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1144 return $pout->getText();
1147 function getDescription() {
1149 return $this->description
;
1152 function getTimestamp() {
1154 return $this->timestamp
;
1157 function getSha1() {
1159 // Initialise now if necessary
1160 if ( $this->sha1
== '' && $this->fileExists
) {
1161 $this->sha1
= File
::sha1Base36( $this->getPath() );
1162 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1163 $dbw = $this->repo
->getMasterDB();
1164 $dbw->update( 'image',
1165 array( 'img_sha1' => $this->sha1
),
1166 array( 'img_name' => $this->getName() ),
1168 $this->saveToCache();
1176 * Start a transaction and lock the image for update
1177 * Increments a reference counter if the lock is already held
1178 * @return boolean True if the image exists, false otherwise
1181 $dbw = $this->repo
->getMasterDB();
1182 if ( !$this->locked
) {
1186 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1190 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1191 * the transaction and thereby releases the image lock.
1194 if ( $this->locked
) {
1196 if ( !$this->locked
) {
1197 $dbw = $this->repo
->getMasterDB();
1204 * Roll back the DB transaction and mark the image unlocked
1206 function unlockAndRollback() {
1207 $this->locked
= false;
1208 $dbw = $this->repo
->getMasterDB();
1211 } // LocalFile class
1213 #------------------------------------------------------------------------------
1216 * Helper class for file deletion
1219 class LocalFileDeleteBatch
{
1220 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1223 function __construct( File
$file, $reason = '', $suppress = false ) {
1224 $this->file
= $file;
1225 $this->reason
= $reason;
1226 $this->suppress
= $suppress;
1227 $this->status
= $file->repo
->newGood();
1230 function addCurrent() {
1231 $this->srcRels
['.'] = $this->file
->getRel();
1234 function addOld( $oldName ) {
1235 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1236 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1239 function getOldRels() {
1240 if ( !isset( $this->srcRels
['.'] ) ) {
1241 $oldRels =& $this->srcRels
;
1242 $deleteCurrent = false;
1244 $oldRels = $this->srcRels
;
1245 unset( $oldRels['.'] );
1246 $deleteCurrent = true;
1248 return array( $oldRels, $deleteCurrent );
1251 /*protected*/ function getHashes() {
1253 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1254 if ( $deleteCurrent ) {
1255 $hashes['.'] = $this->file
->getSha1();
1257 if ( count( $oldRels ) ) {
1258 $dbw = $this->file
->repo
->getMasterDB();
1259 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1260 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1262 while ( $row = $dbw->fetchObject( $res ) ) {
1263 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1264 // Get the hash from the file
1265 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1266 $props = $this->file
->repo
->getFileProps( $oldUrl );
1267 if ( $props['fileExists'] ) {
1268 // Upgrade the oldimage row
1269 $dbw->update( 'oldimage',
1270 array( 'oi_sha1' => $props['sha1'] ),
1271 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1273 $hashes[$row->oi_archive_name
] = $props['sha1'];
1275 $hashes[$row->oi_archive_name
] = false;
1278 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1282 $missing = array_diff_key( $this->srcRels
, $hashes );
1283 foreach ( $missing as $name => $rel ) {
1284 $this->status
->error( 'filedelete-old-unregistered', $name );
1286 foreach ( $hashes as $name => $hash ) {
1288 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1289 unset( $hashes[$name] );
1296 function doDBInserts() {
1298 $dbw = $this->file
->repo
->getMasterDB();
1299 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1300 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1301 $encReason = $dbw->addQuotes( $this->reason
);
1302 $encGroup = $dbw->addQuotes( 'deleted' );
1303 $ext = $this->file
->getExtension();
1304 $dotExt = $ext === '' ?
'' : ".$ext";
1305 $encExt = $dbw->addQuotes( $dotExt );
1306 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1308 // Bitfields to further suppress the content
1309 if ( $this->suppress
) {
1311 // This should be 15...
1312 $bitfield |
= Revision
::DELETED_TEXT
;
1313 $bitfield |
= Revision
::DELETED_COMMENT
;
1314 $bitfield |
= Revision
::DELETED_USER
;
1315 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1317 $bitfield = 'oi_deleted';
1320 if ( $deleteCurrent ) {
1321 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1322 $where = array( 'img_name' => $this->file
->getName() );
1323 $dbw->insertSelect( 'filearchive', 'image',
1325 'fa_storage_group' => $encGroup,
1326 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1327 'fa_deleted_user' => $encUserId,
1328 'fa_deleted_timestamp' => $encTimestamp,
1329 'fa_deleted_reason' => $encReason,
1330 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1332 'fa_name' => 'img_name',
1333 'fa_archive_name' => 'NULL',
1334 'fa_size' => 'img_size',
1335 'fa_width' => 'img_width',
1336 'fa_height' => 'img_height',
1337 'fa_metadata' => 'img_metadata',
1338 'fa_bits' => 'img_bits',
1339 'fa_media_type' => 'img_media_type',
1340 'fa_major_mime' => 'img_major_mime',
1341 'fa_minor_mime' => 'img_minor_mime',
1342 'fa_description' => 'img_description',
1343 'fa_user' => 'img_user',
1344 'fa_user_text' => 'img_user_text',
1345 'fa_timestamp' => 'img_timestamp'
1346 ), $where, __METHOD__
);
1349 if ( count( $oldRels ) ) {
1350 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1352 'oi_name' => $this->file
->getName(),
1353 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1354 $dbw->insertSelect( 'filearchive', 'oldimage',
1356 'fa_storage_group' => $encGroup,
1357 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1358 'fa_deleted_user' => $encUserId,
1359 'fa_deleted_timestamp' => $encTimestamp,
1360 'fa_deleted_reason' => $encReason,
1361 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1363 'fa_name' => 'oi_name',
1364 'fa_archive_name' => 'oi_archive_name',
1365 'fa_size' => 'oi_size',
1366 'fa_width' => 'oi_width',
1367 'fa_height' => 'oi_height',
1368 'fa_metadata' => 'oi_metadata',
1369 'fa_bits' => 'oi_bits',
1370 'fa_media_type' => 'oi_media_type',
1371 'fa_major_mime' => 'oi_major_mime',
1372 'fa_minor_mime' => 'oi_minor_mime',
1373 'fa_description' => 'oi_description',
1374 'fa_user' => 'oi_user',
1375 'fa_user_text' => 'oi_user_text',
1376 'fa_timestamp' => 'oi_timestamp',
1377 'fa_deleted' => $bitfield
1378 ), $where, __METHOD__
);
1382 function doDBDeletes() {
1383 $dbw = $this->file
->repo
->getMasterDB();
1384 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1385 if ( count( $oldRels ) ) {
1386 $dbw->delete( 'oldimage',
1388 'oi_name' => $this->file
->getName(),
1389 'oi_archive_name' => array_keys( $oldRels )
1392 if ( $deleteCurrent ) {
1393 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1398 * Run the transaction
1400 function execute() {
1402 wfProfileIn( __METHOD__
);
1404 $this->file
->lock();
1405 // Leave private files alone
1406 $privateFiles = array();
1407 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1408 $dbw = $this->file
->repo
->getMasterDB();
1409 if( !empty( $oldRels ) ) {
1410 $res = $dbw->select( 'oldimage',
1411 array( 'oi_archive_name' ),
1412 array( 'oi_name' => $this->file
->getName(),
1413 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1414 'oi_deleted & ' . File
::DELETED_FILE
=> File
::DELETED_FILE
),
1416 while( $row = $dbw->fetchObject( $res ) ) {
1417 $privateFiles[$row->oi_archive_name
] = 1;
1420 // Prepare deletion batch
1421 $hashes = $this->getHashes();
1422 $this->deletionBatch
= array();
1423 $ext = $this->file
->getExtension();
1424 $dotExt = $ext === '' ?
'' : ".$ext";
1425 foreach ( $this->srcRels
as $name => $srcRel ) {
1426 // Skip files that have no hash (missing source).
1427 // Keep private files where they are.
1428 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1429 $hash = $hashes[$name];
1430 $key = $hash . $dotExt;
1431 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1432 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1436 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1437 // We acquire this lock by running the inserts now, before the file operations.
1439 // This potentially has poor lock contention characteristics -- an alternative
1440 // scheme would be to insert stub filearchive entries with no fa_name and commit
1441 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1442 $this->doDBInserts();
1444 // Removes non-existent file from the batch, so we don't get errors.
1445 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1447 // Execute the file deletion batch
1448 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1449 if ( !$status->isGood() ) {
1450 $this->status
->merge( $status );
1453 if ( !$this->status
->ok
) {
1454 // Critical file deletion error
1455 // Roll back inserts, release lock and abort
1456 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1457 $this->file
->unlockAndRollback();
1458 wfProfileOut( __METHOD__
);
1459 return $this->status
;
1463 if ( $wgUseSquid ) {
1465 foreach ( $this->srcRels
as $srcRel ) {
1466 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1467 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1469 SquidUpdate
::purge( $urls );
1472 // Delete image/oldimage rows
1473 $this->doDBDeletes();
1475 // Commit and return
1476 $this->file
->unlock();
1477 wfProfileOut( __METHOD__
);
1478 return $this->status
;
1482 * Removes non-existent files from a deletion batch.
1484 function removeNonexistentFiles( $batch ) {
1485 $files = $newBatch = array();
1486 foreach( $batch as $batchItem ) {
1487 list( $src, $dest ) = $batchItem;
1488 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1490 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1491 foreach( $batch as $batchItem )
1492 if( $result[$batchItem[0]] )
1493 $newBatch[] = $batchItem;
1498 #------------------------------------------------------------------------------
1501 * Helper class for file undeletion
1504 class LocalFileRestoreBatch
{
1505 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1507 function __construct( File
$file, $unsuppress = false ) {
1508 $this->file
= $file;
1509 $this->cleanupBatch
= $this->ids
= array();
1510 $this->ids
= array();
1511 $this->unsuppress
= $unsuppress;
1517 function addId( $fa_id ) {
1518 $this->ids
[] = $fa_id;
1522 * Add a whole lot of files by ID
1524 function addIds( $ids ) {
1525 $this->ids
= array_merge( $this->ids
, $ids );
1529 * Add all revisions of the file
1536 * Run the transaction, except the cleanup batch.
1537 * The cleanup batch should be run in a separate transaction, because it locks different
1538 * rows and there's no need to keep the image row locked while it's acquiring those locks
1539 * The caller may have its own transaction open.
1540 * So we save the batch and let the caller call cleanup()
1542 function execute() {
1544 if ( !$this->all
&& !$this->ids
) {
1546 return $this->file
->repo
->newGood();
1549 $exists = $this->file
->lock();
1550 $dbw = $this->file
->repo
->getMasterDB();
1551 $status = $this->file
->repo
->newGood();
1553 // Fetch all or selected archived revisions for the file,
1554 // sorted from the most recent to the oldest.
1555 $conditions = array( 'fa_name' => $this->file
->getName() );
1557 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1560 $result = $dbw->select( 'filearchive', '*',
1563 array( 'ORDER BY' => 'fa_timestamp DESC' )
1566 $idsPresent = array();
1567 $storeBatch = array();
1568 $insertBatch = array();
1569 $insertCurrent = false;
1570 $deleteIds = array();
1572 $archiveNames = array();
1573 while( $row = $dbw->fetchObject( $result ) ) {
1574 $idsPresent[] = $row->fa_id
;
1576 if ( $row->fa_name
!= $this->file
->getName() ) {
1577 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1578 $status->failCount++
;
1581 if ( $row->fa_storage_key
== '' ) {
1582 // Revision was missing pre-deletion
1583 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1584 $status->failCount++
;
1588 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1589 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1591 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1593 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1594 $sha1 = substr( $sha1, 1 );
1597 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1598 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1599 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1600 ||
is_null( $row->fa_metadata
) ) {
1601 // Refresh our metadata
1602 // Required for a new current revision; nice for older ones too. :)
1603 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1606 'minor_mime' => $row->fa_minor_mime
,
1607 'major_mime' => $row->fa_major_mime
,
1608 'media_type' => $row->fa_media_type
,
1609 'metadata' => $row->fa_metadata
1613 if ( $first && !$exists ) {
1614 // This revision will be published as the new current version
1615 $destRel = $this->file
->getRel();
1616 $insertCurrent = array(
1617 'img_name' => $row->fa_name
,
1618 'img_size' => $row->fa_size
,
1619 'img_width' => $row->fa_width
,
1620 'img_height' => $row->fa_height
,
1621 'img_metadata' => $props['metadata'],
1622 'img_bits' => $row->fa_bits
,
1623 'img_media_type' => $props['media_type'],
1624 'img_major_mime' => $props['major_mime'],
1625 'img_minor_mime' => $props['minor_mime'],
1626 'img_description' => $row->fa_description
,
1627 'img_user' => $row->fa_user
,
1628 'img_user_text' => $row->fa_user_text
,
1629 'img_timestamp' => $row->fa_timestamp
,
1632 // The live (current) version cannot be hidden!
1633 if( !$this->unsuppress
&& $row->fa_deleted
) {
1634 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1635 $this->cleanupBatch
[] = $row->fa_storage_key
;
1638 $archiveName = $row->fa_archive_name
;
1639 if( $archiveName == '' ) {
1640 // This was originally a current version; we
1641 // have to devise a new archive name for it.
1642 // Format is <timestamp of archiving>!<name>
1643 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1645 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1647 } while ( isset( $archiveNames[$archiveName] ) );
1649 $archiveNames[$archiveName] = true;
1650 $destRel = $this->file
->getArchiveRel( $archiveName );
1651 $insertBatch[] = array(
1652 'oi_name' => $row->fa_name
,
1653 'oi_archive_name' => $archiveName,
1654 'oi_size' => $row->fa_size
,
1655 'oi_width' => $row->fa_width
,
1656 'oi_height' => $row->fa_height
,
1657 'oi_bits' => $row->fa_bits
,
1658 'oi_description' => $row->fa_description
,
1659 'oi_user' => $row->fa_user
,
1660 'oi_user_text' => $row->fa_user_text
,
1661 'oi_timestamp' => $row->fa_timestamp
,
1662 'oi_metadata' => $props['metadata'],
1663 'oi_media_type' => $props['media_type'],
1664 'oi_major_mime' => $props['major_mime'],
1665 'oi_minor_mime' => $props['minor_mime'],
1666 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1667 'oi_sha1' => $sha1 );
1670 $deleteIds[] = $row->fa_id
;
1671 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1672 // private files can stay where they are
1673 $status->successCount++
;
1675 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1676 $this->cleanupBatch
[] = $row->fa_storage_key
;
1682 // Add a warning to the status object for missing IDs
1683 $missingIds = array_diff( $this->ids
, $idsPresent );
1684 foreach ( $missingIds as $id ) {
1685 $status->error( 'undelete-missing-filearchive', $id );
1688 // Remove missing files from batch, so we don't get errors when undeleting them
1689 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1691 // Run the store batch
1692 // Use the OVERWRITE_SAME flag to smooth over a common error
1693 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1694 $status->merge( $storeStatus );
1696 if ( !$status->ok
) {
1697 // Store batch returned a critical error -- this usually means nothing was stored
1698 // Stop now and return an error
1699 $this->file
->unlock();
1703 // Run the DB updates
1704 // Because we have locked the image row, key conflicts should be rare.
1705 // If they do occur, we can roll back the transaction at this time with
1706 // no data loss, but leaving unregistered files scattered throughout the
1708 // This is not ideal, which is why it's important to lock the image row.
1709 if ( $insertCurrent ) {
1710 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1712 if ( $insertBatch ) {
1713 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1716 $dbw->delete( 'filearchive',
1717 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1721 if( $status->successCount
> 0 ||
!$storeBatch ) { // If store batch is empty (all files are missing), deletion is to be considered successful
1723 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1725 // Update site_stats
1726 $site_stats = $dbw->tableName( 'site_stats' );
1727 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1729 $this->file
->purgeEverything();
1731 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1732 $this->file
->purgeDescription();
1733 $this->file
->purgeHistory();
1736 $this->file
->unlock();
1741 * Removes non-existent files from a store batch.
1743 function removeNonexistentFiles( $triplets ) {
1744 $files = $filteredTriplets = array();
1745 foreach( $triplets as $file )
1746 $files[$file[0]] = $file[0];
1747 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1748 foreach( $triplets as $file )
1749 if( $result[$file[0]] )
1750 $filteredTriplets[] = $file;
1751 return $filteredTriplets;
1755 * Removes non-existent files from a cleanup batch.
1757 function removeNonexistentFromCleanup( $batch ) {
1758 $files = $newBatch = array();
1759 $repo = $this->file
->repo
;
1760 foreach( $batch as $file ) {
1761 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1762 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1765 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1766 foreach( $batch as $file )
1767 if( $result[$file] )
1768 $newBatch[] = $file;
1773 * Delete unused files in the deleted zone.
1774 * This should be called from outside the transaction in which execute() was called.
1776 function cleanup() {
1777 if ( !$this->cleanupBatch
) {
1778 return $this->file
->repo
->newGood();
1780 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1781 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1786 #------------------------------------------------------------------------------
1789 * Helper class for file movement
1792 class LocalFileMoveBatch
{
1793 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1795 function __construct( File
$file, Title
$target ) {
1796 $this->file
= $file;
1797 $this->target
= $target;
1798 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1799 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBKey() );
1800 $this->oldName
= $this->file
->getName();
1801 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1802 $this->oldRel
= $this->oldHash
. $this->oldName
;
1803 $this->newRel
= $this->newHash
. $this->newName
;
1804 $this->db
= $file->repo
->getMasterDb();
1808 * Add the current image to the batch
1810 function addCurrent() {
1811 $this->cur
= array( $this->oldRel
, $this->newRel
);
1815 * Add the old versions of the image to the batch
1817 function addOlds() {
1818 $archiveBase = 'archive';
1819 $this->olds
= array();
1820 $this->oldCount
= 0;
1822 $result = $this->db
->select( 'oldimage',
1823 array( 'oi_archive_name', 'oi_deleted' ),
1824 array( 'oi_name' => $this->oldName
),
1827 while( $row = $this->db
->fetchObject( $result ) ) {
1828 $oldName = $row->oi_archive_name
;
1829 $bits = explode( '!', $oldName, 2 );
1830 if( count( $bits ) != 2 ) {
1831 wfDebug( "Invalid old file name: $oldName \n" );
1834 list( $timestamp, $filename ) = $bits;
1835 if( $this->oldName
!= $filename ) {
1836 wfDebug( "Invalid old file name: $oldName \n" );
1840 // Do we want to add those to oldCount?
1841 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1844 $this->olds
[] = array(
1845 "{$archiveBase}/{$this->oldHash}{$oldName}",
1846 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1849 $this->db
->freeResult( $result );
1855 function execute() {
1856 $repo = $this->file
->repo
;
1857 $status = $repo->newGood();
1858 $triplets = $this->getMoveTriplets();
1860 $triplets = $this->removeNonexistentFiles( $triplets );
1861 $statusDb = $this->doDBUpdates();
1862 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1863 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1864 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1865 if( !$statusMove->isOk() ) {
1866 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1867 $this->db
->rollback();
1870 $status->merge( $statusDb );
1871 $status->merge( $statusMove );
1876 * Do the database updates and return a new WikiError indicating how many
1877 * rows where updated.
1879 function doDBUpdates() {
1880 $repo = $this->file
->repo
;
1881 $status = $repo->newGood();
1884 // Update current image
1887 array( 'img_name' => $this->newName
),
1888 array( 'img_name' => $this->oldName
),
1891 if( $dbw->affectedRows() ) {
1892 $status->successCount++
;
1894 $status->failCount++
;
1897 // Update old images
1901 'oi_name' => $this->newName
,
1902 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1904 array( 'oi_name' => $this->oldName
),
1907 $affected = $dbw->affectedRows();
1908 $total = $this->oldCount
;
1909 $status->successCount +
= $affected;
1910 $status->failCount +
= $total - $affected;
1916 * Generate triplets for FSRepo::storeBatch().
1918 function getMoveTriplets() {
1919 $moves = array_merge( array( $this->cur
), $this->olds
);
1920 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1921 foreach( $moves as $move ) {
1922 // $move: (oldRelativePath, newRelativePath)
1923 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1924 $triplets[] = array( $srcUrl, 'public', $move[1] );
1925 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
1931 * Removes non-existent files from move batch.
1933 function removeNonexistentFiles( $triplets ) {
1935 foreach( $triplets as $file )
1936 $files[$file[0]] = $file[0];
1937 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1938 $filteredTriplets = array();
1939 foreach( $triplets as $file )
1940 if( $result[$file[0]] ) {
1941 $filteredTriplets[] = $file;
1943 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
1945 return $filteredTriplets;