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,$wgUseLatin1,
47 $wgSharedLatin1,$wgLang;
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}";
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;
77 $this->imagePath
= $wgSharedUploadDirectory . '/' . $sharedname;
79 $this->fileExists
= file_exists( $this->imagePath
);
80 $this->fromSharedDirectory
= true;
83 if($this->fileExists
) {
84 $this->url
= $this->wfImageUrl( $name, $this->fromSharedDirectory
);
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
);
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'];
112 $this->historyLine
= 0;
118 * Create a new image object from a title object.
120 * @param Title $nt Title object. Must be from namespace "image"
123 function newFromTitle( $nt )
125 $img = new Image( $nt->getDBKey() );
131 * Return the name of this image
140 * Return the associated title object
149 * Return the URL of the image file
157 function getViewURL() {
158 if( $this->mustRender() ) {
159 return $this->createThumb( $this->getWidth() );
161 return $this->getURL();
166 * Return the image path of the image in the
167 * local file system as an absolute path
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
187 * Return the height of the image
189 * Returns -1 if the file specified is not a known image type
194 return $this->height
;
198 * Return the size of the image file, in bytes
203 $st = stat( $this->getImagePath() );
208 * Return the type of the image
222 * Return the escapeLocalURL of this image
225 function getEscapeLocalURL()
227 return $this->title
->escapeLocalURL();
231 * Return the escapeFullURL of this image
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?
246 function wfImageUrl( $name, $fromSharedDirectory = false )
248 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory,
249 $wgHashedSharedUploadDirectory,$wgSharedUploadPath;
250 if($fromSharedDirectory) {
251 $hash = $wgHashedSharedUploadDirectory;
253 $path = $wgSharedUploadPath;
255 $hash = $wgHashedUploadDirectory;
256 $base = $wgUploadBaseUrl;
257 $path = $wgUploadPath;
260 $hash = md5( $name );
261 $url = "{$base}{$path}/" . $hash{0} . "/" .
262 substr( $hash, 0, 2 ) . "/{$name}";
264 $url = "{$base}{$path}/{$name}";
266 return wfUrlencode( $url );
270 * Returns true iff the image file exists on disk.
276 return $this->fileExists
;
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;
291 $path = $wgSharedUploadPath;
292 if($wgUseLatin1 && !$wgSharedLatin1) {
293 $name=utf8_encode($name);
296 $hashdir = $wgHashedUploadDirectory;
297 $base = $wgUploadBaseUrl;
298 $path = $wgUploadPath;
301 $hash = md5( $name );
302 $url = "{$base}{$path}/{$subdir}/" . $hash{0} . "/" .
303 substr( $hash, 0, 2 ) . "/{$name}";
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?
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
325 if( $shared && $wgUseLatin1 && !$wgSharedLatin1) {
326 $thumb=utf8_encode($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.
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)
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;
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.
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
392 # Sanity check $width
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;
409 array( '$path/', '$width', '$input', '$output' ),
410 array( $wgSVGConverterPath,
412 escapeshellarg( $this->imagePath
),
413 escapeshellarg( $thumbPath ) ),
414 $wgSVGConverters[$wgSVGConverter] );
415 $conv = shell_exec( $cmd );
419 } elseif ( $wgUseImageMagick ) {
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 );
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.
436 switch( $this->type
) {
438 $src_image = imagecreatefromgif( $this->imagePath
);
441 $src_image = imagecreatefromjpeg( $this->imagePath
);
445 $src_image = imagecreatefrompng( $this->imagePath
);
446 $truecolor = ( $this->bits
> 8 );
448 case 15: # WBMP for WML
449 $src_image = imagecreatefromwbmp( $this->imagePath
);
452 $src_image = imagecreatefromxbm( $this->imagePath
);
455 return 'Image type not supported';
458 $height = floor( $this->height
* ( $width/$this->width
) );
460 $dst_image = imagecreatetruecolor( $width, $height );
462 $dst_image = imagecreate( $width, $height );
464 imagecopyresampled( $dst_image, $src_image,
466 $width, $height, $this->width
, $this->height
);
467 switch( $this->type
) {
472 #$thumbUrl .= ".png";
473 #$thumbPath .= ".png";
474 imagepng( $dst_image, $thumbPath );
477 #$thumbUrl .= ".jpg";
478 #$thumbPath .= ".jpg";
479 imageinterlace( $dst_image );
480 imagejpeg( $dst_image, $thumbPath, 95 );
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 );
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
505 $wgInternalServer.$thumbUrl
507 wfPurgeSquidServers($urlArr);
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
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() ),
533 if ( 0 == wfNumRows( $this->historyRes
) ) {
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
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.
562 function mustRender() {
563 return ( $this->extension
== 'svg' );
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
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 ); }
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
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)
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 ); }
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',
680 'img_timestamp' => $dbw->timestamp($now),
681 'img_description' => $desc,
682 'img_user' => $wgUser->getID(),
683 'img_user_text' => $wgUser->getName(),
686 $descTitle = Title
::makeTitleSafe( NS_IMAGE
, $name );
688 if ( $dbw->affectedRows() ) {
689 # Successfully inserted, this is a new image
690 $id = $descTitle->getArticleID();
693 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
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),
704 'cur_text' => $textdesc,
705 'inverse_timestamp' => $won,
706 'cur_touched' => $dbw->timestamp($now)
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 );
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',
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
735 # Update the current image row
736 $dbw->update( 'image',
739 'img_timestamp' => $dbw->timestamp(),
740 'img_user' => $wgUser->getID(),
741 'img_user_text' => $wgUser->getName(),
742 'img_description' => $desc,
743 ), array( /* WHERE */
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'
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;
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(
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] );
798 return round( $length * $unitLength[$unit] );
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
814 function getSVGsize( $filename ) {
818 // Read a chunk of the file
819 $f = fopen( $filename, "rt" );
820 if( !$f ) return false;
821 $chunk = fread( $f, 4096 );
824 // Uber-crappy hack! Run through a real XML parser.
825 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
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\"" );