0b1d8d6a237ec7c600c0d05cc48e1c29ebf4fab9
7 * NOTE FOR WINDOWS USERS:
8 * To enable EXIF functions, add the folloing lines to the
9 * "Windows extensions" section of php.ini:
11 * extension=extensions/php_mbstring.dll
12 * extension=extensions/php_exif.dll
16 * Bump this number when serialized cache records may be incompatible.
18 define( 'MW_IMAGE_VERSION', 1 );
21 * Class to represent an image
23 * Provides methods to retrieve paths (physical, logical, URL),
24 * to generate thumbnails or for uploading.
32 var $name, # name of the image (constructor)
33 $imagePath, # Path of the image (loadFromXxx)
34 $url, # Image URL (accessor)
35 $title, # Title object for this image (constructor)
36 $fileExists, # does the image file exist on disk? (loadFromXxx)
37 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
38 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
39 $historyRes, # result of the query for the image's history (nextHistoryLine)
42 $bits, # --- returned by getimagesize (loadFromXxx)
44 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
45 $mime, # MIME type, determined by MimeMagic::guessMimeType
46 $size, # Size in bytes (loadFromXxx)
48 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
49 $lastError; # Error string associated with a thumbnail display error
55 * Create an Image object from an image name
57 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
60 function newFromName( $name ) {
61 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
62 if ( is_object( $title ) ) {
63 return new Image( $title );
70 * Obsolete factory function, use constructor
73 function newFromTitle( $title ) {
74 return new Image( $title );
77 function Image( $title ) {
78 if( !is_object( $title ) ) {
79 throw new MWException( 'Image constructor given bogus title.' );
81 $this->title
=& $title;
82 $this->name
= $title->getDBkey();
83 $this->metadata
= serialize ( array() ) ;
85 $n = strrpos( $this->name
, '.' );
86 $this->extension
= Image
::normalizeExtension( $n ?
87 substr( $this->name
, $n +
1 ) : '' );
88 $this->historyLine
= 0;
90 $this->dataLoaded
= false;
95 * Normalize a file extension to the common form, and ensure it's clean.
96 * Extensions with non-alphanumeric characters will be discarded.
98 * @param $ext string (without the .)
101 static function normalizeExtension( $ext ) {
102 $lower = strtolower( $ext );
108 if( isset( $squish[$lower] ) ) {
109 return $squish[$lower];
110 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
118 * Get the memcached keys
119 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
121 function getCacheKeys( ) {
122 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
124 $hashedName = md5($this->name
);
125 $keys = array( "$wgDBname:Image:$hashedName" );
126 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
127 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
133 * Try to load image metadata from memcached. Returns true on success.
135 function loadFromCache() {
136 global $wgUseSharedUploads, $wgMemc;
137 $fname = 'Image::loadFromMemcached';
138 wfProfileIn( $fname );
139 $this->dataLoaded
= false;
140 $keys = $this->getCacheKeys();
141 $cachedValues = $wgMemc->get( $keys[0] );
143 // Check if the key existed and belongs to this version of MediaWiki
144 if (!empty($cachedValues) && is_array($cachedValues)
145 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
146 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
148 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
149 # if this is shared file, we need to check if image
150 # in shared repository has not changed
151 if ( isset( $keys[1] ) ) {
152 $commonsCachedValues = $wgMemc->get( $keys[1] );
153 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
154 && isset($commonsCachedValues['version'])
155 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
156 && isset($commonsCachedValues['mime'])) {
157 wfDebug( "Pulling image metadata from shared repository cache\n" );
158 $this->name
= $commonsCachedValues['name'];
159 $this->imagePath
= $commonsCachedValues['imagePath'];
160 $this->fileExists
= $commonsCachedValues['fileExists'];
161 $this->width
= $commonsCachedValues['width'];
162 $this->height
= $commonsCachedValues['height'];
163 $this->bits
= $commonsCachedValues['bits'];
164 $this->type
= $commonsCachedValues['type'];
165 $this->mime
= $commonsCachedValues['mime'];
166 $this->metadata
= $commonsCachedValues['metadata'];
167 $this->size
= $commonsCachedValues['size'];
168 $this->fromSharedDirectory
= true;
169 $this->dataLoaded
= true;
170 $this->imagePath
= $this->getFullPath(true);
174 wfDebug( "Pulling image metadata from local cache\n" );
175 $this->name
= $cachedValues['name'];
176 $this->imagePath
= $cachedValues['imagePath'];
177 $this->fileExists
= $cachedValues['fileExists'];
178 $this->width
= $cachedValues['width'];
179 $this->height
= $cachedValues['height'];
180 $this->bits
= $cachedValues['bits'];
181 $this->type
= $cachedValues['type'];
182 $this->mime
= $cachedValues['mime'];
183 $this->metadata
= $cachedValues['metadata'];
184 $this->size
= $cachedValues['size'];
185 $this->fromSharedDirectory
= false;
186 $this->dataLoaded
= true;
187 $this->imagePath
= $this->getFullPath();
190 if ( $this->dataLoaded
) {
191 wfIncrStats( 'image_cache_hit' );
193 wfIncrStats( 'image_cache_miss' );
196 wfProfileOut( $fname );
197 return $this->dataLoaded
;
201 * Save the image metadata to memcached
203 function saveToCache() {
206 $keys = $this->getCacheKeys();
207 if ( $this->fileExists
) {
208 // We can't cache negative metadata for non-existent files,
209 // because if the file later appears in commons, the local
210 // keys won't be purged.
211 $cachedValues = array(
212 'version' => MW_IMAGE_VERSION
,
213 'name' => $this->name
,
214 'imagePath' => $this->imagePath
,
215 'fileExists' => $this->fileExists
,
216 'fromShared' => $this->fromSharedDirectory
,
217 'width' => $this->width
,
218 'height' => $this->height
,
219 'bits' => $this->bits
,
220 'type' => $this->type
,
221 'mime' => $this->mime
,
222 'metadata' => $this->metadata
,
223 'size' => $this->size
);
225 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
227 // However we should clear them, so they aren't leftover
228 // if we've deleted the file.
229 $wgMemc->delete( $keys[0] );
234 * Load metadata from the file itself
236 function loadFromFile() {
237 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang, $wgShowEXIF;
238 $fname = 'Image::loadFromFile';
239 wfProfileIn( $fname );
240 $this->imagePath
= $this->getFullPath();
241 $this->fileExists
= file_exists( $this->imagePath
);
242 $this->fromSharedDirectory
= false;
245 if (!$this->fileExists
) wfDebug("$fname: ".$this->imagePath
." not found locally!\n");
247 # If the file is not found, and a shared upload directory is used, look for it there.
248 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
249 # In case we're on a wgCapitalLinks=false wiki, we
250 # capitalize the first letter of the filename before
251 # looking it up in the shared repository.
252 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
253 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
254 if ( $this->fileExists
) {
255 $this->name
= $sharedImage->name
;
256 $this->imagePath
= $this->getFullPath(true);
257 $this->fromSharedDirectory
= true;
262 if ( $this->fileExists
) {
263 $magic=& wfGetMimeMagic();
265 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
266 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
269 $this->size
= filesize( $this->imagePath
);
271 $magic=& wfGetMimeMagic();
274 if( $this->mime
== 'image/svg' ) {
275 wfSuppressWarnings();
276 $gis = wfGetSVGsize( $this->imagePath
);
279 elseif ( !$magic->isPHPImageType( $this->mime
) ) {
280 # Don't try to get the width and height of sound and video files, that's bad for performance
283 $gis[2]= 0; //unknown
284 $gis[3]= ""; //width height string
287 wfSuppressWarnings();
288 $gis = getimagesize( $this->imagePath
);
292 wfDebug("$fname: ".$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
297 $gis[2]= 0; //unknown
298 $gis[3]= ""; //width height string
301 $this->type
= MEDIATYPE_UNKNOWN
;
302 wfDebug("$fname: ".$this->imagePath
." NOT FOUND!\n");
305 $this->width
= $gis[0];
306 $this->height
= $gis[1];
308 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
310 #NOTE: we have to set this flag early to avoid load() to be called
311 # be some of the functions below. This may lead to recursion or other bad things!
312 # as ther's only one thread of execution, this should be safe anyway.
313 $this->dataLoaded
= true;
316 $this->metadata
= serialize( $this->retrieveExifData( $this->imagePath
) );
318 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
319 else $this->bits
= 0;
321 wfProfileOut( $fname );
325 * Load image metadata from the DB
327 function loadFromDB() {
328 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
329 $fname = 'Image::loadFromDB';
330 wfProfileIn( $fname );
332 $dbr =& wfGetDB( DB_SLAVE
);
334 $this->checkDBSchema($dbr);
336 $row = $dbr->selectRow( 'image',
337 array( 'img_size', 'img_width', 'img_height', 'img_bits',
338 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
339 array( 'img_name' => $this->name
), $fname );
341 $this->fromSharedDirectory
= false;
342 $this->fileExists
= true;
343 $this->loadFromRow( $row );
344 $this->imagePath
= $this->getFullPath();
345 // Check for rows from a previous schema, quietly upgrade them
346 if ( is_null($this->type
) ) {
349 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
350 # In case we're on a wgCapitalLinks=false wiki, we
351 # capitalize the first letter of the filename before
352 # looking it up in the shared repository.
353 $name = $wgContLang->ucfirst($this->name
);
354 $dbc =& wfGetDB( DB_SLAVE
, 'commons' );
356 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
358 'img_size', 'img_width', 'img_height', 'img_bits',
359 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
360 array( 'img_name' => $name ), $fname );
362 $this->fromSharedDirectory
= true;
363 $this->fileExists
= true;
364 $this->imagePath
= $this->getFullPath(true);
366 $this->loadFromRow( $row );
368 // Check for rows from a previous schema, quietly upgrade them
369 if ( is_null($this->type
) ) {
381 $this->fileExists
= false;
382 $this->fromSharedDirectory
= false;
383 $this->metadata
= serialize ( array() ) ;
386 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
387 $this->dataLoaded
= true;
388 wfProfileOut( $fname );
392 * Load image metadata from a DB result row
394 function loadFromRow( &$row ) {
395 $this->size
= $row->img_size
;
396 $this->width
= $row->img_width
;
397 $this->height
= $row->img_height
;
398 $this->bits
= $row->img_bits
;
399 $this->type
= $row->img_media_type
;
401 $major= $row->img_major_mime
;
402 $minor= $row->img_minor_mime
;
404 if (!$major) $this->mime
= "unknown/unknown";
406 if (!$minor) $minor= "unknown";
407 $this->mime
= $major.'/'.$minor;
410 $this->metadata
= $row->img_metadata
;
411 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
413 $this->dataLoaded
= true;
417 * Load image metadata from cache or DB, unless already loaded
420 global $wgSharedUploadDBname, $wgUseSharedUploads;
421 if ( !$this->dataLoaded
) {
422 if ( !$this->loadFromCache() ) {
424 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
425 $this->loadFromFile();
426 } elseif ( $this->fileExists
) {
427 $this->saveToCache();
430 $this->dataLoaded
= true;
435 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
436 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
438 function upgradeRow() {
439 global $wgDBname, $wgSharedUploadDBname;
440 $fname = 'Image::upgradeRow';
441 wfProfileIn( $fname );
443 $this->loadFromFile();
445 if ( $this->fromSharedDirectory
) {
446 if ( !$wgSharedUploadDBname ) {
447 wfProfileOut( $fname );
451 // Write to the other DB using selectDB, not database selectors
452 // This avoids breaking replication in MySQL
453 $dbw =& wfGetDB( DB_MASTER
, 'commons' );
454 $dbw->selectDB( $wgSharedUploadDBname );
456 $dbw =& wfGetDB( DB_MASTER
);
459 $this->checkDBSchema($dbw);
461 list( $major, $minor ) = self
::splitMime( $this->mime
);
463 wfDebug("$fname: upgrading ".$this->name
." to 1.5 schema\n");
465 $dbw->update( 'image',
467 'img_width' => $this->width
,
468 'img_height' => $this->height
,
469 'img_bits' => $this->bits
,
470 'img_media_type' => $this->type
,
471 'img_major_mime' => $major,
472 'img_minor_mime' => $minor,
473 'img_metadata' => $this->metadata
,
474 ), array( 'img_name' => $this->name
), $fname
476 if ( $this->fromSharedDirectory
) {
477 $dbw->selectDB( $wgDBname );
479 wfProfileOut( $fname );
483 * Split an internet media type into its two components; if not
484 * a two-part name, set the minor type to 'unknown'.
486 * @param $mime "text/html" etc
487 * @return array ("text", "html") etc
489 static function splitMime( $mime ) {
490 if( strpos( $mime, '/' ) !== false ) {
491 return explode( '/', $mime, 2 );
493 return array( $mime, 'unknown' );
498 * Return the name of this image
506 * Return the associated title object
509 function getTitle() {
514 * Return the URL of the image file
520 if($this->fileExists
) {
521 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
529 function getViewURL() {
530 if( $this->mustRender()) {
531 if( $this->canRender() ) {
532 return $this->createThumb( $this->getWidth() );
535 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
536 return $this->getURL(); #hm... return NULL?
539 return $this->getURL();
544 * Return the image path of the image in the
545 * local file system as an absolute path
548 function getImagePath() {
550 return $this->imagePath
;
554 * Return the width of the image
556 * Returns -1 if the file specified is not a known image type
559 function getWidth() {
565 * Return the height of the image
567 * Returns -1 if the file specified is not a known image type
570 function getHeight() {
572 return $this->height
;
576 * Return the size of the image file, in bytes
585 * Returns the mime type of the file.
587 function getMimeType() {
593 * Return the type of the media in the file.
594 * Use the value returned by this function with the MEDIATYPE_xxx constants.
596 function getMediaType() {
602 * Checks if the file can be presented to the browser as a bitmap.
604 * Currently, this checks if the file is an image format
605 * that can be converted to a format
606 * supported by all browsers (namely GIF, PNG and JPEG),
607 * or if it is an SVG image and SVG conversion is enabled.
609 * @todo remember the result of this check.
611 function canRender() {
612 global $wgUseImageMagick;
614 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
616 $mime= $this->getMimeType();
618 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
620 #if it's SVG, check if there's a converter enabled
621 if ($mime === 'image/svg') {
622 global $wgSVGConverters, $wgSVGConverter;
624 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
625 wfDebug( "Image::canRender: SVG is ready!\n" );
628 wfDebug( "Image::canRender: SVG renderer missing\n" );
632 #image formats available on ALL browsers
633 if ( $mime === 'image/gif'
634 ||
$mime === 'image/png'
635 ||
$mime === 'image/jpeg' ) return true;
637 #image formats that can be converted to the above formats
638 if ($wgUseImageMagick) {
639 #convertable by ImageMagick (there are more...)
640 if ( $mime === 'image/vnd.wap.wbmp'
641 ||
$mime === 'image/x-xbitmap'
642 ||
$mime === 'image/x-xpixmap'
643 #|| $mime === 'image/x-icon' #file may be split into multiple parts
644 ||
$mime === 'image/x-portable-anymap'
645 ||
$mime === 'image/x-portable-bitmap'
646 ||
$mime === 'image/x-portable-graymap'
647 ||
$mime === 'image/x-portable-pixmap'
648 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
649 ||
$mime === 'image/x-rgb'
650 ||
$mime === 'image/x-bmp'
651 ||
$mime === 'image/tiff' ) return true;
654 #convertable by the PHP GD image lib
655 if ( $mime === 'image/vnd.wap.wbmp'
656 ||
$mime === 'image/x-xbitmap' ) return true;
664 * Return true if the file is of a type that can't be directly
665 * rendered by typical browsers and needs to be re-rasterized.
667 * This returns true for everything but the bitmap types
668 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
669 * also return true for any non-image formats.
673 function mustRender() {
674 $mime= $this->getMimeType();
676 if ( $mime === "image/gif"
677 ||
$mime === "image/png"
678 ||
$mime === "image/jpeg" ) return false;
684 * Determines if this media file may be shown inline on a page.
686 * This is currently synonymous to canRender(), but this could be
687 * extended to also allow inline display of other media,
688 * like flash animations or videos. If you do so, please keep in mind that
689 * that could be a security risk.
691 function allowInlineDisplay() {
692 return $this->canRender();
696 * Determines if this media file is in a format that is unlikely to
697 * contain viruses or malicious content. It uses the global
698 * $wgTrustedMediaFormats list to determine if the file is safe.
700 * This is used to show a warning on the description page of non-safe files.
701 * It may also be used to disallow direct [[media:...]] links to such files.
703 * Note that this function will always return true if allowInlineDisplay()
704 * or isTrustedFile() is true for this file.
706 function isSafeFile() {
707 if ($this->allowInlineDisplay()) return true;
708 if ($this->isTrustedFile()) return true;
710 global $wgTrustedMediaFormats;
712 $type= $this->getMediaType();
713 $mime= $this->getMimeType();
714 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
716 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
717 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
719 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
720 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
725 /** Returns true if the file is flagged as trusted. Files flagged that way
726 * can be linked to directly, even if that is not allowed for this type of
729 * This is a dummy function right now and always returns false. It could be
730 * implemented to extract a flag from the database. The trusted flag could be
731 * set on upload, if the user has sufficient privileges, to bypass script-
732 * and html-filters. It may even be coupled with cryptographics signatures
735 function isTrustedFile() {
736 #this could be implemented to check a flag in the databas,
737 #look for signatures, etc
742 * Return the escapeLocalURL of this image
745 function getEscapeLocalURL() {
747 return $this->title
->escapeLocalURL();
751 * Return the escapeFullURL of this image
754 function getEscapeFullURL() {
756 return $this->title
->escapeFullURL();
760 * Return the URL of an image, provided its name.
762 * @param string $name Name of the image, without the leading "Image:"
763 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
764 * @return string URL of $name image
768 function imageUrl( $name, $fromSharedDirectory = false ) {
769 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
770 if($fromSharedDirectory) {
772 $path = $wgSharedUploadPath;
774 $base = $wgUploadBaseUrl;
775 $path = $wgUploadPath;
777 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
778 return wfUrlencode( $url );
782 * Returns true if the image file exists on disk.
783 * @return boolean Whether image file exist on disk.
788 return $this->fileExists
;
795 function thumbUrl( $width, $subdir='thumb') {
796 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
797 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
799 // Generate thumb.php URL if possible
803 if ( $this->fromSharedDirectory
) {
804 if ( $wgSharedThumbnailScriptPath ) {
805 $script = $wgSharedThumbnailScriptPath;
808 if ( $wgThumbnailScriptPath ) {
809 $script = $wgThumbnailScriptPath;
813 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
814 if( $this->mustRender() ) {
818 $name = $this->thumbName( $width );
819 if($this->fromSharedDirectory
) {
821 $path = $wgSharedUploadPath;
823 $base = $wgUploadBaseUrl;
824 $path = $wgUploadPath;
826 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
827 $url = "{$base}{$path}/{$subdir}" .
828 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
829 . $this->name
.'/'.$name;
830 $url = wfUrlencode( $url );
832 $url = "{$base}{$path}/{$subdir}/{$name}";
835 return array( $script !== false, $url );
839 * Return the file name of a thumbnail of the specified width
841 * @param integer $width Width of the thumbnail image
842 * @param boolean $shared Does the thumbnail come from the shared repository?
845 function thumbName( $width ) {
846 $thumb = $width."px-".$this->name
;
848 if( $this->mustRender() ) {
849 if( $this->canRender() ) {
850 # Rasterize to PNG (for SVG vector images, etc)
854 #should we use iconThumb here to get a symbolic thumbnail?
855 #or should we fail with an internal error?
856 return NULL; //can't make bitmap
863 * Create a thumbnail of the image having the specified width/height.
864 * The thumbnail will not be created if the width is larger than the
865 * image's width. Let the browser do the scaling in this case.
866 * The thumbnail is stored on disk and is only computed if the thumbnail
867 * file does not exist OR if it is older than the image.
870 * Keeps aspect ratio of original image. If both width and height are
871 * specified, the generated image will be no bigger than width x height,
872 * and will also have correct aspect ratio.
874 * @param integer $width maximum width of the generated thumbnail
875 * @param integer $height maximum height of the image (optional)
878 function createThumb( $width, $height=-1 ) {
879 $thumb = $this->getThumbnail( $width, $height );
880 if( is_null( $thumb ) ) return '';
881 return $thumb->getUrl();
885 * As createThumb, but returns a ThumbnailImage object. This can
886 * provide access to the actual file, the real size of the thumb,
887 * and can produce a convenient <img> tag for you.
889 * @param integer $width maximum width of the generated thumbnail
890 * @param integer $height maximum height of the image (optional)
891 * @return ThumbnailImage or null on failure
894 function getThumbnail( $width, $height=-1 ) {
895 if ( $height <= 0 ) {
896 return $this->renderThumb( $width );
900 if ($this->canRender()) {
901 if ( $width > $this->width
* $height / $this->height
)
902 $width = wfFitBoxWidth( $this->width
, $this->height
, $height );
903 $thumb = $this->renderThumb( $width );
905 else $thumb= NULL; #not a bitmap or renderable image, don't try.
911 * @return ThumbnailImage
913 function iconThumb() {
914 global $wgStylePath, $wgStyleDirectory;
916 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
917 foreach( $try as $icon ) {
918 $path = '/common/images/icons/' . $icon;
919 $filepath = $wgStyleDirectory . $path;
920 if( file_exists( $filepath ) ) {
921 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
928 * Create a thumbnail of the image having the specified width.
929 * The thumbnail will not be created if the width is larger than the
930 * image's width. Let the browser do the scaling in this case.
931 * The thumbnail is stored on disk and is only computed if the thumbnail
932 * file does not exist OR if it is older than the image.
933 * Returns an object which can return the pathname, URL, and physical
934 * pixel size of the thumbnail -- or null on failure.
936 * @return ThumbnailImage or null on failure
939 function renderThumb( $width, $useScript = true ) {
941 global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
943 $fname = 'Image::renderThumb';
944 wfProfileIn( $fname );
946 $width = intval( $width );
949 if ( ! $this->exists() )
951 # If there is no image, there will be no thumbnail
952 wfProfileOut( $fname );
956 # Sanity check $width
957 if( $width <= 0 ||
$this->width
<= 0) {
959 wfProfileOut( $fname );
963 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
964 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
965 # an exception for it.
966 if ( $this->getMediaType() == MEDIATYPE_BITMAP
&&
967 $this->getMimeType() !== 'image/jpeg' &&
968 $this->width
* $this->height
> $wgMaxImageArea )
970 wfProfileOut( $fname );
974 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
975 if ( $this->mustRender() ) {
976 $width = min( $width, $wgSVGMaxSize );
977 } elseif ( $width > $this->width
- 1 ) {
978 $thumb = new ThumbnailImage( $this->getURL(), $this->getWidth(), $this->getHeight() );
979 wfProfileOut( $fname );
983 $height = round( $this->height
* $width / $this->width
);
985 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
986 if ( $isScriptUrl && $useScript ) {
987 // Use thumb.php to render the image
988 $thumb = new ThumbnailImage( $url, $width, $height );
989 wfProfileOut( $fname );
993 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
994 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
996 if ( is_dir( $thumbPath ) ) {
997 // Directory where file should be
998 // This happened occasionally due to broken migration code in 1.5
999 // Rename to broken-*
1000 global $wgUploadDirectory;
1001 for ( $i = 0; $i < 100 ; $i++
) {
1002 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1003 if ( !file_exists( $broken ) ) {
1004 rename( $thumbPath, $broken );
1008 // Code below will ask if it exists, and the answer is now no
1013 if ( !file_exists( $thumbPath ) ||
1014 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX
, $wgThumbnailEpoch ) ) {
1015 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
1019 // Migration from old directory structure
1020 if ( is_file( $oldThumbPath ) ) {
1021 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
1022 if ( file_exists( $thumbPath ) ) {
1023 if ( !is_dir( $thumbPath ) ) {
1024 // Old image in the way of rename
1025 unlink( $thumbPath );
1027 // This should have been dealt with already
1028 throw new MWException( "Directory where image should be: $thumbPath" );
1031 // Rename the old image into the new location
1032 rename( $oldThumbPath, $thumbPath );
1035 unlink( $oldThumbPath );
1039 $this->lastError
= $this->reallyRenderThumb( $thumbPath, $width, $height );
1040 if ( $this->lastError
=== true ) {
1042 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1043 // Log the error but output anyway.
1044 // With luck it's a transitory error...
1049 # This has to be done after the image is updated and present for all machines on NFS,
1050 # or else the old version might be stored into the squid again
1051 if ( $wgUseSquid ) {
1052 $urlArr = array( $url );
1053 wfPurgeSquidServers($urlArr);
1059 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1063 wfProfileOut( $fname );
1065 } // END OF function renderThumb
1068 * Really render a thumbnail
1069 * Call this only for images for which canRender() returns true.
1071 * @param string $thumbPath Path to thumbnail
1072 * @param int $width Desired width in pixels
1073 * @param int $height Desired height in pixels
1074 * @return bool True on error, false or error string on failure.
1077 function reallyRenderThumb( $thumbPath, $width, $height ) {
1078 global $wgSVGConverters, $wgSVGConverter;
1079 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1080 global $wgCustomConvertCommand;
1088 if( $this->mime
=== "image/svg" ) {
1089 #Right now we have only SVG
1091 global $wgSVGConverters, $wgSVGConverter;
1092 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1093 global $wgSVGConverterPath;
1095 array( '$path/', '$width', '$height', '$input', '$output' ),
1096 array( $wgSVGConverterPath ?
"$wgSVGConverterPath/" : "",
1099 wfEscapeShellArg( $this->imagePath
),
1100 wfEscapeShellArg( $thumbPath ) ),
1101 $wgSVGConverters[$wgSVGConverter] );
1102 wfProfileIn( 'rsvg' );
1103 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1104 $err = wfShellExec( $cmd, $retval );
1105 wfProfileOut( 'rsvg' );
1107 } elseif ( $wgUseImageMagick ) {
1110 if ( $this->mime
== 'image/jpeg' ) {
1111 $quality = "-quality 80"; // 80%
1112 } elseif ( $this->mime
== 'image/png' ) {
1113 $quality = "-quality 95"; // zlib 9, adaptive filtering
1115 $quality = ''; // default
1118 # Specify white background color, will be used for transparent images
1119 # in Internet Explorer/Windows instead of default black.
1121 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1122 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1123 # the wrong size in the second case.
1125 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1126 " {$quality} -background white -size {$width} ".
1127 wfEscapeShellArg($this->imagePath
) .
1128 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1130 // For the -resize option a "!" is needed to force exact size,
1131 // or ImageMagick may decide your ratio is wrong and slice off
1133 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1135 wfEscapeShellArg($thumbPath) . " 2>&1";
1136 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1137 wfProfileIn( 'convert' );
1138 $err = wfShellExec( $cmd, $retval );
1139 wfProfileOut( 'convert' );
1140 } elseif( $wgCustomConvertCommand ) {
1141 # Use a custom convert command
1142 # Variables: %s %d %w %h
1143 $src = wfEscapeShellArg( $this->imagePath
);
1144 $dst = wfEscapeShellArg( $thumbPath );
1145 $cmd = $wgCustomConvertCommand;
1146 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1147 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1148 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1149 wfProfileIn( 'convert' );
1150 $err = wfShellExec( $cmd, $retval );
1151 wfProfileOut( 'convert' );
1153 # Use PHP's builtin GD library functions.
1155 # First find out what kind of file this is, and select the correct
1156 # input routine for this.
1159 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1160 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1161 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1162 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1163 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1165 if( !isset( $typemap[$this->mime
] ) ) {
1166 $err = 'Image type not supported';
1167 wfDebug( "$err\n" );
1170 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1172 if( !function_exists( $loader ) ) {
1173 $err = "Incomplete GD library configuration: missing function $loader";
1174 wfDebug( "$err\n" );
1177 if( $colorStyle == 'palette' ) {
1179 } elseif( $colorStyle == 'truecolor' ) {
1181 } elseif( $colorStyle == 'bits' ) {
1182 $truecolor = ( $this->bits
> 8 );
1185 $src_image = call_user_func( $loader, $this->imagePath
);
1187 $dst_image = imagecreatetruecolor( $width, $height );
1189 $dst_image = imagecreate( $width, $height );
1191 imagecopyresampled( $dst_image, $src_image,
1193 $width, $height, $this->width
, $this->height
);
1194 call_user_func( $saveType, $dst_image, $thumbPath );
1195 imagedestroy( $dst_image );
1196 imagedestroy( $src_image );
1200 # Check for zero-sized thumbnails. Those can be generated when
1201 # no disk space is available or some other error occurs
1203 if( file_exists( $thumbPath ) ) {
1204 $thumbstat = stat( $thumbPath );
1205 if( $thumbstat['size'] == 0 ||
$retval != 0 ) {
1206 wfDebugLog( 'thumbnail',
1207 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1208 $thumbstat['size'], $thumbPath ) );
1209 unlink( $thumbPath );
1212 if ( $retval != 0 ) {
1213 wfDebugLog( 'thumbnail',
1214 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1215 wfHostname(), $retval, trim($err), $cmd ) );
1216 return wfMsg( 'thumbnail_error', $err );
1222 function getLastError() {
1223 return $this->lastError
;
1226 function imageJpegWrapper( $dst_image, $thumbPath ) {
1227 imageinterlace( $dst_image );
1228 imagejpeg( $dst_image, $thumbPath, 95 );
1232 * Get all thumbnail names previously generated for this image
1234 function getThumbnails( $shared = false ) {
1235 if ( Image
::isHashed( $shared ) ) {
1238 $dir = wfImageThumbDir( $this->name
, $shared );
1240 // This generates an error on failure, hence the @
1241 $handle = @opendir
( $dir );
1244 while ( false !== ( $file = readdir($handle) ) ) {
1245 if ( $file{0} != '.' ) {
1249 closedir( $handle );
1259 * Refresh metadata in memcached, but don't touch thumbnails or squid
1261 function purgeMetadataCache() {
1263 $this->loadFromFile();
1264 $this->saveToCache();
1268 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1270 function purgeCache( $archiveFiles = array(), $shared = false ) {
1273 // Refresh metadata cache
1274 $this->purgeMetadataCache();
1276 // Delete thumbnails
1277 $files = $this->getThumbnails( $shared );
1278 $dir = wfImageThumbDir( $this->name
, $shared );
1280 foreach ( $files as $file ) {
1281 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1282 $urls[] = $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1283 @unlink
( "$dir/$file" );
1288 if ( $wgUseSquid ) {
1289 $urls[] = $this->getViewURL();
1290 foreach ( $archiveFiles as $file ) {
1291 $urls[] = wfImageArchiveUrl( $file );
1293 wfPurgeSquidServers( $urls );
1298 * Purge the image description page, but don't go after
1299 * pages using the image. Use when modifying file history
1300 * but not the current data.
1302 function purgeDescription() {
1303 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1304 $page->invalidateCache();
1308 * Purge metadata and all affected pages when the image is created,
1309 * deleted, or majorly updated. A set of additional URLs may be
1310 * passed to purge, such as specific image files which have changed.
1311 * @param $urlArray array
1313 function purgeEverything( $urlArr=array() ) {
1314 // Delete thumbnails and refresh image metadata cache
1315 $this->purgeCache();
1316 $this->purgeDescription();
1318 // Purge cache of all pages using this image
1319 $linksTo = $this->getLinksTo();
1320 global $wgUseSquid, $wgPostCommitUpdateList;
1321 if ( $wgUseSquid ) {
1322 $u = SquidUpdate
::newFromTitles( $linksTo, $urlArr );
1323 array_push( $wgPostCommitUpdateList, $u );
1326 // Invalidate parser cache and client cache for pages using this image
1327 // This is left until relatively late to reduce lock time
1328 Title
::touchArray( $linksTo );
1331 function checkDBSchema(&$db) {
1332 global $wgCheckDBSchema;
1333 if (!$wgCheckDBSchema) {
1336 # img_name must be unique
1337 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1338 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1341 # new fields must exist
1343 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1344 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1345 # something. The only reason I put the above schema check in was because the absence of that particular
1346 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1349 if ( !$db->fieldExists( 'image', 'img_media_type' )
1350 || !$db->fieldExists( 'image', 'img_metadata' )
1351 || !$db->fieldExists( 'image', 'img_width' ) ) {
1353 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1359 * Return the image history of this image, line by line.
1360 * starts with current version, then old versions.
1361 * uses $this->historyLine to check which line to return:
1362 * 0 return line for current version
1363 * 1 query for old versions, return first one
1364 * 2, ... return next old version from above query
1368 function nextHistoryLine() {
1369 $fname = 'Image::nextHistoryLine()';
1370 $dbr =& wfGetDB( DB_SLAVE
);
1372 $this->checkDBSchema($dbr);
1374 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1375 $this->historyRes
= $dbr->select( 'image',
1379 'img_user','img_user_text',
1383 "'' AS oi_archive_name"
1385 array( 'img_name' => $this->title
->getDBkey() ),
1388 if ( 0 == wfNumRows( $this->historyRes
) ) {
1391 } else if ( $this->historyLine
== 1 ) {
1392 $this->historyRes
= $dbr->select( 'oldimage',
1394 'oi_size AS img_size',
1395 'oi_description AS img_description',
1396 'oi_user AS img_user',
1397 'oi_user_text AS img_user_text',
1398 'oi_timestamp AS img_timestamp',
1399 'oi_width as img_width',
1400 'oi_height as img_height',
1403 array( 'oi_name' => $this->title
->getDBkey() ),
1405 array( 'ORDER BY' => 'oi_timestamp DESC' )
1408 $this->historyLine ++
;
1410 return $dbr->fetchObject( $this->historyRes
);
1414 * Reset the history pointer to the first element of the history
1417 function resetHistory() {
1418 $this->historyLine
= 0;
1422 * Return the full filesystem path to the file. Note that this does
1423 * not mean that a file actually exists under that location.
1425 * This path depends on whether directory hashing is active or not,
1426 * i.e. whether the images are all found in the same directory,
1427 * or in hashed paths like /images/3/3c.
1430 * @param boolean $fromSharedDirectory Return the path to the file
1431 * in a shared repository (see $wgUseSharedRepository and related
1432 * options in DefaultSettings.php) instead of a local one.
1435 function getFullPath( $fromSharedRepository = false ) {
1436 global $wgUploadDirectory, $wgSharedUploadDirectory;
1438 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1441 // $wgSharedUploadDirectory may be false, if thumb.php is used
1443 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1455 function isHashed( $shared ) {
1456 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1457 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1461 * Record an image upload in the upload log and the image table
1463 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1464 global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1466 $fname = 'Image::recordUpload';
1467 $dbw =& wfGetDB( DB_MASTER
);
1469 $this->checkDBSchema($dbw);
1471 // Delete thumbnails and refresh the metadata cache
1472 $this->purgeCache();
1474 // Fail now if the image isn't there
1475 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1476 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1480 if ( $wgUseCopyrightUpload ) {
1481 if ( $license != '' ) {
1482 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1484 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1485 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1487 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1489 if ( $license != '' ) {
1490 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1491 $textdesc = $filedesc .
1492 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1498 $now = $dbw->timestamp();
1501 if (strpos($this->mime
,'/')!==false) {
1502 list($major,$minor)= explode('/',$this->mime
,2);
1505 $major= $this->mime
;
1509 # Test to see if the row exists using INSERT IGNORE
1510 # This avoids race conditions by locking the row until the commit, and also
1511 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1512 $dbw->insert( 'image',
1514 'img_name' => $this->name
,
1515 'img_size'=> $this->size
,
1516 'img_width' => intval( $this->width
),
1517 'img_height' => intval( $this->height
),
1518 'img_bits' => $this->bits
,
1519 'img_media_type' => $this->type
,
1520 'img_major_mime' => $major,
1521 'img_minor_mime' => $minor,
1522 'img_timestamp' => $now,
1523 'img_description' => $desc,
1524 'img_user' => $wgUser->getID(),
1525 'img_user_text' => $wgUser->getName(),
1526 'img_metadata' => $this->metadata
,
1531 $descTitle = $this->getTitle();
1532 $purgeURLs = array();
1534 if( $dbw->affectedRows() == 0 ) {
1535 # Collision, this is an update of an image
1536 # Insert previous contents into oldimage
1537 $dbw->insertSelect( 'oldimage', 'image',
1539 'oi_name' => 'img_name',
1540 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1541 'oi_size' => 'img_size',
1542 'oi_width' => 'img_width',
1543 'oi_height' => 'img_height',
1544 'oi_bits' => 'img_bits',
1545 'oi_timestamp' => 'img_timestamp',
1546 'oi_description' => 'img_description',
1547 'oi_user' => 'img_user',
1548 'oi_user_text' => 'img_user_text',
1549 ), array( 'img_name' => $this->name
), $fname
1552 # Update the current image row
1553 $dbw->update( 'image',
1555 'img_size' => $this->size
,
1556 'img_width' => intval( $this->width
),
1557 'img_height' => intval( $this->height
),
1558 'img_bits' => $this->bits
,
1559 'img_media_type' => $this->type
,
1560 'img_major_mime' => $major,
1561 'img_minor_mime' => $minor,
1562 'img_timestamp' => $now,
1563 'img_description' => $desc,
1564 'img_user' => $wgUser->getID(),
1565 'img_user_text' => $wgUser->getName(),
1566 'img_metadata' => $this->metadata
,
1567 ), array( /* WHERE */
1568 'img_name' => $this->name
1572 # This is a new image
1573 # Update the image count
1574 $site_stats = $dbw->tableName( 'site_stats' );
1575 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
1578 $article = new Article( $descTitle );
1580 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1581 $suppressRC = true; // There's already a log entry, so don't double the RC load
1583 if( $descTitle->exists() ) {
1584 // TODO: insert a null revision into the page history for this update.
1586 $wgUser->addWatch( $descTitle );
1589 # Invalidate the cache for the description page
1590 $descTitle->invalidateCache();
1591 $purgeURLs[] = $descTitle->getInternalURL();
1593 // New image; create the description page.
1594 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1597 # Invalidate cache for all pages using this image
1598 $linksTo = $this->getLinksTo();
1600 if ( $wgUseSquid ) {
1601 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1602 array_push( $wgPostCommitUpdateList, $u );
1604 Title
::touchArray( $linksTo );
1606 $log = new LogPage( 'upload' );
1607 $log->addEntry( 'upload', $descTitle, $desc );
1613 * Get an array of Title objects which are articles which use this image
1614 * Also adds their IDs to the link cache
1616 * This is mostly copied from Title::getLinksTo()
1618 function getLinksTo( $options = '' ) {
1619 $fname = 'Image::getLinksTo';
1620 wfProfileIn( $fname );
1623 $db =& wfGetDB( DB_MASTER
);
1625 $db =& wfGetDB( DB_SLAVE
);
1627 $linkCache =& LinkCache
::singleton();
1629 extract( $db->tableNames( 'page', 'imagelinks' ) );
1630 $encName = $db->addQuotes( $this->name
);
1631 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1632 $res = $db->query( $sql, $fname );
1635 if ( $db->numRows( $res ) ) {
1636 while ( $row = $db->fetchObject( $res ) ) {
1637 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1638 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1639 $retVal[] = $titleObj;
1643 $db->freeResult( $res );
1644 wfProfileOut( $fname );
1649 * Retrive Exif data from the file and prune unrecognized tags
1650 * and/or tags with invalid contents
1655 private function retrieveExifData( $filename ) {
1659 if ( $this->getMimeType() !== "image/jpeg" )
1663 if( $wgShowEXIF && file_exists( $filename ) ) {
1664 $exif = new Exif( $filename );
1665 return $exif->getFilteredData();
1671 function getExifData() {
1673 if ( $this->metadata
=== '0' )
1676 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1677 $ret = unserialize( $this->metadata
);
1679 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1680 $newver = Exif
::version();
1682 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1683 $this->purgeMetadataCache();
1684 $this->updateExifData( $newver );
1686 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1687 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1688 $format = new FormatExif( $ret );
1690 return $format->getFormattedData();
1693 function updateExifData( $version ) {
1694 $fname = 'Image:updateExifData';
1696 if ( $this->getImagePath() === false ) # Not a local image
1699 # Get EXIF data from image
1700 $exif = $this->retrieveExifData( $this->imagePath
);
1701 if ( count( $exif ) ) {
1702 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1703 $this->metadata
= serialize( $exif );
1705 $this->metadata
= '0';
1708 # Update EXIF data in database
1709 $dbw =& wfGetDB( DB_MASTER
);
1711 $this->checkDBSchema($dbw);
1713 $dbw->update( 'image',
1714 array( 'img_metadata' => $this->metadata
),
1715 array( 'img_name' => $this->name
),
1721 * Returns true if the image does not come from the shared
1726 function isLocal() {
1727 return !$this->fromSharedDirectory
;
1731 * Was this image ever deleted from the wiki?
1735 function wasDeleted() {
1736 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1737 return ( $title->isDeleted() > 0 );
1741 * Delete all versions of the image.
1743 * Moves the files into an archive directory (or deletes them)
1744 * and removes the database rows.
1746 * Cache purging is done; logging is caller's responsibility.
1749 * @return true on success, false on some kind of failure
1751 function delete( $reason ) {
1752 $fname = __CLASS__
. '::' . __FUNCTION__
;
1753 $transaction = new FSTransaction();
1754 $urlArr = array( $this->getURL() );
1756 if( !FileStore
::lock() ) {
1757 wfDebug( "$fname: failed to acquire file store lock, aborting\n" );
1762 $dbw = wfGetDB( DB_MASTER
);
1765 // Delete old versions
1766 $result = $dbw->select( 'oldimage',
1767 array( 'oi_archive_name' ),
1768 array( 'oi_name' => $this->name
) );
1770 while( $row = $dbw->fetchObject( $result ) ) {
1771 $oldName = $row->oi_archive_name
;
1773 $transaction->add( $this->prepareDeleteOld( $oldName, $reason ) );
1775 // We'll need to purge this URL from caches...
1776 $urlArr[] = wfImageArchiveUrl( $oldName );
1778 $dbw->freeResult( $result );
1780 // And the current version...
1781 $transaction->add( $this->prepareDeleteCurrent( $reason ) );
1783 $dbw->immediateCommit();
1784 } catch( MWException
$e ) {
1785 wfDebug( "$fname: db error, rolling back file transactions\n" );
1786 $transaction->rollback();
1787 FileStore
::unlock();
1791 wfDebug( "$fname: deleted db items, applying file transactions\n" );
1792 $transaction->commit();
1793 FileStore
::unlock();
1796 // Update site_stats
1797 $site_stats = $dbw->tableName( 'site_stats' );
1798 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", $fname );
1800 $this->purgeEverything( $urlArr );
1807 * Delete an old version of the image.
1809 * Moves the file into an archive directory (or deletes it)
1810 * and removes the database row.
1812 * Cache purging is done; logging is caller's responsibility.
1815 * @throws MWException or FSException on database or filestore failure
1816 * @return true on success, false on some kind of failure
1818 function deleteOld( $archiveName, $reason ) {
1819 $fname = __CLASS__
. '::' . __FUNCTION__
;
1820 $transaction = new FSTransaction();
1823 if( !FileStore
::lock() ) {
1824 wfDebug( "$fname: failed to acquire file store lock, aborting\n" );
1828 $transaction = new FSTransaction();
1830 $dbw = wfGetDB( DB_MASTER
);
1832 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason ) );
1833 $dbw->immediateCommit();
1834 } catch( MWException
$e ) {
1835 wfDebug( "$fname: db error, rolling back file transaction\n" );
1836 $transaction->rollback();
1837 FileStore
::unlock();
1841 wfDebug( "$fname: deleted db items, applying file transaction\n" );
1842 $transaction->commit();
1843 FileStore
::unlock();
1845 $this->purgeDescription();
1849 if ( $wgUseSquid ) {
1851 wfImageArchiveUrl( $archiveName ),
1852 $page->getInternalURL()
1854 wfPurgeSquidServers( $urlArr );
1860 * Delete the current version of a file.
1861 * May throw a database error.
1862 * @return true on success, false on failure
1864 private function prepareDeleteCurrent( $reason ) {
1865 $fname = __CLASS__
. '::' . __FUNCTION__
;
1866 return $this->prepareDeleteVersion(
1867 $this->getFullPath(),
1871 'fa_name' => 'img_name',
1872 'fa_archive_name' => 'NULL',
1873 'fa_size' => 'img_size',
1874 'fa_width' => 'img_width',
1875 'fa_height' => 'img_height',
1876 'fa_metadata' => 'img_metadata',
1877 'fa_bits' => 'img_bits',
1878 'fa_media_type' => 'img_media_type',
1879 'fa_major_mime' => 'img_major_mime',
1880 'fa_minor_mime' => 'img_minor_mime',
1881 'fa_description' => 'img_description',
1882 'fa_user' => 'img_user',
1883 'fa_user_text' => 'img_user_text',
1884 'fa_timestamp' => 'img_timestamp' ),
1885 array( 'img_name' => $this->name
),
1890 * Delete a given older version of a file.
1891 * May throw a database error.
1892 * @return true on success, false on failure
1894 private function prepareDeleteOld( $archiveName, $reason ) {
1895 $fname = __CLASS__
. '::' . __FUNCTION__
;
1896 $oldpath = wfImageArchiveDir( $this->name
) .
1897 DIRECTORY_SEPARATOR
. $archiveName;
1898 return $this->prepareDeleteVersion(
1903 'fa_name' => 'oi_name',
1904 'fa_archive_name' => 'oi_archive_name',
1905 'fa_size' => 'oi_size',
1906 'fa_width' => 'oi_width',
1907 'fa_height' => 'oi_height',
1908 'fa_metadata' => 'NULL',
1909 'fa_bits' => 'oi_bits',
1910 'fa_media_type' => 'NULL',
1911 'fa_major_mime' => 'NULL',
1912 'fa_minor_mime' => 'NULL',
1913 'fa_description' => 'oi_description',
1914 'fa_user' => 'oi_user',
1915 'fa_user_text' => 'oi_user_text',
1916 'fa_timestamp' => 'oi_timestamp' ),
1918 'oi_name' => $this->name
,
1919 'oi_archive_name' => $archiveName ),
1924 * Do the dirty work of backing up an image row and its file
1925 * (if $wgSaveDeletedFiles is on) and removing the originals.
1927 * Must be run while the file store is locked and a database
1928 * transaction is open to avoid race conditions.
1930 * @return FSTransaction
1932 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $fname ) {
1933 global $wgUser, $wgSaveDeletedFiles;
1935 // Dupe the file into the file store
1936 if( file_exists( $path ) ) {
1937 if( $wgSaveDeletedFiles ) {
1940 $store = FileStore
::get( $group );
1941 $key = FileStore
::calculateKey( $path, $this->extension
);
1942 $transaction = $store->insert( $key, $path,
1943 FileStore
::DELETE_ORIGINAL
);
1947 $transaction = FileStore
::deleteFile( $path );
1950 wfDebug( "$fname deleting already-missing '$path'; moving on to database\n" );
1953 $transaction = new FSTransaction(); // empty
1956 if( $transaction === false ) {
1958 wfDebug( "$fname: import to file store failed, aborting\n" );
1959 throw new MWException( "Could not archive and delete file $path" );
1963 $dbw = wfGetDB( DB_MASTER
);
1964 $storageMap = array(
1965 'fa_storage_group' => $dbw->addQuotes( $group ),
1966 'fa_storage_key' => $dbw->addQuotes( $key ),
1968 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1969 'fa_deleted_timestamp' => $dbw->timestamp(),
1970 'fa_deleted_reason' => $dbw->addQuotes( $reason ) );
1971 $allFields = array_merge( $storageMap, $fieldMap );
1974 if( $wgSaveDeletedFiles ) {
1975 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1977 $dbw->delete( $table, $where, $fname );
1978 } catch( DBQueryError
$e ) {
1979 // Something went horribly wrong!
1980 // Leave the file as it was...
1981 wfDebug( "$fname: database error, rolling back file transaction\n" );
1982 $transaction->rollback();
1986 return $transaction;
1990 * Restore all or specified deleted revisions to the given file.
1991 * Permissions and logging are left to the caller.
1993 * May throw database exceptions on error.
1995 * @param $versions set of record ids of deleted items to restore,
1996 * or empty to restore all revisions.
1997 * @return the number of file revisions restored if successful,
1998 * or false on failure
2000 function restore( $versions=array() ) {
2001 $fname = __CLASS__
. '::' . __FUNCTION__
;
2002 if( !FileStore
::lock() ) {
2003 wfDebug( "$fname could not acquire filestore lock\n" );
2007 $transaction = new FSTransaction();
2009 $dbw = wfGetDB( DB_MASTER
);
2012 // Re-confirm whether this image presently exists;
2013 // if no we'll need to create an image record for the
2014 // first item we restore.
2015 $exists = $dbw->selectField( 'image', '1',
2016 array( 'img_name' => $this->name
),
2019 // Fetch all or selected archived revisions for the file,
2020 // sorted from the most recent to the oldest.
2021 $conditions = array( 'fa_name' => $this->name
);
2023 $conditions['fa_id'] = $versions;
2026 $result = $dbw->select( 'filearchive', '*',
2029 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2031 if( $dbw->numRows( $result ) < count( $versions ) ) {
2032 // There's some kind of conflict or confusion;
2033 // we can't restore everything we were asked to.
2034 wfDebug( "$fname: couldn't find requested items\n" );
2036 FileStore
::unlock();
2040 if( $dbw->numRows( $result ) == 0 ) {
2042 wfDebug( "$fname: nothing to do\n" );
2044 FileStore
::unlock();
2049 while( $row = $dbw->fetchObject( $result ) ) {
2051 $store = FileStore
::get( $row->fa_storage_group
);
2053 wfDebug( "$fname: skipping row with no file.\n" );
2057 if( $revisions == 1 && !$exists ) {
2058 $destPath = wfImageDir( $row->fa_name
) .
2059 DIRECTORY_SEPARATOR
.
2062 // We may have to fill in data if this was originally
2063 // an archived file revision.
2064 if( is_null( $row->fa_metadata
) ) {
2065 $tempFile = $store->filePath( $row->fa_storage_key
);
2066 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2068 $magic = wfGetMimeMagic();
2069 $mime = $magic->guessMimeType( $tempFile, true );
2070 $media_type = $magic->getMediaType( $tempFile, $mime );
2071 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
2073 $metadata = $row->fa_metadata
;
2074 $major_mime = $row->fa_major_mime
;
2075 $minor_mime = $row->fa_minor_mime
;
2076 $media_type = $row->fa_media_type
;
2081 'img_name' => $row->fa_name
,
2082 'img_size' => $row->fa_size
,
2083 'img_width' => $row->fa_width
,
2084 'img_height' => $row->fa_height
,
2085 'img_metadata' => $metadata,
2086 'img_bits' => $row->fa_bits
,
2087 'img_media_type' => $media_type,
2088 'img_major_mime' => $major_mime,
2089 'img_minor_mime' => $minor_mime,
2090 'img_description' => $row->fa_description
,
2091 'img_user' => $row->fa_user
,
2092 'img_user_text' => $row->fa_user_text
,
2093 'img_timestamp' => $row->fa_timestamp
);
2095 $archiveName = $row->fa_archive_name
;
2096 if( $archiveName == '' ) {
2097 // This was originally a current version; we
2098 // have to devise a new archive name for it.
2099 // Format is <timestamp of archiving>!<name>
2101 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
2102 '!' . $row->fa_name
;
2104 $destPath = wfImageArchiveDir( $row->fa_name
) .
2105 DIRECTORY_SEPARATOR
. $archiveName;
2107 $table = 'oldimage';
2109 'oi_name' => $row->fa_name
,
2110 'oi_archive_name' => $archiveName,
2111 'oi_size' => $row->fa_size
,
2112 'oi_width' => $row->fa_width
,
2113 'oi_height' => $row->fa_height
,
2114 'oi_bits' => $row->fa_bits
,
2115 'oi_description' => $row->fa_description
,
2116 'oi_user' => $row->fa_user
,
2117 'oi_user_text' => $row->fa_user_text
,
2118 'oi_timestamp' => $row->fa_timestamp
);
2121 $dbw->insert( $table, $fields, $fname );
2122 /// @fixme this delete is not totally safe, potentially
2123 $dbw->delete( 'filearchive',
2124 array( 'fa_id' => $row->fa_id
),
2127 // Check if any other stored revisions use this file;
2128 // if so, we shouldn't remove the file from the deletion
2129 // archives so they will still work.
2130 $useCount = $dbw->selectField( 'filearchive',
2133 'fa_storage_group' => $row->fa_storage_group
,
2134 'fa_storage_key' => $row->fa_storage_key
),
2136 if( $useCount == 0 ) {
2137 wfDebug( "$fname: nothing else using {$row->fa_storage_key}, will deleting after\n" );
2138 $flags = FileStore
::DELETE_ORIGINAL
;
2143 $transaction->add( $store->export( $row->fa_storage_key
,
2144 $destPath, $flags ) );
2147 $dbw->immediateCommit();
2148 } catch( MWException
$e ) {
2149 wfDebug( "$fname caught error, aborting\n" );
2150 $transaction->rollback();
2154 $transaction->commit();
2155 FileStore
::unlock();
2157 if( $revisions > 0 ) {
2159 wfDebug( "$fname restored $revisions items, creating a new current\n" );
2161 // Update site_stats
2162 $site_stats = $dbw->tableName( 'site_stats' );
2163 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
2165 $this->purgeEverything();
2167 wfDebug( "$fname restored $revisions as archived versions\n" );
2168 $this->purgeDescription();
2179 * Returns the image directory of an image
2180 * If the directory does not exist, it is created.
2181 * The result is an absolute path.
2183 * This function is called from thumb.php before Setup.php is included
2185 * @param $fname String: file name of the image file.
2188 function wfImageDir( $fname ) {
2189 global $wgUploadDirectory, $wgHashedUploadDirectory;
2191 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
2193 $hash = md5( $fname );
2194 $oldumask = umask(0);
2195 $dest = $wgUploadDirectory . '/' . $hash{0};
2196 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
2197 $dest .= '/' . substr( $hash, 0, 2 );
2198 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
2205 * Returns the image directory of an image's thubnail
2206 * If the directory does not exist, it is created.
2207 * The result is an absolute path.
2209 * This function is called from thumb.php before Setup.php is included
2211 * @param $fname String: file name of the original image file
2212 * @param $shared Boolean: (optional) use the shared upload directory (default: 'false').
2215 function wfImageThumbDir( $fname, $shared = false ) {
2216 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
2217 if ( Image
::isHashed( $shared ) ) {
2218 $dir = "$base/$fname";
2220 if ( !is_dir( $base ) ) {
2221 $oldumask = umask(0);
2222 @mkdir
( $base, 0777 );
2226 if ( ! is_dir( $dir ) ) {
2227 if ( is_file( $dir ) ) {
2228 // Old thumbnail in the way of directory creation, kill it
2231 $oldumask = umask(0);
2232 @mkdir
( $dir, 0777 );
2243 * Old thumbnail directory, kept for conversion
2245 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
2246 return wfImageArchiveDir( $thumbName, $subdir, $shared );
2250 * Returns the image directory of an image's old version
2251 * If the directory does not exist, it is created.
2252 * The result is an absolute path.
2254 * This function is called from thumb.php before Setup.php is included
2256 * @param $fname String: file name of the thumbnail file, including file size prefix.
2257 * @param $subdir String: subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'.
2258 * @param $shared Boolean use the shared upload directory (only relevant for other functions which call this one). Default is 'false'.
2261 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
2262 global $wgUploadDirectory, $wgHashedUploadDirectory;
2263 global $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
2264 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
2265 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
2266 if (!$hashdir) { return $dir.'/'.$subdir; }
2267 $hash = md5( $fname );
2268 $oldumask = umask(0);
2270 # Suppress warning messages here; if the file itself can't
2271 # be written we'll worry about it then.
2272 wfSuppressWarnings();
2274 $archive = $dir.'/'.$subdir;
2275 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
2276 $archive .= '/' . $hash{0};
2277 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
2278 $archive .= '/' . substr( $hash, 0, 2 );
2279 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
2281 wfRestoreWarnings();
2288 * Return the hash path component of an image path (URL or filesystem),
2289 * e.g. "/3/3c/", or just "/" if hashing is not used.
2291 * @param $dbkey The filesystem / database name of the file
2292 * @param $fromSharedDirectory Use the shared file repository? It may
2293 * use different hash settings from the local one.
2295 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
2296 if( Image
::isHashed( $fromSharedDirectory ) ) {
2297 $hash = md5($dbkey);
2298 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
2305 * Returns the image URL of an image's old version
2307 * @param $name String: file name of the image file
2308 * @param $subdir String: (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
2311 function wfImageArchiveUrl( $name, $subdir='archive' ) {
2312 global $wgUploadPath, $wgHashedUploadDirectory;
2314 if ($wgHashedUploadDirectory) {
2315 $hash = md5( substr( $name, 15) );
2316 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
2317 substr( $hash, 0, 2 ) . '/'.$name;
2319 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
2321 return wfUrlencode($url);
2325 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
2326 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
2328 * @param $length String: CSS/SVG length.
2329 * @return Integer: length in pixels
2331 function wfScaleSVGUnit( $length ) {
2332 static $unitLength = array(
2339 '' => 1.0, // "User units" pixels by default
2340 '%' => 2.0, // Fake it!
2342 if( preg_match( '/^(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
2343 $length = floatval( $matches[1] );
2344 $unit = $matches[2];
2345 return round( $length * $unitLength[$unit] );
2348 return round( floatval( $length ) );
2353 * Compatible with PHP getimagesize()
2354 * @todo support gzipped SVGZ
2355 * @todo check XML more carefully
2356 * @todo sensible defaults
2358 * @param $filename String: full name of the file (passed to php fopen()).
2361 function wfGetSVGsize( $filename ) {
2365 // Read a chunk of the file
2366 $f = fopen( $filename, "rt" );
2367 if( !$f ) return false;
2368 $chunk = fread( $f, 4096 );
2371 // Uber-crappy hack! Run through a real XML parser.
2372 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
2376 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
2377 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
2379 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
2380 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
2383 return array( $width, $height, 'SVG',
2384 "width=\"$width\" height=\"$height\"" );
2388 * Determine if an image exists on the 'bad image list'.
2390 * @param $name String: the image name to check
2393 function wfIsBadImage( $name ) {
2394 static $titleList = false;
2397 # Build the list now
2398 $titleList = array();
2399 $lines = explode( "\n", wfMsgForContent( 'bad_image_list' ) );
2400 foreach( $lines as $line ) {
2401 if( preg_match( '/^\*\s*\[\[:?(.*?)\]\]/i', $line, $matches ) ) {
2402 $title = Title
::newFromText( $matches[1] );
2403 if( is_object( $title ) && $title->getNamespace() == NS_IMAGE
)
2404 $titleList[ $title->getDBkey() ] = true;
2408 return array_key_exists( $name, $titleList );
2414 * Wrapper class for thumbnail images
2415 * @package MediaWiki
2417 class ThumbnailImage
{
2419 * @param string $path Filesystem path to the thumb
2420 * @param string $url URL path to the thumb
2423 function ThumbnailImage( $url, $width, $height, $path = false ) {
2425 $this->width
= round( $width );
2426 $this->height
= round( $height );
2427 # These should be integers when they get here.
2428 # If not, there's a bug somewhere. But let's at
2429 # least produce valid HTML code regardless.
2430 $this->path
= $path;
2434 * @return string The thumbnail URL
2441 * Return HTML <img ... /> tag for the thumbnail, will include
2442 * width and height attributes and a blank alt text (as required).
2444 * You can set or override additional attributes by passing an
2445 * associative array of name => data pairs. The data will be escaped
2446 * for HTML output, so should be in plaintext.
2448 * @param array $attribs
2452 function toHtml( $attribs = array() ) {
2453 $attribs['src'] = $this->url
;
2454 $attribs['width'] = $this->width
;
2455 $attribs['height'] = $this->height
;
2456 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2459 foreach( $attribs as $name => $data ) {
2460 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
2469 * Calculate the largest thumbnail width for a given original file size
2470 * such that the thumbnail's height is at most $maxHeight.
2471 * @param $boxWidth Integer Width of the thumbnail box.
2472 * @param $boxHeight Integer Height of the thumbnail box.
2473 * @param $maxHeight Integer Maximum height expected for the thumbnail.
2476 function wfFitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
2477 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
2478 $roundedUp = ceil( $idealWidth );
2479 if( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight )
2480 return floor( $idealWidth );