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 // Cache presence for 1 week and negatives for 1 day
256 $wgMemc->set( $key, $cache, $this->fileExists ?
86400 * 7 : 86400 );
260 * Load metadata from the file itself
262 function loadFromFile() {
263 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
264 $this->setProps( $props );
268 * @param $prefix string
271 function getCacheFields( $prefix = 'img_' ) {
272 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
273 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
274 static $results = array();
276 if ( $prefix == '' ) {
280 if ( !isset( $results[$prefix] ) ) {
281 $prefixedFields = array();
282 foreach ( $fields as $field ) {
283 $prefixedFields[] = $prefix . $field;
285 $results[$prefix] = $prefixedFields;
288 return $results[$prefix];
292 * Load file metadata from the DB
294 function loadFromDB() {
295 # Polymorphic function name to distinguish foreign and local fetches
296 $fname = get_class( $this ) . '::' . __FUNCTION__
;
297 wfProfileIn( $fname );
299 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
300 $this->dataLoaded
= true;
302 $dbr = $this->repo
->getMasterDB();
304 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
305 array( 'img_name' => $this->getName() ), $fname );
308 $this->loadFromRow( $row );
310 $this->fileExists
= false;
313 wfProfileOut( $fname );
317 * Decode a row from the database (either object or array) to an array
318 * with timestamps and MIME types decoded, and the field prefix removed.
320 * @param $prefix string
321 * @throws MWException
324 function decodeRow( $row, $prefix = 'img_' ) {
325 $array = (array)$row;
326 $prefixLength = strlen( $prefix );
328 // Sanity check prefix once
329 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
330 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
335 foreach ( $array as $name => $value ) {
336 $decoded[substr( $name, $prefixLength )] = $value;
339 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
341 if ( empty( $decoded['major_mime'] ) ) {
342 $decoded['mime'] = 'unknown/unknown';
344 if ( !$decoded['minor_mime'] ) {
345 $decoded['minor_mime'] = 'unknown';
347 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
350 # Trim zero padding from char/binary field
351 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
357 * Load file metadata from a DB result row
359 function loadFromRow( $row, $prefix = 'img_' ) {
360 $this->dataLoaded
= true;
361 $array = $this->decodeRow( $row, $prefix );
363 foreach ( $array as $name => $value ) {
364 $this->$name = $value;
367 $this->fileExists
= true;
368 $this->maybeUpgradeRow();
372 * Load file metadata from cache or DB, unless already loaded
375 if ( !$this->dataLoaded
) {
376 if ( !$this->loadFromCache() ) {
378 $this->saveToCache();
380 $this->dataLoaded
= true;
385 * Upgrade a row if it needs it
387 function maybeUpgradeRow() {
388 global $wgUpdateCompatibleMetadata;
389 if ( wfReadOnly() ) {
393 if ( is_null( $this->media_type
) ||
394 $this->mime
== 'image/svg'
397 $this->upgraded
= true;
399 $handler = $this->getHandler();
401 $validity = $handler->isMetadataValid( $this, $this->metadata
);
402 if ( $validity === MediaHandler
::METADATA_BAD
403 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
406 $this->upgraded
= true;
412 function getUpgraded() {
413 return $this->upgraded
;
417 * Fix assorted version-related problems with the image row by reloading it from the file
419 function upgradeRow() {
420 wfProfileIn( __METHOD__
);
422 $this->lock(); // begin
424 $this->loadFromFile();
426 # Don't destroy file info of missing files
427 if ( !$this->fileExists
) {
428 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
429 wfProfileOut( __METHOD__
);
433 $dbw = $this->repo
->getMasterDB();
434 list( $major, $minor ) = self
::splitMime( $this->mime
);
436 if ( wfReadOnly() ) {
437 wfProfileOut( __METHOD__
);
440 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
442 $dbw->update( 'image',
444 'img_size' => $this->size
, // sanity
445 'img_width' => $this->width
,
446 'img_height' => $this->height
,
447 'img_bits' => $this->bits
,
448 'img_media_type' => $this->media_type
,
449 'img_major_mime' => $major,
450 'img_minor_mime' => $minor,
451 'img_metadata' => $this->metadata
,
452 'img_sha1' => $this->sha1
,
454 array( 'img_name' => $this->getName() ),
458 $this->saveToCache();
460 $this->unlock(); // done
462 wfProfileOut( __METHOD__
);
466 * Set properties in this object to be equal to those given in the
467 * associative array $info. Only cacheable fields can be set.
469 * If 'mime' is given, it will be split into major_mime/minor_mime.
470 * If major_mime/minor_mime are given, $this->mime will also be set.
472 function setProps( $info ) {
473 $this->dataLoaded
= true;
474 $fields = $this->getCacheFields( '' );
475 $fields[] = 'fileExists';
477 foreach ( $fields as $field ) {
478 if ( isset( $info[$field] ) ) {
479 $this->$field = $info[$field];
483 // Fix up mime fields
484 if ( isset( $info['major_mime'] ) ) {
485 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
486 } elseif ( isset( $info['mime'] ) ) {
487 $this->mime
= $info['mime'];
488 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
492 /** splitMime inherited */
493 /** getName inherited */
494 /** getTitle inherited */
495 /** getURL inherited */
496 /** getViewURL inherited */
497 /** getPath inherited */
498 /** isVisible inhereted */
503 function isMissing() {
504 if ( $this->missing
=== null ) {
505 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
506 $this->missing
= !$fileExists;
508 return $this->missing
;
512 * Return the width of the image
515 * @return bool|int Returns false on error
517 public function getWidth( $page = 1 ) {
520 if ( $this->isMultipage() ) {
521 $dim = $this->getHandler()->getPageDimensions( $this, $page );
523 return $dim['width'];
533 * Return the height of the image
536 * @return bool|int Returns false on error
538 public function getHeight( $page = 1 ) {
541 if ( $this->isMultipage() ) {
542 $dim = $this->getHandler()->getPageDimensions( $this, $page );
544 return $dim['height'];
549 return $this->height
;
554 * Returns ID or name of user who uploaded the file
556 * @param $type string 'text' or 'id'
559 function getUser( $type = 'text' ) {
562 if ( $type == 'text' ) {
563 return $this->user_text
;
564 } elseif ( $type == 'id' ) {
570 * Get handler-specific metadata
573 function getMetadata() {
575 return $this->metadata
;
581 function getBitDepth() {
587 * Return the size of the image file, in bytes
590 public function getSize() {
596 * Returns the mime type of the file.
599 function getMimeType() {
605 * Return the type of the media in the file.
606 * Use the value returned by this function with the MEDIATYPE_xxx constants.
609 function getMediaType() {
611 return $this->media_type
;
614 /** canRender inherited */
615 /** mustRender inherited */
616 /** allowInlineDisplay inherited */
617 /** isSafeFile inherited */
618 /** isTrustedFile inherited */
621 * Returns true if the file exists on disk.
622 * @return boolean Whether file exist on disk.
624 public function exists() {
626 return $this->fileExists
;
629 /** getTransformScript inherited */
630 /** getUnscaledThumb inherited */
631 /** thumbName inherited */
632 /** createThumb inherited */
633 /** transform inherited */
636 * Fix thumbnail files from 1.4 or before, with extreme prejudice
637 * @todo : do we still care about this? Perhaps a maintenance script
638 * can be made instead. Enabling this code results in a serious
639 * RTT regression for wikis without 404 handling.
641 function migrateThumbFile( $thumbName ) {
642 $thumbDir = $this->getThumbPath();
644 /* Old code for bug 2532
645 $thumbPath = "$thumbDir/$thumbName";
646 if ( is_dir( $thumbPath ) ) {
647 // Directory where file should be
648 // This happened occasionally due to broken migration code in 1.5
649 // Rename to broken-*
650 for ( $i = 0; $i < 100 ; $i++ ) {
651 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
652 if ( !file_exists( $broken ) ) {
653 rename( $thumbPath, $broken );
657 // Doesn't exist anymore
663 if ( $this->repo->fileExists( $thumbDir ) ) {
664 // Delete file where directory should be
665 $this->repo->cleanupBatch( array( $thumbDir ) );
670 /** getHandler inherited */
671 /** iconThumb inherited */
672 /** getLastError inherited */
675 * Get all thumbnail names previously generated for this file
676 * @param $archiveName string|bool Name of an archive file, default false
677 * @return array first element is the base dir, then files in that base dir.
679 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 wfProfileIn( __METHOD__
);
746 // Get a list of old thumbnails and URLs
747 $files = $this->getThumbnails( $archiveName );
748 $dir = array_shift( $files );
749 $this->purgeThumbList( $dir, $files );
751 // Purge any custom thumbnail caches
752 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
757 foreach( $files as $file ) {
758 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
760 SquidUpdate
::purge( $urls );
763 wfProfileOut( __METHOD__
);
767 * Delete cached transformed files for the current version only.
769 function purgeThumbnails( $options = array() ) {
771 wfProfileIn( __METHOD__
);
774 $files = $this->getThumbnails();
775 // Always purge all files from squid regardless of handler filters
778 foreach( $files as $file ) {
779 $urls[] = $this->getThumbUrl( $file );
781 array_shift( $urls ); // don't purge directory
784 // Give media handler a chance to filter the file purge list
785 if ( !empty( $options['forThumbRefresh'] ) ) {
786 $handler = $this->getHandler();
788 $handler->filterThumbnailPurgeList( $files, $options );
792 $dir = array_shift( $files );
793 $this->purgeThumbList( $dir, $files );
795 // Purge any custom thumbnail caches
796 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
800 SquidUpdate
::purge( $urls );
803 wfProfileOut( __METHOD__
);
807 * Delete a list of thumbnails visible at urls
808 * @param $dir string base dir of the files.
809 * @param $files array of strings: relative filenames (to $dir)
811 protected function purgeThumbList( $dir, $files ) {
812 $fileListDebug = strtr(
813 var_export( $files, true ),
816 wfDebug( __METHOD__
. ": $fileListDebug\n" );
818 $purgeList = array();
819 foreach ( $files as $file ) {
820 # Check that the base file name is part of the thumb name
821 # This is a basic sanity check to avoid erasing unrelated directories
822 if ( strpos( $file, $this->getName() ) !== false
823 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
825 $purgeList[] = "{$dir}/{$file}";
829 # Delete the thumbnails
830 $this->repo
->quickPurgeBatch( $purgeList );
831 # Clear out the thumbnail directory if empty
832 $this->repo
->quickCleanDir( $dir );
835 /** purgeDescription inherited */
836 /** purgeEverything inherited */
845 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
846 $dbr = $this->repo
->getSlaveDB();
847 $tables = array( 'oldimage' );
848 $fields = OldLocalFile
::selectFields();
849 $conds = $opts = $join_conds = array();
850 $eq = $inc ?
'=' : '';
851 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
854 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
858 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
862 $opts['LIMIT'] = $limit;
865 // Search backwards for time > x queries
866 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
867 $opts['ORDER BY'] = "oi_timestamp $order";
868 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
870 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
871 &$conds, &$opts, &$join_conds ) );
873 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
876 foreach ( $res as $row ) {
877 if ( $this->repo
->oldFileFromRowFactory
) {
878 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
880 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
884 if ( $order == 'ASC' ) {
885 $r = array_reverse( $r ); // make sure it ends up descending
892 * Return the history of this file, line by line.
893 * starts with current version, then old versions.
894 * uses $this->historyLine to check which line to return:
895 * 0 return line for current version
896 * 1 query for old versions, return first one
897 * 2, ... return next old version from above query
900 public function nextHistoryLine() {
901 # Polymorphic function name to distinguish foreign and local fetches
902 $fname = get_class( $this ) . '::' . __FUNCTION__
;
904 $dbr = $this->repo
->getSlaveDB();
906 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
907 $this->historyRes
= $dbr->select( 'image',
910 "'' AS oi_archive_name",
914 array( 'img_name' => $this->title
->getDBkey() ),
918 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
919 $this->historyRes
= null;
922 } elseif ( $this->historyLine
== 1 ) {
923 $this->historyRes
= $dbr->select( 'oldimage', '*',
924 array( 'oi_name' => $this->title
->getDBkey() ),
926 array( 'ORDER BY' => 'oi_timestamp DESC' )
929 $this->historyLine ++
;
931 return $dbr->fetchObject( $this->historyRes
);
935 * Reset the history pointer to the first element of the history
937 public function resetHistory() {
938 $this->historyLine
= 0;
940 if ( !is_null( $this->historyRes
) ) {
941 $this->historyRes
= null;
945 /** getHashPath inherited */
946 /** getRel inherited */
947 /** getUrlRel inherited */
948 /** getArchiveRel inherited */
949 /** getArchivePath inherited */
950 /** getThumbPath inherited */
951 /** getArchiveUrl inherited */
952 /** getThumbUrl inherited */
953 /** getArchiveVirtualUrl inherited */
954 /** getThumbVirtualUrl inherited */
955 /** isHashed inherited */
958 * Upload a file and record it in the DB
959 * @param $srcPath String: source storage path, virtual URL, or filesystem path
960 * @param $comment String: upload description
961 * @param $pageText String: text to use for the new description page,
962 * if a new description page is created
963 * @param $flags Integer|bool: flags for publish()
964 * @param $props Array|bool: File properties, if known. This can be used to reduce the
965 * upload time when uploading virtual URLs for which the file info
967 * @param $timestamp String|bool: timestamp for img_timestamp, or false to use the current time
968 * @param $user User|null: User object or null to use $wgUser
970 * @return FileRepoStatus object. On success, the value member contains the
971 * archive name, or an empty string if it was a new file.
973 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
976 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
977 return $this->readOnlyFatalStatus();
981 wfProfileIn( __METHOD__
. '-getProps' );
982 if ( $this->repo
->isVirtualUrl( $srcPath )
983 || FileBackend
::isStoragePath( $srcPath ) )
985 $props = $this->repo
->getFileProps( $srcPath );
987 $props = FSFile
::getPropsFromPath( $srcPath );
989 wfProfileOut( __METHOD__
. '-getProps' );
993 $handler = MediaHandler
::getHandler( $props['mime'] );
995 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
997 $options['headers'] = array();
1000 // Trim spaces on user supplied text
1001 $comment = trim( $comment );
1003 // truncate nicely or the DB will do it for us
1004 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1005 $comment = $wgContLang->truncate( $comment, 255 );
1006 $this->lock(); // begin
1007 $status = $this->publish( $srcPath, $flags, $options );
1009 if ( $status->successCount
> 0 ) {
1010 # Essentially we are displacing any existing current file and saving
1011 # a new current file at the old location. If just the first succeeded,
1012 # we still need to displace the current DB entry and put in a new one.
1013 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1014 $status->fatal( 'filenotfound', $srcPath );
1018 $this->unlock(); // done
1024 * Record a file upload in the upload log and the image table
1026 * @param $desc string
1027 * @param $license string
1028 * @param $copyStatus string
1029 * @param $source string
1030 * @param $watch bool
1031 * @param $timestamp string|bool
1034 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1035 $watch = false, $timestamp = false )
1037 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1039 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp ) ) {
1045 $wgUser->addWatch( $this->getTitle() );
1051 * Record a file upload in the upload log and the image table
1053 * @param $comment string
1054 * @param $pageText string
1055 * @param $props bool|array
1056 * @param $timestamp bool|string
1057 * @param $user null|User
1060 function recordUpload2(
1061 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1063 wfProfileIn( __METHOD__
);
1065 if ( is_null( $user ) ) {
1070 $dbw = $this->repo
->getMasterDB();
1071 $dbw->begin( __METHOD__
);
1074 wfProfileIn( __METHOD__
. '-getProps' );
1075 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1076 wfProfileOut( __METHOD__
. '-getProps' );
1079 if ( $timestamp === false ) {
1080 $timestamp = $dbw->timestamp();
1083 $props['description'] = $comment;
1084 $props['user'] = $user->getId();
1085 $props['user_text'] = $user->getName();
1086 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1087 $this->setProps( $props );
1089 # Fail now if the file isn't there
1090 if ( !$this->fileExists
) {
1091 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1092 wfProfileOut( __METHOD__
);
1098 # Test to see if the row exists using INSERT IGNORE
1099 # This avoids race conditions by locking the row until the commit, and also
1100 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1101 $dbw->insert( 'image',
1103 'img_name' => $this->getName(),
1104 'img_size' => $this->size
,
1105 'img_width' => intval( $this->width
),
1106 'img_height' => intval( $this->height
),
1107 'img_bits' => $this->bits
,
1108 'img_media_type' => $this->media_type
,
1109 'img_major_mime' => $this->major_mime
,
1110 'img_minor_mime' => $this->minor_mime
,
1111 'img_timestamp' => $timestamp,
1112 'img_description' => $comment,
1113 'img_user' => $user->getId(),
1114 'img_user_text' => $user->getName(),
1115 'img_metadata' => $this->metadata
,
1116 'img_sha1' => $this->sha1
1121 if ( $dbw->affectedRows() == 0 ) {
1122 # (bug 34993) Note: $oldver can be empty here, if the previous
1123 # version of the file was broken. Allow registration of the new
1124 # version to continue anyway, because that's better than having
1125 # an image that's not fixable by user operations.
1128 # Collision, this is an update of a file
1129 # Insert previous contents into oldimage
1130 $dbw->insertSelect( 'oldimage', 'image',
1132 'oi_name' => 'img_name',
1133 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1134 'oi_size' => 'img_size',
1135 'oi_width' => 'img_width',
1136 'oi_height' => 'img_height',
1137 'oi_bits' => 'img_bits',
1138 'oi_timestamp' => 'img_timestamp',
1139 'oi_description' => 'img_description',
1140 'oi_user' => 'img_user',
1141 'oi_user_text' => 'img_user_text',
1142 'oi_metadata' => 'img_metadata',
1143 'oi_media_type' => 'img_media_type',
1144 'oi_major_mime' => 'img_major_mime',
1145 'oi_minor_mime' => 'img_minor_mime',
1146 'oi_sha1' => 'img_sha1'
1148 array( 'img_name' => $this->getName() ),
1152 # Update the current image row
1153 $dbw->update( 'image',
1155 'img_size' => $this->size
,
1156 'img_width' => intval( $this->width
),
1157 'img_height' => intval( $this->height
),
1158 'img_bits' => $this->bits
,
1159 'img_media_type' => $this->media_type
,
1160 'img_major_mime' => $this->major_mime
,
1161 'img_minor_mime' => $this->minor_mime
,
1162 'img_timestamp' => $timestamp,
1163 'img_description' => $comment,
1164 'img_user' => $user->getId(),
1165 'img_user_text' => $user->getName(),
1166 'img_metadata' => $this->metadata
,
1167 'img_sha1' => $this->sha1
1169 array( 'img_name' => $this->getName() ),
1173 # This is a new file, so update the image count
1174 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1177 $descTitle = $this->getTitle();
1178 $wikiPage = new WikiFilePage( $descTitle );
1179 $wikiPage->setFile( $this );
1182 $log = new LogPage( 'upload' );
1183 $action = $reupload ?
'overwrite' : 'upload';
1184 $logId = $log->addEntry( $action, $descTitle, $comment, array(), $user );
1186 wfProfileIn( __METHOD__
. '-edit' );
1187 $exists = $descTitle->exists();
1190 # Create a null revision
1191 $latest = $descTitle->getLatestRevID();
1192 $nullRevision = Revision
::newNullRevision(
1194 $descTitle->getArticleID(),
1195 $log->getRcComment(),
1198 if (!is_null($nullRevision)) {
1199 $nullRevision->insertOn( $dbw );
1201 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1202 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1206 # Commit the transaction now, in case something goes wrong later
1207 # The most important thing is that files don't get lost, especially archives
1208 # NOTE: once we have support for nested transactions, the commit may be moved
1209 # to after $wikiPage->doEdit has been called.
1210 $dbw->commit( __METHOD__
);
1213 # Invalidate the cache for the description page
1214 $descTitle->invalidateCache();
1215 $descTitle->purgeSquid();
1217 # New file; create the description page.
1218 # There's already a log entry, so don't make a second RC entry
1219 # Squid and file cache for the description page are purged by doEditContent.
1220 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1221 $status = $wikiPage->doEditContent( $content, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
, false, $user );
1223 if ( isset( $status->value
['revision'] ) ) { // XXX; doEdit() uses a transaction
1224 $dbw->begin( __METHOD__
);
1225 $dbw->update( 'logging',
1226 array( 'log_page' => $status->value
['revision']->getPage() ),
1227 array( 'log_id' => $logId ),
1230 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1233 wfProfileOut( __METHOD__
. '-edit' );
1235 # Save to cache and purge the squid
1236 # We shall not saveToCache before the commit since otherwise
1237 # in case of a rollback there is an usable file from memcached
1238 # which in fact doesn't really exist (bug 24978)
1239 $this->saveToCache();
1242 # Delete old thumbnails
1243 wfProfileIn( __METHOD__
. '-purge' );
1244 $this->purgeThumbnails();
1245 wfProfileOut( __METHOD__
. '-purge' );
1247 # Remove the old file from the squid cache
1248 SquidUpdate
::purge( array( $this->getURL() ) );
1251 # Hooks, hooks, the magic of hooks...
1252 wfProfileIn( __METHOD__
. '-hooks' );
1253 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1254 wfProfileOut( __METHOD__
. '-hooks' );
1256 # Invalidate cache for all pages using this file
1257 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1258 $update->doUpdate();
1260 # Invalidate cache for all pages that redirects on this page
1261 $redirs = $this->getTitle()->getRedirectsHere();
1263 foreach ( $redirs as $redir ) {
1264 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1265 $update->doUpdate();
1268 wfProfileOut( __METHOD__
);
1273 * Move or copy a file to its public location. If a file exists at the
1274 * destination, move it to an archive. Returns a FileRepoStatus object with
1275 * the archive name in the "value" member on success.
1277 * The archive name should be passed through to recordUpload for database
1280 * @param $srcPath String: local filesystem path to the source image
1281 * @param $flags Integer: a bitwise combination of:
1282 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1283 * @param $options Array Optional additional parameters
1284 * @return FileRepoStatus object. On success, the value member contains the
1285 * archive name, or an empty string if it was a new file.
1287 function publish( $srcPath, $flags = 0, array $options = array() ) {
1288 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1292 * Move or copy a file to a specified location. Returns a FileRepoStatus
1293 * object with the archive name in the "value" member on success.
1295 * The archive name should be passed through to recordUpload for database
1298 * @param $srcPath String: local filesystem path to the source image
1299 * @param $dstRel String: target relative path
1300 * @param $flags Integer: a bitwise combination of:
1301 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1302 * @param $options Array Optional additional parameters
1303 * @return FileRepoStatus object. On success, the value member contains the
1304 * archive name, or an empty string if it was a new file.
1306 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1307 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1308 return $this->readOnlyFatalStatus();
1311 $this->lock(); // begin
1313 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1314 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1315 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1316 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1318 if ( $status->value
== 'new' ) {
1319 $status->value
= '';
1321 $status->value
= $archiveName;
1324 $this->unlock(); // done
1329 /** getLinksTo inherited */
1330 /** getExifData inherited */
1331 /** isLocal inherited */
1332 /** wasDeleted inherited */
1335 * Move file to the new title
1337 * Move current, old version and all thumbnails
1338 * to the new filename. Old file is deleted.
1340 * Cache purging is done; checks for validity
1341 * and logging are caller's responsibility
1343 * @param $target Title New file name
1344 * @return FileRepoStatus object.
1346 function move( $target ) {
1347 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1348 return $this->readOnlyFatalStatus();
1351 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1352 $batch = new LocalFileMoveBatch( $this, $target );
1354 $this->lock(); // begin
1355 $batch->addCurrent();
1356 $archiveNames = $batch->addOlds();
1357 $status = $batch->execute();
1358 $this->unlock(); // done
1360 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1362 $this->purgeEverything();
1363 foreach ( $archiveNames as $archiveName ) {
1364 $this->purgeOldThumbnails( $archiveName );
1366 if ( $status->isOK() ) {
1367 // Now switch the object
1368 $this->title
= $target;
1369 // Force regeneration of the name and hashpath
1370 unset( $this->name
);
1371 unset( $this->hashPath
);
1372 // Purge the new image
1373 $this->purgeEverything();
1380 * Delete all versions of the file.
1382 * Moves the files into an archive directory (or deletes them)
1383 * and removes the database rows.
1385 * Cache purging is done; logging is caller's responsibility.
1389 * @return FileRepoStatus object.
1391 function delete( $reason, $suppress = false ) {
1392 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1393 return $this->readOnlyFatalStatus();
1396 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1398 $this->lock(); // begin
1399 $batch->addCurrent();
1400 # Get old version relative paths
1401 $archiveNames = $batch->addOlds();
1402 $status = $batch->execute();
1403 $this->unlock(); // done
1405 if ( $status->isOK() ) {
1406 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1409 $this->purgeEverything();
1410 foreach ( $archiveNames as $archiveName ) {
1411 $this->purgeOldThumbnails( $archiveName );
1418 * Delete an old version of the file.
1420 * Moves the file into an archive directory (or deletes it)
1421 * and removes the database row.
1423 * Cache purging is done; logging is caller's responsibility.
1425 * @param $archiveName String
1426 * @param $reason String
1427 * @param $suppress Boolean
1428 * @throws MWException or FSException on database or file store failure
1429 * @return FileRepoStatus object.
1431 function deleteOld( $archiveName, $reason, $suppress = false ) {
1432 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1433 return $this->readOnlyFatalStatus();
1436 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1438 $this->lock(); // begin
1439 $batch->addOld( $archiveName );
1440 $status = $batch->execute();
1441 $this->unlock(); // done
1443 $this->purgeOldThumbnails( $archiveName );
1444 if ( $status->isOK() ) {
1445 $this->purgeDescription();
1446 $this->purgeHistory();
1453 * Restore all or specified deleted revisions to the given file.
1454 * Permissions and logging are left to the caller.
1456 * May throw database exceptions on error.
1458 * @param $versions array set of record ids of deleted items to restore,
1459 * or empty to restore all revisions.
1460 * @param $unsuppress Boolean
1461 * @return FileRepoStatus
1463 function restore( $versions = array(), $unsuppress = false ) {
1464 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1465 return $this->readOnlyFatalStatus();
1468 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1470 $this->lock(); // begin
1474 $batch->addIds( $versions );
1476 $status = $batch->execute();
1477 if ( $status->isGood() ) {
1478 $cleanupStatus = $batch->cleanup();
1479 $cleanupStatus->successCount
= 0;
1480 $cleanupStatus->failCount
= 0;
1481 $status->merge( $cleanupStatus );
1483 $this->unlock(); // done
1488 /** isMultipage inherited */
1489 /** pageCount inherited */
1490 /** scaleHeight inherited */
1491 /** getImageSize inherited */
1494 * Get the URL of the file description page.
1497 function getDescriptionUrl() {
1498 return $this->title
->getLocalUrl();
1502 * Get the HTML text of the description page
1503 * This is not used by ImagePage for local files, since (among other things)
1504 * it skips the parser cache.
1505 * @return bool|mixed
1507 function getDescriptionText() {
1508 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1509 if ( !$revision ) return false;
1510 $content = $revision->getContent();
1511 if ( !$content ) return false;
1512 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions() );
1513 return $pout->getText();
1519 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1521 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1523 } elseif ( $audience == self
::FOR_THIS_USER
1524 && !$this->userCan( self
::DELETED_COMMENT
, $user ) )
1528 return $this->description
;
1533 * @return bool|string
1535 function getTimestamp() {
1537 return $this->timestamp
;
1543 function getSha1() {
1545 // Initialise now if necessary
1546 if ( $this->sha1
== '' && $this->fileExists
) {
1547 $this->lock(); // begin
1549 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1550 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1551 $dbw = $this->repo
->getMasterDB();
1552 $dbw->update( 'image',
1553 array( 'img_sha1' => $this->sha1
),
1554 array( 'img_name' => $this->getName() ),
1556 $this->saveToCache();
1559 $this->unlock(); // done
1568 function isCacheable() {
1570 return strlen( $this->metadata
) <= self
::CACHE_FIELD_MAX_LEN
; // avoid OOMs
1574 * Start a transaction and lock the image for update
1575 * Increments a reference counter if the lock is already held
1576 * @return boolean True if the image exists, false otherwise
1579 $dbw = $this->repo
->getMasterDB();
1581 if ( !$this->locked
) {
1582 $dbw->begin( __METHOD__
);
1586 return $dbw->selectField( 'image', '1',
1587 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1591 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1592 * the transaction and thereby releases the image lock.
1595 if ( $this->locked
) {
1597 if ( !$this->locked
) {
1598 $dbw = $this->repo
->getMasterDB();
1599 $dbw->commit( __METHOD__
);
1605 * Roll back the DB transaction and mark the image unlocked
1607 function unlockAndRollback() {
1608 $this->locked
= false;
1609 $dbw = $this->repo
->getMasterDB();
1610 $dbw->rollback( __METHOD__
);
1616 protected function readOnlyFatalStatus() {
1617 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1618 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1620 } // LocalFile class
1622 # ------------------------------------------------------------------------------
1625 * Helper class for file deletion
1626 * @ingroup FileAbstraction
1628 class LocalFileDeleteBatch
{
1635 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1640 * @param $reason string
1641 * @param $suppress bool
1643 function __construct( File
$file, $reason = '', $suppress = false ) {
1644 $this->file
= $file;
1645 $this->reason
= $reason;
1646 $this->suppress
= $suppress;
1647 $this->status
= $file->repo
->newGood();
1650 function addCurrent() {
1651 $this->srcRels
['.'] = $this->file
->getRel();
1655 * @param $oldName string
1657 function addOld( $oldName ) {
1658 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1659 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1663 * Add the old versions of the image to the batch
1664 * @return Array List of archive names from old versions
1666 function addOlds() {
1667 $archiveNames = array();
1669 $dbw = $this->file
->repo
->getMasterDB();
1670 $result = $dbw->select( 'oldimage',
1671 array( 'oi_archive_name' ),
1672 array( 'oi_name' => $this->file
->getName() ),
1676 foreach ( $result as $row ) {
1677 $this->addOld( $row->oi_archive_name
);
1678 $archiveNames[] = $row->oi_archive_name
;
1681 return $archiveNames;
1687 function getOldRels() {
1688 if ( !isset( $this->srcRels
['.'] ) ) {
1689 $oldRels =& $this->srcRels
;
1690 $deleteCurrent = false;
1692 $oldRels = $this->srcRels
;
1693 unset( $oldRels['.'] );
1694 $deleteCurrent = true;
1697 return array( $oldRels, $deleteCurrent );
1703 protected function getHashes() {
1705 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1707 if ( $deleteCurrent ) {
1708 $hashes['.'] = $this->file
->getSha1();
1711 if ( count( $oldRels ) ) {
1712 $dbw = $this->file
->repo
->getMasterDB();
1713 $res = $dbw->select(
1715 array( 'oi_archive_name', 'oi_sha1' ),
1716 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1720 foreach ( $res as $row ) {
1721 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1722 // Get the hash from the file
1723 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1724 $props = $this->file
->repo
->getFileProps( $oldUrl );
1726 if ( $props['fileExists'] ) {
1727 // Upgrade the oldimage row
1728 $dbw->update( 'oldimage',
1729 array( 'oi_sha1' => $props['sha1'] ),
1730 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1732 $hashes[$row->oi_archive_name
] = $props['sha1'];
1734 $hashes[$row->oi_archive_name
] = false;
1737 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1742 $missing = array_diff_key( $this->srcRels
, $hashes );
1744 foreach ( $missing as $name => $rel ) {
1745 $this->status
->error( 'filedelete-old-unregistered', $name );
1748 foreach ( $hashes as $name => $hash ) {
1750 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1751 unset( $hashes[$name] );
1758 function doDBInserts() {
1761 $dbw = $this->file
->repo
->getMasterDB();
1762 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1763 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1764 $encReason = $dbw->addQuotes( $this->reason
);
1765 $encGroup = $dbw->addQuotes( 'deleted' );
1766 $ext = $this->file
->getExtension();
1767 $dotExt = $ext === '' ?
'' : ".$ext";
1768 $encExt = $dbw->addQuotes( $dotExt );
1769 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1771 // Bitfields to further suppress the content
1772 if ( $this->suppress
) {
1774 // This should be 15...
1775 $bitfield |
= Revision
::DELETED_TEXT
;
1776 $bitfield |
= Revision
::DELETED_COMMENT
;
1777 $bitfield |
= Revision
::DELETED_USER
;
1778 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1780 $bitfield = 'oi_deleted';
1783 if ( $deleteCurrent ) {
1784 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1785 $where = array( 'img_name' => $this->file
->getName() );
1786 $dbw->insertSelect( 'filearchive', 'image',
1788 'fa_storage_group' => $encGroup,
1789 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1790 'fa_deleted_user' => $encUserId,
1791 'fa_deleted_timestamp' => $encTimestamp,
1792 'fa_deleted_reason' => $encReason,
1793 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1795 'fa_name' => 'img_name',
1796 'fa_archive_name' => 'NULL',
1797 'fa_size' => 'img_size',
1798 'fa_width' => 'img_width',
1799 'fa_height' => 'img_height',
1800 'fa_metadata' => 'img_metadata',
1801 'fa_bits' => 'img_bits',
1802 'fa_media_type' => 'img_media_type',
1803 'fa_major_mime' => 'img_major_mime',
1804 'fa_minor_mime' => 'img_minor_mime',
1805 'fa_description' => 'img_description',
1806 'fa_user' => 'img_user',
1807 'fa_user_text' => 'img_user_text',
1808 'fa_timestamp' => 'img_timestamp',
1809 'fa_sha1' => 'img_sha1',
1810 ), $where, __METHOD__
);
1813 if ( count( $oldRels ) ) {
1814 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1816 'oi_name' => $this->file
->getName(),
1817 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1818 $dbw->insertSelect( 'filearchive', 'oldimage',
1820 'fa_storage_group' => $encGroup,
1821 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1822 'fa_deleted_user' => $encUserId,
1823 'fa_deleted_timestamp' => $encTimestamp,
1824 'fa_deleted_reason' => $encReason,
1825 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1827 'fa_name' => 'oi_name',
1828 'fa_archive_name' => 'oi_archive_name',
1829 'fa_size' => 'oi_size',
1830 'fa_width' => 'oi_width',
1831 'fa_height' => 'oi_height',
1832 'fa_metadata' => 'oi_metadata',
1833 'fa_bits' => 'oi_bits',
1834 'fa_media_type' => 'oi_media_type',
1835 'fa_major_mime' => 'oi_major_mime',
1836 'fa_minor_mime' => 'oi_minor_mime',
1837 'fa_description' => 'oi_description',
1838 'fa_user' => 'oi_user',
1839 'fa_user_text' => 'oi_user_text',
1840 'fa_timestamp' => 'oi_timestamp',
1841 'fa_sha1' => 'oi_sha1',
1842 ), $where, __METHOD__
);
1846 function doDBDeletes() {
1847 $dbw = $this->file
->repo
->getMasterDB();
1848 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1850 if ( count( $oldRels ) ) {
1851 $dbw->delete( 'oldimage',
1853 'oi_name' => $this->file
->getName(),
1854 'oi_archive_name' => array_keys( $oldRels )
1858 if ( $deleteCurrent ) {
1859 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1864 * Run the transaction
1865 * @return FileRepoStatus
1867 function execute() {
1868 wfProfileIn( __METHOD__
);
1870 $this->file
->lock();
1871 // Leave private files alone
1872 $privateFiles = array();
1873 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1874 $dbw = $this->file
->repo
->getMasterDB();
1876 if ( !empty( $oldRels ) ) {
1877 $res = $dbw->select( 'oldimage',
1878 array( 'oi_archive_name' ),
1879 array( 'oi_name' => $this->file
->getName(),
1880 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1881 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1884 foreach ( $res as $row ) {
1885 $privateFiles[$row->oi_archive_name
] = 1;
1888 // Prepare deletion batch
1889 $hashes = $this->getHashes();
1890 $this->deletionBatch
= array();
1891 $ext = $this->file
->getExtension();
1892 $dotExt = $ext === '' ?
'' : ".$ext";
1894 foreach ( $this->srcRels
as $name => $srcRel ) {
1895 // Skip files that have no hash (missing source).
1896 // Keep private files where they are.
1897 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1898 $hash = $hashes[$name];
1899 $key = $hash . $dotExt;
1900 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1901 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1905 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1906 // We acquire this lock by running the inserts now, before the file operations.
1908 // This potentially has poor lock contention characteristics -- an alternative
1909 // scheme would be to insert stub filearchive entries with no fa_name and commit
1910 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1911 $this->doDBInserts();
1913 // Removes non-existent file from the batch, so we don't get errors.
1914 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1916 // Execute the file deletion batch
1917 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1919 if ( !$status->isGood() ) {
1920 $this->status
->merge( $status );
1923 if ( !$this->status
->isOK() ) {
1924 // Critical file deletion error
1925 // Roll back inserts, release lock and abort
1926 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1927 $this->file
->unlockAndRollback();
1928 wfProfileOut( __METHOD__
);
1929 return $this->status
;
1932 // Delete image/oldimage rows
1933 $this->doDBDeletes();
1935 // Commit and return
1936 $this->file
->unlock();
1937 wfProfileOut( __METHOD__
);
1939 return $this->status
;
1943 * Removes non-existent files from a deletion batch.
1944 * @param $batch array
1947 function removeNonexistentFiles( $batch ) {
1948 $files = $newBatch = array();
1950 foreach ( $batch as $batchItem ) {
1951 list( $src, $dest ) = $batchItem;
1952 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1955 $result = $this->file
->repo
->fileExistsBatch( $files );
1957 foreach ( $batch as $batchItem ) {
1958 if ( $result[$batchItem[0]] ) {
1959 $newBatch[] = $batchItem;
1967 # ------------------------------------------------------------------------------
1970 * Helper class for file undeletion
1971 * @ingroup FileAbstraction
1973 class LocalFileRestoreBatch
{
1979 var $cleanupBatch, $ids, $all, $unsuppress = false;
1983 * @param $unsuppress bool
1985 function __construct( File
$file, $unsuppress = false ) {
1986 $this->file
= $file;
1987 $this->cleanupBatch
= $this->ids
= array();
1988 $this->ids
= array();
1989 $this->unsuppress
= $unsuppress;
1995 function addId( $fa_id ) {
1996 $this->ids
[] = $fa_id;
2000 * Add a whole lot of files by ID
2002 function addIds( $ids ) {
2003 $this->ids
= array_merge( $this->ids
, $ids );
2007 * Add all revisions of the file
2014 * Run the transaction, except the cleanup batch.
2015 * The cleanup batch should be run in a separate transaction, because it locks different
2016 * rows and there's no need to keep the image row locked while it's acquiring those locks
2017 * The caller may have its own transaction open.
2018 * So we save the batch and let the caller call cleanup()
2019 * @return FileRepoStatus
2021 function execute() {
2024 if ( !$this->all
&& !$this->ids
) {
2026 return $this->file
->repo
->newGood();
2029 $exists = $this->file
->lock();
2030 $dbw = $this->file
->repo
->getMasterDB();
2031 $status = $this->file
->repo
->newGood();
2033 // Fetch all or selected archived revisions for the file,
2034 // sorted from the most recent to the oldest.
2035 $conditions = array( 'fa_name' => $this->file
->getName() );
2037 if ( !$this->all
) {
2038 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
2041 $result = $dbw->select( 'filearchive', '*',
2044 array( 'ORDER BY' => 'fa_timestamp DESC' )
2047 $idsPresent = array();
2048 $storeBatch = array();
2049 $insertBatch = array();
2050 $insertCurrent = false;
2051 $deleteIds = array();
2053 $archiveNames = array();
2055 foreach ( $result as $row ) {
2056 $idsPresent[] = $row->fa_id
;
2058 if ( $row->fa_name
!= $this->file
->getName() ) {
2059 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2060 $status->failCount++
;
2064 if ( $row->fa_storage_key
== '' ) {
2065 // Revision was missing pre-deletion
2066 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2067 $status->failCount++
;
2071 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
2072 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2074 if( isset( $row->fa_sha1
) ) {
2075 $sha1 = $row->fa_sha1
;
2077 // old row, populate from key
2078 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2082 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2083 $sha1 = substr( $sha1, 1 );
2086 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2087 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2088 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2089 ||
is_null( $row->fa_metadata
) ) {
2090 // Refresh our metadata
2091 // Required for a new current revision; nice for older ones too. :)
2092 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2095 'minor_mime' => $row->fa_minor_mime
,
2096 'major_mime' => $row->fa_major_mime
,
2097 'media_type' => $row->fa_media_type
,
2098 'metadata' => $row->fa_metadata
2102 if ( $first && !$exists ) {
2103 // This revision will be published as the new current version
2104 $destRel = $this->file
->getRel();
2105 $insertCurrent = array(
2106 'img_name' => $row->fa_name
,
2107 'img_size' => $row->fa_size
,
2108 'img_width' => $row->fa_width
,
2109 'img_height' => $row->fa_height
,
2110 'img_metadata' => $props['metadata'],
2111 'img_bits' => $row->fa_bits
,
2112 'img_media_type' => $props['media_type'],
2113 'img_major_mime' => $props['major_mime'],
2114 'img_minor_mime' => $props['minor_mime'],
2115 'img_description' => $row->fa_description
,
2116 'img_user' => $row->fa_user
,
2117 'img_user_text' => $row->fa_user_text
,
2118 'img_timestamp' => $row->fa_timestamp
,
2122 // The live (current) version cannot be hidden!
2123 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2124 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2125 $this->cleanupBatch
[] = $row->fa_storage_key
;
2128 $archiveName = $row->fa_archive_name
;
2130 if ( $archiveName == '' ) {
2131 // This was originally a current version; we
2132 // have to devise a new archive name for it.
2133 // Format is <timestamp of archiving>!<name>
2134 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2137 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2139 } while ( isset( $archiveNames[$archiveName] ) );
2142 $archiveNames[$archiveName] = true;
2143 $destRel = $this->file
->getArchiveRel( $archiveName );
2144 $insertBatch[] = array(
2145 'oi_name' => $row->fa_name
,
2146 'oi_archive_name' => $archiveName,
2147 'oi_size' => $row->fa_size
,
2148 'oi_width' => $row->fa_width
,
2149 'oi_height' => $row->fa_height
,
2150 'oi_bits' => $row->fa_bits
,
2151 'oi_description' => $row->fa_description
,
2152 'oi_user' => $row->fa_user
,
2153 'oi_user_text' => $row->fa_user_text
,
2154 'oi_timestamp' => $row->fa_timestamp
,
2155 'oi_metadata' => $props['metadata'],
2156 'oi_media_type' => $props['media_type'],
2157 'oi_major_mime' => $props['major_mime'],
2158 'oi_minor_mime' => $props['minor_mime'],
2159 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2160 'oi_sha1' => $sha1 );
2163 $deleteIds[] = $row->fa_id
;
2165 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2166 // private files can stay where they are
2167 $status->successCount++
;
2169 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2170 $this->cleanupBatch
[] = $row->fa_storage_key
;
2178 // Add a warning to the status object for missing IDs
2179 $missingIds = array_diff( $this->ids
, $idsPresent );
2181 foreach ( $missingIds as $id ) {
2182 $status->error( 'undelete-missing-filearchive', $id );
2185 // Remove missing files from batch, so we don't get errors when undeleting them
2186 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2188 // Run the store batch
2189 // Use the OVERWRITE_SAME flag to smooth over a common error
2190 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2191 $status->merge( $storeStatus );
2193 if ( !$status->isGood() ) {
2194 // Even if some files could be copied, fail entirely as that is the
2195 // easiest thing to do without data loss
2196 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2197 $status->ok
= false;
2198 $this->file
->unlock();
2203 // Run the DB updates
2204 // Because we have locked the image row, key conflicts should be rare.
2205 // If they do occur, we can roll back the transaction at this time with
2206 // no data loss, but leaving unregistered files scattered throughout the
2208 // This is not ideal, which is why it's important to lock the image row.
2209 if ( $insertCurrent ) {
2210 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2213 if ( $insertBatch ) {
2214 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2218 $dbw->delete( 'filearchive',
2219 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2223 // If store batch is empty (all files are missing), deletion is to be considered successful
2224 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2226 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2228 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2230 $this->file
->purgeEverything();
2232 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2233 $this->file
->purgeDescription();
2234 $this->file
->purgeHistory();
2238 $this->file
->unlock();
2244 * Removes non-existent files from a store batch.
2245 * @param $triplets array
2248 function removeNonexistentFiles( $triplets ) {
2249 $files = $filteredTriplets = array();
2250 foreach ( $triplets as $file ) {
2251 $files[$file[0]] = $file[0];
2254 $result = $this->file
->repo
->fileExistsBatch( $files );
2256 foreach ( $triplets as $file ) {
2257 if ( $result[$file[0]] ) {
2258 $filteredTriplets[] = $file;
2262 return $filteredTriplets;
2266 * Removes non-existent files from a cleanup batch.
2267 * @param $batch array
2270 function removeNonexistentFromCleanup( $batch ) {
2271 $files = $newBatch = array();
2272 $repo = $this->file
->repo
;
2274 foreach ( $batch as $file ) {
2275 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2276 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2279 $result = $repo->fileExistsBatch( $files );
2281 foreach ( $batch as $file ) {
2282 if ( $result[$file] ) {
2283 $newBatch[] = $file;
2291 * Delete unused files in the deleted zone.
2292 * This should be called from outside the transaction in which execute() was called.
2293 * @return FileRepoStatus|void
2295 function cleanup() {
2296 if ( !$this->cleanupBatch
) {
2297 return $this->file
->repo
->newGood();
2300 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2302 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2308 * Cleanup a failed batch. The batch was only partially successful, so
2309 * rollback by removing all items that were succesfully copied.
2311 * @param Status $storeStatus
2312 * @param array $storeBatch
2314 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2315 $cleanupBatch = array();
2317 foreach ( $storeStatus->success
as $i => $success ) {
2318 // Check if this item of the batch was successfully copied
2320 // Item was successfully copied and needs to be removed again
2321 // Extract ($dstZone, $dstRel) from the batch
2322 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2325 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2329 # ------------------------------------------------------------------------------
2332 * Helper class for file movement
2333 * @ingroup FileAbstraction
2335 class LocalFileMoveBatch
{
2347 var $cur, $olds, $oldCount, $archive;
2356 * @param Title $target
2358 function __construct( File
$file, Title
$target ) {
2359 $this->file
= $file;
2360 $this->target
= $target;
2361 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2362 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2363 $this->oldName
= $this->file
->getName();
2364 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2365 $this->oldRel
= $this->oldHash
. $this->oldName
;
2366 $this->newRel
= $this->newHash
. $this->newName
;
2367 $this->db
= $file->getRepo()->getMasterDb();
2371 * Add the current image to the batch
2373 function addCurrent() {
2374 $this->cur
= array( $this->oldRel
, $this->newRel
);
2378 * Add the old versions of the image to the batch
2379 * @return Array List of archive names from old versions
2381 function addOlds() {
2382 $archiveBase = 'archive';
2383 $this->olds
= array();
2384 $this->oldCount
= 0;
2385 $archiveNames = array();
2387 $result = $this->db
->select( 'oldimage',
2388 array( 'oi_archive_name', 'oi_deleted' ),
2389 array( 'oi_name' => $this->oldName
),
2393 foreach ( $result as $row ) {
2394 $archiveNames[] = $row->oi_archive_name
;
2395 $oldName = $row->oi_archive_name
;
2396 $bits = explode( '!', $oldName, 2 );
2398 if ( count( $bits ) != 2 ) {
2399 wfDebug( "Old file name missing !: '$oldName' \n" );
2403 list( $timestamp, $filename ) = $bits;
2405 if ( $this->oldName
!= $filename ) {
2406 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2412 // Do we want to add those to oldCount?
2413 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2417 $this->olds
[] = array(
2418 "{$archiveBase}/{$this->oldHash}{$oldName}",
2419 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2423 return $archiveNames;
2428 * @return FileRepoStatus
2430 function execute() {
2431 $repo = $this->file
->repo
;
2432 $status = $repo->newGood();
2434 $triplets = $this->getMoveTriplets();
2435 $triplets = $this->removeNonexistentFiles( $triplets );
2437 $this->file
->lock(); // begin
2438 // Rename the file versions metadata in the DB.
2439 // This implicitly locks the destination file, which avoids race conditions.
2440 // If we moved the files from A -> C before DB updates, another process could
2441 // move files from B -> C at this point, causing storeBatch() to fail and thus
2442 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2443 $statusDb = $this->doDBUpdates();
2444 if ( !$statusDb->isGood() ) {
2445 $this->file
->unlockAndRollback();
2446 $statusDb->ok
= false;
2449 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2451 // Copy the files into their new location.
2452 // If a prior process fataled copying or cleaning up files we tolerate any
2453 // of the existing files if they are identical to the ones being stored.
2454 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2455 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2456 if ( !$statusMove->isGood() ) {
2457 // Delete any files copied over (while the destination is still locked)
2458 $this->cleanupTarget( $triplets );
2459 $this->file
->unlockAndRollback(); // unlocks the destination
2460 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2461 $statusMove->ok
= false;
2464 $this->file
->unlock(); // done
2466 // Everything went ok, remove the source files
2467 $this->cleanupSource( $triplets );
2469 $status->merge( $statusDb );
2470 $status->merge( $statusMove );
2476 * Do the database updates and return a new FileRepoStatus indicating how
2477 * many rows where updated.
2479 * @return FileRepoStatus
2481 function doDBUpdates() {
2482 $repo = $this->file
->repo
;
2483 $status = $repo->newGood();
2486 // Update current image
2489 array( 'img_name' => $this->newName
),
2490 array( 'img_name' => $this->oldName
),
2494 if ( $dbw->affectedRows() ) {
2495 $status->successCount++
;
2497 $status->failCount++
;
2498 $status->fatal( 'imageinvalidfilename' );
2502 // Update old images
2506 'oi_name' => $this->newName
,
2507 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2508 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2510 array( 'oi_name' => $this->oldName
),
2514 $affected = $dbw->affectedRows();
2515 $total = $this->oldCount
;
2516 $status->successCount +
= $affected;
2517 // Bug 34934: $total is based on files that actually exist.
2518 // There may be more DB rows than such files, in which case $affected
2519 // can be greater than $total. We use max() to avoid negatives here.
2520 $status->failCount +
= max( 0, $total - $affected );
2521 if ( $status->failCount
) {
2522 $status->error( 'imageinvalidfilename' );
2529 * Generate triplets for FileRepo::storeBatch().
2532 function getMoveTriplets() {
2533 $moves = array_merge( array( $this->cur
), $this->olds
);
2534 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2536 foreach ( $moves as $move ) {
2537 // $move: (oldRelativePath, newRelativePath)
2538 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2539 $triplets[] = array( $srcUrl, 'public', $move[1] );
2540 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2547 * Removes non-existent files from move batch.
2548 * @param $triplets array
2551 function removeNonexistentFiles( $triplets ) {
2554 foreach ( $triplets as $file ) {
2555 $files[$file[0]] = $file[0];
2558 $result = $this->file
->repo
->fileExistsBatch( $files );
2559 $filteredTriplets = array();
2561 foreach ( $triplets as $file ) {
2562 if ( $result[$file[0]] ) {
2563 $filteredTriplets[] = $file;
2565 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2569 return $filteredTriplets;
2573 * Cleanup a partially moved array of triplets by deleting the target
2574 * files. Called if something went wrong half way.
2576 function cleanupTarget( $triplets ) {
2577 // Create dest pairs from the triplets
2579 foreach ( $triplets as $triplet ) {
2580 // $triplet: (old source virtual URL, dst zone, dest rel)
2581 $pairs[] = array( $triplet[1], $triplet[2] );
2584 $this->file
->repo
->cleanupBatch( $pairs );
2588 * Cleanup a fully moved array of triplets by deleting the source files.
2589 * Called at the end of the move process if everything else went ok.
2591 function cleanupSource( $triplets ) {
2592 // Create source file names from the triplets
2594 foreach ( $triplets as $triplet ) {
2595 $files[] = $triplet[0];
2598 $this->file
->repo
->cleanupBatch( $files );