6 * NOTE FOR WINDOWS USERS:
7 * To enable EXIF functions, add the folloing lines to the
8 * "Windows extensions" section of php.ini:
10 * extension=extensions/php_mbstring.dll
11 * extension=extensions/php_exif.dll
15 * Bump this number when serialized cache records may be incompatible.
17 define( 'MW_IMAGE_VERSION', 2 );
20 * Class to represent an image
22 * Provides methods to retrieve paths (physical, logical, URL),
23 * to generate thumbnails or for uploading.
29 const DELETED_FILE
= 1;
30 const DELETED_COMMENT
= 2;
31 const DELETED_USER
= 4;
32 const DELETED_RESTRICTED
= 8;
38 var $name, # name of the image (constructor)
39 $imagePath, # Path of the image (loadFromXxx)
40 $url, # Image URL (accessor)
41 $title, # Title object for this image (constructor)
42 $fileExists, # does the image file exist on disk? (loadFromXxx)
43 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
44 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
45 $historyRes, # result of the query for the image's history (nextHistoryLine)
48 $bits, # --- returned by getimagesize (loadFromXxx)
50 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
51 $mime, # MIME type, determined by MimeMagic::guessMimeType
52 $extension, # The file extension (constructor)
53 $size, # Size in bytes (loadFromXxx)
55 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
56 $page, # Page to render when creating thumbnails
57 $lastError; # Error string associated with a thumbnail display error
63 * Create an Image object from an image name
65 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
68 public static function newFromName( $name ) {
69 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
70 if ( is_object( $title ) ) {
71 return new Image( $title );
78 * Obsolete factory function, use constructor
81 function newFromTitle( $title ) {
82 return new Image( $title );
85 function Image( $title ) {
86 if( !is_object( $title ) ) {
87 throw new MWException( 'Image constructor given bogus title.' );
89 $this->title
=& $title;
90 $this->name
= $title->getDBkey();
93 $n = strrpos( $this->name
, '.' );
94 $this->extension
= Image
::normalizeExtension( $n ?
95 substr( $this->name
, $n +
1 ) : '' );
96 $this->historyLine
= 0;
98 $this->dataLoaded
= false;
102 * Normalize a file extension to the common form, and ensure it's clean.
103 * Extensions with non-alphanumeric characters will be discarded.
105 * @param $ext string (without the .)
108 static function normalizeExtension( $ext ) {
109 $lower = strtolower( $ext );
115 if( isset( $squish[$lower] ) ) {
116 return $squish[$lower];
117 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
125 * Get the memcached keys
126 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
128 function getCacheKeys( ) {
129 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
131 $hashedName = md5($this->name
);
132 $keys = array( wfMemcKey( 'Image', $hashedName ) );
133 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
134 $keys[] = wfForeignMemcKey( $wgSharedUploadDBname, false, 'Image', $hashedName );
140 * Try to load image metadata from memcached. Returns true on success.
142 function loadFromCache() {
143 global $wgUseSharedUploads, $wgMemc;
144 wfProfileIn( __METHOD__
);
145 $this->dataLoaded
= false;
146 $keys = $this->getCacheKeys();
147 $cachedValues = $wgMemc->get( $keys[0] );
149 // Check if the key existed and belongs to this version of MediaWiki
150 if (!empty($cachedValues) && is_array($cachedValues)
151 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
152 && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
154 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
155 # if this is shared file, we need to check if image
156 # in shared repository has not changed
157 if ( isset( $keys[1] ) ) {
158 $commonsCachedValues = $wgMemc->get( $keys[1] );
159 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
160 && isset($commonsCachedValues['version'])
161 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
162 && isset($commonsCachedValues['mime'])) {
163 wfDebug( "Pulling image metadata from shared repository cache\n" );
164 $this->name
= $commonsCachedValues['name'];
165 $this->imagePath
= $commonsCachedValues['imagePath'];
166 $this->fileExists
= $commonsCachedValues['fileExists'];
167 $this->width
= $commonsCachedValues['width'];
168 $this->height
= $commonsCachedValues['height'];
169 $this->bits
= $commonsCachedValues['bits'];
170 $this->type
= $commonsCachedValues['type'];
171 $this->mime
= $commonsCachedValues['mime'];
172 $this->metadata
= $commonsCachedValues['metadata'];
173 $this->size
= $commonsCachedValues['size'];
174 $this->fromSharedDirectory
= true;
175 $this->dataLoaded
= true;
176 $this->imagePath
= $this->getFullPath(true);
180 wfDebug( "Pulling image metadata from local cache\n" );
181 $this->name
= $cachedValues['name'];
182 $this->imagePath
= $cachedValues['imagePath'];
183 $this->fileExists
= $cachedValues['fileExists'];
184 $this->width
= $cachedValues['width'];
185 $this->height
= $cachedValues['height'];
186 $this->bits
= $cachedValues['bits'];
187 $this->type
= $cachedValues['type'];
188 $this->mime
= $cachedValues['mime'];
189 $this->metadata
= $cachedValues['metadata'];
190 $this->size
= $cachedValues['size'];
191 $this->fromSharedDirectory
= false;
192 $this->dataLoaded
= true;
193 $this->imagePath
= $this->getFullPath();
196 if ( $this->dataLoaded
) {
197 wfIncrStats( 'image_cache_hit' );
199 wfIncrStats( 'image_cache_miss' );
202 wfProfileOut( __METHOD__
);
203 return $this->dataLoaded
;
207 * Save the image metadata to memcached
209 function saveToCache() {
210 global $wgMemc, $wgUseSharedUploads;
212 $keys = $this->getCacheKeys();
213 // We can't cache negative metadata for non-existent files,
214 // because if the file later appears in commons, the local
215 // keys won't be purged.
216 if ( $this->fileExists ||
!$wgUseSharedUploads ) {
217 $cachedValues = array(
218 'version' => MW_IMAGE_VERSION
,
219 'name' => $this->name
,
220 'imagePath' => $this->imagePath
,
221 'fileExists' => $this->fileExists
,
222 'fromShared' => $this->fromSharedDirectory
,
223 'width' => $this->width
,
224 'height' => $this->height
,
225 'bits' => $this->bits
,
226 'type' => $this->type
,
227 'mime' => $this->mime
,
228 'metadata' => $this->metadata
,
229 'size' => $this->size
);
231 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
233 // However we should clear them, so they aren't leftover
234 // if we've deleted the file.
235 $wgMemc->delete( $keys[0] );
240 * Load metadata from the file itself
242 function loadFromFile() {
243 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang;
244 wfProfileIn( __METHOD__
);
245 $this->imagePath
= $this->getFullPath();
246 $this->fileExists
= file_exists( $this->imagePath
);
247 $this->fromSharedDirectory
= false;
250 if (!$this->fileExists
) wfDebug(__METHOD__
.': '.$this->imagePath
." not found locally!\n");
252 # If the file is not found, and a shared upload directory is used, look for it there.
253 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
254 # In case we're on a wgCapitalLinks=false wiki, we
255 # capitalize the first letter of the filename before
256 # looking it up in the shared repository.
257 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
258 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
259 if ( $this->fileExists
) {
260 $this->name
= $sharedImage->name
;
261 $this->imagePath
= $this->getFullPath(true);
262 $this->fromSharedDirectory
= true;
267 if ( $this->fileExists
) {
268 $magic=& MimeMagic
::singleton();
270 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
271 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
272 $handler = MediaHandler
::getHandler( $this->mime
);
275 $this->size
= filesize( $this->imagePath
);
277 # Height, width and metadata
279 $gis = $handler->getImageSize( $this, $this->imagePath
);
280 $this->metadata
= $handler->getMetadata( $this, $this->imagePath
);
283 $this->metadata
= '';
286 wfDebug(__METHOD__
.': '.$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
290 $this->type
= MEDIATYPE_UNKNOWN
;
291 $this->metadata
= '';
292 wfDebug(__METHOD__
.': '.$this->imagePath
." NOT FOUND!\n");
296 $this->width
= $gis[0];
297 $this->height
= $gis[1];
303 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
305 #NOTE: we have to set this flag early to avoid load() to be called
306 # be some of the functions below. This may lead to recursion or other bad things!
307 # as ther's only one thread of execution, this should be safe anyway.
308 $this->dataLoaded
= true;
310 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
311 else $this->bits
= 0;
313 wfProfileOut( __METHOD__
);
317 * Load image metadata from the DB
319 function loadFromDB() {
320 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
321 wfProfileIn( __METHOD__
);
323 $dbr = wfGetDB( DB_SLAVE
);
324 $this->checkDBSchema($dbr);
326 $row = $dbr->selectRow( 'image',
327 array( 'img_size', 'img_width', 'img_height', 'img_bits',
328 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
329 array( 'img_name' => $this->name
), __METHOD__
);
331 $this->fromSharedDirectory
= false;
332 $this->fileExists
= true;
333 $this->loadFromRow( $row );
334 $this->imagePath
= $this->getFullPath();
335 // Check for rows from a previous schema, quietly upgrade them
336 $this->maybeUpgradeRow();
337 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
338 # In case we're on a wgCapitalLinks=false wiki, we
339 # capitalize the first letter of the filename before
340 # looking it up in the shared repository.
341 $name = $wgContLang->ucfirst($this->name
);
342 $dbc = Image
::getCommonsDB();
344 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
346 'img_size', 'img_width', 'img_height', 'img_bits',
347 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
348 array( 'img_name' => $name ), __METHOD__
);
350 $this->fromSharedDirectory
= true;
351 $this->fileExists
= true;
352 $this->imagePath
= $this->getFullPath(true);
354 $this->loadFromRow( $row );
356 // Check for rows from a previous schema, quietly upgrade them
357 $this->maybeUpgradeRow();
367 $this->fileExists
= false;
368 $this->fromSharedDirectory
= false;
369 $this->metadata
= '';
373 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
374 $this->dataLoaded
= true;
375 wfProfileOut( __METHOD__
);
379 * Load image metadata from a DB result row
381 function loadFromRow( &$row ) {
382 $this->size
= $row->img_size
;
383 $this->width
= $row->img_width
;
384 $this->height
= $row->img_height
;
385 $this->bits
= $row->img_bits
;
386 $this->type
= $row->img_media_type
;
388 $major= $row->img_major_mime
;
389 $minor= $row->img_minor_mime
;
391 if (!$major) $this->mime
= "unknown/unknown";
393 if (!$minor) $minor= "unknown";
394 $this->mime
= $major.'/'.$minor;
396 $this->metadata
= $row->img_metadata
;
398 $this->dataLoaded
= true;
402 * Load image metadata from cache or DB, unless already loaded
405 global $wgSharedUploadDBname, $wgUseSharedUploads;
406 if ( !$this->dataLoaded
) {
407 if ( !$this->loadFromCache() ) {
409 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
410 $this->loadFromFile();
411 } elseif ( $this->fileExists ||
!$wgUseSharedUploads ) {
412 // We can do negative caching for local images, because the cache
413 // will be purged on upload. But we can't do it when shared images
414 // are enabled, since updates to that won't purge foreign caches.
415 $this->saveToCache();
418 $this->dataLoaded
= true;
423 * Upgrade a row if it needs it
425 function maybeUpgradeRow() {
426 if ( is_null($this->type
) ||
$this->mime
== 'image/svg' ) {
429 $handler = $this->getHandler();
430 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
437 * Fix assorted version-related problems with the image row by reloading it from the file
439 function upgradeRow() {
440 global $wgDBname, $wgSharedUploadDBname;
441 wfProfileIn( __METHOD__
);
443 $this->loadFromFile();
445 if ( $this->fromSharedDirectory
) {
446 if ( !$wgSharedUploadDBname ) {
447 wfProfileOut( __METHOD__
);
451 // Write to the other DB using selectDB, not database selectors
452 // This avoids breaking replication in MySQL
453 $dbw = Image
::getCommonsDB();
455 $dbw = wfGetDB( DB_MASTER
);
458 $this->checkDBSchema($dbw);
460 list( $major, $minor ) = self
::splitMime( $this->mime
);
462 wfDebug(__METHOD__
.': upgrading '.$this->name
." to the current schema\n");
464 $dbw->update( 'image',
466 'img_width' => $this->width
,
467 'img_height' => $this->height
,
468 'img_bits' => $this->bits
,
469 'img_media_type' => $this->type
,
470 'img_major_mime' => $major,
471 'img_minor_mime' => $minor,
472 'img_metadata' => $this->metadata
,
473 ), array( 'img_name' => $this->name
), __METHOD__
475 if ( $this->fromSharedDirectory
) {
476 $dbw->selectDB( $wgDBname );
478 wfProfileOut( __METHOD__
);
482 * Split an internet media type into its two components; if not
483 * a two-part name, set the minor type to 'unknown'.
485 * @param $mime "text/html" etc
486 * @return array ("text", "html") etc
488 static function splitMime( $mime ) {
489 if( strpos( $mime, '/' ) !== false ) {
490 return explode( '/', $mime, 2 );
492 return array( $mime, 'unknown' );
497 * Return the name of this image
505 * Return the associated title object
508 function getTitle() {
513 * Return the URL of the image file
519 if($this->fileExists
) {
520 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
528 function getViewURL() {
529 if( $this->mustRender()) {
530 if( $this->canRender() ) {
531 return $this->createThumb( $this->getWidth() );
534 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
535 return $this->getURL(); #hm... return NULL?
538 return $this->getURL();
543 * Return the image path of the image in the
544 * local file system as an absolute path
547 function getImagePath() {
549 return $this->imagePath
;
553 * Return the width of the image
555 * Returns false on error
558 function getWidth( $page = 1 ) {
560 if ( $this->isMultipage() ) {
561 $dim = $this->getHandler()->getPageDimensions( $this, $page );
563 return $dim['width'];
573 * Return the height of the image
575 * Returns false on error
578 function getHeight( $page = 1 ) {
580 if ( $this->isMultipage() ) {
581 $dim = $this->getHandler()->getPageDimensions( $this, $page );
583 return $dim['height'];
588 return $this->height
;
593 * Get handler-specific metadata
595 function getMetadata() {
597 return $this->metadata
;
601 * Return the size of the image file, in bytes
610 * Returns the mime type of the file.
612 function getMimeType() {
618 * Return the type of the media in the file.
619 * Use the value returned by this function with the MEDIATYPE_xxx constants.
621 function getMediaType() {
627 * Checks if the file can be presented to the browser as a bitmap.
629 * Currently, this checks if the file is an image format
630 * that can be converted to a format
631 * supported by all browsers (namely GIF, PNG and JPEG),
632 * or if it is an SVG image and SVG conversion is enabled.
634 * @todo remember the result of this check.
636 function canRender() {
637 $handler = $this->getHandler();
638 return $handler && $handler->canRender();
642 * Return true if the file is of a type that can't be directly
643 * rendered by typical browsers and needs to be re-rasterized.
645 * This returns true for everything but the bitmap types
646 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
647 * also return true for any non-image formats.
651 function mustRender() {
652 $handler = $this->getHandler();
653 return $handler && $handler->mustRender();
657 * Determines if this media file may be shown inline on a page.
659 * This is currently synonymous to canRender(), but this could be
660 * extended to also allow inline display of other media,
661 * like flash animations or videos. If you do so, please keep in mind that
662 * that could be a security risk.
664 function allowInlineDisplay() {
665 return $this->canRender();
669 * Determines if this media file is in a format that is unlikely to
670 * contain viruses or malicious content. It uses the global
671 * $wgTrustedMediaFormats list to determine if the file is safe.
673 * This is used to show a warning on the description page of non-safe files.
674 * It may also be used to disallow direct [[media:...]] links to such files.
676 * Note that this function will always return true if allowInlineDisplay()
677 * or isTrustedFile() is true for this file.
679 function isSafeFile() {
680 if ($this->allowInlineDisplay()) return true;
681 if ($this->isTrustedFile()) return true;
683 global $wgTrustedMediaFormats;
685 $type= $this->getMediaType();
686 $mime= $this->getMimeType();
687 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
689 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
690 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
692 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
693 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
698 /** Returns true if the file is flagged as trusted. Files flagged that way
699 * can be linked to directly, even if that is not allowed for this type of
702 * This is a dummy function right now and always returns false. It could be
703 * implemented to extract a flag from the database. The trusted flag could be
704 * set on upload, if the user has sufficient privileges, to bypass script-
705 * and html-filters. It may even be coupled with cryptographics signatures
708 function isTrustedFile() {
709 #this could be implemented to check a flag in the databas,
710 #look for signatures, etc
715 * Return the escapeLocalURL of this image
718 function getEscapeLocalURL( $query=false) {
719 return $this->getTitle()->escapeLocalURL( $query );
723 * Return the escapeFullURL of this image
726 function getEscapeFullURL() {
728 return $this->title
->escapeFullURL();
732 * Return the URL of an image, provided its name.
734 * @param string $name Name of the image, without the leading "Image:"
735 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
736 * @return string URL of $name image
740 function imageUrl( $name, $fromSharedDirectory = false ) {
741 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
742 if($fromSharedDirectory) {
744 $path = $wgSharedUploadPath;
746 $base = $wgUploadBaseUrl;
747 $path = $wgUploadPath;
749 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
750 return wfUrlencode( $url );
754 * Returns true if the image file exists on disk.
755 * @return boolean Whether image file exist on disk.
760 return $this->fileExists
;
767 function thumbUrlFromName( $thumbName, $subdir = 'thumb' ) {
768 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
769 if($this->fromSharedDirectory
) {
771 $path = $wgSharedUploadPath;
773 $base = $wgUploadBaseUrl;
774 $path = $wgUploadPath;
776 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
777 $hashdir = wfGetHashPath($this->name
, $this->fromSharedDirectory
) .
778 wfUrlencode( $this->name
);
782 $url = "{$base}{$path}/{$subdir}{$hashdir}/" . wfUrlencode( $thumbName );
787 * @deprecated Use $image->transform()->getUrl() or thumbUrlFromName()
789 function thumbUrl( $width, $subdir = 'thumb' ) {
790 $name = $this->thumbName( array( 'width' => $width ) );
791 if ( strval( $name ) !== '' ) {
792 return array( false, $this->thumbUrlFromName( $name, $subdir ) );
794 return array( false, false );
798 function getTransformScript() {
799 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
800 if ( $this->fromSharedDirectory
) {
801 $script = $wgSharedThumbnailScriptPath;
803 $script = $wgThumbnailScriptPath;
806 return "$script?f=" . urlencode( $this->name
);
813 * Get a ThumbnailImage which is the same size as the source
815 function getUnscaledThumb( $page = false ) {
819 'width' => $this->getWidth( $page )
822 $params = array( 'width' => $this->getWidth() );
824 return $this->transform( $params );
828 * Return the file name of a thumbnail with the specified parameters
830 * @param array $params Handler-specific parameters
833 function thumbName( $params ) {
834 $handler = $this->getHandler();
838 list( $thumbExt, $thumbMime ) = self
::getThumbType( $this->extension
, $this->mime
);
839 $thumbName = $handler->makeParamString( $params ) . '-' . $this->name
;
840 if ( $thumbExt != $this->extension
) {
841 $thumbName .= ".$thumbExt";
847 * Create a thumbnail of the image having the specified width/height.
848 * The thumbnail will not be created if the width is larger than the
849 * image's width. Let the browser do the scaling in this case.
850 * The thumbnail is stored on disk and is only computed if the thumbnail
851 * file does not exist OR if it is older than the image.
854 * Keeps aspect ratio of original image. If both width and height are
855 * specified, the generated image will be no bigger than width x height,
856 * and will also have correct aspect ratio.
858 * @param integer $width maximum width of the generated thumbnail
859 * @param integer $height maximum height of the image (optional)
862 function createThumb( $width, $height = -1 ) {
863 $params = array( 'width' => $width );
864 if ( $height != -1 ) {
865 $params['height'] = $height;
867 $thumb = $this->transform( $params );
868 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
869 return $thumb->getUrl();
873 * As createThumb, but returns a ThumbnailImage object. This can
874 * provide access to the actual file, the real size of the thumb,
875 * and can produce a convenient <img> tag for you.
877 * For non-image formats, this may return a filetype-specific icon.
879 * @param integer $width maximum width of the generated thumbnail
880 * @param integer $height maximum height of the image (optional)
881 * @param boolean $render True to render the thumbnail if it doesn't exist,
882 * false to just return the URL
884 * @return ThumbnailImage or null on failure
887 * @deprecated use transform()
889 function getThumbnail( $width, $height=-1, $render = true ) {
890 $params = array( 'width' => $width );
891 if ( $height != -1 ) {
892 $params['height'] = $height;
894 $flags = $render ? self
::RENDER_NOW
: 0;
895 return $this->transform( $params, $flags );
899 * Transform a media file
901 * @param array $params An associative array of handler-specific parameters. Typical
902 * keys are width, height and page.
903 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
904 * @return MediaTransformOutput
906 function transform( $params, $flags = 0 ) {
907 global $wgGenerateThumbnailOnParse, $wgUseSquid, $wgIgnoreImageErrors;
909 wfProfileIn( __METHOD__
);
911 $handler = $this->getHandler();
912 if ( !$handler ||
!$handler->canRender() ) {
913 // not a bitmap or renderable image, don't try.
914 $thumb = $this->iconThumb();
918 $script = $this->getTransformScript();
919 if ( $script && !($flags & self
::RENDER_NOW
) ) {
920 // Use a script to transform on client request
921 $thumb = $handler->getScriptedTransform( $this, $script, $params );
925 $normalisedParams = $params;
926 $handler->normaliseParams( $this, $normalisedParams );
927 list( $thumbExt, $thumbMime ) = self
::getThumbType( $this->extension
, $this->mime
);
928 $thumbName = $this->thumbName( $normalisedParams );
929 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
) . "/$thumbName";
930 $thumbUrl = $this->thumbUrlFromName( $thumbName );
932 $this->migrateThumbFile( $thumbName );
934 if ( file_exists( $thumbPath ) ) {
935 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
939 if ( !$wgGenerateThumbnailOnParse && !($flags & self
::RENDER_NOW
) ) {
940 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
943 $thumb = $handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
945 // Ignore errors if requested
948 } elseif ( $thumb->isError() ) {
949 $this->lastError
= $thumb->toText();
950 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
951 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
956 wfPurgeSquidServers( array( $thumbUrl ) );
960 wfProfileOut( __METHOD__
);
965 * Fix thumbnail files from 1.4 or before, with extreme prejudice
967 function migrateThumbFile( $thumbName ) {
968 $thumbDir = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
);
969 $thumbPath = "$thumbDir/$thumbName";
970 if ( is_dir( $thumbPath ) ) {
971 // Directory where file should be
972 // This happened occasionally due to broken migration code in 1.5
973 // Rename to broken-*
974 global $wgUploadDirectory;
975 for ( $i = 0; $i < 100 ; $i++
) {
976 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
977 if ( !file_exists( $broken ) ) {
978 rename( $thumbPath, $broken );
982 // Doesn't exist anymore
985 if ( is_file( $thumbDir ) ) {
986 // File where directory should be
988 // Doesn't exist anymore
994 * Get a MediaHandler instance for this image
996 function getHandler() {
997 return MediaHandler
::getHandler( $this->getMimeType() );
1001 * Get a ThumbnailImage representing a file type icon
1002 * @return ThumbnailImage
1004 function iconThumb() {
1005 global $wgStylePath, $wgStyleDirectory;
1007 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
1008 foreach( $try as $icon ) {
1009 $path = '/common/images/icons/' . $icon;
1010 $filepath = $wgStyleDirectory . $path;
1011 if( file_exists( $filepath ) ) {
1012 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
1019 * Get last thumbnailing error.
1022 function getLastError() {
1023 return $this->lastError
;
1027 * Get all thumbnail names previously generated for this image
1029 function getThumbnails( $shared = false ) {
1030 if ( Image
::isHashed( $shared ) ) {
1033 $dir = wfImageThumbDir( $this->name
, $shared );
1035 if ( is_dir( $dir ) ) {
1036 $handle = opendir( $dir );
1039 while ( false !== ( $file = readdir($handle) ) ) {
1040 if ( $file{0} != '.' ) {
1044 closedir( $handle );
1055 * Refresh metadata in memcached, but don't touch thumbnails or squid
1057 function purgeMetadataCache() {
1059 $this->upgradeRow();
1060 $this->saveToCache();
1064 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1066 function purgeCache( $archiveFiles = array(), $shared = false ) {
1069 // Refresh metadata cache
1070 $this->purgeMetadataCache();
1072 // Delete thumbnails
1073 $files = $this->getThumbnails( $shared );
1074 $dir = wfImageThumbDir( $this->name
, $shared );
1076 foreach ( $files as $file ) {
1078 if ( preg_match( '/^\d+px/', $file, $m ) ) {
1079 $url = $this->thumbUrlFromName( $file );
1081 @unlink
( "$dir/$file" );
1086 if ( $wgUseSquid ) {
1087 $urls[] = $this->getURL();
1088 foreach ( $archiveFiles as $file ) {
1089 $urls[] = wfImageArchiveUrl( $file );
1091 wfPurgeSquidServers( $urls );
1096 * Purge the image description page, but don't go after
1097 * pages using the image. Use when modifying file history
1098 * but not the current data.
1100 function purgeDescription() {
1101 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1102 $page->invalidateCache();
1103 $page->purgeSquid();
1107 * Purge metadata and all affected pages when the image is created,
1108 * deleted, or majorly updated. A set of additional URLs may be
1109 * passed to purge, such as specific image files which have changed.
1110 * @param $urlArray array
1112 function purgeEverything( $urlArr=array() ) {
1113 // Delete thumbnails and refresh image metadata cache
1114 $this->purgeCache();
1115 $this->purgeDescription();
1117 // Purge cache of all pages using this image
1118 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1119 $update->doUpdate();
1123 * Check the image table schema on the given connection for subtle problems
1125 function checkDBSchema(&$db) {
1126 static $checkDone = false;
1127 global $wgCheckDBSchema;
1128 if (!$wgCheckDBSchema ||
$checkDone) {
1131 # img_name must be unique
1132 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1133 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1137 # new fields must exist
1139 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1140 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1141 # something. The only reason I put the above schema check in was because the absence of that particular
1142 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1145 if ( !$db->fieldExists( 'image', 'img_media_type' )
1146 || !$db->fieldExists( 'image', 'img_metadata' )
1147 || !$db->fieldExists( 'image', 'img_width' ) ) {
1149 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1155 * Return the image history of this image, line by line.
1156 * starts with current version, then old versions.
1157 * uses $this->historyLine to check which line to return:
1158 * 0 return line for current version
1159 * 1 query for old versions, return first one
1160 * 2, ... return next old version from above query
1164 function nextHistoryLine() {
1165 $dbr = wfGetDB( DB_SLAVE
);
1167 $this->checkDBSchema($dbr);
1169 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1170 $this->historyRes
= $dbr->select( 'image',
1174 'img_user','img_user_text',
1178 "'' AS oi_archive_name"
1180 array( 'img_name' => $this->title
->getDBkey() ),
1183 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1186 } else if ( $this->historyLine
== 1 ) {
1187 $this->historyRes
= $dbr->select( 'oldimage',
1189 'oi_size AS img_size',
1190 'oi_description AS img_description',
1191 'oi_user AS img_user',
1192 'oi_user_text AS img_user_text',
1193 'oi_timestamp AS img_timestamp',
1194 'oi_width as img_width',
1195 'oi_height as img_height',
1198 array( 'oi_name' => $this->title
->getDBkey() ),
1200 array( 'ORDER BY' => 'oi_timestamp DESC' )
1203 $this->historyLine ++
;
1205 return $dbr->fetchObject( $this->historyRes
);
1209 * Reset the history pointer to the first element of the history
1212 function resetHistory() {
1213 $this->historyLine
= 0;
1217 * Return the full filesystem path to the file. Note that this does
1218 * not mean that a file actually exists under that location.
1220 * This path depends on whether directory hashing is active or not,
1221 * i.e. whether the images are all found in the same directory,
1222 * or in hashed paths like /images/3/3c.
1225 * @param boolean $fromSharedDirectory Return the path to the file
1226 * in a shared repository (see $wgUseSharedRepository and related
1227 * options in DefaultSettings.php) instead of a local one.
1230 function getFullPath( $fromSharedRepository = false ) {
1231 global $wgUploadDirectory, $wgSharedUploadDirectory;
1233 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1236 // $wgSharedUploadDirectory may be false, if thumb.php is used
1238 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1250 public static function isHashed( $shared ) {
1251 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1252 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1256 * Record an image upload in the upload log and the image table
1258 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1259 global $wgUser, $wgUseCopyrightUpload;
1261 $dbw = wfGetDB( DB_MASTER
);
1263 $this->checkDBSchema($dbw);
1265 // Delete thumbnails and refresh the metadata cache
1266 $this->purgeCache();
1268 // Fail now if the image isn't there
1269 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1270 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1274 if ( $wgUseCopyrightUpload ) {
1275 if ( $license != '' ) {
1276 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1278 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1279 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1281 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1283 if ( $license != '' ) {
1284 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1285 $textdesc = $filedesc .
1286 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1292 $now = $dbw->timestamp();
1295 if (strpos($this->mime
,'/')!==false) {
1296 list($major,$minor)= explode('/',$this->mime
,2);
1299 $major= $this->mime
;
1303 # Test to see if the row exists using INSERT IGNORE
1304 # This avoids race conditions by locking the row until the commit, and also
1305 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1306 $dbw->insert( 'image',
1308 'img_name' => $this->name
,
1309 'img_size'=> $this->size
,
1310 'img_width' => intval( $this->width
),
1311 'img_height' => intval( $this->height
),
1312 'img_bits' => $this->bits
,
1313 'img_media_type' => $this->type
,
1314 'img_major_mime' => $major,
1315 'img_minor_mime' => $minor,
1316 'img_timestamp' => $now,
1317 'img_description' => $desc,
1318 'img_user' => $wgUser->getID(),
1319 'img_user_text' => $wgUser->getName(),
1320 'img_metadata' => $this->metadata
,
1326 if( $dbw->affectedRows() == 0 ) {
1327 # Collision, this is an update of an image
1328 # Insert previous contents into oldimage
1329 $dbw->insertSelect( 'oldimage', 'image',
1331 'oi_name' => 'img_name',
1332 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1333 'oi_size' => 'img_size',
1334 'oi_width' => 'img_width',
1335 'oi_height' => 'img_height',
1336 'oi_bits' => 'img_bits',
1337 'oi_timestamp' => 'img_timestamp',
1338 'oi_description' => 'img_description',
1339 'oi_user' => 'img_user',
1340 'oi_user_text' => 'img_user_text',
1341 ), array( 'img_name' => $this->name
), __METHOD__
1344 # Update the current image row
1345 $dbw->update( 'image',
1347 'img_size' => $this->size
,
1348 'img_width' => intval( $this->width
),
1349 'img_height' => intval( $this->height
),
1350 'img_bits' => $this->bits
,
1351 'img_media_type' => $this->type
,
1352 'img_major_mime' => $major,
1353 'img_minor_mime' => $minor,
1354 'img_timestamp' => $now,
1355 'img_description' => $desc,
1356 'img_user' => $wgUser->getID(),
1357 'img_user_text' => $wgUser->getName(),
1358 'img_metadata' => $this->metadata
,
1359 ), array( /* WHERE */
1360 'img_name' => $this->name
1364 # This is a new image
1365 # Update the image count
1366 $site_stats = $dbw->tableName( 'site_stats' );
1367 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1370 $descTitle = $this->getTitle();
1371 $article = new Article( $descTitle );
1373 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1374 $suppressRC = true; // There's already a log entry, so don't double the RC load
1376 if( $descTitle->exists() ) {
1377 // TODO: insert a null revision into the page history for this update.
1379 $wgUser->addWatch( $descTitle );
1382 # Invalidate the cache for the description page
1383 $descTitle->invalidateCache();
1384 $descTitle->purgeSquid();
1386 // New image; create the description page.
1387 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1390 # Hooks, hooks, the magic of hooks...
1391 wfRunHooks( 'FileUpload', array( $this ) );
1394 $log = new LogPage( 'upload' );
1395 $log->addEntry( 'upload', $descTitle, $desc );
1397 # Commit the transaction now, in case something goes wrong later
1398 # The most important thing is that images don't get lost, especially archives
1399 $dbw->immediateCommit();
1401 # Invalidate cache for all pages using this image
1402 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1403 $update->doUpdate();
1409 * Get an array of Title objects which are articles which use this image
1410 * Also adds their IDs to the link cache
1412 * This is mostly copied from Title::getLinksTo()
1414 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1416 function getLinksTo( $options = '' ) {
1417 wfProfileIn( __METHOD__
);
1420 $db = wfGetDB( DB_MASTER
);
1422 $db = wfGetDB( DB_SLAVE
);
1424 $linkCache =& LinkCache
::singleton();
1426 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1427 $encName = $db->addQuotes( $this->name
);
1428 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1429 $res = $db->query( $sql, __METHOD__
);
1432 if ( $db->numRows( $res ) ) {
1433 while ( $row = $db->fetchObject( $res ) ) {
1434 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1435 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1436 $retVal[] = $titleObj;
1440 $db->freeResult( $res );
1441 wfProfileOut( __METHOD__
);
1445 function getExifData() {
1447 $handler = $this->getHandler();
1448 if ( !$handler ||
$handler->getMetadataType( $this ) != 'exif' ) {
1451 if ( !$this->metadata
) {
1454 $exif = unserialize( $this->metadata
);
1458 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
1459 $format = new FormatExif( $exif );
1461 return $format->getFormattedData();
1465 * Returns true if the image does not come from the shared
1470 function isLocal() {
1471 return !$this->fromSharedDirectory
;
1475 * Was this image ever deleted from the wiki?
1479 function wasDeleted() {
1480 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1481 return ( $title->isDeleted() > 0 );
1485 * Delete all versions of the image.
1487 * Moves the files into an archive directory (or deletes them)
1488 * and removes the database rows.
1490 * Cache purging is done; logging is caller's responsibility.
1493 * @return true on success, false on some kind of failure
1495 function delete( $reason, $suppress=false ) {
1496 $transaction = new FSTransaction();
1497 $urlArr = array( $this->getURL() );
1499 if( !FileStore
::lock() ) {
1500 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1505 $dbw = wfGetDB( DB_MASTER
);
1508 // Delete old versions
1509 $result = $dbw->select( 'oldimage',
1510 array( 'oi_archive_name' ),
1511 array( 'oi_name' => $this->name
) );
1513 while( $row = $dbw->fetchObject( $result ) ) {
1514 $oldName = $row->oi_archive_name
;
1516 $transaction->add( $this->prepareDeleteOld( $oldName, $reason, $suppress ) );
1518 // We'll need to purge this URL from caches...
1519 $urlArr[] = wfImageArchiveUrl( $oldName );
1521 $dbw->freeResult( $result );
1523 // And the current version...
1524 $transaction->add( $this->prepareDeleteCurrent( $reason, $suppress ) );
1526 $dbw->immediateCommit();
1527 } catch( MWException
$e ) {
1528 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
1529 $transaction->rollback();
1530 FileStore
::unlock();
1534 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
1535 $transaction->commit();
1536 FileStore
::unlock();
1539 // Update site_stats
1540 $site_stats = $dbw->tableName( 'site_stats' );
1541 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1543 $this->purgeEverything( $urlArr );
1550 * Delete an old version of the image.
1552 * Moves the file into an archive directory (or deletes it)
1553 * and removes the database row.
1555 * Cache purging is done; logging is caller's responsibility.
1558 * @throws MWException or FSException on database or filestore failure
1559 * @return true on success, false on some kind of failure
1561 function deleteOld( $archiveName, $reason, $suppress=false ) {
1562 $transaction = new FSTransaction();
1565 if( !FileStore
::lock() ) {
1566 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1570 $transaction = new FSTransaction();
1572 $dbw = wfGetDB( DB_MASTER
);
1574 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason, $suppress ) );
1575 $dbw->immediateCommit();
1576 } catch( MWException
$e ) {
1577 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
1578 $transaction->rollback();
1579 FileStore
::unlock();
1583 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
1584 $transaction->commit();
1585 FileStore
::unlock();
1587 $this->purgeDescription();
1591 if ( $wgUseSquid ) {
1593 wfImageArchiveUrl( $archiveName ),
1595 wfPurgeSquidServers( $urlArr );
1601 * Delete the current version of a file.
1602 * May throw a database error.
1603 * @return true on success, false on failure
1605 private function prepareDeleteCurrent( $reason, $suppress=false ) {
1606 return $this->prepareDeleteVersion(
1607 $this->getFullPath(),
1611 'fa_name' => 'img_name',
1612 'fa_archive_name' => 'NULL',
1613 'fa_size' => 'img_size',
1614 'fa_width' => 'img_width',
1615 'fa_height' => 'img_height',
1616 'fa_metadata' => 'img_metadata',
1617 'fa_bits' => 'img_bits',
1618 'fa_media_type' => 'img_media_type',
1619 'fa_major_mime' => 'img_major_mime',
1620 'fa_minor_mime' => 'img_minor_mime',
1621 'fa_description' => 'img_description',
1622 'fa_user' => 'img_user',
1623 'fa_user_text' => 'img_user_text',
1624 'fa_timestamp' => 'img_timestamp' ),
1625 array( 'img_name' => $this->name
),
1631 * Delete a given older version of a file.
1632 * May throw a database error.
1633 * @return true on success, false on failure
1635 private function prepareDeleteOld( $archiveName, $reason, $suppress=false ) {
1636 $oldpath = wfImageArchiveDir( $this->name
) .
1637 DIRECTORY_SEPARATOR
. $archiveName;
1638 return $this->prepareDeleteVersion(
1643 'fa_name' => 'oi_name',
1644 'fa_archive_name' => 'oi_archive_name',
1645 'fa_size' => 'oi_size',
1646 'fa_width' => 'oi_width',
1647 'fa_height' => 'oi_height',
1648 'fa_metadata' => 'NULL',
1649 'fa_bits' => 'oi_bits',
1650 'fa_media_type' => 'NULL',
1651 'fa_major_mime' => 'NULL',
1652 'fa_minor_mime' => 'NULL',
1653 'fa_description' => 'oi_description',
1654 'fa_user' => 'oi_user',
1655 'fa_user_text' => 'oi_user_text',
1656 'fa_timestamp' => 'oi_timestamp' ),
1658 'oi_name' => $this->name
,
1659 'oi_archive_name' => $archiveName ),
1665 * Do the dirty work of backing up an image row and its file
1666 * (if $wgSaveDeletedFiles is on) and removing the originals.
1668 * Must be run while the file store is locked and a database
1669 * transaction is open to avoid race conditions.
1671 * @return FSTransaction
1673 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $suppress=false, $fname ) {
1674 global $wgUser, $wgSaveDeletedFiles;
1676 // Dupe the file into the file store
1677 if( file_exists( $path ) ) {
1678 if( $wgSaveDeletedFiles ) {
1681 $store = FileStore
::get( $group );
1682 $key = FileStore
::calculateKey( $path, $this->extension
);
1683 $transaction = $store->insert( $key, $path,
1684 FileStore
::DELETE_ORIGINAL
);
1688 $transaction = FileStore
::deleteFile( $path );
1691 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
1694 $transaction = new FSTransaction(); // empty
1697 if( $transaction === false ) {
1699 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
1700 throw new MWException( "Could not archive and delete file $path" );
1704 // Bitfields to further supress the image content
1705 // Note that currently, live images are stored elsewhere
1706 // and cannot be partially deleted
1709 $bitfield |
= self
::DELETED_FILE
;
1710 $bitfield |
= self
::DELETED_COMMENT
;
1711 $bitfield |
= self
::DELETED_USER
;
1712 $bitfield |
= self
::DELETED_RESTRICTED
;
1715 $dbw = wfGetDB( DB_MASTER
);
1716 $storageMap = array(
1717 'fa_storage_group' => $dbw->addQuotes( $group ),
1718 'fa_storage_key' => $dbw->addQuotes( $key ),
1720 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1721 'fa_deleted_timestamp' => $dbw->timestamp(),
1722 'fa_deleted_reason' => $dbw->addQuotes( $reason ),
1723 'fa_deleted' => $bitfield);
1724 $allFields = array_merge( $storageMap, $fieldMap );
1727 if( $wgSaveDeletedFiles ) {
1728 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1730 $dbw->delete( $table, $where, $fname );
1731 } catch( DBQueryError
$e ) {
1732 // Something went horribly wrong!
1733 // Leave the file as it was...
1734 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
1735 $transaction->rollback();
1739 return $transaction;
1743 * Restore all or specified deleted revisions to the given file.
1744 * Permissions and logging are left to the caller.
1746 * May throw database exceptions on error.
1748 * @param $versions set of record ids of deleted items to restore,
1749 * or empty to restore all revisions.
1750 * @return the number of file revisions restored if successful,
1751 * or false on failure
1753 function restore( $versions=array(), $Unsuppress=false ) {
1756 if( !FileStore
::lock() ) {
1757 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
1761 $transaction = new FSTransaction();
1763 $dbw = wfGetDB( DB_MASTER
);
1766 // Re-confirm whether this image presently exists;
1767 // if no we'll need to create an image record for the
1768 // first item we restore.
1769 $exists = $dbw->selectField( 'image', '1',
1770 array( 'img_name' => $this->name
),
1773 // Fetch all or selected archived revisions for the file,
1774 // sorted from the most recent to the oldest.
1775 $conditions = array( 'fa_name' => $this->name
);
1777 $conditions['fa_id'] = $versions;
1780 $result = $dbw->select( 'filearchive', '*',
1783 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1785 if( $dbw->numRows( $result ) < count( $versions ) ) {
1786 // There's some kind of conflict or confusion;
1787 // we can't restore everything we were asked to.
1788 wfDebug( __METHOD__
.": couldn't find requested items\n" );
1790 FileStore
::unlock();
1794 if( $dbw->numRows( $result ) == 0 ) {
1796 wfDebug( __METHOD__
.": nothing to do\n" );
1798 FileStore
::unlock();
1803 while( $row = $dbw->fetchObject( $result ) ) {
1804 if ( $Unsuppress ) {
1805 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1806 } else if ( ($row->fa_deleted
& Revision
::DELETED_RESTRICTED
) && !$wgUser->isAllowed('hiderevision') ) {
1807 // Skip restoring file revisions that the user cannot restore
1811 $store = FileStore
::get( $row->fa_storage_group
);
1813 wfDebug( __METHOD__
.": skipping row with no file.\n" );
1817 if( $revisions == 1 && !$exists ) {
1818 $destDir = wfImageDir( $row->fa_name
);
1819 if ( !is_dir( $destDir ) ) {
1820 wfMkdirParents( $destDir );
1822 $destPath = $destDir . DIRECTORY_SEPARATOR
. $row->fa_name
;
1824 // We may have to fill in data if this was originally
1825 // an archived file revision.
1826 if( is_null( $row->fa_metadata
) ) {
1827 $tempFile = $store->filePath( $row->fa_storage_key
);
1829 $magic = MimeMagic
::singleton();
1830 $mime = $magic->guessMimeType( $tempFile, true );
1831 $media_type = $magic->getMediaType( $tempFile, $mime );
1832 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
1833 $handler = MediaHandler
::getHandler( $mime );
1835 $metadata = $handler->getMetadata( $image, $tempFile );
1840 $metadata = $row->fa_metadata
;
1841 $major_mime = $row->fa_major_mime
;
1842 $minor_mime = $row->fa_minor_mime
;
1843 $media_type = $row->fa_media_type
;
1848 'img_name' => $row->fa_name
,
1849 'img_size' => $row->fa_size
,
1850 'img_width' => $row->fa_width
,
1851 'img_height' => $row->fa_height
,
1852 'img_metadata' => $metadata,
1853 'img_bits' => $row->fa_bits
,
1854 'img_media_type' => $media_type,
1855 'img_major_mime' => $major_mime,
1856 'img_minor_mime' => $minor_mime,
1857 'img_description' => $row->fa_description
,
1858 'img_user' => $row->fa_user
,
1859 'img_user_text' => $row->fa_user_text
,
1860 'img_timestamp' => $row->fa_timestamp
);
1862 $archiveName = $row->fa_archive_name
;
1863 if( $archiveName == '' ) {
1864 // This was originally a current version; we
1865 // have to devise a new archive name for it.
1866 // Format is <timestamp of archiving>!<name>
1868 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
1869 '!' . $row->fa_name
;
1871 $destDir = wfImageArchiveDir( $row->fa_name
);
1872 if ( !is_dir( $destDir ) ) {
1873 wfMkdirParents( $destDir );
1875 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
1877 $table = 'oldimage';
1879 'oi_name' => $row->fa_name
,
1880 'oi_archive_name' => $archiveName,
1881 'oi_size' => $row->fa_size
,
1882 'oi_width' => $row->fa_width
,
1883 'oi_height' => $row->fa_height
,
1884 'oi_bits' => $row->fa_bits
,
1885 'oi_description' => $row->fa_description
,
1886 'oi_user' => $row->fa_user
,
1887 'oi_user_text' => $row->fa_user_text
,
1888 'oi_timestamp' => $row->fa_timestamp
);
1891 $dbw->insert( $table, $fields, __METHOD__
);
1892 // @todo this delete is not totally safe, potentially
1893 $dbw->delete( 'filearchive',
1894 array( 'fa_id' => $row->fa_id
),
1897 // Check if any other stored revisions use this file;
1898 // if so, we shouldn't remove the file from the deletion
1899 // archives so they will still work.
1900 $useCount = $dbw->selectField( 'filearchive',
1903 'fa_storage_group' => $row->fa_storage_group
,
1904 'fa_storage_key' => $row->fa_storage_key
),
1906 if( $useCount == 0 ) {
1907 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
1908 $flags = FileStore
::DELETE_ORIGINAL
;
1913 $transaction->add( $store->export( $row->fa_storage_key
,
1914 $destPath, $flags ) );
1917 $dbw->immediateCommit();
1918 } catch( MWException
$e ) {
1919 wfDebug( __METHOD__
." caught error, aborting\n" );
1920 $transaction->rollback();
1924 $transaction->commit();
1925 FileStore
::unlock();
1927 if( $revisions > 0 ) {
1929 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
1931 // Update site_stats
1932 $site_stats = $dbw->tableName( 'site_stats' );
1933 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1935 $this->purgeEverything();
1937 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
1938 $this->purgeDescription();
1946 * Returns 'true' if this image is a multipage document, e.g. a DJVU
1951 function isMultipage() {
1952 $handler = $this->getHandler();
1953 return $handler && $handler->isMultiPage();
1957 * Returns the number of pages of a multipage document, or NULL for
1958 * documents which aren't multipage documents
1960 function pageCount() {
1961 $handler = $this->getHandler();
1962 if ( $handler && $handler->isMultiPage() ) {
1963 return $handler->pageCount( $this );
1969 static function getCommonsDB() {
1971 global $wgLoadBalancer, $wgSharedUploadDBname;
1972 if ( !isset( $dbc ) ) {
1973 $i = $wgLoadBalancer->getGroupIndex( 'commons' );
1974 $dbinfo = $wgLoadBalancer->mServers
[$i];
1975 $dbc = new Database( $dbinfo['host'], $dbinfo['user'],
1976 $dbinfo['password'], $wgSharedUploadDBname );
1982 * Calculate the height of a thumbnail using the source and destination width
1984 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1985 // Exact integer multiply followed by division
1986 if ( $srcWidth == 0 ) {
1989 return round( $srcHeight * $dstWidth / $srcWidth );
1994 * Get an image size array like that returned by getimagesize(), or false if it
1995 * can't be determined.
1997 * @param string $fileName The filename
2000 function getImageSize( $fileName ) {
2001 $handler = $this->getHandler();
2002 return $handler->getImageSize( $this, $fileName );
2006 * Get the thumbnail extension and MIME type for a given source MIME type
2007 * @return array thumbnail extension and MIME type
2009 static function getThumbType( $ext, $mime ) {
2010 $handler = MediaHandler
::getHandler( $mime );
2012 return $handler->getThumbType( $ext, $mime );
2014 return array( $ext, $mime );
2027 * Returns a file object from the filearchive table
2028 * In the future, all current and old image storage
2029 * may use FileStore. There will be a "old" storage
2030 * for current and previous file revisions as well as
2031 * the "deleted" group for archived revisions
2032 * @param $title, the corresponding image page title
2033 * @param $id, the image id, a unique key
2034 * @param $key, optional storage key
2035 * @return ResultWrapper
2037 function ArchivedFile( $title, $id=0, $key='' ) {
2038 if( !is_object( $title ) ) {
2039 throw new MWException( 'Image constructor given bogus title.' );
2041 $conds = ($id) ?
"fa_id = $id" : "fa_storage_key = '$key'";
2042 if( $title->getNamespace() == NS_IMAGE
) {
2043 $dbr = wfGetDB( DB_SLAVE
);
2044 $res = $dbr->select( 'filearchive',
2064 'fa_name' => $title->getDbKey(),
2067 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2069 if ( $dbr->numRows( $res ) == 0 ) {
2070 // this revision does not exist?
2073 $ret = $dbr->resultObject( $res );
2074 $row = $ret->fetchObject();
2076 // initialize fields for filestore image object
2077 $this->mId
= intval($row->fa_id
);
2078 $this->mName
= $row->fa_name
;
2079 $this->mGroup
= $row->fa_storage_group
;
2080 $this->mKey
= $row->fa_storage_key
;
2081 $this->mSize
= $row->fa_size
;
2082 $this->mBits
= $row->fa_bits
;
2083 $this->mWidth
= $row->fa_width
;
2084 $this->mHeight
= $row->fa_height
;
2085 $this->mMetaData
= $row->fa_metadata
;
2086 $this->mMime
= "$row->fa_major_mime/$row->fa_minor_mime";
2087 $this->mType
= $row->fa_media_type
;
2088 $this->mDescription
= $row->fa_description
;
2089 $this->mUser
= $row->fa_user
;
2090 $this->mUserText
= $row->fa_user_text
;
2091 $this->mTimestamp
= $row->fa_timestamp
;
2092 $this->mDeleted
= $row->fa_deleted
;
2094 throw new MWException( 'This title does not correspond to an image page.' );
2101 * int $field one of DELETED_* bitfield constants
2102 * for file or revision rows
2105 function isDeleted( $field ) {
2106 return ($this->mDeleted
& $field) == $field;
2110 * Determine if the current user is allowed to view a particular
2111 * field of this FileStore image file, if it's marked as deleted.
2115 function userCan( $field ) {
2116 if( isset($this->mDeleted
) && ($this->mDeleted
& $field) == $field ) {
2119 $permission = ( $this->mDeleted
& Revision
::DELETED_RESTRICTED
) == Revision
::DELETED_RESTRICTED
2122 wfDebug( "Checking for $permission due to $field match on $this->mDeleted\n" );
2123 return $wgUser->isAllowed( $permission );
2131 * Aliases for backwards compatibility with 1.6
2133 define( 'MW_IMG_DELETED_FILE', Image
::DELETED_FILE
);
2134 define( 'MW_IMG_DELETED_COMMENT', Image
::DELETED_COMMENT
);
2135 define( 'MW_IMG_DELETED_USER', Image
::DELETED_USER
);
2136 define( 'MW_IMG_DELETED_RESTRICTED', Image
::DELETED_RESTRICTED
);