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 for the main data for this file, or false if
137 * there is no access to the shared cache.
139 function getCacheKey() {
140 $hashedName = md5($this->getName());
141 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
145 * Try to load file metadata from memcached. Returns true on success.
147 function loadFromCache() {
149 wfProfileIn( __METHOD__
);
150 $this->dataLoaded
= false;
151 $key = $this->getCacheKey();
153 wfProfileOut( __METHOD__
);
156 $cachedValues = $wgMemc->get( $key );
158 // Check if the key existed and belongs to this version of MediaWiki
159 if ( isset($cachedValues['version']) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
160 wfDebug( "Pulling file metadata from cache key $key\n" );
161 $this->fileExists
= $cachedValues['fileExists'];
162 if ( $this->fileExists
) {
163 $this->setProps( $cachedValues );
165 $this->dataLoaded
= true;
167 if ( $this->dataLoaded
) {
168 wfIncrStats( 'image_cache_hit' );
170 wfIncrStats( 'image_cache_miss' );
173 wfProfileOut( __METHOD__
);
174 return $this->dataLoaded
;
178 * Save the file metadata to memcached
180 function saveToCache() {
183 $key = $this->getCacheKey();
187 $fields = $this->getCacheFields( '' );
188 $cache = array( 'version' => MW_FILE_VERSION
);
189 $cache['fileExists'] = $this->fileExists
;
190 if ( $this->fileExists
) {
191 foreach ( $fields as $field ) {
192 $cache[$field] = $this->$field;
196 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
200 * Load metadata from the file itself
202 function loadFromFile() {
203 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
206 function getCacheFields( $prefix = 'img_' ) {
207 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
208 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
209 static $results = array();
210 if ( $prefix == '' ) {
213 if ( !isset( $results[$prefix] ) ) {
214 $prefixedFields = array();
215 foreach ( $fields as $field ) {
216 $prefixedFields[] = $prefix . $field;
218 $results[$prefix] = $prefixedFields;
220 return $results[$prefix];
224 * Load file metadata from the DB
226 function loadFromDB() {
227 # Polymorphic function name to distinguish foreign and local fetches
228 $fname = get_class( $this ) . '::' . __FUNCTION__
;
229 wfProfileIn( $fname );
231 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
232 $this->dataLoaded
= true;
234 $dbr = $this->repo
->getMasterDB();
236 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
237 array( 'img_name' => $this->getName() ), $fname );
239 $this->loadFromRow( $row );
241 $this->fileExists
= false;
244 wfProfileOut( $fname );
248 * Decode a row from the database (either object or array) to an array
249 * with timestamps and MIME types decoded, and the field prefix removed.
251 function decodeRow( $row, $prefix = 'img_' ) {
252 $array = (array)$row;
253 $prefixLength = strlen( $prefix );
254 // Sanity check prefix once
255 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
256 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
259 foreach ( $array as $name => $value ) {
260 $decoded[substr( $name, $prefixLength )] = $value;
262 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
263 if ( empty( $decoded['major_mime'] ) ) {
264 $decoded['mime'] = "unknown/unknown";
266 if (!$decoded['minor_mime']) {
267 $decoded['minor_mime'] = "unknown";
269 $decoded['mime'] = $decoded['major_mime'].'/'.$decoded['minor_mime'];
271 # Trim zero padding from char/binary field
272 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
277 * Load file metadata from a DB result row
279 function loadFromRow( $row, $prefix = 'img_' ) {
280 $this->dataLoaded
= true;
281 $array = $this->decodeRow( $row, $prefix );
282 foreach ( $array as $name => $value ) {
283 $this->$name = $value;
285 $this->fileExists
= true;
286 $this->maybeUpgradeRow();
290 * Load file metadata from cache or DB, unless already loaded
293 if ( !$this->dataLoaded
) {
294 if ( !$this->loadFromCache() ) {
296 $this->saveToCache();
298 $this->dataLoaded
= true;
303 * Upgrade a row if it needs it
305 function maybeUpgradeRow() {
306 if ( wfReadOnly() ) {
309 if ( is_null($this->media_type
) ||
310 $this->mime
== 'image/svg'
313 $this->upgraded
= true;
315 $handler = $this->getHandler();
316 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
318 $this->upgraded
= true;
323 function getUpgraded() {
324 return $this->upgraded
;
328 * Fix assorted version-related problems with the image row by reloading it from the file
330 function upgradeRow() {
331 wfProfileIn( __METHOD__
);
333 $this->loadFromFile();
335 # Don't destroy file info of missing files
336 if ( !$this->fileExists
) {
337 wfDebug( __METHOD__
.": file does not exist, aborting\n" );
338 wfProfileOut( __METHOD__
);
341 $dbw = $this->repo
->getMasterDB();
342 list( $major, $minor ) = self
::splitMime( $this->mime
);
344 if ( wfReadOnly() ) {
345 wfProfileOut( __METHOD__
);
348 wfDebug(__METHOD__
.': upgrading '.$this->getName()." to the current schema\n");
350 $dbw->update( 'image',
352 'img_width' => $this->width
,
353 'img_height' => $this->height
,
354 'img_bits' => $this->bits
,
355 'img_media_type' => $this->media_type
,
356 'img_major_mime' => $major,
357 'img_minor_mime' => $minor,
358 'img_metadata' => $this->metadata
,
359 'img_sha1' => $this->sha1
,
360 ), array( 'img_name' => $this->getName() ),
363 $this->saveToCache();
364 wfProfileOut( __METHOD__
);
368 * Set properties in this object to be equal to those given in the
369 * associative array $info. Only cacheable fields can be set.
371 * If 'mime' is given, it will be split into major_mime/minor_mime.
372 * If major_mime/minor_mime are given, $this->mime will also be set.
374 function setProps( $info ) {
375 $this->dataLoaded
= true;
376 $fields = $this->getCacheFields( '' );
377 $fields[] = 'fileExists';
378 foreach ( $fields as $field ) {
379 if ( isset( $info[$field] ) ) {
380 $this->$field = $info[$field];
383 // Fix up mime fields
384 if ( isset( $info['major_mime'] ) ) {
385 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
386 } elseif ( isset( $info['mime'] ) ) {
387 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
391 /** splitMime inherited */
392 /** getName inherited */
393 /** getTitle inherited */
394 /** getURL inherited */
395 /** getViewURL inherited */
396 /** getPath inherited */
397 /** isVisible inhereted */
399 function isMissing() {
400 if( $this->missing
=== null ) {
401 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
402 $this->missing
= !$fileExists;
404 return $this->missing
;
408 * Return the width of the image
410 * Returns false on error
413 function getWidth( $page = 1 ) {
415 if ( $this->isMultipage() ) {
416 $dim = $this->getHandler()->getPageDimensions( $this, $page );
418 return $dim['width'];
428 * Return the height of the image
430 * Returns false on error
433 function getHeight( $page = 1 ) {
435 if ( $this->isMultipage() ) {
436 $dim = $this->getHandler()->getPageDimensions( $this, $page );
438 return $dim['height'];
443 return $this->height
;
448 * Returns ID or name of user who uploaded the file
450 * @param $type string 'text' or 'id'
452 function getUser($type='text') {
454 if( $type == 'text' ) {
455 return $this->user_text
;
456 } elseif( $type == 'id' ) {
462 * Get handler-specific metadata
464 function getMetadata() {
466 return $this->metadata
;
469 function getBitDepth() {
475 * Return the size of the image file, in bytes
484 * Returns the mime type of the file.
486 function getMimeType() {
492 * Return the type of the media in the file.
493 * Use the value returned by this function with the MEDIATYPE_xxx constants.
495 function getMediaType() {
497 return $this->media_type
;
500 /** canRender inherited */
501 /** mustRender inherited */
502 /** allowInlineDisplay inherited */
503 /** isSafeFile inherited */
504 /** isTrustedFile inherited */
507 * Returns true if the file file exists on disk.
508 * @return boolean Whether file file exist on disk.
513 return $this->fileExists
;
516 /** getTransformScript inherited */
517 /** getUnscaledThumb inherited */
518 /** thumbName inherited */
519 /** createThumb inherited */
520 /** getThumbnail inherited */
521 /** transform inherited */
524 * Fix thumbnail files from 1.4 or before, with extreme prejudice
526 function migrateThumbFile( $thumbName ) {
527 $thumbDir = $this->getThumbPath();
528 $thumbPath = "$thumbDir/$thumbName";
529 if ( is_dir( $thumbPath ) ) {
530 // Directory where file should be
531 // This happened occasionally due to broken migration code in 1.5
532 // Rename to broken-*
533 for ( $i = 0; $i < 100 ; $i++
) {
534 $broken = $this->repo
->getZonePath('public') . "/broken-$i-$thumbName";
535 if ( !file_exists( $broken ) ) {
536 rename( $thumbPath, $broken );
540 // Doesn't exist anymore
543 if ( is_file( $thumbDir ) ) {
544 // File where directory should be
546 // Doesn't exist anymore
551 /** getHandler inherited */
552 /** iconThumb inherited */
553 /** getLastError inherited */
556 * Get all thumbnail names previously generated for this file
558 function getThumbnails() {
561 $dir = $this->getThumbPath();
563 if ( is_dir( $dir ) ) {
564 $handle = opendir( $dir );
567 while ( false !== ( $file = readdir($handle) ) ) {
568 if ( $file{0} != '.' ) {
580 * Refresh metadata in memcached, but don't touch thumbnails or squid
582 function purgeMetadataCache() {
584 $this->saveToCache();
585 $this->purgeHistory();
589 * Purge the shared history (OldLocalFile) cache
591 function purgeHistory() {
593 $hashedName = md5($this->getName());
594 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
596 $wgMemc->delete( $oldKey );
601 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
603 function purgeCache() {
604 // Refresh metadata cache
605 $this->purgeMetadataCache();
608 $this->purgeThumbnails();
610 // Purge squid cache for this file
611 SquidUpdate
::purge( array( $this->getURL() ) );
615 * Delete cached transformed files
617 function purgeThumbnails() {
620 $files = $this->getThumbnails();
621 $dir = $this->getThumbPath();
623 foreach ( $files as $file ) {
624 # Check that the base file name is part of the thumb name
625 # This is a basic sanity check to avoid erasing unrelated directories
626 if ( strpos( $file, $this->getName() ) !== false ) {
627 $url = $this->getThumbUrl( $file );
629 @unlink
( "$dir/$file" );
635 SquidUpdate
::purge( $urls );
639 /** purgeDescription inherited */
640 /** purgeEverything inherited */
642 function getHistory($limit = null, $start = null, $end = null, $inc = true) {
643 $dbr = $this->repo
->getSlaveDB();
644 $tables = array('oldimage');
645 $fields = OldLocalFile
::selectFields();
646 $conds = $opts = $join_conds = array();
647 $eq = $inc ?
"=" : "";
648 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
650 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
653 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
656 $opts['LIMIT'] = $limit;
658 // Search backwards for time > x queries
659 $order = (!$start && $end !== null) ?
"ASC" : "DESC";
660 $opts['ORDER BY'] = "oi_timestamp $order";
661 $opts['USE INDEX'] = array('oldimage' => 'oi_name_timestamp');
663 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
664 &$conds, &$opts, &$join_conds ) );
666 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
668 while( $row = $dbr->fetchObject($res) ) {
669 $r[] = OldLocalFile
::newFromRow($row, $this->repo
);
671 if( $order == "ASC" ) {
672 $r = array_reverse( $r ); // make sure it ends up descending
678 * Return the history of this file, line by line.
679 * starts with current version, then old versions.
680 * uses $this->historyLine to check which line to return:
681 * 0 return line for current version
682 * 1 query for old versions, return first one
683 * 2, ... return next old version from above query
687 function nextHistoryLine() {
688 # Polymorphic function name to distinguish foreign and local fetches
689 $fname = get_class( $this ) . '::' . __FUNCTION__
;
691 $dbr = $this->repo
->getSlaveDB();
693 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
694 $this->historyRes
= $dbr->select( 'image',
697 "'' AS oi_archive_name",
701 array( 'img_name' => $this->title
->getDBkey() ),
704 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
705 $dbr->freeResult($this->historyRes
);
706 $this->historyRes
= null;
709 } else if ( $this->historyLine
== 1 ) {
710 $dbr->freeResult($this->historyRes
);
711 $this->historyRes
= $dbr->select( 'oldimage', '*',
712 array( 'oi_name' => $this->title
->getDBkey() ),
714 array( 'ORDER BY' => 'oi_timestamp DESC' )
717 $this->historyLine ++
;
719 return $dbr->fetchObject( $this->historyRes
);
723 * Reset the history pointer to the first element of the history
726 function resetHistory() {
727 $this->historyLine
= 0;
728 if (!is_null($this->historyRes
)) {
729 $this->repo
->getSlaveDB()->freeResult($this->historyRes
);
730 $this->historyRes
= null;
734 /** getFullPath inherited */
735 /** getHashPath inherited */
736 /** getRel inherited */
737 /** getUrlRel inherited */
738 /** getArchiveRel inherited */
739 /** getThumbRel inherited */
740 /** getArchivePath inherited */
741 /** getThumbPath inherited */
742 /** getArchiveUrl inherited */
743 /** getThumbUrl inherited */
744 /** getArchiveVirtualUrl inherited */
745 /** getThumbVirtualUrl inherited */
746 /** isHashed inherited */
749 * Upload a file and record it in the DB
750 * @param string $srcPath Source path or virtual URL
751 * @param string $comment Upload description
752 * @param string $pageText Text to use for the new description page, if a new description page is created
753 * @param integer $flags Flags for publish()
754 * @param array $props File properties, if known. This can be used to reduce the
755 * upload time when uploading virtual URLs for which the file info
757 * @param string $timestamp Timestamp for img_timestamp, or false to use the current time
759 * @return FileRepoStatus object. On success, the value member contains the
760 * archive name, or an empty string if it was a new file.
762 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
764 $status = $this->publish( $srcPath, $flags );
766 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
767 $status->fatal( 'filenotfound', $srcPath );
775 * Record a file upload in the upload log and the image table
776 * @deprecated use upload()
778 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
779 $watch = false, $timestamp = false )
781 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
782 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
787 $wgUser->addWatch( $this->getTitle() );
794 * Record a file upload in the upload log and the image table
796 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
798 if( is_null( $user ) ) {
803 $dbw = $this->repo
->getMasterDB();
807 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
809 $props['description'] = $comment;
810 $props['user'] = $user->getId();
811 $props['user_text'] = $user->getName();
812 $props['timestamp'] = wfTimestamp( TS_MW
);
813 $this->setProps( $props );
815 // Delete thumbnails and refresh the metadata cache
816 $this->purgeThumbnails();
817 $this->saveToCache();
818 SquidUpdate
::purge( array( $this->getURL() ) );
820 // Fail now if the file isn't there
821 if ( !$this->fileExists
) {
822 wfDebug( __METHOD__
.": File ".$this->getPath()." went missing!\n" );
827 if ( $timestamp === false ) {
828 $timestamp = $dbw->timestamp();
831 # Test to see if the row exists using INSERT IGNORE
832 # This avoids race conditions by locking the row until the commit, and also
833 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
834 $dbw->insert( 'image',
836 'img_name' => $this->getName(),
837 'img_size'=> $this->size
,
838 'img_width' => intval( $this->width
),
839 'img_height' => intval( $this->height
),
840 'img_bits' => $this->bits
,
841 'img_media_type' => $this->media_type
,
842 'img_major_mime' => $this->major_mime
,
843 'img_minor_mime' => $this->minor_mime
,
844 'img_timestamp' => $timestamp,
845 'img_description' => $comment,
846 'img_user' => $user->getId(),
847 'img_user_text' => $user->getName(),
848 'img_metadata' => $this->metadata
,
849 'img_sha1' => $this->sha1
855 if( $dbw->affectedRows() == 0 ) {
858 # Collision, this is an update of a file
859 # Insert previous contents into oldimage
860 $dbw->insertSelect( 'oldimage', 'image',
862 'oi_name' => 'img_name',
863 'oi_archive_name' => $dbw->addQuotes( $oldver ),
864 'oi_size' => 'img_size',
865 'oi_width' => 'img_width',
866 'oi_height' => 'img_height',
867 'oi_bits' => 'img_bits',
868 'oi_timestamp' => 'img_timestamp',
869 'oi_description' => 'img_description',
870 'oi_user' => 'img_user',
871 'oi_user_text' => 'img_user_text',
872 'oi_metadata' => 'img_metadata',
873 'oi_media_type' => 'img_media_type',
874 'oi_major_mime' => 'img_major_mime',
875 'oi_minor_mime' => 'img_minor_mime',
876 'oi_sha1' => 'img_sha1'
877 ), array( 'img_name' => $this->getName() ), __METHOD__
880 # Update the current image row
881 $dbw->update( 'image',
883 'img_size' => $this->size
,
884 'img_width' => intval( $this->width
),
885 'img_height' => intval( $this->height
),
886 'img_bits' => $this->bits
,
887 'img_media_type' => $this->media_type
,
888 'img_major_mime' => $this->major_mime
,
889 'img_minor_mime' => $this->minor_mime
,
890 'img_timestamp' => $timestamp,
891 'img_description' => $comment,
892 'img_user' => $user->getId(),
893 'img_user_text' => $user->getName(),
894 'img_metadata' => $this->metadata
,
895 'img_sha1' => $this->sha1
896 ), array( /* WHERE */
897 'img_name' => $this->getName()
902 # Update the image count
903 $site_stats = $dbw->tableName( 'site_stats' );
904 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
907 $descTitle = $this->getTitle();
908 $article = new ImagePage( $descTitle );
909 $article->setFile( $this );
912 $log = new LogPage( 'upload' );
913 $action = $reupload ?
'overwrite' : 'upload';
914 $log->addEntry( $action, $descTitle, $comment, array(), $user );
916 if( $descTitle->exists() ) {
917 # Create a null revision
918 $latest = $descTitle->getLatestRevID();
919 $nullRevision = Revision
::newNullRevision( $dbw, $descTitle->getArticleId(),
920 $log->getRcComment(), false );
921 $nullRevision->insertOn( $dbw );
923 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $user) );
924 $article->updateRevisionOn( $dbw, $nullRevision );
926 # Invalidate the cache for the description page
927 $descTitle->invalidateCache();
928 $descTitle->purgeSquid();
930 // New file; create the description page.
931 // There's already a log entry, so don't make a second RC entry
932 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
935 # Hooks, hooks, the magic of hooks...
936 wfRunHooks( 'FileUpload', array( $this ) );
938 # Commit the transaction now, in case something goes wrong later
939 # The most important thing is that files don't get lost, especially archives
940 $dbw->immediateCommit();
942 # Invalidate cache for all pages using this file
943 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
945 # Invalidate cache for all pages that redirects on this page
946 $redirs = $this->getTitle()->getRedirectsHere();
947 foreach( $redirs as $redir ) {
948 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
956 * Move or copy a file to its public location. If a file exists at the
957 * destination, move it to an archive. Returns the archive name on success
958 * or an empty string if it was a new file, and a wikitext-formatted
959 * WikiError object on failure.
961 * The archive name should be passed through to recordUpload for database
964 * @param string $sourcePath Local filesystem path to the source image
965 * @param integer $flags A bitwise combination of:
966 * File::DELETE_SOURCE Delete the source file, i.e. move
968 * @return FileRepoStatus object. On success, the value member contains the
969 * archive name, or an empty string if it was a new file.
971 function publish( $srcPath, $flags = 0 ) {
973 $dstRel = $this->getRel();
974 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
975 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
976 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
977 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
978 if ( $status->value
== 'new' ) {
981 $status->value
= $archiveName;
987 /** getLinksTo inherited */
988 /** getExifData inherited */
989 /** isLocal inherited */
990 /** wasDeleted inherited */
993 * Move file to the new title
995 * Move current, old version and all thumbnails
996 * to the new filename. Old file is deleted.
998 * Cache purging is done; checks for validity
999 * and logging are caller's responsibility
1001 * @param $target Title New file name
1002 * @return FileRepoStatus object.
1004 function move( $target ) {
1005 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1007 $batch = new LocalFileMoveBatch( $this, $target );
1008 $batch->addCurrent();
1011 $status = $batch->execute();
1012 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1013 $this->purgeEverything();
1016 if ( $status->isOk() ) {
1017 // Now switch the object
1018 $this->title
= $target;
1019 // Force regeneration of the name and hashpath
1020 unset( $this->name
);
1021 unset( $this->hashPath
);
1022 // Purge the new image
1023 $this->purgeEverything();
1030 * Delete all versions of the file.
1032 * Moves the files into an archive directory (or deletes them)
1033 * and removes the database rows.
1035 * Cache purging is done; logging is caller's responsibility.
1039 * @return FileRepoStatus object.
1041 function delete( $reason, $suppress = false ) {
1043 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1044 $batch->addCurrent();
1046 # Get old version relative paths
1047 $dbw = $this->repo
->getMasterDB();
1048 $result = $dbw->select( 'oldimage',
1049 array( 'oi_archive_name' ),
1050 array( 'oi_name' => $this->getName() ) );
1051 while ( $row = $dbw->fetchObject( $result ) ) {
1052 $batch->addOld( $row->oi_archive_name
);
1054 $status = $batch->execute();
1056 if ( $status->ok
) {
1057 // Update site_stats
1058 $site_stats = $dbw->tableName( 'site_stats' );
1059 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1060 $this->purgeEverything();
1068 * Delete an old version of the file.
1070 * Moves the file into an archive directory (or deletes it)
1071 * and removes the database row.
1073 * Cache purging is done; logging is caller's responsibility.
1077 * @throws MWException or FSException on database or file store failure
1078 * @return FileRepoStatus object.
1080 function deleteOld( $archiveName, $reason, $suppress=false ) {
1082 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1083 $batch->addOld( $archiveName );
1084 $status = $batch->execute();
1086 if ( $status->ok
) {
1087 $this->purgeDescription();
1088 $this->purgeHistory();
1094 * Restore all or specified deleted revisions to the given file.
1095 * Permissions and logging are left to the caller.
1097 * May throw database exceptions on error.
1099 * @param $versions set of record ids of deleted items to restore,
1100 * or empty to restore all revisions.
1102 * @return FileRepoStatus
1104 function restore( $versions = array(), $unsuppress = false ) {
1105 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1109 $batch->addIds( $versions );
1111 $status = $batch->execute();
1112 if ( !$status->ok
) {
1116 $cleanupStatus = $batch->cleanup();
1117 $cleanupStatus->successCount
= 0;
1118 $cleanupStatus->failCount
= 0;
1119 $status->merge( $cleanupStatus );
1123 /** isMultipage inherited */
1124 /** pageCount inherited */
1125 /** scaleHeight inherited */
1126 /** getImageSize inherited */
1129 * Get the URL of the file description page.
1131 function getDescriptionUrl() {
1132 return $this->title
->getLocalUrl();
1136 * Get the HTML text of the description page
1137 * This is not used by ImagePage for local files, since (among other things)
1138 * it skips the parser cache.
1140 function getDescriptionText() {
1142 $revision = Revision
::newFromTitle( $this->title
);
1143 if ( !$revision ) return false;
1144 $text = $revision->getText();
1145 if ( !$text ) return false;
1146 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1147 return $pout->getText();
1150 function getDescription() {
1152 return $this->description
;
1155 function getTimestamp() {
1157 return $this->timestamp
;
1160 function getSha1() {
1162 // Initialise now if necessary
1163 if ( $this->sha1
== '' && $this->fileExists
) {
1164 $this->sha1
= File
::sha1Base36( $this->getPath() );
1165 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1166 $dbw = $this->repo
->getMasterDB();
1167 $dbw->update( 'image',
1168 array( 'img_sha1' => $this->sha1
),
1169 array( 'img_name' => $this->getName() ),
1171 $this->saveToCache();
1179 * Start a transaction and lock the image for update
1180 * Increments a reference counter if the lock is already held
1181 * @return boolean True if the image exists, false otherwise
1184 $dbw = $this->repo
->getMasterDB();
1185 if ( !$this->locked
) {
1189 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1193 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1194 * the transaction and thereby releases the image lock.
1197 if ( $this->locked
) {
1199 if ( !$this->locked
) {
1200 $dbw = $this->repo
->getMasterDB();
1207 * Roll back the DB transaction and mark the image unlocked
1209 function unlockAndRollback() {
1210 $this->locked
= false;
1211 $dbw = $this->repo
->getMasterDB();
1214 } // LocalFile class
1216 #------------------------------------------------------------------------------
1219 * Helper class for file deletion
1222 class LocalFileDeleteBatch
{
1223 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1226 function __construct( File
$file, $reason = '', $suppress = false ) {
1227 $this->file
= $file;
1228 $this->reason
= $reason;
1229 $this->suppress
= $suppress;
1230 $this->status
= $file->repo
->newGood();
1233 function addCurrent() {
1234 $this->srcRels
['.'] = $this->file
->getRel();
1237 function addOld( $oldName ) {
1238 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1239 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1242 function getOldRels() {
1243 if ( !isset( $this->srcRels
['.'] ) ) {
1244 $oldRels =& $this->srcRels
;
1245 $deleteCurrent = false;
1247 $oldRels = $this->srcRels
;
1248 unset( $oldRels['.'] );
1249 $deleteCurrent = true;
1251 return array( $oldRels, $deleteCurrent );
1254 /*protected*/ function getHashes() {
1256 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1257 if ( $deleteCurrent ) {
1258 $hashes['.'] = $this->file
->getSha1();
1260 if ( count( $oldRels ) ) {
1261 $dbw = $this->file
->repo
->getMasterDB();
1262 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1263 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1265 while ( $row = $dbw->fetchObject( $res ) ) {
1266 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1267 // Get the hash from the file
1268 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1269 $props = $this->file
->repo
->getFileProps( $oldUrl );
1270 if ( $props['fileExists'] ) {
1271 // Upgrade the oldimage row
1272 $dbw->update( 'oldimage',
1273 array( 'oi_sha1' => $props['sha1'] ),
1274 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1276 $hashes[$row->oi_archive_name
] = $props['sha1'];
1278 $hashes[$row->oi_archive_name
] = false;
1281 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1285 $missing = array_diff_key( $this->srcRels
, $hashes );
1286 foreach ( $missing as $name => $rel ) {
1287 $this->status
->error( 'filedelete-old-unregistered', $name );
1289 foreach ( $hashes as $name => $hash ) {
1291 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1292 unset( $hashes[$name] );
1299 function doDBInserts() {
1301 $dbw = $this->file
->repo
->getMasterDB();
1302 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1303 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1304 $encReason = $dbw->addQuotes( $this->reason
);
1305 $encGroup = $dbw->addQuotes( 'deleted' );
1306 $ext = $this->file
->getExtension();
1307 $dotExt = $ext === '' ?
'' : ".$ext";
1308 $encExt = $dbw->addQuotes( $dotExt );
1309 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1311 // Bitfields to further suppress the content
1312 if ( $this->suppress
) {
1314 // This should be 15...
1315 $bitfield |
= Revision
::DELETED_TEXT
;
1316 $bitfield |
= Revision
::DELETED_COMMENT
;
1317 $bitfield |
= Revision
::DELETED_USER
;
1318 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1320 $bitfield = 'oi_deleted';
1323 if ( $deleteCurrent ) {
1324 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1325 $where = array( 'img_name' => $this->file
->getName() );
1326 $dbw->insertSelect( 'filearchive', 'image',
1328 'fa_storage_group' => $encGroup,
1329 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1330 'fa_deleted_user' => $encUserId,
1331 'fa_deleted_timestamp' => $encTimestamp,
1332 'fa_deleted_reason' => $encReason,
1333 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1335 'fa_name' => 'img_name',
1336 'fa_archive_name' => 'NULL',
1337 'fa_size' => 'img_size',
1338 'fa_width' => 'img_width',
1339 'fa_height' => 'img_height',
1340 'fa_metadata' => 'img_metadata',
1341 'fa_bits' => 'img_bits',
1342 'fa_media_type' => 'img_media_type',
1343 'fa_major_mime' => 'img_major_mime',
1344 'fa_minor_mime' => 'img_minor_mime',
1345 'fa_description' => 'img_description',
1346 'fa_user' => 'img_user',
1347 'fa_user_text' => 'img_user_text',
1348 'fa_timestamp' => 'img_timestamp'
1349 ), $where, __METHOD__
);
1352 if ( count( $oldRels ) ) {
1353 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1355 'oi_name' => $this->file
->getName(),
1356 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1357 $dbw->insertSelect( 'filearchive', 'oldimage',
1359 'fa_storage_group' => $encGroup,
1360 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1361 'fa_deleted_user' => $encUserId,
1362 'fa_deleted_timestamp' => $encTimestamp,
1363 'fa_deleted_reason' => $encReason,
1364 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1366 'fa_name' => 'oi_name',
1367 'fa_archive_name' => 'oi_archive_name',
1368 'fa_size' => 'oi_size',
1369 'fa_width' => 'oi_width',
1370 'fa_height' => 'oi_height',
1371 'fa_metadata' => 'oi_metadata',
1372 'fa_bits' => 'oi_bits',
1373 'fa_media_type' => 'oi_media_type',
1374 'fa_major_mime' => 'oi_major_mime',
1375 'fa_minor_mime' => 'oi_minor_mime',
1376 'fa_description' => 'oi_description',
1377 'fa_user' => 'oi_user',
1378 'fa_user_text' => 'oi_user_text',
1379 'fa_timestamp' => 'oi_timestamp',
1380 'fa_deleted' => $bitfield
1381 ), $where, __METHOD__
);
1385 function doDBDeletes() {
1386 $dbw = $this->file
->repo
->getMasterDB();
1387 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1388 if ( count( $oldRels ) ) {
1389 $dbw->delete( 'oldimage',
1391 'oi_name' => $this->file
->getName(),
1392 'oi_archive_name' => array_keys( $oldRels )
1395 if ( $deleteCurrent ) {
1396 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1401 * Run the transaction
1403 function execute() {
1405 wfProfileIn( __METHOD__
);
1407 $this->file
->lock();
1408 // Leave private files alone
1409 $privateFiles = array();
1410 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1411 $dbw = $this->file
->repo
->getMasterDB();
1412 if( !empty( $oldRels ) ) {
1413 $res = $dbw->select( 'oldimage',
1414 array( 'oi_archive_name' ),
1415 array( 'oi_name' => $this->file
->getName(),
1416 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1417 $dbw->bitAnd('oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1419 while( $row = $dbw->fetchObject( $res ) ) {
1420 $privateFiles[$row->oi_archive_name
] = 1;
1423 // Prepare deletion batch
1424 $hashes = $this->getHashes();
1425 $this->deletionBatch
= array();
1426 $ext = $this->file
->getExtension();
1427 $dotExt = $ext === '' ?
'' : ".$ext";
1428 foreach ( $this->srcRels
as $name => $srcRel ) {
1429 // Skip files that have no hash (missing source).
1430 // Keep private files where they are.
1431 if ( isset($hashes[$name]) && !array_key_exists($name,$privateFiles) ) {
1432 $hash = $hashes[$name];
1433 $key = $hash . $dotExt;
1434 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1435 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1439 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1440 // We acquire this lock by running the inserts now, before the file operations.
1442 // This potentially has poor lock contention characteristics -- an alternative
1443 // scheme would be to insert stub filearchive entries with no fa_name and commit
1444 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1445 $this->doDBInserts();
1447 // Removes non-existent file from the batch, so we don't get errors.
1448 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1450 // Execute the file deletion batch
1451 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1452 if ( !$status->isGood() ) {
1453 $this->status
->merge( $status );
1456 if ( !$this->status
->ok
) {
1457 // Critical file deletion error
1458 // Roll back inserts, release lock and abort
1459 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1460 $this->file
->unlockAndRollback();
1461 wfProfileOut( __METHOD__
);
1462 return $this->status
;
1466 if ( $wgUseSquid ) {
1468 foreach ( $this->srcRels
as $srcRel ) {
1469 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1470 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1472 SquidUpdate
::purge( $urls );
1475 // Delete image/oldimage rows
1476 $this->doDBDeletes();
1478 // Commit and return
1479 $this->file
->unlock();
1480 wfProfileOut( __METHOD__
);
1481 return $this->status
;
1485 * Removes non-existent files from a deletion batch.
1487 function removeNonexistentFiles( $batch ) {
1488 $files = $newBatch = array();
1489 foreach( $batch as $batchItem ) {
1490 list( $src, $dest ) = $batchItem;
1491 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1493 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1494 foreach( $batch as $batchItem )
1495 if( $result[$batchItem[0]] )
1496 $newBatch[] = $batchItem;
1501 #------------------------------------------------------------------------------
1504 * Helper class for file undeletion
1507 class LocalFileRestoreBatch
{
1508 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1510 function __construct( File
$file, $unsuppress = false ) {
1511 $this->file
= $file;
1512 $this->cleanupBatch
= $this->ids
= array();
1513 $this->ids
= array();
1514 $this->unsuppress
= $unsuppress;
1520 function addId( $fa_id ) {
1521 $this->ids
[] = $fa_id;
1525 * Add a whole lot of files by ID
1527 function addIds( $ids ) {
1528 $this->ids
= array_merge( $this->ids
, $ids );
1532 * Add all revisions of the file
1539 * Run the transaction, except the cleanup batch.
1540 * The cleanup batch should be run in a separate transaction, because it locks different
1541 * rows and there's no need to keep the image row locked while it's acquiring those locks
1542 * The caller may have its own transaction open.
1543 * So we save the batch and let the caller call cleanup()
1545 function execute() {
1547 if ( !$this->all
&& !$this->ids
) {
1549 return $this->file
->repo
->newGood();
1552 $exists = $this->file
->lock();
1553 $dbw = $this->file
->repo
->getMasterDB();
1554 $status = $this->file
->repo
->newGood();
1556 // Fetch all or selected archived revisions for the file,
1557 // sorted from the most recent to the oldest.
1558 $conditions = array( 'fa_name' => $this->file
->getName() );
1560 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1563 $result = $dbw->select( 'filearchive', '*',
1566 array( 'ORDER BY' => 'fa_timestamp DESC' )
1569 $idsPresent = array();
1570 $storeBatch = array();
1571 $insertBatch = array();
1572 $insertCurrent = false;
1573 $deleteIds = array();
1575 $archiveNames = array();
1576 while( $row = $dbw->fetchObject( $result ) ) {
1577 $idsPresent[] = $row->fa_id
;
1579 if ( $row->fa_name
!= $this->file
->getName() ) {
1580 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1581 $status->failCount++
;
1584 if ( $row->fa_storage_key
== '' ) {
1585 // Revision was missing pre-deletion
1586 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1587 $status->failCount++
;
1591 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1592 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1594 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1596 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1597 $sha1 = substr( $sha1, 1 );
1600 if( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1601 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1602 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1603 ||
is_null( $row->fa_metadata
) ) {
1604 // Refresh our metadata
1605 // Required for a new current revision; nice for older ones too. :)
1606 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1609 'minor_mime' => $row->fa_minor_mime
,
1610 'major_mime' => $row->fa_major_mime
,
1611 'media_type' => $row->fa_media_type
,
1612 'metadata' => $row->fa_metadata
1616 if ( $first && !$exists ) {
1617 // This revision will be published as the new current version
1618 $destRel = $this->file
->getRel();
1619 $insertCurrent = array(
1620 'img_name' => $row->fa_name
,
1621 'img_size' => $row->fa_size
,
1622 'img_width' => $row->fa_width
,
1623 'img_height' => $row->fa_height
,
1624 'img_metadata' => $props['metadata'],
1625 'img_bits' => $row->fa_bits
,
1626 'img_media_type' => $props['media_type'],
1627 'img_major_mime' => $props['major_mime'],
1628 'img_minor_mime' => $props['minor_mime'],
1629 'img_description' => $row->fa_description
,
1630 'img_user' => $row->fa_user
,
1631 'img_user_text' => $row->fa_user_text
,
1632 'img_timestamp' => $row->fa_timestamp
,
1635 // The live (current) version cannot be hidden!
1636 if( !$this->unsuppress
&& $row->fa_deleted
) {
1637 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1638 $this->cleanupBatch
[] = $row->fa_storage_key
;
1641 $archiveName = $row->fa_archive_name
;
1642 if( $archiveName == '' ) {
1643 // This was originally a current version; we
1644 // have to devise a new archive name for it.
1645 // Format is <timestamp of archiving>!<name>
1646 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1648 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1650 } while ( isset( $archiveNames[$archiveName] ) );
1652 $archiveNames[$archiveName] = true;
1653 $destRel = $this->file
->getArchiveRel( $archiveName );
1654 $insertBatch[] = array(
1655 'oi_name' => $row->fa_name
,
1656 'oi_archive_name' => $archiveName,
1657 'oi_size' => $row->fa_size
,
1658 'oi_width' => $row->fa_width
,
1659 'oi_height' => $row->fa_height
,
1660 'oi_bits' => $row->fa_bits
,
1661 'oi_description' => $row->fa_description
,
1662 'oi_user' => $row->fa_user
,
1663 'oi_user_text' => $row->fa_user_text
,
1664 'oi_timestamp' => $row->fa_timestamp
,
1665 'oi_metadata' => $props['metadata'],
1666 'oi_media_type' => $props['media_type'],
1667 'oi_major_mime' => $props['major_mime'],
1668 'oi_minor_mime' => $props['minor_mime'],
1669 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1670 'oi_sha1' => $sha1 );
1673 $deleteIds[] = $row->fa_id
;
1674 if( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1675 // private files can stay where they are
1676 $status->successCount++
;
1678 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1679 $this->cleanupBatch
[] = $row->fa_storage_key
;
1685 // Add a warning to the status object for missing IDs
1686 $missingIds = array_diff( $this->ids
, $idsPresent );
1687 foreach ( $missingIds as $id ) {
1688 $status->error( 'undelete-missing-filearchive', $id );
1691 // Remove missing files from batch, so we don't get errors when undeleting them
1692 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1694 // Run the store batch
1695 // Use the OVERWRITE_SAME flag to smooth over a common error
1696 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1697 $status->merge( $storeStatus );
1699 if ( !$status->ok
) {
1700 // Store batch returned a critical error -- this usually means nothing was stored
1701 // Stop now and return an error
1702 $this->file
->unlock();
1706 // Run the DB updates
1707 // Because we have locked the image row, key conflicts should be rare.
1708 // If they do occur, we can roll back the transaction at this time with
1709 // no data loss, but leaving unregistered files scattered throughout the
1711 // This is not ideal, which is why it's important to lock the image row.
1712 if ( $insertCurrent ) {
1713 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1715 if ( $insertBatch ) {
1716 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1719 $dbw->delete( 'filearchive',
1720 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1724 if( $status->successCount
> 0 ||
!$storeBatch ) { // If store batch is empty (all files are missing), deletion is to be considered successful
1726 wfDebug( __METHOD__
." restored {$status->successCount} items, creating a new current\n" );
1728 // Update site_stats
1729 $site_stats = $dbw->tableName( 'site_stats' );
1730 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1732 $this->file
->purgeEverything();
1734 wfDebug( __METHOD__
." restored {$status->successCount} as archived versions\n" );
1735 $this->file
->purgeDescription();
1736 $this->file
->purgeHistory();
1739 $this->file
->unlock();
1744 * Removes non-existent files from a store batch.
1746 function removeNonexistentFiles( $triplets ) {
1747 $files = $filteredTriplets = array();
1748 foreach( $triplets as $file )
1749 $files[$file[0]] = $file[0];
1750 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1751 foreach( $triplets as $file )
1752 if( $result[$file[0]] )
1753 $filteredTriplets[] = $file;
1754 return $filteredTriplets;
1758 * Removes non-existent files from a cleanup batch.
1760 function removeNonexistentFromCleanup( $batch ) {
1761 $files = $newBatch = array();
1762 $repo = $this->file
->repo
;
1763 foreach( $batch as $file ) {
1764 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1765 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1768 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1769 foreach( $batch as $file )
1770 if( $result[$file] )
1771 $newBatch[] = $file;
1776 * Delete unused files in the deleted zone.
1777 * This should be called from outside the transaction in which execute() was called.
1779 function cleanup() {
1780 if ( !$this->cleanupBatch
) {
1781 return $this->file
->repo
->newGood();
1783 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1784 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1789 #------------------------------------------------------------------------------
1792 * Helper class for file movement
1795 class LocalFileMoveBatch
{
1796 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1798 function __construct( File
$file, Title
$target ) {
1799 $this->file
= $file;
1800 $this->target
= $target;
1801 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1802 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1803 $this->oldName
= $this->file
->getName();
1804 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1805 $this->oldRel
= $this->oldHash
. $this->oldName
;
1806 $this->newRel
= $this->newHash
. $this->newName
;
1807 $this->db
= $file->repo
->getMasterDb();
1811 * Add the current image to the batch
1813 function addCurrent() {
1814 $this->cur
= array( $this->oldRel
, $this->newRel
);
1818 * Add the old versions of the image to the batch
1820 function addOlds() {
1821 $archiveBase = 'archive';
1822 $this->olds
= array();
1823 $this->oldCount
= 0;
1825 $result = $this->db
->select( 'oldimage',
1826 array( 'oi_archive_name', 'oi_deleted' ),
1827 array( 'oi_name' => $this->oldName
),
1830 while( $row = $this->db
->fetchObject( $result ) ) {
1831 $oldName = $row->oi_archive_name
;
1832 $bits = explode( '!', $oldName, 2 );
1833 if( count( $bits ) != 2 ) {
1834 wfDebug( "Invalid old file name: $oldName \n" );
1837 list( $timestamp, $filename ) = $bits;
1838 if( $this->oldName
!= $filename ) {
1839 wfDebug( "Invalid old file name: $oldName \n" );
1843 // Do we want to add those to oldCount?
1844 if( $row->oi_deleted
& File
::DELETED_FILE
) {
1847 $this->olds
[] = array(
1848 "{$archiveBase}/{$this->oldHash}{$oldName}",
1849 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1852 $this->db
->freeResult( $result );
1858 function execute() {
1859 $repo = $this->file
->repo
;
1860 $status = $repo->newGood();
1861 $triplets = $this->getMoveTriplets();
1863 $triplets = $this->removeNonexistentFiles( $triplets );
1864 $statusDb = $this->doDBUpdates();
1865 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1866 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
1867 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1868 if( !$statusMove->isOk() ) {
1869 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1870 $this->db
->rollback();
1873 $status->merge( $statusDb );
1874 $status->merge( $statusMove );
1879 * Do the database updates and return a new WikiError indicating how many
1880 * rows where updated.
1882 function doDBUpdates() {
1883 $repo = $this->file
->repo
;
1884 $status = $repo->newGood();
1887 // Update current image
1890 array( 'img_name' => $this->newName
),
1891 array( 'img_name' => $this->oldName
),
1894 if( $dbw->affectedRows() ) {
1895 $status->successCount++
;
1897 $status->failCount++
;
1900 // Update old images
1904 'oi_name' => $this->newName
,
1905 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName
), $dbw->addQuotes($this->newName
) ),
1907 array( 'oi_name' => $this->oldName
),
1910 $affected = $dbw->affectedRows();
1911 $total = $this->oldCount
;
1912 $status->successCount +
= $affected;
1913 $status->failCount +
= $total - $affected;
1919 * Generate triplets for FSRepo::storeBatch().
1921 function getMoveTriplets() {
1922 $moves = array_merge( array( $this->cur
), $this->olds
);
1923 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1924 foreach( $moves as $move ) {
1925 // $move: (oldRelativePath, newRelativePath)
1926 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1927 $triplets[] = array( $srcUrl, 'public', $move[1] );
1928 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
1934 * Removes non-existent files from move batch.
1936 function removeNonexistentFiles( $triplets ) {
1938 foreach( $triplets as $file )
1939 $files[$file[0]] = $file[0];
1940 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1941 $filteredTriplets = array();
1942 foreach( $triplets as $file )
1943 if( $result[$file[0]] ) {
1944 $filteredTriplets[] = $file;
1946 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
1948 return $filteredTriplets;