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 /** getFullPath inherited */
876 /** getHashPath inherited */
877 /** getRel inherited */
878 /** getUrlRel inherited */
879 /** getArchiveRel inherited */
880 /** getArchivePath inherited */
881 /** getThumbPath inherited */
882 /** getArchiveUrl inherited */
883 /** getThumbUrl inherited */
884 /** getArchiveVirtualUrl inherited */
885 /** getThumbVirtualUrl inherited */
886 /** isHashed inherited */
889 * Upload a file and record it in the DB
890 * @param $srcPath String: source path or virtual URL
891 * @param $comment String: upload description
892 * @param $pageText String: text to use for the new description page,
893 * if a new description page is created
894 * @param $flags Integer: flags for publish()
895 * @param $props Array: File properties, if known. This can be used to reduce the
896 * upload time when uploading virtual URLs for which the file info
898 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
899 * @param $user Mixed: User object or null to use $wgUser
901 * @return FileRepoStatus object. On success, the value member contains the
902 * archive name, or an empty string if it was a new file.
904 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
906 $status = $this->publish( $srcPath, $flags );
909 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
910 $status->fatal( 'filenotfound', $srcPath );
920 * Record a file upload in the upload log and the image table
922 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
923 $watch = false, $timestamp = false )
925 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
927 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
933 $wgUser->addWatch( $this->getTitle() );
939 * Record a file upload in the upload log and the image table
941 function recordUpload2(
942 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
944 if ( is_null( $user ) ) {
949 $dbw = $this->repo
->getMasterDB();
953 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
956 if ( $timestamp === false ) {
957 $timestamp = $dbw->timestamp();
960 $props['description'] = $comment;
961 $props['user'] = $user->getId();
962 $props['user_text'] = $user->getName();
963 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
964 $this->setProps( $props );
967 $this->purgeThumbnails();
969 # The file is already on its final location, remove it from the squid cache
970 SquidUpdate
::purge( array( $this->getURL() ) );
972 # Fail now if the file isn't there
973 if ( !$this->fileExists
) {
974 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
980 # Test to see if the row exists using INSERT IGNORE
981 # This avoids race conditions by locking the row until the commit, and also
982 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
983 $dbw->insert( 'image',
985 'img_name' => $this->getName(),
986 'img_size' => $this->size
,
987 'img_width' => intval( $this->width
),
988 'img_height' => intval( $this->height
),
989 'img_bits' => $this->bits
,
990 'img_media_type' => $this->media_type
,
991 'img_major_mime' => $this->major_mime
,
992 'img_minor_mime' => $this->minor_mime
,
993 'img_timestamp' => $timestamp,
994 'img_description' => $comment,
995 'img_user' => $user->getId(),
996 'img_user_text' => $user->getName(),
997 'img_metadata' => $this->metadata
,
998 'img_sha1' => $this->sha1
1004 if ( $dbw->affectedRows() == 0 ) {
1007 # Collision, this is an update of a file
1008 # Insert previous contents into oldimage
1009 $dbw->insertSelect( 'oldimage', 'image',
1011 'oi_name' => 'img_name',
1012 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1013 'oi_size' => 'img_size',
1014 'oi_width' => 'img_width',
1015 'oi_height' => 'img_height',
1016 'oi_bits' => 'img_bits',
1017 'oi_timestamp' => 'img_timestamp',
1018 'oi_description' => 'img_description',
1019 'oi_user' => 'img_user',
1020 'oi_user_text' => 'img_user_text',
1021 'oi_metadata' => 'img_metadata',
1022 'oi_media_type' => 'img_media_type',
1023 'oi_major_mime' => 'img_major_mime',
1024 'oi_minor_mime' => 'img_minor_mime',
1025 'oi_sha1' => 'img_sha1'
1026 ), array( 'img_name' => $this->getName() ), __METHOD__
1029 # Update the current image row
1030 $dbw->update( 'image',
1032 'img_size' => $this->size
,
1033 'img_width' => intval( $this->width
),
1034 'img_height' => intval( $this->height
),
1035 'img_bits' => $this->bits
,
1036 'img_media_type' => $this->media_type
,
1037 'img_major_mime' => $this->major_mime
,
1038 'img_minor_mime' => $this->minor_mime
,
1039 'img_timestamp' => $timestamp,
1040 'img_description' => $comment,
1041 'img_user' => $user->getId(),
1042 'img_user_text' => $user->getName(),
1043 'img_metadata' => $this->metadata
,
1044 'img_sha1' => $this->sha1
1045 ), array( /* WHERE */
1046 'img_name' => $this->getName()
1050 # This is a new file
1051 # Update the image count
1052 $dbw->begin( __METHOD__
);
1055 array( 'ss_images = ss_images+1' ),
1059 $dbw->commit( __METHOD__
);
1062 $descTitle = $this->getTitle();
1063 $article = new ImagePage( $descTitle );
1064 $article->setFile( $this );
1067 $log = new LogPage( 'upload' );
1068 $action = $reupload ?
'overwrite' : 'upload';
1069 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1071 if ( $descTitle->exists() ) {
1072 # Create a null revision
1073 $latest = $descTitle->getLatestRevID();
1074 $nullRevision = Revision
::newNullRevision(
1076 $descTitle->getArticleId(),
1077 $log->getRcComment(),
1080 if (!is_null($nullRevision)) {
1081 $nullRevision->insertOn( $dbw );
1083 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
1084 $article->updateRevisionOn( $dbw, $nullRevision );
1086 # Invalidate the cache for the description page
1087 $descTitle->invalidateCache();
1088 $descTitle->purgeSquid();
1090 # New file; create the description page.
1091 # There's already a log entry, so don't make a second RC entry
1092 # Squid and file cache for the description page are purged by doEdit.
1093 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
1096 # Commit the transaction now, in case something goes wrong later
1097 # The most important thing is that files don't get lost, especially archives
1100 # Save to cache and purge the squid
1101 # We shall not saveToCache before the commit since otherwise
1102 # in case of a rollback there is an usable file from memcached
1103 # which in fact doesn't really exist (bug 24978)
1104 $this->saveToCache();
1106 # Hooks, hooks, the magic of hooks...
1107 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1109 # Invalidate cache for all pages using this file
1110 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1111 $update->doUpdate();
1113 # Invalidate cache for all pages that redirects on this page
1114 $redirs = $this->getTitle()->getRedirectsHere();
1116 foreach ( $redirs as $redir ) {
1117 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1118 $update->doUpdate();
1125 * Move or copy a file to its public location. If a file exists at the
1126 * destination, move it to an archive. Returns a FileRepoStatus object with
1127 * the archive name in the "value" member on success.
1129 * The archive name should be passed through to recordUpload for database
1132 * @param $srcPath String: local filesystem path to the source image
1133 * @param $flags Integer: a bitwise combination of:
1134 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1135 * @return FileRepoStatus object. On success, the value member contains the
1136 * archive name, or an empty string if it was a new file.
1138 function publish( $srcPath, $flags = 0 ) {
1139 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1143 * Move or copy a file to a specified location. Returns a FileRepoStatus
1144 * object with the archive name in the "value" member on success.
1146 * The archive name should be passed through to recordUpload for database
1149 * @param $srcPath String: local filesystem path to the source image
1150 * @param $dstRel String: target relative path
1151 * @param $flags Integer: a bitwise combination of:
1152 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1153 * @return FileRepoStatus object. On success, the value member contains the
1154 * archive name, or an empty string if it was a new file.
1156 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1159 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1160 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1161 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1162 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1164 if ( $status->value
== 'new' ) {
1165 $status->value
= '';
1167 $status->value
= $archiveName;
1175 /** getLinksTo inherited */
1176 /** getExifData inherited */
1177 /** isLocal inherited */
1178 /** wasDeleted inherited */
1181 * Move file to the new title
1183 * Move current, old version and all thumbnails
1184 * to the new filename. Old file is deleted.
1186 * Cache purging is done; checks for validity
1187 * and logging are caller's responsibility
1189 * @param $target Title New file name
1190 * @return FileRepoStatus object.
1192 function move( $target ) {
1193 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1196 $batch = new LocalFileMoveBatch( $this, $target );
1197 $batch->addCurrent();
1200 $status = $batch->execute();
1201 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1203 $this->purgeEverything();
1206 if ( $status->isOk() ) {
1207 // Now switch the object
1208 $this->title
= $target;
1209 // Force regeneration of the name and hashpath
1210 unset( $this->name
);
1211 unset( $this->hashPath
);
1212 // Purge the new image
1213 $this->purgeEverything();
1220 * Delete all versions of the file.
1222 * Moves the files into an archive directory (or deletes them)
1223 * and removes the database rows.
1225 * Cache purging is done; logging is caller's responsibility.
1229 * @return FileRepoStatus object.
1231 function delete( $reason, $suppress = false ) {
1234 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1235 $batch->addCurrent();
1237 # Get old version relative paths
1238 $dbw = $this->repo
->getMasterDB();
1239 $result = $dbw->select( 'oldimage',
1240 array( 'oi_archive_name' ),
1241 array( 'oi_name' => $this->getName() ) );
1242 foreach ( $result as $row ) {
1243 $batch->addOld( $row->oi_archive_name
);
1244 $this->purgeOldThumbnails( $row->oi_archive_name
);
1246 $status = $batch->execute();
1248 if ( $status->ok
) {
1249 // Update site_stats
1250 $site_stats = $dbw->tableName( 'site_stats' );
1251 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1252 $this->purgeEverything();
1261 * Delete an old version of the file.
1263 * Moves the file into an archive directory (or deletes it)
1264 * and removes the database row.
1266 * Cache purging is done; logging is caller's responsibility.
1268 * @param $archiveName String
1269 * @param $reason String
1270 * @param $suppress Boolean
1271 * @throws MWException or FSException on database or file store failure
1272 * @return FileRepoStatus object.
1274 function deleteOld( $archiveName, $reason, $suppress = false ) {
1277 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1278 $batch->addOld( $archiveName );
1279 $this->purgeOldThumbnails( $archiveName );
1280 $status = $batch->execute();
1284 if ( $status->ok
) {
1285 $this->purgeDescription();
1286 $this->purgeHistory();
1293 * Restore all or specified deleted revisions to the given file.
1294 * Permissions and logging are left to the caller.
1296 * May throw database exceptions on error.
1298 * @param $versions set of record ids of deleted items to restore,
1299 * or empty to restore all revisions.
1300 * @param $unsuppress Boolean
1301 * @return FileRepoStatus
1303 function restore( $versions = array(), $unsuppress = false ) {
1304 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1309 $batch->addIds( $versions );
1312 $status = $batch->execute();
1314 if ( !$status->isGood() ) {
1318 $cleanupStatus = $batch->cleanup();
1319 $cleanupStatus->successCount
= 0;
1320 $cleanupStatus->failCount
= 0;
1321 $status->merge( $cleanupStatus );
1326 /** isMultipage inherited */
1327 /** pageCount inherited */
1328 /** scaleHeight inherited */
1329 /** getImageSize inherited */
1332 * Get the URL of the file description page.
1334 function getDescriptionUrl() {
1335 return $this->title
->getLocalUrl();
1339 * Get the HTML text of the description page
1340 * This is not used by ImagePage for local files, since (among other things)
1341 * it skips the parser cache.
1343 function getDescriptionText() {
1345 $revision = Revision
::newFromTitle( $this->title
);
1346 if ( !$revision ) return false;
1347 $text = $revision->getText();
1348 if ( !$text ) return false;
1349 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1350 return $pout->getText();
1353 function getDescription() {
1355 return $this->description
;
1358 function getTimestamp() {
1360 return $this->timestamp
;
1363 function getSha1() {
1365 // Initialise now if necessary
1366 if ( $this->sha1
== '' && $this->fileExists
) {
1367 $this->sha1
= File
::sha1Base36( $this->getPath() );
1368 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1369 $dbw = $this->repo
->getMasterDB();
1370 $dbw->update( 'image',
1371 array( 'img_sha1' => $this->sha1
),
1372 array( 'img_name' => $this->getName() ),
1374 $this->saveToCache();
1382 * Start a transaction and lock the image for update
1383 * Increments a reference counter if the lock is already held
1384 * @return boolean True if the image exists, false otherwise
1387 $dbw = $this->repo
->getMasterDB();
1389 if ( !$this->locked
) {
1394 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1398 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1399 * the transaction and thereby releases the image lock.
1402 if ( $this->locked
) {
1404 if ( !$this->locked
) {
1405 $dbw = $this->repo
->getMasterDB();
1412 * Roll back the DB transaction and mark the image unlocked
1414 function unlockAndRollback() {
1415 $this->locked
= false;
1416 $dbw = $this->repo
->getMasterDB();
1419 } // LocalFile class
1421 # ------------------------------------------------------------------------------
1424 * Helper class for file deletion
1427 class LocalFileDeleteBatch
{
1434 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1437 function __construct( File
$file, $reason = '', $suppress = false ) {
1438 $this->file
= $file;
1439 $this->reason
= $reason;
1440 $this->suppress
= $suppress;
1441 $this->status
= $file->repo
->newGood();
1444 function addCurrent() {
1445 $this->srcRels
['.'] = $this->file
->getRel();
1448 function addOld( $oldName ) {
1449 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1450 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1453 function getOldRels() {
1454 if ( !isset( $this->srcRels
['.'] ) ) {
1455 $oldRels =& $this->srcRels
;
1456 $deleteCurrent = false;
1458 $oldRels = $this->srcRels
;
1459 unset( $oldRels['.'] );
1460 $deleteCurrent = true;
1463 return array( $oldRels, $deleteCurrent );
1466 protected function getHashes() {
1468 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1470 if ( $deleteCurrent ) {
1471 $hashes['.'] = $this->file
->getSha1();
1474 if ( count( $oldRels ) ) {
1475 $dbw = $this->file
->repo
->getMasterDB();
1476 $res = $dbw->select(
1478 array( 'oi_archive_name', 'oi_sha1' ),
1479 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1483 foreach ( $res as $row ) {
1484 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1485 // Get the hash from the file
1486 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1487 $props = $this->file
->repo
->getFileProps( $oldUrl );
1489 if ( $props['fileExists'] ) {
1490 // Upgrade the oldimage row
1491 $dbw->update( 'oldimage',
1492 array( 'oi_sha1' => $props['sha1'] ),
1493 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1495 $hashes[$row->oi_archive_name
] = $props['sha1'];
1497 $hashes[$row->oi_archive_name
] = false;
1500 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1505 $missing = array_diff_key( $this->srcRels
, $hashes );
1507 foreach ( $missing as $name => $rel ) {
1508 $this->status
->error( 'filedelete-old-unregistered', $name );
1511 foreach ( $hashes as $name => $hash ) {
1513 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1514 unset( $hashes[$name] );
1521 function doDBInserts() {
1524 $dbw = $this->file
->repo
->getMasterDB();
1525 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1526 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1527 $encReason = $dbw->addQuotes( $this->reason
);
1528 $encGroup = $dbw->addQuotes( 'deleted' );
1529 $ext = $this->file
->getExtension();
1530 $dotExt = $ext === '' ?
'' : ".$ext";
1531 $encExt = $dbw->addQuotes( $dotExt );
1532 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1534 // Bitfields to further suppress the content
1535 if ( $this->suppress
) {
1537 // This should be 15...
1538 $bitfield |
= Revision
::DELETED_TEXT
;
1539 $bitfield |
= Revision
::DELETED_COMMENT
;
1540 $bitfield |
= Revision
::DELETED_USER
;
1541 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1543 $bitfield = 'oi_deleted';
1546 if ( $deleteCurrent ) {
1547 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1548 $where = array( 'img_name' => $this->file
->getName() );
1549 $dbw->insertSelect( 'filearchive', 'image',
1551 'fa_storage_group' => $encGroup,
1552 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1553 'fa_deleted_user' => $encUserId,
1554 'fa_deleted_timestamp' => $encTimestamp,
1555 'fa_deleted_reason' => $encReason,
1556 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1558 'fa_name' => 'img_name',
1559 'fa_archive_name' => 'NULL',
1560 'fa_size' => 'img_size',
1561 'fa_width' => 'img_width',
1562 'fa_height' => 'img_height',
1563 'fa_metadata' => 'img_metadata',
1564 'fa_bits' => 'img_bits',
1565 'fa_media_type' => 'img_media_type',
1566 'fa_major_mime' => 'img_major_mime',
1567 'fa_minor_mime' => 'img_minor_mime',
1568 'fa_description' => 'img_description',
1569 'fa_user' => 'img_user',
1570 'fa_user_text' => 'img_user_text',
1571 'fa_timestamp' => 'img_timestamp'
1572 ), $where, __METHOD__
);
1575 if ( count( $oldRels ) ) {
1576 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1578 'oi_name' => $this->file
->getName(),
1579 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1580 $dbw->insertSelect( 'filearchive', 'oldimage',
1582 'fa_storage_group' => $encGroup,
1583 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1584 'fa_deleted_user' => $encUserId,
1585 'fa_deleted_timestamp' => $encTimestamp,
1586 'fa_deleted_reason' => $encReason,
1587 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1589 'fa_name' => 'oi_name',
1590 'fa_archive_name' => 'oi_archive_name',
1591 'fa_size' => 'oi_size',
1592 'fa_width' => 'oi_width',
1593 'fa_height' => 'oi_height',
1594 'fa_metadata' => 'oi_metadata',
1595 'fa_bits' => 'oi_bits',
1596 'fa_media_type' => 'oi_media_type',
1597 'fa_major_mime' => 'oi_major_mime',
1598 'fa_minor_mime' => 'oi_minor_mime',
1599 'fa_description' => 'oi_description',
1600 'fa_user' => 'oi_user',
1601 'fa_user_text' => 'oi_user_text',
1602 'fa_timestamp' => 'oi_timestamp',
1603 'fa_deleted' => $bitfield
1604 ), $where, __METHOD__
);
1608 function doDBDeletes() {
1609 $dbw = $this->file
->repo
->getMasterDB();
1610 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1612 if ( count( $oldRels ) ) {
1613 $dbw->delete( 'oldimage',
1615 'oi_name' => $this->file
->getName(),
1616 'oi_archive_name' => array_keys( $oldRels )
1620 if ( $deleteCurrent ) {
1621 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1626 * Run the transaction
1628 function execute() {
1630 wfProfileIn( __METHOD__
);
1632 $this->file
->lock();
1633 // Leave private files alone
1634 $privateFiles = array();
1635 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1636 $dbw = $this->file
->repo
->getMasterDB();
1638 if ( !empty( $oldRels ) ) {
1639 $res = $dbw->select( 'oldimage',
1640 array( 'oi_archive_name' ),
1641 array( 'oi_name' => $this->file
->getName(),
1642 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1643 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1646 foreach ( $res as $row ) {
1647 $privateFiles[$row->oi_archive_name
] = 1;
1650 // Prepare deletion batch
1651 $hashes = $this->getHashes();
1652 $this->deletionBatch
= array();
1653 $ext = $this->file
->getExtension();
1654 $dotExt = $ext === '' ?
'' : ".$ext";
1656 foreach ( $this->srcRels
as $name => $srcRel ) {
1657 // Skip files that have no hash (missing source).
1658 // Keep private files where they are.
1659 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1660 $hash = $hashes[$name];
1661 $key = $hash . $dotExt;
1662 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1663 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1667 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1668 // We acquire this lock by running the inserts now, before the file operations.
1670 // This potentially has poor lock contention characteristics -- an alternative
1671 // scheme would be to insert stub filearchive entries with no fa_name and commit
1672 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1673 $this->doDBInserts();
1675 // Removes non-existent file from the batch, so we don't get errors.
1676 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1678 // Execute the file deletion batch
1679 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1681 if ( !$status->isGood() ) {
1682 $this->status
->merge( $status );
1685 if ( !$this->status
->ok
) {
1686 // Critical file deletion error
1687 // Roll back inserts, release lock and abort
1688 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1689 $this->file
->unlockAndRollback();
1690 wfProfileOut( __METHOD__
);
1691 return $this->status
;
1695 if ( $wgUseSquid ) {
1698 foreach ( $this->srcRels
as $srcRel ) {
1699 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1700 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1702 SquidUpdate
::purge( $urls );
1705 // Delete image/oldimage rows
1706 $this->doDBDeletes();
1708 // Commit and return
1709 $this->file
->unlock();
1710 wfProfileOut( __METHOD__
);
1712 return $this->status
;
1716 * Removes non-existent files from a deletion batch.
1718 function removeNonexistentFiles( $batch ) {
1719 $files = $newBatch = array();
1721 foreach ( $batch as $batchItem ) {
1722 list( $src, $dest ) = $batchItem;
1723 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1726 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1728 foreach ( $batch as $batchItem ) {
1729 if ( $result[$batchItem[0]] ) {
1730 $newBatch[] = $batchItem;
1738 # ------------------------------------------------------------------------------
1741 * Helper class for file undeletion
1744 class LocalFileRestoreBatch
{
1750 var $cleanupBatch, $ids, $all, $unsuppress = false;
1752 function __construct( File
$file, $unsuppress = false ) {
1753 $this->file
= $file;
1754 $this->cleanupBatch
= $this->ids
= array();
1755 $this->ids
= array();
1756 $this->unsuppress
= $unsuppress;
1762 function addId( $fa_id ) {
1763 $this->ids
[] = $fa_id;
1767 * Add a whole lot of files by ID
1769 function addIds( $ids ) {
1770 $this->ids
= array_merge( $this->ids
, $ids );
1774 * Add all revisions of the file
1781 * Run the transaction, except the cleanup batch.
1782 * The cleanup batch should be run in a separate transaction, because it locks different
1783 * rows and there's no need to keep the image row locked while it's acquiring those locks
1784 * The caller may have its own transaction open.
1785 * So we save the batch and let the caller call cleanup()
1787 function execute() {
1790 if ( !$this->all
&& !$this->ids
) {
1792 return $this->file
->repo
->newGood();
1795 $exists = $this->file
->lock();
1796 $dbw = $this->file
->repo
->getMasterDB();
1797 $status = $this->file
->repo
->newGood();
1799 // Fetch all or selected archived revisions for the file,
1800 // sorted from the most recent to the oldest.
1801 $conditions = array( 'fa_name' => $this->file
->getName() );
1803 if ( !$this->all
) {
1804 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1807 $result = $dbw->select( 'filearchive', '*',
1810 array( 'ORDER BY' => 'fa_timestamp DESC' )
1813 $idsPresent = array();
1814 $storeBatch = array();
1815 $insertBatch = array();
1816 $insertCurrent = false;
1817 $deleteIds = array();
1819 $archiveNames = array();
1821 foreach ( $result as $row ) {
1822 $idsPresent[] = $row->fa_id
;
1824 if ( $row->fa_name
!= $this->file
->getName() ) {
1825 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1826 $status->failCount++
;
1830 if ( $row->fa_storage_key
== '' ) {
1831 // Revision was missing pre-deletion
1832 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1833 $status->failCount++
;
1837 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1838 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1840 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1843 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1844 $sha1 = substr( $sha1, 1 );
1847 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1848 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1849 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1850 ||
is_null( $row->fa_metadata
) ) {
1851 // Refresh our metadata
1852 // Required for a new current revision; nice for older ones too. :)
1853 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1856 'minor_mime' => $row->fa_minor_mime
,
1857 'major_mime' => $row->fa_major_mime
,
1858 'media_type' => $row->fa_media_type
,
1859 'metadata' => $row->fa_metadata
1863 if ( $first && !$exists ) {
1864 // This revision will be published as the new current version
1865 $destRel = $this->file
->getRel();
1866 $insertCurrent = array(
1867 'img_name' => $row->fa_name
,
1868 'img_size' => $row->fa_size
,
1869 'img_width' => $row->fa_width
,
1870 'img_height' => $row->fa_height
,
1871 'img_metadata' => $props['metadata'],
1872 'img_bits' => $row->fa_bits
,
1873 'img_media_type' => $props['media_type'],
1874 'img_major_mime' => $props['major_mime'],
1875 'img_minor_mime' => $props['minor_mime'],
1876 'img_description' => $row->fa_description
,
1877 'img_user' => $row->fa_user
,
1878 'img_user_text' => $row->fa_user_text
,
1879 'img_timestamp' => $row->fa_timestamp
,
1883 // The live (current) version cannot be hidden!
1884 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1885 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1886 $this->cleanupBatch
[] = $row->fa_storage_key
;
1889 $archiveName = $row->fa_archive_name
;
1891 if ( $archiveName == '' ) {
1892 // This was originally a current version; we
1893 // have to devise a new archive name for it.
1894 // Format is <timestamp of archiving>!<name>
1895 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1898 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1900 } while ( isset( $archiveNames[$archiveName] ) );
1903 $archiveNames[$archiveName] = true;
1904 $destRel = $this->file
->getArchiveRel( $archiveName );
1905 $insertBatch[] = array(
1906 'oi_name' => $row->fa_name
,
1907 'oi_archive_name' => $archiveName,
1908 'oi_size' => $row->fa_size
,
1909 'oi_width' => $row->fa_width
,
1910 'oi_height' => $row->fa_height
,
1911 'oi_bits' => $row->fa_bits
,
1912 'oi_description' => $row->fa_description
,
1913 'oi_user' => $row->fa_user
,
1914 'oi_user_text' => $row->fa_user_text
,
1915 'oi_timestamp' => $row->fa_timestamp
,
1916 'oi_metadata' => $props['metadata'],
1917 'oi_media_type' => $props['media_type'],
1918 'oi_major_mime' => $props['major_mime'],
1919 'oi_minor_mime' => $props['minor_mime'],
1920 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1921 'oi_sha1' => $sha1 );
1924 $deleteIds[] = $row->fa_id
;
1926 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1927 // private files can stay where they are
1928 $status->successCount++
;
1930 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1931 $this->cleanupBatch
[] = $row->fa_storage_key
;
1939 // Add a warning to the status object for missing IDs
1940 $missingIds = array_diff( $this->ids
, $idsPresent );
1942 foreach ( $missingIds as $id ) {
1943 $status->error( 'undelete-missing-filearchive', $id );
1946 // Remove missing files from batch, so we don't get errors when undeleting them
1947 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1949 // Run the store batch
1950 // Use the OVERWRITE_SAME flag to smooth over a common error
1951 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1952 $status->merge( $storeStatus );
1954 if ( !$status->isGood() ) {
1955 // Even if some files could be copied, fail entirely as that is the
1956 // easiest thing to do without data loss
1957 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1958 $status->ok
= false;
1959 $this->file
->unlock();
1964 // Run the DB updates
1965 // Because we have locked the image row, key conflicts should be rare.
1966 // If they do occur, we can roll back the transaction at this time with
1967 // no data loss, but leaving unregistered files scattered throughout the
1969 // This is not ideal, which is why it's important to lock the image row.
1970 if ( $insertCurrent ) {
1971 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1974 if ( $insertBatch ) {
1975 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1979 $dbw->delete( 'filearchive',
1980 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1984 // If store batch is empty (all files are missing), deletion is to be considered successful
1985 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1987 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1989 // Update site_stats
1990 $site_stats = $dbw->tableName( 'site_stats' );
1991 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1993 $this->file
->purgeEverything();
1995 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1996 $this->file
->purgeDescription();
1997 $this->file
->purgeHistory();
2001 $this->file
->unlock();
2007 * Removes non-existent files from a store batch.
2009 function removeNonexistentFiles( $triplets ) {
2010 $files = $filteredTriplets = array();
2011 foreach ( $triplets as $file )
2012 $files[$file[0]] = $file[0];
2014 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2016 foreach ( $triplets as $file ) {
2017 if ( $result[$file[0]] ) {
2018 $filteredTriplets[] = $file;
2022 return $filteredTriplets;
2026 * Removes non-existent files from a cleanup batch.
2028 function removeNonexistentFromCleanup( $batch ) {
2029 $files = $newBatch = array();
2030 $repo = $this->file
->repo
;
2032 foreach ( $batch as $file ) {
2033 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2034 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2037 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2039 foreach ( $batch as $file ) {
2040 if ( $result[$file] ) {
2041 $newBatch[] = $file;
2049 * Delete unused files in the deleted zone.
2050 * This should be called from outside the transaction in which execute() was called.
2052 function cleanup() {
2053 if ( !$this->cleanupBatch
) {
2054 return $this->file
->repo
->newGood();
2057 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2059 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2065 * Cleanup a failed batch. The batch was only partially successful, so
2066 * rollback by removing all items that were succesfully copied.
2068 * @param Status $storeStatus
2069 * @param array $storeBatch
2071 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2072 $cleanupBatch = array();
2074 foreach ( $storeStatus->success
as $i => $success ) {
2075 // Check if this item of the batch was successfully copied
2077 // Item was successfully copied and needs to be removed again
2078 // Extract ($dstZone, $dstRel) from the batch
2079 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2082 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2086 # ------------------------------------------------------------------------------
2089 * Helper class for file movement
2092 class LocalFileMoveBatch
{
2104 var $cur, $olds, $oldCount, $archive, $db;
2106 function __construct( File
$file, Title
$target ) {
2107 $this->file
= $file;
2108 $this->target
= $target;
2109 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2110 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2111 $this->oldName
= $this->file
->getName();
2112 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2113 $this->oldRel
= $this->oldHash
. $this->oldName
;
2114 $this->newRel
= $this->newHash
. $this->newName
;
2115 $this->db
= $file->repo
->getMasterDb();
2119 * Add the current image to the batch
2121 function addCurrent() {
2122 $this->cur
= array( $this->oldRel
, $this->newRel
);
2126 * Add the old versions of the image to the batch
2128 function addOlds() {
2129 $archiveBase = 'archive';
2130 $this->olds
= array();
2131 $this->oldCount
= 0;
2133 $result = $this->db
->select( 'oldimage',
2134 array( 'oi_archive_name', 'oi_deleted' ),
2135 array( 'oi_name' => $this->oldName
),
2139 foreach ( $result as $row ) {
2140 $oldName = $row->oi_archive_name
;
2141 $bits = explode( '!', $oldName, 2 );
2143 if ( count( $bits ) != 2 ) {
2144 wfDebug( "Old file name missing !: '$oldName' \n" );
2148 list( $timestamp, $filename ) = $bits;
2150 if ( $this->oldName
!= $filename ) {
2151 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2157 // Do we want to add those to oldCount?
2158 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2162 $this->olds
[] = array(
2163 "{$archiveBase}/{$this->oldHash}{$oldName}",
2164 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2172 function execute() {
2173 $repo = $this->file
->repo
;
2174 $status = $repo->newGood();
2175 $triplets = $this->getMoveTriplets();
2177 $triplets = $this->removeNonexistentFiles( $triplets );
2179 // Copy the files into their new location
2180 $statusMove = $repo->storeBatch( $triplets );
2181 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2182 if ( !$statusMove->isGood() ) {
2183 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2184 $this->cleanupTarget( $triplets );
2185 $statusMove->ok
= false;
2190 $statusDb = $this->doDBUpdates();
2191 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2192 if ( !$statusDb->isGood() ) {
2193 $this->db
->rollback();
2194 // Something went wrong with the DB updates, so remove the target files
2195 $this->cleanupTarget( $triplets );
2196 $statusDb->ok
= false;
2199 $this->db
->commit();
2201 // Everything went ok, remove the source files
2202 $this->cleanupSource( $triplets );
2204 $status->merge( $statusDb );
2205 $status->merge( $statusMove );
2211 * Do the database updates and return a new FileRepoStatus indicating how
2212 * many rows where updated.
2214 * @return FileRepoStatus
2216 function doDBUpdates() {
2217 $repo = $this->file
->repo
;
2218 $status = $repo->newGood();
2221 // Update current image
2224 array( 'img_name' => $this->newName
),
2225 array( 'img_name' => $this->oldName
),
2229 if ( $dbw->affectedRows() ) {
2230 $status->successCount++
;
2232 $status->failCount++
;
2233 $status->fatal( 'imageinvalidfilename' );
2237 // Update old images
2241 'oi_name' => $this->newName
,
2242 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2244 array( 'oi_name' => $this->oldName
),
2248 $affected = $dbw->affectedRows();
2249 $total = $this->oldCount
;
2250 $status->successCount +
= $affected;
2251 $status->failCount +
= $total - $affected;
2252 if ( $status->failCount
) {
2253 $status->error( 'imageinvalidfilename' );
2260 * Generate triplets for FSRepo::storeBatch().
2262 function getMoveTriplets() {
2263 $moves = array_merge( array( $this->cur
), $this->olds
);
2264 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2266 foreach ( $moves as $move ) {
2267 // $move: (oldRelativePath, newRelativePath)
2268 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2269 $triplets[] = array( $srcUrl, 'public', $move[1] );
2270 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2277 * Removes non-existent files from move batch.
2279 function removeNonexistentFiles( $triplets ) {
2282 foreach ( $triplets as $file ) {
2283 $files[$file[0]] = $file[0];
2286 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2287 $filteredTriplets = array();
2289 foreach ( $triplets as $file ) {
2290 if ( $result[$file[0]] ) {
2291 $filteredTriplets[] = $file;
2293 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2297 return $filteredTriplets;
2301 * Cleanup a partially moved array of triplets by deleting the target
2302 * files. Called if something went wrong half way.
2304 function cleanupTarget( $triplets ) {
2305 // Create dest pairs from the triplets
2307 foreach ( $triplets as $triplet ) {
2308 $pairs[] = array( $triplet[1], $triplet[2] );
2311 $this->file
->repo
->cleanupBatch( $pairs );
2315 * Cleanup a fully moved array of triplets by deleting the source files.
2316 * Called at the end of the move process if everything else went ok.
2318 function cleanupSource( $triplets ) {
2319 // Create source file names from the triplets
2321 foreach ( $triplets as $triplet ) {
2322 $files[] = $triplet[0];
2325 $this->file
->repo
->cleanupBatch( $files );