Fix whitespace
[mediawiki.git] / includes / filerepo / LocalFile.php
blob3ce2415867671f8938de476e7cc046596387fb2a
1 <?php
2 /**
3 * Local file in the wiki's own database
5 * @file
6 * @ingroup FileRepo
7 */
9 /**
10 * Bump this number when serialized cache records may be incompatible.
12 define( 'MW_FILE_VERSION', 8 );
14 /**
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
27 * in most cases.
29 * @ingroup FileRepo
31 class LocalFile extends File {
32 /**#@+
33 * @private
35 var
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)
39 $width, # \
40 $height, # |
41 $bits, # --- returned by getimagesize (loadFromXxx)
42 $attr, # /
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
59 /**#@-*/
61 /**
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 );
71 /**
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 );
80 return $file;
83 /**
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 );
90 if ( $timestamp ) {
91 $conds['img_timestamp'] = $timestamp;
94 $dbr = $repo->getSlaveDB();
95 $row = $dbr->selectRow( 'image', self::selectFields(), $conds, __METHOD__ );
97 if ( $row ) {
98 return self::newFromRow( $row, $repo );
99 } else {
100 return false;
105 * Fields in the image table
107 static function selectFields() {
108 return array(
109 'img_name',
110 'img_size',
111 'img_width',
112 'img_height',
113 'img_metadata',
114 'img_bits',
115 'img_media_type',
116 'img_major_mime',
117 'img_minor_mime',
118 'img_description',
119 'img_user',
120 'img_user_text',
121 'img_timestamp',
122 'img_sha1',
127 * Constructor.
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() {
157 global $wgMemc;
159 wfProfileIn( __METHOD__ );
160 $this->dataLoaded = false;
161 $key = $this->getCacheKey();
163 if ( !$key ) {
164 wfProfileOut( __METHOD__ );
165 return false;
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' );
182 } else {
183 wfIncrStats( 'image_cache_miss' );
186 wfProfileOut( __METHOD__ );
187 return $this->dataLoaded;
191 * Save the file metadata to memcached
193 function saveToCache() {
194 global $wgMemc;
196 $this->load();
197 $key = $this->getCacheKey();
199 if ( !$key ) {
200 return;
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 == '' ) {
229 return $fields;
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 );
259 if ( $row ) {
260 $this->loadFromRow( $row );
261 } else {
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' );
281 $decoded = array();
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';
291 } else {
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" );
301 return $decoded;
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
322 function load() {
323 if ( !$this->dataLoaded ) {
324 if ( !$this->loadFromCache() ) {
325 $this->loadFromDB();
326 $this->saveToCache();
328 $this->dataLoaded = true;
333 * Upgrade a row if it needs it
335 function maybeUpgradeRow() {
336 if ( wfReadOnly() ) {
337 return;
340 if ( is_null( $this->media_type ) ||
341 $this->mime == 'image/svg'
343 $this->upgradeRow();
344 $this->upgraded = true;
345 } else {
346 $handler = $this->getHandler();
347 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata ) ) {
348 $this->upgradeRow();
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__ );
370 return;
373 $dbw = $this->repo->getMasterDB();
374 list( $major, $minor ) = self::splitMime( $this->mime );
376 if ( wfReadOnly() ) {
377 wfProfileOut( __METHOD__ );
378 return;
380 wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" );
382 $dbw->update( 'image',
383 array(
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() ),
393 __METHOD__
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 ) {
449 $this->load();
451 if ( $this->isMultipage() ) {
452 $dim = $this->getHandler()->getPageDimensions( $this, $page );
453 if ( $dim ) {
454 return $dim['width'];
455 } else {
456 return false;
458 } else {
459 return $this->width;
464 * Return the height of the image
466 * Returns false on error
468 public function getHeight( $page = 1 ) {
469 $this->load();
471 if ( $this->isMultipage() ) {
472 $dim = $this->getHandler()->getPageDimensions( $this, $page );
473 if ( $dim ) {
474 return $dim['height'];
475 } else {
476 return false;
478 } else {
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' ) {
489 $this->load();
491 if ( $type == 'text' ) {
492 return $this->user_text;
493 } elseif ( $type == 'id' ) {
494 return $this->user;
499 * Get handler-specific metadata
501 function getMetadata() {
502 $this->load();
503 return $this->metadata;
506 function getBitDepth() {
507 $this->load();
508 return $this->bits;
512 * Return the size of the image file, in bytes
514 public function getSize() {
515 $this->load();
516 return $this->size;
520 * Returns the mime type of the file.
522 function getMimeType() {
523 $this->load();
524 return $this->mime;
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() {
532 $this->load();
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() {
547 $this->load();
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 );
573 break;
576 // Doesn't exist anymore
577 clearstatcache();
580 if ( is_file( $thumbDir ) ) {
581 // File where directory should be
582 unlink( $thumbDir );
583 // Doesn't exist anymore
584 clearstatcache();
588 /** getHandler inherited */
589 /** iconThumb inherited */
590 /** getLastError inherited */
593 * Get all thumbnail names previously generated for this file
595 function getThumbnails() {
596 $this->load();
598 $files = array();
599 $dir = $this->getThumbPath();
601 if ( is_dir( $dir ) ) {
602 $handle = opendir( $dir );
604 if ( $handle ) {
605 while ( false !== ( $file = readdir( $handle ) ) ) {
606 if ( $file { 0 } != '.' ) {
607 $files[] = $file;
611 closedir( $handle );
615 return $files;
619 * Refresh metadata in memcached, but don't touch thumbnails or squid
621 function purgeMetadataCache() {
622 $this->loadFromDB();
623 $this->saveToCache();
624 $this->purgeHistory();
628 * Purge the shared history (OldLocalFile) cache
630 function purgeHistory() {
631 global $wgMemc;
633 $hashedName = md5( $this->getName() );
634 $oldKey = $this->repo->getSharedCacheKey( 'oldfile', $hashedName );
636 if ( $oldKey ) {
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();
648 // Delete thumbnails
649 $this->purgeThumbnails();
651 // Purge squid cache for this file
652 SquidUpdate::purge( array( $this->getURL() ) );
656 * Delete cached transformed files
658 function purgeThumbnails() {
659 global $wgUseSquid;
661 // Delete thumbnails
662 $files = $this->getThumbnails();
663 $dir = $this->getThumbPath();
664 $urls = array();
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 );
671 $urls[] = $url;
672 @unlink( "$dir/$file" );
676 // Purge the squid
677 if ( $wgUseSquid ) {
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() );
693 if ( $start ) {
694 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
697 if ( $end ) {
698 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
701 if ( $limit ) {
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 );
714 $r = array();
716 while ( $row = $dbr->fetchObject( $res ) ) {
717 if ( $this->repo->oldFileFromRowFactory ) {
718 $r[] = call_user_func( $this->repo->oldFileFromRowFactory, $row, $this->repo );
719 } else {
720 $r[] = OldLocalFile::newFromRow( $row, $this->repo );
724 if ( $order == 'ASC' ) {
725 $r = array_reverse( $r ); // make sure it ends up descending
728 return $r;
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',
747 array(
748 '*',
749 "'' AS oi_archive_name",
750 '0 as oi_deleted',
751 'img_sha1'
753 array( 'img_name' => $this->title->getDBkey() ),
754 $fname
757 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
758 $this->historyRes = null;
759 return false;
761 } elseif ( $this->historyLine == 1 ) {
762 $this->historyRes = $dbr->select( 'oldimage', '*',
763 array( 'oi_name' => $this->title->getDBkey() ),
764 $fname,
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
807 * is already known
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 ) {
815 $this->lock();
816 $status = $this->publish( $srcPath, $flags );
818 if ( $status->ok ) {
819 if ( !$this->recordUpload2( $status->value, $comment, $pageText, $props, $timestamp, $user ) ) {
820 $status->fatal( 'filenotfound', $srcPath );
824 $this->unlock();
826 return $status;
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 ) ) {
839 return false;
842 if ( $watch ) {
843 global $wgUser;
844 $wgUser->addWatch( $this->getTitle() );
846 return true;
851 * Record a file upload in the upload log and the image table
853 function recordUpload2( $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null )
855 if ( is_null( $user ) ) {
856 global $wgUser;
857 $user = $wgUser;
860 $dbw = $this->repo->getMasterDB();
861 $dbw->begin();
863 if ( !$props ) {
864 $props = $this->repo->getFileProps( $this->getVirtualUrl() );
867 $props['description'] = $comment;
868 $props['user'] = $user->getId();
869 $props['user_text'] = $user->getName();
870 $props['timestamp'] = wfTimestamp( TS_MW );
871 $this->setProps( $props );
873 # Delete thumbnails
874 $this->purgeThumbnails();
876 # The file is already on its final location, remove it from the squid cache
877 SquidUpdate::purge( array( $this->getURL() ) );
879 # Fail now if the file isn't there
880 if ( !$this->fileExists ) {
881 wfDebug( __METHOD__ . ": File " . $this->getPath() . " went missing!\n" );
882 return false;
885 $reupload = false;
887 if ( $timestamp === false ) {
888 $timestamp = $dbw->timestamp();
891 # Test to see if the row exists using INSERT IGNORE
892 # This avoids race conditions by locking the row until the commit, and also
893 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
894 $dbw->insert( 'image',
895 array(
896 'img_name' => $this->getName(),
897 'img_size' => $this->size,
898 'img_width' => intval( $this->width ),
899 'img_height' => intval( $this->height ),
900 'img_bits' => $this->bits,
901 'img_media_type' => $this->media_type,
902 'img_major_mime' => $this->major_mime,
903 'img_minor_mime' => $this->minor_mime,
904 'img_timestamp' => $timestamp,
905 'img_description' => $comment,
906 'img_user' => $user->getId(),
907 'img_user_text' => $user->getName(),
908 'img_metadata' => $this->metadata,
909 'img_sha1' => $this->sha1
911 __METHOD__,
912 'IGNORE'
915 if ( $dbw->affectedRows() == 0 ) {
916 $reupload = true;
918 # Collision, this is an update of a file
919 # Insert previous contents into oldimage
920 $dbw->insertSelect( 'oldimage', 'image',
921 array(
922 'oi_name' => 'img_name',
923 'oi_archive_name' => $dbw->addQuotes( $oldver ),
924 'oi_size' => 'img_size',
925 'oi_width' => 'img_width',
926 'oi_height' => 'img_height',
927 'oi_bits' => 'img_bits',
928 'oi_timestamp' => 'img_timestamp',
929 'oi_description' => 'img_description',
930 'oi_user' => 'img_user',
931 'oi_user_text' => 'img_user_text',
932 'oi_metadata' => 'img_metadata',
933 'oi_media_type' => 'img_media_type',
934 'oi_major_mime' => 'img_major_mime',
935 'oi_minor_mime' => 'img_minor_mime',
936 'oi_sha1' => 'img_sha1'
937 ), array( 'img_name' => $this->getName() ), __METHOD__
940 # Update the current image row
941 $dbw->update( 'image',
942 array( /* SET */
943 'img_size' => $this->size,
944 'img_width' => intval( $this->width ),
945 'img_height' => intval( $this->height ),
946 'img_bits' => $this->bits,
947 'img_media_type' => $this->media_type,
948 'img_major_mime' => $this->major_mime,
949 'img_minor_mime' => $this->minor_mime,
950 'img_timestamp' => $timestamp,
951 'img_description' => $comment,
952 'img_user' => $user->getId(),
953 'img_user_text' => $user->getName(),
954 'img_metadata' => $this->metadata,
955 'img_sha1' => $this->sha1
956 ), array( /* WHERE */
957 'img_name' => $this->getName()
958 ), __METHOD__
960 } else {
961 # This is a new file
962 # Update the image count
963 $site_stats = $dbw->tableName( 'site_stats' );
964 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
967 $descTitle = $this->getTitle();
968 $article = new ImagePage( $descTitle );
969 $article->setFile( $this );
971 # Add the log entry
972 $log = new LogPage( 'upload' );
973 $action = $reupload ? 'overwrite' : 'upload';
974 $log->addEntry( $action, $descTitle, $comment, array(), $user );
976 if ( $descTitle->exists() ) {
977 # Create a null revision
978 $latest = $descTitle->getLatestRevID();
979 $nullRevision = Revision::newNullRevision(
980 $dbw,
981 $descTitle->getArticleId(),
982 $log->getRcComment(),
983 false
985 $nullRevision->insertOn( $dbw );
987 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $user ) );
988 $article->updateRevisionOn( $dbw, $nullRevision );
990 # Invalidate the cache for the description page
991 $descTitle->invalidateCache();
992 $descTitle->purgeSquid();
993 } else {
994 # New file; create the description page.
995 # There's already a log entry, so don't make a second RC entry
996 # Squid and file cache for the description page are purged by doEdit.
997 $article->doEdit( $pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC );
1000 # Commit the transaction now, in case something goes wrong later
1001 # The most important thing is that files don't get lost, especially archives
1002 $dbw->commit();
1004 # Save to cache and purge the squid
1005 # We shall not saveToCache before the commit since otherwise
1006 # in case of a rollback there is an usable file from memcached
1007 # which in fact doesn't really exist (bug 24978)
1008 $this->saveToCache();
1010 # Hooks, hooks, the magic of hooks...
1011 wfRunHooks( 'FileUpload', array( $this, $reupload, $descTitle->exists() ) );
1013 # Invalidate cache for all pages using this file
1014 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1015 $update->doUpdate();
1017 # Invalidate cache for all pages that redirects on this page
1018 $redirs = $this->getTitle()->getRedirectsHere();
1020 foreach ( $redirs as $redir ) {
1021 $update = new HTMLCacheUpdate( $redir, 'imagelinks' );
1022 $update->doUpdate();
1025 return true;
1029 * Move or copy a file to its public location. If a file exists at the
1030 * destination, move it to an archive. Returns a FileRepoStatus object with
1031 * the archive name in the "value" member on success.
1033 * The archive name should be passed through to recordUpload for database
1034 * registration.
1036 * @param $srcPath String: local filesystem path to the source image
1037 * @param $flags Integer: a bitwise combination of:
1038 * File::DELETE_SOURCE Delete the source file, i.e. move
1039 * rather than copy
1040 * @return FileRepoStatus object. On success, the value member contains the
1041 * archive name, or an empty string if it was a new file.
1043 function publish( $srcPath, $flags = 0 ) {
1044 $this->lock();
1046 $dstRel = $this->getRel();
1047 $archiveName = gmdate( 'YmdHis' ) . '!' . $this->getName();
1048 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1049 $flags = $flags & File::DELETE_SOURCE ? LocalRepo::DELETE_SOURCE : 0;
1050 $status = $this->repo->publish( $srcPath, $dstRel, $archiveRel, $flags );
1052 if ( $status->value == 'new' ) {
1053 $status->value = '';
1054 } else {
1055 $status->value = $archiveName;
1058 $this->unlock();
1060 return $status;
1063 /** getLinksTo inherited */
1064 /** getExifData inherited */
1065 /** isLocal inherited */
1066 /** wasDeleted inherited */
1069 * Move file to the new title
1071 * Move current, old version and all thumbnails
1072 * to the new filename. Old file is deleted.
1074 * Cache purging is done; checks for validity
1075 * and logging are caller's responsibility
1077 * @param $target Title New file name
1078 * @return FileRepoStatus object.
1080 function move( $target ) {
1081 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1082 $this->lock();
1084 $batch = new LocalFileMoveBatch( $this, $target );
1085 $batch->addCurrent();
1086 $batch->addOlds();
1088 $status = $batch->execute();
1089 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1091 $this->purgeEverything();
1092 $this->unlock();
1094 if ( $status->isOk() ) {
1095 // Now switch the object
1096 $this->title = $target;
1097 // Force regeneration of the name and hashpath
1098 unset( $this->name );
1099 unset( $this->hashPath );
1100 // Purge the new image
1101 $this->purgeEverything();
1104 return $status;
1108 * Delete all versions of the file.
1110 * Moves the files into an archive directory (or deletes them)
1111 * and removes the database rows.
1113 * Cache purging is done; logging is caller's responsibility.
1115 * @param $reason
1116 * @param $suppress
1117 * @return FileRepoStatus object.
1119 function delete( $reason, $suppress = false ) {
1120 $this->lock();
1122 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1123 $batch->addCurrent();
1125 # Get old version relative paths
1126 $dbw = $this->repo->getMasterDB();
1127 $result = $dbw->select( 'oldimage',
1128 array( 'oi_archive_name' ),
1129 array( 'oi_name' => $this->getName() ) );
1130 while ( $row = $dbw->fetchObject( $result ) ) {
1131 $batch->addOld( $row->oi_archive_name );
1133 $status = $batch->execute();
1135 if ( $status->ok ) {
1136 // Update site_stats
1137 $site_stats = $dbw->tableName( 'site_stats' );
1138 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1139 $this->purgeEverything();
1142 $this->unlock();
1144 return $status;
1148 * Delete an old version of the file.
1150 * Moves the file into an archive directory (or deletes it)
1151 * and removes the database row.
1153 * Cache purging is done; logging is caller's responsibility.
1155 * @param $archiveName String
1156 * @param $reason String
1157 * @param $suppress Boolean
1158 * @throws MWException or FSException on database or file store failure
1159 * @return FileRepoStatus object.
1161 function deleteOld( $archiveName, $reason, $suppress = false ) {
1162 $this->lock();
1164 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress );
1165 $batch->addOld( $archiveName );
1166 $status = $batch->execute();
1168 $this->unlock();
1170 if ( $status->ok ) {
1171 $this->purgeDescription();
1172 $this->purgeHistory();
1175 return $status;
1179 * Restore all or specified deleted revisions to the given file.
1180 * Permissions and logging are left to the caller.
1182 * May throw database exceptions on error.
1184 * @param $versions set of record ids of deleted items to restore,
1185 * or empty to restore all revisions.
1186 * @param $unsuppress Boolean
1187 * @return FileRepoStatus
1189 function restore( $versions = array(), $unsuppress = false ) {
1190 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1192 if ( !$versions ) {
1193 $batch->addAll();
1194 } else {
1195 $batch->addIds( $versions );
1198 $status = $batch->execute();
1200 if ( !$status->ok ) {
1201 return $status;
1204 $cleanupStatus = $batch->cleanup();
1205 $cleanupStatus->successCount = 0;
1206 $cleanupStatus->failCount = 0;
1207 $status->merge( $cleanupStatus );
1209 return $status;
1212 /** isMultipage inherited */
1213 /** pageCount inherited */
1214 /** scaleHeight inherited */
1215 /** getImageSize inherited */
1217 /** getDescriptionUrl inherited */
1218 /** getDescriptionText inherited */
1220 function getDescription() {
1221 $this->load();
1222 return $this->description;
1225 function getTimestamp() {
1226 $this->load();
1227 return $this->timestamp;
1230 function getSha1() {
1231 $this->load();
1232 // Initialise now if necessary
1233 if ( $this->sha1 == '' && $this->fileExists ) {
1234 $this->sha1 = File::sha1Base36( $this->getPath() );
1235 if ( !wfReadOnly() && strval( $this->sha1 ) != '' ) {
1236 $dbw = $this->repo->getMasterDB();
1237 $dbw->update( 'image',
1238 array( 'img_sha1' => $this->sha1 ),
1239 array( 'img_name' => $this->getName() ),
1240 __METHOD__ );
1241 $this->saveToCache();
1245 return $this->sha1;
1249 * Start a transaction and lock the image for update
1250 * Increments a reference counter if the lock is already held
1251 * @return boolean True if the image exists, false otherwise
1253 function lock() {
1254 $dbw = $this->repo->getMasterDB();
1256 if ( !$this->locked ) {
1257 $dbw->begin();
1258 $this->locked++;
1261 return $dbw->selectField( 'image', '1', array( 'img_name' => $this->getName() ), __METHOD__ );
1265 * Decrement the lock reference count. If the reference count is reduced to zero, commits
1266 * the transaction and thereby releases the image lock.
1268 function unlock() {
1269 if ( $this->locked ) {
1270 --$this->locked;
1271 if ( !$this->locked ) {
1272 $dbw = $this->repo->getMasterDB();
1273 $dbw->commit();
1279 * Roll back the DB transaction and mark the image unlocked
1281 function unlockAndRollback() {
1282 $this->locked = false;
1283 $dbw = $this->repo->getMasterDB();
1284 $dbw->rollback();
1286 } // LocalFile class
1288 # ------------------------------------------------------------------------------
1291 * Helper class for file deletion
1292 * @ingroup FileRepo
1294 class LocalFileDeleteBatch {
1295 var $file, $reason, $srcRels = array(), $archiveUrls = array(), $deletionBatch, $suppress;
1296 var $status;
1298 function __construct( File $file, $reason = '', $suppress = false ) {
1299 $this->file = $file;
1300 $this->reason = $reason;
1301 $this->suppress = $suppress;
1302 $this->status = $file->repo->newGood();
1305 function addCurrent() {
1306 $this->srcRels['.'] = $this->file->getRel();
1309 function addOld( $oldName ) {
1310 $this->srcRels[$oldName] = $this->file->getArchiveRel( $oldName );
1311 $this->archiveUrls[] = $this->file->getArchiveUrl( $oldName );
1314 function getOldRels() {
1315 if ( !isset( $this->srcRels['.'] ) ) {
1316 $oldRels =& $this->srcRels;
1317 $deleteCurrent = false;
1318 } else {
1319 $oldRels = $this->srcRels;
1320 unset( $oldRels['.'] );
1321 $deleteCurrent = true;
1324 return array( $oldRels, $deleteCurrent );
1327 /*protected*/ function getHashes() {
1328 $hashes = array();
1329 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1331 if ( $deleteCurrent ) {
1332 $hashes['.'] = $this->file->getSha1();
1335 if ( count( $oldRels ) ) {
1336 $dbw = $this->file->repo->getMasterDB();
1337 $res = $dbw->select(
1338 'oldimage',
1339 array( 'oi_archive_name', 'oi_sha1' ),
1340 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1341 __METHOD__
1344 while ( $row = $dbw->fetchObject( $res ) ) {
1345 if ( rtrim( $row->oi_sha1, "\0" ) === '' ) {
1346 // Get the hash from the file
1347 $oldUrl = $this->file->getArchiveVirtualUrl( $row->oi_archive_name );
1348 $props = $this->file->repo->getFileProps( $oldUrl );
1350 if ( $props['fileExists'] ) {
1351 // Upgrade the oldimage row
1352 $dbw->update( 'oldimage',
1353 array( 'oi_sha1' => $props['sha1'] ),
1354 array( 'oi_name' => $this->file->getName(), 'oi_archive_name' => $row->oi_archive_name ),
1355 __METHOD__ );
1356 $hashes[$row->oi_archive_name] = $props['sha1'];
1357 } else {
1358 $hashes[$row->oi_archive_name] = false;
1360 } else {
1361 $hashes[$row->oi_archive_name] = $row->oi_sha1;
1366 $missing = array_diff_key( $this->srcRels, $hashes );
1368 foreach ( $missing as $name => $rel ) {
1369 $this->status->error( 'filedelete-old-unregistered', $name );
1372 foreach ( $hashes as $name => $hash ) {
1373 if ( !$hash ) {
1374 $this->status->error( 'filedelete-missing', $this->srcRels[$name] );
1375 unset( $hashes[$name] );
1379 return $hashes;
1382 function doDBInserts() {
1383 global $wgUser;
1385 $dbw = $this->file->repo->getMasterDB();
1386 $encTimestamp = $dbw->addQuotes( $dbw->timestamp() );
1387 $encUserId = $dbw->addQuotes( $wgUser->getId() );
1388 $encReason = $dbw->addQuotes( $this->reason );
1389 $encGroup = $dbw->addQuotes( 'deleted' );
1390 $ext = $this->file->getExtension();
1391 $dotExt = $ext === '' ? '' : ".$ext";
1392 $encExt = $dbw->addQuotes( $dotExt );
1393 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1395 // Bitfields to further suppress the content
1396 if ( $this->suppress ) {
1397 $bitfield = 0;
1398 // This should be 15...
1399 $bitfield |= Revision::DELETED_TEXT;
1400 $bitfield |= Revision::DELETED_COMMENT;
1401 $bitfield |= Revision::DELETED_USER;
1402 $bitfield |= Revision::DELETED_RESTRICTED;
1403 } else {
1404 $bitfield = 'oi_deleted';
1407 if ( $deleteCurrent ) {
1408 $concat = $dbw->buildConcat( array( "img_sha1", $encExt ) );
1409 $where = array( 'img_name' => $this->file->getName() );
1410 $dbw->insertSelect( 'filearchive', 'image',
1411 array(
1412 'fa_storage_group' => $encGroup,
1413 'fa_storage_key' => "CASE WHEN img_sha1='' THEN '' ELSE $concat END",
1414 'fa_deleted_user' => $encUserId,
1415 'fa_deleted_timestamp' => $encTimestamp,
1416 'fa_deleted_reason' => $encReason,
1417 'fa_deleted' => $this->suppress ? $bitfield : 0,
1419 'fa_name' => 'img_name',
1420 'fa_archive_name' => 'NULL',
1421 'fa_size' => 'img_size',
1422 'fa_width' => 'img_width',
1423 'fa_height' => 'img_height',
1424 'fa_metadata' => 'img_metadata',
1425 'fa_bits' => 'img_bits',
1426 'fa_media_type' => 'img_media_type',
1427 'fa_major_mime' => 'img_major_mime',
1428 'fa_minor_mime' => 'img_minor_mime',
1429 'fa_description' => 'img_description',
1430 'fa_user' => 'img_user',
1431 'fa_user_text' => 'img_user_text',
1432 'fa_timestamp' => 'img_timestamp'
1433 ), $where, __METHOD__ );
1436 if ( count( $oldRels ) ) {
1437 $concat = $dbw->buildConcat( array( "oi_sha1", $encExt ) );
1438 $where = array(
1439 'oi_name' => $this->file->getName(),
1440 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')' );
1441 $dbw->insertSelect( 'filearchive', 'oldimage',
1442 array(
1443 'fa_storage_group' => $encGroup,
1444 'fa_storage_key' => "CASE WHEN oi_sha1='' THEN '' ELSE $concat END",
1445 'fa_deleted_user' => $encUserId,
1446 'fa_deleted_timestamp' => $encTimestamp,
1447 'fa_deleted_reason' => $encReason,
1448 'fa_deleted' => $this->suppress ? $bitfield : 'oi_deleted',
1450 'fa_name' => 'oi_name',
1451 'fa_archive_name' => 'oi_archive_name',
1452 'fa_size' => 'oi_size',
1453 'fa_width' => 'oi_width',
1454 'fa_height' => 'oi_height',
1455 'fa_metadata' => 'oi_metadata',
1456 'fa_bits' => 'oi_bits',
1457 'fa_media_type' => 'oi_media_type',
1458 'fa_major_mime' => 'oi_major_mime',
1459 'fa_minor_mime' => 'oi_minor_mime',
1460 'fa_description' => 'oi_description',
1461 'fa_user' => 'oi_user',
1462 'fa_user_text' => 'oi_user_text',
1463 'fa_timestamp' => 'oi_timestamp',
1464 'fa_deleted' => $bitfield
1465 ), $where, __METHOD__ );
1469 function doDBDeletes() {
1470 $dbw = $this->file->repo->getMasterDB();
1471 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1473 if ( count( $oldRels ) ) {
1474 $dbw->delete( 'oldimage',
1475 array(
1476 'oi_name' => $this->file->getName(),
1477 'oi_archive_name' => array_keys( $oldRels )
1478 ), __METHOD__ );
1481 if ( $deleteCurrent ) {
1482 $dbw->delete( 'image', array( 'img_name' => $this->file->getName() ), __METHOD__ );
1487 * Run the transaction
1489 function execute() {
1490 global $wgUseSquid;
1491 wfProfileIn( __METHOD__ );
1493 $this->file->lock();
1494 // Leave private files alone
1495 $privateFiles = array();
1496 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
1497 $dbw = $this->file->repo->getMasterDB();
1499 if ( !empty( $oldRels ) ) {
1500 $res = $dbw->select( 'oldimage',
1501 array( 'oi_archive_name' ),
1502 array( 'oi_name' => $this->file->getName(),
1503 'oi_archive_name IN (' . $dbw->makeList( array_keys( $oldRels ) ) . ')',
1504 $dbw->bitAnd( 'oi_deleted', File::DELETED_FILE ) => File::DELETED_FILE ),
1505 __METHOD__ );
1507 while ( $row = $dbw->fetchObject( $res ) ) {
1508 $privateFiles[$row->oi_archive_name] = 1;
1511 // Prepare deletion batch
1512 $hashes = $this->getHashes();
1513 $this->deletionBatch = array();
1514 $ext = $this->file->getExtension();
1515 $dotExt = $ext === '' ? '' : ".$ext";
1517 foreach ( $this->srcRels as $name => $srcRel ) {
1518 // Skip files that have no hash (missing source).
1519 // Keep private files where they are.
1520 if ( isset( $hashes[$name] ) && !array_key_exists( $name, $privateFiles ) ) {
1521 $hash = $hashes[$name];
1522 $key = $hash . $dotExt;
1523 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1524 $this->deletionBatch[$name] = array( $srcRel, $dstRel );
1528 // Lock the filearchive rows so that the files don't get deleted by a cleanup operation
1529 // We acquire this lock by running the inserts now, before the file operations.
1531 // This potentially has poor lock contention characteristics -- an alternative
1532 // scheme would be to insert stub filearchive entries with no fa_name and commit
1533 // them in a separate transaction, then run the file ops, then update the fa_name fields.
1534 $this->doDBInserts();
1536 // Removes non-existent file from the batch, so we don't get errors.
1537 $this->deletionBatch = $this->removeNonexistentFiles( $this->deletionBatch );
1539 // Execute the file deletion batch
1540 $status = $this->file->repo->deleteBatch( $this->deletionBatch );
1542 if ( !$status->isGood() ) {
1543 $this->status->merge( $status );
1546 if ( !$this->status->ok ) {
1547 // Critical file deletion error
1548 // Roll back inserts, release lock and abort
1549 // TODO: delete the defunct filearchive rows if we are using a non-transactional DB
1550 $this->file->unlockAndRollback();
1551 wfProfileOut( __METHOD__ );
1552 return $this->status;
1555 // Purge squid
1556 if ( $wgUseSquid ) {
1557 $urls = array();
1559 foreach ( $this->srcRels as $srcRel ) {
1560 $urlRel = str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1561 $urls[] = $this->file->repo->getZoneUrl( 'public' ) . '/' . $urlRel;
1563 SquidUpdate::purge( $urls );
1566 // Delete image/oldimage rows
1567 $this->doDBDeletes();
1569 // Commit and return
1570 $this->file->unlock();
1571 wfProfileOut( __METHOD__ );
1573 return $this->status;
1577 * Removes non-existent files from a deletion batch.
1579 function removeNonexistentFiles( $batch ) {
1580 $files = $newBatch = array();
1582 foreach ( $batch as $batchItem ) {
1583 list( $src, $dest ) = $batchItem;
1584 $files[$src] = $this->file->repo->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
1587 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1589 foreach ( $batch as $batchItem ) {
1590 if ( $result[$batchItem[0]] ) {
1591 $newBatch[] = $batchItem;
1595 return $newBatch;
1599 # ------------------------------------------------------------------------------
1602 * Helper class for file undeletion
1603 * @ingroup FileRepo
1605 class LocalFileRestoreBatch {
1606 var $file, $cleanupBatch, $ids, $all, $unsuppress = false;
1608 function __construct( File $file, $unsuppress = false ) {
1609 $this->file = $file;
1610 $this->cleanupBatch = $this->ids = array();
1611 $this->ids = array();
1612 $this->unsuppress = $unsuppress;
1616 * Add a file by ID
1618 function addId( $fa_id ) {
1619 $this->ids[] = $fa_id;
1623 * Add a whole lot of files by ID
1625 function addIds( $ids ) {
1626 $this->ids = array_merge( $this->ids, $ids );
1630 * Add all revisions of the file
1632 function addAll() {
1633 $this->all = true;
1637 * Run the transaction, except the cleanup batch.
1638 * The cleanup batch should be run in a separate transaction, because it locks different
1639 * rows and there's no need to keep the image row locked while it's acquiring those locks
1640 * The caller may have its own transaction open.
1641 * So we save the batch and let the caller call cleanup()
1643 function execute() {
1644 global $wgLang;
1646 if ( !$this->all && !$this->ids ) {
1647 // Do nothing
1648 return $this->file->repo->newGood();
1651 $exists = $this->file->lock();
1652 $dbw = $this->file->repo->getMasterDB();
1653 $status = $this->file->repo->newGood();
1655 // Fetch all or selected archived revisions for the file,
1656 // sorted from the most recent to the oldest.
1657 $conditions = array( 'fa_name' => $this->file->getName() );
1659 if ( !$this->all ) {
1660 $conditions[] = 'fa_id IN (' . $dbw->makeList( $this->ids ) . ')';
1663 $result = $dbw->select( 'filearchive', '*',
1664 $conditions,
1665 __METHOD__,
1666 array( 'ORDER BY' => 'fa_timestamp DESC' )
1669 $idsPresent = array();
1670 $storeBatch = array();
1671 $insertBatch = array();
1672 $insertCurrent = false;
1673 $deleteIds = array();
1674 $first = true;
1675 $archiveNames = array();
1677 while ( $row = $dbw->fetchObject( $result ) ) {
1678 $idsPresent[] = $row->fa_id;
1680 if ( $row->fa_name != $this->file->getName() ) {
1681 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp ) );
1682 $status->failCount++;
1683 continue;
1686 if ( $row->fa_storage_key == '' ) {
1687 // Revision was missing pre-deletion
1688 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp ) );
1689 $status->failCount++;
1690 continue;
1693 $deletedRel = $this->file->repo->getDeletedHashPath( $row->fa_storage_key ) . $row->fa_storage_key;
1694 $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel;
1696 $sha1 = substr( $row->fa_storage_key, 0, strcspn( $row->fa_storage_key, '.' ) );
1698 # Fix leading zero
1699 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
1700 $sha1 = substr( $sha1, 1 );
1703 if ( is_null( $row->fa_major_mime ) || $row->fa_major_mime == 'unknown'
1704 || is_null( $row->fa_minor_mime ) || $row->fa_minor_mime == 'unknown'
1705 || is_null( $row->fa_media_type ) || $row->fa_media_type == 'UNKNOWN'
1706 || is_null( $row->fa_metadata ) ) {
1707 // Refresh our metadata
1708 // Required for a new current revision; nice for older ones too. :)
1709 $props = RepoGroup::singleton()->getFileProps( $deletedUrl );
1710 } else {
1711 $props = array(
1712 'minor_mime' => $row->fa_minor_mime,
1713 'major_mime' => $row->fa_major_mime,
1714 'media_type' => $row->fa_media_type,
1715 'metadata' => $row->fa_metadata
1719 if ( $first && !$exists ) {
1720 // This revision will be published as the new current version
1721 $destRel = $this->file->getRel();
1722 $insertCurrent = array(
1723 'img_name' => $row->fa_name,
1724 'img_size' => $row->fa_size,
1725 'img_width' => $row->fa_width,
1726 'img_height' => $row->fa_height,
1727 'img_metadata' => $props['metadata'],
1728 'img_bits' => $row->fa_bits,
1729 'img_media_type' => $props['media_type'],
1730 'img_major_mime' => $props['major_mime'],
1731 'img_minor_mime' => $props['minor_mime'],
1732 'img_description' => $row->fa_description,
1733 'img_user' => $row->fa_user,
1734 'img_user_text' => $row->fa_user_text,
1735 'img_timestamp' => $row->fa_timestamp,
1736 'img_sha1' => $sha1
1739 // The live (current) version cannot be hidden!
1740 if ( !$this->unsuppress && $row->fa_deleted ) {
1741 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1742 $this->cleanupBatch[] = $row->fa_storage_key;
1744 } else {
1745 $archiveName = $row->fa_archive_name;
1747 if ( $archiveName == '' ) {
1748 // This was originally a current version; we
1749 // have to devise a new archive name for it.
1750 // Format is <timestamp of archiving>!<name>
1751 $timestamp = wfTimestamp( TS_UNIX, $row->fa_deleted_timestamp );
1753 do {
1754 $archiveName = wfTimestamp( TS_MW, $timestamp ) . '!' . $row->fa_name;
1755 $timestamp++;
1756 } while ( isset( $archiveNames[$archiveName] ) );
1759 $archiveNames[$archiveName] = true;
1760 $destRel = $this->file->getArchiveRel( $archiveName );
1761 $insertBatch[] = array(
1762 'oi_name' => $row->fa_name,
1763 'oi_archive_name' => $archiveName,
1764 'oi_size' => $row->fa_size,
1765 'oi_width' => $row->fa_width,
1766 'oi_height' => $row->fa_height,
1767 'oi_bits' => $row->fa_bits,
1768 'oi_description' => $row->fa_description,
1769 'oi_user' => $row->fa_user,
1770 'oi_user_text' => $row->fa_user_text,
1771 'oi_timestamp' => $row->fa_timestamp,
1772 'oi_metadata' => $props['metadata'],
1773 'oi_media_type' => $props['media_type'],
1774 'oi_major_mime' => $props['major_mime'],
1775 'oi_minor_mime' => $props['minor_mime'],
1776 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted,
1777 'oi_sha1' => $sha1 );
1780 $deleteIds[] = $row->fa_id;
1782 if ( !$this->unsuppress && $row->fa_deleted & File::DELETED_FILE ) {
1783 // private files can stay where they are
1784 $status->successCount++;
1785 } else {
1786 $storeBatch[] = array( $deletedUrl, 'public', $destRel );
1787 $this->cleanupBatch[] = $row->fa_storage_key;
1790 $first = false;
1793 unset( $result );
1795 // Add a warning to the status object for missing IDs
1796 $missingIds = array_diff( $this->ids, $idsPresent );
1798 foreach ( $missingIds as $id ) {
1799 $status->error( 'undelete-missing-filearchive', $id );
1802 // Remove missing files from batch, so we don't get errors when undeleting them
1803 $storeBatch = $this->removeNonexistentFiles( $storeBatch );
1805 // Run the store batch
1806 // Use the OVERWRITE_SAME flag to smooth over a common error
1807 $storeStatus = $this->file->repo->storeBatch( $storeBatch, FileRepo::OVERWRITE_SAME );
1808 $status->merge( $storeStatus );
1810 if ( !$status->ok ) {
1811 // Store batch returned a critical error -- this usually means nothing was stored
1812 // Stop now and return an error
1813 $this->file->unlock();
1815 return $status;
1818 // Run the DB updates
1819 // Because we have locked the image row, key conflicts should be rare.
1820 // If they do occur, we can roll back the transaction at this time with
1821 // no data loss, but leaving unregistered files scattered throughout the
1822 // public zone.
1823 // This is not ideal, which is why it's important to lock the image row.
1824 if ( $insertCurrent ) {
1825 $dbw->insert( 'image', $insertCurrent, __METHOD__ );
1828 if ( $insertBatch ) {
1829 $dbw->insert( 'oldimage', $insertBatch, __METHOD__ );
1832 if ( $deleteIds ) {
1833 $dbw->delete( 'filearchive',
1834 array( 'fa_id IN (' . $dbw->makeList( $deleteIds ) . ')' ),
1835 __METHOD__ );
1838 // If store batch is empty (all files are missing), deletion is to be considered successful
1839 if ( $status->successCount > 0 || !$storeBatch ) {
1840 if ( !$exists ) {
1841 wfDebug( __METHOD__ . " restored {$status->successCount} items, creating a new current\n" );
1843 // Update site_stats
1844 $site_stats = $dbw->tableName( 'site_stats' );
1845 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1847 $this->file->purgeEverything();
1848 } else {
1849 wfDebug( __METHOD__ . " restored {$status->successCount} as archived versions\n" );
1850 $this->file->purgeDescription();
1851 $this->file->purgeHistory();
1855 $this->file->unlock();
1857 return $status;
1861 * Removes non-existent files from a store batch.
1863 function removeNonexistentFiles( $triplets ) {
1864 $files = $filteredTriplets = array();
1865 foreach ( $triplets as $file )
1866 $files[$file[0]] = $file[0];
1868 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1870 foreach ( $triplets as $file ) {
1871 if ( $result[$file[0]] ) {
1872 $filteredTriplets[] = $file;
1876 return $filteredTriplets;
1880 * Removes non-existent files from a cleanup batch.
1882 function removeNonexistentFromCleanup( $batch ) {
1883 $files = $newBatch = array();
1884 $repo = $this->file->repo;
1886 foreach ( $batch as $file ) {
1887 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
1888 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
1891 $result = $repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
1893 foreach ( $batch as $file ) {
1894 if ( $result[$file] ) {
1895 $newBatch[] = $file;
1899 return $newBatch;
1903 * Delete unused files in the deleted zone.
1904 * This should be called from outside the transaction in which execute() was called.
1906 function cleanup() {
1907 if ( !$this->cleanupBatch ) {
1908 return $this->file->repo->newGood();
1911 $this->cleanupBatch = $this->removeNonexistentFromCleanup( $this->cleanupBatch );
1913 $status = $this->file->repo->cleanupDeletedBatch( $this->cleanupBatch );
1915 return $status;
1919 # ------------------------------------------------------------------------------
1922 * Helper class for file movement
1923 * @ingroup FileRepo
1925 class LocalFileMoveBatch {
1926 var $file, $cur, $olds, $oldCount, $archive, $target, $db;
1928 function __construct( File $file, Title $target ) {
1929 $this->file = $file;
1930 $this->target = $target;
1931 $this->oldHash = $this->file->repo->getHashPath( $this->file->getName() );
1932 $this->newHash = $this->file->repo->getHashPath( $this->target->getDBkey() );
1933 $this->oldName = $this->file->getName();
1934 $this->newName = $this->file->repo->getNameFromTitle( $this->target );
1935 $this->oldRel = $this->oldHash . $this->oldName;
1936 $this->newRel = $this->newHash . $this->newName;
1937 $this->db = $file->repo->getMasterDb();
1941 * Add the current image to the batch
1943 function addCurrent() {
1944 $this->cur = array( $this->oldRel, $this->newRel );
1948 * Add the old versions of the image to the batch
1950 function addOlds() {
1951 $archiveBase = 'archive';
1952 $this->olds = array();
1953 $this->oldCount = 0;
1955 $result = $this->db->select( 'oldimage',
1956 array( 'oi_archive_name', 'oi_deleted' ),
1957 array( 'oi_name' => $this->oldName ),
1958 __METHOD__
1961 while ( $row = $this->db->fetchObject( $result ) ) {
1962 $oldName = $row->oi_archive_name;
1963 $bits = explode( '!', $oldName, 2 );
1965 if ( count( $bits ) != 2 ) {
1966 wfDebug( "Invalid old file name: $oldName \n" );
1967 continue;
1970 list( $timestamp, $filename ) = $bits;
1972 if ( $this->oldName != $filename ) {
1973 wfDebug( "Invalid old file name: $oldName \n" );
1974 continue;
1977 $this->oldCount++;
1979 // Do we want to add those to oldCount?
1980 if ( $row->oi_deleted & File::DELETED_FILE ) {
1981 continue;
1984 $this->olds[] = array(
1985 "{$archiveBase}/{$this->oldHash}{$oldName}",
1986 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
1992 * Perform the move.
1994 function execute() {
1995 $repo = $this->file->repo;
1996 $status = $repo->newGood();
1997 $triplets = $this->getMoveTriplets();
1999 $triplets = $this->removeNonexistentFiles( $triplets );
2000 $statusDb = $this->doDBUpdates();
2001 wfDebugLog( 'imagemove', "Renamed {$this->file->name} in database: {$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2002 $statusMove = $repo->storeBatch( $triplets, FSRepo::DELETE_SOURCE );
2003 wfDebugLog( 'imagemove', "Moved files for {$this->file->name}: {$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2005 if ( !$statusMove->isOk() ) {
2006 wfDebugLog( 'imagemove', "Error in moving files: " . $statusMove->getWikiText() );
2007 $this->db->rollback();
2010 $status->merge( $statusDb );
2011 $status->merge( $statusMove );
2013 return $status;
2017 * Do the database updates and return a new FileRepoStatus indicating how
2018 * many rows where updated.
2020 * @return FileRepoStatus
2022 function doDBUpdates() {
2023 $repo = $this->file->repo;
2024 $status = $repo->newGood();
2025 $dbw = $this->db;
2027 // Update current image
2028 $dbw->update(
2029 'image',
2030 array( 'img_name' => $this->newName ),
2031 array( 'img_name' => $this->oldName ),
2032 __METHOD__
2035 if ( $dbw->affectedRows() ) {
2036 $status->successCount++;
2037 } else {
2038 $status->failCount++;
2041 // Update old images
2042 $dbw->update(
2043 'oldimage',
2044 array(
2045 'oi_name' => $this->newName,
2046 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name', $dbw->addQuotes( $this->oldName ), $dbw->addQuotes( $this->newName ) ),
2048 array( 'oi_name' => $this->oldName ),
2049 __METHOD__
2052 $affected = $dbw->affectedRows();
2053 $total = $this->oldCount;
2054 $status->successCount += $affected;
2055 $status->failCount += $total - $affected;
2057 return $status;
2061 * Generate triplets for FSRepo::storeBatch().
2063 function getMoveTriplets() {
2064 $moves = array_merge( array( $this->cur ), $this->olds );
2065 $triplets = array(); // The format is: (srcUrl, destZone, destUrl)
2067 foreach ( $moves as $move ) {
2068 // $move: (oldRelativePath, newRelativePath)
2069 $srcUrl = $this->file->repo->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
2070 $triplets[] = array( $srcUrl, 'public', $move[1] );
2071 wfDebugLog( 'imagemove', "Generated move triplet for {$this->file->name}: {$srcUrl} :: public :: {$move[1]}" );
2074 return $triplets;
2078 * Removes non-existent files from move batch.
2080 function removeNonexistentFiles( $triplets ) {
2081 $files = array();
2083 foreach ( $triplets as $file ) {
2084 $files[$file[0]] = $file[0];
2087 $result = $this->file->repo->fileExistsBatch( $files, FSRepo::FILES_ONLY );
2088 $filteredTriplets = array();
2090 foreach ( $triplets as $file ) {
2091 if ( $result[$file[0]] ) {
2092 $filteredTriplets[] = $file;
2093 } else {
2094 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
2098 return $filteredTriplets;