7 * Class to represent an image
9 * Provides methods to retrieve paths (physical, logical, URL),
10 * to generate thumbnails or for uploading.
18 var $name, # name of the image
19 $imagePath, # Path of the image
21 $title, # Title object for this image. Initialized when needed.
22 $fileExists, # does the image file exist on disk?
23 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory
24 $historyLine, # Number of line to return by nextHistoryLine()
25 $historyRes, # result of the query for the image's history
28 $bits, # --- returned by getimagesize, see http://de3.php.net/manual/en/function.getimagesize.php
36 * Create an Image object from an image name
38 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
41 function Image( $name )
43 global $wgUploadDirectory,$wgHashedUploadDirectory,
44 $wgUseSharedUploads, $wgSharedUploadDirectory,
45 $wgHashedSharedUploadDirectory,$wgUseLatin1,
46 $wgSharedLatin1,$wgLang;
49 $this->title
= Title
::makeTitleSafe( NS_IMAGE
, $this->name
);
50 $this->fromSharedDirectory
= false;
51 if ($wgHashedUploadDirectory) {
52 $hash = md5( $this->title
->getDBkey() );
53 $this->imagePath
= $wgUploadDirectory . '/' . $hash{0} . '/' .
54 substr( $hash, 0, 2 ) . "/{$name}";
56 $this->imagePath
= $wgUploadDirectory . '/' . $name;
58 $this->fileExists
= file_exists( $this->imagePath
);
60 # If the file is not found, and a shared upload directory
61 # like the Wikimedia Commons is used, look for it there.
62 if (!$this->fileExists
&& $wgUseSharedUploads) {
63 # in case we're running a capitallinks=false wiki
64 $sharedname=$wgLang->ucfirst($name);
65 $sharedtitle=$wgLang->ucfirst($this->title
->getDBkey());
66 if($wgUseLatin1 && !$wgSharedLatin1) {
67 $sharedname=utf8_encode($sharedname);
68 $sharedtitle=utf8_encode($sharedtitle);
71 if($wgHashedSharedUploadDirectory) {
72 $hash = md5( $sharedtitle );
73 $this->imagePath
= $wgSharedUploadDirectory . '/' . $hash{0} . '/' .
74 substr( $hash, 0, 2 ) . "/".$sharedname;
76 $this->imagePath
= $wgSharedUploadDirectory . '/' . $sharedname;
78 $this->fileExists
= file_exists( $this->imagePath
);
79 $this->fromSharedDirectory
= true;
82 if($this->fileExists
) {
83 $this->url
= $this->wfImageUrl( $name, $this->fromSharedDirectory
);
88 $n = strrpos( $name, '.' );
89 $this->extension
= strtolower( $n ?
substr( $name, $n +
1 ) : '' );
92 if ( $this->fileExists
)
94 if( $this->extension
== 'svg' ) {
95 @$gis = getSVGsize( $this->imagePath
);
97 @$gis = getimagesize( $this->imagePath
);
99 if( $gis !== false ) {
100 $this->width
= $gis[0];
101 $this->height
= $gis[1];
102 $this->type
= $gis[2];
103 $this->attr
= $gis[3];
104 if ( isset( $gis['bits'] ) ) {
105 $this->bits
= $gis['bits'];
111 $this->historyLine
= 0;
117 * Create a new image object from a title object.
119 * @param Title $nt Title object. Must be from namespace "image"
122 function newFromTitle( $nt )
124 $img = new Image( $nt->getDBKey() );
130 * Return the name of this image
139 * Return the associated title object
148 * Return the URL of the image file
156 function getViewURL() {
157 if( $this->mustRender() ) {
158 return $this->createThumb( $this->getWidth() );
160 return $this->getURL();
165 * Return the image path of the image in the
166 * local file system as an absolute path
169 function getImagePath()
171 return $this->imagePath
;
175 * Return the width of the image
177 * Returns -1 if the file specified is not a known image type
186 * Return the height of the image
188 * Returns -1 if the file specified is not a known image type
193 return $this->height
;
197 * Return the size of the image file, in bytes
202 $st = stat( $this->getImagePath() );
207 * Return the type of the image
221 * Return the escapeLocalURL of this image
224 function getEscapeLocalURL()
226 return $this->title
->escapeLocalURL();
230 * Return the escapeFullURL of this image
233 function getEscapeFullURL()
235 return $this->title
->escapeFullURL();
239 * Return the URL of an image, provided its name.
241 * @param string $name Name of the image, without the leading "Image:"
242 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
245 function wfImageUrl( $name, $fromSharedDirectory = false )
247 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory,
248 $wgHashedSharedUploadDirectory,$wgSharedUploadPath;
249 if($fromSharedDirectory) {
250 $hash = $wgHashedSharedUploadDirectory;
252 $path = $wgSharedUploadPath;
254 $hash = $wgHashedUploadDirectory;
255 $base = $wgUploadBaseUrl;
256 $path = $wgUploadPath;
259 $hash = md5( $name );
260 $url = "{$base}{$path}/" . $hash{0} . "/" .
261 substr( $hash, 0, 2 ) . "/{$name}";
263 $url = "{$base}{$path}/{$name}";
265 return wfUrlencode( $url );
269 * Returns true iff the image file exists on disk.
275 return $this->fileExists
;
282 function thumbUrl( $width, $subdir='thumb') {
283 global $wgUploadPath,$wgHashedUploadDirectory, $wgUploadBaseUrl,
284 $wgSharedUploadPath,$wgSharedUploadDirectory,
285 $wgHashedSharedUploadDirectory,$wgUseLatin1,$wgSharedLatin1;
286 $name = $this->thumbName( $width );
287 if($this->fromSharedDirectory
) {
288 $hashdir = $wgHashedSharedUploadDirectory;
290 $path = $wgSharedUploadPath;
291 if($wgUseLatin1 && !$wgSharedLatin1) {
292 $name=utf8_encode($name);
295 $hashdir = $wgHashedUploadDirectory;
296 $base = $wgUploadBaseUrl;
297 $path = $wgUploadPath;
300 $hash = md5( $name );
301 $url = "{$base}{$path}/{$subdir}/" . $hash{0} . "/" .
302 substr( $hash, 0, 2 ) . "/{$name}";
304 $url = "{$base}{$path}/{$subdir}/{$name}";
307 return wfUrlencode($url);
311 * Return the file name of a thumbnail of the specified width
313 * @param integer $width Width of the thumbnail image
314 * @param boolean $shared Does the thumbnail come from the shared repository?
317 function thumbName( $width, $shared=false ) {
318 global $wgUseLatin1,$wgSharedLatin1;
319 $thumb = $width."px-".$this->name
;
320 if( $this->extension
== 'svg' ) {
321 # Rasterize SVG vector images to PNG
324 if( $shared && $wgUseLatin1 && !$wgSharedLatin1) {
325 $thumb=utf8_encode($thumb);
331 * Create a thumbnail of the image having the specified width/height.
332 * The thumbnail will not be created if the width is larger than the
333 * image's width. Let the browser do the scaling in this case.
334 * The thumbnail is stored on disk and is only computed if the thumbnail
335 * file does not exist OR if it is older than the image.
338 * Keeps aspect ratio of original image. If both width and height are
339 * specified, the generated image will be no bigger than width x height,
340 * and will also have correct aspect ratio.
342 * @param integer $width maximum width of the generated thumbnail
343 * @param integer $height maximum height of the image (optional)
346 function createThumb( $width, $height=-1 ) {
347 if ( $height == -1 ) {
348 return $this->renderThumb( $width );
350 if ( $width < $this->width
) {
351 $thumbheight = $this->height
* $width / $this->width
;
352 $thumbwidth = $width;
354 $thumbheight = $this->height
;
355 $thumbwidth = $this->width
;
357 if ( $thumbheight > $height ) {
358 $thumbwidth = $thumbwidth * $height / $thumbheight;
359 $thumbheight = $height;
361 return $this->renderThumb( $thumbwidth );
365 * Create a thumbnail of the image having the specified width.
366 * The thumbnail will not be created if the width is larger than the
367 * image's width. Let the browser do the scaling in this case.
368 * The thumbnail is stored on disk and is only computed if the thumbnail
369 * file does not exist OR if it is older than the image.
374 function /* private */ renderThumb( $width ) {
375 global $wgImageMagickConvertCommand;
376 global $wgUseImageMagick;
377 global $wgUseSquid, $wgInternalServer;
379 $width = IntVal( $width );
381 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
382 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).'/'.$thumbName;
383 $thumbUrl = $this->thumbUrl( $width );
384 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
385 if ( ! $this->exists() )
387 # If there is no image, there will be no thumbnail
391 # Sanity check $width
397 if( $width > $this->width
&& !$this->mustRender() ) {
398 # Don't make an image bigger than the source
399 return $this->getViewURL();
402 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
403 if( $this->extension
== 'svg' ) {
404 global $wgSVGConverters, $wgSVGConverter;
405 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
406 global $wgSVGConverterPath;
408 array( '$path/', '$width', '$input', '$output' ),
409 array( $wgSVGConverterPath,
411 escapeshellarg( $this->imagePath
),
412 escapeshellarg( $thumbPath ) ),
413 $wgSVGConverters[$wgSVGConverter] );
414 $conv = shell_exec( $cmd );
418 } elseif ( $wgUseImageMagick ) {
420 # Specify white background color, will be used for transparent images
421 # in Internet Explorer/Windows instead of default black.
422 $cmd = $wgImageMagickConvertCommand .
423 " -quality 85 -background white -geometry {$width} ".
424 escapeshellarg($this->imagePath
) . " " .
425 escapeshellarg($thumbPath);
426 $conv = shell_exec( $cmd );
428 # Use PHP's builtin GD library functions.
430 # First find out what kind of file this is, and select the correct
431 # input routine for this.
435 switch( $this->type
) {
437 $src_image = imagecreatefromgif( $this->imagePath
);
440 $src_image = imagecreatefromjpeg( $this->imagePath
);
444 $src_image = imagecreatefrompng( $this->imagePath
);
445 $truecolor = ( $this->bits
> 8 );
447 case 15: # WBMP for WML
448 $src_image = imagecreatefromwbmp( $this->imagePath
);
451 $src_image = imagecreatefromxbm( $this->imagePath
);
454 return 'Image type not supported';
457 $height = floor( $this->height
* ( $width/$this->width
) );
459 $dst_image = imagecreatetruecolor( $width, $height );
461 $dst_image = imagecreate( $width, $height );
463 imagecopyresampled( $dst_image, $src_image,
465 $width, $height, $this->width
, $this->height
);
466 switch( $this->type
) {
471 #$thumbUrl .= ".png";
472 #$thumbPath .= ".png";
473 imagepng( $dst_image, $thumbPath );
476 #$thumbUrl .= ".jpg";
477 #$thumbPath .= ".jpg";
478 imageinterlace( $dst_image );
479 imagejpeg( $dst_image, $thumbPath, 95 );
484 imagedestroy( $dst_image );
485 imagedestroy( $src_image );
490 # Check for zero-sized thumbnails. Those can be generated when
491 # no disk space is available or some other error occurs
493 $thumbstat = stat( $thumbPath );
494 if( $thumbstat['size'] == 0 )
496 unlink( $thumbPath );
500 # This has to be done after the image is updated and present for all machines on NFS,
501 # or else the old version might be stored into the squid again
504 $wgInternalServer.$thumbUrl
506 wfPurgeSquidServers($urlArr);
510 } // END OF function createThumb
513 * Return the image history of this image, line by line.
514 * starts with current version, then old versions.
515 * uses $this->historyLine to check which line to return:
516 * 0 return line for current version
517 * 1 query for old versions, return first one
518 * 2, ... return next old version from above query
522 function nextHistoryLine()
524 $fname = 'Image::nextHistoryLine()';
525 $dbr =& wfGetDB( DB_SLAVE
);
526 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
527 $this->historyRes
= $dbr->select( 'image',
528 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
529 array( 'img_name' => $this->title
->getDBkey() ),
532 if ( 0 == wfNumRows( $this->historyRes
) ) {
535 } else if ( $this->historyLine
== 1 ) {
536 $this->historyRes
= $dbr->select( 'oldimage',
537 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
538 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
539 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
542 $this->historyLine ++
;
544 return $dbr->fetchObject( $this->historyRes
);
548 * Reset the history pointer to the first element of the history
551 function resetHistory()
553 $this->historyLine
= 0;
557 * Return true if the file is of a type that can't be directly
558 * rendered by typical browsers and needs to be re-rasterized.
561 function mustRender() {
562 return ( $this->extension
== 'svg' );
569 * Returns the image directory of an image
570 * If the directory does not exist, it is created.
571 * The result is an absolute path.
573 * @param string $fname file name of the image file
576 function wfImageDir( $fname )
578 global $wgUploadDirectory, $wgHashedUploadDirectory;
580 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
582 $hash = md5( $fname );
583 $oldumask = umask(0);
584 $dest = $wgUploadDirectory . '/' . $hash{0};
585 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
586 $dest .= '/' . substr( $hash, 0, 2 );
587 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
594 * Returns the image directory of an image's thubnail
595 * If the directory does not exist, it is created.
596 * The result is an absolute path.
598 * @param string $fname file name of the thumbnail file, including file size prefix
599 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
600 * @param boolean $shared (optional) use the shared upload directory
603 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
605 return wfImageArchiveDir( $fname, $subdir, $shared );
609 * Returns the image directory of an image's old version
610 * If the directory does not exist, it is created.
611 * The result is an absolute path.
613 * @param string $fname file name of the thumbnail file, including file size prefix
614 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
615 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
618 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
620 global $wgUploadDirectory, $wgHashedUploadDirectory,
621 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
622 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
623 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
624 if (!$hashdir) { return $dir.'/'.$subdir; }
625 $hash = md5( $fname );
626 $oldumask = umask(0);
627 # Suppress warning messages here; if the file itself can't
628 # be written we'll worry about it then.
629 $archive = $dir.'/'.$subdir;
630 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
631 $archive .= '/' . $hash{0};
632 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
633 $archive .= '/' . substr( $hash, 0, 2 );
634 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
641 * Record an image upload in the upload log.
643 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
645 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
646 global $wgUseCopyrightUpload;
648 $fname = 'wfRecordUpload';
649 $dbw =& wfGetDB( DB_MASTER
);
651 # img_name must be unique
652 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
653 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
657 $now = wfTimestampNow();
658 $won = wfInvertTimestamp( $now );
659 $size = IntVal( $size );
661 if ( $wgUseCopyrightUpload )
663 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
664 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
665 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
667 else $textdesc = $desc ;
669 $now = wfTimestampNow();
670 $won = wfInvertTimestamp( $now );
672 # Test to see if the row exists using INSERT IGNORE
673 # This avoids race conditions by locking the row until the commit, and also
674 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
675 $dbw->insert( 'image',
679 'img_timestamp' => $dbw->timestamp($now),
680 'img_description' => $desc,
681 'img_user' => $wgUser->getID(),
682 'img_user_text' => $wgUser->getName(),
685 $descTitle = Title
::makeTitleSafe( NS_IMAGE
, $name );
687 if ( $dbw->affectedRows() ) {
688 # Successfully inserted, this is a new image
689 $id = $descTitle->getArticleID();
692 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
696 'cur_namespace' => NS_IMAGE
,
697 'cur_title' => $name,
698 'cur_comment' => $desc,
699 'cur_user' => $wgUser->getID(),
700 'cur_user_text' => $wgUser->getName(),
701 'cur_timestamp' => $dbw->timestamp($now),
703 'cur_text' => $textdesc,
704 'inverse_timestamp' => $won,
705 'cur_touched' => $dbw->timestamp($now)
708 $id = $dbw->insertId() or 0; # We should throw an error instead
710 RecentChange
::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
712 $u = new SearchUpdate( $id, $name, $desc );
716 # Collision, this is an update of an image
717 # Get current image row for update
718 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
719 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
721 # Insert it into oldimage
722 $dbw->insert( 'oldimage',
724 'oi_name' => $s->img_name
,
725 'oi_archive_name' => $oldver,
726 'oi_size' => $s->img_size
,
727 'oi_timestamp' => $dbw->timestamp($s->img_timestamp
),
728 'oi_description' => $s->img_description
,
729 'oi_user' => $s->img_user
,
730 'oi_user_text' => $s->img_user_text
734 # Update the current image row
735 $dbw->update( 'image',
738 'img_timestamp' => $dbw->timestamp(),
739 'img_user' => $wgUser->getID(),
740 'img_user_text' => $wgUser->getName(),
741 'img_description' => $desc,
742 ), array( /* WHERE */
747 # Invalidate the cache for the description page
748 $descTitle->invalidateCache();
751 $log = new LogPage( 'upload' );
752 $log->addEntry( 'upload', $descTitle, $desc );
756 * Returns the image URL of an image's old version
758 * @param string $fname file name of the image file
759 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
762 function wfImageArchiveUrl( $name, $subdir='archive' )
764 global $wgUploadPath, $wgHashedUploadDirectory;
766 if ($wgHashedUploadDirectory) {
767 $hash = md5( substr( $name, 15) );
768 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
769 substr( $hash, 0, 2 ) . '/'.$name;
771 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
773 return wfUrlencode($url);
777 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
778 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
780 * @param string $length
781 * @return int Length in pixels
783 function scaleSVGUnit( $length ) {
784 static $unitLength = array(
791 '' => 1.0, // "User units" pixels by default
792 '%' => 2.0, // Fake it!
794 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
795 $length = FloatVal( $matches[1] );
797 return round( $length * $unitLength[$unit] );
800 return round( FloatVal( $length ) );
805 * Compatible with PHP getimagesize()
806 * @todo support gzipped SVGZ
807 * @todo check XML more carefully
808 * @todo sensible defaults
810 * @param string $filename
813 function getSVGsize( $filename ) {
817 // Read a chunk of the file
818 $f = fopen( $filename, "rt" );
819 if( !$f ) return false;
820 $chunk = fread( $f, 4096 );
823 // Uber-crappy hack! Run through a real XML parser.
824 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
828 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
829 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
831 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
832 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
835 return array( $width, $height, 'SVG',
836 "width=\"$width\" height=\"$height\"" );