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 );
266 function getCacheFields( $prefix = 'img_' ) {
267 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
268 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
269 static $results = array();
271 if ( $prefix == '' ) {
275 if ( !isset( $results[$prefix] ) ) {
276 $prefixedFields = array();
277 foreach ( $fields as $field ) {
278 $prefixedFields[] = $prefix . $field;
280 $results[$prefix] = $prefixedFields;
283 return $results[$prefix];
287 * Load file metadata from the DB
289 function loadFromDB() {
290 # Polymorphic function name to distinguish foreign and local fetches
291 $fname = get_class( $this ) . '::' . __FUNCTION__
;
292 wfProfileIn( $fname );
294 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
295 $this->dataLoaded
= true;
297 $dbr = $this->repo
->getMasterDB();
299 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
300 array( 'img_name' => $this->getName() ), $fname );
303 $this->loadFromRow( $row );
305 $this->fileExists
= false;
308 wfProfileOut( $fname );
312 * Decode a row from the database (either object or array) to an array
313 * with timestamps and MIME types decoded, and the field prefix removed.
316 function decodeRow( $row, $prefix = 'img_' ) {
317 $array = (array)$row;
318 $prefixLength = strlen( $prefix );
320 // Sanity check prefix once
321 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
322 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
327 foreach ( $array as $name => $value ) {
328 $decoded[substr( $name, $prefixLength )] = $value;
331 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
333 if ( empty( $decoded['major_mime'] ) ) {
334 $decoded['mime'] = 'unknown/unknown';
336 if ( !$decoded['minor_mime'] ) {
337 $decoded['minor_mime'] = 'unknown';
339 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
342 # Trim zero padding from char/binary field
343 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
349 * Load file metadata from a DB result row
351 function loadFromRow( $row, $prefix = 'img_' ) {
352 $this->dataLoaded
= true;
353 $array = $this->decodeRow( $row, $prefix );
355 foreach ( $array as $name => $value ) {
356 $this->$name = $value;
359 $this->fileExists
= true;
360 $this->maybeUpgradeRow();
364 * Load file metadata from cache or DB, unless already loaded
367 if ( !$this->dataLoaded
) {
368 if ( !$this->loadFromCache() ) {
370 $this->saveToCache();
372 $this->dataLoaded
= true;
377 * Upgrade a row if it needs it
379 function maybeUpgradeRow() {
380 global $wgUpdateCompatibleMetadata;
381 if ( wfReadOnly() ) {
385 if ( is_null( $this->media_type
) ||
386 $this->mime
== 'image/svg'
389 $this->upgraded
= true;
391 $handler = $this->getHandler();
393 $validity = $handler->isMetadataValid( $this, $this->metadata
);
394 if ( $validity === MediaHandler
::METADATA_BAD
395 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
398 $this->upgraded
= true;
404 function getUpgraded() {
405 return $this->upgraded
;
409 * Fix assorted version-related problems with the image row by reloading it from the file
411 function upgradeRow() {
412 wfProfileIn( __METHOD__
);
414 $this->lock(); // begin
416 $this->loadFromFile();
418 # Don't destroy file info of missing files
419 if ( !$this->fileExists
) {
420 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
421 wfProfileOut( __METHOD__
);
425 $dbw = $this->repo
->getMasterDB();
426 list( $major, $minor ) = self
::splitMime( $this->mime
);
428 if ( wfReadOnly() ) {
429 wfProfileOut( __METHOD__
);
432 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
434 $dbw->update( 'image',
436 'img_width' => $this->width
,
437 'img_height' => $this->height
,
438 'img_bits' => $this->bits
,
439 'img_media_type' => $this->media_type
,
440 'img_major_mime' => $major,
441 'img_minor_mime' => $minor,
442 'img_metadata' => $this->metadata
,
443 'img_sha1' => $this->sha1
,
445 array( 'img_name' => $this->getName() ),
449 $this->saveToCache();
451 $this->unlock(); // done
453 wfProfileOut( __METHOD__
);
457 * Set properties in this object to be equal to those given in the
458 * associative array $info. Only cacheable fields can be set.
460 * If 'mime' is given, it will be split into major_mime/minor_mime.
461 * If major_mime/minor_mime are given, $this->mime will also be set.
463 function setProps( $info ) {
464 $this->dataLoaded
= true;
465 $fields = $this->getCacheFields( '' );
466 $fields[] = 'fileExists';
468 foreach ( $fields as $field ) {
469 if ( isset( $info[$field] ) ) {
470 $this->$field = $info[$field];
474 // Fix up mime fields
475 if ( isset( $info['major_mime'] ) ) {
476 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
477 } elseif ( isset( $info['mime'] ) ) {
478 $this->mime
= $info['mime'];
479 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
483 /** splitMime inherited */
484 /** getName inherited */
485 /** getTitle inherited */
486 /** getURL inherited */
487 /** getViewURL inherited */
488 /** getPath inherited */
489 /** isVisible inhereted */
491 function isMissing() {
492 if ( $this->missing
=== null ) {
493 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
494 $this->missing
= !$fileExists;
496 return $this->missing
;
500 * Return the width of the image
502 * Returns false on error
505 public function getWidth( $page = 1 ) {
508 if ( $this->isMultipage() ) {
509 $dim = $this->getHandler()->getPageDimensions( $this, $page );
511 return $dim['width'];
521 * Return the height of the image
523 * Returns false on error
526 public function getHeight( $page = 1 ) {
529 if ( $this->isMultipage() ) {
530 $dim = $this->getHandler()->getPageDimensions( $this, $page );
532 return $dim['height'];
537 return $this->height
;
542 * Returns ID or name of user who uploaded the file
544 * @param $type string 'text' or 'id'
546 function getUser( $type = 'text' ) {
549 if ( $type == 'text' ) {
550 return $this->user_text
;
551 } elseif ( $type == 'id' ) {
557 * Get handler-specific metadata
560 function getMetadata() {
562 return $this->metadata
;
565 function getBitDepth() {
571 * Return the size of the image file, in bytes
573 public function getSize() {
579 * Returns the mime type of the file.
581 function getMimeType() {
587 * Return the type of the media in the file.
588 * Use the value returned by this function with the MEDIATYPE_xxx constants.
590 function getMediaType() {
592 return $this->media_type
;
595 /** canRender inherited */
596 /** mustRender inherited */
597 /** allowInlineDisplay inherited */
598 /** isSafeFile inherited */
599 /** isTrustedFile inherited */
602 * Returns true if the file exists on disk.
603 * @return boolean Whether file exist on disk.
605 public function exists() {
607 return $this->fileExists
;
610 /** getTransformScript inherited */
611 /** getUnscaledThumb inherited */
612 /** thumbName inherited */
613 /** createThumb inherited */
614 /** transform inherited */
617 * Fix thumbnail files from 1.4 or before, with extreme prejudice
619 function migrateThumbFile( $thumbName ) {
620 $thumbDir = $this->getThumbPath();
622 /* Old code for bug 2532
623 $thumbPath = "$thumbDir/$thumbName";
624 if ( is_dir( $thumbPath ) ) {
625 // Directory where file should be
626 // This happened occasionally due to broken migration code in 1.5
627 // Rename to broken-*
628 for ( $i = 0; $i < 100 ; $i++ ) {
629 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
630 if ( !file_exists( $broken ) ) {
631 rename( $thumbPath, $broken );
635 // Doesn't exist anymore
640 if ( $this->repo
->fileExists( $thumbDir ) ) {
641 // Delete file where directory should be
642 $this->repo
->cleanupBatch( array( $thumbDir ) );
646 /** getHandler inherited */
647 /** iconThumb inherited */
648 /** getLastError inherited */
651 * Get all thumbnail names previously generated for this file
652 * @param $archiveName string|bool Name of an archive file, default false
653 * @return array first element is the base dir, then files in that base dir.
655 function getThumbnails( $archiveName = false ) {
658 if ( $archiveName ) {
659 $dir = $this->getArchiveThumbPath( $archiveName );
661 $dir = $this->getThumbPath();
664 $backend = $this->repo
->getBackend();
665 $files = array( $dir );
666 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
667 foreach ( $iterator as $file ) {
675 * Refresh metadata in memcached, but don't touch thumbnails or squid
677 function purgeMetadataCache() {
679 $this->saveToCache();
680 $this->purgeHistory();
684 * Purge the shared history (OldLocalFile) cache
686 function purgeHistory() {
689 $hashedName = md5( $this->getName() );
690 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
692 // Must purge thumbnails for old versions too! bug 30192
693 foreach( $this->getHistory() as $oldFile ) {
694 $oldFile->purgeThumbnails();
698 $wgMemc->delete( $oldKey );
703 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
705 function purgeCache( $options = array() ) {
706 // Refresh metadata cache
707 $this->purgeMetadataCache();
710 $this->purgeThumbnails( $options );
712 // Purge squid cache for this file
713 SquidUpdate
::purge( array( $this->getURL() ) );
717 * Delete cached transformed files for an archived version only.
718 * @param $archiveName string name of the archived file
720 function purgeOldThumbnails( $archiveName ) {
722 // Get a list of old thumbnails and URLs
723 $files = $this->getThumbnails( $archiveName );
724 $dir = array_shift( $files );
725 $this->purgeThumbList( $dir, $files );
727 // Purge any custom thumbnail caches
728 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
733 foreach( $files as $file ) {
734 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
736 SquidUpdate
::purge( $urls );
741 * Delete cached transformed files for the current version only.
743 function purgeThumbnails( $options = array() ) {
747 $files = $this->getThumbnails();
749 // Give media handler a chance to filter the purge list
750 if ( !empty( $options['forThumbRefresh'] ) ) {
751 $handler = $this->getHandler();
753 $handler->filterThumbnailPurgeList( $files, $options );
757 $dir = array_shift( $files );
758 $this->purgeThumbList( $dir, $files );
760 // Purge any custom thumbnail caches
761 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
766 foreach( $files as $file ) {
767 $urls[] = $this->getThumbUrl( $file );
769 SquidUpdate
::purge( $urls );
774 * Delete a list of thumbnails visible at urls
775 * @param $dir string base dir of the files.
776 * @param $files array of strings: relative filenames (to $dir)
778 protected function purgeThumbList( $dir, $files ) {
779 $fileListDebug = strtr(
780 var_export( $files, true ),
783 wfDebug( __METHOD__
. ": $fileListDebug\n" );
785 $purgeList = array();
786 foreach ( $files as $file ) {
787 # Check that the base file name is part of the thumb name
788 # This is a basic sanity check to avoid erasing unrelated directories
789 if ( strpos( $file, $this->getName() ) !== false ) {
790 $purgeList[] = "{$dir}/{$file}";
794 # Delete the thumbnails
795 $this->repo
->quickPurgeBatch( $purgeList );
796 # Clear out the thumbnail directory if empty
797 $this->repo
->quickCleanDir( $dir );
800 /** purgeDescription inherited */
801 /** purgeEverything inherited */
803 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
804 $dbr = $this->repo
->getSlaveDB();
805 $tables = array( 'oldimage' );
806 $fields = OldLocalFile
::selectFields();
807 $conds = $opts = $join_conds = array();
808 $eq = $inc ?
'=' : '';
809 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
812 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
816 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
820 $opts['LIMIT'] = $limit;
823 // Search backwards for time > x queries
824 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
825 $opts['ORDER BY'] = "oi_timestamp $order";
826 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
828 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
829 &$conds, &$opts, &$join_conds ) );
831 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
834 foreach ( $res as $row ) {
835 if ( $this->repo
->oldFileFromRowFactory
) {
836 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
838 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
842 if ( $order == 'ASC' ) {
843 $r = array_reverse( $r ); // make sure it ends up descending
850 * Return the history of this file, line by line.
851 * starts with current version, then old versions.
852 * uses $this->historyLine to check which line to return:
853 * 0 return line for current version
854 * 1 query for old versions, return first one
855 * 2, ... return next old version from above query
858 public function nextHistoryLine() {
859 # Polymorphic function name to distinguish foreign and local fetches
860 $fname = get_class( $this ) . '::' . __FUNCTION__
;
862 $dbr = $this->repo
->getSlaveDB();
864 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
865 $this->historyRes
= $dbr->select( 'image',
868 "'' AS oi_archive_name",
872 array( 'img_name' => $this->title
->getDBkey() ),
876 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
877 $this->historyRes
= null;
880 } elseif ( $this->historyLine
== 1 ) {
881 $this->historyRes
= $dbr->select( 'oldimage', '*',
882 array( 'oi_name' => $this->title
->getDBkey() ),
884 array( 'ORDER BY' => 'oi_timestamp DESC' )
887 $this->historyLine ++
;
889 return $dbr->fetchObject( $this->historyRes
);
893 * Reset the history pointer to the first element of the history
895 public function resetHistory() {
896 $this->historyLine
= 0;
898 if ( !is_null( $this->historyRes
) ) {
899 $this->historyRes
= null;
903 /** getHashPath inherited */
904 /** getRel inherited */
905 /** getUrlRel inherited */
906 /** getArchiveRel inherited */
907 /** getArchivePath inherited */
908 /** getThumbPath inherited */
909 /** getArchiveUrl inherited */
910 /** getThumbUrl inherited */
911 /** getArchiveVirtualUrl inherited */
912 /** getThumbVirtualUrl inherited */
913 /** isHashed inherited */
916 * Upload a file and record it in the DB
917 * @param $srcPath String: source storage path or virtual URL
918 * @param $comment String: upload description
919 * @param $pageText String: text to use for the new description page,
920 * if a new description page is created
921 * @param $flags Integer: flags for publish()
922 * @param $props Array: File properties, if known. This can be used to reduce the
923 * upload time when uploading virtual URLs for which the file info
925 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
926 * @param $user Mixed: User object or null to use $wgUser
928 * @return FileRepoStatus object. On success, the value member contains the
929 * archive name, or an empty string if it was a new file.
931 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
934 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
935 return $this->readOnlyFatalStatus();
938 // truncate nicely or the DB will do it for us
939 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
940 $comment = $wgContLang->truncate( $comment, 255 );
941 $this->lock(); // begin
942 $status = $this->publish( $srcPath, $flags );
944 if ( $status->successCount
> 0 ) {
945 # Essentially we are displacing any existing current file and saving
946 # a new current file at the old location. If just the first succeeded,
947 # we still need to displace the current DB entry and put in a new one.
948 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
949 $status->fatal( 'filenotfound', $srcPath );
953 $this->unlock(); // done
959 * Record a file upload in the upload log and the image table
962 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
963 $watch = false, $timestamp = false )
965 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
967 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
973 $wgUser->addWatch( $this->getTitle() );
979 * Record a file upload in the upload log and the image table
982 function recordUpload2(
983 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
985 if ( is_null( $user ) ) {
990 $dbw = $this->repo
->getMasterDB();
991 $dbw->begin( __METHOD__
);
994 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
997 if ( $timestamp === false ) {
998 $timestamp = $dbw->timestamp();
1001 $props['description'] = $comment;
1002 $props['user'] = $user->getId();
1003 $props['user_text'] = $user->getName();
1004 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1005 $this->setProps( $props );
1008 $this->purgeThumbnails();
1010 # The file is already on its final location, remove it from the squid cache
1011 SquidUpdate
::purge( array( $this->getURL() ) );
1013 # Fail now if the file isn't there
1014 if ( !$this->fileExists
) {
1015 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1021 # Test to see if the row exists using INSERT IGNORE
1022 # This avoids race conditions by locking the row until the commit, and also
1023 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1024 $dbw->insert( 'image',
1026 'img_name' => $this->getName(),
1027 'img_size' => $this->size
,
1028 'img_width' => intval( $this->width
),
1029 'img_height' => intval( $this->height
),
1030 'img_bits' => $this->bits
,
1031 'img_media_type' => $this->media_type
,
1032 'img_major_mime' => $this->major_mime
,
1033 'img_minor_mime' => $this->minor_mime
,
1034 'img_timestamp' => $timestamp,
1035 'img_description' => $comment,
1036 'img_user' => $user->getId(),
1037 'img_user_text' => $user->getName(),
1038 'img_metadata' => $this->metadata
,
1039 'img_sha1' => $this->sha1
1045 if ( $dbw->affectedRows() == 0 ) {
1046 # (bug 34993) Note: $oldver can be empty here, if the previous
1047 # version of the file was broken. Allow registration of the new
1048 # version to continue anyway, because that's better than having
1049 # an image that's not fixable by user operations.
1052 # Collision, this is an update of a file
1053 # Insert previous contents into oldimage
1054 $dbw->insertSelect( 'oldimage', 'image',
1056 'oi_name' => 'img_name',
1057 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1058 'oi_size' => 'img_size',
1059 'oi_width' => 'img_width',
1060 'oi_height' => 'img_height',
1061 'oi_bits' => 'img_bits',
1062 'oi_timestamp' => 'img_timestamp',
1063 'oi_description' => 'img_description',
1064 'oi_user' => 'img_user',
1065 'oi_user_text' => 'img_user_text',
1066 'oi_metadata' => 'img_metadata',
1067 'oi_media_type' => 'img_media_type',
1068 'oi_major_mime' => 'img_major_mime',
1069 'oi_minor_mime' => 'img_minor_mime',
1070 'oi_sha1' => 'img_sha1'
1072 array( 'img_name' => $this->getName() ),
1076 # Update the current image row
1077 $dbw->update( 'image',
1079 'img_size' => $this->size
,
1080 'img_width' => intval( $this->width
),
1081 'img_height' => intval( $this->height
),
1082 'img_bits' => $this->bits
,
1083 'img_media_type' => $this->media_type
,
1084 'img_major_mime' => $this->major_mime
,
1085 'img_minor_mime' => $this->minor_mime
,
1086 'img_timestamp' => $timestamp,
1087 'img_description' => $comment,
1088 'img_user' => $user->getId(),
1089 'img_user_text' => $user->getName(),
1090 'img_metadata' => $this->metadata
,
1091 'img_sha1' => $this->sha1
1093 array( 'img_name' => $this->getName() ),
1097 # This is a new file
1098 # Update the image count
1099 $dbw->begin( __METHOD__
);
1102 array( 'ss_images = ss_images+1' ),
1106 $dbw->commit( __METHOD__
);
1109 $descTitle = $this->getTitle();
1110 $wikiPage = new WikiFilePage( $descTitle );
1111 $wikiPage->setFile( $this );
1114 $log = new LogPage( 'upload' );
1115 $action = $reupload ?
'overwrite' : 'upload';
1116 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1118 if ( $descTitle->exists() ) {
1119 # Create a null revision
1120 $latest = $descTitle->getLatestRevID();
1121 $nullRevision = Revision
::newNullRevision(
1123 $descTitle->getArticleID(),
1124 $log->getRcComment(),
1127 if (!is_null($nullRevision)) {
1128 $nullRevision->insertOn( $dbw );
1130 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1131 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1133 # Invalidate the cache for the description page
1134 $descTitle->invalidateCache();
1135 $descTitle->purgeSquid();
1137 # New file; create the description page.
1138 # There's already a log entry, so don't make a second RC entry
1139 # Squid and file cache for the description page are purged by doEdit.
1140 $wikiPage->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
, false, $user );
1143 # Commit the transaction now, in case something goes wrong later
1144 # The most important thing is that files don't get lost, especially archives
1145 $dbw->commit( __METHOD__
);
1147 # Save to cache and purge the squid
1148 # We shall not saveToCache before the commit since otherwise
1149 # in case of a rollback there is an usable file from memcached
1150 # which in fact doesn't really exist (bug 24978)
1151 $this->saveToCache();
1153 # Hooks, hooks, the magic of hooks...
1154 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1156 # Invalidate cache for all pages using this file
1157 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1158 $update->doUpdate();
1160 # Invalidate cache for all pages that redirects on this page
1161 $redirs = $this->getTitle()->getRedirectsHere();
1163 foreach ( $redirs as $redir ) {
1164 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1165 $update->doUpdate();
1172 * Move or copy a file to its public location. If a file exists at the
1173 * destination, move it to an archive. Returns a FileRepoStatus object with
1174 * the archive name in the "value" member on success.
1176 * The archive name should be passed through to recordUpload for database
1179 * @param $srcPath String: local filesystem path to the source image
1180 * @param $flags Integer: a bitwise combination of:
1181 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1182 * @return FileRepoStatus object. On success, the value member contains the
1183 * archive name, or an empty string if it was a new file.
1185 function publish( $srcPath, $flags = 0 ) {
1186 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1190 * Move or copy a file to a specified location. Returns a FileRepoStatus
1191 * object with the archive name in the "value" member on success.
1193 * The archive name should be passed through to recordUpload for database
1196 * @param $srcPath String: local filesystem path to the source image
1197 * @param $dstRel String: target relative path
1198 * @param $flags Integer: a bitwise combination of:
1199 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1200 * @return FileRepoStatus object. On success, the value member contains the
1201 * archive name, or an empty string if it was a new file.
1203 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1204 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1205 return $this->readOnlyFatalStatus();
1208 $this->lock(); // begin
1210 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1211 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1212 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1213 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1215 if ( $status->value
== 'new' ) {
1216 $status->value
= '';
1218 $status->value
= $archiveName;
1221 $this->unlock(); // done
1226 /** getLinksTo inherited */
1227 /** getExifData inherited */
1228 /** isLocal inherited */
1229 /** wasDeleted inherited */
1232 * Move file to the new title
1234 * Move current, old version and all thumbnails
1235 * to the new filename. Old file is deleted.
1237 * Cache purging is done; checks for validity
1238 * and logging are caller's responsibility
1240 * @param $target Title New file name
1241 * @return FileRepoStatus object.
1243 function move( $target ) {
1244 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1245 return $this->readOnlyFatalStatus();
1248 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1249 $batch = new LocalFileMoveBatch( $this, $target );
1251 $this->lock(); // begin
1252 $batch->addCurrent();
1253 $archiveNames = $batch->addOlds();
1254 $status = $batch->execute();
1255 $this->unlock(); // done
1257 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1259 $this->purgeEverything();
1260 foreach ( $archiveNames as $archiveName ) {
1261 $this->purgeOldThumbnails( $archiveName );
1263 if ( $status->isOK() ) {
1264 // Now switch the object
1265 $this->title
= $target;
1266 // Force regeneration of the name and hashpath
1267 unset( $this->name
);
1268 unset( $this->hashPath
);
1269 // Purge the new image
1270 $this->purgeEverything();
1277 * Delete all versions of the file.
1279 * Moves the files into an archive directory (or deletes them)
1280 * and removes the database rows.
1282 * Cache purging is done; logging is caller's responsibility.
1286 * @return FileRepoStatus object.
1288 function delete( $reason, $suppress = false ) {
1289 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1290 return $this->readOnlyFatalStatus();
1293 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1295 $this->lock(); // begin
1296 $batch->addCurrent();
1297 # Get old version relative paths
1298 $archiveNames = $batch->addOlds();
1299 $status = $batch->execute();
1300 if ( $status->isOK() ) {
1301 // Update site_stats
1302 $dbw = $this->repo
->getMasterDB();
1303 $site_stats = $dbw->tableName( 'site_stats' );
1304 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1306 $this->unlock(); // done
1308 $this->purgeEverything();
1309 foreach ( $archiveNames as $archiveName ) {
1310 $this->purgeOldThumbnails( $archiveName );
1317 * Delete an old version of the file.
1319 * Moves the file into an archive directory (or deletes it)
1320 * and removes the database row.
1322 * Cache purging is done; logging is caller's responsibility.
1324 * @param $archiveName String
1325 * @param $reason String
1326 * @param $suppress Boolean
1327 * @throws MWException or FSException on database or file store failure
1328 * @return FileRepoStatus object.
1330 function deleteOld( $archiveName, $reason, $suppress = false ) {
1331 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1332 return $this->readOnlyFatalStatus();
1335 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1337 $this->lock(); // begin
1338 $batch->addOld( $archiveName );
1339 $status = $batch->execute();
1340 $this->unlock(); // done
1342 $this->purgeOldThumbnails( $archiveName );
1343 if ( $status->isOK() ) {
1344 $this->purgeDescription();
1345 $this->purgeHistory();
1352 * Restore all or specified deleted revisions to the given file.
1353 * Permissions and logging are left to the caller.
1355 * May throw database exceptions on error.
1357 * @param $versions array set of record ids of deleted items to restore,
1358 * or empty to restore all revisions.
1359 * @param $unsuppress Boolean
1360 * @return FileRepoStatus
1362 function restore( $versions = array(), $unsuppress = false ) {
1363 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1364 return $this->readOnlyFatalStatus();
1367 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1369 $this->lock(); // begin
1373 $batch->addIds( $versions );
1375 $status = $batch->execute();
1376 if ( $status->isGood() ) {
1377 $cleanupStatus = $batch->cleanup();
1378 $cleanupStatus->successCount
= 0;
1379 $cleanupStatus->failCount
= 0;
1380 $status->merge( $cleanupStatus );
1382 $this->unlock(); // done
1387 /** isMultipage inherited */
1388 /** pageCount inherited */
1389 /** scaleHeight inherited */
1390 /** getImageSize inherited */
1393 * Get the URL of the file description page.
1396 function getDescriptionUrl() {
1397 return $this->title
->getLocalUrl();
1401 * Get the HTML text of the description page
1402 * This is not used by ImagePage for local files, since (among other things)
1403 * it skips the parser cache.
1404 * @return bool|mixed
1406 function getDescriptionText() {
1408 $revision = Revision
::newFromTitle( $this->title
);
1409 if ( !$revision ) return false;
1410 $text = $revision->getText();
1411 if ( !$text ) return false;
1412 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1413 return $pout->getText();
1416 function getDescription() {
1418 return $this->description
;
1421 function getTimestamp() {
1423 return $this->timestamp
;
1426 function getSha1() {
1428 // Initialise now if necessary
1429 if ( $this->sha1
== '' && $this->fileExists
) {
1430 $this->lock(); // begin
1432 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1433 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1434 $dbw = $this->repo
->getMasterDB();
1435 $dbw->update( 'image',
1436 array( 'img_sha1' => $this->sha1
),
1437 array( 'img_name' => $this->getName() ),
1439 $this->saveToCache();
1442 $this->unlock(); // done
1448 function isCacheable() {
1450 return strlen( $this->metadata
) <= self
::CACHE_FIELD_MAX_LEN
; // avoid OOMs
1454 * Start a transaction and lock the image for update
1455 * Increments a reference counter if the lock is already held
1456 * @return boolean True if the image exists, false otherwise
1459 $dbw = $this->repo
->getMasterDB();
1461 if ( !$this->locked
) {
1462 $dbw->begin( __METHOD__
);
1466 return $dbw->selectField( 'image', '1',
1467 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1471 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1472 * the transaction and thereby releases the image lock.
1475 if ( $this->locked
) {
1477 if ( !$this->locked
) {
1478 $dbw = $this->repo
->getMasterDB();
1479 $dbw->commit( __METHOD__
);
1485 * Roll back the DB transaction and mark the image unlocked
1487 function unlockAndRollback() {
1488 $this->locked
= false;
1489 $dbw = $this->repo
->getMasterDB();
1490 $dbw->rollback( __METHOD__
);
1496 protected function readOnlyFatalStatus() {
1497 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1498 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1500 } // LocalFile class
1502 # ------------------------------------------------------------------------------
1505 * Helper class for file deletion
1506 * @ingroup FileAbstraction
1508 class LocalFileDeleteBatch
{
1515 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1518 function __construct( File
$file, $reason = '', $suppress = false ) {
1519 $this->file
= $file;
1520 $this->reason
= $reason;
1521 $this->suppress
= $suppress;
1522 $this->status
= $file->repo
->newGood();
1525 function addCurrent() {
1526 $this->srcRels
['.'] = $this->file
->getRel();
1529 function addOld( $oldName ) {
1530 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1531 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1535 * Add the old versions of the image to the batch
1536 * @return Array List of archive names from old versions
1538 function addOlds() {
1539 $archiveNames = array();
1541 $dbw = $this->file
->repo
->getMasterDB();
1542 $result = $dbw->select( 'oldimage',
1543 array( 'oi_archive_name' ),
1544 array( 'oi_name' => $this->file
->getName() ),
1548 foreach ( $result as $row ) {
1549 $this->addOld( $row->oi_archive_name
);
1550 $archiveNames[] = $row->oi_archive_name
;
1553 return $archiveNames;
1556 function getOldRels() {
1557 if ( !isset( $this->srcRels
['.'] ) ) {
1558 $oldRels =& $this->srcRels
;
1559 $deleteCurrent = false;
1561 $oldRels = $this->srcRels
;
1562 unset( $oldRels['.'] );
1563 $deleteCurrent = true;
1566 return array( $oldRels, $deleteCurrent );
1569 protected function getHashes() {
1571 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1573 if ( $deleteCurrent ) {
1574 $hashes['.'] = $this->file
->getSha1();
1577 if ( count( $oldRels ) ) {
1578 $dbw = $this->file
->repo
->getMasterDB();
1579 $res = $dbw->select(
1581 array( 'oi_archive_name', 'oi_sha1' ),
1582 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1586 foreach ( $res as $row ) {
1587 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1588 // Get the hash from the file
1589 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1590 $props = $this->file
->repo
->getFileProps( $oldUrl );
1592 if ( $props['fileExists'] ) {
1593 // Upgrade the oldimage row
1594 $dbw->update( 'oldimage',
1595 array( 'oi_sha1' => $props['sha1'] ),
1596 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1598 $hashes[$row->oi_archive_name
] = $props['sha1'];
1600 $hashes[$row->oi_archive_name
] = false;
1603 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1608 $missing = array_diff_key( $this->srcRels
, $hashes );
1610 foreach ( $missing as $name => $rel ) {
1611 $this->status
->error( 'filedelete-old-unregistered', $name );
1614 foreach ( $hashes as $name => $hash ) {
1616 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1617 unset( $hashes[$name] );
1624 function doDBInserts() {
1627 $dbw = $this->file
->repo
->getMasterDB();
1628 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1629 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1630 $encReason = $dbw->addQuotes( $this->reason
);
1631 $encGroup = $dbw->addQuotes( 'deleted' );
1632 $ext = $this->file
->getExtension();
1633 $dotExt = $ext === '' ?
'' : ".$ext";
1634 $encExt = $dbw->addQuotes( $dotExt );
1635 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1637 // Bitfields to further suppress the content
1638 if ( $this->suppress
) {
1640 // This should be 15...
1641 $bitfield |
= Revision
::DELETED_TEXT
;
1642 $bitfield |
= Revision
::DELETED_COMMENT
;
1643 $bitfield |
= Revision
::DELETED_USER
;
1644 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1646 $bitfield = 'oi_deleted';
1649 if ( $deleteCurrent ) {
1650 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1651 $where = array( 'img_name' => $this->file
->getName() );
1652 $dbw->insertSelect( 'filearchive', 'image',
1654 'fa_storage_group' => $encGroup,
1655 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1656 'fa_deleted_user' => $encUserId,
1657 'fa_deleted_timestamp' => $encTimestamp,
1658 'fa_deleted_reason' => $encReason,
1659 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1661 'fa_name' => 'img_name',
1662 'fa_archive_name' => 'NULL',
1663 'fa_size' => 'img_size',
1664 'fa_width' => 'img_width',
1665 'fa_height' => 'img_height',
1666 'fa_metadata' => 'img_metadata',
1667 'fa_bits' => 'img_bits',
1668 'fa_media_type' => 'img_media_type',
1669 'fa_major_mime' => 'img_major_mime',
1670 'fa_minor_mime' => 'img_minor_mime',
1671 'fa_description' => 'img_description',
1672 'fa_user' => 'img_user',
1673 'fa_user_text' => 'img_user_text',
1674 'fa_timestamp' => 'img_timestamp'
1675 ), $where, __METHOD__
);
1678 if ( count( $oldRels ) ) {
1679 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1681 'oi_name' => $this->file
->getName(),
1682 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1683 $dbw->insertSelect( 'filearchive', 'oldimage',
1685 'fa_storage_group' => $encGroup,
1686 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1687 'fa_deleted_user' => $encUserId,
1688 'fa_deleted_timestamp' => $encTimestamp,
1689 'fa_deleted_reason' => $encReason,
1690 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1692 'fa_name' => 'oi_name',
1693 'fa_archive_name' => 'oi_archive_name',
1694 'fa_size' => 'oi_size',
1695 'fa_width' => 'oi_width',
1696 'fa_height' => 'oi_height',
1697 'fa_metadata' => 'oi_metadata',
1698 'fa_bits' => 'oi_bits',
1699 'fa_media_type' => 'oi_media_type',
1700 'fa_major_mime' => 'oi_major_mime',
1701 'fa_minor_mime' => 'oi_minor_mime',
1702 'fa_description' => 'oi_description',
1703 'fa_user' => 'oi_user',
1704 'fa_user_text' => 'oi_user_text',
1705 'fa_timestamp' => 'oi_timestamp',
1706 ), $where, __METHOD__
);
1710 function doDBDeletes() {
1711 $dbw = $this->file
->repo
->getMasterDB();
1712 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1714 if ( count( $oldRels ) ) {
1715 $dbw->delete( 'oldimage',
1717 'oi_name' => $this->file
->getName(),
1718 'oi_archive_name' => array_keys( $oldRels )
1722 if ( $deleteCurrent ) {
1723 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1728 * Run the transaction
1729 * @return FileRepoStatus
1731 function execute() {
1733 wfProfileIn( __METHOD__
);
1735 $this->file
->lock();
1736 // Leave private files alone
1737 $privateFiles = array();
1738 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1739 $dbw = $this->file
->repo
->getMasterDB();
1741 if ( !empty( $oldRels ) ) {
1742 $res = $dbw->select( 'oldimage',
1743 array( 'oi_archive_name' ),
1744 array( 'oi_name' => $this->file
->getName(),
1745 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1746 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1749 foreach ( $res as $row ) {
1750 $privateFiles[$row->oi_archive_name
] = 1;
1753 // Prepare deletion batch
1754 $hashes = $this->getHashes();
1755 $this->deletionBatch
= array();
1756 $ext = $this->file
->getExtension();
1757 $dotExt = $ext === '' ?
'' : ".$ext";
1759 foreach ( $this->srcRels
as $name => $srcRel ) {
1760 // Skip files that have no hash (missing source).
1761 // Keep private files where they are.
1762 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1763 $hash = $hashes[$name];
1764 $key = $hash . $dotExt;
1765 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1766 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1770 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1771 // We acquire this lock by running the inserts now, before the file operations.
1773 // This potentially has poor lock contention characteristics -- an alternative
1774 // scheme would be to insert stub filearchive entries with no fa_name and commit
1775 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1776 $this->doDBInserts();
1778 // Removes non-existent file from the batch, so we don't get errors.
1779 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1781 // Execute the file deletion batch
1782 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1784 if ( !$status->isGood() ) {
1785 $this->status
->merge( $status );
1788 if ( !$this->status
->isOK() ) {
1789 // Critical file deletion error
1790 // Roll back inserts, release lock and abort
1791 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1792 $this->file
->unlockAndRollback();
1793 wfProfileOut( __METHOD__
);
1794 return $this->status
;
1797 // Delete image/oldimage rows
1798 $this->doDBDeletes();
1800 // Commit and return
1801 $this->file
->unlock();
1802 wfProfileOut( __METHOD__
);
1804 return $this->status
;
1808 * Removes non-existent files from a deletion batch.
1811 function removeNonexistentFiles( $batch ) {
1812 $files = $newBatch = array();
1814 foreach ( $batch as $batchItem ) {
1815 list( $src, $dest ) = $batchItem;
1816 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1819 $result = $this->file
->repo
->fileExistsBatch( $files );
1821 foreach ( $batch as $batchItem ) {
1822 if ( $result[$batchItem[0]] ) {
1823 $newBatch[] = $batchItem;
1831 # ------------------------------------------------------------------------------
1834 * Helper class for file undeletion
1835 * @ingroup FileAbstraction
1837 class LocalFileRestoreBatch
{
1843 var $cleanupBatch, $ids, $all, $unsuppress = false;
1845 function __construct( File
$file, $unsuppress = false ) {
1846 $this->file
= $file;
1847 $this->cleanupBatch
= $this->ids
= array();
1848 $this->ids
= array();
1849 $this->unsuppress
= $unsuppress;
1855 function addId( $fa_id ) {
1856 $this->ids
[] = $fa_id;
1860 * Add a whole lot of files by ID
1862 function addIds( $ids ) {
1863 $this->ids
= array_merge( $this->ids
, $ids );
1867 * Add all revisions of the file
1874 * Run the transaction, except the cleanup batch.
1875 * The cleanup batch should be run in a separate transaction, because it locks different
1876 * rows and there's no need to keep the image row locked while it's acquiring those locks
1877 * The caller may have its own transaction open.
1878 * So we save the batch and let the caller call cleanup()
1879 * @return FileRepoStatus
1881 function execute() {
1884 if ( !$this->all
&& !$this->ids
) {
1886 return $this->file
->repo
->newGood();
1889 $exists = $this->file
->lock();
1890 $dbw = $this->file
->repo
->getMasterDB();
1891 $status = $this->file
->repo
->newGood();
1893 // Fetch all or selected archived revisions for the file,
1894 // sorted from the most recent to the oldest.
1895 $conditions = array( 'fa_name' => $this->file
->getName() );
1897 if ( !$this->all
) {
1898 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1901 $result = $dbw->select( 'filearchive', '*',
1904 array( 'ORDER BY' => 'fa_timestamp DESC' )
1907 $idsPresent = array();
1908 $storeBatch = array();
1909 $insertBatch = array();
1910 $insertCurrent = false;
1911 $deleteIds = array();
1913 $archiveNames = array();
1915 foreach ( $result as $row ) {
1916 $idsPresent[] = $row->fa_id
;
1918 if ( $row->fa_name
!= $this->file
->getName() ) {
1919 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1920 $status->failCount++
;
1924 if ( $row->fa_storage_key
== '' ) {
1925 // Revision was missing pre-deletion
1926 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1927 $status->failCount++
;
1931 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1932 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1934 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1937 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1938 $sha1 = substr( $sha1, 1 );
1941 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1942 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1943 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1944 ||
is_null( $row->fa_metadata
) ) {
1945 // Refresh our metadata
1946 // Required for a new current revision; nice for older ones too. :)
1947 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1950 'minor_mime' => $row->fa_minor_mime
,
1951 'major_mime' => $row->fa_major_mime
,
1952 'media_type' => $row->fa_media_type
,
1953 'metadata' => $row->fa_metadata
1957 if ( $first && !$exists ) {
1958 // This revision will be published as the new current version
1959 $destRel = $this->file
->getRel();
1960 $insertCurrent = array(
1961 'img_name' => $row->fa_name
,
1962 'img_size' => $row->fa_size
,
1963 'img_width' => $row->fa_width
,
1964 'img_height' => $row->fa_height
,
1965 'img_metadata' => $props['metadata'],
1966 'img_bits' => $row->fa_bits
,
1967 'img_media_type' => $props['media_type'],
1968 'img_major_mime' => $props['major_mime'],
1969 'img_minor_mime' => $props['minor_mime'],
1970 'img_description' => $row->fa_description
,
1971 'img_user' => $row->fa_user
,
1972 'img_user_text' => $row->fa_user_text
,
1973 'img_timestamp' => $row->fa_timestamp
,
1977 // The live (current) version cannot be hidden!
1978 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1979 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1980 $this->cleanupBatch
[] = $row->fa_storage_key
;
1983 $archiveName = $row->fa_archive_name
;
1985 if ( $archiveName == '' ) {
1986 // This was originally a current version; we
1987 // have to devise a new archive name for it.
1988 // Format is <timestamp of archiving>!<name>
1989 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1992 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1994 } while ( isset( $archiveNames[$archiveName] ) );
1997 $archiveNames[$archiveName] = true;
1998 $destRel = $this->file
->getArchiveRel( $archiveName );
1999 $insertBatch[] = array(
2000 'oi_name' => $row->fa_name
,
2001 'oi_archive_name' => $archiveName,
2002 'oi_size' => $row->fa_size
,
2003 'oi_width' => $row->fa_width
,
2004 'oi_height' => $row->fa_height
,
2005 'oi_bits' => $row->fa_bits
,
2006 'oi_description' => $row->fa_description
,
2007 'oi_user' => $row->fa_user
,
2008 'oi_user_text' => $row->fa_user_text
,
2009 'oi_timestamp' => $row->fa_timestamp
,
2010 'oi_metadata' => $props['metadata'],
2011 'oi_media_type' => $props['media_type'],
2012 'oi_major_mime' => $props['major_mime'],
2013 'oi_minor_mime' => $props['minor_mime'],
2014 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2015 'oi_sha1' => $sha1 );
2018 $deleteIds[] = $row->fa_id
;
2020 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2021 // private files can stay where they are
2022 $status->successCount++
;
2024 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2025 $this->cleanupBatch
[] = $row->fa_storage_key
;
2033 // Add a warning to the status object for missing IDs
2034 $missingIds = array_diff( $this->ids
, $idsPresent );
2036 foreach ( $missingIds as $id ) {
2037 $status->error( 'undelete-missing-filearchive', $id );
2040 // Remove missing files from batch, so we don't get errors when undeleting them
2041 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2043 // Run the store batch
2044 // Use the OVERWRITE_SAME flag to smooth over a common error
2045 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2046 $status->merge( $storeStatus );
2048 if ( !$status->isGood() ) {
2049 // Even if some files could be copied, fail entirely as that is the
2050 // easiest thing to do without data loss
2051 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2052 $status->ok
= false;
2053 $this->file
->unlock();
2058 // Run the DB updates
2059 // Because we have locked the image row, key conflicts should be rare.
2060 // If they do occur, we can roll back the transaction at this time with
2061 // no data loss, but leaving unregistered files scattered throughout the
2063 // This is not ideal, which is why it's important to lock the image row.
2064 if ( $insertCurrent ) {
2065 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2068 if ( $insertBatch ) {
2069 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2073 $dbw->delete( 'filearchive',
2074 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2078 // If store batch is empty (all files are missing), deletion is to be considered successful
2079 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2081 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2083 // Update site_stats
2084 $site_stats = $dbw->tableName( 'site_stats' );
2085 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2087 $this->file
->purgeEverything();
2089 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2090 $this->file
->purgeDescription();
2091 $this->file
->purgeHistory();
2095 $this->file
->unlock();
2101 * Removes non-existent files from a store batch.
2104 function removeNonexistentFiles( $triplets ) {
2105 $files = $filteredTriplets = array();
2106 foreach ( $triplets as $file )
2107 $files[$file[0]] = $file[0];
2109 $result = $this->file
->repo
->fileExistsBatch( $files );
2111 foreach ( $triplets as $file ) {
2112 if ( $result[$file[0]] ) {
2113 $filteredTriplets[] = $file;
2117 return $filteredTriplets;
2121 * Removes non-existent files from a cleanup batch.
2124 function removeNonexistentFromCleanup( $batch ) {
2125 $files = $newBatch = array();
2126 $repo = $this->file
->repo
;
2128 foreach ( $batch as $file ) {
2129 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2130 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2133 $result = $repo->fileExistsBatch( $files );
2135 foreach ( $batch as $file ) {
2136 if ( $result[$file] ) {
2137 $newBatch[] = $file;
2145 * Delete unused files in the deleted zone.
2146 * This should be called from outside the transaction in which execute() was called.
2147 * @return FileRepoStatus|void
2149 function cleanup() {
2150 if ( !$this->cleanupBatch
) {
2151 return $this->file
->repo
->newGood();
2154 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2156 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2162 * Cleanup a failed batch. The batch was only partially successful, so
2163 * rollback by removing all items that were succesfully copied.
2165 * @param Status $storeStatus
2166 * @param array $storeBatch
2168 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2169 $cleanupBatch = array();
2171 foreach ( $storeStatus->success
as $i => $success ) {
2172 // Check if this item of the batch was successfully copied
2174 // Item was successfully copied and needs to be removed again
2175 // Extract ($dstZone, $dstRel) from the batch
2176 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2179 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2183 # ------------------------------------------------------------------------------
2186 * Helper class for file movement
2187 * @ingroup FileAbstraction
2189 class LocalFileMoveBatch
{
2201 var $cur, $olds, $oldCount, $archive, $db;
2203 function __construct( File
$file, Title
$target ) {
2204 $this->file
= $file;
2205 $this->target
= $target;
2206 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2207 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2208 $this->oldName
= $this->file
->getName();
2209 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2210 $this->oldRel
= $this->oldHash
. $this->oldName
;
2211 $this->newRel
= $this->newHash
. $this->newName
;
2212 $this->db
= $file->repo
->getMasterDb();
2216 * Add the current image to the batch
2218 function addCurrent() {
2219 $this->cur
= array( $this->oldRel
, $this->newRel
);
2223 * Add the old versions of the image to the batch
2224 * @return Array List of archive names from old versions
2226 function addOlds() {
2227 $archiveBase = 'archive';
2228 $this->olds
= array();
2229 $this->oldCount
= 0;
2230 $archiveNames = array();
2232 $result = $this->db
->select( 'oldimage',
2233 array( 'oi_archive_name', 'oi_deleted' ),
2234 array( 'oi_name' => $this->oldName
),
2238 foreach ( $result as $row ) {
2239 $archiveNames[] = $row->oi_archive_name
;
2240 $oldName = $row->oi_archive_name
;
2241 $bits = explode( '!', $oldName, 2 );
2243 if ( count( $bits ) != 2 ) {
2244 wfDebug( "Old file name missing !: '$oldName' \n" );
2248 list( $timestamp, $filename ) = $bits;
2250 if ( $this->oldName
!= $filename ) {
2251 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2257 // Do we want to add those to oldCount?
2258 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2262 $this->olds
[] = array(
2263 "{$archiveBase}/{$this->oldHash}{$oldName}",
2264 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2268 return $archiveNames;
2273 * @return FileRepoStatus
2275 function execute() {
2276 $repo = $this->file
->repo
;
2277 $status = $repo->newGood();
2279 $triplets = $this->getMoveTriplets();
2280 $triplets = $this->removeNonexistentFiles( $triplets );
2282 // Copy the files into their new location
2283 $statusMove = $repo->storeBatch( $triplets );
2284 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2285 if ( !$statusMove->isGood() ) {
2286 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2287 $this->cleanupTarget( $triplets );
2288 $statusMove->ok
= false;
2292 $this->file
->lock(); // begin
2293 $statusDb = $this->doDBUpdates();
2294 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2295 if ( !$statusDb->isGood() ) {
2296 $this->file
->unlockAndRollback();
2297 // Something went wrong with the DB updates, so remove the target files
2298 $this->cleanupTarget( $triplets );
2299 $statusDb->ok
= false;
2302 $this->file
->unlock(); // done
2304 // Everything went ok, remove the source files
2305 $this->cleanupSource( $triplets );
2307 $status->merge( $statusDb );
2308 $status->merge( $statusMove );
2314 * Do the database updates and return a new FileRepoStatus indicating how
2315 * many rows where updated.
2317 * @return FileRepoStatus
2319 function doDBUpdates() {
2320 $repo = $this->file
->repo
;
2321 $status = $repo->newGood();
2324 // Update current image
2327 array( 'img_name' => $this->newName
),
2328 array( 'img_name' => $this->oldName
),
2332 if ( $dbw->affectedRows() ) {
2333 $status->successCount++
;
2335 $status->failCount++
;
2336 $status->fatal( 'imageinvalidfilename' );
2340 // Update old images
2344 'oi_name' => $this->newName
,
2345 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2346 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2348 array( 'oi_name' => $this->oldName
),
2352 $affected = $dbw->affectedRows();
2353 $total = $this->oldCount
;
2354 $status->successCount +
= $affected;
2355 // Bug 34934: $total is based on files that actually exist.
2356 // There may be more DB rows than such files, in which case $affected
2357 // can be greater than $total. We use max() to avoid negatives here.
2358 $status->failCount +
= max( 0, $total - $affected );
2359 if ( $status->failCount
) {
2360 $status->error( 'imageinvalidfilename' );
2367 * Generate triplets for FileRepo::storeBatch().
2370 function getMoveTriplets() {
2371 $moves = array_merge( array( $this->cur
), $this->olds
);
2372 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2374 foreach ( $moves as $move ) {
2375 // $move: (oldRelativePath, newRelativePath)
2376 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2377 $triplets[] = array( $srcUrl, 'public', $move[1] );
2378 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2385 * Removes non-existent files from move batch.
2388 function removeNonexistentFiles( $triplets ) {
2391 foreach ( $triplets as $file ) {
2392 $files[$file[0]] = $file[0];
2395 $result = $this->file
->repo
->fileExistsBatch( $files );
2396 $filteredTriplets = array();
2398 foreach ( $triplets as $file ) {
2399 if ( $result[$file[0]] ) {
2400 $filteredTriplets[] = $file;
2402 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2406 return $filteredTriplets;
2410 * Cleanup a partially moved array of triplets by deleting the target
2411 * files. Called if something went wrong half way.
2413 function cleanupTarget( $triplets ) {
2414 // Create dest pairs from the triplets
2416 foreach ( $triplets as $triplet ) {
2417 $pairs[] = array( $triplet[1], $triplet[2] );
2420 $this->file
->repo
->cleanupBatch( $pairs );
2424 * Cleanup a fully moved array of triplets by deleting the source files.
2425 * Called at the end of the move process if everything else went ok.
2427 function cleanupSource( $triplets ) {
2428 // Create source file names from the triplets
2430 foreach ( $triplets as $triplet ) {
2431 $files[] = $triplet[0];
2434 $this->file
->repo
->cleanupBatch( $files );