Apache-GDGraph

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN


0.95	Mon Apr  7 15:06:53 PDT 2003
	- Fixed a possible misreading of the CacheSize parameter reported by
	  CPAN testers.

0.94	Thu Apr  3 21:06:14 PST 2003
	- Added compatibility with mod_perl for Apache2.
	- Made test skip in Apache2 (too lazy to fix it right now).

0.93	Sat Nov 17 14:59:03 PST 2001
	- Added relative path support for files/fonts etc. So that things like
	  ../fonts/arial.ttf will resolve relative to DocumentRoot. Or
	  to_file=../images/foo.png, etc.. Thanks to Joseph Pepin for the
	  suggestion.
	- Boxed captions in plain/dashed/dotted/whatever style.
	- Support builtin GD fonts Like gdSmallFont.
	- Cleaner code and misc. minor bugs fixed.

0.92	Tue Apr 24 11:36:19 PDT 2001
	- Previous versions couldn't handle more than 9 arguments because of a
	  silly string increment bug :) Thanks to Drew Degentesh for pointing
	  this out.

0.91	Tue Feb  6 16:37:56 PST 2001
	- Added a background_image option to make it simpler to add background
	  images to graphs.
	- Added no_axes parameter.
	- Added PerlSetVar TTFFontPath to set the path to search for True Type
	  fonts in GD::Text, and consequently any font related methods in
	  GD::Graph.
	- Fixed another minor caching snafu (PerlSetVar CacheSize 0 still
	  checked for cached images).
	- Expanded pod docs a bit.
	- Fixed exceptions, for the last time I hope.
	- Added support for captions at arbitrary locations in the graph, with
	  any font.

0.9	Tue Oct 17 11:38:53 PDT 2000
	- Added a list type () for set_XXX methods. Eg. legend=(mon,tue,wed)
	  will now work.
	- Now support x-www-form-urlencoded data sent via a POST request.
	- Added a to_file parameter, if set the generated graph will be saved
	  to the destination file on the server.

0.8	Mon Oct  9 22:44:05 PDT 2000
	- Since 0.7, the default for the X axis is to NOT have any labels.
	- The "expires" parameter didn't really work, fixed.
	- The parameter cache=0 in the query string still hit the cache if the
	  image was already there, fixed.
	- Was checking for "Accepts" header, when needed to check for "Accept"
	  header.
	- Now checking for set_XXX methods as options, so methods like
	  set_legend(), set_font(), etc will work.

0.7	Wed Sep 14 18:47:27 PDT 2000
	- Added support for image types other than png via PerlSetVar
	  ImageType, and the image_type parameter, and via Accepts header
	  (Thanks to Scott Holdren for the idea and patch.)
	- Better parsing. Empty values in arrays (like [,foo,bar,,]) will work,
	  as well as quoted strings. (Thanks to Scott Holdren for the former.)
	- New argument "expires" allows configuration of Expires header on a
	  request basis.
	- New argument "cache" allows requests to not use the server-side

README  view on Meta::CPAN

            SetHandler      perl-script
            PerlHandler     +Apache::GD::Graph
            ## These are optional (defaults shown)
            ##                              In days:
            #PerlSetVar     Expires         30
            #
            ##                              In megs:
            #PerlSetVar     CacheSize       5242880
            #PerlSetVar     ImageType       png
            #PerlSetVar     JpegQuality     75 # 0 to 100
            #PerlSetVar     TTFFontPath     /usr/ttfonts:
            #/var/ttfonts:/usr/X11R6/lib/X11/fonts/ttf/:
            #/usr/X11R6/lib/X11/fonts/truetype/:
            #/usr/share/fonts/truetype
            </Location>

    Then send requests to:

            http://www.server.com/chart?type=lines&
            x_labels=[1st,2nd,3rd,4th,5th]&
            data1=[1,2,3,4,5]&
            data2=[6,7,8,9,10]&
            dclrs=[blue,yellow,green]>

README  view on Meta::CPAN

    interface.

    Firstly, make sure you are not using any spaces! If you want to pass
    a space in a parameter in a URL-encoded string, use %20, in a form
    use a "+".

    Make sure to use "cache=0" or "PerlSetVar CacheSize 0" when
    debugging, otherwise you will spend hours being very confused.

FONTS
    GD::Graph has some options that take a font description, such as
    title_font, legend_font, etc. (these map to the appropriate set_FOO
    methods in GD::Graph, see that manpage).

    The following fonts are built-in to GD, these strings will resolve
    into the appropriate fonts except when quoted:

    gdSmallFont, gdLargeFont, gdMediumBoldFont, gdTinyFont, gdGiantFont

    There is also a way to use your own True Type Fonts. See the
    TTFFontPath variable under SYNOPSIS for how to set the search path
    for fonts. MAKE SURE your fonts are readable by the user the Apache
    server runs under, this is usually "www-data" or "nobody". Otherwise
    your fonts will mysteriously fail with no notice.

    Fonts can also be specified as a relative path to the DocumentRoot
    of the server, these must begin with "../". For example, if you have
    a directory "fonts" under DocumentRoot, then you might specify a
    font like so:

            ../fonts/arial.ttf

    If DocumentRoot happens to be "/var/www" then the font that will be
    looked up is "/var/www/fonts/arial.ttf".

    Sizes can be specified by using a list with the name and size. For
    example, if arial.ttf can be found somewhere in your TTFFontPath,
    you can do:

            ...title_font=(arial.ttf,20)

    To get a title using font Arial, in 20 points.

    Note that GD::Text does not parse out the names of fonts and such,
    you have to give it an actual filename, matches are
    case-insensitive. So if using the Microsoft Windows core fonts,
    Arial Bold would be "arialbd.ttf". Here's an example:

            http://server/chart?data1=[1,2,3,4,5]&
            title_font=(arialbd.ttf,20)&
            title=Just%20A%20Line

COLORS
    All colors, including those specified for the captionN option, are
    specified using the colour names from GD::Graph::colour. They are,
    at time of writing:

    white, lgray, gray, dgray, black, lblue, blue, dblue, gold, lyellow,
    yellow, dyellow, lgreen, green, dgreen, lred, red, dred, lpurple,
    purple, dpurple, lorange, orange, pink, dpink, marine, cyan, lbrown,

README  view on Meta::CPAN

            Set an image as the background for the graph. You are
            responsible for choosing a sane image to go with your graph,
            the background should be either transparent or the same
            color you will use. This is the same as using the "logo"
            parameter with an image of the same size as the graph,
            except this option will resize the image if necessary,
            making it more convenient for this purpose. The file or URL
            can be of any type your copy of GD supports.

    captionN
            Draws a character string using a TrueType font at an
            arbitrary location. Takes an array of
            "($fgcolor,$fontname,$ptsize,$angle,$x,$y,$string[,$box_colo
            r,$box_offset])" where $fgcolor is the foreground color,
            $fontname is the name of a TTF font see "FONTS" , $ptsize is
            the point size, $x and $y are the coordinates, and $string
            is the actual characters to draw.

            $box_color and $box_offset are optional parameters, if set
            the caption will be drawn with a box around it in that color
            and that distance from the caption string. The default
            offset of 9 should work well in most cases.

            N is an integer from 1 onward, like for the dataN option.
            This lets you specify multiple strings to draw.

            Note: you cannot use builtin GD fonts like gdTinyFont for
            captions, you have to use a real TTF font.

            This uses the GD stringTTF method, see GD. Colour names are
            indexed using the GD::Graph::colour builtins (see above),
            fonts are resolved by font path or relative to DocumentRoot,
            parameters are processed as per "DATA TYPES".

            Angle is in degrees, you will primarily use angle 0 for
            normal left-to-right text. $x and $y are pixel coordinates
            from the upper left corner. $fontname is the name of a
            true-type font that will be found in the font path "FONTS".
            Example:

                    http://isis/chart?data1=[1,2,3,4,5]&
                    caption1=(1,arial.ttf,9,0,30,30,Hello,red)

            To draw the box around the caption as a dashed or dotted
            line use:

    gd_set_style
            This option sets the style for the special gdStyled color

README  view on Meta::CPAN

            array and used in an ordinary option.

    {one,1,two,2}
            Becomes a hash reference.

    http://somewhere/file.png
            Is pulled into a file and the file name is passed to the
            respective option. (Can be any scheme besides http:// that
            LWP::Simple supports.)

    ../fonts/arial.ttf
            Paths following this pattern will be interpreted as paths
            relative to DocumentRoot of the web server.

    gdSmallFont, gdLargeFont, gdMediumBoldFont, gdTinyFont, gdGiantFont,
    gdStyled, gdBrushed, gdStyledBrushed, gdTransparent
            These are reserved strings. If not quoted, they will be
            converted to the builtin GD constants of the same name. See
            GD for details.

    [undef,something,undef] or {key,undef}

lib/Apache/GD/Graph.pm  view on Meta::CPAN

	SetHandler	perl-script
	PerlHandler	+Apache::GD::Graph
	## These are optional (defaults shown)
	## 				In days:
	#PerlSetVar	Expires		30
	#
	##				In megs:
	#PerlSetVar	CacheSize	5242880
	#PerlSetVar	ImageType	png
	#PerlSetVar	JpegQuality	75 # 0 to 100
	#PerlSetVar	TTFFontPath	/usr/ttfonts:
	#/var/ttfonts:/usr/X11R6/lib/X11/fonts/ttf/:
	#/usr/X11R6/lib/X11/fonts/truetype/:
	#/usr/share/fonts/truetype
	</Location>

Then send requests to:

	http://www.server.com/chart?type=lines&
	x_labels=[1st,2nd,3rd,4th,5th]&
	data1=[1,2,3,4,5]&
	data2=[6,7,8,9,10]&
	dclrs=[blue,yellow,green]>

lib/Apache/GD/Graph.pm  view on Meta::CPAN

Most more complicated things depend on knowing the GD::Graph interface.

Firstly, B<make sure you are not using any spaces!> If you want to pass a space in
a parameter in a URL-encoded string, use C<%20>, in a form use a C<+>.

Make sure to use C<cache=0> or C<PerlSetVar CacheSize 0> when debugging,
otherwise you will spend hours being very confused.

=head1 FONTS

GD::Graph has some options that take a font description, such as title_font,
legend_font, etc. (these map to the appropriate set_FOO methods in GD::Graph,
see that manpage).

The following fonts are built-in to GD, these strings will resolve into the
appropriate fonts except when quoted:

gdSmallFont, gdLargeFont, gdMediumBoldFont, gdTinyFont, gdGiantFont

There is also a way to use your own True Type Fonts. See the TTFFontPath
variable under SYNOPSIS for how to set the search path for fonts. MAKE SURE
your fonts are readable by the user the Apache server runs under, this is
usually "www-data" or "nobody". Otherwise your fonts will mysteriously fail
with no notice.

Fonts can also be specified as a relative path to the DocumentRoot of the
server, these must begin with "../". For example, if you have a directory
"fonts" under DocumentRoot, then you might specify a font like so:

	../fonts/arial.ttf

If DocumentRoot happens to be C</var/www> then the font that will be looked up
is C</var/www/fonts/arial.ttf>.

Sizes can be specified by using a list with the name and size. For example, if
arial.ttf can be found somewhere in your TTFFontPath, you can do:

	...title_font=(arial.ttf,20)

To get a title using font Arial, in 20 points.

Note that GD::Text does not parse out the names of fonts and such, you have to
give it an actual filename, matches are case-insensitive. So if using the
Microsoft Windows core fonts, Arial Bold would be C<arialbd.ttf>. Here's an
example:

	http://server/chart?data1=[1,2,3,4,5]&
	title_font=(arialbd.ttf,20)&
	title=Just%20A%20Line

=head1 COLORS

All colors, including those specified for the captionN option, are specified
using the colour names from L<GD::Graph::colour>. They are, at time of writing:

white, lgray, gray, dgray, black, lblue, blue, dblue, gold, lyellow, yellow,
dyellow, lgreen, green, dgreen, lred, red, dred, lpurple, purple, dpurple,
lorange, orange, pink, dpink, marine, cyan, lbrown, dbrown.

lib/Apache/GD/Graph.pm  view on Meta::CPAN


Set an image as the background for the graph. You are responsible for choosing
a sane image to go with your graph, the background should be either transparent
or the same color you will use. This is the same as using the C<logo> parameter
with an image of the same size as the graph, except this option will resize the
image if necessary, making it more convenient for this purpose. The file or URL
can be of any type your copy of GD supports.

=item B<captionN>

Draws a character string using a TrueType font at an arbitrary location.  Takes
an array of
C<($fgcolor,$fontname,$ptsize,$angle,$x,$y,$string[,$box_color,$box_offset])>
where $fgcolor is the foreground color, $fontname is the name of a TTF font see
L</FONTS> , $ptsize is the point size, $x and $y are the coordinates, and
$string is the actual characters to draw.

$box_color and $box_offset are optional parameters, if set the caption will be
drawn with a box around it in that color and that distance from the caption
string. The default offset of 9 should work well in most cases.

N is an integer from 1 onward, like for the dataN option. This lets you specify
multiple strings to draw.

B<Note:> you cannot use builtin GD fonts like gdTinyFont for captions, you have
to use a real TTF font.

This uses the GD stringTTF method, see L<GD>. Colour names are indexed using
the GD::Graph::colour builtins (see above), fonts are resolved by font path or
relative to DocumentRoot, parameters are processed as per L</DATA TYPES>.

Angle is in degrees, you will primarily use angle C<0> for normal left-to-right
text. $x and $y are pixel coordinates from the upper left corner. $fontname is
the name of a true-type font that will be found in the font path L</FONTS>.
Example:

	http://isis/chart?data1=[1,2,3,4,5]&
	caption1=(1,arial.ttf,9,0,30,30,Hello,red)

To draw the box around the caption as a dashed or dotted line use:

=item B<gd_set_style>

This option sets the style for the special gdStyled color index. It's simply a

lib/Apache/GD/Graph.pm  view on Meta::CPAN


=item B<{one,1,two,2}>

Becomes a hash reference.

=item B<http://somewhere/file.png>

Is pulled into a file and the file name is passed to the respective option.
(Can be any scheme besides http:// that LWP::Simple supports.)

=item B<../fonts/arial.ttf>

Paths following this pattern will be interpreted as paths relative to
DocumentRoot of the web server.

=item B<gdSmallFont, gdLargeFont, gdMediumBoldFont, gdTinyFont, gdGiantFont,
	gdStyled, gdBrushed, gdStyledBrushed, gdTransparent>

These are reserved strings. If not quoted, they will be converted to the
builtin GD constants of the same name. See L<GD> for details.

lib/Apache/GD/Graph.pm  view on Meta::CPAN

use File::Cache;

use constant TRUE	=> 1;
use constant FALSE	=> 0;

use constant SECONDS_IN_DAY => 24 * 60 * 60;

use constant EXPIRES	=> 30;
use constant CACHE_SIZE	=> 5242880;
use constant IMAGE_TYPE => 'png';
use constant TTF_FONT_PATH	=> '/usr/ttfonts:/var/ttfonts:/usr/X11R6/lib/X11/fonts/ttf/:/usr/X11R6/lib/X11/fonts/truetype/:/usr/share/fonts/truetype';

use constant DEFAULT_TYPE	=> 'lines';
use constant DEFAULT_WIDTH	=> 400;
use constant DEFAULT_HEIGHT	=> 300;

use constant DEFAULT_CAPTION_BOX_OFFSET => 9;

use constant TYPE_UNDEF		=> 0;
use constant TYPE_SCALAR	=> 1;
use constant TYPE_ARRAY		=> 2;

lib/Apache/GD/Graph.pm  view on Meta::CPAN

my $first_request = TRUE;
my ($r, $cache_size, $image_cache, $document_root, @cleanup_files);

# Subs:

# init()
#
# Called only once on the first request received. May be called once per child
# in Apache.
sub init() {
# Set the GD::Text fontpath.
	GD::Text->font_path ($r->dir_config('TTFFontPath') || TTF_FONT_PATH);

	$cache_size = $r->dir_config('CacheSize');

	$cache_size = CACHE_SIZE if $cache_size <= 0;

	$image_cache = new File::Cache ({
		namespace	=> 'Images',
		max_size	=> $cache_size,
		filemode	=> 0660
	});

lib/Apache/GD/Graph.pm  view on Meta::CPAN

		) if $gd_style;

# Draw captions.
		for my $caption (@captions) {
			undef $@;

# Argument 1 is the color, have to resolve GD::Graph::colour builtins into
# indexes on the GD image.
			$caption->[0] = resolveColor($graph => $caption->[0]);

# Argument 2 to caption is the font name, GD expects a full path.
			$caption->[1] = findFont($caption->[1]);

			my @bounds = $image->stringTTF(@$caption[0..6]);

			die "Could not draw caption: @{[ join ', ', @$caption ]}: $@" if $@;

# Draw box around caption.
			next unless defined(my $box_clr = $caption->[7]);

			my $offset = defined $caption->[8] ?

lib/Apache/GD/Graph.pm  view on Meta::CPAN

	return parseElement $_, $dir;
}

# parseElement ($value)
#
# First strips quotes off the ends of $value.  Then checks whether $value is a
# URL, and if so, fetches it into a file and returns the (TYPE_URL, file_name),
# otherwise returns (TYPE_SCALAR, $value).
#
# Will also parse paths relative to DocumentRoot, for example
# ../fonts/arial.ttf.
sub parseElement ($;$) {
	$_	= shift;
	my $dir	= shift || '/tmp';

	if (defined(my $constant = GD_CONSTANTS->{$_})) {
		return (TYPE_SCALAR, $constant)
	}

	$_ = $1 if /@{[STRIP_QUOTES]}/;

lib/Apache/GD/Graph.pm  view on Meta::CPAN

sub error ($) {
	my $message	= shift;
# Ending newlines look ugly in the error log.
	chomp $message;
	my $contact	= $r->server->server_admin;
	$r->send_http_header("text/html");
	$r->print(<<"EOF");
<html>
<head></head>
<body bgcolor="lightblue">
<font color="red"><h1>Error:</h1></font>
<p>
$message
<p>
The Request was:<br>
@{[ $r->the_request ]}
<p>
Please contact the server administrator, <a href="$contact">$contact</a> and
inform them of the time the error occured, and anything you might have done to
cause the error.
</body>
</html>
EOF

	$r->log_error (__PACKAGE__.': '.$r->the_request.': '.$message);
}

# findFont ($basename)
#
# Searches the true type font path for a file, returns the first match.
#
# Returns undef if no font was found.
sub findFont ($) {
	my $name = shift || return undef;

# Don't need to search for qualified file names or font objects.
	return $name
		if ($name =~ m!^/!) || (ref $name);

	my @path = map { m!(.*?)/*$! } split /:/, GD::Text->font_path;

	for my $path (@path) {
		for my $font (<$path/*>) {
			return $font if $font =~ m!/$name$!i;
		}
	}
}

# resolveColor ($gd_graph_object, $color_name)
#
# Resolve a GD::Graph::colour builtin into the index for GD, if it's not
# numeric already.
#
sub resolveColor ($$) {



( run in 1.972 second using v1.01-cache-2.11-cpan-ceb78f64989 )