92396286827ff551b2210aed94fcb0ea36c0ab00
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;
82 if($this->fileExists
) {
83 $this->url
= $this->wfImageUrl( $sharedname, $this->fromSharedDirectory
);
88 $n = strrpos( $name, '.' );
89 $this->extension
= strtolower( $n ?
substr( $name, $n +
1 ) : '' );
92 if ( $this->fileExists
)
94 if( $this->extension
== 'svg' ) {
95 @$gis = getSVGsize( $this->imagePath
);
97 @$gis = getimagesize( $this->imagePath
);
99 if( $gis !== false ) {
100 $this->width
= $gis[0];
101 $this->height
= $gis[1];
102 $this->type
= $gis[2];
103 $this->attr
= $gis[3];
104 if ( isset( $gis['bits'] ) ) {
105 $this->bits
= $gis['bits'];
111 $this->historyLine
= 0;
117 * Create a new image object from a title object.
119 * @param Title $nt Title object. Must be from namespace "image"
122 function newFromTitle( $nt )
124 $img = new Image( $nt->getDBKey() );
130 * Return the name of this image
139 * Return the associated title object
148 * Return the URL of the image file
156 function getViewURL() {
157 if( $this->mustRender() ) {
158 return $this->createThumb( $this->getWidth() );
160 return $this->getURL();
165 * Return the image path of the image in the
166 * local file system as an absolute path
169 function getImagePath()
171 return $this->imagePath
;
175 * Return the width of the image
177 * Returns -1 if the file specified is not a known image type
186 * Return the height of the image
188 * Returns -1 if the file specified is not a known image type
193 return $this->height
;
197 * Return the size of the image file, in bytes
202 $st = stat( $this->getImagePath() );
207 * Return the type of the image
221 * Return the escapeLocalURL of this image
224 function getEscapeLocalURL()
226 return $this->title
->escapeLocalURL();
230 * Return the escapeFullURL of this image
233 function getEscapeFullURL()
235 return $this->title
->escapeFullURL();
239 * Return the URL of an image, provided its name.
241 * @param string $name Name of the image, without the leading "Image:"
242 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
245 function wfImageUrl( $name, $fromSharedDirectory = false )
247 global $wgUploadPath,$wgUploadBaseUrl,$wgHashedUploadDirectory,
248 $wgHashedSharedUploadDirectory,$wgSharedUploadPath,
249 $wgUseLatin1, $wgSharedLatin1;
250 if($fromSharedDirectory) {
251 $hash = $wgHashedSharedUploadDirectory;
253 $path = $wgSharedUploadPath;
254 if($wgUseLatin1 && !$wgSharedLatin1) {
255 $name=utf8_encode($name);
258 $hash = $wgHashedUploadDirectory;
259 $base = $wgUploadBaseUrl;
260 $path = $wgUploadPath;
263 $hash = md5( $name );
264 $url = "{$base}{$path}/" . $hash{0} . "/" .
265 substr( $hash, 0, 2 ) . "/{$name}";
267 $url = "{$base}{$path}/{$name}";
269 return wfUrlencode( $url );
273 * Returns true iff the image file exists on disk.
279 return $this->fileExists
;
286 function thumbUrl( $width, $subdir='thumb') {
287 global $wgUploadPath,$wgHashedUploadDirectory, $wgUploadBaseUrl,
288 $wgSharedUploadPath,$wgSharedUploadDirectory,
289 $wgHashedSharedUploadDirectory,$wgUseLatin1,$wgSharedLatin1;
290 $name = $this->thumbName( $width );
291 if($this->fromSharedDirectory
) {
292 $hashdir = $wgHashedSharedUploadDirectory;
294 $path = $wgSharedUploadPath;
295 if($wgUseLatin1 && !$wgSharedLatin1) {
296 $name=utf8_encode($name);
299 $hashdir = $wgHashedUploadDirectory;
300 $base = $wgUploadBaseUrl;
301 $path = $wgUploadPath;
304 $hash = md5( $name );
305 $url = "{$base}{$path}/{$subdir}/" . $hash{0} . "/" .
306 substr( $hash, 0, 2 ) . "/{$name}";
308 $url = "{$base}{$path}/{$subdir}/{$name}";
311 return wfUrlencode($url);
315 * Return the file name of a thumbnail of the specified width
317 * @param integer $width Width of the thumbnail image
318 * @param boolean $shared Does the thumbnail come from the shared repository?
321 function thumbName( $width, $shared=false ) {
322 global $wgUseLatin1,$wgSharedLatin1;
323 $thumb = $width."px-".$this->name
;
324 if( $this->extension
== 'svg' ) {
325 # Rasterize SVG vector images to PNG
328 if( $shared && $wgUseLatin1 && !$wgSharedLatin1) {
329 $thumb=utf8_encode($thumb);
335 * Create a thumbnail of the image having the specified width/height.
336 * The thumbnail will not be created if the width is larger than the
337 * image's width. Let the browser do the scaling in this case.
338 * The thumbnail is stored on disk and is only computed if the thumbnail
339 * file does not exist OR if it is older than the image.
342 * Keeps aspect ratio of original image. If both width and height are
343 * specified, the generated image will be no bigger than width x height,
344 * and will also have correct aspect ratio.
346 * @param integer $width maximum width of the generated thumbnail
347 * @param integer $height maximum height of the image (optional)
350 function createThumb( $width, $height=-1 ) {
351 if ( $height == -1 ) {
352 return $this->renderThumb( $width );
354 if ( $width < $this->width
) {
355 $thumbheight = $this->height
* $width / $this->width
;
356 $thumbwidth = $width;
358 $thumbheight = $this->height
;
359 $thumbwidth = $this->width
;
361 if ( $thumbheight > $height ) {
362 $thumbwidth = $thumbwidth * $height / $thumbheight;
363 $thumbheight = $height;
365 return $this->renderThumb( $thumbwidth );
369 * Create a thumbnail of the image having the specified width.
370 * The thumbnail will not be created if the width is larger than the
371 * image's width. Let the browser do the scaling in this case.
372 * The thumbnail is stored on disk and is only computed if the thumbnail
373 * file does not exist OR if it is older than the image.
378 function /* private */ renderThumb( $width ) {
379 global $wgImageMagickConvertCommand;
380 global $wgUseImageMagick;
381 global $wgUseSquid, $wgInternalServer;
383 $width = IntVal( $width );
385 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory
);
386 $thumbPath = wfImageThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory
).'/'.$thumbName;
387 $thumbUrl = $this->thumbUrl( $width );
388 #wfDebug ( "Render name: $thumbName path: $thumbPath url: $thumbUrl\n");
389 if ( ! $this->exists() )
391 # If there is no image, there will be no thumbnail
395 # Sanity check $width
401 if( $width > $this->width
&& !$this->mustRender() ) {
402 # Don't make an image bigger than the source
403 return $this->getViewURL();
406 if ( (! file_exists( $thumbPath ) ) ||
( filemtime($thumbPath) < filemtime($this->imagePath
) ) ) {
407 if( $this->extension
== 'svg' ) {
408 global $wgSVGConverters, $wgSVGConverter;
409 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
410 global $wgSVGConverterPath;
412 array( '$path/', '$width', '$input', '$output' ),
413 array( $wgSVGConverterPath,
415 escapeshellarg( $this->imagePath
),
416 escapeshellarg( $thumbPath ) ),
417 $wgSVGConverters[$wgSVGConverter] );
418 $conv = shell_exec( $cmd );
422 } elseif ( $wgUseImageMagick ) {
424 # Specify white background color, will be used for transparent images
425 # in Internet Explorer/Windows instead of default black.
426 $cmd = $wgImageMagickConvertCommand .
427 " -quality 85 -background white -geometry {$width} ".
428 escapeshellarg($this->imagePath
) . " " .
429 escapeshellarg($thumbPath);
430 $conv = shell_exec( $cmd );
432 # Use PHP's builtin GD library functions.
434 # First find out what kind of file this is, and select the correct
435 # input routine for this.
439 switch( $this->type
) {
441 $src_image = imagecreatefromgif( $this->imagePath
);
444 $src_image = imagecreatefromjpeg( $this->imagePath
);
448 $src_image = imagecreatefrompng( $this->imagePath
);
449 $truecolor = ( $this->bits
> 8 );
451 case 15: # WBMP for WML
452 $src_image = imagecreatefromwbmp( $this->imagePath
);
455 $src_image = imagecreatefromxbm( $this->imagePath
);
458 return 'Image type not supported';
461 $height = floor( $this->height
* ( $width/$this->width
) );
463 $dst_image = imagecreatetruecolor( $width, $height );
465 $dst_image = imagecreate( $width, $height );
467 imagecopyresampled( $dst_image, $src_image,
469 $width, $height, $this->width
, $this->height
);
470 switch( $this->type
) {
475 #$thumbUrl .= ".png";
476 #$thumbPath .= ".png";
477 imagepng( $dst_image, $thumbPath );
480 #$thumbUrl .= ".jpg";
481 #$thumbPath .= ".jpg";
482 imageinterlace( $dst_image );
483 imagejpeg( $dst_image, $thumbPath, 95 );
488 imagedestroy( $dst_image );
489 imagedestroy( $src_image );
494 # Check for zero-sized thumbnails. Those can be generated when
495 # no disk space is available or some other error occurs
497 $thumbstat = stat( $thumbPath );
498 if( $thumbstat['size'] == 0 )
500 unlink( $thumbPath );
504 # This has to be done after the image is updated and present for all machines on NFS,
505 # or else the old version might be stored into the squid again
508 $wgInternalServer.$thumbUrl
510 wfPurgeSquidServers($urlArr);
514 } // END OF function createThumb
517 * Return the image history of this image, line by line.
518 * starts with current version, then old versions.
519 * uses $this->historyLine to check which line to return:
520 * 0 return line for current version
521 * 1 query for old versions, return first one
522 * 2, ... return next old version from above query
526 function nextHistoryLine()
528 $fname = 'Image::nextHistoryLine()';
529 $dbr =& wfGetDB( DB_SLAVE
);
530 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
531 $this->historyRes
= $dbr->select( 'image',
532 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
533 array( 'img_name' => $this->title
->getDBkey() ),
536 if ( 0 == wfNumRows( $this->historyRes
) ) {
539 } else if ( $this->historyLine
== 1 ) {
540 $this->historyRes
= $dbr->select( 'oldimage',
541 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
542 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
543 ), array( 'oi_name' => $this->title
->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
546 $this->historyLine ++
;
548 return $dbr->fetchObject( $this->historyRes
);
552 * Reset the history pointer to the first element of the history
555 function resetHistory()
557 $this->historyLine
= 0;
561 * Return true if the file is of a type that can't be directly
562 * rendered by typical browsers and needs to be re-rasterized.
565 function mustRender() {
566 return ( $this->extension
== 'svg' );
573 * Returns the image directory of an image
574 * If the directory does not exist, it is created.
575 * The result is an absolute path.
577 * @param string $fname file name of the image file
580 function wfImageDir( $fname )
582 global $wgUploadDirectory, $wgHashedUploadDirectory;
584 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
586 $hash = md5( $fname );
587 $oldumask = umask(0);
588 $dest = $wgUploadDirectory . '/' . $hash{0};
589 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
590 $dest .= '/' . substr( $hash, 0, 2 );
591 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
598 * Returns the image directory of an image's thubnail
599 * If the directory does not exist, it is created.
600 * The result is an absolute path.
602 * @param string $fname file name of the thumbnail file, including file size prefix
603 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
604 * @param boolean $shared (optional) use the shared upload directory
607 function wfImageThumbDir( $fname , $subdir='thumb', $shared=false)
609 return wfImageArchiveDir( $fname, $subdir, $shared );
613 * Returns the image directory of an image's old version
614 * If the directory does not exist, it is created.
615 * The result is an absolute path.
617 * @param string $fname file name of the thumbnail file, including file size prefix
618 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
619 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
622 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false )
624 global $wgUploadDirectory, $wgHashedUploadDirectory,
625 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
626 $dir = $shared ?
$wgSharedUploadDirectory : $wgUploadDirectory;
627 $hashdir = $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
628 if (!$hashdir) { return $dir.'/'.$subdir; }
629 $hash = md5( $fname );
630 $oldumask = umask(0);
631 # Suppress warning messages here; if the file itself can't
632 # be written we'll worry about it then.
633 $archive = $dir.'/'.$subdir;
634 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
635 $archive .= '/' . $hash{0};
636 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
637 $archive .= '/' . substr( $hash, 0, 2 );
638 if ( ! is_dir( $archive ) ) { @mkdir
( $archive, 0777 ); }
645 * Record an image upload in the upload log.
647 function wfRecordUpload( $name, $oldver, $size, $desc, $copyStatus = "", $source = "" )
649 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
650 global $wgUseCopyrightUpload;
652 $fname = 'wfRecordUpload';
653 $dbw =& wfGetDB( DB_MASTER
);
655 # img_name must be unique
656 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
657 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
661 $now = wfTimestampNow();
662 $won = wfInvertTimestamp( $now );
663 $size = IntVal( $size );
665 if ( $wgUseCopyrightUpload )
667 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
668 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
669 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
671 else $textdesc = $desc ;
673 $now = wfTimestampNow();
674 $won = wfInvertTimestamp( $now );
676 # Test to see if the row exists using INSERT IGNORE
677 # This avoids race conditions by locking the row until the commit, and also
678 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
679 $dbw->insert( 'image',
683 'img_timestamp' => $dbw->timestamp($now),
684 'img_description' => $desc,
685 'img_user' => $wgUser->getID(),
686 'img_user_text' => $wgUser->getName(),
689 $descTitle = Title
::makeTitleSafe( NS_IMAGE
, $name );
691 if ( $dbw->affectedRows() ) {
692 # Successfully inserted, this is a new image
693 $id = $descTitle->getArticleID();
696 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
700 'cur_namespace' => NS_IMAGE
,
701 'cur_title' => $name,
702 'cur_comment' => $desc,
703 'cur_user' => $wgUser->getID(),
704 'cur_user_text' => $wgUser->getName(),
705 'cur_timestamp' => $dbw->timestamp($now),
707 'cur_text' => $textdesc,
708 'inverse_timestamp' => $won,
709 'cur_touched' => $dbw->timestamp($now)
712 $id = $dbw->insertId() or 0; # We should throw an error instead
714 RecentChange
::notifyNew( $now, $descTitle, 0, $wgUser, $desc );
716 $u = new SearchUpdate( $id, $name, $desc );
720 # Collision, this is an update of an image
721 # Get current image row for update
722 $s = $dbw->selectRow( 'image', array( 'img_name','img_size','img_timestamp','img_description',
723 'img_user','img_user_text' ), array( 'img_name' => $name ), $fname, 'FOR UPDATE' );
725 # Insert it into oldimage
726 $dbw->insert( 'oldimage',
728 'oi_name' => $s->img_name
,
729 'oi_archive_name' => $oldver,
730 'oi_size' => $s->img_size
,
731 'oi_timestamp' => $dbw->timestamp($s->img_timestamp
),
732 'oi_description' => $s->img_description
,
733 'oi_user' => $s->img_user
,
734 'oi_user_text' => $s->img_user_text
738 # Update the current image row
739 $dbw->update( 'image',
742 'img_timestamp' => $dbw->timestamp(),
743 'img_user' => $wgUser->getID(),
744 'img_user_text' => $wgUser->getName(),
745 'img_description' => $desc,
746 ), array( /* WHERE */
751 # Invalidate the cache for the description page
752 $descTitle->invalidateCache();
755 $log = new LogPage( 'upload' );
756 $log->addEntry( 'upload', $descTitle, $desc );
760 * Returns the image URL of an image's old version
762 * @param string $fname file name of the image file
763 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
766 function wfImageArchiveUrl( $name, $subdir='archive' )
768 global $wgUploadPath, $wgHashedUploadDirectory;
770 if ($wgHashedUploadDirectory) {
771 $hash = md5( substr( $name, 15) );
772 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
773 substr( $hash, 0, 2 ) . '/'.$name;
775 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
777 return wfUrlencode($url);
781 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
782 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
784 * @param string $length
785 * @return int Length in pixels
787 function scaleSVGUnit( $length ) {
788 static $unitLength = array(
795 '' => 1.0, // "User units" pixels by default
796 '%' => 2.0, // Fake it!
798 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
799 $length = FloatVal( $matches[1] );
801 return round( $length * $unitLength[$unit] );
804 return round( FloatVal( $length ) );
809 * Compatible with PHP getimagesize()
810 * @todo support gzipped SVGZ
811 * @todo check XML more carefully
812 * @todo sensible defaults
814 * @param string $filename
817 function getSVGsize( $filename ) {
821 // Read a chunk of the file
822 $f = fopen( $filename, "rt" );
823 if( !$f ) return false;
824 $chunk = fread( $f, 4096 );
827 // Uber-crappy hack! Run through a real XML parser.
828 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
832 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
833 $width = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
835 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
836 $height = scaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
839 return array( $width, $height, 'SVG',
840 "width=\"$width\" height=\"$height\"" );