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 $width = IntVal( $width );
922 if ( ! $this->exists() )
924 # If there is no image, there will be no thumbnail
928 # Sanity check $width
929 if( $width <= 0 ||
$this->width
<= 0) {
934 if( $width >= $this->width
&& !$this->mustRender() ) {
935 # Don't make an image bigger than the source
936 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
939 $height = floor( $this->height
* ( $width/$this->width
) );
941 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
942 if ( $isScriptUrl && $useScript ) {
943 // Use thumb.php to render the image
944 return new ThumbnailImage( $url, $width, $height );
947 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
948 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
950 if ( !file_exists( $thumbPath ) ) {
951 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
954 if ( file_exists( $oldThumbPath ) ) {
955 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
956 rename( $oldThumbPath, $thumbPath );
959 unlink( $oldThumbPath );
963 $this->reallyRenderThumb( $thumbPath, $width, $height );
966 # This has to be done after the image is updated and present for all machines on NFS,
967 # or else the old version might be stored into the squid again
969 if ( substr( $url, 0, 4 ) == 'http' ) {
970 $urlArr = array( $url );
972 $urlArr = array( $wgInternalServer.$url );
974 wfPurgeSquidServers($urlArr);
979 return new ThumbnailImage( $url, $width, $height, $thumbPath );
980 } // END OF function renderThumb
983 * Really render a thumbnail
984 * Call this only for images for which canRender() returns true.
988 function reallyRenderThumb( $thumbPath, $width, $height ) {
989 global $wgSVGConverters, $wgSVGConverter,
990 $wgUseImageMagick, $wgImageMagickConvertCommand;
994 if( $this->mime
=== "image/svg" ) {
995 #Right now we have only SVG
997 global $wgSVGConverters, $wgSVGConverter;
998 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
999 global $wgSVGConverterPath;
1001 array( '$path/', '$width', '$input', '$output' ),
1002 array( $wgSVGConverterPath,
1004 wfEscapeShellArg( $this->imagePath
),
1005 wfEscapeShellArg( $thumbPath ) ),
1006 $wgSVGConverters[$wgSVGConverter] );
1007 $conv = shell_exec( $cmd );
1011 } elseif ( $wgUseImageMagick ) {
1013 # Specify white background color, will be used for transparent images
1014 # in Internet Explorer/Windows instead of default black.
1015 $cmd = $wgImageMagickConvertCommand .
1016 " -quality 85 -background white -geometry {$width} ".
1017 wfEscapeShellArg($this->imagePath
) . " " .
1018 wfEscapeShellArg($thumbPath);
1019 wfDebug("reallyRenderThumb: running ImageMagick: $cmd");
1020 $conv = shell_exec( $cmd );
1022 # Use PHP's builtin GD library functions.
1024 # First find out what kind of file this is, and select the correct
1025 # input routine for this.
1028 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1029 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1030 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1031 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1032 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1034 if( !isset( $typemap[$this->mime
] ) ) {
1035 $err = 'Image type not supported';
1036 wfDebug( "$err\n" );
1039 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1041 if( !function_exists( $loader ) ) {
1042 $err = "Incomplete GD library configuration: missing function $loader";
1043 wfDebug( "$err\n" );
1046 if( $colorStyle == 'palette' ) {
1048 } elseif( $colorStyle == 'truecolor' ) {
1050 } elseif( $colorStyle == 'bits' ) {
1051 $truecolor = ( $this->bits
> 8 );
1054 $src_image = call_user_func( $loader, $this->imagePath
);
1056 $dst_image = imagecreatetruecolor( $width, $height );
1058 $dst_image = imagecreate( $width, $height );
1060 imagecopyresampled( $dst_image, $src_image,
1062 $width, $height, $this->width
, $this->height
);
1063 call_user_func( $saveType, $dst_image, $thumbPath );
1064 imagedestroy( $dst_image );
1065 imagedestroy( $src_image );
1069 # Check for zero-sized thumbnails. Those can be generated when
1070 # no disk space is available or some other error occurs
1072 if( file_exists( $thumbPath ) ) {
1073 $thumbstat = stat( $thumbPath );
1074 if( $thumbstat['size'] == 0 ) {
1075 unlink( $thumbPath );
1080 function imageJpegWrapper( $dst_image, $thumbPath ) {
1081 imageinterlace( $dst_image );
1082 imagejpeg( $dst_image, $thumbPath, 95 );
1086 * Get all thumbnail names previously generated for this image
1088 function getThumbnails( $shared = false ) {
1089 if ( Image
::isHashed( $shared ) ) {
1092 $dir = wfImageThumbDir( $this->name
, $shared );
1094 // This generates an error on failure, hence the @
1095 $handle = @opendir
( $dir );
1098 while ( false !== ( $file = readdir($handle) ) ) {
1099 if ( $file{0} != '.' ) {
1103 closedir( $handle );
1113 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1115 function purgeCache( $archiveFiles = array(), $shared = false ) {
1116 global $wgInternalServer, $wgUseSquid;
1118 // Refresh metadata cache
1120 $this->loadFromFile();
1121 $this->saveToCache();
1123 // Delete thumbnails
1124 $files = $this->getThumbnails( $shared );
1125 $dir = wfImageThumbDir( $this->name
, $shared );
1127 foreach ( $files as $file ) {
1128 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1129 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1130 @unlink
( "$dir/$file" );
1135 if ( $wgUseSquid ) {
1136 $urls[] = $wgInternalServer . $this->getViewURL();
1137 foreach ( $archiveFiles as $file ) {
1138 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1140 wfPurgeSquidServers( $urls );
1144 function checkDBSchema(&$db) {
1145 # img_name must be unique
1146 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1147 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1150 #new fields must exist
1151 if ( !$db->fieldExists( 'image', 'img_media_type' )
1152 ||
!$db->fieldExists( 'image', 'img_metadata' )
1153 ||
!$db->fieldExists( 'image', 'img_width' ) ) {
1155 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1160 * Return the image history of this image, line by line.
1161 * starts with current version, then old versions.
1162 * uses $this->historyLine to check which line to return:
1163 * 0 return line for current version
1164 * 1 query for old versions, return first one
1165 * 2, ... return next old version from above query
1169 function nextHistoryLine() {
1170 $fname = 'Image::nextHistoryLine()';
1171 $dbr =& wfGetDB( DB_SLAVE
);
1173 $this->checkDBSchema($dbr);
1175 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1176 $this->historyRes
= $dbr->select( 'image',
1177 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
1178 array( 'img_name' => $this->title
->getDBkey() ),
1181 if ( 0 == wfNumRows( $this->historyRes
) ) {
1184 } else if ( $this->historyLine
== 1 ) {
1185 $this->historyRes
= $dbr->select( 'oldimage',
1186 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
1187 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
1188 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
1191 $this->historyLine ++
;
1193 return $dbr->fetchObject( $this->historyRes
);
1197 * Reset the history pointer to the first element of the history
1200 function resetHistory() {
1201 $this->historyLine
= 0;
1205 * Return the full filesystem path to the file. Note that this does
1206 * not mean that a file actually exists under that location.
1208 * This path depends on whether directory hashing is active or not,
1209 * i.e. whether the images are all found in the same directory,
1210 * or in hashed paths like /images/3/3c.
1213 * @param boolean $fromSharedDirectory Return the path to the file
1214 * in a shared repository (see $wgUseSharedRepository and related
1215 * options in DefaultSettings.php) instead of a local one.
1218 function getFullPath( $fromSharedRepository = false ) {
1219 global $wgUploadDirectory, $wgSharedUploadDirectory;
1220 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1222 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1225 // $wgSharedUploadDirectory may be false, if thumb.php is used
1227 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1239 function isHashed( $shared ) {
1240 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1241 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1245 * Record an image upload in the upload log and the image table
1247 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
1248 global $wgUser, $wgLang, $wgTitle, $wgDeferredUpdateList;
1249 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1251 $fname = 'Image::recordUpload';
1252 $dbw =& wfGetDB( DB_MASTER
);
1254 $this->checkDBSchema($dbw);
1256 // Delete thumbnails and refresh the metadata cache
1257 $this->purgeCache();
1259 // Fail now if the image isn't there
1260 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1261 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1265 if ( $wgUseCopyrightUpload ) {
1266 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1267 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1268 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1273 $now = $dbw->timestamp();
1276 if (strpos($this->mime
,'/')!==false) {
1277 list($major,$minor)= explode('/',$this->mime
,2);
1280 $major= $this->mime
;
1284 # Test to see if the row exists using INSERT IGNORE
1285 # This avoids race conditions by locking the row until the commit, and also
1286 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1287 $dbw->insert( 'image',
1289 'img_name' => $this->name
,
1290 'img_size'=> $this->size
,
1291 'img_width' => IntVal( $this->width
),
1292 'img_height' => IntVal( $this->height
),
1293 'img_bits' => $this->bits
,
1294 'img_media_type' => $this->type
,
1295 'img_major_mime' => $major,
1296 'img_minor_mime' => $minor,
1297 'img_timestamp' => $now,
1298 'img_description' => $desc,
1299 'img_user' => $wgUser->getID(),
1300 'img_user_text' => $wgUser->getName(),
1301 'img_metadata' => $this->metadata
,
1304 $descTitle = $this->getTitle();
1305 $purgeURLs = array();
1307 if ( $dbw->affectedRows() ) {
1308 # Successfully inserted, this is a new image
1309 $id = $descTitle->getArticleID();
1312 $article = new Article( $descTitle );
1313 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1316 # Collision, this is an update of an image
1317 # Insert previous contents into oldimage
1318 $dbw->insertSelect( 'oldimage', 'image',
1320 'oi_name' => 'img_name',
1321 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1322 'oi_size' => 'img_size',
1323 'oi_width' => 'img_width',
1324 'oi_height' => 'img_height',
1325 'oi_bits' => 'img_bits',
1326 'oi_timestamp' => 'img_timestamp',
1327 'oi_description' => 'img_description',
1328 'oi_user' => 'img_user',
1329 'oi_user_text' => 'img_user_text',
1330 ), array( 'img_name' => $this->name
), $fname
1333 # Update the current image row
1334 $dbw->update( 'image',
1336 'img_size' => $this->size
,
1337 'img_width' => intval( $this->width
),
1338 'img_height' => intval( $this->height
),
1339 'img_bits' => $this->bits
,
1340 'img_media_type' => $this->type
,
1341 'img_major_mime' => $major,
1342 'img_minor_mime' => $minor,
1343 'img_timestamp' => $now,
1344 'img_description' => $desc,
1345 'img_user' => $wgUser->getID(),
1346 'img_user_text' => $wgUser->getName(),
1347 'img_metadata' => $this->metadata
,
1348 ), array( /* WHERE */
1349 'img_name' => $this->name
1353 # Invalidate the cache for the description page
1354 $descTitle->invalidateCache();
1355 $purgeURLs[] = $descTitle->getInternalURL();
1358 # Invalidate cache for all pages using this image
1359 $linksTo = $this->getLinksTo();
1361 if ( $wgUseSquid ) {
1362 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1363 array_push( $wgPostCommitUpdateList, $u );
1365 Title
::touchArray( $linksTo );
1367 $log = new LogPage( 'upload' );
1368 $log->addEntry( 'upload', $descTitle, $desc );
1374 * Get an array of Title objects which are articles which use this image
1375 * Also adds their IDs to the link cache
1377 * This is mostly copied from Title::getLinksTo()
1379 function getLinksTo( $options = '' ) {
1380 global $wgLinkCache;
1381 $fname = 'Image::getLinksTo';
1382 wfProfileIn( $fname );
1385 $db =& wfGetDB( DB_MASTER
);
1387 $db =& wfGetDB( DB_SLAVE
);
1390 extract( $db->tableNames( 'page', 'imagelinks' ) );
1391 $encName = $db->addQuotes( $this->name
);
1392 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1393 $res = $db->query( $sql, $fname );
1396 if ( $db->numRows( $res ) ) {
1397 while ( $row = $db->fetchObject( $res ) ) {
1398 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1399 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1400 $retVal[] = $titleObj;
1404 $db->freeResult( $res );
1408 * Retrive Exif data from the database
1410 * Retrive Exif data from the database and prune unrecognized tags
1411 * and/or tags with invalid contents
1415 function retrieveExifData () {
1416 if ( $this->getMimeType() !== "image/jpeg" ) return array ();
1418 $exif = new Exif( $this->imagePath
);
1419 return $exif->getFilteredData();
1422 function getExifData () {
1424 if ( $this->metadata
=== '0' )
1427 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1428 $ret = unserialize ( $this->metadata
);
1430 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1431 $newver = Exif
::version();
1433 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1434 $this->updateExifData( $newver );
1436 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1437 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1438 $format = new FormatExif( $ret );
1439 return $format->getFormattedData();
1442 function updateExifData( $version ) {
1443 $fname = 'Image:updateExifData';
1445 if ( $this->getImagePath() === false ) # Not a local image
1448 # Get EXIF data from image
1449 $exif = $this->retrieveExifData();
1450 if ( count( $exif ) ) {
1451 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1452 $this->metadata
= serialize( $exif );
1454 $this->metadata
= '0';
1457 # Update EXIF data in database
1458 $dbw =& wfGetDB( DB_MASTER
);
1460 $this->checkDBSchema($dbw);
1462 $dbw->update( 'image',
1463 array( 'img_metadata' => $this->metadata
),
1464 array( 'img_name' => $this->name
),
1473 * Returns the image directory of an image
1474 * If the directory does not exist, it is created.
1475 * The result is an absolute path.
1477 * This function is called from thumb.php before Setup.php is included
1479 * @param string $fname file name of the image file
1482 function wfImageDir( $fname ) {
1483 global $wgUploadDirectory, $wgHashedUploadDirectory;
1485 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1487 $hash = md5( $fname );
1488 $oldumask = umask(0);
1489 $dest = $wgUploadDirectory . '/' . $hash{0};
1490 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1491 $dest .= '/' . substr( $hash, 0, 2 );
1492 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1499 * Returns the image directory of an image's thubnail
1500 * If the directory does not exist, it is created.
1501 * The result is an absolute path.
1503 * This function is called from thumb.php before Setup.php is included
1505 * @param string $fname file name of the original image file
1506 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1507 * @param boolean $shared (optional) use the shared upload directory
1510 function wfImageThumbDir( $fname, $shared = false ) {
1511 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1512 if ( Image
::isHashed( $shared ) ) {
1513 $dir = "$base/$fname";
1515 if ( !is_dir( $base ) ) {
1516 $oldumask = umask(0);
1517 @mkdir
( $base, 0777 );
1521 if ( ! is_dir( $dir ) ) {
1522 $oldumask = umask(0);
1523 @mkdir
( $dir, 0777 );
1534 * Old thumbnail directory, kept for conversion
1536 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1537 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1541 * Returns the image directory of an image's old version
1542 * If the directory does not exist, it is created.
1543 * The result is an absolute path.
1545 * This function is called from thumb.php before Setup.php is included
1547 * @param string $fname file name of the thumbnail file, including file size prefix
1548 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1549 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1552 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1553 global $wgUploadDirectory, $wgHashedUploadDirectory,
1554 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1555 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1556 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1557 if (!$hashdir) { return $dir.'/'.$subdir; }
1558 $hash = md5( $fname );
1559 $oldumask = umask(0);
1561 # Suppress warning messages here; if the file itself can't
1562 # be written we'll worry about it then.
1563 wfSuppressWarnings();
1565 $archive = $dir.'/'.$subdir;
1566 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1567 $archive .= '/' . $hash{0};
1568 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1569 $archive .= '/' . substr( $hash, 0, 2 );
1570 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1572 wfRestoreWarnings();
1579 * Return the hash path component of an image path (URL or filesystem),
1580 * e.g. "/3/3c/", or just "/" if hashing is not used.
1582 * @param $dbkey The filesystem / database name of the file
1583 * @param $fromSharedDirectory Use the shared file repository? It may
1584 * use different hash settings from the local one.
1586 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1587 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1588 global $wgHashedUploadDirectory;
1590 if( Image
::isHashed( $fromSharedDirectory ) ) {
1591 $hash = md5($dbkey);
1592 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1599 * Returns the image URL of an image's old version
1601 * @param string $fname file name of the image file
1602 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1605 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1606 global $wgUploadPath, $wgHashedUploadDirectory;
1608 if ($wgHashedUploadDirectory) {
1609 $hash = md5( substr( $name, 15) );
1610 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1611 substr( $hash, 0, 2 ) . '/'.$name;
1613 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1615 return wfUrlencode($url);
1619 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1620 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1622 * @param string $length
1623 * @return int Length in pixels
1625 function wfScaleSVGUnit( $length ) {
1626 static $unitLength = array(
1633 '' => 1.0, // "User units" pixels by default
1634 '%' => 2.0, // Fake it!
1636 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1637 $length = FloatVal( $matches[1] );
1638 $unit = $matches[2];
1639 return round( $length * $unitLength[$unit] );
1642 return round( FloatVal( $length ) );
1647 * Compatible with PHP getimagesize()
1648 * @todo support gzipped SVGZ
1649 * @todo check XML more carefully
1650 * @todo sensible defaults
1652 * @param string $filename
1655 function wfGetSVGsize( $filename ) {
1659 // Read a chunk of the file
1660 $f = fopen( $filename, "rt" );
1661 if( !$f ) return false;
1662 $chunk = fread( $f, 4096 );
1665 // Uber-crappy hack! Run through a real XML parser.
1666 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1670 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1671 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1673 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1674 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1677 return array( $width, $height, 'SVG',
1678 "width=\"$width\" height=\"$height\"" );
1682 * Determine if an image exists on the 'bad image list'
1684 * @param string $name The image to check
1687 function wfIsBadImage( $name ) {
1689 static $titleList = false;
1690 if ( $titleList === false ) {
1691 $titleList = array();
1693 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1694 foreach ( $lines as $line ) {
1695 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1696 $t = Title
::newFromText( $m[1] );
1697 $titleList[$t->getDBkey()] = 1;
1702 return array_key_exists( $name, $titleList );
1708 * Wrapper class for thumbnail images
1709 * @package MediaWiki
1711 class ThumbnailImage
{
1713 * @param string $path Filesystem path to the thumb
1714 * @param string $url URL path to the thumb
1717 function ThumbnailImage( $url, $width, $height, $path = false ) {
1719 $this->width
= $width;
1720 $this->height
= $height;
1721 $this->path
= $path;
1725 * @return string The thumbnail URL
1732 * Return HTML <img ... /> tag for the thumbnail, will include
1733 * width and height attributes and a blank alt text (as required).
1735 * You can set or override additional attributes by passing an
1736 * associative array of name => data pairs. The data will be escaped
1737 * for HTML output, so should be in plaintext.
1739 * @param array $attribs
1743 function toHtml( $attribs = array() ) {
1744 $attribs['src'] = $this->url
;
1745 $attribs['width'] = $this->width
;
1746 $attribs['height'] = $this->height
;
1747 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1750 foreach( $attribs as $name => $data ) {
1751 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';