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,$wgSharedUploadPath;
243 if($fromSharedDirectory) {
244 $hash = $wgHashedSharedUploadDirectory;
246 $path = $wgSharedUploadPath;
248 $hash = $wgHashedUploadDirectory;
249 $base = $wgUploadBaseUrl;
250 $path = $wgUploadPath;
253 $hash = md5( $name );
254 $url = "{$base}{$path}/" . $hash{0} . "/" .
255 substr( $hash, 0, 2 ) . "/{$name}";
257 $url = "{$base}{$path}/{$name}";
259 return wfUrlencode( $url );
263 * Returns true iff the image file exists on disk.
269 return $this->fileExists
;
276 function thumbUrl( $width, $subdir='thumb') {
277 global $wgUploadPath,$wgHashedUploadDirectory, $wgUploadBaseUrl,
278 $wgSharedUploadPath,$wgSharedUploadDirectory,
279 $wgHashedSharedUploadDirectory;
280 $name = $this->thumbName( $width );
281 if($this->fromSharedDirectory
) {
282 $hashdir = $wgHashedSharedUploadDirectory;
284 $path = $wgSharedUploadPath;
286 $hashdir = $wgHashedUploadDirectory;
287 $base = $wgUploadBaseUrl;
288 $path = $wgUploadPath;
291 $hash = md5( $name );
292 $url = "{$base}{$path}/{$subdir}/" . $hash{0} . "/" .
293 substr( $hash, 0, 2 ) . "/{$name}";
295 $url = "{$base}{$path}/{$subdir}/{$name}";
298 return wfUrlencode($url);
302 * Return the file name of a thumbnail of the specified width
304 * @param integer $width Width of the thumbnail image
307 function thumbName( $width ) {
308 $thumb = $width."px-".$this->name
;
309 if( $this->extension
== 'svg' ) {
310 # Rasterize SVG vector images to PNG
317 * Create a thumbnail of the image having the specified width/height.
318 * The thumbnail will not be created if the width is larger than the
319 * image's width. Let the browser do the scaling in this case.
320 * The thumbnail is stored on disk and is only computed if the thumbnail
321 * file does not exist OR if it is older than the image.
324 * Keeps aspect ratio of original image. If both width and height are
325 * specified, the generated image will be no bigger than width x height,
326 * and will also have correct aspect ratio.
328 * @param integer $width maximum width of the generated thumbnail
329 * @param integer $height maximum height of the image (optional)
332 function createThumb( $width, $height=-1 ) {
333 if ( $height == -1 ) {
334 return $this->renderThumb( $width );
336 if ( $width < $this->width
) {
337 $thumbheight = $this->height
* $width / $this->width
;
338 $thumbwidth = $width;
340 $thumbheight = $this->height
;
341 $thumbwidth = $this->width
;
343 if ( $thumbheight > $height ) {
344 $thumbwidth = $thumbwidth * $height / $thumbheight;
345 $thumbheight = $height;
347 return $this->renderThumb( $thumbwidth );
351 * Create a thumbnail of the image having the specified width.
352 * The thumbnail will not be created if the width is larger than the
353 * image's width. Let the browser do the scaling in this case.
354 * The thumbnail is stored on disk and is only computed if the thumbnail
355 * file does not exist OR if it is older than the image.
360 function /* private */ renderThumb( $width ) {
361 global $wgImageMagickConvertCommand;
362 global $wgUseImageMagick;
363 global $wgUseSquid, $wgInternalServer;
365 $width = IntVal( $width );
367 $thumbName = $this->thumbName( $width );
368 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).'/'.$thumbName;
369 $thumbUrl = $this->thumbUrl( $width );
370 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
371 if ( ! $this->exists() )
373 # If there is no image, there will be no thumbnail
377 # Sanity check $width
383 if( $width > $this->width
&& !$this->mustRender() ) {
384 # Don't make an image bigger than the source
385 return $this->getViewURL();
388 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
389 if( $this->extension
== 'svg' ) {
390 global $wgSVGConverters, $wgSVGConverter;
391 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
392 global $wgSVGConverterPath;
394 array( '$path/', '$width', '$input', '$output' ),
395 array( $wgSVGConverterPath,
397 escapeshellarg( $this->imagePath
),
398 escapeshellarg( $thumbPath ) ),
399 $wgSVGConverters[$wgSVGConverter] );
400 $conv = shell_exec( $cmd );
404 } elseif ( $wgUseImageMagick ) {
406 # Specify white background color, will be used for transparent images
407 # in Internet Explorer/Windows instead of default black.
408 $cmd = $wgImageMagickConvertCommand .
409 " -quality 85 -background white -geometry {$width} ".
410 escapeshellarg($this->imagePath
) . " " .
411 escapeshellarg($thumbPath);
412 $conv = shell_exec( $cmd );
414 # Use PHP's builtin GD library functions.
416 # First find out what kind of file this is, and select the correct
417 # input routine for this.
421 switch( $this->type
) {
423 $src_image = imagecreatefromgif( $this->imagePath
);
426 $src_image = imagecreatefromjpeg( $this->imagePath
);
430 $src_image = imagecreatefrompng( $this->imagePath
);
431 $truecolor = ( $this->bits
> 8 );
433 case 15: # WBMP for WML
434 $src_image = imagecreatefromwbmp( $this->imagePath
);
437 $src_image = imagecreatefromxbm( $this->imagePath
);
440 return 'Image type not supported';
443 $height = floor( $this->height
* ( $width/$this->width
) );
445 $dst_image = imagecreatetruecolor( $width, $height );
447 $dst_image = imagecreate( $width, $height );
449 imagecopyresampled( $dst_image, $src_image,
451 $width, $height, $this->width
, $this->height
);
452 switch( $this->type
) {
457 #$thumbUrl .= ".png";
458 #$thumbPath .= ".png";
459 imagepng( $dst_image, $thumbPath );
462 #$thumbUrl .= ".jpg";
463 #$thumbPath .= ".jpg";
464 imageinterlace( $dst_image );
465 imagejpeg( $dst_image, $thumbPath, 95 );
470 imagedestroy( $dst_image );
471 imagedestroy( $src_image );
476 # Check for zero-sized thumbnails. Those can be generated when
477 # no disk space is available or some other error occurs
479 $thumbstat = stat( $thumbPath );
480 if( $thumbstat['size'] == 0 )
482 unlink( $thumbPath );
486 # This has to be done after the image is updated and present for all machines on NFS,
487 # or else the old version might be stored into the squid again
490 $wgInternalServer.$thumbUrl
492 wfPurgeSquidServers($urlArr);
496 } // END OF function createThumb
499 * Return the image history of this image, line by line.
500 * starts with current version, then old versions.
501 * uses $this->historyLine to check which line to return:
502 * 0 return line for current version
503 * 1 query for old versions, return first one
504 * 2, ... return next old version from above query
508 function nextHistoryLine()
510 $fname = 'Image::nextHistoryLine()';
511 $dbr =& wfGetDB( DB_SLAVE
);
512 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
513 $this->historyRes
= $dbr->select( 'image',
514 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
515 array( 'img_name' => $this->title
->getDBkey() ),
518 if ( 0 == wfNumRows( $this->historyRes
) ) {
521 } else if ( $this->historyLine
== 1 ) {
522 $this->historyRes
= $dbr->select( 'oldimage',
523 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
524 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
525 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
528 $this->historyLine ++
;
530 return $dbr->fetchObject( $this->historyRes
);
534 * Reset the history pointer to the first element of the history
537 function resetHistory()
539 $this->historyLine
= 0;
543 * Return true if the file is of a type that can't be directly
544 * rendered by typical browsers and needs to be re-rasterized.
547 function mustRender() {
548 return ( $this->extension
== 'svg' );
555 * Returns the image directory of an image
556 * If the directory does not exist, it is created.
557 * The result is an absolute path.
559 * @param string $fname file name of the image file
562 function wfImageDir( $fname )
564 global $wgUploadDirectory, $wgHashedUploadDirectory;
566 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
568 $hash = md5( $fname );
569 $oldumask = umask(0);
570 $dest = $wgUploadDirectory . '/' . $hash{0};
571 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
572 $dest .= '/' . substr( $hash, 0, 2 );
573 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
580 * Returns the image directory of an image's thubnail
581 * If the directory does not exist, it is created.
582 * The result is an absolute path.
584 * @param string $fname file name of the thumbnail file, including file size prefix
585 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
586 * @param boolean $shared (optional) use the shared upload directory
589 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
591 return wfImageArchiveDir( $fname, $subdir, $shared );
595 * Returns the image directory of an image's old version
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 old version. Default is 'archive'
601 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
604 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
606 global $wgUploadDirectory, $wgHashedUploadDirectory,
607 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
608 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
609 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
610 if (!$hashdir) { return $dir.'/'.$subdir; }
612 $hash = md5( $fname );
613 $oldumask = umask(0);
614 # Suppress warning messages here; if the file itself can't
615 # be written we'll worry about it then.
616 $archive = $dir.'/'.$subdir;
617 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
618 $archive .= '/' . $hash{0};
619 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
620 $archive .= '/' . substr( $hash, 0, 2 );
621 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
628 * Record an image upload in the upload log.
630 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
632 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
633 global $wgUseCopyrightUpload;
635 $fname = 'wfRecordUpload';
636 $dbw =& wfGetDB( DB_MASTER
);
638 # img_name must be unique
639 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
640 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
644 $now = wfTimestampNow();
645 $won = wfInvertTimestamp( $now );
646 $size = IntVal( $size );
648 if ( $wgUseCopyrightUpload )
650 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
651 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
652 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
654 else $textdesc = $desc ;
656 $now = wfTimestampNow();
657 $won = wfInvertTimestamp( $now );
659 # Test to see if the row exists using INSERT IGNORE
660 # This avoids race conditions by locking the row until the commit, and also
661 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
662 $dbw->insert( 'image',
666 'img_timestamp' => $dbw->timestamp($now),
667 'img_description' => $desc,
668 'img_user' => $wgUser->getID(),
669 'img_user_text' => $wgUser->getName(),
672 $descTitle = Title
::makeTitleSafe( NS_IMAGE
, $name );
674 if ( $dbw->affectedRows() ) {
675 # Successfully inserted, this is a new image
676 $id = $descTitle->getArticleID();
679 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
683 'cur_namespace' => NS_IMAGE
,
684 'cur_title' => $name,
685 'cur_comment' => $desc,
686 'cur_user' => $wgUser->getID(),
687 'cur_user_text' => $wgUser->getName(),
688 'cur_timestamp' => $dbw->timestamp($now),
690 'cur_text' => $textdesc,
691 'inverse_timestamp' => $won,
692 'cur_touched' => $dbw->timestamp($now)
695 $id = $dbw->insertId() or 0; # We should throw an error instead
697 RecentChange
::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
699 $u = new SearchUpdate( $id, $name, $desc );
703 # Collision, this is an update of an image
704 # Get current image row for update
705 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
706 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
708 # Insert it into oldimage
709 $dbw->insert( 'oldimage',
711 'oi_name' => $s->img_name
,
712 'oi_archive_name' => $oldver,
713 'oi_size' => $s->img_size
,
714 'oi_timestamp' => $dbw->timestamp($s->img_timestamp
),
715 'oi_description' => $s->img_description
,
716 'oi_user' => $s->img_user
,
717 'oi_user_text' => $s->img_user_text
721 # Update the current image row
722 $dbw->update( 'image',
725 'img_timestamp' => $dbw->timestamp(),
726 'img_user' => $wgUser->getID(),
727 'img_user_text' => $wgUser->getName(),
728 'img_description' => $desc,
729 ), array( /* WHERE */
734 # Invalidate the cache for the description page
735 $descTitle->invalidateCache();
738 $log = new LogPage( 'upload' );
739 $log->addEntry( 'upload', $descTitle, $desc );
743 * Returns the image URL of an image's old version
745 * @param string $fname file name of the image file
746 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
749 function wfImageArchiveUrl( $name, $subdir='archive' )
751 global $wgUploadPath, $wgHashedUploadDirectory;
753 if ($wgHashedUploadDirectory) {
754 $hash = md5( substr( $name, 15) );
755 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
756 substr( $hash, 0, 2 ) . '/'.$name;
758 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
760 return wfUrlencode($url);
764 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
765 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
767 * @param string $length
768 * @return int Length in pixels
770 function scaleSVGUnit( $length ) {
771 static $unitLength = array(
778 '' => 1.0, // "User units" pixels by default
779 '%' => 2.0, // Fake it!
781 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
782 $length = FloatVal( $matches[1] );
784 return round( $length * $unitLength[$unit] );
787 return round( FloatVal( $length ) );
792 * Compatible with PHP getimagesize()
793 * @todo support gzipped SVGZ
794 * @todo check XML more carefully
795 * @todo sensible defaults
797 * @param string $filename
800 function getSVGsize( $filename ) {
804 // Read a chunk of the file
805 $f = fopen( $filename, "rt" );
806 if( !$f ) return false;
807 $chunk = fread( $f, 4096 );
810 // Uber-crappy hack! Run through a real XML parser.
811 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
815 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
816 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
818 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
819 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
822 return array( $width, $height, 'SVG',
823 "width=\"$width\" height=\"$height\"" );