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();
774 // Always purge all files from squid regardless of handler filters
777 foreach( $files as $file ) {
778 $urls[] = $this->getThumbUrl( $file );
780 array_shift( $urls ); // don't purge directory
783 // Give media handler a chance to filter the file purge list
784 if ( !empty( $options['forThumbRefresh'] ) ) {
785 $handler = $this->getHandler();
787 $handler->filterThumbnailPurgeList( $files, $options );
791 $dir = array_shift( $files );
792 $this->purgeThumbList( $dir, $files );
794 // Purge any custom thumbnail caches
795 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
799 SquidUpdate
::purge( $urls );
802 wfProfileOut( __METHOD__
);
806 * Delete a list of thumbnails visible at urls
807 * @param $dir string base dir of the files.
808 * @param $files array of strings: relative filenames (to $dir)
810 protected function purgeThumbList( $dir, $files ) {
811 $fileListDebug = strtr(
812 var_export( $files, true ),
815 wfDebug( __METHOD__
. ": $fileListDebug\n" );
817 $purgeList = array();
818 foreach ( $files as $file ) {
819 # Check that the base file name is part of the thumb name
820 # This is a basic sanity check to avoid erasing unrelated directories
821 if ( strpos( $file, $this->getName() ) !== false
822 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
824 $purgeList[] = "{$dir}/{$file}";
828 # Delete the thumbnails
829 $this->repo
->quickPurgeBatch( $purgeList );
830 # Clear out the thumbnail directory if empty
831 $this->repo
->quickCleanDir( $dir );
834 /** purgeDescription inherited */
835 /** purgeEverything inherited */
844 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
845 $dbr = $this->repo
->getSlaveDB();
846 $tables = array( 'oldimage' );
847 $fields = OldLocalFile
::selectFields();
848 $conds = $opts = $join_conds = array();
849 $eq = $inc ?
'=' : '';
850 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
853 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
857 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
861 $opts['LIMIT'] = $limit;
864 // Search backwards for time > x queries
865 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
866 $opts['ORDER BY'] = "oi_timestamp $order";
867 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
869 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
870 &$conds, &$opts, &$join_conds ) );
872 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
875 foreach ( $res as $row ) {
876 if ( $this->repo
->oldFileFromRowFactory
) {
877 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
879 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
883 if ( $order == 'ASC' ) {
884 $r = array_reverse( $r ); // make sure it ends up descending
891 * Return the history of this file, line by line.
892 * starts with current version, then old versions.
893 * uses $this->historyLine to check which line to return:
894 * 0 return line for current version
895 * 1 query for old versions, return first one
896 * 2, ... return next old version from above query
899 public function nextHistoryLine() {
900 # Polymorphic function name to distinguish foreign and local fetches
901 $fname = get_class( $this ) . '::' . __FUNCTION__
;
903 $dbr = $this->repo
->getSlaveDB();
905 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
906 $this->historyRes
= $dbr->select( 'image',
909 "'' AS oi_archive_name",
913 array( 'img_name' => $this->title
->getDBkey() ),
917 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
918 $this->historyRes
= null;
921 } elseif ( $this->historyLine
== 1 ) {
922 $this->historyRes
= $dbr->select( 'oldimage', '*',
923 array( 'oi_name' => $this->title
->getDBkey() ),
925 array( 'ORDER BY' => 'oi_timestamp DESC' )
928 $this->historyLine ++
;
930 return $dbr->fetchObject( $this->historyRes
);
934 * Reset the history pointer to the first element of the history
936 public function resetHistory() {
937 $this->historyLine
= 0;
939 if ( !is_null( $this->historyRes
) ) {
940 $this->historyRes
= null;
944 /** getHashPath inherited */
945 /** getRel inherited */
946 /** getUrlRel inherited */
947 /** getArchiveRel inherited */
948 /** getArchivePath inherited */
949 /** getThumbPath inherited */
950 /** getArchiveUrl inherited */
951 /** getThumbUrl inherited */
952 /** getArchiveVirtualUrl inherited */
953 /** getThumbVirtualUrl inherited */
954 /** isHashed inherited */
957 * Upload a file and record it in the DB
958 * @param $srcPath String: source storage path, virtual URL, or filesystem path
959 * @param $comment String: upload description
960 * @param $pageText String: text to use for the new description page,
961 * if a new description page is created
962 * @param $flags Integer|bool: flags for publish()
963 * @param $props Array|bool: File properties, if known. This can be used to reduce the
964 * upload time when uploading virtual URLs for which the file info
966 * @param $timestamp String|bool: timestamp for img_timestamp, or false to use the current time
967 * @param $user User|null: User object or null to use $wgUser
969 * @return FileRepoStatus object. On success, the value member contains the
970 * archive name, or an empty string if it was a new file.
972 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
975 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
976 return $this->readOnlyFatalStatus();
980 wfProfileIn( __METHOD__
. '-getProps' );
981 if ( $this->repo
->isVirtualUrl( $srcPath )
982 || FileBackend
::isStoragePath( $srcPath ) )
984 $props = $this->repo
->getFileProps( $srcPath );
986 $props = FSFile
::getPropsFromPath( $srcPath );
988 wfProfileOut( __METHOD__
. '-getProps' );
992 $handler = MediaHandler
::getHandler( $props['mime'] );
994 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
996 $options['headers'] = array();
999 // Trim spaces on user supplied text
1000 $comment = trim( $comment );
1002 // truncate nicely or the DB will do it for us
1003 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1004 $comment = $wgContLang->truncate( $comment, 255 );
1005 $this->lock(); // begin
1006 $status = $this->publish( $srcPath, $flags, $options );
1008 if ( $status->successCount
> 0 ) {
1009 # Essentially we are displacing any existing current file and saving
1010 # a new current file at the old location. If just the first succeeded,
1011 # we still need to displace the current DB entry and put in a new one.
1012 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
1013 $status->fatal( 'filenotfound', $srcPath );
1017 $this->unlock(); // done
1023 * Record a file upload in the upload log and the image table
1025 * @param $desc string
1026 * @param $license string
1027 * @param $copyStatus string
1028 * @param $source string
1029 * @param $watch bool
1030 * @param $timestamp string|bool
1033 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1034 $watch = false, $timestamp = false )
1036 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1038 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp ) ) {
1044 $wgUser->addWatch( $this->getTitle() );
1050 * Record a file upload in the upload log and the image table
1052 * @param $comment string
1053 * @param $pageText string
1054 * @param $props bool|array
1055 * @param $timestamp bool|string
1056 * @param $user null|User
1059 function recordUpload2(
1060 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1062 wfProfileIn( __METHOD__
);
1064 if ( is_null( $user ) ) {
1069 $dbw = $this->repo
->getMasterDB();
1070 $dbw->begin( __METHOD__
);
1073 wfProfileIn( __METHOD__
. '-getProps' );
1074 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1075 wfProfileOut( __METHOD__
. '-getProps' );
1078 if ( $timestamp === false ) {
1079 $timestamp = $dbw->timestamp();
1082 $props['description'] = $comment;
1083 $props['user'] = $user->getId();
1084 $props['user_text'] = $user->getName();
1085 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1086 $this->setProps( $props );
1088 # Fail now if the file isn't there
1089 if ( !$this->fileExists
) {
1090 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1091 wfProfileOut( __METHOD__
);
1097 # Test to see if the row exists using INSERT IGNORE
1098 # This avoids race conditions by locking the row until the commit, and also
1099 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1100 $dbw->insert( 'image',
1102 'img_name' => $this->getName(),
1103 'img_size' => $this->size
,
1104 'img_width' => intval( $this->width
),
1105 'img_height' => intval( $this->height
),
1106 'img_bits' => $this->bits
,
1107 'img_media_type' => $this->media_type
,
1108 'img_major_mime' => $this->major_mime
,
1109 'img_minor_mime' => $this->minor_mime
,
1110 'img_timestamp' => $timestamp,
1111 'img_description' => $comment,
1112 'img_user' => $user->getId(),
1113 'img_user_text' => $user->getName(),
1114 'img_metadata' => $this->metadata
,
1115 'img_sha1' => $this->sha1
1120 if ( $dbw->affectedRows() == 0 ) {
1121 # (bug 34993) Note: $oldver can be empty here, if the previous
1122 # version of the file was broken. Allow registration of the new
1123 # version to continue anyway, because that's better than having
1124 # an image that's not fixable by user operations.
1127 # Collision, this is an update of a file
1128 # Insert previous contents into oldimage
1129 $dbw->insertSelect( 'oldimage', 'image',
1131 'oi_name' => 'img_name',
1132 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1133 'oi_size' => 'img_size',
1134 'oi_width' => 'img_width',
1135 'oi_height' => 'img_height',
1136 'oi_bits' => 'img_bits',
1137 'oi_timestamp' => 'img_timestamp',
1138 'oi_description' => 'img_description',
1139 'oi_user' => 'img_user',
1140 'oi_user_text' => 'img_user_text',
1141 'oi_metadata' => 'img_metadata',
1142 'oi_media_type' => 'img_media_type',
1143 'oi_major_mime' => 'img_major_mime',
1144 'oi_minor_mime' => 'img_minor_mime',
1145 'oi_sha1' => 'img_sha1'
1147 array( 'img_name' => $this->getName() ),
1151 # Update the current image row
1152 $dbw->update( 'image',
1154 'img_size' => $this->size
,
1155 'img_width' => intval( $this->width
),
1156 'img_height' => intval( $this->height
),
1157 'img_bits' => $this->bits
,
1158 'img_media_type' => $this->media_type
,
1159 'img_major_mime' => $this->major_mime
,
1160 'img_minor_mime' => $this->minor_mime
,
1161 'img_timestamp' => $timestamp,
1162 'img_description' => $comment,
1163 'img_user' => $user->getId(),
1164 'img_user_text' => $user->getName(),
1165 'img_metadata' => $this->metadata
,
1166 'img_sha1' => $this->sha1
1168 array( 'img_name' => $this->getName() ),
1172 # This is a new file, so update the image count
1173 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1176 $descTitle = $this->getTitle();
1177 $wikiPage = new WikiFilePage( $descTitle );
1178 $wikiPage->setFile( $this );
1181 $log = new LogPage( 'upload' );
1182 $action = $reupload ?
'overwrite' : 'upload';
1183 $logId = $log->addEntry( $action, $descTitle, $comment, array(), $user );
1185 wfProfileIn( __METHOD__
. '-edit' );
1186 $exists = $descTitle->exists();
1189 # Create a null revision
1190 $latest = $descTitle->getLatestRevID();
1191 $nullRevision = Revision
::newNullRevision(
1193 $descTitle->getArticleID(),
1194 $log->getRcComment(),
1197 if (!is_null($nullRevision)) {
1198 $nullRevision->insertOn( $dbw );
1200 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1201 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1205 # Commit the transaction now, in case something goes wrong later
1206 # The most important thing is that files don't get lost, especially archives
1207 # NOTE: once we have support for nested transactions, the commit may be moved
1208 # to after $wikiPage->doEdit has been called.
1209 $dbw->commit( __METHOD__
);
1212 # Invalidate the cache for the description page
1213 $descTitle->invalidateCache();
1214 $descTitle->purgeSquid();
1216 # New file; create the description page.
1217 # There's already a log entry, so don't make a second RC entry
1218 # Squid and file cache for the description page are purged by doEditContent.
1219 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1220 $status = $wikiPage->doEditContent( $content, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
, false, $user );
1222 if ( isset( $status->value
['revision'] ) ) { // XXX; doEdit() uses a transaction
1223 $dbw->begin( __METHOD__
);
1224 $dbw->update( 'logging',
1225 array( 'log_page' => $status->value
['revision']->getPage() ),
1226 array( 'log_id' => $logId ),
1229 $dbw->commit( __METHOD__
); // commit before anything bad can happen
1232 wfProfileOut( __METHOD__
. '-edit' );
1234 # Save to cache and purge the squid
1235 # We shall not saveToCache before the commit since otherwise
1236 # in case of a rollback there is an usable file from memcached
1237 # which in fact doesn't really exist (bug 24978)
1238 $this->saveToCache();
1241 # Delete old thumbnails
1242 wfProfileIn( __METHOD__
. '-purge' );
1243 $this->purgeThumbnails();
1244 wfProfileOut( __METHOD__
. '-purge' );
1246 # Remove the old file from the squid cache
1247 SquidUpdate
::purge( array( $this->getURL() ) );
1250 # Hooks, hooks, the magic of hooks...
1251 wfProfileIn( __METHOD__
. '-hooks' );
1252 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1253 wfProfileOut( __METHOD__
. '-hooks' );
1255 # Invalidate cache for all pages using this file
1256 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1257 $update->doUpdate();
1259 # Invalidate cache for all pages that redirects on this page
1260 $redirs = $this->getTitle()->getRedirectsHere();
1262 foreach ( $redirs as $redir ) {
1263 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1264 $update->doUpdate();
1267 wfProfileOut( __METHOD__
);
1272 * Move or copy a file to its public location. If a file exists at the
1273 * destination, move it to an archive. Returns a FileRepoStatus object with
1274 * the archive name in the "value" member on success.
1276 * The archive name should be passed through to recordUpload for database
1279 * @param $srcPath String: local filesystem path to the source image
1280 * @param $flags Integer: a bitwise combination of:
1281 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1282 * @param $options Array Optional additional parameters
1283 * @return FileRepoStatus object. On success, the value member contains the
1284 * archive name, or an empty string if it was a new file.
1286 function publish( $srcPath, $flags = 0, array $options = array() ) {
1287 return $this->publishTo( $srcPath, $this->getRel(), $flags, $options );
1291 * Move or copy a file to a specified location. Returns a FileRepoStatus
1292 * object with the archive name in the "value" member on success.
1294 * The archive name should be passed through to recordUpload for database
1297 * @param $srcPath String: local filesystem path to the source image
1298 * @param $dstRel String: target relative path
1299 * @param $flags Integer: a bitwise combination of:
1300 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1301 * @param $options Array Optional additional parameters
1302 * @return FileRepoStatus object. On success, the value member contains the
1303 * archive name, or an empty string if it was a new file.
1305 function publishTo( $srcPath, $dstRel, $flags = 0, array $options = array() ) {
1306 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1307 return $this->readOnlyFatalStatus();
1310 $this->lock(); // begin
1312 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1313 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1314 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1315 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1317 if ( $status->value
== 'new' ) {
1318 $status->value
= '';
1320 $status->value
= $archiveName;
1323 $this->unlock(); // done
1328 /** getLinksTo inherited */
1329 /** getExifData inherited */
1330 /** isLocal inherited */
1331 /** wasDeleted inherited */
1334 * Move file to the new title
1336 * Move current, old version and all thumbnails
1337 * to the new filename. Old file is deleted.
1339 * Cache purging is done; checks for validity
1340 * and logging are caller's responsibility
1342 * @param $target Title New file name
1343 * @return FileRepoStatus object.
1345 function move( $target ) {
1346 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1347 return $this->readOnlyFatalStatus();
1350 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1351 $batch = new LocalFileMoveBatch( $this, $target );
1353 $this->lock(); // begin
1354 $batch->addCurrent();
1355 $archiveNames = $batch->addOlds();
1356 $status = $batch->execute();
1357 $this->unlock(); // done
1359 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1361 $this->purgeEverything();
1362 foreach ( $archiveNames as $archiveName ) {
1363 $this->purgeOldThumbnails( $archiveName );
1365 if ( $status->isOK() ) {
1366 // Now switch the object
1367 $this->title
= $target;
1368 // Force regeneration of the name and hashpath
1369 unset( $this->name
);
1370 unset( $this->hashPath
);
1371 // Purge the new image
1372 $this->purgeEverything();
1379 * Delete all versions of the file.
1381 * Moves the files into an archive directory (or deletes them)
1382 * and removes the database rows.
1384 * Cache purging is done; logging is caller's responsibility.
1388 * @return FileRepoStatus object.
1390 function delete( $reason, $suppress = false ) {
1391 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1392 return $this->readOnlyFatalStatus();
1395 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1397 $this->lock(); // begin
1398 $batch->addCurrent();
1399 # Get old version relative paths
1400 $archiveNames = $batch->addOlds();
1401 $status = $batch->execute();
1402 $this->unlock(); // done
1404 if ( $status->isOK() ) {
1405 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1408 $this->purgeEverything();
1409 foreach ( $archiveNames as $archiveName ) {
1410 $this->purgeOldThumbnails( $archiveName );
1417 * Delete an old version of the file.
1419 * Moves the file into an archive directory (or deletes it)
1420 * and removes the database row.
1422 * Cache purging is done; logging is caller's responsibility.
1424 * @param $archiveName String
1425 * @param $reason String
1426 * @param $suppress Boolean
1427 * @throws MWException or FSException on database or file store failure
1428 * @return FileRepoStatus object.
1430 function deleteOld( $archiveName, $reason, $suppress = false ) {
1431 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1432 return $this->readOnlyFatalStatus();
1435 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1437 $this->lock(); // begin
1438 $batch->addOld( $archiveName );
1439 $status = $batch->execute();
1440 $this->unlock(); // done
1442 $this->purgeOldThumbnails( $archiveName );
1443 if ( $status->isOK() ) {
1444 $this->purgeDescription();
1445 $this->purgeHistory();
1452 * Restore all or specified deleted revisions to the given file.
1453 * Permissions and logging are left to the caller.
1455 * May throw database exceptions on error.
1457 * @param $versions array set of record ids of deleted items to restore,
1458 * or empty to restore all revisions.
1459 * @param $unsuppress Boolean
1460 * @return FileRepoStatus
1462 function restore( $versions = array(), $unsuppress = false ) {
1463 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1464 return $this->readOnlyFatalStatus();
1467 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1469 $this->lock(); // begin
1473 $batch->addIds( $versions );
1475 $status = $batch->execute();
1476 if ( $status->isGood() ) {
1477 $cleanupStatus = $batch->cleanup();
1478 $cleanupStatus->successCount
= 0;
1479 $cleanupStatus->failCount
= 0;
1480 $status->merge( $cleanupStatus );
1482 $this->unlock(); // done
1487 /** isMultipage inherited */
1488 /** pageCount inherited */
1489 /** scaleHeight inherited */
1490 /** getImageSize inherited */
1493 * Get the URL of the file description page.
1496 function getDescriptionUrl() {
1497 return $this->title
->getLocalUrl();
1501 * Get the HTML text of the description page
1502 * This is not used by ImagePage for local files, since (among other things)
1503 * it skips the parser cache.
1504 * @return bool|mixed
1506 function getDescriptionText() {
1507 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1508 if ( !$revision ) return false;
1509 $content = $revision->getContent();
1510 if ( !$content ) return false;
1511 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions() );
1512 return $pout->getText();
1518 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1520 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1522 } elseif ( $audience == self
::FOR_THIS_USER
1523 && !$this->userCan( self
::DELETED_COMMENT
, $user ) )
1527 return $this->description
;
1532 * @return bool|string
1534 function getTimestamp() {
1536 return $this->timestamp
;
1542 function getSha1() {
1544 // Initialise now if necessary
1545 if ( $this->sha1
== '' && $this->fileExists
) {
1546 $this->lock(); // begin
1548 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1549 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1550 $dbw = $this->repo
->getMasterDB();
1551 $dbw->update( 'image',
1552 array( 'img_sha1' => $this->sha1
),
1553 array( 'img_name' => $this->getName() ),
1555 $this->saveToCache();
1558 $this->unlock(); // done
1567 function isCacheable() {
1569 return strlen( $this->metadata
) <= self
::CACHE_FIELD_MAX_LEN
; // avoid OOMs
1573 * Start a transaction and lock the image for update
1574 * Increments a reference counter if the lock is already held
1575 * @return boolean True if the image exists, false otherwise
1578 $dbw = $this->repo
->getMasterDB();
1580 if ( !$this->locked
) {
1581 $dbw->begin( __METHOD__
);
1585 return $dbw->selectField( 'image', '1',
1586 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1590 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1591 * the transaction and thereby releases the image lock.
1594 if ( $this->locked
) {
1596 if ( !$this->locked
) {
1597 $dbw = $this->repo
->getMasterDB();
1598 $dbw->commit( __METHOD__
);
1604 * Roll back the DB transaction and mark the image unlocked
1606 function unlockAndRollback() {
1607 $this->locked
= false;
1608 $dbw = $this->repo
->getMasterDB();
1609 $dbw->rollback( __METHOD__
);
1615 protected function readOnlyFatalStatus() {
1616 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1617 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1619 } // LocalFile class
1621 # ------------------------------------------------------------------------------
1624 * Helper class for file deletion
1625 * @ingroup FileAbstraction
1627 class LocalFileDeleteBatch
{
1634 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1639 * @param $reason string
1640 * @param $suppress bool
1642 function __construct( File
$file, $reason = '', $suppress = false ) {
1643 $this->file
= $file;
1644 $this->reason
= $reason;
1645 $this->suppress
= $suppress;
1646 $this->status
= $file->repo
->newGood();
1649 function addCurrent() {
1650 $this->srcRels
['.'] = $this->file
->getRel();
1654 * @param $oldName string
1656 function addOld( $oldName ) {
1657 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1658 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1662 * Add the old versions of the image to the batch
1663 * @return Array List of archive names from old versions
1665 function addOlds() {
1666 $archiveNames = array();
1668 $dbw = $this->file
->repo
->getMasterDB();
1669 $result = $dbw->select( 'oldimage',
1670 array( 'oi_archive_name' ),
1671 array( 'oi_name' => $this->file
->getName() ),
1675 foreach ( $result as $row ) {
1676 $this->addOld( $row->oi_archive_name
);
1677 $archiveNames[] = $row->oi_archive_name
;
1680 return $archiveNames;
1686 function getOldRels() {
1687 if ( !isset( $this->srcRels
['.'] ) ) {
1688 $oldRels =& $this->srcRels
;
1689 $deleteCurrent = false;
1691 $oldRels = $this->srcRels
;
1692 unset( $oldRels['.'] );
1693 $deleteCurrent = true;
1696 return array( $oldRels, $deleteCurrent );
1702 protected function getHashes() {
1704 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1706 if ( $deleteCurrent ) {
1707 $hashes['.'] = $this->file
->getSha1();
1710 if ( count( $oldRels ) ) {
1711 $dbw = $this->file
->repo
->getMasterDB();
1712 $res = $dbw->select(
1714 array( 'oi_archive_name', 'oi_sha1' ),
1715 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1719 foreach ( $res as $row ) {
1720 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1721 // Get the hash from the file
1722 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1723 $props = $this->file
->repo
->getFileProps( $oldUrl );
1725 if ( $props['fileExists'] ) {
1726 // Upgrade the oldimage row
1727 $dbw->update( 'oldimage',
1728 array( 'oi_sha1' => $props['sha1'] ),
1729 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1731 $hashes[$row->oi_archive_name
] = $props['sha1'];
1733 $hashes[$row->oi_archive_name
] = false;
1736 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1741 $missing = array_diff_key( $this->srcRels
, $hashes );
1743 foreach ( $missing as $name => $rel ) {
1744 $this->status
->error( 'filedelete-old-unregistered', $name );
1747 foreach ( $hashes as $name => $hash ) {
1749 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1750 unset( $hashes[$name] );
1757 function doDBInserts() {
1760 $dbw = $this->file
->repo
->getMasterDB();
1761 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1762 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1763 $encReason = $dbw->addQuotes( $this->reason
);
1764 $encGroup = $dbw->addQuotes( 'deleted' );
1765 $ext = $this->file
->getExtension();
1766 $dotExt = $ext === '' ?
'' : ".$ext";
1767 $encExt = $dbw->addQuotes( $dotExt );
1768 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1770 // Bitfields to further suppress the content
1771 if ( $this->suppress
) {
1773 // This should be 15...
1774 $bitfield |
= Revision
::DELETED_TEXT
;
1775 $bitfield |
= Revision
::DELETED_COMMENT
;
1776 $bitfield |
= Revision
::DELETED_USER
;
1777 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1779 $bitfield = 'oi_deleted';
1782 if ( $deleteCurrent ) {
1783 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1784 $where = array( 'img_name' => $this->file
->getName() );
1785 $dbw->insertSelect( 'filearchive', 'image',
1787 'fa_storage_group' => $encGroup,
1788 'fa_storage_key' => "CASE WHEN img_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 : 0,
1794 'fa_name' => 'img_name',
1795 'fa_archive_name' => 'NULL',
1796 'fa_size' => 'img_size',
1797 'fa_width' => 'img_width',
1798 'fa_height' => 'img_height',
1799 'fa_metadata' => 'img_metadata',
1800 'fa_bits' => 'img_bits',
1801 'fa_media_type' => 'img_media_type',
1802 'fa_major_mime' => 'img_major_mime',
1803 'fa_minor_mime' => 'img_minor_mime',
1804 'fa_description' => 'img_description',
1805 'fa_user' => 'img_user',
1806 'fa_user_text' => 'img_user_text',
1807 'fa_timestamp' => 'img_timestamp',
1808 'fa_sha1' => 'img_sha1',
1809 ), $where, __METHOD__
);
1812 if ( count( $oldRels ) ) {
1813 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1815 'oi_name' => $this->file
->getName(),
1816 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1817 $dbw->insertSelect( 'filearchive', 'oldimage',
1819 'fa_storage_group' => $encGroup,
1820 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1821 'fa_deleted_user' => $encUserId,
1822 'fa_deleted_timestamp' => $encTimestamp,
1823 'fa_deleted_reason' => $encReason,
1824 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1826 'fa_name' => 'oi_name',
1827 'fa_archive_name' => 'oi_archive_name',
1828 'fa_size' => 'oi_size',
1829 'fa_width' => 'oi_width',
1830 'fa_height' => 'oi_height',
1831 'fa_metadata' => 'oi_metadata',
1832 'fa_bits' => 'oi_bits',
1833 'fa_media_type' => 'oi_media_type',
1834 'fa_major_mime' => 'oi_major_mime',
1835 'fa_minor_mime' => 'oi_minor_mime',
1836 'fa_description' => 'oi_description',
1837 'fa_user' => 'oi_user',
1838 'fa_user_text' => 'oi_user_text',
1839 'fa_timestamp' => 'oi_timestamp',
1840 'fa_sha1' => 'oi_sha1',
1841 ), $where, __METHOD__
);
1845 function doDBDeletes() {
1846 $dbw = $this->file
->repo
->getMasterDB();
1847 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1849 if ( count( $oldRels ) ) {
1850 $dbw->delete( 'oldimage',
1852 'oi_name' => $this->file
->getName(),
1853 'oi_archive_name' => array_keys( $oldRels )
1857 if ( $deleteCurrent ) {
1858 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1863 * Run the transaction
1864 * @return FileRepoStatus
1866 function execute() {
1867 wfProfileIn( __METHOD__
);
1869 $this->file
->lock();
1870 // Leave private files alone
1871 $privateFiles = array();
1872 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1873 $dbw = $this->file
->repo
->getMasterDB();
1875 if ( !empty( $oldRels ) ) {
1876 $res = $dbw->select( 'oldimage',
1877 array( 'oi_archive_name' ),
1878 array( 'oi_name' => $this->file
->getName(),
1879 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1880 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1883 foreach ( $res as $row ) {
1884 $privateFiles[$row->oi_archive_name
] = 1;
1887 // Prepare deletion batch
1888 $hashes = $this->getHashes();
1889 $this->deletionBatch
= array();
1890 $ext = $this->file
->getExtension();
1891 $dotExt = $ext === '' ?
'' : ".$ext";
1893 foreach ( $this->srcRels
as $name => $srcRel ) {
1894 // Skip files that have no hash (missing source).
1895 // Keep private files where they are.
1896 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1897 $hash = $hashes[$name];
1898 $key = $hash . $dotExt;
1899 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1900 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1904 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1905 // We acquire this lock by running the inserts now, before the file operations.
1907 // This potentially has poor lock contention characteristics -- an alternative
1908 // scheme would be to insert stub filearchive entries with no fa_name and commit
1909 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1910 $this->doDBInserts();
1912 // Removes non-existent file from the batch, so we don't get errors.
1913 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1915 // Execute the file deletion batch
1916 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1918 if ( !$status->isGood() ) {
1919 $this->status
->merge( $status );
1922 if ( !$this->status
->isOK() ) {
1923 // Critical file deletion error
1924 // Roll back inserts, release lock and abort
1925 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1926 $this->file
->unlockAndRollback();
1927 wfProfileOut( __METHOD__
);
1928 return $this->status
;
1931 // Delete image/oldimage rows
1932 $this->doDBDeletes();
1934 // Commit and return
1935 $this->file
->unlock();
1936 wfProfileOut( __METHOD__
);
1938 return $this->status
;
1942 * Removes non-existent files from a deletion batch.
1943 * @param $batch array
1946 function removeNonexistentFiles( $batch ) {
1947 $files = $newBatch = array();
1949 foreach ( $batch as $batchItem ) {
1950 list( $src, $dest ) = $batchItem;
1951 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1954 $result = $this->file
->repo
->fileExistsBatch( $files );
1956 foreach ( $batch as $batchItem ) {
1957 if ( $result[$batchItem[0]] ) {
1958 $newBatch[] = $batchItem;
1966 # ------------------------------------------------------------------------------
1969 * Helper class for file undeletion
1970 * @ingroup FileAbstraction
1972 class LocalFileRestoreBatch
{
1978 var $cleanupBatch, $ids, $all, $unsuppress = false;
1982 * @param $unsuppress bool
1984 function __construct( File
$file, $unsuppress = false ) {
1985 $this->file
= $file;
1986 $this->cleanupBatch
= $this->ids
= array();
1987 $this->ids
= array();
1988 $this->unsuppress
= $unsuppress;
1994 function addId( $fa_id ) {
1995 $this->ids
[] = $fa_id;
1999 * Add a whole lot of files by ID
2001 function addIds( $ids ) {
2002 $this->ids
= array_merge( $this->ids
, $ids );
2006 * Add all revisions of the file
2013 * Run the transaction, except the cleanup batch.
2014 * The cleanup batch should be run in a separate transaction, because it locks different
2015 * rows and there's no need to keep the image row locked while it's acquiring those locks
2016 * The caller may have its own transaction open.
2017 * So we save the batch and let the caller call cleanup()
2018 * @return FileRepoStatus
2020 function execute() {
2023 if ( !$this->all
&& !$this->ids
) {
2025 return $this->file
->repo
->newGood();
2028 $exists = $this->file
->lock();
2029 $dbw = $this->file
->repo
->getMasterDB();
2030 $status = $this->file
->repo
->newGood();
2032 // Fetch all or selected archived revisions for the file,
2033 // sorted from the most recent to the oldest.
2034 $conditions = array( 'fa_name' => $this->file
->getName() );
2036 if ( !$this->all
) {
2037 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
2040 $result = $dbw->select( 'filearchive', '*',
2043 array( 'ORDER BY' => 'fa_timestamp DESC' )
2046 $idsPresent = array();
2047 $storeBatch = array();
2048 $insertBatch = array();
2049 $insertCurrent = false;
2050 $deleteIds = array();
2052 $archiveNames = array();
2054 foreach ( $result as $row ) {
2055 $idsPresent[] = $row->fa_id
;
2057 if ( $row->fa_name
!= $this->file
->getName() ) {
2058 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2059 $status->failCount++
;
2063 if ( $row->fa_storage_key
== '' ) {
2064 // Revision was missing pre-deletion
2065 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2066 $status->failCount++
;
2070 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
2071 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2073 if( isset( $row->fa_sha1
) ) {
2074 $sha1 = $row->fa_sha1
;
2076 // old row, populate from key
2077 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2081 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2082 $sha1 = substr( $sha1, 1 );
2085 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2086 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2087 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2088 ||
is_null( $row->fa_metadata
) ) {
2089 // Refresh our metadata
2090 // Required for a new current revision; nice for older ones too. :)
2091 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2094 'minor_mime' => $row->fa_minor_mime
,
2095 'major_mime' => $row->fa_major_mime
,
2096 'media_type' => $row->fa_media_type
,
2097 'metadata' => $row->fa_metadata
2101 if ( $first && !$exists ) {
2102 // This revision will be published as the new current version
2103 $destRel = $this->file
->getRel();
2104 $insertCurrent = array(
2105 'img_name' => $row->fa_name
,
2106 'img_size' => $row->fa_size
,
2107 'img_width' => $row->fa_width
,
2108 'img_height' => $row->fa_height
,
2109 'img_metadata' => $props['metadata'],
2110 'img_bits' => $row->fa_bits
,
2111 'img_media_type' => $props['media_type'],
2112 'img_major_mime' => $props['major_mime'],
2113 'img_minor_mime' => $props['minor_mime'],
2114 'img_description' => $row->fa_description
,
2115 'img_user' => $row->fa_user
,
2116 'img_user_text' => $row->fa_user_text
,
2117 'img_timestamp' => $row->fa_timestamp
,
2121 // The live (current) version cannot be hidden!
2122 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2123 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2124 $this->cleanupBatch
[] = $row->fa_storage_key
;
2127 $archiveName = $row->fa_archive_name
;
2129 if ( $archiveName == '' ) {
2130 // This was originally a current version; we
2131 // have to devise a new archive name for it.
2132 // Format is <timestamp of archiving>!<name>
2133 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2136 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2138 } while ( isset( $archiveNames[$archiveName] ) );
2141 $archiveNames[$archiveName] = true;
2142 $destRel = $this->file
->getArchiveRel( $archiveName );
2143 $insertBatch[] = array(
2144 'oi_name' => $row->fa_name
,
2145 'oi_archive_name' => $archiveName,
2146 'oi_size' => $row->fa_size
,
2147 'oi_width' => $row->fa_width
,
2148 'oi_height' => $row->fa_height
,
2149 'oi_bits' => $row->fa_bits
,
2150 'oi_description' => $row->fa_description
,
2151 'oi_user' => $row->fa_user
,
2152 'oi_user_text' => $row->fa_user_text
,
2153 'oi_timestamp' => $row->fa_timestamp
,
2154 'oi_metadata' => $props['metadata'],
2155 'oi_media_type' => $props['media_type'],
2156 'oi_major_mime' => $props['major_mime'],
2157 'oi_minor_mime' => $props['minor_mime'],
2158 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2159 'oi_sha1' => $sha1 );
2162 $deleteIds[] = $row->fa_id
;
2164 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2165 // private files can stay where they are
2166 $status->successCount++
;
2168 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2169 $this->cleanupBatch
[] = $row->fa_storage_key
;
2177 // Add a warning to the status object for missing IDs
2178 $missingIds = array_diff( $this->ids
, $idsPresent );
2180 foreach ( $missingIds as $id ) {
2181 $status->error( 'undelete-missing-filearchive', $id );
2184 // Remove missing files from batch, so we don't get errors when undeleting them
2185 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2187 // Run the store batch
2188 // Use the OVERWRITE_SAME flag to smooth over a common error
2189 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2190 $status->merge( $storeStatus );
2192 if ( !$status->isGood() ) {
2193 // Even if some files could be copied, fail entirely as that is the
2194 // easiest thing to do without data loss
2195 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2196 $status->ok
= false;
2197 $this->file
->unlock();
2202 // Run the DB updates
2203 // Because we have locked the image row, key conflicts should be rare.
2204 // If they do occur, we can roll back the transaction at this time with
2205 // no data loss, but leaving unregistered files scattered throughout the
2207 // This is not ideal, which is why it's important to lock the image row.
2208 if ( $insertCurrent ) {
2209 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2212 if ( $insertBatch ) {
2213 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2217 $dbw->delete( 'filearchive',
2218 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2222 // If store batch is empty (all files are missing), deletion is to be considered successful
2223 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2225 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2227 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2229 $this->file
->purgeEverything();
2231 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2232 $this->file
->purgeDescription();
2233 $this->file
->purgeHistory();
2237 $this->file
->unlock();
2243 * Removes non-existent files from a store batch.
2244 * @param $triplets array
2247 function removeNonexistentFiles( $triplets ) {
2248 $files = $filteredTriplets = array();
2249 foreach ( $triplets as $file ) {
2250 $files[$file[0]] = $file[0];
2253 $result = $this->file
->repo
->fileExistsBatch( $files );
2255 foreach ( $triplets as $file ) {
2256 if ( $result[$file[0]] ) {
2257 $filteredTriplets[] = $file;
2261 return $filteredTriplets;
2265 * Removes non-existent files from a cleanup batch.
2266 * @param $batch array
2269 function removeNonexistentFromCleanup( $batch ) {
2270 $files = $newBatch = array();
2271 $repo = $this->file
->repo
;
2273 foreach ( $batch as $file ) {
2274 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2275 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2278 $result = $repo->fileExistsBatch( $files );
2280 foreach ( $batch as $file ) {
2281 if ( $result[$file] ) {
2282 $newBatch[] = $file;
2290 * Delete unused files in the deleted zone.
2291 * This should be called from outside the transaction in which execute() was called.
2292 * @return FileRepoStatus|void
2294 function cleanup() {
2295 if ( !$this->cleanupBatch
) {
2296 return $this->file
->repo
->newGood();
2299 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2301 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2307 * Cleanup a failed batch. The batch was only partially successful, so
2308 * rollback by removing all items that were succesfully copied.
2310 * @param Status $storeStatus
2311 * @param array $storeBatch
2313 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2314 $cleanupBatch = array();
2316 foreach ( $storeStatus->success
as $i => $success ) {
2317 // Check if this item of the batch was successfully copied
2319 // Item was successfully copied and needs to be removed again
2320 // Extract ($dstZone, $dstRel) from the batch
2321 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2324 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2328 # ------------------------------------------------------------------------------
2331 * Helper class for file movement
2332 * @ingroup FileAbstraction
2334 class LocalFileMoveBatch
{
2346 var $cur, $olds, $oldCount, $archive;
2355 * @param Title $target
2357 function __construct( File
$file, Title
$target ) {
2358 $this->file
= $file;
2359 $this->target
= $target;
2360 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2361 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2362 $this->oldName
= $this->file
->getName();
2363 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2364 $this->oldRel
= $this->oldHash
. $this->oldName
;
2365 $this->newRel
= $this->newHash
. $this->newName
;
2366 $this->db
= $file->getRepo()->getMasterDb();
2370 * Add the current image to the batch
2372 function addCurrent() {
2373 $this->cur
= array( $this->oldRel
, $this->newRel
);
2377 * Add the old versions of the image to the batch
2378 * @return Array List of archive names from old versions
2380 function addOlds() {
2381 $archiveBase = 'archive';
2382 $this->olds
= array();
2383 $this->oldCount
= 0;
2384 $archiveNames = array();
2386 $result = $this->db
->select( 'oldimage',
2387 array( 'oi_archive_name', 'oi_deleted' ),
2388 array( 'oi_name' => $this->oldName
),
2392 foreach ( $result as $row ) {
2393 $archiveNames[] = $row->oi_archive_name
;
2394 $oldName = $row->oi_archive_name
;
2395 $bits = explode( '!', $oldName, 2 );
2397 if ( count( $bits ) != 2 ) {
2398 wfDebug( "Old file name missing !: '$oldName' \n" );
2402 list( $timestamp, $filename ) = $bits;
2404 if ( $this->oldName
!= $filename ) {
2405 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2411 // Do we want to add those to oldCount?
2412 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2416 $this->olds
[] = array(
2417 "{$archiveBase}/{$this->oldHash}{$oldName}",
2418 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2422 return $archiveNames;
2427 * @return FileRepoStatus
2429 function execute() {
2430 $repo = $this->file
->repo
;
2431 $status = $repo->newGood();
2433 $triplets = $this->getMoveTriplets();
2434 $triplets = $this->removeNonexistentFiles( $triplets );
2436 $this->file
->lock(); // begin
2437 // Rename the file versions metadata in the DB.
2438 // This implicitly locks the destination file, which avoids race conditions.
2439 // If we moved the files from A -> C before DB updates, another process could
2440 // move files from B -> C at this point, causing storeBatch() to fail and thus
2441 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2442 $statusDb = $this->doDBUpdates();
2443 if ( !$statusDb->isGood() ) {
2444 $this->file
->unlockAndRollback();
2445 $statusDb->ok
= false;
2448 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2450 // Copy the files into their new location.
2451 // If a prior process fataled copying or cleaning up files we tolerate any
2452 // of the existing files if they are identical to the ones being stored.
2453 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2454 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2455 if ( !$statusMove->isGood() ) {
2456 // Delete any files copied over (while the destination is still locked)
2457 $this->cleanupTarget( $triplets );
2458 $this->file
->unlockAndRollback(); // unlocks the destination
2459 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2460 $statusMove->ok
= false;
2463 $this->file
->unlock(); // done
2465 // Everything went ok, remove the source files
2466 $this->cleanupSource( $triplets );
2468 $status->merge( $statusDb );
2469 $status->merge( $statusMove );
2475 * Do the database updates and return a new FileRepoStatus indicating how
2476 * many rows where updated.
2478 * @return FileRepoStatus
2480 function doDBUpdates() {
2481 $repo = $this->file
->repo
;
2482 $status = $repo->newGood();
2485 // Update current image
2488 array( 'img_name' => $this->newName
),
2489 array( 'img_name' => $this->oldName
),
2493 if ( $dbw->affectedRows() ) {
2494 $status->successCount++
;
2496 $status->failCount++
;
2497 $status->fatal( 'imageinvalidfilename' );
2501 // Update old images
2505 'oi_name' => $this->newName
,
2506 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2507 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2509 array( 'oi_name' => $this->oldName
),
2513 $affected = $dbw->affectedRows();
2514 $total = $this->oldCount
;
2515 $status->successCount +
= $affected;
2516 // Bug 34934: $total is based on files that actually exist.
2517 // There may be more DB rows than such files, in which case $affected
2518 // can be greater than $total. We use max() to avoid negatives here.
2519 $status->failCount +
= max( 0, $total - $affected );
2520 if ( $status->failCount
) {
2521 $status->error( 'imageinvalidfilename' );
2528 * Generate triplets for FileRepo::storeBatch().
2531 function getMoveTriplets() {
2532 $moves = array_merge( array( $this->cur
), $this->olds
);
2533 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2535 foreach ( $moves as $move ) {
2536 // $move: (oldRelativePath, newRelativePath)
2537 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2538 $triplets[] = array( $srcUrl, 'public', $move[1] );
2539 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2546 * Removes non-existent files from move batch.
2547 * @param $triplets array
2550 function removeNonexistentFiles( $triplets ) {
2553 foreach ( $triplets as $file ) {
2554 $files[$file[0]] = $file[0];
2557 $result = $this->file
->repo
->fileExistsBatch( $files );
2558 $filteredTriplets = array();
2560 foreach ( $triplets as $file ) {
2561 if ( $result[$file[0]] ) {
2562 $filteredTriplets[] = $file;
2564 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2568 return $filteredTriplets;
2572 * Cleanup a partially moved array of triplets by deleting the target
2573 * files. Called if something went wrong half way.
2575 function cleanupTarget( $triplets ) {
2576 // Create dest pairs from the triplets
2578 foreach ( $triplets as $triplet ) {
2579 // $triplet: (old source virtual URL, dst zone, dest rel)
2580 $pairs[] = array( $triplet[1], $triplet[2] );
2583 $this->file
->repo
->cleanupBatch( $pairs );
2587 * Cleanup a fully moved array of triplets by deleting the source files.
2588 * Called at the end of the move process if everything else went ok.
2590 function cleanupSource( $triplets ) {
2591 // Create source file names from the triplets
2593 foreach ( $triplets as $triplet ) {
2594 $files[] = $triplet[0];
2597 $this->file
->repo
->cleanupBatch( $files );