8 * Class to represent an image
10 * Provides methods to retrieve paths (physical, logical, URL),
11 * to generate thumbnails or for uploading.
19 var $name, # name of the image
20 $imagePath, # Path of the image
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
29 $bits, # --- returned by getimagesize, see http://de3.php.net/manual/en/function.getimagesize.php
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
42 function Image( $name )
44 global $wgUploadDirectory,$wgHashedUploadDirectory,
45 $wgUseSharedUploads, $wgSharedUploadDirectory,
46 $wgHashedSharedUploadDirectory;
49 $this->title
= Title
::makeTitleSafe( NS_IMAGE
, $this->name
);
50 $this->fromSharedDirectory
= false;
52 if ($wgHashedUploadDirectory) {
53 $hash = md5( $this->title
->getDBkey() );
54 $this->imagePath
= $wgUploadDirectory . '/' . $hash{0} . '/' .
55 substr( $hash, 0, 2 ) . "/{$name}";
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) {
65 if($wgHashedSharedUploadDirectory) {
66 $hash = md5( $this->title
->getDBkey() );
67 $this->imagePath
= $wgSharedUploadDirectory . '/' . $hash{0} . '/' .
68 substr( $hash, 0, 2 ) . "/{$name}";
70 $this->imagePath
= $wgSharedUploadDirectory . '/' . $name;
72 $this->fileExists
= file_exists( $this->imagePath
);
73 $this->fromSharedDirectory
= true;
74 #wfDebug ("File from shared directory: ".$this->imagePath."\n");
76 if($this->fileExists
) {
77 $this->url
= $this->wfImageUrl( $name, $this->fromSharedDirectory
);
82 $n = strrpos( $name, '.' );
83 $this->extension
= strtolower( $n ?
substr( $name, $n +
1 ) : '' );
86 if ( $this->fileExists
)
88 if( $this->extension
== 'svg' ) {
89 @$gis = getSVGsize( $this->imagePath
);
91 @$gis = getimagesize( $this->imagePath
);
93 if( $gis !== false ) {
94 $this->width
= $gis[0];
95 $this->height
= $gis[1];
96 $this->type
= $gis[2];
97 $this->attr
= $gis[3];
98 if ( isset( $gis['bits'] ) ) {
99 $this->bits
= $gis['bits'];
105 $this->historyLine
= 0;
111 * Create a new image object from a title object.
113 * @param Title $nt Title object. Must be from namespace "image"
116 function newFromTitle( $nt )
118 $img = new Image( $nt->getDBKey() );
124 * Return the name of this image
133 * Return the associated title object
142 * Return the URL of the image file
150 function getViewURL() {
151 if( $this->mustRender() ) {
152 return $this->createThumb( $this->getWidth() );
154 return $this->getURL();
159 * Return the image path of the image in the
160 * local file system as an absolute path
163 function getImagePath()
165 return $this->imagePath
;
169 * Return the width of the image
171 * Returns -1 if the file specified is not a known image type
180 * Return the height of the image
182 * Returns -1 if the file specified is not a known image type
187 return $this->height
;
191 * Return the size of the image file, in bytes
196 $st = stat( $this->getImagePath() );
201 * Return the type of the image
215 * Return the escapeLocalURL of this image
218 function getEscapeLocalURL()
220 return $this->title
->escapeLocalURL();
224 * Return the escapeFullURL of this image
227 function getEscapeFullURL()
229 return $this->title
->escapeFullURL();
233 * Return the URL of an image, provided its name.
235 * @param string $name Name of the image, without the leading "Image:"
236 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
239 function wfImageUrl( $name, $fromSharedDirectory = false )
241 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory,
242 $wgHashedSharedUploadDirectory,$wgSharedUploadBaseUrl,
244 if($fromSharedDirectory) {
245 $hash = $wgHashedSharedUploadDirectory;
246 $base = $wgSharedUploadBaseUrl;
247 $path = $wgSharedUploadPath;
249 $hash = $wgHashedUploadDirectory;
250 $base = $wgUploadBaseUrl;
251 $path = $wgUploadPath;
254 $hash = md5( $name );
255 $url = "{$base}{$path}/" . $hash{0} . "/" .
256 substr( $hash, 0, 2 ) . "/{$name}";
258 $url = "{$base}{$path}/{$name}";
260 return wfUrlencode( $url );
264 * Returns true iff the image file exists on disk.
270 return $this->fileExists
;
277 function thumbUrl( $width, $subdir='thumb') {
278 global $wgUploadPath,$wgHashedUploadDirectory, $wgUploadBaseUrl,
279 $wgSharedUploadPath,$wgSharedUploadDirectory,
280 $wgHashedSharedUploadDirectory, $wgSharedUploadBaseUrl;
281 $name = $this->thumbName( $width );
282 if($this->fromSharedDirectory
) {
283 $hashdir = $wgHashedSharedUploadDirectory;
284 $base = $wgSharedUploadBaseUrl;
285 $path = $wgSharedUploadPath;
287 $hashdir = $wgHashedUploadDirectory;
288 $base = $wgUploadBaseUrl;
289 $path = $wgUploadPath;
292 $hash = md5( $name );
293 $url = "{$base}{$path}/{$subdir}/" . $hash{0} . "/" .
294 substr( $hash, 0, 2 ) . "/{$name}";
296 $url = "{$base}{$path}/{$subdir}/{$name}";
299 return wfUrlencode($url);
303 * Return the file name of a thumbnail of the specified width
305 * @param integer $width Width of the thumbnail image
308 function thumbName( $width ) {
309 $thumb = $width."px-".$this->name
;
310 if( $this->extension
== 'svg' ) {
311 # Rasterize SVG vector images to PNG
318 * Create a thumbnail of the image having the specified width/height.
319 * The thumbnail will not be created if the width is larger than the
320 * image's width. Let the browser do the scaling in this case.
321 * The thumbnail is stored on disk and is only computed if the thumbnail
322 * file does not exist OR if it is older than the image.
325 * Keeps aspect ratio of original image. If both width and height are
326 * specified, the generated image will be no bigger than width x height,
327 * and will also have correct aspect ratio.
329 * @param integer $width maximum width of the generated thumbnail
330 * @param integer $height maximum height of the image (optional)
333 function createThumb( $width, $height=-1 ) {
334 if ( $height == -1 ) {
335 return $this->renderThumb( $width );
337 if ( $width < $this->width
) {
338 $thumbheight = $this->height
* $width / $this->width
;
339 $thumbwidth = $width;
341 $thumbheight = $this->height
;
342 $thumbwidth = $this->width
;
344 if ( $thumbheight > $height ) {
345 $thumbwidth = $thumbwidth * $height / $thumbheight;
346 $thumbheight = $height;
348 return $this->renderThumb( $thumbwidth );
352 * Create a thumbnail of the image having the specified width.
353 * The thumbnail will not be created if the width is larger than the
354 * image's width. Let the browser do the scaling in this case.
355 * The thumbnail is stored on disk and is only computed if the thumbnail
356 * file does not exist OR if it is older than the image.
361 function /* private */ renderThumb( $width ) {
362 global $wgImageMagickConvertCommand;
363 global $wgUseImageMagick;
364 global $wgUseSquid, $wgInternalServer;
366 $width = IntVal( $width );
368 $thumbName = $this->thumbName( $width );
369 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).'/'.$thumbName;
370 $thumbUrl = $this->thumbUrl( $width );
371 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
372 if ( ! $this->exists() )
374 # If there is no image, there will be no thumbnail
378 # Sanity check $width
384 if( $width > $this->width
&& !$this->mustRender() ) {
385 # Don't make an image bigger than the source
386 return $this->getViewURL();
389 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
390 if( $this->extension
== 'svg' ) {
391 global $wgSVGConverters, $wgSVGConverter;
392 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
393 global $wgSVGConverterPath;
395 array( '$path/', '$width', '$input', '$output' ),
396 array( $wgSVGConverterPath,
398 escapeshellarg( $this->imagePath
),
399 escapeshellarg( $thumbPath ) ),
400 $wgSVGConverters[$wgSVGConverter] );
401 $conv = shell_exec( $cmd );
405 } elseif ( $wgUseImageMagick ) {
407 # Specify white background color, will be used for transparent images
408 # in Internet Explorer/Windows instead of default black.
409 $cmd = $wgImageMagickConvertCommand .
410 " -quality 85 -background white -geometry {$width} ".
411 escapeshellarg($this->imagePath
) . " " .
412 escapeshellarg($thumbPath);
413 $conv = shell_exec( $cmd );
415 # Use PHP's builtin GD library functions.
417 # First find out what kind of file this is, and select the correct
418 # input routine for this.
422 switch( $this->type
) {
424 $src_image = imagecreatefromgif( $this->imagePath
);
427 $src_image = imagecreatefromjpeg( $this->imagePath
);
431 $src_image = imagecreatefrompng( $this->imagePath
);
432 $truecolor = ( $this->bits
> 8 );
434 case 15: # WBMP for WML
435 $src_image = imagecreatefromwbmp( $this->imagePath
);
438 $src_image = imagecreatefromxbm( $this->imagePath
);
441 return 'Image type not supported';
444 $height = floor( $this->height
* ( $width/$this->width
) );
446 $dst_image = imagecreatetruecolor( $width, $height );
448 $dst_image = imagecreate( $width, $height );
450 imagecopyresampled( $dst_image, $src_image,
452 $width, $height, $this->width
, $this->height
);
453 switch( $this->type
) {
458 #$thumbUrl .= ".png";
459 #$thumbPath .= ".png";
460 imagepng( $dst_image, $thumbPath );
463 #$thumbUrl .= ".jpg";
464 #$thumbPath .= ".jpg";
465 imageinterlace( $dst_image );
466 imagejpeg( $dst_image, $thumbPath, 95 );
471 imagedestroy( $dst_image );
472 imagedestroy( $src_image );
477 # Check for zero-sized thumbnails. Those can be generated when
478 # no disk space is available or some other error occurs
480 $thumbstat = stat( $thumbPath );
481 if( $thumbstat['size'] == 0 )
483 unlink( $thumbPath );
487 # This has to be done after the image is updated and present for all machines on NFS,
488 # or else the old version might be stored into the squid again
491 $wgInternalServer.$thumbUrl
493 wfPurgeSquidServers($urlArr);
497 } // END OF function createThumb
500 * Return the image history of this image, line by line.
501 * starts with current version, then old versions.
502 * uses $this->historyLine to check which line to return:
503 * 0 return line for current version
504 * 1 query for old versions, return first one
505 * 2, ... return next old version from above query
509 function nextHistoryLine()
511 $fname = 'Image::nextHistoryLine()';
512 $dbr =& wfGetDB( DB_SLAVE
);
513 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
514 $this->historyRes
= $dbr->select( 'image',
515 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
516 array( 'img_name' => $this->title
->getDBkey() ),
519 if ( 0 == wfNumRows( $this->historyRes
) ) {
522 } else if ( $this->historyLine
== 1 ) {
523 $this->historyRes
= $dbr->select( 'oldimage',
524 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
525 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
526 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
529 $this->historyLine ++
;
531 return $dbr->fetchObject( $this->historyRes
);
535 * Reset the history pointer to the first element of the history
538 function resetHistory()
540 $this->historyLine
= 0;
544 * Return true if the file is of a type that can't be directly
545 * rendered by typical browsers and needs to be re-rasterized.
548 function mustRender() {
549 return ( $this->extension
== 'svg' );
556 * Returns the image directory of an image
557 * If the directory does not exist, it is created.
558 * The result is an absolute path.
560 * @param string $fname file name of the image file
563 function wfImageDir( $fname )
565 global $wgUploadDirectory, $wgHashedUploadDirectory;
567 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
569 $hash = md5( $fname );
570 $oldumask = umask(0);
571 $dest = $wgUploadDirectory . '/' . $hash{0};
572 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
573 $dest .= '/' . substr( $hash, 0, 2 );
574 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
581 * Returns the image directory of an image's thubnail
582 * If the directory does not exist, it is created.
583 * The result is an absolute path.
585 * @param string $fname file name of the thumbnail file, including file size prefix
586 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
587 * @param boolean $shared (optional) use the shared upload directory
590 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
592 return wfImageArchiveDir( $fname, $subdir, $shared );
596 * Returns the image directory of an image's old version
597 * If the directory does not exist, it is created.
598 * The result is an absolute path.
600 * @param string $fname file name of the thumbnail file, including file size prefix
601 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
602 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
605 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
607 global $wgUploadDirectory, $wgHashedUploadDirectory,
608 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
609 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
610 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
611 if (!$hashdir) { return $dir.'/'.$subdir; }
613 $hash = md5( $fname );
614 $oldumask = umask(0);
615 # Suppress warning messages here; if the file itself can't
616 # be written we'll worry about it then.
617 $archive = $dir.'/'.$subdir;
618 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
619 $archive .= '/' . $hash{0};
620 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
621 $archive .= '/' . substr( $hash, 0, 2 );
622 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
629 * Record an image upload in the upload log.
631 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
633 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
634 global $wgUseCopyrightUpload;
636 $fname = 'wfRecordUpload';
637 $dbw =& wfGetDB( DB_MASTER
);
639 # img_name must be unique
640 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
641 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
645 $now = wfTimestampNow();
646 $won = wfInvertTimestamp( $now );
647 $size = IntVal( $size );
649 if ( $wgUseCopyrightUpload )
651 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
652 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
653 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
655 else $textdesc = $desc ;
657 $now = wfTimestampNow();
658 $won = wfInvertTimestamp( $now );
660 # Test to see if the row exists using INSERT IGNORE
661 # This avoids race conditions by locking the row until the commit, and also
662 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
663 $dbw->insert( 'image',
667 'img_timestamp' => $dbw->timestamp($now),
668 'img_description' => $desc,
669 'img_user' => $wgUser->getID(),
670 'img_user_text' => $wgUser->getName(),
673 $descTitle = Title
::makeTitleSafe( NS_IMAGE
, $name );
675 if ( $dbw->affectedRows() ) {
676 # Successfully inserted, this is a new image
677 $id = $descTitle->getArticleID();
680 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
684 'cur_namespace' => NS_IMAGE
,
685 'cur_title' => $name,
686 'cur_comment' => $desc,
687 'cur_user' => $wgUser->getID(),
688 'cur_user_text' => $wgUser->getName(),
689 'cur_timestamp' => $dbw->timestamp($now),
691 'cur_text' => $textdesc,
692 'inverse_timestamp' => $won,
693 'cur_touched' => $dbw->timestamp($now)
696 $id = $dbw->insertId() or 0; # We should throw an error instead
698 RecentChange
::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
700 $u = new SearchUpdate( $id, $name, $desc );
704 # Collision, this is an update of an image
705 # Get current image row for update
706 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
707 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
709 # Insert it into oldimage
710 $dbw->insert( 'oldimage',
712 'oi_name' => $s->img_name
,
713 'oi_archive_name' => $oldver,
714 'oi_size' => $s->img_size
,
715 'oi_timestamp' => $dbw->timestamp($s->img_timestamp
),
716 'oi_description' => $s->img_description
,
717 'oi_user' => $s->img_user
,
718 'oi_user_text' => $s->img_user_text
722 # Update the current image row
723 $dbw->update( 'image',
726 'img_timestamp' => $dbw->timestamp(),
727 'img_user' => $wgUser->getID(),
728 'img_user_text' => $wgUser->getName(),
729 'img_description' => $desc,
730 ), array( /* WHERE */
735 # Invalidate the cache for the description page
736 $descTitle->invalidateCache();
739 $log = new LogPage( 'upload' );
740 $log->addEntry( 'upload', $descTitle, $desc );
744 * Returns the image URL of an image's old version
746 * @param string $fname file name of the image file
747 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
750 function wfImageArchiveUrl( $name, $subdir='archive' )
752 global $wgUploadPath, $wgHashedUploadDirectory;
754 if ($wgHashedUploadDirectory) {
755 $hash = md5( substr( $name, 15) );
756 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
757 substr( $hash, 0, 2 ) . '/'.$name;
759 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
761 return wfUrlencode($url);
765 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
766 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
768 * @param string $length
769 * @return int Length in pixels
771 function scaleSVGUnit( $length ) {
772 static $unitLength = array(
779 '' => 1.0, // "User units" pixels by default
780 '%' => 2.0, // Fake it!
782 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
783 $length = FloatVal( $matches[1] );
785 return round( $length * $unitLength[$unit] );
788 return round( FloatVal( $length ) );
793 * Compatible with PHP getimagesize()
794 * @todo support gzipped SVGZ
795 * @todo check XML more carefully
796 * @todo sensible defaults
798 * @param string $filename
801 function getSVGsize( $filename ) {
805 // Read a chunk of the file
806 $f = fopen( $filename, "rt" );
807 if( !$f ) return false;
808 $chunk = fread( $f, 4096 );
811 // Uber-crappy hack! Run through a real XML parser.
812 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
816 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
817 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
819 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
820 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
823 return array( $width, $height, 'SVG',
824 "width=\"$width\" height=\"$height\"" );