3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
25 * Bump this number when serialized cache records may be incompatible.
27 define( 'MW_FILE_VERSION', 8 );
30 * Class to represent a local file in the wiki's own database
32 * Provides methods to retrieve paths (physical, logical, URL),
33 * to generate image thumbnails or for uploading.
35 * Note that only the repo object knows what its file class is called. You should
36 * never name a file class explictly outside of the repo class. Instead use the
37 * repo's factory functions to generate file objects, for example:
39 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
41 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
44 * @ingroup FileAbstraction
46 class LocalFile
extends File
{
47 const CACHE_FIELD_MAX_LEN
= 1000;
53 $fileExists, # does the file exist on disk? (loadFromXxx)
54 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
55 $historyRes, # result of the query for the file's history (nextHistoryLine)
58 $bits, # --- returned by getimagesize (loadFromXxx)
60 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
61 $mime, # MIME type, determined by MimeMagic::guessMimeType
62 $major_mime, # Major mime type
63 $minor_mime, # Minor mime type
64 $size, # Size in bytes (loadFromXxx)
65 $metadata, # Handler-specific metadata
66 $timestamp, # Upload timestamp
67 $sha1, # SHA-1 base 36 content hash
68 $user, $user_text, # User, who uploaded the file
69 $description, # Description of current revision of the file
70 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
71 $upgraded, # Whether the row was upgraded on load
72 $locked, # True if the image row is locked
73 $missing, # True if file is not present in file system. Not to be cached in memcached
74 $deleted; # Bitfield akin to rev_deleted
83 protected $repoClass = 'LocalRepo';
86 * Create a LocalFile from a title
87 * Do not call this except from inside a repo class.
89 * Note: $unused param is only here to avoid an E_STRICT
97 static function newFromTitle( $title, $repo, $unused = null ) {
98 return new self( $title, $repo );
102 * Create a LocalFile from a title
103 * Do not call this except from inside a repo class.
110 static function newFromRow( $row, $repo ) {
111 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
112 $file = new self( $title, $repo );
113 $file->loadFromRow( $row );
119 * Create a LocalFile from a SHA-1 key
120 * Do not call this except from inside a repo class.
122 * @param $sha1 string base-36 SHA-1
123 * @param $repo LocalRepo
124 * @param string|bool $timestamp MW_timestamp (optional)
126 * @return bool|LocalFile
128 static function newFromKey( $sha1, $repo, $timestamp = false ) {
129 $dbr = $repo->getSlaveDB();
131 $conds = array( 'img_sha1' => $sha1 );
133 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
136 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
138 return self
::newFromRow( $row, $repo );
145 * Fields in the image table
148 static function selectFields() {
169 * Do not call this except from inside a repo class.
171 function __construct( $title, $repo ) {
172 parent
::__construct( $title, $repo );
174 $this->metadata
= '';
175 $this->historyLine
= 0;
176 $this->historyRes
= null;
177 $this->dataLoaded
= false;
179 $this->assertRepoDefined();
180 $this->assertTitleDefined();
184 * Get the memcached key for the main data for this file, or false if
185 * there is no access to the shared cache.
188 function getCacheKey() {
189 $hashedName = md5( $this->getName() );
191 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
195 * Try to load file metadata from memcached. Returns true on success.
198 function loadFromCache() {
201 wfProfileIn( __METHOD__
);
202 $this->dataLoaded
= false;
203 $key = $this->getCacheKey();
206 wfProfileOut( __METHOD__
);
210 $cachedValues = $wgMemc->get( $key );
212 // Check if the key existed and belongs to this version of MediaWiki
213 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
214 wfDebug( "Pulling file metadata from cache key $key\n" );
215 $this->fileExists
= $cachedValues['fileExists'];
216 if ( $this->fileExists
) {
217 $this->setProps( $cachedValues );
219 $this->dataLoaded
= true;
222 if ( $this->dataLoaded
) {
223 wfIncrStats( 'image_cache_hit' );
225 wfIncrStats( 'image_cache_miss' );
228 wfProfileOut( __METHOD__
);
229 return $this->dataLoaded
;
233 * Save the file metadata to memcached
235 function saveToCache() {
239 $key = $this->getCacheKey();
245 $fields = $this->getCacheFields( '' );
246 $cache = array( 'version' => MW_FILE_VERSION
);
247 $cache['fileExists'] = $this->fileExists
;
249 if ( $this->fileExists
) {
250 foreach ( $fields as $field ) {
251 $cache[$field] = $this->$field;
255 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
259 * Load metadata from the file itself
261 function loadFromFile() {
262 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
263 $this->setProps( $props );
267 * @param $prefix string
270 function getCacheFields( $prefix = 'img_' ) {
271 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
272 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
273 static $results = array();
275 if ( $prefix == '' ) {
279 if ( !isset( $results[$prefix] ) ) {
280 $prefixedFields = array();
281 foreach ( $fields as $field ) {
282 $prefixedFields[] = $prefix . $field;
284 $results[$prefix] = $prefixedFields;
287 return $results[$prefix];
291 * Load file metadata from the DB
293 function loadFromDB() {
294 # Polymorphic function name to distinguish foreign and local fetches
295 $fname = get_class( $this ) . '::' . __FUNCTION__
;
296 wfProfileIn( $fname );
298 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
299 $this->dataLoaded
= true;
301 $dbr = $this->repo
->getMasterDB();
303 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
304 array( 'img_name' => $this->getName() ), $fname );
307 $this->loadFromRow( $row );
309 $this->fileExists
= false;
312 wfProfileOut( $fname );
316 * Decode a row from the database (either object or array) to an array
317 * with timestamps and MIME types decoded, and the field prefix removed.
319 * @param $prefix string
320 * @throws MWException
323 function decodeRow( $row, $prefix = 'img_' ) {
324 $array = (array)$row;
325 $prefixLength = strlen( $prefix );
327 // Sanity check prefix once
328 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
329 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
334 foreach ( $array as $name => $value ) {
335 $decoded[substr( $name, $prefixLength )] = $value;
338 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
340 if ( empty( $decoded['major_mime'] ) ) {
341 $decoded['mime'] = 'unknown/unknown';
343 if ( !$decoded['minor_mime'] ) {
344 $decoded['minor_mime'] = 'unknown';
346 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
349 # Trim zero padding from char/binary field
350 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
356 * Load file metadata from a DB result row
358 function loadFromRow( $row, $prefix = 'img_' ) {
359 $this->dataLoaded
= true;
360 $array = $this->decodeRow( $row, $prefix );
362 foreach ( $array as $name => $value ) {
363 $this->$name = $value;
366 $this->fileExists
= true;
367 $this->maybeUpgradeRow();
371 * Load file metadata from cache or DB, unless already loaded
374 if ( !$this->dataLoaded
) {
375 if ( !$this->loadFromCache() ) {
377 $this->saveToCache();
379 $this->dataLoaded
= true;
384 * Upgrade a row if it needs it
386 function maybeUpgradeRow() {
387 global $wgUpdateCompatibleMetadata;
388 if ( wfReadOnly() ) {
392 if ( is_null( $this->media_type
) ||
393 $this->mime
== 'image/svg'
396 $this->upgraded
= true;
398 $handler = $this->getHandler();
400 $validity = $handler->isMetadataValid( $this, $this->metadata
);
401 if ( $validity === MediaHandler
::METADATA_BAD
402 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
405 $this->upgraded
= true;
411 function getUpgraded() {
412 return $this->upgraded
;
416 * Fix assorted version-related problems with the image row by reloading it from the file
418 function upgradeRow() {
419 wfProfileIn( __METHOD__
);
421 $this->lock(); // begin
423 $this->loadFromFile();
425 # Don't destroy file info of missing files
426 if ( !$this->fileExists
) {
427 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
428 wfProfileOut( __METHOD__
);
432 $dbw = $this->repo
->getMasterDB();
433 list( $major, $minor ) = self
::splitMime( $this->mime
);
435 if ( wfReadOnly() ) {
436 wfProfileOut( __METHOD__
);
439 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
441 $dbw->update( 'image',
443 'img_size' => $this->size
, // sanity
444 'img_width' => $this->width
,
445 'img_height' => $this->height
,
446 'img_bits' => $this->bits
,
447 'img_media_type' => $this->media_type
,
448 'img_major_mime' => $major,
449 'img_minor_mime' => $minor,
450 'img_metadata' => $this->metadata
,
451 'img_sha1' => $this->sha1
,
453 array( 'img_name' => $this->getName() ),
457 $this->saveToCache();
459 $this->unlock(); // done
461 wfProfileOut( __METHOD__
);
465 * Set properties in this object to be equal to those given in the
466 * associative array $info. Only cacheable fields can be set.
468 * If 'mime' is given, it will be split into major_mime/minor_mime.
469 * If major_mime/minor_mime are given, $this->mime will also be set.
471 function setProps( $info ) {
472 $this->dataLoaded
= true;
473 $fields = $this->getCacheFields( '' );
474 $fields[] = 'fileExists';
476 foreach ( $fields as $field ) {
477 if ( isset( $info[$field] ) ) {
478 $this->$field = $info[$field];
482 // Fix up mime fields
483 if ( isset( $info['major_mime'] ) ) {
484 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
485 } elseif ( isset( $info['mime'] ) ) {
486 $this->mime
= $info['mime'];
487 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
491 /** splitMime inherited */
492 /** getName inherited */
493 /** getTitle inherited */
494 /** getURL inherited */
495 /** getViewURL inherited */
496 /** getPath inherited */
497 /** isVisible inhereted */
502 function isMissing() {
503 if ( $this->missing
=== null ) {
504 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
505 $this->missing
= !$fileExists;
507 return $this->missing
;
511 * Return the width of the image
514 * @return bool|int Returns false on error
516 public function getWidth( $page = 1 ) {
519 if ( $this->isMultipage() ) {
520 $dim = $this->getHandler()->getPageDimensions( $this, $page );
522 return $dim['width'];
532 * Return the height of the image
535 * @return bool|int Returns false on error
537 public function getHeight( $page = 1 ) {
540 if ( $this->isMultipage() ) {
541 $dim = $this->getHandler()->getPageDimensions( $this, $page );
543 return $dim['height'];
548 return $this->height
;
553 * Returns ID or name of user who uploaded the file
555 * @param $type string 'text' or 'id'
558 function getUser( $type = 'text' ) {
561 if ( $type == 'text' ) {
562 return $this->user_text
;
563 } elseif ( $type == 'id' ) {
569 * Get handler-specific metadata
572 function getMetadata() {
574 return $this->metadata
;
580 function getBitDepth() {
586 * Return the size of the image file, in bytes
589 public function getSize() {
595 * Returns the mime type of the file.
598 function getMimeType() {
604 * Return the type of the media in the file.
605 * Use the value returned by this function with the MEDIATYPE_xxx constants.
608 function getMediaType() {
610 return $this->media_type
;
613 /** canRender inherited */
614 /** mustRender inherited */
615 /** allowInlineDisplay inherited */
616 /** isSafeFile inherited */
617 /** isTrustedFile inherited */
620 * Returns true if the file exists on disk.
621 * @return boolean Whether file exist on disk.
623 public function exists() {
625 return $this->fileExists
;
628 /** getTransformScript inherited */
629 /** getUnscaledThumb inherited */
630 /** thumbName inherited */
631 /** createThumb inherited */
632 /** transform inherited */
635 * Fix thumbnail files from 1.4 or before, with extreme prejudice
636 * @todo : do we still care about this? Perhaps a maintenance script
637 * can be made instead. Enabling this code results in a serious
638 * RTT regression for wikis without 404 handling.
640 function migrateThumbFile( $thumbName ) {
641 $thumbDir = $this->getThumbPath();
643 /* Old code for bug 2532
644 $thumbPath = "$thumbDir/$thumbName";
645 if ( is_dir( $thumbPath ) ) {
646 // Directory where file should be
647 // This happened occasionally due to broken migration code in 1.5
648 // Rename to broken-*
649 for ( $i = 0; $i < 100 ; $i++ ) {
650 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
651 if ( !file_exists( $broken ) ) {
652 rename( $thumbPath, $broken );
656 // Doesn't exist anymore
662 if ( $this->repo->fileExists( $thumbDir ) ) {
663 // Delete file where directory should be
664 $this->repo->cleanupBatch( array( $thumbDir ) );
669 /** getHandler inherited */
670 /** iconThumb inherited */
671 /** getLastError inherited */
674 * Get all thumbnail names previously generated for this file
675 * @param $archiveName string|bool Name of an archive file, default false
676 * @return array first element is the base dir, then files in that base dir.
678 function getThumbnails( $archiveName = false ) {
679 if ( $archiveName ) {
680 $dir = $this->getArchiveThumbPath( $archiveName );
682 $dir = $this->getThumbPath();
685 $backend = $this->repo
->getBackend();
686 $files = array( $dir );
687 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
688 foreach ( $iterator as $file ) {
696 * Refresh metadata in memcached, but don't touch thumbnails or squid
698 function purgeMetadataCache() {
700 $this->saveToCache();
701 $this->purgeHistory();
705 * Purge the shared history (OldLocalFile) cache
707 function purgeHistory() {
710 $hashedName = md5( $this->getName() );
711 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
713 // Must purge thumbnails for old versions too! bug 30192
714 foreach( $this->getHistory() as $oldFile ) {
715 $oldFile->purgeThumbnails();
719 $wgMemc->delete( $oldKey );
724 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
726 function purgeCache( $options = array() ) {
727 // Refresh metadata cache
728 $this->purgeMetadataCache();
731 $this->purgeThumbnails( $options );
733 // Purge squid cache for this file
734 SquidUpdate
::purge( array( $this->getURL() ) );
738 * Delete cached transformed files for an archived version only.
739 * @param $archiveName string name of the archived file
741 function purgeOldThumbnails( $archiveName ) {
743 wfProfileIn( __METHOD__
);
745 // Get a list of old thumbnails and URLs
746 $files = $this->getThumbnails( $archiveName );
747 $dir = array_shift( $files );
748 $this->purgeThumbList( $dir, $files );
750 // Purge any custom thumbnail caches
751 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
756 foreach( $files as $file ) {
757 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
759 SquidUpdate
::purge( $urls );
762 wfProfileOut( __METHOD__
);
766 * Delete cached transformed files for the current version only.
768 function purgeThumbnails( $options = array() ) {
770 wfProfileIn( __METHOD__
);
773 $files = $this->getThumbnails();
775 // Give media handler a chance to filter the purge list
776 if ( !empty( $options['forThumbRefresh'] ) ) {
777 $handler = $this->getHandler();
779 $handler->filterThumbnailPurgeList( $files, $options );
783 $dir = array_shift( $files );
784 $this->purgeThumbList( $dir, $files );
786 // Purge any custom thumbnail caches
787 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
792 foreach( $files as $file ) {
793 $urls[] = $this->getThumbUrl( $file );
795 SquidUpdate
::purge( $urls );
798 wfProfileOut( __METHOD__
);
802 * Delete a list of thumbnails visible at urls
803 * @param $dir string base dir of the files.
804 * @param $files array of strings: relative filenames (to $dir)
806 protected function purgeThumbList( $dir, $files ) {
807 $fileListDebug = strtr(
808 var_export( $files, true ),
811 wfDebug( __METHOD__
. ": $fileListDebug\n" );
813 $purgeList = array();
814 foreach ( $files as $file ) {
815 # Check that the base file name is part of the thumb name
816 # This is a basic sanity check to avoid erasing unrelated directories
817 if ( strpos( $file, $this->getName() ) !== false
818 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
820 $purgeList[] = "{$dir}/{$file}";
824 # Delete the thumbnails
825 $this->repo
->quickPurgeBatch( $purgeList );
826 # Clear out the thumbnail directory if empty
827 $this->repo
->quickCleanDir( $dir );
830 /** purgeDescription inherited */
831 /** purgeEverything inherited */
840 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
841 $dbr = $this->repo
->getSlaveDB();
842 $tables = array( 'oldimage' );
843 $fields = OldLocalFile
::selectFields();
844 $conds = $opts = $join_conds = array();
845 $eq = $inc ?
'=' : '';
846 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
849 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
853 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
857 $opts['LIMIT'] = $limit;
860 // Search backwards for time > x queries
861 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
862 $opts['ORDER BY'] = "oi_timestamp $order";
863 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
865 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
866 &$conds, &$opts, &$join_conds ) );
868 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
871 foreach ( $res as $row ) {
872 if ( $this->repo
->oldFileFromRowFactory
) {
873 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
875 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
879 if ( $order == 'ASC' ) {
880 $r = array_reverse( $r ); // make sure it ends up descending
887 * Return the history of this file, line by line.
888 * starts with current version, then old versions.
889 * uses $this->historyLine to check which line to return:
890 * 0 return line for current version
891 * 1 query for old versions, return first one
892 * 2, ... return next old version from above query
895 public function nextHistoryLine() {
896 # Polymorphic function name to distinguish foreign and local fetches
897 $fname = get_class( $this ) . '::' . __FUNCTION__
;
899 $dbr = $this->repo
->getSlaveDB();
901 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
902 $this->historyRes
= $dbr->select( 'image',
905 "'' AS oi_archive_name",
909 array( 'img_name' => $this->title
->getDBkey() ),
913 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
914 $this->historyRes
= null;
917 } elseif ( $this->historyLine
== 1 ) {
918 $this->historyRes
= $dbr->select( 'oldimage', '*',
919 array( 'oi_name' => $this->title
->getDBkey() ),
921 array( 'ORDER BY' => 'oi_timestamp DESC' )
924 $this->historyLine ++
;
926 return $dbr->fetchObject( $this->historyRes
);
930 * Reset the history pointer to the first element of the history
932 public function resetHistory() {
933 $this->historyLine
= 0;
935 if ( !is_null( $this->historyRes
) ) {
936 $this->historyRes
= null;
940 /** getHashPath inherited */
941 /** getRel inherited */
942 /** getUrlRel inherited */
943 /** getArchiveRel inherited */
944 /** getArchivePath inherited */
945 /** getThumbPath inherited */
946 /** getArchiveUrl inherited */
947 /** getThumbUrl inherited */
948 /** getArchiveVirtualUrl inherited */
949 /** getThumbVirtualUrl inherited */
950 /** isHashed inherited */
953 * Upload a file and record it in the DB
954 * @param $srcPath String: source storage path or virtual URL
955 * @param $comment String: upload description
956 * @param $pageText String: text to use for the new description page,
957 * if a new description page is created
958 * @param $flags Integer|bool: flags for publish()
959 * @param $props Array|bool: File properties, if known. This can be used to reduce the
960 * upload time when uploading virtual URLs for which the file info
962 * @param $timestamp String|bool: timestamp for img_timestamp, or false to use the current time
963 * @param $user User|null: User object or null to use $wgUser
965 * @return FileRepoStatus object. On success, the value member contains the
966 * archive name, or an empty string if it was a new file.
968 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
971 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
972 return $this->readOnlyFatalStatus();
975 // truncate nicely or the DB will do it for us
976 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
977 $comment = $wgContLang->truncate( $comment, 255 );
978 $this->lock(); // begin
979 $status = $this->publish( $srcPath, $flags );
981 if ( $status->successCount
> 0 ) {
982 # Essentially we are displacing any existing current file and saving
983 # a new current file at the old location. If just the first succeeded,
984 # we still need to displace the current DB entry and put in a new one.
985 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
986 $status->fatal( 'filenotfound', $srcPath );
990 $this->unlock(); // done
996 * Record a file upload in the upload log and the image table
998 * @param $desc string
999 * @param $license string
1000 * @param $copyStatus string
1001 * @param $source string
1002 * @param $watch bool
1003 * @param $timestamp string|bool
1006 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1007 $watch = false, $timestamp = false )
1009 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1011 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp ) ) {
1017 $wgUser->addWatch( $this->getTitle() );
1023 * Record a file upload in the upload log and the image table
1025 * @param $comment string
1026 * @param $pageText string
1027 * @param $props bool|array
1028 * @param $timestamp bool|string
1029 * @param $user null|User
1032 function recordUpload2(
1033 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
1035 wfProfileIn( __METHOD__
);
1037 if ( is_null( $user ) ) {
1042 $dbw = $this->repo
->getMasterDB();
1043 $dbw->begin( __METHOD__
);
1046 wfProfileIn( __METHOD__
. '-getProps' );
1047 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
1048 wfProfileOut( __METHOD__
. '-getProps' );
1051 if ( $timestamp === false ) {
1052 $timestamp = $dbw->timestamp();
1055 $props['description'] = $comment;
1056 $props['user'] = $user->getId();
1057 $props['user_text'] = $user->getName();
1058 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1059 $this->setProps( $props );
1061 # Fail now if the file isn't there
1062 if ( !$this->fileExists
) {
1063 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1064 wfProfileOut( __METHOD__
);
1070 # Test to see if the row exists using INSERT IGNORE
1071 # This avoids race conditions by locking the row until the commit, and also
1072 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1073 $dbw->insert( 'image',
1075 'img_name' => $this->getName(),
1076 'img_size' => $this->size
,
1077 'img_width' => intval( $this->width
),
1078 'img_height' => intval( $this->height
),
1079 'img_bits' => $this->bits
,
1080 'img_media_type' => $this->media_type
,
1081 'img_major_mime' => $this->major_mime
,
1082 'img_minor_mime' => $this->minor_mime
,
1083 'img_timestamp' => $timestamp,
1084 'img_description' => $comment,
1085 'img_user' => $user->getId(),
1086 'img_user_text' => $user->getName(),
1087 'img_metadata' => $this->metadata
,
1088 'img_sha1' => $this->sha1
1093 if ( $dbw->affectedRows() == 0 ) {
1094 # (bug 34993) Note: $oldver can be empty here, if the previous
1095 # version of the file was broken. Allow registration of the new
1096 # version to continue anyway, because that's better than having
1097 # an image that's not fixable by user operations.
1100 # Collision, this is an update of a file
1101 # Insert previous contents into oldimage
1102 $dbw->insertSelect( 'oldimage', 'image',
1104 'oi_name' => 'img_name',
1105 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1106 'oi_size' => 'img_size',
1107 'oi_width' => 'img_width',
1108 'oi_height' => 'img_height',
1109 'oi_bits' => 'img_bits',
1110 'oi_timestamp' => 'img_timestamp',
1111 'oi_description' => 'img_description',
1112 'oi_user' => 'img_user',
1113 'oi_user_text' => 'img_user_text',
1114 'oi_metadata' => 'img_metadata',
1115 'oi_media_type' => 'img_media_type',
1116 'oi_major_mime' => 'img_major_mime',
1117 'oi_minor_mime' => 'img_minor_mime',
1118 'oi_sha1' => 'img_sha1'
1120 array( 'img_name' => $this->getName() ),
1124 # Update the current image row
1125 $dbw->update( 'image',
1127 'img_size' => $this->size
,
1128 'img_width' => intval( $this->width
),
1129 'img_height' => intval( $this->height
),
1130 'img_bits' => $this->bits
,
1131 'img_media_type' => $this->media_type
,
1132 'img_major_mime' => $this->major_mime
,
1133 'img_minor_mime' => $this->minor_mime
,
1134 'img_timestamp' => $timestamp,
1135 'img_description' => $comment,
1136 'img_user' => $user->getId(),
1137 'img_user_text' => $user->getName(),
1138 'img_metadata' => $this->metadata
,
1139 'img_sha1' => $this->sha1
1141 array( 'img_name' => $this->getName() ),
1145 # This is a new file, so update the image count
1146 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
1149 $descTitle = $this->getTitle();
1150 $wikiPage = new WikiFilePage( $descTitle );
1151 $wikiPage->setFile( $this );
1154 $log = new LogPage( 'upload' );
1155 $action = $reupload ?
'overwrite' : 'upload';
1156 $logId = $log->addEntry( $action, $descTitle, $comment, array(), $user );
1158 wfProfileIn( __METHOD__
. '-edit' );
1159 $exists = $descTitle->exists();
1162 # Create a null revision
1163 $latest = $descTitle->getLatestRevID();
1164 $nullRevision = Revision
::newNullRevision(
1166 $descTitle->getArticleID(),
1167 $log->getRcComment(),
1170 if (!is_null($nullRevision)) {
1171 $nullRevision->insertOn( $dbw );
1173 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1174 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1178 # Commit the transaction now, in case something goes wrong later
1179 # The most important thing is that files don't get lost, especially archives
1180 # NOTE: once we have support for nested transactions, the commit may be moved
1181 # to after $wikiPage->doEdit has been called.
1182 $dbw->commit( __METHOD__
);
1185 # Invalidate the cache for the description page
1186 $descTitle->invalidateCache();
1187 $descTitle->purgeSquid();
1189 # New file; create the description page.
1190 # There's already a log entry, so don't make a second RC entry
1191 # Squid and file cache for the description page are purged by doEditContent.
1192 $content = ContentHandler
::makeContent( $pageText, $descTitle );
1193 $status = $wikiPage->doEditContent( $content, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
, false, $user );
1195 if ( isset( $status->value
['revision'] ) ) { // XXX; doEdit() uses a transaction
1197 $dbw->update( 'logging',
1198 array( 'log_page' => $status->value
['revision']->getPage() ),
1199 array( 'log_id' => $logId ),
1202 $dbw->commit(); // commit before anything bad can happen
1205 wfProfileOut( __METHOD__
. '-edit' );
1207 # Save to cache and purge the squid
1208 # We shall not saveToCache before the commit since otherwise
1209 # in case of a rollback there is an usable file from memcached
1210 # which in fact doesn't really exist (bug 24978)
1211 $this->saveToCache();
1214 # Delete old thumbnails
1215 wfProfileIn( __METHOD__
. '-purge' );
1216 $this->purgeThumbnails();
1217 wfProfileOut( __METHOD__
. '-purge' );
1219 # Remove the old file from the squid cache
1220 SquidUpdate
::purge( array( $this->getURL() ) );
1223 # Hooks, hooks, the magic of hooks...
1224 wfProfileIn( __METHOD__
. '-hooks' );
1225 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1226 wfProfileOut( __METHOD__
. '-hooks' );
1228 # Invalidate cache for all pages using this file
1229 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1230 $update->doUpdate();
1232 # Invalidate cache for all pages that redirects on this page
1233 $redirs = $this->getTitle()->getRedirectsHere();
1235 foreach ( $redirs as $redir ) {
1236 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1237 $update->doUpdate();
1240 wfProfileOut( __METHOD__
);
1245 * Move or copy a file to its public location. If a file exists at the
1246 * destination, move it to an archive. Returns a FileRepoStatus object with
1247 * the archive name in the "value" member on success.
1249 * The archive name should be passed through to recordUpload for database
1252 * @param $srcPath String: local filesystem path to the source image
1253 * @param $flags Integer: a bitwise combination of:
1254 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1255 * @return FileRepoStatus object. On success, the value member contains the
1256 * archive name, or an empty string if it was a new file.
1258 function publish( $srcPath, $flags = 0 ) {
1259 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1263 * Move or copy a file to a specified location. Returns a FileRepoStatus
1264 * object with the archive name in the "value" member on success.
1266 * The archive name should be passed through to recordUpload for database
1269 * @param $srcPath String: local filesystem path to the source image
1270 * @param $dstRel String: target relative path
1271 * @param $flags Integer: a bitwise combination of:
1272 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1273 * @return FileRepoStatus object. On success, the value member contains the
1274 * archive name, or an empty string if it was a new file.
1276 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1277 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1278 return $this->readOnlyFatalStatus();
1281 $this->lock(); // begin
1283 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1284 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1285 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1286 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1288 if ( $status->value
== 'new' ) {
1289 $status->value
= '';
1291 $status->value
= $archiveName;
1294 $this->unlock(); // done
1299 /** getLinksTo inherited */
1300 /** getExifData inherited */
1301 /** isLocal inherited */
1302 /** wasDeleted inherited */
1305 * Move file to the new title
1307 * Move current, old version and all thumbnails
1308 * to the new filename. Old file is deleted.
1310 * Cache purging is done; checks for validity
1311 * and logging are caller's responsibility
1313 * @param $target Title New file name
1314 * @return FileRepoStatus object.
1316 function move( $target ) {
1317 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1318 return $this->readOnlyFatalStatus();
1321 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1322 $batch = new LocalFileMoveBatch( $this, $target );
1324 $this->lock(); // begin
1325 $batch->addCurrent();
1326 $archiveNames = $batch->addOlds();
1327 $status = $batch->execute();
1328 $this->unlock(); // done
1330 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1332 $this->purgeEverything();
1333 foreach ( $archiveNames as $archiveName ) {
1334 $this->purgeOldThumbnails( $archiveName );
1336 if ( $status->isOK() ) {
1337 // Now switch the object
1338 $this->title
= $target;
1339 // Force regeneration of the name and hashpath
1340 unset( $this->name
);
1341 unset( $this->hashPath
);
1342 // Purge the new image
1343 $this->purgeEverything();
1350 * Delete all versions of the file.
1352 * Moves the files into an archive directory (or deletes them)
1353 * and removes the database rows.
1355 * Cache purging is done; logging is caller's responsibility.
1359 * @return FileRepoStatus object.
1361 function delete( $reason, $suppress = false ) {
1362 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1363 return $this->readOnlyFatalStatus();
1366 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1368 $this->lock(); // begin
1369 $batch->addCurrent();
1370 # Get old version relative paths
1371 $archiveNames = $batch->addOlds();
1372 $status = $batch->execute();
1373 $this->unlock(); // done
1375 if ( $status->isOK() ) {
1376 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => -1 ) ) );
1379 $this->purgeEverything();
1380 foreach ( $archiveNames as $archiveName ) {
1381 $this->purgeOldThumbnails( $archiveName );
1388 * Delete an old version of the file.
1390 * Moves the file into an archive directory (or deletes it)
1391 * and removes the database row.
1393 * Cache purging is done; logging is caller's responsibility.
1395 * @param $archiveName String
1396 * @param $reason String
1397 * @param $suppress Boolean
1398 * @throws MWException or FSException on database or file store failure
1399 * @return FileRepoStatus object.
1401 function deleteOld( $archiveName, $reason, $suppress = false ) {
1402 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1403 return $this->readOnlyFatalStatus();
1406 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1408 $this->lock(); // begin
1409 $batch->addOld( $archiveName );
1410 $status = $batch->execute();
1411 $this->unlock(); // done
1413 $this->purgeOldThumbnails( $archiveName );
1414 if ( $status->isOK() ) {
1415 $this->purgeDescription();
1416 $this->purgeHistory();
1423 * Restore all or specified deleted revisions to the given file.
1424 * Permissions and logging are left to the caller.
1426 * May throw database exceptions on error.
1428 * @param $versions array set of record ids of deleted items to restore,
1429 * or empty to restore all revisions.
1430 * @param $unsuppress Boolean
1431 * @return FileRepoStatus
1433 function restore( $versions = array(), $unsuppress = false ) {
1434 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1435 return $this->readOnlyFatalStatus();
1438 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1440 $this->lock(); // begin
1444 $batch->addIds( $versions );
1446 $status = $batch->execute();
1447 if ( $status->isGood() ) {
1448 $cleanupStatus = $batch->cleanup();
1449 $cleanupStatus->successCount
= 0;
1450 $cleanupStatus->failCount
= 0;
1451 $status->merge( $cleanupStatus );
1453 $this->unlock(); // done
1458 /** isMultipage inherited */
1459 /** pageCount inherited */
1460 /** scaleHeight inherited */
1461 /** getImageSize inherited */
1464 * Get the URL of the file description page.
1467 function getDescriptionUrl() {
1468 return $this->title
->getLocalUrl();
1472 * Get the HTML text of the description page
1473 * This is not used by ImagePage for local files, since (among other things)
1474 * it skips the parser cache.
1475 * @return bool|mixed
1477 function getDescriptionText() {
1479 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1480 if ( !$revision ) return false;
1481 $content = $revision->getContent();
1482 if ( !$content ) return false;
1483 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions() );
1484 return $pout->getText();
1490 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1492 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1494 } elseif ( $audience == self
::FOR_THIS_USER
1495 && !$this->userCan( self
::DELETED_COMMENT
, $user ) )
1499 return $this->description
;
1504 * @return bool|string
1506 function getTimestamp() {
1508 return $this->timestamp
;
1514 function getSha1() {
1516 // Initialise now if necessary
1517 if ( $this->sha1
== '' && $this->fileExists
) {
1518 $this->lock(); // begin
1520 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1521 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1522 $dbw = $this->repo
->getMasterDB();
1523 $dbw->update( 'image',
1524 array( 'img_sha1' => $this->sha1
),
1525 array( 'img_name' => $this->getName() ),
1527 $this->saveToCache();
1530 $this->unlock(); // done
1539 function isCacheable() {
1541 return strlen( $this->metadata
) <= self
::CACHE_FIELD_MAX_LEN
; // avoid OOMs
1545 * Start a transaction and lock the image for update
1546 * Increments a reference counter if the lock is already held
1547 * @return boolean True if the image exists, false otherwise
1550 $dbw = $this->repo
->getMasterDB();
1552 if ( !$this->locked
) {
1553 $dbw->begin( __METHOD__
);
1557 return $dbw->selectField( 'image', '1',
1558 array( 'img_name' => $this->getName() ), __METHOD__
, array( 'FOR UPDATE' ) );
1562 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1563 * the transaction and thereby releases the image lock.
1566 if ( $this->locked
) {
1568 if ( !$this->locked
) {
1569 $dbw = $this->repo
->getMasterDB();
1570 $dbw->commit( __METHOD__
);
1576 * Roll back the DB transaction and mark the image unlocked
1578 function unlockAndRollback() {
1579 $this->locked
= false;
1580 $dbw = $this->repo
->getMasterDB();
1581 $dbw->rollback( __METHOD__
);
1587 protected function readOnlyFatalStatus() {
1588 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
1589 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
1591 } // LocalFile class
1593 # ------------------------------------------------------------------------------
1596 * Helper class for file deletion
1597 * @ingroup FileAbstraction
1599 class LocalFileDeleteBatch
{
1606 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1611 * @param $reason string
1612 * @param $suppress bool
1614 function __construct( File
$file, $reason = '', $suppress = false ) {
1615 $this->file
= $file;
1616 $this->reason
= $reason;
1617 $this->suppress
= $suppress;
1618 $this->status
= $file->repo
->newGood();
1621 function addCurrent() {
1622 $this->srcRels
['.'] = $this->file
->getRel();
1626 * @param $oldName string
1628 function addOld( $oldName ) {
1629 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1630 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1634 * Add the old versions of the image to the batch
1635 * @return Array List of archive names from old versions
1637 function addOlds() {
1638 $archiveNames = array();
1640 $dbw = $this->file
->repo
->getMasterDB();
1641 $result = $dbw->select( 'oldimage',
1642 array( 'oi_archive_name' ),
1643 array( 'oi_name' => $this->file
->getName() ),
1647 foreach ( $result as $row ) {
1648 $this->addOld( $row->oi_archive_name
);
1649 $archiveNames[] = $row->oi_archive_name
;
1652 return $archiveNames;
1658 function getOldRels() {
1659 if ( !isset( $this->srcRels
['.'] ) ) {
1660 $oldRels =& $this->srcRels
;
1661 $deleteCurrent = false;
1663 $oldRels = $this->srcRels
;
1664 unset( $oldRels['.'] );
1665 $deleteCurrent = true;
1668 return array( $oldRels, $deleteCurrent );
1674 protected function getHashes() {
1676 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1678 if ( $deleteCurrent ) {
1679 $hashes['.'] = $this->file
->getSha1();
1682 if ( count( $oldRels ) ) {
1683 $dbw = $this->file
->repo
->getMasterDB();
1684 $res = $dbw->select(
1686 array( 'oi_archive_name', 'oi_sha1' ),
1687 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1691 foreach ( $res as $row ) {
1692 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1693 // Get the hash from the file
1694 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1695 $props = $this->file
->repo
->getFileProps( $oldUrl );
1697 if ( $props['fileExists'] ) {
1698 // Upgrade the oldimage row
1699 $dbw->update( 'oldimage',
1700 array( 'oi_sha1' => $props['sha1'] ),
1701 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1703 $hashes[$row->oi_archive_name
] = $props['sha1'];
1705 $hashes[$row->oi_archive_name
] = false;
1708 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1713 $missing = array_diff_key( $this->srcRels
, $hashes );
1715 foreach ( $missing as $name => $rel ) {
1716 $this->status
->error( 'filedelete-old-unregistered', $name );
1719 foreach ( $hashes as $name => $hash ) {
1721 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1722 unset( $hashes[$name] );
1729 function doDBInserts() {
1732 $dbw = $this->file
->repo
->getMasterDB();
1733 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1734 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1735 $encReason = $dbw->addQuotes( $this->reason
);
1736 $encGroup = $dbw->addQuotes( 'deleted' );
1737 $ext = $this->file
->getExtension();
1738 $dotExt = $ext === '' ?
'' : ".$ext";
1739 $encExt = $dbw->addQuotes( $dotExt );
1740 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1742 // Bitfields to further suppress the content
1743 if ( $this->suppress
) {
1745 // This should be 15...
1746 $bitfield |
= Revision
::DELETED_TEXT
;
1747 $bitfield |
= Revision
::DELETED_COMMENT
;
1748 $bitfield |
= Revision
::DELETED_USER
;
1749 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1751 $bitfield = 'oi_deleted';
1754 if ( $deleteCurrent ) {
1755 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1756 $where = array( 'img_name' => $this->file
->getName() );
1757 $dbw->insertSelect( 'filearchive', 'image',
1759 'fa_storage_group' => $encGroup,
1760 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1761 'fa_deleted_user' => $encUserId,
1762 'fa_deleted_timestamp' => $encTimestamp,
1763 'fa_deleted_reason' => $encReason,
1764 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1766 'fa_name' => 'img_name',
1767 'fa_archive_name' => 'NULL',
1768 'fa_size' => 'img_size',
1769 'fa_width' => 'img_width',
1770 'fa_height' => 'img_height',
1771 'fa_metadata' => 'img_metadata',
1772 'fa_bits' => 'img_bits',
1773 'fa_media_type' => 'img_media_type',
1774 'fa_major_mime' => 'img_major_mime',
1775 'fa_minor_mime' => 'img_minor_mime',
1776 'fa_description' => 'img_description',
1777 'fa_user' => 'img_user',
1778 'fa_user_text' => 'img_user_text',
1779 'fa_timestamp' => 'img_timestamp',
1780 'fa_sha1' => 'img_sha1',
1781 ), $where, __METHOD__
);
1784 if ( count( $oldRels ) ) {
1785 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1787 'oi_name' => $this->file
->getName(),
1788 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1789 $dbw->insertSelect( 'filearchive', 'oldimage',
1791 'fa_storage_group' => $encGroup,
1792 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1793 'fa_deleted_user' => $encUserId,
1794 'fa_deleted_timestamp' => $encTimestamp,
1795 'fa_deleted_reason' => $encReason,
1796 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1798 'fa_name' => 'oi_name',
1799 'fa_archive_name' => 'oi_archive_name',
1800 'fa_size' => 'oi_size',
1801 'fa_width' => 'oi_width',
1802 'fa_height' => 'oi_height',
1803 'fa_metadata' => 'oi_metadata',
1804 'fa_bits' => 'oi_bits',
1805 'fa_media_type' => 'oi_media_type',
1806 'fa_major_mime' => 'oi_major_mime',
1807 'fa_minor_mime' => 'oi_minor_mime',
1808 'fa_description' => 'oi_description',
1809 'fa_user' => 'oi_user',
1810 'fa_user_text' => 'oi_user_text',
1811 'fa_timestamp' => 'oi_timestamp',
1812 'fa_sha1' => 'oi_sha1',
1813 ), $where, __METHOD__
);
1817 function doDBDeletes() {
1818 $dbw = $this->file
->repo
->getMasterDB();
1819 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1821 if ( count( $oldRels ) ) {
1822 $dbw->delete( 'oldimage',
1824 'oi_name' => $this->file
->getName(),
1825 'oi_archive_name' => array_keys( $oldRels )
1829 if ( $deleteCurrent ) {
1830 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1835 * Run the transaction
1836 * @return FileRepoStatus
1838 function execute() {
1839 wfProfileIn( __METHOD__
);
1841 $this->file
->lock();
1842 // Leave private files alone
1843 $privateFiles = array();
1844 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1845 $dbw = $this->file
->repo
->getMasterDB();
1847 if ( !empty( $oldRels ) ) {
1848 $res = $dbw->select( 'oldimage',
1849 array( 'oi_archive_name' ),
1850 array( 'oi_name' => $this->file
->getName(),
1851 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1852 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1855 foreach ( $res as $row ) {
1856 $privateFiles[$row->oi_archive_name
] = 1;
1859 // Prepare deletion batch
1860 $hashes = $this->getHashes();
1861 $this->deletionBatch
= array();
1862 $ext = $this->file
->getExtension();
1863 $dotExt = $ext === '' ?
'' : ".$ext";
1865 foreach ( $this->srcRels
as $name => $srcRel ) {
1866 // Skip files that have no hash (missing source).
1867 // Keep private files where they are.
1868 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1869 $hash = $hashes[$name];
1870 $key = $hash . $dotExt;
1871 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1872 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1876 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1877 // We acquire this lock by running the inserts now, before the file operations.
1879 // This potentially has poor lock contention characteristics -- an alternative
1880 // scheme would be to insert stub filearchive entries with no fa_name and commit
1881 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1882 $this->doDBInserts();
1884 // Removes non-existent file from the batch, so we don't get errors.
1885 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1887 // Execute the file deletion batch
1888 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1890 if ( !$status->isGood() ) {
1891 $this->status
->merge( $status );
1894 if ( !$this->status
->isOK() ) {
1895 // Critical file deletion error
1896 // Roll back inserts, release lock and abort
1897 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1898 $this->file
->unlockAndRollback();
1899 wfProfileOut( __METHOD__
);
1900 return $this->status
;
1903 // Delete image/oldimage rows
1904 $this->doDBDeletes();
1906 // Commit and return
1907 $this->file
->unlock();
1908 wfProfileOut( __METHOD__
);
1910 return $this->status
;
1914 * Removes non-existent files from a deletion batch.
1915 * @param $batch array
1918 function removeNonexistentFiles( $batch ) {
1919 $files = $newBatch = array();
1921 foreach ( $batch as $batchItem ) {
1922 list( $src, $dest ) = $batchItem;
1923 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1926 $result = $this->file
->repo
->fileExistsBatch( $files );
1928 foreach ( $batch as $batchItem ) {
1929 if ( $result[$batchItem[0]] ) {
1930 $newBatch[] = $batchItem;
1938 # ------------------------------------------------------------------------------
1941 * Helper class for file undeletion
1942 * @ingroup FileAbstraction
1944 class LocalFileRestoreBatch
{
1950 var $cleanupBatch, $ids, $all, $unsuppress = false;
1954 * @param $unsuppress bool
1956 function __construct( File
$file, $unsuppress = false ) {
1957 $this->file
= $file;
1958 $this->cleanupBatch
= $this->ids
= array();
1959 $this->ids
= array();
1960 $this->unsuppress
= $unsuppress;
1966 function addId( $fa_id ) {
1967 $this->ids
[] = $fa_id;
1971 * Add a whole lot of files by ID
1973 function addIds( $ids ) {
1974 $this->ids
= array_merge( $this->ids
, $ids );
1978 * Add all revisions of the file
1985 * Run the transaction, except the cleanup batch.
1986 * The cleanup batch should be run in a separate transaction, because it locks different
1987 * rows and there's no need to keep the image row locked while it's acquiring those locks
1988 * The caller may have its own transaction open.
1989 * So we save the batch and let the caller call cleanup()
1990 * @return FileRepoStatus
1992 function execute() {
1995 if ( !$this->all
&& !$this->ids
) {
1997 return $this->file
->repo
->newGood();
2000 $exists = $this->file
->lock();
2001 $dbw = $this->file
->repo
->getMasterDB();
2002 $status = $this->file
->repo
->newGood();
2004 // Fetch all or selected archived revisions for the file,
2005 // sorted from the most recent to the oldest.
2006 $conditions = array( 'fa_name' => $this->file
->getName() );
2008 if ( !$this->all
) {
2009 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
2012 $result = $dbw->select( 'filearchive', '*',
2015 array( 'ORDER BY' => 'fa_timestamp DESC' )
2018 $idsPresent = array();
2019 $storeBatch = array();
2020 $insertBatch = array();
2021 $insertCurrent = false;
2022 $deleteIds = array();
2024 $archiveNames = array();
2026 foreach ( $result as $row ) {
2027 $idsPresent[] = $row->fa_id
;
2029 if ( $row->fa_name
!= $this->file
->getName() ) {
2030 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2031 $status->failCount++
;
2035 if ( $row->fa_storage_key
== '' ) {
2036 // Revision was missing pre-deletion
2037 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2038 $status->failCount++
;
2042 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
2043 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
2045 if( isset( $row->fa_sha1
) ) {
2046 $sha1 = $row->fa_sha1
;
2048 // old row, populate from key
2049 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2053 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2054 $sha1 = substr( $sha1, 1 );
2057 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2058 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2059 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2060 ||
is_null( $row->fa_metadata
) ) {
2061 // Refresh our metadata
2062 // Required for a new current revision; nice for older ones too. :)
2063 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2066 'minor_mime' => $row->fa_minor_mime
,
2067 'major_mime' => $row->fa_major_mime
,
2068 'media_type' => $row->fa_media_type
,
2069 'metadata' => $row->fa_metadata
2073 if ( $first && !$exists ) {
2074 // This revision will be published as the new current version
2075 $destRel = $this->file
->getRel();
2076 $insertCurrent = array(
2077 'img_name' => $row->fa_name
,
2078 'img_size' => $row->fa_size
,
2079 'img_width' => $row->fa_width
,
2080 'img_height' => $row->fa_height
,
2081 'img_metadata' => $props['metadata'],
2082 'img_bits' => $row->fa_bits
,
2083 'img_media_type' => $props['media_type'],
2084 'img_major_mime' => $props['major_mime'],
2085 'img_minor_mime' => $props['minor_mime'],
2086 'img_description' => $row->fa_description
,
2087 'img_user' => $row->fa_user
,
2088 'img_user_text' => $row->fa_user_text
,
2089 'img_timestamp' => $row->fa_timestamp
,
2093 // The live (current) version cannot be hidden!
2094 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2095 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2096 $this->cleanupBatch
[] = $row->fa_storage_key
;
2099 $archiveName = $row->fa_archive_name
;
2101 if ( $archiveName == '' ) {
2102 // This was originally a current version; we
2103 // have to devise a new archive name for it.
2104 // Format is <timestamp of archiving>!<name>
2105 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2108 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2110 } while ( isset( $archiveNames[$archiveName] ) );
2113 $archiveNames[$archiveName] = true;
2114 $destRel = $this->file
->getArchiveRel( $archiveName );
2115 $insertBatch[] = array(
2116 'oi_name' => $row->fa_name
,
2117 'oi_archive_name' => $archiveName,
2118 'oi_size' => $row->fa_size
,
2119 'oi_width' => $row->fa_width
,
2120 'oi_height' => $row->fa_height
,
2121 'oi_bits' => $row->fa_bits
,
2122 'oi_description' => $row->fa_description
,
2123 'oi_user' => $row->fa_user
,
2124 'oi_user_text' => $row->fa_user_text
,
2125 'oi_timestamp' => $row->fa_timestamp
,
2126 'oi_metadata' => $props['metadata'],
2127 'oi_media_type' => $props['media_type'],
2128 'oi_major_mime' => $props['major_mime'],
2129 'oi_minor_mime' => $props['minor_mime'],
2130 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2131 'oi_sha1' => $sha1 );
2134 $deleteIds[] = $row->fa_id
;
2136 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2137 // private files can stay where they are
2138 $status->successCount++
;
2140 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
2141 $this->cleanupBatch
[] = $row->fa_storage_key
;
2149 // Add a warning to the status object for missing IDs
2150 $missingIds = array_diff( $this->ids
, $idsPresent );
2152 foreach ( $missingIds as $id ) {
2153 $status->error( 'undelete-missing-filearchive', $id );
2156 // Remove missing files from batch, so we don't get errors when undeleting them
2157 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
2159 // Run the store batch
2160 // Use the OVERWRITE_SAME flag to smooth over a common error
2161 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2162 $status->merge( $storeStatus );
2164 if ( !$status->isGood() ) {
2165 // Even if some files could be copied, fail entirely as that is the
2166 // easiest thing to do without data loss
2167 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2168 $status->ok
= false;
2169 $this->file
->unlock();
2174 // Run the DB updates
2175 // Because we have locked the image row, key conflicts should be rare.
2176 // If they do occur, we can roll back the transaction at this time with
2177 // no data loss, but leaving unregistered files scattered throughout the
2179 // This is not ideal, which is why it's important to lock the image row.
2180 if ( $insertCurrent ) {
2181 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2184 if ( $insertBatch ) {
2185 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2189 $dbw->delete( 'filearchive',
2190 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
2194 // If store batch is empty (all files are missing), deletion is to be considered successful
2195 if ( $status->successCount
> 0 ||
!$storeBatch ) {
2197 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2199 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array( 'images' => 1 ) ) );
2201 $this->file
->purgeEverything();
2203 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2204 $this->file
->purgeDescription();
2205 $this->file
->purgeHistory();
2209 $this->file
->unlock();
2215 * Removes non-existent files from a store batch.
2216 * @param $triplets array
2219 function removeNonexistentFiles( $triplets ) {
2220 $files = $filteredTriplets = array();
2221 foreach ( $triplets as $file ) {
2222 $files[$file[0]] = $file[0];
2225 $result = $this->file
->repo
->fileExistsBatch( $files );
2227 foreach ( $triplets as $file ) {
2228 if ( $result[$file[0]] ) {
2229 $filteredTriplets[] = $file;
2233 return $filteredTriplets;
2237 * Removes non-existent files from a cleanup batch.
2238 * @param $batch array
2241 function removeNonexistentFromCleanup( $batch ) {
2242 $files = $newBatch = array();
2243 $repo = $this->file
->repo
;
2245 foreach ( $batch as $file ) {
2246 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2247 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2250 $result = $repo->fileExistsBatch( $files );
2252 foreach ( $batch as $file ) {
2253 if ( $result[$file] ) {
2254 $newBatch[] = $file;
2262 * Delete unused files in the deleted zone.
2263 * This should be called from outside the transaction in which execute() was called.
2264 * @return FileRepoStatus|void
2266 function cleanup() {
2267 if ( !$this->cleanupBatch
) {
2268 return $this->file
->repo
->newGood();
2271 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2273 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2279 * Cleanup a failed batch. The batch was only partially successful, so
2280 * rollback by removing all items that were succesfully copied.
2282 * @param Status $storeStatus
2283 * @param array $storeBatch
2285 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2286 $cleanupBatch = array();
2288 foreach ( $storeStatus->success
as $i => $success ) {
2289 // Check if this item of the batch was successfully copied
2291 // Item was successfully copied and needs to be removed again
2292 // Extract ($dstZone, $dstRel) from the batch
2293 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2296 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2300 # ------------------------------------------------------------------------------
2303 * Helper class for file movement
2304 * @ingroup FileAbstraction
2306 class LocalFileMoveBatch
{
2318 var $cur, $olds, $oldCount, $archive;
2327 * @param Title $target
2329 function __construct( File
$file, Title
$target ) {
2330 $this->file
= $file;
2331 $this->target
= $target;
2332 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2333 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2334 $this->oldName
= $this->file
->getName();
2335 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2336 $this->oldRel
= $this->oldHash
. $this->oldName
;
2337 $this->newRel
= $this->newHash
. $this->newName
;
2338 $this->db
= $file->getRepo()->getMasterDb();
2342 * Add the current image to the batch
2344 function addCurrent() {
2345 $this->cur
= array( $this->oldRel
, $this->newRel
);
2349 * Add the old versions of the image to the batch
2350 * @return Array List of archive names from old versions
2352 function addOlds() {
2353 $archiveBase = 'archive';
2354 $this->olds
= array();
2355 $this->oldCount
= 0;
2356 $archiveNames = array();
2358 $result = $this->db
->select( 'oldimage',
2359 array( 'oi_archive_name', 'oi_deleted' ),
2360 array( 'oi_name' => $this->oldName
),
2364 foreach ( $result as $row ) {
2365 $archiveNames[] = $row->oi_archive_name
;
2366 $oldName = $row->oi_archive_name
;
2367 $bits = explode( '!', $oldName, 2 );
2369 if ( count( $bits ) != 2 ) {
2370 wfDebug( "Old file name missing !: '$oldName' \n" );
2374 list( $timestamp, $filename ) = $bits;
2376 if ( $this->oldName
!= $filename ) {
2377 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2383 // Do we want to add those to oldCount?
2384 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2388 $this->olds
[] = array(
2389 "{$archiveBase}/{$this->oldHash}{$oldName}",
2390 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2394 return $archiveNames;
2399 * @return FileRepoStatus
2401 function execute() {
2402 $repo = $this->file
->repo
;
2403 $status = $repo->newGood();
2405 $triplets = $this->getMoveTriplets();
2406 $triplets = $this->removeNonexistentFiles( $triplets );
2408 $this->file
->lock(); // begin
2409 // Rename the file versions metadata in the DB.
2410 // This implicitly locks the destination file, which avoids race conditions.
2411 // If we moved the files from A -> C before DB updates, another process could
2412 // move files from B -> C at this point, causing storeBatch() to fail and thus
2413 // cleanupTarget() to trigger. It would delete the C files and cause data loss.
2414 $statusDb = $this->doDBUpdates();
2415 if ( !$statusDb->isGood() ) {
2416 $this->file
->unlockAndRollback();
2417 $statusDb->ok
= false;
2420 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2422 // Copy the files into their new location.
2423 // If a prior process fataled copying or cleaning up files we tolerate any
2424 // of the existing files if they are identical to the ones being stored.
2425 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2426 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2427 if ( !$statusMove->isGood() ) {
2428 // Delete any files copied over (while the destination is still locked)
2429 $this->cleanupTarget( $triplets );
2430 $this->file
->unlockAndRollback(); // unlocks the destination
2431 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2432 $statusMove->ok
= false;
2435 $this->file
->unlock(); // done
2437 // Everything went ok, remove the source files
2438 $this->cleanupSource( $triplets );
2440 $status->merge( $statusDb );
2441 $status->merge( $statusMove );
2447 * Do the database updates and return a new FileRepoStatus indicating how
2448 * many rows where updated.
2450 * @return FileRepoStatus
2452 function doDBUpdates() {
2453 $repo = $this->file
->repo
;
2454 $status = $repo->newGood();
2457 // Update current image
2460 array( 'img_name' => $this->newName
),
2461 array( 'img_name' => $this->oldName
),
2465 if ( $dbw->affectedRows() ) {
2466 $status->successCount++
;
2468 $status->failCount++
;
2469 $status->fatal( 'imageinvalidfilename' );
2473 // Update old images
2477 'oi_name' => $this->newName
,
2478 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
2479 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2481 array( 'oi_name' => $this->oldName
),
2485 $affected = $dbw->affectedRows();
2486 $total = $this->oldCount
;
2487 $status->successCount +
= $affected;
2488 // Bug 34934: $total is based on files that actually exist.
2489 // There may be more DB rows than such files, in which case $affected
2490 // can be greater than $total. We use max() to avoid negatives here.
2491 $status->failCount +
= max( 0, $total - $affected );
2492 if ( $status->failCount
) {
2493 $status->error( 'imageinvalidfilename' );
2500 * Generate triplets for FileRepo::storeBatch().
2503 function getMoveTriplets() {
2504 $moves = array_merge( array( $this->cur
), $this->olds
);
2505 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2507 foreach ( $moves as $move ) {
2508 // $move: (oldRelativePath, newRelativePath)
2509 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2510 $triplets[] = array( $srcUrl, 'public', $move[1] );
2511 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2518 * Removes non-existent files from move batch.
2519 * @param $triplets array
2522 function removeNonexistentFiles( $triplets ) {
2525 foreach ( $triplets as $file ) {
2526 $files[$file[0]] = $file[0];
2529 $result = $this->file
->repo
->fileExistsBatch( $files );
2530 $filteredTriplets = array();
2532 foreach ( $triplets as $file ) {
2533 if ( $result[$file[0]] ) {
2534 $filteredTriplets[] = $file;
2536 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2540 return $filteredTriplets;
2544 * Cleanup a partially moved array of triplets by deleting the target
2545 * files. Called if something went wrong half way.
2547 function cleanupTarget( $triplets ) {
2548 // Create dest pairs from the triplets
2550 foreach ( $triplets as $triplet ) {
2551 // $triplet: (old source virtual URL, dst zone, dest rel)
2552 $pairs[] = array( $triplet[1], $triplet[2] );
2555 $this->file
->repo
->cleanupBatch( $pairs );
2559 * Cleanup a fully moved array of triplets by deleting the source files.
2560 * Called at the end of the move process if everything else went ok.
2562 function cleanupSource( $triplets ) {
2563 // Create source file names from the triplets
2565 foreach ( $triplets as $triplet ) {
2566 $files[] = $triplet[0];
2569 $this->file
->repo
->cleanupBatch( $files );