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
{
35 var $fileExists, # does the file file exist on disk? (loadFromXxx)
36 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
37 $historyRes, # result of the query for the file's history (nextHistoryLine)
40 $bits, # --- returned by getimagesize (loadFromXxx)
42 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
43 $mime, # MIME type, determined by MimeMagic::guessMimeType
44 $major_mime, # Major mime type
45 $minor_mime, # Minor mime type
46 $size, # Size in bytes (loadFromXxx)
47 $metadata, # Handler-specific metadata
48 $timestamp, # Upload timestamp
49 $sha1, # SHA-1 base 36 content hash
50 $user, $user_text, # User, who uploaded the file
51 $description, # Description of current revision of the file
52 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
53 $upgraded, # Whether the row was upgraded on load
54 $locked, # True if the image row is locked
55 $missing, # True if file is not present in file system. Not to be cached in memcached
56 $deleted; # Bitfield akin to rev_deleted
61 * Create a LocalFile from a title
62 * Do not call this except from inside a repo class.
64 * Note: $unused param is only here to avoid an E_STRICT
66 static function newFromTitle( $title, $repo, $unused = null ) {
67 return new self( $title, $repo );
71 * Create a LocalFile from a title
72 * Do not call this except from inside a repo class.
74 static function newFromRow( $row, $repo ) {
75 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
76 $file = new self( $title, $repo );
77 $file->loadFromRow( $row );
83 * Create a LocalFile from a SHA-1 key
84 * Do not call this except from inside a repo class.
86 static function newFromKey( $sha1, $repo, $timestamp = false ) {
87 $conds = array( 'img_sha1' => $sha1 );
90 $conds['img_timestamp'] = $timestamp;
93 $dbr = $repo->getSlaveDB();
94 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
97 return self
::newFromRow( $row, $repo );
104 * Fields in the image table
106 static function selectFields() {
127 * Do not call this except from inside a repo class.
129 function __construct( $title, $repo ) {
130 if ( !is_object( $title ) ) {
131 throw new MWException( __CLASS__
. ' constructor given bogus title.' );
134 parent
::__construct( $title, $repo );
136 $this->metadata
= '';
137 $this->historyLine
= 0;
138 $this->historyRes
= null;
139 $this->dataLoaded
= false;
143 * Get the memcached key for the main data for this file, or false if
144 * there is no access to the shared cache.
146 function getCacheKey() {
147 $hashedName = md5( $this->getName() );
149 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
153 * Try to load file metadata from memcached. Returns true on success.
155 function loadFromCache() {
158 wfProfileIn( __METHOD__
);
159 $this->dataLoaded
= false;
160 $key = $this->getCacheKey();
163 wfProfileOut( __METHOD__
);
167 $cachedValues = $wgMemc->get( $key );
169 // Check if the key existed and belongs to this version of MediaWiki
170 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
171 wfDebug( "Pulling file metadata from cache key $key\n" );
172 $this->fileExists
= $cachedValues['fileExists'];
173 if ( $this->fileExists
) {
174 $this->setProps( $cachedValues );
176 $this->dataLoaded
= true;
179 if ( $this->dataLoaded
) {
180 wfIncrStats( 'image_cache_hit' );
182 wfIncrStats( 'image_cache_miss' );
185 wfProfileOut( __METHOD__
);
186 return $this->dataLoaded
;
190 * Save the file metadata to memcached
192 function saveToCache() {
196 $key = $this->getCacheKey();
202 $fields = $this->getCacheFields( '' );
203 $cache = array( 'version' => MW_FILE_VERSION
);
204 $cache['fileExists'] = $this->fileExists
;
206 if ( $this->fileExists
) {
207 foreach ( $fields as $field ) {
208 $cache[$field] = $this->$field;
212 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
216 * Load metadata from the file itself
218 function loadFromFile() {
219 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
222 function getCacheFields( $prefix = 'img_' ) {
223 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
224 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
225 static $results = array();
227 if ( $prefix == '' ) {
231 if ( !isset( $results[$prefix] ) ) {
232 $prefixedFields = array();
233 foreach ( $fields as $field ) {
234 $prefixedFields[] = $prefix . $field;
236 $results[$prefix] = $prefixedFields;
239 return $results[$prefix];
243 * Load file metadata from the DB
245 function loadFromDB() {
246 # Polymorphic function name to distinguish foreign and local fetches
247 $fname = get_class( $this ) . '::' . __FUNCTION__
;
248 wfProfileIn( $fname );
250 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
251 $this->dataLoaded
= true;
253 $dbr = $this->repo
->getMasterDB();
255 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
256 array( 'img_name' => $this->getName() ), $fname );
259 $this->loadFromRow( $row );
261 $this->fileExists
= false;
264 wfProfileOut( $fname );
268 * Decode a row from the database (either object or array) to an array
269 * with timestamps and MIME types decoded, and the field prefix removed.
271 function decodeRow( $row, $prefix = 'img_' ) {
272 $array = (array)$row;
273 $prefixLength = strlen( $prefix );
275 // Sanity check prefix once
276 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
277 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
282 foreach ( $array as $name => $value ) {
283 $decoded[substr( $name, $prefixLength )] = $value;
286 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
288 if ( empty( $decoded['major_mime'] ) ) {
289 $decoded['mime'] = 'unknown/unknown';
291 if ( !$decoded['minor_mime'] ) {
292 $decoded['minor_mime'] = 'unknown';
294 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
297 # Trim zero padding from char/binary field
298 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
304 * Load file metadata from a DB result row
306 function loadFromRow( $row, $prefix = 'img_' ) {
307 $this->dataLoaded
= true;
308 $array = $this->decodeRow( $row, $prefix );
310 foreach ( $array as $name => $value ) {
311 $this->$name = $value;
314 $this->fileExists
= true;
315 $this->maybeUpgradeRow();
319 * Load file metadata from cache or DB, unless already loaded
322 if ( !$this->dataLoaded
) {
323 if ( !$this->loadFromCache() ) {
325 $this->saveToCache();
327 $this->dataLoaded
= true;
332 * Upgrade a row if it needs it
334 function maybeUpgradeRow() {
335 if ( wfReadOnly() ) {
339 if ( is_null( $this->media_type
) ||
340 $this->mime
== 'image/svg'
343 $this->upgraded
= true;
345 $handler = $this->getHandler();
346 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
348 $this->upgraded
= true;
353 function getUpgraded() {
354 return $this->upgraded
;
358 * Fix assorted version-related problems with the image row by reloading it from the file
360 function upgradeRow() {
361 wfProfileIn( __METHOD__
);
363 $this->loadFromFile();
365 # Don't destroy file info of missing files
366 if ( !$this->fileExists
) {
367 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
368 wfProfileOut( __METHOD__
);
372 $dbw = $this->repo
->getMasterDB();
373 list( $major, $minor ) = self
::splitMime( $this->mime
);
375 if ( wfReadOnly() ) {
376 wfProfileOut( __METHOD__
);
379 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
381 $dbw->update( 'image',
383 'img_width' => $this->width
,
384 'img_height' => $this->height
,
385 'img_bits' => $this->bits
,
386 'img_media_type' => $this->media_type
,
387 'img_major_mime' => $major,
388 'img_minor_mime' => $minor,
389 'img_metadata' => $this->metadata
,
390 'img_sha1' => $this->sha1
,
391 ), array( 'img_name' => $this->getName() ),
395 $this->saveToCache();
396 wfProfileOut( __METHOD__
);
400 * Set properties in this object to be equal to those given in the
401 * associative array $info. Only cacheable fields can be set.
403 * If 'mime' is given, it will be split into major_mime/minor_mime.
404 * If major_mime/minor_mime are given, $this->mime will also be set.
406 function setProps( $info ) {
407 $this->dataLoaded
= true;
408 $fields = $this->getCacheFields( '' );
409 $fields[] = 'fileExists';
411 foreach ( $fields as $field ) {
412 if ( isset( $info[$field] ) ) {
413 $this->$field = $info[$field];
417 // Fix up mime fields
418 if ( isset( $info['major_mime'] ) ) {
419 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
420 } elseif ( isset( $info['mime'] ) ) {
421 $this->mime
= $info['mime'];
422 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
426 /** splitMime inherited */
427 /** getName inherited */
428 /** getTitle inherited */
429 /** getURL inherited */
430 /** getViewURL inherited */
431 /** getPath inherited */
432 /** isVisible inhereted */
434 function isMissing() {
435 if ( $this->missing
=== null ) {
436 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
437 $this->missing
= !$fileExists;
439 return $this->missing
;
443 * Return the width of the image
445 * Returns false on error
447 public function getWidth( $page = 1 ) {
450 if ( $this->isMultipage() ) {
451 $dim = $this->getHandler()->getPageDimensions( $this, $page );
453 return $dim['width'];
463 * Return the height of the image
465 * Returns false on error
467 public function getHeight( $page = 1 ) {
470 if ( $this->isMultipage() ) {
471 $dim = $this->getHandler()->getPageDimensions( $this, $page );
473 return $dim['height'];
478 return $this->height
;
483 * Returns ID or name of user who uploaded the file
485 * @param $type string 'text' or 'id'
487 function getUser( $type = 'text' ) {
490 if ( $type == 'text' ) {
491 return $this->user_text
;
492 } elseif ( $type == 'id' ) {
498 * Get handler-specific metadata
500 function getMetadata() {
502 return $this->metadata
;
505 function getBitDepth() {
511 * Return the size of the image file, in bytes
513 public function getSize() {
519 * Returns the mime type of the file.
521 function getMimeType() {
527 * Return the type of the media in the file.
528 * Use the value returned by this function with the MEDIATYPE_xxx constants.
530 function getMediaType() {
532 return $this->media_type
;
535 /** canRender inherited */
536 /** mustRender inherited */
537 /** allowInlineDisplay inherited */
538 /** isSafeFile inherited */
539 /** isTrustedFile inherited */
542 * Returns true if the file file exists on disk.
543 * @return boolean Whether file file exist on disk.
545 public function exists() {
547 return $this->fileExists
;
550 /** getTransformScript inherited */
551 /** getUnscaledThumb inherited */
552 /** thumbName inherited */
553 /** createThumb inherited */
554 /** getThumbnail inherited */
555 /** transform inherited */
558 * Fix thumbnail files from 1.4 or before, with extreme prejudice
560 function migrateThumbFile( $thumbName ) {
561 $thumbDir = $this->getThumbPath();
562 $thumbPath = "$thumbDir/$thumbName";
564 if ( is_dir( $thumbPath ) ) {
565 // Directory where file should be
566 // This happened occasionally due to broken migration code in 1.5
567 // Rename to broken-*
568 for ( $i = 0; $i < 100 ; $i++
) {
569 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
570 if ( !file_exists( $broken ) ) {
571 rename( $thumbPath, $broken );
575 // Doesn't exist anymore
579 if ( is_file( $thumbDir ) ) {
580 // File where directory should be
582 // Doesn't exist anymore
587 /** getHandler inherited */
588 /** iconThumb inherited */
589 /** getLastError inherited */
592 * Get all thumbnail names previously generated for this file
594 function getThumbnails() {
598 $dir = $this->getThumbPath();
600 if ( is_dir( $dir ) ) {
601 $handle = opendir( $dir );
604 while ( false !== ( $file = readdir( $handle ) ) ) {
605 if ( $file { 0 } != '.' ) {
618 * Refresh metadata in memcached, but don't touch thumbnails or squid
620 function purgeMetadataCache() {
622 $this->saveToCache();
623 $this->purgeHistory();
627 * Purge the shared history (OldLocalFile) cache
629 function purgeHistory() {
632 $hashedName = md5( $this->getName() );
633 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
636 $wgMemc->delete( $oldKey );
641 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
643 function purgeCache() {
644 // Refresh metadata cache
645 $this->purgeMetadataCache();
648 $this->purgeThumbnails();
650 // Purge squid cache for this file
651 SquidUpdate
::purge( array( $this->getURL() ) );
655 * Delete cached transformed files
657 function purgeThumbnails() {
661 $files = $this->getThumbnails();
662 $dir = $this->getThumbPath();
665 foreach ( $files as $file ) {
666 # Check that the base file name is part of the thumb name
667 # This is a basic sanity check to avoid erasing unrelated directories
668 if ( strpos( $file, $this->getName() ) !== false ) {
669 $url = $this->getThumbUrl( $file );
671 @unlink
( "$dir/$file" );
677 SquidUpdate
::purge( $urls );
681 /** purgeDescription inherited */
682 /** purgeEverything inherited */
684 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
685 $dbr = $this->repo
->getSlaveDB();
686 $tables = array( 'oldimage' );
687 $fields = OldLocalFile
::selectFields();
688 $conds = $opts = $join_conds = array();
689 $eq = $inc ?
'=' : '';
690 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
693 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
697 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
701 $opts['LIMIT'] = $limit;
704 // Search backwards for time > x queries
705 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
706 $opts['ORDER BY'] = "oi_timestamp $order";
707 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
709 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
710 &$conds, &$opts, &$join_conds ) );
712 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
715 while ( $row = $dbr->fetchObject( $res ) ) {
716 if ( $this->repo
->oldFileFromRowFactory
) {
717 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
719 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
723 if ( $order == 'ASC' ) {
724 $r = array_reverse( $r ); // make sure it ends up descending
731 * Return the history of this file, line by line.
732 * starts with current version, then old versions.
733 * uses $this->historyLine to check which line to return:
734 * 0 return line for current version
735 * 1 query for old versions, return first one
736 * 2, ... return next old version from above query
738 public function nextHistoryLine() {
739 # Polymorphic function name to distinguish foreign and local fetches
740 $fname = get_class( $this ) . '::' . __FUNCTION__
;
742 $dbr = $this->repo
->getSlaveDB();
744 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
745 $this->historyRes
= $dbr->select( 'image',
748 "'' AS oi_archive_name",
752 array( 'img_name' => $this->title
->getDBkey() ),
756 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
757 $this->historyRes
= null;
760 } elseif ( $this->historyLine
== 1 ) {
761 $this->historyRes
= $dbr->select( 'oldimage', '*',
762 array( 'oi_name' => $this->title
->getDBkey() ),
764 array( 'ORDER BY' => 'oi_timestamp DESC' )
767 $this->historyLine ++
;
769 return $dbr->fetchObject( $this->historyRes
);
773 * Reset the history pointer to the first element of the history
775 public function resetHistory() {
776 $this->historyLine
= 0;
778 if ( !is_null( $this->historyRes
) ) {
779 $this->historyRes
= null;
783 /** getFullPath inherited */
784 /** getHashPath inherited */
785 /** getRel inherited */
786 /** getUrlRel inherited */
787 /** getArchiveRel inherited */
788 /** getThumbRel inherited */
789 /** getArchivePath inherited */
790 /** getThumbPath inherited */
791 /** getArchiveUrl inherited */
792 /** getThumbUrl inherited */
793 /** getArchiveVirtualUrl inherited */
794 /** getThumbVirtualUrl inherited */
795 /** isHashed inherited */
798 * Upload a file and record it in the DB
799 * @param $srcPath String: source path or virtual URL
800 * @param $comment String: upload description
801 * @param $pageText String: text to use for the new description page,
802 * if a new description page is created
803 * @param $flags Integer: flags for publish()
804 * @param $props Array: File properties, if known. This can be used to reduce the
805 * upload time when uploading virtual URLs for which the file info
807 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
808 * @param $user Mixed: User object or null to use $wgUser
810 * @return FileRepoStatus object. On success, the value member contains the
811 * archive name, or an empty string if it was a new file.
813 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
815 $status = $this->publish( $srcPath, $flags );
818 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
819 $status->fatal( 'filenotfound', $srcPath );
829 * Record a file upload in the upload log and the image table
830 * @deprecated use upload()
832 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
833 $watch = false, $timestamp = false )
835 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
837 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
843 $wgUser->addWatch( $this->getTitle() );
850 * Record a file upload in the upload log and the image table
852 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
854 if ( is_null( $user ) ) {
859 $dbw = $this->repo
->getMasterDB();
863 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
866 $props['description'] = $comment;
867 $props['user'] = $user->getId();
868 $props['user_text'] = $user->getName();
869 $props['timestamp'] = wfTimestamp( TS_MW
);
870 $this->setProps( $props );
873 $this->purgeThumbnails();
875 # The file is already on its final location, remove it from the squid cache
876 SquidUpdate
::purge( array( $this->getURL() ) );
878 # Fail now if the file isn't there
879 if ( !$this->fileExists
) {
880 wfDebug( __METHOD__
. ": File " . $this->getPath() . " went missing!\n" );
886 if ( $timestamp === false ) {
887 $timestamp = $dbw->timestamp();
890 # Test to see if the row exists using INSERT IGNORE
891 # This avoids race conditions by locking the row until the commit, and also
892 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
893 $dbw->insert( 'image',
895 'img_name' => $this->getName(),
896 'img_size' => $this->size
,
897 'img_width' => intval( $this->width
),
898 'img_height' => intval( $this->height
),
899 'img_bits' => $this->bits
,
900 'img_media_type' => $this->media_type
,
901 'img_major_mime' => $this->major_mime
,
902 'img_minor_mime' => $this->minor_mime
,
903 'img_timestamp' => $timestamp,
904 'img_description' => $comment,
905 'img_user' => $user->getId(),
906 'img_user_text' => $user->getName(),
907 'img_metadata' => $this->metadata
,
908 'img_sha1' => $this->sha1
914 if ( $dbw->affectedRows() == 0 ) {
917 # Collision, this is an update of a file
918 # Insert previous contents into oldimage
919 $dbw->insertSelect( 'oldimage', 'image',
921 'oi_name' => 'img_name',
922 'oi_archive_name' => $dbw->addQuotes( $oldver ),
923 'oi_size' => 'img_size',
924 'oi_width' => 'img_width',
925 'oi_height' => 'img_height',
926 'oi_bits' => 'img_bits',
927 'oi_timestamp' => 'img_timestamp',
928 'oi_description' => 'img_description',
929 'oi_user' => 'img_user',
930 'oi_user_text' => 'img_user_text',
931 'oi_metadata' => 'img_metadata',
932 'oi_media_type' => 'img_media_type',
933 'oi_major_mime' => 'img_major_mime',
934 'oi_minor_mime' => 'img_minor_mime',
935 'oi_sha1' => 'img_sha1'
936 ), array( 'img_name' => $this->getName() ), __METHOD__
939 # Update the current image row
940 $dbw->update( 'image',
942 'img_size' => $this->size
,
943 'img_width' => intval( $this->width
),
944 'img_height' => intval( $this->height
),
945 'img_bits' => $this->bits
,
946 'img_media_type' => $this->media_type
,
947 'img_major_mime' => $this->major_mime
,
948 'img_minor_mime' => $this->minor_mime
,
949 'img_timestamp' => $timestamp,
950 'img_description' => $comment,
951 'img_user' => $user->getId(),
952 'img_user_text' => $user->getName(),
953 'img_metadata' => $this->metadata
,
954 'img_sha1' => $this->sha1
955 ), array( /* WHERE */
956 'img_name' => $this->getName()
961 # Update the image count
962 $site_stats = $dbw->tableName( 'site_stats' );
963 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
966 $descTitle = $this->getTitle();
967 $article = new ImagePage( $descTitle );
968 $article->setFile( $this );
971 $log = new LogPage( 'upload' );
972 $action = $reupload ?
'overwrite' : 'upload';
973 $log->addEntry( $action, $descTitle, $comment, array(), $user );
975 if ( $descTitle->exists() ) {
976 # Create a null revision
977 $latest = $descTitle->getLatestRevID();
978 $nullRevision = Revision
::newNullRevision(
980 $descTitle->getArticleId(),
981 $log->getRcComment(),
984 $nullRevision->insertOn( $dbw );
986 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
987 $article->updateRevisionOn( $dbw, $nullRevision );
989 # Invalidate the cache for the description page
990 $descTitle->invalidateCache();
991 $descTitle->purgeSquid();
993 # New file; create the description page.
994 # There's already a log entry, so don't make a second RC entry
995 # Squid and file cache for the description page are purged by doEdit.
996 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
999 # Commit the transaction now, in case something goes wrong later
1000 # The most important thing is that files don't get lost, especially archives
1003 # Save to cache and purge the squid
1004 # We shall not saveToCache before the commit since otherwise
1005 # in case of a rollback there is an usable file from memcached
1006 # which in fact doesn't really exist (bug 24978)
1007 $this->saveToCache();
1009 # Hooks, hooks, the magic of hooks...
1010 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1012 # Invalidate cache for all pages using this file
1013 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1014 $update->doUpdate();
1016 # Invalidate cache for all pages that redirects on this page
1017 $redirs = $this->getTitle()->getRedirectsHere();
1019 foreach ( $redirs as $redir ) {
1020 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1021 $update->doUpdate();
1028 * Move or copy a file to its public location. If a file exists at the
1029 * destination, move it to an archive. Returns a FileRepoStatus object with
1030 * the archive name in the "value" member on success.
1032 * The archive name should be passed through to recordUpload for database
1035 * @param $srcPath String: local filesystem path to the source image
1036 * @param $flags Integer: a bitwise combination of:
1037 * File::DELETE_SOURCE Delete the source file, i.e. move
1039 * @return FileRepoStatus object. On success, the value member contains the
1040 * archive name, or an empty string if it was a new file.
1042 function publish( $srcPath, $flags = 0 ) {
1045 $dstRel = $this->getRel();
1046 $archiveName = gmdate( 'YmdHis' ) . '!' . $this->getName();
1047 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1048 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1049 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1051 if ( $status->value
== 'new' ) {
1052 $status->value
= '';
1054 $status->value
= $archiveName;
1062 /** getLinksTo inherited */
1063 /** getExifData inherited */
1064 /** isLocal inherited */
1065 /** wasDeleted inherited */
1068 * Move file to the new title
1070 * Move current, old version and all thumbnails
1071 * to the new filename. Old file is deleted.
1073 * Cache purging is done; checks for validity
1074 * and logging are caller's responsibility
1076 * @param $target Title New file name
1077 * @return FileRepoStatus object.
1079 function move( $target ) {
1080 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1083 $batch = new LocalFileMoveBatch( $this, $target );
1084 $batch->addCurrent();
1087 $status = $batch->execute();
1088 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1090 $this->purgeEverything();
1093 if ( $status->isOk() ) {
1094 // Now switch the object
1095 $this->title
= $target;
1096 // Force regeneration of the name and hashpath
1097 unset( $this->name
);
1098 unset( $this->hashPath
);
1099 // Purge the new image
1100 $this->purgeEverything();
1107 * Delete all versions of the file.
1109 * Moves the files into an archive directory (or deletes them)
1110 * and removes the database rows.
1112 * Cache purging is done; logging is caller's responsibility.
1116 * @return FileRepoStatus object.
1118 function delete( $reason, $suppress = false ) {
1121 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1122 $batch->addCurrent();
1124 # Get old version relative paths
1125 $dbw = $this->repo
->getMasterDB();
1126 $result = $dbw->select( 'oldimage',
1127 array( 'oi_archive_name' ),
1128 array( 'oi_name' => $this->getName() ) );
1129 while ( $row = $dbw->fetchObject( $result ) ) {
1130 $batch->addOld( $row->oi_archive_name
);
1132 $status = $batch->execute();
1134 if ( $status->ok
) {
1135 // Update site_stats
1136 $site_stats = $dbw->tableName( 'site_stats' );
1137 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1138 $this->purgeEverything();
1147 * Delete an old version of the file.
1149 * Moves the file into an archive directory (or deletes it)
1150 * and removes the database row.
1152 * Cache purging is done; logging is caller's responsibility.
1154 * @param $archiveName String
1155 * @param $reason String
1156 * @param $suppress Boolean
1157 * @throws MWException or FSException on database or file store failure
1158 * @return FileRepoStatus object.
1160 function deleteOld( $archiveName, $reason, $suppress = false ) {
1163 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1164 $batch->addOld( $archiveName );
1165 $status = $batch->execute();
1169 if ( $status->ok
) {
1170 $this->purgeDescription();
1171 $this->purgeHistory();
1178 * Restore all or specified deleted revisions to the given file.
1179 * Permissions and logging are left to the caller.
1181 * May throw database exceptions on error.
1183 * @param $versions set of record ids of deleted items to restore,
1184 * or empty to restore all revisions.
1185 * @param $unsuppress Boolean
1186 * @return FileRepoStatus
1188 function restore( $versions = array(), $unsuppress = false ) {
1189 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1194 $batch->addIds( $versions );
1197 $status = $batch->execute();
1199 if ( !$status->ok
) {
1203 $cleanupStatus = $batch->cleanup();
1204 $cleanupStatus->successCount
= 0;
1205 $cleanupStatus->failCount
= 0;
1206 $status->merge( $cleanupStatus );
1211 /** isMultipage inherited */
1212 /** pageCount inherited */
1213 /** scaleHeight inherited */
1214 /** getImageSize inherited */
1216 /** getDescriptionUrl inherited */
1217 /** getDescriptionText inherited */
1219 function getDescription() {
1221 return $this->description
;
1224 function getTimestamp() {
1226 return $this->timestamp
;
1229 function getSha1() {
1231 // Initialise now if necessary
1232 if ( $this->sha1
== '' && $this->fileExists
) {
1233 $this->sha1
= File
::sha1Base36( $this->getPath() );
1234 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1235 $dbw = $this->repo
->getMasterDB();
1236 $dbw->update( 'image',
1237 array( 'img_sha1' => $this->sha1
),
1238 array( 'img_name' => $this->getName() ),
1240 $this->saveToCache();
1248 * Start a transaction and lock the image for update
1249 * Increments a reference counter if the lock is already held
1250 * @return boolean True if the image exists, false otherwise
1253 $dbw = $this->repo
->getMasterDB();
1255 if ( !$this->locked
) {
1260 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1264 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1265 * the transaction and thereby releases the image lock.
1268 if ( $this->locked
) {
1270 if ( !$this->locked
) {
1271 $dbw = $this->repo
->getMasterDB();
1278 * Roll back the DB transaction and mark the image unlocked
1280 function unlockAndRollback() {
1281 $this->locked
= false;
1282 $dbw = $this->repo
->getMasterDB();
1285 } // LocalFile class
1287 # ------------------------------------------------------------------------------
1290 * Helper class for file deletion
1293 class LocalFileDeleteBatch
{
1294 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1297 function __construct( File
$file, $reason = '', $suppress = false ) {
1298 $this->file
= $file;
1299 $this->reason
= $reason;
1300 $this->suppress
= $suppress;
1301 $this->status
= $file->repo
->newGood();
1304 function addCurrent() {
1305 $this->srcRels
['.'] = $this->file
->getRel();
1308 function addOld( $oldName ) {
1309 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1310 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1313 function getOldRels() {
1314 if ( !isset( $this->srcRels
['.'] ) ) {
1315 $oldRels =& $this->srcRels
;
1316 $deleteCurrent = false;
1318 $oldRels = $this->srcRels
;
1319 unset( $oldRels['.'] );
1320 $deleteCurrent = true;
1323 return array( $oldRels, $deleteCurrent );
1326 /*protected*/ function getHashes() {
1328 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1330 if ( $deleteCurrent ) {
1331 $hashes['.'] = $this->file
->getSha1();
1334 if ( count( $oldRels ) ) {
1335 $dbw = $this->file
->repo
->getMasterDB();
1336 $res = $dbw->select(
1338 array( 'oi_archive_name', 'oi_sha1' ),
1339 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1343 while ( $row = $dbw->fetchObject( $res ) ) {
1344 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1345 // Get the hash from the file
1346 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1347 $props = $this->file
->repo
->getFileProps( $oldUrl );
1349 if ( $props['fileExists'] ) {
1350 // Upgrade the oldimage row
1351 $dbw->update( 'oldimage',
1352 array( 'oi_sha1' => $props['sha1'] ),
1353 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1355 $hashes[$row->oi_archive_name
] = $props['sha1'];
1357 $hashes[$row->oi_archive_name
] = false;
1360 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1365 $missing = array_diff_key( $this->srcRels
, $hashes );
1367 foreach ( $missing as $name => $rel ) {
1368 $this->status
->error( 'filedelete-old-unregistered', $name );
1371 foreach ( $hashes as $name => $hash ) {
1373 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1374 unset( $hashes[$name] );
1381 function doDBInserts() {
1384 $dbw = $this->file
->repo
->getMasterDB();
1385 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1386 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1387 $encReason = $dbw->addQuotes( $this->reason
);
1388 $encGroup = $dbw->addQuotes( 'deleted' );
1389 $ext = $this->file
->getExtension();
1390 $dotExt = $ext === '' ?
'' : ".$ext";
1391 $encExt = $dbw->addQuotes( $dotExt );
1392 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1394 // Bitfields to further suppress the content
1395 if ( $this->suppress
) {
1397 // This should be 15...
1398 $bitfield |
= Revision
::DELETED_TEXT
;
1399 $bitfield |
= Revision
::DELETED_COMMENT
;
1400 $bitfield |
= Revision
::DELETED_USER
;
1401 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1403 $bitfield = 'oi_deleted';
1406 if ( $deleteCurrent ) {
1407 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1408 $where = array( 'img_name' => $this->file
->getName() );
1409 $dbw->insertSelect( 'filearchive', 'image',
1411 'fa_storage_group' => $encGroup,
1412 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1413 'fa_deleted_user' => $encUserId,
1414 'fa_deleted_timestamp' => $encTimestamp,
1415 'fa_deleted_reason' => $encReason,
1416 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1418 'fa_name' => 'img_name',
1419 'fa_archive_name' => 'NULL',
1420 'fa_size' => 'img_size',
1421 'fa_width' => 'img_width',
1422 'fa_height' => 'img_height',
1423 'fa_metadata' => 'img_metadata',
1424 'fa_bits' => 'img_bits',
1425 'fa_media_type' => 'img_media_type',
1426 'fa_major_mime' => 'img_major_mime',
1427 'fa_minor_mime' => 'img_minor_mime',
1428 'fa_description' => 'img_description',
1429 'fa_user' => 'img_user',
1430 'fa_user_text' => 'img_user_text',
1431 'fa_timestamp' => 'img_timestamp'
1432 ), $where, __METHOD__
);
1435 if ( count( $oldRels ) ) {
1436 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1438 'oi_name' => $this->file
->getName(),
1439 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1440 $dbw->insertSelect( 'filearchive', 'oldimage',
1442 'fa_storage_group' => $encGroup,
1443 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1444 'fa_deleted_user' => $encUserId,
1445 'fa_deleted_timestamp' => $encTimestamp,
1446 'fa_deleted_reason' => $encReason,
1447 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1449 'fa_name' => 'oi_name',
1450 'fa_archive_name' => 'oi_archive_name',
1451 'fa_size' => 'oi_size',
1452 'fa_width' => 'oi_width',
1453 'fa_height' => 'oi_height',
1454 'fa_metadata' => 'oi_metadata',
1455 'fa_bits' => 'oi_bits',
1456 'fa_media_type' => 'oi_media_type',
1457 'fa_major_mime' => 'oi_major_mime',
1458 'fa_minor_mime' => 'oi_minor_mime',
1459 'fa_description' => 'oi_description',
1460 'fa_user' => 'oi_user',
1461 'fa_user_text' => 'oi_user_text',
1462 'fa_timestamp' => 'oi_timestamp',
1463 'fa_deleted' => $bitfield
1464 ), $where, __METHOD__
);
1468 function doDBDeletes() {
1469 $dbw = $this->file
->repo
->getMasterDB();
1470 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1472 if ( count( $oldRels ) ) {
1473 $dbw->delete( 'oldimage',
1475 'oi_name' => $this->file
->getName(),
1476 'oi_archive_name' => array_keys( $oldRels )
1480 if ( $deleteCurrent ) {
1481 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1486 * Run the transaction
1488 function execute() {
1490 wfProfileIn( __METHOD__
);
1492 $this->file
->lock();
1493 // Leave private files alone
1494 $privateFiles = array();
1495 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1496 $dbw = $this->file
->repo
->getMasterDB();
1498 if ( !empty( $oldRels ) ) {
1499 $res = $dbw->select( 'oldimage',
1500 array( 'oi_archive_name' ),
1501 array( 'oi_name' => $this->file
->getName(),
1502 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1503 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1506 while ( $row = $dbw->fetchObject( $res ) ) {
1507 $privateFiles[$row->oi_archive_name
] = 1;
1510 // Prepare deletion batch
1511 $hashes = $this->getHashes();
1512 $this->deletionBatch
= array();
1513 $ext = $this->file
->getExtension();
1514 $dotExt = $ext === '' ?
'' : ".$ext";
1516 foreach ( $this->srcRels
as $name => $srcRel ) {
1517 // Skip files that have no hash (missing source).
1518 // Keep private files where they are.
1519 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1520 $hash = $hashes[$name];
1521 $key = $hash . $dotExt;
1522 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1523 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1527 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1528 // We acquire this lock by running the inserts now, before the file operations.
1530 // This potentially has poor lock contention characteristics -- an alternative
1531 // scheme would be to insert stub filearchive entries with no fa_name and commit
1532 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1533 $this->doDBInserts();
1535 // Removes non-existent file from the batch, so we don't get errors.
1536 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1538 // Execute the file deletion batch
1539 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1541 if ( !$status->isGood() ) {
1542 $this->status
->merge( $status );
1545 if ( !$this->status
->ok
) {
1546 // Critical file deletion error
1547 // Roll back inserts, release lock and abort
1548 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1549 $this->file
->unlockAndRollback();
1550 wfProfileOut( __METHOD__
);
1551 return $this->status
;
1555 if ( $wgUseSquid ) {
1558 foreach ( $this->srcRels
as $srcRel ) {
1559 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1560 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1562 SquidUpdate
::purge( $urls );
1565 // Delete image/oldimage rows
1566 $this->doDBDeletes();
1568 // Commit and return
1569 $this->file
->unlock();
1570 wfProfileOut( __METHOD__
);
1572 return $this->status
;
1576 * Removes non-existent files from a deletion batch.
1578 function removeNonexistentFiles( $batch ) {
1579 $files = $newBatch = array();
1581 foreach ( $batch as $batchItem ) {
1582 list( $src, $dest ) = $batchItem;
1583 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1586 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1588 foreach ( $batch as $batchItem ) {
1589 if ( $result[$batchItem[0]] ) {
1590 $newBatch[] = $batchItem;
1598 # ------------------------------------------------------------------------------
1601 * Helper class for file undeletion
1604 class LocalFileRestoreBatch
{
1605 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1607 function __construct( File
$file, $unsuppress = false ) {
1608 $this->file
= $file;
1609 $this->cleanupBatch
= $this->ids
= array();
1610 $this->ids
= array();
1611 $this->unsuppress
= $unsuppress;
1617 function addId( $fa_id ) {
1618 $this->ids
[] = $fa_id;
1622 * Add a whole lot of files by ID
1624 function addIds( $ids ) {
1625 $this->ids
= array_merge( $this->ids
, $ids );
1629 * Add all revisions of the file
1636 * Run the transaction, except the cleanup batch.
1637 * The cleanup batch should be run in a separate transaction, because it locks different
1638 * rows and there's no need to keep the image row locked while it's acquiring those locks
1639 * The caller may have its own transaction open.
1640 * So we save the batch and let the caller call cleanup()
1642 function execute() {
1645 if ( !$this->all
&& !$this->ids
) {
1647 return $this->file
->repo
->newGood();
1650 $exists = $this->file
->lock();
1651 $dbw = $this->file
->repo
->getMasterDB();
1652 $status = $this->file
->repo
->newGood();
1654 // Fetch all or selected archived revisions for the file,
1655 // sorted from the most recent to the oldest.
1656 $conditions = array( 'fa_name' => $this->file
->getName() );
1658 if ( !$this->all
) {
1659 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1662 $result = $dbw->select( 'filearchive', '*',
1665 array( 'ORDER BY' => 'fa_timestamp DESC' )
1668 $idsPresent = array();
1669 $storeBatch = array();
1670 $insertBatch = array();
1671 $insertCurrent = false;
1672 $deleteIds = array();
1674 $archiveNames = array();
1676 while ( $row = $dbw->fetchObject( $result ) ) {
1677 $idsPresent[] = $row->fa_id
;
1679 if ( $row->fa_name
!= $this->file
->getName() ) {
1680 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1681 $status->failCount++
;
1685 if ( $row->fa_storage_key
== '' ) {
1686 // Revision was missing pre-deletion
1687 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1688 $status->failCount++
;
1692 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1693 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1695 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1698 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1699 $sha1 = substr( $sha1, 1 );
1702 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1703 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1704 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1705 ||
is_null( $row->fa_metadata
) ) {
1706 // Refresh our metadata
1707 // Required for a new current revision; nice for older ones too. :)
1708 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1711 'minor_mime' => $row->fa_minor_mime
,
1712 'major_mime' => $row->fa_major_mime
,
1713 'media_type' => $row->fa_media_type
,
1714 'metadata' => $row->fa_metadata
1718 if ( $first && !$exists ) {
1719 // This revision will be published as the new current version
1720 $destRel = $this->file
->getRel();
1721 $insertCurrent = array(
1722 'img_name' => $row->fa_name
,
1723 'img_size' => $row->fa_size
,
1724 'img_width' => $row->fa_width
,
1725 'img_height' => $row->fa_height
,
1726 'img_metadata' => $props['metadata'],
1727 'img_bits' => $row->fa_bits
,
1728 'img_media_type' => $props['media_type'],
1729 'img_major_mime' => $props['major_mime'],
1730 'img_minor_mime' => $props['minor_mime'],
1731 'img_description' => $row->fa_description
,
1732 'img_user' => $row->fa_user
,
1733 'img_user_text' => $row->fa_user_text
,
1734 'img_timestamp' => $row->fa_timestamp
,
1738 // The live (current) version cannot be hidden!
1739 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1740 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1741 $this->cleanupBatch
[] = $row->fa_storage_key
;
1744 $archiveName = $row->fa_archive_name
;
1746 if ( $archiveName == '' ) {
1747 // This was originally a current version; we
1748 // have to devise a new archive name for it.
1749 // Format is <timestamp of archiving>!<name>
1750 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1753 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1755 } while ( isset( $archiveNames[$archiveName] ) );
1758 $archiveNames[$archiveName] = true;
1759 $destRel = $this->file
->getArchiveRel( $archiveName );
1760 $insertBatch[] = array(
1761 'oi_name' => $row->fa_name
,
1762 'oi_archive_name' => $archiveName,
1763 'oi_size' => $row->fa_size
,
1764 'oi_width' => $row->fa_width
,
1765 'oi_height' => $row->fa_height
,
1766 'oi_bits' => $row->fa_bits
,
1767 'oi_description' => $row->fa_description
,
1768 'oi_user' => $row->fa_user
,
1769 'oi_user_text' => $row->fa_user_text
,
1770 'oi_timestamp' => $row->fa_timestamp
,
1771 'oi_metadata' => $props['metadata'],
1772 'oi_media_type' => $props['media_type'],
1773 'oi_major_mime' => $props['major_mime'],
1774 'oi_minor_mime' => $props['minor_mime'],
1775 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1776 'oi_sha1' => $sha1 );
1779 $deleteIds[] = $row->fa_id
;
1781 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1782 // private files can stay where they are
1783 $status->successCount++
;
1785 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1786 $this->cleanupBatch
[] = $row->fa_storage_key
;
1794 // Add a warning to the status object for missing IDs
1795 $missingIds = array_diff( $this->ids
, $idsPresent );
1797 foreach ( $missingIds as $id ) {
1798 $status->error( 'undelete-missing-filearchive', $id );
1801 // Remove missing files from batch, so we don't get errors when undeleting them
1802 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1804 // Run the store batch
1805 // Use the OVERWRITE_SAME flag to smooth over a common error
1806 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1807 $status->merge( $storeStatus );
1809 if ( !$status->ok
) {
1810 // Store batch returned a critical error -- this usually means nothing was stored
1811 // Stop now and return an error
1812 $this->file
->unlock();
1817 // Run the DB updates
1818 // Because we have locked the image row, key conflicts should be rare.
1819 // If they do occur, we can roll back the transaction at this time with
1820 // no data loss, but leaving unregistered files scattered throughout the
1822 // This is not ideal, which is why it's important to lock the image row.
1823 if ( $insertCurrent ) {
1824 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1827 if ( $insertBatch ) {
1828 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1832 $dbw->delete( 'filearchive',
1833 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1837 // If store batch is empty (all files are missing), deletion is to be considered successful
1838 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1840 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1842 // Update site_stats
1843 $site_stats = $dbw->tableName( 'site_stats' );
1844 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1846 $this->file
->purgeEverything();
1848 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1849 $this->file
->purgeDescription();
1850 $this->file
->purgeHistory();
1854 $this->file
->unlock();
1860 * Removes non-existent files from a store batch.
1862 function removeNonexistentFiles( $triplets ) {
1863 $files = $filteredTriplets = array();
1864 foreach ( $triplets as $file )
1865 $files[$file[0]] = $file[0];
1867 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1869 foreach ( $triplets as $file ) {
1870 if ( $result[$file[0]] ) {
1871 $filteredTriplets[] = $file;
1875 return $filteredTriplets;
1879 * Removes non-existent files from a cleanup batch.
1881 function removeNonexistentFromCleanup( $batch ) {
1882 $files = $newBatch = array();
1883 $repo = $this->file
->repo
;
1885 foreach ( $batch as $file ) {
1886 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1887 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1890 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1892 foreach ( $batch as $file ) {
1893 if ( $result[$file] ) {
1894 $newBatch[] = $file;
1902 * Delete unused files in the deleted zone.
1903 * This should be called from outside the transaction in which execute() was called.
1905 function cleanup() {
1906 if ( !$this->cleanupBatch
) {
1907 return $this->file
->repo
->newGood();
1910 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
1912 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
1918 # ------------------------------------------------------------------------------
1921 * Helper class for file movement
1924 class LocalFileMoveBatch
{
1925 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1927 function __construct( File
$file, Title
$target ) {
1928 $this->file
= $file;
1929 $this->target
= $target;
1930 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
1931 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
1932 $this->oldName
= $this->file
->getName();
1933 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
1934 $this->oldRel
= $this->oldHash
. $this->oldName
;
1935 $this->newRel
= $this->newHash
. $this->newName
;
1936 $this->db
= $file->repo
->getMasterDb();
1940 * Add the current image to the batch
1942 function addCurrent() {
1943 $this->cur
= array( $this->oldRel
, $this->newRel
);
1947 * Add the old versions of the image to the batch
1949 function addOlds() {
1950 $archiveBase = 'archive';
1951 $this->olds
= array();
1952 $this->oldCount
= 0;
1954 $result = $this->db
->select( 'oldimage',
1955 array( 'oi_archive_name', 'oi_deleted' ),
1956 array( 'oi_name' => $this->oldName
),
1960 while ( $row = $this->db
->fetchObject( $result ) ) {
1961 $oldName = $row->oi_archive_name
;
1962 $bits = explode( '!', $oldName, 2 );
1964 if ( count( $bits ) != 2 ) {
1965 wfDebug( "Invalid old file name: $oldName \n" );
1969 list( $timestamp, $filename ) = $bits;
1971 if ( $this->oldName
!= $filename ) {
1972 wfDebug( "Invalid old file name: $oldName \n" );
1978 // Do we want to add those to oldCount?
1979 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
1983 $this->olds
[] = array(
1984 "{$archiveBase}/{$this->oldHash}{$oldName}",
1985 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1993 function execute() {
1994 $repo = $this->file
->repo
;
1995 $status = $repo->newGood();
1996 $triplets = $this->getMoveTriplets();
1998 $triplets = $this->removeNonexistentFiles( $triplets );
1999 $statusDb = $this->doDBUpdates();
2000 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2001 $statusMove = $repo->storeBatch( $triplets, FSRepo
::DELETE_SOURCE
);
2002 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2004 if ( !$statusMove->isOk() ) {
2005 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2006 $this->db
->rollback();
2009 $status->merge( $statusDb );
2010 $status->merge( $statusMove );
2016 * Do the database updates and return a new FileRepoStatus indicating how
2017 * many rows where updated.
2019 * @return FileRepoStatus
2021 function doDBUpdates() {
2022 $repo = $this->file
->repo
;
2023 $status = $repo->newGood();
2026 // Update current image
2029 array( 'img_name' => $this->newName
),
2030 array( 'img_name' => $this->oldName
),
2034 if ( $dbw->affectedRows() ) {
2035 $status->successCount++
;
2037 $status->failCount++
;
2040 // Update old images
2044 'oi_name' => $this->newName
,
2045 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2047 array( 'oi_name' => $this->oldName
),
2051 $affected = $dbw->affectedRows();
2052 $total = $this->oldCount
;
2053 $status->successCount +
= $affected;
2054 $status->failCount +
= $total - $affected;
2060 * Generate triplets for FSRepo::storeBatch().
2062 function getMoveTriplets() {
2063 $moves = array_merge( array( $this->cur
), $this->olds
);
2064 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2066 foreach ( $moves as $move ) {
2067 // $move: (oldRelativePath, newRelativePath)
2068 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2069 $triplets[] = array( $srcUrl, 'public', $move[1] );
2070 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2077 * Removes non-existent files from move batch.
2079 function removeNonexistentFiles( $triplets ) {
2082 foreach ( $triplets as $file ) {
2083 $files[$file[0]] = $file[0];
2086 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2087 $filteredTriplets = array();
2089 foreach ( $triplets as $file ) {
2090 if ( $result[$file[0]] ) {
2091 $filteredTriplets[] = $file;
2093 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2097 return $filteredTriplets;