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 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
238 $this->setProps( $props );
241 function getCacheFields( $prefix = 'img_' ) {
242 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
243 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
244 static $results = array();
246 if ( $prefix == '' ) {
250 if ( !isset( $results[$prefix] ) ) {
251 $prefixedFields = array();
252 foreach ( $fields as $field ) {
253 $prefixedFields[] = $prefix . $field;
255 $results[$prefix] = $prefixedFields;
258 return $results[$prefix];
262 * Load file metadata from the DB
264 function loadFromDB() {
265 # Polymorphic function name to distinguish foreign and local fetches
266 $fname = get_class( $this ) . '::' . __FUNCTION__
;
267 wfProfileIn( $fname );
269 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
270 $this->dataLoaded
= true;
272 $dbr = $this->repo
->getMasterDB();
274 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
275 array( 'img_name' => $this->getName() ), $fname );
278 $this->loadFromRow( $row );
280 $this->fileExists
= false;
283 wfProfileOut( $fname );
287 * Decode a row from the database (either object or array) to an array
288 * with timestamps and MIME types decoded, and the field prefix removed.
290 function decodeRow( $row, $prefix = 'img_' ) {
291 $array = (array)$row;
292 $prefixLength = strlen( $prefix );
294 // Sanity check prefix once
295 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
296 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
301 foreach ( $array as $name => $value ) {
302 $decoded[substr( $name, $prefixLength )] = $value;
305 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
307 if ( empty( $decoded['major_mime'] ) ) {
308 $decoded['mime'] = 'unknown/unknown';
310 if ( !$decoded['minor_mime'] ) {
311 $decoded['minor_mime'] = 'unknown';
313 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
316 # Trim zero padding from char/binary field
317 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
323 * Load file metadata from a DB result row
325 function loadFromRow( $row, $prefix = 'img_' ) {
326 $this->dataLoaded
= true;
327 $array = $this->decodeRow( $row, $prefix );
329 foreach ( $array as $name => $value ) {
330 $this->$name = $value;
333 $this->fileExists
= true;
334 $this->maybeUpgradeRow();
338 * Load file metadata from cache or DB, unless already loaded
341 if ( !$this->dataLoaded
) {
342 if ( !$this->loadFromCache() ) {
344 $this->saveToCache();
346 $this->dataLoaded
= true;
351 * Upgrade a row if it needs it
353 function maybeUpgradeRow() {
354 global $wgUpdateCompatibleMetadata;
355 if ( wfReadOnly() ) {
359 if ( is_null( $this->media_type
) ||
360 $this->mime
== 'image/svg'
363 $this->upgraded
= true;
365 $handler = $this->getHandler();
367 $validity = $handler->isMetadataValid( $this, $this->metadata
);
368 if ( $validity === MediaHandler
::METADATA_BAD
369 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
372 $this->upgraded
= true;
378 function getUpgraded() {
379 return $this->upgraded
;
383 * Fix assorted version-related problems with the image row by reloading it from the file
385 function upgradeRow() {
386 wfProfileIn( __METHOD__
);
388 $this->loadFromFile();
390 # Don't destroy file info of missing files
391 if ( !$this->fileExists
) {
392 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
393 wfProfileOut( __METHOD__
);
397 $dbw = $this->repo
->getMasterDB();
398 list( $major, $minor ) = self
::splitMime( $this->mime
);
400 if ( wfReadOnly() ) {
401 wfProfileOut( __METHOD__
);
404 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
406 $dbw->update( 'image',
408 'img_width' => $this->width
,
409 'img_height' => $this->height
,
410 'img_bits' => $this->bits
,
411 'img_media_type' => $this->media_type
,
412 'img_major_mime' => $major,
413 'img_minor_mime' => $minor,
414 'img_metadata' => $this->metadata
,
415 'img_sha1' => $this->sha1
,
416 ), array( 'img_name' => $this->getName() ),
420 $this->saveToCache();
421 wfProfileOut( __METHOD__
);
425 * Set properties in this object to be equal to those given in the
426 * associative array $info. Only cacheable fields can be set.
428 * If 'mime' is given, it will be split into major_mime/minor_mime.
429 * If major_mime/minor_mime are given, $this->mime will also be set.
431 function setProps( $info ) {
432 $this->dataLoaded
= true;
433 $fields = $this->getCacheFields( '' );
434 $fields[] = 'fileExists';
436 foreach ( $fields as $field ) {
437 if ( isset( $info[$field] ) ) {
438 $this->$field = $info[$field];
442 // Fix up mime fields
443 if ( isset( $info['major_mime'] ) ) {
444 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
445 } elseif ( isset( $info['mime'] ) ) {
446 $this->mime
= $info['mime'];
447 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
451 /** splitMime inherited */
452 /** getName inherited */
453 /** getTitle inherited */
454 /** getURL inherited */
455 /** getViewURL inherited */
456 /** getPath inherited */
457 /** isVisible inhereted */
459 function isMissing() {
460 if ( $this->missing
=== null ) {
461 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
462 $this->missing
= !$fileExists;
464 return $this->missing
;
468 * Return the width of the image
470 * Returns false on error
472 public function getWidth( $page = 1 ) {
475 if ( $this->isMultipage() ) {
476 $dim = $this->getHandler()->getPageDimensions( $this, $page );
478 return $dim['width'];
488 * Return the height of the image
490 * Returns false on error
492 public function getHeight( $page = 1 ) {
495 if ( $this->isMultipage() ) {
496 $dim = $this->getHandler()->getPageDimensions( $this, $page );
498 return $dim['height'];
503 return $this->height
;
508 * Returns ID or name of user who uploaded the file
510 * @param $type string 'text' or 'id'
512 function getUser( $type = 'text' ) {
515 if ( $type == 'text' ) {
516 return $this->user_text
;
517 } elseif ( $type == 'id' ) {
523 * Get handler-specific metadata
525 function getMetadata() {
527 return $this->metadata
;
530 function getBitDepth() {
536 * Return the size of the image file, in bytes
538 public function getSize() {
544 * Returns the mime type of the file.
546 function getMimeType() {
552 * Return the type of the media in the file.
553 * Use the value returned by this function with the MEDIATYPE_xxx constants.
555 function getMediaType() {
557 return $this->media_type
;
560 /** canRender inherited */
561 /** mustRender inherited */
562 /** allowInlineDisplay inherited */
563 /** isSafeFile inherited */
564 /** isTrustedFile inherited */
567 * Returns true if the file exists on disk.
568 * @return boolean Whether file exist on disk.
570 public function exists() {
572 return $this->fileExists
;
575 /** getTransformScript inherited */
576 /** getUnscaledThumb inherited */
577 /** thumbName inherited */
578 /** createThumb inherited */
579 /** transform inherited */
582 * Fix thumbnail files from 1.4 or before, with extreme prejudice
584 function migrateThumbFile( $thumbName ) {
585 $thumbDir = $this->getThumbPath();
587 /* Old code for bug 2532
588 $thumbPath = "$thumbDir/$thumbName";
589 if ( is_dir( $thumbPath ) ) {
590 // Directory where file should be
591 // This happened occasionally due to broken migration code in 1.5
592 // Rename to broken-*
593 for ( $i = 0; $i < 100 ; $i++ ) {
594 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
595 if ( !file_exists( $broken ) ) {
596 rename( $thumbPath, $broken );
600 // Doesn't exist anymore
605 if ( $this->repo
->fileExists( $thumbDir, FileRepo
::FILES_ONLY
) ) {
606 // File where directory should be
607 $op = array( 'op' => 'delete', 'src' => $thumbDir );
608 $this->repo
->getBackend()->doOperation( $op );
612 /** getHandler inherited */
613 /** iconThumb inherited */
614 /** getLastError inherited */
617 * Get all thumbnail names previously generated for this file
618 * @param $archiveName string|false Name of an archive file
619 * @return array first element is the base dir, then files in that base dir.
621 function getThumbnails( $archiveName = false ) {
624 if ( $archiveName ) {
625 $dir = $this->getArchiveThumbPath( $archiveName );
627 $dir = $this->getThumbPath();
630 $backend = $this->repo
->getBackend();
631 $files = array( $dir );
632 $iterator = $backend->getFileList( array( 'dir' => $dir ) );
633 foreach ( $iterator as $file ) {
641 * Refresh metadata in memcached, but don't touch thumbnails or squid
643 function purgeMetadataCache() {
645 $this->saveToCache();
646 $this->purgeHistory();
650 * Purge the shared history (OldLocalFile) cache
652 function purgeHistory() {
655 $hashedName = md5( $this->getName() );
656 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
658 // Must purge thumbnails for old versions too! bug 30192
659 foreach( $this->getHistory() as $oldFile ) {
660 $oldFile->purgeThumbnails();
664 $wgMemc->delete( $oldKey );
669 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
671 function purgeCache( $options = array() ) {
672 // Refresh metadata cache
673 $this->purgeMetadataCache();
676 $this->purgeThumbnails( $options );
678 // Purge squid cache for this file
679 SquidUpdate
::purge( array( $this->getURL() ) );
683 * Delete cached transformed files for an archived version only.
684 * @param $archiveName string name of the archived file
686 function purgeOldThumbnails( $archiveName ) {
688 // Get a list of old thumbnails and URLs
689 $files = $this->getThumbnails( $archiveName );
690 $dir = array_shift( $files );
691 $this->purgeThumbList( $dir, $files );
693 // Directory should be empty, delete it too. This will probably suck on
694 // something like NFS or if the directory isn't actually empty, so hide
696 wfSuppressWarnings();
697 if( !rmdir( $dir ) ) {
698 wfDebug( __METHOD__
. ": unable to remove archive directory: $dir\n" );
702 // Purge any custom thumbnail caches
703 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, $archiveName ) );
708 foreach( $files as $file ) {
709 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
711 SquidUpdate
::purge( $urls );
716 * Delete cached transformed files for the current version only.
718 function purgeThumbnails( $options = array() ) {
722 $files = $this->getThumbnails();
724 // Give media handler a chance to filter the purge list
725 if ( !empty( $options['forRefresh'] ) ) {
726 $handler = $this->getHandler();
728 $handler->filterThumbnailPurgeList( $files, $options );
732 $dir = array_shift( $files );
733 $this->purgeThumbList( $dir, $files );
735 // Purge any custom thumbnail caches
736 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, false ) );
741 foreach( $files as $file ) {
742 $urls[] = $this->getThumbUrl( $file );
744 SquidUpdate
::purge( $urls );
749 * Delete a list of thumbnails visible at urls
750 * @param $dir string base dir of the files.
751 * @param $files array of strings: relative filenames (to $dir)
753 protected function purgeThumbList( $dir, $files ) {
754 $fileListDebug = strtr(
755 var_export( $files, true ),
758 wfDebug( __METHOD__
. ": $fileListDebug\n" );
760 $backend = $this->repo
->getBackend();
761 foreach ( $files as $file ) {
762 # Check that the base file name is part of the thumb name
763 # This is a basic sanity check to avoid erasing unrelated directories
764 if ( strpos( $file, $this->getName() ) !== false ) {
765 $op = array( 'op' => 'delete', 'src' => "{$dir}/{$file}" );
766 $backend->doOperation( $op );
769 # Clear out directory if empty
770 $backend->clean( array( 'dir' => $dir ) );
773 /** purgeDescription inherited */
774 /** purgeEverything inherited */
776 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
777 $dbr = $this->repo
->getSlaveDB();
778 $tables = array( 'oldimage' );
779 $fields = OldLocalFile
::selectFields();
780 $conds = $opts = $join_conds = array();
781 $eq = $inc ?
'=' : '';
782 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
785 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
789 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
793 $opts['LIMIT'] = $limit;
796 // Search backwards for time > x queries
797 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
798 $opts['ORDER BY'] = "oi_timestamp $order";
799 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
801 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
802 &$conds, &$opts, &$join_conds ) );
804 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
807 foreach ( $res as $row ) {
808 if ( $this->repo
->oldFileFromRowFactory
) {
809 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
811 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
815 if ( $order == 'ASC' ) {
816 $r = array_reverse( $r ); // make sure it ends up descending
823 * Return the history of this file, line by line.
824 * starts with current version, then old versions.
825 * uses $this->historyLine to check which line to return:
826 * 0 return line for current version
827 * 1 query for old versions, return first one
828 * 2, ... return next old version from above query
830 public function nextHistoryLine() {
831 # Polymorphic function name to distinguish foreign and local fetches
832 $fname = get_class( $this ) . '::' . __FUNCTION__
;
834 $dbr = $this->repo
->getSlaveDB();
836 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
837 $this->historyRes
= $dbr->select( 'image',
840 "'' AS oi_archive_name",
844 array( 'img_name' => $this->title
->getDBkey() ),
848 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
849 $this->historyRes
= null;
852 } elseif ( $this->historyLine
== 1 ) {
853 $this->historyRes
= $dbr->select( 'oldimage', '*',
854 array( 'oi_name' => $this->title
->getDBkey() ),
856 array( 'ORDER BY' => 'oi_timestamp DESC' )
859 $this->historyLine ++
;
861 return $dbr->fetchObject( $this->historyRes
);
865 * Reset the history pointer to the first element of the history
867 public function resetHistory() {
868 $this->historyLine
= 0;
870 if ( !is_null( $this->historyRes
) ) {
871 $this->historyRes
= null;
875 /** getHashPath inherited */
876 /** getRel inherited */
877 /** getUrlRel inherited */
878 /** getArchiveRel inherited */
879 /** getArchivePath inherited */
880 /** getThumbPath inherited */
881 /** getArchiveUrl inherited */
882 /** getThumbUrl inherited */
883 /** getArchiveVirtualUrl inherited */
884 /** getThumbVirtualUrl inherited */
885 /** isHashed inherited */
888 * Upload a file and record it in the DB
889 * @param $srcPath String: source storage path or virtual URL
890 * @param $comment String: upload description
891 * @param $pageText String: text to use for the new description page,
892 * if a new description page is created
893 * @param $flags Integer: flags for publish()
894 * @param $props Array: File properties, if known. This can be used to reduce the
895 * upload time when uploading virtual URLs for which the file info
897 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
898 * @param $user Mixed: User object or null to use $wgUser
900 * @return FileRepoStatus object. On success, the value member contains the
901 * archive name, or an empty string if it was a new file.
903 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
905 // truncate nicely or the DB will do it for us
906 // non-nicely (dangling multi-byte chars, non-truncated
907 // version in cache).
908 $comment = $wgContLang->truncate( $comment, 255 );
910 $status = $this->publish( $srcPath, $flags );
913 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
914 $status->fatal( 'filenotfound', $srcPath );
924 * Record a file upload in the upload log and the image table
926 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
927 $watch = false, $timestamp = false )
929 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
931 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
937 $wgUser->addWatch( $this->getTitle() );
943 * Record a file upload in the upload log and the image table
945 function recordUpload2(
946 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
948 if ( is_null( $user ) ) {
953 $dbw = $this->repo
->getMasterDB();
957 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
960 if ( $timestamp === false ) {
961 $timestamp = $dbw->timestamp();
964 $props['description'] = $comment;
965 $props['user'] = $user->getId();
966 $props['user_text'] = $user->getName();
967 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
968 $this->setProps( $props );
971 $this->purgeThumbnails();
973 # The file is already on its final location, remove it from the squid cache
974 SquidUpdate
::purge( array( $this->getURL() ) );
976 # Fail now if the file isn't there
977 if ( !$this->fileExists
) {
978 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
984 # Test to see if the row exists using INSERT IGNORE
985 # This avoids race conditions by locking the row until the commit, and also
986 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
987 $dbw->insert( 'image',
989 'img_name' => $this->getName(),
990 'img_size' => $this->size
,
991 'img_width' => intval( $this->width
),
992 'img_height' => intval( $this->height
),
993 'img_bits' => $this->bits
,
994 'img_media_type' => $this->media_type
,
995 'img_major_mime' => $this->major_mime
,
996 'img_minor_mime' => $this->minor_mime
,
997 'img_timestamp' => $timestamp,
998 'img_description' => $comment,
999 'img_user' => $user->getId(),
1000 'img_user_text' => $user->getName(),
1001 'img_metadata' => $this->metadata
,
1002 'img_sha1' => $this->sha1
1008 if ( $dbw->affectedRows() == 0 ) {
1009 if ( $oldver == '' ) {
1010 throw new MWException( "Empty oi_archive_name. Database and storage out of sync?" );
1013 # Collision, this is an update of a file
1014 # Insert previous contents into oldimage
1015 $dbw->insertSelect( 'oldimage', 'image',
1017 'oi_name' => 'img_name',
1018 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1019 'oi_size' => 'img_size',
1020 'oi_width' => 'img_width',
1021 'oi_height' => 'img_height',
1022 'oi_bits' => 'img_bits',
1023 'oi_timestamp' => 'img_timestamp',
1024 'oi_description' => 'img_description',
1025 'oi_user' => 'img_user',
1026 'oi_user_text' => 'img_user_text',
1027 'oi_metadata' => 'img_metadata',
1028 'oi_media_type' => 'img_media_type',
1029 'oi_major_mime' => 'img_major_mime',
1030 'oi_minor_mime' => 'img_minor_mime',
1031 'oi_sha1' => 'img_sha1'
1032 ), array( 'img_name' => $this->getName() ), __METHOD__
1035 # Update the current image row
1036 $dbw->update( 'image',
1038 'img_size' => $this->size
,
1039 'img_width' => intval( $this->width
),
1040 'img_height' => intval( $this->height
),
1041 'img_bits' => $this->bits
,
1042 'img_media_type' => $this->media_type
,
1043 'img_major_mime' => $this->major_mime
,
1044 'img_minor_mime' => $this->minor_mime
,
1045 'img_timestamp' => $timestamp,
1046 'img_description' => $comment,
1047 'img_user' => $user->getId(),
1048 'img_user_text' => $user->getName(),
1049 'img_metadata' => $this->metadata
,
1050 'img_sha1' => $this->sha1
1051 ), array( /* WHERE */
1052 'img_name' => $this->getName()
1056 # This is a new file
1057 # Update the image count
1058 $dbw->begin( __METHOD__
);
1061 array( 'ss_images = ss_images+1' ),
1065 $dbw->commit( __METHOD__
);
1068 $descTitle = $this->getTitle();
1069 $wikiPage = new WikiFilePage( $descTitle );
1070 $wikiPage->setFile( $this );
1073 $log = new LogPage( 'upload' );
1074 $action = $reupload ?
'overwrite' : 'upload';
1075 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1077 if ( $descTitle->exists() ) {
1078 # Create a null revision
1079 $latest = $descTitle->getLatestRevID();
1080 $nullRevision = Revision
::newNullRevision(
1082 $descTitle->getArticleId(),
1083 $log->getRcComment(),
1086 if (!is_null($nullRevision)) {
1087 $nullRevision->insertOn( $dbw );
1089 wfRunHooks( 'NewRevisionFromEditComplete', array( $wikiPage, $nullRevision, $latest, $user ) );
1090 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1092 # Invalidate the cache for the description page
1093 $descTitle->invalidateCache();
1094 $descTitle->purgeSquid();
1096 # New file; create the description page.
1097 # There's already a log entry, so don't make a second RC entry
1098 # Squid and file cache for the description page are purged by doEdit.
1099 $wikiPage->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
1102 # Commit the transaction now, in case something goes wrong later
1103 # The most important thing is that files don't get lost, especially archives
1106 # Save to cache and purge the squid
1107 # We shall not saveToCache before the commit since otherwise
1108 # in case of a rollback there is an usable file from memcached
1109 # which in fact doesn't really exist (bug 24978)
1110 $this->saveToCache();
1112 # Hooks, hooks, the magic of hooks...
1113 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1115 # Invalidate cache for all pages using this file
1116 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1117 $update->doUpdate();
1119 # Invalidate cache for all pages that redirects on this page
1120 $redirs = $this->getTitle()->getRedirectsHere();
1122 foreach ( $redirs as $redir ) {
1123 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1124 $update->doUpdate();
1131 * Move or copy a file to its public location. If a file exists at the
1132 * destination, move it to an archive. Returns a FileRepoStatus object with
1133 * the archive name in the "value" member on success.
1135 * The archive name should be passed through to recordUpload for database
1138 * @param $srcPath String: local filesystem path to the source image
1139 * @param $flags Integer: a bitwise combination of:
1140 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1141 * @return FileRepoStatus object. On success, the value member contains the
1142 * archive name, or an empty string if it was a new file.
1144 function publish( $srcPath, $flags = 0 ) {
1145 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1149 * Move or copy a file to a specified location. Returns a FileRepoStatus
1150 * object with the archive name in the "value" member on success.
1152 * The archive name should be passed through to recordUpload for database
1155 * @param $srcPath String: local filesystem path to the source image
1156 * @param $dstRel String: target relative path
1157 * @param $flags Integer: a bitwise combination of:
1158 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1159 * @return FileRepoStatus object. On success, the value member contains the
1160 * archive name, or an empty string if it was a new file.
1162 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1165 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1166 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1167 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1168 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1170 if ( $status->value
== 'new' ) {
1171 $status->value
= '';
1173 $status->value
= $archiveName;
1181 /** getLinksTo inherited */
1182 /** getExifData inherited */
1183 /** isLocal inherited */
1184 /** wasDeleted inherited */
1187 * Move file to the new title
1189 * Move current, old version and all thumbnails
1190 * to the new filename. Old file is deleted.
1192 * Cache purging is done; checks for validity
1193 * and logging are caller's responsibility
1195 * @param $target Title New file name
1196 * @return FileRepoStatus object.
1198 function move( $target ) {
1199 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1202 $batch = new LocalFileMoveBatch( $this, $target );
1203 $batch->addCurrent();
1206 $status = $batch->execute();
1207 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1209 $this->purgeEverything();
1212 if ( $status->isOk() ) {
1213 // Now switch the object
1214 $this->title
= $target;
1215 // Force regeneration of the name and hashpath
1216 unset( $this->name
);
1217 unset( $this->hashPath
);
1218 // Purge the new image
1219 $this->purgeEverything();
1226 * Delete all versions of the file.
1228 * Moves the files into an archive directory (or deletes them)
1229 * and removes the database rows.
1231 * Cache purging is done; logging is caller's responsibility.
1235 * @return FileRepoStatus object.
1237 function delete( $reason, $suppress = false ) {
1240 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1241 $batch->addCurrent();
1243 # Get old version relative paths
1244 $dbw = $this->repo
->getMasterDB();
1245 $result = $dbw->select( 'oldimage',
1246 array( 'oi_archive_name' ),
1247 array( 'oi_name' => $this->getName() ) );
1248 foreach ( $result as $row ) {
1249 $batch->addOld( $row->oi_archive_name
);
1250 $this->purgeOldThumbnails( $row->oi_archive_name
);
1252 $status = $batch->execute();
1254 if ( $status->ok
) {
1255 // Update site_stats
1256 $site_stats = $dbw->tableName( 'site_stats' );
1257 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1258 $this->purgeEverything();
1267 * Delete an old version of the file.
1269 * Moves the file into an archive directory (or deletes it)
1270 * and removes the database row.
1272 * Cache purging is done; logging is caller's responsibility.
1274 * @param $archiveName String
1275 * @param $reason String
1276 * @param $suppress Boolean
1277 * @throws MWException or FSException on database or file store failure
1278 * @return FileRepoStatus object.
1280 function deleteOld( $archiveName, $reason, $suppress = false ) {
1283 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1284 $batch->addOld( $archiveName );
1285 $this->purgeOldThumbnails( $archiveName );
1286 $status = $batch->execute();
1290 if ( $status->ok
) {
1291 $this->purgeDescription();
1292 $this->purgeHistory();
1299 * Restore all or specified deleted revisions to the given file.
1300 * Permissions and logging are left to the caller.
1302 * May throw database exceptions on error.
1304 * @param $versions set of record ids of deleted items to restore,
1305 * or empty to restore all revisions.
1306 * @param $unsuppress Boolean
1307 * @return FileRepoStatus
1309 function restore( $versions = array(), $unsuppress = false ) {
1310 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1315 $batch->addIds( $versions );
1318 $status = $batch->execute();
1320 if ( !$status->isGood() ) {
1324 $cleanupStatus = $batch->cleanup();
1325 $cleanupStatus->successCount
= 0;
1326 $cleanupStatus->failCount
= 0;
1327 $status->merge( $cleanupStatus );
1332 /** isMultipage inherited */
1333 /** pageCount inherited */
1334 /** scaleHeight inherited */
1335 /** getImageSize inherited */
1338 * Get the URL of the file description page.
1340 function getDescriptionUrl() {
1341 return $this->title
->getLocalUrl();
1345 * Get the HTML text of the description page
1346 * This is not used by ImagePage for local files, since (among other things)
1347 * it skips the parser cache.
1349 function getDescriptionText() {
1351 $revision = Revision
::newFromTitle( $this->title
);
1352 if ( !$revision ) return false;
1353 $text = $revision->getText();
1354 if ( !$text ) return false;
1355 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1356 return $pout->getText();
1359 function getDescription() {
1361 return $this->description
;
1364 function getTimestamp() {
1366 return $this->timestamp
;
1369 function getSha1() {
1371 // Initialise now if necessary
1372 if ( $this->sha1
== '' && $this->fileExists
) {
1373 $tmpPath = $this->getLocalRefPath();
1374 $this->sha1
= FSFile
::sha1Base36( $tmpPath );
1375 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1376 $dbw = $this->repo
->getMasterDB();
1377 $dbw->update( 'image',
1378 array( 'img_sha1' => $this->sha1
),
1379 array( 'img_name' => $this->getName() ),
1381 $this->saveToCache();
1389 * Start a transaction and lock the image for update
1390 * Increments a reference counter if the lock is already held
1391 * @return boolean True if the image exists, false otherwise
1394 $dbw = $this->repo
->getMasterDB();
1396 if ( !$this->locked
) {
1401 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1405 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1406 * the transaction and thereby releases the image lock.
1409 if ( $this->locked
) {
1411 if ( !$this->locked
) {
1412 $dbw = $this->repo
->getMasterDB();
1419 * Roll back the DB transaction and mark the image unlocked
1421 function unlockAndRollback() {
1422 $this->locked
= false;
1423 $dbw = $this->repo
->getMasterDB();
1426 } // LocalFile class
1428 # ------------------------------------------------------------------------------
1431 * Helper class for file deletion
1434 class LocalFileDeleteBatch
{
1441 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1444 function __construct( File
$file, $reason = '', $suppress = false ) {
1445 $this->file
= $file;
1446 $this->reason
= $reason;
1447 $this->suppress
= $suppress;
1448 $this->status
= $file->repo
->newGood();
1451 function addCurrent() {
1452 $this->srcRels
['.'] = $this->file
->getRel();
1455 function addOld( $oldName ) {
1456 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1457 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1460 function getOldRels() {
1461 if ( !isset( $this->srcRels
['.'] ) ) {
1462 $oldRels =& $this->srcRels
;
1463 $deleteCurrent = false;
1465 $oldRels = $this->srcRels
;
1466 unset( $oldRels['.'] );
1467 $deleteCurrent = true;
1470 return array( $oldRels, $deleteCurrent );
1473 protected function getHashes() {
1475 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1477 if ( $deleteCurrent ) {
1478 $hashes['.'] = $this->file
->getSha1();
1481 if ( count( $oldRels ) ) {
1482 $dbw = $this->file
->repo
->getMasterDB();
1483 $res = $dbw->select(
1485 array( 'oi_archive_name', 'oi_sha1' ),
1486 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1490 foreach ( $res as $row ) {
1491 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1492 // Get the hash from the file
1493 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1494 $props = $this->file
->repo
->getFileProps( $oldUrl );
1496 if ( $props['fileExists'] ) {
1497 // Upgrade the oldimage row
1498 $dbw->update( 'oldimage',
1499 array( 'oi_sha1' => $props['sha1'] ),
1500 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1502 $hashes[$row->oi_archive_name
] = $props['sha1'];
1504 $hashes[$row->oi_archive_name
] = false;
1507 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1512 $missing = array_diff_key( $this->srcRels
, $hashes );
1514 foreach ( $missing as $name => $rel ) {
1515 $this->status
->error( 'filedelete-old-unregistered', $name );
1518 foreach ( $hashes as $name => $hash ) {
1520 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1521 unset( $hashes[$name] );
1528 function doDBInserts() {
1531 $dbw = $this->file
->repo
->getMasterDB();
1532 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1533 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1534 $encReason = $dbw->addQuotes( $this->reason
);
1535 $encGroup = $dbw->addQuotes( 'deleted' );
1536 $ext = $this->file
->getExtension();
1537 $dotExt = $ext === '' ?
'' : ".$ext";
1538 $encExt = $dbw->addQuotes( $dotExt );
1539 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1541 // Bitfields to further suppress the content
1542 if ( $this->suppress
) {
1544 // This should be 15...
1545 $bitfield |
= Revision
::DELETED_TEXT
;
1546 $bitfield |
= Revision
::DELETED_COMMENT
;
1547 $bitfield |
= Revision
::DELETED_USER
;
1548 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1550 $bitfield = 'oi_deleted';
1553 if ( $deleteCurrent ) {
1554 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1555 $where = array( 'img_name' => $this->file
->getName() );
1556 $dbw->insertSelect( 'filearchive', 'image',
1558 'fa_storage_group' => $encGroup,
1559 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1560 'fa_deleted_user' => $encUserId,
1561 'fa_deleted_timestamp' => $encTimestamp,
1562 'fa_deleted_reason' => $encReason,
1563 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1565 'fa_name' => 'img_name',
1566 'fa_archive_name' => 'NULL',
1567 'fa_size' => 'img_size',
1568 'fa_width' => 'img_width',
1569 'fa_height' => 'img_height',
1570 'fa_metadata' => 'img_metadata',
1571 'fa_bits' => 'img_bits',
1572 'fa_media_type' => 'img_media_type',
1573 'fa_major_mime' => 'img_major_mime',
1574 'fa_minor_mime' => 'img_minor_mime',
1575 'fa_description' => 'img_description',
1576 'fa_user' => 'img_user',
1577 'fa_user_text' => 'img_user_text',
1578 'fa_timestamp' => 'img_timestamp'
1579 ), $where, __METHOD__
);
1582 if ( count( $oldRels ) ) {
1583 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1585 'oi_name' => $this->file
->getName(),
1586 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1587 $dbw->insertSelect( 'filearchive', 'oldimage',
1589 'fa_storage_group' => $encGroup,
1590 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1591 'fa_deleted_user' => $encUserId,
1592 'fa_deleted_timestamp' => $encTimestamp,
1593 'fa_deleted_reason' => $encReason,
1594 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1596 'fa_name' => 'oi_name',
1597 'fa_archive_name' => 'oi_archive_name',
1598 'fa_size' => 'oi_size',
1599 'fa_width' => 'oi_width',
1600 'fa_height' => 'oi_height',
1601 'fa_metadata' => 'oi_metadata',
1602 'fa_bits' => 'oi_bits',
1603 'fa_media_type' => 'oi_media_type',
1604 'fa_major_mime' => 'oi_major_mime',
1605 'fa_minor_mime' => 'oi_minor_mime',
1606 'fa_description' => 'oi_description',
1607 'fa_user' => 'oi_user',
1608 'fa_user_text' => 'oi_user_text',
1609 'fa_timestamp' => 'oi_timestamp',
1610 'fa_deleted' => $bitfield
1611 ), $where, __METHOD__
);
1615 function doDBDeletes() {
1616 $dbw = $this->file
->repo
->getMasterDB();
1617 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1619 if ( count( $oldRels ) ) {
1620 $dbw->delete( 'oldimage',
1622 'oi_name' => $this->file
->getName(),
1623 'oi_archive_name' => array_keys( $oldRels )
1627 if ( $deleteCurrent ) {
1628 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1633 * Run the transaction
1635 function execute() {
1637 wfProfileIn( __METHOD__
);
1639 $this->file
->lock();
1640 // Leave private files alone
1641 $privateFiles = array();
1642 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1643 $dbw = $this->file
->repo
->getMasterDB();
1645 if ( !empty( $oldRels ) ) {
1646 $res = $dbw->select( 'oldimage',
1647 array( 'oi_archive_name' ),
1648 array( 'oi_name' => $this->file
->getName(),
1649 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1650 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1653 foreach ( $res as $row ) {
1654 $privateFiles[$row->oi_archive_name
] = 1;
1657 // Prepare deletion batch
1658 $hashes = $this->getHashes();
1659 $this->deletionBatch
= array();
1660 $ext = $this->file
->getExtension();
1661 $dotExt = $ext === '' ?
'' : ".$ext";
1663 foreach ( $this->srcRels
as $name => $srcRel ) {
1664 // Skip files that have no hash (missing source).
1665 // Keep private files where they are.
1666 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1667 $hash = $hashes[$name];
1668 $key = $hash . $dotExt;
1669 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1670 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1674 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1675 // We acquire this lock by running the inserts now, before the file operations.
1677 // This potentially has poor lock contention characteristics -- an alternative
1678 // scheme would be to insert stub filearchive entries with no fa_name and commit
1679 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1680 $this->doDBInserts();
1682 // Removes non-existent file from the batch, so we don't get errors.
1683 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1685 // Execute the file deletion batch
1686 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1688 if ( !$status->isGood() ) {
1689 $this->status
->merge( $status );
1692 if ( !$this->status
->ok
) {
1693 // Critical file deletion error
1694 // Roll back inserts, release lock and abort
1695 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1696 $this->file
->unlockAndRollback();
1697 wfProfileOut( __METHOD__
);
1698 return $this->status
;
1702 if ( $wgUseSquid ) {
1705 foreach ( $this->srcRels
as $srcRel ) {
1706 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1707 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1709 SquidUpdate
::purge( $urls );
1712 // Delete image/oldimage rows
1713 $this->doDBDeletes();
1715 // Commit and return
1716 $this->file
->unlock();
1717 wfProfileOut( __METHOD__
);
1719 return $this->status
;
1723 * Removes non-existent files from a deletion batch.
1725 function removeNonexistentFiles( $batch ) {
1726 $files = $newBatch = array();
1728 foreach ( $batch as $batchItem ) {
1729 list( $src, $dest ) = $batchItem;
1730 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1733 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1735 foreach ( $batch as $batchItem ) {
1736 if ( $result[$batchItem[0]] ) {
1737 $newBatch[] = $batchItem;
1745 # ------------------------------------------------------------------------------
1748 * Helper class for file undeletion
1751 class LocalFileRestoreBatch
{
1757 var $cleanupBatch, $ids, $all, $unsuppress = false;
1759 function __construct( File
$file, $unsuppress = false ) {
1760 $this->file
= $file;
1761 $this->cleanupBatch
= $this->ids
= array();
1762 $this->ids
= array();
1763 $this->unsuppress
= $unsuppress;
1769 function addId( $fa_id ) {
1770 $this->ids
[] = $fa_id;
1774 * Add a whole lot of files by ID
1776 function addIds( $ids ) {
1777 $this->ids
= array_merge( $this->ids
, $ids );
1781 * Add all revisions of the file
1788 * Run the transaction, except the cleanup batch.
1789 * The cleanup batch should be run in a separate transaction, because it locks different
1790 * rows and there's no need to keep the image row locked while it's acquiring those locks
1791 * The caller may have its own transaction open.
1792 * So we save the batch and let the caller call cleanup()
1794 function execute() {
1797 if ( !$this->all
&& !$this->ids
) {
1799 return $this->file
->repo
->newGood();
1802 $exists = $this->file
->lock();
1803 $dbw = $this->file
->repo
->getMasterDB();
1804 $status = $this->file
->repo
->newGood();
1806 // Fetch all or selected archived revisions for the file,
1807 // sorted from the most recent to the oldest.
1808 $conditions = array( 'fa_name' => $this->file
->getName() );
1810 if ( !$this->all
) {
1811 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1814 $result = $dbw->select( 'filearchive', '*',
1817 array( 'ORDER BY' => 'fa_timestamp DESC' )
1820 $idsPresent = array();
1821 $storeBatch = array();
1822 $insertBatch = array();
1823 $insertCurrent = false;
1824 $deleteIds = array();
1826 $archiveNames = array();
1828 foreach ( $result as $row ) {
1829 $idsPresent[] = $row->fa_id
;
1831 if ( $row->fa_name
!= $this->file
->getName() ) {
1832 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1833 $status->failCount++
;
1837 if ( $row->fa_storage_key
== '' ) {
1838 // Revision was missing pre-deletion
1839 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1840 $status->failCount++
;
1844 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1845 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1847 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1850 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1851 $sha1 = substr( $sha1, 1 );
1854 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1855 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1856 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1857 ||
is_null( $row->fa_metadata
) ) {
1858 // Refresh our metadata
1859 // Required for a new current revision; nice for older ones too. :)
1860 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1863 'minor_mime' => $row->fa_minor_mime
,
1864 'major_mime' => $row->fa_major_mime
,
1865 'media_type' => $row->fa_media_type
,
1866 'metadata' => $row->fa_metadata
1870 if ( $first && !$exists ) {
1871 // This revision will be published as the new current version
1872 $destRel = $this->file
->getRel();
1873 $insertCurrent = array(
1874 'img_name' => $row->fa_name
,
1875 'img_size' => $row->fa_size
,
1876 'img_width' => $row->fa_width
,
1877 'img_height' => $row->fa_height
,
1878 'img_metadata' => $props['metadata'],
1879 'img_bits' => $row->fa_bits
,
1880 'img_media_type' => $props['media_type'],
1881 'img_major_mime' => $props['major_mime'],
1882 'img_minor_mime' => $props['minor_mime'],
1883 'img_description' => $row->fa_description
,
1884 'img_user' => $row->fa_user
,
1885 'img_user_text' => $row->fa_user_text
,
1886 'img_timestamp' => $row->fa_timestamp
,
1890 // The live (current) version cannot be hidden!
1891 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1892 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1893 $this->cleanupBatch
[] = $row->fa_storage_key
;
1896 $archiveName = $row->fa_archive_name
;
1898 if ( $archiveName == '' ) {
1899 // This was originally a current version; we
1900 // have to devise a new archive name for it.
1901 // Format is <timestamp of archiving>!<name>
1902 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1905 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1907 } while ( isset( $archiveNames[$archiveName] ) );
1910 $archiveNames[$archiveName] = true;
1911 $destRel = $this->file
->getArchiveRel( $archiveName );
1912 $insertBatch[] = array(
1913 'oi_name' => $row->fa_name
,
1914 'oi_archive_name' => $archiveName,
1915 'oi_size' => $row->fa_size
,
1916 'oi_width' => $row->fa_width
,
1917 'oi_height' => $row->fa_height
,
1918 'oi_bits' => $row->fa_bits
,
1919 'oi_description' => $row->fa_description
,
1920 'oi_user' => $row->fa_user
,
1921 'oi_user_text' => $row->fa_user_text
,
1922 'oi_timestamp' => $row->fa_timestamp
,
1923 'oi_metadata' => $props['metadata'],
1924 'oi_media_type' => $props['media_type'],
1925 'oi_major_mime' => $props['major_mime'],
1926 'oi_minor_mime' => $props['minor_mime'],
1927 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1928 'oi_sha1' => $sha1 );
1931 $deleteIds[] = $row->fa_id
;
1933 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1934 // private files can stay where they are
1935 $status->successCount++
;
1937 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1938 $this->cleanupBatch
[] = $row->fa_storage_key
;
1946 // Add a warning to the status object for missing IDs
1947 $missingIds = array_diff( $this->ids
, $idsPresent );
1949 foreach ( $missingIds as $id ) {
1950 $status->error( 'undelete-missing-filearchive', $id );
1953 // Remove missing files from batch, so we don't get errors when undeleting them
1954 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1956 // Run the store batch
1957 // Use the OVERWRITE_SAME flag to smooth over a common error
1958 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1959 $status->merge( $storeStatus );
1961 if ( !$status->isGood() ) {
1962 // Even if some files could be copied, fail entirely as that is the
1963 // easiest thing to do without data loss
1964 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1965 $status->ok
= false;
1966 $this->file
->unlock();
1971 // Run the DB updates
1972 // Because we have locked the image row, key conflicts should be rare.
1973 // If they do occur, we can roll back the transaction at this time with
1974 // no data loss, but leaving unregistered files scattered throughout the
1976 // This is not ideal, which is why it's important to lock the image row.
1977 if ( $insertCurrent ) {
1978 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1981 if ( $insertBatch ) {
1982 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1986 $dbw->delete( 'filearchive',
1987 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1991 // If store batch is empty (all files are missing), deletion is to be considered successful
1992 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1994 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1996 // Update site_stats
1997 $site_stats = $dbw->tableName( 'site_stats' );
1998 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
2000 $this->file
->purgeEverything();
2002 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2003 $this->file
->purgeDescription();
2004 $this->file
->purgeHistory();
2008 $this->file
->unlock();
2014 * Removes non-existent files from a store batch.
2016 function removeNonexistentFiles( $triplets ) {
2017 $files = $filteredTriplets = array();
2018 foreach ( $triplets as $file )
2019 $files[$file[0]] = $file[0];
2021 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2023 foreach ( $triplets as $file ) {
2024 if ( $result[$file[0]] ) {
2025 $filteredTriplets[] = $file;
2029 return $filteredTriplets;
2033 * Removes non-existent files from a cleanup batch.
2035 function removeNonexistentFromCleanup( $batch ) {
2036 $files = $newBatch = array();
2037 $repo = $this->file
->repo
;
2039 foreach ( $batch as $file ) {
2040 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2041 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2044 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2046 foreach ( $batch as $file ) {
2047 if ( $result[$file] ) {
2048 $newBatch[] = $file;
2056 * Delete unused files in the deleted zone.
2057 * This should be called from outside the transaction in which execute() was called.
2059 function cleanup() {
2060 if ( !$this->cleanupBatch
) {
2061 return $this->file
->repo
->newGood();
2064 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2066 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2072 * Cleanup a failed batch. The batch was only partially successful, so
2073 * rollback by removing all items that were succesfully copied.
2075 * @param Status $storeStatus
2076 * @param array $storeBatch
2078 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2079 $cleanupBatch = array();
2081 foreach ( $storeStatus->success
as $i => $success ) {
2082 // Check if this item of the batch was successfully copied
2084 // Item was successfully copied and needs to be removed again
2085 // Extract ($dstZone, $dstRel) from the batch
2086 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2089 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2093 # ------------------------------------------------------------------------------
2096 * Helper class for file movement
2099 class LocalFileMoveBatch
{
2111 var $cur, $olds, $oldCount, $archive, $db;
2113 function __construct( File
$file, Title
$target ) {
2114 $this->file
= $file;
2115 $this->target
= $target;
2116 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2117 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2118 $this->oldName
= $this->file
->getName();
2119 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2120 $this->oldRel
= $this->oldHash
. $this->oldName
;
2121 $this->newRel
= $this->newHash
. $this->newName
;
2122 $this->db
= $file->repo
->getMasterDb();
2126 * Add the current image to the batch
2128 function addCurrent() {
2129 $this->cur
= array( $this->oldRel
, $this->newRel
);
2133 * Add the old versions of the image to the batch
2135 function addOlds() {
2136 $archiveBase = 'archive';
2137 $this->olds
= array();
2138 $this->oldCount
= 0;
2140 $result = $this->db
->select( 'oldimage',
2141 array( 'oi_archive_name', 'oi_deleted' ),
2142 array( 'oi_name' => $this->oldName
),
2146 foreach ( $result as $row ) {
2147 $oldName = $row->oi_archive_name
;
2148 $bits = explode( '!', $oldName, 2 );
2150 if ( count( $bits ) != 2 ) {
2151 wfDebug( "Old file name missing !: '$oldName' \n" );
2155 list( $timestamp, $filename ) = $bits;
2157 if ( $this->oldName
!= $filename ) {
2158 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2164 // Do we want to add those to oldCount?
2165 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2169 $this->olds
[] = array(
2170 "{$archiveBase}/{$this->oldHash}{$oldName}",
2171 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2179 function execute() {
2180 $repo = $this->file
->repo
;
2181 $status = $repo->newGood();
2182 $triplets = $this->getMoveTriplets();
2184 $triplets = $this->removeNonexistentFiles( $triplets );
2186 // Copy the files into their new location
2187 $statusMove = $repo->storeBatch( $triplets );
2188 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2189 if ( !$statusMove->isGood() ) {
2190 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2191 $this->cleanupTarget( $triplets );
2192 $statusMove->ok
= false;
2197 $statusDb = $this->doDBUpdates();
2198 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2199 if ( !$statusDb->isGood() ) {
2200 $this->db
->rollback();
2201 // Something went wrong with the DB updates, so remove the target files
2202 $this->cleanupTarget( $triplets );
2203 $statusDb->ok
= false;
2206 $this->db
->commit();
2208 // Everything went ok, remove the source files
2209 $this->cleanupSource( $triplets );
2211 $status->merge( $statusDb );
2212 $status->merge( $statusMove );
2218 * Do the database updates and return a new FileRepoStatus indicating how
2219 * many rows where updated.
2221 * @return FileRepoStatus
2223 function doDBUpdates() {
2224 $repo = $this->file
->repo
;
2225 $status = $repo->newGood();
2228 // Update current image
2231 array( 'img_name' => $this->newName
),
2232 array( 'img_name' => $this->oldName
),
2236 if ( $dbw->affectedRows() ) {
2237 $status->successCount++
;
2239 $status->failCount++
;
2240 $status->fatal( 'imageinvalidfilename' );
2244 // Update old images
2248 'oi_name' => $this->newName
,
2249 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2251 array( 'oi_name' => $this->oldName
),
2255 $affected = $dbw->affectedRows();
2256 $total = $this->oldCount
;
2257 $status->successCount +
= $affected;
2258 $status->failCount +
= $total - $affected;
2259 if ( $status->failCount
) {
2260 $status->error( 'imageinvalidfilename' );
2267 * Generate triplets for FSRepo::storeBatch().
2269 function getMoveTriplets() {
2270 $moves = array_merge( array( $this->cur
), $this->olds
);
2271 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2273 foreach ( $moves as $move ) {
2274 // $move: (oldRelativePath, newRelativePath)
2275 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2276 $triplets[] = array( $srcUrl, 'public', $move[1] );
2277 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2284 * Removes non-existent files from move batch.
2286 function removeNonexistentFiles( $triplets ) {
2289 foreach ( $triplets as $file ) {
2290 $files[$file[0]] = $file[0];
2293 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2294 $filteredTriplets = array();
2296 foreach ( $triplets as $file ) {
2297 if ( $result[$file[0]] ) {
2298 $filteredTriplets[] = $file;
2300 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2304 return $filteredTriplets;
2308 * Cleanup a partially moved array of triplets by deleting the target
2309 * files. Called if something went wrong half way.
2311 function cleanupTarget( $triplets ) {
2312 // Create dest pairs from the triplets
2314 foreach ( $triplets as $triplet ) {
2315 $pairs[] = array( $triplet[1], $triplet[2] );
2318 $this->file
->repo
->cleanupBatch( $pairs );
2322 * Cleanup a fully moved array of triplets by deleting the source files.
2323 * Called at the end of the move process if everything else went ok.
2325 function cleanupSource( $triplets ) {
2326 // Create source file names from the triplets
2328 foreach ( $triplets as $triplet ) {
2329 $files[] = $triplet[0];
2332 $this->file
->repo
->cleanupBatch( $files );