3 * Local file in the wiki's own database
10 * Bump this number when serialized cache records may be incompatible.
12 define( 'MW_FILE_VERSION', 8 );
15 * Class to represent a local file in the wiki's own database
17 * Provides methods to retrieve paths (physical, logical, URL),
18 * to generate image thumbnails or for uploading.
20 * Note that only the repo object knows what its file class is called. You should
21 * never name a file class explictly outside of the repo class. Instead use the
22 * repo's factory functions to generate file objects, for example:
24 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
26 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
31 class LocalFile
extends File
{
36 $fileExists, # does the file exist on disk? (loadFromXxx)
37 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
38 $historyRes, # result of the query for the file's history (nextHistoryLine)
41 $bits, # --- returned by getimagesize (loadFromXxx)
43 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
44 $mime, # MIME type, determined by MimeMagic::guessMimeType
45 $major_mime, # Major mime type
46 $minor_mime, # Minor mime type
47 $size, # Size in bytes (loadFromXxx)
48 $metadata, # Handler-specific metadata
49 $timestamp, # Upload timestamp
50 $sha1, # SHA-1 base 36 content hash
51 $user, $user_text, # User, who uploaded the file
52 $description, # Description of current revision of the file
53 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
54 $upgraded, # Whether the row was upgraded on load
55 $locked, # True if the image row is locked
56 $missing, # True if file is not present in file system. Not to be cached in memcached
57 $deleted; # Bitfield akin to rev_deleted
62 * Create a LocalFile from a title
63 * Do not call this except from inside a repo class.
65 * Note: $unused param is only here to avoid an E_STRICT
73 static function newFromTitle( $title, $repo, $unused = null ) {
74 return new self( $title, $repo );
78 * Create a LocalFile from a title
79 * Do not call this except from inside a repo class.
86 static function newFromRow( $row, $repo ) {
87 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
88 $file = new self( $title, $repo );
89 $file->loadFromRow( $row );
95 * Create a LocalFile from a SHA-1 key
96 * Do not call this except from inside a repo class.
98 * @param $sha1 string base-36 SHA-1
99 * @param $repo LocalRepo
100 * @param string|bool $timestamp MW_timestamp (optional)
102 * @return bool|LocalFile
104 static function newFromKey( $sha1, $repo, $timestamp = false ) {
105 $dbr = $repo->getSlaveDB();
107 $conds = array( 'img_sha1' => $sha1 );
109 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
112 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
114 return self
::newFromRow( $row, $repo );
121 * Fields in the image table
123 static function selectFields() {
144 * Do not call this except from inside a repo class.
146 function __construct( $title, $repo ) {
147 if ( !is_object( $title ) ) {
148 throw new MWException( __CLASS__
. ' constructor given bogus title.' );
151 parent
::__construct( $title, $repo );
153 $this->metadata
= '';
154 $this->historyLine
= 0;
155 $this->historyRes
= null;
156 $this->dataLoaded
= false;
160 * Get the memcached key for the main data for this file, or false if
161 * there is no access to the shared cache.
163 function getCacheKey() {
164 $hashedName = md5( $this->getName() );
166 return $this->repo
->getSharedCacheKey( 'file', $hashedName );
170 * Try to load file metadata from memcached. Returns true on success.
172 function loadFromCache() {
175 wfProfileIn( __METHOD__
);
176 $this->dataLoaded
= false;
177 $key = $this->getCacheKey();
180 wfProfileOut( __METHOD__
);
184 $cachedValues = $wgMemc->get( $key );
186 // Check if the key existed and belongs to this version of MediaWiki
187 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION
) ) {
188 wfDebug( "Pulling file metadata from cache key $key\n" );
189 $this->fileExists
= $cachedValues['fileExists'];
190 if ( $this->fileExists
) {
191 $this->setProps( $cachedValues );
193 $this->dataLoaded
= true;
196 if ( $this->dataLoaded
) {
197 wfIncrStats( 'image_cache_hit' );
199 wfIncrStats( 'image_cache_miss' );
202 wfProfileOut( __METHOD__
);
203 return $this->dataLoaded
;
207 * Save the file metadata to memcached
209 function saveToCache() {
213 $key = $this->getCacheKey();
219 $fields = $this->getCacheFields( '' );
220 $cache = array( 'version' => MW_FILE_VERSION
);
221 $cache['fileExists'] = $this->fileExists
;
223 if ( $this->fileExists
) {
224 foreach ( $fields as $field ) {
225 $cache[$field] = $this->$field;
229 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
233 * Load metadata from the file itself
235 function loadFromFile() {
236 $this->setProps( self
::getPropsFromPath( $this->getPath() ) );
239 function getCacheFields( $prefix = 'img_' ) {
240 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
241 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
242 static $results = array();
244 if ( $prefix == '' ) {
248 if ( !isset( $results[$prefix] ) ) {
249 $prefixedFields = array();
250 foreach ( $fields as $field ) {
251 $prefixedFields[] = $prefix . $field;
253 $results[$prefix] = $prefixedFields;
256 return $results[$prefix];
260 * Load file metadata from the DB
262 function loadFromDB() {
263 # Polymorphic function name to distinguish foreign and local fetches
264 $fname = get_class( $this ) . '::' . __FUNCTION__
;
265 wfProfileIn( $fname );
267 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
268 $this->dataLoaded
= true;
270 $dbr = $this->repo
->getMasterDB();
272 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
273 array( 'img_name' => $this->getName() ), $fname );
276 $this->loadFromRow( $row );
278 $this->fileExists
= false;
281 wfProfileOut( $fname );
285 * Decode a row from the database (either object or array) to an array
286 * with timestamps and MIME types decoded, and the field prefix removed.
288 function decodeRow( $row, $prefix = 'img_' ) {
289 $array = (array)$row;
290 $prefixLength = strlen( $prefix );
292 // Sanity check prefix once
293 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
294 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
299 foreach ( $array as $name => $value ) {
300 $decoded[substr( $name, $prefixLength )] = $value;
303 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
305 if ( empty( $decoded['major_mime'] ) ) {
306 $decoded['mime'] = 'unknown/unknown';
308 if ( !$decoded['minor_mime'] ) {
309 $decoded['minor_mime'] = 'unknown';
311 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
314 # Trim zero padding from char/binary field
315 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
321 * Load file metadata from a DB result row
323 function loadFromRow( $row, $prefix = 'img_' ) {
324 $this->dataLoaded
= true;
325 $array = $this->decodeRow( $row, $prefix );
327 foreach ( $array as $name => $value ) {
328 $this->$name = $value;
331 $this->fileExists
= true;
332 $this->maybeUpgradeRow();
336 * Load file metadata from cache or DB, unless already loaded
339 if ( !$this->dataLoaded
) {
340 if ( !$this->loadFromCache() ) {
342 $this->saveToCache();
344 $this->dataLoaded
= true;
349 * Upgrade a row if it needs it
351 function maybeUpgradeRow() {
352 global $wgUpdateCompatibleMetadata;
353 if ( wfReadOnly() ) {
357 if ( is_null( $this->media_type
) ||
358 $this->mime
== 'image/svg'
361 $this->upgraded
= true;
363 $handler = $this->getHandler();
365 $validity = $handler->isMetadataValid( $this, $this->metadata
);
366 if ( $validity === MediaHandler
::METADATA_BAD
367 ||
( $validity === MediaHandler
::METADATA_COMPATIBLE
&& $wgUpdateCompatibleMetadata )
370 $this->upgraded
= true;
376 function getUpgraded() {
377 return $this->upgraded
;
381 * Fix assorted version-related problems with the image row by reloading it from the file
383 function upgradeRow() {
384 wfProfileIn( __METHOD__
);
386 $this->loadFromFile();
388 # Don't destroy file info of missing files
389 if ( !$this->fileExists
) {
390 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
391 wfProfileOut( __METHOD__
);
395 $dbw = $this->repo
->getMasterDB();
396 list( $major, $minor ) = self
::splitMime( $this->mime
);
398 if ( wfReadOnly() ) {
399 wfProfileOut( __METHOD__
);
402 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
404 $dbw->update( 'image',
406 'img_width' => $this->width
,
407 'img_height' => $this->height
,
408 'img_bits' => $this->bits
,
409 'img_media_type' => $this->media_type
,
410 'img_major_mime' => $major,
411 'img_minor_mime' => $minor,
412 'img_metadata' => $this->metadata
,
413 'img_sha1' => $this->sha1
,
414 ), array( 'img_name' => $this->getName() ),
418 $this->saveToCache();
419 wfProfileOut( __METHOD__
);
423 * Set properties in this object to be equal to those given in the
424 * associative array $info. Only cacheable fields can be set.
426 * If 'mime' is given, it will be split into major_mime/minor_mime.
427 * If major_mime/minor_mime are given, $this->mime will also be set.
429 function setProps( $info ) {
430 $this->dataLoaded
= true;
431 $fields = $this->getCacheFields( '' );
432 $fields[] = 'fileExists';
434 foreach ( $fields as $field ) {
435 if ( isset( $info[$field] ) ) {
436 $this->$field = $info[$field];
440 // Fix up mime fields
441 if ( isset( $info['major_mime'] ) ) {
442 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
443 } elseif ( isset( $info['mime'] ) ) {
444 $this->mime
= $info['mime'];
445 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
449 /** splitMime inherited */
450 /** getName inherited */
451 /** getTitle inherited */
452 /** getURL inherited */
453 /** getViewURL inherited */
454 /** getPath inherited */
455 /** isVisible inhereted */
457 function isMissing() {
458 if ( $this->missing
=== null ) {
459 list( $fileExists ) = $this->repo
->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo
::FILES_ONLY
);
460 $this->missing
= !$fileExists;
462 return $this->missing
;
466 * Return the width of the image
468 * Returns false on error
470 public function getWidth( $page = 1 ) {
473 if ( $this->isMultipage() ) {
474 $dim = $this->getHandler()->getPageDimensions( $this, $page );
476 return $dim['width'];
486 * Return the height of the image
488 * Returns false on error
490 public function getHeight( $page = 1 ) {
493 if ( $this->isMultipage() ) {
494 $dim = $this->getHandler()->getPageDimensions( $this, $page );
496 return $dim['height'];
501 return $this->height
;
506 * Returns ID or name of user who uploaded the file
508 * @param $type string 'text' or 'id'
510 function getUser( $type = 'text' ) {
513 if ( $type == 'text' ) {
514 return $this->user_text
;
515 } elseif ( $type == 'id' ) {
521 * Get handler-specific metadata
523 function getMetadata() {
525 return $this->metadata
;
528 function getBitDepth() {
534 * Return the size of the image file, in bytes
536 public function getSize() {
542 * Returns the mime type of the file.
544 function getMimeType() {
550 * Return the type of the media in the file.
551 * Use the value returned by this function with the MEDIATYPE_xxx constants.
553 function getMediaType() {
555 return $this->media_type
;
558 /** canRender inherited */
559 /** mustRender inherited */
560 /** allowInlineDisplay inherited */
561 /** isSafeFile inherited */
562 /** isTrustedFile inherited */
565 * Returns true if the file exists on disk.
566 * @return boolean Whether file exist on disk.
568 public function exists() {
570 return $this->fileExists
;
573 /** getTransformScript inherited */
574 /** getUnscaledThumb inherited */
575 /** thumbName inherited */
576 /** createThumb inherited */
577 /** transform inherited */
580 * Fix thumbnail files from 1.4 or before, with extreme prejudice
582 function migrateThumbFile( $thumbName ) {
583 $thumbDir = $this->getThumbPath();
584 $thumbPath = "$thumbDir/$thumbName";
586 if ( is_dir( $thumbPath ) ) {
587 // Directory where file should be
588 // This happened occasionally due to broken migration code in 1.5
589 // Rename to broken-*
590 for ( $i = 0; $i < 100 ; $i++
) {
591 $broken = $this->repo
->getZonePath( 'public' ) . "/broken-$i-$thumbName";
592 if ( !file_exists( $broken ) ) {
593 rename( $thumbPath, $broken );
597 // Doesn't exist anymore
601 if ( is_file( $thumbDir ) ) {
602 // File where directory should be
604 // Doesn't exist anymore
609 /** getHandler inherited */
610 /** iconThumb inherited */
611 /** getLastError inherited */
614 * Get all thumbnail names previously generated for this file
615 * @param $archiveName string|false Name of an archive file
616 * @return array first element is the base dir, then files in that base dir.
618 function getThumbnails( $archiveName = false ) {
621 if ( $archiveName ) {
622 $dir = $this->getArchiveThumbPath( $archiveName );
624 $dir = $this->getThumbPath();
629 if ( is_dir( $dir ) ) {
630 $handle = opendir( $dir );
633 while ( false !== ( $file = readdir( $handle ) ) ) {
634 if ( $file { 0 } != '.' ) {
647 * Refresh metadata in memcached, but don't touch thumbnails or squid
649 function purgeMetadataCache() {
651 $this->saveToCache();
652 $this->purgeHistory();
656 * Purge the shared history (OldLocalFile) cache
658 function purgeHistory() {
661 $hashedName = md5( $this->getName() );
662 $oldKey = $this->repo
->getSharedCacheKey( 'oldfile', $hashedName );
664 // Must purge thumbnails for old versions too! bug 30192
665 foreach( $this->getHistory() as $oldFile ) {
666 $oldFile->purgeThumbnails();
670 $wgMemc->delete( $oldKey );
675 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
677 function purgeCache() {
678 // Refresh metadata cache
679 $this->purgeMetadataCache();
682 $this->purgeThumbnails();
684 // Purge squid cache for this file
685 SquidUpdate
::purge( array( $this->getURL() ) );
689 * Delete cached transformed files for archived files
690 * @param $archiveName string name of the archived file
692 function purgeOldThumbnails( $archiveName ) {
694 // Get a list of old thumbnails and URLs
695 $files = $this->getThumbnails( $archiveName );
696 $dir = array_shift( $files );
697 $this->purgeThumbList( $dir, $files );
699 // Directory should be empty, delete it too. This will probably suck on
700 // something like NFS or if the directory isn't actually empty, so hide
702 wfSuppressWarnings();
703 if( !rmdir( $dir ) ) {
704 wfDebug( __METHOD__
. ": unable to remove archive directory: $dir\n" );
708 // Purge any custom thumbnail caches
709 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, 'archive' ) );
714 foreach( $files as $file ) {
715 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
717 SquidUpdate
::purge( $urls );
723 * Delete cached transformed files for the current version only.
725 function purgeThumbnails() {
729 $files = $this->getThumbnails();
730 $dir = array_shift( $files );
731 $this->purgeThumbList( $dir, $files );
733 // Purge any custom thumbnail caches
734 wfRunHooks( 'LocalFilePurgeThumbnails', array( $this, 'current' ) );
739 foreach( $files as $file ) {
740 $urls[] = $this->getThumbUrl( $file );
742 SquidUpdate
::purge( $urls );
747 * Delete a list of thumbnails visible at urls
748 * @param $dir string base dir of the files.
749 * @param $files array of strings: relative filenames (to $dir)
751 protected function purgeThumbList($dir, $files) {
752 wfDebug( __METHOD__
. ": " . var_export( $files, true ) . "\n" );
753 foreach ( $files as $file ) {
754 # Check that the base file name is part of the thumb name
755 # This is a basic sanity check to avoid erasing unrelated directories
756 if ( strpos( $file, $this->getName() ) !== false ) {
757 wfSuppressWarnings();
758 unlink( "$dir/$file" );
764 /** purgeDescription inherited */
765 /** purgeEverything inherited */
767 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
768 $dbr = $this->repo
->getSlaveDB();
769 $tables = array( 'oldimage' );
770 $fields = OldLocalFile
::selectFields();
771 $conds = $opts = $join_conds = array();
772 $eq = $inc ?
'=' : '';
773 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
776 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
780 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
784 $opts['LIMIT'] = $limit;
787 // Search backwards for time > x queries
788 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
789 $opts['ORDER BY'] = "oi_timestamp $order";
790 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
792 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
793 &$conds, &$opts, &$join_conds ) );
795 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
798 foreach ( $res as $row ) {
799 if ( $this->repo
->oldFileFromRowFactory
) {
800 $r[] = call_user_func( $this->repo
->oldFileFromRowFactory
, $row, $this->repo
);
802 $r[] = OldLocalFile
::newFromRow( $row, $this->repo
);
806 if ( $order == 'ASC' ) {
807 $r = array_reverse( $r ); // make sure it ends up descending
814 * Return the history of this file, line by line.
815 * starts with current version, then old versions.
816 * uses $this->historyLine to check which line to return:
817 * 0 return line for current version
818 * 1 query for old versions, return first one
819 * 2, ... return next old version from above query
821 public function nextHistoryLine() {
822 # Polymorphic function name to distinguish foreign and local fetches
823 $fname = get_class( $this ) . '::' . __FUNCTION__
;
825 $dbr = $this->repo
->getSlaveDB();
827 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
828 $this->historyRes
= $dbr->select( 'image',
831 "'' AS oi_archive_name",
835 array( 'img_name' => $this->title
->getDBkey() ),
839 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
840 $this->historyRes
= null;
843 } elseif ( $this->historyLine
== 1 ) {
844 $this->historyRes
= $dbr->select( 'oldimage', '*',
845 array( 'oi_name' => $this->title
->getDBkey() ),
847 array( 'ORDER BY' => 'oi_timestamp DESC' )
850 $this->historyLine ++
;
852 return $dbr->fetchObject( $this->historyRes
);
856 * Reset the history pointer to the first element of the history
858 public function resetHistory() {
859 $this->historyLine
= 0;
861 if ( !is_null( $this->historyRes
) ) {
862 $this->historyRes
= null;
866 /** getHashPath inherited */
867 /** getRel inherited */
868 /** getUrlRel inherited */
869 /** getArchiveRel inherited */
870 /** getArchivePath inherited */
871 /** getThumbPath inherited */
872 /** getArchiveUrl inherited */
873 /** getThumbUrl inherited */
874 /** getArchiveVirtualUrl inherited */
875 /** getThumbVirtualUrl inherited */
876 /** isHashed inherited */
879 * Upload a file and record it in the DB
880 * @param $srcPath String: source path or virtual URL
881 * @param $comment String: upload description
882 * @param $pageText String: text to use for the new description page,
883 * if a new description page is created
884 * @param $flags Integer: flags for publish()
885 * @param $props Array: File properties, if known. This can be used to reduce the
886 * upload time when uploading virtual URLs for which the file info
888 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
889 * @param $user Mixed: User object or null to use $wgUser
891 * @return FileRepoStatus object. On success, the value member contains the
892 * archive name, or an empty string if it was a new file.
894 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
896 $status = $this->publish( $srcPath, $flags );
899 if ( !$this->recordUpload2( $status->value
, $comment, $pageText, $props, $timestamp, $user ) ) {
900 $status->fatal( 'filenotfound', $srcPath );
910 * Record a file upload in the upload log and the image table
912 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
913 $watch = false, $timestamp = false )
915 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
917 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
923 $wgUser->addWatch( $this->getTitle() );
929 * Record a file upload in the upload log and the image table
931 function recordUpload2(
932 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
934 if ( is_null( $user ) ) {
939 $dbw = $this->repo
->getMasterDB();
943 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
946 if ( $timestamp === false ) {
947 $timestamp = $dbw->timestamp();
950 $props['description'] = $comment;
951 $props['user'] = $user->getId();
952 $props['user_text'] = $user->getName();
953 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
954 $this->setProps( $props );
957 $this->purgeThumbnails();
959 # The file is already on its final location, remove it from the squid cache
960 SquidUpdate
::purge( array( $this->getURL() ) );
962 # Fail now if the file isn't there
963 if ( !$this->fileExists
) {
964 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
970 # Test to see if the row exists using INSERT IGNORE
971 # This avoids race conditions by locking the row until the commit, and also
972 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
973 $dbw->insert( 'image',
975 'img_name' => $this->getName(),
976 'img_size' => $this->size
,
977 'img_width' => intval( $this->width
),
978 'img_height' => intval( $this->height
),
979 'img_bits' => $this->bits
,
980 'img_media_type' => $this->media_type
,
981 'img_major_mime' => $this->major_mime
,
982 'img_minor_mime' => $this->minor_mime
,
983 'img_timestamp' => $timestamp,
984 'img_description' => $comment,
985 'img_user' => $user->getId(),
986 'img_user_text' => $user->getName(),
987 'img_metadata' => $this->metadata
,
988 'img_sha1' => $this->sha1
994 if ( $dbw->affectedRows() == 0 ) {
997 # Collision, this is an update of a file
998 # Insert previous contents into oldimage
999 $dbw->insertSelect( 'oldimage', 'image',
1001 'oi_name' => 'img_name',
1002 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1003 'oi_size' => 'img_size',
1004 'oi_width' => 'img_width',
1005 'oi_height' => 'img_height',
1006 'oi_bits' => 'img_bits',
1007 'oi_timestamp' => 'img_timestamp',
1008 'oi_description' => 'img_description',
1009 'oi_user' => 'img_user',
1010 'oi_user_text' => 'img_user_text',
1011 'oi_metadata' => 'img_metadata',
1012 'oi_media_type' => 'img_media_type',
1013 'oi_major_mime' => 'img_major_mime',
1014 'oi_minor_mime' => 'img_minor_mime',
1015 'oi_sha1' => 'img_sha1'
1016 ), array( 'img_name' => $this->getName() ), __METHOD__
1019 # Update the current image row
1020 $dbw->update( 'image',
1022 'img_size' => $this->size
,
1023 'img_width' => intval( $this->width
),
1024 'img_height' => intval( $this->height
),
1025 'img_bits' => $this->bits
,
1026 'img_media_type' => $this->media_type
,
1027 'img_major_mime' => $this->major_mime
,
1028 'img_minor_mime' => $this->minor_mime
,
1029 'img_timestamp' => $timestamp,
1030 'img_description' => $comment,
1031 'img_user' => $user->getId(),
1032 'img_user_text' => $user->getName(),
1033 'img_metadata' => $this->metadata
,
1034 'img_sha1' => $this->sha1
1035 ), array( /* WHERE */
1036 'img_name' => $this->getName()
1040 # This is a new file
1041 # Update the image count
1042 $dbw->begin( __METHOD__
);
1045 array( 'ss_images = ss_images+1' ),
1049 $dbw->commit( __METHOD__
);
1052 $descTitle = $this->getTitle();
1053 $article = new ImagePage( $descTitle );
1054 $article->setFile( $this );
1057 $log = new LogPage( 'upload' );
1058 $action = $reupload ?
'overwrite' : 'upload';
1059 $log->addEntry( $action, $descTitle, $comment, array(), $user );
1061 if ( $descTitle->exists() ) {
1062 # Create a null revision
1063 $latest = $descTitle->getLatestRevID();
1064 $nullRevision = Revision
::newNullRevision(
1066 $descTitle->getArticleId(),
1067 $log->getRcComment(),
1070 if (!is_null($nullRevision)) {
1071 $nullRevision->insertOn( $dbw );
1073 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
1074 $article->updateRevisionOn( $dbw, $nullRevision );
1076 # Invalidate the cache for the description page
1077 $descTitle->invalidateCache();
1078 $descTitle->purgeSquid();
1080 # New file; create the description page.
1081 # There's already a log entry, so don't make a second RC entry
1082 # Squid and file cache for the description page are purged by doEdit.
1083 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC
);
1086 # Commit the transaction now, in case something goes wrong later
1087 # The most important thing is that files don't get lost, especially archives
1090 # Save to cache and purge the squid
1091 # We shall not saveToCache before the commit since otherwise
1092 # in case of a rollback there is an usable file from memcached
1093 # which in fact doesn't really exist (bug 24978)
1094 $this->saveToCache();
1096 # Hooks, hooks, the magic of hooks...
1097 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1099 # Invalidate cache for all pages using this file
1100 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1101 $update->doUpdate();
1103 # Invalidate cache for all pages that redirects on this page
1104 $redirs = $this->getTitle()->getRedirectsHere();
1106 foreach ( $redirs as $redir ) {
1107 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1108 $update->doUpdate();
1115 * Move or copy a file to its public location. If a file exists at the
1116 * destination, move it to an archive. Returns a FileRepoStatus object with
1117 * the archive name in the "value" member on success.
1119 * The archive name should be passed through to recordUpload for database
1122 * @param $srcPath String: local filesystem path to the source image
1123 * @param $flags Integer: a bitwise combination of:
1124 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1125 * @return FileRepoStatus object. On success, the value member contains the
1126 * archive name, or an empty string if it was a new file.
1128 function publish( $srcPath, $flags = 0 ) {
1129 return $this->publishTo( $srcPath, $this->getRel(), $flags );
1133 * Move or copy a file to a specified location. Returns a FileRepoStatus
1134 * object with the archive name in the "value" member on success.
1136 * The archive name should be passed through to recordUpload for database
1139 * @param $srcPath String: local filesystem path to the source image
1140 * @param $dstRel String: target relative path
1141 * @param $flags Integer: a bitwise combination of:
1142 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1143 * @return FileRepoStatus object. On success, the value member contains the
1144 * archive name, or an empty string if it was a new file.
1146 function publishTo( $srcPath, $dstRel, $flags = 0 ) {
1149 $archiveName = wfTimestamp( TS_MW
) . '!'. $this->getName();
1150 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1151 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1152 $status = $this->repo
->publish( $srcPath, $dstRel, $archiveRel, $flags );
1154 if ( $status->value
== 'new' ) {
1155 $status->value
= '';
1157 $status->value
= $archiveName;
1165 /** getLinksTo inherited */
1166 /** getExifData inherited */
1167 /** isLocal inherited */
1168 /** wasDeleted inherited */
1171 * Move file to the new title
1173 * Move current, old version and all thumbnails
1174 * to the new filename. Old file is deleted.
1176 * Cache purging is done; checks for validity
1177 * and logging are caller's responsibility
1179 * @param $target Title New file name
1180 * @return FileRepoStatus object.
1182 function move( $target ) {
1183 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1186 $batch = new LocalFileMoveBatch( $this, $target );
1187 $batch->addCurrent();
1190 $status = $batch->execute();
1191 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1193 $this->purgeEverything();
1196 if ( $status->isOk() ) {
1197 // Now switch the object
1198 $this->title
= $target;
1199 // Force regeneration of the name and hashpath
1200 unset( $this->name
);
1201 unset( $this->hashPath
);
1202 // Purge the new image
1203 $this->purgeEverything();
1210 * Delete all versions of the file.
1212 * Moves the files into an archive directory (or deletes them)
1213 * and removes the database rows.
1215 * Cache purging is done; logging is caller's responsibility.
1219 * @return FileRepoStatus object.
1221 function delete( $reason, $suppress = false ) {
1224 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1225 $batch->addCurrent();
1227 # Get old version relative paths
1228 $dbw = $this->repo
->getMasterDB();
1229 $result = $dbw->select( 'oldimage',
1230 array( 'oi_archive_name' ),
1231 array( 'oi_name' => $this->getName() ) );
1232 foreach ( $result as $row ) {
1233 $batch->addOld( $row->oi_archive_name
);
1234 $this->purgeOldThumbnails( $row->oi_archive_name
);
1236 $status = $batch->execute();
1238 if ( $status->ok
) {
1239 // Update site_stats
1240 $site_stats = $dbw->tableName( 'site_stats' );
1241 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1242 $this->purgeEverything();
1251 * Delete an old version of the file.
1253 * Moves the file into an archive directory (or deletes it)
1254 * and removes the database row.
1256 * Cache purging is done; logging is caller's responsibility.
1258 * @param $archiveName String
1259 * @param $reason String
1260 * @param $suppress Boolean
1261 * @throws MWException or FSException on database or file store failure
1262 * @return FileRepoStatus object.
1264 function deleteOld( $archiveName, $reason, $suppress = false ) {
1267 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1268 $batch->addOld( $archiveName );
1269 $this->purgeOldThumbnails( $archiveName );
1270 $status = $batch->execute();
1274 if ( $status->ok
) {
1275 $this->purgeDescription();
1276 $this->purgeHistory();
1283 * Restore all or specified deleted revisions to the given file.
1284 * Permissions and logging are left to the caller.
1286 * May throw database exceptions on error.
1288 * @param $versions set of record ids of deleted items to restore,
1289 * or empty to restore all revisions.
1290 * @param $unsuppress Boolean
1291 * @return FileRepoStatus
1293 function restore( $versions = array(), $unsuppress = false ) {
1294 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1299 $batch->addIds( $versions );
1302 $status = $batch->execute();
1304 if ( !$status->isGood() ) {
1308 $cleanupStatus = $batch->cleanup();
1309 $cleanupStatus->successCount
= 0;
1310 $cleanupStatus->failCount
= 0;
1311 $status->merge( $cleanupStatus );
1316 /** isMultipage inherited */
1317 /** pageCount inherited */
1318 /** scaleHeight inherited */
1319 /** getImageSize inherited */
1322 * Get the URL of the file description page.
1324 function getDescriptionUrl() {
1325 return $this->title
->getLocalUrl();
1329 * Get the HTML text of the description page
1330 * This is not used by ImagePage for local files, since (among other things)
1331 * it skips the parser cache.
1333 function getDescriptionText() {
1335 $revision = Revision
::newFromTitle( $this->title
);
1336 if ( !$revision ) return false;
1337 $text = $revision->getText();
1338 if ( !$text ) return false;
1339 $pout = $wgParser->parse( $text, $this->title
, new ParserOptions() );
1340 return $pout->getText();
1343 function getDescription() {
1345 return $this->description
;
1348 function getTimestamp() {
1350 return $this->timestamp
;
1353 function getSha1() {
1355 // Initialise now if necessary
1356 if ( $this->sha1
== '' && $this->fileExists
) {
1357 $this->sha1
= File
::sha1Base36( $this->getPath() );
1358 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1359 $dbw = $this->repo
->getMasterDB();
1360 $dbw->update( 'image',
1361 array( 'img_sha1' => $this->sha1
),
1362 array( 'img_name' => $this->getName() ),
1364 $this->saveToCache();
1372 * Start a transaction and lock the image for update
1373 * Increments a reference counter if the lock is already held
1374 * @return boolean True if the image exists, false otherwise
1377 $dbw = $this->repo
->getMasterDB();
1379 if ( !$this->locked
) {
1384 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__
);
1388 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1389 * the transaction and thereby releases the image lock.
1392 if ( $this->locked
) {
1394 if ( !$this->locked
) {
1395 $dbw = $this->repo
->getMasterDB();
1402 * Roll back the DB transaction and mark the image unlocked
1404 function unlockAndRollback() {
1405 $this->locked
= false;
1406 $dbw = $this->repo
->getMasterDB();
1409 } // LocalFile class
1411 # ------------------------------------------------------------------------------
1414 * Helper class for file deletion
1417 class LocalFileDeleteBatch
{
1424 var $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1427 function __construct( File
$file, $reason = '', $suppress = false ) {
1428 $this->file
= $file;
1429 $this->reason
= $reason;
1430 $this->suppress
= $suppress;
1431 $this->status
= $file->repo
->newGood();
1434 function addCurrent() {
1435 $this->srcRels
['.'] = $this->file
->getRel();
1438 function addOld( $oldName ) {
1439 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
1440 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
1443 function getOldRels() {
1444 if ( !isset( $this->srcRels
['.'] ) ) {
1445 $oldRels =& $this->srcRels
;
1446 $deleteCurrent = false;
1448 $oldRels = $this->srcRels
;
1449 unset( $oldRels['.'] );
1450 $deleteCurrent = true;
1453 return array( $oldRels, $deleteCurrent );
1456 protected function getHashes() {
1458 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1460 if ( $deleteCurrent ) {
1461 $hashes['.'] = $this->file
->getSha1();
1464 if ( count( $oldRels ) ) {
1465 $dbw = $this->file
->repo
->getMasterDB();
1466 $res = $dbw->select(
1468 array( 'oi_archive_name', 'oi_sha1' ),
1469 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1473 foreach ( $res as $row ) {
1474 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
1475 // Get the hash from the file
1476 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
1477 $props = $this->file
->repo
->getFileProps( $oldUrl );
1479 if ( $props['fileExists'] ) {
1480 // Upgrade the oldimage row
1481 $dbw->update( 'oldimage',
1482 array( 'oi_sha1' => $props['sha1'] ),
1483 array( 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
),
1485 $hashes[$row->oi_archive_name
] = $props['sha1'];
1487 $hashes[$row->oi_archive_name
] = false;
1490 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
1495 $missing = array_diff_key( $this->srcRels
, $hashes );
1497 foreach ( $missing as $name => $rel ) {
1498 $this->status
->error( 'filedelete-old-unregistered', $name );
1501 foreach ( $hashes as $name => $hash ) {
1503 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
1504 unset( $hashes[$name] );
1511 function doDBInserts() {
1514 $dbw = $this->file
->repo
->getMasterDB();
1515 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1516 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1517 $encReason = $dbw->addQuotes( $this->reason
);
1518 $encGroup = $dbw->addQuotes( 'deleted' );
1519 $ext = $this->file
->getExtension();
1520 $dotExt = $ext === '' ?
'' : ".$ext";
1521 $encExt = $dbw->addQuotes( $dotExt );
1522 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1524 // Bitfields to further suppress the content
1525 if ( $this->suppress
) {
1527 // This should be 15...
1528 $bitfield |
= Revision
::DELETED_TEXT
;
1529 $bitfield |
= Revision
::DELETED_COMMENT
;
1530 $bitfield |
= Revision
::DELETED_USER
;
1531 $bitfield |
= Revision
::DELETED_RESTRICTED
;
1533 $bitfield = 'oi_deleted';
1536 if ( $deleteCurrent ) {
1537 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1538 $where = array( 'img_name' => $this->file
->getName() );
1539 $dbw->insertSelect( 'filearchive', 'image',
1541 'fa_storage_group' => $encGroup,
1542 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1543 'fa_deleted_user' => $encUserId,
1544 'fa_deleted_timestamp' => $encTimestamp,
1545 'fa_deleted_reason' => $encReason,
1546 'fa_deleted' => $this->suppress ?
$bitfield : 0,
1548 'fa_name' => 'img_name',
1549 'fa_archive_name' => 'NULL',
1550 'fa_size' => 'img_size',
1551 'fa_width' => 'img_width',
1552 'fa_height' => 'img_height',
1553 'fa_metadata' => 'img_metadata',
1554 'fa_bits' => 'img_bits',
1555 'fa_media_type' => 'img_media_type',
1556 'fa_major_mime' => 'img_major_mime',
1557 'fa_minor_mime' => 'img_minor_mime',
1558 'fa_description' => 'img_description',
1559 'fa_user' => 'img_user',
1560 'fa_user_text' => 'img_user_text',
1561 'fa_timestamp' => 'img_timestamp'
1562 ), $where, __METHOD__
);
1565 if ( count( $oldRels ) ) {
1566 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1568 'oi_name' => $this->file
->getName(),
1569 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1570 $dbw->insertSelect( 'filearchive', 'oldimage',
1572 'fa_storage_group' => $encGroup,
1573 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1574 'fa_deleted_user' => $encUserId,
1575 'fa_deleted_timestamp' => $encTimestamp,
1576 'fa_deleted_reason' => $encReason,
1577 'fa_deleted' => $this->suppress ?
$bitfield : 'oi_deleted',
1579 'fa_name' => 'oi_name',
1580 'fa_archive_name' => 'oi_archive_name',
1581 'fa_size' => 'oi_size',
1582 'fa_width' => 'oi_width',
1583 'fa_height' => 'oi_height',
1584 'fa_metadata' => 'oi_metadata',
1585 'fa_bits' => 'oi_bits',
1586 'fa_media_type' => 'oi_media_type',
1587 'fa_major_mime' => 'oi_major_mime',
1588 'fa_minor_mime' => 'oi_minor_mime',
1589 'fa_description' => 'oi_description',
1590 'fa_user' => 'oi_user',
1591 'fa_user_text' => 'oi_user_text',
1592 'fa_timestamp' => 'oi_timestamp',
1593 'fa_deleted' => $bitfield
1594 ), $where, __METHOD__
);
1598 function doDBDeletes() {
1599 $dbw = $this->file
->repo
->getMasterDB();
1600 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1602 if ( count( $oldRels ) ) {
1603 $dbw->delete( 'oldimage',
1605 'oi_name' => $this->file
->getName(),
1606 'oi_archive_name' => array_keys( $oldRels )
1610 if ( $deleteCurrent ) {
1611 $dbw->delete( 'image', array( 'img_name' => $this->file
->getName() ), __METHOD__
);
1616 * Run the transaction
1618 function execute() {
1620 wfProfileIn( __METHOD__
);
1622 $this->file
->lock();
1623 // Leave private files alone
1624 $privateFiles = array();
1625 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1626 $dbw = $this->file
->repo
->getMasterDB();
1628 if ( !empty( $oldRels ) ) {
1629 $res = $dbw->select( 'oldimage',
1630 array( 'oi_archive_name' ),
1631 array( 'oi_name' => $this->file
->getName(),
1632 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1633 $dbw->bitAnd( 'oi_deleted', File
::DELETED_FILE
) => File
::DELETED_FILE
),
1636 foreach ( $res as $row ) {
1637 $privateFiles[$row->oi_archive_name
] = 1;
1640 // Prepare deletion batch
1641 $hashes = $this->getHashes();
1642 $this->deletionBatch
= array();
1643 $ext = $this->file
->getExtension();
1644 $dotExt = $ext === '' ?
'' : ".$ext";
1646 foreach ( $this->srcRels
as $name => $srcRel ) {
1647 // Skip files that have no hash (missing source).
1648 // Keep private files where they are.
1649 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1650 $hash = $hashes[$name];
1651 $key = $hash . $dotExt;
1652 $dstRel = $this->file
->repo
->getDeletedHashPath( $key ) . $key;
1653 $this->deletionBatch
[$name] = array( $srcRel, $dstRel );
1657 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1658 // We acquire this lock by running the inserts now, before the file operations.
1660 // This potentially has poor lock contention characteristics -- an alternative
1661 // scheme would be to insert stub filearchive entries with no fa_name and commit
1662 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1663 $this->doDBInserts();
1665 // Removes non-existent file from the batch, so we don't get errors.
1666 $this->deletionBatch
= $this->removeNonexistentFiles( $this->deletionBatch
);
1668 // Execute the file deletion batch
1669 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
1671 if ( !$status->isGood() ) {
1672 $this->status
->merge( $status );
1675 if ( !$this->status
->ok
) {
1676 // Critical file deletion error
1677 // Roll back inserts, release lock and abort
1678 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1679 $this->file
->unlockAndRollback();
1680 wfProfileOut( __METHOD__
);
1681 return $this->status
;
1685 if ( $wgUseSquid ) {
1688 foreach ( $this->srcRels
as $srcRel ) {
1689 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1690 $urls[] = $this->file
->repo
->getZoneUrl( 'public' ) . '/' . $urlRel;
1692 SquidUpdate
::purge( $urls );
1695 // Delete image/oldimage rows
1696 $this->doDBDeletes();
1698 // Commit and return
1699 $this->file
->unlock();
1700 wfProfileOut( __METHOD__
);
1702 return $this->status
;
1706 * Removes non-existent files from a deletion batch.
1708 function removeNonexistentFiles( $batch ) {
1709 $files = $newBatch = array();
1711 foreach ( $batch as $batchItem ) {
1712 list( $src, $dest ) = $batchItem;
1713 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1716 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
1718 foreach ( $batch as $batchItem ) {
1719 if ( $result[$batchItem[0]] ) {
1720 $newBatch[] = $batchItem;
1728 # ------------------------------------------------------------------------------
1731 * Helper class for file undeletion
1734 class LocalFileRestoreBatch
{
1740 var $cleanupBatch, $ids, $all, $unsuppress = false;
1742 function __construct( File
$file, $unsuppress = false ) {
1743 $this->file
= $file;
1744 $this->cleanupBatch
= $this->ids
= array();
1745 $this->ids
= array();
1746 $this->unsuppress
= $unsuppress;
1752 function addId( $fa_id ) {
1753 $this->ids
[] = $fa_id;
1757 * Add a whole lot of files by ID
1759 function addIds( $ids ) {
1760 $this->ids
= array_merge( $this->ids
, $ids );
1764 * Add all revisions of the file
1771 * Run the transaction, except the cleanup batch.
1772 * The cleanup batch should be run in a separate transaction, because it locks different
1773 * rows and there's no need to keep the image row locked while it's acquiring those locks
1774 * The caller may have its own transaction open.
1775 * So we save the batch and let the caller call cleanup()
1777 function execute() {
1780 if ( !$this->all
&& !$this->ids
) {
1782 return $this->file
->repo
->newGood();
1785 $exists = $this->file
->lock();
1786 $dbw = $this->file
->repo
->getMasterDB();
1787 $status = $this->file
->repo
->newGood();
1789 // Fetch all or selected archived revisions for the file,
1790 // sorted from the most recent to the oldest.
1791 $conditions = array( 'fa_name' => $this->file
->getName() );
1793 if ( !$this->all
) {
1794 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids
) . ')';
1797 $result = $dbw->select( 'filearchive', '*',
1800 array( 'ORDER BY' => 'fa_timestamp DESC' )
1803 $idsPresent = array();
1804 $storeBatch = array();
1805 $insertBatch = array();
1806 $insertCurrent = false;
1807 $deleteIds = array();
1809 $archiveNames = array();
1811 foreach ( $result as $row ) {
1812 $idsPresent[] = $row->fa_id
;
1814 if ( $row->fa_name
!= $this->file
->getName() ) {
1815 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
1816 $status->failCount++
;
1820 if ( $row->fa_storage_key
== '' ) {
1821 // Revision was missing pre-deletion
1822 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
1823 $status->failCount++
;
1827 $deletedRel = $this->file
->repo
->getDeletedHashPath( $row->fa_storage_key
) . $row->fa_storage_key
;
1828 $deletedUrl = $this->file
->repo
->getVirtualUrl() . '/deleted/' . $deletedRel;
1830 $sha1 = substr( $row->fa_storage_key
, 0, strcspn( $row->fa_storage_key
, '.' ) );
1833 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1834 $sha1 = substr( $sha1, 1 );
1837 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
1838 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
1839 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
1840 ||
is_null( $row->fa_metadata
) ) {
1841 // Refresh our metadata
1842 // Required for a new current revision; nice for older ones too. :)
1843 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
1846 'minor_mime' => $row->fa_minor_mime
,
1847 'major_mime' => $row->fa_major_mime
,
1848 'media_type' => $row->fa_media_type
,
1849 'metadata' => $row->fa_metadata
1853 if ( $first && !$exists ) {
1854 // This revision will be published as the new current version
1855 $destRel = $this->file
->getRel();
1856 $insertCurrent = array(
1857 'img_name' => $row->fa_name
,
1858 'img_size' => $row->fa_size
,
1859 'img_width' => $row->fa_width
,
1860 'img_height' => $row->fa_height
,
1861 'img_metadata' => $props['metadata'],
1862 'img_bits' => $row->fa_bits
,
1863 'img_media_type' => $props['media_type'],
1864 'img_major_mime' => $props['major_mime'],
1865 'img_minor_mime' => $props['minor_mime'],
1866 'img_description' => $row->fa_description
,
1867 'img_user' => $row->fa_user
,
1868 'img_user_text' => $row->fa_user_text
,
1869 'img_timestamp' => $row->fa_timestamp
,
1873 // The live (current) version cannot be hidden!
1874 if ( !$this->unsuppress
&& $row->fa_deleted
) {
1875 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1876 $this->cleanupBatch
[] = $row->fa_storage_key
;
1879 $archiveName = $row->fa_archive_name
;
1881 if ( $archiveName == '' ) {
1882 // This was originally a current version; we
1883 // have to devise a new archive name for it.
1884 // Format is <timestamp of archiving>!<name>
1885 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
1888 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
1890 } while ( isset( $archiveNames[$archiveName] ) );
1893 $archiveNames[$archiveName] = true;
1894 $destRel = $this->file
->getArchiveRel( $archiveName );
1895 $insertBatch[] = array(
1896 'oi_name' => $row->fa_name
,
1897 'oi_archive_name' => $archiveName,
1898 'oi_size' => $row->fa_size
,
1899 'oi_width' => $row->fa_width
,
1900 'oi_height' => $row->fa_height
,
1901 'oi_bits' => $row->fa_bits
,
1902 'oi_description' => $row->fa_description
,
1903 'oi_user' => $row->fa_user
,
1904 'oi_user_text' => $row->fa_user_text
,
1905 'oi_timestamp' => $row->fa_timestamp
,
1906 'oi_metadata' => $props['metadata'],
1907 'oi_media_type' => $props['media_type'],
1908 'oi_major_mime' => $props['major_mime'],
1909 'oi_minor_mime' => $props['minor_mime'],
1910 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
1911 'oi_sha1' => $sha1 );
1914 $deleteIds[] = $row->fa_id
;
1916 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
1917 // private files can stay where they are
1918 $status->successCount++
;
1920 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1921 $this->cleanupBatch
[] = $row->fa_storage_key
;
1929 // Add a warning to the status object for missing IDs
1930 $missingIds = array_diff( $this->ids
, $idsPresent );
1932 foreach ( $missingIds as $id ) {
1933 $status->error( 'undelete-missing-filearchive', $id );
1936 // Remove missing files from batch, so we don't get errors when undeleting them
1937 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1939 // Run the store batch
1940 // Use the OVERWRITE_SAME flag to smooth over a common error
1941 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
1942 $status->merge( $storeStatus );
1944 if ( !$status->isGood() ) {
1945 // Even if some files could be copied, fail entirely as that is the
1946 // easiest thing to do without data loss
1947 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
1948 $status->ok
= false;
1949 $this->file
->unlock();
1954 // Run the DB updates
1955 // Because we have locked the image row, key conflicts should be rare.
1956 // If they do occur, we can roll back the transaction at this time with
1957 // no data loss, but leaving unregistered files scattered throughout the
1959 // This is not ideal, which is why it's important to lock the image row.
1960 if ( $insertCurrent ) {
1961 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
1964 if ( $insertBatch ) {
1965 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
1969 $dbw->delete( 'filearchive',
1970 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1974 // If store batch is empty (all files are missing), deletion is to be considered successful
1975 if ( $status->successCount
> 0 ||
!$storeBatch ) {
1977 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
1979 // Update site_stats
1980 $site_stats = $dbw->tableName( 'site_stats' );
1981 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1983 $this->file
->purgeEverything();
1985 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
1986 $this->file
->purgeDescription();
1987 $this->file
->purgeHistory();
1991 $this->file
->unlock();
1997 * Removes non-existent files from a store batch.
1999 function removeNonexistentFiles( $triplets ) {
2000 $files = $filteredTriplets = array();
2001 foreach ( $triplets as $file )
2002 $files[$file[0]] = $file[0];
2004 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2006 foreach ( $triplets as $file ) {
2007 if ( $result[$file[0]] ) {
2008 $filteredTriplets[] = $file;
2012 return $filteredTriplets;
2016 * Removes non-existent files from a cleanup batch.
2018 function removeNonexistentFromCleanup( $batch ) {
2019 $files = $newBatch = array();
2020 $repo = $this->file
->repo
;
2022 foreach ( $batch as $file ) {
2023 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2024 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2027 $result = $repo->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2029 foreach ( $batch as $file ) {
2030 if ( $result[$file] ) {
2031 $newBatch[] = $file;
2039 * Delete unused files in the deleted zone.
2040 * This should be called from outside the transaction in which execute() was called.
2042 function cleanup() {
2043 if ( !$this->cleanupBatch
) {
2044 return $this->file
->repo
->newGood();
2047 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2049 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2055 * Cleanup a failed batch. The batch was only partially successful, so
2056 * rollback by removing all items that were succesfully copied.
2058 * @param Status $storeStatus
2059 * @param array $storeBatch
2061 function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2062 $cleanupBatch = array();
2064 foreach ( $storeStatus->success
as $i => $success ) {
2065 // Check if this item of the batch was successfully copied
2067 // Item was successfully copied and needs to be removed again
2068 // Extract ($dstZone, $dstRel) from the batch
2069 $cleanupBatch[] = array( $storeBatch[$i][1], $storeBatch[$i][2] );
2072 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2076 # ------------------------------------------------------------------------------
2079 * Helper class for file movement
2082 class LocalFileMoveBatch
{
2094 var $cur, $olds, $oldCount, $archive, $db;
2096 function __construct( File
$file, Title
$target ) {
2097 $this->file
= $file;
2098 $this->target
= $target;
2099 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2100 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2101 $this->oldName
= $this->file
->getName();
2102 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2103 $this->oldRel
= $this->oldHash
. $this->oldName
;
2104 $this->newRel
= $this->newHash
. $this->newName
;
2105 $this->db
= $file->repo
->getMasterDb();
2109 * Add the current image to the batch
2111 function addCurrent() {
2112 $this->cur
= array( $this->oldRel
, $this->newRel
);
2116 * Add the old versions of the image to the batch
2118 function addOlds() {
2119 $archiveBase = 'archive';
2120 $this->olds
= array();
2121 $this->oldCount
= 0;
2123 $result = $this->db
->select( 'oldimage',
2124 array( 'oi_archive_name', 'oi_deleted' ),
2125 array( 'oi_name' => $this->oldName
),
2129 foreach ( $result as $row ) {
2130 $oldName = $row->oi_archive_name
;
2131 $bits = explode( '!', $oldName, 2 );
2133 if ( count( $bits ) != 2 ) {
2134 wfDebug( "Old file name missing !: '$oldName' \n" );
2138 list( $timestamp, $filename ) = $bits;
2140 if ( $this->oldName
!= $filename ) {
2141 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2147 // Do we want to add those to oldCount?
2148 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2152 $this->olds
[] = array(
2153 "{$archiveBase}/{$this->oldHash}{$oldName}",
2154 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2162 function execute() {
2163 $repo = $this->file
->repo
;
2164 $status = $repo->newGood();
2165 $triplets = $this->getMoveTriplets();
2167 $triplets = $this->removeNonexistentFiles( $triplets );
2169 // Copy the files into their new location
2170 $statusMove = $repo->storeBatch( $triplets );
2171 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2172 if ( !$statusMove->isGood() ) {
2173 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2174 $this->cleanupTarget( $triplets );
2175 $statusMove->ok
= false;
2180 $statusDb = $this->doDBUpdates();
2181 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2182 if ( !$statusDb->isGood() ) {
2183 $this->db
->rollback();
2184 // Something went wrong with the DB updates, so remove the target files
2185 $this->cleanupTarget( $triplets );
2186 $statusDb->ok
= false;
2189 $this->db
->commit();
2191 // Everything went ok, remove the source files
2192 $this->cleanupSource( $triplets );
2194 $status->merge( $statusDb );
2195 $status->merge( $statusMove );
2201 * Do the database updates and return a new FileRepoStatus indicating how
2202 * many rows where updated.
2204 * @return FileRepoStatus
2206 function doDBUpdates() {
2207 $repo = $this->file
->repo
;
2208 $status = $repo->newGood();
2211 // Update current image
2214 array( 'img_name' => $this->newName
),
2215 array( 'img_name' => $this->oldName
),
2219 if ( $dbw->affectedRows() ) {
2220 $status->successCount++
;
2222 $status->failCount++
;
2223 $status->fatal( 'imageinvalidfilename' );
2227 // Update old images
2231 'oi_name' => $this->newName
,
2232 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
2234 array( 'oi_name' => $this->oldName
),
2238 $affected = $dbw->affectedRows();
2239 $total = $this->oldCount
;
2240 $status->successCount +
= $affected;
2241 $status->failCount +
= $total - $affected;
2242 if ( $status->failCount
) {
2243 $status->error( 'imageinvalidfilename' );
2250 * Generate triplets for FSRepo::storeBatch().
2252 function getMoveTriplets() {
2253 $moves = array_merge( array( $this->cur
), $this->olds
);
2254 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2256 foreach ( $moves as $move ) {
2257 // $move: (oldRelativePath, newRelativePath)
2258 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2259 $triplets[] = array( $srcUrl, 'public', $move[1] );
2260 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}" );
2267 * Removes non-existent files from move batch.
2269 function removeNonexistentFiles( $triplets ) {
2272 foreach ( $triplets as $file ) {
2273 $files[$file[0]] = $file[0];
2276 $result = $this->file
->repo
->fileExistsBatch( $files, FSRepo
::FILES_ONLY
);
2277 $filteredTriplets = array();
2279 foreach ( $triplets as $file ) {
2280 if ( $result[$file[0]] ) {
2281 $filteredTriplets[] = $file;
2283 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2287 return $filteredTriplets;
2291 * Cleanup a partially moved array of triplets by deleting the target
2292 * files. Called if something went wrong half way.
2294 function cleanupTarget( $triplets ) {
2295 // Create dest pairs from the triplets
2297 foreach ( $triplets as $triplet ) {
2298 $pairs[] = array( $triplet[1], $triplet[2] );
2301 $this->file
->repo
->cleanupBatch( $pairs );
2305 * Cleanup a fully moved array of triplets by deleting the source files.
2306 * Called at the end of the move process if everything else went ok.
2308 function cleanupSource( $triplets ) {
2309 // Create source file names from the triplets
2311 foreach ( $triplets as $triplet ) {
2312 $files[] = $triplet[0];
2315 $this->file
->repo
->cleanupBatch( $files );