3 * Local file in the wiki's own database
10 * Bump this number when serialized cache records may be incompatible.
12 define( 'MW_FILE_VERSION', 8 );
15 * Class to represent a local file in the wiki's own database
17 * Provides methods to retrieve paths (physical, logical, URL),
18 * to generate image thumbnails or for uploading.
20 * Note that only the repo object knows what its file class is called. You should
21 * never name a file class explictly outside of the repo class. Instead use the
22 * repo's factory functions to generate file objects, for example:
24 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
26 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
31 class LocalFile extends File {
36 $fileExists, # does the file file exist on disk? (loadFromXxx)
37 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
38 $historyRes, # result of the query for the file's history (nextHistoryLine)
41 $bits, # --- returned by getimagesize (loadFromXxx)
43 $media_type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
44 $mime, # MIME type, determined by MimeMagic::guessMimeType
45 $major_mime, # Major mime type
46 $minor_mime, # Minor mime type
47 $size, # Size in bytes (loadFromXxx)
48 $metadata, # Handler-specific metadata
49 $timestamp, # Upload timestamp
50 $sha1, # SHA-1 base 36 content hash
51 $user, $user_text, # User, who uploaded the file
52 $description, # Description of current revision of the file
53 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
54 $upgraded, # Whether the row was upgraded on load
55 $locked, # True if the image row is locked
56 $missing, # True if file is not present in file system. Not to be cached in memcached
57 $deleted; # Bitfield akin to rev_deleted
62 * Create a LocalFile from a title
63 * Do not call this except from inside a repo class.
65 * Note: $unused param is only here to avoid an E_STRICT
67 static function newFromTitle( $title, $repo, $unused = null ) {
68 return new self( $title, $repo );
72 * Create a LocalFile from a title
73 * Do not call this except from inside a repo class.
75 static function newFromRow( $row, $repo ) {
76 $title = Title::makeTitle( NS_FILE, $row->img_name );
77 $file = new self( $title, $repo );
78 $file->loadFromRow( $row );
84 * Create a LocalFile from a SHA-1 key
85 * Do not call this except from inside a repo class.
87 static function newFromKey( $sha1, $repo, $timestamp = false ) {
88 $conds = array( 'img_sha1' => $sha1 );
91 $conds['img_timestamp'] = $timestamp;
94 $dbr = $repo->getSlaveDB();
95 $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
98 return self::newFromRow( $row, $repo );
105 * Fields in the image table
107 static function selectFields() {
128 * Do not call this except from inside a repo class.
130 function __construct( $title, $repo ) {
131 if ( !is_object( $title ) ) {
132 throw new MWException( __CLASS__ . ' constructor given bogus title.' );
135 parent::__construct( $title, $repo );
137 $this->metadata = '';
138 $this->historyLine = 0;
139 $this->historyRes = null;
140 $this->dataLoaded = false;
144 * Get the memcached key for the main data for this file, or false if
145 * there is no access to the shared cache.
147 function getCacheKey() {
148 $hashedName = md5( $this->getName() );
150 return $this->repo->getSharedCacheKey( 'file', $hashedName );
154 * Try to load file metadata from memcached. Returns true on success.
156 function loadFromCache() {
159 wfProfileIn( __METHOD__ );
160 $this->dataLoaded = false;
161 $key = $this->getCacheKey();
164 wfProfileOut( __METHOD__ );
168 $cachedValues = $wgMemc->get( $key );
170 // Check if the key existed and belongs to this version of MediaWiki
171 if ( isset( $cachedValues['version'] ) && ( $cachedValues['version'] == MW_FILE_VERSION ) ) {
172 wfDebug( "Pulling file metadata from cache key $key\n" );
173 $this->fileExists = $cachedValues['fileExists'];
174 if ( $this->fileExists ) {
175 $this->setProps( $cachedValues );
177 $this->dataLoaded = true;
180 if ( $this->dataLoaded ) {
181 wfIncrStats( 'image_cache_hit' );
183 wfIncrStats( 'image_cache_miss' );
186 wfProfileOut( __METHOD__ );
187 return $this->dataLoaded;
191 * Save the file metadata to memcached
193 function saveToCache() {
197 $key = $this->getCacheKey();
203 $fields = $this->getCacheFields( '' );
204 $cache = array( 'version' => MW_FILE_VERSION );
205 $cache['fileExists'] = $this->fileExists;
207 if ( $this->fileExists ) {
208 foreach ( $fields as $field ) {
209 $cache[$field] = $this->$field;
213 $wgMemc->set( $key, $cache, 60 * 60 * 24 * 7 ); // A week
217 * Load metadata from the file itself
219 function loadFromFile() {
220 $this->setProps( self::getPropsFromPath( $this->getPath() ) );
223 function getCacheFields( $prefix = 'img_' ) {
224 static $fields = array( 'size', 'width', 'height', 'bits', 'media_type',
225 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', 'user_text', 'description' );
226 static $results = array();
228 if ( $prefix == '' ) {
232 if ( !isset( $results[$prefix] ) ) {
233 $prefixedFields = array();
234 foreach ( $fields as $field ) {
235 $prefixedFields[] = $prefix . $field;
237 $results[$prefix] = $prefixedFields;
240 return $results[$prefix];
244 * Load file metadata from the DB
246 function loadFromDB() {
247 # Polymorphic function name to distinguish foreign and local fetches
248 $fname = get_class( $this ) . '::' . __FUNCTION__;
249 wfProfileIn( $fname );
251 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
252 $this->dataLoaded = true;
254 $dbr = $this->repo->getMasterDB();
256 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
257 array( 'img_name' => $this->getName() ), $fname );
260 $this->loadFromRow( $row );
262 $this->fileExists = false;
265 wfProfileOut( $fname );
269 * Decode a row from the database (either object or array) to an array
270 * with timestamps and MIME types decoded, and the field prefix removed.
272 function decodeRow( $row, $prefix = 'img_' ) {
273 $array = (array)$row;
274 $prefixLength = strlen( $prefix );
276 // Sanity check prefix once
277 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
278 throw new MWException( __METHOD__ . ': incorrect $prefix parameter' );
283 foreach ( $array as $name => $value ) {
284 $decoded[substr( $name, $prefixLength )] = $value;
287 $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] );
289 if ( empty( $decoded['major_mime'] ) ) {
290 $decoded['mime'] = 'unknown/unknown';
292 if ( !$decoded['minor_mime'] ) {
293 $decoded['minor_mime'] = 'unknown';
295 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
298 # Trim zero padding from char/binary field
299 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
305 * Load file metadata from a DB result row
307 function loadFromRow( $row, $prefix = 'img_' ) {
308 $this->dataLoaded = true;
309 $array = $this->decodeRow( $row, $prefix );
311 foreach ( $array as $name => $value ) {
312 $this->$name = $value;
315 $this->fileExists = true;
316 $this->maybeUpgradeRow();
320 * Load file metadata from cache or DB, unless already loaded
323 if ( !$this->dataLoaded ) {
324 if ( !$this->loadFromCache() ) {
326 $this->saveToCache();
328 $this->dataLoaded = true;
333 * Upgrade a row if it needs it
335 function maybeUpgradeRow() {
336 if ( wfReadOnly() ) {
340 if ( is_null( $this->media_type ) ||
341 $this->mime == 'image/svg'
344 $this->upgraded = true;
346 $handler = $this->getHandler();
347 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata ) ) {
349 $this->upgraded = true;
354 function getUpgraded() {
355 return $this->upgraded;
359 * Fix assorted version-related problems with the image row by reloading it from the file
361 function upgradeRow() {
362 wfProfileIn( __METHOD__ );
364 $this->loadFromFile();
366 # Don't destroy file info of missing files
367 if ( !$this->fileExists ) {
368 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
369 wfProfileOut( __METHOD__ );
373 $dbw = $this->repo->getMasterDB();
374 list( $major, $minor ) = self::splitMime( $this->mime );
376 if ( wfReadOnly() ) {
377 wfProfileOut( __METHOD__ );
380 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
382 $dbw->update( 'image',
384 'img_width' => $this->width,
385 'img_height' => $this->height,
386 'img_bits' => $this->bits,
387 'img_media_type' => $this->media_type,
388 'img_major_mime' => $major,
389 'img_minor_mime' => $minor,
390 'img_metadata' => $this->metadata,
391 'img_sha1' => $this->sha1,
392 ), array( 'img_name' => $this->getName() ),
396 $this->saveToCache();
397 wfProfileOut( __METHOD__ );
401 * Set properties in this object to be equal to those given in the
402 * associative array $info. Only cacheable fields can be set.
404 * If 'mime' is given, it will be split into major_mime/minor_mime.
405 * If major_mime/minor_mime are given, $this->mime will also be set.
407 function setProps( $info ) {
408 $this->dataLoaded = true;
409 $fields = $this->getCacheFields( '' );
410 $fields[] = 'fileExists';
412 foreach ( $fields as $field ) {
413 if ( isset( $info[$field] ) ) {
414 $this->$field = $info[$field];
418 // Fix up mime fields
419 if ( isset( $info['major_mime'] ) ) {
420 $this->mime = "{$info['major_mime']}/{$info['minor_mime']}";
421 } elseif ( isset( $info['mime'] ) ) {
422 $this->mime = $info['mime'];
423 list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime );
427 /** splitMime inherited */
428 /** getName inherited */
429 /** getTitle inherited */
430 /** getURL inherited */
431 /** getViewURL inherited */
432 /** getPath inherited */
433 /** isVisible inhereted */
435 function isMissing() {
436 if ( $this->missing === null ) {
437 list( $fileExists ) = $this->repo->fileExistsBatch( array( $this->getVirtualUrl() ), FileRepo::FILES_ONLY );
438 $this->missing = !$fileExists;
440 return $this->missing;
444 * Return the width of the image
446 * Returns false on error
448 public function getWidth( $page = 1 ) {
451 if ( $this->isMultipage() ) {
452 $dim = $this->getHandler()->getPageDimensions( $this, $page );
454 return $dim['width'];
464 * Return the height of the image
466 * Returns false on error
468 public function getHeight( $page = 1 ) {
471 if ( $this->isMultipage() ) {
472 $dim = $this->getHandler()->getPageDimensions( $this, $page );
474 return $dim['height'];
479 return $this->height;
484 * Returns ID or name of user who uploaded the file
486 * @param $type string 'text' or 'id'
488 function getUser( $type = 'text' ) {
491 if ( $type == 'text' ) {
492 return $this->user_text;
493 } elseif ( $type == 'id' ) {
499 * Get handler-specific metadata
501 function getMetadata() {
503 return $this->metadata;
506 function getBitDepth() {
512 * Return the size of the image file, in bytes
514 public function getSize() {
520 * Returns the mime type of the file.
522 function getMimeType() {
528 * Return the type of the media in the file.
529 * Use the value returned by this function with the MEDIATYPE_xxx constants.
531 function getMediaType() {
533 return $this->media_type;
536 /** canRender inherited */
537 /** mustRender inherited */
538 /** allowInlineDisplay inherited */
539 /** isSafeFile inherited */
540 /** isTrustedFile inherited */
543 * Returns true if the file file exists on disk.
544 * @return boolean Whether file file exist on disk.
546 public function exists() {
548 return $this->fileExists;
551 /** getTransformScript inherited */
552 /** getUnscaledThumb inherited */
553 /** thumbName inherited */
554 /** createThumb inherited */
555 /** getThumbnail inherited */
556 /** transform inherited */
559 * Fix thumbnail files from 1.4 or before, with extreme prejudice
561 function migrateThumbFile( $thumbName ) {
562 $thumbDir = $this->getThumbPath();
563 $thumbPath = "$thumbDir/$thumbName";
565 if ( is_dir( $thumbPath ) ) {
566 // Directory where file should be
567 // This happened occasionally due to broken migration code in 1.5
568 // Rename to broken-*
569 for ( $i = 0; $i < 100 ; $i++ ) {
570 $broken = $this->repo->getZonePath( 'public' ) . "/broken-$i-$thumbName";
571 if ( !file_exists( $broken ) ) {
572 rename( $thumbPath, $broken );
576 // Doesn't exist anymore
580 if ( is_file( $thumbDir ) ) {
581 // File where directory should be
583 // Doesn't exist anymore
588 /** getHandler inherited */
589 /** iconThumb inherited */
590 /** getLastError inherited */
593 * Get all thumbnail names previously generated for this file
595 function getThumbnails() {
599 $dir = $this->getThumbPath();
601 if ( is_dir( $dir ) ) {
602 $handle = opendir( $dir );
605 while ( false !== ( $file = readdir( $handle ) ) ) {
606 if ( $file { 0 } != '.' ) {
619 * Refresh metadata in memcached, but don't touch thumbnails or squid
621 function purgeMetadataCache() {
623 $this->saveToCache();
624 $this->purgeHistory();
628 * Purge the shared history (OldLocalFile) cache
630 function purgeHistory() {
633 $hashedName = md5( $this->getName() );
634 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
637 $wgMemc->delete( $oldKey );
642 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
644 function purgeCache() {
645 // Refresh metadata cache
646 $this->purgeMetadataCache();
649 $this->purgeThumbnails();
651 // Purge squid cache for this file
652 SquidUpdate::purge( array( $this->getURL() ) );
656 * Delete cached transformed files
658 function purgeThumbnails() {
662 $files = $this->getThumbnails();
663 $dir = $this->getThumbPath();
666 foreach ( $files as $file ) {
667 # Check that the base file name is part of the thumb name
668 # This is a basic sanity check to avoid erasing unrelated directories
669 if ( strpos( $file, $this->getName() ) !== false ) {
670 $url = $this->getThumbUrl( $file );
672 @unlink( "$dir/$file" );
678 SquidUpdate::purge( $urls );
682 /** purgeDescription inherited */
683 /** purgeEverything inherited */
685 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
686 $dbr = $this->repo->getSlaveDB();
687 $tables = array( 'oldimage' );
688 $fields = OldLocalFile::selectFields();
689 $conds = $opts = $join_conds = array();
690 $eq = $inc ? '=' : '';
691 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() );
694 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
698 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
702 $opts['LIMIT'] = $limit;
705 // Search backwards for time > x queries
706 $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC';
707 $opts['ORDER BY'] = "oi_timestamp $order";
708 $opts['USE INDEX'] = array( 'oldimage' => 'oi_name_timestamp' );
710 wfRunHooks( 'LocalFile::getHistory', array( &$this, &$tables, &$fields,
711 &$conds, &$opts, &$join_conds ) );
713 $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds );
716 foreach ( $res as $row ) {
717 if ( $this->repo->oldFileFromRowFactory ) {
718 $r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
720 $r[] = OldLocalFile::newFromRow( $row, $this->repo );
724 if ( $order == 'ASC' ) {
725 $r = array_reverse( $r ); // make sure it ends up descending
732 * Return the history of this file, line by line.
733 * starts with current version, then old versions.
734 * uses $this->historyLine to check which line to return:
735 * 0 return line for current version
736 * 1 query for old versions, return first one
737 * 2, ... return next old version from above query
739 public function nextHistoryLine() {
740 # Polymorphic function name to distinguish foreign and local fetches
741 $fname = get_class( $this ) . '::' . __FUNCTION__;
743 $dbr = $this->repo->getSlaveDB();
745 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
746 $this->historyRes = $dbr->select( 'image',
749 "'' AS oi_archive_name",
753 array( 'img_name' => $this->title->getDBkey() ),
757 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
758 $this->historyRes = null;
761 } elseif ( $this->historyLine == 1 ) {
762 $this->historyRes = $dbr->select( 'oldimage', '*',
763 array( 'oi_name' => $this->title->getDBkey() ),
765 array( 'ORDER BY' => 'oi_timestamp DESC' )
768 $this->historyLine ++;
770 return $dbr->fetchObject( $this->historyRes );
774 * Reset the history pointer to the first element of the history
776 public function resetHistory() {
777 $this->historyLine = 0;
779 if ( !is_null( $this->historyRes ) ) {
780 $this->historyRes = null;
784 /** getFullPath inherited */
785 /** getHashPath inherited */
786 /** getRel inherited */
787 /** getUrlRel inherited */
788 /** getArchiveRel inherited */
789 /** getThumbRel inherited */
790 /** getArchivePath inherited */
791 /** getThumbPath inherited */
792 /** getArchiveUrl inherited */
793 /** getThumbUrl inherited */
794 /** getArchiveVirtualUrl inherited */
795 /** getThumbVirtualUrl inherited */
796 /** isHashed inherited */
799 * Upload a file and record it in the DB
800 * @param $srcPath String: source path or virtual URL
801 * @param $comment String: upload description
802 * @param $pageText String: text to use for the new description page,
803 * if a new description page is created
804 * @param $flags Integer: flags for publish()
805 * @param $props Array: File properties, if known. This can be used to reduce the
806 * upload time when uploading virtual URLs for which the file info
808 * @param $timestamp String: timestamp for img_timestamp, or false to use the current time
809 * @param $user Mixed: User object or null to use $wgUser
811 * @return FileRepoStatus object. On success, the value member contains the
812 * archive name, or an empty string if it was a new file.
814 function upload( $srcPath, $comment, $pageText, $flags = 0, $props = false, $timestamp = false, $user = null ) {
816 $status = $this->publish( $srcPath, $flags );
819 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
820 $status->fatal( 'filenotfound', $srcPath );
830 * Record a file upload in the upload log and the image table
831 * @deprecated use upload()
833 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
834 $watch = false, $timestamp = false )
836 $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source );
838 if ( !$this->recordUpload2( $oldver, $desc, $pageText ) ) {
844 $wgUser->addWatch( $this->getTitle() );
851 * Record a file upload in the upload log and the image table
853 function recordUpload2(
854 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null
856 if ( is_null( $user ) ) {
861 $dbw = $this->repo->getMasterDB();
865 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
868 if ( $timestamp === false ) {
869 $timestamp = $dbw->timestamp();
872 $props['description'] = $comment;
873 $props['user'] = $user->getId();
874 $props['user_text'] = $user->getName();
875 $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW
876 $this->setProps( $props );
879 $this->purgeThumbnails();
881 # The file is already on its final location, remove it from the squid cache
882 SquidUpdate::purge( array( $this->getURL() ) );
884 # Fail now if the file isn't there
885 if ( !$this->fileExists ) {
886 wfDebug( __METHOD__ . ": File " . $this->getPath() . " went missing!\n" );
892 # Test to see if the row exists using INSERT IGNORE
893 # This avoids race conditions by locking the row until the commit, and also
894 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
895 $dbw->insert( 'image',
897 'img_name' => $this->getName(),
898 'img_size' => $this->size,
899 'img_width' => intval( $this->width ),
900 'img_height' => intval( $this->height ),
901 'img_bits' => $this->bits,
902 'img_media_type' => $this->media_type,
903 'img_major_mime' => $this->major_mime,
904 'img_minor_mime' => $this->minor_mime,
905 'img_timestamp' => $timestamp,
906 'img_description' => $comment,
907 'img_user' => $user->getId(),
908 'img_user_text' => $user->getName(),
909 'img_metadata' => $this->metadata,
910 'img_sha1' => $this->sha1
916 if ( $dbw->affectedRows() == 0 ) {
919 # Collision, this is an update of a file
920 # Insert previous contents into oldimage
921 $dbw->insertSelect( 'oldimage', 'image',
923 'oi_name' => 'img_name',
924 'oi_archive_name' => $dbw->addQuotes( $oldver ),
925 'oi_size' => 'img_size',
926 'oi_width' => 'img_width',
927 'oi_height' => 'img_height',
928 'oi_bits' => 'img_bits',
929 'oi_timestamp' => 'img_timestamp',
930 'oi_description' => 'img_description',
931 'oi_user' => 'img_user',
932 'oi_user_text' => 'img_user_text',
933 'oi_metadata' => 'img_metadata',
934 'oi_media_type' => 'img_media_type',
935 'oi_major_mime' => 'img_major_mime',
936 'oi_minor_mime' => 'img_minor_mime',
937 'oi_sha1' => 'img_sha1'
938 ), array( 'img_name' => $this->getName() ), __METHOD__
941 # Update the current image row
942 $dbw->update( 'image',
944 'img_size' => $this->size,
945 'img_width' => intval( $this->width ),
946 'img_height' => intval( $this->height ),
947 'img_bits' => $this->bits,
948 'img_media_type' => $this->media_type,
949 'img_major_mime' => $this->major_mime,
950 'img_minor_mime' => $this->minor_mime,
951 'img_timestamp' => $timestamp,
952 'img_description' => $comment,
953 'img_user' => $user->getId(),
954 'img_user_text' => $user->getName(),
955 'img_metadata' => $this->metadata,
956 'img_sha1' => $this->sha1
957 ), array( /* WHERE */
958 'img_name' => $this->getName()
963 # Update the image count
964 $site_stats = $dbw->tableName( 'site_stats' );
965 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
968 $descTitle = $this->getTitle();
969 $article = new ImagePage( $descTitle );
970 $article->setFile( $this );
973 $log = new LogPage( 'upload' );
974 $action = $reupload ? 'overwrite' : 'upload';
975 $log->addEntry( $action, $descTitle, $comment, array(), $user );
977 if ( $descTitle->exists() ) {
978 # Create a null revision
979 $latest = $descTitle->getLatestRevID();
980 $nullRevision = Revision::newNullRevision(
982 $descTitle->getArticleId(),
983 $log->getRcComment(),
986 $nullRevision->insertOn( $dbw );
988 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
989 $article->updateRevisionOn( $dbw, $nullRevision );
991 # Invalidate the cache for the description page
992 $descTitle->invalidateCache();
993 $descTitle->purgeSquid();
995 # New file; create the description page.
996 # There's already a log entry, so don't make a second RC entry
997 # Squid and file cache for the description page are purged by doEdit.
998 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
1001 # Commit the transaction now, in case something goes wrong later
1002 # The most important thing is that files don't get lost, especially archives
1005 # Save to cache and purge the squid
1006 # We shall not saveToCache before the commit since otherwise
1007 # in case of a rollback there is an usable file from memcached
1008 # which in fact doesn't really exist (bug 24978)
1009 $this->saveToCache();
1011 # Hooks, hooks, the magic of hooks...
1012 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1014 # Invalidate cache for all pages using this file
1015 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1016 $update->doUpdate();
1018 # Invalidate cache for all pages that redirects on this page
1019 $redirs = $this->getTitle()->getRedirectsHere();
1021 foreach ( $redirs as $redir ) {
1022 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1023 $update->doUpdate();
1030 * Move or copy a file to its public location. If a file exists at the
1031 * destination, move it to an archive. Returns a FileRepoStatus object with
1032 * the archive name in the "value" member on success.
1034 * The archive name should be passed through to recordUpload for database
1037 * @param $srcPath String: local filesystem path to the source image
1038 * @param $flags Integer: a bitwise combination of:
1039 * File::DELETE_SOURCE Delete the source file, i.e. move
1041 * @return FileRepoStatus object. On success, the value member contains the
1042 * archive name, or an empty string if it was a new file.
1044 function publish( $srcPath, $flags = 0 ) {
1047 $dstRel = $this->getRel();
1048 $archiveName = gmdate( 'YmdHis' ) . '!' . $this->getName();
1049 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1050 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1051 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
1053 if ( $status->value == 'new' ) {
1054 $status->value = '';
1056 $status->value = $archiveName;
1064 /** getLinksTo inherited */
1065 /** getExifData inherited */
1066 /** isLocal inherited */
1067 /** wasDeleted inherited */
1070 * Move file to the new title
1072 * Move current, old version and all thumbnails
1073 * to the new filename. Old file is deleted.
1075 * Cache purging is done; checks for validity
1076 * and logging are caller's responsibility
1078 * @param $target Title New file name
1079 * @return FileRepoStatus object.
1081 function move( $target ) {
1082 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1085 $batch = new LocalFileMoveBatch( $this, $target );
1086 $batch->addCurrent();
1089 $status = $batch->execute();
1090 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1092 $this->purgeEverything();
1095 if ( $status->isOk() ) {
1096 // Now switch the object
1097 $this->title = $target;
1098 // Force regeneration of the name and hashpath
1099 unset( $this->name );
1100 unset( $this->hashPath );
1101 // Purge the new image
1102 $this->purgeEverything();
1109 * Delete all versions of the file.
1111 * Moves the files into an archive directory (or deletes them)
1112 * and removes the database rows.
1114 * Cache purging is done; logging is caller's responsibility.
1118 * @return FileRepoStatus object.
1120 function delete( $reason, $suppress = false ) {
1123 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1124 $batch->addCurrent();
1126 # Get old version relative paths
1127 $dbw = $this->repo->getMasterDB();
1128 $result = $dbw->select( 'oldimage',
1129 array( 'oi_archive_name' ),
1130 array( 'oi_name' => $this->getName() ) );
1131 foreach ( $result as $row ) {
1132 $batch->addOld( $row->oi_archive_name );
1134 $status = $batch->execute();
1136 if ( $status->ok ) {
1137 // Update site_stats
1138 $site_stats = $dbw->tableName( 'site_stats' );
1139 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1140 $this->purgeEverything();
1149 * Delete an old version of the file.
1151 * Moves the file into an archive directory (or deletes it)
1152 * and removes the database row.
1154 * Cache purging is done; logging is caller's responsibility.
1156 * @param $archiveName String
1157 * @param $reason String
1158 * @param $suppress Boolean
1159 * @throws MWException or FSException on database or file store failure
1160 * @return FileRepoStatus object.
1162 function deleteOld( $archiveName, $reason, $suppress = false ) {
1165 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1166 $batch->addOld( $archiveName );
1167 $status = $batch->execute();
1171 if ( $status->ok ) {
1172 $this->purgeDescription();
1173 $this->purgeHistory();
1180 * Restore all or specified deleted revisions to the given file.
1181 * Permissions and logging are left to the caller.
1183 * May throw database exceptions on error.
1185 * @param $versions set of record ids of deleted items to restore,
1186 * or empty to restore all revisions.
1187 * @param $unsuppress Boolean
1188 * @return FileRepoStatus
1190 function restore( $versions = array(), $unsuppress = false ) {
1191 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1196 $batch->addIds( $versions );
1199 $status = $batch->execute();
1201 if ( !$status->ok ) {
1205 $cleanupStatus = $batch->cleanup();
1206 $cleanupStatus->successCount = 0;
1207 $cleanupStatus->failCount = 0;
1208 $status->merge( $cleanupStatus );
1213 /** isMultipage inherited */
1214 /** pageCount inherited */
1215 /** scaleHeight inherited */
1216 /** getImageSize inherited */
1219 * Get the URL of the file description page.
1221 function getDescriptionUrl() {
1222 return $this->title->getLocalUrl();
1226 * Get the HTML text of the description page
1227 * This is not used by ImagePage for local files, since (among other things)
1228 * it skips the parser cache.
1230 function getDescriptionText() {
1232 $revision = Revision::newFromTitle( $this->title );
1233 if ( !$revision ) return false;
1234 $text = $revision->getText();
1235 if ( !$text ) return false;
1236 $pout = $wgParser->parse( $text, $this->title, new ParserOptions() );
1237 return $pout->getText();
1240 function getDescription() {
1242 return $this->description;
1245 function getTimestamp() {
1247 return $this->timestamp;
1250 function getSha1() {
1252 // Initialise now if necessary
1253 if ( $this->sha1 == '' && $this->fileExists ) {
1254 $this->sha1 = File::sha1Base36( $this->getPath() );
1255 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1256 $dbw = $this->repo->getMasterDB();
1257 $dbw->update( 'image',
1258 array( 'img_sha1' => $this->sha1 ),
1259 array( 'img_name' => $this->getName() ),
1261 $this->saveToCache();
1269 * Start a transaction and lock the image for update
1270 * Increments a reference counter if the lock is already held
1271 * @return boolean True if the image exists, false otherwise
1274 $dbw = $this->repo->getMasterDB();
1276 if ( !$this->locked ) {
1281 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1285 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1286 * the transaction and thereby releases the image lock.
1289 if ( $this->locked ) {
1291 if ( !$this->locked ) {
1292 $dbw = $this->repo->getMasterDB();
1299 * Roll back the DB transaction and mark the image unlocked
1301 function unlockAndRollback() {
1302 $this->locked = false;
1303 $dbw = $this->repo->getMasterDB();
1306 } // LocalFile class
1308 # ------------------------------------------------------------------------------
1311 * Helper class for file deletion
1314 class LocalFileDeleteBatch {
1315 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1318 function __construct( File $file, $reason = '', $suppress = false ) {
1319 $this->file = $file;
1320 $this->reason = $reason;
1321 $this->suppress = $suppress;
1322 $this->status = $file->repo->newGood();
1325 function addCurrent() {
1326 $this->srcRels['.'] = $this->file->getRel();
1329 function addOld( $oldName ) {
1330 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1331 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1334 function getOldRels() {
1335 if ( !isset( $this->srcRels['.'] ) ) {
1336 $oldRels =& $this->srcRels;
1337 $deleteCurrent = false;
1339 $oldRels = $this->srcRels;
1340 unset( $oldRels['.'] );
1341 $deleteCurrent = true;
1344 return array( $oldRels, $deleteCurrent );
1347 /*protected*/ function getHashes() {
1349 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1351 if ( $deleteCurrent ) {
1352 $hashes['.'] = $this->file->getSha1();
1355 if ( count( $oldRels ) ) {
1356 $dbw = $this->file->repo->getMasterDB();
1357 $res = $dbw->select(
1359 array( 'oi_archive_name', 'oi_sha1' ),
1360 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1364 foreach ( $res as $row ) {
1365 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1366 // Get the hash from the file
1367 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1368 $props = $this->file->repo->getFileProps( $oldUrl );
1370 if ( $props['fileExists'] ) {
1371 // Upgrade the oldimage row
1372 $dbw->update( 'oldimage',
1373 array( 'oi_sha1' => $props['sha1'] ),
1374 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1376 $hashes[$row->oi_archive_name] = $props['sha1'];
1378 $hashes[$row->oi_archive_name] = false;
1381 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1386 $missing = array_diff_key( $this->srcRels, $hashes );
1388 foreach ( $missing as $name => $rel ) {
1389 $this->status->error( 'filedelete-old-unregistered', $name );
1392 foreach ( $hashes as $name => $hash ) {
1394 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1395 unset( $hashes[$name] );
1402 function doDBInserts() {
1405 $dbw = $this->file->repo->getMasterDB();
1406 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1407 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1408 $encReason = $dbw->addQuotes( $this->reason );
1409 $encGroup = $dbw->addQuotes( 'deleted' );
1410 $ext = $this->file->getExtension();
1411 $dotExt = $ext === '' ? '' : ".$ext";
1412 $encExt = $dbw->addQuotes( $dotExt );
1413 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1415 // Bitfields to further suppress the content
1416 if ( $this->suppress ) {
1418 // This should be 15...
1419 $bitfield |= Revision::DELETED_TEXT;
1420 $bitfield |= Revision::DELETED_COMMENT;
1421 $bitfield |= Revision::DELETED_USER;
1422 $bitfield |= Revision::DELETED_RESTRICTED;
1424 $bitfield = 'oi_deleted';
1427 if ( $deleteCurrent ) {
1428 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1429 $where = array( 'img_name' => $this->file->getName() );
1430 $dbw->insertSelect( 'filearchive', 'image',
1432 'fa_storage_group' => $encGroup,
1433 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1434 'fa_deleted_user' => $encUserId,
1435 'fa_deleted_timestamp' => $encTimestamp,
1436 'fa_deleted_reason' => $encReason,
1437 'fa_deleted' => $this->suppress ? $bitfield : 0,
1439 'fa_name' => 'img_name',
1440 'fa_archive_name' => 'NULL',
1441 'fa_size' => 'img_size',
1442 'fa_width' => 'img_width',
1443 'fa_height' => 'img_height',
1444 'fa_metadata' => 'img_metadata',
1445 'fa_bits' => 'img_bits',
1446 'fa_media_type' => 'img_media_type',
1447 'fa_major_mime' => 'img_major_mime',
1448 'fa_minor_mime' => 'img_minor_mime',
1449 'fa_description' => 'img_description',
1450 'fa_user' => 'img_user',
1451 'fa_user_text' => 'img_user_text',
1452 'fa_timestamp' => 'img_timestamp'
1453 ), $where, __METHOD__ );
1456 if ( count( $oldRels ) ) {
1457 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1459 'oi_name' => $this->file->getName(),
1460 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1461 $dbw->insertSelect( 'filearchive', 'oldimage',
1463 'fa_storage_group' => $encGroup,
1464 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1465 'fa_deleted_user' => $encUserId,
1466 'fa_deleted_timestamp' => $encTimestamp,
1467 'fa_deleted_reason' => $encReason,
1468 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1470 'fa_name' => 'oi_name',
1471 'fa_archive_name' => 'oi_archive_name',
1472 'fa_size' => 'oi_size',
1473 'fa_width' => 'oi_width',
1474 'fa_height' => 'oi_height',
1475 'fa_metadata' => 'oi_metadata',
1476 'fa_bits' => 'oi_bits',
1477 'fa_media_type' => 'oi_media_type',
1478 'fa_major_mime' => 'oi_major_mime',
1479 'fa_minor_mime' => 'oi_minor_mime',
1480 'fa_description' => 'oi_description',
1481 'fa_user' => 'oi_user',
1482 'fa_user_text' => 'oi_user_text',
1483 'fa_timestamp' => 'oi_timestamp',
1484 'fa_deleted' => $bitfield
1485 ), $where, __METHOD__ );
1489 function doDBDeletes() {
1490 $dbw = $this->file->repo->getMasterDB();
1491 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1493 if ( count( $oldRels ) ) {
1494 $dbw->delete( 'oldimage',
1496 'oi_name' => $this->file->getName(),
1497 'oi_archive_name' => array_keys( $oldRels )
1501 if ( $deleteCurrent ) {
1502 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1507 * Run the transaction
1509 function execute() {
1511 wfProfileIn( __METHOD__ );
1513 $this->file->lock();
1514 // Leave private files alone
1515 $privateFiles = array();
1516 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1517 $dbw = $this->file->repo->getMasterDB();
1519 if ( !empty( $oldRels ) ) {
1520 $res = $dbw->select( 'oldimage',
1521 array( 'oi_archive_name' ),
1522 array( 'oi_name' => $this->file->getName(),
1523 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1524 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
1527 foreach ( $res as $row ) {
1528 $privateFiles[$row->oi_archive_name] = 1;
1531 // Prepare deletion batch
1532 $hashes = $this->getHashes();
1533 $this->deletionBatch = array();
1534 $ext = $this->file->getExtension();
1535 $dotExt = $ext === '' ? '' : ".$ext";
1537 foreach ( $this->srcRels as $name => $srcRel ) {
1538 // Skip files that have no hash (missing source).
1539 // Keep private files where they are.
1540 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1541 $hash = $hashes[$name];
1542 $key = $hash . $dotExt;
1543 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1544 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1548 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1549 // We acquire this lock by running the inserts now, before the file operations.
1551 // This potentially has poor lock contention characteristics -- an alternative
1552 // scheme would be to insert stub filearchive entries with no fa_name and commit
1553 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1554 $this->doDBInserts();
1556 // Removes non-existent file from the batch, so we don't get errors.
1557 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
1559 // Execute the file deletion batch
1560 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1562 if ( !$status->isGood() ) {
1563 $this->status->merge( $status );
1566 if ( !$this->status->ok ) {
1567 // Critical file deletion error
1568 // Roll back inserts, release lock and abort
1569 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1570 $this->file->unlockAndRollback();
1571 wfProfileOut( __METHOD__ );
1572 return $this->status;
1576 if ( $wgUseSquid ) {
1579 foreach ( $this->srcRels as $srcRel ) {
1580 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1581 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1583 SquidUpdate::purge( $urls );
1586 // Delete image/oldimage rows
1587 $this->doDBDeletes();
1589 // Commit and return
1590 $this->file->unlock();
1591 wfProfileOut( __METHOD__ );
1593 return $this->status;
1597 * Removes non-existent files from a deletion batch.
1599 function removeNonexistentFiles( $batch ) {
1600 $files = $newBatch = array();
1602 foreach ( $batch as $batchItem ) {
1603 list( $src, $dest ) = $batchItem;
1604 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1607 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1609 foreach ( $batch as $batchItem ) {
1610 if ( $result[$batchItem[0]] ) {
1611 $newBatch[] = $batchItem;
1619 # ------------------------------------------------------------------------------
1622 * Helper class for file undeletion
1625 class LocalFileRestoreBatch {
1626 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1628 function __construct( File $file, $unsuppress = false ) {
1629 $this->file = $file;
1630 $this->cleanupBatch = $this->ids = array();
1631 $this->ids = array();
1632 $this->unsuppress = $unsuppress;
1638 function addId( $fa_id ) {
1639 $this->ids[] = $fa_id;
1643 * Add a whole lot of files by ID
1645 function addIds( $ids ) {
1646 $this->ids = array_merge( $this->ids, $ids );
1650 * Add all revisions of the file
1657 * Run the transaction, except the cleanup batch.
1658 * The cleanup batch should be run in a separate transaction, because it locks different
1659 * rows and there's no need to keep the image row locked while it's acquiring those locks
1660 * The caller may have its own transaction open.
1661 * So we save the batch and let the caller call cleanup()
1663 function execute() {
1666 if ( !$this->all && !$this->ids ) {
1668 return $this->file->repo->newGood();
1671 $exists = $this->file->lock();
1672 $dbw = $this->file->repo->getMasterDB();
1673 $status = $this->file->repo->newGood();
1675 // Fetch all or selected archived revisions for the file,
1676 // sorted from the most recent to the oldest.
1677 $conditions = array( 'fa_name' => $this->file->getName() );
1679 if ( !$this->all ) {
1680 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1683 $result = $dbw->select( 'filearchive', '*',
1686 array( 'ORDER BY' => 'fa_timestamp DESC' )
1689 $idsPresent = array();
1690 $storeBatch = array();
1691 $insertBatch = array();
1692 $insertCurrent = false;
1693 $deleteIds = array();
1695 $archiveNames = array();
1697 foreach ( $result as $row ) {
1698 $idsPresent[] = $row->fa_id;
1700 if ( $row->fa_name != $this->file->getName() ) {
1701 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1702 $status->failCount++;
1706 if ( $row->fa_storage_key == '' ) {
1707 // Revision was missing pre-deletion
1708 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1709 $status->failCount++;
1713 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1714 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1716 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1719 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1720 $sha1 = substr( $sha1, 1 );
1723 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1724 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1725 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1726 || is_null( $row->fa_metadata ) ) {
1727 // Refresh our metadata
1728 // Required for a new current revision; nice for older ones too. :)
1729 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1732 'minor_mime' => $row->fa_minor_mime,
1733 'major_mime' => $row->fa_major_mime,
1734 'media_type' => $row->fa_media_type,
1735 'metadata' => $row->fa_metadata
1739 if ( $first && !$exists ) {
1740 // This revision will be published as the new current version
1741 $destRel = $this->file->getRel();
1742 $insertCurrent = array(
1743 'img_name' => $row->fa_name,
1744 'img_size' => $row->fa_size,
1745 'img_width' => $row->fa_width,
1746 'img_height' => $row->fa_height,
1747 'img_metadata' => $props['metadata'],
1748 'img_bits' => $row->fa_bits,
1749 'img_media_type' => $props['media_type'],
1750 'img_major_mime' => $props['major_mime'],
1751 'img_minor_mime' => $props['minor_mime'],
1752 'img_description' => $row->fa_description,
1753 'img_user' => $row->fa_user,
1754 'img_user_text' => $row->fa_user_text,
1755 'img_timestamp' => $row->fa_timestamp,
1759 // The live (current) version cannot be hidden!
1760 if ( !$this->unsuppress && $row->fa_deleted ) {
1761 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1762 $this->cleanupBatch[] = $row->fa_storage_key;
1765 $archiveName = $row->fa_archive_name;
1767 if ( $archiveName == '' ) {
1768 // This was originally a current version; we
1769 // have to devise a new archive name for it.
1770 // Format is <timestamp of archiving>!<name>
1771 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1774 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1776 } while ( isset( $archiveNames[$archiveName] ) );
1779 $archiveNames[$archiveName] = true;
1780 $destRel = $this->file->getArchiveRel( $archiveName );
1781 $insertBatch[] = array(
1782 'oi_name' => $row->fa_name,
1783 'oi_archive_name' => $archiveName,
1784 'oi_size' => $row->fa_size,
1785 'oi_width' => $row->fa_width,
1786 'oi_height' => $row->fa_height,
1787 'oi_bits' => $row->fa_bits,
1788 'oi_description' => $row->fa_description,
1789 'oi_user' => $row->fa_user,
1790 'oi_user_text' => $row->fa_user_text,
1791 'oi_timestamp' => $row->fa_timestamp,
1792 'oi_metadata' => $props['metadata'],
1793 'oi_media_type' => $props['media_type'],
1794 'oi_major_mime' => $props['major_mime'],
1795 'oi_minor_mime' => $props['minor_mime'],
1796 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
1797 'oi_sha1' => $sha1 );
1800 $deleteIds[] = $row->fa_id;
1802 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
1803 // private files can stay where they are
1804 $status->successCount++;
1806 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1807 $this->cleanupBatch[] = $row->fa_storage_key;
1815 // Add a warning to the status object for missing IDs
1816 $missingIds = array_diff( $this->ids, $idsPresent );
1818 foreach ( $missingIds as $id ) {
1819 $status->error( 'undelete-missing-filearchive', $id );
1822 // Remove missing files from batch, so we don't get errors when undeleting them
1823 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1825 // Run the store batch
1826 // Use the OVERWRITE_SAME flag to smooth over a common error
1827 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1828 $status->merge( $storeStatus );
1830 if ( !$status->ok ) {
1831 // Store batch returned a critical error -- this usually means nothing was stored
1832 // Stop now and return an error
1833 $this->file->unlock();
1838 // Run the DB updates
1839 // Because we have locked the image row, key conflicts should be rare.
1840 // If they do occur, we can roll back the transaction at this time with
1841 // no data loss, but leaving unregistered files scattered throughout the
1843 // This is not ideal, which is why it's important to lock the image row.
1844 if ( $insertCurrent ) {
1845 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1848 if ( $insertBatch ) {
1849 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1853 $dbw->delete( 'filearchive',
1854 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1858 // If store batch is empty (all files are missing), deletion is to be considered successful
1859 if ( $status->successCount > 0 || !$storeBatch ) {
1861 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
1863 // Update site_stats
1864 $site_stats = $dbw->tableName( 'site_stats' );
1865 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1867 $this->file->purgeEverything();
1869 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
1870 $this->file->purgeDescription();
1871 $this->file->purgeHistory();
1875 $this->file->unlock();
1881 * Removes non-existent files from a store batch.
1883 function removeNonexistentFiles( $triplets ) {
1884 $files = $filteredTriplets = array();
1885 foreach ( $triplets as $file )
1886 $files[$file[0]] = $file[0];
1888 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1890 foreach ( $triplets as $file ) {
1891 if ( $result[$file[0]] ) {
1892 $filteredTriplets[] = $file;
1896 return $filteredTriplets;
1900 * Removes non-existent files from a cleanup batch.
1902 function removeNonexistentFromCleanup( $batch ) {
1903 $files = $newBatch = array();
1904 $repo = $this->file->repo;
1906 foreach ( $batch as $file ) {
1907 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1908 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1911 $result = $repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1913 foreach ( $batch as $file ) {
1914 if ( $result[$file] ) {
1915 $newBatch[] = $file;
1923 * Delete unused files in the deleted zone.
1924 * This should be called from outside the transaction in which execute() was called.
1926 function cleanup() {
1927 if ( !$this->cleanupBatch ) {
1928 return $this->file->repo->newGood();
1931 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
1933 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
1939 # ------------------------------------------------------------------------------
1942 * Helper class for file movement
1945 class LocalFileMoveBatch {
1946 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1948 function __construct( File $file, Title $target ) {
1949 $this->file = $file;
1950 $this->target = $target;
1951 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
1952 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
1953 $this->oldName = $this->file->getName();
1954 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
1955 $this->oldRel = $this->oldHash . $this->oldName;
1956 $this->newRel = $this->newHash . $this->newName;
1957 $this->db = $file->repo->getMasterDb();
1961 * Add the current image to the batch
1963 function addCurrent() {
1964 $this->cur = array( $this->oldRel, $this->newRel );
1968 * Add the old versions of the image to the batch
1970 function addOlds() {
1971 $archiveBase = 'archive';
1972 $this->olds = array();
1973 $this->oldCount = 0;
1975 $result = $this->db->select( 'oldimage',
1976 array( 'oi_archive_name', 'oi_deleted' ),
1977 array( 'oi_name' => $this->oldName ),
1981 foreach ( $result as $row ) {
1982 $oldName = $row->oi_archive_name;
1983 $bits = explode( '!', $oldName, 2 );
1985 if ( count( $bits ) != 2 ) {
1986 wfDebug( "Invalid old file name: $oldName \n" );
1990 list( $timestamp, $filename ) = $bits;
1992 if ( $this->oldName != $filename ) {
1993 wfDebug( "Invalid old file name: $oldName \n" );
1999 // Do we want to add those to oldCount?
2000 if ( $row->oi_deleted & File::DELETED_FILE ) {
2004 $this->olds[] = array(
2005 "{$archiveBase}/{$this->oldHash}{$oldName}",
2006 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2014 function execute() {
2015 $repo = $this->file->repo;
2016 $status = $repo->newGood();
2017 $triplets = $this->getMoveTriplets();
2019 $triplets = $this->removeNonexistentFiles( $triplets );
2020 $statusDb = $this->doDBUpdates();
2021 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2022 $statusMove = $repo->storeBatch( $triplets, FSRepo::DELETE_SOURCE );
2023 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2025 if ( !$statusMove->isOk() ) {
2026 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2027 $this->db->rollback();
2030 $status->merge( $statusDb );
2031 $status->merge( $statusMove );
2037 * Do the database updates and return a new FileRepoStatus indicating how
2038 * many rows where updated.
2040 * @return FileRepoStatus
2042 function doDBUpdates() {
2043 $repo = $this->file->repo;
2044 $status = $repo->newGood();
2047 // Update current image
2050 array( 'img_name' => $this->newName ),
2051 array( 'img_name' => $this->oldName ),
2055 if ( $dbw->affectedRows() ) {
2056 $status->successCount++;
2058 $status->failCount++;
2061 // Update old images
2065 'oi_name' => $this->newName,
2066 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2068 array( 'oi_name' => $this->oldName ),
2072 $affected = $dbw->affectedRows();
2073 $total = $this->oldCount;
2074 $status->successCount += $affected;
2075 $status->failCount += $total - $affected;
2081 * Generate triplets for FSRepo::storeBatch().
2083 function getMoveTriplets() {
2084 $moves = array_merge( array( $this->cur ), $this->olds );
2085 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2087 foreach ( $moves as $move ) {
2088 // $move: (oldRelativePath, newRelativePath)
2089 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2090 $triplets[] = array( $srcUrl, 'public', $move[1] );
2091 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2098 * Removes non-existent files from move batch.
2100 function removeNonexistentFiles( $triplets ) {
2103 foreach ( $triplets as $file ) {
2104 $files[$file[0]] = $file[0];
2107 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
2108 $filteredTriplets = array();
2110 foreach ( $triplets as $file ) {
2111 if ( $result[$file[0]] ) {
2112 $filteredTriplets[] = $file;
2114 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2118 return $filteredTriplets;