3 * Local file in the wiki's own database
10 * Bump this number when serialized cache records may be incompatible.
12 define( 'MW_FILE_VERSION', 8 );
15 * Class to represent a local file in the wiki's own database
17 * Provides methods to retrieve paths (physical, logical, URL),
18 * to generate image thumbnails or for uploading.
20 * Note that only the repo object knows what its file class is called. You should
21 * never name a file class explictly outside of the repo class. Instead use the
22 * repo's factory functions to generate file objects, for example:
24 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
26 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
31 class LocalFile
extends File
{
36 $fileExists, # does the file exist on disk? (loadFromXxx)
37 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
38 $historyRes, # result of the query for the file's history (nextHistoryLine)
41 $bits, # --- returned by getimagesize (loadFromXxx)
43 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
44 $mime, # MIME type, determined by MimeMagic::guessMimeType
45 $major_mime, # Major mime type
46 $minor_mime, # Minor mime type
47 $size, # Size in bytes (loadFromXxx)
48 $metadata, # Handler-specific metadata
49 $timestamp, # Upload timestamp
50 $sha1, # SHA-1 base 36 content hash
51 $user, $user_text, # User, who uploaded the file
52 $description, # Description of current revision of the file
53 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
54 $upgraded, # Whether the row was upgraded on load
55 $locked, # True if the image row is locked
56 $missing, # True if file is not present in file system. Not to be cached in memcached
57 $deleted; # Bitfield akin to rev_deleted
61 protected $repoClass = 'LocalRepo';
64 * Create a LocalFile from a title
65 * Do not call this except from inside a repo class.
67 * Note: $unused param is only here to avoid an E_STRICT
75 static function newFromTitle( $title, $repo, $unused = null ) {
76 return new self( $title, $repo );
80 * Create a LocalFile from a title
81 * Do not call this except from inside a repo class.
88 static function newFromRow( $row, $repo ) {
89 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
90 $file = new self( $title, $repo );
91 $file->loadFromRow( $row );
97 * Create a LocalFile from a SHA-1 key
98 * Do not call this except from inside a repo class.
100 * @param $sha1 string base-36 SHA-1
101 * @param $repo LocalRepo
102 * @param string|bool $timestamp MW_timestamp (optional)
104 * @return bool|LocalFile
106 static function newFromKey( $sha1, $repo, $timestamp = false ) {
107 $dbr = $repo->getSlaveDB();
109 $conds = array( 'img_sha1' => $sha1 );
111 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
114 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
116 return self
::newFromRow( $row, $repo );
123 * Fields in the image table
125 static function selectFields() {
146 * Do not call this except from inside a repo class.
148 function __construct( $title, $repo ) {
149 parent
::__construct( $title, $repo );
151 $this->metadata
= '';
152 $this->historyLine
= 0;
153 $this->historyRes
= null;
154 $this->dataLoaded
= false;
156 $this->assertRepoDefined();
157 $this->assertTitleDefined();
161 * Get the memcached key for the main data for this file, or false if
162 * there is no access to the shared cache.
164 function getCacheKey() {
165 $hashedName = md5( $this->getName() );
167 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
171 * Try to load file metadata from memcached. Returns true on success.
173 function loadFromCache() {
176 wfProfileIn( __METHOD__
);
177 $this->dataLoaded
= false;
178 $key = $this->getCacheKey();
181 wfProfileOut( __METHOD__
);
185 $cachedValues = $wgMemc->get( $key );
187 // Check if the key existed and belongs to this version of MediaWiki
188 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
189 wfDebug( "Pulling file metadata from cache key $key\n" );
190 $this->fileExists
= $cachedValues['fileExists'];
191 if ( $this->fileExists
) {
192 $this->setProps( $cachedValues );
194 $this->dataLoaded
= true;
197 if ( $this->dataLoaded
) {
198 wfIncrStats( 'image_cache_hit' );
200 wfIncrStats( 'image_cache_miss' );
203 wfProfileOut( __METHOD__
);
204 return $this->dataLoaded
;
208 * Save the file metadata to memcached
210 function saveToCache() {
214 $key = $this->getCacheKey();
220 $fields = $this->getCacheFields( '' );
221 $cache = array( 'version' => MW_FILE_VERSION
);
222 $cache['fileExists'] = $this->fileExists
;
224 if ( $this->fileExists
) {
225 foreach ( $fields as $field ) {
226 $cache[$field] = $this->$field;
230 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
234 * Load metadata from the file itself
236 function loadFromFile() {
237 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
240 function getCacheFields( $prefix = 'img_' ) {
241 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
242 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
243 static $results = array();
245 if ( $prefix == '' ) {
249 if ( !isset( $results[$prefix] ) ) {
250 $prefixedFields = array();
251 foreach ( $fields as $field ) {
252 $prefixedFields[] = $prefix . $field;
254 $results[$prefix] = $prefixedFields;
257 return $results[$prefix];
261 * Load file metadata from the DB
263 function loadFromDB() {
264 # Polymorphic function name to distinguish foreign and local fetches
265 $fname = get_class( $this ) . '::' . __FUNCTION__
;
266 wfProfileIn( $fname );
268 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
269 $this->dataLoaded
= true;
271 $dbr = $this->repo
->getMasterDB();
273 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
274 array( 'img_name' => $this->getName() ), $fname );
277 $this->loadFromRow( $row );
279 $this->fileExists
= false;
282 wfProfileOut( $fname );
286 * Decode a row from the database (either object or array) to an array
287 * with timestamps and MIME types decoded, and the field prefix removed.
289 function decodeRow( $row, $prefix = 'img_' ) {
290 $array = (array)$row;
291 $prefixLength = strlen( $prefix );
293 // Sanity check prefix once
294 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
295 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
300 foreach ( $array as $name => $value ) {
301 $decoded[substr( $name, $prefixLength )] = $value;
304 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
306 if ( empty( $decoded['major_mime'] ) ) {
307 $decoded['mime'] = 'unknown/unknown';
309 if ( !$decoded['minor_mime'] ) {
310 $decoded['minor_mime'] = 'unknown';
312 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
315 # Trim zero padding from char/binary field
316 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
322 * Load file metadata from a DB result row
324 function loadFromRow( $row, $prefix = 'img_' ) {
325 $this->dataLoaded
= true;
326 $array = $this->decodeRow( $row, $prefix );
328 foreach ( $array as $name => $value ) {
329 $this->$name = $value;
332 $this->fileExists
= true;
333 $this->maybeUpgradeRow();
337 * Load file metadata from cache or DB, unless already loaded
340 if ( !$this->dataLoaded
) {
341 if ( !$this->loadFromCache() ) {
343 $this->saveToCache();
345 $this->dataLoaded
= true;
350 * Upgrade a row if it needs it
352 function maybeUpgradeRow() {
353 global $wgUpdateCompatibleMetadata;
354 if ( wfReadOnly() ) {
358 if ( is_null( $this->media_type
) ||
359 $this->mime
== 'image/svg'
362 $this->upgraded
= true;
364 $handler = $this->getHandler();
366 $validity = $handler->isMetadataValid( $this, $this->metadata
);
367 if ( $validity === MediaHandler
::METADATA_BAD
368 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
371 $this->upgraded
= true;
377 function getUpgraded() {
378 return $this->upgraded
;
382 * Fix assorted version-related problems with the image row by reloading it from the file
384 function upgradeRow() {
385 wfProfileIn( __METHOD__
);
387 $this->loadFromFile();
389 # Don't destroy file info of missing files
390 if ( !$this->fileExists
) {
391 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
392 wfProfileOut( __METHOD__
);
396 $dbw = $this->repo
->getMasterDB();
397 list( $major, $minor ) = self
::splitMime( $this->mime
);
399 if ( wfReadOnly() ) {
400 wfProfileOut( __METHOD__
);
403 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
405 $dbw->update( 'image',
407 'img_width' => $this->width
,
408 'img_height' => $this->height
,
409 'img_bits' => $this->bits
,
410 'img_media_type' => $this->media_type
,
411 'img_major_mime' => $major,
412 'img_minor_mime' => $minor,
413 'img_metadata' => $this->metadata
,
414 'img_sha1' => $this->sha1
,
415 ), array( 'img_name' => $this->getName() ),
419 $this->saveToCache();
420 wfProfileOut( __METHOD__
);
424 * Set properties in this object to be equal to those given in the
425 * associative array $info. Only cacheable fields can be set.
427 * If 'mime' is given, it will be split into major_mime/minor_mime.
428 * If major_mime/minor_mime are given, $this->mime will also be set.
430 function setProps( $info ) {
431 $this->dataLoaded
= true;
432 $fields = $this->getCacheFields( '' );
433 $fields[] = 'fileExists';
435 foreach ( $fields as $field ) {
436 if ( isset( $info[$field] ) ) {
437 $this->$field = $info[$field];
441 // Fix up mime fields
442 if ( isset( $info['major_mime'] ) ) {
443 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
444 } elseif ( isset( $info['mime'] ) ) {
445 $this->mime
= $info['mime'];
446 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
450 /** splitMime inherited */
451 /** getName inherited */
452 /** getTitle inherited */
453 /** getURL inherited */
454 /** getViewURL inherited */
455 /** getPath inherited */
456 /** isVisible inhereted */
458 function isMissing() {
459 if ( $this->missing
=== null ) {
460 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
461 $this->missing
= !$fileExists;
463 return $this->missing
;
467 * Return the width of the image
469 * Returns false on error
471 public function getWidth( $page = 1 ) {
474 if ( $this->isMultipage() ) {
475 $dim = $this->getHandler()->getPageDimensions( $this, $page );
477 return $dim['width'];
487 * Return the height of the image
489 * Returns false on error
491 public function getHeight( $page = 1 ) {
494 if ( $this->isMultipage() ) {
495 $dim = $this->getHandler()->getPageDimensions( $this, $page );
497 return $dim['height'];
502 return $this->height
;
507 * Returns ID or name of user who uploaded the file
509 * @param $type string 'text' or 'id'
511 function getUser( $type = 'text' ) {
514 if ( $type == 'text' ) {
515 return $this->user_text
;
516 } elseif ( $type == 'id' ) {
522 * Get handler-specific metadata
524 function getMetadata() {
526 return $this->metadata
;
529 function getBitDepth() {
535 * Return the size of the image file, in bytes
537 public function getSize() {
543 * Returns the mime type of the file.
545 function getMimeType() {
551 * Return the type of the media in the file.
552 * Use the value returned by this function with the MEDIATYPE_xxx constants.
554 function getMediaType() {
556 return $this->media_type
;
559 /** canRender inherited */
560 /** mustRender inherited */
561 /** allowInlineDisplay inherited */
562 /** isSafeFile inherited */
563 /** isTrustedFile inherited */
566 * Returns true if the file exists on disk.
567 * @return boolean Whether file exist on disk.
569 public function exists() {
571 return $this->fileExists
;
574 /** getTransformScript inherited */
575 /** getUnscaledThumb inherited */
576 /** thumbName inherited */
577 /** createThumb inherited */
578 /** transform inherited */
581 * Fix thumbnail files from 1.4 or before, with extreme prejudice
583 function migrateThumbFile( $thumbName ) {
584 $thumbDir = $this->getThumbPath();
585 $thumbPath = "$thumbDir/$thumbName";
587 if ( is_dir( $thumbPath ) ) {
588 // Directory where file should be
589 // This happened occasionally due to broken migration code in 1.5
590 // Rename to broken-*
591 for ( $i = 0; $i < 100 ; $i++
) {
592 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
593 if ( !file_exists( $broken ) ) {
594 rename( $thumbPath, $broken );
598 // Doesn't exist anymore
602 if ( is_file( $thumbDir ) ) {
603 // File where directory should be
605 // Doesn't exist anymore
610 /** getHandler inherited */
611 /** iconThumb inherited */
612 /** getLastError inherited */
615 * Get all thumbnail names previously generated for this file
616 * @param $archiveName string|false Name of an archive file
617 * @return array first element is the base dir, then files in that base dir.
619 function getThumbnails( $archiveName = false ) {
622 if ( $archiveName ) {
623 $dir = $this->getArchiveThumbPath( $archiveName );
625 $dir = $this->getThumbPath();
630 if ( is_dir( $dir ) ) {
631 $handle = opendir( $dir );
634 while ( false !== ( $file = readdir( $handle ) ) ) {
635 if ( $file { 0 } != '.' ) {
648 * Refresh metadata in memcached, but don't touch thumbnails or squid
650 function purgeMetadataCache() {
652 $this->saveToCache();
653 $this->purgeHistory();
657 * Purge the shared history (OldLocalFile) cache
659 function purgeHistory() {
662 $hashedName = md5( $this->getName() );
663 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
665 // Must purge thumbnails for old versions too! bug 30192
666 foreach( $this->getHistory() as $oldFile ) {
667 $oldFile->purgeThumbnails();
671 $wgMemc->delete( $oldKey );
676 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
678 function purgeCache( $options = array() ) {
679 // Refresh metadata cache
680 $this->purgeMetadataCache();
683 $this->purgeThumbnails( $options );
685 // Purge squid cache for this file
686 SquidUpdate
::purge( array( $this->getURL() ) );
690 * Delete cached transformed files for an archived version only.
691 * @param $archiveName string name of the archived file
693 function purgeOldThumbnails( $archiveName ) {
695 // Get a list of old thumbnails and URLs
696 $files = $this->getThumbnails( $archiveName );
697 $dir = array_shift( $files );
698 $this->purgeThumbList( $dir, $files );
700 // Directory should be empty, delete it too. This will probably suck on
701 // something like NFS or if the directory isn't actually empty, so hide
703 wfSuppressWarnings();
704 if( !rmdir( $dir ) ) {
705 wfDebug( __METHOD__
. ": unable to remove archive directory: $dir\n" );
709 // Purge any custom thumbnail caches
710 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
715 foreach( $files as $file ) {
716 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
718 SquidUpdate
::purge( $urls );
724 * Delete cached transformed files for the current version only.
726 function purgeThumbnails( $options = array() ) {
730 $files = $this->getThumbnails();
732 // Give media handler a chance to filter the purge list
733 if ( !empty( $options['forRefresh'] ) ) {
734 $handler = $this->getHandler();
736 $handler->filterThumbnailPurgeList( $files, $options );
740 $dir = array_shift( $files );
741 $this->purgeThumbList( $dir, $files );
743 // Purge any custom thumbnail caches
744 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
749 foreach( $files as $file ) {
750 $urls[] = $this->getThumbUrl( $file );
752 SquidUpdate
::purge( $urls );
757 * Delete a list of thumbnails visible at urls
758 * @param $dir string base dir of the files.
759 * @param $files array of strings: relative filenames (to $dir)
761 protected function purgeThumbList($dir, $files) {
762 $fileListDebug = strtr(
763 var_export( $files, true ),
766 wfDebug( __METHOD__
. ": $fileListDebug\n" );
768 foreach ( $files as $file ) {
769 # Check that the base file name is part of the thumb name
770 # This is a basic sanity check to avoid erasing unrelated directories
771 if ( strpos( $file, $this->getName() ) !== false ) {
772 wfSuppressWarnings();
773 unlink( "$dir/$file" );
779 /** purgeDescription inherited */
780 /** purgeEverything inherited */
782 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
783 $dbr = $this->repo
->getSlaveDB();
784 $tables = array( 'oldimage' );
785 $fields = OldLocalFile
::selectFields();
786 $conds = $opts = $join_conds = array();
787 $eq = $inc ?
'=' : '';
788 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
791 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
795 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
799 $opts['LIMIT'] = $limit;
802 // Search backwards for time > x queries
803 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
804 $opts['ORDER BY'] = "oi_timestamp $order";
805 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
807 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
808 &$conds, &$opts, &$join_conds ) );
810 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
813 foreach ( $res as $row ) {
814 if ( $this->repo
->oldFileFromRowFactory
) {
815 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
817 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
821 if ( $order == 'ASC' ) {
822 $r = array_reverse( $r ); // make sure it ends up descending
829 * Return the history of this file, line by line.
830 * starts with current version, then old versions.
831 * uses $this->historyLine to check which line to return:
832 * 0 return line for current version
833 * 1 query for old versions, return first one
834 * 2, ... return next old version from above query
836 public function nextHistoryLine() {
837 # Polymorphic function name to distinguish foreign and local fetches
838 $fname = get_class( $this ) . '::' . __FUNCTION__
;
840 $dbr = $this->repo
->getSlaveDB();
842 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
843 $this->historyRes
= $dbr->select( 'image',
846 "'' AS oi_archive_name",
850 array( 'img_name' => $this->title
->getDBkey() ),
854 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
855 $this->historyRes
= null;
858 } elseif ( $this->historyLine
== 1 ) {
859 $this->historyRes
= $dbr->select( 'oldimage', '*',
860 array( 'oi_name' => $this->title
->getDBkey() ),
862 array( 'ORDER BY' => 'oi_timestamp DESC' )
865 $this->historyLine ++
;
867 return $dbr->fetchObject( $this->historyRes
);
871 * Reset the history pointer to the first element of the history
873 public function resetHistory() {
874 $this->historyLine
= 0;
876 if ( !is_null( $this->historyRes
) ) {
877 $this->historyRes
= null;
881 /** getHashPath inherited */
882 /** getRel inherited */
883 /** getUrlRel inherited */
884 /** getArchiveRel inherited */
885 /** getArchivePath inherited */
886 /** getThumbPath inherited */
887 /** getArchiveUrl inherited */
888 /** getThumbUrl inherited */
889 /** getArchiveVirtualUrl inherited */
890 /** getThumbVirtualUrl inherited */
891 /** isHashed inherited */
894 * Upload a file and record it in the DB
895 * @param $srcPath String: source path or virtual URL
896 * @param $comment String: upload description
897 * @param $pageText String: text to use for the new description page,
898 * if a new description page is created
899 * @param $flags Integer: flags for publish()
900 * @param $props Array: File properties, if known. This can be used to reduce the
901 * upload time when uploading virtual URLs for which the file info
903 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
904 * @param $user Mixed: User object or null to use $wgUser
906 * @return FileRepoStatus object. On success, the value member contains the
907 * archive name, or an empty string if it was a new file.
909 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
911 // truncate nicely or the DB will do it for us
912 // non-nicely (dangling multi-byte chars, non-truncated
913 // version in cache).
914 $comment = $wgContLang->truncate( $comment, 255 );
916 $status = $this->publish( $srcPath, $flags );
919 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
920 $status->fatal( 'filenotfound', $srcPath );
930 * Record a file upload in the upload log and the image table
932 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
933 $watch = false, $timestamp = false )
935 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
937 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
943 $wgUser->addWatch( $this->getTitle() );
949 * Record a file upload in the upload log and the image table
951 function recordUpload2(
952 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
954 if ( is_null( $user ) ) {
959 $dbw = $this->repo
->getMasterDB();
963 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
966 if ( $timestamp === false ) {
967 $timestamp = $dbw->timestamp();
970 $props['description'] = $comment;
971 $props['user'] = $user->getId();
972 $props['user_text'] = $user->getName();
973 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
974 $this->setProps( $props );
977 $this->purgeThumbnails();
979 # The file is already on its final location, remove it from the squid cache
980 SquidUpdate
::purge( array( $this->getURL() ) );
982 # Fail now if the file isn't there
983 if ( !$this->fileExists
) {
984 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
990 # Test to see if the row exists using INSERT IGNORE
991 # This avoids race conditions by locking the row until the commit, and also
992 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
993 $dbw->insert( 'image',
995 'img_name' => $this->getName(),
996 'img_size' => $this->size
,
997 'img_width' => intval( $this->width
),
998 'img_height' => intval( $this->height
),
999 'img_bits' => $this->bits
,
1000 'img_media_type' => $this->media_type
,
1001 'img_major_mime' => $this->major_mime
,
1002 'img_minor_mime' => $this->minor_mime
,
1003 'img_timestamp' => $timestamp,
1004 'img_description' => $comment,
1005 'img_user' => $user->getId(),
1006 'img_user_text' => $user->getName(),
1007 'img_metadata' => $this->metadata
,
1008 'img_sha1' => $this->sha1
1014 if ( $dbw->affectedRows() == 0 ) {
1017 # Collision, this is an update of a file
1018 # Insert previous contents into oldimage
1019 $dbw->insertSelect( 'oldimage', 'image',
1021 'oi_name' => 'img_name',
1022 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1023 'oi_size' => 'img_size',
1024 'oi_width' => 'img_width',
1025 'oi_height' => 'img_height',
1026 'oi_bits' => 'img_bits',
1027 'oi_timestamp' => 'img_timestamp',
1028 'oi_description' => 'img_description',
1029 'oi_user' => 'img_user',
1030 'oi_user_text' => 'img_user_text',
1031 'oi_metadata' => 'img_metadata',
1032 'oi_media_type' => 'img_media_type',
1033 'oi_major_mime' => 'img_major_mime',
1034 'oi_minor_mime' => 'img_minor_mime',
1035 'oi_sha1' => 'img_sha1'
1036 ), array( 'img_name' => $this->getName() ), __METHOD__
1039 # Update the current image row
1040 $dbw->update( 'image',
1042 'img_size' => $this->size
,
1043 'img_width' => intval( $this->width
),
1044 'img_height' => intval( $this->height
),
1045 'img_bits' => $this->bits
,
1046 'img_media_type' => $this->media_type
,
1047 'img_major_mime' => $this->major_mime
,
1048 'img_minor_mime' => $this->minor_mime
,
1049 'img_timestamp' => $timestamp,
1050 'img_description' => $comment,
1051 'img_user' => $user->getId(),
1052 'img_user_text' => $user->getName(),
1053 'img_metadata' => $this->metadata
,
1054 'img_sha1' => $this->sha1
1055 ), array( /* WHERE */
1056 'img_name' => $this->getName()
1060 # This is a new file
1061 # Update the image count
1062 $dbw->begin( __METHOD__
);
1065 array( 'ss_images = ss_images+1' ),
1069 $dbw->commit( __METHOD__
);
1072 $descTitle = $this->getTitle();
1073 $wikiPage = new WikiFilePage( $descTitle );
1074 $wikiPage->setFile( $this );
1077 $log = new LogPage( 'upload' );
1078 $action = $reupload ?
'overwrite' : 'upload';
1079 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1081 if ( $descTitle->exists() ) {
1082 # Create a null revision
1083 $latest = $descTitle->getLatestRevID();
1084 $nullRevision = Revision
::newNullRevision(
1086 $descTitle->getArticleId(),
1087 $log->getRcComment(),
1090 if (!is_null($nullRevision)) {
1091 $nullRevision->insertOn( $dbw );
1093 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1094 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1096 # Invalidate the cache for the description page
1097 $descTitle->invalidateCache();
1098 $descTitle->purgeSquid();
1100 # New file; create the description page.
1101 # There's already a log entry, so don't make a second RC entry
1102 # Squid and file cache for the description page are purged by doEdit.
1103 $wikiPage->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
1106 # Commit the transaction now, in case something goes wrong later
1107 # The most important thing is that files don't get lost, especially archives
1110 # Save to cache and purge the squid
1111 # We shall not saveToCache before the commit since otherwise
1112 # in case of a rollback there is an usable file from memcached
1113 # which in fact doesn't really exist (bug 24978)
1114 $this->saveToCache();
1116 # Hooks, hooks, the magic of hooks...
1117 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1119 # Invalidate cache for all pages using this file
1120 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1121 $update->doUpdate();
1123 # Invalidate cache for all pages that redirects on this page
1124 $redirs = $this->getTitle()->getRedirectsHere();
1126 foreach ( $redirs as $redir ) {
1127 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1128 $update->doUpdate();
1135 * Move or copy a file to its public location. If a file exists at the
1136 * destination, move it to an archive. Returns a FileRepoStatus object with
1137 * the archive name in the "value" member on success.
1139 * The archive name should be passed through to recordUpload for database
1142 * @param $srcPath String: local filesystem path to the source image
1143 * @param $flags Integer: a bitwise combination of:
1144 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1145 * @return FileRepoStatus object. On success, the value member contains the
1146 * archive name, or an empty string if it was a new file.
1148 function publish( $srcPath, $flags = 0 ) {
1149 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1153 * Move or copy a file to a specified location. Returns a FileRepoStatus
1154 * object with the archive name in the "value" member on success.
1156 * The archive name should be passed through to recordUpload for database
1159 * @param $srcPath String: local filesystem path to the source image
1160 * @param $dstRel String: target relative path
1161 * @param $flags Integer: a bitwise combination of:
1162 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1163 * @return FileRepoStatus object. On success, the value member contains the
1164 * archive name, or an empty string if it was a new file.
1166 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1169 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1170 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1171 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1172 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1174 if ( $status->value
== 'new' ) {
1175 $status->value
= '';
1177 $status->value
= $archiveName;
1185 /** getLinksTo inherited */
1186 /** getExifData inherited */
1187 /** isLocal inherited */
1188 /** wasDeleted inherited */
1191 * Move file to the new title
1193 * Move current, old version and all thumbnails
1194 * to the new filename. Old file is deleted.
1196 * Cache purging is done; checks for validity
1197 * and logging are caller's responsibility
1199 * @param $target Title New file name
1200 * @return FileRepoStatus object.
1202 function move( $target ) {
1203 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1206 $batch = new LocalFileMoveBatch( $this, $target );
1207 $batch->addCurrent();
1210 $status = $batch->execute();
1211 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1213 $this->purgeEverything();
1216 if ( $status->isOk() ) {
1217 // Now switch the object
1218 $this->title
= $target;
1219 // Force regeneration of the name and hashpath
1220 unset( $this->name
);
1221 unset( $this->hashPath
);
1222 // Purge the new image
1223 $this->purgeEverything();
1230 * Delete all versions of the file.
1232 * Moves the files into an archive directory (or deletes them)
1233 * and removes the database rows.
1235 * Cache purging is done; logging is caller's responsibility.
1239 * @return FileRepoStatus object.
1241 function delete( $reason, $suppress = false ) {
1244 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1245 $batch->addCurrent();
1247 # Get old version relative paths
1248 $dbw = $this->repo
->getMasterDB();
1249 $result = $dbw->select( 'oldimage',
1250 array( 'oi_archive_name' ),
1251 array( 'oi_name' => $this->getName() ) );
1252 foreach ( $result as $row ) {
1253 $batch->addOld( $row->oi_archive_name
);
1254 $this->purgeOldThumbnails( $row->oi_archive_name
);
1256 $status = $batch->execute();
1258 if ( $status->ok
) {
1259 // Update site_stats
1260 $site_stats = $dbw->tableName( 'site_stats' );
1261 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1262 $this->purgeEverything();
1271 * Delete an old version of the file.
1273 * Moves the file into an archive directory (or deletes it)
1274 * and removes the database row.
1276 * Cache purging is done; logging is caller's responsibility.
1278 * @param $archiveName String
1279 * @param $reason String
1280 * @param $suppress Boolean
1281 * @throws MWException or FSException on database or file store failure
1282 * @return FileRepoStatus object.
1284 function deleteOld( $archiveName, $reason, $suppress = false ) {
1287 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1288 $batch->addOld( $archiveName );
1289 $this->purgeOldThumbnails( $archiveName );
1290 $status = $batch->execute();
1294 if ( $status->ok
) {
1295 $this->purgeDescription();
1296 $this->purgeHistory();
1303 * Restore all or specified deleted revisions to the given file.
1304 * Permissions and logging are left to the caller.
1306 * May throw database exceptions on error.
1308 * @param $versions set of record ids of deleted items to restore,
1309 * or empty to restore all revisions.
1310 * @param $unsuppress Boolean
1311 * @return FileRepoStatus
1313 function restore( $versions = array(), $unsuppress = false ) {
1314 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1319 $batch->addIds( $versions );
1322 $status = $batch->execute();
1324 if ( !$status->isGood() ) {
1328 $cleanupStatus = $batch->cleanup();
1329 $cleanupStatus->successCount
= 0;
1330 $cleanupStatus->failCount
= 0;
1331 $status->merge( $cleanupStatus );
1336 /** isMultipage inherited */
1337 /** pageCount inherited */
1338 /** scaleHeight inherited */
1339 /** getImageSize inherited */
1342 * Get the URL of the file description page.
1344 function getDescriptionUrl() {
1345 return $this->title
->getLocalUrl();
1349 * Get the HTML text of the description page
1350 * This is not used by ImagePage for local files, since (among other things)
1351 * it skips the parser cache.
1353 function getDescriptionText() {
1355 $revision = Revision
::newFromTitle( $this->title
);
1356 if ( !$revision ) return false;
1357 $text = $revision->getText();
1358 if ( !$text ) return false;
1359 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1360 return $pout->getText();
1363 function getDescription() {
1365 return $this->description
;
1368 function getTimestamp() {
1370 return $this->timestamp
;
1373 function getSha1() {
1375 // Initialise now if necessary
1376 if ( $this->sha1
== '' && $this->fileExists
) {
1377 $this->sha1
= File
::sha1Base36( $this->getPath() );
1378 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1379 $dbw = $this->repo
->getMasterDB();
1380 $dbw->update( 'image',
1381 array( 'img_sha1' => $this->sha1
),
1382 array( 'img_name' => $this->getName() ),
1384 $this->saveToCache();
1392 * Start a transaction and lock the image for update
1393 * Increments a reference counter if the lock is already held
1394 * @return boolean True if the image exists, false otherwise
1397 $dbw = $this->repo
->getMasterDB();
1399 if ( !$this->locked
) {
1404 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1408 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1409 * the transaction and thereby releases the image lock.
1412 if ( $this->locked
) {
1414 if ( !$this->locked
) {
1415 $dbw = $this->repo
->getMasterDB();
1422 * Roll back the DB transaction and mark the image unlocked
1424 function unlockAndRollback() {
1425 $this->locked
= false;
1426 $dbw = $this->repo
->getMasterDB();
1429 } // LocalFile class
1431 # ------------------------------------------------------------------------------
1434 * Helper class for file deletion
1437 class LocalFileDeleteBatch
{
1444 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1447 function __construct( File
$file, $reason = '', $suppress = false ) {
1448 $this->file
= $file;
1449 $this->reason
= $reason;
1450 $this->suppress
= $suppress;
1451 $this->status
= $file->repo
->newGood();
1454 function addCurrent() {
1455 $this->srcRels
['.'] = $this->file
->getRel();
1458 function addOld( $oldName ) {
1459 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1460 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1463 function getOldRels() {
1464 if ( !isset( $this->srcRels
['.'] ) ) {
1465 $oldRels =& $this->srcRels
;
1466 $deleteCurrent = false;
1468 $oldRels = $this->srcRels
;
1469 unset( $oldRels['.'] );
1470 $deleteCurrent = true;
1473 return array( $oldRels, $deleteCurrent );
1476 protected function getHashes() {
1478 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1480 if ( $deleteCurrent ) {
1481 $hashes['.'] = $this->file
->getSha1();
1484 if ( count( $oldRels ) ) {
1485 $dbw = $this->file
->repo
->getMasterDB();
1486 $res = $dbw->select(
1488 array( 'oi_archive_name', 'oi_sha1' ),
1489 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1493 foreach ( $res as $row ) {
1494 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1495 // Get the hash from the file
1496 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1497 $props = $this->file
->repo
->getFileProps( $oldUrl );
1499 if ( $props['fileExists'] ) {
1500 // Upgrade the oldimage row
1501 $dbw->update( 'oldimage',
1502 array( 'oi_sha1' => $props['sha1'] ),
1503 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1505 $hashes[$row->oi_archive_name
] = $props['sha1'];
1507 $hashes[$row->oi_archive_name
] = false;
1510 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1515 $missing = array_diff_key( $this->srcRels
, $hashes );
1517 foreach ( $missing as $name => $rel ) {
1518 $this->status
->error( 'filedelete-old-unregistered', $name );
1521 foreach ( $hashes as $name => $hash ) {
1523 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1524 unset( $hashes[$name] );
1531 function doDBInserts() {
1534 $dbw = $this->file
->repo
->getMasterDB();
1535 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1536 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1537 $encReason = $dbw->addQuotes( $this->reason
);
1538 $encGroup = $dbw->addQuotes( 'deleted' );
1539 $ext = $this->file
->getExtension();
1540 $dotExt = $ext === '' ?
'' : ".$ext";
1541 $encExt = $dbw->addQuotes( $dotExt );
1542 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1544 // Bitfields to further suppress the content
1545 if ( $this->suppress
) {
1547 // This should be 15...
1548 $bitfield |
= Revision
::DELETED_TEXT
;
1549 $bitfield |
= Revision
::DELETED_COMMENT
;
1550 $bitfield |
= Revision
::DELETED_USER
;
1551 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1553 $bitfield = 'oi_deleted';
1556 if ( $deleteCurrent ) {
1557 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1558 $where = array( 'img_name' => $this->file
->getName() );
1559 $dbw->insertSelect( 'filearchive', 'image',
1561 'fa_storage_group' => $encGroup,
1562 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1563 'fa_deleted_user' => $encUserId,
1564 'fa_deleted_timestamp' => $encTimestamp,
1565 'fa_deleted_reason' => $encReason,
1566 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1568 'fa_name' => 'img_name',
1569 'fa_archive_name' => 'NULL',
1570 'fa_size' => 'img_size',
1571 'fa_width' => 'img_width',
1572 'fa_height' => 'img_height',
1573 'fa_metadata' => 'img_metadata',
1574 'fa_bits' => 'img_bits',
1575 'fa_media_type' => 'img_media_type',
1576 'fa_major_mime' => 'img_major_mime',
1577 'fa_minor_mime' => 'img_minor_mime',
1578 'fa_description' => 'img_description',
1579 'fa_user' => 'img_user',
1580 'fa_user_text' => 'img_user_text',
1581 'fa_timestamp' => 'img_timestamp'
1582 ), $where, __METHOD__
);
1585 if ( count( $oldRels ) ) {
1586 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1588 'oi_name' => $this->file
->getName(),
1589 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1590 $dbw->insertSelect( 'filearchive', 'oldimage',
1592 'fa_storage_group' => $encGroup,
1593 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1594 'fa_deleted_user' => $encUserId,
1595 'fa_deleted_timestamp' => $encTimestamp,
1596 'fa_deleted_reason' => $encReason,
1597 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1599 'fa_name' => 'oi_name',
1600 'fa_archive_name' => 'oi_archive_name',
1601 'fa_size' => 'oi_size',
1602 'fa_width' => 'oi_width',
1603 'fa_height' => 'oi_height',
1604 'fa_metadata' => 'oi_metadata',
1605 'fa_bits' => 'oi_bits',
1606 'fa_media_type' => 'oi_media_type',
1607 'fa_major_mime' => 'oi_major_mime',
1608 'fa_minor_mime' => 'oi_minor_mime',
1609 'fa_description' => 'oi_description',
1610 'fa_user' => 'oi_user',
1611 'fa_user_text' => 'oi_user_text',
1612 'fa_timestamp' => 'oi_timestamp',
1613 'fa_deleted' => $bitfield
1614 ), $where, __METHOD__
);
1618 function doDBDeletes() {
1619 $dbw = $this->file
->repo
->getMasterDB();
1620 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1622 if ( count( $oldRels ) ) {
1623 $dbw->delete( 'oldimage',
1625 'oi_name' => $this->file
->getName(),
1626 'oi_archive_name' => array_keys( $oldRels )
1630 if ( $deleteCurrent ) {
1631 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1636 * Run the transaction
1638 function execute() {
1640 wfProfileIn( __METHOD__
);
1642 $this->file
->lock();
1643 // Leave private files alone
1644 $privateFiles = array();
1645 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1646 $dbw = $this->file
->repo
->getMasterDB();
1648 if ( !empty( $oldRels ) ) {
1649 $res = $dbw->select( 'oldimage',
1650 array( 'oi_archive_name' ),
1651 array( 'oi_name' => $this->file
->getName(),
1652 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1653 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1656 foreach ( $res as $row ) {
1657 $privateFiles[$row->oi_archive_name
] = 1;
1660 // Prepare deletion batch
1661 $hashes = $this->getHashes();
1662 $this->deletionBatch
= array();
1663 $ext = $this->file
->getExtension();
1664 $dotExt = $ext === '' ?
'' : ".$ext";
1666 foreach ( $this->srcRels
as $name => $srcRel ) {
1667 // Skip files that have no hash (missing source).
1668 // Keep private files where they are.
1669 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1670 $hash = $hashes[$name];
1671 $key = $hash . $dotExt;
1672 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1673 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1677 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1678 // We acquire this lock by running the inserts now, before the file operations.
1680 // This potentially has poor lock contention characteristics -- an alternative
1681 // scheme would be to insert stub filearchive entries with no fa_name and commit
1682 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1683 $this->doDBInserts();
1685 // Removes non-existent file from the batch, so we don't get errors.
1686 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1688 // Execute the file deletion batch
1689 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1691 if ( !$status->isGood() ) {
1692 $this->status
->merge( $status );
1695 if ( !$this->status
->ok
) {
1696 // Critical file deletion error
1697 // Roll back inserts, release lock and abort
1698 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1699 $this->file
->unlockAndRollback();
1700 wfProfileOut( __METHOD__
);
1701 return $this->status
;
1705 if ( $wgUseSquid ) {
1708 foreach ( $this->srcRels
as $srcRel ) {
1709 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1710 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1712 SquidUpdate
::purge( $urls );
1715 // Delete image/oldimage rows
1716 $this->doDBDeletes();
1718 // Commit and return
1719 $this->file
->unlock();
1720 wfProfileOut( __METHOD__
);
1722 return $this->status
;
1726 * Removes non-existent files from a deletion batch.
1728 function removeNonexistentFiles( $batch ) {
1729 $files = $newBatch = array();
1731 foreach ( $batch as $batchItem ) {
1732 list( $src, $dest ) = $batchItem;
1733 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1736 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1738 foreach ( $batch as $batchItem ) {
1739 if ( $result[$batchItem[0]] ) {
1740 $newBatch[] = $batchItem;
1748 # ------------------------------------------------------------------------------
1751 * Helper class for file undeletion
1754 class LocalFileRestoreBatch
{
1760 var $cleanupBatch, $ids, $all, $unsuppress = false;
1762 function __construct( File
$file, $unsuppress = false ) {
1763 $this->file
= $file;
1764 $this->cleanupBatch
= $this->ids
= array();
1765 $this->ids
= array();
1766 $this->unsuppress
= $unsuppress;
1772 function addId( $fa_id ) {
1773 $this->ids
[] = $fa_id;
1777 * Add a whole lot of files by ID
1779 function addIds( $ids ) {
1780 $this->ids
= array_merge( $this->ids
, $ids );
1784 * Add all revisions of the file
1791 * Run the transaction, except the cleanup batch.
1792 * The cleanup batch should be run in a separate transaction, because it locks different
1793 * rows and there's no need to keep the image row locked while it's acquiring those locks
1794 * The caller may have its own transaction open.
1795 * So we save the batch and let the caller call cleanup()
1797 function execute() {
1800 if ( !$this->all
&& !$this->ids
) {
1802 return $this->file
->repo
->newGood();
1805 $exists = $this->file
->lock();
1806 $dbw = $this->file
->repo
->getMasterDB();
1807 $status = $this->file
->repo
->newGood();
1809 // Fetch all or selected archived revisions for the file,
1810 // sorted from the most recent to the oldest.
1811 $conditions = array( 'fa_name' => $this->file
->getName() );
1813 if ( !$this->all
) {
1814 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1817 $result = $dbw->select( 'filearchive', '*',
1820 array( 'ORDER BY' => 'fa_timestamp DESC' )
1823 $idsPresent = array();
1824 $storeBatch = array();
1825 $insertBatch = array();
1826 $insertCurrent = false;
1827 $deleteIds = array();
1829 $archiveNames = array();
1831 foreach ( $result as $row ) {
1832 $idsPresent[] = $row->fa_id
;
1834 if ( $row->fa_name
!= $this->file
->getName() ) {
1835 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1836 $status->failCount++
;
1840 if ( $row->fa_storage_key
== '' ) {
1841 // Revision was missing pre-deletion
1842 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1843 $status->failCount++
;
1847 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1848 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1850 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1853 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1854 $sha1 = substr( $sha1, 1 );
1857 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1858 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1859 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1860 ||
is_null( $row->fa_metadata
) ) {
1861 // Refresh our metadata
1862 // Required for a new current revision; nice for older ones too. :)
1863 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1866 'minor_mime' => $row->fa_minor_mime
,
1867 'major_mime' => $row->fa_major_mime
,
1868 'media_type' => $row->fa_media_type
,
1869 'metadata' => $row->fa_metadata
1873 if ( $first && !$exists ) {
1874 // This revision will be published as the new current version
1875 $destRel = $this->file
->getRel();
1876 $insertCurrent = array(
1877 'img_name' => $row->fa_name
,
1878 'img_size' => $row->fa_size
,
1879 'img_width' => $row->fa_width
,
1880 'img_height' => $row->fa_height
,
1881 'img_metadata' => $props['metadata'],
1882 'img_bits' => $row->fa_bits
,
1883 'img_media_type' => $props['media_type'],
1884 'img_major_mime' => $props['major_mime'],
1885 'img_minor_mime' => $props['minor_mime'],
1886 'img_description' => $row->fa_description
,
1887 'img_user' => $row->fa_user
,
1888 'img_user_text' => $row->fa_user_text
,
1889 'img_timestamp' => $row->fa_timestamp
,
1893 // The live (current) version cannot be hidden!
1894 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1895 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1896 $this->cleanupBatch
[] = $row->fa_storage_key
;
1899 $archiveName = $row->fa_archive_name
;
1901 if ( $archiveName == '' ) {
1902 // This was originally a current version; we
1903 // have to devise a new archive name for it.
1904 // Format is <timestamp of archiving>!<name>
1905 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1908 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1910 } while ( isset( $archiveNames[$archiveName] ) );
1913 $archiveNames[$archiveName] = true;
1914 $destRel = $this->file
->getArchiveRel( $archiveName );
1915 $insertBatch[] = array(
1916 'oi_name' => $row->fa_name
,
1917 'oi_archive_name' => $archiveName,
1918 'oi_size' => $row->fa_size
,
1919 'oi_width' => $row->fa_width
,
1920 'oi_height' => $row->fa_height
,
1921 'oi_bits' => $row->fa_bits
,
1922 'oi_description' => $row->fa_description
,
1923 'oi_user' => $row->fa_user
,
1924 'oi_user_text' => $row->fa_user_text
,
1925 'oi_timestamp' => $row->fa_timestamp
,
1926 'oi_metadata' => $props['metadata'],
1927 'oi_media_type' => $props['media_type'],
1928 'oi_major_mime' => $props['major_mime'],
1929 'oi_minor_mime' => $props['minor_mime'],
1930 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1931 'oi_sha1' => $sha1 );
1934 $deleteIds[] = $row->fa_id
;
1936 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1937 // private files can stay where they are
1938 $status->successCount++
;
1940 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1941 $this->cleanupBatch
[] = $row->fa_storage_key
;
1949 // Add a warning to the status object for missing IDs
1950 $missingIds = array_diff( $this->ids
, $idsPresent );
1952 foreach ( $missingIds as $id ) {
1953 $status->error( 'undelete-missing-filearchive', $id );
1956 // Remove missing files from batch, so we don't get errors when undeleting them
1957 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1959 // Run the store batch
1960 // Use the OVERWRITE_SAME flag to smooth over a common error
1961 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1962 $status->merge( $storeStatus );
1964 if ( !$status->isGood() ) {
1965 // Even if some files could be copied, fail entirely as that is the
1966 // easiest thing to do without data loss
1967 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1968 $status->ok
= false;
1969 $this->file
->unlock();
1974 // Run the DB updates
1975 // Because we have locked the image row, key conflicts should be rare.
1976 // If they do occur, we can roll back the transaction at this time with
1977 // no data loss, but leaving unregistered files scattered throughout the
1979 // This is not ideal, which is why it's important to lock the image row.
1980 if ( $insertCurrent ) {
1981 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1984 if ( $insertBatch ) {
1985 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1989 $dbw->delete( 'filearchive',
1990 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1994 // If store batch is empty (all files are missing), deletion is to be considered successful
1995 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1997 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1999 // Update site_stats
2000 $site_stats = $dbw->tableName( 'site_stats' );
2001 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2003 $this->file
->purgeEverything();
2005 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2006 $this->file
->purgeDescription();
2007 $this->file
->purgeHistory();
2011 $this->file
->unlock();
2017 * Removes non-existent files from a store batch.
2019 function removeNonexistentFiles( $triplets ) {
2020 $files = $filteredTriplets = array();
2021 foreach ( $triplets as $file )
2022 $files[$file[0]] = $file[0];
2024 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2026 foreach ( $triplets as $file ) {
2027 if ( $result[$file[0]] ) {
2028 $filteredTriplets[] = $file;
2032 return $filteredTriplets;
2036 * Removes non-existent files from a cleanup batch.
2038 function removeNonexistentFromCleanup( $batch ) {
2039 $files = $newBatch = array();
2040 $repo = $this->file
->repo
;
2042 foreach ( $batch as $file ) {
2043 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2044 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2047 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2049 foreach ( $batch as $file ) {
2050 if ( $result[$file] ) {
2051 $newBatch[] = $file;
2059 * Delete unused files in the deleted zone.
2060 * This should be called from outside the transaction in which execute() was called.
2062 function cleanup() {
2063 if ( !$this->cleanupBatch
) {
2064 return $this->file
->repo
->newGood();
2067 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2069 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2075 * Cleanup a failed batch. The batch was only partially successful, so
2076 * rollback by removing all items that were succesfully copied.
2078 * @param Status $storeStatus
2079 * @param array $storeBatch
2081 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2082 $cleanupBatch = array();
2084 foreach ( $storeStatus->success
as $i => $success ) {
2085 // Check if this item of the batch was successfully copied
2087 // Item was successfully copied and needs to be removed again
2088 // Extract ($dstZone, $dstRel) from the batch
2089 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2092 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2096 # ------------------------------------------------------------------------------
2099 * Helper class for file movement
2102 class LocalFileMoveBatch
{
2114 var $cur, $olds, $oldCount, $archive, $db;
2116 function __construct( File
$file, Title
$target ) {
2117 $this->file
= $file;
2118 $this->target
= $target;
2119 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2120 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2121 $this->oldName
= $this->file
->getName();
2122 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2123 $this->oldRel
= $this->oldHash
. $this->oldName
;
2124 $this->newRel
= $this->newHash
. $this->newName
;
2125 $this->db
= $file->repo
->getMasterDb();
2129 * Add the current image to the batch
2131 function addCurrent() {
2132 $this->cur
= array( $this->oldRel
, $this->newRel
);
2136 * Add the old versions of the image to the batch
2138 function addOlds() {
2139 $archiveBase = 'archive';
2140 $this->olds
= array();
2141 $this->oldCount
= 0;
2143 $result = $this->db
->select( 'oldimage',
2144 array( 'oi_archive_name', 'oi_deleted' ),
2145 array( 'oi_name' => $this->oldName
),
2149 foreach ( $result as $row ) {
2150 $oldName = $row->oi_archive_name
;
2151 $bits = explode( '!', $oldName, 2 );
2153 if ( count( $bits ) != 2 ) {
2154 wfDebug( "Old file name missing !: '$oldName' \n" );
2158 list( $timestamp, $filename ) = $bits;
2160 if ( $this->oldName
!= $filename ) {
2161 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2167 // Do we want to add those to oldCount?
2168 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2172 $this->olds
[] = array(
2173 "{$archiveBase}/{$this->oldHash}{$oldName}",
2174 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2182 function execute() {
2183 $repo = $this->file
->repo
;
2184 $status = $repo->newGood();
2185 $triplets = $this->getMoveTriplets();
2187 $triplets = $this->removeNonexistentFiles( $triplets );
2189 // Copy the files into their new location
2190 $statusMove = $repo->storeBatch( $triplets );
2191 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2192 if ( !$statusMove->isGood() ) {
2193 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2194 $this->cleanupTarget( $triplets );
2195 $statusMove->ok
= false;
2200 $statusDb = $this->doDBUpdates();
2201 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2202 if ( !$statusDb->isGood() ) {
2203 $this->db
->rollback();
2204 // Something went wrong with the DB updates, so remove the target files
2205 $this->cleanupTarget( $triplets );
2206 $statusDb->ok
= false;
2209 $this->db
->commit();
2211 // Everything went ok, remove the source files
2212 $this->cleanupSource( $triplets );
2214 $status->merge( $statusDb );
2215 $status->merge( $statusMove );
2221 * Do the database updates and return a new FileRepoStatus indicating how
2222 * many rows where updated.
2224 * @return FileRepoStatus
2226 function doDBUpdates() {
2227 $repo = $this->file
->repo
;
2228 $status = $repo->newGood();
2231 // Update current image
2234 array( 'img_name' => $this->newName
),
2235 array( 'img_name' => $this->oldName
),
2239 if ( $dbw->affectedRows() ) {
2240 $status->successCount++
;
2242 $status->failCount++
;
2243 $status->fatal( 'imageinvalidfilename' );
2247 // Update old images
2251 'oi_name' => $this->newName
,
2252 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2254 array( 'oi_name' => $this->oldName
),
2258 $affected = $dbw->affectedRows();
2259 $total = $this->oldCount
;
2260 $status->successCount +
= $affected;
2261 $status->failCount +
= $total - $affected;
2262 if ( $status->failCount
) {
2263 $status->error( 'imageinvalidfilename' );
2270 * Generate triplets for FSRepo::storeBatch().
2272 function getMoveTriplets() {
2273 $moves = array_merge( array( $this->cur
), $this->olds
);
2274 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2276 foreach ( $moves as $move ) {
2277 // $move: (oldRelativePath, newRelativePath)
2278 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2279 $triplets[] = array( $srcUrl, 'public', $move[1] );
2280 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2287 * Removes non-existent files from move batch.
2289 function removeNonexistentFiles( $triplets ) {
2292 foreach ( $triplets as $file ) {
2293 $files[$file[0]] = $file[0];
2296 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2297 $filteredTriplets = array();
2299 foreach ( $triplets as $file ) {
2300 if ( $result[$file[0]] ) {
2301 $filteredTriplets[] = $file;
2303 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2307 return $filteredTriplets;
2311 * Cleanup a partially moved array of triplets by deleting the target
2312 * files. Called if something went wrong half way.
2314 function cleanupTarget( $triplets ) {
2315 // Create dest pairs from the triplets
2317 foreach ( $triplets as $triplet ) {
2318 $pairs[] = array( $triplet[1], $triplet[2] );
2321 $this->file
->repo
->cleanupBatch( $pairs );
2325 * Cleanup a fully moved array of triplets by deleting the source files.
2326 * Called at the end of the move process if everything else went ok.
2328 function cleanupSource( $triplets ) {
2329 // Create source file names from the triplets
2331 foreach ( $triplets as $triplet ) {
2332 $files[] = $triplet[0];
2335 $this->file
->repo
->cleanupBatch( $files );