3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
25 * Bump this number when serialized cache records may be incompatible.
27 define( 'MW_FILE_VERSION', 8 );
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
39 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * @ingroup FileAbstraction
46 class LocalFile
extends File
{
47 const CACHE_FIELD_MAX_LEN
= 1000;
53 $fileExists, # does the file exist on disk? (loadFromXxx)
54 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
55 $historyRes, # result of the query for the file's history (nextHistoryLine)
58 $bits, # --- returned by getimagesize (loadFromXxx)
60 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
61 $mime, # MIME type, determined by MimeMagic::guessMimeType
62 $major_mime, # Major mime type
63 $minor_mime, # Minor mime type
64 $size, # Size in bytes (loadFromXxx)
65 $metadata, # Handler-specific metadata
66 $timestamp, # Upload timestamp
67 $sha1, # SHA-1 base 36 content hash
68 $user, $user_text, # User, who uploaded the file
69 $description, # Description of current revision of the file
70 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
71 $upgraded, # Whether the row was upgraded on load
72 $locked, # True if the image row is locked
73 $missing, # True if file is not present in file system. Not to be cached in memcached
74 $deleted; # Bitfield akin to rev_deleted
83 protected $repoClass = 'LocalRepo';
86 * Create a LocalFile from a title
87 * Do not call this except from inside a repo class.
89 * Note: $unused param is only here to avoid an E_STRICT
97 static function newFromTitle( $title, $repo, $unused = null ) {
98 return new self( $title, $repo );
102 * Create a LocalFile from a title
103 * Do not call this except from inside a repo class.
110 static function newFromRow( $row, $repo ) {
111 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
112 $file = new self( $title, $repo );
113 $file->loadFromRow( $row );
119 * Create a LocalFile from a SHA-1 key
120 * Do not call this except from inside a repo class.
122 * @param $sha1 string base-36 SHA-1
123 * @param $repo LocalRepo
124 * @param string|bool $timestamp MW_timestamp (optional)
126 * @return bool|LocalFile
128 static function newFromKey( $sha1, $repo, $timestamp = false ) {
129 $dbr = $repo->getSlaveDB();
131 $conds = array( 'img_sha1' => $sha1 );
133 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
136 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
138 return self
::newFromRow( $row, $repo );
145 * Fields in the image table
148 static function selectFields() {
169 * Do not call this except from inside a repo class.
171 function __construct( $title, $repo ) {
172 parent
::__construct( $title, $repo );
174 $this->metadata
= '';
175 $this->historyLine
= 0;
176 $this->historyRes
= null;
177 $this->dataLoaded
= false;
179 $this->assertRepoDefined();
180 $this->assertTitleDefined();
184 * Get the memcached key for the main data for this file, or false if
185 * there is no access to the shared cache.
188 function getCacheKey() {
189 $hashedName = md5( $this->getName() );
191 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
195 * Try to load file metadata from memcached. Returns true on success.
198 function loadFromCache() {
201 wfProfileIn( __METHOD__
);
202 $this->dataLoaded
= false;
203 $key = $this->getCacheKey();
206 wfProfileOut( __METHOD__
);
210 $cachedValues = $wgMemc->get( $key );
212 // Check if the key existed and belongs to this version of MediaWiki
213 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
214 wfDebug( "Pulling file metadata from cache key $key\n" );
215 $this->fileExists
= $cachedValues['fileExists'];
216 if ( $this->fileExists
) {
217 $this->setProps( $cachedValues );
219 $this->dataLoaded
= true;
222 if ( $this->dataLoaded
) {
223 wfIncrStats( 'image_cache_hit' );
225 wfIncrStats( 'image_cache_miss' );
228 wfProfileOut( __METHOD__
);
229 return $this->dataLoaded
;
233 * Save the file metadata to memcached
235 function saveToCache() {
239 $key = $this->getCacheKey();
245 $fields = $this->getCacheFields( '' );
246 $cache = array( 'version' => MW_FILE_VERSION
);
247 $cache['fileExists'] = $this->fileExists
;
249 if ( $this->fileExists
) {
250 foreach ( $fields as $field ) {
251 $cache[$field] = $this->$field;
255 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
259 * Load metadata from the file itself
261 function loadFromFile() {
262 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
263 $this->setProps( $props );
267 * @param $prefix string
270 function getCacheFields( $prefix = 'img_' ) {
271 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
272 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
273 static $results = array();
275 if ( $prefix == '' ) {
279 if ( !isset( $results[$prefix] ) ) {
280 $prefixedFields = array();
281 foreach ( $fields as $field ) {
282 $prefixedFields[] = $prefix . $field;
284 $results[$prefix] = $prefixedFields;
287 return $results[$prefix];
291 * Load file metadata from the DB
293 function loadFromDB() {
294 # Polymorphic function name to distinguish foreign and local fetches
295 $fname = get_class( $this ) . '::' . __FUNCTION__
;
296 wfProfileIn( $fname );
298 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
299 $this->dataLoaded
= true;
301 $dbr = $this->repo
->getMasterDB();
303 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
304 array( 'img_name' => $this->getName() ), $fname );
307 $this->loadFromRow( $row );
309 $this->fileExists
= false;
312 wfProfileOut( $fname );
316 * Decode a row from the database (either object or array) to an array
317 * with timestamps and MIME types decoded, and the field prefix removed.
319 * @param $prefix string
320 * @throws MWException
323 function decodeRow( $row, $prefix = 'img_' ) {
324 $array = (array)$row;
325 $prefixLength = strlen( $prefix );
327 // Sanity check prefix once
328 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
329 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
334 foreach ( $array as $name => $value ) {
335 $decoded[substr( $name, $prefixLength )] = $value;
338 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
340 if ( empty( $decoded['major_mime'] ) ) {
341 $decoded['mime'] = 'unknown/unknown';
343 if ( !$decoded['minor_mime'] ) {
344 $decoded['minor_mime'] = 'unknown';
346 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
349 # Trim zero padding from char/binary field
350 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
356 * Load file metadata from a DB result row
358 function loadFromRow( $row, $prefix = 'img_' ) {
359 $this->dataLoaded
= true;
360 $array = $this->decodeRow( $row, $prefix );
362 foreach ( $array as $name => $value ) {
363 $this->$name = $value;
366 $this->fileExists
= true;
367 $this->maybeUpgradeRow();
371 * Load file metadata from cache or DB, unless already loaded
374 if ( !$this->dataLoaded
) {
375 if ( !$this->loadFromCache() ) {
377 $this->saveToCache();
379 $this->dataLoaded
= true;
384 * Upgrade a row if it needs it
386 function maybeUpgradeRow() {
387 global $wgUpdateCompatibleMetadata;
388 if ( wfReadOnly() ) {
392 if ( is_null( $this->media_type
) ||
393 $this->mime
== 'image/svg'
396 $this->upgraded
= true;
398 $handler = $this->getHandler();
400 $validity = $handler->isMetadataValid( $this, $this->metadata
);
401 if ( $validity === MediaHandler
::METADATA_BAD
402 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
405 $this->upgraded
= true;
411 function getUpgraded() {
412 return $this->upgraded
;
416 * Fix assorted version-related problems with the image row by reloading it from the file
418 function upgradeRow() {
419 wfProfileIn( __METHOD__
);
421 $this->lock(); // begin
423 $this->loadFromFile();
425 # Don't destroy file info of missing files
426 if ( !$this->fileExists
) {
427 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
428 wfProfileOut( __METHOD__
);
432 $dbw = $this->repo
->getMasterDB();
433 list( $major, $minor ) = self
::splitMime( $this->mime
);
435 if ( wfReadOnly() ) {
436 wfProfileOut( __METHOD__
);
439 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
441 $dbw->update( 'image',
443 'img_width' => $this->width
,
444 'img_height' => $this->height
,
445 'img_bits' => $this->bits
,
446 'img_media_type' => $this->media_type
,
447 'img_major_mime' => $major,
448 'img_minor_mime' => $minor,
449 'img_metadata' => $this->metadata
,
450 'img_sha1' => $this->sha1
,
452 array( 'img_name' => $this->getName() ),
456 $this->saveToCache();
458 $this->unlock(); // done
460 wfProfileOut( __METHOD__
);
464 * Set properties in this object to be equal to those given in the
465 * associative array $info. Only cacheable fields can be set.
467 * If 'mime' is given, it will be split into major_mime/minor_mime.
468 * If major_mime/minor_mime are given, $this->mime will also be set.
470 function setProps( $info ) {
471 $this->dataLoaded
= true;
472 $fields = $this->getCacheFields( '' );
473 $fields[] = 'fileExists';
475 foreach ( $fields as $field ) {
476 if ( isset( $info[$field] ) ) {
477 $this->$field = $info[$field];
481 // Fix up mime fields
482 if ( isset( $info['major_mime'] ) ) {
483 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
484 } elseif ( isset( $info['mime'] ) ) {
485 $this->mime
= $info['mime'];
486 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
490 /** splitMime inherited */
491 /** getName inherited */
492 /** getTitle inherited */
493 /** getURL inherited */
494 /** getViewURL inherited */
495 /** getPath inherited */
496 /** isVisible inhereted */
501 function isMissing() {
502 if ( $this->missing
=== null ) {
503 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
504 $this->missing
= !$fileExists;
506 return $this->missing
;
510 * Return the width of the image
513 * @return bool|int Returns false on error
515 public function getWidth( $page = 1 ) {
518 if ( $this->isMultipage() ) {
519 $dim = $this->getHandler()->getPageDimensions( $this, $page );
521 return $dim['width'];
531 * Return the height of the image
534 * @return bool|int Returns false on error
536 public function getHeight( $page = 1 ) {
539 if ( $this->isMultipage() ) {
540 $dim = $this->getHandler()->getPageDimensions( $this, $page );
542 return $dim['height'];
547 return $this->height
;
552 * Returns ID or name of user who uploaded the file
554 * @param $type string 'text' or 'id'
557 function getUser( $type = 'text' ) {
560 if ( $type == 'text' ) {
561 return $this->user_text
;
562 } elseif ( $type == 'id' ) {
568 * Get handler-specific metadata
571 function getMetadata() {
573 return $this->metadata
;
579 function getBitDepth() {
585 * Return the size of the image file, in bytes
588 public function getSize() {
594 * Returns the mime type of the file.
597 function getMimeType() {
603 * Return the type of the media in the file.
604 * Use the value returned by this function with the MEDIATYPE_xxx constants.
607 function getMediaType() {
609 return $this->media_type
;
612 /** canRender inherited */
613 /** mustRender inherited */
614 /** allowInlineDisplay inherited */
615 /** isSafeFile inherited */
616 /** isTrustedFile inherited */
619 * Returns true if the file exists on disk.
620 * @return boolean Whether file exist on disk.
622 public function exists() {
624 return $this->fileExists
;
627 /** getTransformScript inherited */
628 /** getUnscaledThumb inherited */
629 /** thumbName inherited */
630 /** createThumb inherited */
631 /** transform inherited */
634 * Fix thumbnail files from 1.4 or before, with extreme prejudice
635 * @TODO: do we still care about this? Perhaps a maintenance script
636 * can be made instead. Enabling this code results in a serious
637 * RTT regression for wikis without 404 handling.
639 function migrateThumbFile( $thumbName ) {
640 $thumbDir = $this->getThumbPath();
642 /* Old code for bug 2532
643 $thumbPath = "$thumbDir/$thumbName";
644 if ( is_dir( $thumbPath ) ) {
645 // Directory where file should be
646 // This happened occasionally due to broken migration code in 1.5
647 // Rename to broken-*
648 for ( $i = 0; $i < 100 ; $i++ ) {
649 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
650 if ( !file_exists( $broken ) ) {
651 rename( $thumbPath, $broken );
655 // Doesn't exist anymore
661 if ( $this->repo->fileExists( $thumbDir ) ) {
662 // Delete file where directory should be
663 $this->repo->cleanupBatch( array( $thumbDir ) );
668 /** getHandler inherited */
669 /** iconThumb inherited */
670 /** getLastError inherited */
673 * Get all thumbnail names previously generated for this file
674 * @param $archiveName string|bool Name of an archive file, default false
675 * @return array first element is the base dir, then files in that base dir.
677 function getThumbnails( $archiveName = false ) {
680 if ( $archiveName ) {
681 $dir = $this->getArchiveThumbPath( $archiveName );
683 $dir = $this->getThumbPath();
686 $backend = $this->repo
->getBackend();
687 $files = array( $dir );
688 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
689 foreach ( $iterator as $file ) {
697 * Refresh metadata in memcached, but don't touch thumbnails or squid
699 function purgeMetadataCache() {
701 $this->saveToCache();
702 $this->purgeHistory();
706 * Purge the shared history (OldLocalFile) cache
708 function purgeHistory() {
711 $hashedName = md5( $this->getName() );
712 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
714 // Must purge thumbnails for old versions too! bug 30192
715 foreach( $this->getHistory() as $oldFile ) {
716 $oldFile->purgeThumbnails();
720 $wgMemc->delete( $oldKey );
725 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
727 function purgeCache( $options = array() ) {
728 // Refresh metadata cache
729 $this->purgeMetadataCache();
732 $this->purgeThumbnails( $options );
734 // Purge squid cache for this file
735 SquidUpdate
::purge( array( $this->getURL() ) );
739 * Delete cached transformed files for an archived version only.
740 * @param $archiveName string name of the archived file
742 function purgeOldThumbnails( $archiveName ) {
744 // Get a list of old thumbnails and URLs
745 $files = $this->getThumbnails( $archiveName );
746 $dir = array_shift( $files );
747 $this->purgeThumbList( $dir, $files );
749 // Purge any custom thumbnail caches
750 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
755 foreach( $files as $file ) {
756 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
758 SquidUpdate
::purge( $urls );
763 * Delete cached transformed files for the current version only.
765 function purgeThumbnails( $options = array() ) {
769 $files = $this->getThumbnails();
771 // Give media handler a chance to filter the purge list
772 if ( !empty( $options['forThumbRefresh'] ) ) {
773 $handler = $this->getHandler();
775 $handler->filterThumbnailPurgeList( $files, $options );
779 $dir = array_shift( $files );
780 $this->purgeThumbList( $dir, $files );
782 // Purge any custom thumbnail caches
783 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
788 foreach( $files as $file ) {
789 $urls[] = $this->getThumbUrl( $file );
791 SquidUpdate
::purge( $urls );
796 * Delete a list of thumbnails visible at urls
797 * @param $dir string base dir of the files.
798 * @param $files array of strings: relative filenames (to $dir)
800 protected function purgeThumbList( $dir, $files ) {
801 $fileListDebug = strtr(
802 var_export( $files, true ),
805 wfDebug( __METHOD__
. ": $fileListDebug\n" );
807 $purgeList = array();
808 foreach ( $files as $file ) {
809 # Check that the base file name is part of the thumb name
810 # This is a basic sanity check to avoid erasing unrelated directories
811 if ( strpos( $file, $this->getName() ) !== false ) {
812 $purgeList[] = "{$dir}/{$file}";
816 # Delete the thumbnails
817 $this->repo
->quickPurgeBatch( $purgeList );
818 # Clear out the thumbnail directory if empty
819 $this->repo
->quickCleanDir( $dir );
822 /** purgeDescription inherited */
823 /** purgeEverything inherited */
832 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
833 $dbr = $this->repo
->getSlaveDB();
834 $tables = array( 'oldimage' );
835 $fields = OldLocalFile
::selectFields();
836 $conds = $opts = $join_conds = array();
837 $eq = $inc ?
'=' : '';
838 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
841 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
845 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
849 $opts['LIMIT'] = $limit;
852 // Search backwards for time > x queries
853 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
854 $opts['ORDER BY'] = "oi_timestamp $order";
855 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
857 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
858 &$conds, &$opts, &$join_conds ) );
860 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
863 foreach ( $res as $row ) {
864 if ( $this->repo
->oldFileFromRowFactory
) {
865 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
867 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
871 if ( $order == 'ASC' ) {
872 $r = array_reverse( $r ); // make sure it ends up descending
879 * Return the history of this file, line by line.
880 * starts with current version, then old versions.
881 * uses $this->historyLine to check which line to return:
882 * 0 return line for current version
883 * 1 query for old versions, return first one
884 * 2, ... return next old version from above query
887 public function nextHistoryLine() {
888 # Polymorphic function name to distinguish foreign and local fetches
889 $fname = get_class( $this ) . '::' . __FUNCTION__
;
891 $dbr = $this->repo
->getSlaveDB();
893 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
894 $this->historyRes
= $dbr->select( 'image',
897 "'' AS oi_archive_name",
901 array( 'img_name' => $this->title
->getDBkey() ),
905 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
906 $this->historyRes
= null;
909 } elseif ( $this->historyLine
== 1 ) {
910 $this->historyRes
= $dbr->select( 'oldimage', '*',
911 array( 'oi_name' => $this->title
->getDBkey() ),
913 array( 'ORDER BY' => 'oi_timestamp DESC' )
916 $this->historyLine ++
;
918 return $dbr->fetchObject( $this->historyRes
);
922 * Reset the history pointer to the first element of the history
924 public function resetHistory() {
925 $this->historyLine
= 0;
927 if ( !is_null( $this->historyRes
) ) {
928 $this->historyRes
= null;
932 /** getHashPath inherited */
933 /** getRel inherited */
934 /** getUrlRel inherited */
935 /** getArchiveRel inherited */
936 /** getArchivePath inherited */
937 /** getThumbPath inherited */
938 /** getArchiveUrl inherited */
939 /** getThumbUrl inherited */
940 /** getArchiveVirtualUrl inherited */
941 /** getThumbVirtualUrl inherited */
942 /** isHashed inherited */
945 * Upload a file and record it in the DB
946 * @param $srcPath String: source storage path or virtual URL
947 * @param $comment String: upload description
948 * @param $pageText String: text to use for the new description page,
949 * if a new description page is created
950 * @param $flags Integer|bool: flags for publish()
951 * @param $props Array|bool: File properties, if known. This can be used to reduce the
952 * upload time when uploading virtual URLs for which the file info
954 * @param $timestamp String|bool: timestamp for img_timestamp, or false to use the current time
955 * @param $user User|null: User object or null to use $wgUser
957 * @return FileRepoStatus object. On success, the value member contains the
958 * archive name, or an empty string if it was a new file.
960 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
963 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
964 return $this->readOnlyFatalStatus();
967 // truncate nicely or the DB will do it for us
968 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
969 $comment = $wgContLang->truncate( $comment, 255 );
970 $this->lock(); // begin
971 $status = $this->publish( $srcPath, $flags );
973 if ( $status->successCount
> 0 ) {
974 # Essentially we are displacing any existing current file and saving
975 # a new current file at the old location. If just the first succeeded,
976 # we still need to displace the current DB entry and put in a new one.
977 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
978 $status->fatal( 'filenotfound', $srcPath );
982 $this->unlock(); // done
988 * Record a file upload in the upload log and the image table
990 * @param $desc string
991 * @param $license string
992 * @param $copyStatus string
993 * @param $source string
995 * @param $timestamp string|bool
998 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
999 $watch = false, $timestamp = false )
1001 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1003 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
1009 $wgUser->addWatch( $this->getTitle() );
1015 * Record a file upload in the upload log and the image table
1017 * @param $comment string
1018 * @param $pageText string
1019 * @param $props bool|array
1020 * @param $timestamp bool|string
1021 * @param $user null|User
1024 function recordUpload2(
1025 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1027 if ( is_null( $user ) ) {
1032 $dbw = $this->repo
->getMasterDB();
1033 $dbw->begin( __METHOD__
);
1036 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1039 if ( $timestamp === false ) {
1040 $timestamp = $dbw->timestamp();
1043 $props['description'] = $comment;
1044 $props['user'] = $user->getId();
1045 $props['user_text'] = $user->getName();
1046 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1047 $this->setProps( $props );
1050 $this->purgeThumbnails();
1052 # The file is already on its final location, remove it from the squid cache
1053 SquidUpdate
::purge( array( $this->getURL() ) );
1055 # Fail now if the file isn't there
1056 if ( !$this->fileExists
) {
1057 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1063 # Test to see if the row exists using INSERT IGNORE
1064 # This avoids race conditions by locking the row until the commit, and also
1065 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1066 $dbw->insert( 'image',
1068 'img_name' => $this->getName(),
1069 'img_size' => $this->size
,
1070 'img_width' => intval( $this->width
),
1071 'img_height' => intval( $this->height
),
1072 'img_bits' => $this->bits
,
1073 'img_media_type' => $this->media_type
,
1074 'img_major_mime' => $this->major_mime
,
1075 'img_minor_mime' => $this->minor_mime
,
1076 'img_timestamp' => $timestamp,
1077 'img_description' => $comment,
1078 'img_user' => $user->getId(),
1079 'img_user_text' => $user->getName(),
1080 'img_metadata' => $this->metadata
,
1081 'img_sha1' => $this->sha1
1087 if ( $dbw->affectedRows() == 0 ) {
1088 # (bug 34993) Note: $oldver can be empty here, if the previous
1089 # version of the file was broken. Allow registration of the new
1090 # version to continue anyway, because that's better than having
1091 # an image that's not fixable by user operations.
1094 # Collision, this is an update of a file
1095 # Insert previous contents into oldimage
1096 $dbw->insertSelect( 'oldimage', 'image',
1098 'oi_name' => 'img_name',
1099 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1100 'oi_size' => 'img_size',
1101 'oi_width' => 'img_width',
1102 'oi_height' => 'img_height',
1103 'oi_bits' => 'img_bits',
1104 'oi_timestamp' => 'img_timestamp',
1105 'oi_description' => 'img_description',
1106 'oi_user' => 'img_user',
1107 'oi_user_text' => 'img_user_text',
1108 'oi_metadata' => 'img_metadata',
1109 'oi_media_type' => 'img_media_type',
1110 'oi_major_mime' => 'img_major_mime',
1111 'oi_minor_mime' => 'img_minor_mime',
1112 'oi_sha1' => 'img_sha1'
1114 array( 'img_name' => $this->getName() ),
1118 # Update the current image row
1119 $dbw->update( 'image',
1121 'img_size' => $this->size
,
1122 'img_width' => intval( $this->width
),
1123 'img_height' => intval( $this->height
),
1124 'img_bits' => $this->bits
,
1125 'img_media_type' => $this->media_type
,
1126 'img_major_mime' => $this->major_mime
,
1127 'img_minor_mime' => $this->minor_mime
,
1128 'img_timestamp' => $timestamp,
1129 'img_description' => $comment,
1130 'img_user' => $user->getId(),
1131 'img_user_text' => $user->getName(),
1132 'img_metadata' => $this->metadata
,
1133 'img_sha1' => $this->sha1
1135 array( 'img_name' => $this->getName() ),
1139 # This is a new file, so update the image count
1140 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1143 $descTitle = $this->getTitle();
1144 $wikiPage = new WikiFilePage( $descTitle );
1145 $wikiPage->setFile( $this );
1148 $log = new LogPage( 'upload' );
1149 $action = $reupload ?
'overwrite' : 'upload';
1150 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1152 if ( $descTitle->exists() ) {
1153 # Create a null revision
1154 $latest = $descTitle->getLatestRevID();
1155 $nullRevision = Revision
::newNullRevision(
1157 $descTitle->getArticleID(),
1158 $log->getRcComment(),
1161 if (!is_null($nullRevision)) {
1162 $nullRevision->insertOn( $dbw );
1164 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1165 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1167 # Invalidate the cache for the description page
1168 $descTitle->invalidateCache();
1169 $descTitle->purgeSquid();
1171 # New file; create the description page.
1172 # There's already a log entry, so don't make a second RC entry
1173 # Squid and file cache for the description page are purged by doEdit.
1174 $wikiPage->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
, false, $user );
1177 # Commit the transaction now, in case something goes wrong later
1178 # The most important thing is that files don't get lost, especially archives
1179 $dbw->commit( __METHOD__
);
1181 # Save to cache and purge the squid
1182 # We shall not saveToCache before the commit since otherwise
1183 # in case of a rollback there is an usable file from memcached
1184 # which in fact doesn't really exist (bug 24978)
1185 $this->saveToCache();
1187 # Hooks, hooks, the magic of hooks...
1188 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1190 # Invalidate cache for all pages using this file
1191 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1192 $update->doUpdate();
1194 # Invalidate cache for all pages that redirects on this page
1195 $redirs = $this->getTitle()->getRedirectsHere();
1197 foreach ( $redirs as $redir ) {
1198 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1199 $update->doUpdate();
1206 * Move or copy a file to its public location. If a file exists at the
1207 * destination, move it to an archive. Returns a FileRepoStatus object with
1208 * the archive name in the "value" member on success.
1210 * The archive name should be passed through to recordUpload for database
1213 * @param $srcPath String: local filesystem path to the source image
1214 * @param $flags Integer: a bitwise combination of:
1215 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1216 * @return FileRepoStatus object. On success, the value member contains the
1217 * archive name, or an empty string if it was a new file.
1219 function publish( $srcPath, $flags = 0 ) {
1220 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1224 * Move or copy a file to a specified location. Returns a FileRepoStatus
1225 * object with the archive name in the "value" member on success.
1227 * The archive name should be passed through to recordUpload for database
1230 * @param $srcPath String: local filesystem path to the source image
1231 * @param $dstRel String: target relative path
1232 * @param $flags Integer: a bitwise combination of:
1233 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1234 * @return FileRepoStatus object. On success, the value member contains the
1235 * archive name, or an empty string if it was a new file.
1237 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1238 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1239 return $this->readOnlyFatalStatus();
1242 $this->lock(); // begin
1244 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1245 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1246 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1247 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1249 if ( $status->value
== 'new' ) {
1250 $status->value
= '';
1252 $status->value
= $archiveName;
1255 $this->unlock(); // done
1260 /** getLinksTo inherited */
1261 /** getExifData inherited */
1262 /** isLocal inherited */
1263 /** wasDeleted inherited */
1266 * Move file to the new title
1268 * Move current, old version and all thumbnails
1269 * to the new filename. Old file is deleted.
1271 * Cache purging is done; checks for validity
1272 * and logging are caller's responsibility
1274 * @param $target Title New file name
1275 * @return FileRepoStatus object.
1277 function move( $target ) {
1278 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1279 return $this->readOnlyFatalStatus();
1282 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1283 $batch = new LocalFileMoveBatch( $this, $target );
1285 $this->lock(); // begin
1286 $batch->addCurrent();
1287 $archiveNames = $batch->addOlds();
1288 $status = $batch->execute();
1289 $this->unlock(); // done
1291 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1293 $this->purgeEverything();
1294 foreach ( $archiveNames as $archiveName ) {
1295 $this->purgeOldThumbnails( $archiveName );
1297 if ( $status->isOK() ) {
1298 // Now switch the object
1299 $this->title
= $target;
1300 // Force regeneration of the name and hashpath
1301 unset( $this->name
);
1302 unset( $this->hashPath
);
1303 // Purge the new image
1304 $this->purgeEverything();
1311 * Delete all versions of the file.
1313 * Moves the files into an archive directory (or deletes them)
1314 * and removes the database rows.
1316 * Cache purging is done; logging is caller's responsibility.
1320 * @return FileRepoStatus object.
1322 function delete( $reason, $suppress = false ) {
1323 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1324 return $this->readOnlyFatalStatus();
1327 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1329 $this->lock(); // begin
1330 $batch->addCurrent();
1331 # Get old version relative paths
1332 $archiveNames = $batch->addOlds();
1333 $status = $batch->execute();
1334 $this->unlock(); // done
1336 if ( $status->isOK() ) {
1337 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1340 $this->purgeEverything();
1341 foreach ( $archiveNames as $archiveName ) {
1342 $this->purgeOldThumbnails( $archiveName );
1349 * Delete an old version of the file.
1351 * Moves the file into an archive directory (or deletes it)
1352 * and removes the database row.
1354 * Cache purging is done; logging is caller's responsibility.
1356 * @param $archiveName String
1357 * @param $reason String
1358 * @param $suppress Boolean
1359 * @throws MWException or FSException on database or file store failure
1360 * @return FileRepoStatus object.
1362 function deleteOld( $archiveName, $reason, $suppress = false ) {
1363 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1364 return $this->readOnlyFatalStatus();
1367 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1369 $this->lock(); // begin
1370 $batch->addOld( $archiveName );
1371 $status = $batch->execute();
1372 $this->unlock(); // done
1374 $this->purgeOldThumbnails( $archiveName );
1375 if ( $status->isOK() ) {
1376 $this->purgeDescription();
1377 $this->purgeHistory();
1384 * Restore all or specified deleted revisions to the given file.
1385 * Permissions and logging are left to the caller.
1387 * May throw database exceptions on error.
1389 * @param $versions array set of record ids of deleted items to restore,
1390 * or empty to restore all revisions.
1391 * @param $unsuppress Boolean
1392 * @return FileRepoStatus
1394 function restore( $versions = array(), $unsuppress = false ) {
1395 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1396 return $this->readOnlyFatalStatus();
1399 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1401 $this->lock(); // begin
1405 $batch->addIds( $versions );
1407 $status = $batch->execute();
1408 if ( $status->isGood() ) {
1409 $cleanupStatus = $batch->cleanup();
1410 $cleanupStatus->successCount
= 0;
1411 $cleanupStatus->failCount
= 0;
1412 $status->merge( $cleanupStatus );
1414 $this->unlock(); // done
1419 /** isMultipage inherited */
1420 /** pageCount inherited */
1421 /** scaleHeight inherited */
1422 /** getImageSize inherited */
1425 * Get the URL of the file description page.
1428 function getDescriptionUrl() {
1429 return $this->title
->getLocalUrl();
1433 * Get the HTML text of the description page
1434 * This is not used by ImagePage for local files, since (among other things)
1435 * it skips the parser cache.
1436 * @return bool|mixed
1438 function getDescriptionText() {
1440 $revision = Revision
::newFromTitle( $this->title
);
1441 if ( !$revision ) return false;
1442 $text = $revision->getText();
1443 if ( !$text ) return false;
1444 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1445 return $pout->getText();
1451 function getDescription() {
1453 return $this->description
;
1457 * @return bool|string
1459 function getTimestamp() {
1461 return $this->timestamp
;
1467 function getSha1() {
1469 // Initialise now if necessary
1470 if ( $this->sha1
== '' && $this->fileExists
) {
1471 $this->lock(); // begin
1473 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1474 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1475 $dbw = $this->repo
->getMasterDB();
1476 $dbw->update( 'image',
1477 array( 'img_sha1' => $this->sha1
),
1478 array( 'img_name' => $this->getName() ),
1480 $this->saveToCache();
1483 $this->unlock(); // done
1492 function isCacheable() {
1494 return strlen( $this->metadata
) <= self
::CACHE_FIELD_MAX_LEN
; // avoid OOMs
1498 * Start a transaction and lock the image for update
1499 * Increments a reference counter if the lock is already held
1500 * @return boolean True if the image exists, false otherwise
1503 $dbw = $this->repo
->getMasterDB();
1505 if ( !$this->locked
) {
1506 $dbw->begin( __METHOD__
);
1510 return $dbw->selectField( 'image', '1',
1511 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1515 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1516 * the transaction and thereby releases the image lock.
1519 if ( $this->locked
) {
1521 if ( !$this->locked
) {
1522 $dbw = $this->repo
->getMasterDB();
1523 $dbw->commit( __METHOD__
);
1529 * Roll back the DB transaction and mark the image unlocked
1531 function unlockAndRollback() {
1532 $this->locked
= false;
1533 $dbw = $this->repo
->getMasterDB();
1534 $dbw->rollback( __METHOD__
);
1540 protected function readOnlyFatalStatus() {
1541 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1542 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1544 } // LocalFile class
1546 # ------------------------------------------------------------------------------
1549 * Helper class for file deletion
1550 * @ingroup FileAbstraction
1552 class LocalFileDeleteBatch
{
1559 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1564 * @param $reason string
1565 * @param $suppress bool
1567 function __construct( File
$file, $reason = '', $suppress = false ) {
1568 $this->file
= $file;
1569 $this->reason
= $reason;
1570 $this->suppress
= $suppress;
1571 $this->status
= $file->repo
->newGood();
1574 function addCurrent() {
1575 $this->srcRels
['.'] = $this->file
->getRel();
1579 * @param $oldName string
1581 function addOld( $oldName ) {
1582 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1583 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1587 * Add the old versions of the image to the batch
1588 * @return Array List of archive names from old versions
1590 function addOlds() {
1591 $archiveNames = array();
1593 $dbw = $this->file
->repo
->getMasterDB();
1594 $result = $dbw->select( 'oldimage',
1595 array( 'oi_archive_name' ),
1596 array( 'oi_name' => $this->file
->getName() ),
1600 foreach ( $result as $row ) {
1601 $this->addOld( $row->oi_archive_name
);
1602 $archiveNames[] = $row->oi_archive_name
;
1605 return $archiveNames;
1611 function getOldRels() {
1612 if ( !isset( $this->srcRels
['.'] ) ) {
1613 $oldRels =& $this->srcRels
;
1614 $deleteCurrent = false;
1616 $oldRels = $this->srcRels
;
1617 unset( $oldRels['.'] );
1618 $deleteCurrent = true;
1621 return array( $oldRels, $deleteCurrent );
1627 protected function getHashes() {
1629 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1631 if ( $deleteCurrent ) {
1632 $hashes['.'] = $this->file
->getSha1();
1635 if ( count( $oldRels ) ) {
1636 $dbw = $this->file
->repo
->getMasterDB();
1637 $res = $dbw->select(
1639 array( 'oi_archive_name', 'oi_sha1' ),
1640 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1644 foreach ( $res as $row ) {
1645 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1646 // Get the hash from the file
1647 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1648 $props = $this->file
->repo
->getFileProps( $oldUrl );
1650 if ( $props['fileExists'] ) {
1651 // Upgrade the oldimage row
1652 $dbw->update( 'oldimage',
1653 array( 'oi_sha1' => $props['sha1'] ),
1654 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1656 $hashes[$row->oi_archive_name
] = $props['sha1'];
1658 $hashes[$row->oi_archive_name
] = false;
1661 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1666 $missing = array_diff_key( $this->srcRels
, $hashes );
1668 foreach ( $missing as $name => $rel ) {
1669 $this->status
->error( 'filedelete-old-unregistered', $name );
1672 foreach ( $hashes as $name => $hash ) {
1674 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1675 unset( $hashes[$name] );
1682 function doDBInserts() {
1685 $dbw = $this->file
->repo
->getMasterDB();
1686 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1687 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1688 $encReason = $dbw->addQuotes( $this->reason
);
1689 $encGroup = $dbw->addQuotes( 'deleted' );
1690 $ext = $this->file
->getExtension();
1691 $dotExt = $ext === '' ?
'' : ".$ext";
1692 $encExt = $dbw->addQuotes( $dotExt );
1693 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1695 // Bitfields to further suppress the content
1696 if ( $this->suppress
) {
1698 // This should be 15...
1699 $bitfield |
= Revision
::DELETED_TEXT
;
1700 $bitfield |
= Revision
::DELETED_COMMENT
;
1701 $bitfield |
= Revision
::DELETED_USER
;
1702 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1704 $bitfield = 'oi_deleted';
1707 if ( $deleteCurrent ) {
1708 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1709 $where = array( 'img_name' => $this->file
->getName() );
1710 $dbw->insertSelect( 'filearchive', 'image',
1712 'fa_storage_group' => $encGroup,
1713 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1714 'fa_deleted_user' => $encUserId,
1715 'fa_deleted_timestamp' => $encTimestamp,
1716 'fa_deleted_reason' => $encReason,
1717 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1719 'fa_name' => 'img_name',
1720 'fa_archive_name' => 'NULL',
1721 'fa_size' => 'img_size',
1722 'fa_width' => 'img_width',
1723 'fa_height' => 'img_height',
1724 'fa_metadata' => 'img_metadata',
1725 'fa_bits' => 'img_bits',
1726 'fa_media_type' => 'img_media_type',
1727 'fa_major_mime' => 'img_major_mime',
1728 'fa_minor_mime' => 'img_minor_mime',
1729 'fa_description' => 'img_description',
1730 'fa_user' => 'img_user',
1731 'fa_user_text' => 'img_user_text',
1732 'fa_timestamp' => 'img_timestamp'
1733 ), $where, __METHOD__
);
1736 if ( count( $oldRels ) ) {
1737 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1739 'oi_name' => $this->file
->getName(),
1740 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1741 $dbw->insertSelect( 'filearchive', 'oldimage',
1743 'fa_storage_group' => $encGroup,
1744 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1745 'fa_deleted_user' => $encUserId,
1746 'fa_deleted_timestamp' => $encTimestamp,
1747 'fa_deleted_reason' => $encReason,
1748 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1750 'fa_name' => 'oi_name',
1751 'fa_archive_name' => 'oi_archive_name',
1752 'fa_size' => 'oi_size',
1753 'fa_width' => 'oi_width',
1754 'fa_height' => 'oi_height',
1755 'fa_metadata' => 'oi_metadata',
1756 'fa_bits' => 'oi_bits',
1757 'fa_media_type' => 'oi_media_type',
1758 'fa_major_mime' => 'oi_major_mime',
1759 'fa_minor_mime' => 'oi_minor_mime',
1760 'fa_description' => 'oi_description',
1761 'fa_user' => 'oi_user',
1762 'fa_user_text' => 'oi_user_text',
1763 'fa_timestamp' => 'oi_timestamp',
1764 ), $where, __METHOD__
);
1768 function doDBDeletes() {
1769 $dbw = $this->file
->repo
->getMasterDB();
1770 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1772 if ( count( $oldRels ) ) {
1773 $dbw->delete( 'oldimage',
1775 'oi_name' => $this->file
->getName(),
1776 'oi_archive_name' => array_keys( $oldRels )
1780 if ( $deleteCurrent ) {
1781 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1786 * Run the transaction
1787 * @return FileRepoStatus
1789 function execute() {
1791 wfProfileIn( __METHOD__
);
1793 $this->file
->lock();
1794 // Leave private files alone
1795 $privateFiles = array();
1796 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1797 $dbw = $this->file
->repo
->getMasterDB();
1799 if ( !empty( $oldRels ) ) {
1800 $res = $dbw->select( 'oldimage',
1801 array( 'oi_archive_name' ),
1802 array( 'oi_name' => $this->file
->getName(),
1803 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1804 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1807 foreach ( $res as $row ) {
1808 $privateFiles[$row->oi_archive_name
] = 1;
1811 // Prepare deletion batch
1812 $hashes = $this->getHashes();
1813 $this->deletionBatch
= array();
1814 $ext = $this->file
->getExtension();
1815 $dotExt = $ext === '' ?
'' : ".$ext";
1817 foreach ( $this->srcRels
as $name => $srcRel ) {
1818 // Skip files that have no hash (missing source).
1819 // Keep private files where they are.
1820 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1821 $hash = $hashes[$name];
1822 $key = $hash . $dotExt;
1823 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1824 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1828 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1829 // We acquire this lock by running the inserts now, before the file operations.
1831 // This potentially has poor lock contention characteristics -- an alternative
1832 // scheme would be to insert stub filearchive entries with no fa_name and commit
1833 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1834 $this->doDBInserts();
1836 // Removes non-existent file from the batch, so we don't get errors.
1837 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1839 // Execute the file deletion batch
1840 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1842 if ( !$status->isGood() ) {
1843 $this->status
->merge( $status );
1846 if ( !$this->status
->isOK() ) {
1847 // Critical file deletion error
1848 // Roll back inserts, release lock and abort
1849 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1850 $this->file
->unlockAndRollback();
1851 wfProfileOut( __METHOD__
);
1852 return $this->status
;
1855 // Delete image/oldimage rows
1856 $this->doDBDeletes();
1858 // Commit and return
1859 $this->file
->unlock();
1860 wfProfileOut( __METHOD__
);
1862 return $this->status
;
1866 * Removes non-existent files from a deletion batch.
1867 * @param $batch array
1870 function removeNonexistentFiles( $batch ) {
1871 $files = $newBatch = array();
1873 foreach ( $batch as $batchItem ) {
1874 list( $src, $dest ) = $batchItem;
1875 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1878 $result = $this->file
->repo
->fileExistsBatch( $files );
1880 foreach ( $batch as $batchItem ) {
1881 if ( $result[$batchItem[0]] ) {
1882 $newBatch[] = $batchItem;
1890 # ------------------------------------------------------------------------------
1893 * Helper class for file undeletion
1894 * @ingroup FileAbstraction
1896 class LocalFileRestoreBatch
{
1902 var $cleanupBatch, $ids, $all, $unsuppress = false;
1906 * @param $unsuppress bool
1908 function __construct( File
$file, $unsuppress = false ) {
1909 $this->file
= $file;
1910 $this->cleanupBatch
= $this->ids
= array();
1911 $this->ids
= array();
1912 $this->unsuppress
= $unsuppress;
1918 function addId( $fa_id ) {
1919 $this->ids
[] = $fa_id;
1923 * Add a whole lot of files by ID
1925 function addIds( $ids ) {
1926 $this->ids
= array_merge( $this->ids
, $ids );
1930 * Add all revisions of the file
1937 * Run the transaction, except the cleanup batch.
1938 * The cleanup batch should be run in a separate transaction, because it locks different
1939 * rows and there's no need to keep the image row locked while it's acquiring those locks
1940 * The caller may have its own transaction open.
1941 * So we save the batch and let the caller call cleanup()
1942 * @return FileRepoStatus
1944 function execute() {
1947 if ( !$this->all
&& !$this->ids
) {
1949 return $this->file
->repo
->newGood();
1952 $exists = $this->file
->lock();
1953 $dbw = $this->file
->repo
->getMasterDB();
1954 $status = $this->file
->repo
->newGood();
1956 // Fetch all or selected archived revisions for the file,
1957 // sorted from the most recent to the oldest.
1958 $conditions = array( 'fa_name' => $this->file
->getName() );
1960 if ( !$this->all
) {
1961 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1964 $result = $dbw->select( 'filearchive', '*',
1967 array( 'ORDER BY' => 'fa_timestamp DESC' )
1970 $idsPresent = array();
1971 $storeBatch = array();
1972 $insertBatch = array();
1973 $insertCurrent = false;
1974 $deleteIds = array();
1976 $archiveNames = array();
1978 foreach ( $result as $row ) {
1979 $idsPresent[] = $row->fa_id
;
1981 if ( $row->fa_name
!= $this->file
->getName() ) {
1982 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1983 $status->failCount++
;
1987 if ( $row->fa_storage_key
== '' ) {
1988 // Revision was missing pre-deletion
1989 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1990 $status->failCount++
;
1994 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1995 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1997 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
2000 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2001 $sha1 = substr( $sha1, 1 );
2004 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2005 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2006 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2007 ||
is_null( $row->fa_metadata
) ) {
2008 // Refresh our metadata
2009 // Required for a new current revision; nice for older ones too. :)
2010 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2013 'minor_mime' => $row->fa_minor_mime
,
2014 'major_mime' => $row->fa_major_mime
,
2015 'media_type' => $row->fa_media_type
,
2016 'metadata' => $row->fa_metadata
2020 if ( $first && !$exists ) {
2021 // This revision will be published as the new current version
2022 $destRel = $this->file
->getRel();
2023 $insertCurrent = array(
2024 'img_name' => $row->fa_name
,
2025 'img_size' => $row->fa_size
,
2026 'img_width' => $row->fa_width
,
2027 'img_height' => $row->fa_height
,
2028 'img_metadata' => $props['metadata'],
2029 'img_bits' => $row->fa_bits
,
2030 'img_media_type' => $props['media_type'],
2031 'img_major_mime' => $props['major_mime'],
2032 'img_minor_mime' => $props['minor_mime'],
2033 'img_description' => $row->fa_description
,
2034 'img_user' => $row->fa_user
,
2035 'img_user_text' => $row->fa_user_text
,
2036 'img_timestamp' => $row->fa_timestamp
,
2040 // The live (current) version cannot be hidden!
2041 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2042 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2043 $this->cleanupBatch
[] = $row->fa_storage_key
;
2046 $archiveName = $row->fa_archive_name
;
2048 if ( $archiveName == '' ) {
2049 // This was originally a current version; we
2050 // have to devise a new archive name for it.
2051 // Format is <timestamp of archiving>!<name>
2052 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2055 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2057 } while ( isset( $archiveNames[$archiveName] ) );
2060 $archiveNames[$archiveName] = true;
2061 $destRel = $this->file
->getArchiveRel( $archiveName );
2062 $insertBatch[] = array(
2063 'oi_name' => $row->fa_name
,
2064 'oi_archive_name' => $archiveName,
2065 'oi_size' => $row->fa_size
,
2066 'oi_width' => $row->fa_width
,
2067 'oi_height' => $row->fa_height
,
2068 'oi_bits' => $row->fa_bits
,
2069 'oi_description' => $row->fa_description
,
2070 'oi_user' => $row->fa_user
,
2071 'oi_user_text' => $row->fa_user_text
,
2072 'oi_timestamp' => $row->fa_timestamp
,
2073 'oi_metadata' => $props['metadata'],
2074 'oi_media_type' => $props['media_type'],
2075 'oi_major_mime' => $props['major_mime'],
2076 'oi_minor_mime' => $props['minor_mime'],
2077 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2078 'oi_sha1' => $sha1 );
2081 $deleteIds[] = $row->fa_id
;
2083 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2084 // private files can stay where they are
2085 $status->successCount++
;
2087 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2088 $this->cleanupBatch
[] = $row->fa_storage_key
;
2096 // Add a warning to the status object for missing IDs
2097 $missingIds = array_diff( $this->ids
, $idsPresent );
2099 foreach ( $missingIds as $id ) {
2100 $status->error( 'undelete-missing-filearchive', $id );
2103 // Remove missing files from batch, so we don't get errors when undeleting them
2104 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2106 // Run the store batch
2107 // Use the OVERWRITE_SAME flag to smooth over a common error
2108 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2109 $status->merge( $storeStatus );
2111 if ( !$status->isGood() ) {
2112 // Even if some files could be copied, fail entirely as that is the
2113 // easiest thing to do without data loss
2114 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2115 $status->ok
= false;
2116 $this->file
->unlock();
2121 // Run the DB updates
2122 // Because we have locked the image row, key conflicts should be rare.
2123 // If they do occur, we can roll back the transaction at this time with
2124 // no data loss, but leaving unregistered files scattered throughout the
2126 // This is not ideal, which is why it's important to lock the image row.
2127 if ( $insertCurrent ) {
2128 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2131 if ( $insertBatch ) {
2132 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2136 $dbw->delete( 'filearchive',
2137 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2141 // If store batch is empty (all files are missing), deletion is to be considered successful
2142 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2144 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2146 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2148 $this->file
->purgeEverything();
2150 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2151 $this->file
->purgeDescription();
2152 $this->file
->purgeHistory();
2156 $this->file
->unlock();
2162 * Removes non-existent files from a store batch.
2163 * @param $triplets array
2166 function removeNonexistentFiles( $triplets ) {
2167 $files = $filteredTriplets = array();
2168 foreach ( $triplets as $file ) {
2169 $files[$file[0]] = $file[0];
2172 $result = $this->file
->repo
->fileExistsBatch( $files );
2174 foreach ( $triplets as $file ) {
2175 if ( $result[$file[0]] ) {
2176 $filteredTriplets[] = $file;
2180 return $filteredTriplets;
2184 * Removes non-existent files from a cleanup batch.
2185 * @param $batch array
2188 function removeNonexistentFromCleanup( $batch ) {
2189 $files = $newBatch = array();
2190 $repo = $this->file
->repo
;
2192 foreach ( $batch as $file ) {
2193 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2194 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2197 $result = $repo->fileExistsBatch( $files );
2199 foreach ( $batch as $file ) {
2200 if ( $result[$file] ) {
2201 $newBatch[] = $file;
2209 * Delete unused files in the deleted zone.
2210 * This should be called from outside the transaction in which execute() was called.
2211 * @return FileRepoStatus|void
2213 function cleanup() {
2214 if ( !$this->cleanupBatch
) {
2215 return $this->file
->repo
->newGood();
2218 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2220 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2226 * Cleanup a failed batch. The batch was only partially successful, so
2227 * rollback by removing all items that were succesfully copied.
2229 * @param Status $storeStatus
2230 * @param array $storeBatch
2232 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2233 $cleanupBatch = array();
2235 foreach ( $storeStatus->success
as $i => $success ) {
2236 // Check if this item of the batch was successfully copied
2238 // Item was successfully copied and needs to be removed again
2239 // Extract ($dstZone, $dstRel) from the batch
2240 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2243 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2247 # ------------------------------------------------------------------------------
2250 * Helper class for file movement
2251 * @ingroup FileAbstraction
2253 class LocalFileMoveBatch
{
2265 var $cur, $olds, $oldCount, $archive;
2274 * @param Title $target
2276 function __construct( File
$file, Title
$target ) {
2277 $this->file
= $file;
2278 $this->target
= $target;
2279 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2280 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2281 $this->oldName
= $this->file
->getName();
2282 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2283 $this->oldRel
= $this->oldHash
. $this->oldName
;
2284 $this->newRel
= $this->newHash
. $this->newName
;
2285 $this->db
= $file->getRepo()->getMasterDb();
2289 * Add the current image to the batch
2291 function addCurrent() {
2292 $this->cur
= array( $this->oldRel
, $this->newRel
);
2296 * Add the old versions of the image to the batch
2297 * @return Array List of archive names from old versions
2299 function addOlds() {
2300 $archiveBase = 'archive';
2301 $this->olds
= array();
2302 $this->oldCount
= 0;
2303 $archiveNames = array();
2305 $result = $this->db
->select( 'oldimage',
2306 array( 'oi_archive_name', 'oi_deleted' ),
2307 array( 'oi_name' => $this->oldName
),
2311 foreach ( $result as $row ) {
2312 $archiveNames[] = $row->oi_archive_name
;
2313 $oldName = $row->oi_archive_name
;
2314 $bits = explode( '!', $oldName, 2 );
2316 if ( count( $bits ) != 2 ) {
2317 wfDebug( "Old file name missing !: '$oldName' \n" );
2321 list( $timestamp, $filename ) = $bits;
2323 if ( $this->oldName
!= $filename ) {
2324 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2330 // Do we want to add those to oldCount?
2331 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2335 $this->olds
[] = array(
2336 "{$archiveBase}/{$this->oldHash}{$oldName}",
2337 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2341 return $archiveNames;
2346 * @return FileRepoStatus
2348 function execute() {
2349 $repo = $this->file
->repo
;
2350 $status = $repo->newGood();
2352 $triplets = $this->getMoveTriplets();
2353 $triplets = $this->removeNonexistentFiles( $triplets );
2355 // Copy the files into their new location
2356 $statusMove = $repo->storeBatch( $triplets );
2357 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2358 if ( !$statusMove->isGood() ) {
2359 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2360 $this->cleanupTarget( $triplets );
2361 $statusMove->ok
= false;
2365 $this->file
->lock(); // begin
2366 $statusDb = $this->doDBUpdates();
2367 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2368 if ( !$statusDb->isGood() ) {
2369 $this->file
->unlockAndRollback();
2370 // Something went wrong with the DB updates, so remove the target files
2371 $this->cleanupTarget( $triplets );
2372 $statusDb->ok
= false;
2375 $this->file
->unlock(); // done
2377 // Everything went ok, remove the source files
2378 $this->cleanupSource( $triplets );
2380 $status->merge( $statusDb );
2381 $status->merge( $statusMove );
2387 * Do the database updates and return a new FileRepoStatus indicating how
2388 * many rows where updated.
2390 * @return FileRepoStatus
2392 function doDBUpdates() {
2393 $repo = $this->file
->repo
;
2394 $status = $repo->newGood();
2397 // Update current image
2400 array( 'img_name' => $this->newName
),
2401 array( 'img_name' => $this->oldName
),
2405 if ( $dbw->affectedRows() ) {
2406 $status->successCount++
;
2408 $status->failCount++
;
2409 $status->fatal( 'imageinvalidfilename' );
2413 // Update old images
2417 'oi_name' => $this->newName
,
2418 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2419 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2421 array( 'oi_name' => $this->oldName
),
2425 $affected = $dbw->affectedRows();
2426 $total = $this->oldCount
;
2427 $status->successCount +
= $affected;
2428 // Bug 34934: $total is based on files that actually exist.
2429 // There may be more DB rows than such files, in which case $affected
2430 // can be greater than $total. We use max() to avoid negatives here.
2431 $status->failCount +
= max( 0, $total - $affected );
2432 if ( $status->failCount
) {
2433 $status->error( 'imageinvalidfilename' );
2440 * Generate triplets for FileRepo::storeBatch().
2443 function getMoveTriplets() {
2444 $moves = array_merge( array( $this->cur
), $this->olds
);
2445 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2447 foreach ( $moves as $move ) {
2448 // $move: (oldRelativePath, newRelativePath)
2449 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2450 $triplets[] = array( $srcUrl, 'public', $move[1] );
2451 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2458 * Removes non-existent files from move batch.
2459 * @param $triplets array
2462 function removeNonexistentFiles( $triplets ) {
2465 foreach ( $triplets as $file ) {
2466 $files[$file[0]] = $file[0];
2469 $result = $this->file
->repo
->fileExistsBatch( $files );
2470 $filteredTriplets = array();
2472 foreach ( $triplets as $file ) {
2473 if ( $result[$file[0]] ) {
2474 $filteredTriplets[] = $file;
2476 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2480 return $filteredTriplets;
2484 * Cleanup a partially moved array of triplets by deleting the target
2485 * files. Called if something went wrong half way.
2487 function cleanupTarget( $triplets ) {
2488 // Create dest pairs from the triplets
2490 foreach ( $triplets as $triplet ) {
2491 $pairs[] = array( $triplet[1], $triplet[2] );
2494 $this->file
->repo
->cleanupBatch( $pairs );
2498 * Cleanup a fully moved array of triplets by deleting the source files.
2499 * Called at the end of the move process if everything else went ok.
2501 function cleanupSource( $triplets ) {
2502 // Create source file names from the triplets
2504 foreach ( $triplets as $triplet ) {
2505 $files[] = $triplet[0];
2508 $this->file
->repo
->cleanupBatch( $files );