02424dc83ef281dc71377abb9b261360863e0a21
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 $exif, # The Exif class
52 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
58 * Create an Image object from an image name
60 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
63 function newFromName( $name ) {
64 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
65 return new Image( $title );
69 * Obsolete factory function, use constructor
71 function newFromTitle( $title ) {
72 return new Image( $title );
75 function Image( $title ) {
78 if( !is_object( $title ) ) {
79 wfDebugDieBacktrace( 'Image constructor given bogus title.' );
81 $this->title
=& $title;
82 $this->name
= $title->getDBkey();
83 $this->metadata
= serialize ( array() ) ;
85 $n = strrpos( $this->name
, '.' );
86 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
87 $this->historyLine
= 0;
89 $this->dataLoaded
= false;
92 $this->exif
= new Exif
;
96 * Get the memcached keys
97 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
99 function getCacheKeys( $shared = false ) {
100 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
102 $foundCached = false;
103 $hashedName = md5($this->name
);
104 $keys = array( "$wgDBname:Image:$hashedName" );
105 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
106 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
112 * Try to load image metadata from memcached. Returns true on success.
114 function loadFromCache() {
115 global $wgUseSharedUploads, $wgMemc;
116 $fname = 'Image::loadFromMemcached';
117 wfProfileIn( $fname );
118 $this->dataLoaded
= false;
119 $keys = $this->getCacheKeys();
120 $cachedValues = $wgMemc->get( $keys[0] );
122 // Check if the key existed and belongs to this version of MediaWiki
123 if (!empty($cachedValues) && is_array($cachedValues)
124 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
125 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
127 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
128 # if this is shared file, we need to check if image
129 # in shared repository has not changed
130 if ( isset( $keys[1] ) ) {
131 $commonsCachedValues = $wgMemc->get( $keys[1] );
132 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
133 && isset($commonsCachedValues['version'])
134 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
135 && isset($commonsCachedValues['mime'])) {
136 wfDebug( "Pulling image metadata from shared repository cache\n" );
137 $this->name
= $commonsCachedValues['name'];
138 $this->imagePath
= $commonsCachedValues['imagePath'];
139 $this->fileExists
= $commonsCachedValues['fileExists'];
140 $this->width
= $commonsCachedValues['width'];
141 $this->height
= $commonsCachedValues['height'];
142 $this->bits
= $commonsCachedValues['bits'];
143 $this->type
= $commonsCachedValues['type'];
144 $this->mime
= $commonsCachedValues['mime'];
145 $this->metadata
= $commonsCachedValues['metadata'];
146 $this->size
= $commonsCachedValues['size'];
147 $this->fromSharedDirectory
= true;
148 $this->dataLoaded
= true;
149 $this->imagePath
= $this->getFullPath(true);
153 wfDebug( "Pulling image metadata from local cache\n" );
154 $this->name
= $cachedValues['name'];
155 $this->imagePath
= $cachedValues['imagePath'];
156 $this->fileExists
= $cachedValues['fileExists'];
157 $this->width
= $cachedValues['width'];
158 $this->height
= $cachedValues['height'];
159 $this->bits
= $cachedValues['bits'];
160 $this->type
= $cachedValues['type'];
161 $this->mime
= $cachedValues['mime'];
162 $this->metadata
= $cachedValues['metadata'];
163 $this->size
= $cachedValues['size'];
164 $this->fromSharedDirectory
= false;
165 $this->dataLoaded
= true;
166 $this->imagePath
= $this->getFullPath();
169 if ( $this->dataLoaded
) {
170 wfIncrStats( 'image_cache_hit' );
172 wfIncrStats( 'image_cache_miss' );
175 wfProfileOut( $fname );
176 return $this->dataLoaded
;
180 * Save the image metadata to memcached
182 function saveToCache() {
185 $keys = $this->getCacheKeys();
186 if ( $this->fileExists
) {
187 // We can't cache negative metadata for non-existent files,
188 // because if the file later appears in commons, the local
189 // keys won't be purged.
190 $cachedValues = array(
191 'version' => MW_IMAGE_VERSION
,
192 'name' => $this->name
,
193 'imagePath' => $this->imagePath
,
194 'fileExists' => $this->fileExists
,
195 'fromShared' => $this->fromSharedDirectory
,
196 'width' => $this->width
,
197 'height' => $this->height
,
198 'bits' => $this->bits
,
199 'type' => $this->type
,
200 'mime' => $this->mime
,
201 'metadata' => $this->metadata
,
202 'size' => $this->size
);
204 $wgMemc->set( $keys[0], $cachedValues );
206 // However we should clear them, so they aren't leftover
207 // if we've deleted the file.
208 $wgMemc->delete( $keys[0] );
213 * Load metadata from the file itself
215 function loadFromFile() {
216 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang,
218 $fname = 'Image::loadFromFile';
219 wfProfileIn( $fname );
220 $this->imagePath
= $this->getFullPath();
221 $this->fileExists
= file_exists( $this->imagePath
);
222 $this->fromSharedDirectory
= false;
225 if (!$this->fileExists
) wfDebug("$fname: ".$this->imagePath
." not found locally!\n");
227 # If the file is not found, and a shared upload directory is used, look for it there.
228 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
229 # In case we're on a wgCapitalLinks=false wiki, we
230 # capitalize the first letter of the filename before
231 # looking it up in the shared repository.
232 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
233 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
234 if ( $this->fileExists
) {
235 $this->name
= $sharedImage->name
;
236 $this->imagePath
= $this->getFullPath(true);
237 $this->fromSharedDirectory
= true;
242 if ( $this->fileExists
) {
243 $magic=& wfGetMimeMagic();
245 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
246 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
249 $this->size
= filesize( $this->imagePath
);
251 $magic=& wfGetMimeMagic();
254 if( $this->mime
== 'image/svg' ) {
255 wfSuppressWarnings();
256 $gis = wfGetSVGsize( $this->imagePath
);
259 elseif ( !$magic->isPHPImageType( $this->mime
) ) {
260 # Don't try to get the width and height of sound and video files, that's bad for performance
263 $gis[2]= 0; //unknown
264 $gis[3]= ""; //width height string
267 wfSuppressWarnings();
268 $gis = getimagesize( $this->imagePath
);
272 wfDebug("$fname: ".$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
277 $gis[2]= 0; //unknown
278 $gis[3]= ""; //width height string
281 $this->type
= MEDIATYPE_UNKNOWN
;
282 wfDebug("$fname: ".$this->imagePath
." NOT FOUND!\n");
285 $this->width
= $gis[0];
286 $this->height
= $gis[1];
288 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
290 #NOTE: we have to set this flag early to avoid load() to be called
291 # be some of the functions below. This may lead to recursion or other bad things!
292 # as ther's only one thread of execution, this should be safe anyway.
293 $this->dataLoaded
= true;
296 if ($this->fileExists
&& $wgShowEXIF) $this->metadata
= serialize ( $this->retrieveExifData() ) ;
297 else $this->metadata
= serialize ( array() ) ;
299 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
300 else $this->bits
= 0;
302 wfProfileOut( $fname );
306 * Load image metadata from the DB
308 function loadFromDB() {
309 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
310 $fname = 'Image::loadFromDB';
311 wfProfileIn( $fname );
313 $dbr =& wfGetDB( DB_SLAVE
);
315 $this->checkDBSchema($dbr);
317 $row = $dbr->selectRow( 'image',
318 array( 'img_size', 'img_width', 'img_height', 'img_bits',
319 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
320 array( 'img_name' => $this->name
), $fname );
322 $this->fromSharedDirectory
= false;
323 $this->fileExists
= true;
324 $this->loadFromRow( $row );
325 $this->imagePath
= $this->getFullPath();
326 // Check for rows from a previous schema, quietly upgrade them
327 if ( is_null($this->type
) ) {
330 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
331 # In case we're on a wgCapitalLinks=false wiki, we
332 # capitalize the first letter of the filename before
333 # looking it up in the shared repository.
334 $name = $wgLang->ucfirst($this->name
);
336 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
338 'img_size', 'img_width', 'img_height', 'img_bits',
339 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
340 array( 'img_name' => $name ), $fname );
342 $this->fromSharedDirectory
= true;
343 $this->fileExists
= true;
344 $this->imagePath
= $this->getFullPath(true);
346 $this->loadFromRow( $row );
348 // Check for rows from a previous schema, quietly upgrade them
349 if ( is_null($this->type
) ) {
361 $this->fileExists
= false;
362 $this->fromSharedDirectory
= false;
363 $this->metadata
= serialize ( array() ) ;
366 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
367 $this->dataLoaded
= true;
368 wfProfileOut( $fname );
372 * Load image metadata from a DB result row
374 function loadFromRow( &$row ) {
375 $this->size
= $row->img_size
;
376 $this->width
= $row->img_width
;
377 $this->height
= $row->img_height
;
378 $this->bits
= $row->img_bits
;
379 $this->type
= $row->img_media_type
;
381 $major= $row->img_major_mime
;
382 $minor= $row->img_minor_mime
;
384 if (!$major) $this->mime
= "unknown/unknown";
386 if (!$minor) $minor= "unknown";
387 $this->mime
= $major.'/'.$minor;
390 $this->metadata
= $row->img_metadata
;
391 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
393 $this->dataLoaded
= true;
397 * Load image metadata from cache or DB, unless already loaded
400 global $wgSharedUploadDBname, $wgUseSharedUploads;
401 if ( !$this->dataLoaded
) {
402 if ( !$this->loadFromCache() ) {
404 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
405 $this->loadFromFile();
406 } elseif ( $this->fileExists
) {
407 $this->saveToCache();
410 $this->dataLoaded
= true;
415 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
416 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
418 function upgradeRow() {
419 global $wgDBname, $wgSharedUploadDBname;
420 $fname = 'Image::upgradeRow';
421 wfProfileIn( $fname );
423 $this->loadFromFile();
424 $dbw =& wfGetDB( DB_MASTER
);
426 if ( $this->fromSharedDirectory
) {
427 if ( !$wgSharedUploadDBname ) {
428 wfProfileOut( $fname );
432 // Write to the other DB using selectDB, not database selectors
433 // This avoids breaking replication in MySQL
434 $dbw->selectDB( $wgSharedUploadDBname );
437 $this->checkDBSchema($dbw);
439 if (strpos($this->mime
,'/')!==false) {
440 list($major,$minor)= explode('/',$this->mime
,2);
447 wfDebug("$fname: upgrading ".$this->name
." to 1.5 schema\n");
449 $dbw->update( 'image',
451 'img_width' => $this->width
,
452 'img_height' => $this->height
,
453 'img_bits' => $this->bits
,
454 'img_media_type' => $this->type
,
455 'img_major_mime' => $major,
456 'img_minor_mime' => $minor,
457 'img_metadata' => $this->metadata
,
458 ), array( 'img_name' => $this->name
), $fname
460 if ( $this->fromSharedDirectory
) {
461 $dbw->selectDB( $wgDBname );
463 wfProfileOut( $fname );
467 * Return the name of this image
475 * Return the associated title object
478 function getTitle() {
483 * Return the URL of the image file
489 if($this->fileExists
) {
490 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
498 function getViewURL() {
499 if( $this->mustRender()) {
500 if( $this->canRender() ) {
501 return $this->createThumb( $this->getWidth() );
504 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
505 return $this->getURL(); #hm... return NULL?
508 return $this->getURL();
513 * Return the image path of the image in the
514 * local file system as an absolute path
517 function getImagePath() {
519 return $this->imagePath
;
523 * Return the width of the image
525 * Returns -1 if the file specified is not a known image type
528 function getWidth() {
534 * Return the height of the image
536 * Returns -1 if the file specified is not a known image type
539 function getHeight() {
541 return $this->height
;
545 * Return the size of the image file, in bytes
554 * Returns the mime type of the file.
556 function getMimeType() {
562 * Return the type of the media in the file.
563 * Use the value returned by this function with the MEDIATYPE_xxx constants.
565 function getMediaType() {
571 * Checks if the file can be presented to the browser as a bitmap.
573 * Currently, this checks if the file is an image format
574 * that can be converted to a format
575 * supported by all browsers (namely GIF, PNG and JPEG),
576 * or if it is an SVG image and SVG conversion is enabled.
578 * @todo remember the result of this check.
580 function canRender() {
581 global $wgUseImageMagick;
583 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
585 $mime= $this->getMimeType();
587 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
589 #if it's SVG, check if ther's a converter enabled
590 if ($mime === 'image/svg') {
591 global $wgSVGConverters, $wgSVGConverter;
593 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
598 #image formats available on ALL browsers
599 if ( $mime === 'image/gif'
600 ||
$mime === 'image/png'
601 ||
$mime === 'image/jpeg' ) return true;
603 #image formats that can be converted to the above formats
604 if ($wgUseImageMagick) {
605 #convertable by ImageMagick (there are more...)
606 if ( $mime === 'image/vnd.wap.wbmp'
607 ||
$mime === 'image/x-xbitmap'
608 ||
$mime === 'image/x-xpixmap'
609 #|| $mime === 'image/x-icon' #file may be split into multiple parts
610 ||
$mime === 'image/x-portable-anymap'
611 ||
$mime === 'image/x-portable-bitmap'
612 ||
$mime === 'image/x-portable-graymap'
613 ||
$mime === 'image/x-portable-pixmap'
614 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
615 ||
$mime === 'image/x-rgb'
616 ||
$mime === 'image/x-bmp'
617 ||
$mime === 'image/tiff' ) return true;
620 #convertable by the PHP GD image lib
621 if ( $mime === 'image/vnd.wap.wbmp'
622 ||
$mime === 'image/x-xbitmap' ) return true;
630 * Return true if the file is of a type that can't be directly
631 * rendered by typical browsers and needs to be re-rasterized.
633 * This returns true for everything but the bitmap types
634 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
635 * also return true for any non-image formats.
639 function mustRender() {
640 $mime= $this->getMimeType();
642 if ( $mime === "image/gif"
643 ||
$mime === "image/png"
644 ||
$mime === "image/jpeg" ) return false;
650 * Determines if this media file may be shown inline on a page.
652 * This is currently synonymous to canRender(), but this could be
653 * extended to also allow inline display of other media,
654 * like flash animations or videos. If you do so, please keep in mind that
655 * that could be a security risk.
657 function allowInlineDisplay() {
658 return $this->canRender();
662 * Determines if this media file is in a format that is unlikely to
663 * contain viruses or malicious content. It uses the global
664 * $wgTrustedMediaFormats list to determine if the file is safe.
666 * This is used to show a warning on the description page of non-safe files.
667 * It may also be used to disallow direct [[media:...]] links to such files.
669 * Note that this function will always return ture if allowInlineDisplay()
670 * or isTrustedFile() is true for this file.
672 function isSafeFile() {
673 if ($this->allowInlineDisplay()) return true;
674 if ($this->isTrustedFile()) return true;
676 global $wgTrustedMediaFormats;
678 $type= $this->getMediaType();
679 $mime= $this->getMimeType();
680 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
682 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
683 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
685 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
686 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
691 /** Returns true if the file is flagegd as trusted. Files flagged that way
692 * can be linked to directly, even if that is not allowed for this type of
695 * This is a dummy function right now and always returns false. It could be
696 * implemented to extract a flag from the database. The trusted flag could be
697 * set on upload, if the user has sufficient privileges, to bypass script-
698 * and html-filters. It may even be coupeled with cryptographics signatures
701 function isTrustedFile() {
702 #this could be implemented to check a flag in the databas,
703 #look for signatures, etc
708 * Return the escapeLocalURL of this image
711 function getEscapeLocalURL() {
713 return $this->title
->escapeLocalURL();
717 * Return the escapeFullURL of this image
720 function getEscapeFullURL() {
722 return $this->title
->escapeFullURL();
726 * Return the URL of an image, provided its name.
728 * @param string $name Name of the image, without the leading "Image:"
729 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
730 * @return string URL of $name image
734 function imageUrl( $name, $fromSharedDirectory = false ) {
735 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
736 if($fromSharedDirectory) {
738 $path = $wgSharedUploadPath;
740 $base = $wgUploadBaseUrl;
741 $path = $wgUploadPath;
743 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
744 return wfUrlencode( $url );
748 * Returns true if the image file exists on disk.
749 * @return boolean Whether image file exist on disk.
754 return $this->fileExists
;
761 function thumbUrl( $width, $subdir='thumb') {
762 global $wgUploadPath, $wgUploadBaseUrl,
763 $wgSharedUploadPath,$wgSharedUploadDirectory,
764 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
766 // Generate thumb.php URL if possible
770 if ( $this->fromSharedDirectory
) {
771 if ( $wgSharedThumbnailScriptPath ) {
772 $script = $wgSharedThumbnailScriptPath;
775 if ( $wgThumbnailScriptPath ) {
776 $script = $wgThumbnailScriptPath;
780 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
781 if( $this->mustRender() ) {
785 $name = $this->thumbName( $width );
786 if($this->fromSharedDirectory
) {
788 $path = $wgSharedUploadPath;
790 $base = $wgUploadBaseUrl;
791 $path = $wgUploadPath;
793 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
794 $url = "{$base}{$path}/{$subdir}" .
795 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
796 . $this->name
.'/'.$name;
797 $url = wfUrlencode( $url );
799 $url = "{$base}{$path}/{$subdir}/{$name}";
802 return array( $script !== false, $url );
806 * Return the file name of a thumbnail of the specified width
808 * @param integer $width Width of the thumbnail image
809 * @param boolean $shared Does the thumbnail come from the shared repository?
812 function thumbName( $width ) {
813 $thumb = $width."px-".$this->name
;
815 if( $this->mustRender() ) {
816 if( $this->canRender() ) {
817 # Rasterize to PNG (for SVG vector images, etc)
821 #should we use iconThumb here to get a symbolic thumbnail?
822 #or should we fail with an internal error?
823 return NULL; //can't make bitmap
830 * Create a thumbnail of the image having the specified width/height.
831 * The thumbnail will not be created if the width is larger than the
832 * image's width. Let the browser do the scaling in this case.
833 * The thumbnail is stored on disk and is only computed if the thumbnail
834 * file does not exist OR if it is older than the image.
837 * Keeps aspect ratio of original image. If both width and height are
838 * specified, the generated image will be no bigger than width x height,
839 * and will also have correct aspect ratio.
841 * @param integer $width maximum width of the generated thumbnail
842 * @param integer $height maximum height of the image (optional)
845 function createThumb( $width, $height=-1 ) {
846 $thumb = $this->getThumbnail( $width, $height );
847 if( is_null( $thumb ) ) return '';
848 return $thumb->getUrl();
852 * As createThumb, but returns a ThumbnailImage object. This can
853 * provide access to the actual file, the real size of the thumb,
854 * and can produce a convenient <img> tag for you.
856 * @param integer $width maximum width of the generated thumbnail
857 * @param integer $height maximum height of the image (optional)
858 * @return ThumbnailImage
861 function &getThumbnail( $width, $height=-1 ) {
862 if ( $height == -1 ) {
863 return $this->renderThumb( $width );
867 if ($this->canRender()) {
868 if ( $width < $this->width
) {
869 $thumbheight = $this->height
* $width / $this->width
;
870 $thumbwidth = $width;
872 $thumbheight = $this->height
;
873 $thumbwidth = $this->width
;
875 if ( $thumbheight > $height ) {
876 $thumbwidth = $thumbwidth * $height / $thumbheight;
877 $thumbheight = $height;
880 $thumb = $this->renderThumb( $thumbwidth );
882 else $thumb= NULL; #not a bitmap or renderable image, don't try.
884 if( is_null( $thumb ) ) {
885 $thumb = $this->iconThumb();
891 * @return ThumbnailImage
893 function iconThumb() {
894 global $wgStylePath, $wgStyleDirectory;
896 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
897 foreach( $try as $icon ) {
898 $path = '/common/images/icons/' . $icon;
899 $filepath = $wgStyleDirectory . $path;
900 if( file_exists( $filepath ) ) {
901 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
908 * Create a thumbnail of the image having the specified width.
909 * The thumbnail will not be created if the width is larger than the
910 * image's width. Let the browser do the scaling in this case.
911 * The thumbnail is stored on disk and is only computed if the thumbnail
912 * file does not exist OR if it is older than the image.
913 * Returns an object which can return the pathname, URL, and physical
914 * pixel size of the thumbnail -- or null on failure.
916 * @return ThumbnailImage
919 function renderThumb( $width, $useScript = true ) {
920 global $wgUseSquid, $wgInternalServer;
921 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
923 $width = IntVal( $width );
926 if ( ! $this->exists() )
928 # If there is no image, there will be no thumbnail
932 # Sanity check $width
933 if( $width <= 0 ||
$this->width
<= 0) {
938 if( $width >= $this->width
&& !$this->mustRender() ) {
939 # Don't make an image bigger than the source
940 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
943 $height = floor( $this->height
* ( $width/$this->width
) );
945 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
946 if ( $isScriptUrl && $useScript ) {
947 // Use thumb.php to render the image
948 return new ThumbnailImage( $url, $width, $height );
951 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
952 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
954 if ( !file_exists( $thumbPath ) ) {
955 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
958 if ( file_exists( $oldThumbPath ) ) {
959 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
960 rename( $oldThumbPath, $thumbPath );
963 unlink( $oldThumbPath );
967 $this->reallyRenderThumb( $thumbPath, $width, $height );
970 # This has to be done after the image is updated and present for all machines on NFS,
971 # or else the old version might be stored into the squid again
973 if ( substr( $url, 0, 4 ) == 'http' ) {
974 $urlArr = array( $url );
976 $urlArr = array( $wgInternalServer.$url );
978 wfPurgeSquidServers($urlArr);
983 return new ThumbnailImage( $url, $width, $height, $thumbPath );
984 } // END OF function renderThumb
987 * Really render a thumbnail
988 * Call this only for images for which canRender() returns true.
992 function reallyRenderThumb( $thumbPath, $width, $height ) {
993 global $wgSVGConverters, $wgSVGConverter,
994 $wgUseImageMagick, $wgImageMagickConvertCommand;
998 if( $this->mime
=== "image/svg" ) {
999 #Right now we have only SVG
1001 global $wgSVGConverters, $wgSVGConverter;
1002 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1003 global $wgSVGConverterPath;
1005 array( '$path/', '$width', '$input', '$output' ),
1006 array( $wgSVGConverterPath,
1008 wfEscapeShellArg( $this->imagePath
),
1009 wfEscapeShellArg( $thumbPath ) ),
1010 $wgSVGConverters[$wgSVGConverter] );
1011 $conv = shell_exec( $cmd );
1015 } elseif ( $wgUseImageMagick ) {
1017 # Specify white background color, will be used for transparent images
1018 # in Internet Explorer/Windows instead of default black.
1019 $cmd = $wgImageMagickConvertCommand .
1020 " -quality 85 -background white -geometry {$width} ".
1021 wfEscapeShellArg($this->imagePath
) . " " .
1022 wfEscapeShellArg($thumbPath);
1023 wfDebug("reallyRenderThumb: running ImageMagick: $cmd");
1024 $conv = shell_exec( $cmd );
1026 # Use PHP's builtin GD library functions.
1028 # First find out what kind of file this is, and select the correct
1029 # input routine for this.
1033 switch( $this->type
) {
1035 $src_image = imagecreatefromgif( $this->imagePath
);
1038 $src_image = imagecreatefromjpeg( $this->imagePath
);
1042 $src_image = imagecreatefrompng( $this->imagePath
);
1043 $truecolor = ( $this->bits
> 8 );
1045 case 15: # WBMP for WML
1046 $src_image = imagecreatefromwbmp( $this->imagePath
);
1049 $src_image = imagecreatefromxbm( $this->imagePath
);
1052 return 'Image type not supported';
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 switch( $this->type
) {
1068 imagepng( $dst_image, $thumbPath );
1071 imageinterlace( $dst_image );
1072 imagejpeg( $dst_image, $thumbPath, 95 );
1077 imagedestroy( $dst_image );
1078 imagedestroy( $src_image );
1082 # Check for zero-sized thumbnails. Those can be generated when
1083 # no disk space is available or some other error occurs
1085 if( file_exists( $thumbPath ) ) {
1086 $thumbstat = stat( $thumbPath );
1087 if( $thumbstat['size'] == 0 ) {
1088 unlink( $thumbPath );
1094 * Get all thumbnail names previously generated for this image
1096 function getThumbnails( $shared = false ) {
1097 if ( Image
::isHashed( $shared ) ) {
1100 $dir = wfImageThumbDir( $this->name
, $shared );
1102 // This generates an error on failure, hence the @
1103 $handle = @opendir
( $dir );
1106 while ( false !== ( $file = readdir($handle) ) ) {
1107 if ( $file{0} != '.' ) {
1111 closedir( $handle );
1121 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1123 function purgeCache( $archiveFiles = array(), $shared = false ) {
1124 global $wgInternalServer, $wgUseSquid;
1126 // Refresh metadata cache
1128 $this->loadFromFile();
1129 $this->saveToCache();
1131 // Delete thumbnails
1132 $files = $this->getThumbnails( $shared );
1133 $dir = wfImageThumbDir( $this->name
, $shared );
1135 foreach ( $files as $file ) {
1136 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1137 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1138 @unlink
( "$dir/$file" );
1143 if ( $wgUseSquid ) {
1144 $urls[] = $wgInternalServer . $this->getViewURL();
1145 foreach ( $archiveFiles as $file ) {
1146 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1148 wfPurgeSquidServers( $urls );
1152 function checkDBSchema(&$db) {
1153 # img_name must be unique
1154 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1155 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1158 #new fields must exist
1159 if ( !$db->fieldExists( 'image', 'img_media_type' )
1160 ||
!$db->fieldExists( 'image', 'img_metadata' )
1161 ||
!$db->fieldExists( 'image', 'img_width' ) ) {
1163 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1168 * Return the image history of this image, line by line.
1169 * starts with current version, then old versions.
1170 * uses $this->historyLine to check which line to return:
1171 * 0 return line for current version
1172 * 1 query for old versions, return first one
1173 * 2, ... return next old version from above query
1177 function nextHistoryLine() {
1178 $fname = 'Image::nextHistoryLine()';
1179 $dbr =& wfGetDB( DB_SLAVE
);
1181 $this->checkDBSchema($dbr);
1183 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1184 $this->historyRes
= $dbr->select( 'image',
1185 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
1186 array( 'img_name' => $this->title
->getDBkey() ),
1189 if ( 0 == wfNumRows( $this->historyRes
) ) {
1192 } else if ( $this->historyLine
== 1 ) {
1193 $this->historyRes
= $dbr->select( 'oldimage',
1194 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
1195 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
1196 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
1199 $this->historyLine ++
;
1201 return $dbr->fetchObject( $this->historyRes
);
1205 * Reset the history pointer to the first element of the history
1208 function resetHistory() {
1209 $this->historyLine
= 0;
1213 * Return the full filesystem path to the file. Note that this does
1214 * not mean that a file actually exists under that location.
1216 * This path depends on whether directory hashing is active or not,
1217 * i.e. whether the images are all found in the same directory,
1218 * or in hashed paths like /images/3/3c.
1221 * @param boolean $fromSharedDirectory Return the path to the file
1222 * in a shared repository (see $wgUseSharedRepository and related
1223 * options in DefaultSettings.php) instead of a local one.
1226 function getFullPath( $fromSharedRepository = false ) {
1227 global $wgUploadDirectory, $wgSharedUploadDirectory;
1228 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1230 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1233 // $wgSharedUploadDirectory may be false, if thumb.php is used
1235 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1247 function isHashed( $shared ) {
1248 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1249 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1253 * Record an image upload in the upload log and the image table
1255 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
1256 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
1257 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1259 $fname = 'Image::recordUpload';
1260 $dbw =& wfGetDB( DB_MASTER
);
1262 $this->checkDBSchema($dbw);
1264 // Delete thumbnails and refresh the metadata cache
1265 $this->purgeCache();
1267 // Fail now if the image isn't there
1268 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1269 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1273 if ( $wgUseCopyrightUpload ) {
1274 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1275 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1276 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1281 $now = $dbw->timestamp();
1284 if (strpos($this->mime
,'/')!==false) {
1285 list($major,$minor)= explode('/',$this->mime
,2);
1288 $major= $this->mime
;
1292 # Test to see if the row exists using INSERT IGNORE
1293 # This avoids race conditions by locking the row until the commit, and also
1294 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1295 $dbw->insert( 'image',
1297 'img_name' => $this->name
,
1298 'img_size'=> $this->size
,
1299 'img_width' => IntVal( $this->width
),
1300 'img_height' => IntVal( $this->height
),
1301 'img_bits' => $this->bits
,
1302 'img_media_type' => $this->type
,
1303 'img_major_mime' => $major,
1304 'img_minor_mime' => $minor,
1305 'img_timestamp' => $now,
1306 'img_description' => $desc,
1307 'img_user' => $wgUser->getID(),
1308 'img_user_text' => $wgUser->getName(),
1309 'img_metadata' => $this->metadata
,
1312 $descTitle = $this->getTitle();
1313 $purgeURLs = array();
1315 if ( $dbw->affectedRows() ) {
1316 # Successfully inserted, this is a new image
1317 $id = $descTitle->getArticleID();
1320 $article = new Article( $descTitle );
1321 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1324 # Collision, this is an update of an image
1325 # Insert previous contents into oldimage
1326 $dbw->insertSelect( 'oldimage', 'image',
1328 'oi_name' => 'img_name',
1329 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1330 'oi_size' => 'img_size',
1331 'oi_width' => 'img_width',
1332 'oi_height' => 'img_height',
1333 'oi_bits' => 'img_bits',
1334 'oi_timestamp' => 'img_timestamp',
1335 'oi_description' => 'img_description',
1336 'oi_user' => 'img_user',
1337 'oi_user_text' => 'img_user_text',
1338 ), array( 'img_name' => $this->name
), $fname
1341 # Update the current image row
1342 $dbw->update( 'image',
1344 'img_size' => $this->size
,
1345 'img_width' => intval( $this->width
),
1346 'img_height' => intval( $this->height
),
1347 'img_bits' => $this->bits
,
1348 'img_media_type' => $this->type
,
1349 'img_major_mime' => $major,
1350 'img_minor_mime' => $minor,
1351 'img_timestamp' => $now,
1352 'img_description' => $desc,
1353 'img_user' => $wgUser->getID(),
1354 'img_user_text' => $wgUser->getName(),
1355 'img_metadata' => $this->metadata
,
1356 ), array( /* WHERE */
1357 'img_name' => $this->name
1361 # Invalidate the cache for the description page
1362 $descTitle->invalidateCache();
1363 $purgeURLs[] = $descTitle->getInternalURL();
1366 # Invalidate cache for all pages using this image
1367 $linksTo = $this->getLinksTo();
1369 if ( $wgUseSquid ) {
1370 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1371 array_push( $wgPostCommitUpdateList, $u );
1373 Title
::touchArray( $linksTo );
1375 $log = new LogPage( 'upload' );
1376 $log->addEntry( 'upload', $descTitle, $desc );
1382 * Get an array of Title objects which are articles which use this image
1383 * Also adds their IDs to the link cache
1385 * This is mostly copied from Title::getLinksTo()
1387 function getLinksTo( $options = '' ) {
1388 global $wgLinkCache;
1389 $fname = 'Image::getLinksTo';
1390 wfProfileIn( $fname );
1393 $db =& wfGetDB( DB_MASTER
);
1395 $db =& wfGetDB( DB_SLAVE
);
1398 extract( $db->tableNames( 'page', 'imagelinks' ) );
1399 $encName = $db->addQuotes( $this->name
);
1400 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1401 $res = $db->query( $sql, $fname );
1404 if ( $db->numRows( $res ) ) {
1405 while ( $row = $db->fetchObject( $res ) ) {
1406 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1407 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1408 $retVal[] = $titleObj;
1412 $db->freeResult( $res );
1416 * Retrive Exif data from the database
1418 * Retrive Exif data from the database and prune unrecognized tags
1419 * and/or tags with invalid contents
1423 function retrieveExifData () {
1424 if ( $this->getMimeType() !== "image/jpeg" ) return array ();
1426 wfSuppressWarnings();
1427 $exif = exif_read_data( $this->imagePath
);
1428 wfRestoreWarnings();
1430 foreach($exif as $k => $v) {
1431 if ( !in_array($k, array_keys($this->exif
->mFlatExif
)) ) {
1432 wfDebug( "Image::retrieveExifData: '$k' is not a valid Exif tag (type: '" . gettype($v) . "'; data: '$v')\n");
1437 foreach($exif as $k => $v) {
1438 if ( !$this->exif
->validate($k, $v) ) {
1439 wfDebug( "Image::retrieveExifData: '$k' contained invalid data (type: '" . gettype($v) . "'; data: '$v')\n");
1446 function getExifData () {
1448 if ( $this->metadata
=== '0' )
1451 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1452 $ret = unserialize ( $this->metadata
);
1454 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1455 $newver = $this->exif
->version();
1457 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1458 $this->updateExifData( $newver );
1460 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1461 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1463 foreach($ret as $k => $v) {
1464 $ret[$k] = $this->exif
->format($k, $v);
1470 function updateExifData( $version ) {
1471 $fname = 'Image:updateExifData';
1473 if ( $this->getImagePath() === false ) # Not a local image
1476 # Get EXIF data from image
1477 $exif = $this->retrieveExifData();
1478 if ( count( $exif ) ) {
1479 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1480 $this->metadata
= serialize( $exif );
1482 $this->metadata
= '0';
1485 # Update EXIF data in database
1486 $dbw =& wfGetDB( DB_MASTER
);
1488 $this->checkDBSchema($dbw);
1490 $dbw->update( 'image',
1491 array( 'img_metadata' => $this->metadata
),
1492 array( 'img_name' => $this->name
),
1501 * Returns the image directory of an image
1502 * If the directory does not exist, it is created.
1503 * The result is an absolute path.
1505 * This function is called from thumb.php before Setup.php is included
1507 * @param string $fname file name of the image file
1510 function wfImageDir( $fname ) {
1511 global $wgUploadDirectory, $wgHashedUploadDirectory;
1513 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1515 $hash = md5( $fname );
1516 $oldumask = umask(0);
1517 $dest = $wgUploadDirectory . '/' . $hash{0};
1518 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1519 $dest .= '/' . substr( $hash, 0, 2 );
1520 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1527 * Returns the image directory of an image's thubnail
1528 * If the directory does not exist, it is created.
1529 * The result is an absolute path.
1531 * This function is called from thumb.php before Setup.php is included
1533 * @param string $fname file name of the original image file
1534 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1535 * @param boolean $shared (optional) use the shared upload directory
1538 function wfImageThumbDir( $fname, $shared = false ) {
1539 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1540 if ( Image
::isHashed( $shared ) ) {
1541 $dir = "$base/$fname";
1543 if ( !is_dir( $base ) ) {
1544 $oldumask = umask(0);
1545 @mkdir
( $base, 0777 );
1549 if ( ! is_dir( $dir ) ) {
1550 $oldumask = umask(0);
1551 @mkdir
( $dir, 0777 );
1562 * Old thumbnail directory, kept for conversion
1564 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1565 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1569 * Returns the image directory of an image's old version
1570 * If the directory does not exist, it is created.
1571 * The result is an absolute path.
1573 * This function is called from thumb.php before Setup.php is included
1575 * @param string $fname file name of the thumbnail file, including file size prefix
1576 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1577 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1580 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1581 global $wgUploadDirectory, $wgHashedUploadDirectory,
1582 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1583 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1584 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1585 if (!$hashdir) { return $dir.'/'.$subdir; }
1586 $hash = md5( $fname );
1587 $oldumask = umask(0);
1589 # Suppress warning messages here; if the file itself can't
1590 # be written we'll worry about it then.
1591 wfSuppressWarnings();
1593 $archive = $dir.'/'.$subdir;
1594 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1595 $archive .= '/' . $hash{0};
1596 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1597 $archive .= '/' . substr( $hash, 0, 2 );
1598 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1600 wfRestoreWarnings();
1607 * Return the hash path component of an image path (URL or filesystem),
1608 * e.g. "/3/3c/", or just "/" if hashing is not used.
1610 * @param $dbkey The filesystem / database name of the file
1611 * @param $fromSharedDirectory Use the shared file repository? It may
1612 * use different hash settings from the local one.
1614 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1615 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1616 global $wgHashedUploadDirectory;
1618 if( Image
::isHashed( $fromSharedDirectory ) ) {
1619 $hash = md5($dbkey);
1620 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1627 * Returns the image URL of an image's old version
1629 * @param string $fname file name of the image file
1630 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1633 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1634 global $wgUploadPath, $wgHashedUploadDirectory;
1636 if ($wgHashedUploadDirectory) {
1637 $hash = md5( substr( $name, 15) );
1638 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1639 substr( $hash, 0, 2 ) . '/'.$name;
1641 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1643 return wfUrlencode($url);
1647 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1648 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1650 * @param string $length
1651 * @return int Length in pixels
1653 function wfScaleSVGUnit( $length ) {
1654 static $unitLength = array(
1661 '' => 1.0, // "User units" pixels by default
1662 '%' => 2.0, // Fake it!
1664 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1665 $length = FloatVal( $matches[1] );
1666 $unit = $matches[2];
1667 return round( $length * $unitLength[$unit] );
1670 return round( FloatVal( $length ) );
1675 * Compatible with PHP getimagesize()
1676 * @todo support gzipped SVGZ
1677 * @todo check XML more carefully
1678 * @todo sensible defaults
1680 * @param string $filename
1683 function wfGetSVGsize( $filename ) {
1687 // Read a chunk of the file
1688 $f = fopen( $filename, "rt" );
1689 if( !$f ) return false;
1690 $chunk = fread( $f, 4096 );
1693 // Uber-crappy hack! Run through a real XML parser.
1694 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1698 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1699 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1701 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1702 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1705 return array( $width, $height, 'SVG',
1706 "width=\"$width\" height=\"$height\"" );
1710 * Determine if an image exists on the 'bad image list'
1712 * @param string $name The image to check
1715 function wfIsBadImage( $name ) {
1717 static $titleList = false;
1718 if ( $titleList === false ) {
1719 $titleList = array();
1721 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1722 foreach ( $lines as $line ) {
1723 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1724 $t = Title
::newFromText( $m[1] );
1725 $titleList[$t->getDBkey()] = 1;
1730 return array_key_exists( $name, $titleList );
1736 * Wrapper class for thumbnail images
1737 * @package MediaWiki
1739 class ThumbnailImage
{
1741 * @param string $path Filesystem path to the thumb
1742 * @param string $url URL path to the thumb
1745 function ThumbnailImage( $url, $width, $height, $path = false ) {
1747 $this->width
= $width;
1748 $this->height
= $height;
1749 $this->path
= $path;
1753 * @return string The thumbnail URL
1760 * Return HTML <img ... /> tag for the thumbnail, will include
1761 * width and height attributes and a blank alt text (as required).
1763 * You can set or override additional attributes by passing an
1764 * associative array of name => data pairs. The data will be escaped
1765 * for HTML output, so should be in plaintext.
1767 * @param array $attribs
1771 function toHtml( $attribs = array() ) {
1772 $attribs['src'] = $this->url
;
1773 $attribs['width'] = $this->width
;
1774 $attribs['height'] = $this->height
;
1775 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1778 foreach( $attribs as $name => $data ) {
1779 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';