3 * Local file in the wiki's own database
10 * Bump this number when serialized cache records may be incompatible.
12 define( 'MW_FILE_VERSION', 8 );
15 * Class to represent a local file in the wiki's own database
17 * Provides methods to retrieve paths (physical, logical, URL),
18 * to generate image thumbnails or for uploading.
20 * Note that only the repo object knows what its file class is called. You should
21 * never name a file class explictly outside of the repo class. Instead use the
22 * repo's factory functions to generate file objects, for example:
24 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
26 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
31 class LocalFile
extends File
{
36 $fileExists, # does the file exist on disk? (loadFromXxx)
37 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
38 $historyRes, # result of the query for the file's history (nextHistoryLine)
41 $bits, # --- returned by getimagesize (loadFromXxx)
43 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
44 $mime, # MIME type, determined by MimeMagic::guessMimeType
45 $major_mime, # Major mime type
46 $minor_mime, # Minor mime type
47 $size, # Size in bytes (loadFromXxx)
48 $metadata, # Handler-specific metadata
49 $timestamp, # Upload timestamp
50 $sha1, # SHA-1 base 36 content hash
51 $user, $user_text, # User, who uploaded the file
52 $description, # Description of current revision of the file
53 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
54 $upgraded, # Whether the row was upgraded on load
55 $locked, # True if the image row is locked
56 $missing, # True if file is not present in file system. Not to be cached in memcached
57 $deleted; # Bitfield akin to rev_deleted
62 * Create a LocalFile from a title
63 * Do not call this except from inside a repo class.
65 * Note: $unused param is only here to avoid an E_STRICT
73 static function newFromTitle( $title, $repo, $unused = null ) {
74 return new self( $title, $repo );
78 * Create a LocalFile from a title
79 * Do not call this except from inside a repo class.
86 static function newFromRow( $row, $repo ) {
87 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
88 $file = new self( $title, $repo );
89 $file->loadFromRow( $row );
95 * Create a LocalFile from a SHA-1 key
96 * Do not call this except from inside a repo class.
98 * @param $sha1 string base-36 SHA-1
99 * @param $repo LocalRepo
100 * @param string|bool $timestamp MW_timestamp (optional)
102 * @return bool|LocalFile
104 static function newFromKey( $sha1, $repo, $timestamp = false ) {
105 $dbr = $repo->getSlaveDB();
107 $conds = array( 'img_sha1' => $sha1 );
109 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
112 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
114 return self
::newFromRow( $row, $repo );
121 * Fields in the image table
123 static function selectFields() {
144 * Do not call this except from inside a repo class.
146 function __construct( $title, $repo ) {
147 if ( !is_object( $title ) ) {
148 throw new MWException( __CLASS__
. ' constructor given bogus title.' );
151 parent
::__construct( $title, $repo );
153 $this->metadata
= '';
154 $this->historyLine
= 0;
155 $this->historyRes
= null;
156 $this->dataLoaded
= false;
160 * Get the memcached key for the main data for this file, or false if
161 * there is no access to the shared cache.
163 function getCacheKey() {
164 $hashedName = md5( $this->getName() );
166 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
170 * Try to load file metadata from memcached. Returns true on success.
172 function loadFromCache() {
175 wfProfileIn( __METHOD__
);
176 $this->dataLoaded
= false;
177 $key = $this->getCacheKey();
180 wfProfileOut( __METHOD__
);
184 $cachedValues = $wgMemc->get( $key );
186 // Check if the key existed and belongs to this version of MediaWiki
187 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
188 wfDebug( "Pulling file metadata from cache key $key\n" );
189 $this->fileExists
= $cachedValues['fileExists'];
190 if ( $this->fileExists
) {
191 $this->setProps( $cachedValues );
193 $this->dataLoaded
= true;
196 if ( $this->dataLoaded
) {
197 wfIncrStats( 'image_cache_hit' );
199 wfIncrStats( 'image_cache_miss' );
202 wfProfileOut( __METHOD__
);
203 return $this->dataLoaded
;
207 * Save the file metadata to memcached
209 function saveToCache() {
213 $key = $this->getCacheKey();
219 $fields = $this->getCacheFields( '' );
220 $cache = array( 'version' => MW_FILE_VERSION
);
221 $cache['fileExists'] = $this->fileExists
;
223 if ( $this->fileExists
) {
224 foreach ( $fields as $field ) {
225 $cache[$field] = $this->$field;
229 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
233 * Load metadata from the file itself
235 function loadFromFile() {
236 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
239 function getCacheFields( $prefix = 'img_' ) {
240 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
241 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
242 static $results = array();
244 if ( $prefix == '' ) {
248 if ( !isset( $results[$prefix] ) ) {
249 $prefixedFields = array();
250 foreach ( $fields as $field ) {
251 $prefixedFields[] = $prefix . $field;
253 $results[$prefix] = $prefixedFields;
256 return $results[$prefix];
260 * Load file metadata from the DB
262 function loadFromDB() {
263 # Polymorphic function name to distinguish foreign and local fetches
264 $fname = get_class( $this ) . '::' . __FUNCTION__
;
265 wfProfileIn( $fname );
267 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
268 $this->dataLoaded
= true;
270 $dbr = $this->repo
->getMasterDB();
272 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
273 array( 'img_name' => $this->getName() ), $fname );
276 $this->loadFromRow( $row );
278 $this->fileExists
= false;
281 wfProfileOut( $fname );
285 * Decode a row from the database (either object or array) to an array
286 * with timestamps and MIME types decoded, and the field prefix removed.
288 function decodeRow( $row, $prefix = 'img_' ) {
289 $array = (array)$row;
290 $prefixLength = strlen( $prefix );
292 // Sanity check prefix once
293 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
294 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
299 foreach ( $array as $name => $value ) {
300 $decoded[substr( $name, $prefixLength )] = $value;
303 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
305 if ( empty( $decoded['major_mime'] ) ) {
306 $decoded['mime'] = 'unknown/unknown';
308 if ( !$decoded['minor_mime'] ) {
309 $decoded['minor_mime'] = 'unknown';
311 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
314 # Trim zero padding from char/binary field
315 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
321 * Load file metadata from a DB result row
323 function loadFromRow( $row, $prefix = 'img_' ) {
324 $this->dataLoaded
= true;
325 $array = $this->decodeRow( $row, $prefix );
327 foreach ( $array as $name => $value ) {
328 $this->$name = $value;
331 $this->fileExists
= true;
332 $this->maybeUpgradeRow();
336 * Load file metadata from cache or DB, unless already loaded
339 if ( !$this->dataLoaded
) {
340 if ( !$this->loadFromCache() ) {
342 $this->saveToCache();
344 $this->dataLoaded
= true;
349 * Upgrade a row if it needs it
351 function maybeUpgradeRow() {
352 global $wgUpdateCompatibleMetadata;
353 if ( wfReadOnly() ) {
357 if ( is_null( $this->media_type
) ||
358 $this->mime
== 'image/svg'
361 $this->upgraded
= true;
363 $handler = $this->getHandler();
365 $validity = $handler->isMetadataValid( $this, $this->metadata
);
366 if ( $validity === MediaHandler
::METADATA_BAD
367 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
370 $this->upgraded
= true;
376 function getUpgraded() {
377 return $this->upgraded
;
381 * Fix assorted version-related problems with the image row by reloading it from the file
383 function upgradeRow() {
384 wfProfileIn( __METHOD__
);
386 $this->loadFromFile();
388 # Don't destroy file info of missing files
389 if ( !$this->fileExists
) {
390 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
391 wfProfileOut( __METHOD__
);
395 $dbw = $this->repo
->getMasterDB();
396 list( $major, $minor ) = self
::splitMime( $this->mime
);
398 if ( wfReadOnly() ) {
399 wfProfileOut( __METHOD__
);
402 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
404 $dbw->update( 'image',
406 'img_width' => $this->width
,
407 'img_height' => $this->height
,
408 'img_bits' => $this->bits
,
409 'img_media_type' => $this->media_type
,
410 'img_major_mime' => $major,
411 'img_minor_mime' => $minor,
412 'img_metadata' => $this->metadata
,
413 'img_sha1' => $this->sha1
,
414 ), array( 'img_name' => $this->getName() ),
418 $this->saveToCache();
419 wfProfileOut( __METHOD__
);
423 * Set properties in this object to be equal to those given in the
424 * associative array $info. Only cacheable fields can be set.
426 * If 'mime' is given, it will be split into major_mime/minor_mime.
427 * If major_mime/minor_mime are given, $this->mime will also be set.
429 function setProps( $info ) {
430 $this->dataLoaded
= true;
431 $fields = $this->getCacheFields( '' );
432 $fields[] = 'fileExists';
434 foreach ( $fields as $field ) {
435 if ( isset( $info[$field] ) ) {
436 $this->$field = $info[$field];
440 // Fix up mime fields
441 if ( isset( $info['major_mime'] ) ) {
442 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
443 } elseif ( isset( $info['mime'] ) ) {
444 $this->mime
= $info['mime'];
445 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
449 /** splitMime inherited */
450 /** getName inherited */
451 /** getTitle inherited */
452 /** getURL inherited */
453 /** getViewURL inherited */
454 /** getPath inherited */
455 /** isVisible inhereted */
457 function isMissing() {
458 if ( $this->missing
=== null ) {
459 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
460 $this->missing
= !$fileExists;
462 return $this->missing
;
466 * Return the width of the image
468 * Returns false on error
470 public function getWidth( $page = 1 ) {
473 if ( $this->isMultipage() ) {
474 $dim = $this->getHandler()->getPageDimensions( $this, $page );
476 return $dim['width'];
486 * Return the height of the image
488 * Returns false on error
490 public function getHeight( $page = 1 ) {
493 if ( $this->isMultipage() ) {
494 $dim = $this->getHandler()->getPageDimensions( $this, $page );
496 return $dim['height'];
501 return $this->height
;
506 * Returns ID or name of user who uploaded the file
508 * @param $type string 'text' or 'id'
510 function getUser( $type = 'text' ) {
513 if ( $type == 'text' ) {
514 return $this->user_text
;
515 } elseif ( $type == 'id' ) {
521 * Get handler-specific metadata
523 function getMetadata() {
525 return $this->metadata
;
528 function getBitDepth() {
534 * Return the size of the image file, in bytes
536 public function getSize() {
542 * Returns the mime type of the file.
544 function getMimeType() {
550 * Return the type of the media in the file.
551 * Use the value returned by this function with the MEDIATYPE_xxx constants.
553 function getMediaType() {
555 return $this->media_type
;
558 /** canRender inherited */
559 /** mustRender inherited */
560 /** allowInlineDisplay inherited */
561 /** isSafeFile inherited */
562 /** isTrustedFile inherited */
565 * Returns true if the file exists on disk.
566 * @return boolean Whether file exist on disk.
568 public function exists() {
570 return $this->fileExists
;
573 /** getTransformScript inherited */
574 /** getUnscaledThumb inherited */
575 /** thumbName inherited */
576 /** createThumb inherited */
577 /** transform inherited */
580 * Fix thumbnail files from 1.4 or before, with extreme prejudice
582 function migrateThumbFile( $thumbName ) {
583 $thumbDir = $this->getThumbPath();
584 $thumbPath = "$thumbDir/$thumbName";
586 if ( is_dir( $thumbPath ) ) {
587 // Directory where file should be
588 // This happened occasionally due to broken migration code in 1.5
589 // Rename to broken-*
590 for ( $i = 0; $i < 100 ; $i++
) {
591 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
592 if ( !file_exists( $broken ) ) {
593 rename( $thumbPath, $broken );
597 // Doesn't exist anymore
601 if ( is_file( $thumbDir ) ) {
602 // File where directory should be
604 // Doesn't exist anymore
609 /** getHandler inherited */
610 /** iconThumb inherited */
611 /** getLastError inherited */
614 * Get all thumbnail names previously generated for this file
615 * @param $archiveName string|false Name of an archive file
616 * @return array first element is the base dir, then files in that base dir.
618 function getThumbnails( $archiveName = false ) {
621 if ( $archiveName ) {
622 $dir = $this->getArchiveThumbPath( $archiveName );
624 $dir = $this->getThumbPath();
629 if ( is_dir( $dir ) ) {
630 $handle = opendir( $dir );
633 while ( false !== ( $file = readdir( $handle ) ) ) {
634 if ( $file { 0 } != '.' ) {
647 * Refresh metadata in memcached, but don't touch thumbnails or squid
649 function purgeMetadataCache() {
651 $this->saveToCache();
652 $this->purgeHistory();
656 * Purge the shared history (OldLocalFile) cache
658 function purgeHistory() {
661 $hashedName = md5( $this->getName() );
662 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
664 // Must purge thumbnails for old versions too! bug 30192
665 foreach( $this->getHistory() as $oldFile ) {
666 $oldFile->purgeThumbnails();
670 $wgMemc->delete( $oldKey );
675 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
677 function purgeCache( $options = array() ) {
678 // Refresh metadata cache
679 $this->purgeMetadataCache();
682 $this->purgeThumbnails( $options );
684 // Purge squid cache for this file
685 SquidUpdate
::purge( array( $this->getURL() ) );
689 * Delete cached transformed files for archived files
690 * @param $archiveName string name of the archived file
692 function purgeOldThumbnails( $archiveName ) {
694 // get a list of old thumbnails and URLs
695 $files = $this->getThumbnails( $archiveName );
696 $dir = array_shift( $files );
697 $this->purgeThumbList( $dir, $files );
699 // Directory should be empty, delete it too. This will probably suck on
700 // something like NFS or if the directory isn't actually empty, so hide
702 wfSuppressWarnings();
703 if( !rmdir( $dir ) ) {
704 wfDebug( __METHOD__
. ": unable to remove archive directory: $dir\n" );
711 foreach( $files as $file ) {
712 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
714 SquidUpdate
::purge( $urls );
720 * Delete cached transformed files for the current version only.
722 function purgeThumbnails( $options = array() ) {
725 // Get a list of thumbnails and URLs
726 $files = $this->getThumbnails();
728 // Give media handler a chance to filter the purge list
729 $handler = $this->getHandler();
731 $handler->filterThumbnailPurgeList( $files, $options );
734 $dir = array_shift( $files );
735 $this->purgeThumbList( $dir, $files );
740 foreach( $files as $file ) {
741 $urls[] = $this->getThumbUrl( $file );
743 SquidUpdate
::purge( $urls );
748 * Delete a list of thumbnails visible at urls
749 * @param $dir string base dir of the files.
750 * @param $files array of strings: relative filenames (to $dir)
752 function purgeThumbList($dir, $files) {
753 global $wgExcludeFromThumbnailPurge;
755 wfDebug( __METHOD__
. ": " . var_export( $files, true ) . "\n" );
756 foreach ( $files as $file ) {
757 // Only remove files not in the $wgExcludeFromThumbnailPurge configuration variable
758 $ext = pathinfo( "$dir/$file", PATHINFO_EXTENSION
);
759 if ( in_array( $ext, $wgExcludeFromThumbnailPurge ) ) {
763 # Check that the base file name is part of the thumb name
764 # This is a basic sanity check to avoid erasing unrelated directories
765 if ( strpos( $file, $this->getName() ) !== false ) {
766 wfSuppressWarnings();
767 unlink( "$dir/$file" );
773 /** purgeDescription inherited */
774 /** purgeEverything inherited */
776 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
777 $dbr = $this->repo
->getSlaveDB();
778 $tables = array( 'oldimage' );
779 $fields = OldLocalFile
::selectFields();
780 $conds = $opts = $join_conds = array();
781 $eq = $inc ?
'=' : '';
782 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
785 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
789 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
793 $opts['LIMIT'] = $limit;
796 // Search backwards for time > x queries
797 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
798 $opts['ORDER BY'] = "oi_timestamp $order";
799 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
801 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
802 &$conds, &$opts, &$join_conds ) );
804 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
807 foreach ( $res as $row ) {
808 if ( $this->repo
->oldFileFromRowFactory
) {
809 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
811 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
815 if ( $order == 'ASC' ) {
816 $r = array_reverse( $r ); // make sure it ends up descending
823 * Return the history of this file, line by line.
824 * starts with current version, then old versions.
825 * uses $this->historyLine to check which line to return:
826 * 0 return line for current version
827 * 1 query for old versions, return first one
828 * 2, ... return next old version from above query
830 public function nextHistoryLine() {
831 # Polymorphic function name to distinguish foreign and local fetches
832 $fname = get_class( $this ) . '::' . __FUNCTION__
;
834 $dbr = $this->repo
->getSlaveDB();
836 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
837 $this->historyRes
= $dbr->select( 'image',
840 "'' AS oi_archive_name",
844 array( 'img_name' => $this->title
->getDBkey() ),
848 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
849 $this->historyRes
= null;
852 } elseif ( $this->historyLine
== 1 ) {
853 $this->historyRes
= $dbr->select( 'oldimage', '*',
854 array( 'oi_name' => $this->title
->getDBkey() ),
856 array( 'ORDER BY' => 'oi_timestamp DESC' )
859 $this->historyLine ++
;
861 return $dbr->fetchObject( $this->historyRes
);
865 * Reset the history pointer to the first element of the history
867 public function resetHistory() {
868 $this->historyLine
= 0;
870 if ( !is_null( $this->historyRes
) ) {
871 $this->historyRes
= null;
875 /** getHashPath inherited */
876 /** getRel inherited */
877 /** getUrlRel inherited */
878 /** getArchiveRel inherited */
879 /** getArchivePath inherited */
880 /** getThumbPath inherited */
881 /** getArchiveUrl inherited */
882 /** getThumbUrl inherited */
883 /** getArchiveVirtualUrl inherited */
884 /** getThumbVirtualUrl inherited */
885 /** isHashed inherited */
888 * Upload a file and record it in the DB
889 * @param $srcPath String: source path or virtual URL
890 * @param $comment String: upload description
891 * @param $pageText String: text to use for the new description page,
892 * if a new description page is created
893 * @param $flags Integer: flags for publish()
894 * @param $props Array: File properties, if known. This can be used to reduce the
895 * upload time when uploading virtual URLs for which the file info
897 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
898 * @param $user Mixed: User object or null to use $wgUser
900 * @return FileRepoStatus object. On success, the value member contains the
901 * archive name, or an empty string if it was a new file.
903 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
905 $status = $this->publish( $srcPath, $flags );
908 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
909 $status->fatal( 'filenotfound', $srcPath );
919 * Record a file upload in the upload log and the image table
921 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
922 $watch = false, $timestamp = false )
924 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
926 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
932 $wgUser->addWatch( $this->getTitle() );
938 * Record a file upload in the upload log and the image table
940 function recordUpload2(
941 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
943 if ( is_null( $user ) ) {
948 $dbw = $this->repo
->getMasterDB();
952 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
955 if ( $timestamp === false ) {
956 $timestamp = $dbw->timestamp();
959 $props['description'] = $comment;
960 $props['user'] = $user->getId();
961 $props['user_text'] = $user->getName();
962 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
963 $this->setProps( $props );
966 $this->purgeThumbnails();
968 # The file is already on its final location, remove it from the squid cache
969 SquidUpdate
::purge( array( $this->getURL() ) );
971 # Fail now if the file isn't there
972 if ( !$this->fileExists
) {
973 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
979 # Test to see if the row exists using INSERT IGNORE
980 # This avoids race conditions by locking the row until the commit, and also
981 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
982 $dbw->insert( 'image',
984 'img_name' => $this->getName(),
985 'img_size' => $this->size
,
986 'img_width' => intval( $this->width
),
987 'img_height' => intval( $this->height
),
988 'img_bits' => $this->bits
,
989 'img_media_type' => $this->media_type
,
990 'img_major_mime' => $this->major_mime
,
991 'img_minor_mime' => $this->minor_mime
,
992 'img_timestamp' => $timestamp,
993 'img_description' => $comment,
994 'img_user' => $user->getId(),
995 'img_user_text' => $user->getName(),
996 'img_metadata' => $this->metadata
,
997 'img_sha1' => $this->sha1
1003 if ( $dbw->affectedRows() == 0 ) {
1006 # Collision, this is an update of a file
1007 # Insert previous contents into oldimage
1008 $dbw->insertSelect( 'oldimage', 'image',
1010 'oi_name' => 'img_name',
1011 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1012 'oi_size' => 'img_size',
1013 'oi_width' => 'img_width',
1014 'oi_height' => 'img_height',
1015 'oi_bits' => 'img_bits',
1016 'oi_timestamp' => 'img_timestamp',
1017 'oi_description' => 'img_description',
1018 'oi_user' => 'img_user',
1019 'oi_user_text' => 'img_user_text',
1020 'oi_metadata' => 'img_metadata',
1021 'oi_media_type' => 'img_media_type',
1022 'oi_major_mime' => 'img_major_mime',
1023 'oi_minor_mime' => 'img_minor_mime',
1024 'oi_sha1' => 'img_sha1'
1025 ), array( 'img_name' => $this->getName() ), __METHOD__
1028 # Update the current image row
1029 $dbw->update( 'image',
1031 'img_size' => $this->size
,
1032 'img_width' => intval( $this->width
),
1033 'img_height' => intval( $this->height
),
1034 'img_bits' => $this->bits
,
1035 'img_media_type' => $this->media_type
,
1036 'img_major_mime' => $this->major_mime
,
1037 'img_minor_mime' => $this->minor_mime
,
1038 'img_timestamp' => $timestamp,
1039 'img_description' => $comment,
1040 'img_user' => $user->getId(),
1041 'img_user_text' => $user->getName(),
1042 'img_metadata' => $this->metadata
,
1043 'img_sha1' => $this->sha1
1044 ), array( /* WHERE */
1045 'img_name' => $this->getName()
1049 # This is a new file
1050 # Update the image count
1051 $dbw->begin( __METHOD__
);
1054 array( 'ss_images = ss_images+1' ),
1058 $dbw->commit( __METHOD__
);
1061 $descTitle = $this->getTitle();
1062 $article = new ImagePage( $descTitle );
1063 $article->setFile( $this );
1066 $log = new LogPage( 'upload' );
1067 $action = $reupload ?
'overwrite' : 'upload';
1068 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1070 if ( $descTitle->exists() ) {
1071 # Create a null revision
1072 $latest = $descTitle->getLatestRevID();
1073 $nullRevision = Revision
::newNullRevision(
1075 $descTitle->getArticleId(),
1076 $log->getRcComment(),
1079 if (!is_null($nullRevision)) {
1080 $nullRevision->insertOn( $dbw );
1082 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
1083 $article->updateRevisionOn( $dbw, $nullRevision );
1085 # Invalidate the cache for the description page
1086 $descTitle->invalidateCache();
1087 $descTitle->purgeSquid();
1089 # New file; create the description page.
1090 # There's already a log entry, so don't make a second RC entry
1091 # Squid and file cache for the description page are purged by doEdit.
1092 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
1095 # Commit the transaction now, in case something goes wrong later
1096 # The most important thing is that files don't get lost, especially archives
1099 # Save to cache and purge the squid
1100 # We shall not saveToCache before the commit since otherwise
1101 # in case of a rollback there is an usable file from memcached
1102 # which in fact doesn't really exist (bug 24978)
1103 $this->saveToCache();
1105 # Hooks, hooks, the magic of hooks...
1106 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1108 # Invalidate cache for all pages using this file
1109 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1110 $update->doUpdate();
1112 # Invalidate cache for all pages that redirects on this page
1113 $redirs = $this->getTitle()->getRedirectsHere();
1115 foreach ( $redirs as $redir ) {
1116 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1117 $update->doUpdate();
1124 * Move or copy a file to its public location. If a file exists at the
1125 * destination, move it to an archive. Returns a FileRepoStatus object with
1126 * the archive name in the "value" member on success.
1128 * The archive name should be passed through to recordUpload for database
1131 * @param $srcPath String: local filesystem path to the source image
1132 * @param $flags Integer: a bitwise combination of:
1133 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1134 * @return FileRepoStatus object. On success, the value member contains the
1135 * archive name, or an empty string if it was a new file.
1137 function publish( $srcPath, $flags = 0 ) {
1138 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1142 * Move or copy a file to a specified location. Returns a FileRepoStatus
1143 * object with the archive name in the "value" member on success.
1145 * The archive name should be passed through to recordUpload for database
1148 * @param $srcPath String: local filesystem path to the source image
1149 * @param $dstRel String: target relative path
1150 * @param $flags Integer: a bitwise combination of:
1151 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1152 * @return FileRepoStatus object. On success, the value member contains the
1153 * archive name, or an empty string if it was a new file.
1155 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1158 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1159 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1160 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1161 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1163 if ( $status->value
== 'new' ) {
1164 $status->value
= '';
1166 $status->value
= $archiveName;
1174 /** getLinksTo inherited */
1175 /** getExifData inherited */
1176 /** isLocal inherited */
1177 /** wasDeleted inherited */
1180 * Move file to the new title
1182 * Move current, old version and all thumbnails
1183 * to the new filename. Old file is deleted.
1185 * Cache purging is done; checks for validity
1186 * and logging are caller's responsibility
1188 * @param $target Title New file name
1189 * @return FileRepoStatus object.
1191 function move( $target ) {
1192 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1195 $batch = new LocalFileMoveBatch( $this, $target );
1196 $batch->addCurrent();
1199 $status = $batch->execute();
1200 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1202 $this->purgeEverything();
1205 if ( $status->isOk() ) {
1206 // Now switch the object
1207 $this->title
= $target;
1208 // Force regeneration of the name and hashpath
1209 unset( $this->name
);
1210 unset( $this->hashPath
);
1211 // Purge the new image
1212 $this->purgeEverything();
1219 * Delete all versions of the file.
1221 * Moves the files into an archive directory (or deletes them)
1222 * and removes the database rows.
1224 * Cache purging is done; logging is caller's responsibility.
1228 * @return FileRepoStatus object.
1230 function delete( $reason, $suppress = false ) {
1233 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1234 $batch->addCurrent();
1236 # Get old version relative paths
1237 $dbw = $this->repo
->getMasterDB();
1238 $result = $dbw->select( 'oldimage',
1239 array( 'oi_archive_name' ),
1240 array( 'oi_name' => $this->getName() ) );
1241 foreach ( $result as $row ) {
1242 $batch->addOld( $row->oi_archive_name
);
1243 $this->purgeOldThumbnails( $row->oi_archive_name
);
1245 $status = $batch->execute();
1247 if ( $status->ok
) {
1248 // Update site_stats
1249 $site_stats = $dbw->tableName( 'site_stats' );
1250 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1251 $this->purgeEverything();
1260 * Delete an old version of the file.
1262 * Moves the file into an archive directory (or deletes it)
1263 * and removes the database row.
1265 * Cache purging is done; logging is caller's responsibility.
1267 * @param $archiveName String
1268 * @param $reason String
1269 * @param $suppress Boolean
1270 * @throws MWException or FSException on database or file store failure
1271 * @return FileRepoStatus object.
1273 function deleteOld( $archiveName, $reason, $suppress = false ) {
1276 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1277 $batch->addOld( $archiveName );
1278 $this->purgeOldThumbnails( $archiveName );
1279 $status = $batch->execute();
1283 if ( $status->ok
) {
1284 $this->purgeDescription();
1285 $this->purgeHistory();
1292 * Restore all or specified deleted revisions to the given file.
1293 * Permissions and logging are left to the caller.
1295 * May throw database exceptions on error.
1297 * @param $versions set of record ids of deleted items to restore,
1298 * or empty to restore all revisions.
1299 * @param $unsuppress Boolean
1300 * @return FileRepoStatus
1302 function restore( $versions = array(), $unsuppress = false ) {
1303 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1308 $batch->addIds( $versions );
1311 $status = $batch->execute();
1313 if ( !$status->isGood() ) {
1317 $cleanupStatus = $batch->cleanup();
1318 $cleanupStatus->successCount
= 0;
1319 $cleanupStatus->failCount
= 0;
1320 $status->merge( $cleanupStatus );
1325 /** isMultipage inherited */
1326 /** pageCount inherited */
1327 /** scaleHeight inherited */
1328 /** getImageSize inherited */
1331 * Get the URL of the file description page.
1333 function getDescriptionUrl() {
1334 return $this->title
->getLocalUrl();
1338 * Get the HTML text of the description page
1339 * This is not used by ImagePage for local files, since (among other things)
1340 * it skips the parser cache.
1342 function getDescriptionText() {
1344 $revision = Revision
::newFromTitle( $this->title
);
1345 if ( !$revision ) return false;
1346 $text = $revision->getText();
1347 if ( !$text ) return false;
1348 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1349 return $pout->getText();
1352 function getDescription() {
1354 return $this->description
;
1357 function getTimestamp() {
1359 return $this->timestamp
;
1362 function getSha1() {
1364 // Initialise now if necessary
1365 if ( $this->sha1
== '' && $this->fileExists
) {
1366 $this->sha1
= File
::sha1Base36( $this->getPath() );
1367 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1368 $dbw = $this->repo
->getMasterDB();
1369 $dbw->update( 'image',
1370 array( 'img_sha1' => $this->sha1
),
1371 array( 'img_name' => $this->getName() ),
1373 $this->saveToCache();
1381 * Start a transaction and lock the image for update
1382 * Increments a reference counter if the lock is already held
1383 * @return boolean True if the image exists, false otherwise
1386 $dbw = $this->repo
->getMasterDB();
1388 if ( !$this->locked
) {
1393 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1397 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1398 * the transaction and thereby releases the image lock.
1401 if ( $this->locked
) {
1403 if ( !$this->locked
) {
1404 $dbw = $this->repo
->getMasterDB();
1411 * Roll back the DB transaction and mark the image unlocked
1413 function unlockAndRollback() {
1414 $this->locked
= false;
1415 $dbw = $this->repo
->getMasterDB();
1418 } // LocalFile class
1420 # ------------------------------------------------------------------------------
1423 * Helper class for file deletion
1426 class LocalFileDeleteBatch
{
1433 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1436 function __construct( File
$file, $reason = '', $suppress = false ) {
1437 $this->file
= $file;
1438 $this->reason
= $reason;
1439 $this->suppress
= $suppress;
1440 $this->status
= $file->repo
->newGood();
1443 function addCurrent() {
1444 $this->srcRels
['.'] = $this->file
->getRel();
1447 function addOld( $oldName ) {
1448 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1449 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1452 function getOldRels() {
1453 if ( !isset( $this->srcRels
['.'] ) ) {
1454 $oldRels =& $this->srcRels
;
1455 $deleteCurrent = false;
1457 $oldRels = $this->srcRels
;
1458 unset( $oldRels['.'] );
1459 $deleteCurrent = true;
1462 return array( $oldRels, $deleteCurrent );
1465 protected function getHashes() {
1467 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1469 if ( $deleteCurrent ) {
1470 $hashes['.'] = $this->file
->getSha1();
1473 if ( count( $oldRels ) ) {
1474 $dbw = $this->file
->repo
->getMasterDB();
1475 $res = $dbw->select(
1477 array( 'oi_archive_name', 'oi_sha1' ),
1478 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1482 foreach ( $res as $row ) {
1483 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1484 // Get the hash from the file
1485 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1486 $props = $this->file
->repo
->getFileProps( $oldUrl );
1488 if ( $props['fileExists'] ) {
1489 // Upgrade the oldimage row
1490 $dbw->update( 'oldimage',
1491 array( 'oi_sha1' => $props['sha1'] ),
1492 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1494 $hashes[$row->oi_archive_name
] = $props['sha1'];
1496 $hashes[$row->oi_archive_name
] = false;
1499 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1504 $missing = array_diff_key( $this->srcRels
, $hashes );
1506 foreach ( $missing as $name => $rel ) {
1507 $this->status
->error( 'filedelete-old-unregistered', $name );
1510 foreach ( $hashes as $name => $hash ) {
1512 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1513 unset( $hashes[$name] );
1520 function doDBInserts() {
1523 $dbw = $this->file
->repo
->getMasterDB();
1524 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1525 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1526 $encReason = $dbw->addQuotes( $this->reason
);
1527 $encGroup = $dbw->addQuotes( 'deleted' );
1528 $ext = $this->file
->getExtension();
1529 $dotExt = $ext === '' ?
'' : ".$ext";
1530 $encExt = $dbw->addQuotes( $dotExt );
1531 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1533 // Bitfields to further suppress the content
1534 if ( $this->suppress
) {
1536 // This should be 15...
1537 $bitfield |
= Revision
::DELETED_TEXT
;
1538 $bitfield |
= Revision
::DELETED_COMMENT
;
1539 $bitfield |
= Revision
::DELETED_USER
;
1540 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1542 $bitfield = 'oi_deleted';
1545 if ( $deleteCurrent ) {
1546 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1547 $where = array( 'img_name' => $this->file
->getName() );
1548 $dbw->insertSelect( 'filearchive', 'image',
1550 'fa_storage_group' => $encGroup,
1551 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1552 'fa_deleted_user' => $encUserId,
1553 'fa_deleted_timestamp' => $encTimestamp,
1554 'fa_deleted_reason' => $encReason,
1555 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1557 'fa_name' => 'img_name',
1558 'fa_archive_name' => 'NULL',
1559 'fa_size' => 'img_size',
1560 'fa_width' => 'img_width',
1561 'fa_height' => 'img_height',
1562 'fa_metadata' => 'img_metadata',
1563 'fa_bits' => 'img_bits',
1564 'fa_media_type' => 'img_media_type',
1565 'fa_major_mime' => 'img_major_mime',
1566 'fa_minor_mime' => 'img_minor_mime',
1567 'fa_description' => 'img_description',
1568 'fa_user' => 'img_user',
1569 'fa_user_text' => 'img_user_text',
1570 'fa_timestamp' => 'img_timestamp'
1571 ), $where, __METHOD__
);
1574 if ( count( $oldRels ) ) {
1575 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1577 'oi_name' => $this->file
->getName(),
1578 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1579 $dbw->insertSelect( 'filearchive', 'oldimage',
1581 'fa_storage_group' => $encGroup,
1582 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1583 'fa_deleted_user' => $encUserId,
1584 'fa_deleted_timestamp' => $encTimestamp,
1585 'fa_deleted_reason' => $encReason,
1586 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1588 'fa_name' => 'oi_name',
1589 'fa_archive_name' => 'oi_archive_name',
1590 'fa_size' => 'oi_size',
1591 'fa_width' => 'oi_width',
1592 'fa_height' => 'oi_height',
1593 'fa_metadata' => 'oi_metadata',
1594 'fa_bits' => 'oi_bits',
1595 'fa_media_type' => 'oi_media_type',
1596 'fa_major_mime' => 'oi_major_mime',
1597 'fa_minor_mime' => 'oi_minor_mime',
1598 'fa_description' => 'oi_description',
1599 'fa_user' => 'oi_user',
1600 'fa_user_text' => 'oi_user_text',
1601 'fa_timestamp' => 'oi_timestamp',
1602 'fa_deleted' => $bitfield
1603 ), $where, __METHOD__
);
1607 function doDBDeletes() {
1608 $dbw = $this->file
->repo
->getMasterDB();
1609 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1611 if ( count( $oldRels ) ) {
1612 $dbw->delete( 'oldimage',
1614 'oi_name' => $this->file
->getName(),
1615 'oi_archive_name' => array_keys( $oldRels )
1619 if ( $deleteCurrent ) {
1620 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1625 * Run the transaction
1627 function execute() {
1629 wfProfileIn( __METHOD__
);
1631 $this->file
->lock();
1632 // Leave private files alone
1633 $privateFiles = array();
1634 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1635 $dbw = $this->file
->repo
->getMasterDB();
1637 if ( !empty( $oldRels ) ) {
1638 $res = $dbw->select( 'oldimage',
1639 array( 'oi_archive_name' ),
1640 array( 'oi_name' => $this->file
->getName(),
1641 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1642 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1645 foreach ( $res as $row ) {
1646 $privateFiles[$row->oi_archive_name
] = 1;
1649 // Prepare deletion batch
1650 $hashes = $this->getHashes();
1651 $this->deletionBatch
= array();
1652 $ext = $this->file
->getExtension();
1653 $dotExt = $ext === '' ?
'' : ".$ext";
1655 foreach ( $this->srcRels
as $name => $srcRel ) {
1656 // Skip files that have no hash (missing source).
1657 // Keep private files where they are.
1658 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1659 $hash = $hashes[$name];
1660 $key = $hash . $dotExt;
1661 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1662 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1666 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1667 // We acquire this lock by running the inserts now, before the file operations.
1669 // This potentially has poor lock contention characteristics -- an alternative
1670 // scheme would be to insert stub filearchive entries with no fa_name and commit
1671 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1672 $this->doDBInserts();
1674 // Removes non-existent file from the batch, so we don't get errors.
1675 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1677 // Execute the file deletion batch
1678 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1680 if ( !$status->isGood() ) {
1681 $this->status
->merge( $status );
1684 if ( !$this->status
->ok
) {
1685 // Critical file deletion error
1686 // Roll back inserts, release lock and abort
1687 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1688 $this->file
->unlockAndRollback();
1689 wfProfileOut( __METHOD__
);
1690 return $this->status
;
1694 if ( $wgUseSquid ) {
1697 foreach ( $this->srcRels
as $srcRel ) {
1698 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1699 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1701 SquidUpdate
::purge( $urls );
1704 // Delete image/oldimage rows
1705 $this->doDBDeletes();
1707 // Commit and return
1708 $this->file
->unlock();
1709 wfProfileOut( __METHOD__
);
1711 return $this->status
;
1715 * Removes non-existent files from a deletion batch.
1717 function removeNonexistentFiles( $batch ) {
1718 $files = $newBatch = array();
1720 foreach ( $batch as $batchItem ) {
1721 list( $src, $dest ) = $batchItem;
1722 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1725 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1727 foreach ( $batch as $batchItem ) {
1728 if ( $result[$batchItem[0]] ) {
1729 $newBatch[] = $batchItem;
1737 # ------------------------------------------------------------------------------
1740 * Helper class for file undeletion
1743 class LocalFileRestoreBatch
{
1749 var $cleanupBatch, $ids, $all, $unsuppress = false;
1751 function __construct( File
$file, $unsuppress = false ) {
1752 $this->file
= $file;
1753 $this->cleanupBatch
= $this->ids
= array();
1754 $this->ids
= array();
1755 $this->unsuppress
= $unsuppress;
1761 function addId( $fa_id ) {
1762 $this->ids
[] = $fa_id;
1766 * Add a whole lot of files by ID
1768 function addIds( $ids ) {
1769 $this->ids
= array_merge( $this->ids
, $ids );
1773 * Add all revisions of the file
1780 * Run the transaction, except the cleanup batch.
1781 * The cleanup batch should be run in a separate transaction, because it locks different
1782 * rows and there's no need to keep the image row locked while it's acquiring those locks
1783 * The caller may have its own transaction open.
1784 * So we save the batch and let the caller call cleanup()
1786 function execute() {
1789 if ( !$this->all
&& !$this->ids
) {
1791 return $this->file
->repo
->newGood();
1794 $exists = $this->file
->lock();
1795 $dbw = $this->file
->repo
->getMasterDB();
1796 $status = $this->file
->repo
->newGood();
1798 // Fetch all or selected archived revisions for the file,
1799 // sorted from the most recent to the oldest.
1800 $conditions = array( 'fa_name' => $this->file
->getName() );
1802 if ( !$this->all
) {
1803 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1806 $result = $dbw->select( 'filearchive', '*',
1809 array( 'ORDER BY' => 'fa_timestamp DESC' )
1812 $idsPresent = array();
1813 $storeBatch = array();
1814 $insertBatch = array();
1815 $insertCurrent = false;
1816 $deleteIds = array();
1818 $archiveNames = array();
1820 foreach ( $result as $row ) {
1821 $idsPresent[] = $row->fa_id
;
1823 if ( $row->fa_name
!= $this->file
->getName() ) {
1824 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1825 $status->failCount++
;
1829 if ( $row->fa_storage_key
== '' ) {
1830 // Revision was missing pre-deletion
1831 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1832 $status->failCount++
;
1836 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1837 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1839 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1842 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1843 $sha1 = substr( $sha1, 1 );
1846 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1847 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1848 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1849 ||
is_null( $row->fa_metadata
) ) {
1850 // Refresh our metadata
1851 // Required for a new current revision; nice for older ones too. :)
1852 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1855 'minor_mime' => $row->fa_minor_mime
,
1856 'major_mime' => $row->fa_major_mime
,
1857 'media_type' => $row->fa_media_type
,
1858 'metadata' => $row->fa_metadata
1862 if ( $first && !$exists ) {
1863 // This revision will be published as the new current version
1864 $destRel = $this->file
->getRel();
1865 $insertCurrent = array(
1866 'img_name' => $row->fa_name
,
1867 'img_size' => $row->fa_size
,
1868 'img_width' => $row->fa_width
,
1869 'img_height' => $row->fa_height
,
1870 'img_metadata' => $props['metadata'],
1871 'img_bits' => $row->fa_bits
,
1872 'img_media_type' => $props['media_type'],
1873 'img_major_mime' => $props['major_mime'],
1874 'img_minor_mime' => $props['minor_mime'],
1875 'img_description' => $row->fa_description
,
1876 'img_user' => $row->fa_user
,
1877 'img_user_text' => $row->fa_user_text
,
1878 'img_timestamp' => $row->fa_timestamp
,
1882 // The live (current) version cannot be hidden!
1883 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1884 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1885 $this->cleanupBatch
[] = $row->fa_storage_key
;
1888 $archiveName = $row->fa_archive_name
;
1890 if ( $archiveName == '' ) {
1891 // This was originally a current version; we
1892 // have to devise a new archive name for it.
1893 // Format is <timestamp of archiving>!<name>
1894 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1897 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1899 } while ( isset( $archiveNames[$archiveName] ) );
1902 $archiveNames[$archiveName] = true;
1903 $destRel = $this->file
->getArchiveRel( $archiveName );
1904 $insertBatch[] = array(
1905 'oi_name' => $row->fa_name
,
1906 'oi_archive_name' => $archiveName,
1907 'oi_size' => $row->fa_size
,
1908 'oi_width' => $row->fa_width
,
1909 'oi_height' => $row->fa_height
,
1910 'oi_bits' => $row->fa_bits
,
1911 'oi_description' => $row->fa_description
,
1912 'oi_user' => $row->fa_user
,
1913 'oi_user_text' => $row->fa_user_text
,
1914 'oi_timestamp' => $row->fa_timestamp
,
1915 'oi_metadata' => $props['metadata'],
1916 'oi_media_type' => $props['media_type'],
1917 'oi_major_mime' => $props['major_mime'],
1918 'oi_minor_mime' => $props['minor_mime'],
1919 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1920 'oi_sha1' => $sha1 );
1923 $deleteIds[] = $row->fa_id
;
1925 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1926 // private files can stay where they are
1927 $status->successCount++
;
1929 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1930 $this->cleanupBatch
[] = $row->fa_storage_key
;
1938 // Add a warning to the status object for missing IDs
1939 $missingIds = array_diff( $this->ids
, $idsPresent );
1941 foreach ( $missingIds as $id ) {
1942 $status->error( 'undelete-missing-filearchive', $id );
1945 // Remove missing files from batch, so we don't get errors when undeleting them
1946 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1948 // Run the store batch
1949 // Use the OVERWRITE_SAME flag to smooth over a common error
1950 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1951 $status->merge( $storeStatus );
1953 if ( !$status->isGood() ) {
1954 // Even if some files could be copied, fail entirely as that is the
1955 // easiest thing to do without data loss
1956 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1957 $status->ok
= false;
1958 $this->file
->unlock();
1963 // Run the DB updates
1964 // Because we have locked the image row, key conflicts should be rare.
1965 // If they do occur, we can roll back the transaction at this time with
1966 // no data loss, but leaving unregistered files scattered throughout the
1968 // This is not ideal, which is why it's important to lock the image row.
1969 if ( $insertCurrent ) {
1970 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1973 if ( $insertBatch ) {
1974 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1978 $dbw->delete( 'filearchive',
1979 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1983 // If store batch is empty (all files are missing), deletion is to be considered successful
1984 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1986 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1988 // Update site_stats
1989 $site_stats = $dbw->tableName( 'site_stats' );
1990 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1992 $this->file
->purgeEverything();
1994 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1995 $this->file
->purgeDescription();
1996 $this->file
->purgeHistory();
2000 $this->file
->unlock();
2006 * Removes non-existent files from a store batch.
2008 function removeNonexistentFiles( $triplets ) {
2009 $files = $filteredTriplets = array();
2010 foreach ( $triplets as $file )
2011 $files[$file[0]] = $file[0];
2013 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2015 foreach ( $triplets as $file ) {
2016 if ( $result[$file[0]] ) {
2017 $filteredTriplets[] = $file;
2021 return $filteredTriplets;
2025 * Removes non-existent files from a cleanup batch.
2027 function removeNonexistentFromCleanup( $batch ) {
2028 $files = $newBatch = array();
2029 $repo = $this->file
->repo
;
2031 foreach ( $batch as $file ) {
2032 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2033 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2036 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2038 foreach ( $batch as $file ) {
2039 if ( $result[$file] ) {
2040 $newBatch[] = $file;
2048 * Delete unused files in the deleted zone.
2049 * This should be called from outside the transaction in which execute() was called.
2051 function cleanup() {
2052 if ( !$this->cleanupBatch
) {
2053 return $this->file
->repo
->newGood();
2056 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2058 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2064 * Cleanup a failed batch. The batch was only partially successful, so
2065 * rollback by removing all items that were succesfully copied.
2067 * @param Status $storeStatus
2068 * @param array $storeBatch
2070 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2071 $cleanupBatch = array();
2073 foreach ( $storeStatus->success
as $i => $success ) {
2074 // Check if this item of the batch was successfully copied
2076 // Item was successfully copied and needs to be removed again
2077 // Extract ($dstZone, $dstRel) from the batch
2078 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2081 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2085 # ------------------------------------------------------------------------------
2088 * Helper class for file movement
2091 class LocalFileMoveBatch
{
2103 var $cur, $olds, $oldCount, $archive, $db;
2105 function __construct( File
$file, Title
$target ) {
2106 $this->file
= $file;
2107 $this->target
= $target;
2108 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2109 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2110 $this->oldName
= $this->file
->getName();
2111 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2112 $this->oldRel
= $this->oldHash
. $this->oldName
;
2113 $this->newRel
= $this->newHash
. $this->newName
;
2114 $this->db
= $file->repo
->getMasterDb();
2118 * Add the current image to the batch
2120 function addCurrent() {
2121 $this->cur
= array( $this->oldRel
, $this->newRel
);
2125 * Add the old versions of the image to the batch
2127 function addOlds() {
2128 $archiveBase = 'archive';
2129 $this->olds
= array();
2130 $this->oldCount
= 0;
2132 $result = $this->db
->select( 'oldimage',
2133 array( 'oi_archive_name', 'oi_deleted' ),
2134 array( 'oi_name' => $this->oldName
),
2138 foreach ( $result as $row ) {
2139 $oldName = $row->oi_archive_name
;
2140 $bits = explode( '!', $oldName, 2 );
2142 if ( count( $bits ) != 2 ) {
2143 wfDebug( "Old file name missing !: '$oldName' \n" );
2147 list( $timestamp, $filename ) = $bits;
2149 if ( $this->oldName
!= $filename ) {
2150 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2156 // Do we want to add those to oldCount?
2157 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2161 $this->olds
[] = array(
2162 "{$archiveBase}/{$this->oldHash}{$oldName}",
2163 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2171 function execute() {
2172 $repo = $this->file
->repo
;
2173 $status = $repo->newGood();
2174 $triplets = $this->getMoveTriplets();
2176 $triplets = $this->removeNonexistentFiles( $triplets );
2178 // Copy the files into their new location
2179 $statusMove = $repo->storeBatch( $triplets );
2180 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2181 if ( !$statusMove->isGood() ) {
2182 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2183 $this->cleanupTarget( $triplets );
2184 $statusMove->ok
= false;
2189 $statusDb = $this->doDBUpdates();
2190 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2191 if ( !$statusDb->isGood() ) {
2192 $this->db
->rollback();
2193 // Something went wrong with the DB updates, so remove the target files
2194 $this->cleanupTarget( $triplets );
2195 $statusDb->ok
= false;
2198 $this->db
->commit();
2200 // Everything went ok, remove the source files
2201 $this->cleanupSource( $triplets );
2203 $status->merge( $statusDb );
2204 $status->merge( $statusMove );
2210 * Do the database updates and return a new FileRepoStatus indicating how
2211 * many rows where updated.
2213 * @return FileRepoStatus
2215 function doDBUpdates() {
2216 $repo = $this->file
->repo
;
2217 $status = $repo->newGood();
2220 // Update current image
2223 array( 'img_name' => $this->newName
),
2224 array( 'img_name' => $this->oldName
),
2228 if ( $dbw->affectedRows() ) {
2229 $status->successCount++
;
2231 $status->failCount++
;
2232 $status->fatal( 'imageinvalidfilename' );
2236 // Update old images
2240 'oi_name' => $this->newName
,
2241 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2243 array( 'oi_name' => $this->oldName
),
2247 $affected = $dbw->affectedRows();
2248 $total = $this->oldCount
;
2249 $status->successCount +
= $affected;
2250 $status->failCount +
= $total - $affected;
2251 if ( $status->failCount
) {
2252 $status->error( 'imageinvalidfilename' );
2259 * Generate triplets for FSRepo::storeBatch().
2261 function getMoveTriplets() {
2262 $moves = array_merge( array( $this->cur
), $this->olds
);
2263 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2265 foreach ( $moves as $move ) {
2266 // $move: (oldRelativePath, newRelativePath)
2267 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2268 $triplets[] = array( $srcUrl, 'public', $move[1] );
2269 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2276 * Removes non-existent files from move batch.
2278 function removeNonexistentFiles( $triplets ) {
2281 foreach ( $triplets as $file ) {
2282 $files[$file[0]] = $file[0];
2285 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2286 $filteredTriplets = array();
2288 foreach ( $triplets as $file ) {
2289 if ( $result[$file[0]] ) {
2290 $filteredTriplets[] = $file;
2292 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2296 return $filteredTriplets;
2300 * Cleanup a partially moved array of triplets by deleting the target
2301 * files. Called if something went wrong half way.
2303 function cleanupTarget( $triplets ) {
2304 // Create dest pairs from the triplets
2306 foreach ( $triplets as $triplet ) {
2307 $pairs[] = array( $triplet[1], $triplet[2] );
2310 $this->file
->repo
->cleanupBatch( $pairs );
2314 * Cleanup a fully moved array of triplets by deleting the source files.
2315 * Called at the end of the move process if everything else went ok.
2317 function cleanupSource( $triplets ) {
2318 // Create source file names from the triplets
2320 foreach ( $triplets as $triplet ) {
2321 $files[] = $triplet[0];
2324 $this->file
->repo
->cleanupBatch( $files );