jpgraph.php

来自「eGroupWare is a multi-user, web-based gr」· PHP 代码 · 共 1,955 行 · 第 1/5 页

PHP
1,955
字号
<?php
/*=======================================================================
// File:	JPGRAPH.PHP
// Description:	PHP4 Graph Plotting library. Base module.
// Created: 	2001-01-08
// Author:	Johan Persson (johanp@aditus.nu)
// Ver:		$Id: jpgraph.php,v 1.7 2004/06/08 04:51:56 lkneschke Exp $
//
// License:	This code is released under GPL 2.0 
// Copyright (C) 2001 Johan Persson 
//========================================================================
*/

// Get all directory paths
include ( "jpgraph_dir.php" );

// What group should the cached file belong to
// (Set to "" will give the default group for the "PHP-user")
// Please note that the Apache user must be a member of the
// specified group since otherwise it is impossible for Apache
// to set the specified group.
DEFINE("CACHE_FILE_GROUP","");

// What permissions should the cached file have
// (Set to "" will give the default persmissions for the "PHP-user")
DEFINE("CACHE_FILE_MOD",0664);

// Should we try to find an image in the cache before generating it? 
// Set this define to false to bypass the reading of the cache and always
// regenerate the image. Note that even if reading the cache is 
// disabled the cached will still be updated with the newly generated
// image. Set also "USE_CACHE" below.
DEFINE("READ_CACHE",false);

// Should the cache be used at all? By setting this to false no
// files will be generated in the cache directory.  
// The difference from READ_CACHE being that setting READ_CACHE to
// false will still create the image in the cache directory
// just not use it. By setting USE_CACHE=false no files will even
// be generated in the cache directory.
DEFINE("USE_CACHE",false);

// If the color palette is full should JpGraph try to allocate
// the closest match? If you plan on using background image or
// gradient fills it might be a good idea to enable this.
// If not you will otherwise get an error saying that the color palette is 
// exhausted. The drawback of using approximations is that the colors 
// might not be exactly what you specified. 
// Note1: This does only apply to paletted images, not truecolor 
// images since they don't have the limitations of maximum number
// of colors.
DEFINE("USE_APPROX_COLORS",true);

// Should usage of deprecated functions and parameters give a fatal error?
// (Useful to check if code is future proof.)
DEFINE("ERR_DEPRECATED",true);

// Should the time taken to generate each picture be branded to the lower
// left in corner in each generated image? Useful for performace measurements
// generating graphs
DEFINE("BRAND_TIMING",false);

// What format should be used for the timing string?
DEFINE("BRAND_TIME_FORMAT","Generated in: %01.3fs");

// Decide if we should use the bresenham circle algorithm or the
// built in Arc(). Bresenham gives better visual apperance of circles 
// but is more CPU intensive and slower then the built in Arc() function
// in GD. Turned off by default for speed
DEFINE("USE_BRESENHAM",false);

// Deafult graphic format set to "auto" which will automtically
// choose the best available format in the order png,gif,jpg
// (The supported format depends on what your PHP installation supports)
DEFINE("DEFAULT_GFORMAT","auto");

// Special unicode language support
DEFINE("LANGUAGE_CYRILLIC",false);

// Enable some extra debug information to be shown. 
// (Should only be used if your first name is Johan)
DEFINE("JPG_DEBUG",false);

// Should the image be a truecolor image? 
// Note 1: Can only be used with GD 2.0.2 and above.
// Note 2: GD 2.0.1 + PHP 4.0.6 on Win32 crashes when trying to use 
// trucolor. Truecolor support is to be considered alpha since GD 2.x
// is still not considered stable (especially on Win32). 
// Note 1: MUST be enabled to get background images working with GD2
// Note 2: If enabled then truetype fonts will look very ugly
// => You can't have both background images and truetype fonts in the same
// image until these bugs has been fixed in GD 2.01  
DEFINE('USE_TRUECOLOR',true);

//------------------------------------------------------------------
// Constants which are used as parameters for the method calls
//------------------------------------------------------------------

// TTF Font families
DEFINE("FF_COURIER",10);
DEFINE("FF_VERDANA",11);
DEFINE("FF_TIMES",12);
DEFINE("FF_HANDWRT",13);
DEFINE("FF_COMIC",14);
DEFINE("FF_ARIAL",15);
DEFINE("FF_BOOK",16);
DEFINE("FF_VERA",17);

// TTF Font styles
DEFINE("FS_NORMAL",1);
DEFINE("FS_BOLD",2);
DEFINE("FS_ITALIC",3);
DEFINE("FS_BOLDIT",4);

//Definitions for internal font, new style
DEFINE("FF_FONT0",1);
DEFINE("FF_FONT1",2);
DEFINE("FF_FONT2",4);

//Definitions for internal font, old style
// (Only defined here to be able to generate an error mesage
// when used)
DEFINE("FONT0",99);			// Deprecated from 1.2
DEFINE("FONT1",98);			// Deprecated from 1.2
DEFINE("FONT1_BOLD",97);	// Deprecated from 1.2
DEFINE("FONT2",96);			// Deprecated from 1.2
DEFINE("FONT2_BOLD",95); 	// Deprecated from 1.2

// Tick density
DEFINE("TICKD_DENSE",1);
DEFINE("TICKD_NORMAL",2);
DEFINE("TICKD_SPARSE",3);
DEFINE("TICKD_VERYSPARSE",4);

// Side for ticks and labels. 
DEFINE("SIDE_LEFT",-1);
DEFINE("SIDE_RIGHT",1);
DEFINE("SIDE_DOWN",-1);
DEFINE("SIDE_UP",1);

// Legend type stacked vertical or horizontal
DEFINE("LEGEND_VERT",0);
DEFINE("LEGEND_HOR",1);

// Mark types for plot marks
DEFINE("MARK_SQUARE",1);
DEFINE("MARK_UTRIANGLE",2);
DEFINE("MARK_DTRIANGLE",3);
DEFINE("MARK_DIAMOND",4);
DEFINE("MARK_CIRCLE",5);
DEFINE("MARK_FILLEDCIRCLE",6);
DEFINE("MARK_CROSS",7);
DEFINE("MARK_STAR",8);
DEFINE("MARK_X",9);

// Styles for gradient color fill
DEFINE("GRAD_VER",1);
DEFINE("GRAD_HOR",2);
DEFINE("GRAD_MIDHOR",3);
DEFINE("GRAD_MIDVER",4);
DEFINE("GRAD_CENTER",5);
DEFINE("GRAD_WIDE_MIDVER",6);
DEFINE("GRAD_WIDE_MIDHOR",7);

// Inline defines
DEFINE("INLINE_YES",1);
DEFINE("INLINE_NO",0);

// Format for background images
DEFINE("BGIMG_FILLPLOT",1);
DEFINE("BGIMG_FILLFRAME",2);
DEFINE("BGIMG_COPY",3);
DEFINE("BGIMG_CENTER",4);

// Depth of objects
DEFINE("DEPTH_BACK",0);
DEFINE("DEPTH_FRONT",1);

// Direction
DEFINE("VERTICAL",1);
DEFINE("HORIZONTAL",0);

// Constants for types of static bands in plot area
DEFINE("BAND_RDIAG",1);	// Right diagonal lines
DEFINE("BAND_LDIAG",2); // Left diagonal lines
DEFINE("BAND_SOLID",3); // Solid one color
DEFINE("BAND_LVERT",4); // Vertical lines
DEFINE("BAND_LHOR",5);  // Horizontal lines
DEFINE("BAND_VLINE",4); // Vertical lines
DEFINE("BAND_HLINE",5);  // Horizontal lines
DEFINE("BAND_3DPLANE",6);  // "3D" Plane
DEFINE("BAND_HVCROSS",7);  // Vertical/Hor crosses
DEFINE("BAND_DIAGCROSS",8); // Diagonal crosses



//
// First of all set up a default error handler
//

//=============================================================
// The default trivial error handler.
// A production quality error handler should generate an image
// containing the text of the error. 
//=============================================================
class JpGraphErrObject {
    function JpGraphErrObject() {
	// Empty. Reserved for future use
    }

    // If aHalt is true then execution can't continue. Typical used for
    // fatal errors
    function Raise($aMsg,$aHalt=true) {
	if( $aHalt )
	    die($aMsg);
	else 
	    echo $aMsg."<p>";
    }
}

//
// A wrapper class that is used to access the specified error object
// (to hide the global error parameter and avoid having a GLOBAL directive
// in all methods.
//
class JpGraphError {
    function Install($aErrObject) {
	GLOBAL $__jpg_err;
	$__jpg_err = $aErrObject;
    }
    function Raise($aMsg,$aHalt=true){
	GLOBAL $__jpg_err;
	$tmp = new $__jpg_err;
	$tmp->Raise($aMsg,$aHalt);
    }
}

//
// ... and install the default error handler
//
JpGraphError::Install("JpGraphErrObject");

//
//Check if there were any warnings, perhaps some wrong includes by the
//user
//
if( isset($GLOBALS['php_errormsg']) ) {
    JpGraphError::Raise("<b>General PHP error:</b><br>".$GLOBALS['php_errormsg']);
}

//
// Check what version of the GD library is being used
//
if(function_exists('imagecopyresampled') ) {
    $gd2 = true;
    $copyfunc = "imagecopyresampled";
} elseif(function_exists('imagecopyresized')) {
    $copyfunc = "imagecopyresized";
    $gd2 = false;
}
else {
    JpGraphError::Raise("<b>JpGraph Error:</b> Your PHP installation does not 
	have the required GD library.
	Please see the PHP documentation on how to install and enable the GD library.");
}


// Usefull mathematical function
function sign($a) {if( $a>=0) return 1; else return -1;}

// Utility function to generate an image name based on the filename we
// are running from AND assuming we use auto detection of graphic format
// (top level), i.e it is safe to call this function
// from a script that uses JpGraph
function GenImgName() {
    global $HTTP_SERVER_VARS;
    $supported = imagetypes();
    if( $supported & IMG_PNG )
	$img_format="png";
    elseif( $supported & IMG_GIF )
	$img_format="gif";
    elseif( $supported & IMG_JPG )
	$img_format="jpeg";
    if( !isset($HTTP_SERVER_VARS['PHP_SELF']) )
	JpGraphError::Raise("<b>JpGraph Error:</b> Can't access PHP_SELF, PHP global variable. You can't run PHP from command line
		if you want to use the 'auto' naming of cache or image files.");
    $fname=basename($HTTP_SERVER_VARS['PHP_SELF']);
    // Replace the ".php" extension with the image format extension
    return substr($fname,0,strlen($fname)-4).".".$img_format;
}


class LanguageConv {

//  Translate iso encoding to unicode
    function iso2uni ($isoline){
	for ($i=0; $i < strlen($isoline); $i++){
	    $thischar=substr($isoline,$i,1);
	    $charcode=ord($thischar);
	    $uniline.=($charcode>175) ? "&#" . (1040+($charcode-176)). ";" : $thischar;
	}
	return $uniline;
    }

    function ToCyrillic($aTxt) {
	$koistring = $aTxt;
	$isostring = convert_cyr_string($koistring, "k", "i");
	$unistring = LanguageConv::iso2uni($isostring);
	$this->t = $unistring;
	return $aTxt;
    }
}

//===================================================
// CLASS JpgTimer
// Description: General timing utility class to handle
// timne measurement of generating graphs. Multiple
// timers can be started by pushing new on a stack.
//===================================================
class JpgTimer {
    var $start;
    var $idx;	
//---------------
// CONSTRUCTOR
    function JpgTimer() {
	$this->idx=0;
    }

//---------------
// PUBLIC METHODS	

    // Push a new timer start on stack
    function Push() {
	list($ms,$s)=explode(" ",microtime());	
	$this->start[$this->idx++]=floor($ms*1000) + 1000*$s;	
    }

    // Pop the latest timer start and return the diff with the
    // current time
    function Pop() {
	assert($this->idx>0);
	list($ms,$s)=explode(" ",microtime());	
	$etime=floor($ms*1000) + (1000*$s);
	$this->idx--;
	return $etime-$this->start[$this->idx];
    }
} // Class


//===================================================
// CLASS Graph
// Description: Main class to handle graphs
//===================================================
class Graph {
    var $cache=null;		// Cache object (singleton)
    var $img=null;			// Img object (singleton)
    var $plots=array();	// Array of all plot object in the graph (for Y 1 axis)
    var $y2plots=array();// Array of all plot object in the graph (for Y 2 axis)
    var $xscale=null;		// X Scale object (could be instance of LinearScale or LogScale
    var $yscale=null,$y2scale=null;
    var $cache_name;		// File name to be used for the current graph in the cache directory
    var $xgrid=null;		// X Grid object (linear or logarithmic)
    var $ygrid=null,$y2grid=null; //dito for Y
    var $doframe=true,$frame_color=array(0,0,0), $frame_weight=1;	// Frame around graph
    var $boxed=false, $box_color=array(0,0,0), $box_weight=1;		// Box around plot area
    var $doshadow=false,$shadow_width=4,$shadow_color=array(102,102,102);	// Shadow for graph
    var $xaxis=null;		// X-axis (instane of Axis class)
    var $yaxis=null, $y2axis=null;	// Y axis (instance of Axis class)
    var $margin_color=array(198,198,198);	// Margin coor of graph
    var $plotarea_color=array(255,255,255);	// Plot area color
    var $title,$subtitle; 	// Title and subtitle text object
    var $axtype="linlin";	// Type of axis
    var $xtick_factor;	// Factot to determine the maximum number of ticks depending on the plot with
    var $texts=null;		// Text object to ge shown in the graph
    var $lines=null;
    var $bands=null;
    var $text_scale_off=0;	// Text scale offset in world coordinates
    var $background_image="",$background_image_type=-1,$background_image_format="png";
    var $background_image_bright=0,$background_image_contr=0,$background_image_sat=0;
    var $image_bright=0, $image_contr=0, $image_sat=0;
    var $inline;
    var $showcsim=0,$csimcolor="red"; //debug stuff, draw the csim boundaris on the image if <>0
    var $grid_depth=DEPTH_BACK;	// Draw grid under all plots as default
//---------------
// CONSTRUCTOR

    // aWIdth 		Width in pixels of image
    // aHeight  	Height in pixels of image
    // aCachedName	Name for image file in cache directory 
    //  aTimeOut	Timeout in minutes for image in cache
    // aInline		If true the image is streamed back in the call to Stroke()

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?