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_size' => $this->size
, // sanity
444 'img_width' => $this->width
,
445 'img_height' => $this->height
,
446 'img_bits' => $this->bits
,
447 'img_media_type' => $this->media_type
,
448 'img_major_mime' => $major,
449 'img_minor_mime' => $minor,
450 'img_metadata' => $this->metadata
,
451 'img_sha1' => $this->sha1
,
453 array( 'img_name' => $this->getName() ),
457 $this->saveToCache();
459 $this->unlock(); // done
461 wfProfileOut( __METHOD__
);
465 * Set properties in this object to be equal to those given in the
466 * associative array $info. Only cacheable fields can be set.
468 * If 'mime' is given, it will be split into major_mime/minor_mime.
469 * If major_mime/minor_mime are given, $this->mime will also be set.
471 function setProps( $info ) {
472 $this->dataLoaded
= true;
473 $fields = $this->getCacheFields( '' );
474 $fields[] = 'fileExists';
476 foreach ( $fields as $field ) {
477 if ( isset( $info[$field] ) ) {
478 $this->$field = $info[$field];
482 // Fix up mime fields
483 if ( isset( $info['major_mime'] ) ) {
484 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
485 } elseif ( isset( $info['mime'] ) ) {
486 $this->mime
= $info['mime'];
487 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
491 /** splitMime inherited */
492 /** getName inherited */
493 /** getTitle inherited */
494 /** getURL inherited */
495 /** getViewURL inherited */
496 /** getPath inherited */
497 /** isVisible inhereted */
502 function isMissing() {
503 if ( $this->missing
=== null ) {
504 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
505 $this->missing
= !$fileExists;
507 return $this->missing
;
511 * Return the width of the image
514 * @return bool|int Returns false on error
516 public function getWidth( $page = 1 ) {
519 if ( $this->isMultipage() ) {
520 $dim = $this->getHandler()->getPageDimensions( $this, $page );
522 return $dim['width'];
532 * Return the height of the image
535 * @return bool|int Returns false on error
537 public function getHeight( $page = 1 ) {
540 if ( $this->isMultipage() ) {
541 $dim = $this->getHandler()->getPageDimensions( $this, $page );
543 return $dim['height'];
548 return $this->height
;
553 * Returns ID or name of user who uploaded the file
555 * @param $type string 'text' or 'id'
558 function getUser( $type = 'text' ) {
561 if ( $type == 'text' ) {
562 return $this->user_text
;
563 } elseif ( $type == 'id' ) {
569 * Get handler-specific metadata
572 function getMetadata() {
574 return $this->metadata
;
580 function getBitDepth() {
586 * Return the size of the image file, in bytes
589 public function getSize() {
595 * Returns the mime type of the file.
598 function getMimeType() {
604 * Return the type of the media in the file.
605 * Use the value returned by this function with the MEDIATYPE_xxx constants.
608 function getMediaType() {
610 return $this->media_type
;
613 /** canRender inherited */
614 /** mustRender inherited */
615 /** allowInlineDisplay inherited */
616 /** isSafeFile inherited */
617 /** isTrustedFile inherited */
620 * Returns true if the file exists on disk.
621 * @return boolean Whether file exist on disk.
623 public function exists() {
625 return $this->fileExists
;
628 /** getTransformScript inherited */
629 /** getUnscaledThumb inherited */
630 /** thumbName inherited */
631 /** createThumb inherited */
632 /** transform inherited */
635 * Fix thumbnail files from 1.4 or before, with extreme prejudice
636 * @todo : do we still care about this? Perhaps a maintenance script
637 * can be made instead. Enabling this code results in a serious
638 * RTT regression for wikis without 404 handling.
640 function migrateThumbFile( $thumbName ) {
641 $thumbDir = $this->getThumbPath();
643 /* Old code for bug 2532
644 $thumbPath = "$thumbDir/$thumbName";
645 if ( is_dir( $thumbPath ) ) {
646 // Directory where file should be
647 // This happened occasionally due to broken migration code in 1.5
648 // Rename to broken-*
649 for ( $i = 0; $i < 100 ; $i++ ) {
650 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
651 if ( !file_exists( $broken ) ) {
652 rename( $thumbPath, $broken );
656 // Doesn't exist anymore
662 if ( $this->repo->fileExists( $thumbDir ) ) {
663 // Delete file where directory should be
664 $this->repo->cleanupBatch( array( $thumbDir ) );
669 /** getHandler inherited */
670 /** iconThumb inherited */
671 /** getLastError inherited */
674 * Get all thumbnail names previously generated for this file
675 * @param $archiveName string|bool Name of an archive file, default false
676 * @return array first element is the base dir, then files in that base dir.
678 function getThumbnails( $archiveName = false ) {
679 if ( $archiveName ) {
680 $dir = $this->getArchiveThumbPath( $archiveName );
682 $dir = $this->getThumbPath();
685 $backend = $this->repo
->getBackend();
686 $files = array( $dir );
687 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
688 foreach ( $iterator as $file ) {
696 * Refresh metadata in memcached, but don't touch thumbnails or squid
698 function purgeMetadataCache() {
700 $this->saveToCache();
701 $this->purgeHistory();
705 * Purge the shared history (OldLocalFile) cache
707 function purgeHistory() {
710 $hashedName = md5( $this->getName() );
711 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
713 // Must purge thumbnails for old versions too! bug 30192
714 foreach( $this->getHistory() as $oldFile ) {
715 $oldFile->purgeThumbnails();
719 $wgMemc->delete( $oldKey );
724 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
726 function purgeCache( $options = array() ) {
727 // Refresh metadata cache
728 $this->purgeMetadataCache();
731 $this->purgeThumbnails( $options );
733 // Purge squid cache for this file
734 SquidUpdate
::purge( array( $this->getURL() ) );
738 * Delete cached transformed files for an archived version only.
739 * @param $archiveName string name of the archived file
741 function purgeOldThumbnails( $archiveName ) {
743 wfProfileIn( __METHOD__
);
745 // Get a list of old thumbnails and URLs
746 $files = $this->getThumbnails( $archiveName );
747 $dir = array_shift( $files );
748 $this->purgeThumbList( $dir, $files );
750 // Purge any custom thumbnail caches
751 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
756 foreach( $files as $file ) {
757 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
759 SquidUpdate
::purge( $urls );
762 wfProfileOut( __METHOD__
);
766 * Delete cached transformed files for the current version only.
768 function purgeThumbnails( $options = array() ) {
770 wfProfileIn( __METHOD__
);
773 $files = $this->getThumbnails();
775 // Give media handler a chance to filter the purge list
776 if ( !empty( $options['forThumbRefresh'] ) ) {
777 $handler = $this->getHandler();
779 $handler->filterThumbnailPurgeList( $files, $options );
783 $dir = array_shift( $files );
784 $this->purgeThumbList( $dir, $files );
786 // Purge any custom thumbnail caches
787 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
792 foreach( $files as $file ) {
793 $urls[] = $this->getThumbUrl( $file );
795 SquidUpdate
::purge( $urls );
798 wfProfileOut( __METHOD__
);
802 * Delete a list of thumbnails visible at urls
803 * @param $dir string base dir of the files.
804 * @param $files array of strings: relative filenames (to $dir)
806 protected function purgeThumbList( $dir, $files ) {
807 $fileListDebug = strtr(
808 var_export( $files, true ),
811 wfDebug( __METHOD__
. ": $fileListDebug\n" );
813 $purgeList = array();
814 foreach ( $files as $file ) {
815 # Check that the base file name is part of the thumb name
816 # This is a basic sanity check to avoid erasing unrelated directories
817 if ( strpos( $file, $this->getName() ) !== false ) {
818 $purgeList[] = "{$dir}/{$file}";
822 # Delete the thumbnails
823 $this->repo
->quickPurgeBatch( $purgeList );
824 # Clear out the thumbnail directory if empty
825 $this->repo
->quickCleanDir( $dir );
828 /** purgeDescription inherited */
829 /** purgeEverything inherited */
838 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
839 $dbr = $this->repo
->getSlaveDB();
840 $tables = array( 'oldimage' );
841 $fields = OldLocalFile
::selectFields();
842 $conds = $opts = $join_conds = array();
843 $eq = $inc ?
'=' : '';
844 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
847 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
851 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
855 $opts['LIMIT'] = $limit;
858 // Search backwards for time > x queries
859 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
860 $opts['ORDER BY'] = "oi_timestamp $order";
861 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
863 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
864 &$conds, &$opts, &$join_conds ) );
866 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
869 foreach ( $res as $row ) {
870 if ( $this->repo
->oldFileFromRowFactory
) {
871 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
873 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
877 if ( $order == 'ASC' ) {
878 $r = array_reverse( $r ); // make sure it ends up descending
885 * Return the history of this file, line by line.
886 * starts with current version, then old versions.
887 * uses $this->historyLine to check which line to return:
888 * 0 return line for current version
889 * 1 query for old versions, return first one
890 * 2, ... return next old version from above query
893 public function nextHistoryLine() {
894 # Polymorphic function name to distinguish foreign and local fetches
895 $fname = get_class( $this ) . '::' . __FUNCTION__
;
897 $dbr = $this->repo
->getSlaveDB();
899 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
900 $this->historyRes
= $dbr->select( 'image',
903 "'' AS oi_archive_name",
907 array( 'img_name' => $this->title
->getDBkey() ),
911 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
912 $this->historyRes
= null;
915 } elseif ( $this->historyLine
== 1 ) {
916 $this->historyRes
= $dbr->select( 'oldimage', '*',
917 array( 'oi_name' => $this->title
->getDBkey() ),
919 array( 'ORDER BY' => 'oi_timestamp DESC' )
922 $this->historyLine ++
;
924 return $dbr->fetchObject( $this->historyRes
);
928 * Reset the history pointer to the first element of the history
930 public function resetHistory() {
931 $this->historyLine
= 0;
933 if ( !is_null( $this->historyRes
) ) {
934 $this->historyRes
= null;
938 /** getHashPath inherited */
939 /** getRel inherited */
940 /** getUrlRel inherited */
941 /** getArchiveRel inherited */
942 /** getArchivePath inherited */
943 /** getThumbPath inherited */
944 /** getArchiveUrl inherited */
945 /** getThumbUrl inherited */
946 /** getArchiveVirtualUrl inherited */
947 /** getThumbVirtualUrl inherited */
948 /** isHashed inherited */
951 * Upload a file and record it in the DB
952 * @param $srcPath String: source storage path or virtual URL
953 * @param $comment String: upload description
954 * @param $pageText String: text to use for the new description page,
955 * if a new description page is created
956 * @param $flags Integer|bool: flags for publish()
957 * @param $props Array|bool: File properties, if known. This can be used to reduce the
958 * upload time when uploading virtual URLs for which the file info
960 * @param $timestamp String|bool: timestamp for img_timestamp, or false to use the current time
961 * @param $user User|null: User object or null to use $wgUser
963 * @return FileRepoStatus object. On success, the value member contains the
964 * archive name, or an empty string if it was a new file.
966 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
969 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
970 return $this->readOnlyFatalStatus();
973 // truncate nicely or the DB will do it for us
974 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
975 $comment = $wgContLang->truncate( $comment, 255 );
976 $this->lock(); // begin
977 $status = $this->publish( $srcPath, $flags );
979 if ( $status->successCount
> 0 ) {
980 # Essentially we are displacing any existing current file and saving
981 # a new current file at the old location. If just the first succeeded,
982 # we still need to displace the current DB entry and put in a new one.
983 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
984 $status->fatal( 'filenotfound', $srcPath );
988 $this->unlock(); // done
994 * Record a file upload in the upload log and the image table
996 * @param $desc string
997 * @param $license string
998 * @param $copyStatus string
999 * @param $source string
1000 * @param $watch bool
1001 * @param $timestamp string|bool
1004 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1005 $watch = false, $timestamp = false )
1007 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1009 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
1015 $wgUser->addWatch( $this->getTitle() );
1021 * Record a file upload in the upload log and the image table
1023 * @param $comment string
1024 * @param $pageText string
1025 * @param $props bool|array
1026 * @param $timestamp bool|string
1027 * @param $user null|User
1030 function recordUpload2(
1031 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1033 wfProfileIn( __METHOD__
);
1035 if ( is_null( $user ) ) {
1040 $dbw = $this->repo
->getMasterDB();
1041 $dbw->begin( __METHOD__
);
1044 wfProfileIn( __METHOD__
. '-getProps' );
1045 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1046 wfProfileOut( __METHOD__
. '-getProps' );
1049 if ( $timestamp === false ) {
1050 $timestamp = $dbw->timestamp();
1053 $props['description'] = $comment;
1054 $props['user'] = $user->getId();
1055 $props['user_text'] = $user->getName();
1056 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1057 $this->setProps( $props );
1059 # Fail now if the file isn't there
1060 if ( !$this->fileExists
) {
1061 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1062 wfProfileOut( __METHOD__
);
1068 # Test to see if the row exists using INSERT IGNORE
1069 # This avoids race conditions by locking the row until the commit, and also
1070 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1071 $dbw->insert( 'image',
1073 'img_name' => $this->getName(),
1074 'img_size' => $this->size
,
1075 'img_width' => intval( $this->width
),
1076 'img_height' => intval( $this->height
),
1077 'img_bits' => $this->bits
,
1078 'img_media_type' => $this->media_type
,
1079 'img_major_mime' => $this->major_mime
,
1080 'img_minor_mime' => $this->minor_mime
,
1081 'img_timestamp' => $timestamp,
1082 'img_description' => $comment,
1083 'img_user' => $user->getId(),
1084 'img_user_text' => $user->getName(),
1085 'img_metadata' => $this->metadata
,
1086 'img_sha1' => $this->sha1
1091 if ( $dbw->affectedRows() == 0 ) {
1092 # (bug 34993) Note: $oldver can be empty here, if the previous
1093 # version of the file was broken. Allow registration of the new
1094 # version to continue anyway, because that's better than having
1095 # an image that's not fixable by user operations.
1098 # Collision, this is an update of a file
1099 # Insert previous contents into oldimage
1100 $dbw->insertSelect( 'oldimage', 'image',
1102 'oi_name' => 'img_name',
1103 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1104 'oi_size' => 'img_size',
1105 'oi_width' => 'img_width',
1106 'oi_height' => 'img_height',
1107 'oi_bits' => 'img_bits',
1108 'oi_timestamp' => 'img_timestamp',
1109 'oi_description' => 'img_description',
1110 'oi_user' => 'img_user',
1111 'oi_user_text' => 'img_user_text',
1112 'oi_metadata' => 'img_metadata',
1113 'oi_media_type' => 'img_media_type',
1114 'oi_major_mime' => 'img_major_mime',
1115 'oi_minor_mime' => 'img_minor_mime',
1116 'oi_sha1' => 'img_sha1'
1118 array( 'img_name' => $this->getName() ),
1122 # Update the current image row
1123 $dbw->update( 'image',
1125 'img_size' => $this->size
,
1126 'img_width' => intval( $this->width
),
1127 'img_height' => intval( $this->height
),
1128 'img_bits' => $this->bits
,
1129 'img_media_type' => $this->media_type
,
1130 'img_major_mime' => $this->major_mime
,
1131 'img_minor_mime' => $this->minor_mime
,
1132 'img_timestamp' => $timestamp,
1133 'img_description' => $comment,
1134 'img_user' => $user->getId(),
1135 'img_user_text' => $user->getName(),
1136 'img_metadata' => $this->metadata
,
1137 'img_sha1' => $this->sha1
1139 array( 'img_name' => $this->getName() ),
1143 # This is a new file, so update the image count
1144 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1147 $descTitle = $this->getTitle();
1148 $wikiPage = new WikiFilePage( $descTitle );
1149 $wikiPage->setFile( $this );
1152 $log = new LogPage( 'upload' );
1153 $action = $reupload ?
'overwrite' : 'upload';
1154 $logId = $log->addEntry( $action, $descTitle, $comment, array(), $user );
1156 wfProfileIn( __METHOD__
. '-edit' );
1157 $exists = $descTitle->exists();
1160 # Create a null revision
1161 $latest = $descTitle->getLatestRevID();
1162 $nullRevision = Revision
::newNullRevision(
1164 $descTitle->getArticleID(),
1165 $log->getRcComment(),
1168 if (!is_null($nullRevision)) {
1169 $nullRevision->insertOn( $dbw );
1171 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1172 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1176 # Commit the transaction now, in case something goes wrong later
1177 # The most important thing is that files don't get lost, especially archives
1178 # NOTE: once we have support for nested transactions, the commit may be moved
1179 # to after $wikiPage->doEdit has been called.
1180 $dbw->commit( __METHOD__
);
1183 # Invalidate the cache for the description page
1184 $descTitle->invalidateCache();
1185 $descTitle->purgeSquid();
1187 # New file; create the description page.
1188 # There's already a log entry, so don't make a second RC entry
1189 # Squid and file cache for the description page are purged by doEdit.
1190 $status = $wikiPage->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
, false, $user );
1192 if ( isset( $status->value
['revision'] ) ) { // XXX; doEdit() uses a transaction
1194 $dbw->update( 'logging',
1195 array( 'log_page' => $status->value
['revision']->getPage() ),
1196 array( 'log_id' => $logId ),
1199 $dbw->commit(); // commit before anything bad can happen
1202 wfProfileOut( __METHOD__
. '-edit' );
1204 # Save to cache and purge the squid
1205 # We shall not saveToCache before the commit since otherwise
1206 # in case of a rollback there is an usable file from memcached
1207 # which in fact doesn't really exist (bug 24978)
1208 $this->saveToCache();
1211 # Delete old thumbnails
1212 wfProfileIn( __METHOD__
. '-purge' );
1213 $this->purgeThumbnails();
1214 wfProfileOut( __METHOD__
. '-purge' );
1216 # Remove the old file from the squid cache
1217 SquidUpdate
::purge( array( $this->getURL() ) );
1220 # Hooks, hooks, the magic of hooks...
1221 wfProfileIn( __METHOD__
. '-hooks' );
1222 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1223 wfProfileOut( __METHOD__
. '-hooks' );
1225 # Invalidate cache for all pages using this file
1226 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1227 $update->doUpdate();
1229 # Invalidate cache for all pages that redirects on this page
1230 $redirs = $this->getTitle()->getRedirectsHere();
1232 foreach ( $redirs as $redir ) {
1233 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1234 $update->doUpdate();
1237 wfProfileOut( __METHOD__
);
1242 * Move or copy a file to its public location. If a file exists at the
1243 * destination, move it to an archive. Returns a FileRepoStatus object with
1244 * the archive name in the "value" member on success.
1246 * The archive name should be passed through to recordUpload for database
1249 * @param $srcPath String: local filesystem path to the source image
1250 * @param $flags Integer: a bitwise combination of:
1251 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1252 * @return FileRepoStatus object. On success, the value member contains the
1253 * archive name, or an empty string if it was a new file.
1255 function publish( $srcPath, $flags = 0 ) {
1256 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1260 * Move or copy a file to a specified location. Returns a FileRepoStatus
1261 * object with the archive name in the "value" member on success.
1263 * The archive name should be passed through to recordUpload for database
1266 * @param $srcPath String: local filesystem path to the source image
1267 * @param $dstRel String: target relative path
1268 * @param $flags Integer: a bitwise combination of:
1269 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1270 * @return FileRepoStatus object. On success, the value member contains the
1271 * archive name, or an empty string if it was a new file.
1273 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1274 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1275 return $this->readOnlyFatalStatus();
1278 $this->lock(); // begin
1280 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1281 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1282 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1283 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1285 if ( $status->value
== 'new' ) {
1286 $status->value
= '';
1288 $status->value
= $archiveName;
1291 $this->unlock(); // done
1296 /** getLinksTo inherited */
1297 /** getExifData inherited */
1298 /** isLocal inherited */
1299 /** wasDeleted inherited */
1302 * Move file to the new title
1304 * Move current, old version and all thumbnails
1305 * to the new filename. Old file is deleted.
1307 * Cache purging is done; checks for validity
1308 * and logging are caller's responsibility
1310 * @param $target Title New file name
1311 * @return FileRepoStatus object.
1313 function move( $target ) {
1314 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1315 return $this->readOnlyFatalStatus();
1318 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1319 $batch = new LocalFileMoveBatch( $this, $target );
1321 $this->lock(); // begin
1322 $batch->addCurrent();
1323 $archiveNames = $batch->addOlds();
1324 $status = $batch->execute();
1325 $this->unlock(); // done
1327 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1329 $this->purgeEverything();
1330 foreach ( $archiveNames as $archiveName ) {
1331 $this->purgeOldThumbnails( $archiveName );
1333 if ( $status->isOK() ) {
1334 // Now switch the object
1335 $this->title
= $target;
1336 // Force regeneration of the name and hashpath
1337 unset( $this->name
);
1338 unset( $this->hashPath
);
1339 // Purge the new image
1340 $this->purgeEverything();
1347 * Delete all versions of the file.
1349 * Moves the files into an archive directory (or deletes them)
1350 * and removes the database rows.
1352 * Cache purging is done; logging is caller's responsibility.
1356 * @return FileRepoStatus object.
1358 function delete( $reason, $suppress = false ) {
1359 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1360 return $this->readOnlyFatalStatus();
1363 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1365 $this->lock(); // begin
1366 $batch->addCurrent();
1367 # Get old version relative paths
1368 $archiveNames = $batch->addOlds();
1369 $status = $batch->execute();
1370 $this->unlock(); // done
1372 if ( $status->isOK() ) {
1373 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1376 $this->purgeEverything();
1377 foreach ( $archiveNames as $archiveName ) {
1378 $this->purgeOldThumbnails( $archiveName );
1385 * Delete an old version of the file.
1387 * Moves the file into an archive directory (or deletes it)
1388 * and removes the database row.
1390 * Cache purging is done; logging is caller's responsibility.
1392 * @param $archiveName String
1393 * @param $reason String
1394 * @param $suppress Boolean
1395 * @throws MWException or FSException on database or file store failure
1396 * @return FileRepoStatus object.
1398 function deleteOld( $archiveName, $reason, $suppress = false ) {
1399 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1400 return $this->readOnlyFatalStatus();
1403 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1405 $this->lock(); // begin
1406 $batch->addOld( $archiveName );
1407 $status = $batch->execute();
1408 $this->unlock(); // done
1410 $this->purgeOldThumbnails( $archiveName );
1411 if ( $status->isOK() ) {
1412 $this->purgeDescription();
1413 $this->purgeHistory();
1420 * Restore all or specified deleted revisions to the given file.
1421 * Permissions and logging are left to the caller.
1423 * May throw database exceptions on error.
1425 * @param $versions array set of record ids of deleted items to restore,
1426 * or empty to restore all revisions.
1427 * @param $unsuppress Boolean
1428 * @return FileRepoStatus
1430 function restore( $versions = array(), $unsuppress = false ) {
1431 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1432 return $this->readOnlyFatalStatus();
1435 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1437 $this->lock(); // begin
1441 $batch->addIds( $versions );
1443 $status = $batch->execute();
1444 if ( $status->isGood() ) {
1445 $cleanupStatus = $batch->cleanup();
1446 $cleanupStatus->successCount
= 0;
1447 $cleanupStatus->failCount
= 0;
1448 $status->merge( $cleanupStatus );
1450 $this->unlock(); // done
1455 /** isMultipage inherited */
1456 /** pageCount inherited */
1457 /** scaleHeight inherited */
1458 /** getImageSize inherited */
1461 * Get the URL of the file description page.
1464 function getDescriptionUrl() {
1465 return $this->title
->getLocalUrl();
1469 * Get the HTML text of the description page
1470 * This is not used by ImagePage for local files, since (among other things)
1471 * it skips the parser cache.
1472 * @return bool|mixed
1474 function getDescriptionText() {
1476 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1477 if ( !$revision ) return false;
1478 $text = $revision->getText();
1479 if ( !$text ) return false;
1480 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1481 return $pout->getText();
1487 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1489 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1491 } elseif ( $audience == self
::FOR_THIS_USER
1492 && !$this->userCan( self
::DELETED_COMMENT
, $user ) )
1496 return $this->description
;
1501 * @return bool|string
1503 function getTimestamp() {
1505 return $this->timestamp
;
1511 function getSha1() {
1513 // Initialise now if necessary
1514 if ( $this->sha1
== '' && $this->fileExists
) {
1515 $this->lock(); // begin
1517 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1518 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1519 $dbw = $this->repo
->getMasterDB();
1520 $dbw->update( 'image',
1521 array( 'img_sha1' => $this->sha1
),
1522 array( 'img_name' => $this->getName() ),
1524 $this->saveToCache();
1527 $this->unlock(); // done
1536 function isCacheable() {
1538 return strlen( $this->metadata
) <= self
::CACHE_FIELD_MAX_LEN
; // avoid OOMs
1542 * Start a transaction and lock the image for update
1543 * Increments a reference counter if the lock is already held
1544 * @return boolean True if the image exists, false otherwise
1547 $dbw = $this->repo
->getMasterDB();
1549 if ( !$this->locked
) {
1550 $dbw->begin( __METHOD__
);
1554 return $dbw->selectField( 'image', '1',
1555 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1559 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1560 * the transaction and thereby releases the image lock.
1563 if ( $this->locked
) {
1565 if ( !$this->locked
) {
1566 $dbw = $this->repo
->getMasterDB();
1567 $dbw->commit( __METHOD__
);
1573 * Roll back the DB transaction and mark the image unlocked
1575 function unlockAndRollback() {
1576 $this->locked
= false;
1577 $dbw = $this->repo
->getMasterDB();
1578 $dbw->rollback( __METHOD__
);
1584 protected function readOnlyFatalStatus() {
1585 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1586 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1588 } // LocalFile class
1590 # ------------------------------------------------------------------------------
1593 * Helper class for file deletion
1594 * @ingroup FileAbstraction
1596 class LocalFileDeleteBatch
{
1603 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1608 * @param $reason string
1609 * @param $suppress bool
1611 function __construct( File
$file, $reason = '', $suppress = false ) {
1612 $this->file
= $file;
1613 $this->reason
= $reason;
1614 $this->suppress
= $suppress;
1615 $this->status
= $file->repo
->newGood();
1618 function addCurrent() {
1619 $this->srcRels
['.'] = $this->file
->getRel();
1623 * @param $oldName string
1625 function addOld( $oldName ) {
1626 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1627 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1631 * Add the old versions of the image to the batch
1632 * @return Array List of archive names from old versions
1634 function addOlds() {
1635 $archiveNames = array();
1637 $dbw = $this->file
->repo
->getMasterDB();
1638 $result = $dbw->select( 'oldimage',
1639 array( 'oi_archive_name' ),
1640 array( 'oi_name' => $this->file
->getName() ),
1644 foreach ( $result as $row ) {
1645 $this->addOld( $row->oi_archive_name
);
1646 $archiveNames[] = $row->oi_archive_name
;
1649 return $archiveNames;
1655 function getOldRels() {
1656 if ( !isset( $this->srcRels
['.'] ) ) {
1657 $oldRels =& $this->srcRels
;
1658 $deleteCurrent = false;
1660 $oldRels = $this->srcRels
;
1661 unset( $oldRels['.'] );
1662 $deleteCurrent = true;
1665 return array( $oldRels, $deleteCurrent );
1671 protected function getHashes() {
1673 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1675 if ( $deleteCurrent ) {
1676 $hashes['.'] = $this->file
->getSha1();
1679 if ( count( $oldRels ) ) {
1680 $dbw = $this->file
->repo
->getMasterDB();
1681 $res = $dbw->select(
1683 array( 'oi_archive_name', 'oi_sha1' ),
1684 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1688 foreach ( $res as $row ) {
1689 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1690 // Get the hash from the file
1691 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1692 $props = $this->file
->repo
->getFileProps( $oldUrl );
1694 if ( $props['fileExists'] ) {
1695 // Upgrade the oldimage row
1696 $dbw->update( 'oldimage',
1697 array( 'oi_sha1' => $props['sha1'] ),
1698 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1700 $hashes[$row->oi_archive_name
] = $props['sha1'];
1702 $hashes[$row->oi_archive_name
] = false;
1705 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1710 $missing = array_diff_key( $this->srcRels
, $hashes );
1712 foreach ( $missing as $name => $rel ) {
1713 $this->status
->error( 'filedelete-old-unregistered', $name );
1716 foreach ( $hashes as $name => $hash ) {
1718 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1719 unset( $hashes[$name] );
1726 function doDBInserts() {
1729 $dbw = $this->file
->repo
->getMasterDB();
1730 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1731 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1732 $encReason = $dbw->addQuotes( $this->reason
);
1733 $encGroup = $dbw->addQuotes( 'deleted' );
1734 $ext = $this->file
->getExtension();
1735 $dotExt = $ext === '' ?
'' : ".$ext";
1736 $encExt = $dbw->addQuotes( $dotExt );
1737 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1739 // Bitfields to further suppress the content
1740 if ( $this->suppress
) {
1742 // This should be 15...
1743 $bitfield |
= Revision
::DELETED_TEXT
;
1744 $bitfield |
= Revision
::DELETED_COMMENT
;
1745 $bitfield |
= Revision
::DELETED_USER
;
1746 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1748 $bitfield = 'oi_deleted';
1751 if ( $deleteCurrent ) {
1752 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1753 $where = array( 'img_name' => $this->file
->getName() );
1754 $dbw->insertSelect( 'filearchive', 'image',
1756 'fa_storage_group' => $encGroup,
1757 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1758 'fa_deleted_user' => $encUserId,
1759 'fa_deleted_timestamp' => $encTimestamp,
1760 'fa_deleted_reason' => $encReason,
1761 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1763 'fa_name' => 'img_name',
1764 'fa_archive_name' => 'NULL',
1765 'fa_size' => 'img_size',
1766 'fa_width' => 'img_width',
1767 'fa_height' => 'img_height',
1768 'fa_metadata' => 'img_metadata',
1769 'fa_bits' => 'img_bits',
1770 'fa_media_type' => 'img_media_type',
1771 'fa_major_mime' => 'img_major_mime',
1772 'fa_minor_mime' => 'img_minor_mime',
1773 'fa_description' => 'img_description',
1774 'fa_user' => 'img_user',
1775 'fa_user_text' => 'img_user_text',
1776 'fa_timestamp' => 'img_timestamp'
1777 ), $where, __METHOD__
);
1780 if ( count( $oldRels ) ) {
1781 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1783 'oi_name' => $this->file
->getName(),
1784 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1785 $dbw->insertSelect( 'filearchive', 'oldimage',
1787 'fa_storage_group' => $encGroup,
1788 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1789 'fa_deleted_user' => $encUserId,
1790 'fa_deleted_timestamp' => $encTimestamp,
1791 'fa_deleted_reason' => $encReason,
1792 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1794 'fa_name' => 'oi_name',
1795 'fa_archive_name' => 'oi_archive_name',
1796 'fa_size' => 'oi_size',
1797 'fa_width' => 'oi_width',
1798 'fa_height' => 'oi_height',
1799 'fa_metadata' => 'oi_metadata',
1800 'fa_bits' => 'oi_bits',
1801 'fa_media_type' => 'oi_media_type',
1802 'fa_major_mime' => 'oi_major_mime',
1803 'fa_minor_mime' => 'oi_minor_mime',
1804 'fa_description' => 'oi_description',
1805 'fa_user' => 'oi_user',
1806 'fa_user_text' => 'oi_user_text',
1807 'fa_timestamp' => 'oi_timestamp',
1808 ), $where, __METHOD__
);
1812 function doDBDeletes() {
1813 $dbw = $this->file
->repo
->getMasterDB();
1814 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1816 if ( count( $oldRels ) ) {
1817 $dbw->delete( 'oldimage',
1819 'oi_name' => $this->file
->getName(),
1820 'oi_archive_name' => array_keys( $oldRels )
1824 if ( $deleteCurrent ) {
1825 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1830 * Run the transaction
1831 * @return FileRepoStatus
1833 function execute() {
1834 wfProfileIn( __METHOD__
);
1836 $this->file
->lock();
1837 // Leave private files alone
1838 $privateFiles = array();
1839 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1840 $dbw = $this->file
->repo
->getMasterDB();
1842 if ( !empty( $oldRels ) ) {
1843 $res = $dbw->select( 'oldimage',
1844 array( 'oi_archive_name' ),
1845 array( 'oi_name' => $this->file
->getName(),
1846 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1847 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1850 foreach ( $res as $row ) {
1851 $privateFiles[$row->oi_archive_name
] = 1;
1854 // Prepare deletion batch
1855 $hashes = $this->getHashes();
1856 $this->deletionBatch
= array();
1857 $ext = $this->file
->getExtension();
1858 $dotExt = $ext === '' ?
'' : ".$ext";
1860 foreach ( $this->srcRels
as $name => $srcRel ) {
1861 // Skip files that have no hash (missing source).
1862 // Keep private files where they are.
1863 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1864 $hash = $hashes[$name];
1865 $key = $hash . $dotExt;
1866 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1867 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1871 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1872 // We acquire this lock by running the inserts now, before the file operations.
1874 // This potentially has poor lock contention characteristics -- an alternative
1875 // scheme would be to insert stub filearchive entries with no fa_name and commit
1876 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1877 $this->doDBInserts();
1879 // Removes non-existent file from the batch, so we don't get errors.
1880 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1882 // Execute the file deletion batch
1883 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1885 if ( !$status->isGood() ) {
1886 $this->status
->merge( $status );
1889 if ( !$this->status
->isOK() ) {
1890 // Critical file deletion error
1891 // Roll back inserts, release lock and abort
1892 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1893 $this->file
->unlockAndRollback();
1894 wfProfileOut( __METHOD__
);
1895 return $this->status
;
1898 // Delete image/oldimage rows
1899 $this->doDBDeletes();
1901 // Commit and return
1902 $this->file
->unlock();
1903 wfProfileOut( __METHOD__
);
1905 return $this->status
;
1909 * Removes non-existent files from a deletion batch.
1910 * @param $batch array
1913 function removeNonexistentFiles( $batch ) {
1914 $files = $newBatch = array();
1916 foreach ( $batch as $batchItem ) {
1917 list( $src, $dest ) = $batchItem;
1918 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1921 $result = $this->file
->repo
->fileExistsBatch( $files );
1923 foreach ( $batch as $batchItem ) {
1924 if ( $result[$batchItem[0]] ) {
1925 $newBatch[] = $batchItem;
1933 # ------------------------------------------------------------------------------
1936 * Helper class for file undeletion
1937 * @ingroup FileAbstraction
1939 class LocalFileRestoreBatch
{
1945 var $cleanupBatch, $ids, $all, $unsuppress = false;
1949 * @param $unsuppress bool
1951 function __construct( File
$file, $unsuppress = false ) {
1952 $this->file
= $file;
1953 $this->cleanupBatch
= $this->ids
= array();
1954 $this->ids
= array();
1955 $this->unsuppress
= $unsuppress;
1961 function addId( $fa_id ) {
1962 $this->ids
[] = $fa_id;
1966 * Add a whole lot of files by ID
1968 function addIds( $ids ) {
1969 $this->ids
= array_merge( $this->ids
, $ids );
1973 * Add all revisions of the file
1980 * Run the transaction, except the cleanup batch.
1981 * The cleanup batch should be run in a separate transaction, because it locks different
1982 * rows and there's no need to keep the image row locked while it's acquiring those locks
1983 * The caller may have its own transaction open.
1984 * So we save the batch and let the caller call cleanup()
1985 * @return FileRepoStatus
1987 function execute() {
1990 if ( !$this->all
&& !$this->ids
) {
1992 return $this->file
->repo
->newGood();
1995 $exists = $this->file
->lock();
1996 $dbw = $this->file
->repo
->getMasterDB();
1997 $status = $this->file
->repo
->newGood();
1999 // Fetch all or selected archived revisions for the file,
2000 // sorted from the most recent to the oldest.
2001 $conditions = array( 'fa_name' => $this->file
->getName() );
2003 if ( !$this->all
) {
2004 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
2007 $result = $dbw->select( 'filearchive', '*',
2010 array( 'ORDER BY' => 'fa_timestamp DESC' )
2013 $idsPresent = array();
2014 $storeBatch = array();
2015 $insertBatch = array();
2016 $insertCurrent = false;
2017 $deleteIds = array();
2019 $archiveNames = array();
2021 foreach ( $result as $row ) {
2022 $idsPresent[] = $row->fa_id
;
2024 if ( $row->fa_name
!= $this->file
->getName() ) {
2025 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2026 $status->failCount++
;
2030 if ( $row->fa_storage_key
== '' ) {
2031 // Revision was missing pre-deletion
2032 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2033 $status->failCount++
;
2037 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
2038 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2040 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
2043 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2044 $sha1 = substr( $sha1, 1 );
2047 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2048 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2049 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2050 ||
is_null( $row->fa_metadata
) ) {
2051 // Refresh our metadata
2052 // Required for a new current revision; nice for older ones too. :)
2053 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2056 'minor_mime' => $row->fa_minor_mime
,
2057 'major_mime' => $row->fa_major_mime
,
2058 'media_type' => $row->fa_media_type
,
2059 'metadata' => $row->fa_metadata
2063 if ( $first && !$exists ) {
2064 // This revision will be published as the new current version
2065 $destRel = $this->file
->getRel();
2066 $insertCurrent = array(
2067 'img_name' => $row->fa_name
,
2068 'img_size' => $row->fa_size
,
2069 'img_width' => $row->fa_width
,
2070 'img_height' => $row->fa_height
,
2071 'img_metadata' => $props['metadata'],
2072 'img_bits' => $row->fa_bits
,
2073 'img_media_type' => $props['media_type'],
2074 'img_major_mime' => $props['major_mime'],
2075 'img_minor_mime' => $props['minor_mime'],
2076 'img_description' => $row->fa_description
,
2077 'img_user' => $row->fa_user
,
2078 'img_user_text' => $row->fa_user_text
,
2079 'img_timestamp' => $row->fa_timestamp
,
2083 // The live (current) version cannot be hidden!
2084 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2085 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2086 $this->cleanupBatch
[] = $row->fa_storage_key
;
2089 $archiveName = $row->fa_archive_name
;
2091 if ( $archiveName == '' ) {
2092 // This was originally a current version; we
2093 // have to devise a new archive name for it.
2094 // Format is <timestamp of archiving>!<name>
2095 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2098 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2100 } while ( isset( $archiveNames[$archiveName] ) );
2103 $archiveNames[$archiveName] = true;
2104 $destRel = $this->file
->getArchiveRel( $archiveName );
2105 $insertBatch[] = array(
2106 'oi_name' => $row->fa_name
,
2107 'oi_archive_name' => $archiveName,
2108 'oi_size' => $row->fa_size
,
2109 'oi_width' => $row->fa_width
,
2110 'oi_height' => $row->fa_height
,
2111 'oi_bits' => $row->fa_bits
,
2112 'oi_description' => $row->fa_description
,
2113 'oi_user' => $row->fa_user
,
2114 'oi_user_text' => $row->fa_user_text
,
2115 'oi_timestamp' => $row->fa_timestamp
,
2116 'oi_metadata' => $props['metadata'],
2117 'oi_media_type' => $props['media_type'],
2118 'oi_major_mime' => $props['major_mime'],
2119 'oi_minor_mime' => $props['minor_mime'],
2120 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2121 'oi_sha1' => $sha1 );
2124 $deleteIds[] = $row->fa_id
;
2126 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2127 // private files can stay where they are
2128 $status->successCount++
;
2130 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2131 $this->cleanupBatch
[] = $row->fa_storage_key
;
2139 // Add a warning to the status object for missing IDs
2140 $missingIds = array_diff( $this->ids
, $idsPresent );
2142 foreach ( $missingIds as $id ) {
2143 $status->error( 'undelete-missing-filearchive', $id );
2146 // Remove missing files from batch, so we don't get errors when undeleting them
2147 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2149 // Run the store batch
2150 // Use the OVERWRITE_SAME flag to smooth over a common error
2151 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2152 $status->merge( $storeStatus );
2154 if ( !$status->isGood() ) {
2155 // Even if some files could be copied, fail entirely as that is the
2156 // easiest thing to do without data loss
2157 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2158 $status->ok
= false;
2159 $this->file
->unlock();
2164 // Run the DB updates
2165 // Because we have locked the image row, key conflicts should be rare.
2166 // If they do occur, we can roll back the transaction at this time with
2167 // no data loss, but leaving unregistered files scattered throughout the
2169 // This is not ideal, which is why it's important to lock the image row.
2170 if ( $insertCurrent ) {
2171 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2174 if ( $insertBatch ) {
2175 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2179 $dbw->delete( 'filearchive',
2180 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2184 // If store batch is empty (all files are missing), deletion is to be considered successful
2185 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2187 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2189 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2191 $this->file
->purgeEverything();
2193 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2194 $this->file
->purgeDescription();
2195 $this->file
->purgeHistory();
2199 $this->file
->unlock();
2205 * Removes non-existent files from a store batch.
2206 * @param $triplets array
2209 function removeNonexistentFiles( $triplets ) {
2210 $files = $filteredTriplets = array();
2211 foreach ( $triplets as $file ) {
2212 $files[$file[0]] = $file[0];
2215 $result = $this->file
->repo
->fileExistsBatch( $files );
2217 foreach ( $triplets as $file ) {
2218 if ( $result[$file[0]] ) {
2219 $filteredTriplets[] = $file;
2223 return $filteredTriplets;
2227 * Removes non-existent files from a cleanup batch.
2228 * @param $batch array
2231 function removeNonexistentFromCleanup( $batch ) {
2232 $files = $newBatch = array();
2233 $repo = $this->file
->repo
;
2235 foreach ( $batch as $file ) {
2236 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2237 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2240 $result = $repo->fileExistsBatch( $files );
2242 foreach ( $batch as $file ) {
2243 if ( $result[$file] ) {
2244 $newBatch[] = $file;
2252 * Delete unused files in the deleted zone.
2253 * This should be called from outside the transaction in which execute() was called.
2254 * @return FileRepoStatus|void
2256 function cleanup() {
2257 if ( !$this->cleanupBatch
) {
2258 return $this->file
->repo
->newGood();
2261 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2263 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2269 * Cleanup a failed batch. The batch was only partially successful, so
2270 * rollback by removing all items that were succesfully copied.
2272 * @param Status $storeStatus
2273 * @param array $storeBatch
2275 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2276 $cleanupBatch = array();
2278 foreach ( $storeStatus->success
as $i => $success ) {
2279 // Check if this item of the batch was successfully copied
2281 // Item was successfully copied and needs to be removed again
2282 // Extract ($dstZone, $dstRel) from the batch
2283 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2286 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2290 # ------------------------------------------------------------------------------
2293 * Helper class for file movement
2294 * @ingroup FileAbstraction
2296 class LocalFileMoveBatch
{
2308 var $cur, $olds, $oldCount, $archive;
2317 * @param Title $target
2319 function __construct( File
$file, Title
$target ) {
2320 $this->file
= $file;
2321 $this->target
= $target;
2322 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2323 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2324 $this->oldName
= $this->file
->getName();
2325 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2326 $this->oldRel
= $this->oldHash
. $this->oldName
;
2327 $this->newRel
= $this->newHash
. $this->newName
;
2328 $this->db
= $file->getRepo()->getMasterDb();
2332 * Add the current image to the batch
2334 function addCurrent() {
2335 $this->cur
= array( $this->oldRel
, $this->newRel
);
2339 * Add the old versions of the image to the batch
2340 * @return Array List of archive names from old versions
2342 function addOlds() {
2343 $archiveBase = 'archive';
2344 $this->olds
= array();
2345 $this->oldCount
= 0;
2346 $archiveNames = array();
2348 $result = $this->db
->select( 'oldimage',
2349 array( 'oi_archive_name', 'oi_deleted' ),
2350 array( 'oi_name' => $this->oldName
),
2354 foreach ( $result as $row ) {
2355 $archiveNames[] = $row->oi_archive_name
;
2356 $oldName = $row->oi_archive_name
;
2357 $bits = explode( '!', $oldName, 2 );
2359 if ( count( $bits ) != 2 ) {
2360 wfDebug( "Old file name missing !: '$oldName' \n" );
2364 list( $timestamp, $filename ) = $bits;
2366 if ( $this->oldName
!= $filename ) {
2367 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2373 // Do we want to add those to oldCount?
2374 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2378 $this->olds
[] = array(
2379 "{$archiveBase}/{$this->oldHash}{$oldName}",
2380 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2384 return $archiveNames;
2389 * @return FileRepoStatus
2391 function execute() {
2392 $repo = $this->file
->repo
;
2393 $status = $repo->newGood();
2395 $triplets = $this->getMoveTriplets();
2396 $triplets = $this->removeNonexistentFiles( $triplets );
2398 $this->file
->lock(); // begin
2399 // Rename the file versions metadata in the DB.
2400 // This implicitly locks the destination file, which avoids race conditions.
2401 // If we moved the files from A -> C before DB updates, another process could
2402 // move files from B -> C at this point, causing storeBatch() to fail and thus
2403 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2404 $statusDb = $this->doDBUpdates();
2405 if ( !$statusDb->isGood() ) {
2406 $this->file
->unlockAndRollback();
2407 $statusDb->ok
= false;
2410 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2412 // Copy the files into their new location.
2413 // If a prior process fataled copying or cleaning up files we tolerate any
2414 // of the existing files if they are identical to the ones being stored.
2415 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2416 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2417 if ( !$statusMove->isGood() ) {
2418 // Delete any files copied over (while the destination is still locked)
2419 $this->cleanupTarget( $triplets );
2420 $this->file
->unlockAndRollback(); // unlocks the destination
2421 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2422 $statusMove->ok
= false;
2425 $this->file
->unlock(); // done
2427 // Everything went ok, remove the source files
2428 $this->cleanupSource( $triplets );
2430 $status->merge( $statusDb );
2431 $status->merge( $statusMove );
2437 * Do the database updates and return a new FileRepoStatus indicating how
2438 * many rows where updated.
2440 * @return FileRepoStatus
2442 function doDBUpdates() {
2443 $repo = $this->file
->repo
;
2444 $status = $repo->newGood();
2447 // Update current image
2450 array( 'img_name' => $this->newName
),
2451 array( 'img_name' => $this->oldName
),
2455 if ( $dbw->affectedRows() ) {
2456 $status->successCount++
;
2458 $status->failCount++
;
2459 $status->fatal( 'imageinvalidfilename' );
2463 // Update old images
2467 'oi_name' => $this->newName
,
2468 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2469 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2471 array( 'oi_name' => $this->oldName
),
2475 $affected = $dbw->affectedRows();
2476 $total = $this->oldCount
;
2477 $status->successCount +
= $affected;
2478 // Bug 34934: $total is based on files that actually exist.
2479 // There may be more DB rows than such files, in which case $affected
2480 // can be greater than $total. We use max() to avoid negatives here.
2481 $status->failCount +
= max( 0, $total - $affected );
2482 if ( $status->failCount
) {
2483 $status->error( 'imageinvalidfilename' );
2490 * Generate triplets for FileRepo::storeBatch().
2493 function getMoveTriplets() {
2494 $moves = array_merge( array( $this->cur
), $this->olds
);
2495 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2497 foreach ( $moves as $move ) {
2498 // $move: (oldRelativePath, newRelativePath)
2499 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2500 $triplets[] = array( $srcUrl, 'public', $move[1] );
2501 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2508 * Removes non-existent files from move batch.
2509 * @param $triplets array
2512 function removeNonexistentFiles( $triplets ) {
2515 foreach ( $triplets as $file ) {
2516 $files[$file[0]] = $file[0];
2519 $result = $this->file
->repo
->fileExistsBatch( $files );
2520 $filteredTriplets = array();
2522 foreach ( $triplets as $file ) {
2523 if ( $result[$file[0]] ) {
2524 $filteredTriplets[] = $file;
2526 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2530 return $filteredTriplets;
2534 * Cleanup a partially moved array of triplets by deleting the target
2535 * files. Called if something went wrong half way.
2537 function cleanupTarget( $triplets ) {
2538 // Create dest pairs from the triplets
2540 foreach ( $triplets as $triplet ) {
2541 // $triplet: (old source virtual URL, dst zone, dest rel)
2542 $pairs[] = array( $triplet[1], $triplet[2] );
2545 $this->file
->repo
->cleanupBatch( $pairs );
2549 * Cleanup a fully moved array of triplets by deleting the source files.
2550 * Called at the end of the move process if everything else went ok.
2552 function cleanupSource( $triplets ) {
2553 // Create source file names from the triplets
2555 foreach ( $triplets as $triplet ) {
2556 $files[] = $triplet[0];
2559 $this->file
->repo
->cleanupBatch( $files );