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 require_once('Exif.php');
19 * Bump this number when serialized cache records may be incompatible.
21 define( 'MW_IMAGE_VERSION', 1 );
24 * Class to represent an image
26 * Provides methods to retrieve paths (physical, logical, URL),
27 * to generate thumbnails or for uploading.
35 var $name, # name of the image (constructor)
36 $imagePath, # Path of the image (loadFromXxx)
37 $url, # Image URL (accessor)
38 $title, # Title object for this image (constructor)
39 $fileExists, # does the image file exist on disk? (loadFromXxx)
40 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
41 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
42 $historyRes, # result of the query for the image's history (nextHistoryLine)
45 $bits, # --- returned by getimagesize (loadFromXxx)
47 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
48 $mime, # MIME type, determined by MimeMagic::guessMimeType
49 $size, # Size in bytes (loadFromXxx)
51 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
57 * Create an Image object from an image name
59 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
62 function newFromName( $name ) {
63 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
64 return new Image( $title );
68 * Obsolete factory function, use constructor
70 function newFromTitle( $title ) {
71 return new Image( $title );
74 function Image( $title ) {
77 if( !is_object( $title ) ) {
78 wfDebugDieBacktrace( 'Image constructor given bogus title.' );
80 $this->title
=& $title;
81 $this->name
= $title->getDBkey();
82 $this->metadata
= serialize ( array() ) ;
84 $n = strrpos( $this->name
, '.' );
85 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
86 $this->historyLine
= 0;
88 $this->dataLoaded
= false;
92 * Get the memcached keys
93 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
95 function getCacheKeys( $shared = false ) {
96 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
99 $hashedName = md5($this->name
);
100 $keys = array( "$wgDBname:Image:$hashedName" );
101 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
102 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
108 * Try to load image metadata from memcached. Returns true on success.
110 function loadFromCache() {
111 global $wgUseSharedUploads, $wgMemc;
112 $fname = 'Image::loadFromMemcached';
113 wfProfileIn( $fname );
114 $this->dataLoaded
= false;
115 $keys = $this->getCacheKeys();
116 $cachedValues = $wgMemc->get( $keys[0] );
118 // Check if the key existed and belongs to this version of MediaWiki
119 if (!empty($cachedValues) && is_array($cachedValues)
120 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
121 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
123 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
124 # if this is shared file, we need to check if image
125 # in shared repository has not changed
126 if ( isset( $keys[1] ) ) {
127 $commonsCachedValues = $wgMemc->get( $keys[1] );
128 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
129 && isset($commonsCachedValues['version'])
130 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
131 && isset($commonsCachedValues['mime'])) {
132 wfDebug( "Pulling image metadata from shared repository cache\n" );
133 $this->name
= $commonsCachedValues['name'];
134 $this->imagePath
= $commonsCachedValues['imagePath'];
135 $this->fileExists
= $commonsCachedValues['fileExists'];
136 $this->width
= $commonsCachedValues['width'];
137 $this->height
= $commonsCachedValues['height'];
138 $this->bits
= $commonsCachedValues['bits'];
139 $this->type
= $commonsCachedValues['type'];
140 $this->mime
= $commonsCachedValues['mime'];
141 $this->metadata
= $commonsCachedValues['metadata'];
142 $this->size
= $commonsCachedValues['size'];
143 $this->fromSharedDirectory
= true;
144 $this->dataLoaded
= true;
145 $this->imagePath
= $this->getFullPath(true);
149 wfDebug( "Pulling image metadata from local cache\n" );
150 $this->name
= $cachedValues['name'];
151 $this->imagePath
= $cachedValues['imagePath'];
152 $this->fileExists
= $cachedValues['fileExists'];
153 $this->width
= $cachedValues['width'];
154 $this->height
= $cachedValues['height'];
155 $this->bits
= $cachedValues['bits'];
156 $this->type
= $cachedValues['type'];
157 $this->mime
= $cachedValues['mime'];
158 $this->metadata
= $cachedValues['metadata'];
159 $this->size
= $cachedValues['size'];
160 $this->fromSharedDirectory
= false;
161 $this->dataLoaded
= true;
162 $this->imagePath
= $this->getFullPath();
165 if ( $this->dataLoaded
) {
166 wfIncrStats( 'image_cache_hit' );
168 wfIncrStats( 'image_cache_miss' );
171 wfProfileOut( $fname );
172 return $this->dataLoaded
;
176 * Save the image metadata to memcached
178 function saveToCache() {
181 $keys = $this->getCacheKeys();
182 if ( $this->fileExists
) {
183 // We can't cache negative metadata for non-existent files,
184 // because if the file later appears in commons, the local
185 // keys won't be purged.
186 $cachedValues = array(
187 'version' => MW_IMAGE_VERSION
,
188 'name' => $this->name
,
189 'imagePath' => $this->imagePath
,
190 'fileExists' => $this->fileExists
,
191 'fromShared' => $this->fromSharedDirectory
,
192 'width' => $this->width
,
193 'height' => $this->height
,
194 'bits' => $this->bits
,
195 'type' => $this->type
,
196 'mime' => $this->mime
,
197 'metadata' => $this->metadata
,
198 'size' => $this->size
);
200 $wgMemc->set( $keys[0], $cachedValues );
202 // However we should clear them, so they aren't leftover
203 // if we've deleted the file.
204 $wgMemc->delete( $keys[0] );
209 * Load metadata from the file itself
211 function loadFromFile() {
212 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang,
214 $fname = 'Image::loadFromFile';
215 wfProfileIn( $fname );
216 $this->imagePath
= $this->getFullPath();
217 $this->fileExists
= file_exists( $this->imagePath
);
218 $this->fromSharedDirectory
= false;
221 if (!$this->fileExists
) wfDebug("$fname: ".$this->imagePath
." not found locally!\n");
223 # If the file is not found, and a shared upload directory is used, look for it there.
224 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
225 # In case we're on a wgCapitalLinks=false wiki, we
226 # capitalize the first letter of the filename before
227 # looking it up in the shared repository.
228 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
229 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
230 if ( $this->fileExists
) {
231 $this->name
= $sharedImage->name
;
232 $this->imagePath
= $this->getFullPath(true);
233 $this->fromSharedDirectory
= true;
238 if ( $this->fileExists
) {
239 $magic=& wfGetMimeMagic();
241 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
242 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
245 $this->size
= filesize( $this->imagePath
);
247 $magic=& wfGetMimeMagic();
250 if( $this->mime
== 'image/svg' ) {
251 wfSuppressWarnings();
252 $gis = wfGetSVGsize( $this->imagePath
);
255 elseif ( !$magic->isPHPImageType( $this->mime
) ) {
256 # Don't try to get the width and height of sound and video files, that's bad for performance
259 $gis[2]= 0; //unknown
260 $gis[3]= ""; //width height string
263 wfSuppressWarnings();
264 $gis = getimagesize( $this->imagePath
);
268 wfDebug("$fname: ".$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
273 $gis[2]= 0; //unknown
274 $gis[3]= ""; //width height string
277 $this->type
= MEDIATYPE_UNKNOWN
;
278 wfDebug("$fname: ".$this->imagePath
." NOT FOUND!\n");
281 $this->width
= $gis[0];
282 $this->height
= $gis[1];
284 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
286 #NOTE: we have to set this flag early to avoid load() to be called
287 # be some of the functions below. This may lead to recursion or other bad things!
288 # as ther's only one thread of execution, this should be safe anyway.
289 $this->dataLoaded
= true;
292 if ($this->fileExists
&& $wgShowEXIF) $this->metadata
= serialize ( $this->retrieveExifData() ) ;
293 else $this->metadata
= serialize ( array() ) ;
295 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
296 else $this->bits
= 0;
298 wfProfileOut( $fname );
302 * Load image metadata from the DB
304 function loadFromDB() {
305 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgLang;
306 $fname = 'Image::loadFromDB';
307 wfProfileIn( $fname );
309 $dbr =& wfGetDB( DB_SLAVE
);
311 $this->checkDBSchema($dbr);
313 $row = $dbr->selectRow( 'image',
314 array( 'img_size', 'img_width', 'img_height', 'img_bits',
315 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
316 array( 'img_name' => $this->name
), $fname );
318 $this->fromSharedDirectory
= false;
319 $this->fileExists
= true;
320 $this->loadFromRow( $row );
321 $this->imagePath
= $this->getFullPath();
322 // Check for rows from a previous schema, quietly upgrade them
323 if ( is_null($this->type
) ) {
326 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
327 # In case we're on a wgCapitalLinks=false wiki, we
328 # capitalize the first letter of the filename before
329 # looking it up in the shared repository.
330 $name = $wgLang->ucfirst($this->name
);
332 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
334 'img_size', 'img_width', 'img_height', 'img_bits',
335 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
336 array( 'img_name' => $name ), $fname );
338 $this->fromSharedDirectory
= true;
339 $this->fileExists
= true;
340 $this->imagePath
= $this->getFullPath(true);
342 $this->loadFromRow( $row );
344 // Check for rows from a previous schema, quietly upgrade them
345 if ( is_null($this->type
) ) {
357 $this->fileExists
= false;
358 $this->fromSharedDirectory
= false;
359 $this->metadata
= serialize ( array() ) ;
362 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
363 $this->dataLoaded
= true;
364 wfProfileOut( $fname );
368 * Load image metadata from a DB result row
370 function loadFromRow( &$row ) {
371 $this->size
= $row->img_size
;
372 $this->width
= $row->img_width
;
373 $this->height
= $row->img_height
;
374 $this->bits
= $row->img_bits
;
375 $this->type
= $row->img_media_type
;
377 $major= $row->img_major_mime
;
378 $minor= $row->img_minor_mime
;
380 if (!$major) $this->mime
= "unknown/unknown";
382 if (!$minor) $minor= "unknown";
383 $this->mime
= $major.'/'.$minor;
386 $this->metadata
= $row->img_metadata
;
387 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
389 $this->dataLoaded
= true;
393 * Load image metadata from cache or DB, unless already loaded
396 global $wgSharedUploadDBname, $wgUseSharedUploads;
397 if ( !$this->dataLoaded
) {
398 if ( !$this->loadFromCache() ) {
400 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
401 $this->loadFromFile();
402 } elseif ( $this->fileExists
) {
403 $this->saveToCache();
406 $this->dataLoaded
= true;
411 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
412 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
414 function upgradeRow() {
415 global $wgDBname, $wgSharedUploadDBname;
416 $fname = 'Image::upgradeRow';
417 wfProfileIn( $fname );
419 $this->loadFromFile();
420 $dbw =& wfGetDB( DB_MASTER
);
422 if ( $this->fromSharedDirectory
) {
423 if ( !$wgSharedUploadDBname ) {
424 wfProfileOut( $fname );
428 // Write to the other DB using selectDB, not database selectors
429 // This avoids breaking replication in MySQL
430 $dbw->selectDB( $wgSharedUploadDBname );
433 $this->checkDBSchema($dbw);
435 if (strpos($this->mime
,'/')!==false) {
436 list($major,$minor)= explode('/',$this->mime
,2);
443 wfDebug("$fname: upgrading ".$this->name
." to 1.5 schema\n");
445 $dbw->update( 'image',
447 'img_width' => $this->width
,
448 'img_height' => $this->height
,
449 'img_bits' => $this->bits
,
450 'img_media_type' => $this->type
,
451 'img_major_mime' => $major,
452 'img_minor_mime' => $minor,
453 'img_metadata' => $this->metadata
,
454 ), array( 'img_name' => $this->name
), $fname
456 if ( $this->fromSharedDirectory
) {
457 $dbw->selectDB( $wgDBname );
459 wfProfileOut( $fname );
463 * Return the name of this image
471 * Return the associated title object
474 function getTitle() {
479 * Return the URL of the image file
485 if($this->fileExists
) {
486 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
494 function getViewURL() {
495 if( $this->mustRender()) {
496 if( $this->canRender() ) {
497 return $this->createThumb( $this->getWidth() );
500 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
501 return $this->getURL(); #hm... return NULL?
504 return $this->getURL();
509 * Return the image path of the image in the
510 * local file system as an absolute path
513 function getImagePath() {
515 return $this->imagePath
;
519 * Return the width of the image
521 * Returns -1 if the file specified is not a known image type
524 function getWidth() {
530 * Return the height of the image
532 * Returns -1 if the file specified is not a known image type
535 function getHeight() {
537 return $this->height
;
541 * Return the size of the image file, in bytes
550 * Returns the mime type of the file.
552 function getMimeType() {
558 * Return the type of the media in the file.
559 * Use the value returned by this function with the MEDIATYPE_xxx constants.
561 function getMediaType() {
567 * Checks if the file can be presented to the browser as a bitmap.
569 * Currently, this checks if the file is an image format
570 * that can be converted to a format
571 * supported by all browsers (namely GIF, PNG and JPEG),
572 * or if it is an SVG image and SVG conversion is enabled.
574 * @todo remember the result of this check.
576 function canRender() {
577 global $wgUseImageMagick;
579 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
581 $mime= $this->getMimeType();
583 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
585 #if it's SVG, check if ther's a converter enabled
586 if ($mime === 'image/svg') {
587 global $wgSVGConverters, $wgSVGConverter;
589 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
594 #image formats available on ALL browsers
595 if ( $mime === 'image/gif'
596 ||
$mime === 'image/png'
597 ||
$mime === 'image/jpeg' ) return true;
599 #image formats that can be converted to the above formats
600 if ($wgUseImageMagick) {
601 #convertable by ImageMagick (there are more...)
602 if ( $mime === 'image/vnd.wap.wbmp'
603 ||
$mime === 'image/x-xbitmap'
604 ||
$mime === 'image/x-xpixmap'
605 #|| $mime === 'image/x-icon' #file may be split into multiple parts
606 ||
$mime === 'image/x-portable-anymap'
607 ||
$mime === 'image/x-portable-bitmap'
608 ||
$mime === 'image/x-portable-graymap'
609 ||
$mime === 'image/x-portable-pixmap'
610 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
611 ||
$mime === 'image/x-rgb'
612 ||
$mime === 'image/x-bmp'
613 ||
$mime === 'image/tiff' ) return true;
616 #convertable by the PHP GD image lib
617 if ( $mime === 'image/vnd.wap.wbmp'
618 ||
$mime === 'image/x-xbitmap' ) return true;
626 * Return true if the file is of a type that can't be directly
627 * rendered by typical browsers and needs to be re-rasterized.
629 * This returns true for everything but the bitmap types
630 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
631 * also return true for any non-image formats.
635 function mustRender() {
636 $mime= $this->getMimeType();
638 if ( $mime === "image/gif"
639 ||
$mime === "image/png"
640 ||
$mime === "image/jpeg" ) return false;
646 * Determines if this media file may be shown inline on a page.
648 * This is currently synonymous to canRender(), but this could be
649 * extended to also allow inline display of other media,
650 * like flash animations or videos. If you do so, please keep in mind that
651 * that could be a security risk.
653 function allowInlineDisplay() {
654 return $this->canRender();
658 * Determines if this media file is in a format that is unlikely to
659 * contain viruses or malicious content. It uses the global
660 * $wgTrustedMediaFormats list to determine if the file is safe.
662 * This is used to show a warning on the description page of non-safe files.
663 * It may also be used to disallow direct [[media:...]] links to such files.
665 * Note that this function will always return ture if allowInlineDisplay()
666 * or isTrustedFile() is true for this file.
668 function isSafeFile() {
669 if ($this->allowInlineDisplay()) return true;
670 if ($this->isTrustedFile()) return true;
672 global $wgTrustedMediaFormats;
674 $type= $this->getMediaType();
675 $mime= $this->getMimeType();
676 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
678 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
679 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
681 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
682 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
687 /** Returns true if the file is flagegd as trusted. Files flagged that way
688 * can be linked to directly, even if that is not allowed for this type of
691 * This is a dummy function right now and always returns false. It could be
692 * implemented to extract a flag from the database. The trusted flag could be
693 * set on upload, if the user has sufficient privileges, to bypass script-
694 * and html-filters. It may even be coupeled with cryptographics signatures
697 function isTrustedFile() {
698 #this could be implemented to check a flag in the databas,
699 #look for signatures, etc
704 * Return the escapeLocalURL of this image
707 function getEscapeLocalURL() {
709 return $this->title
->escapeLocalURL();
713 * Return the escapeFullURL of this image
716 function getEscapeFullURL() {
718 return $this->title
->escapeFullURL();
722 * Return the URL of an image, provided its name.
724 * @param string $name Name of the image, without the leading "Image:"
725 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
726 * @return string URL of $name image
730 function imageUrl( $name, $fromSharedDirectory = false ) {
731 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
732 if($fromSharedDirectory) {
734 $path = $wgSharedUploadPath;
736 $base = $wgUploadBaseUrl;
737 $path = $wgUploadPath;
739 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
740 return wfUrlencode( $url );
744 * Returns true if the image file exists on disk.
745 * @return boolean Whether image file exist on disk.
750 return $this->fileExists
;
757 function thumbUrl( $width, $subdir='thumb') {
758 global $wgUploadPath, $wgUploadBaseUrl,
759 $wgSharedUploadPath,$wgSharedUploadDirectory,
760 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
762 // Generate thumb.php URL if possible
766 if ( $this->fromSharedDirectory
) {
767 if ( $wgSharedThumbnailScriptPath ) {
768 $script = $wgSharedThumbnailScriptPath;
771 if ( $wgThumbnailScriptPath ) {
772 $script = $wgThumbnailScriptPath;
776 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
777 if( $this->mustRender() ) {
781 $name = $this->thumbName( $width );
782 if($this->fromSharedDirectory
) {
784 $path = $wgSharedUploadPath;
786 $base = $wgUploadBaseUrl;
787 $path = $wgUploadPath;
789 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
790 $url = "{$base}{$path}/{$subdir}" .
791 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
792 . $this->name
.'/'.$name;
793 $url = wfUrlencode( $url );
795 $url = "{$base}{$path}/{$subdir}/{$name}";
798 return array( $script !== false, $url );
802 * Return the file name of a thumbnail of the specified width
804 * @param integer $width Width of the thumbnail image
805 * @param boolean $shared Does the thumbnail come from the shared repository?
808 function thumbName( $width ) {
809 $thumb = $width."px-".$this->name
;
811 if( $this->mustRender() ) {
812 if( $this->canRender() ) {
813 # Rasterize to PNG (for SVG vector images, etc)
817 #should we use iconThumb here to get a symbolic thumbnail?
818 #or should we fail with an internal error?
819 return NULL; //can't make bitmap
826 * Create a thumbnail of the image having the specified width/height.
827 * The thumbnail will not be created if the width is larger than the
828 * image's width. Let the browser do the scaling in this case.
829 * The thumbnail is stored on disk and is only computed if the thumbnail
830 * file does not exist OR if it is older than the image.
833 * Keeps aspect ratio of original image. If both width and height are
834 * specified, the generated image will be no bigger than width x height,
835 * and will also have correct aspect ratio.
837 * @param integer $width maximum width of the generated thumbnail
838 * @param integer $height maximum height of the image (optional)
841 function createThumb( $width, $height=-1 ) {
842 $thumb = $this->getThumbnail( $width, $height );
843 if( is_null( $thumb ) ) return '';
844 return $thumb->getUrl();
848 * As createThumb, but returns a ThumbnailImage object. This can
849 * provide access to the actual file, the real size of the thumb,
850 * and can produce a convenient <img> tag for you.
852 * @param integer $width maximum width of the generated thumbnail
853 * @param integer $height maximum height of the image (optional)
854 * @return ThumbnailImage
857 function getThumbnail( $width, $height=-1 ) {
858 if ( $height == -1 ) {
859 return $this->renderThumb( $width );
863 if ($this->canRender()) {
864 if ( $width < $this->width
) {
865 $thumbheight = $this->height
* $width / $this->width
;
866 $thumbwidth = $width;
868 $thumbheight = $this->height
;
869 $thumbwidth = $this->width
;
871 if ( $thumbheight > $height ) {
872 $thumbwidth = $thumbwidth * $height / $thumbheight;
873 $thumbheight = $height;
876 $thumb = $this->renderThumb( $thumbwidth );
878 else $thumb= NULL; #not a bitmap or renderable image, don't try.
880 if( is_null( $thumb ) ) {
881 $thumb = $this->iconThumb();
887 * @return ThumbnailImage
889 function iconThumb() {
890 global $wgStylePath, $wgStyleDirectory;
892 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
893 foreach( $try as $icon ) {
894 $path = '/common/images/icons/' . $icon;
895 $filepath = $wgStyleDirectory . $path;
896 if( file_exists( $filepath ) ) {
897 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
904 * Create a thumbnail of the image having the specified width.
905 * The thumbnail will not be created if the width is larger than the
906 * image's width. Let the browser do the scaling in this case.
907 * The thumbnail is stored on disk and is only computed if the thumbnail
908 * file does not exist OR if it is older than the image.
909 * Returns an object which can return the pathname, URL, and physical
910 * pixel size of the thumbnail -- or null on failure.
912 * @return ThumbnailImage
915 function renderThumb( $width, $useScript = true ) {
916 global $wgUseSquid, $wgInternalServer;
917 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
919 $fname = 'Image::renderThumb';
920 wfProfileIn( $fname );
922 $width = intval( $width );
925 if ( ! $this->exists() )
927 # If there is no image, there will be no thumbnail
928 wfProfileOut( $fname );
932 # Sanity check $width
933 if( $width <= 0 ||
$this->width
<= 0) {
935 wfProfileOut( $fname );
939 if( $width >= $this->width
&& !$this->mustRender() ) {
940 # Don't make an image bigger than the source
941 $thumb = new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
942 wfProfileOut( $fname );
946 $height = floor( $this->height
* ( $width/$this->width
) );
948 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
949 if ( $isScriptUrl && $useScript ) {
950 // Use thumb.php to render the image
951 $thumb = new ThumbnailImage( $url, $width, $height );
952 wfProfileOut( $fname );
956 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
957 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
959 if ( !file_exists( $thumbPath ) ) {
960 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
963 if ( file_exists( $oldThumbPath ) ) {
964 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
965 rename( $oldThumbPath, $thumbPath );
968 unlink( $oldThumbPath );
972 $this->reallyRenderThumb( $thumbPath, $width, $height );
975 # This has to be done after the image is updated and present for all machines on NFS,
976 # or else the old version might be stored into the squid again
978 if ( substr( $url, 0, 4 ) == 'http' ) {
979 $urlArr = array( $url );
981 $urlArr = array( $wgInternalServer.$url );
983 wfPurgeSquidServers($urlArr);
988 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
989 wfProfileOut( $fname );
991 } // END OF function renderThumb
994 * Really render a thumbnail
995 * Call this only for images for which canRender() returns true.
999 function reallyRenderThumb( $thumbPath, $width, $height ) {
1000 global $wgSVGConverters, $wgSVGConverter,
1001 $wgUseImageMagick, $wgImageMagickConvertCommand;
1005 if( $this->mime
=== "image/svg" ) {
1006 #Right now we have only SVG
1008 global $wgSVGConverters, $wgSVGConverter;
1009 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1010 global $wgSVGConverterPath;
1012 array( '$path/', '$width', '$input', '$output' ),
1013 array( $wgSVGConverterPath,
1015 wfEscapeShellArg( $this->imagePath
),
1016 wfEscapeShellArg( $thumbPath ) ),
1017 $wgSVGConverters[$wgSVGConverter] );
1018 $conv = shell_exec( $cmd );
1022 } elseif ( $wgUseImageMagick ) {
1024 # Specify white background color, will be used for transparent images
1025 # in Internet Explorer/Windows instead of default black.
1026 $cmd = $wgImageMagickConvertCommand .
1027 " -quality 85 -background white -geometry {$width} ".
1028 wfEscapeShellArg($this->imagePath
) . " " .
1029 wfEscapeShellArg($thumbPath);
1030 wfDebug("reallyRenderThumb: running ImageMagick: $cmd");
1031 $conv = shell_exec( $cmd );
1033 # Use PHP's builtin GD library functions.
1035 # First find out what kind of file this is, and select the correct
1036 # input routine for this.
1039 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1040 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1041 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1042 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1043 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1045 if( !isset( $typemap[$this->mime
] ) ) {
1046 $err = 'Image type not supported';
1047 wfDebug( "$err\n" );
1050 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1052 if( !function_exists( $loader ) ) {
1053 $err = "Incomplete GD library configuration: missing function $loader";
1054 wfDebug( "$err\n" );
1057 if( $colorStyle == 'palette' ) {
1059 } elseif( $colorStyle == 'truecolor' ) {
1061 } elseif( $colorStyle == 'bits' ) {
1062 $truecolor = ( $this->bits
> 8 );
1065 $src_image = call_user_func( $loader, $this->imagePath
);
1067 $dst_image = imagecreatetruecolor( $width, $height );
1069 $dst_image = imagecreate( $width, $height );
1071 imagecopyresampled( $dst_image, $src_image,
1073 $width, $height, $this->width
, $this->height
);
1074 call_user_func( $saveType, $dst_image, $thumbPath );
1075 imagedestroy( $dst_image );
1076 imagedestroy( $src_image );
1080 # Check for zero-sized thumbnails. Those can be generated when
1081 # no disk space is available or some other error occurs
1083 if( file_exists( $thumbPath ) ) {
1084 $thumbstat = stat( $thumbPath );
1085 if( $thumbstat['size'] == 0 ) {
1086 unlink( $thumbPath );
1091 function imageJpegWrapper( $dst_image, $thumbPath ) {
1092 imageinterlace( $dst_image );
1093 imagejpeg( $dst_image, $thumbPath, 95 );
1097 * Get all thumbnail names previously generated for this image
1099 function getThumbnails( $shared = false ) {
1100 if ( Image
::isHashed( $shared ) ) {
1103 $dir = wfImageThumbDir( $this->name
, $shared );
1105 // This generates an error on failure, hence the @
1106 $handle = @opendir
( $dir );
1109 while ( false !== ( $file = readdir($handle) ) ) {
1110 if ( $file{0} != '.' ) {
1114 closedir( $handle );
1124 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1126 function purgeCache( $archiveFiles = array(), $shared = false ) {
1127 global $wgInternalServer, $wgUseSquid;
1129 // Refresh metadata cache
1131 $this->loadFromFile();
1132 $this->saveToCache();
1134 // Delete thumbnails
1135 $files = $this->getThumbnails( $shared );
1136 $dir = wfImageThumbDir( $this->name
, $shared );
1138 foreach ( $files as $file ) {
1139 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1140 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1141 @unlink
( "$dir/$file" );
1146 if ( $wgUseSquid ) {
1147 $urls[] = $wgInternalServer . $this->getViewURL();
1148 foreach ( $archiveFiles as $file ) {
1149 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1151 wfPurgeSquidServers( $urls );
1155 function checkDBSchema(&$db) {
1156 # img_name must be unique
1157 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1158 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1161 #new fields must exist
1162 if ( !$db->fieldExists( 'image', 'img_media_type' )
1163 ||
!$db->fieldExists( 'image', 'img_metadata' )
1164 ||
!$db->fieldExists( 'image', 'img_width' ) ) {
1166 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1171 * Return the image history of this image, line by line.
1172 * starts with current version, then old versions.
1173 * uses $this->historyLine to check which line to return:
1174 * 0 return line for current version
1175 * 1 query for old versions, return first one
1176 * 2, ... return next old version from above query
1180 function nextHistoryLine() {
1181 $fname = 'Image::nextHistoryLine()';
1182 $dbr =& wfGetDB( DB_SLAVE
);
1184 $this->checkDBSchema($dbr);
1186 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1187 $this->historyRes
= $dbr->select( 'image',
1188 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
1189 array( 'img_name' => $this->title
->getDBkey() ),
1192 if ( 0 == wfNumRows( $this->historyRes
) ) {
1195 } else if ( $this->historyLine
== 1 ) {
1196 $this->historyRes
= $dbr->select( 'oldimage',
1197 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
1198 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
1199 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
1202 $this->historyLine ++
;
1204 return $dbr->fetchObject( $this->historyRes
);
1208 * Reset the history pointer to the first element of the history
1211 function resetHistory() {
1212 $this->historyLine
= 0;
1216 * Return the full filesystem path to the file. Note that this does
1217 * not mean that a file actually exists under that location.
1219 * This path depends on whether directory hashing is active or not,
1220 * i.e. whether the images are all found in the same directory,
1221 * or in hashed paths like /images/3/3c.
1224 * @param boolean $fromSharedDirectory Return the path to the file
1225 * in a shared repository (see $wgUseSharedRepository and related
1226 * options in DefaultSettings.php) instead of a local one.
1229 function getFullPath( $fromSharedRepository = false ) {
1230 global $wgUploadDirectory, $wgSharedUploadDirectory;
1231 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1233 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1236 // $wgSharedUploadDirectory may be false, if thumb.php is used
1238 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1250 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, $copyStatus = '', $source = '' ) {
1259 global $wgUser, $wgLang, $wgTitle, $wgDeferredUpdateList;
1260 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1262 $fname = 'Image::recordUpload';
1263 $dbw =& wfGetDB( DB_MASTER
);
1265 $this->checkDBSchema($dbw);
1267 // Delete thumbnails and refresh the metadata cache
1268 $this->purgeCache();
1270 // Fail now if the image isn't there
1271 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1272 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1276 if ( $wgUseCopyrightUpload ) {
1277 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1278 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1279 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1284 $now = $dbw->timestamp();
1287 if (strpos($this->mime
,'/')!==false) {
1288 list($major,$minor)= explode('/',$this->mime
,2);
1291 $major= $this->mime
;
1295 # Test to see if the row exists using INSERT IGNORE
1296 # This avoids race conditions by locking the row until the commit, and also
1297 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1298 $dbw->insert( 'image',
1300 'img_name' => $this->name
,
1301 'img_size'=> $this->size
,
1302 'img_width' => intval( $this->width
),
1303 'img_height' => intval( $this->height
),
1304 'img_bits' => $this->bits
,
1305 'img_media_type' => $this->type
,
1306 'img_major_mime' => $major,
1307 'img_minor_mime' => $minor,
1308 'img_timestamp' => $now,
1309 'img_description' => $desc,
1310 'img_user' => $wgUser->getID(),
1311 'img_user_text' => $wgUser->getName(),
1312 'img_metadata' => $this->metadata
,
1315 $descTitle = $this->getTitle();
1316 $purgeURLs = array();
1318 if ( $dbw->affectedRows() ) {
1319 # Successfully inserted, this is a new image
1320 $id = $descTitle->getArticleID();
1323 $article = new Article( $descTitle );
1324 $article->insertNewArticle( $textdesc, $desc, false, false, true );
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
), $fname
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 # Invalidate the cache for the description page
1365 $descTitle->invalidateCache();
1366 $purgeURLs[] = $descTitle->getInternalURL();
1369 # Invalidate cache for all pages using this image
1370 $linksTo = $this->getLinksTo();
1372 if ( $wgUseSquid ) {
1373 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1374 array_push( $wgPostCommitUpdateList, $u );
1376 Title
::touchArray( $linksTo );
1378 $log = new LogPage( 'upload' );
1379 $log->addEntry( 'upload', $descTitle, $desc );
1385 * Get an array of Title objects which are articles which use this image
1386 * Also adds their IDs to the link cache
1388 * This is mostly copied from Title::getLinksTo()
1390 function getLinksTo( $options = '' ) {
1391 global $wgLinkCache;
1392 $fname = 'Image::getLinksTo';
1393 wfProfileIn( $fname );
1396 $db =& wfGetDB( DB_MASTER
);
1398 $db =& wfGetDB( DB_SLAVE
);
1401 extract( $db->tableNames( 'page', 'imagelinks' ) );
1402 $encName = $db->addQuotes( $this->name
);
1403 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1404 $res = $db->query( $sql, $fname );
1407 if ( $db->numRows( $res ) ) {
1408 while ( $row = $db->fetchObject( $res ) ) {
1409 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1410 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1411 $retVal[] = $titleObj;
1415 $db->freeResult( $res );
1419 * Retrive Exif data from the database
1421 * Retrive Exif data from the database and prune unrecognized tags
1422 * and/or tags with invalid contents
1426 function retrieveExifData () {
1427 if ( $this->getMimeType() !== "image/jpeg" ) return array ();
1429 $exif = new Exif( $this->imagePath
);
1430 return $exif->getFilteredData();
1433 function getExifData () {
1435 if ( $this->metadata
=== '0' )
1438 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1439 $ret = unserialize ( $this->metadata
);
1441 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1442 $newver = Exif
::version();
1444 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1445 $this->updateExifData( $newver );
1447 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1448 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1449 $format = new FormatExif( $ret );
1450 return $format->getFormattedData();
1453 function updateExifData( $version ) {
1454 $fname = 'Image:updateExifData';
1456 if ( $this->getImagePath() === false ) # Not a local image
1459 # Get EXIF data from image
1460 $exif = $this->retrieveExifData();
1461 if ( count( $exif ) ) {
1462 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1463 $this->metadata
= serialize( $exif );
1465 $this->metadata
= '0';
1468 # Update EXIF data in database
1469 $dbw =& wfGetDB( DB_MASTER
);
1471 $this->checkDBSchema($dbw);
1473 $dbw->update( 'image',
1474 array( 'img_metadata' => $this->metadata
),
1475 array( 'img_name' => $this->name
),
1484 * Returns the image directory of an image
1485 * If the directory does not exist, it is created.
1486 * The result is an absolute path.
1488 * This function is called from thumb.php before Setup.php is included
1490 * @param string $fname file name of the image file
1493 function wfImageDir( $fname ) {
1494 global $wgUploadDirectory, $wgHashedUploadDirectory;
1496 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1498 $hash = md5( $fname );
1499 $oldumask = umask(0);
1500 $dest = $wgUploadDirectory . '/' . $hash{0};
1501 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1502 $dest .= '/' . substr( $hash, 0, 2 );
1503 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1510 * Returns the image directory of an image's thubnail
1511 * If the directory does not exist, it is created.
1512 * The result is an absolute path.
1514 * This function is called from thumb.php before Setup.php is included
1516 * @param string $fname file name of the original image file
1517 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1518 * @param boolean $shared (optional) use the shared upload directory
1521 function wfImageThumbDir( $fname, $shared = false ) {
1522 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1523 if ( Image
::isHashed( $shared ) ) {
1524 $dir = "$base/$fname";
1526 if ( !is_dir( $base ) ) {
1527 $oldumask = umask(0);
1528 @mkdir
( $base, 0777 );
1532 if ( ! is_dir( $dir ) ) {
1533 $oldumask = umask(0);
1534 @mkdir
( $dir, 0777 );
1545 * Old thumbnail directory, kept for conversion
1547 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1548 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1552 * Returns the image directory of an image's old version
1553 * If the directory does not exist, it is created.
1554 * The result is an absolute path.
1556 * This function is called from thumb.php before Setup.php is included
1558 * @param string $fname file name of the thumbnail file, including file size prefix
1559 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1560 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1563 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1564 global $wgUploadDirectory, $wgHashedUploadDirectory,
1565 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1566 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1567 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1568 if (!$hashdir) { return $dir.'/'.$subdir; }
1569 $hash = md5( $fname );
1570 $oldumask = umask(0);
1572 # Suppress warning messages here; if the file itself can't
1573 # be written we'll worry about it then.
1574 wfSuppressWarnings();
1576 $archive = $dir.'/'.$subdir;
1577 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1578 $archive .= '/' . $hash{0};
1579 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1580 $archive .= '/' . substr( $hash, 0, 2 );
1581 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1583 wfRestoreWarnings();
1590 * Return the hash path component of an image path (URL or filesystem),
1591 * e.g. "/3/3c/", or just "/" if hashing is not used.
1593 * @param $dbkey The filesystem / database name of the file
1594 * @param $fromSharedDirectory Use the shared file repository? It may
1595 * use different hash settings from the local one.
1597 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1598 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1599 global $wgHashedUploadDirectory;
1601 if( Image
::isHashed( $fromSharedDirectory ) ) {
1602 $hash = md5($dbkey);
1603 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1610 * Returns the image URL of an image's old version
1612 * @param string $fname file name of the image file
1613 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1616 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1617 global $wgUploadPath, $wgHashedUploadDirectory;
1619 if ($wgHashedUploadDirectory) {
1620 $hash = md5( substr( $name, 15) );
1621 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1622 substr( $hash, 0, 2 ) . '/'.$name;
1624 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1626 return wfUrlencode($url);
1630 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1631 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1633 * @param string $length
1634 * @return int Length in pixels
1636 function wfScaleSVGUnit( $length ) {
1637 static $unitLength = array(
1644 '' => 1.0, // "User units" pixels by default
1645 '%' => 2.0, // Fake it!
1647 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1648 $length = floatval( $matches[1] );
1649 $unit = $matches[2];
1650 return round( $length * $unitLength[$unit] );
1653 return round( floatval( $length ) );
1658 * Compatible with PHP getimagesize()
1659 * @todo support gzipped SVGZ
1660 * @todo check XML more carefully
1661 * @todo sensible defaults
1663 * @param string $filename
1666 function wfGetSVGsize( $filename ) {
1670 // Read a chunk of the file
1671 $f = fopen( $filename, "rt" );
1672 if( !$f ) return false;
1673 $chunk = fread( $f, 4096 );
1676 // Uber-crappy hack! Run through a real XML parser.
1677 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1681 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1682 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1684 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1685 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1688 return array( $width, $height, 'SVG',
1689 "width=\"$width\" height=\"$height\"" );
1693 * Determine if an image exists on the 'bad image list'
1695 * @param string $name The image to check
1698 function wfIsBadImage( $name ) {
1700 static $titleList = false;
1701 if ( $titleList === false ) {
1702 $titleList = array();
1704 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1705 foreach ( $lines as $line ) {
1706 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1707 $t = Title
::newFromText( $m[1] );
1708 $titleList[$t->getDBkey()] = 1;
1713 return array_key_exists( $name, $titleList );
1719 * Wrapper class for thumbnail images
1720 * @package MediaWiki
1722 class ThumbnailImage
{
1724 * @param string $path Filesystem path to the thumb
1725 * @param string $url URL path to the thumb
1728 function ThumbnailImage( $url, $width, $height, $path = false ) {
1730 $this->width
= $width;
1731 $this->height
= $height;
1732 $this->path
= $path;
1736 * @return string The thumbnail URL
1743 * Return HTML <img ... /> tag for the thumbnail, will include
1744 * width and height attributes and a blank alt text (as required).
1746 * You can set or override additional attributes by passing an
1747 * associative array of name => data pairs. The data will be escaped
1748 * for HTML output, so should be in plaintext.
1750 * @param array $attribs
1754 function toHtml( $attribs = array() ) {
1755 $attribs['src'] = $this->url
;
1756 $attribs['width'] = $this->width
;
1757 $attribs['height'] = $this->height
;
1758 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1761 foreach( $attribs as $name => $data ) {
1762 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';