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) {
64 # in case we're running a capitallinks=false wiki
65 $sharedname=ucfirst($name);
67 if($wgHashedSharedUploadDirectory) {
68 $hash = md5( $this->title
->getDBkey() );
69 $this->imagePath
= $wgSharedUploadDirectory . '/' . $hash{0} . '/' .
70 substr( $hash, 0, 2 ) . "/".$sharedname;
72 $this->imagePath
= $wgSharedUploadDirectory . '/' . $sharedname;
74 $this->fileExists
= file_exists( $this->imagePath
);
75 $this->fromSharedDirectory
= true;
76 #wfDebug ("File from shared directory: ".$this->imagePath."\n");
78 if($this->fileExists
) {
79 $this->url
= $this->wfImageUrl( $name, $this->fromSharedDirectory
);
84 $n = strrpos( $name, '.' );
85 $this->extension
= strtolower( $n ?
substr( $name, $n +
1 ) : '' );
88 if ( $this->fileExists
)
90 if( $this->extension
== 'svg' ) {
91 @$gis = getSVGsize( $this->imagePath
);
93 @$gis = getimagesize( $this->imagePath
);
95 if( $gis !== false ) {
96 $this->width
= $gis[0];
97 $this->height
= $gis[1];
98 $this->type
= $gis[2];
99 $this->attr
= $gis[3];
100 if ( isset( $gis['bits'] ) ) {
101 $this->bits
= $gis['bits'];
107 $this->historyLine
= 0;
113 * Create a new image object from a title object.
115 * @param Title $nt Title object. Must be from namespace "image"
118 function newFromTitle( $nt )
120 $img = new Image( $nt->getDBKey() );
126 * Return the name of this image
135 * Return the associated title object
144 * Return the URL of the image file
152 function getViewURL() {
153 if( $this->mustRender() ) {
154 return $this->createThumb( $this->getWidth() );
156 return $this->getURL();
161 * Return the image path of the image in the
162 * local file system as an absolute path
165 function getImagePath()
167 return $this->imagePath
;
171 * Return the width of the image
173 * Returns -1 if the file specified is not a known image type
182 * Return the height of the image
184 * Returns -1 if the file specified is not a known image type
189 return $this->height
;
193 * Return the size of the image file, in bytes
198 $st = stat( $this->getImagePath() );
203 * Return the type of the image
217 * Return the escapeLocalURL of this image
220 function getEscapeLocalURL()
222 return $this->title
->escapeLocalURL();
226 * Return the escapeFullURL of this image
229 function getEscapeFullURL()
231 return $this->title
->escapeFullURL();
235 * Return the URL of an image, provided its name.
237 * @param string $name Name of the image, without the leading "Image:"
238 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
241 function wfImageUrl( $name, $fromSharedDirectory = false )
243 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory,
244 $wgHashedSharedUploadDirectory,$wgSharedUploadPath;
245 if($fromSharedDirectory) {
246 $hash = $wgHashedSharedUploadDirectory;
248 $path = $wgSharedUploadPath;
250 $hash = $wgHashedUploadDirectory;
251 $base = $wgUploadBaseUrl;
252 $path = $wgUploadPath;
255 $hash = md5( $name );
256 $url = "{$base}{$path}/" . $hash{0} . "/" .
257 substr( $hash, 0, 2 ) . "/{$name}";
259 $url = "{$base}{$path}/{$name}";
261 return wfUrlencode( $url );
265 * Returns true iff the image file exists on disk.
271 return $this->fileExists
;
278 function thumbUrl( $width, $subdir='thumb') {
279 global $wgUploadPath,$wgHashedUploadDirectory, $wgUploadBaseUrl,
280 $wgSharedUploadPath,$wgSharedUploadDirectory,
281 $wgHashedSharedUploadDirectory;
282 $name = $this->thumbName( $width );
283 if($this->fromSharedDirectory
) {
284 $hashdir = $wgHashedSharedUploadDirectory;
286 $path = $wgSharedUploadPath;
288 $hashdir = $wgHashedUploadDirectory;
289 $base = $wgUploadBaseUrl;
290 $path = $wgUploadPath;
293 $hash = md5( $name );
294 $url = "{$base}{$path}/{$subdir}/" . $hash{0} . "/" .
295 substr( $hash, 0, 2 ) . "/{$name}";
297 $url = "{$base}{$path}/{$subdir}/{$name}";
300 return wfUrlencode($url);
304 * Return the file name of a thumbnail of the specified width
306 * @param integer $width Width of the thumbnail image
309 function thumbName( $width ) {
310 $thumb = $width."px-".$this->name
;
311 if( $this->extension
== 'svg' ) {
312 # Rasterize SVG vector images to PNG
319 * Create a thumbnail of the image having the specified width/height.
320 * The thumbnail will not be created if the width is larger than the
321 * image's width. Let the browser do the scaling in this case.
322 * The thumbnail is stored on disk and is only computed if the thumbnail
323 * file does not exist OR if it is older than the image.
326 * Keeps aspect ratio of original image. If both width and height are
327 * specified, the generated image will be no bigger than width x height,
328 * and will also have correct aspect ratio.
330 * @param integer $width maximum width of the generated thumbnail
331 * @param integer $height maximum height of the image (optional)
334 function createThumb( $width, $height=-1 ) {
335 if ( $height == -1 ) {
336 return $this->renderThumb( $width );
338 if ( $width < $this->width
) {
339 $thumbheight = $this->height
* $width / $this->width
;
340 $thumbwidth = $width;
342 $thumbheight = $this->height
;
343 $thumbwidth = $this->width
;
345 if ( $thumbheight > $height ) {
346 $thumbwidth = $thumbwidth * $height / $thumbheight;
347 $thumbheight = $height;
349 return $this->renderThumb( $thumbwidth );
353 * Create a thumbnail of the image having the specified width.
354 * The thumbnail will not be created if the width is larger than the
355 * image's width. Let the browser do the scaling in this case.
356 * The thumbnail is stored on disk and is only computed if the thumbnail
357 * file does not exist OR if it is older than the image.
362 function /* private */ renderThumb( $width ) {
363 global $wgImageMagickConvertCommand;
364 global $wgUseImageMagick;
365 global $wgUseSquid, $wgInternalServer;
367 $width = IntVal( $width );
369 $thumbName = $this->thumbName( $width );
370 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).'/'.$thumbName;
371 $thumbUrl = $this->thumbUrl( $width );
372 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
373 if ( ! $this->exists() )
375 # If there is no image, there will be no thumbnail
379 # Sanity check $width
385 if( $width > $this->width
&& !$this->mustRender() ) {
386 # Don't make an image bigger than the source
387 return $this->getViewURL();
390 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
391 if( $this->extension
== 'svg' ) {
392 global $wgSVGConverters, $wgSVGConverter;
393 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
394 global $wgSVGConverterPath;
396 array( '$path/', '$width', '$input', '$output' ),
397 array( $wgSVGConverterPath,
399 escapeshellarg( $this->imagePath
),
400 escapeshellarg( $thumbPath ) ),
401 $wgSVGConverters[$wgSVGConverter] );
402 $conv = shell_exec( $cmd );
406 } elseif ( $wgUseImageMagick ) {
408 # Specify white background color, will be used for transparent images
409 # in Internet Explorer/Windows instead of default black.
410 $cmd = $wgImageMagickConvertCommand .
411 " -quality 85 -background white -geometry {$width} ".
412 escapeshellarg($this->imagePath
) . " " .
413 escapeshellarg($thumbPath);
414 $conv = shell_exec( $cmd );
416 # Use PHP's builtin GD library functions.
418 # First find out what kind of file this is, and select the correct
419 # input routine for this.
423 switch( $this->type
) {
425 $src_image = imagecreatefromgif( $this->imagePath
);
428 $src_image = imagecreatefromjpeg( $this->imagePath
);
432 $src_image = imagecreatefrompng( $this->imagePath
);
433 $truecolor = ( $this->bits
> 8 );
435 case 15: # WBMP for WML
436 $src_image = imagecreatefromwbmp( $this->imagePath
);
439 $src_image = imagecreatefromxbm( $this->imagePath
);
442 return 'Image type not supported';
445 $height = floor( $this->height
* ( $width/$this->width
) );
447 $dst_image = imagecreatetruecolor( $width, $height );
449 $dst_image = imagecreate( $width, $height );
451 imagecopyresampled( $dst_image, $src_image,
453 $width, $height, $this->width
, $this->height
);
454 switch( $this->type
) {
459 #$thumbUrl .= ".png";
460 #$thumbPath .= ".png";
461 imagepng( $dst_image, $thumbPath );
464 #$thumbUrl .= ".jpg";
465 #$thumbPath .= ".jpg";
466 imageinterlace( $dst_image );
467 imagejpeg( $dst_image, $thumbPath, 95 );
472 imagedestroy( $dst_image );
473 imagedestroy( $src_image );
478 # Check for zero-sized thumbnails. Those can be generated when
479 # no disk space is available or some other error occurs
481 $thumbstat = stat( $thumbPath );
482 if( $thumbstat['size'] == 0 )
484 unlink( $thumbPath );
488 # This has to be done after the image is updated and present for all machines on NFS,
489 # or else the old version might be stored into the squid again
492 $wgInternalServer.$thumbUrl
494 wfPurgeSquidServers($urlArr);
498 } // END OF function createThumb
501 * Return the image history of this image, line by line.
502 * starts with current version, then old versions.
503 * uses $this->historyLine to check which line to return:
504 * 0 return line for current version
505 * 1 query for old versions, return first one
506 * 2, ... return next old version from above query
510 function nextHistoryLine()
512 $fname = 'Image::nextHistoryLine()';
513 $dbr =& wfGetDB( DB_SLAVE
);
514 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
515 $this->historyRes
= $dbr->select( 'image',
516 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
517 array( 'img_name' => $this->title
->getDBkey() ),
520 if ( 0 == wfNumRows( $this->historyRes
) ) {
523 } else if ( $this->historyLine
== 1 ) {
524 $this->historyRes
= $dbr->select( 'oldimage',
525 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
526 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
527 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
530 $this->historyLine ++
;
532 return $dbr->fetchObject( $this->historyRes
);
536 * Reset the history pointer to the first element of the history
539 function resetHistory()
541 $this->historyLine
= 0;
545 * Return true if the file is of a type that can't be directly
546 * rendered by typical browsers and needs to be re-rasterized.
549 function mustRender() {
550 return ( $this->extension
== 'svg' );
557 * Returns the image directory of an image
558 * If the directory does not exist, it is created.
559 * The result is an absolute path.
561 * @param string $fname file name of the image file
564 function wfImageDir( $fname )
566 global $wgUploadDirectory, $wgHashedUploadDirectory;
568 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
570 $hash = md5( $fname );
571 $oldumask = umask(0);
572 $dest = $wgUploadDirectory . '/' . $hash{0};
573 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
574 $dest .= '/' . substr( $hash, 0, 2 );
575 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
582 * Returns the image directory of an image's thubnail
583 * If the directory does not exist, it is created.
584 * The result is an absolute path.
586 * @param string $fname file name of the thumbnail file, including file size prefix
587 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
588 * @param boolean $shared (optional) use the shared upload directory
591 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
593 return wfImageArchiveDir( $fname, $subdir, $shared );
597 * Returns the image directory of an image's old version
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 old version. Default is 'archive'
603 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
606 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
608 global $wgUploadDirectory, $wgHashedUploadDirectory,
609 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
610 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
611 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
612 if (!$hashdir) { return $dir.'/'.$subdir; }
614 $hash = md5( $fname );
615 $oldumask = umask(0);
616 # Suppress warning messages here; if the file itself can't
617 # be written we'll worry about it then.
618 $archive = $dir.'/'.$subdir;
619 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
620 $archive .= '/' . $hash{0};
621 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
622 $archive .= '/' . substr( $hash, 0, 2 );
623 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
630 * Record an image upload in the upload log.
632 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
634 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
635 global $wgUseCopyrightUpload;
637 $fname = 'wfRecordUpload';
638 $dbw =& wfGetDB( DB_MASTER
);
640 # img_name must be unique
641 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
642 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
646 $now = wfTimestampNow();
647 $won = wfInvertTimestamp( $now );
648 $size = IntVal( $size );
650 if ( $wgUseCopyrightUpload )
652 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
653 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
654 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
656 else $textdesc = $desc ;
658 $now = wfTimestampNow();
659 $won = wfInvertTimestamp( $now );
661 # Test to see if the row exists using INSERT IGNORE
662 # This avoids race conditions by locking the row until the commit, and also
663 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
664 $dbw->insert( 'image',
668 'img_timestamp' => $dbw->timestamp($now),
669 'img_description' => $desc,
670 'img_user' => $wgUser->getID(),
671 'img_user_text' => $wgUser->getName(),
674 $descTitle = Title
::makeTitleSafe( NS_IMAGE
, $name );
676 if ( $dbw->affectedRows() ) {
677 # Successfully inserted, this is a new image
678 $id = $descTitle->getArticleID();
681 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
685 'cur_namespace' => NS_IMAGE
,
686 'cur_title' => $name,
687 'cur_comment' => $desc,
688 'cur_user' => $wgUser->getID(),
689 'cur_user_text' => $wgUser->getName(),
690 'cur_timestamp' => $dbw->timestamp($now),
692 'cur_text' => $textdesc,
693 'inverse_timestamp' => $won,
694 'cur_touched' => $dbw->timestamp($now)
697 $id = $dbw->insertId() or 0; # We should throw an error instead
699 RecentChange
::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
701 $u = new SearchUpdate( $id, $name, $desc );
705 # Collision, this is an update of an image
706 # Get current image row for update
707 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
708 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
710 # Insert it into oldimage
711 $dbw->insert( 'oldimage',
713 'oi_name' => $s->img_name
,
714 'oi_archive_name' => $oldver,
715 'oi_size' => $s->img_size
,
716 'oi_timestamp' => $dbw->timestamp($s->img_timestamp
),
717 'oi_description' => $s->img_description
,
718 'oi_user' => $s->img_user
,
719 'oi_user_text' => $s->img_user_text
723 # Update the current image row
724 $dbw->update( 'image',
727 'img_timestamp' => $dbw->timestamp(),
728 'img_user' => $wgUser->getID(),
729 'img_user_text' => $wgUser->getName(),
730 'img_description' => $desc,
731 ), array( /* WHERE */
736 # Invalidate the cache for the description page
737 $descTitle->invalidateCache();
740 $log = new LogPage( 'upload' );
741 $log->addEntry( 'upload', $descTitle, $desc );
745 * Returns the image URL of an image's old version
747 * @param string $fname file name of the image file
748 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
751 function wfImageArchiveUrl( $name, $subdir='archive' )
753 global $wgUploadPath, $wgHashedUploadDirectory;
755 if ($wgHashedUploadDirectory) {
756 $hash = md5( substr( $name, 15) );
757 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
758 substr( $hash, 0, 2 ) . '/'.$name;
760 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
762 return wfUrlencode($url);
766 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
767 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
769 * @param string $length
770 * @return int Length in pixels
772 function scaleSVGUnit( $length ) {
773 static $unitLength = array(
780 '' => 1.0, // "User units" pixels by default
781 '%' => 2.0, // Fake it!
783 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
784 $length = FloatVal( $matches[1] );
786 return round( $length * $unitLength[$unit] );
789 return round( FloatVal( $length ) );
794 * Compatible with PHP getimagesize()
795 * @todo support gzipped SVGZ
796 * @todo check XML more carefully
797 * @todo sensible defaults
799 * @param string $filename
802 function getSVGsize( $filename ) {
806 // Read a chunk of the file
807 $f = fopen( $filename, "rt" );
808 if( !$f ) return false;
809 $chunk = fread( $f, 4096 );
812 // Uber-crappy hack! Run through a real XML parser.
813 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
817 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
818 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
820 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
821 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
824 return array( $width, $height, 'SVG',
825 "width=\"$width\" height=\"$height\"" );