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 $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;
46 $this->title
= Title
::makeTitleSafe( NS_IMAGE
, $this->name
);
47 //$this->imagePath = wfImagePath( $name );
48 if ($wgHashedUploadDirectory) {
49 $hash = md5( $this->title
->getDBkey() );
50 $this->imagePath
= $wgUploadDirectory . '/' . $hash{0} . '/' .
51 substr( $hash, 0, 2 ) . "/{$name}";
53 $this->imagePath
= $wgUploadDirectory . '/' . $name;
56 $this->url
= $this->wfImageUrl( $name );
58 $n = strrpos( $name, '.' );
59 $this->extension
= strtolower( $n ?
substr( $name, $n +
1 ) : '' );
61 if ( $this->fileExists
= file_exists( $this->imagePath
) ) // Sic!, "=" is intended
63 if( $this->extension
== 'svg' ) {
64 @$gis = getSVGsize( $this->imagePath
);
66 @$gis = getimagesize( $this->imagePath
);
68 if( $gis !== false ) {
69 $this->width
= $gis[0];
70 $this->height
= $gis[1];
71 $this->type
= $gis[2];
72 $this->attr
= $gis[3];
73 if ( isset( $gis['bits'] ) ) {
74 $this->bits
= $gis['bits'];
80 $this->historyLine
= 0;
86 * Create a new image object from a title object.
88 * @param Title $nt Title object. Must be from namespace "image"
91 function newFromTitle( $nt )
93 $img = new Image( $nt->getDBKey() );
99 * Return the name of this image
108 * Return the associated title object
117 * Return the URL of the image file
125 function getViewURL() {
126 if( $this->mustRender() ) {
127 return $this->createThumb( $this->getWidth() );
129 return $this->getURL();
134 * Return the image path of the image in the
135 * local file system as an absolute path
138 function getImagePath()
140 return $this->imagePath
;
144 * Return the width of the image
146 * Returns -1 if the file specified is not a known image type
155 * Return the height of the image
157 * Returns -1 if the file specified is not a known image type
162 return $this->height
;
166 * Return the size of the image file, in bytes
171 $st = stat( $this->getImagePath() );
176 * Return the type of the image
190 * Return the escapeLocalURL of this image
193 function getEscapeLocalURL()
195 return $this->title
->escapeLocalURL();
199 * Return the URL of an image, provided its name.
201 * @param string $name Name of the image, without the leading Image:
204 function wfImageUrl( $name )
206 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory;
207 if ($wgHashedUploadDirectory) {
208 $hash = md5( $name );
209 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/" . $hash{0} . "/" .
210 substr( $hash, 0, 2 ) . "/{$name}";
212 $url = "{$wgUploadBaseUrl}{$wgUploadPath}/{$name}";
214 return wfUrlencode( $url );
218 * Returns true iff the image file exists on disk.
224 return $this->fileExists
;
231 function thumbUrl( $width, $subdir='thumb' ) {
232 global $wgUploadPath,$wgHashedUploadDirectory;
233 $name = $this->thumbName( $width );
234 if ($wgHashedUploadDirectory) {
235 $hash = md5( $name );
236 $url = "{$wgUploadPath}/{$subdir}/" . $hash{0} . "/" .
237 substr( $hash, 0, 2 ) . "/{$name}";
239 $url = "{$wgUploadPath}/{$subdir}/{$name}";
242 return wfUrlencode($url);
246 * Return the file name of a thumbnail of the specified width
248 * @param integer $width Width of the thumbnail image
251 function thumbName( $width ) {
252 $thumb = $width."px-".$this->name
;
253 if( $this->extension
== 'svg' ) {
254 # Rasterize SVG vector images to PNG
261 * Create a thumbnail of the image having the specified width/height.
262 * The thumbnail will not be created if the width is larger than the
263 * image's width. Let the browser do the scaling in this case.
264 * The thumbnail is stored on disk and is only computed if the thumbnail
265 * file does not exist OR if it is older than the image.
268 * Keeps aspect ratio of original image. If both width and height are
269 * specified, the generated image will be no bigger than width x height,
270 * and will also have correct aspect ratio.
272 * @param integer $width maximum width of the generated thumbnail
273 * @param integer $height maximum height of the image (optional)
276 function createThumb( $width, $height=-1 ) {
277 if ( $height == -1 ) {
278 return $this->renderThumb( $width );
280 if ( $width < $this->width
) {
281 $thumbheight = $this->height
* $width / $this->width
;
282 $thumbwidth = $width;
284 $thumbheight = $this->height
;
285 $thumbwidth = $this->width
;
287 if ( $thumbheight > $height ) {
288 $thumbwidth = $thumbwidth * $height / $thumbheight;
289 $thumbheight = $height;
291 return $this->renderThumb( $thumbwidth );
295 * Create a thumbnail of the image having the specified width.
296 * The thumbnail will not be created if the width is larger than the
297 * image's width. Let the browser do the scaling in this case.
298 * The thumbnail is stored on disk and is only computed if the thumbnail
299 * file does not exist OR if it is older than the image.
304 function /* private */ renderThumb( $width ) {
305 global $wgUploadDirectory;
306 global $wgImageMagickConvertCommand;
307 global $wgUseImageMagick;
308 global $wgUseSquid, $wgInternalServer;
310 $width = IntVal( $width );
312 $thumbName = $this->thumbName( $width );
313 $thumbPath = wfImageThumbDir( $thumbName ).'/'.$thumbName;
314 $thumbUrl = $this->thumbUrl( $width );
316 if ( ! $this->exists() )
318 # If there is no image, there will be no thumbnail
322 # Sanity check $width
328 if( $width > $this->width
&& !$this->mustRender() ) {
329 # Don't make an image bigger than the source
330 return $this->getViewURL();
333 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
334 if( $this->extension
== 'svg' ) {
335 global $wgSVGConverters, $wgSVGConverter;
336 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
337 global $wgSVGConverterPath;
339 array( '$path/', '$width', '$input', '$output' ),
340 array( $wgSVGConverterPath,
342 escapeshellarg( $this->imagePath
),
343 escapeshellarg( $thumbPath ) ),
344 $wgSVGConverters[$wgSVGConverter] );
345 $conv = shell_exec( $cmd );
349 } elseif ( $wgUseImageMagick ) {
351 # Specify white background color, will be used for transparent images
352 # in Internet Explorer/Windows instead of default black.
353 $cmd = $wgImageMagickConvertCommand .
354 " -quality 85 -background white -geometry {$width} ".
355 escapeshellarg($this->imagePath
) . " " .
356 escapeshellarg($thumbPath);
357 $conv = shell_exec( $cmd );
359 # Use PHP's builtin GD library functions.
361 # First find out what kind of file this is, and select the correct
362 # input routine for this.
366 switch( $this->type
) {
368 $src_image = imagecreatefromgif( $this->imagePath
);
371 $src_image = imagecreatefromjpeg( $this->imagePath
);
375 $src_image = imagecreatefrompng( $this->imagePath
);
376 $truecolor = ( $this->bits
> 8 );
378 case 15: # WBMP for WML
379 $src_image = imagecreatefromwbmp( $this->imagePath
);
382 $src_image = imagecreatefromxbm( $this->imagePath
);
385 return 'Image type not supported';
388 $height = floor( $this->height
* ( $width/$this->width
) );
390 $dst_image = imagecreatetruecolor( $width, $height );
392 $dst_image = imagecreate( $width, $height );
394 imagecopyresampled( $dst_image, $src_image,
396 $width, $height, $this->width
, $this->height
);
397 switch( $this->type
) {
402 #$thumbUrl .= ".png";
403 #$thumbPath .= ".png";
404 imagepng( $dst_image, $thumbPath );
407 #$thumbUrl .= ".jpg";
408 #$thumbPath .= ".jpg";
409 imageinterlace( $dst_image );
410 imagejpeg( $dst_image, $thumbPath, 95 );
415 imagedestroy( $dst_image );
416 imagedestroy( $src_image );
421 # Check for zero-sized thumbnails. Those can be generated when
422 # no disk space is available or some other error occurs
424 $thumbstat = stat( $thumbPath );
425 if( $thumbstat['size'] == 0 )
427 unlink( $thumbPath );
431 # This has to be done after the image is updated and present for all machines on NFS,
432 # or else the old version might be stored into the squid again
435 $wgInternalServer.$thumbUrl
437 wfPurgeSquidServers($urlArr);
441 } // END OF function createThumb
444 * Return the image history of this image, line by line.
445 * starts with current version, then old versions.
446 * uses $this->historyLine to check which line to return:
447 * 0 return line for current version
448 * 1 query for old versions, return first one
449 * 2, ... return next old version from above query
453 function nextHistoryLine()
455 $fname = 'Image::nextHistoryLine()';
456 $dbr =& wfGetDB( DB_SLAVE
);
457 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
458 $this->historyRes
= $dbr->select( 'image',
459 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
460 array( 'img_name' => $this->title
->getDBkey() ),
463 if ( 0 == wfNumRows( $this->historyRes
) ) {
466 } else if ( $this->historyLine
== 1 ) {
467 $this->historyRes
= $dbr->select( 'oldimage',
468 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
469 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
470 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
473 $this->historyLine ++
;
475 return $dbr->fetchObject( $this->historyRes
);
479 * Reset the history pointer to the first element of the history
482 function resetHistory()
484 $this->historyLine
= 0;
488 * Return true if the file is of a type that can't be directly
489 * rendered by typical browsers and needs to be re-rasterized.
492 function mustRender() {
493 return ( $this->extension
== 'svg' );
500 * Returns the image directory of an image
501 * If the directory does not exist, it is created.
502 * The result is an absolute path.
504 * @param string $fname file name of the image file
507 function wfImageDir( $fname )
509 global $wgUploadDirectory, $wgHashedUploadDirectory;
511 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
513 $hash = md5( $fname );
514 $oldumask = umask(0);
515 $dest = $wgUploadDirectory . '/' . $hash{0};
516 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
517 $dest .= '/' . substr( $hash, 0, 2 );
518 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
525 * Returns the image directory of an image's thubnail
526 * If the directory does not exist, it is created.
527 * The result is an absolute path.
529 * @param string $fname file name of the thumbnail file, including file size prefix
530 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
533 function wfImageThumbDir( $fname , $subdir='thumb')
535 return wfImageArchiveDir( $fname, $subdir );
539 * Returns the image directory of an image's old version
540 * If the directory does not exist, it is created.
541 * The result is an absolute path.
543 * @param string $fname file name of the thumbnail file, including file size prefix
544 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
547 function wfImageArchiveDir( $fname , $subdir='archive')
549 global $wgUploadDirectory, $wgHashedUploadDirectory;
551 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory.'/'.$subdir; }
553 $hash = md5( $fname );
554 $oldumask = umask(0);
556 # Suppress warning messages here; if the file itself can't
557 # be written we'll worry about it then.
558 $archive = $wgUploadDirectory.'/'.$subdir;
559 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
560 $archive .= '/' . $hash{0};
561 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
562 $archive .= '/' . substr( $hash, 0, 2 );
563 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
570 * Record an image upload in the upload log.
572 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
574 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
575 global $wgUseCopyrightUpload;
577 $fname = 'wfRecordUpload';
578 $dbw =& wfGetDB( DB_MASTER
);
580 # img_name must be unique
581 if ( !$dbw->indexUnique( 'image', 'img_name' ) ) {
582 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
586 $now = wfTimestampNow();
587 $won = wfInvertTimestamp( $now );
588 $size = IntVal( $size );
590 if ( $wgUseCopyrightUpload )
592 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
593 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
594 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
596 else $textdesc = $desc ;
598 $now = wfTimestampNow();
599 $won = wfInvertTimestamp( $now );
601 # Test to see if the row exists using INSERT IGNORE
602 # This avoids race conditions by locking the row until the commit, and also
603 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
604 $dbw->insertArray( 'image',
608 'img_timestamp' => $dbw->timestamp($now),
609 'img_description' => $desc,
610 'img_user' => $wgUser->getID(),
611 'img_user_text' => $wgUser->getName(),
614 $descTitle = Title
::makeTitleSafe( NS_IMAGE
, $name );
616 if ( $dbw->affectedRows() ) {
617 # Successfully inserted, this is a new image
618 $id = $descTitle->getArticleID();
621 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
622 $dbw->insertArray( 'cur',
625 'cur_namespace' => NS_IMAGE
,
626 'cur_title' => $name,
627 'cur_comment' => $desc,
628 'cur_user' => $wgUser->getID(),
629 'cur_user_text' => $wgUser->getName(),
630 'cur_timestamp' => $dbw->timestamp($now),
632 'cur_text' => $textdesc,
633 'inverse_timestamp' => $won,
634 'cur_touched' => $dbw->timestamp($now)
637 $id = $dbw->insertId() or 0; # We should throw an error instead
639 RecentChange
::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
641 $u = new SearchUpdate( $id, $name, $desc );
645 # Collision, this is an update of an image
646 # Get current image row for update
647 $s = $dbw->getArray( 'image', array( 'img_name','img_size','img_timestamp','img_description',
648 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
650 # Insert it into oldimage
651 $dbw->insertArray( 'oldimage',
653 'oi_name' => $s->img_name
,
654 'oi_archive_name' => $oldver,
655 'oi_size' => $s->img_size
,
656 'oi_timestamp' => $dbw->timestamp($s->img_timestamp
),
657 'oi_description' => $s->img_description
,
658 'oi_user' => $s->img_user
,
659 'oi_user_text' => $s->img_user_text
663 # Update the current image row
664 $dbw->updateArray( 'image',
667 'img_timestamp' => $dbw->timestamp(),
668 'img_user' => $wgUser->getID(),
669 'img_user_text' => $wgUser->getName(),
670 'img_description' => $desc,
671 ), array( /* WHERE */
676 # Invalidate the cache for the description page
677 $descTitle->invalidateCache();
680 $log = new LogPage( 'upload' );
681 $log->addEntry( 'upload', $descTitle, $desc );
685 * Returns the image URL of an image's old version
687 * @param string $fname file name of the image file
688 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
691 function wfImageArchiveUrl( $name, $subdir='archive' )
693 global $wgUploadPath, $wgHashedUploadDirectory;
695 if ($wgHashedUploadDirectory) {
696 $hash = md5( substr( $name, 15) );
697 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
698 substr( $hash, 0, 2 ) . '/'.$name;
700 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
702 return wfUrlencode($url);
706 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
707 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
709 * @param string $length
710 * @return int Length in pixels
712 function scaleSVGUnit( $length ) {
713 static $unitLength = array(
720 '' => 1.0, // "User units" pixels by default
721 '%' => 2.0, // Fake it!
723 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
724 $length = FloatVal( $matches[1] );
726 return round( $length * $unitLength[$unit] );
729 return round( FloatVal( $length ) );
734 * Compatible with PHP getimagesize()
735 * @todo support gzipped SVGZ
736 * @todo check XML more carefully
737 * @todo sensible defaults
739 * @param string $filename
742 function getSVGsize( $filename ) {
746 // Read a chunk of the file
747 $f = fopen( $filename, "rt" );
748 if( !$f ) return false;
749 $chunk = fread( $f, 4096 );
752 // Uber-crappy hack! Run through a real XML parser.
753 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
757 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
758 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
760 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
761 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
764 return array( $width, $height, 'SVG',
765 "width=\"$width\" height=\"$height\"" );