Minor followup to r64197
[mediawiki.git] / includes / filerepo / LocalFile.php
blobb17214ee395170f39d922ccf3209d90ce3e3a687
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 string $timestamp Timestamp for img_timestamp, or false to use the current time
752 * @return FileRepoStatus object. On success, the value member contains the
753 * archive name, or an empty string if it was a new file.
755 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
756 $this->lock();
757 $status = $this->publish( $srcPath, $flags );
758 if ( $status->ok ) {
759 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
760 $status->fatal( 'filenotfound', $srcPath );
763 $this->unlock();
764 return $status;
768 * Record a file upload in the upload log and the image table
769 * @deprecated use upload()
771 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
772 $watch = false, $timestamp = false )
774 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
775 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
776 return false;
778 if ( $watch ) {
779 global $wgUser;
780 $wgUser->addWatch( $this->getTitle() );
782 return true;
787 * Record a file upload in the upload log and the image table
789 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
791 if( is_null( $user ) ) {
792 global $wgUser;
793 $user = $wgUser;
796 $dbw = $this->repo->getMasterDB();
797 $dbw->begin();
799 if ( !$props ) {
800 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
802 $props['description'] = $comment;
803 $props['user'] = $user->getId();
804 $props['user_text'] = $user->getName();
805 $props['timestamp'] = wfTimestamp( TS_MW );
806 $this->setProps( $props );
808 // Delete thumbnails and refresh the metadata cache
809 $this->purgeThumbnails();
810 $this->saveToCache();
811 SquidUpdate::purge( array( $this->getURL() ) );
813 // Fail now if the file isn't there
814 if ( !$this->fileExists ) {
815 wfDebug( __METHOD__ . ": File " . $this->getPath() . " went missing!\n" );
816 return false;
819 $reupload = false;
820 if ( $timestamp === false ) {
821 $timestamp = $dbw->timestamp();
824 # Test to see if the row exists using INSERT IGNORE
825 # This avoids race conditions by locking the row until the commit, and also
826 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
827 $dbw->insert( 'image',
828 array(
829 'img_name' => $this->getName(),
830 'img_size'=> $this->size,
831 'img_width' => intval( $this->width ),
832 'img_height' => intval( $this->height ),
833 'img_bits' => $this->bits,
834 'img_media_type' => $this->media_type,
835 'img_major_mime' => $this->major_mime,
836 'img_minor_mime' => $this->minor_mime,
837 'img_timestamp' => $timestamp,
838 'img_description' => $comment,
839 'img_user' => $user->getId(),
840 'img_user_text' => $user->getName(),
841 'img_metadata' => $this->metadata,
842 'img_sha1' => $this->sha1
844 __METHOD__,
845 'IGNORE'
848 if( $dbw->affectedRows() == 0 ) {
849 $reupload = true;
851 # Collision, this is an update of a file
852 # Insert previous contents into oldimage
853 $dbw->insertSelect( 'oldimage', 'image',
854 array(
855 'oi_name' => 'img_name',
856 'oi_archive_name' => $dbw->addQuotes( $oldver ),
857 'oi_size' => 'img_size',
858 'oi_width' => 'img_width',
859 'oi_height' => 'img_height',
860 'oi_bits' => 'img_bits',
861 'oi_timestamp' => 'img_timestamp',
862 'oi_description' => 'img_description',
863 'oi_user' => 'img_user',
864 'oi_user_text' => 'img_user_text',
865 'oi_metadata' => 'img_metadata',
866 'oi_media_type' => 'img_media_type',
867 'oi_major_mime' => 'img_major_mime',
868 'oi_minor_mime' => 'img_minor_mime',
869 'oi_sha1' => 'img_sha1'
870 ), array( 'img_name' => $this->getName() ), __METHOD__
873 # Update the current image row
874 $dbw->update( 'image',
875 array( /* SET */
876 'img_size' => $this->size,
877 'img_width' => intval( $this->width ),
878 'img_height' => intval( $this->height ),
879 'img_bits' => $this->bits,
880 'img_media_type' => $this->media_type,
881 'img_major_mime' => $this->major_mime,
882 'img_minor_mime' => $this->minor_mime,
883 'img_timestamp' => $timestamp,
884 'img_description' => $comment,
885 'img_user' => $user->getId(),
886 'img_user_text' => $user->getName(),
887 'img_metadata' => $this->metadata,
888 'img_sha1' => $this->sha1
889 ), array( /* WHERE */
890 'img_name' => $this->getName()
891 ), __METHOD__
893 } else {
894 # This is a new file
895 # Update the image count
896 $site_stats = $dbw->tableName( 'site_stats' );
897 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
900 $descTitle = $this->getTitle();
901 $article = new ImagePage( $descTitle );
902 $article->setFile( $this );
904 # Add the log entry
905 $log = new LogPage( 'upload' );
906 $action = $reupload ? 'overwrite' : 'upload';
907 $log->addEntry( $action, $descTitle, $comment, array(), $user );
909 if( $descTitle->exists() ) {
910 # Create a null revision
911 $latest = $descTitle->getLatestRevID();
912 $nullRevision = Revision::newNullRevision( $dbw, $descTitle->getArticleId(),
913 $log->getRcComment(), false );
914 $nullRevision->insertOn( $dbw );
916 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
917 $article->updateRevisionOn( $dbw, $nullRevision );
919 # Invalidate the cache for the description page
920 $descTitle->invalidateCache();
921 $descTitle->purgeSquid();
922 } else {
923 // New file; create the description page.
924 // There's already a log entry, so don't make a second RC entry
925 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
928 # Hooks, hooks, the magic of hooks...
929 wfRunHooks( 'FileUpload', array( $this ) );
931 # Commit the transaction now, in case something goes wrong later
932 # The most important thing is that files don't get lost, especially archives
933 $dbw->commit();
935 # Invalidate cache for all pages using this file
936 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
937 $update->doUpdate();
938 # Invalidate cache for all pages that redirects on this page
939 $redirs = $this->getTitle()->getRedirectsHere();
940 foreach( $redirs as $redir ) {
941 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
942 $update->doUpdate();
945 return true;
949 * Move or copy a file to its public location. If a file exists at the
950 * destination, move it to an archive. Returns the archive name on success
951 * or an empty string if it was a new file, and a wikitext-formatted
952 * WikiError object on failure.
954 * The archive name should be passed through to recordUpload for database
955 * registration.
957 * @param $sourcePath String: local filesystem path to the source image
958 * @param $flags Integer: a bitwise combination of:
959 * File::DELETE_SOURCE Delete the source file, i.e. move
960 * rather than copy
961 * @return FileRepoStatus object. On success, the value member contains the
962 * archive name, or an empty string if it was a new file.
964 function publish( $srcPath, $flags = 0 ) {
965 $this->lock();
966 $dstRel = $this->getRel();
967 $archiveName = gmdate( 'YmdHis' ) . '!'. $this->getName();
968 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
969 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
970 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
971 if ( $status->value == 'new' ) {
972 $status->value = '';
973 } else {
974 $status->value = $archiveName;
976 $this->unlock();
977 return $status;
980 /** getLinksTo inherited */
981 /** getExifData inherited */
982 /** isLocal inherited */
983 /** wasDeleted inherited */
986 * Move file to the new title
988 * Move current, old version and all thumbnails
989 * to the new filename. Old file is deleted.
991 * Cache purging is done; checks for validity
992 * and logging are caller's responsibility
994 * @param $target Title New file name
995 * @return FileRepoStatus object.
997 function move( $target ) {
998 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
999 $this->lock();
1000 $batch = new LocalFileMoveBatch( $this, $target );
1001 $batch->addCurrent();
1002 $batch->addOlds();
1004 $status = $batch->execute();
1005 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1006 $this->purgeEverything();
1007 $this->unlock();
1009 if ( $status->isOk() ) {
1010 // Now switch the object
1011 $this->title = $target;
1012 // Force regeneration of the name and hashpath
1013 unset( $this->name );
1014 unset( $this->hashPath );
1015 // Purge the new image
1016 $this->purgeEverything();
1019 return $status;
1023 * Delete all versions of the file.
1025 * Moves the files into an archive directory (or deletes them)
1026 * and removes the database rows.
1028 * Cache purging is done; logging is caller's responsibility.
1030 * @param $reason
1031 * @param $suppress
1032 * @return FileRepoStatus object.
1034 function delete( $reason, $suppress = false ) {
1035 $this->lock();
1036 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1037 $batch->addCurrent();
1039 # Get old version relative paths
1040 $dbw = $this->repo->getMasterDB();
1041 $result = $dbw->select( 'oldimage',
1042 array( 'oi_archive_name' ),
1043 array( 'oi_name' => $this->getName() ) );
1044 while ( $row = $dbw->fetchObject( $result ) ) {
1045 $batch->addOld( $row->oi_archive_name );
1047 $status = $batch->execute();
1049 if ( $status->ok ) {
1050 // Update site_stats
1051 $site_stats = $dbw->tableName( 'site_stats' );
1052 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1053 $this->purgeEverything();
1056 $this->unlock();
1057 return $status;
1061 * Delete an old version of the file.
1063 * Moves the file into an archive directory (or deletes it)
1064 * and removes the database row.
1066 * Cache purging is done; logging is caller's responsibility.
1068 * @param $archiveName String
1069 * @param $reason String
1070 * @param $suppress Boolean
1071 * @throws MWException or FSException on database or file store failure
1072 * @return FileRepoStatus object.
1074 function deleteOld( $archiveName, $reason, $suppress=false ) {
1075 $this->lock();
1076 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1077 $batch->addOld( $archiveName );
1078 $status = $batch->execute();
1079 $this->unlock();
1080 if ( $status->ok ) {
1081 $this->purgeDescription();
1082 $this->purgeHistory();
1084 return $status;
1088 * Restore all or specified deleted revisions to the given file.
1089 * Permissions and logging are left to the caller.
1091 * May throw database exceptions on error.
1093 * @param $versions set of record ids of deleted items to restore,
1094 * or empty to restore all revisions.
1095 * @param $unsuppress Boolean
1096 * @return FileRepoStatus
1098 function restore( $versions = array(), $unsuppress = false ) {
1099 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1100 if ( !$versions ) {
1101 $batch->addAll();
1102 } else {
1103 $batch->addIds( $versions );
1105 $status = $batch->execute();
1106 if ( !$status->ok ) {
1107 return $status;
1110 $cleanupStatus = $batch->cleanup();
1111 $cleanupStatus->successCount = 0;
1112 $cleanupStatus->failCount = 0;
1113 $status->merge( $cleanupStatus );
1114 return $status;
1117 /** isMultipage inherited */
1118 /** pageCount inherited */
1119 /** scaleHeight inherited */
1120 /** getImageSize inherited */
1123 * Get the URL of the file description page.
1125 function getDescriptionUrl() {
1126 return $this->title->getLocalUrl();
1130 * Get the HTML text of the description page
1131 * This is not used by ImagePage for local files, since (among other things)
1132 * it skips the parser cache.
1134 function getDescriptionText() {
1135 global $wgParser;
1136 $revision = Revision::newFromTitle( $this->title );
1137 if ( !$revision ) return false;
1138 $text = $revision->getText();
1139 if ( !$text ) return false;
1140 $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
1141 return $pout->getText();
1144 function getDescription() {
1145 $this->load();
1146 return $this->description;
1149 function getTimestamp() {
1150 $this->load();
1151 return $this->timestamp;
1154 function getSha1() {
1155 $this->load();
1156 // Initialise now if necessary
1157 if ( $this->sha1 == '' && $this->fileExists ) {
1158 $this->sha1 = File::sha1Base36( $this->getPath() );
1159 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1160 $dbw = $this->repo->getMasterDB();
1161 $dbw->update( 'image',
1162 array( 'img_sha1' => $this->sha1 ),
1163 array( 'img_name' => $this->getName() ),
1164 __METHOD__ );
1165 $this->saveToCache();
1169 return $this->sha1;
1173 * Start a transaction and lock the image for update
1174 * Increments a reference counter if the lock is already held
1175 * @return boolean True if the image exists, false otherwise
1177 function lock() {
1178 $dbw = $this->repo->getMasterDB();
1179 if ( !$this->locked ) {
1180 $dbw->begin();
1181 $this->locked++;
1183 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1187 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1188 * the transaction and thereby releases the image lock.
1190 function unlock() {
1191 if ( $this->locked ) {
1192 --$this->locked;
1193 if ( !$this->locked ) {
1194 $dbw = $this->repo->getMasterDB();
1195 $dbw->commit();
1201 * Roll back the DB transaction and mark the image unlocked
1203 function unlockAndRollback() {
1204 $this->locked = false;
1205 $dbw = $this->repo->getMasterDB();
1206 $dbw->rollback();
1208 } // LocalFile class
1210 #------------------------------------------------------------------------------
1213 * Helper class for file deletion
1214 * @ingroup FileRepo
1216 class LocalFileDeleteBatch {
1217 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1218 var $status;
1220 function __construct( File $file, $reason = '', $suppress = false ) {
1221 $this->file = $file;
1222 $this->reason = $reason;
1223 $this->suppress = $suppress;
1224 $this->status = $file->repo->newGood();
1227 function addCurrent() {
1228 $this->srcRels['.'] = $this->file->getRel();
1231 function addOld( $oldName ) {
1232 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1233 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1236 function getOldRels() {
1237 if ( !isset( $this->srcRels['.'] ) ) {
1238 $oldRels =& $this->srcRels;
1239 $deleteCurrent = false;
1240 } else {
1241 $oldRels = $this->srcRels;
1242 unset( $oldRels['.'] );
1243 $deleteCurrent = true;
1245 return array( $oldRels, $deleteCurrent );
1248 /*protected*/ function getHashes() {
1249 $hashes = array();
1250 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1251 if ( $deleteCurrent ) {
1252 $hashes['.'] = $this->file->getSha1();
1254 if ( count( $oldRels ) ) {
1255 $dbw = $this->file->repo->getMasterDB();
1256 $res = $dbw->select( 'oldimage', array( 'oi_archive_name', 'oi_sha1' ),
1257 'oi_archive_name IN(' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1258 __METHOD__ );
1259 while ( $row = $dbw->fetchObject( $res ) ) {
1260 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1261 // Get the hash from the file
1262 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1263 $props = $this->file->repo->getFileProps( $oldUrl );
1264 if ( $props['fileExists'] ) {
1265 // Upgrade the oldimage row
1266 $dbw->update( 'oldimage',
1267 array( 'oi_sha1' => $props['sha1'] ),
1268 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1269 __METHOD__ );
1270 $hashes[$row->oi_archive_name] = $props['sha1'];
1271 } else {
1272 $hashes[$row->oi_archive_name] = false;
1274 } else {
1275 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1279 $missing = array_diff_key( $this->srcRels, $hashes );
1280 foreach ( $missing as $name => $rel ) {
1281 $this->status->error( 'filedelete-old-unregistered', $name );
1283 foreach ( $hashes as $name => $hash ) {
1284 if ( !$hash ) {
1285 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1286 unset( $hashes[$name] );
1290 return $hashes;
1293 function doDBInserts() {
1294 global $wgUser;
1295 $dbw = $this->file->repo->getMasterDB();
1296 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1297 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1298 $encReason = $dbw->addQuotes( $this->reason );
1299 $encGroup = $dbw->addQuotes( 'deleted' );
1300 $ext = $this->file->getExtension();
1301 $dotExt = $ext === '' ? '' : ".$ext";
1302 $encExt = $dbw->addQuotes( $dotExt );
1303 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1305 // Bitfields to further suppress the content
1306 if ( $this->suppress ) {
1307 $bitfield = 0;
1308 // This should be 15...
1309 $bitfield |= Revision::DELETED_TEXT;
1310 $bitfield |= Revision::DELETED_COMMENT;
1311 $bitfield |= Revision::DELETED_USER;
1312 $bitfield |= Revision::DELETED_RESTRICTED;
1313 } else {
1314 $bitfield = 'oi_deleted';
1317 if ( $deleteCurrent ) {
1318 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1319 $where = array( 'img_name' => $this->file->getName() );
1320 $dbw->insertSelect( 'filearchive', 'image',
1321 array(
1322 'fa_storage_group' => $encGroup,
1323 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1324 'fa_deleted_user' => $encUserId,
1325 'fa_deleted_timestamp' => $encTimestamp,
1326 'fa_deleted_reason' => $encReason,
1327 'fa_deleted' => $this->suppress ? $bitfield : 0,
1329 'fa_name' => 'img_name',
1330 'fa_archive_name' => 'NULL',
1331 'fa_size' => 'img_size',
1332 'fa_width' => 'img_width',
1333 'fa_height' => 'img_height',
1334 'fa_metadata' => 'img_metadata',
1335 'fa_bits' => 'img_bits',
1336 'fa_media_type' => 'img_media_type',
1337 'fa_major_mime' => 'img_major_mime',
1338 'fa_minor_mime' => 'img_minor_mime',
1339 'fa_description' => 'img_description',
1340 'fa_user' => 'img_user',
1341 'fa_user_text' => 'img_user_text',
1342 'fa_timestamp' => 'img_timestamp'
1343 ), $where, __METHOD__ );
1346 if ( count( $oldRels ) ) {
1347 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1348 $where = array(
1349 'oi_name' => $this->file->getName(),
1350 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1351 $dbw->insertSelect( 'filearchive', 'oldimage',
1352 array(
1353 'fa_storage_group' => $encGroup,
1354 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1355 'fa_deleted_user' => $encUserId,
1356 'fa_deleted_timestamp' => $encTimestamp,
1357 'fa_deleted_reason' => $encReason,
1358 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1360 'fa_name' => 'oi_name',
1361 'fa_archive_name' => 'oi_archive_name',
1362 'fa_size' => 'oi_size',
1363 'fa_width' => 'oi_width',
1364 'fa_height' => 'oi_height',
1365 'fa_metadata' => 'oi_metadata',
1366 'fa_bits' => 'oi_bits',
1367 'fa_media_type' => 'oi_media_type',
1368 'fa_major_mime' => 'oi_major_mime',
1369 'fa_minor_mime' => 'oi_minor_mime',
1370 'fa_description' => 'oi_description',
1371 'fa_user' => 'oi_user',
1372 'fa_user_text' => 'oi_user_text',
1373 'fa_timestamp' => 'oi_timestamp',
1374 'fa_deleted' => $bitfield
1375 ), $where, __METHOD__ );
1379 function doDBDeletes() {
1380 $dbw = $this->file->repo->getMasterDB();
1381 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1382 if ( count( $oldRels ) ) {
1383 $dbw->delete( 'oldimage',
1384 array(
1385 'oi_name' => $this->file->getName(),
1386 'oi_archive_name' => array_keys( $oldRels )
1387 ), __METHOD__ );
1389 if ( $deleteCurrent ) {
1390 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1395 * Run the transaction
1397 function execute() {
1398 global $wgUseSquid;
1399 wfProfileIn( __METHOD__ );
1401 $this->file->lock();
1402 // Leave private files alone
1403 $privateFiles = array();
1404 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1405 $dbw = $this->file->repo->getMasterDB();
1406 if( !empty( $oldRels ) ) {
1407 $res = $dbw->select( 'oldimage',
1408 array( 'oi_archive_name' ),
1409 array( 'oi_name' => $this->file->getName(),
1410 'oi_archive_name IN (' . $dbw->makeList( array_keys($oldRels) ) . ')',
1411 $dbw->bitAnd('oi_deleted', File::DELETED_FILE) => File::DELETED_FILE ),
1412 __METHOD__ );
1413 while( $row = $dbw->fetchObject( $res ) ) {
1414 $privateFiles[$row->oi_archive_name] = 1;
1417 // Prepare deletion batch
1418 $hashes = $this->getHashes();
1419 $this->deletionBatch = array();
1420 $ext = $this->file->getExtension();
1421 $dotExt = $ext === '' ? '' : ".$ext";
1422 foreach ( $this->srcRels as $name => $srcRel ) {
1423 // Skip files that have no hash (missing source).
1424 // Keep private files where they are.
1425 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1426 $hash = $hashes[$name];
1427 $key = $hash . $dotExt;
1428 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1429 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1433 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1434 // We acquire this lock by running the inserts now, before the file operations.
1436 // This potentially has poor lock contention characteristics -- an alternative
1437 // scheme would be to insert stub filearchive entries with no fa_name and commit
1438 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1439 $this->doDBInserts();
1441 // Removes non-existent file from the batch, so we don't get errors.
1442 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
1444 // Execute the file deletion batch
1445 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1446 if ( !$status->isGood() ) {
1447 $this->status->merge( $status );
1450 if ( !$this->status->ok ) {
1451 // Critical file deletion error
1452 // Roll back inserts, release lock and abort
1453 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1454 $this->file->unlockAndRollback();
1455 wfProfileOut( __METHOD__ );
1456 return $this->status;
1459 // Purge squid
1460 if ( $wgUseSquid ) {
1461 $urls = array();
1462 foreach ( $this->srcRels as $srcRel ) {
1463 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1464 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1466 SquidUpdate::purge( $urls );
1469 // Delete image/oldimage rows
1470 $this->doDBDeletes();
1472 // Commit and return
1473 $this->file->unlock();
1474 wfProfileOut( __METHOD__ );
1475 return $this->status;
1479 * Removes non-existent files from a deletion batch.
1481 function removeNonexistentFiles( $batch ) {
1482 $files = $newBatch = array();
1483 foreach( $batch as $batchItem ) {
1484 list( $src, $dest ) = $batchItem;
1485 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1487 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1488 foreach( $batch as $batchItem )
1489 if( $result[$batchItem[0]] )
1490 $newBatch[] = $batchItem;
1491 return $newBatch;
1495 #------------------------------------------------------------------------------
1498 * Helper class for file undeletion
1499 * @ingroup FileRepo
1501 class LocalFileRestoreBatch {
1502 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1504 function __construct( File $file, $unsuppress = false ) {
1505 $this->file = $file;
1506 $this->cleanupBatch = $this->ids = array();
1507 $this->ids = array();
1508 $this->unsuppress = $unsuppress;
1512 * Add a file by ID
1514 function addId( $fa_id ) {
1515 $this->ids[] = $fa_id;
1519 * Add a whole lot of files by ID
1521 function addIds( $ids ) {
1522 $this->ids = array_merge( $this->ids, $ids );
1526 * Add all revisions of the file
1528 function addAll() {
1529 $this->all = true;
1533 * Run the transaction, except the cleanup batch.
1534 * The cleanup batch should be run in a separate transaction, because it locks different
1535 * rows and there's no need to keep the image row locked while it's acquiring those locks
1536 * The caller may have its own transaction open.
1537 * So we save the batch and let the caller call cleanup()
1539 function execute() {
1540 global $wgLang;
1541 if ( !$this->all && !$this->ids ) {
1542 // Do nothing
1543 return $this->file->repo->newGood();
1546 $exists = $this->file->lock();
1547 $dbw = $this->file->repo->getMasterDB();
1548 $status = $this->file->repo->newGood();
1550 // Fetch all or selected archived revisions for the file,
1551 // sorted from the most recent to the oldest.
1552 $conditions = array( 'fa_name' => $this->file->getName() );
1553 if( !$this->all ) {
1554 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1557 $result = $dbw->select( 'filearchive', '*',
1558 $conditions,
1559 __METHOD__,
1560 array( 'ORDER BY' => 'fa_timestamp DESC' )
1563 $idsPresent = array();
1564 $storeBatch = array();
1565 $insertBatch = array();
1566 $insertCurrent = false;
1567 $deleteIds = array();
1568 $first = true;
1569 $archiveNames = array();
1570 while( $row = $dbw->fetchObject( $result ) ) {
1571 $idsPresent[] = $row->fa_id;
1573 if ( $row->fa_name != $this->file->getName() ) {
1574 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1575 $status->failCount++;
1576 continue;
1578 if ( $row->fa_storage_key == '' ) {
1579 // Revision was missing pre-deletion
1580 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1581 $status->failCount++;
1582 continue;
1585 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1586 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1588 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1589 # Fix leading zero
1590 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1591 $sha1 = substr( $sha1, 1 );
1594 if( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1595 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1596 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1597 || is_null( $row->fa_metadata ) ) {
1598 // Refresh our metadata
1599 // Required for a new current revision; nice for older ones too. :)
1600 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1601 } else {
1602 $props = array(
1603 'minor_mime' => $row->fa_minor_mime,
1604 'major_mime' => $row->fa_major_mime,
1605 'media_type' => $row->fa_media_type,
1606 'metadata' => $row->fa_metadata
1610 if ( $first && !$exists ) {
1611 // This revision will be published as the new current version
1612 $destRel = $this->file->getRel();
1613 $insertCurrent = array(
1614 'img_name' => $row->fa_name,
1615 'img_size' => $row->fa_size,
1616 'img_width' => $row->fa_width,
1617 'img_height' => $row->fa_height,
1618 'img_metadata' => $props['metadata'],
1619 'img_bits' => $row->fa_bits,
1620 'img_media_type' => $props['media_type'],
1621 'img_major_mime' => $props['major_mime'],
1622 'img_minor_mime' => $props['minor_mime'],
1623 'img_description' => $row->fa_description,
1624 'img_user' => $row->fa_user,
1625 'img_user_text' => $row->fa_user_text,
1626 'img_timestamp' => $row->fa_timestamp,
1627 'img_sha1' => $sha1
1629 // The live (current) version cannot be hidden!
1630 if( !$this->unsuppress && $row->fa_deleted ) {
1631 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1632 $this->cleanupBatch[] = $row->fa_storage_key;
1634 } else {
1635 $archiveName = $row->fa_archive_name;
1636 if( $archiveName == '' ) {
1637 // This was originally a current version; we
1638 // have to devise a new archive name for it.
1639 // Format is <timestamp of archiving>!<name>
1640 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1641 do {
1642 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1643 $timestamp++;
1644 } while ( isset( $archiveNames[$archiveName] ) );
1646 $archiveNames[$archiveName] = true;
1647 $destRel = $this->file->getArchiveRel( $archiveName );
1648 $insertBatch[] = array(
1649 'oi_name' => $row->fa_name,
1650 'oi_archive_name' => $archiveName,
1651 'oi_size' => $row->fa_size,
1652 'oi_width' => $row->fa_width,
1653 'oi_height' => $row->fa_height,
1654 'oi_bits' => $row->fa_bits,
1655 'oi_description' => $row->fa_description,
1656 'oi_user' => $row->fa_user,
1657 'oi_user_text' => $row->fa_user_text,
1658 'oi_timestamp' => $row->fa_timestamp,
1659 'oi_metadata' => $props['metadata'],
1660 'oi_media_type' => $props['media_type'],
1661 'oi_major_mime' => $props['major_mime'],
1662 'oi_minor_mime' => $props['minor_mime'],
1663 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
1664 'oi_sha1' => $sha1 );
1667 $deleteIds[] = $row->fa_id;
1668 if( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
1669 // private files can stay where they are
1670 $status->successCount++;
1671 } else {
1672 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1673 $this->cleanupBatch[] = $row->fa_storage_key;
1675 $first = false;
1677 unset( $result );
1679 // Add a warning to the status object for missing IDs
1680 $missingIds = array_diff( $this->ids, $idsPresent );
1681 foreach ( $missingIds as $id ) {
1682 $status->error( 'undelete-missing-filearchive', $id );
1685 // Remove missing files from batch, so we don't get errors when undeleting them
1686 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1688 // Run the store batch
1689 // Use the OVERWRITE_SAME flag to smooth over a common error
1690 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1691 $status->merge( $storeStatus );
1693 if ( !$status->ok ) {
1694 // Store batch returned a critical error -- this usually means nothing was stored
1695 // Stop now and return an error
1696 $this->file->unlock();
1697 return $status;
1700 // Run the DB updates
1701 // Because we have locked the image row, key conflicts should be rare.
1702 // If they do occur, we can roll back the transaction at this time with
1703 // no data loss, but leaving unregistered files scattered throughout the
1704 // public zone.
1705 // This is not ideal, which is why it's important to lock the image row.
1706 if ( $insertCurrent ) {
1707 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1709 if ( $insertBatch ) {
1710 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1712 if ( $deleteIds ) {
1713 $dbw->delete( 'filearchive',
1714 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1715 __METHOD__ );
1718 // If store batch is empty (all files are missing), deletion is to be considered successful
1719 if( $status->successCount > 0 || !$storeBatch ) {
1720 if( !$exists ) {
1721 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
1723 // Update site_stats
1724 $site_stats = $dbw->tableName( 'site_stats' );
1725 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1727 $this->file->purgeEverything();
1728 } else {
1729 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
1730 $this->file->purgeDescription();
1731 $this->file->purgeHistory();
1734 $this->file->unlock();
1735 return $status;
1739 * Removes non-existent files from a store batch.
1741 function removeNonexistentFiles( $triplets ) {
1742 $files = $filteredTriplets = array();
1743 foreach( $triplets as $file )
1744 $files[$file[0]] = $file[0];
1745 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1746 foreach( $triplets as $file )
1747 if( $result[$file[0]] )
1748 $filteredTriplets[] = $file;
1749 return $filteredTriplets;
1753 * Removes non-existent files from a cleanup batch.
1755 function removeNonexistentFromCleanup( $batch ) {
1756 $files = $newBatch = array();
1757 $repo = $this->file->repo;
1758 foreach( $batch as $file ) {
1759 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1760 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1763 $result = $repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1764 foreach( $batch as $file )
1765 if( $result[$file] )
1766 $newBatch[] = $file;
1767 return $newBatch;
1771 * Delete unused files in the deleted zone.
1772 * This should be called from outside the transaction in which execute() was called.
1774 function cleanup() {
1775 if ( !$this->cleanupBatch ) {
1776 return $this->file->repo->newGood();
1778 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
1779 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
1780 return $status;
1784 #------------------------------------------------------------------------------
1787 * Helper class for file movement
1788 * @ingroup FileRepo
1790 class LocalFileMoveBatch {
1791 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1793 function __construct( File $file, Title $target ) {
1794 $this->file = $file;
1795 $this->target = $target;
1796 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
1797 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
1798 $this->oldName = $this->file->getName();
1799 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
1800 $this->oldRel = $this->oldHash . $this->oldName;
1801 $this->newRel = $this->newHash . $this->newName;
1802 $this->db = $file->repo->getMasterDb();
1806 * Add the current image to the batch
1808 function addCurrent() {
1809 $this->cur = array( $this->oldRel, $this->newRel );
1813 * Add the old versions of the image to the batch
1815 function addOlds() {
1816 $archiveBase = 'archive';
1817 $this->olds = array();
1818 $this->oldCount = 0;
1820 $result = $this->db->select( 'oldimage',
1821 array( 'oi_archive_name', 'oi_deleted' ),
1822 array( 'oi_name' => $this->oldName ),
1823 __METHOD__
1825 while( $row = $this->db->fetchObject( $result ) ) {
1826 $oldName = $row->oi_archive_name;
1827 $bits = explode( '!', $oldName, 2 );
1828 if( count( $bits ) != 2 ) {
1829 wfDebug( "Invalid old file name: $oldName \n" );
1830 continue;
1832 list( $timestamp, $filename ) = $bits;
1833 if( $this->oldName != $filename ) {
1834 wfDebug( "Invalid old file name: $oldName \n" );
1835 continue;
1837 $this->oldCount++;
1838 // Do we want to add those to oldCount?
1839 if( $row->oi_deleted & File::DELETED_FILE ) {
1840 continue;
1842 $this->olds[] = array(
1843 "{$archiveBase}/{$this->oldHash}{$oldName}",
1844 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1847 $this->db->freeResult( $result );
1851 * Perform the move.
1853 function execute() {
1854 $repo = $this->file->repo;
1855 $status = $repo->newGood();
1856 $triplets = $this->getMoveTriplets();
1858 $triplets = $this->removeNonexistentFiles( $triplets );
1859 $statusDb = $this->doDBUpdates();
1860 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
1861 $statusMove = $repo->storeBatch( $triplets, FSRepo::DELETE_SOURCE );
1862 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
1863 if( !$statusMove->isOk() ) {
1864 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
1865 $this->db->rollback();
1868 $status->merge( $statusDb );
1869 $status->merge( $statusMove );
1870 return $status;
1874 * Do the database updates and return a new WikiError indicating how many
1875 * rows where updated.
1877 function doDBUpdates() {
1878 $repo = $this->file->repo;
1879 $status = $repo->newGood();
1880 $dbw = $this->db;
1882 // Update current image
1883 $dbw->update(
1884 'image',
1885 array( 'img_name' => $this->newName ),
1886 array( 'img_name' => $this->oldName ),
1887 __METHOD__
1889 if( $dbw->affectedRows() ) {
1890 $status->successCount++;
1891 } else {
1892 $status->failCount++;
1895 // Update old images
1896 $dbw->update(
1897 'oldimage',
1898 array(
1899 'oi_name' => $this->newName,
1900 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes($this->oldName), $dbw->addQuotes($this->newName) ),
1902 array( 'oi_name' => $this->oldName ),
1903 __METHOD__
1905 $affected = $dbw->affectedRows();
1906 $total = $this->oldCount;
1907 $status->successCount += $affected;
1908 $status->failCount += $total - $affected;
1910 return $status;
1914 * Generate triplets for FSRepo::storeBatch().
1916 function getMoveTriplets() {
1917 $moves = array_merge( array( $this->cur ), $this->olds );
1918 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
1919 foreach( $moves as $move ) {
1920 // $move: (oldRelativePath, newRelativePath)
1921 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
1922 $triplets[] = array( $srcUrl, 'public', $move[1] );
1923 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
1925 return $triplets;
1929 * Removes non-existent files from move batch.
1931 function removeNonexistentFiles( $triplets ) {
1932 $files = array();
1933 foreach( $triplets as $file )
1934 $files[$file[0]] = $file[0];
1935 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1936 $filteredTriplets = array();
1937 foreach( $triplets as $file )
1938 if( $result[$file[0]] ) {
1939 $filteredTriplets[] = $file;
1940 } else {
1941 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
1943 return $filteredTriplets;