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 )
44 global $wgUseSharedUploads, $wgUseLatin1, $wgSharedLatin1, $wgLang;
47 $this->title
= Title
::makeTitleSafe( NS_IMAGE
, $this->name
);
48 $this->fromSharedDirectory
= false;
49 $this->imagePath
= $this->getFullPath();
50 $this->fileExists
= file_exists( $this->imagePath
);
52 # If the file is not found, and a shared upload directory
53 # like the Wikimedia Commons is used, look for it there.
54 if (!$this->fileExists
&& $wgUseSharedUploads) {
56 # In case we're on a wgCapitalLinks=false wiki, we
57 # capitalize the first letter of the filename before
58 # looking it up in the shared repository.
59 $this->name
= $wgLang->ucfirst($name);
61 # Encode the filename if we're on a Latin1 wiki and the
62 # shared repository is UTF-8
63 if($wgUseLatin1 && !$wgSharedLatin1) {
64 $this->name
= utf8_encode($name);
67 $this->imagePath
= $this->getFullPath(true);
68 $this->fileExists
= file_exists( $this->imagePath
);
69 $this->fromSharedDirectory
= true;
73 if($this->fileExists
) {
74 $this->url
= $this->wfImageUrl( $this->name
, $this->fromSharedDirectory
);
79 $n = strrpos( $name, '.' );
80 $this->extension
= strtolower( $n ?
substr( $name, $n +
1 ) : '' );
83 if ( $this->fileExists
)
85 if( $this->extension
== 'svg' ) {
86 @$gis = getSVGsize( $this->imagePath
);
88 @$gis = getimagesize( $this->imagePath
);
90 if( $gis !== false ) {
91 $this->width
= $gis[0];
92 $this->height
= $gis[1];
93 $this->type
= $gis[2];
94 $this->attr
= $gis[3];
95 if ( isset( $gis['bits'] ) ) {
96 $this->bits
= $gis['bits'];
102 $this->historyLine
= 0;
108 * Create a new image object from a title object.
110 * @param Title $nt Title object. Must be from namespace "image"
113 function newFromTitle( $nt )
115 $img = new Image( $nt->getDBKey() );
121 * Return the name of this image
130 * Return the associated title object
139 * Return the URL of the image file
147 function getViewURL() {
148 if( $this->mustRender() ) {
149 return $this->createThumb( $this->getWidth() );
151 return $this->getURL();
156 * Return the image path of the image in the
157 * local file system as an absolute path
160 function getImagePath()
162 return $this->imagePath
;
166 * Return the width of the image
168 * Returns -1 if the file specified is not a known image type
177 * Return the height of the image
179 * Returns -1 if the file specified is not a known image type
184 return $this->height
;
188 * Return the size of the image file, in bytes
193 $st = stat( $this->getImagePath() );
198 * Return the type of the image
212 * Return the escapeLocalURL of this image
215 function getEscapeLocalURL()
217 return $this->title
->escapeLocalURL();
221 * Return the escapeFullURL of this image
224 function getEscapeFullURL()
226 return $this->title
->escapeFullURL();
230 * Return the URL of an image, provided its name.
232 * @param string $name Name of the image, without the leading "Image:"
233 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
236 function wfImageUrl( $name, $fromSharedDirectory = false )
238 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
239 if($fromSharedDirectory) {
241 $path = $wgSharedUploadPath;
243 $base = $wgUploadBaseUrl;
244 $path = $wgUploadPath;
246 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
247 return wfUrlencode( $url );
251 * Returns true iff the image file exists on disk.
257 return $this->fileExists
;
264 function thumbUrl( $width, $subdir='thumb') {
265 global $wgUploadPath, $wgUploadBaseUrl,
266 $wgSharedUploadPath,$wgSharedUploadDirectory,
267 $wgUseLatin1,$wgSharedLatin1;
268 $name = $this->thumbName( $width );
269 if($this->fromSharedDirectory
) {
271 $path = $wgSharedUploadPath;
272 if($wgUseLatin1 && !$wgSharedLatin1) {
273 $name=utf8_encode($name);
276 $base = $wgUploadBaseUrl;
277 $path = $wgUploadPath;
279 $url = "{$base}{$path}/{$subdir}" .
280 wfGetHashPath($name, $this->fromSharedDirectory
)
282 return wfUrlencode($url);
286 * Return the file name of a thumbnail of the specified width
288 * @param integer $width Width of the thumbnail image
289 * @param boolean $shared Does the thumbnail come from the shared repository?
292 function thumbName( $width, $shared=false ) {
293 global $wgUseLatin1,$wgSharedLatin1;
294 $thumb = $width."px-".$this->name
;
295 if( $this->extension
== 'svg' ) {
296 # Rasterize SVG vector images to PNG
299 if( $shared && $wgUseLatin1 && !$wgSharedLatin1) {
300 $thumb=utf8_encode($thumb);
306 * Create a thumbnail of the image having the specified width/height.
307 * The thumbnail will not be created if the width is larger than the
308 * image's width. Let the browser do the scaling in this case.
309 * The thumbnail is stored on disk and is only computed if the thumbnail
310 * file does not exist OR if it is older than the image.
313 * Keeps aspect ratio of original image. If both width and height are
314 * specified, the generated image will be no bigger than width x height,
315 * and will also have correct aspect ratio.
317 * @param integer $width maximum width of the generated thumbnail
318 * @param integer $height maximum height of the image (optional)
321 function createThumb( $width, $height=-1 ) {
322 if ( $height == -1 ) {
323 return $this->renderThumb( $width );
325 if ( $width < $this->width
) {
326 $thumbheight = $this->height
* $width / $this->width
;
327 $thumbwidth = $width;
329 $thumbheight = $this->height
;
330 $thumbwidth = $this->width
;
332 if ( $thumbheight > $height ) {
333 $thumbwidth = $thumbwidth * $height / $thumbheight;
334 $thumbheight = $height;
336 return $this->renderThumb( $thumbwidth );
340 * Create a thumbnail of the image having the specified width.
341 * The thumbnail will not be created if the width is larger than the
342 * image's width. Let the browser do the scaling in this case.
343 * The thumbnail is stored on disk and is only computed if the thumbnail
344 * file does not exist OR if it is older than the image.
349 function /* private */ renderThumb( $width ) {
350 global $wgImageMagickConvertCommand;
351 global $wgUseImageMagick;
352 global $wgUseSquid, $wgInternalServer;
354 $width = IntVal( $width );
356 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
357 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).'/'.$thumbName;
358 $thumbUrl = $this->thumbUrl( $width );
359 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
360 if ( ! $this->exists() )
362 # If there is no image, there will be no thumbnail
366 # Sanity check $width
372 if( $width > $this->width
&& !$this->mustRender() ) {
373 # Don't make an image bigger than the source
374 return $this->getViewURL();
377 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
378 if( $this->extension
== 'svg' ) {
379 global $wgSVGConverters, $wgSVGConverter;
380 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
381 global $wgSVGConverterPath;
383 array( '$path/', '$width', '$input', '$output' ),
384 array( $wgSVGConverterPath,
386 escapeshellarg( $this->imagePath
),
387 escapeshellarg( $thumbPath ) ),
388 $wgSVGConverters[$wgSVGConverter] );
389 $conv = shell_exec( $cmd );
393 } elseif ( $wgUseImageMagick ) {
395 # Specify white background color, will be used for transparent images
396 # in Internet Explorer/Windows instead of default black.
397 $cmd = $wgImageMagickConvertCommand .
398 " -quality 85 -background white -geometry {$width} ".
399 escapeshellarg($this->imagePath
) . " " .
400 escapeshellarg($thumbPath);
401 $conv = shell_exec( $cmd );
403 # Use PHP's builtin GD library functions.
405 # First find out what kind of file this is, and select the correct
406 # input routine for this.
410 switch( $this->type
) {
412 $src_image = imagecreatefromgif( $this->imagePath
);
415 $src_image = imagecreatefromjpeg( $this->imagePath
);
419 $src_image = imagecreatefrompng( $this->imagePath
);
420 $truecolor = ( $this->bits
> 8 );
422 case 15: # WBMP for WML
423 $src_image = imagecreatefromwbmp( $this->imagePath
);
426 $src_image = imagecreatefromxbm( $this->imagePath
);
429 return 'Image type not supported';
432 $height = floor( $this->height
* ( $width/$this->width
) );
434 $dst_image = imagecreatetruecolor( $width, $height );
436 $dst_image = imagecreate( $width, $height );
438 imagecopyresampled( $dst_image, $src_image,
440 $width, $height, $this->width
, $this->height
);
441 switch( $this->type
) {
446 #$thumbUrl .= ".png";
447 #$thumbPath .= ".png";
448 imagepng( $dst_image, $thumbPath );
451 #$thumbUrl .= ".jpg";
452 #$thumbPath .= ".jpg";
453 imageinterlace( $dst_image );
454 imagejpeg( $dst_image, $thumbPath, 95 );
459 imagedestroy( $dst_image );
460 imagedestroy( $src_image );
465 # Check for zero-sized thumbnails. Those can be generated when
466 # no disk space is available or some other error occurs
468 $thumbstat = stat( $thumbPath );
469 if( $thumbstat['size'] == 0 )
471 unlink( $thumbPath );
475 # This has to be done after the image is updated and present for all machines on NFS,
476 # or else the old version might be stored into the squid again
479 $wgInternalServer.$thumbUrl
481 wfPurgeSquidServers($urlArr);
485 } // END OF function createThumb
488 * Return the image history of this image, line by line.
489 * starts with current version, then old versions.
490 * uses $this->historyLine to check which line to return:
491 * 0 return line for current version
492 * 1 query for old versions, return first one
493 * 2, ... return next old version from above query
497 function nextHistoryLine()
499 $fname = 'Image::nextHistoryLine()';
500 $dbr =& wfGetDB( DB_SLAVE
);
501 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
502 $this->historyRes
= $dbr->select( 'image',
503 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
504 array( 'img_name' => $this->title
->getDBkey() ),
507 if ( 0 == wfNumRows( $this->historyRes
) ) {
510 } else if ( $this->historyLine
== 1 ) {
511 $this->historyRes
= $dbr->select( 'oldimage',
512 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
513 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
514 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
517 $this->historyLine ++
;
519 return $dbr->fetchObject( $this->historyRes
);
523 * Reset the history pointer to the first element of the history
526 function resetHistory()
528 $this->historyLine
= 0;
532 * Return true if the file is of a type that can't be directly
533 * rendered by typical browsers and needs to be re-rasterized.
536 function mustRender() {
537 return ( $this->extension
== 'svg' );
541 * Return the full filesystem path to the file. Note that this does
542 * not mean that a file actually exists under that location.
544 * This path depends on whether directory hashing is active or not,
545 * i.e. whether the images are all found in the same directory,
546 * or in hashed paths like /images/3/3c.
549 * @param boolean $fromSharedDirectory Return the path to the file
550 * in a shared repository (see $wgUseSharedRepository and related
551 * options in DefaultSettings.php) instead of a local one.
554 function getFullPath( $fromSharedRepository = false )
556 global $wgUploadDirectory, $wgSharedUploadDirectory;
558 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
560 $ishashed = $fromSharedRepository ?
$wgHashedSharedUploadDirectory :
561 $wgHashedUploadDirectory;
563 $fullpath = $dir . wfGetHashPath($name) . $name;
572 * Returns the image directory of an image
573 * If the directory does not exist, it is created.
574 * The result is an absolute path.
576 * @param string $fname file name of the image file
579 function wfImageDir( $fname )
581 global $wgUploadDirectory, $wgHashedUploadDirectory;
583 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
585 $hash = md5( $fname );
586 $oldumask = umask(0);
587 $dest = $wgUploadDirectory . '/' . $hash{0};
588 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
589 $dest .= '/' . substr( $hash, 0, 2 );
590 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
597 * Returns the image directory of an image's thubnail
598 * If the directory does not exist, it is created.
599 * The result is an absolute path.
601 * @param string $fname file name of the thumbnail file, including file size prefix
602 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
603 * @param boolean $shared (optional) use the shared upload directory
606 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
608 return wfImageArchiveDir( $fname, $subdir, $shared );
612 * Returns the image directory of an image's old version
613 * If the directory does not exist, it is created.
614 * The result is an absolute path.
616 * @param string $fname file name of the thumbnail file, including file size prefix
617 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
618 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
621 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
623 global $wgUploadDirectory, $wgHashedUploadDirectory,
624 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
625 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
626 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
627 if (!$hashdir) { return $dir.'/'.$subdir; }
628 $hash = md5( $fname );
629 $oldumask = umask(0);
630 # Suppress warning messages here; if the file itself can't
631 # be written we'll worry about it then.
632 $archive = $dir.'/'.$subdir;
633 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
634 $archive .= '/' . $hash{0};
635 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
636 $archive .= '/' . substr( $hash, 0, 2 );
637 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
645 * Return the hash path component of an image path (URL or filesystem),
646 * e.g. "/3/3c/", or just "/" if hashing is not used.
648 * @param $dbkey The filesystem / database name of the file
649 * @param $fromSharedDirectory Use the shared file repository? It may
650 * use different hash settings from the local one.
652 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
653 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
655 $ishashed = $fromSharedDirectory ?
$wgHashedSharedUploadDirectory :
656 $wgSharedUploadDirectory;
659 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . "/";
667 * Record an image upload in the upload log.
669 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
671 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
672 global $wgUseCopyrightUpload;
674 $fname = 'wfRecordUpload';
675 $dbw =& wfGetDB( DB_MASTER
);
677 # img_name must be unique
678 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
679 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
683 $now = wfTimestampNow();
684 $won = wfInvertTimestamp( $now );
685 $size = IntVal( $size );
687 if ( $wgUseCopyrightUpload )
689 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
690 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
691 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
693 else $textdesc = $desc ;
695 $now = wfTimestampNow();
696 $won = wfInvertTimestamp( $now );
698 # Test to see if the row exists using INSERT IGNORE
699 # This avoids race conditions by locking the row until the commit, and also
700 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
701 $dbw->insert( 'image',
705 'img_timestamp' => $dbw->timestamp($now),
706 'img_description' => $desc,
707 'img_user' => $wgUser->getID(),
708 'img_user_text' => $wgUser->getName(),
711 $descTitle = Title
::makeTitleSafe( NS_IMAGE
, $name );
713 if ( $dbw->affectedRows() ) {
714 # Successfully inserted, this is a new image
715 $id = $descTitle->getArticleID();
718 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
722 'cur_namespace' => NS_IMAGE
,
723 'cur_title' => $name,
724 'cur_comment' => $desc,
725 'cur_user' => $wgUser->getID(),
726 'cur_user_text' => $wgUser->getName(),
727 'cur_timestamp' => $dbw->timestamp($now),
729 'cur_text' => $textdesc,
730 'inverse_timestamp' => $won,
731 'cur_touched' => $dbw->timestamp($now)
734 $id = $dbw->insertId() or 0; # We should throw an error instead
736 RecentChange
::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
738 $u = new SearchUpdate( $id, $name, $desc );
742 # Collision, this is an update of an image
743 # Get current image row for update
744 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
745 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
747 # Insert it into oldimage
748 $dbw->insert( 'oldimage',
750 'oi_name' => $s->img_name
,
751 'oi_archive_name' => $oldver,
752 'oi_size' => $s->img_size
,
753 'oi_timestamp' => $dbw->timestamp($s->img_timestamp
),
754 'oi_description' => $s->img_description
,
755 'oi_user' => $s->img_user
,
756 'oi_user_text' => $s->img_user_text
760 # Update the current image row
761 $dbw->update( 'image',
764 'img_timestamp' => $dbw->timestamp(),
765 'img_user' => $wgUser->getID(),
766 'img_user_text' => $wgUser->getName(),
767 'img_description' => $desc,
768 ), array( /* WHERE */
773 # Invalidate the cache for the description page
774 $descTitle->invalidateCache();
777 $log = new LogPage( 'upload' );
778 $log->addEntry( 'upload', $descTitle, $desc );
782 * Returns the image URL of an image's old version
784 * @param string $fname file name of the image file
785 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
788 function wfImageArchiveUrl( $name, $subdir='archive' )
790 global $wgUploadPath, $wgHashedUploadDirectory;
792 if ($wgHashedUploadDirectory) {
793 $hash = md5( substr( $name, 15) );
794 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
795 substr( $hash, 0, 2 ) . '/'.$name;
797 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
799 return wfUrlencode($url);
803 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
804 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
806 * @param string $length
807 * @return int Length in pixels
809 function scaleSVGUnit( $length ) {
810 static $unitLength = array(
817 '' => 1.0, // "User units" pixels by default
818 '%' => 2.0, // Fake it!
820 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
821 $length = FloatVal( $matches[1] );
823 return round( $length * $unitLength[$unit] );
826 return round( FloatVal( $length ) );
831 * Compatible with PHP getimagesize()
832 * @todo support gzipped SVGZ
833 * @todo check XML more carefully
834 * @todo sensible defaults
836 * @param string $filename
839 function getSVGsize( $filename ) {
843 // Read a chunk of the file
844 $f = fopen( $filename, "rt" );
845 if( !$f ) return false;
846 $chunk = fread( $f, 4096 );
849 // Uber-crappy hack! Run through a real XML parser.
850 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
854 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
855 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
857 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
858 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
861 return array( $width, $height, 'SVG',
862 "width=\"$width\" height=\"$height\"" );