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 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
67 static function newFromTitle( $title, $repo, $unused = null ) {
68 return new self( $title, $repo );
72 * Create a LocalFile from a title
73 * Do not call this except from inside a repo class.
75 static function newFromRow( $row, $repo ) {
76 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
77 $file = new self( $title, $repo );
78 $file->loadFromRow( $row );
84 * Create a LocalFile from a SHA-1 key
85 * Do not call this except from inside a repo class.
87 * @param $repo LocalRepo
90 static function newFromKey( $sha1, $repo, $timestamp = false ) {
91 $conds = array( 'img_sha1' => $sha1 );
94 $conds['img_timestamp'] = $timestamp;
97 $dbr = $repo->getSlaveDB();
98 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
101 return self
::newFromRow( $row, $repo );
108 * Fields in the image table
110 static function selectFields() {
131 * Do not call this except from inside a repo class.
133 function __construct( $title, $repo ) {
134 if ( !is_object( $title ) ) {
135 throw new MWException( __CLASS__
. ' constructor given bogus title.' );
138 parent
::__construct( $title, $repo );
140 $this->metadata
= '';
141 $this->historyLine
= 0;
142 $this->historyRes
= null;
143 $this->dataLoaded
= false;
147 * Get the memcached key for the main data for this file, or false if
148 * there is no access to the shared cache.
150 function getCacheKey() {
151 $hashedName = md5( $this->getName() );
153 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
157 * Try to load file metadata from memcached. Returns true on success.
159 function loadFromCache() {
162 wfProfileIn( __METHOD__
);
163 $this->dataLoaded
= false;
164 $key = $this->getCacheKey();
167 wfProfileOut( __METHOD__
);
171 $cachedValues = $wgMemc->get( $key );
173 // Check if the key existed and belongs to this version of MediaWiki
174 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
175 wfDebug( "Pulling file metadata from cache key $key\n" );
176 $this->fileExists
= $cachedValues['fileExists'];
177 if ( $this->fileExists
) {
178 $this->setProps( $cachedValues );
180 $this->dataLoaded
= true;
183 if ( $this->dataLoaded
) {
184 wfIncrStats( 'image_cache_hit' );
186 wfIncrStats( 'image_cache_miss' );
189 wfProfileOut( __METHOD__
);
190 return $this->dataLoaded
;
194 * Save the file metadata to memcached
196 function saveToCache() {
200 $key = $this->getCacheKey();
206 $fields = $this->getCacheFields( '' );
207 $cache = array( 'version' => MW_FILE_VERSION
);
208 $cache['fileExists'] = $this->fileExists
;
210 if ( $this->fileExists
) {
211 foreach ( $fields as $field ) {
212 $cache[$field] = $this->$field;
216 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
220 * Load metadata from the file itself
222 function loadFromFile() {
223 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
226 function getCacheFields( $prefix = 'img_' ) {
227 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
228 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
229 static $results = array();
231 if ( $prefix == '' ) {
235 if ( !isset( $results[$prefix] ) ) {
236 $prefixedFields = array();
237 foreach ( $fields as $field ) {
238 $prefixedFields[] = $prefix . $field;
240 $results[$prefix] = $prefixedFields;
243 return $results[$prefix];
247 * Load file metadata from the DB
249 function loadFromDB() {
250 # Polymorphic function name to distinguish foreign and local fetches
251 $fname = get_class( $this ) . '::' . __FUNCTION__
;
252 wfProfileIn( $fname );
254 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
255 $this->dataLoaded
= true;
257 $dbr = $this->repo
->getMasterDB();
259 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
260 array( 'img_name' => $this->getName() ), $fname );
263 $this->loadFromRow( $row );
265 $this->fileExists
= false;
268 wfProfileOut( $fname );
272 * Decode a row from the database (either object or array) to an array
273 * with timestamps and MIME types decoded, and the field prefix removed.
275 function decodeRow( $row, $prefix = 'img_' ) {
276 $array = (array)$row;
277 $prefixLength = strlen( $prefix );
279 // Sanity check prefix once
280 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
281 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
286 foreach ( $array as $name => $value ) {
287 $decoded[substr( $name, $prefixLength )] = $value;
290 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
292 if ( empty( $decoded['major_mime'] ) ) {
293 $decoded['mime'] = 'unknown/unknown';
295 if ( !$decoded['minor_mime'] ) {
296 $decoded['minor_mime'] = 'unknown';
298 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
301 # Trim zero padding from char/binary field
302 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
308 * Load file metadata from a DB result row
310 function loadFromRow( $row, $prefix = 'img_' ) {
311 $this->dataLoaded
= true;
312 $array = $this->decodeRow( $row, $prefix );
314 foreach ( $array as $name => $value ) {
315 $this->$name = $value;
318 $this->fileExists
= true;
319 $this->maybeUpgradeRow();
323 * Load file metadata from cache or DB, unless already loaded
326 if ( !$this->dataLoaded
) {
327 if ( !$this->loadFromCache() ) {
329 $this->saveToCache();
331 $this->dataLoaded
= true;
336 * Upgrade a row if it needs it
338 function maybeUpgradeRow() {
339 if ( wfReadOnly() ) {
343 if ( is_null( $this->media_type
) ||
344 $this->mime
== 'image/svg'
347 $this->upgraded
= true;
349 $handler = $this->getHandler();
350 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
352 $this->upgraded
= true;
357 function getUpgraded() {
358 return $this->upgraded
;
362 * Fix assorted version-related problems with the image row by reloading it from the file
364 function upgradeRow() {
365 wfProfileIn( __METHOD__
);
367 $this->loadFromFile();
369 # Don't destroy file info of missing files
370 if ( !$this->fileExists
) {
371 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
372 wfProfileOut( __METHOD__
);
376 $dbw = $this->repo
->getMasterDB();
377 list( $major, $minor ) = self
::splitMime( $this->mime
);
379 if ( wfReadOnly() ) {
380 wfProfileOut( __METHOD__
);
383 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
385 $dbw->update( 'image',
387 'img_width' => $this->width
,
388 'img_height' => $this->height
,
389 'img_bits' => $this->bits
,
390 'img_media_type' => $this->media_type
,
391 'img_major_mime' => $major,
392 'img_minor_mime' => $minor,
393 'img_metadata' => $this->metadata
,
394 'img_sha1' => $this->sha1
,
395 ), array( 'img_name' => $this->getName() ),
399 $this->saveToCache();
400 wfProfileOut( __METHOD__
);
404 * Set properties in this object to be equal to those given in the
405 * associative array $info. Only cacheable fields can be set.
407 * If 'mime' is given, it will be split into major_mime/minor_mime.
408 * If major_mime/minor_mime are given, $this->mime will also be set.
410 function setProps( $info ) {
411 $this->dataLoaded
= true;
412 $fields = $this->getCacheFields( '' );
413 $fields[] = 'fileExists';
415 foreach ( $fields as $field ) {
416 if ( isset( $info[$field] ) ) {
417 $this->$field = $info[$field];
421 // Fix up mime fields
422 if ( isset( $info['major_mime'] ) ) {
423 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
424 } elseif ( isset( $info['mime'] ) ) {
425 $this->mime
= $info['mime'];
426 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
430 /** splitMime inherited */
431 /** getName inherited */
432 /** getTitle inherited */
433 /** getURL inherited */
434 /** getViewURL inherited */
435 /** getPath inherited */
436 /** isVisible inhereted */
438 function isMissing() {
439 if ( $this->missing
=== null ) {
440 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
441 $this->missing
= !$fileExists;
443 return $this->missing
;
447 * Return the width of the image
449 * Returns false on error
451 public function getWidth( $page = 1 ) {
454 if ( $this->isMultipage() ) {
455 $dim = $this->getHandler()->getPageDimensions( $this, $page );
457 return $dim['width'];
467 * Return the height of the image
469 * Returns false on error
471 public function getHeight( $page = 1 ) {
474 if ( $this->isMultipage() ) {
475 $dim = $this->getHandler()->getPageDimensions( $this, $page );
477 return $dim['height'];
482 return $this->height
;
487 * Returns ID or name of user who uploaded the file
489 * @param $type string 'text' or 'id'
491 function getUser( $type = 'text' ) {
494 if ( $type == 'text' ) {
495 return $this->user_text
;
496 } elseif ( $type == 'id' ) {
502 * Get handler-specific metadata
504 function getMetadata() {
506 return $this->metadata
;
509 function getBitDepth() {
515 * Return the size of the image file, in bytes
517 public function getSize() {
523 * Returns the mime type of the file.
525 function getMimeType() {
531 * Return the type of the media in the file.
532 * Use the value returned by this function with the MEDIATYPE_xxx constants.
534 function getMediaType() {
536 return $this->media_type
;
539 /** canRender inherited */
540 /** mustRender inherited */
541 /** allowInlineDisplay inherited */
542 /** isSafeFile inherited */
543 /** isTrustedFile inherited */
546 * Returns true if the file file exists on disk.
547 * @return boolean Whether file file exist on disk.
549 public function exists() {
551 return $this->fileExists
;
554 /** getTransformScript inherited */
555 /** getUnscaledThumb inherited */
556 /** thumbName inherited */
557 /** createThumb inherited */
558 /** getThumbnail inherited */
559 /** transform inherited */
562 * Fix thumbnail files from 1.4 or before, with extreme prejudice
564 function migrateThumbFile( $thumbName ) {
565 $thumbDir = $this->getThumbPath();
566 $thumbPath = "$thumbDir/$thumbName";
568 if ( is_dir( $thumbPath ) ) {
569 // Directory where file should be
570 // This happened occasionally due to broken migration code in 1.5
571 // Rename to broken-*
572 for ( $i = 0; $i < 100 ; $i++
) {
573 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
574 if ( !file_exists( $broken ) ) {
575 rename( $thumbPath, $broken );
579 // Doesn't exist anymore
583 if ( is_file( $thumbDir ) ) {
584 // File where directory should be
586 // Doesn't exist anymore
591 /** getHandler inherited */
592 /** iconThumb inherited */
593 /** getLastError inherited */
596 * Get all thumbnail names previously generated for this file
598 function getThumbnails() {
602 $dir = $this->getThumbPath();
604 if ( is_dir( $dir ) ) {
605 $handle = opendir( $dir );
608 while ( false !== ( $file = readdir( $handle ) ) ) {
609 if ( $file { 0 } != '.' ) {
622 * Refresh metadata in memcached, but don't touch thumbnails or squid
624 function purgeMetadataCache() {
626 $this->saveToCache();
627 $this->purgeHistory();
631 * Purge the shared history (OldLocalFile) cache
633 function purgeHistory() {
636 $hashedName = md5( $this->getName() );
637 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
640 $wgMemc->delete( $oldKey );
645 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
647 function purgeCache() {
648 // Refresh metadata cache
649 $this->purgeMetadataCache();
652 $this->purgeThumbnails();
654 // Purge squid cache for this file
655 SquidUpdate
::purge( array( $this->getURL() ) );
659 * Delete cached transformed files
661 function purgeThumbnails() {
662 global $wgUseSquid, $wgExcludeFromThumbnailPurge;
665 $files = $this->getThumbnails();
666 $dir = $this->getThumbPath();
669 foreach ( $files as $file ) {
670 // Only remove files not in the $wgExcludeFromThumbnailPurge configuration variable
671 $ext = pathinfo( "$dir/$file", PATHINFO_EXTENSION
);
672 if ( in_array( $ext, $wgExcludeFromThumbnailPurge ) ) {
676 # Check that the base file name is part of the thumb name
677 # This is a basic sanity check to avoid erasing unrelated directories
678 if ( strpos( $file, $this->getName() ) !== false ) {
679 $url = $this->getThumbUrl( $file );
681 @unlink
( "$dir/$file" );
687 SquidUpdate
::purge( $urls );
691 /** purgeDescription inherited */
692 /** purgeEverything inherited */
694 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
695 $dbr = $this->repo
->getSlaveDB();
696 $tables = array( 'oldimage' );
697 $fields = OldLocalFile
::selectFields();
698 $conds = $opts = $join_conds = array();
699 $eq = $inc ?
'=' : '';
700 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
703 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
707 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
711 $opts['LIMIT'] = $limit;
714 // Search backwards for time > x queries
715 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
716 $opts['ORDER BY'] = "oi_timestamp $order";
717 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
719 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
720 &$conds, &$opts, &$join_conds ) );
722 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
725 foreach ( $res as $row ) {
726 if ( $this->repo
->oldFileFromRowFactory
) {
727 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
729 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
733 if ( $order == 'ASC' ) {
734 $r = array_reverse( $r ); // make sure it ends up descending
741 * Return the history of this file, line by line.
742 * starts with current version, then old versions.
743 * uses $this->historyLine to check which line to return:
744 * 0 return line for current version
745 * 1 query for old versions, return first one
746 * 2, ... return next old version from above query
748 public function nextHistoryLine() {
749 # Polymorphic function name to distinguish foreign and local fetches
750 $fname = get_class( $this ) . '::' . __FUNCTION__
;
752 $dbr = $this->repo
->getSlaveDB();
754 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
755 $this->historyRes
= $dbr->select( 'image',
758 "'' AS oi_archive_name",
762 array( 'img_name' => $this->title
->getDBkey() ),
766 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
767 $this->historyRes
= null;
770 } elseif ( $this->historyLine
== 1 ) {
771 $this->historyRes
= $dbr->select( 'oldimage', '*',
772 array( 'oi_name' => $this->title
->getDBkey() ),
774 array( 'ORDER BY' => 'oi_timestamp DESC' )
777 $this->historyLine ++
;
779 return $dbr->fetchObject( $this->historyRes
);
783 * Reset the history pointer to the first element of the history
785 public function resetHistory() {
786 $this->historyLine
= 0;
788 if ( !is_null( $this->historyRes
) ) {
789 $this->historyRes
= null;
793 /** getFullPath inherited */
794 /** getHashPath inherited */
795 /** getRel inherited */
796 /** getUrlRel inherited */
797 /** getArchiveRel inherited */
798 /** getThumbRel inherited */
799 /** getArchivePath inherited */
800 /** getThumbPath inherited */
801 /** getArchiveUrl inherited */
802 /** getThumbUrl inherited */
803 /** getArchiveVirtualUrl inherited */
804 /** getThumbVirtualUrl inherited */
805 /** isHashed inherited */
808 * Upload a file and record it in the DB
809 * @param $srcPath String: source path or virtual URL
810 * @param $comment String: upload description
811 * @param $pageText String: text to use for the new description page,
812 * if a new description page is created
813 * @param $flags Integer: flags for publish()
814 * @param $props Array: File properties, if known. This can be used to reduce the
815 * upload time when uploading virtual URLs for which the file info
817 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
818 * @param $user Mixed: User object or null to use $wgUser
820 * @return FileRepoStatus object. On success, the value member contains the
821 * archive name, or an empty string if it was a new file.
823 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
825 $status = $this->publish( $srcPath, $flags );
828 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
829 $status->fatal( 'filenotfound', $srcPath );
839 * Record a file upload in the upload log and the image table
840 * @deprecated use upload()
842 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
843 $watch = false, $timestamp = false )
845 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
847 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
853 $wgUser->addWatch( $this->getTitle() );
860 * Record a file upload in the upload log and the image table
862 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
864 if ( is_null( $user ) ) {
869 $dbw = $this->repo
->getMasterDB();
873 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
876 $props['description'] = $comment;
877 $props['user'] = $user->getId();
878 $props['user_text'] = $user->getName();
879 $props['timestamp'] = wfTimestamp( TS_MW
);
880 $this->setProps( $props );
883 $this->purgeThumbnails();
885 # The file is already on its final location, remove it from the squid cache
886 SquidUpdate
::purge( array( $this->getURL() ) );
888 # Fail now if the file isn't there
889 if ( !$this->fileExists
) {
890 wfDebug( __METHOD__
. ": File " . $this->getPath() . " went missing!\n" );
896 if ( $timestamp === false ) {
897 $timestamp = $dbw->timestamp();
900 # Test to see if the row exists using INSERT IGNORE
901 # This avoids race conditions by locking the row until the commit, and also
902 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
903 $dbw->insert( 'image',
905 'img_name' => $this->getName(),
906 'img_size' => $this->size
,
907 'img_width' => intval( $this->width
),
908 'img_height' => intval( $this->height
),
909 'img_bits' => $this->bits
,
910 'img_media_type' => $this->media_type
,
911 'img_major_mime' => $this->major_mime
,
912 'img_minor_mime' => $this->minor_mime
,
913 'img_timestamp' => $timestamp,
914 'img_description' => $comment,
915 'img_user' => $user->getId(),
916 'img_user_text' => $user->getName(),
917 'img_metadata' => $this->metadata
,
918 'img_sha1' => $this->sha1
924 if ( $dbw->affectedRows() == 0 ) {
927 # Collision, this is an update of a file
928 # Insert previous contents into oldimage
929 $dbw->insertSelect( 'oldimage', 'image',
931 'oi_name' => 'img_name',
932 'oi_archive_name' => $dbw->addQuotes( $oldver ),
933 'oi_size' => 'img_size',
934 'oi_width' => 'img_width',
935 'oi_height' => 'img_height',
936 'oi_bits' => 'img_bits',
937 'oi_timestamp' => 'img_timestamp',
938 'oi_description' => 'img_description',
939 'oi_user' => 'img_user',
940 'oi_user_text' => 'img_user_text',
941 'oi_metadata' => 'img_metadata',
942 'oi_media_type' => 'img_media_type',
943 'oi_major_mime' => 'img_major_mime',
944 'oi_minor_mime' => 'img_minor_mime',
945 'oi_sha1' => 'img_sha1'
946 ), array( 'img_name' => $this->getName() ), __METHOD__
949 # Update the current image row
950 $dbw->update( 'image',
952 'img_size' => $this->size
,
953 'img_width' => intval( $this->width
),
954 'img_height' => intval( $this->height
),
955 'img_bits' => $this->bits
,
956 'img_media_type' => $this->media_type
,
957 'img_major_mime' => $this->major_mime
,
958 'img_minor_mime' => $this->minor_mime
,
959 'img_timestamp' => $timestamp,
960 'img_description' => $comment,
961 'img_user' => $user->getId(),
962 'img_user_text' => $user->getName(),
963 'img_metadata' => $this->metadata
,
964 'img_sha1' => $this->sha1
965 ), array( /* WHERE */
966 'img_name' => $this->getName()
971 # Update the image count
972 $site_stats = $dbw->tableName( 'site_stats' );
973 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
976 $descTitle = $this->getTitle();
977 $article = new ImagePage( $descTitle );
978 $article->setFile( $this );
981 $log = new LogPage( 'upload' );
982 $action = $reupload ?
'overwrite' : 'upload';
983 $log->addEntry( $action, $descTitle, $comment, array(), $user );
985 if ( $descTitle->exists() ) {
986 # Create a null revision
987 $latest = $descTitle->getLatestRevID();
988 $nullRevision = Revision
::newNullRevision(
990 $descTitle->getArticleId(),
991 $log->getRcComment(),
994 $nullRevision->insertOn( $dbw );
996 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
997 $article->updateRevisionOn( $dbw, $nullRevision );
999 # Invalidate the cache for the description page
1000 $descTitle->invalidateCache();
1001 $descTitle->purgeSquid();
1003 # New file; create the description page.
1004 # There's already a log entry, so don't make a second RC entry
1005 # Squid and file cache for the description page are purged by doEdit.
1006 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
1009 # Commit the transaction now, in case something goes wrong later
1010 # The most important thing is that files don't get lost, especially archives
1013 # Save to cache and purge the squid
1014 # We shall not saveToCache before the commit since otherwise
1015 # in case of a rollback there is an usable file from memcached
1016 # which in fact doesn't really exist (bug 24978)
1017 $this->saveToCache();
1019 # Hooks, hooks, the magic of hooks...
1020 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1022 # Invalidate cache for all pages using this file
1023 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1024 $update->doUpdate();
1026 # Invalidate cache for all pages that redirects on this page
1027 $redirs = $this->getTitle()->getRedirectsHere();
1029 foreach ( $redirs as $redir ) {
1030 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1031 $update->doUpdate();
1038 * Move or copy a file to its public location. If a file exists at the
1039 * destination, move it to an archive. Returns a FileRepoStatus object with
1040 * the archive name in the "value" member on success.
1042 * The archive name should be passed through to recordUpload for database
1045 * @param $srcPath String: local filesystem path to the source image
1046 * @param $flags Integer: a bitwise combination of:
1047 * File::DELETE_SOURCE Delete the source file, i.e. move
1049 * @return FileRepoStatus object. On success, the value member contains the
1050 * archive name, or an empty string if it was a new file.
1052 function publish( $srcPath, $flags = 0 ) {
1055 $dstRel = $this->getRel();
1056 $archiveName = gmdate( 'YmdHis' ) . '!' . $this->getName();
1057 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1058 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1059 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1061 if ( $status->value
== 'new' ) {
1062 $status->value
= '';
1064 $status->value
= $archiveName;
1072 /** getLinksTo inherited */
1073 /** getExifData inherited */
1074 /** isLocal inherited */
1075 /** wasDeleted inherited */
1078 * Move file to the new title
1080 * Move current, old version and all thumbnails
1081 * to the new filename. Old file is deleted.
1083 * Cache purging is done; checks for validity
1084 * and logging are caller's responsibility
1086 * @param $target Title New file name
1087 * @return FileRepoStatus object.
1089 function move( $target ) {
1090 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1093 $batch = new LocalFileMoveBatch( $this, $target );
1094 $batch->addCurrent();
1097 $status = $batch->execute();
1098 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1100 $this->purgeEverything();
1103 if ( $status->isOk() ) {
1104 // Now switch the object
1105 $this->title
= $target;
1106 // Force regeneration of the name and hashpath
1107 unset( $this->name
);
1108 unset( $this->hashPath
);
1109 // Purge the new image
1110 $this->purgeEverything();
1117 * Delete all versions of the file.
1119 * Moves the files into an archive directory (or deletes them)
1120 * and removes the database rows.
1122 * Cache purging is done; logging is caller's responsibility.
1126 * @return FileRepoStatus object.
1128 function delete( $reason, $suppress = false ) {
1131 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1132 $batch->addCurrent();
1134 # Get old version relative paths
1135 $dbw = $this->repo
->getMasterDB();
1136 $result = $dbw->select( 'oldimage',
1137 array( 'oi_archive_name' ),
1138 array( 'oi_name' => $this->getName() ) );
1139 foreach ( $result as $row ) {
1140 $batch->addOld( $row->oi_archive_name
);
1142 $status = $batch->execute();
1144 if ( $status->ok
) {
1145 // Update site_stats
1146 $site_stats = $dbw->tableName( 'site_stats' );
1147 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1148 $this->purgeEverything();
1157 * Delete an old version of the file.
1159 * Moves the file into an archive directory (or deletes it)
1160 * and removes the database row.
1162 * Cache purging is done; logging is caller's responsibility.
1164 * @param $archiveName String
1165 * @param $reason String
1166 * @param $suppress Boolean
1167 * @throws MWException or FSException on database or file store failure
1168 * @return FileRepoStatus object.
1170 function deleteOld( $archiveName, $reason, $suppress = false ) {
1173 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1174 $batch->addOld( $archiveName );
1175 $status = $batch->execute();
1179 if ( $status->ok
) {
1180 $this->purgeDescription();
1181 $this->purgeHistory();
1188 * Restore all or specified deleted revisions to the given file.
1189 * Permissions and logging are left to the caller.
1191 * May throw database exceptions on error.
1193 * @param $versions set of record ids of deleted items to restore,
1194 * or empty to restore all revisions.
1195 * @param $unsuppress Boolean
1196 * @return FileRepoStatus
1198 function restore( $versions = array(), $unsuppress = false ) {
1199 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1204 $batch->addIds( $versions );
1207 $status = $batch->execute();
1209 if ( !$status->isGood() ) {
1213 $cleanupStatus = $batch->cleanup();
1214 $cleanupStatus->successCount
= 0;
1215 $cleanupStatus->failCount
= 0;
1216 $status->merge( $cleanupStatus );
1221 /** isMultipage inherited */
1222 /** pageCount inherited */
1223 /** scaleHeight inherited */
1224 /** getImageSize inherited */
1227 * Get the URL of the file description page.
1229 function getDescriptionUrl() {
1230 return $this->title
->getLocalUrl();
1234 * Get the HTML text of the description page
1235 * This is not used by ImagePage for local files, since (among other things)
1236 * it skips the parser cache.
1238 function getDescriptionText() {
1240 $revision = Revision
::newFromTitle( $this->title
);
1241 if ( !$revision ) return false;
1242 $text = $revision->getText();
1243 if ( !$text ) return false;
1244 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1245 return $pout->getText();
1248 function getDescription() {
1250 return $this->description
;
1253 function getTimestamp() {
1255 return $this->timestamp
;
1258 function getSha1() {
1260 // Initialise now if necessary
1261 if ( $this->sha1
== '' && $this->fileExists
) {
1262 $this->sha1
= File
::sha1Base36( $this->getPath() );
1263 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1264 $dbw = $this->repo
->getMasterDB();
1265 $dbw->update( 'image',
1266 array( 'img_sha1' => $this->sha1
),
1267 array( 'img_name' => $this->getName() ),
1269 $this->saveToCache();
1277 * Start a transaction and lock the image for update
1278 * Increments a reference counter if the lock is already held
1279 * @return boolean True if the image exists, false otherwise
1282 $dbw = $this->repo
->getMasterDB();
1284 if ( !$this->locked
) {
1289 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1293 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1294 * the transaction and thereby releases the image lock.
1297 if ( $this->locked
) {
1299 if ( !$this->locked
) {
1300 $dbw = $this->repo
->getMasterDB();
1307 * Roll back the DB transaction and mark the image unlocked
1309 function unlockAndRollback() {
1310 $this->locked
= false;
1311 $dbw = $this->repo
->getMasterDB();
1314 } // LocalFile class
1316 # ------------------------------------------------------------------------------
1319 * Helper class for file deletion
1322 class LocalFileDeleteBatch
{
1329 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1332 function __construct( File
$file, $reason = '', $suppress = false ) {
1333 $this->file
= $file;
1334 $this->reason
= $reason;
1335 $this->suppress
= $suppress;
1336 $this->status
= $file->repo
->newGood();
1339 function addCurrent() {
1340 $this->srcRels
['.'] = $this->file
->getRel();
1343 function addOld( $oldName ) {
1344 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1345 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1348 function getOldRels() {
1349 if ( !isset( $this->srcRels
['.'] ) ) {
1350 $oldRels =& $this->srcRels
;
1351 $deleteCurrent = false;
1353 $oldRels = $this->srcRels
;
1354 unset( $oldRels['.'] );
1355 $deleteCurrent = true;
1358 return array( $oldRels, $deleteCurrent );
1361 /*protected*/ function getHashes() {
1363 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1365 if ( $deleteCurrent ) {
1366 $hashes['.'] = $this->file
->getSha1();
1369 if ( count( $oldRels ) ) {
1370 $dbw = $this->file
->repo
->getMasterDB();
1371 $res = $dbw->select(
1373 array( 'oi_archive_name', 'oi_sha1' ),
1374 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1378 foreach ( $res as $row ) {
1379 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1380 // Get the hash from the file
1381 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1382 $props = $this->file
->repo
->getFileProps( $oldUrl );
1384 if ( $props['fileExists'] ) {
1385 // Upgrade the oldimage row
1386 $dbw->update( 'oldimage',
1387 array( 'oi_sha1' => $props['sha1'] ),
1388 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1390 $hashes[$row->oi_archive_name
] = $props['sha1'];
1392 $hashes[$row->oi_archive_name
] = false;
1395 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1400 $missing = array_diff_key( $this->srcRels
, $hashes );
1402 foreach ( $missing as $name => $rel ) {
1403 $this->status
->error( 'filedelete-old-unregistered', $name );
1406 foreach ( $hashes as $name => $hash ) {
1408 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1409 unset( $hashes[$name] );
1416 function doDBInserts() {
1419 $dbw = $this->file
->repo
->getMasterDB();
1420 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1421 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1422 $encReason = $dbw->addQuotes( $this->reason
);
1423 $encGroup = $dbw->addQuotes( 'deleted' );
1424 $ext = $this->file
->getExtension();
1425 $dotExt = $ext === '' ?
'' : ".$ext";
1426 $encExt = $dbw->addQuotes( $dotExt );
1427 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1429 // Bitfields to further suppress the content
1430 if ( $this->suppress
) {
1432 // This should be 15...
1433 $bitfield |
= Revision
::DELETED_TEXT
;
1434 $bitfield |
= Revision
::DELETED_COMMENT
;
1435 $bitfield |
= Revision
::DELETED_USER
;
1436 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1438 $bitfield = 'oi_deleted';
1441 if ( $deleteCurrent ) {
1442 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1443 $where = array( 'img_name' => $this->file
->getName() );
1444 $dbw->insertSelect( 'filearchive', 'image',
1446 'fa_storage_group' => $encGroup,
1447 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1448 'fa_deleted_user' => $encUserId,
1449 'fa_deleted_timestamp' => $encTimestamp,
1450 'fa_deleted_reason' => $encReason,
1451 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1453 'fa_name' => 'img_name',
1454 'fa_archive_name' => 'NULL',
1455 'fa_size' => 'img_size',
1456 'fa_width' => 'img_width',
1457 'fa_height' => 'img_height',
1458 'fa_metadata' => 'img_metadata',
1459 'fa_bits' => 'img_bits',
1460 'fa_media_type' => 'img_media_type',
1461 'fa_major_mime' => 'img_major_mime',
1462 'fa_minor_mime' => 'img_minor_mime',
1463 'fa_description' => 'img_description',
1464 'fa_user' => 'img_user',
1465 'fa_user_text' => 'img_user_text',
1466 'fa_timestamp' => 'img_timestamp'
1467 ), $where, __METHOD__
);
1470 if ( count( $oldRels ) ) {
1471 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1473 'oi_name' => $this->file
->getName(),
1474 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1475 $dbw->insertSelect( 'filearchive', 'oldimage',
1477 'fa_storage_group' => $encGroup,
1478 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1479 'fa_deleted_user' => $encUserId,
1480 'fa_deleted_timestamp' => $encTimestamp,
1481 'fa_deleted_reason' => $encReason,
1482 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1484 'fa_name' => 'oi_name',
1485 'fa_archive_name' => 'oi_archive_name',
1486 'fa_size' => 'oi_size',
1487 'fa_width' => 'oi_width',
1488 'fa_height' => 'oi_height',
1489 'fa_metadata' => 'oi_metadata',
1490 'fa_bits' => 'oi_bits',
1491 'fa_media_type' => 'oi_media_type',
1492 'fa_major_mime' => 'oi_major_mime',
1493 'fa_minor_mime' => 'oi_minor_mime',
1494 'fa_description' => 'oi_description',
1495 'fa_user' => 'oi_user',
1496 'fa_user_text' => 'oi_user_text',
1497 'fa_timestamp' => 'oi_timestamp',
1498 'fa_deleted' => $bitfield
1499 ), $where, __METHOD__
);
1503 function doDBDeletes() {
1504 $dbw = $this->file
->repo
->getMasterDB();
1505 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1507 if ( count( $oldRels ) ) {
1508 $dbw->delete( 'oldimage',
1510 'oi_name' => $this->file
->getName(),
1511 'oi_archive_name' => array_keys( $oldRels )
1515 if ( $deleteCurrent ) {
1516 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1521 * Run the transaction
1523 function execute() {
1525 wfProfileIn( __METHOD__
);
1527 $this->file
->lock();
1528 // Leave private files alone
1529 $privateFiles = array();
1530 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1531 $dbw = $this->file
->repo
->getMasterDB();
1533 if ( !empty( $oldRels ) ) {
1534 $res = $dbw->select( 'oldimage',
1535 array( 'oi_archive_name' ),
1536 array( 'oi_name' => $this->file
->getName(),
1537 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1538 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1541 foreach ( $res as $row ) {
1542 $privateFiles[$row->oi_archive_name
] = 1;
1545 // Prepare deletion batch
1546 $hashes = $this->getHashes();
1547 $this->deletionBatch
= array();
1548 $ext = $this->file
->getExtension();
1549 $dotExt = $ext === '' ?
'' : ".$ext";
1551 foreach ( $this->srcRels
as $name => $srcRel ) {
1552 // Skip files that have no hash (missing source).
1553 // Keep private files where they are.
1554 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1555 $hash = $hashes[$name];
1556 $key = $hash . $dotExt;
1557 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1558 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1562 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1563 // We acquire this lock by running the inserts now, before the file operations.
1565 // This potentially has poor lock contention characteristics -- an alternative
1566 // scheme would be to insert stub filearchive entries with no fa_name and commit
1567 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1568 $this->doDBInserts();
1570 // Removes non-existent file from the batch, so we don't get errors.
1571 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1573 // Execute the file deletion batch
1574 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1576 if ( !$status->isGood() ) {
1577 $this->status
->merge( $status );
1580 if ( !$this->status
->ok
) {
1581 // Critical file deletion error
1582 // Roll back inserts, release lock and abort
1583 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1584 $this->file
->unlockAndRollback();
1585 wfProfileOut( __METHOD__
);
1586 return $this->status
;
1590 if ( $wgUseSquid ) {
1593 foreach ( $this->srcRels
as $srcRel ) {
1594 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1595 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1597 SquidUpdate
::purge( $urls );
1600 // Delete image/oldimage rows
1601 $this->doDBDeletes();
1603 // Commit and return
1604 $this->file
->unlock();
1605 wfProfileOut( __METHOD__
);
1607 return $this->status
;
1611 * Removes non-existent files from a deletion batch.
1613 function removeNonexistentFiles( $batch ) {
1614 $files = $newBatch = array();
1616 foreach ( $batch as $batchItem ) {
1617 list( $src, $dest ) = $batchItem;
1618 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1621 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1623 foreach ( $batch as $batchItem ) {
1624 if ( $result[$batchItem[0]] ) {
1625 $newBatch[] = $batchItem;
1633 # ------------------------------------------------------------------------------
1636 * Helper class for file undeletion
1639 class LocalFileRestoreBatch
{
1645 var $cleanupBatch, $ids, $all, $unsuppress = false;
1647 function __construct( File
$file, $unsuppress = false ) {
1648 $this->file
= $file;
1649 $this->cleanupBatch
= $this->ids
= array();
1650 $this->ids
= array();
1651 $this->unsuppress
= $unsuppress;
1657 function addId( $fa_id ) {
1658 $this->ids
[] = $fa_id;
1662 * Add a whole lot of files by ID
1664 function addIds( $ids ) {
1665 $this->ids
= array_merge( $this->ids
, $ids );
1669 * Add all revisions of the file
1676 * Run the transaction, except the cleanup batch.
1677 * The cleanup batch should be run in a separate transaction, because it locks different
1678 * rows and there's no need to keep the image row locked while it's acquiring those locks
1679 * The caller may have its own transaction open.
1680 * So we save the batch and let the caller call cleanup()
1682 function execute() {
1685 if ( !$this->all
&& !$this->ids
) {
1687 return $this->file
->repo
->newGood();
1690 $exists = $this->file
->lock();
1691 $dbw = $this->file
->repo
->getMasterDB();
1692 $status = $this->file
->repo
->newGood();
1694 // Fetch all or selected archived revisions for the file,
1695 // sorted from the most recent to the oldest.
1696 $conditions = array( 'fa_name' => $this->file
->getName() );
1698 if ( !$this->all
) {
1699 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1702 $result = $dbw->select( 'filearchive', '*',
1705 array( 'ORDER BY' => 'fa_timestamp DESC' )
1708 $idsPresent = array();
1709 $storeBatch = array();
1710 $insertBatch = array();
1711 $insertCurrent = false;
1712 $deleteIds = array();
1714 $archiveNames = array();
1716 foreach ( $result as $row ) {
1717 $idsPresent[] = $row->fa_id
;
1719 if ( $row->fa_name
!= $this->file
->getName() ) {
1720 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1721 $status->failCount++
;
1725 if ( $row->fa_storage_key
== '' ) {
1726 // Revision was missing pre-deletion
1727 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1728 $status->failCount++
;
1732 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1733 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1735 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1738 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1739 $sha1 = substr( $sha1, 1 );
1742 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1743 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1744 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1745 ||
is_null( $row->fa_metadata
) ) {
1746 // Refresh our metadata
1747 // Required for a new current revision; nice for older ones too. :)
1748 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1751 'minor_mime' => $row->fa_minor_mime
,
1752 'major_mime' => $row->fa_major_mime
,
1753 'media_type' => $row->fa_media_type
,
1754 'metadata' => $row->fa_metadata
1758 if ( $first && !$exists ) {
1759 // This revision will be published as the new current version
1760 $destRel = $this->file
->getRel();
1761 $insertCurrent = array(
1762 'img_name' => $row->fa_name
,
1763 'img_size' => $row->fa_size
,
1764 'img_width' => $row->fa_width
,
1765 'img_height' => $row->fa_height
,
1766 'img_metadata' => $props['metadata'],
1767 'img_bits' => $row->fa_bits
,
1768 'img_media_type' => $props['media_type'],
1769 'img_major_mime' => $props['major_mime'],
1770 'img_minor_mime' => $props['minor_mime'],
1771 'img_description' => $row->fa_description
,
1772 'img_user' => $row->fa_user
,
1773 'img_user_text' => $row->fa_user_text
,
1774 'img_timestamp' => $row->fa_timestamp
,
1778 // The live (current) version cannot be hidden!
1779 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1780 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1781 $this->cleanupBatch
[] = $row->fa_storage_key
;
1784 $archiveName = $row->fa_archive_name
;
1786 if ( $archiveName == '' ) {
1787 // This was originally a current version; we
1788 // have to devise a new archive name for it.
1789 // Format is <timestamp of archiving>!<name>
1790 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1793 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1795 } while ( isset( $archiveNames[$archiveName] ) );
1798 $archiveNames[$archiveName] = true;
1799 $destRel = $this->file
->getArchiveRel( $archiveName );
1800 $insertBatch[] = array(
1801 'oi_name' => $row->fa_name
,
1802 'oi_archive_name' => $archiveName,
1803 'oi_size' => $row->fa_size
,
1804 'oi_width' => $row->fa_width
,
1805 'oi_height' => $row->fa_height
,
1806 'oi_bits' => $row->fa_bits
,
1807 'oi_description' => $row->fa_description
,
1808 'oi_user' => $row->fa_user
,
1809 'oi_user_text' => $row->fa_user_text
,
1810 'oi_timestamp' => $row->fa_timestamp
,
1811 'oi_metadata' => $props['metadata'],
1812 'oi_media_type' => $props['media_type'],
1813 'oi_major_mime' => $props['major_mime'],
1814 'oi_minor_mime' => $props['minor_mime'],
1815 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1816 'oi_sha1' => $sha1 );
1819 $deleteIds[] = $row->fa_id
;
1821 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1822 // private files can stay where they are
1823 $status->successCount++
;
1825 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1826 $this->cleanupBatch
[] = $row->fa_storage_key
;
1834 // Add a warning to the status object for missing IDs
1835 $missingIds = array_diff( $this->ids
, $idsPresent );
1837 foreach ( $missingIds as $id ) {
1838 $status->error( 'undelete-missing-filearchive', $id );
1841 // Remove missing files from batch, so we don't get errors when undeleting them
1842 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1844 // Run the store batch
1845 // Use the OVERWRITE_SAME flag to smooth over a common error
1846 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1847 $status->merge( $storeStatus );
1849 if ( !$status->isGood() ) {
1850 // Even if some files could be copied, fail entirely as that is the
1851 // easiest thing to do without data loss
1852 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1853 $status->ok
= false;
1854 $this->file
->unlock();
1859 // Run the DB updates
1860 // Because we have locked the image row, key conflicts should be rare.
1861 // If they do occur, we can roll back the transaction at this time with
1862 // no data loss, but leaving unregistered files scattered throughout the
1864 // This is not ideal, which is why it's important to lock the image row.
1865 if ( $insertCurrent ) {
1866 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1869 if ( $insertBatch ) {
1870 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1874 $dbw->delete( 'filearchive',
1875 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1879 // If store batch is empty (all files are missing), deletion is to be considered successful
1880 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1882 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1884 // Update site_stats
1885 $site_stats = $dbw->tableName( 'site_stats' );
1886 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1888 $this->file
->purgeEverything();
1890 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1891 $this->file
->purgeDescription();
1892 $this->file
->purgeHistory();
1896 $this->file
->unlock();
1902 * Removes non-existent files from a store batch.
1904 function removeNonexistentFiles( $triplets ) {
1905 $files = $filteredTriplets = array();
1906 foreach ( $triplets as $file )
1907 $files[$file[0]] = $file[0];
1909 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1911 foreach ( $triplets as $file ) {
1912 if ( $result[$file[0]] ) {
1913 $filteredTriplets[] = $file;
1917 return $filteredTriplets;
1921 * Removes non-existent files from a cleanup batch.
1923 function removeNonexistentFromCleanup( $batch ) {
1924 $files = $newBatch = array();
1925 $repo = $this->file
->repo
;
1927 foreach ( $batch as $file ) {
1928 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1929 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1932 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1934 foreach ( $batch as $file ) {
1935 if ( $result[$file] ) {
1936 $newBatch[] = $file;
1944 * Delete unused files in the deleted zone.
1945 * This should be called from outside the transaction in which execute() was called.
1947 function cleanup() {
1948 if ( !$this->cleanupBatch
) {
1949 return $this->file
->repo
->newGood();
1952 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1954 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1959 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
1960 $cleanupBatch = array();
1962 foreach ( $storeStatus->success
as $i => $success ) {
1964 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][1] );
1967 $this->file
->repo
->cleanupBatch( $cleanupBatch );
1971 # ------------------------------------------------------------------------------
1974 * Helper class for file movement
1977 class LocalFileMoveBatch
{
1978 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1980 function __construct( File
$file, Title
$target ) {
1981 $this->file
= $file;
1982 $this->target
= $target;
1983 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1984 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1985 $this->oldName
= $this->file
->getName();
1986 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1987 $this->oldRel
= $this->oldHash
. $this->oldName
;
1988 $this->newRel
= $this->newHash
. $this->newName
;
1989 $this->db
= $file->repo
->getMasterDb();
1993 * Add the current image to the batch
1995 function addCurrent() {
1996 $this->cur
= array( $this->oldRel
, $this->newRel
);
2000 * Add the old versions of the image to the batch
2002 function addOlds() {
2003 $archiveBase = 'archive';
2004 $this->olds
= array();
2005 $this->oldCount
= 0;
2007 $result = $this->db
->select( 'oldimage',
2008 array( 'oi_archive_name', 'oi_deleted' ),
2009 array( 'oi_name' => $this->oldName
),
2013 foreach ( $result as $row ) {
2014 $oldName = $row->oi_archive_name
;
2015 $bits = explode( '!', $oldName, 2 );
2017 if ( count( $bits ) != 2 ) {
2018 wfDebug( "Invalid old file name: $oldName \n" );
2022 list( $timestamp, $filename ) = $bits;
2024 if ( $this->oldName
!= $filename ) {
2025 wfDebug( "Invalid old file name: $oldName \n" );
2031 // Do we want to add those to oldCount?
2032 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2036 $this->olds
[] = array(
2037 "{$archiveBase}/{$this->oldHash}{$oldName}",
2038 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2046 function execute() {
2047 $repo = $this->file
->repo
;
2048 $status = $repo->newGood();
2049 $triplets = $this->getMoveTriplets();
2051 $triplets = $this->removeNonexistentFiles( $triplets );
2053 // Copy the files into their new location
2054 $statusMove = $repo->storeBatch( $triplets );
2055 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2056 if ( !$statusMove->isGood() ) {
2057 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2058 $this->cleanupTarget( $triplets );
2059 $statusMove->ok
= false;
2064 $statusDb = $this->doDBUpdates();
2065 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2066 if ( !$statusDb->isGood() ) {
2067 $this->db
->rollback();
2068 // Something went wrong with the DB updates, so remove the target files
2069 $this->cleanupTarget( $triplets );
2070 $statusDb->ok
= false;
2073 $this->db
->commit();
2075 // Everything went ok, remove the source files
2076 $this->cleanupSource( $triplets );
2078 $status->merge( $statusDb );
2079 $status->merge( $statusMove );
2085 * Do the database updates and return a new FileRepoStatus indicating how
2086 * many rows where updated.
2088 * @return FileRepoStatus
2090 function doDBUpdates() {
2091 $repo = $this->file
->repo
;
2092 $status = $repo->newGood();
2095 // Update current image
2098 array( 'img_name' => $this->newName
),
2099 array( 'img_name' => $this->oldName
),
2103 if ( $dbw->affectedRows() ) {
2104 $status->successCount++
;
2106 $status->failCount++
;
2107 $status->fatal( 'imageinvalidfilename' );
2111 // Update old images
2115 'oi_name' => $this->newName
,
2116 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2118 array( 'oi_name' => $this->oldName
),
2122 $affected = $dbw->affectedRows();
2123 $total = $this->oldCount
;
2124 $status->successCount +
= $affected;
2125 $status->failCount +
= $total - $affected;
2126 if ( $status->failCount
) {
2127 $status->error( 'imageinvalidfilename' );
2134 * Generate triplets for FSRepo::storeBatch().
2136 function getMoveTriplets() {
2137 $moves = array_merge( array( $this->cur
), $this->olds
);
2138 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2140 foreach ( $moves as $move ) {
2141 // $move: (oldRelativePath, newRelativePath)
2142 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2143 $triplets[] = array( $srcUrl, 'public', $move[1] );
2144 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2151 * Removes non-existent files from move batch.
2153 function removeNonexistentFiles( $triplets ) {
2156 foreach ( $triplets as $file ) {
2157 $files[$file[0]] = $file[0];
2160 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2161 $filteredTriplets = array();
2163 foreach ( $triplets as $file ) {
2164 if ( $result[$file[0]] ) {
2165 $filteredTriplets[] = $file;
2167 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2171 return $filteredTriplets;
2175 * Cleanup a partially moved array of triplets by deleting the target
2176 * files. Called if something went wrong half way.
2178 function cleanupTarget( $triplets ) {
2179 // Create dest pairs from the triplets
2181 foreach ( $triplets as $triplet ) {
2182 $pairs[] = array( $triplet[1], $triplet[2] );
2185 $this->file
->repo
->cleanupBatch( $pairs );
2189 * Cleanup a fully moved array of triplets by deleting the source files.
2190 * Called at the end of the move process if everything else went ok.
2192 function cleanupSource( $triplets ) {
2193 // Create source file names from the triplets
2195 foreach ( $triplets as $triplet ) {
2196 $files[] = $triplet[0];
2199 $this->file
->repo
->cleanupBatch( $files );