RC patrol fixlet: include rcid in 'diff' link in enhanced mode, for individually...
[mediawiki.git] / includes / Image.php
blob8aafff6af476d6db881cce94eb57dc1c1772bcf1
1 <?php
2 /**
3 * @package MediaWiki
4 * $Id$
5 */
7 /**
8 * Class to represent an image
9 *
10 * Provides methods to retrieve paths (physical, logical, URL),
11 * to generate thumbnails or for uploading.
12 * @package MediaWiki
14 class Image
16 /**#@+
17 * @access private
19 var $name, # name of the image
20 $imagePath, # Path of the image
21 $url, # Image URL
22 $title, # Title object for this image. Initialized when needed.
23 $fileExists, # does the image file exist on disk?
24 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory
25 $historyLine, # Number of line to return by nextHistoryLine()
26 $historyRes, # result of the query for the image's history
27 $width, # \
28 $height, # |
29 $bits, # --- returned by getimagesize, see http://de3.php.net/manual/en/function.getimagesize.php
30 $type, # |
31 $attr; # /
33 /**#@-*/
36 /**
37 * Create an Image object from an image name
39 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
40 * @access public
42 function Image( $name )
44 global $wgUploadDirectory,$wgHashedUploadDirectory,
45 $wgUseSharedUploads, $wgSharedUploadDirectory,
46 $wgHashedSharedUploadDirectory,$wgUseLatin1,
47 $wgSharedLatin1,$wgLang;
49 $this->name = $name;
50 $this->title = Title::makeTitleSafe( NS_IMAGE, $this->name );
51 $this->fromSharedDirectory = false;
52 if ($wgHashedUploadDirectory) {
53 $hash = md5( $this->title->getDBkey() );
54 $this->imagePath = $wgUploadDirectory . '/' . $hash{0} . '/' .
55 substr( $hash, 0, 2 ) . "/{$name}";
56 } else {
57 $this->imagePath = $wgUploadDirectory . '/' . $name;
59 $this->fileExists = file_exists( $this->imagePath);
61 # If the file is not found, and a shared upload directory
62 # like the Wikimedia Commons is used, look for it there.
63 if (!$this->fileExists && $wgUseSharedUploads) {
64 # in case we're running a capitallinks=false wiki
65 $sharedname=$wgLang->ucfirst($name);
66 $sharedtitle=$wgLang->ucfirst($this->title->getDBkey());
67 if($wgUseLatin1 && !$wgSharedLatin1) {
68 $sharedname=utf8_encode($sharedname);
69 $sharedtitle=utf8_encode($sharedtitle);
72 if($wgHashedSharedUploadDirectory) {
73 $hash = md5( $sharedtitle );
74 $this->imagePath = $wgSharedUploadDirectory . '/' . $hash{0} . '/' .
75 substr( $hash, 0, 2 ) . "/".$sharedname;
76 } else {
77 $this->imagePath = $wgSharedUploadDirectory . '/' . $sharedname;
79 $this->fileExists = file_exists( $this->imagePath);
80 $this->fromSharedDirectory = true;
81 $name=$sharedname;
83 if($this->fileExists) {
84 $this->url = $this->wfImageUrl( $name, $this->fromSharedDirectory );
85 } else {
86 $this->url='';
89 $n = strrpos( $name, '.' );
90 $this->extension = strtolower( $n ? substr( $name, $n + 1 ) : '' );
93 if ( $this->fileExists )
95 if( $this->extension == 'svg' ) {
96 @$gis = getSVGsize( $this->imagePath );
97 } else {
98 @$gis = getimagesize( $this->imagePath );
100 if( $gis !== false ) {
101 $this->width = $gis[0];
102 $this->height = $gis[1];
103 $this->type = $gis[2];
104 $this->attr = $gis[3];
105 if ( isset( $gis['bits'] ) ) {
106 $this->bits = $gis['bits'];
107 } else {
108 $this->bits = 0;
112 $this->historyLine = 0;
116 * Factory function
118 * Create a new image object from a title object.
120 * @param Title $nt Title object. Must be from namespace "image"
121 * @access public
123 function newFromTitle( $nt )
125 $img = new Image( $nt->getDBKey() );
126 $img->title = $nt;
127 return $img;
131 * Return the name of this image
132 * @access public
134 function getName()
136 return $this->name;
140 * Return the associated title object
141 * @access public
143 function getTitle()
145 return $this->title;
149 * Return the URL of the image file
150 * @access public
152 function getURL()
154 return $this->url;
157 function getViewURL() {
158 if( $this->mustRender() ) {
159 return $this->createThumb( $this->getWidth() );
160 } else {
161 return $this->getURL();
166 * Return the image path of the image in the
167 * local file system as an absolute path
168 * @access public
170 function getImagePath()
172 return $this->imagePath;
176 * Return the width of the image
178 * Returns -1 if the file specified is not a known image type
179 * @access public
181 function getWidth()
183 return $this->width;
187 * Return the height of the image
189 * Returns -1 if the file specified is not a known image type
190 * @access public
192 function getHeight()
194 return $this->height;
198 * Return the size of the image file, in bytes
199 * @access public
201 function getSize()
203 $st = stat( $this->getImagePath() );
204 return $st['size'];
208 * Return the type of the image
210 * - 1 GIF
211 * - 2 JPG
212 * - 3 PNG
213 * - 15 WBMP
214 * - 16 XBM
216 function getType()
218 return $this->type;
222 * Return the escapeLocalURL of this image
223 * @access public
225 function getEscapeLocalURL()
227 return $this->title->escapeLocalURL();
231 * Return the escapeFullURL of this image
232 * @access public
234 function getEscapeFullURL()
236 return $this->title->escapeFullURL();
240 * Return the URL of an image, provided its name.
242 * @param string $name Name of the image, without the leading "Image:"
243 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
244 * @access public
246 function wfImageUrl( $name, $fromSharedDirectory = false )
248 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory,
249 $wgHashedSharedUploadDirectory,$wgSharedUploadPath;
250 if($fromSharedDirectory) {
251 $hash = $wgHashedSharedUploadDirectory;
252 $base = '';
253 $path = $wgSharedUploadPath;
254 } else {
255 $hash = $wgHashedUploadDirectory;
256 $base = $wgUploadBaseUrl;
257 $path = $wgUploadPath;
259 if ( $hash ) {
260 $hash = md5( $name );
261 $url = "{$base}{$path}/" . $hash{0} . "/" .
262 substr( $hash, 0, 2 ) . "/{$name}";
263 } else {
264 $url = "{$base}{$path}/{$name}";
266 return wfUrlencode( $url );
270 * Returns true iff the image file exists on disk.
272 * @access public
274 function exists()
276 return $this->fileExists;
281 * @access private
283 function thumbUrl( $width, $subdir='thumb') {
284 global $wgUploadPath,$wgHashedUploadDirectory, $wgUploadBaseUrl,
285 $wgSharedUploadPath,$wgSharedUploadDirectory,
286 $wgHashedSharedUploadDirectory,$wgUseLatin1,$wgSharedLatin1;
287 $name = $this->thumbName( $width );
288 if($this->fromSharedDirectory) {
289 $hashdir = $wgHashedSharedUploadDirectory;
290 $base = '';
291 $path = $wgSharedUploadPath;
292 if($wgUseLatin1 && !$wgSharedLatin1) {
293 $name=utf8_encode($name);
295 } else {
296 $hashdir = $wgHashedUploadDirectory;
297 $base = $wgUploadBaseUrl;
298 $path = $wgUploadPath;
300 if ($hashdir) {
301 $hash = md5( $name );
302 $url = "{$base}{$path}/{$subdir}/" . $hash{0} . "/" .
303 substr( $hash, 0, 2 ) . "/{$name}";
304 } else {
305 $url = "{$base}{$path}/{$subdir}/{$name}";
308 return wfUrlencode($url);
312 * Return the file name of a thumbnail of the specified width
314 * @param integer $width Width of the thumbnail image
315 * @param boolean $shared Does the thumbnail come from the shared repository?
316 * @access private
318 function thumbName( $width, $shared=false ) {
319 global $wgUseLatin1,$wgSharedLatin1;
320 $thumb = $width."px-".$this->name;
321 if( $this->extension == 'svg' ) {
322 # Rasterize SVG vector images to PNG
323 $thumb .= '.png';
325 if( $shared && $wgUseLatin1 && !$wgSharedLatin1) {
326 $thumb=utf8_encode($thumb);
328 return $thumb;
332 * Create a thumbnail of the image having the specified width/height.
333 * The thumbnail will not be created if the width is larger than the
334 * image's width. Let the browser do the scaling in this case.
335 * The thumbnail is stored on disk and is only computed if the thumbnail
336 * file does not exist OR if it is older than the image.
337 * Returns the URL.
339 * Keeps aspect ratio of original image. If both width and height are
340 * specified, the generated image will be no bigger than width x height,
341 * and will also have correct aspect ratio.
343 * @param integer $width maximum width of the generated thumbnail
344 * @param integer $height maximum height of the image (optional)
345 * @access public
347 function createThumb( $width, $height=-1 ) {
348 if ( $height == -1 ) {
349 return $this->renderThumb( $width );
351 if ( $width < $this->width ) {
352 $thumbheight = $this->height * $width / $this->width;
353 $thumbwidth = $width;
354 } else {
355 $thumbheight = $this->height;
356 $thumbwidth = $this->width;
358 if ( $thumbheight > $height ) {
359 $thumbwidth = $thumbwidth * $height / $thumbheight;
360 $thumbheight = $height;
362 return $this->renderThumb( $thumbwidth );
366 * Create a thumbnail of the image having the specified width.
367 * The thumbnail will not be created if the width is larger than the
368 * image's width. Let the browser do the scaling in this case.
369 * The thumbnail is stored on disk and is only computed if the thumbnail
370 * file does not exist OR if it is older than the image.
371 * Returns the URL.
373 * @access private
375 function /* private */ renderThumb( $width ) {
376 global $wgImageMagickConvertCommand;
377 global $wgUseImageMagick;
378 global $wgUseSquid, $wgInternalServer;
380 $width = IntVal( $width );
382 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
383 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).'/'.$thumbName;
384 $thumbUrl = $this->thumbUrl( $width );
385 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
386 if ( ! $this->exists() )
388 # If there is no image, there will be no thumbnail
389 return '';
392 # Sanity check $width
393 if( $width <= 0 ) {
394 # BZZZT
395 return '';
398 if( $width > $this->width && !$this->mustRender() ) {
399 # Don't make an image bigger than the source
400 return $this->getViewURL();
403 if ( (! file_exists( $thumbPath ) ) || ( filemtime($thumbPath) < filemtime($this->imagePath) ) ) {
404 if( $this->extension == 'svg' ) {
405 global $wgSVGConverters, $wgSVGConverter;
406 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
407 global $wgSVGConverterPath;
408 $cmd = str_replace(
409 array( '$path/', '$width', '$input', '$output' ),
410 array( $wgSVGConverterPath,
411 $width,
412 escapeshellarg( $this->imagePath ),
413 escapeshellarg( $thumbPath ) ),
414 $wgSVGConverters[$wgSVGConverter] );
415 $conv = shell_exec( $cmd );
416 } else {
417 $conv = false;
419 } elseif ( $wgUseImageMagick ) {
420 # use ImageMagick
421 # Specify white background color, will be used for transparent images
422 # in Internet Explorer/Windows instead of default black.
423 $cmd = $wgImageMagickConvertCommand .
424 " -quality 85 -background white -geometry {$width} ".
425 escapeshellarg($this->imagePath) . " " .
426 escapeshellarg($thumbPath);
427 $conv = shell_exec( $cmd );
428 } else {
429 # Use PHP's builtin GD library functions.
431 # First find out what kind of file this is, and select the correct
432 # input routine for this.
434 $truecolor = false;
436 switch( $this->type ) {
437 case 1: # GIF
438 $src_image = imagecreatefromgif( $this->imagePath );
439 break;
440 case 2: # JPG
441 $src_image = imagecreatefromjpeg( $this->imagePath );
442 $truecolor = true;
443 break;
444 case 3: # PNG
445 $src_image = imagecreatefrompng( $this->imagePath );
446 $truecolor = ( $this->bits > 8 );
447 break;
448 case 15: # WBMP for WML
449 $src_image = imagecreatefromwbmp( $this->imagePath );
450 break;
451 case 16: # XBM
452 $src_image = imagecreatefromxbm( $this->imagePath );
453 break;
454 default:
455 return 'Image type not supported';
456 break;
458 $height = floor( $this->height * ( $width/$this->width ) );
459 if ( $truecolor ) {
460 $dst_image = imagecreatetruecolor( $width, $height );
461 } else {
462 $dst_image = imagecreate( $width, $height );
464 imagecopyresampled( $dst_image, $src_image,
465 0,0,0,0,
466 $width, $height, $this->width, $this->height );
467 switch( $this->type ) {
468 case 1: # GIF
469 case 3: # PNG
470 case 15: # WBMP
471 case 16: # XBM
472 #$thumbUrl .= ".png";
473 #$thumbPath .= ".png";
474 imagepng( $dst_image, $thumbPath );
475 break;
476 case 2: # JPEG
477 #$thumbUrl .= ".jpg";
478 #$thumbPath .= ".jpg";
479 imageinterlace( $dst_image );
480 imagejpeg( $dst_image, $thumbPath, 95 );
481 break;
482 default:
483 break;
485 imagedestroy( $dst_image );
486 imagedestroy( $src_image );
491 # Check for zero-sized thumbnails. Those can be generated when
492 # no disk space is available or some other error occurs
494 $thumbstat = stat( $thumbPath );
495 if( $thumbstat['size'] == 0 )
497 unlink( $thumbPath );
500 # Purge squid
501 # This has to be done after the image is updated and present for all machines on NFS,
502 # or else the old version might be stored into the squid again
503 if ( $wgUseSquid ) {
504 $urlArr = Array(
505 $wgInternalServer.$thumbUrl
507 wfPurgeSquidServers($urlArr);
510 return $thumbUrl;
511 } // END OF function createThumb
514 * Return the image history of this image, line by line.
515 * starts with current version, then old versions.
516 * uses $this->historyLine to check which line to return:
517 * 0 return line for current version
518 * 1 query for old versions, return first one
519 * 2, ... return next old version from above query
521 * @access public
523 function nextHistoryLine()
525 $fname = 'Image::nextHistoryLine()';
526 $dbr =& wfGetDB( DB_SLAVE );
527 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
528 $this->historyRes = $dbr->select( 'image',
529 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
530 array( 'img_name' => $this->title->getDBkey() ),
531 $fname
533 if ( 0 == wfNumRows( $this->historyRes ) ) {
534 return FALSE;
536 } else if ( $this->historyLine == 1 ) {
537 $this->historyRes = $dbr->select( 'oldimage',
538 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
539 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
540 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
543 $this->historyLine ++;
545 return $dbr->fetchObject( $this->historyRes );
549 * Reset the history pointer to the first element of the history
550 * @access public
552 function resetHistory()
554 $this->historyLine = 0;
558 * Return true if the file is of a type that can't be directly
559 * rendered by typical browsers and needs to be re-rasterized.
560 * @return bool
562 function mustRender() {
563 return ( $this->extension == 'svg' );
566 } //class
570 * Returns the image directory of an image
571 * If the directory does not exist, it is created.
572 * The result is an absolute path.
574 * @param string $fname file name of the image file
575 * @access public
577 function wfImageDir( $fname )
579 global $wgUploadDirectory, $wgHashedUploadDirectory;
581 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
583 $hash = md5( $fname );
584 $oldumask = umask(0);
585 $dest = $wgUploadDirectory . '/' . $hash{0};
586 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
587 $dest .= '/' . substr( $hash, 0, 2 );
588 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
590 umask( $oldumask );
591 return $dest;
595 * Returns the image directory of an image's thubnail
596 * If the directory does not exist, it is created.
597 * The result is an absolute path.
599 * @param string $fname file name of the thumbnail file, including file size prefix
600 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
601 * @param boolean $shared (optional) use the shared upload directory
602 * @access public
604 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
606 return wfImageArchiveDir( $fname, $subdir, $shared );
610 * Returns the image directory of an image's old version
611 * If the directory does not exist, it is created.
612 * The result is an absolute path.
614 * @param string $fname file name of the thumbnail file, including file size prefix
615 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
616 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
617 * @access public
619 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
621 global $wgUploadDirectory, $wgHashedUploadDirectory,
622 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
623 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
624 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
625 if (!$hashdir) { return $dir.'/'.$subdir; }
626 $hash = md5( $fname );
627 $oldumask = umask(0);
628 # Suppress warning messages here; if the file itself can't
629 # be written we'll worry about it then.
630 $archive = $dir.'/'.$subdir;
631 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
632 $archive .= '/' . $hash{0};
633 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
634 $archive .= '/' . substr( $hash, 0, 2 );
635 if ( ! is_dir( $archive ) ) { @mkdir( $archive, 0777 ); }
637 umask( $oldumask );
638 return $archive;
642 * Record an image upload in the upload log.
644 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
646 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
647 global $wgUseCopyrightUpload;
649 $fname = 'wfRecordUpload';
650 $dbw =& wfGetDB( DB_MASTER );
652 # img_name must be unique
653 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
654 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
658 $now = wfTimestampNow();
659 $won = wfInvertTimestamp( $now );
660 $size = IntVal( $size );
662 if ( $wgUseCopyrightUpload )
664 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
665 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
666 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
668 else $textdesc = $desc ;
670 $now = wfTimestampNow();
671 $won = wfInvertTimestamp( $now );
673 # Test to see if the row exists using INSERT IGNORE
674 # This avoids race conditions by locking the row until the commit, and also
675 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
676 $dbw->insert( 'image',
677 array(
678 'img_name' => $name,
679 'img_size'=> $size,
680 'img_timestamp' => $dbw->timestamp($now),
681 'img_description' => $desc,
682 'img_user' => $wgUser->getID(),
683 'img_user_text' => $wgUser->getName(),
684 ), $fname, 'IGNORE'
686 $descTitle = Title::makeTitleSafe( NS_IMAGE, $name );
688 if ( $dbw->affectedRows() ) {
689 # Successfully inserted, this is a new image
690 $id = $descTitle->getArticleID();
692 if ( $id == 0 ) {
693 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
694 $dbw->insert( 'cur',
695 array(
696 'cur_id' => $seqVal,
697 'cur_namespace' => NS_IMAGE,
698 'cur_title' => $name,
699 'cur_comment' => $desc,
700 'cur_user' => $wgUser->getID(),
701 'cur_user_text' => $wgUser->getName(),
702 'cur_timestamp' => $dbw->timestamp($now),
703 'cur_is_new' => 1,
704 'cur_text' => $textdesc,
705 'inverse_timestamp' => $won,
706 'cur_touched' => $dbw->timestamp($now)
707 ), $fname
709 $id = $dbw->insertId() or 0; # We should throw an error instead
711 RecentChange::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
713 $u = new SearchUpdate( $id, $name, $desc );
714 $u->doUpdate();
716 } else {
717 # Collision, this is an update of an image
718 # Get current image row for update
719 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
720 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
722 # Insert it into oldimage
723 $dbw->insert( 'oldimage',
724 array(
725 'oi_name' => $s->img_name,
726 'oi_archive_name' => $oldver,
727 'oi_size' => $s->img_size,
728 'oi_timestamp' => $dbw->timestamp($s->img_timestamp),
729 'oi_description' => $s->img_description,
730 'oi_user' => $s->img_user,
731 'oi_user_text' => $s->img_user_text
732 ), $fname
735 # Update the current image row
736 $dbw->update( 'image',
737 array( /* SET */
738 'img_size' => $size,
739 'img_timestamp' => $dbw->timestamp(),
740 'img_user' => $wgUser->getID(),
741 'img_user_text' => $wgUser->getName(),
742 'img_description' => $desc,
743 ), array( /* WHERE */
744 'img_name' => $name
745 ), $fname
748 # Invalidate the cache for the description page
749 $descTitle->invalidateCache();
752 $log = new LogPage( 'upload' );
753 $log->addEntry( 'upload', $descTitle, $desc );
757 * Returns the image URL of an image's old version
759 * @param string $fname file name of the image file
760 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
761 * @access public
763 function wfImageArchiveUrl( $name, $subdir='archive' )
765 global $wgUploadPath, $wgHashedUploadDirectory;
767 if ($wgHashedUploadDirectory) {
768 $hash = md5( substr( $name, 15) );
769 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
770 substr( $hash, 0, 2 ) . '/'.$name;
771 } else {
772 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
774 return wfUrlencode($url);
778 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
779 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
781 * @param string $length
782 * @return int Length in pixels
784 function scaleSVGUnit( $length ) {
785 static $unitLength = array(
786 'px' => 1.0,
787 'pt' => 1.25,
788 'pc' => 15.0,
789 'mm' => 3.543307,
790 'cm' => 35.43307,
791 'in' => 90.0,
792 '' => 1.0, // "User units" pixels by default
793 '%' => 2.0, // Fake it!
795 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
796 $length = FloatVal( $matches[1] );
797 $unit = $matches[2];
798 return round( $length * $unitLength[$unit] );
799 } else {
800 // Assume pixels
801 return round( FloatVal( $length ) );
806 * Compatible with PHP getimagesize()
807 * @todo support gzipped SVGZ
808 * @todo check XML more carefully
809 * @todo sensible defaults
811 * @param string $filename
812 * @return array
814 function getSVGsize( $filename ) {
815 $width = 256;
816 $height = 256;
818 // Read a chunk of the file
819 $f = fopen( $filename, "rt" );
820 if( !$f ) return false;
821 $chunk = fread( $f, 4096 );
822 fclose( $f );
824 // Uber-crappy hack! Run through a real XML parser.
825 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
826 return false;
828 $tag = $matches[1];
829 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
830 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
832 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
833 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
836 return array( $width, $height, 'SVG',
837 "width=\"$width\" height=\"$height\"" );