Localisation updates for core and extension messages from translatewiki.net (2010...
[mediawiki.git] / includes / filerepo / LocalFile.php
blob29c6b7adbf04102501cdace4799e5d5adf3db64e
1 <?php
2 /**
3 */
5 /**
6 * Bump this number when serialized cache records may be incompatible.
7 */
8 define( 'MW_FILE_VERSION', 8 );
10 /**
11 * Class to represent a local file in the wiki's own database
13 * Provides methods to retrieve paths (physical, logical, URL),
14 * to generate image thumbnails or for uploading.
16 * Note that only the repo object knows what its file class is called. You should
17 * never name a file class explictly outside of the repo class. Instead use the
18 * repo's factory functions to generate file objects, for example:
20 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
22 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
23 * in most cases.
25 * @ingroup FileRepo
27 class LocalFile extends File {
28 /**#@+
29 * @private
31 var $fileExists, # does the file file exist on disk? (loadFromXxx)
32 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
33 $historyRes, # result of the query for the file's history (nextHistoryLine)
34 $width, # \
35 $height, # |
36 $bits, # --- returned by getimagesize (loadFromXxx)
37 $attr, # /
38 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
39 $mime, # MIME type, determined by MimeMagic::guessMimeType
40 $major_mime, # Major mime type
41 $minor_mime, # Minor mime type
42 $size, # Size in bytes (loadFromXxx)
43 $metadata, # Handler-specific metadata
44 $timestamp, # Upload timestamp
45 $sha1, # SHA-1 base 36 content hash
46 $user, $user_text, # User, who uploaded the file
47 $description, # Description of current revision of the file
48 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
49 $upgraded, # Whether the row was upgraded on load
50 $locked, # True if the image row is locked
51 $missing, # True if file is not present in file system. Not to be cached in memcached
52 $deleted; # Bitfield akin to rev_deleted
54 /**#@-*/
56 /**
57 * Create a LocalFile from a title
58 * Do not call this except from inside a repo class.
60 * Note: $unused param is only here to avoid an E_STRICT
62 static function newFromTitle( $title, $repo, $unused = null ) {
63 return new self( $title, $repo );
66 /**
67 * Create a LocalFile from a title
68 * Do not call this except from inside a repo class.
70 static function newFromRow( $row, $repo ) {
71 $title = Title::makeTitle( NS_FILE, $row->img_name );
72 $file = new self( $title, $repo );
73 $file->loadFromRow( $row );
74 return $file;
77 /**
78 * Create a LocalFile from a SHA-1 key
79 * Do not call this except from inside a repo class.
81 static function newFromKey( $sha1, $repo, $timestamp = false ) {
82 # Polymorphic function name to distinguish foreign and local fetches
83 $fname = get_class( $this ) . '::' . __FUNCTION__;
85 $conds = array( 'img_sha1' => $sha1 );
86 if( $timestamp ) {
87 $conds['img_timestamp'] = $timestamp;
89 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ), $conds, $fname );
90 if( $row ) {
91 return self::newFromRow( $row, $repo );
92 } else {
93 return false;
97 /**
98 * Fields in the image table
100 static function selectFields() {
101 return array(
102 'img_name',
103 'img_size',
104 'img_width',
105 'img_height',
106 'img_metadata',
107 'img_bits',
108 'img_media_type',
109 'img_major_mime',
110 'img_minor_mime',
111 'img_description',
112 'img_user',
113 'img_user_text',
114 'img_timestamp',
115 'img_sha1',
120 * Constructor.
121 * Do not call this except from inside a repo class.
123 function __construct( $title, $repo ) {
124 if( !is_object( $title ) ) {
125 throw new MWException( __CLASS__ . ' constructor given bogus title.' );
127 parent::__construct( $title, $repo );
128 $this->metadata = '';
129 $this->historyLine = 0;
130 $this->historyRes = null;
131 $this->dataLoaded = false;
135 * Get the memcached key for the main data for this file, or false if
136 * there is no access to the shared cache.
138 function getCacheKey() {
139 $hashedName = md5( $this->getName() );
140 return $this->repo->getSharedCacheKey( 'file', $hashedName );
144 * Try to load file metadata from memcached. Returns true on success.
146 function loadFromCache() {
147 global $wgMemc;
148 wfProfileIn( __METHOD__ );
149 $this->dataLoaded = false;
150 $key = $this->getCacheKey();
151 if ( !$key ) {
152 wfProfileOut( __METHOD__ );
153 return false;
155 $cachedValues = $wgMemc->get( $key );
157 // Check if the key existed and belongs to this version of MediaWiki
158 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
159 wfDebug( "Pulling file metadata from cache key $key\n" );
160 $this->fileExists = $cachedValues['fileExists'];
161 if ( $this->fileExists ) {
162 $this->setProps( $cachedValues );
164 $this->dataLoaded = true;
166 if ( $this->dataLoaded ) {
167 wfIncrStats( 'image_cache_hit' );
168 } else {
169 wfIncrStats( 'image_cache_miss' );
172 wfProfileOut( __METHOD__ );
173 return $this->dataLoaded;
177 * Save the file metadata to memcached
179 function saveToCache() {
180 global $wgMemc;
181 $this->load();
182 $key = $this->getCacheKey();
183 if ( !$key ) {
184 return;
186 $fields = $this->getCacheFields( '' );
187 $cache = array( 'version' => MW_FILE_VERSION );
188 $cache['fileExists'] = $this->fileExists;
189 if ( $this->fileExists ) {
190 foreach ( $fields as $field ) {
191 $cache[$field] = $this->$field;
195 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
199 * Load metadata from the file itself
201 function loadFromFile() {
202 $this->setProps( self::getPropsFromPath( $this->getPath() ) );
205 function getCacheFields( $prefix = 'img_' ) {
206 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
207 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
208 static $results = array();
209 if ( $prefix == '' ) {
210 return $fields;
212 if ( !isset( $results[$prefix] ) ) {
213 $prefixedFields = array();
214 foreach ( $fields as $field ) {
215 $prefixedFields[] = $prefix . $field;
217 $results[$prefix] = $prefixedFields;
219 return $results[$prefix];
223 * Load file metadata from the DB
225 function loadFromDB() {
226 # Polymorphic function name to distinguish foreign and local fetches
227 $fname = get_class( $this ) . '::' . __FUNCTION__;
228 wfProfileIn( $fname );
230 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
231 $this->dataLoaded = true;
233 $dbr = $this->repo->getMasterDB();
235 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
236 array( 'img_name' => $this->getName() ), $fname );
237 if ( $row ) {
238 $this->loadFromRow( $row );
239 } else {
240 $this->fileExists = false;
243 wfProfileOut( $fname );
247 * Decode a row from the database (either object or array) to an array
248 * with timestamps and MIME types decoded, and the field prefix removed.
250 function decodeRow( $row, $prefix = 'img_' ) {
251 $array = (array)$row;
252 $prefixLength = strlen( $prefix );
253 // Sanity check prefix once
254 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
255 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
257 $decoded = array();
258 foreach ( $array as $name => $value ) {
259 $decoded[substr( $name, $prefixLength )] = $value;
261 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
262 if ( empty( $decoded['major_mime'] ) ) {
263 $decoded['mime'] = 'unknown/unknown';
264 } else {
265 if ( !$decoded['minor_mime'] ) {
266 $decoded['minor_mime'] = 'unknown';
268 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
270 # Trim zero padding from char/binary field
271 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
272 return $decoded;
276 * Load file metadata from a DB result row
278 function loadFromRow( $row, $prefix = 'img_' ) {
279 $this->dataLoaded = true;
280 $array = $this->decodeRow( $row, $prefix );
281 foreach ( $array as $name => $value ) {
282 $this->$name = $value;
284 $this->fileExists = true;
285 $this->maybeUpgradeRow();
289 * Load file metadata from cache or DB, unless already loaded
291 function load() {
292 if ( !$this->dataLoaded ) {
293 if ( !$this->loadFromCache() ) {
294 $this->loadFromDB();
295 $this->saveToCache();
297 $this->dataLoaded = true;
302 * Upgrade a row if it needs it
304 function maybeUpgradeRow() {
305 if ( wfReadOnly() ) {
306 return;
308 if ( is_null( $this->media_type ) ||
309 $this->mime == 'image/svg'
311 $this->upgradeRow();
312 $this->upgraded = true;
313 } else {
314 $handler = $this->getHandler();
315 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata ) ) {
316 $this->upgradeRow();
317 $this->upgraded = true;
322 function getUpgraded() {
323 return $this->upgraded;
327 * Fix assorted version-related problems with the image row by reloading it from the file
329 function upgradeRow() {
330 wfProfileIn( __METHOD__ );
332 $this->loadFromFile();
334 # Don't destroy file info of missing files
335 if ( !$this->fileExists ) {
336 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
337 wfProfileOut( __METHOD__ );
338 return;
340 $dbw = $this->repo->getMasterDB();
341 list( $major, $minor ) = self::splitMime( $this->mime );
343 if ( wfReadOnly() ) {
344 wfProfileOut( __METHOD__ );
345 return;
347 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
349 $dbw->update( 'image',
350 array(
351 'img_width' => $this->width,
352 'img_height' => $this->height,
353 'img_bits' => $this->bits,
354 'img_media_type' => $this->media_type,
355 'img_major_mime' => $major,
356 'img_minor_mime' => $minor,
357 'img_metadata' => $this->metadata,
358 'img_sha1' => $this->sha1,
359 ), array( 'img_name' => $this->getName() ),
360 __METHOD__
362 $this->saveToCache();
363 wfProfileOut( __METHOD__ );
367 * Set properties in this object to be equal to those given in the
368 * associative array $info. Only cacheable fields can be set.
370 * If 'mime' is given, it will be split into major_mime/minor_mime.
371 * If major_mime/minor_mime are given, $this->mime will also be set.
373 function setProps( $info ) {
374 $this->dataLoaded = true;
375 $fields = $this->getCacheFields( '' );
376 $fields[] = 'fileExists';
377 foreach ( $fields as $field ) {
378 if ( isset( $info[$field] ) ) {
379 $this->$field = $info[$field];
382 // Fix up mime fields
383 if ( isset( $info['major_mime'] ) ) {
384 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
385 } elseif ( isset( $info['mime'] ) ) {
386 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
390 /** splitMime inherited */
391 /** getName inherited */
392 /** getTitle inherited */
393 /** getURL inherited */
394 /** getViewURL inherited */
395 /** getPath inherited */
396 /** isVisible inhereted */
398 function isMissing() {
399 if( $this->missing === null ) {
400 list( $fileExists ) = $this->repo->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo::FILES_ONLY );
401 $this->missing = !$fileExists;
403 return $this->missing;
407 * Return the width of the image
409 * Returns false on error
411 public function getWidth( $page = 1 ) {
412 $this->load();
413 if ( $this->isMultipage() ) {
414 $dim = $this->getHandler()->getPageDimensions( $this, $page );
415 if ( $dim ) {
416 return $dim['width'];
417 } else {
418 return false;
420 } else {
421 return $this->width;
426 * Return the height of the image
428 * Returns false on error
430 public function getHeight( $page = 1 ) {
431 $this->load();
432 if ( $this->isMultipage() ) {
433 $dim = $this->getHandler()->getPageDimensions( $this, $page );
434 if ( $dim ) {
435 return $dim['height'];
436 } else {
437 return false;
439 } else {
440 return $this->height;
445 * Returns ID or name of user who uploaded the file
447 * @param $type string 'text' or 'id'
449 function getUser( $type = 'text' ) {
450 $this->load();
451 if( $type == 'text' ) {
452 return $this->user_text;
453 } elseif( $type == 'id' ) {
454 return $this->user;
459 * Get handler-specific metadata
461 function getMetadata() {
462 $this->load();
463 return $this->metadata;
466 function getBitDepth() {
467 $this->load();
468 return $this->bits;
472 * Return the size of the image file, in bytes
474 public function getSize() {
475 $this->load();
476 return $this->size;
480 * Returns the mime type of the file.
482 function getMimeType() {
483 $this->load();
484 return $this->mime;
488 * Return the type of the media in the file.
489 * Use the value returned by this function with the MEDIATYPE_xxx constants.
491 function getMediaType() {
492 $this->load();
493 return $this->media_type;
496 /** canRender inherited */
497 /** mustRender inherited */
498 /** allowInlineDisplay inherited */
499 /** isSafeFile inherited */
500 /** isTrustedFile inherited */
503 * Returns true if the file file exists on disk.
504 * @return boolean Whether file file exist on disk.
506 public function exists() {
507 $this->load();
508 return $this->fileExists;
511 /** getTransformScript inherited */
512 /** getUnscaledThumb inherited */
513 /** thumbName inherited */
514 /** createThumb inherited */
515 /** getThumbnail inherited */
516 /** transform inherited */
519 * Fix thumbnail files from 1.4 or before, with extreme prejudice
521 function migrateThumbFile( $thumbName ) {
522 $thumbDir = $this->getThumbPath();
523 $thumbPath = "$thumbDir/$thumbName";
524 if ( is_dir( $thumbPath ) ) {
525 // Directory where file should be
526 // This happened occasionally due to broken migration code in 1.5
527 // Rename to broken-*
528 for ( $i = 0; $i < 100 ; $i++ ) {
529 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
530 if ( !file_exists( $broken ) ) {
531 rename( $thumbPath, $broken );
532 break;
535 // Doesn't exist anymore
536 clearstatcache();
538 if ( is_file( $thumbDir ) ) {
539 // File where directory should be
540 unlink( $thumbDir );
541 // Doesn't exist anymore
542 clearstatcache();
546 /** getHandler inherited */
547 /** iconThumb inherited */
548 /** getLastError inherited */
551 * Get all thumbnail names previously generated for this file
553 function getThumbnails() {
554 $this->load();
555 $files = array();
556 $dir = $this->getThumbPath();
558 if ( is_dir( $dir ) ) {
559 $handle = opendir( $dir );
561 if ( $handle ) {
562 while ( false !== ( $file = readdir( $handle ) ) ) {
563 if ( $file{0} != '.' ) {
564 $files[] = $file;
567 closedir( $handle );
571 return $files;
575 * Refresh metadata in memcached, but don't touch thumbnails or squid
577 function purgeMetadataCache() {
578 $this->loadFromDB();
579 $this->saveToCache();
580 $this->purgeHistory();
584 * Purge the shared history (OldLocalFile) cache
586 function purgeHistory() {
587 global $wgMemc;
588 $hashedName = md5( $this->getName() );
589 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
590 if ( $oldKey ) {
591 $wgMemc->delete( $oldKey );
596 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
598 function purgeCache() {
599 // Refresh metadata cache
600 $this->purgeMetadataCache();
602 // Delete thumbnails
603 $this->purgeThumbnails();
605 // Purge squid cache for this file
606 SquidUpdate::purge( array( $this->getURL() ) );
610 * Delete cached transformed files
612 function purgeThumbnails() {
613 global $wgUseSquid;
614 // Delete thumbnails
615 $files = $this->getThumbnails();
616 $dir = $this->getThumbPath();
617 $urls = array();
618 foreach ( $files as $file ) {
619 # Check that the base file name is part of the thumb name
620 # This is a basic sanity check to avoid erasing unrelated directories
621 if ( strpos( $file, $this->getName() ) !== false ) {
622 $url = $this->getThumbUrl( $file );
623 $urls[] = $url;
624 @unlink( "$dir/$file" );
628 // Purge the squid
629 if ( $wgUseSquid ) {
630 SquidUpdate::purge( $urls );
634 /** purgeDescription inherited */
635 /** purgeEverything inherited */
637 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
638 $dbr = $this->repo->getSlaveDB();
639 $tables = array( 'oldimage' );
640 $fields = OldLocalFile::selectFields();
641 $conds = $opts = $join_conds = array();
642 $eq = $inc ? '=' : '';
643 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
644 if( $start ) {
645 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
647 if( $end ) {
648 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
650 if( $limit ) {
651 $opts['LIMIT'] = $limit;
653 // Search backwards for time > x queries
654 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
655 $opts['ORDER BY'] = "oi_timestamp $order";
656 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
658 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
659 &$conds, &$opts, &$join_conds ) );
661 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
662 $r = array();
663 while( $row = $dbr->fetchObject( $res ) ) {
664 $r[] = OldLocalFile::newFromRow( $row, $this->repo );
666 if( $order == 'ASC' ) {
667 $r = array_reverse( $r ); // make sure it ends up descending
669 return $r;
673 * Return the history of this file, line by line.
674 * starts with current version, then old versions.
675 * uses $this->historyLine to check which line to return:
676 * 0 return line for current version
677 * 1 query for old versions, return first one
678 * 2, ... return next old version from above query
680 public function nextHistoryLine() {
681 # Polymorphic function name to distinguish foreign and local fetches
682 $fname = get_class( $this ) . '::' . __FUNCTION__;
684 $dbr = $this->repo->getSlaveDB();
686 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
687 $this->historyRes = $dbr->select( 'image',
688 array(
689 '*',
690 "'' AS oi_archive_name",
691 '0 as oi_deleted',
692 'img_sha1'
694 array( 'img_name' => $this->title->getDBkey() ),
695 $fname
697 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
698 $dbr->freeResult( $this->historyRes );
699 $this->historyRes = null;
700 return false;
702 } elseif ( $this->historyLine == 1 ) {
703 $dbr->freeResult( $this->historyRes );
704 $this->historyRes = $dbr->select( 'oldimage', '*',
705 array( 'oi_name' => $this->title->getDBkey() ),
706 $fname,
707 array( 'ORDER BY' => 'oi_timestamp DESC' )
710 $this->historyLine ++;
712 return $dbr->fetchObject( $this->historyRes );
716 * Reset the history pointer to the first element of the history
718 public function resetHistory() {
719 $this->historyLine = 0;
720 if ( !is_null( $this->historyRes ) ) {
721 $this->repo->getSlaveDB()->freeResult( $this->historyRes );
722 $this->historyRes = null;
726 /** getFullPath inherited */
727 /** getHashPath inherited */
728 /** getRel inherited */
729 /** getUrlRel inherited */
730 /** getArchiveRel inherited */
731 /** getThumbRel inherited */
732 /** getArchivePath inherited */
733 /** getThumbPath inherited */
734 /** getArchiveUrl inherited */
735 /** getThumbUrl inherited */
736 /** getArchiveVirtualUrl inherited */
737 /** getThumbVirtualUrl inherited */
738 /** isHashed inherited */
741 * Upload a file and record it in the DB
742 * @param $srcPath String: source path or virtual URL
743 * @param $comment String: upload description
744 * @param $pageText String: text to use for the new description page,
745 * if a new description page is created
746 * @param $flags Integer: flags for publish()
747 * @param $props Array: File properties, if known. This can be used to reduce the
748 * upload time when uploading virtual URLs for which the file info
749 * is already known
750 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
751 * @param $user Mixed: User object or null to use $wgUser
753 * @return FileRepoStatus object. On success, the value member contains the
754 * archive name, or an empty string if it was a new file.
756 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
757 $this->lock();
758 $status = $this->publish( $srcPath, $flags );
759 if ( $status->ok ) {
760 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
761 $status->fatal( 'filenotfound', $srcPath );
764 $this->unlock();
765 return $status;
769 * Record a file upload in the upload log and the image table
770 * @deprecated use upload()
772 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
773 $watch = false, $timestamp = false )
775 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
776 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
777 return false;
779 if ( $watch ) {
780 global $wgUser;
781 $wgUser->addWatch( $this->getTitle() );
783 return true;
788 * Record a file upload in the upload log and the image table
790 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
792 if( is_null( $user ) ) {
793 global $wgUser;
794 $user = $wgUser;
797 $dbw = $this->repo->getMasterDB();
798 $dbw->begin();
800 if ( !$props ) {
801 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
803 $props['description'] = $comment;
804 $props['user'] = $user->getId();
805 $props['user_text'] = $user->getName();
806 $props['timestamp'] = wfTimestamp( TS_MW );
807 $this->setProps( $props );
809 // Delete thumbnails and refresh the metadata cache
810 $this->purgeThumbnails();
811 $this->saveToCache();
812 SquidUpdate::purge( array( $this->getURL() ) );
814 // Fail now if the file isn't there
815 if ( !$this->fileExists ) {
816 wfDebug( __METHOD__ . ": File " . $this->getPath() . " went missing!\n" );
817 return false;
820 $reupload = false;
821 if ( $timestamp === false ) {
822 $timestamp = $dbw->timestamp();
825 # Test to see if the row exists using INSERT IGNORE
826 # This avoids race conditions by locking the row until the commit, and also
827 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
828 $dbw->insert( 'image',
829 array(
830 'img_name' => $this->getName(),
831 'img_size'=> $this->size,
832 'img_width' => intval( $this->width ),
833 'img_height' => intval( $this->height ),
834 'img_bits' => $this->bits,
835 'img_media_type' => $this->media_type,
836 'img_major_mime' => $this->major_mime,
837 'img_minor_mime' => $this->minor_mime,
838 'img_timestamp' => $timestamp,
839 'img_description' => $comment,
840 'img_user' => $user->getId(),
841 'img_user_text' => $user->getName(),
842 'img_metadata' => $this->metadata,
843 'img_sha1' => $this->sha1
845 __METHOD__,
846 'IGNORE'
849 if( $dbw->affectedRows() == 0 ) {
850 $reupload = true;
852 # Collision, this is an update of a file
853 # Insert previous contents into oldimage
854 $dbw->insertSelect( 'oldimage', 'image',
855 array(
856 'oi_name' => 'img_name',
857 'oi_archive_name' => $dbw->addQuotes( $oldver ),
858 'oi_size' => 'img_size',
859 'oi_width' => 'img_width',
860 'oi_height' => 'img_height',
861 'oi_bits' => 'img_bits',
862 'oi_timestamp' => 'img_timestamp',
863 'oi_description' => 'img_description',
864 'oi_user' => 'img_user',
865 'oi_user_text' => 'img_user_text',
866 'oi_metadata' => 'img_metadata',
867 'oi_media_type' => 'img_media_type',
868 'oi_major_mime' => 'img_major_mime',
869 'oi_minor_mime' => 'img_minor_mime',
870 'oi_sha1' => 'img_sha1'
871 ), array( 'img_name' => $this->getName() ), __METHOD__
874 # Update the current image row
875 $dbw->update( 'image',
876 array( /* SET */
877 'img_size' => $this->size,
878 'img_width' => intval( $this->width ),
879 'img_height' => intval( $this->height ),
880 'img_bits' => $this->bits,
881 'img_media_type' => $this->media_type,
882 'img_major_mime' => $this->major_mime,
883 'img_minor_mime' => $this->minor_mime,
884 'img_timestamp' => $timestamp,
885 'img_description' => $comment,
886 'img_user' => $user->getId(),
887 'img_user_text' => $user->getName(),
888 'img_metadata' => $this->metadata,
889 'img_sha1' => $this->sha1
890 ), array( /* WHERE */
891 'img_name' => $this->getName()
892 ), __METHOD__
894 } else {
895 # This is a new file
896 # Update the image count
897 $site_stats = $dbw->tableName( 'site_stats' );
898 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
901 $descTitle = $this->getTitle();
902 $article = new ImagePage( $descTitle );
903 $article->setFile( $this );
905 # Add the log entry
906 $log = new LogPage( 'upload' );
907 $action = $reupload ? 'overwrite' : 'upload';
908 $log->addEntry( $action, $descTitle, $comment, array(), $user );
910 if( $descTitle->exists() ) {
911 # Create a null revision
912 $latest = $descTitle->getLatestRevID();
913 $nullRevision = Revision::newNullRevision( $dbw, $descTitle->getArticleId(),
914 $log->getRcComment(), false );
915 $nullRevision->insertOn( $dbw );
917 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
918 $article->updateRevisionOn( $dbw, $nullRevision );
920 # Invalidate the cache for the description page
921 $descTitle->invalidateCache();
922 $descTitle->purgeSquid();
923 } else {
924 // New file; create the description page.
925 // There's already a log entry, so don't make a second RC entry
926 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
929 # Hooks, hooks, the magic of hooks...
930 wfRunHooks( 'FileUpload', array( $this ) );
932 # Commit the transaction now, in case something goes wrong later
933 # The most important thing is that files don't get lost, especially archives
934 $dbw->commit();
936 # Invalidate cache for all pages using this file
937 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
938 $update->doUpdate();
939 # Invalidate cache for all pages that redirects on this page
940 $redirs = $this->getTitle()->getRedirectsHere();
941 foreach( $redirs as $redir ) {
942 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
943 $update->doUpdate();
946 return true;
950 * Move or copy a file to its public location. If a file exists at the
951 * destination, move it to an archive. Returns the archive name on success
952 * or an empty string if it was a new file, and a wikitext-formatted
953 * WikiError object on failure.
955 * The archive name should be passed through to recordUpload for database
956 * registration.
958 * @param $srcPath String: local filesystem path to the source image
959 * @param $flags Integer: a bitwise combination of:
960 * File::DELETE_SOURCE Delete the source file, i.e. move
961 * rather than copy
962 * @return FileRepoStatus object. On success, the value member contains the
963 * archive name, or an empty string if it was a new file.
965 function publish( $srcPath, $flags = 0 ) {
966 $this->lock();
967 $dstRel = $this->getRel();
968 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
969 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
970 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
971 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
972 if ( $status->value == 'new' ) {
973 $status->value = '';
974 } else {
975 $status->value = $archiveName;
977 $this->unlock();
978 return $status;
981 /** getLinksTo inherited */
982 /** getExifData inherited */
983 /** isLocal inherited */
984 /** wasDeleted inherited */
987 * Move file to the new title
989 * Move current, old version and all thumbnails
990 * to the new filename. Old file is deleted.
992 * Cache purging is done; checks for validity
993 * and logging are caller's responsibility
995 * @param $target Title New file name
996 * @return FileRepoStatus object.
998 function move( $target ) {
999 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1000 $this->lock();
1001 $batch = new LocalFileMoveBatch( $this, $target );
1002 $batch->addCurrent();
1003 $batch->addOlds();
1005 $status = $batch->execute();
1006 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1007 $this->purgeEverything();
1008 $this->unlock();
1010 if ( $status->isOk() ) {
1011 // Now switch the object
1012 $this->title = $target;
1013 // Force regeneration of the name and hashpath
1014 unset( $this->name );
1015 unset( $this->hashPath );
1016 // Purge the new image
1017 $this->purgeEverything();
1020 return $status;
1024 * Delete all versions of the file.
1026 * Moves the files into an archive directory (or deletes them)
1027 * and removes the database rows.
1029 * Cache purging is done; logging is caller's responsibility.
1031 * @param $reason
1032 * @param $suppress
1033 * @return FileRepoStatus object.
1035 function delete( $reason, $suppress = false ) {
1036 $this->lock();
1037 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1038 $batch->addCurrent();
1040 # Get old version relative paths
1041 $dbw = $this->repo->getMasterDB();
1042 $result = $dbw->select( 'oldimage',
1043 array( 'oi_archive_name' ),
1044 array( 'oi_name' => $this->getName() ) );
1045 while ( $row = $dbw->fetchObject( $result ) ) {
1046 $batch->addOld( $row->oi_archive_name );
1048 $status = $batch->execute();
1050 if ( $status->ok ) {
1051 // Update site_stats
1052 $site_stats = $dbw->tableName( 'site_stats' );
1053 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1054 $this->purgeEverything();
1057 $this->unlock();
1058 return $status;
1062 * Delete an old version of the file.
1064 * Moves the file into an archive directory (or deletes it)
1065 * and removes the database row.
1067 * Cache purging is done; logging is caller's responsibility.
1069 * @param $archiveName String
1070 * @param $reason String
1071 * @param $suppress Boolean
1072 * @throws MWException or FSException on database or file store failure
1073 * @return FileRepoStatus object.
1075 function deleteOld( $archiveName, $reason, $suppress=false ) {
1076 $this->lock();
1077 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1078 $batch->addOld( $archiveName );
1079 $status = $batch->execute();
1080 $this->unlock();
1081 if ( $status->ok ) {
1082 $this->purgeDescription();
1083 $this->purgeHistory();
1085 return $status;
1089 * Restore all or specified deleted revisions to the given file.
1090 * Permissions and logging are left to the caller.
1092 * May throw database exceptions on error.
1094 * @param $versions set of record ids of deleted items to restore,
1095 * or empty to restore all revisions.
1096 * @param $unsuppress Boolean
1097 * @return FileRepoStatus
1099 function restore( $versions = array(), $unsuppress = false ) {
1100 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1101 if ( !$versions ) {
1102 $batch->addAll();
1103 } else {
1104 $batch->addIds( $versions );
1106 $status = $batch->execute();
1107 if ( !$status->ok ) {
1108 return $status;
1111 $cleanupStatus = $batch->cleanup();
1112 $cleanupStatus->successCount = 0;
1113 $cleanupStatus->failCount = 0;
1114 $status->merge( $cleanupStatus );
1115 return $status;
1118 /** isMultipage inherited */
1119 /** pageCount inherited */
1120 /** scaleHeight inherited */
1121 /** getImageSize inherited */
1124 * Get the URL of the file description page.
1126 function getDescriptionUrl() {
1127 return $this->title->getLocalUrl();
1131 * Get the HTML text of the description page
1132 * This is not used by ImagePage for local files, since (among other things)
1133 * it skips the parser cache.
1135 function getDescriptionText() {
1136 global $wgParser;
1137 $revision = Revision::newFromTitle( $this->title );
1138 if ( !$revision ) return false;
1139 $text = $revision->getText();
1140 if ( !$text ) return false;
1141 $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
1142 return $pout->getText();
1145 function getDescription() {
1146 $this->load();
1147 return $this->description;
1150 function getTimestamp() {
1151 $this->load();
1152 return $this->timestamp;
1155 function getSha1() {
1156 $this->load();
1157 // Initialise now if necessary
1158 if ( $this->sha1 == '' && $this->fileExists ) {
1159 $this->sha1 = File::sha1Base36( $this->getPath() );
1160 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1161 $dbw = $this->repo->getMasterDB();
1162 $dbw->update( 'image',
1163 array( 'img_sha1' => $this->sha1 ),
1164 array( 'img_name' => $this->getName() ),
1165 __METHOD__ );
1166 $this->saveToCache();
1170 return $this->sha1;
1174 * Start a transaction and lock the image for update
1175 * Increments a reference counter if the lock is already held
1176 * @return boolean True if the image exists, false otherwise
1178 function lock() {
1179 $dbw = $this->repo->getMasterDB();
1180 if ( !$this->locked ) {
1181 $dbw->begin();
1182 $this->locked++;
1184 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1188 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1189 * the transaction and thereby releases the image lock.
1191 function unlock() {
1192 if ( $this->locked ) {
1193 --$this->locked;
1194 if ( !$this->locked ) {
1195 $dbw = $this->repo->getMasterDB();
1196 $dbw->commit();
1202 * Roll back the DB transaction and mark the image unlocked
1204 function unlockAndRollback() {
1205 $this->locked = false;
1206 $dbw = $this->repo->getMasterDB();
1207 $dbw->rollback();
1209 } // LocalFile class
1211 #------------------------------------------------------------------------------
1214 * Helper class for file deletion
1215 * @ingroup FileRepo
1217 class LocalFileDeleteBatch {
1218 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1219 var $status;
1221 function __construct( File $file, $reason = '', $suppress = false ) {
1222 $this->file = $file;
1223 $this->reason = $reason;
1224 $this->suppress = $suppress;
1225 $this->status = $file->repo->newGood();
1228 function addCurrent() {
1229 $this->srcRels['.'] = $this->file->getRel();
1232 function addOld( $oldName ) {
1233 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1234 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1237 function getOldRels() {
1238 if ( !isset( $this->srcRels['.'] ) ) {
1239 $oldRels =& $this->srcRels;
1240 $deleteCurrent = false;
1241 } else {
1242 $oldRels = $this->srcRels;
1243 unset( $oldRels['.'] );
1244 $deleteCurrent = true;
1246 return array( $oldRels, $deleteCurrent );
1249 /*protected*/ function getHashes() {
1250 $hashes = array();
1251 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1252 if ( $deleteCurrent ) {
1253 $hashes['.'] = $this->file->getSha1();
1255 if ( count( $oldRels ) ) {
1256 $dbw = $this->file->repo->getMasterDB();
1257 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1258 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1259 __METHOD__ );
1260 while ( $row = $dbw->fetchObject( $res ) ) {
1261 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1262 // Get the hash from the file
1263 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1264 $props = $this->file->repo->getFileProps( $oldUrl );
1265 if ( $props['fileExists'] ) {
1266 // Upgrade the oldimage row
1267 $dbw->update( 'oldimage',
1268 array( 'oi_sha1' => $props['sha1'] ),
1269 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1270 __METHOD__ );
1271 $hashes[$row->oi_archive_name] = $props['sha1'];
1272 } else {
1273 $hashes[$row->oi_archive_name] = false;
1275 } else {
1276 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1280 $missing = array_diff_key( $this->srcRels, $hashes );
1281 foreach ( $missing as $name => $rel ) {
1282 $this->status->error( 'filedelete-old-unregistered', $name );
1284 foreach ( $hashes as $name => $hash ) {
1285 if ( !$hash ) {
1286 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1287 unset( $hashes[$name] );
1291 return $hashes;
1294 function doDBInserts() {
1295 global $wgUser;
1296 $dbw = $this->file->repo->getMasterDB();
1297 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1298 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1299 $encReason = $dbw->addQuotes( $this->reason );
1300 $encGroup = $dbw->addQuotes( 'deleted' );
1301 $ext = $this->file->getExtension();
1302 $dotExt = $ext === '' ? '' : ".$ext";
1303 $encExt = $dbw->addQuotes( $dotExt );
1304 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1306 // Bitfields to further suppress the content
1307 if ( $this->suppress ) {
1308 $bitfield = 0;
1309 // This should be 15...
1310 $bitfield |= Revision::DELETED_TEXT;
1311 $bitfield |= Revision::DELETED_COMMENT;
1312 $bitfield |= Revision::DELETED_USER;
1313 $bitfield |= Revision::DELETED_RESTRICTED;
1314 } else {
1315 $bitfield = 'oi_deleted';
1318 if ( $deleteCurrent ) {
1319 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1320 $where = array( 'img_name' => $this->file->getName() );
1321 $dbw->insertSelect( 'filearchive', 'image',
1322 array(
1323 'fa_storage_group' => $encGroup,
1324 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1325 'fa_deleted_user' => $encUserId,
1326 'fa_deleted_timestamp' => $encTimestamp,
1327 'fa_deleted_reason' => $encReason,
1328 'fa_deleted' => $this->suppress ? $bitfield : 0,
1330 'fa_name' => 'img_name',
1331 'fa_archive_name' => 'NULL',
1332 'fa_size' => 'img_size',
1333 'fa_width' => 'img_width',
1334 'fa_height' => 'img_height',
1335 'fa_metadata' => 'img_metadata',
1336 'fa_bits' => 'img_bits',
1337 'fa_media_type' => 'img_media_type',
1338 'fa_major_mime' => 'img_major_mime',
1339 'fa_minor_mime' => 'img_minor_mime',
1340 'fa_description' => 'img_description',
1341 'fa_user' => 'img_user',
1342 'fa_user_text' => 'img_user_text',
1343 'fa_timestamp' => 'img_timestamp'
1344 ), $where, __METHOD__ );
1347 if ( count( $oldRels ) ) {
1348 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1349 $where = array(
1350 'oi_name' => $this->file->getName(),
1351 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1352 $dbw->insertSelect( 'filearchive', 'oldimage',
1353 array(
1354 'fa_storage_group' => $encGroup,
1355 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1356 'fa_deleted_user' => $encUserId,
1357 'fa_deleted_timestamp' => $encTimestamp,
1358 'fa_deleted_reason' => $encReason,
1359 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1361 'fa_name' => 'oi_name',
1362 'fa_archive_name' => 'oi_archive_name',
1363 'fa_size' => 'oi_size',
1364 'fa_width' => 'oi_width',
1365 'fa_height' => 'oi_height',
1366 'fa_metadata' => 'oi_metadata',
1367 'fa_bits' => 'oi_bits',
1368 'fa_media_type' => 'oi_media_type',
1369 'fa_major_mime' => 'oi_major_mime',
1370 'fa_minor_mime' => 'oi_minor_mime',
1371 'fa_description' => 'oi_description',
1372 'fa_user' => 'oi_user',
1373 'fa_user_text' => 'oi_user_text',
1374 'fa_timestamp' => 'oi_timestamp',
1375 'fa_deleted' => $bitfield
1376 ), $where, __METHOD__ );
1380 function doDBDeletes() {
1381 $dbw = $this->file->repo->getMasterDB();
1382 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1383 if ( count( $oldRels ) ) {
1384 $dbw->delete( 'oldimage',
1385 array(
1386 'oi_name' => $this->file->getName(),
1387 'oi_archive_name' => array_keys( $oldRels )
1388 ), __METHOD__ );
1390 if ( $deleteCurrent ) {
1391 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1396 * Run the transaction
1398 function execute() {
1399 global $wgUseSquid;
1400 wfProfileIn( __METHOD__ );
1402 $this->file->lock();
1403 // Leave private files alone
1404 $privateFiles = array();
1405 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1406 $dbw = $this->file->repo->getMasterDB();
1407 if( !empty( $oldRels ) ) {
1408 $res = $dbw->select( 'oldimage',
1409 array( 'oi_archive_name' ),
1410 array( 'oi_name' => $this->file->getName(),
1411 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1412 $dbw->bitAnd('oi_deleted', File::DELETED_FILE) => File::DELETED_FILE ),
1413 __METHOD__ );
1414 while( $row = $dbw->fetchObject( $res ) ) {
1415 $privateFiles[$row->oi_archive_name] = 1;
1418 // Prepare deletion batch
1419 $hashes = $this->getHashes();
1420 $this->deletionBatch = array();
1421 $ext = $this->file->getExtension();
1422 $dotExt = $ext === '' ? '' : ".$ext";
1423 foreach ( $this->srcRels as $name => $srcRel ) {
1424 // Skip files that have no hash (missing source).
1425 // Keep private files where they are.
1426 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1427 $hash = $hashes[$name];
1428 $key = $hash . $dotExt;
1429 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1430 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1434 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1435 // We acquire this lock by running the inserts now, before the file operations.
1437 // This potentially has poor lock contention characteristics -- an alternative
1438 // scheme would be to insert stub filearchive entries with no fa_name and commit
1439 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1440 $this->doDBInserts();
1442 // Removes non-existent file from the batch, so we don't get errors.
1443 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
1445 // Execute the file deletion batch
1446 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1447 if ( !$status->isGood() ) {
1448 $this->status->merge( $status );
1451 if ( !$this->status->ok ) {
1452 // Critical file deletion error
1453 // Roll back inserts, release lock and abort
1454 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1455 $this->file->unlockAndRollback();
1456 wfProfileOut( __METHOD__ );
1457 return $this->status;
1460 // Purge squid
1461 if ( $wgUseSquid ) {
1462 $urls = array();
1463 foreach ( $this->srcRels as $srcRel ) {
1464 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1465 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1467 SquidUpdate::purge( $urls );
1470 // Delete image/oldimage rows
1471 $this->doDBDeletes();
1473 // Commit and return
1474 $this->file->unlock();
1475 wfProfileOut( __METHOD__ );
1476 return $this->status;
1480 * Removes non-existent files from a deletion batch.
1482 function removeNonexistentFiles( $batch ) {
1483 $files = $newBatch = array();
1484 foreach( $batch as $batchItem ) {
1485 list( $src, $dest ) = $batchItem;
1486 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1488 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1489 foreach( $batch as $batchItem )
1490 if( $result[$batchItem[0]] )
1491 $newBatch[] = $batchItem;
1492 return $newBatch;
1496 #------------------------------------------------------------------------------
1499 * Helper class for file undeletion
1500 * @ingroup FileRepo
1502 class LocalFileRestoreBatch {
1503 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1505 function __construct( File $file, $unsuppress = false ) {
1506 $this->file = $file;
1507 $this->cleanupBatch = $this->ids = array();
1508 $this->ids = array();
1509 $this->unsuppress = $unsuppress;
1513 * Add a file by ID
1515 function addId( $fa_id ) {
1516 $this->ids[] = $fa_id;
1520 * Add a whole lot of files by ID
1522 function addIds( $ids ) {
1523 $this->ids = array_merge( $this->ids, $ids );
1527 * Add all revisions of the file
1529 function addAll() {
1530 $this->all = true;
1534 * Run the transaction, except the cleanup batch.
1535 * The cleanup batch should be run in a separate transaction, because it locks different
1536 * rows and there's no need to keep the image row locked while it's acquiring those locks
1537 * The caller may have its own transaction open.
1538 * So we save the batch and let the caller call cleanup()
1540 function execute() {
1541 global $wgLang;
1542 if ( !$this->all && !$this->ids ) {
1543 // Do nothing
1544 return $this->file->repo->newGood();
1547 $exists = $this->file->lock();
1548 $dbw = $this->file->repo->getMasterDB();
1549 $status = $this->file->repo->newGood();
1551 // Fetch all or selected archived revisions for the file,
1552 // sorted from the most recent to the oldest.
1553 $conditions = array( 'fa_name' => $this->file->getName() );
1554 if( !$this->all ) {
1555 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1558 $result = $dbw->select( 'filearchive', '*',
1559 $conditions,
1560 __METHOD__,
1561 array( 'ORDER BY' => 'fa_timestamp DESC' )
1564 $idsPresent = array();
1565 $storeBatch = array();
1566 $insertBatch = array();
1567 $insertCurrent = false;
1568 $deleteIds = array();
1569 $first = true;
1570 $archiveNames = array();
1571 while( $row = $dbw->fetchObject( $result ) ) {
1572 $idsPresent[] = $row->fa_id;
1574 if ( $row->fa_name != $this->file->getName() ) {
1575 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1576 $status->failCount++;
1577 continue;
1579 if ( $row->fa_storage_key == '' ) {
1580 // Revision was missing pre-deletion
1581 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1582 $status->failCount++;
1583 continue;
1586 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1587 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1589 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1590 # Fix leading zero
1591 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1592 $sha1 = substr( $sha1, 1 );
1595 if( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1596 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1597 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1598 || is_null( $row->fa_metadata ) ) {
1599 // Refresh our metadata
1600 // Required for a new current revision; nice for older ones too. :)
1601 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1602 } else {
1603 $props = array(
1604 'minor_mime' => $row->fa_minor_mime,
1605 'major_mime' => $row->fa_major_mime,
1606 'media_type' => $row->fa_media_type,
1607 'metadata' => $row->fa_metadata
1611 if ( $first && !$exists ) {
1612 // This revision will be published as the new current version
1613 $destRel = $this->file->getRel();
1614 $insertCurrent = array(
1615 'img_name' => $row->fa_name,
1616 'img_size' => $row->fa_size,
1617 'img_width' => $row->fa_width,
1618 'img_height' => $row->fa_height,
1619 'img_metadata' => $props['metadata'],
1620 'img_bits' => $row->fa_bits,
1621 'img_media_type' => $props['media_type'],
1622 'img_major_mime' => $props['major_mime'],
1623 'img_minor_mime' => $props['minor_mime'],
1624 'img_description' => $row->fa_description,
1625 'img_user' => $row->fa_user,
1626 'img_user_text' => $row->fa_user_text,
1627 'img_timestamp' => $row->fa_timestamp,
1628 'img_sha1' => $sha1
1630 // The live (current) version cannot be hidden!
1631 if( !$this->unsuppress && $row->fa_deleted ) {
1632 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1633 $this->cleanupBatch[] = $row->fa_storage_key;
1635 } else {
1636 $archiveName = $row->fa_archive_name;
1637 if( $archiveName == '' ) {
1638 // This was originally a current version; we
1639 // have to devise a new archive name for it.
1640 // Format is <timestamp of archiving>!<name>
1641 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1642 do {
1643 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1644 $timestamp++;
1645 } while ( isset( $archiveNames[$archiveName] ) );
1647 $archiveNames[$archiveName] = true;
1648 $destRel = $this->file->getArchiveRel( $archiveName );
1649 $insertBatch[] = array(
1650 'oi_name' => $row->fa_name,
1651 'oi_archive_name' => $archiveName,
1652 'oi_size' => $row->fa_size,
1653 'oi_width' => $row->fa_width,
1654 'oi_height' => $row->fa_height,
1655 'oi_bits' => $row->fa_bits,
1656 'oi_description' => $row->fa_description,
1657 'oi_user' => $row->fa_user,
1658 'oi_user_text' => $row->fa_user_text,
1659 'oi_timestamp' => $row->fa_timestamp,
1660 'oi_metadata' => $props['metadata'],
1661 'oi_media_type' => $props['media_type'],
1662 'oi_major_mime' => $props['major_mime'],
1663 'oi_minor_mime' => $props['minor_mime'],
1664 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
1665 'oi_sha1' => $sha1 );
1668 $deleteIds[] = $row->fa_id;
1669 if( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
1670 // private files can stay where they are
1671 $status->successCount++;
1672 } else {
1673 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1674 $this->cleanupBatch[] = $row->fa_storage_key;
1676 $first = false;
1678 unset( $result );
1680 // Add a warning to the status object for missing IDs
1681 $missingIds = array_diff( $this->ids, $idsPresent );
1682 foreach ( $missingIds as $id ) {
1683 $status->error( 'undelete-missing-filearchive', $id );
1686 // Remove missing files from batch, so we don't get errors when undeleting them
1687 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1689 // Run the store batch
1690 // Use the OVERWRITE_SAME flag to smooth over a common error
1691 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1692 $status->merge( $storeStatus );
1694 if ( !$status->ok ) {
1695 // Store batch returned a critical error -- this usually means nothing was stored
1696 // Stop now and return an error
1697 $this->file->unlock();
1698 return $status;
1701 // Run the DB updates
1702 // Because we have locked the image row, key conflicts should be rare.
1703 // If they do occur, we can roll back the transaction at this time with
1704 // no data loss, but leaving unregistered files scattered throughout the
1705 // public zone.
1706 // This is not ideal, which is why it's important to lock the image row.
1707 if ( $insertCurrent ) {
1708 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1710 if ( $insertBatch ) {
1711 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1713 if ( $deleteIds ) {
1714 $dbw->delete( 'filearchive',
1715 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1716 __METHOD__ );
1719 // If store batch is empty (all files are missing), deletion is to be considered successful
1720 if( $status->successCount > 0 || !$storeBatch ) {
1721 if( !$exists ) {
1722 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
1724 // Update site_stats
1725 $site_stats = $dbw->tableName( 'site_stats' );
1726 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1728 $this->file->purgeEverything();
1729 } else {
1730 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
1731 $this->file->purgeDescription();
1732 $this->file->purgeHistory();
1735 $this->file->unlock();
1736 return $status;
1740 * Removes non-existent files from a store batch.
1742 function removeNonexistentFiles( $triplets ) {
1743 $files = $filteredTriplets = array();
1744 foreach( $triplets as $file )
1745 $files[$file[0]] = $file[0];
1746 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1747 foreach( $triplets as $file )
1748 if( $result[$file[0]] )
1749 $filteredTriplets[] = $file;
1750 return $filteredTriplets;
1754 * Removes non-existent files from a cleanup batch.
1756 function removeNonexistentFromCleanup( $batch ) {
1757 $files = $newBatch = array();
1758 $repo = $this->file->repo;
1759 foreach( $batch as $file ) {
1760 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1761 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1764 $result = $repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1765 foreach( $batch as $file )
1766 if( $result[$file] )
1767 $newBatch[] = $file;
1768 return $newBatch;
1772 * Delete unused files in the deleted zone.
1773 * This should be called from outside the transaction in which execute() was called.
1775 function cleanup() {
1776 if ( !$this->cleanupBatch ) {
1777 return $this->file->repo->newGood();
1779 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
1780 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
1781 return $status;
1785 #------------------------------------------------------------------------------
1788 * Helper class for file movement
1789 * @ingroup FileRepo
1791 class LocalFileMoveBatch {
1792 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1794 function __construct( File $file, Title $target ) {
1795 $this->file = $file;
1796 $this->target = $target;
1797 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
1798 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
1799 $this->oldName = $this->file->getName();
1800 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
1801 $this->oldRel = $this->oldHash . $this->oldName;
1802 $this->newRel = $this->newHash . $this->newName;
1803 $this->db = $file->repo->getMasterDb();
1807 * Add the current image to the batch
1809 function addCurrent() {
1810 $this->cur = array( $this->oldRel, $this->newRel );
1814 * Add the old versions of the image to the batch
1816 function addOlds() {
1817 $archiveBase = 'archive';
1818 $this->olds = array();
1819 $this->oldCount = 0;
1821 $result = $this->db->select( 'oldimage',
1822 array( 'oi_archive_name', 'oi_deleted' ),
1823 array( 'oi_name' => $this->oldName ),
1824 __METHOD__
1826 while( $row = $this->db->fetchObject( $result ) ) {
1827 $oldName = $row->oi_archive_name;
1828 $bits = explode( '!', $oldName, 2 );
1829 if( count( $bits ) != 2 ) {
1830 wfDebug( "Invalid old file name: $oldName \n" );
1831 continue;
1833 list( $timestamp, $filename ) = $bits;
1834 if( $this->oldName != $filename ) {
1835 wfDebug( "Invalid old file name: $oldName \n" );
1836 continue;
1838 $this->oldCount++;
1839 // Do we want to add those to oldCount?
1840 if( $row->oi_deleted & File::DELETED_FILE ) {
1841 continue;
1843 $this->olds[] = array(
1844 "{$archiveBase}/{$this->oldHash}{$oldName}",
1845 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1848 $this->db->freeResult( $result );
1852 * Perform the move.
1854 function execute() {
1855 $repo = $this->file->repo;
1856 $status = $repo->newGood();
1857 $triplets = $this->getMoveTriplets();
1859 $triplets = $this->removeNonexistentFiles( $triplets );
1860 $statusDb = $this->doDBUpdates();
1861 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1862 $statusMove = $repo->storeBatch( $triplets, FSRepo::DELETE_SOURCE );
1863 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1864 if( !$statusMove->isOk() ) {
1865 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1866 $this->db->rollback();
1869 $status->merge( $statusDb );
1870 $status->merge( $statusMove );
1871 return $status;
1875 * Do the database updates and return a new WikiError indicating how many
1876 * rows where updated.
1878 function doDBUpdates() {
1879 $repo = $this->file->repo;
1880 $status = $repo->newGood();
1881 $dbw = $this->db;
1883 // Update current image
1884 $dbw->update(
1885 'image',
1886 array( 'img_name' => $this->newName ),
1887 array( 'img_name' => $this->oldName ),
1888 __METHOD__
1890 if( $dbw->affectedRows() ) {
1891 $status->successCount++;
1892 } else {
1893 $status->failCount++;
1896 // Update old images
1897 $dbw->update(
1898 'oldimage',
1899 array(
1900 'oi_name' => $this->newName,
1901 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName), $dbw->addQuotes($this->newName) ),
1903 array( 'oi_name' => $this->oldName ),
1904 __METHOD__
1906 $affected = $dbw->affectedRows();
1907 $total = $this->oldCount;
1908 $status->successCount += $affected;
1909 $status->failCount += $total - $affected;
1911 return $status;
1915 * Generate triplets for FSRepo::storeBatch().
1917 function getMoveTriplets() {
1918 $moves = array_merge( array( $this->cur ), $this->olds );
1919 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1920 foreach( $moves as $move ) {
1921 // $move: (oldRelativePath, newRelativePath)
1922 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1923 $triplets[] = array( $srcUrl, 'public', $move[1] );
1924 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
1926 return $triplets;
1930 * Removes non-existent files from move batch.
1932 function removeNonexistentFiles( $triplets ) {
1933 $files = array();
1934 foreach( $triplets as $file )
1935 $files[$file[0]] = $file[0];
1936 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1937 $filteredTriplets = array();
1938 foreach( $triplets as $file )
1939 if( $result[$file[0]] ) {
1940 $filteredTriplets[] = $file;
1941 } else {
1942 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
1944 return $filteredTriplets;