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 ) {
75 if( !is_object( $title ) ) {
76 wfDebugDieBacktrace( 'Image constructor given bogus title.' );
78 $this->title
=& $title;
79 $this->name
= $title->getDBkey();
80 $this->metadata
= serialize ( array() ) ;
82 $n = strrpos( $this->name
, '.' );
83 $this->extension
= strtolower( $n ?
substr( $this->name
, $n +
1 ) : '' );
84 $this->historyLine
= 0;
86 $this->dataLoaded
= false;
90 * Get the memcached keys
91 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
93 function getCacheKeys( $shared = false ) {
94 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
97 $hashedName = md5($this->name
);
98 $keys = array( "$wgDBname:Image:$hashedName" );
99 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
100 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
106 * Try to load image metadata from memcached. Returns true on success.
108 function loadFromCache() {
109 global $wgUseSharedUploads, $wgMemc;
110 $fname = 'Image::loadFromMemcached';
111 wfProfileIn( $fname );
112 $this->dataLoaded
= false;
113 $keys = $this->getCacheKeys();
114 $cachedValues = $wgMemc->get( $keys[0] );
116 // Check if the key existed and belongs to this version of MediaWiki
117 if (!empty($cachedValues) && is_array($cachedValues)
118 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
119 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
121 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
122 # if this is shared file, we need to check if image
123 # in shared repository has not changed
124 if ( isset( $keys[1] ) ) {
125 $commonsCachedValues = $wgMemc->get( $keys[1] );
126 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
127 && isset($commonsCachedValues['version'])
128 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
129 && isset($commonsCachedValues['mime'])) {
130 wfDebug( "Pulling image metadata from shared repository cache\n" );
131 $this->name
= $commonsCachedValues['name'];
132 $this->imagePath
= $commonsCachedValues['imagePath'];
133 $this->fileExists
= $commonsCachedValues['fileExists'];
134 $this->width
= $commonsCachedValues['width'];
135 $this->height
= $commonsCachedValues['height'];
136 $this->bits
= $commonsCachedValues['bits'];
137 $this->type
= $commonsCachedValues['type'];
138 $this->mime
= $commonsCachedValues['mime'];
139 $this->metadata
= $commonsCachedValues['metadata'];
140 $this->size
= $commonsCachedValues['size'];
141 $this->fromSharedDirectory
= true;
142 $this->dataLoaded
= true;
143 $this->imagePath
= $this->getFullPath(true);
147 wfDebug( "Pulling image metadata from local cache\n" );
148 $this->name
= $cachedValues['name'];
149 $this->imagePath
= $cachedValues['imagePath'];
150 $this->fileExists
= $cachedValues['fileExists'];
151 $this->width
= $cachedValues['width'];
152 $this->height
= $cachedValues['height'];
153 $this->bits
= $cachedValues['bits'];
154 $this->type
= $cachedValues['type'];
155 $this->mime
= $cachedValues['mime'];
156 $this->metadata
= $cachedValues['metadata'];
157 $this->size
= $cachedValues['size'];
158 $this->fromSharedDirectory
= false;
159 $this->dataLoaded
= true;
160 $this->imagePath
= $this->getFullPath();
163 if ( $this->dataLoaded
) {
164 wfIncrStats( 'image_cache_hit' );
166 wfIncrStats( 'image_cache_miss' );
169 wfProfileOut( $fname );
170 return $this->dataLoaded
;
174 * Save the image metadata to memcached
176 function saveToCache() {
179 $keys = $this->getCacheKeys();
180 if ( $this->fileExists
) {
181 // We can't cache negative metadata for non-existent files,
182 // because if the file later appears in commons, the local
183 // keys won't be purged.
184 $cachedValues = array(
185 'version' => MW_IMAGE_VERSION
,
186 'name' => $this->name
,
187 'imagePath' => $this->imagePath
,
188 'fileExists' => $this->fileExists
,
189 'fromShared' => $this->fromSharedDirectory
,
190 'width' => $this->width
,
191 'height' => $this->height
,
192 'bits' => $this->bits
,
193 'type' => $this->type
,
194 'mime' => $this->mime
,
195 'metadata' => $this->metadata
,
196 'size' => $this->size
);
198 $wgMemc->set( $keys[0], $cachedValues );
200 // However we should clear them, so they aren't leftover
201 // if we've deleted the file.
202 $wgMemc->delete( $keys[0] );
207 * Load metadata from the file itself
209 function loadFromFile() {
210 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang,
212 $fname = 'Image::loadFromFile';
213 wfProfileIn( $fname );
214 $this->imagePath
= $this->getFullPath();
215 $this->fileExists
= file_exists( $this->imagePath
);
216 $this->fromSharedDirectory
= false;
219 if (!$this->fileExists
) wfDebug("$fname: ".$this->imagePath
." not found locally!\n");
221 # If the file is not found, and a shared upload directory is used, look for it there.
222 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
223 # In case we're on a wgCapitalLinks=false wiki, we
224 # capitalize the first letter of the filename before
225 # looking it up in the shared repository.
226 $sharedImage = Image
::newFromName( $wgLang->ucfirst($this->name
) );
227 $this->fileExists
= file_exists( $sharedImage->getFullPath(true) );
228 if ( $this->fileExists
) {
229 $this->name
= $sharedImage->name
;
230 $this->imagePath
= $this->getFullPath(true);
231 $this->fromSharedDirectory
= true;
236 if ( $this->fileExists
) {
237 $magic=& wfGetMimeMagic();
239 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
240 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
243 $this->size
= filesize( $this->imagePath
);
245 $magic=& wfGetMimeMagic();
248 if( $this->mime
== 'image/svg' ) {
249 wfSuppressWarnings();
250 $gis = wfGetSVGsize( $this->imagePath
);
253 elseif ( !$magic->isPHPImageType( $this->mime
) ) {
254 # Don't try to get the width and height of sound and video files, that's bad for performance
257 $gis[2]= 0; //unknown
258 $gis[3]= ""; //width height string
261 wfSuppressWarnings();
262 $gis = getimagesize( $this->imagePath
);
266 wfDebug("$fname: ".$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
271 $gis[2]= 0; //unknown
272 $gis[3]= ""; //width height string
275 $this->type
= MEDIATYPE_UNKNOWN
;
276 wfDebug("$fname: ".$this->imagePath
." NOT FOUND!\n");
279 $this->width
= $gis[0];
280 $this->height
= $gis[1];
282 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
284 #NOTE: we have to set this flag early to avoid load() to be called
285 # be some of the functions below. This may lead to recursion or other bad things!
286 # as ther's only one thread of execution, this should be safe anyway.
287 $this->dataLoaded
= true;
290 if ($this->fileExists
&& $wgShowEXIF) $this->metadata
= serialize ( $this->retrieveExifData() ) ;
291 else $this->metadata
= serialize ( array() ) ;
293 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
294 else $this->bits
= 0;
296 wfProfileOut( $fname );
300 * Load image metadata from the DB
302 function loadFromDB() {
303 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgLang;
304 $fname = 'Image::loadFromDB';
305 wfProfileIn( $fname );
307 $dbr =& wfGetDB( DB_SLAVE
);
309 $this->checkDBSchema($dbr);
311 $row = $dbr->selectRow( 'image',
312 array( 'img_size', 'img_width', 'img_height', 'img_bits',
313 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
314 array( 'img_name' => $this->name
), $fname );
316 $this->fromSharedDirectory
= false;
317 $this->fileExists
= true;
318 $this->loadFromRow( $row );
319 $this->imagePath
= $this->getFullPath();
320 // Check for rows from a previous schema, quietly upgrade them
321 if ( is_null($this->type
) ) {
324 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
325 # In case we're on a wgCapitalLinks=false wiki, we
326 # capitalize the first letter of the filename before
327 # looking it up in the shared repository.
328 $name = $wgLang->ucfirst($this->name
);
330 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
332 'img_size', 'img_width', 'img_height', 'img_bits',
333 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
334 array( 'img_name' => $name ), $fname );
336 $this->fromSharedDirectory
= true;
337 $this->fileExists
= true;
338 $this->imagePath
= $this->getFullPath(true);
340 $this->loadFromRow( $row );
342 // Check for rows from a previous schema, quietly upgrade them
343 if ( is_null($this->type
) ) {
355 $this->fileExists
= false;
356 $this->fromSharedDirectory
= false;
357 $this->metadata
= serialize ( array() ) ;
360 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
361 $this->dataLoaded
= true;
362 wfProfileOut( $fname );
366 * Load image metadata from a DB result row
368 function loadFromRow( &$row ) {
369 $this->size
= $row->img_size
;
370 $this->width
= $row->img_width
;
371 $this->height
= $row->img_height
;
372 $this->bits
= $row->img_bits
;
373 $this->type
= $row->img_media_type
;
375 $major= $row->img_major_mime
;
376 $minor= $row->img_minor_mime
;
378 if (!$major) $this->mime
= "unknown/unknown";
380 if (!$minor) $minor= "unknown";
381 $this->mime
= $major.'/'.$minor;
384 $this->metadata
= $row->img_metadata
;
385 if ( $this->metadata
== "" ) $this->metadata
= serialize ( array() ) ;
387 $this->dataLoaded
= true;
391 * Load image metadata from cache or DB, unless already loaded
394 global $wgSharedUploadDBname, $wgUseSharedUploads;
395 if ( !$this->dataLoaded
) {
396 if ( !$this->loadFromCache() ) {
398 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
399 $this->loadFromFile();
400 } elseif ( $this->fileExists
) {
401 $this->saveToCache();
404 $this->dataLoaded
= true;
409 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
410 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
412 function upgradeRow() {
413 global $wgDBname, $wgSharedUploadDBname;
414 $fname = 'Image::upgradeRow';
415 wfProfileIn( $fname );
417 $this->loadFromFile();
418 $dbw =& wfGetDB( DB_MASTER
);
420 if ( $this->fromSharedDirectory
) {
421 if ( !$wgSharedUploadDBname ) {
422 wfProfileOut( $fname );
426 // Write to the other DB using selectDB, not database selectors
427 // This avoids breaking replication in MySQL
428 $dbw->selectDB( $wgSharedUploadDBname );
431 $this->checkDBSchema($dbw);
433 if (strpos($this->mime
,'/')!==false) {
434 list($major,$minor)= explode('/',$this->mime
,2);
441 wfDebug("$fname: upgrading ".$this->name
." to 1.5 schema\n");
443 $dbw->update( 'image',
445 'img_width' => $this->width
,
446 'img_height' => $this->height
,
447 'img_bits' => $this->bits
,
448 'img_media_type' => $this->type
,
449 'img_major_mime' => $major,
450 'img_minor_mime' => $minor,
451 'img_metadata' => $this->metadata
,
452 ), array( 'img_name' => $this->name
), $fname
454 if ( $this->fromSharedDirectory
) {
455 $dbw->selectDB( $wgDBname );
457 wfProfileOut( $fname );
461 * Return the name of this image
469 * Return the associated title object
472 function getTitle() {
477 * Return the URL of the image file
483 if($this->fileExists
) {
484 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
492 function getViewURL() {
493 if( $this->mustRender()) {
494 if( $this->canRender() ) {
495 return $this->createThumb( $this->getWidth() );
498 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
499 return $this->getURL(); #hm... return NULL?
502 return $this->getURL();
507 * Return the image path of the image in the
508 * local file system as an absolute path
511 function getImagePath() {
513 return $this->imagePath
;
517 * Return the width of the image
519 * Returns -1 if the file specified is not a known image type
522 function getWidth() {
528 * Return the height of the image
530 * Returns -1 if the file specified is not a known image type
533 function getHeight() {
535 return $this->height
;
539 * Return the size of the image file, in bytes
548 * Returns the mime type of the file.
550 function getMimeType() {
556 * Return the type of the media in the file.
557 * Use the value returned by this function with the MEDIATYPE_xxx constants.
559 function getMediaType() {
565 * Checks if the file can be presented to the browser as a bitmap.
567 * Currently, this checks if the file is an image format
568 * that can be converted to a format
569 * supported by all browsers (namely GIF, PNG and JPEG),
570 * or if it is an SVG image and SVG conversion is enabled.
572 * @todo remember the result of this check.
574 function canRender() {
575 global $wgUseImageMagick;
577 if( $this->getWidth()<=0 ||
$this->getHeight()<=0 ) return false;
579 $mime= $this->getMimeType();
581 if (!$mime ||
$mime==='unknown' ||
$mime==='unknown/unknown') return false;
583 #if it's SVG, check if ther's a converter enabled
584 if ($mime === 'image/svg') {
585 global $wgSVGConverters, $wgSVGConverter;
587 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
592 #image formats available on ALL browsers
593 if ( $mime === 'image/gif'
594 ||
$mime === 'image/png'
595 ||
$mime === 'image/jpeg' ) return true;
597 #image formats that can be converted to the above formats
598 if ($wgUseImageMagick) {
599 #convertable by ImageMagick (there are more...)
600 if ( $mime === 'image/vnd.wap.wbmp'
601 ||
$mime === 'image/x-xbitmap'
602 ||
$mime === 'image/x-xpixmap'
603 #|| $mime === 'image/x-icon' #file may be split into multiple parts
604 ||
$mime === 'image/x-portable-anymap'
605 ||
$mime === 'image/x-portable-bitmap'
606 ||
$mime === 'image/x-portable-graymap'
607 ||
$mime === 'image/x-portable-pixmap'
608 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
609 ||
$mime === 'image/x-rgb'
610 ||
$mime === 'image/x-bmp'
611 ||
$mime === 'image/tiff' ) return true;
614 #convertable by the PHP GD image lib
615 if ( $mime === 'image/vnd.wap.wbmp'
616 ||
$mime === 'image/x-xbitmap' ) return true;
624 * Return true if the file is of a type that can't be directly
625 * rendered by typical browsers and needs to be re-rasterized.
627 * This returns true for everything but the bitmap types
628 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
629 * also return true for any non-image formats.
633 function mustRender() {
634 $mime= $this->getMimeType();
636 if ( $mime === "image/gif"
637 ||
$mime === "image/png"
638 ||
$mime === "image/jpeg" ) return false;
644 * Determines if this media file may be shown inline on a page.
646 * This is currently synonymous to canRender(), but this could be
647 * extended to also allow inline display of other media,
648 * like flash animations or videos. If you do so, please keep in mind that
649 * that could be a security risk.
651 function allowInlineDisplay() {
652 return $this->canRender();
656 * Determines if this media file is in a format that is unlikely to
657 * contain viruses or malicious content. It uses the global
658 * $wgTrustedMediaFormats list to determine if the file is safe.
660 * This is used to show a warning on the description page of non-safe files.
661 * It may also be used to disallow direct [[media:...]] links to such files.
663 * Note that this function will always return ture if allowInlineDisplay()
664 * or isTrustedFile() is true for this file.
666 function isSafeFile() {
667 if ($this->allowInlineDisplay()) return true;
668 if ($this->isTrustedFile()) return true;
670 global $wgTrustedMediaFormats;
672 $type= $this->getMediaType();
673 $mime= $this->getMimeType();
674 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
676 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
677 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
679 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
680 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
685 /** Returns true if the file is flagegd as trusted. Files flagged that way
686 * can be linked to directly, even if that is not allowed for this type of
689 * This is a dummy function right now and always returns false. It could be
690 * implemented to extract a flag from the database. The trusted flag could be
691 * set on upload, if the user has sufficient privileges, to bypass script-
692 * and html-filters. It may even be coupeled with cryptographics signatures
695 function isTrustedFile() {
696 #this could be implemented to check a flag in the databas,
697 #look for signatures, etc
702 * Return the escapeLocalURL of this image
705 function getEscapeLocalURL() {
707 return $this->title
->escapeLocalURL();
711 * Return the escapeFullURL of this image
714 function getEscapeFullURL() {
716 return $this->title
->escapeFullURL();
720 * Return the URL of an image, provided its name.
722 * @param string $name Name of the image, without the leading "Image:"
723 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
724 * @return string URL of $name image
728 function imageUrl( $name, $fromSharedDirectory = false ) {
729 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
730 if($fromSharedDirectory) {
732 $path = $wgSharedUploadPath;
734 $base = $wgUploadBaseUrl;
735 $path = $wgUploadPath;
737 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
738 return wfUrlencode( $url );
742 * Returns true if the image file exists on disk.
743 * @return boolean Whether image file exist on disk.
748 return $this->fileExists
;
755 function thumbUrl( $width, $subdir='thumb') {
756 global $wgUploadPath, $wgUploadBaseUrl,
757 $wgSharedUploadPath,$wgSharedUploadDirectory,
758 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
760 // Generate thumb.php URL if possible
764 if ( $this->fromSharedDirectory
) {
765 if ( $wgSharedThumbnailScriptPath ) {
766 $script = $wgSharedThumbnailScriptPath;
769 if ( $wgThumbnailScriptPath ) {
770 $script = $wgThumbnailScriptPath;
774 $url = $script . '?f=' . urlencode( $this->name
) . '&w=' . urlencode( $width );
775 if( $this->mustRender() ) {
779 $name = $this->thumbName( $width );
780 if($this->fromSharedDirectory
) {
782 $path = $wgSharedUploadPath;
784 $base = $wgUploadBaseUrl;
785 $path = $wgUploadPath;
787 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
788 $url = "{$base}{$path}/{$subdir}" .
789 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
790 . $this->name
.'/'.$name;
791 $url = wfUrlencode( $url );
793 $url = "{$base}{$path}/{$subdir}/{$name}";
796 return array( $script !== false, $url );
800 * Return the file name of a thumbnail of the specified width
802 * @param integer $width Width of the thumbnail image
803 * @param boolean $shared Does the thumbnail come from the shared repository?
806 function thumbName( $width ) {
807 $thumb = $width."px-".$this->name
;
809 if( $this->mustRender() ) {
810 if( $this->canRender() ) {
811 # Rasterize to PNG (for SVG vector images, etc)
815 #should we use iconThumb here to get a symbolic thumbnail?
816 #or should we fail with an internal error?
817 return NULL; //can't make bitmap
824 * Create a thumbnail of the image having the specified width/height.
825 * The thumbnail will not be created if the width is larger than the
826 * image's width. Let the browser do the scaling in this case.
827 * The thumbnail is stored on disk and is only computed if the thumbnail
828 * file does not exist OR if it is older than the image.
831 * Keeps aspect ratio of original image. If both width and height are
832 * specified, the generated image will be no bigger than width x height,
833 * and will also have correct aspect ratio.
835 * @param integer $width maximum width of the generated thumbnail
836 * @param integer $height maximum height of the image (optional)
839 function createThumb( $width, $height=-1 ) {
840 $thumb = $this->getThumbnail( $width, $height );
841 if( is_null( $thumb ) ) return '';
842 return $thumb->getUrl();
846 * As createThumb, but returns a ThumbnailImage object. This can
847 * provide access to the actual file, the real size of the thumb,
848 * and can produce a convenient <img> tag for you.
850 * @param integer $width maximum width of the generated thumbnail
851 * @param integer $height maximum height of the image (optional)
852 * @return ThumbnailImage
855 function getThumbnail( $width, $height=-1 ) {
856 if ( $height == -1 ) {
857 return $this->renderThumb( $width );
861 if ($this->canRender()) {
862 if ( $width < $this->width
) {
863 $thumbheight = $this->height
* $width / $this->width
;
864 $thumbwidth = $width;
866 $thumbheight = $this->height
;
867 $thumbwidth = $this->width
;
869 if ( $thumbheight > $height ) {
870 $thumbwidth = $thumbwidth * $height / $thumbheight;
871 $thumbheight = $height;
874 $thumb = $this->renderThumb( $thumbwidth );
876 else $thumb= NULL; #not a bitmap or renderable image, don't try.
878 if( is_null( $thumb ) ) {
879 $thumb = $this->iconThumb();
885 * @return ThumbnailImage
887 function iconThumb() {
888 global $wgStylePath, $wgStyleDirectory;
890 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
891 foreach( $try as $icon ) {
892 $path = '/common/images/icons/' . $icon;
893 $filepath = $wgStyleDirectory . $path;
894 if( file_exists( $filepath ) ) {
895 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
902 * Create a thumbnail of the image having the specified width.
903 * The thumbnail will not be created if the width is larger than the
904 * image's width. Let the browser do the scaling in this case.
905 * The thumbnail is stored on disk and is only computed if the thumbnail
906 * file does not exist OR if it is older than the image.
907 * Returns an object which can return the pathname, URL, and physical
908 * pixel size of the thumbnail -- or null on failure.
910 * @return ThumbnailImage
913 function renderThumb( $width, $useScript = true ) {
914 global $wgUseSquid, $wgInternalServer;
915 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
917 $fname = 'Image::renderThumb';
918 wfProfileIn( $fname );
920 $width = intval( $width );
923 if ( ! $this->exists() )
925 # If there is no image, there will be no thumbnail
926 wfProfileOut( $fname );
930 # Sanity check $width
931 if( $width <= 0 ||
$this->width
<= 0) {
933 wfProfileOut( $fname );
937 if( $width >= $this->width
&& !$this->mustRender() ) {
938 # Don't make an image bigger than the source
939 $thumb = new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
940 wfProfileOut( $fname );
944 $height = floor( $this->height
* ( $width/$this->width
) );
946 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
947 if ( $isScriptUrl && $useScript ) {
948 // Use thumb.php to render the image
949 $thumb = new ThumbnailImage( $url, $width, $height );
950 wfProfileOut( $fname );
954 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
955 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
).'/'.$thumbName;
957 if ( !file_exists( $thumbPath ) ) {
958 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).
961 if ( file_exists( $oldThumbPath ) ) {
962 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath
) ) {
963 rename( $oldThumbPath, $thumbPath );
966 unlink( $oldThumbPath );
970 $this->reallyRenderThumb( $thumbPath, $width, $height );
973 # This has to be done after the image is updated and present for all machines on NFS,
974 # or else the old version might be stored into the squid again
976 if ( substr( $url, 0, 4 ) == 'http' ) {
977 $urlArr = array( $url );
979 $urlArr = array( $wgInternalServer.$url );
981 wfPurgeSquidServers($urlArr);
986 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
987 wfProfileOut( $fname );
989 } // END OF function renderThumb
992 * Really render a thumbnail
993 * Call this only for images for which canRender() returns true.
997 function reallyRenderThumb( $thumbPath, $width, $height ) {
998 global $wgSVGConverters, $wgSVGConverter,
999 $wgUseImageMagick, $wgImageMagickConvertCommand;
1003 if( $this->mime
=== "image/svg" ) {
1004 #Right now we have only SVG
1006 global $wgSVGConverters, $wgSVGConverter;
1007 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1008 global $wgSVGConverterPath;
1010 array( '$path/', '$width', '$input', '$output' ),
1011 array( $wgSVGConverterPath,
1013 wfEscapeShellArg( $this->imagePath
),
1014 wfEscapeShellArg( $thumbPath ) ),
1015 $wgSVGConverters[$wgSVGConverter] );
1016 $conv = shell_exec( $cmd );
1020 } elseif ( $wgUseImageMagick ) {
1022 # Specify white background color, will be used for transparent images
1023 # in Internet Explorer/Windows instead of default black.
1024 $cmd = $wgImageMagickConvertCommand .
1025 " -quality 85 -background white -geometry {$width} ".
1026 wfEscapeShellArg($this->imagePath
) . " " .
1027 wfEscapeShellArg($thumbPath);
1028 wfDebug("reallyRenderThumb: running ImageMagick: $cmd");
1029 $conv = shell_exec( $cmd );
1031 # Use PHP's builtin GD library functions.
1033 # First find out what kind of file this is, and select the correct
1034 # input routine for this.
1037 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1038 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1039 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1040 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1041 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1043 if( !isset( $typemap[$this->mime
] ) ) {
1044 $err = 'Image type not supported';
1045 wfDebug( "$err\n" );
1048 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime
];
1050 if( !function_exists( $loader ) ) {
1051 $err = "Incomplete GD library configuration: missing function $loader";
1052 wfDebug( "$err\n" );
1055 if( $colorStyle == 'palette' ) {
1057 } elseif( $colorStyle == 'truecolor' ) {
1059 } elseif( $colorStyle == 'bits' ) {
1060 $truecolor = ( $this->bits
> 8 );
1063 $src_image = call_user_func( $loader, $this->imagePath
);
1065 $dst_image = imagecreatetruecolor( $width, $height );
1067 $dst_image = imagecreate( $width, $height );
1069 imagecopyresampled( $dst_image, $src_image,
1071 $width, $height, $this->width
, $this->height
);
1072 call_user_func( $saveType, $dst_image, $thumbPath );
1073 imagedestroy( $dst_image );
1074 imagedestroy( $src_image );
1078 # Check for zero-sized thumbnails. Those can be generated when
1079 # no disk space is available or some other error occurs
1081 if( file_exists( $thumbPath ) ) {
1082 $thumbstat = stat( $thumbPath );
1083 if( $thumbstat['size'] == 0 ) {
1084 unlink( $thumbPath );
1089 function imageJpegWrapper( $dst_image, $thumbPath ) {
1090 imageinterlace( $dst_image );
1091 imagejpeg( $dst_image, $thumbPath, 95 );
1095 * Get all thumbnail names previously generated for this image
1097 function getThumbnails( $shared = false ) {
1098 if ( Image
::isHashed( $shared ) ) {
1101 $dir = wfImageThumbDir( $this->name
, $shared );
1103 // This generates an error on failure, hence the @
1104 $handle = @opendir
( $dir );
1107 while ( false !== ( $file = readdir($handle) ) ) {
1108 if ( $file{0} != '.' ) {
1112 closedir( $handle );
1122 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1124 function purgeCache( $archiveFiles = array(), $shared = false ) {
1125 global $wgInternalServer, $wgUseSquid;
1127 // Refresh metadata cache
1129 $this->loadFromFile();
1130 $this->saveToCache();
1132 // Delete thumbnails
1133 $files = $this->getThumbnails( $shared );
1134 $dir = wfImageThumbDir( $this->name
, $shared );
1136 foreach ( $files as $file ) {
1137 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1138 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory
);
1139 @unlink
( "$dir/$file" );
1144 if ( $wgUseSquid ) {
1145 $urls[] = $wgInternalServer . $this->getViewURL();
1146 foreach ( $archiveFiles as $file ) {
1147 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1149 wfPurgeSquidServers( $urls );
1153 function checkDBSchema(&$db) {
1154 # img_name must be unique
1155 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1156 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1159 #new fields must exist
1160 if ( !$db->fieldExists( 'image', 'img_media_type' )
1161 ||
!$db->fieldExists( 'image', 'img_metadata' )
1162 ||
!$db->fieldExists( 'image', 'img_width' ) ) {
1164 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1169 * Return the image history of this image, line by line.
1170 * starts with current version, then old versions.
1171 * uses $this->historyLine to check which line to return:
1172 * 0 return line for current version
1173 * 1 query for old versions, return first one
1174 * 2, ... return next old version from above query
1178 function nextHistoryLine() {
1179 $fname = 'Image::nextHistoryLine()';
1180 $dbr =& wfGetDB( DB_SLAVE
);
1182 $this->checkDBSchema($dbr);
1184 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1185 $this->historyRes
= $dbr->select( 'image',
1186 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
1187 array( 'img_name' => $this->title
->getDBkey() ),
1190 if ( 0 == wfNumRows( $this->historyRes
) ) {
1193 } else if ( $this->historyLine
== 1 ) {
1194 $this->historyRes
= $dbr->select( 'oldimage',
1195 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
1196 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
1197 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
1200 $this->historyLine ++
;
1202 return $dbr->fetchObject( $this->historyRes
);
1206 * Reset the history pointer to the first element of the history
1209 function resetHistory() {
1210 $this->historyLine
= 0;
1214 * Return the full filesystem path to the file. Note that this does
1215 * not mean that a file actually exists under that location.
1217 * This path depends on whether directory hashing is active or not,
1218 * i.e. whether the images are all found in the same directory,
1219 * or in hashed paths like /images/3/3c.
1222 * @param boolean $fromSharedDirectory Return the path to the file
1223 * in a shared repository (see $wgUseSharedRepository and related
1224 * options in DefaultSettings.php) instead of a local one.
1227 function getFullPath( $fromSharedRepository = false ) {
1228 global $wgUploadDirectory, $wgSharedUploadDirectory;
1229 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1231 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1234 // $wgSharedUploadDirectory may be false, if thumb.php is used
1236 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1248 function isHashed( $shared ) {
1249 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1250 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1254 * Record an image upload in the upload log and the image table
1256 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '' ) {
1257 global $wgUser, $wgLang, $wgTitle, $wgDeferredUpdateList;
1258 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1260 $fname = 'Image::recordUpload';
1261 $dbw =& wfGetDB( DB_MASTER
);
1263 $this->checkDBSchema($dbw);
1265 // Delete thumbnails and refresh the metadata cache
1266 $this->purgeCache();
1268 // Fail now if the image isn't there
1269 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1270 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1274 if ( $wgUseCopyrightUpload ) {
1275 if ( $license != '' ) {
1276 $licensetxt = '== ' . wfMsg( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1278 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1279 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1281 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1283 if ( $license != '' ) {
1284 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1285 $textdesc = $filedesc .
1286 '== ' . wfMsg ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1292 $now = $dbw->timestamp();
1295 if (strpos($this->mime
,'/')!==false) {
1296 list($major,$minor)= explode('/',$this->mime
,2);
1299 $major= $this->mime
;
1303 # Test to see if the row exists using INSERT IGNORE
1304 # This avoids race conditions by locking the row until the commit, and also
1305 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1306 $dbw->insert( 'image',
1308 'img_name' => $this->name
,
1309 'img_size'=> $this->size
,
1310 'img_width' => intval( $this->width
),
1311 'img_height' => intval( $this->height
),
1312 'img_bits' => $this->bits
,
1313 'img_media_type' => $this->type
,
1314 'img_major_mime' => $major,
1315 'img_minor_mime' => $minor,
1316 'img_timestamp' => $now,
1317 'img_description' => $desc,
1318 'img_user' => $wgUser->getID(),
1319 'img_user_text' => $wgUser->getName(),
1320 'img_metadata' => $this->metadata
,
1323 $descTitle = $this->getTitle();
1324 $purgeURLs = array();
1326 if ( $dbw->affectedRows() ) {
1327 # Successfully inserted, this is a new image
1328 $id = $descTitle->getArticleID();
1331 $article = new Article( $descTitle );
1332 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1335 # Collision, this is an update of an image
1336 # Insert previous contents into oldimage
1337 $dbw->insertSelect( 'oldimage', 'image',
1339 'oi_name' => 'img_name',
1340 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1341 'oi_size' => 'img_size',
1342 'oi_width' => 'img_width',
1343 'oi_height' => 'img_height',
1344 'oi_bits' => 'img_bits',
1345 'oi_timestamp' => 'img_timestamp',
1346 'oi_description' => 'img_description',
1347 'oi_user' => 'img_user',
1348 'oi_user_text' => 'img_user_text',
1349 ), array( 'img_name' => $this->name
), $fname
1352 # Update the current image row
1353 $dbw->update( 'image',
1355 'img_size' => $this->size
,
1356 'img_width' => intval( $this->width
),
1357 'img_height' => intval( $this->height
),
1358 'img_bits' => $this->bits
,
1359 'img_media_type' => $this->type
,
1360 'img_major_mime' => $major,
1361 'img_minor_mime' => $minor,
1362 'img_timestamp' => $now,
1363 'img_description' => $desc,
1364 'img_user' => $wgUser->getID(),
1365 'img_user_text' => $wgUser->getName(),
1366 'img_metadata' => $this->metadata
,
1367 ), array( /* WHERE */
1368 'img_name' => $this->name
1372 # Invalidate the cache for the description page
1373 $descTitle->invalidateCache();
1374 $purgeURLs[] = $descTitle->getInternalURL();
1377 # Invalidate cache for all pages using this image
1378 $linksTo = $this->getLinksTo();
1380 if ( $wgUseSquid ) {
1381 $u = SquidUpdate
::newFromTitles( $linksTo, $purgeURLs );
1382 array_push( $wgPostCommitUpdateList, $u );
1384 Title
::touchArray( $linksTo );
1386 $log = new LogPage( 'upload' );
1387 $log->addEntry( 'upload', $descTitle, $desc );
1393 * Get an array of Title objects which are articles which use this image
1394 * Also adds their IDs to the link cache
1396 * This is mostly copied from Title::getLinksTo()
1398 function getLinksTo( $options = '' ) {
1399 global $wgLinkCache;
1400 $fname = 'Image::getLinksTo';
1401 wfProfileIn( $fname );
1404 $db =& wfGetDB( DB_MASTER
);
1406 $db =& wfGetDB( DB_SLAVE
);
1409 extract( $db->tableNames( 'page', 'imagelinks' ) );
1410 $encName = $db->addQuotes( $this->name
);
1411 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1412 $res = $db->query( $sql, $fname );
1415 if ( $db->numRows( $res ) ) {
1416 while ( $row = $db->fetchObject( $res ) ) {
1417 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1418 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1419 $retVal[] = $titleObj;
1423 $db->freeResult( $res );
1427 * Retrive Exif data from the database
1429 * Retrive Exif data from the database and prune unrecognized tags
1430 * and/or tags with invalid contents
1434 function retrieveExifData () {
1435 if ( $this->getMimeType() !== "image/jpeg" ) return array ();
1437 $exif = new Exif( $this->imagePath
);
1438 return $exif->getFilteredData();
1441 function getExifData () {
1443 if ( $this->metadata
=== '0' )
1446 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1447 $ret = unserialize ( $this->metadata
);
1449 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ?
$ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1450 $newver = Exif
::version();
1452 if ( !count( $ret ) ||
$purge ||
$oldver != $newver ) {
1453 $this->updateExifData( $newver );
1455 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1456 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1457 $format = new FormatExif( $ret );
1458 return $format->getFormattedData();
1461 function updateExifData( $version ) {
1462 $fname = 'Image:updateExifData';
1464 if ( $this->getImagePath() === false ) # Not a local image
1467 # Get EXIF data from image
1468 $exif = $this->retrieveExifData();
1469 if ( count( $exif ) ) {
1470 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1471 $this->metadata
= serialize( $exif );
1473 $this->metadata
= '0';
1476 # Update EXIF data in database
1477 $dbw =& wfGetDB( DB_MASTER
);
1479 $this->checkDBSchema($dbw);
1481 $dbw->update( 'image',
1482 array( 'img_metadata' => $this->metadata
),
1483 array( 'img_name' => $this->name
),
1489 * Returns true if the image does not come from the shared
1494 function isLocal() {
1495 return !$this->fromSharedDirectory
;
1502 * Returns the image directory of an image
1503 * If the directory does not exist, it is created.
1504 * The result is an absolute path.
1506 * This function is called from thumb.php before Setup.php is included
1508 * @param string $fname file name of the image file
1511 function wfImageDir( $fname ) {
1512 global $wgUploadDirectory, $wgHashedUploadDirectory;
1514 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1516 $hash = md5( $fname );
1517 $oldumask = umask(0);
1518 $dest = $wgUploadDirectory . '/' . $hash{0};
1519 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1520 $dest .= '/' . substr( $hash, 0, 2 );
1521 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1528 * Returns the image directory of an image's thubnail
1529 * If the directory does not exist, it is created.
1530 * The result is an absolute path.
1532 * This function is called from thumb.php before Setup.php is included
1534 * @param string $fname file name of the original image file
1535 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1536 * @param boolean $shared (optional) use the shared upload directory
1539 function wfImageThumbDir( $fname, $shared = false ) {
1540 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1541 if ( Image
::isHashed( $shared ) ) {
1542 $dir = "$base/$fname";
1544 if ( !is_dir( $base ) ) {
1545 $oldumask = umask(0);
1546 @mkdir
( $base, 0777 );
1550 if ( ! is_dir( $dir ) ) {
1551 $oldumask = umask(0);
1552 @mkdir
( $dir, 0777 );
1563 * Old thumbnail directory, kept for conversion
1565 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1566 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1570 * Returns the image directory of an image's old version
1571 * If the directory does not exist, it is created.
1572 * The result is an absolute path.
1574 * This function is called from thumb.php before Setup.php is included
1576 * @param string $fname file name of the thumbnail file, including file size prefix
1577 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1578 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1581 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1582 global $wgUploadDirectory, $wgHashedUploadDirectory,
1583 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1584 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
1585 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1586 if (!$hashdir) { return $dir.'/'.$subdir; }
1587 $hash = md5( $fname );
1588 $oldumask = umask(0);
1590 # Suppress warning messages here; if the file itself can't
1591 # be written we'll worry about it then.
1592 wfSuppressWarnings();
1594 $archive = $dir.'/'.$subdir;
1595 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1596 $archive .= '/' . $hash{0};
1597 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1598 $archive .= '/' . substr( $hash, 0, 2 );
1599 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1601 wfRestoreWarnings();
1608 * Return the hash path component of an image path (URL or filesystem),
1609 * e.g. "/3/3c/", or just "/" if hashing is not used.
1611 * @param $dbkey The filesystem / database name of the file
1612 * @param $fromSharedDirectory Use the shared file repository? It may
1613 * use different hash settings from the local one.
1615 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1616 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1617 global $wgHashedUploadDirectory;
1619 if( Image
::isHashed( $fromSharedDirectory ) ) {
1620 $hash = md5($dbkey);
1621 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1628 * Returns the image URL of an image's old version
1630 * @param string $fname file name of the image file
1631 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1634 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1635 global $wgUploadPath, $wgHashedUploadDirectory;
1637 if ($wgHashedUploadDirectory) {
1638 $hash = md5( substr( $name, 15) );
1639 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1640 substr( $hash, 0, 2 ) . '/'.$name;
1642 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1644 return wfUrlencode($url);
1648 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1649 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1651 * @param string $length
1652 * @return int Length in pixels
1654 function wfScaleSVGUnit( $length ) {
1655 static $unitLength = array(
1662 '' => 1.0, // "User units" pixels by default
1663 '%' => 2.0, // Fake it!
1665 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1666 $length = floatval( $matches[1] );
1667 $unit = $matches[2];
1668 return round( $length * $unitLength[$unit] );
1671 return round( floatval( $length ) );
1676 * Compatible with PHP getimagesize()
1677 * @todo support gzipped SVGZ
1678 * @todo check XML more carefully
1679 * @todo sensible defaults
1681 * @param string $filename
1684 function wfGetSVGsize( $filename ) {
1688 // Read a chunk of the file
1689 $f = fopen( $filename, "rt" );
1690 if( !$f ) return false;
1691 $chunk = fread( $f, 4096 );
1694 // Uber-crappy hack! Run through a real XML parser.
1695 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1699 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1700 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1702 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1703 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1706 return array( $width, $height, 'SVG',
1707 "width=\"$width\" height=\"$height\"" );
1711 * Determine if an image exists on the 'bad image list'
1713 * @param string $name The image to check
1716 function wfIsBadImage( $name ) {
1718 static $titleList = false;
1719 if ( $titleList === false ) {
1720 $titleList = array();
1722 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1723 foreach ( $lines as $line ) {
1724 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE
) . ':.*?)\]{2}/', $line, $m ) ) {
1725 $t = Title
::newFromText( $m[1] );
1726 $titleList[$t->getDBkey()] = 1;
1731 return array_key_exists( $name, $titleList );
1737 * Wrapper class for thumbnail images
1738 * @package MediaWiki
1740 class ThumbnailImage
{
1742 * @param string $path Filesystem path to the thumb
1743 * @param string $url URL path to the thumb
1746 function ThumbnailImage( $url, $width, $height, $path = false ) {
1748 $this->width
= $width;
1749 $this->height
= $height;
1750 $this->path
= $path;
1754 * @return string The thumbnail URL
1761 * Return HTML <img ... /> tag for the thumbnail, will include
1762 * width and height attributes and a blank alt text (as required).
1764 * You can set or override additional attributes by passing an
1765 * associative array of name => data pairs. The data will be escaped
1766 * for HTML output, so should be in plaintext.
1768 * @param array $attribs
1772 function toHtml( $attribs = array() ) {
1773 $attribs['src'] = $this->url
;
1774 $attribs['width'] = $this->width
;
1775 $attribs['height'] = $this->height
;
1776 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1779 foreach( $attribs as $name => $data ) {
1780 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';