PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/jpgraph/jpgraph.php

https://github.com/TICanalyste/netOffice--remix-
PHP | 8244 lines | 6445 code | 880 blank | 919 comment | 1081 complexity | 45d386ac052de53ca76a25b94e99d2b2 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. //=======================================================================
  3. // File: JPGRAPH.PHP
  4. // Description: PHP Graph Plotting library. Base module.
  5. // Created: 2001-01-08
  6. // Author: Johan Persson (johanp@aditus.nu)
  7. // Ver: $Id: jpgraph.php,v 1.6 2005/06/10 01:07:34 madbear Exp $
  8. //
  9. // Copyright (c) Aditus Consulting. All rights reserved.
  10. //========================================================================
  11. require_once('jpg-config.inc');
  12. // Version info
  13. DEFINE('JPG_VERSION','1.18');
  14. // For internal use only
  15. DEFINE("_JPG_DEBUG",false);
  16. DEFINE("_FORCE_IMGTOFILE",false);
  17. DEFINE("_FORCE_IMGDIR",'/tmp/jpgimg/');
  18. //------------------------------------------------------------------------
  19. // Automatic settings of path for cache and font directory
  20. // if they have not been previously specified
  21. //------------------------------------------------------------------------
  22. if(USE_CACHE) {
  23. if (!defined('CACHE_DIR')) {
  24. if ( strstr( PHP_OS, 'WIN') ) {
  25. if( empty($_SERVER['TEMP']) ) {
  26. die('JpGraph Error: No path specified for CACHE_DIR. Please specify CACHE_DIR manually in jpg-config.inc');
  27. }
  28. else {
  29. DEFINE('CACHE_DIR', $_SERVER['TEMP'] . '/');
  30. }
  31. } else {
  32. DEFINE('CACHE_DIR','/tmp/jpgraph_cache/');
  33. }
  34. }
  35. }
  36. elseif( !defined('CACHE_DIR') ) {
  37. DEFINE('CACHE_DIR', '');
  38. }
  39. if (!defined('TTF_DIR')) {
  40. if (strstr( PHP_OS, 'WIN') ) {
  41. $sroot = getenv('SystemRoot');
  42. if( empty($sroot) ) {
  43. die('JpGraph Error: No path specified for TTF_DIR and path can not be determined automatically. Please specify TTF_DIR manually (in jpg-config.inc).');
  44. }
  45. else {
  46. DEFINE('TTF_DIR', $sroot.'/fonts/');
  47. }
  48. } else {
  49. DEFINE('TTF_DIR','/usr/X11R6/lib/X11/fonts/truetype/');
  50. }
  51. }
  52. //------------------------------------------------------------------
  53. // Constants which are used as parameters for the method calls
  54. //------------------------------------------------------------------
  55. // TTF Font families
  56. DEFINE("FF_COURIER",10);
  57. DEFINE("FF_VERDANA",11);
  58. DEFINE("FF_TIMES",12);
  59. DEFINE("FF_COMIC",14);
  60. DEFINE("FF_ARIAL",15);
  61. DEFINE("FF_GEORGIA",16);
  62. DEFINE("FF_TREBUCHE",17);
  63. // Gnome Vera font
  64. // Available from http://www.gnome.org/fonts/
  65. DEFINE("FF_VERA",19);
  66. DEFINE("FF_VERAMONO",20);
  67. DEFINE("FF_VERASERIF",21);
  68. // Chinese font
  69. DEFINE("FF_SIMSUN",30);
  70. DEFINE("FF_CHINESE",31);
  71. DEFINE("FF_BIG5",31);
  72. // Japanese font
  73. DEFINE("FF_MINCHO",40);
  74. DEFINE("FF_PMINCHO",41);
  75. DEFINE("FF_GOTHIC",42);
  76. DEFINE("FF_PGOTHIC",43);
  77. // Limits for TTF fonts
  78. DEFINE('_FF_FIRST',10);
  79. DEFINE('_FF_LAST',43);
  80. // Older deprecated fonts
  81. DEFINE("FF_BOOK",91); // Deprecated fonts from 1.9
  82. DEFINE("FF_HANDWRT",92); // Deprecated fonts from 1.9
  83. // TTF Font styles
  84. DEFINE("FS_NORMAL",9001);
  85. DEFINE("FS_BOLD",9002);
  86. DEFINE("FS_ITALIC",9003);
  87. DEFINE("FS_BOLDIT",9004);
  88. DEFINE("FS_BOLDITALIC",9004);
  89. //Definitions for internal font, new style
  90. DEFINE("FF_FONT0",1);
  91. DEFINE("FF_FONT1",2);
  92. DEFINE("FF_FONT2",4);
  93. // Tick density
  94. DEFINE("TICKD_DENSE",1);
  95. DEFINE("TICKD_NORMAL",2);
  96. DEFINE("TICKD_SPARSE",3);
  97. DEFINE("TICKD_VERYSPARSE",4);
  98. // Side for ticks and labels.
  99. DEFINE("SIDE_LEFT",-1);
  100. DEFINE("SIDE_RIGHT",1);
  101. DEFINE("SIDE_DOWN",-1);
  102. DEFINE("SIDE_BOTTOM",-1);
  103. DEFINE("SIDE_UP",1);
  104. DEFINE("SIDE_TOP",1);
  105. // Legend type stacked vertical or horizontal
  106. DEFINE("LEGEND_VERT",0);
  107. DEFINE("LEGEND_HOR",1);
  108. // Mark types for plot marks
  109. DEFINE("MARK_SQUARE",1);
  110. DEFINE("MARK_UTRIANGLE",2);
  111. DEFINE("MARK_DTRIANGLE",3);
  112. DEFINE("MARK_DIAMOND",4);
  113. DEFINE("MARK_CIRCLE",5);
  114. DEFINE("MARK_FILLEDCIRCLE",6);
  115. DEFINE("MARK_CROSS",7);
  116. DEFINE("MARK_STAR",8);
  117. DEFINE("MARK_X",9);
  118. DEFINE("MARK_LEFTTRIANGLE",10);
  119. DEFINE("MARK_RIGHTTRIANGLE",11);
  120. DEFINE("MARK_FLASH",12);
  121. DEFINE("MARK_IMG",13);
  122. DEFINE("MARK_FLAG1",14);
  123. DEFINE("MARK_FLAG2",15);
  124. DEFINE("MARK_FLAG3",16);
  125. DEFINE("MARK_FLAG4",17);
  126. // Builtin images
  127. DEFINE("MARK_IMG_PUSHPIN",50);
  128. DEFINE("MARK_IMG_SPUSHPIN",50);
  129. DEFINE("MARK_IMG_LPUSHPIN",51);
  130. DEFINE("MARK_IMG_DIAMOND",52);
  131. DEFINE("MARK_IMG_SQUARE",53);
  132. DEFINE("MARK_IMG_STAR",54);
  133. DEFINE("MARK_IMG_BALL",55);
  134. DEFINE("MARK_IMG_SBALL",55);
  135. DEFINE("MARK_IMG_MBALL",56);
  136. DEFINE("MARK_IMG_LBALL",57);
  137. DEFINE("MARK_IMG_BEVEL",58);
  138. // Inline defines
  139. DEFINE("INLINE_YES",1);
  140. DEFINE("INLINE_NO",0);
  141. // Format for background images
  142. DEFINE("BGIMG_FILLPLOT",1);
  143. DEFINE("BGIMG_FILLFRAME",2);
  144. DEFINE("BGIMG_COPY",3);
  145. DEFINE("BGIMG_CENTER",4);
  146. // Depth of objects
  147. DEFINE("DEPTH_BACK",0);
  148. DEFINE("DEPTH_FRONT",1);
  149. // Direction
  150. DEFINE("VERTICAL",1);
  151. DEFINE("HORIZONTAL",0);
  152. // Axis styles for scientific style axis
  153. DEFINE('AXSTYLE_SIMPLE',1);
  154. DEFINE('AXSTYLE_BOXIN',2);
  155. DEFINE('AXSTYLE_BOXOUT',3);
  156. DEFINE('AXSTYLE_YBOXIN',4);
  157. DEFINE('AXSTYLE_YBOXOUT',5);
  158. // Style for title backgrounds
  159. DEFINE('TITLEBKG_STYLE1',1);
  160. DEFINE('TITLEBKG_STYLE2',2);
  161. DEFINE('TITLEBKG_STYLE3',3);
  162. DEFINE('TITLEBKG_FRAME_NONE',0);
  163. DEFINE('TITLEBKG_FRAME_FULL',1);
  164. DEFINE('TITLEBKG_FRAME_BOTTOM',2);
  165. DEFINE('TITLEBKG_FRAME_BEVEL',3);
  166. DEFINE('TITLEBKG_FILLSTYLE_HSTRIPED',1);
  167. DEFINE('TITLEBKG_FILLSTYLE_VSTRIPED',2);
  168. DEFINE('TITLEBKG_FILLSTYLE_SOLID',3);
  169. // Style for background gradient fills
  170. DEFINE('BGRAD_FRAME',1);
  171. DEFINE('BGRAD_MARGIN',2);
  172. DEFINE('BGRAD_PLOT',3);
  173. // Width of tab titles
  174. DEFINE('TABTITLE_WIDTHFIT',0);
  175. DEFINE('TABTITLE_WIDTHFULL',-1);
  176. // Defines for 3D skew directions
  177. DEFINE('SKEW3D_UP',0);
  178. DEFINE('SKEW3D_DOWN',1);
  179. DEFINE('SKEW3D_LEFT',2);
  180. DEFINE('SKEW3D_RIGHT',3);
  181. //
  182. // Get hold of gradient class (In Version 2.x)
  183. // A client of the library has to manually include this
  184. //
  185. require_once 'jpgraph_gradient.php';
  186. //
  187. // A wrapper class that is used to access the specified error object
  188. // (to hide the global error parameter and avoid having a GLOBAL directive
  189. // in all methods.
  190. //
  191. GLOBAL $__jpg_err;
  192. class JpGraphError {
  193. function Install($aErrObject) {
  194. GLOBAL $__jpg_err;
  195. $__jpg_err = $aErrObject;
  196. }
  197. function Raise($aMsg,$aHalt=true){
  198. GLOBAL $__jpg_err;
  199. $tmp = new $__jpg_err;
  200. $tmp->Raise($aMsg,$aHalt);
  201. }
  202. }
  203. //
  204. // ... and install the default error handler
  205. //
  206. if( USE_IMAGE_ERROR_HANDLER ) {
  207. $__jpg_err = "JpGraphErrObjectImg";
  208. }
  209. else {
  210. $__jpg_err = "JpGraphErrObject";
  211. }
  212. //
  213. // Make GD sanity check
  214. //
  215. if( !function_exists("imagetypes") || !function_exists('imagecreatefromstring') ) {
  216. JpGraphError::Raise("This PHP installation is not configured with the GD library. Please recompile PHP with GD support to run JpGraph. (Neither function imagetypes() nor imagecreatefromstring() does exist)");
  217. }
  218. //
  219. // Routine to determine if GD1 or GD2 is installed
  220. //
  221. function CheckGDVersion() {
  222. $GDfuncList = get_extension_funcs('gd');
  223. if( !$GDfuncList ) return 0 ;
  224. else {
  225. if( in_array('imagegd2',$GDfuncList) &&
  226. in_array('imagecreatetruecolor',$GDfuncList))
  227. return 2;
  228. else
  229. return 1;
  230. }
  231. }
  232. //
  233. // Check what version of the GD library is installed.
  234. //
  235. $GLOBALS['gd2'] = false;
  236. if( USE_LIBRARY_GD2 === 'auto' ) {
  237. $gdversion = CheckGDVersion();
  238. if( $gdversion == 2 ) {
  239. $GLOBALS['gd2'] = true;
  240. $GLOBALS['copyfunc'] = 'imagecopyresampled';
  241. }
  242. elseif( $gdversion == 1 ) {
  243. $GLOBALS['gd2'] = false;
  244. $GLOBALS['copyfunc'] = 'imagecopyresized';
  245. }
  246. else {
  247. JpGraphError::Raise(" Your PHP installation does not seem to have the required GD library. Please see the PHP documentation on how to install and enable the GD library.");
  248. }
  249. }
  250. else {
  251. $GLOBALS['gd2'] = USE_LIBRARY_GD2;
  252. $GLOBALS['copyfunc'] = USE_LIBRARY_GD2 ? 'imagecopyresampled' : 'imagecopyresized';
  253. }
  254. //
  255. // First of all set up a default error handler
  256. //
  257. //=============================================================
  258. // The default trivial text error handler.
  259. //=============================================================
  260. class JpGraphErrObject {
  261. var $iTitle = "JpGraph Error";
  262. var $iDest = false;
  263. function JpGraphErrObject() {
  264. // Empty. Reserved for future use
  265. }
  266. function SetTitle($aTitle) {
  267. $this->iTitle = $aTitle;
  268. }
  269. function SetStrokeDest($aDest) {
  270. $this->iDest = $aDest;
  271. }
  272. // If aHalt is true then execution can't continue. Typical used for fatal errors.
  273. function Raise($aMsg,$aHalt=true) {
  274. $aMsg = $this->iTitle.' '.$aMsg;
  275. if ($this->iDest) {
  276. $f = @fopen($this->iDest,'a');
  277. if( $f ) {
  278. @fwrite($f,$aMsg);
  279. @fclose($f);
  280. }
  281. }
  282. if( $aHalt )
  283. die();
  284. }
  285. }
  286. //==============================================================
  287. // An image based error handler
  288. //==============================================================
  289. class JpGraphErrObjectImg extends JpGraphErrObject {
  290. function Raise($aMsg,$aHalt=true) {
  291. $img_iconerror =
  292. 'iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAMAAAC7IEhfAAAAaV'.
  293. 'BMVEX//////2Xy8mLl5V/Z2VvMzFi/v1WyslKlpU+ZmUyMjEh/'.
  294. 'f0VyckJlZT9YWDxMTDjAwMDy8sLl5bnY2K/MzKW/v5yyspKlpY'.
  295. 'iYmH+MjHY/PzV/f2xycmJlZVlZWU9MTEXY2Ms/PzwyMjLFTjea'.
  296. 'AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACx'.
  297. 'IAAAsSAdLdfvwAAAAHdElNRQfTBgISOCqusfs5AAABLUlEQVR4'.
  298. '2tWV3XKCMBBGWfkranCIVClKLd/7P2Q3QsgCxjDTq+6FE2cPH+'.
  299. 'xJ0Ogn2lQbsT+Wrs+buAZAV4W5T6Bs0YXBBwpKgEuIu+JERAX6'.
  300. 'wM2rHjmDdEITmsQEEmWADgZm6rAjhXsoMGY9B/NZBwJzBvn+e3'.
  301. 'wHntCAJdGu9SviwIwoZVDxPB9+Rc0TSEbQr0j3SA1gwdSn6Db0'.
  302. '6Tm1KfV6yzWGQO7zdpvyKLKBDmRFjzeB3LYgK7r6A/noDAfjtS'.
  303. 'IXaIzbJSv6WgUebTMV4EoRB8a2mQiQjgtF91HdKDKZ1gtFtQjk'.
  304. 'YcWaR5OKOhkYt+ZsTFdJRfPAApOpQYJTNHvCRSJR6SJngQadfc'.
  305. 'vd69OLMddVOPCGVnmrFD8bVYd3JXfxXPtLR/+mtv59/ALWiiMx'.
  306. 'qL72fwAAAABJRU5ErkJggg==' ;
  307. if( function_exists("imagetypes") )
  308. $supported = imagetypes();
  309. else
  310. $supported = 0;
  311. if( !function_exists('imagecreatefromstring') )
  312. $supported = 0;
  313. if( ob_get_length() || headers_sent() || !($supported & IMG_PNG) ) {
  314. // Special case for headers already sent or that the installation doesn't support
  315. // the PNG format (which the error icon is encoded in).
  316. // Dont return an image since it can't be displayed
  317. die($this->iTitle.' '.$aMsg);
  318. }
  319. $aMsg = wordwrap($aMsg,55);
  320. $lines = substr_count($aMsg,"\n");
  321. // Create the error icon GD
  322. $erricon = Image::CreateFromString(base64_decode($img_iconerror));
  323. // Create an image that contains the error text.
  324. $w=400;
  325. $h=100 + 15*max(0,$lines-3);
  326. $img = new Image($w,$h);
  327. // Drop shadow
  328. $img->SetColor("gray");
  329. $img->FilledRectangle(5,5,$w-1,$h-1,10);
  330. $img->SetColor("gray:0.7");
  331. $img->FilledRectangle(5,5,$w-3,$h-3,10);
  332. // Window background
  333. $img->SetColor("lightblue");
  334. $img->FilledRectangle(1,1,$w-5,$h-5);
  335. $img->CopyCanvasH($img->img,$erricon,5,30,0,0,40,40);
  336. // Window border
  337. $img->SetColor("black");
  338. $img->Rectangle(1,1,$w-5,$h-5);
  339. $img->Rectangle(0,0,$w-4,$h-4);
  340. // Window top row
  341. $img->SetColor("darkred");
  342. for($y=3; $y < 18; $y += 2 )
  343. $img->Line(1,$y,$w-6,$y);
  344. // "White shadow"
  345. $img->SetColor("white");
  346. // Left window edge
  347. $img->Line(2,2,2,$h-5);
  348. $img->Line(2,2,$w-6,2);
  349. // "Gray button shadow"
  350. $img->SetColor("darkgray");
  351. // Gray window shadow
  352. $img->Line(2,$h-6,$w-5,$h-6);
  353. $img->Line(3,$h-7,$w-5,$h-7);
  354. // Window title
  355. $m = floor($w/2-5);
  356. $l = 100;
  357. $img->SetColor("lightgray:1.3");
  358. $img->FilledRectangle($m-$l,2,$m+$l,16);
  359. // Stroke text
  360. $img->SetColor("darkred");
  361. $img->SetFont(FF_FONT2,FS_BOLD);
  362. $img->StrokeText($m-50,15,$this->iTitle);
  363. $img->SetColor("black");
  364. $img->SetFont(FF_FONT1,FS_NORMAL);
  365. $txt = new Text($aMsg,52,25);
  366. $txt->Align("left","top");
  367. $txt->Stroke($img);
  368. if ($this->iDest) {
  369. $img->Stream($this->iDest);
  370. } else {
  371. $img->Headers();
  372. $img->Stream();
  373. }
  374. if( $aHalt )
  375. die();
  376. }
  377. }
  378. //
  379. // Setup PHP error handler
  380. //
  381. function _phpErrorHandler($errno,$errmsg,$filename, $linenum, $vars) {
  382. // Respect current error level
  383. if( $errno & error_reporting() ) {
  384. JpGraphError::Raise('In '.basename($filename).'#'.$linenum."\n".$errmsg);
  385. }
  386. }
  387. if( INSTALL_PHP_ERR_HANDLER ) {
  388. set_error_handler("_phpErrorHandler");
  389. }
  390. //
  391. //Check if there were any warnings, perhaps some wrong includes by the
  392. //user
  393. //
  394. if( isset($GLOBALS['php_errormsg']) && CATCH_PHPERRMSG ) {
  395. JpGraphError::Raise("General PHP error : ".$GLOBALS['php_errormsg']);
  396. }
  397. // Useful mathematical function
  398. function sign($a) {return $a >= 0 ? 1 : -1;}
  399. // Utility function to generate an image name based on the filename we
  400. // are running from and assuming we use auto detection of graphic format
  401. // (top level), i.e it is safe to call this function
  402. // from a script that uses JpGraph
  403. function GenImgName() {
  404. global $_SERVER;
  405. // Determine what format we should use when we save the images
  406. $supported = imagetypes();
  407. if( $supported & IMG_PNG ) $img_format="png";
  408. elseif( $supported & IMG_GIF ) $img_format="gif";
  409. elseif( $supported & IMG_JPG ) $img_format="jpeg";
  410. if( !isset($_SERVER['PHP_SELF']) )
  411. JpGraphError::Raise(" 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.");
  412. $fname = basename($_SERVER['PHP_SELF']);
  413. if( !empty($_SERVER['QUERY_STRING']) ) {
  414. $q = @$_SERVER['QUERY_STRING'];
  415. $fname .= '?'.preg_replace("/\W/", "_", $q).'.'.$img_format;
  416. }
  417. else {
  418. $fname = substr($fname,0,strlen($fname)-4).'.'.$img_format;
  419. }
  420. return $fname;
  421. }
  422. class LanguageConv {
  423. var $g2312 = null ;
  424. function Convert($aTxt,$aFF) {
  425. if( LANGUAGE_CYRILLIC ) {
  426. if( CYRILLIC_FROM_WINDOWS ) {
  427. $aTxt = convert_cyr_string($aTxt, "w", "k");
  428. }
  429. $isostring = convert_cyr_string($aTxt, "k", "i");
  430. $unistring = LanguageConv::iso2uni($isostring);
  431. return $unistring;
  432. }
  433. elseif( $aFF === FF_SIMSUN ) {
  434. // Do Chinese conversion
  435. if( $this->g2312 == null ) {
  436. include_once 'jpgraph_gb2312.php' ;
  437. $this->g2312 = new GB2312toUTF8();
  438. }
  439. return $this->g2312->gb2utf8($aTxt);
  440. }
  441. elseif( $aFF === FF_CHINESE ) {
  442. if( !function_exists('iconv') ) {
  443. JpGraphError::Raise('Usage of FF_CHINESE (FF_BIG5) font family requires that your PHP setup has the iconv() function. By default this is not compiled into PHP (needs the "--width-iconv" when configured).');
  444. }
  445. return iconv('BIG5','UTF-8',$aTxt);
  446. }
  447. else
  448. return $aTxt;
  449. }
  450. // Translate iso encoding to unicode
  451. function iso2uni ($isoline){
  452. $uniline='';
  453. for ($i=0; $i < strlen($isoline); $i++){
  454. $thischar=substr($isoline,$i,1);
  455. $charcode=ord($thischar);
  456. $uniline.=($charcode>175) ? "&#" . (1040+($charcode-176)). ";" : $thischar;
  457. }
  458. return $uniline;
  459. }
  460. }
  461. //===================================================
  462. // CLASS JpgTimer
  463. // Description: General timing utility class to handle
  464. // time measurement of generating graphs. Multiple
  465. // timers can be started.
  466. //===================================================
  467. class JpgTimer {
  468. var $start;
  469. var $idx;
  470. //---------------
  471. // CONSTRUCTOR
  472. function JpgTimer() {
  473. $this->idx=0;
  474. }
  475. //---------------
  476. // PUBLIC METHODS
  477. // Push a new timer start on stack
  478. function Push() {
  479. list($ms,$s)=explode(" ",microtime());
  480. $this->start[$this->idx++]=floor($ms*1000) + 1000*$s;
  481. }
  482. // Pop the latest timer start and return the diff with the
  483. // current time
  484. function Pop() {
  485. assert($this->idx>0);
  486. list($ms,$s)=explode(" ",microtime());
  487. $etime=floor($ms*1000) + (1000*$s);
  488. $this->idx--;
  489. return $etime-$this->start[$this->idx];
  490. }
  491. } // Class
  492. $gJpgBrandTiming = BRAND_TIMING;
  493. //===================================================
  494. // CLASS DateLocale
  495. // Description: Hold localized text used in dates
  496. //===================================================
  497. class DateLocale {
  498. var $iLocale = 'C'; // environmental locale be used by default
  499. var $iDayAbb = null;
  500. var $iShortDay = null;
  501. var $iShortMonth = null;
  502. var $iMonthName = null;
  503. //---------------
  504. // CONSTRUCTOR
  505. function DateLocale() {
  506. settype($this->iDayAbb, 'array');
  507. settype($this->iShortDay, 'array');
  508. settype($this->iShortMonth, 'array');
  509. settype($this->iMonthName, 'array');
  510. $this->Set('C');
  511. }
  512. //---------------
  513. // PUBLIC METHODS
  514. function Set($aLocale) {
  515. if ( in_array($aLocale, array_keys($this->iDayAbb)) ){
  516. $this->iLocale = $aLocale;
  517. return TRUE; // already cached nothing else to do!
  518. }
  519. $pLocale = setlocale(LC_TIME, 0); // get current locale for LC_TIME
  520. $res = @setlocale(LC_TIME, $aLocale);
  521. if ( ! $res ){
  522. JpGraphError::Raise("You are trying to use the locale ($aLocale) which your PHP installation does not support. Hint: Use '' to indicate the default locale for this geographic region.");
  523. return FALSE;
  524. }
  525. $this->iLocale = $aLocale;
  526. for ( $i = 0, $ofs = 0 - strftime('%w'); $i < 7; $i++, $ofs++ ){
  527. $day = strftime('%a', strtotime("$ofs day"));
  528. $day{0} = strtoupper($day{0});
  529. $this->iDayAbb[$aLocale][]= $day{0};
  530. $this->iShortDay[$aLocale][]= $day;
  531. }
  532. for($i=1; $i<=12; ++$i) {
  533. list($short ,$full) = explode('|', strftime("%b|%B",strtotime("2001-$i-01")));
  534. $this->iShortMonth[$aLocale][] = ucfirst($short);
  535. $this->iMonthName [$aLocale][] = ucfirst($full);
  536. }
  537. // Return to original locale
  538. setlocale(LC_TIME, $pLocale);
  539. return TRUE;
  540. }
  541. function GetDayAbb() {
  542. return $this->iDayAbb[$this->iLocale];
  543. }
  544. function GetShortDay() {
  545. return $this->iShortDay[$this->iLocale];
  546. }
  547. function GetShortMonth() {
  548. return $this->iShortMonth[$this->iLocale];
  549. }
  550. function GetShortMonthName($aNbr) {
  551. return $this->iShortMonth[$this->iLocale][$aNbr];
  552. }
  553. function GetLongMonthName($aNbr) {
  554. return $this->iMonthName[$this->iLocale][$aNbr];
  555. }
  556. function GetMonth() {
  557. return $this->iMonthName[$this->iLocale];
  558. }
  559. }
  560. $gDateLocale = new DateLocale();
  561. $gJpgDateLocale = new DateLocale();
  562. //===================================================
  563. // CLASS FuncGenerator
  564. // Description: Utility class to help generate data for function plots.
  565. // The class supports both parametric and regular functions.
  566. //===================================================
  567. class FuncGenerator {
  568. var $iFunc='',$iXFunc='',$iMin,$iMax,$iStepSize;
  569. function FuncGenerator($aFunc,$aXFunc='') {
  570. $this->iFunc = $aFunc;
  571. $this->iXFunc = $aXFunc;
  572. }
  573. function E($aXMin,$aXMax,$aSteps=50) {
  574. $this->iMin = $aXMin;
  575. $this->iMax = $aXMax;
  576. $this->iStepSize = ($aXMax-$aXMin)/$aSteps;
  577. if( $this->iXFunc != '' )
  578. $t = 'for($i='.$aXMin.'; $i<='.$aXMax.'; $i += '.$this->iStepSize.') {$ya[]='.$this->iFunc.';$xa[]='.$this->iXFunc.';}';
  579. elseif( $this->iFunc != '' )
  580. $t = 'for($x='.$aXMin.'; $x<='.$aXMax.'; $x += '.$this->iStepSize.') {$ya[]='.$this->iFunc.';$xa[]=$x;} $x='.$aXMax.';$ya[]='.$this->iFunc.';$xa[]=$x;';
  581. else
  582. JpGraphError::Raise('FuncGenerator : No function specified. ');
  583. @eval($t);
  584. // If there is an error in the function specifcation this is the only
  585. // way we can discover that.
  586. if( empty($xa) || empty($ya) )
  587. JpGraphError::Raise('FuncGenerator : Syntax error in function specification ');
  588. return array($xa,$ya);
  589. }
  590. }
  591. //=======================================================
  592. // CLASS Footer
  593. // Description: Encapsulates the footer line in the Graph
  594. //=======================================================
  595. class Footer {
  596. var $left,$center,$right;
  597. var $iLeftMargin = 3;
  598. var $iRightMargin = 3;
  599. var $iBottomMargin = 3;
  600. function Footer() {
  601. $this->left = new Text();
  602. $this->left->ParagraphAlign('left');
  603. $this->center = new Text();
  604. $this->center->ParagraphAlign('center');
  605. $this->right = new Text();
  606. $this->right->ParagraphAlign('right');
  607. }
  608. function Stroke($aImg) {
  609. $y = $aImg->height - $this->iBottomMargin;
  610. $x = $this->iLeftMargin;
  611. $this->left->Align('left','bottom');
  612. $this->left->Stroke($aImg,$x,$y);
  613. $x = ($aImg->width - $this->iLeftMargin - $this->iRightMargin)/2;
  614. $this->center->Align('center','bottom');
  615. $this->center->Stroke($aImg,$x,$y);
  616. $x = $aImg->width - $this->iRightMargin;
  617. $this->right->Align('right','bottom');
  618. $this->right->Stroke($aImg,$x,$y);
  619. }
  620. }
  621. //===================================================
  622. // CLASS Graph
  623. // Description: Main class to handle graphs
  624. //===================================================
  625. class Graph {
  626. var $cache=null; // Cache object (singleton)
  627. var $img=null; // Img object (singleton)
  628. var $plots=array(); // Array of all plot object in the graph (for Y 1 axis)
  629. var $y2plots=array();// Array of all plot object in the graph (for Y 2 axis)
  630. var $ynplots=array();
  631. var $xscale=null; // X Scale object (could be instance of LinearScale or LogScale
  632. var $yscale=null,$y2scale=null, $ynscale=array();
  633. var $iIcons = array(); // Array of Icons to add to
  634. var $cache_name; // File name to be used for the current graph in the cache directory
  635. var $xgrid=null; // X Grid object (linear or logarithmic)
  636. var $ygrid=null,$y2grid=null, $yngrid=array(); //dito for Y
  637. var $doframe=true,$frame_color=array(0,0,0), $frame_weight=1; // Frame around graph
  638. var $boxed=false, $box_color=array(0,0,0), $box_weight=1; // Box around plot area
  639. var $doshadow=false,$shadow_width=4,$shadow_color=array(102,102,102); // Shadow for graph
  640. var $xaxis=null; // X-axis (instane of Axis class)
  641. var $yaxis=null, $y2axis=null, $ynaxis=array(); // Y axis (instance of Axis class)
  642. var $margin_color=array(200,200,200); // Margin color of graph
  643. var $plotarea_color=array(255,255,255); // Plot area color
  644. var $title,$subtitle,$subsubtitle; // Title and subtitle(s) text object
  645. var $axtype="linlin"; // Type of axis
  646. var $xtick_factor; // Factot to determine the maximum number of ticks depending on the plot with
  647. var $texts=null, $y2texts=null; // Text object to ge shown in the graph
  648. var $lines=null, $y2lines=null;
  649. var $bands=null, $y2bands=null;
  650. var $text_scale_off=0; // Text scale offset in world coordinates
  651. var $background_image="",$background_image_type=-1,$background_image_format="png";
  652. var $background_image_bright=0,$background_image_contr=0,$background_image_sat=0;
  653. var $image_bright=0, $image_contr=0, $image_sat=0;
  654. var $inline;
  655. var $showcsim=0,$csimcolor="red"; //debug stuff, draw the csim boundaris on the image if <>0
  656. var $grid_depth=DEPTH_BACK; // Draw grid under all plots as default
  657. var $iAxisStyle = AXSTYLE_SIMPLE;
  658. var $iCSIMdisplay=false,$iHasStroked = false;
  659. var $footer;
  660. var $csimcachename = '', $csimcachetimeout = 0;
  661. var $iDoClipping = false;
  662. var $y2orderback=true;
  663. var $tabtitle;
  664. var $bkg_gradtype=-1,$bkg_gradstyle=BGRAD_MARGIN;
  665. var $bkg_gradfrom='navy', $bkg_gradto='silver';
  666. var $titlebackground = false;
  667. var $titlebackground_color = 'lightblue',
  668. $titlebackground_style = 1,
  669. $titlebackground_framecolor = 'blue',
  670. $titlebackground_framestyle = 2,
  671. $titlebackground_frameweight = 1,
  672. $titlebackground_bevelheight = 3 ;
  673. var $titlebkg_fillstyle=TITLEBKG_FILLSTYLE_SOLID;
  674. var $titlebkg_scolor1='black',$titlebkg_scolor2='white';
  675. var $framebevel = false, $framebeveldepth = 2 ;
  676. var $framebevelborder = false, $framebevelbordercolor='black';
  677. var $framebevelcolor1='white@0.4', $framebevelcolor2='black@0.4';
  678. var $background_image_mix=100;
  679. var $background_cflag = '';
  680. var $background_cflag_type = BGIMG_FILLPLOT;
  681. var $background_cflag_mix = 100;
  682. var $iImgTrans=false,
  683. $iImgTransHorizon = 100,$iImgTransSkewDist=150,
  684. $iImgTransDirection = 1, $iImgTransMinSize = true,
  685. $iImgTransFillColor='white',$iImgTransHighQ=false,
  686. $iImgTransBorder=false,$iImgTransHorizonPos=0.5;
  687. var $iYAxisDeltaPos=50;
  688. var $iIconDepth=DEPTH_BACK;
  689. //---------------
  690. // CONSTRUCTOR
  691. // aWIdth Width in pixels of image
  692. // aHeight Height in pixels of image
  693. // aCachedName Name for image file in cache directory
  694. // aTimeOut Timeout in minutes for image in cache
  695. // aInline If true the image is streamed back in the call to Stroke()
  696. // If false the image is just created in the cache
  697. function Graph($aWidth=300,$aHeight=200,$aCachedName="",$aTimeOut=0,$aInline=true) {
  698. GLOBAL $gJpgBrandTiming;
  699. // If timing is used create a new timing object
  700. if( $gJpgBrandTiming ) {
  701. global $tim;
  702. $tim = new JpgTimer();
  703. $tim->Push();
  704. }
  705. if( !is_numeric($aWidth) || !is_numeric($aHeight) ) {
  706. JpGraphError::Raise('Image width/height argument in Graph::Graph() must be numeric');
  707. }
  708. // Automatically generate the image file name based on the name of the script that
  709. // generates the graph
  710. if( $aCachedName=="auto" )
  711. $aCachedName=GenImgName();
  712. // Should the image be streamed back to the browser or only to the cache?
  713. $this->inline=$aInline;
  714. $this->img = new RotImage($aWidth,$aHeight);
  715. $this->cache = new ImgStreamCache($this->img);
  716. $this->cache->SetTimeOut($aTimeOut);
  717. $this->title = new Text();
  718. $this->title->ParagraphAlign('center');
  719. $this->title->SetFont(FF_FONT2,FS_BOLD);
  720. $this->title->SetMargin(3);
  721. $this->title->SetAlign('center');
  722. $this->subtitle = new Text();
  723. $this->subtitle->ParagraphAlign('center');
  724. $this->subtitle->SetMargin(2);
  725. $this->subtitle->SetAlign('center');
  726. $this->subsubtitle = new Text();
  727. $this->subsubtitle->ParagraphAlign('center');
  728. $this->subsubtitle->SetMargin(2);
  729. $this->subsubtitle->SetAlign('center');
  730. $this->legend = new Legend();
  731. $this->footer = new Footer();
  732. // Window doesn't like '?' in the file name so replace it with an '_'
  733. $aCachedName = str_replace("?","_",$aCachedName);
  734. // If the cached version exist just read it directly from the
  735. // cache, stream it back to browser and exit
  736. if( $aCachedName!="" && READ_CACHE && $aInline )
  737. if( $this->cache->GetAndStream($aCachedName) ) {
  738. exit();
  739. }
  740. $this->cache_name = $aCachedName;
  741. $this->SetTickDensity(); // Normal density
  742. $this->tabtitle = new GraphTabTitle();
  743. }
  744. //---------------
  745. // PUBLIC METHODS
  746. // Enable final image perspective transformation
  747. function Set3DPerspective($aDir=1,$aHorizon=100,$aSkewDist=120,$aQuality=false,$aFillColor='#FFFFFF',$aBorder=false,$aMinSize=true,$aHorizonPos=0.5) {
  748. $this->iImgTrans = true;
  749. $this->iImgTransHorizon = $aHorizon;
  750. $this->iImgTransSkewDist= $aSkewDist;
  751. $this->iImgTransDirection = $aDir;
  752. $this->iImgTransMinSize = $aMinSize;
  753. $this->iImgTransFillColor=$aFillColor;
  754. $this->iImgTransHighQ=$aQuality;
  755. $this->iImgTransBorder=$aBorder;
  756. $this->iImgTransHorizonPos=$aHorizonPos;
  757. }
  758. // Should the grid be in front or back of the plot?
  759. function SetGridDepth($aDepth) {
  760. $this->grid_depth=$aDepth;
  761. }
  762. function SetIconDepth($aDepth) {
  763. $this->iIconDepth=$aDepth;
  764. }
  765. // Specify graph angle 0-360 degrees.
  766. function SetAngle($aAngle) {
  767. $this->img->SetAngle($aAngle);
  768. }
  769. function SetAlphaBlending($aFlg=true) {
  770. $this->img->SetAlphaBlending($aFlg);
  771. }
  772. // Shortcut to image margin
  773. function SetMargin($lm,$rm,$tm,$bm) {
  774. $this->img->SetMargin($lm,$rm,$tm,$bm);
  775. }
  776. function SetY2OrderBack($aBack=true) {
  777. $this->y2orderback = $aBack;
  778. }
  779. // Rotate the graph 90 degrees and set the margin
  780. // when we have done a 90 degree rotation
  781. function Set90AndMargin($lm=0,$rm=0,$tm=0,$bm=0) {
  782. $lm = $lm ==0 ? floor(0.2 * $this->img->width) : $lm ;
  783. $rm = $rm ==0 ? floor(0.1 * $this->img->width) : $rm ;
  784. $tm = $tm ==0 ? floor(0.2 * $this->img->height) : $tm ;
  785. $bm = $bm ==0 ? floor(0.1 * $this->img->height) : $bm ;
  786. $adj = ($this->img->height - $this->img->width)/2;
  787. $this->img->SetMargin($tm-$adj,$bm-$adj,$rm+$adj,$lm+$adj);
  788. $this->img->SetCenter(floor($this->img->width/2),floor($this->img->height/2));
  789. $this->SetAngle(90);
  790. if( empty($this->yaxis) || empty($this->xaxis) ) {
  791. JpgraphError::Raise('You must specify what scale to use with a call to Graph::SetScale()');
  792. }
  793. $this->xaxis->SetLabelAlign('right','center');
  794. $this->yaxis->SetLabelAlign('center','bottom');
  795. }
  796. function SetClipping($aFlg=true) {
  797. $this->iDoClipping = $aFlg ;
  798. }
  799. // Add a plot object to the graph
  800. function Add(&$aPlot) {
  801. if( $aPlot == null )
  802. JpGraphError::Raise("Graph::Add() You tried to add a null plot to the graph.");
  803. if( is_array($aPlot) && count($aPlot) > 0 )
  804. $cl = strtolower(get_class($aPlot[0]));
  805. else
  806. $cl = strtolower(get_class($aPlot));
  807. if( $cl == 'text' )
  808. $this->AddText($aPlot);
  809. elseif( $cl == 'plotline' )
  810. $this->AddLine($aPlot);
  811. elseif( $cl == 'plotband' )
  812. $this->AddBand($aPlot);
  813. elseif( $cl == 'iconplot' )
  814. $this->AddIcon($aPlot);
  815. else
  816. $this->plots[] = &$aPlot;
  817. }
  818. function AddIcon(&$aIcon) {
  819. if( is_array($aIcon) ) {
  820. for($i=0; $i < count($aIcon); ++$i )
  821. $this->iIcons[]=&$aIcon[$i];
  822. }
  823. else {
  824. $this->iIcons[] = $aIcon ;
  825. }
  826. }
  827. // Add plot to second Y-scale
  828. function AddY2(&$aPlot) {
  829. if( $aPlot == null )
  830. JpGraphError::Raise("Graph::AddY2() You tried to add a null plot to the graph.");
  831. if( is_array($aPlot) && count($aPlot) > 0 )
  832. $cl = strtolower(get_class($aPlot[0]));
  833. else
  834. $cl = strtolower(get_class($aPlot));
  835. if( $cl == 'text' )
  836. $this->AddText($aPlot,true);
  837. elseif( $cl == 'plotline' )
  838. $this->AddLine($aPlot,true);
  839. elseif( $cl == 'plotband' )
  840. $this->AddBand($aPlot,true);
  841. else
  842. $this->y2plots[] = &$aPlot;
  843. }
  844. // Add plot to second Y-scale
  845. function AddY($aN,&$aPlot) {
  846. if( $aPlot == null )
  847. JpGraphError::Raise("Graph::AddYN() You tried to add a null plot to the graph.");
  848. if( is_array($aPlot) && count($aPlot) > 0 )
  849. $cl = strtolower(get_class($aPlot[0]));
  850. else
  851. $cl = strtolower(get_class($aPlot));
  852. if( $cl == 'text' || $cl == 'plotline' || $cl == 'plotband' )
  853. JpGraph::Raise('You can only add standard plots to multiple Y-axis');
  854. else
  855. $this->ynplots[$aN][] = &$aPlot;
  856. }
  857. // Add text object to the graph
  858. function AddText(&$aTxt,$aToY2=false) {
  859. if( $aTxt == null )
  860. JpGraphError::Raise("Graph::AddText() You tried to add a null text to the graph.");
  861. if( $aToY2 ) {
  862. if( is_array($aTxt) ) {
  863. for($i=0; $i < count($aTxt); ++$i )
  864. $this->y2texts[]=&$aTxt[$i];
  865. }
  866. else
  867. $this->y2texts[] = &$aTxt;
  868. }
  869. else {
  870. if( is_array($aTxt) ) {
  871. for($i=0; $i < count($aTxt); ++$i )
  872. $this->texts[]=&$aTxt[$i];
  873. }
  874. else
  875. $this->texts[] = &$aTxt;
  876. }
  877. }
  878. // Add a line object (class PlotLine) to the graph
  879. function AddLine(&$aLine,$aToY2=false) {
  880. if( $aLine == null )
  881. JpGraphError::Raise("Graph::AddLine() You tried to add a null line to the graph.");
  882. if( $aToY2 ) {
  883. if( is_array($aLine) ) {
  884. for($i=0; $i < count($aLine); ++$i )
  885. $this->y2lines[]=&$aLine[$i];
  886. }
  887. else
  888. $this->y2lines[] = &$aLine;
  889. }
  890. else {
  891. if( is_array($aLine) ) {
  892. for($i=0; $i < count($aLine); ++$i )
  893. $this->lines[]=&$aLine[$i];
  894. }
  895. else
  896. $this->lines[] = &$aLine;
  897. }
  898. }
  899. // Add vertical or horizontal band
  900. function AddBand(&$aBand,$aToY2=false) {
  901. if( $aBand == null )
  902. JpGraphError::Raise(" Graph::AddBand() You tried to add a null band to the graph.");
  903. if( $aToY2 ) {
  904. if( is_array($aBand) ) {
  905. for($i=0; $i < count($aBand); ++$i )
  906. $this->y2bands[] = &$aBand[$i];
  907. }
  908. else
  909. $this->y2bands[] = &$aBand;
  910. }
  911. else {
  912. if( is_array($aBand) ) {
  913. for($i=0; $i < count($aBand); ++$i )
  914. $this->bands[] = &$aBand[$i];
  915. }
  916. else
  917. $this->bands[] = &$aBand;
  918. }
  919. }
  920. function SetBackgroundGradient($aFrom='navy',$aTo='silver',$aGradType=2,$aStyle=BGRAD_FRAME) {
  921. $this->bkg_gradtype=$aGradType;
  922. $this->bkg_gradstyle=$aStyle;
  923. $this->bkg_gradfrom = $aFrom;
  924. $this->bkg_gradto = $aTo;
  925. }
  926. // Set a country flag in the background
  927. function SetBackgroundCFlag($aName,$aBgType=BGIMG_FILLPLOT,$aMix=100) {
  928. $this->background_cflag = $aName;
  929. $this->background_cflag_type = $aBgType;
  930. $this->background_cflag_mix = $aMix;
  931. }
  932. // Alias for the above method
  933. function SetBackgroundCountryFlag($aName,$aBgType=BGIMG_FILLPLOT,$aMix=100) {
  934. $this->background_cflag = $aName;
  935. $this->background_cflag_type = $aBgType;
  936. $this->background_cflag_mix = $aMix;
  937. }
  938. // Specify a background image
  939. function SetBackgroundImage($aFileName,$aBgType=BGIMG_FILLPLOT,$aImgFormat="auto") {
  940. if( $GLOBALS['gd2'] && !USE_TRUECOLOR ) {
  941. JpGraphError::Raise("You are using GD 2.x and are trying to use a background images on a non truecolor image. To use background images with GD 2.x you <b>must</b> enable truecolor by setting the USE_TRUECOLOR constant to TRUE. Due to a bug in GD 2.0.1 using any truetype fonts with truecolor images will result in very poor quality fonts.");
  942. }
  943. // Get extension to determine image type
  944. if( $aImgFormat == "auto" ) {
  945. $e = explode('.',$aFileName);
  946. if( !$e ) {
  947. JpGraphError::Raise('Incorrect file name for Graph::SetBackgroundImage() : '.$aFileName.' Must have a valid image extension (jpg,gif,png) when using autodetection of image type');
  948. }
  949. $valid_formats = array('png', 'jpg', 'gif');
  950. $aImgFormat = strtolower($e[count($e)-1]);
  951. if ($aImgFormat == 'jpeg') {
  952. $aImgFormat = 'jpg';
  953. }
  954. elseif (!in_array($aImgFormat, $valid_formats) ) {
  955. JpGraphError::Raise('Unknown file extension ($aImgFormat) in Graph::SetBackgroundImage() for filename: '.$aFileName);
  956. }
  957. }
  958. $this->background_image = $aFileName;
  959. $this->background_image_type=$aBgType;
  960. $this->background_image_format=$aImgFormat;
  961. }
  962. function SetBackgroundImageMix($aMix) {
  963. $this->background_image_mix = $aMix ;
  964. }
  965. // Adjust brightness and constrast for background image
  966. function AdjBackgroundImage($aBright,$aContr=0,$aSat=0) {
  967. $this->background_image_bright=$aBright;
  968. $this->background_image_contr=$aContr;
  969. $this->background_image_sat=$aSat;
  970. }
  971. // Adjust brightness and constrast for image
  972. function AdjImage($aBright,$aContr=0,$aSat=0) {
  973. $this->image_bright=$aBright;
  974. $this->image_contr=$aContr;
  975. $this->image_sat=$aSat;
  976. }
  977. // Specify axis style (boxed or single)
  978. function SetAxisStyle($aStyle) {
  979. $this->iAxisStyle = $aStyle ;
  980. }
  981. // Set a frame around the plot area
  982. function SetBox($aDrawPlotFrame=true,$aPlotFrameColor=array(0,0,0),$aPlotFrameWeight=1) {
  983. $this->boxed = $aDrawPlotFrame;
  984. $this->box_weight = $aPlotFrameWeight;
  985. $this->box_color = $aPlotFrameColor;
  986. }
  987. // Specify color for the plotarea (not the margins)
  988. function SetColor($aColor) {
  989. $this->plotarea_color=$aColor;
  990. }
  991. // Specify color for the margins (all areas outside the plotarea)
  992. function SetMarginColor($aColor) {
  993. $this->margin_color=$aColor;
  994. }
  995. // Set a frame around the entire image
  996. function SetFrame($aDrawImgFrame=true,$aImgFrameColor=array(0,0,0),$aImgFrameWeight=1) {
  997. $this->doframe = $aDrawImgFrame;
  998. $this->frame_color = $aImgFrameColor;
  999. $this->frame_weight = $aImgFrameWeight;
  1000. }
  1001. function SetFrameBevel($aDepth=3,$aBorder=false,$aBorderColor='black',$aColor1='white@0.4',$aColor2='darkgray@0.4',$aFlg=true) {
  1002. $this->framebevel = $aFlg ;
  1003. $this->framebeveldepth = $aDepth ;
  1004. $this->framebevelborder = $aBorder ;
  1005. $this->framebevelbordercolor = $aBorderColor ;
  1006. $this->framebevelcolor1 = $aColor1 ;
  1007. $this->framebevelcolor2 = $aColor2 ;
  1008. $this->doshadow = false ;
  1009. }
  1010. // Set the shadow around the whole image
  1011. function SetShadow($aShowShadow=true,$aShadowWidth=5,$aShadowColor=array(102,102,102)) {
  1012. $this->doshadow = $aShowShadow;
  1013. $this->shadow_color = $aShadowColor;
  1014. $this->shadow_width = $aShadowWidth;
  1015. $this->footer->iBottomMargin += $aShadowWidth;
  1016. $this->footer->iRightMargin += $aShadowWidth;
  1017. }
  1018. // Specify x,y scale. Note that if you manually specify the scale
  1019. // you must also specify the tick distance with a call to Ticks::Set()
  1020. function SetScale($aAxisType,$aYMin=1,$aYMax=1,$aXMin=1,$aXMax=1) {
  1021. $this->axtype = $aAxisType;
  1022. if( $aYMax < $aYMin || $aXMax < $aXMin )
  1023. JpGraphError::Raise('Graph::SetScale(): Specified Max value must be larger than the specified Min value.');
  1024. $yt=substr($aAxisType,-3,3);
  1025. if( $yt=="lin" )
  1026. $this->yscale = new LinearScale($aYMin,$aYMax);
  1027. elseif( $yt == "int" ) {
  1028. $this->yscale = new LinearScale($aYMin,$aYMax);
  1029. $this->yscale->SetIntScale();
  1030. }
  1031. elseif( $yt=="log" )
  1032. $this->yscale = new LogScale($aYMin,$aYMax);
  1033. else
  1034. JpGraphError::Raise("Unknown scale specification for Y-scale. ($aAxisType)");
  1035. $xt=substr($aAxisType,0,3);
  1036. if( $xt == "lin" || $xt == "tex" ) {
  1037. $this->xscale = new LinearScale($aXMin,$aXMax,"x");
  1038. $this->xscale->textscale = ($xt == "tex");
  1039. }
  1040. elseif( $xt == "int" ) {
  1041. $this->xscale = new LinearScale($aXMin,$aXMax,"x");
  1042. $this->xscale->SetIntScale();
  1043. }
  1044. elseif( $xt == "dat" ) {
  1045. $this->xscale = new DateScale($aXMin,$aXMax,"x");
  1046. }
  1047. elseif( $xt == "log" )
  1048. $this->xscale = new LogScale($aXMin,$aXMax,"x");
  1049. else
  1050. JpGraphError::Raise(" Unknown scale specification for X-scale. ($aAxisType)");
  1051. $this->xaxis = new Axis($this->img,$this->xscale);
  1052. $this->yaxis = new Axis($this->img,$this->yscale);
  1053. $this->xgrid = new Grid($this->xaxis);
  1054. $this->ygrid = new Grid($this->yaxis);
  1055. $this->ygrid->Show();
  1056. }
  1057. // Specify secondary Y scale
  1058. function SetY2Scale($aAxisType="lin",$aY2Min=1,$aY2Max=1) {
  1059. if( $aAxisType=="lin" )
  1060. $this->y2scale = new LinearScale($aY2Min,$aY2Max);
  1061. elseif( $aAxisType == "int" ) {
  1062. $this->y2scale = new LinearScale($aY2Min,$aY2Max);
  1063. $this->y2scale->SetIntScale();
  1064. }
  1065. elseif( $aAxisType=="log" ) {
  1066. $this->y2scale = new LogScale($aY2Min,$aY2Max);
  1067. }
  1068. else JpGraphError::Raise("JpGraph: Unsupported Y2 axis type: $aAxisType\nMust be one of (lin,log,int)");
  1069. $this->y2axis = new Axis($this->img,$this->y2scale);
  1070. $this->y2axis->scale->ticks->SetDirection(SIDE_LEFT);
  1071. $this->y2axis->SetLabelSide(SIDE_RIGHT);
  1072. // Deafult position is the max x-value
  1073. $this->y2grid = new Grid($this->y2axis);
  1074. }
  1075. // Set the delta position (in pixels) between the multiple Y-axis
  1076. function SetYDeltaDist($aDist) {
  1077. $this->iYAxisDeltaPos = $aDist;
  1078. }
  1079. // Specify secondary Y scale
  1080. function SetYScale($aN,$aAxisType="lin",$aYMin=1,$aYMax=1) {
  1081. if( $aAxisType=="lin" )
  1082. $this->ynscale[$aN] = new LinearScale($aYMin,$aYMax);
  1083. elseif( $aAxisType == "int" ) {
  1084. $this->ynscale[$aN] = new LinearScale($aYMin,$aYMax);
  1085. $this->ynscale[$aN]->SetIntScale();
  1086. }
  1087. elseif( $aAxisType=="log" ) {
  1088. $this->ynscale[$aN] = new LogScale($aYMin,$aYMax);
  1089. }
  1090. else JpGraphError::Raise("JpGraph: Unsupported Y axis type: $aAxisType\nMust be one of (lin,log,int)");
  1091. $this->ynaxis[$aN] = new Axis($this->img,$this->ynscale[$aN]);
  1092. $this->ynaxis[$aN]->scale->ticks->SetDirection(SIDE_LEFT);
  1093. $this->ynaxis[$aN]->SetLabelSide(SIDE_RIGHT);
  1094. // Deafult position is the max x-value
  1095. $this->yngrid[$aN] = new Grid($this->ynaxis[$aN]);
  1096. }
  1097. // Specify density of ticks when autoscaling 'normal', 'dense', 'sparse', 'verysparse'
  1098. // The dividing factor have been determined heuristically according to my aesthetic
  1099. // sense (or lack off) y.m.m.v !
  1100. function SetTickDensity($aYDensity=TICKD_NORMAL,$aXDensity=TICKD_NORMAL) {
  1101. $this->xtick_factor=30;
  1102. $this->ytick_factor=25;
  1103. switch( $aYDensity ) {
  1104. case TICKD_DENSE:
  1105. $this->ytick_factor=12;
  1106. break;
  1107. case TICKD_NORMAL:
  1108. $this->ytick_factor=25;
  1109. break;
  1110. case TICKD_SPARSE:
  1111. $this->ytick_factor=40;
  1112. break;
  1113. case TICKD_VERYSPARSE:
  1114. $this->ytick_factor=100;
  1115. break;
  1116. default:
  1117. JpGraphError::Raise("JpGraph: Unsupported Tick density: $densy");
  1118. }
  1119. switch( $aXDensity ) {
  1120. case TICKD_DENSE:
  1121. $this->xtick_factor=15;
  1122. break;
  1123. case TICKD_NORMAL:
  1124. $this->xtick_factor=30;
  1125. break;
  1126. case TICKD_SPARSE:
  1127. $this->xtick_factor=45;
  1128. break;
  1129. case TICKD_VERYSPARSE:
  1130. $this->xtick_factor=60;
  1131. break;
  1132. default:
  1133. JpGraphError::Raise("JpGraph: Unsupported Tick density: $densx");
  1134. }
  1135. }
  1136. // Get a string of all image map areas
  1137. function GetCSIMareas() {
  1138. if( !$this->iHasStroked )
  1139. $this->Stroke(_CSIM_SPECIALFILE);
  1140. $csim = $this->title->GetCSIMAreas();
  1141. $csim .= $this->subtitle->GetCSIMAreas();
  1142. $csim .= $this->subsubtitle->GetCSIMAreas();
  1143. $csim .= $this->legend->GetCSIMAreas();
  1144. if( $this->y2axis != NULL ) {
  1145. $csim .= $this->y2axis->title->GetCSIMAreas();
  1146. }
  1147. if( $this->texts != null ) {
  1148. $n = count($this->texts);
  1149. for($i=0; $i < $n; ++$i ) {
  1150. $csim .= $this->texts[$i]->GetCSIMAreas();
  1151. }
  1152. }
  1153. if( $this->y2texts != null && $this->y2scale != null ) {
  1154. $n = count($this->y2texts);
  1155. for($i=0; $i < $n; ++$i ) {
  1156. $csim .= $this->y2texts[$i]->GetCSIMAreas();
  1157. }
  1158. }
  1159. if( $this->yaxis != null && $this->xaxis != null ) {
  1160. $csim .= $this->yaxis->title->GetCSIMAreas();
  1161. $csim .= $this->xaxis->title->GetCSIMAreas();
  1162. }
  1163. $n = count($this->plots);
  1164. for( $i=0; $i < $n; ++$i )
  1165. $csim .= $this->plots[$i]->GetCSIMareas();
  1166. $n = count($this->y2plots);
  1167. for( $i=0; $i < $n; ++$i )
  1168. $csim .= $this->y2plots[$i]->GetCSIMareas();
  1169. return $csim;
  1170. }
  1171. // Get a complete <MAP>..</MAP> tag for the final image map
  1172. function GetHTMLImageMap($aMapName) {
  1173. $im = "<MAP NAME=\"$aMapName\">\n";
  1174. $im .= $this->GetCSIMareas();
  1175. $im .= "</MAP>";
  1176. return $im;
  1177. }
  1178. function CheckCSIMCache($aCacheName,$aTimeOut=60) {
  1179. global $_SERVER;
  1180. if( $aCacheName=='auto' )
  1181. $aCacheName=basename($_SERVER['PHP_SELF']);
  1182. $this->csimcachename = CSIMCACHE_DIR.$aCacheName;
  1183. $this->csimcachetimeout = $aTimeOut;
  1184. // First determine if we need to check for a cached version
  1185. // This differs from the standard cache in the sense that the
  1186. // image and CSIM map HTML file is written relative to the directory
  1187. // the script executes in and not the specified cache directory.
  1188. // The reason for this is that the cache directory is not necessarily
  1189. // accessible from the HTTP server.
  1190. if( $this->csimcachename != '' ) {
  1191. $dir = dirname($this->csimcachename);
  1192. $base = basename($this->csimcachename);
  1193. $base = strtok($base,'.');
  1194. $suffix = strtok('.');
  1195. $basecsim = $dir.'/'.$base.'_csim_.html';
  1196. $baseimg = $dir.'/'.$base.'.'.$this->img->img_format;
  1197. $timedout=false;
  1198. // Does it exist at all ?
  1199. if( file_exists($basecsim) && file_exists($baseimg) ) {
  1200. // Check that it hasn't timed out
  1201. $diff=time()-filemtime($basecsim);
  1202. if( $this->csimcachetimeout>0 && ($diff > $this->csimcachetimeout*60) ) {
  1203. $timedout=true;
  1204. @unlink($basecsim);
  1205. @unlink($baseimg);
  1206. }
  1207. else {
  1208. if ($fh = @fopen($basecsim, "r")) {
  1209. fpassthru($fh);
  1210. exit();
  1211. }
  1212. else
  1213. JpGraphError::Raise(" Can't open cached CSIM \"$basecsim\" for reading.");
  1214. }
  1215. }
  1216. }
  1217. return false;
  1218. }
  1219. function StrokeCSIM($aScriptName='',$aCSIMName='',$aBorder=0) {
  1220. if( $aCSIMName=='' ) {
  1221. // create a random map name
  1222. srand ((double) microtime() * 1000000);
  1223. $r = rand(0,100000);
  1224. $aCSIMName='__mapname'.$r.'__';
  1225. }
  1226. if( empty($_GET[_CSIM_DISPLAY]) ) {
  1227. // First determine if we need to check for a cached version
  1228. // This differs from the standard cache in the sense that the
  1229. // image and CSIM map HTML file is written relative to the directory
  1230. // the script executes in and not the specified cache directory.
  1231. // The reason for this is that the cache directory is not necessarily
  1232. // accessible from the HTTP server.
  1233. if( $this->csimcachename != '' ) {
  1234. $dir = dirname($this->csimcachename);
  1235. $base = basename($this->csimcachename);
  1236. $base = strtok($base,'.');
  1237. $suffix = strtok('.');
  1238. $basecsim = $dir.'/'.$base.'_csim_.html';
  1239. $baseimg = $base.'.'.$this->img->img_format;
  1240. // Check that apache can write to directory specified
  1241. if( file_exists($dir) && !is_writeable($dir) ) {
  1242. JpgraphError::Raise('Apache/PHP does not have permission to write to the CSIM cache directory ('.$dir.'). Check permissions.');
  1243. }
  1244. // Make sure directory exists
  1245. $this->cache->MakeDirs($dir);
  1246. // Write the image file
  1247. $this->Stroke(CSIMCACHE_DIR.$baseimg);
  1248. // Construct wrapper HTML and write to file and send it back to browser
  1249. $htmlwrap = $this->GetHTMLImageMap($aCSIMName)."\n".
  1250. '<img src="'.CSIMCACHE_HTTP_DIR.$baseimg.'" ISMAP USEMAP="#'.$aCSIMName.'" border='.$aBorder.' width='.$this->img->width.' height='.$this->img->height.">\n";
  1251. if($fh = @fopen($basecsim,'w') ) {
  1252. fwrite($fh,$htmlwrap);
  1253. fclose($fh);
  1254. echo $htmlwrap;
  1255. }
  1256. else
  1257. JpGraphError::Raise(" Can't write CSIM \"$basecsim\" for writing. Check free space and permissions.");
  1258. }
  1259. else {
  1260. if( $aScriptName=='' ) {
  1261. JpGraphError::Raise('Missing script name in call to StrokeCSIM(). You must specify the name of the actual image script as the first parameter to StrokeCSIM().');
  1262. exit();
  1263. }
  1264. // This is a JPGRAPH internal defined that prevents
  1265. // us from recursively coming here again
  1266. $urlarg='?'._CSIM_DISPLAY.'=1';
  1267. // Now reconstruct any user URL argument
  1268. reset($_GET);
  1269. while( list($key,$value) = each($_GET) ) {
  1270. if( is_array($value) ) {
  1271. $n = count($value);
  1272. for( $i=0; $i < $n; ++$i ) {
  1273. $urlarg .= '&'.$key.'%5B%5D='.urlencode($value[$i]);
  1274. }
  1275. }
  1276. else {
  1277. $urlarg .= '&'.$key.'='.urlencode($value);
  1278. }
  1279. }
  1280. // It's not ideal to convert POST argument to GET arguments
  1281. // but there is little else we can do. One idea for the
  1282. // future might be recreate the POST header in case.
  1283. reset($_POST);
  1284. while( list($key,$value) = each($_POST) ) {
  1285. if( is_array($value) ) {
  1286. $n = count($value);
  1287. for( $i=0; $i < $n; ++$i ) {
  1288. $urlarg .= '&'.$key.'%5B%5D='.urlencode($value[$i]);
  1289. }
  1290. }
  1291. else {
  1292. $urlarg .= '&'.$key.'='.urlencode($value);
  1293. }
  1294. }
  1295. echo $this->GetHTMLImageMap($aCSIMName);
  1296. echo "<img src='".$aScriptName.$urlarg."' ISMAP USEMAP='#".$aCSIMName.'\' border='.$aBorder.' width='.$this->img->width.' height='.$this->img->height.">\n";
  1297. }
  1298. }
  1299. else {
  1300. $this->Stroke();
  1301. }
  1302. }
  1303. function GetTextsYMinMax($aY2=false) {
  1304. if( $aY2 )
  1305. $txts = $this->y2texts;
  1306. else
  1307. $txts = $this->texts;
  1308. $n = count($txts);
  1309. $min=null;
  1310. $max=null;
  1311. for( $i=0; $i < $n; ++$i ) {
  1312. if( $txts[$i]->iScalePosY !== null &&
  1313. $txts[$i]->iScalePosX !== null ) {
  1314. if( $min === null ) {
  1315. $min = $max = $txts[$i]->iScalePosY ;
  1316. }
  1317. else {
  1318. $min = min($min,$txts[$i]->iScalePosY);
  1319. $max = max($max,$txts[$i]->iScalePosY);
  1320. }
  1321. }
  1322. }
  1323. if( $min !== null ) {
  1324. return array($min,$max);
  1325. }
  1326. else
  1327. return null;
  1328. }
  1329. function GetTextsXMinMax($aY2=false) {
  1330. if( $aY2 )
  1331. $txts = $this->y2texts;
  1332. else
  1333. $txts = $this->texts;
  1334. $n = count($txts);
  1335. $min=null;
  1336. $max=null;
  1337. for( $i=0; $i < $n; ++$i ) {
  1338. if( $txts[$i]->iScalePosY !== null &&
  1339. $txts[$i]->iScalePosX !== null ) {
  1340. if( $min === null ) {
  1341. $min = $max = $txts[$i]->iScalePosX ;
  1342. }
  1343. else {
  1344. $min = min($min,$txts[$i]->iScalePosX);
  1345. $max = max($max,$txts[$i]->iScalePosX);
  1346. }
  1347. }
  1348. }
  1349. if( $min !== null ) {
  1350. return array($min,$max);
  1351. }
  1352. else
  1353. return null;
  1354. }
  1355. function GetXMinMax() {
  1356. list($min,$ymin) = $this->plots[0]->Min();
  1357. list($max,$ymax) = $this->plots[0]->Max();
  1358. foreach( $this->plots as $p ) {
  1359. list($xmin,$ymin) = $p->Min();
  1360. list($xmax,$ymax) = $p->Max();
  1361. $min = Min($xmin,$min);
  1362. $max = Max($xmax,$max);
  1363. }
  1364. if( $this->y2axis != null ) {
  1365. foreach( $this->y2plots as $p ) {
  1366. list($xmin,$ymin) = $p->Min();
  1367. list($xmax,$ymax) = $p->Max();
  1368. $min = Min($xmin,$min);
  1369. $max = Max($xmax,$max);
  1370. }
  1371. }
  1372. $n = count($this->ynaxis);
  1373. for( $i=0; $i < $n; ++$i ) {
  1374. if( $this->ynaxis[$i] != null) {
  1375. foreach( $this->ynplots[$i] as $p ) {
  1376. list($xmin,$ymin) = $p->Min();
  1377. list($xmax,$ymax) = $p->Max();
  1378. $min = Min($xmin,$min);
  1379. $max = Max($xmax,$max);
  1380. }
  1381. }
  1382. }
  1383. return array($min,$max);
  1384. }
  1385. function AdjustMarginsForTitles() {
  1386. $totrequired =
  1387. ($this->title->t != '' ?
  1388. $this->title->GetTextHeight($this->img) + $this->title->margin + 5 : 0 ) +
  1389. ($this->subtitle->t != '' ?
  1390. $this->subtitle->GetTextHeight($this->img) + $this->subtitle->margin + 5 : 0 ) +
  1391. ($this->subsubtitle->t != '' ?
  1392. $this->subsubtitle->GetTextHeight($this->img) + $this->subsubtitle->margin + 5 : 0 ) ;
  1393. $btotrequired = 0;
  1394. if($this->xaxis != null && !$this->xaxis->hide && !$this->xaxis->hide_labels ) {
  1395. // Minimum bottom margin
  1396. if( $this->xaxis->title->t != '' ) {
  1397. if( $this->img->a == 90 )
  1398. $btotrequired = $this->yaxis->title->GetTextHeight($this->img) + 5 ;
  1399. else
  1400. $btotrequired = $this->xaxis->title->GetTextHeight($this->img) + 5 ;
  1401. }
  1402. else
  1403. $btotrequired = 0;
  1404. if( $this->img->a == 90 ) {
  1405. $this->img->SetFont($this->yaxis->font_family,$this->yaxis->font_style,
  1406. $this->yaxis->font_size);
  1407. $lh = $this->img->GetTextHeight('Mg',$this->yaxis->label_angle);
  1408. }
  1409. else {
  1410. $this->img->SetFont($this->xaxis->font_family,$this->xaxis->font_style,
  1411. $this->xaxis->font_size);
  1412. $lh = $this->img->GetTextHeight('Mg',$this->xaxis->label_angle);
  1413. }
  1414. $btotrequired += $lh + 5;
  1415. }
  1416. if( $this->img->a == 90 ) {
  1417. // DO Nothing. It gets too messy to do this properly for 90 deg...
  1418. }
  1419. else{
  1420. if( $this->img->top_margin < $totrequired ) {
  1421. $this->SetMargin($this->img->left_margin,$this->img->right_margin,
  1422. $totrequired,$this->img->bottom_margin);
  1423. }
  1424. if( $this->img->bottom_margin < $btotrequired ) {
  1425. $this->SetMargin($this->img->left_margin,$this->img->right_margin,
  1426. $this->img->top_margin,$btotrequired);
  1427. }
  1428. }
  1429. }
  1430. // Stroke the graph
  1431. // $aStrokeFileName If != "" the image will be written to this file and NOT
  1432. // streamed back to the browser
  1433. function Stroke($aStrokeFileName="") {
  1434. // Fist make a sanity check that user has specified a scale
  1435. if( empty($this->yscale) ) {
  1436. JpGraphError::Raise('You must specify what scale to use with a call to Graph::SetScale().');
  1437. }
  1438. // Start by adjusting the margin so that potential titles will fit.
  1439. $this->AdjustMarginsForTitles();
  1440. // Setup scale constants
  1441. if( $this->yscale ) $this->yscale->InitConstants($this->img);
  1442. if( $this->xscale ) $this->xscale->InitConstants($this->img);
  1443. if( $this->y2scale ) $this->y2scale->InitConstants($this->img);
  1444. $n=count($this->ynscale);
  1445. for($i=0; $i < $n; ++$i) {
  1446. if( $this->ynscale[$i] ) $this->ynscale[$i]->InitConstants($this->img);
  1447. }
  1448. // If the filename is the predefined value = '_csim_special_'
  1449. // we assume that the call to stroke only needs to do enough
  1450. // to correctly generate the CSIM maps.
  1451. // We use this variable to skip things we don't strictly need
  1452. // to do to generate the image map to improve performance
  1453. // a best we can. Therefor you will see a lot of tests !$_csim in the
  1454. // code below.
  1455. $_csim = ($aStrokeFileName===_CSIM_SPECIALFILE);
  1456. // We need to know if we have stroked the plot in the
  1457. // GetCSIMareas. Otherwise the CSIM hasn't been generated
  1458. // and in the case of GetCSIM called before stroke to generate
  1459. // CSIM without storing an image to disk GetCSIM must call Stroke.
  1460. $this->iHasStroked = true;
  1461. // Do any pre-stroke adjustment that is needed by the different plot types
  1462. // (i.e bar plots want's to add an offset to the x-labels etc)
  1463. for($i=0; $i < count($this->plots) ; ++$i ) {
  1464. $this->plots[$i]->PreStrokeAdjust($this);
  1465. $this->plots[$i]->DoLegend($this);
  1466. }
  1467. // Any plots on the second Y scale?
  1468. if( $this->y2scale != null ) {
  1469. for($i=0; $i<count($this->y2plots) ; ++$i ) {
  1470. $this->y2plots[$i]->PreStrokeAdjust($this);
  1471. $this->y2plots[$i]->DoLegend($this);
  1472. }
  1473. }
  1474. // Any plots on the multiple Y scales?
  1475. $n = count($this->ynaxis);
  1476. for($i=0; $i<$n ; ++$i ) {
  1477. if( $this->ynplots == null || $this->ynplots[$i] == null) {
  1478. JpGraphError::Raise("No plots for Y-axis nbr:$i");
  1479. }
  1480. $m = count($this->ynplots[$i]);
  1481. for($j=0; $j < $m; ++$j ) {
  1482. $this->ynplots[$i][$j]->PreStrokeAdjust($this);
  1483. $this->ynplots[$i][$j]->DoLegend($this);
  1484. }
  1485. }
  1486. // Bail out if any of the Y-axis not been specified and
  1487. // has no plots. (This means it is impossible to do autoscaling and
  1488. // no other scale was given so we can't possible draw anything). If you use manual
  1489. // scaling you also have to supply the tick steps as well.
  1490. if( (!$this->yscale->IsSpecified() && count($this->plots)==0) ||
  1491. ($this->y2scale!=null && !$this->y2scale->IsSpecified() && count($this->y2plots)==0) ) {
  1492. //$e = "n=".count($this->y2plots)."\n";
  1493. $e = "Can't draw unspecified Y-scale.<br>\nYou have either:<br>\n";
  1494. $e .= "1. Specified an Y axis for autoscaling but have not supplied any plots<br>\n";
  1495. $e .= "2. Specified a scale manually but have forgot to specify the tick steps";
  1496. JpGraphError::Raise($e);
  1497. }
  1498. // Bail out if no plots and no specified X-scale
  1499. if( (!$this->xscale->IsSpecified() && count($this->plots)==0 && count($this->y2plots)==0) )
  1500. JpGraphError::Raise("<strong>JpGraph: Can't draw unspecified X-scale.</strong><br>No plots.<br>");
  1501. //Check if we should autoscale y-axis
  1502. if( !$this->yscale->IsSpecified() && count($this->plots)>0 ) {
  1503. list($min,$max) = $this->GetPlotsYMinMax($this->plots);
  1504. $lres = $this->GetLinesYMinMax($this->lines);
  1505. if( is_array($lres) ) {
  1506. list($linmin,$linmax) = $lres ;
  1507. $min = min($min,$linmin);
  1508. $max = max($max,$linmax);
  1509. }
  1510. $tres = $this->GetTextsYMinMax();
  1511. if( is_array($tres) ) {
  1512. list($tmin,$tmax) = $tres ;
  1513. $min = min($min,$tmin);
  1514. $max = max($max,$tmax);
  1515. }
  1516. $this->yscale->AutoScale($this->img,$min,$max,
  1517. $this->img->plotheight/$this->ytick_factor);
  1518. }
  1519. elseif( $this->yscale->IsSpecified() &&
  1520. ( $this->yscale->auto_ticks || !$this->yscale->ticks->IsSpecified()) ) {
  1521. // The tick calculation will use the user suplied min/max values to determine
  1522. // the ticks. If auto_ticks is false the exact user specifed min and max
  1523. // values will be used for the scale.
  1524. // If auto_ticks is true then the scale might be slightly adjusted
  1525. // so that the min and max values falls on an even major step.
  1526. $min = $this->yscale->scale[0];
  1527. $max = $this->yscale->scale[1];
  1528. $this->yscale->AutoScale($this->img,$min,$max,
  1529. $this->img->plotheight/$this->ytick_factor,
  1530. $this->yscale->auto_ticks);
  1531. }
  1532. if( $this->y2scale != null) {
  1533. if( !$this->y2scale->IsSpecified() && count($this->y2plots)>0 ) {
  1534. list($min,$max) = $this->GetPlotsYMinMax($this->y2plots);
  1535. $lres = $this->GetLinesYMinMax($this->y2lines);
  1536. if( is_array($lres) ) {
  1537. list($linmin,$linmax) = $lres ;
  1538. $min = min($min,$linmin);
  1539. $max = max($max,$linmax);
  1540. }
  1541. $tres = $this->GetTextsYMinMax(true);
  1542. if( is_array($tres) ) {
  1543. list($tmin,$tmax) = $tres ;
  1544. $min = min($min,$tmin);
  1545. $max = max($max,$tmax);
  1546. }
  1547. $this->y2scale->AutoScale($this->img,$min,$max,$this->img->plotheight/$this->ytick_factor);
  1548. }
  1549. elseif( $this->y2scale->IsSpecified() &&
  1550. ( $this->y2scale->auto_ticks || !$this->y2scale->ticks->IsSpecified()) ) {
  1551. // The tick calculation will use the user suplied min/max values to determine
  1552. // the ticks. If auto_ticks is false the exact user specifed min and max
  1553. // values will be used for the scale.
  1554. // If auto_ticks is true then the scale might be slightly adjusted
  1555. // so that the min and max values falls on an even major step.
  1556. $min = $this->y2scale->scale[0];
  1557. $max = $this->y2scale->scale[1];
  1558. $this->y2scale->AutoScale($this->img,$min,$max,
  1559. $this->img->plotheight/$this->ytick_factor,
  1560. $this->y2scale->auto_ticks);
  1561. }
  1562. }
  1563. //
  1564. // Autoscale the multiple Y-axis
  1565. //
  1566. $n = count($this->ynaxis);
  1567. for( $i=0; $i < $n; ++$i ) {
  1568. if( $this->ynscale[$i] != null) {
  1569. if( !$this->ynscale[$i]->IsSpecified() && count($this->ynplots[$i])>0 ) {
  1570. list($min,$max) = $this->GetPlotsYMinMax($this->ynplots[$i]);
  1571. $this->ynscale[$i]->AutoScale($this->img,$min,$max,$this->img->plotheight/$this->ytick_factor);
  1572. }
  1573. elseif( $this->ynscale[$i]->IsSpecified() &&
  1574. ( $this->ynscale[$i]->auto_ticks || !$this->ynscale[$i]->ticks->IsSpecified()) ) {
  1575. // The tick calculation will use the user suplied min/max values to determine
  1576. // the ticks. If auto_ticks is false the exact user specifed min and max
  1577. // values will be used for the scale.
  1578. // If auto_ticks is true then the scale might be slightly adjusted
  1579. // so that the min and max values falls on an even major step.
  1580. $min = $this->ynscale[$i]->scale[0];
  1581. $max = $this->ynscale[$i]->scale[1];
  1582. $this->ynscale[$i]->AutoScale($this->img,$min,$max,
  1583. $this->img->plotheight/$this->ytick_factor,
  1584. $this->ynscale[$i]->auto_ticks);
  1585. }
  1586. }
  1587. }
  1588. //Check if we should autoscale x-axis
  1589. if( !$this->xscale->IsSpecified() ) {
  1590. if( substr($this->axtype,0,4) == "text" ) {
  1591. $max=0;
  1592. foreach( $this->plots as $p ) {
  1593. $max=max($max,$p->numpoints-1);
  1594. }
  1595. $min=0;
  1596. if( $this->y2axis != null ) {
  1597. foreach( $this->y2plots as $p ) {
  1598. $max=max($max,$p->numpoints-1);
  1599. }
  1600. }
  1601. $n = count($this->ynaxis);
  1602. for( $i=0; $i < $n; ++$i ) {
  1603. if( $this->ynaxis[$i] != null) {
  1604. foreach( $this->ynplots[$i] as $p ) {
  1605. $max=max($max,$p->numpoints-1);
  1606. }
  1607. }
  1608. }
  1609. $this->xscale->Update($this->img,$min,$max);
  1610. $this->xscale->ticks->Set($this->xaxis->tick_step,1);
  1611. $this->xscale->ticks->SupressMinorTickMarks();
  1612. }
  1613. else {
  1614. list($min,$max) = $this->GetXMinMax();
  1615. $lres = $this->GetLinesXMinMax($this->lines);
  1616. if( $lres ) {
  1617. list($linmin,$linmax) = $lres ;
  1618. $min = min($min,$linmin);
  1619. $max = max($max,$linmax);
  1620. }
  1621. $lres = $this->GetLinesXMinMax($this->y2lines);
  1622. if( $lres ) {
  1623. list($linmin,$linmax) = $lres ;
  1624. $min = min($min,$linmin);
  1625. $max = max($max,$linmax);
  1626. }
  1627. $tres = $this->GetTextsXMinMax();
  1628. if( $tres ) {
  1629. list($tmin,$tmax) = $tres ;
  1630. $min = min($min,$tmin);
  1631. $max = max($max,$tmax);
  1632. }
  1633. $tres = $this->GetTextsXMinMax(true);
  1634. if( $tres ) {
  1635. list($tmin,$tmax) = $tres ;
  1636. $min = min($min,$tmin);
  1637. $max = max($max,$tmax);
  1638. }
  1639. $this->xscale->AutoScale($this->img,$min,$max,round($this->img->plotwidth/$this->xtick_factor));
  1640. }
  1641. //Adjust position of y-axis and y2-axis to minimum/maximum of x-scale
  1642. if( !is_numeric($this->yaxis->pos) && !is_string($this->yaxis->pos) )
  1643. $this->yaxis->SetPos($this->xscale->GetMinVal());
  1644. if( $this->y2axis != null ) {
  1645. if( !is_numeric($this->y2axis->pos) && !is_string($this->y2axis->pos) )
  1646. $this->y2axis->SetPos($this->xscale->GetMaxVal());
  1647. $this->y2axis->SetTitleSide(SIDE_RIGHT);
  1648. }
  1649. $n = count($this->ynaxis);
  1650. $nY2adj = $this->y2axis != null ? $this->iYAxisDeltaPos : 0;
  1651. for( $i=0; $i < $n; ++$i ) {
  1652. if( $this->ynaxis[$i] != null ) {
  1653. if( !is_numeric($this->ynaxis[$i]->pos) && !is_string($this->ynaxis[$i]->pos) ) {
  1654. $this->ynaxis[$i]->SetPos($this->xscale->GetMaxVal());
  1655. $this->ynaxis[$i]->SetPosAbsDelta($i*$this->iYAxisDeltaPos + $nY2adj);
  1656. }
  1657. $this->ynaxis[$i]->SetTitleSide(SIDE_RIGHT);
  1658. }
  1659. }
  1660. }
  1661. elseif( $this->xscale->IsSpecified() &&
  1662. ( $this->xscale->auto_ticks || !$this->xscale->ticks->IsSpecified()) ) {
  1663. // The tick calculation will use the user suplied min/max values to determine
  1664. // the ticks. If auto_ticks is false the exact user specifed min and max
  1665. // values will be used for the scale.
  1666. // If auto_ticks is true then the scale might be slightly adjusted
  1667. // so that the min and max values falls on an even major step.
  1668. $min = $this->xscale->scale[0];
  1669. $max = $this->xscale->scale[1];
  1670. $this->xscale->AutoScale($this->img,$min,$max,
  1671. $this->img->plotwidth/$this->xtick_factor,
  1672. false);
  1673. if( $this->y2axis != null ) {
  1674. if( !is_numeric($this->y2axis->pos) && !is_string($this->y2axis->pos) )
  1675. $this->y2axis->SetPos($this->xscale->GetMaxVal());
  1676. $this->y2axis->SetTitleSide(SIDE_RIGHT);
  1677. }
  1678. }
  1679. // If we have a negative values and x-axis position is at 0
  1680. // we need to supress the first and possible the last tick since
  1681. // they will be drawn on top of the y-axis (and possible y2 axis)
  1682. // The test below might seem strange the reasone being that if
  1683. // the user hasn't specified a value for position this will not
  1684. // be set until we do the stroke for the axis so as of now it
  1685. // is undefined.
  1686. // For X-text scale we ignore all this since the tick are usually
  1687. // much further in and not close to the Y-axis. Hence the test
  1688. // for 'text'
  1689. if( ($this->yaxis->pos==$this->xscale->GetMinVal() ||
  1690. (is_string($this->yaxis->pos) && $this->yaxis->pos=='min')) &&
  1691. !is_numeric($this->xaxis->pos) && $this->yscale->GetMinVal() < 0 &&
  1692. substr($this->axtype,0,4) != 'text' && $this->xaxis->pos!="min" ) {
  1693. //$this->yscale->ticks->SupressZeroLabel(false);
  1694. $this->xscale->ticks->SupressFirst();
  1695. if( $this->y2axis != null ) {
  1696. $this->xscale->ticks->SupressLast();
  1697. }
  1698. }
  1699. elseif( !is_numeric($this->yaxis->pos) && $this->yaxis->pos=='max' ) {
  1700. $this->xscale->ticks->SupressLast();
  1701. }
  1702. if( !$_csim ) {
  1703. $this->StrokePlotArea();
  1704. if( $this->iIconDepth == DEPTH_BACK ) {
  1705. $this->StrokeIcons();
  1706. }
  1707. }
  1708. $this->StrokeAxis();
  1709. // Stroke bands
  1710. if( $this->bands != null && !$_csim)
  1711. for($i=0; $i < count($this->bands); ++$i) {
  1712. // Stroke all bands that asks to be in the background
  1713. if( $this->bands[$i]->depth == DEPTH_BACK )
  1714. $this->bands[$i]->Stroke($this->img,$this->xscale,$this->yscale);
  1715. }
  1716. if( $this->y2bands != null && $this->y2scale != null && !$_csim )
  1717. for($i=0; $i < count($this->y2bands); ++$i) {
  1718. // Stroke all bands that asks to be in the foreground
  1719. if( $this->y2bands[$i]->depth == DEPTH_BACK )
  1720. $this->y2bands[$i]->Stroke($this->img,$this->xscale,$this->y2scale);
  1721. }
  1722. if( $this->grid_depth == DEPTH_BACK && !$_csim) {
  1723. $this->ygrid->Stroke();
  1724. $this->xgrid->Stroke();
  1725. }
  1726. // Stroke Y2-axis
  1727. if( $this->y2axis != null && !$_csim) {
  1728. $this->y2axis->Stroke($this->xscale);
  1729. $this->y2grid->Stroke();
  1730. }
  1731. // Stroke yn-axis
  1732. $n = count($this->ynaxis);
  1733. for( $i=0; $i < $n; ++$i ) {
  1734. $this->ynaxis[$i]->Stroke($this->xscale);
  1735. }
  1736. $oldoff=$this->xscale->off;
  1737. if(substr($this->axtype,0,4)=="text") {
  1738. $this->xscale->off +=
  1739. ceil($this->xscale->scale_factor*$this->text_scale_off*$this->xscale->ticks->minor_step);
  1740. }
  1741. if( $this->iDoClipping ) {
  1742. $oldimage = $this->img->CloneCanvasH();
  1743. }
  1744. if( ! $this->y2orderback ) {
  1745. // Stroke all plots for Y axis
  1746. for($i=0; $i < count($this->plots); ++$i) {
  1747. $this->plots[$i]->Stroke($this->img,$this->xscale,$this->yscale);
  1748. $this->plots[$i]->StrokeMargin($this->img);
  1749. }
  1750. }
  1751. // Stroke all plots for Y2 axis
  1752. if( $this->y2scale != null )
  1753. for($i=0; $i< count($this->y2plots); ++$i ) {
  1754. $this->y2plots[$i]->Stroke($this->img,$this->xscale,$this->y2scale);
  1755. }
  1756. if( $this->y2orderback ) {
  1757. // Stroke all plots for Y1 axis
  1758. for($i=0; $i < count($this->plots); ++$i) {
  1759. $this->plots[$i]->Stroke($this->img,$this->xscale,$this->yscale);
  1760. $this->plots[$i]->StrokeMargin($this->img);
  1761. }
  1762. }
  1763. $n = count($this->ynaxis);
  1764. for( $i=0; $i < $n; ++$i ) {
  1765. $m = count($this->ynplots[$i]);
  1766. for( $j=0; $j < $m; ++$j ) {
  1767. $this->ynplots[$i][$j]->Stroke($this->img,$this->xscale,$this->ynscale[$i]);
  1768. $this->ynplots[$i][$j]->StrokeMargin($this->img);
  1769. }
  1770. }
  1771. if( $this->iIconDepth == DEPTH_FRONT) {
  1772. $this->StrokeIcons();
  1773. }
  1774. if( $this->iDoClipping ) {
  1775. // Clipping only supports graphs at 0 and 90 degrees
  1776. if( $this->img->a == 0 ) {
  1777. $this->img->CopyCanvasH($oldimage,$this->img->img,
  1778. $this->img->left_margin,$this->img->top_margin,
  1779. $this->img->left_margin,$this->img->top_margin,
  1780. $this->img->plotwidth+1,$this->img->plotheight);
  1781. }
  1782. elseif( $this->img->a == 90 ) {
  1783. $adj = ($this->img->height - $this->img->width)/2;
  1784. $this->img->CopyCanvasH($oldimage,$this->img->img,
  1785. $this->img->bottom_margin-$adj,$this->img->left_margin+$adj,
  1786. $this->img->bottom_margin-$adj,$this->img->left_margin+$adj,
  1787. $this->img->plotheight+1,$this->img->plotwidth);
  1788. }
  1789. else {
  1790. JpGraphError::Raise('You have enabled clipping. Cliping is only supported for graphs at 0 or 90 degrees rotation. Please adjust you current angle (='.$this->img->a.' degrees) or disable clipping.');
  1791. }
  1792. $this->img->Destroy();
  1793. $this->img->SetCanvasH($oldimage);
  1794. }
  1795. $this->xscale->off=$oldoff;
  1796. if( $this->grid_depth == DEPTH_FRONT && !$_csim ) {
  1797. $this->ygrid->Stroke();
  1798. $this->xgrid->Stroke();
  1799. }
  1800. // Stroke bands
  1801. if( $this->bands!= null )
  1802. for($i=0; $i < count($this->bands); ++$i) {
  1803. // Stroke all bands that asks to be in the foreground
  1804. if( $this->bands[$i]->depth == DEPTH_FRONT )
  1805. $this->bands[$i]->Stroke($this->img,$this->xscale,$this->yscale);
  1806. }
  1807. if( $this->y2bands!= null && $this->y2scale != null )
  1808. for($i=0; $i < count($this->y2bands); ++$i) {
  1809. // Stroke all bands that asks to be in the foreground
  1810. if( $this->y2bands[$i]->depth == DEPTH_FRONT )
  1811. $this->y2bands[$i]->Stroke($this->img,$this->xscale,$this->y2scale);
  1812. }
  1813. // Stroke any lines added
  1814. if( $this->lines != null ) {
  1815. for($i=0; $i < count($this->lines); ++$i) {
  1816. $this->lines[$i]->Stroke($this->img,$this->xscale,$this->yscale);
  1817. }
  1818. }
  1819. if( $this->y2lines != null && $this->y2scale != null ) {
  1820. for($i=0; $i < count($this->y2lines); ++$i) {
  1821. $this->y2lines[$i]->Stroke($this->img,$this->xscale,$this->y2scale);
  1822. }
  1823. }
  1824. // Finally draw the axis again since some plots may have nagged
  1825. // the axis in the edges.However we do no stroke the labels again
  1826. // since any user defined callback would be called twice. It also
  1827. // enhances performance.
  1828. if( !$_csim )
  1829. $this->StrokeAxis(false);
  1830. if( $this->y2scale != null && !$_csim )
  1831. $this->y2axis->Stroke($this->xscale,false);
  1832. if( !$_csim ) {
  1833. $this->StrokePlotBox();
  1834. }
  1835. // The titles and legends never gets rotated so make sure
  1836. // that the angle is 0 before stroking them
  1837. $aa = $this->img->SetAngle(0);
  1838. $this->StrokeTitles();
  1839. $this->footer->Stroke($this->img);
  1840. $this->legend->Stroke($this->img);
  1841. $this->img->SetAngle($aa);
  1842. $this->StrokeTexts();
  1843. if( !$_csim ) {
  1844. $this->img->SetAngle($aa);
  1845. // Draw an outline around the image map
  1846. if(_JPG_DEBUG) {
  1847. $this->DisplayClientSideaImageMapAreas();
  1848. }
  1849. // Adjust the appearance of the image
  1850. $this->AdjustSaturationBrightnessContrast();
  1851. // Should we do any final image transformation
  1852. if( $this->iImgTrans ) {
  1853. if( !class_exists('ImgTrans') ) {
  1854. require_once('jpgraph_imgtrans.php');
  1855. //JpGraphError::Raise('In order to use image transformation you must include the file jpgraph_imgtrans.php in your script.');
  1856. }
  1857. $tform = new ImgTrans($this->img->img);
  1858. $this->img->img = $tform->Skew3D($this->iImgTransHorizon,$this->iImgTransSkewDist,
  1859. $this->iImgTransDirection,$this->iImgTransHighQ,
  1860. $this->iImgTransMinSize,$this->iImgTransFillColor,
  1861. $this->iImgTransBorder);
  1862. }
  1863. // If the filename is given as the special "__handle"
  1864. // then the image handler is returned and the image is NOT
  1865. // streamed back
  1866. if( $aStrokeFileName == _IMG_HANDLER ) {
  1867. return $this->img->img;
  1868. }
  1869. else {
  1870. // Finally stream the generated picture
  1871. $this->cache->PutAndStream($this->img,$this->cache_name,$this->inline,$aStrokeFileName);
  1872. }
  1873. }
  1874. }
  1875. //---------------
  1876. // PRIVATE METHODS
  1877. function StrokeAxis($aStrokeLabels=true) {
  1878. // Stroke axis
  1879. if( $this->iAxisStyle != AXSTYLE_SIMPLE ) {
  1880. switch( $this->iAxisStyle ) {
  1881. case AXSTYLE_BOXIN :
  1882. $toppos = SIDE_DOWN;
  1883. $bottompos = SIDE_UP;
  1884. $leftpos = SIDE_RIGHT;
  1885. $rightpos = SIDE_LEFT;
  1886. break;
  1887. case AXSTYLE_BOXOUT :
  1888. $toppos = SIDE_UP;
  1889. $bottompos = SIDE_DOWN;
  1890. $leftpos = SIDE_LEFT;
  1891. $rightpos = SIDE_RIGHT;
  1892. break;
  1893. case AXSTYLE_YBOXIN:
  1894. $toppos = -100;
  1895. $bottompos = SIDE_UP;
  1896. $leftpos = SIDE_RIGHT;
  1897. $rightpos = SIDE_LEFT;
  1898. break;
  1899. case AXSTYLE_YBOXOUT:
  1900. $toppos = -100;
  1901. $bottompos = SIDE_DOWN;
  1902. $leftpos = SIDE_LEFT;
  1903. $rightpos = SIDE_RIGHT;
  1904. break;
  1905. default:
  1906. JpGRaphError::Raise('Unknown AxisStyle() : '.$this->iAxisStyle);
  1907. break;
  1908. }
  1909. $this->xaxis->SetPos('min');
  1910. // By default we hide the first label so it doesn't cross the
  1911. // Y-axis in case the positon hasn't been set by the user.
  1912. // However, if we use a box we always want the first value
  1913. // displayed so we make sure it will be displayed.
  1914. $this->xscale->ticks->SupressFirst(false);
  1915. $this->xaxis->SetLabelSide(SIDE_DOWN);
  1916. $this->xaxis->scale->ticks->SetSide($bottompos);
  1917. $this->xaxis->Stroke($this->yscale);
  1918. if( $toppos != -100 ) {
  1919. // To avoid side effects we work on a new copy
  1920. $maxis = $this->xaxis;
  1921. $maxis->SetPos('max');
  1922. $maxis->SetLabelSide(SIDE_UP);
  1923. $maxis->SetLabelMargin(7);
  1924. $this->xaxis->scale->ticks->SetSide($toppos);
  1925. $maxis->Stroke($this->yscale);
  1926. }
  1927. $this->yaxis->SetPos('min');
  1928. $this->yaxis->SetLabelMargin(10);
  1929. $this->yaxis->SetLabelSide(SIDE_LEFT);
  1930. $this->yaxis->scale->ticks->SetSide($leftpos);
  1931. $this->yaxis->Stroke($this->xscale);
  1932. $myaxis = $this->yaxis;
  1933. $myaxis->SetPos('max');
  1934. $myaxis->SetLabelMargin(10);
  1935. $myaxis->SetLabelSide(SIDE_RIGHT);
  1936. $myaxis->title->Set('');
  1937. $myaxis->scale->ticks->SetSide($rightpos);
  1938. $myaxis->Stroke($this->xscale);
  1939. }
  1940. else {
  1941. $this->xaxis->Stroke($this->yscale,$aStrokeLabels);
  1942. $this->yaxis->Stroke($this->xscale,$aStrokeLabels);
  1943. }
  1944. }
  1945. // Private helper function for backgound image
  1946. function LoadBkgImage($aImgFormat='',$aFile='') {
  1947. if( $aFile == '' )
  1948. $aFile = $this->background_image;
  1949. // Remove case sensitivity and setup appropriate function to create image
  1950. // Get file extension. This should be the LAST '.' separated part of the filename
  1951. $e = explode('.',$aFile);
  1952. $ext = strtolower($e[count($e)-1]);
  1953. if ($ext == "jpeg") {
  1954. $ext = "jpg";
  1955. }
  1956. if( trim($ext) == '' )
  1957. $ext = 'png'; // Assume PNG if no extension specified
  1958. if( $aImgFormat == '' )
  1959. $imgtag = $ext;
  1960. else
  1961. $imgtag = $aImgFormat;
  1962. $supported = imagetypes();
  1963. if( ( $ext == 'jpg' && !($supported & IMG_JPG) ) ||
  1964. ( $ext == 'gif' && !($supported & IMG_GIF) ) ||
  1965. ( $ext == 'png' && !($supported & IMG_PNG) ) ) {
  1966. JpGraphError::Raise('The image format of your background image ('.$aFile.') is not supported in your system configuration. ');
  1967. }
  1968. if( $imgtag == "jpg" || $imgtag == "jpeg")
  1969. {
  1970. $f = "imagecreatefromjpeg";
  1971. $imgtag = "jpg";
  1972. }
  1973. else
  1974. {
  1975. $f = "imagecreatefrom".$imgtag;
  1976. }
  1977. // Compare specified image type and file extension
  1978. if( $imgtag != $ext ) {
  1979. $t = " Background image seems to be of different type (has different file extension)".
  1980. " than specified imagetype. Specified: '".
  1981. $aImgFormat."'File: '".$aFile."'";
  1982. JpGraphError::Raise($t);
  1983. }
  1984. $img = @$f($aFile);
  1985. if( !$img ) {
  1986. JpGraphError::Raise(" Can't read background image: '".$aFile."'");
  1987. }
  1988. return $img;
  1989. }
  1990. function StrokeBackgroundGrad() {
  1991. if( $this->bkg_gradtype < 0 )
  1992. return;
  1993. $grad = new Gradient($this->img);
  1994. if( $this->bkg_gradstyle == BGRAD_PLOT ) {
  1995. $xl = $this->img->left_margin;
  1996. $yt = $this->img->top_margin;
  1997. $xr = $xl + $this->img->plotwidth+1 ;
  1998. $yb = $yt + $this->img->plotheight ;
  1999. }
  2000. else {
  2001. $xl = 0;
  2002. $yt = 0;
  2003. $xr = $xl + $this->img->width - 1;
  2004. $yb = $yt + $this->img->height - 1;
  2005. if( $this->doshadow ) {
  2006. $xr -= $this->shadow_width;
  2007. $yb -= $this->shadow_width;
  2008. }
  2009. }
  2010. if( $this->doframe ) {
  2011. $xl += $this->frame_weight;
  2012. $xr -= $this->frame_weight;
  2013. }
  2014. $grad->FilledRectangle($xl,$yt,$xr,$yb,
  2015. $this->bkg_gradfrom,$this->bkg_gradto,
  2016. $this->bkg_gradtype);
  2017. }
  2018. function StrokeFrameBackground() {
  2019. if( $this->background_image != "" && $this->background_cflag != "" ) {
  2020. JpGraphError::Raise('It is not possible to specify both a background image and a background country flag.');
  2021. }
  2022. if( $this->background_image != "" ) {
  2023. $bkgimg = $this->LoadBkgImage($this->background_image_format);
  2024. $this->img->_AdjBrightContrast($bkgimg,$this->background_image_bright,
  2025. $this->background_image_contr);
  2026. $this->img->_AdjSat($bkgimg,$this->background_image_sat);
  2027. }
  2028. elseif( $this->background_cflag != "" ) {
  2029. if( ! class_exists('FlagImages') ) {
  2030. JpGraphError::Raise('In order to use Country flags as
  2031. backgrounds you must include the "jpgraph_flags.php" file.');
  2032. }
  2033. $fobj = new FlagImages(FLAGSIZE4);
  2034. $dummy='';
  2035. $bkgimg = $fobj->GetImgByName($this->background_cflag,$dummy);
  2036. $this->background_image_mix = $this->background_cflag_mix;
  2037. $this->background_image_type = $this->background_cflag_type;
  2038. }
  2039. else {
  2040. return ;
  2041. }
  2042. $bw = ImageSX($bkgimg);
  2043. $bh = ImageSY($bkgimg);
  2044. // No matter what the angle is we always stroke the image and frame
  2045. // assuming it is 0 degree
  2046. $aa = $this->img->SetAngle(0);
  2047. switch( $this->background_image_type ) {
  2048. case BGIMG_FILLPLOT: // Resize to just fill the plotarea
  2049. $this->FillMarginArea();
  2050. $this->StrokeFrame();
  2051. $this->FillPlotArea();
  2052. $this->img->CopyMerge($bkgimg,
  2053. $this->img->left_margin,$this->img->top_margin,
  2054. 0,0,$this->img->plotwidth+1,$this->img->plotheight,
  2055. $bw,$bh,$this->background_image_mix);
  2056. break;
  2057. case BGIMG_FILLFRAME: // Fill the whole area from upper left corner, resize to just fit
  2058. $hadj=0; $vadj=0;
  2059. if( $this->doshadow ) {
  2060. $hadj = $this->shadow_width;
  2061. $vadj = $this->shadow_width;
  2062. }
  2063. $this->FillMarginArea();
  2064. $this->FillPlotArea();
  2065. $this->img->CopyMerge($bkgimg,0,0,0,0,$this->img->width-$hadj,$this->img->height-$vadj,
  2066. $bw,$bh,$this->background_image_mix);
  2067. $this->StrokeFrame();
  2068. break;
  2069. case BGIMG_COPY: // Just copy the image from left corner, no resizing
  2070. $this->FillMarginArea();
  2071. $this->FillPlotArea();
  2072. $this->img->CopyMerge($bkgimg,0,0,0,0,$bw,$bh,
  2073. $bw,$bh,$this->background_image_mix);
  2074. $this->StrokeFrame();
  2075. break;
  2076. case BGIMG_CENTER: // Center original image in the plot area
  2077. $this->FillMarginArea();
  2078. $this->FillPlotArea();
  2079. $centerx = round($this->img->plotwidth/2+$this->img->left_margin-$bw/2);
  2080. $centery = round($this->img->plotheight/2+$this->img->top_margin-$bh/2);
  2081. $this->img->CopyMerge($bkgimg,$centerx,$centery,0,0,$bw,$bh,
  2082. $bw,$bh,$this->background_image_mix);
  2083. $this->StrokeFrame();
  2084. break;
  2085. default:
  2086. JpGraphError::Raise(" Unknown background image layout");
  2087. }
  2088. $this->img->SetAngle($aa);
  2089. }
  2090. // Private
  2091. // Draw a frame around the image
  2092. function StrokeFrame() {
  2093. if( !$this->doframe ) return;
  2094. if( $this->background_image_type <= 1 &&
  2095. ($this->bkg_gradtype < 0 || ($this->bkg_gradtype > 0 && $this->bkg_gradstyle==BGRAD_PLOT)) ) {
  2096. $c = $this->margin_color;
  2097. }
  2098. else {
  2099. $c = false;
  2100. }
  2101. if( $this->doshadow ) {
  2102. $this->img->SetColor($this->frame_color);
  2103. $this->img->ShadowRectangle(0,0,$this->img->width,$this->img->height,
  2104. $c,$this->shadow_width,$this->shadow_color);
  2105. }
  2106. elseif( $this->framebevel ) {
  2107. if( $c ) {
  2108. $this->img->SetColor($this->margin_color);
  2109. $this->img->FilledRectangle(0,0,$this->img->width-1,$this->img->height-1);
  2110. }
  2111. $this->img->Bevel(1,1,$this->img->width-2,$this->img->height-2,
  2112. $this->framebeveldepth,
  2113. $this->framebevelcolor1,$this->framebevelcolor2);
  2114. if( $this->framebevelborder ) {
  2115. $this->img->SetColor($this->framebevelbordercolor);
  2116. $this->img->Rectangle(0,0,$this->img->width-1,$this->img->height-1);
  2117. }
  2118. }
  2119. else {
  2120. $this->img->SetLineWeight($this->frame_weight);
  2121. if( $c ) {
  2122. $this->img->SetColor($this->margin_color);
  2123. $this->img->FilledRectangle(0,0,$this->img->width-1,$this->img->height-1);
  2124. }
  2125. $this->img->SetColor($this->frame_color);
  2126. $this->img->Rectangle(0,0,$this->img->width-1,$this->img->height-1);
  2127. }
  2128. }
  2129. function FillMarginArea() {
  2130. $hadj=0; $vadj=0;
  2131. if( $this->doshadow ) {
  2132. $hadj = $this->shadow_width;
  2133. $vadj = $this->shadow_width;
  2134. }
  2135. $this->img->SetColor($this->margin_color);
  2136. // $this->img->FilledRectangle(0,0,$this->img->width-1-$hadj,$this->img->height-1-$vadj);
  2137. $this->img->FilledRectangle(0,0,$this->img->width-1-$hadj,$this->img->top_margin);
  2138. $this->img->FilledRectangle(0,$this->img->top_margin,$this->img->left_margin,$this->img->height-1-$hadj);
  2139. $this->img->FilledRectangle($this->img->left_margin+1,
  2140. $this->img->height-$this->img->bottom_margin,
  2141. $this->img->width-1-$hadj,
  2142. $this->img->height-1-$hadj);
  2143. $this->img->FilledRectangle($this->img->width-$this->img->right_margin,
  2144. $this->img->top_margin+1,
  2145. $this->img->width-1-$hadj,
  2146. $this->img->height-$this->img->bottom_margin-1);
  2147. }
  2148. function FillPlotArea() {
  2149. $this->img->PushColor($this->plotarea_color);
  2150. $this->img->FilledRectangle($this->img->left_margin,
  2151. $this->img->top_margin,
  2152. $this->img->width-$this->img->right_margin,
  2153. $this->img->height-$this->img->bottom_margin);
  2154. $this->img->PopColor();
  2155. }
  2156. // Stroke the plot area with either a solid color or a background image
  2157. function StrokePlotArea() {
  2158. // Note: To be consistent we really should take a possible shadow
  2159. // into account. However, that causes some problem for the LinearScale class
  2160. // since in the current design it does not have any links to class Graph which
  2161. // means it has no way of compensating for the adjusted plotarea in case of a
  2162. // shadow. So, until I redesign LinearScale we can't compensate for this.
  2163. // So just set the two adjustment parameters to zero for now.
  2164. $boxadj = 0; //$this->doframe ? $this->frame_weight : 0 ;
  2165. $adj = 0; //$this->doshadow ? $this->shadow_width : 0 ;
  2166. if( $this->background_image != "" || $this->background_cflag != "" ) {
  2167. $this->StrokeFrameBackground();
  2168. }
  2169. else {
  2170. $aa = $this->img->SetAngle(0);
  2171. $this->StrokeFrame();
  2172. $aa = $this->img->SetAngle($aa);
  2173. $this->StrokeBackgroundGrad();
  2174. if( $this->bkg_gradtype < 0 ||
  2175. ($this->bkg_gradtype > 0 && $this->bkg_gradstyle==BGRAD_MARGIN) ) {
  2176. $this->FillPlotArea();
  2177. }
  2178. }
  2179. }
  2180. function StrokeIcons() {
  2181. $n = count($this->iIcons);
  2182. for( $i=0; $i < $n; ++$i ) {
  2183. $this->iIcons[$i]->StrokeWithScale($this->img,$this->xscale,$this->yscale);
  2184. }
  2185. }
  2186. function StrokePlotBox() {
  2187. // Should we draw a box around the plot area?
  2188. if( $this->boxed ) {
  2189. $this->img->SetLineWeight(1);
  2190. $this->img->SetLineStyle('solid');
  2191. $this->img->SetColor($this->box_color);
  2192. for($i=0; $i < $this->box_weight; ++$i ) {
  2193. $this->img->Rectangle(
  2194. $this->img->left_margin-$i,$this->img->top_margin-$i,
  2195. $this->img->width-$this->img->right_margin+$i,
  2196. $this->img->height-$this->img->bottom_margin+$i);
  2197. }
  2198. }
  2199. }
  2200. function SetTitleBackgroundFillStyle($aStyle,$aColor1='black',$aColor2='white') {
  2201. $this->titlebkg_fillstyle = $aStyle;
  2202. $this->titlebkg_scolor1 = $aColor1;
  2203. $this->titlebkg_scolor2 = $aColor2;
  2204. }
  2205. function SetTitleBackground($aBackColor='gray', $aStyle=TITLEBKG_STYLE1, $aFrameStyle=TITLEBKG_FRAME_NONE, $aFrameColor='black', $aFrameWeight=1, $aBevelHeight=3, $aEnable=true) {
  2206. $this->titlebackground = $aEnable;
  2207. $this->titlebackground_color = $aBackColor;
  2208. $this->titlebackground_style = $aStyle;
  2209. $this->titlebackground_framecolor = $aFrameColor;
  2210. $this->titlebackground_framestyle = $aFrameStyle;
  2211. $this->titlebackground_frameweight = $aFrameWeight;
  2212. $this->titlebackground_bevelheight = $aBevelHeight ;
  2213. }
  2214. function StrokeTitles() {
  2215. $margin=3;
  2216. if( $this->titlebackground ) {
  2217. // Find out height
  2218. $this->title->margin += 2 ;
  2219. $h = $this->title->GetTextHeight($this->img)+$this->title->margin+$margin;
  2220. if( $this->subtitle->t != "" && !$this->subtitle->hide ) {
  2221. $h += $this->subtitle->GetTextHeight($this->img)+$margin+
  2222. $this->subtitle->margin;
  2223. $h += 2;
  2224. }
  2225. if( $this->subsubtitle->t != "" && !$this->subsubtitle->hide ) {
  2226. $h += $this->subsubtitle->GetTextHeight($this->img)+$margin+
  2227. $this->subsubtitle->margin;
  2228. $h += 2;
  2229. }
  2230. $this->img->PushColor($this->titlebackground_color);
  2231. if( $this->titlebackground_style === TITLEBKG_STYLE1 ) {
  2232. // Inside the frame
  2233. if( $this->framebevel ) {
  2234. $x1 = $y1 = $this->framebeveldepth + 1 ;
  2235. $x2 = $this->img->width - $this->framebeveldepth - 2 ;
  2236. $this->title->margin += $this->framebeveldepth + 1 ;
  2237. $h += $y1 ;
  2238. $h += 2;
  2239. }
  2240. else {
  2241. $x1 = $y1 = $this->frame_weight;
  2242. $x2 = $this->img->width - 2*$x1;
  2243. }
  2244. }
  2245. elseif( $this->titlebackground_style === TITLEBKG_STYLE2 ) {
  2246. // Cover the frame as well
  2247. $x1 = $y1 = 0;
  2248. $x2 = $this->img->width - 1 ;
  2249. }
  2250. elseif( $this->titlebackground_style === TITLEBKG_STYLE3 ) {
  2251. // Cover the frame as well (the difference is that
  2252. // for style==3 a bevel frame border is on top
  2253. // of the title background)
  2254. $x1 = $y1 = 0;
  2255. $x2 = $this->img->width - 1 ;
  2256. $h += $this->framebeveldepth ;
  2257. $this->title->margin += $this->framebeveldepth ;
  2258. }
  2259. else {
  2260. JpGraphError::Raise('Unknown title background style.');
  2261. }
  2262. if( $this->titlebackground_framestyle === 3 ) {
  2263. $h += $this->titlebackground_bevelheight*2 + 1 ;
  2264. $this->title->margin += $this->titlebackground_bevelheight ;
  2265. }
  2266. if( $this->doshadow ) {
  2267. $x2 -= $this->shadow_width ;
  2268. }
  2269. $indent=0;
  2270. if( $this->titlebackground_framestyle == TITLEBKG_FRAME_BEVEL ) {
  2271. $ind = $this->titlebackground_bevelheight;
  2272. }
  2273. if( $this->titlebkg_fillstyle==TITLEBKG_FILLSTYLE_HSTRIPED ) {
  2274. $this->img->FilledRectangle2($x1+$ind,$y1+$ind,$x2-$ind,$h-$ind,
  2275. $this->titlebkg_scolor1,
  2276. $this->titlebkg_scolor2);
  2277. }
  2278. elseif( $this->titlebkg_fillstyle==TITLEBKG_FILLSTYLE_VSTRIPED ) {
  2279. $this->img->FilledRectangle2($x1+$ind,$y1+$ind,$x2-$ind,$h-$ind,
  2280. $this->titlebkg_scolor1,
  2281. $this->titlebkg_scolor2,2);
  2282. }
  2283. else {
  2284. // Solid fill
  2285. $this->img->FilledRectangle($x1,$y1,$x2,$h);
  2286. }
  2287. $this->img->PopColor();
  2288. $this->img->PushColor($this->titlebackground_framecolor);
  2289. $this->img->SetLineWeight($this->titlebackground_frameweight);
  2290. if( $this->titlebackground_framestyle == TITLEBKG_FRAME_FULL ) {
  2291. // Frame background
  2292. $this->img->Rectangle($x1,$y1,$x2,$h);
  2293. }
  2294. elseif( $this->titlebackground_framestyle == TITLEBKG_FRAME_BOTTOM ) {
  2295. // Bottom line only
  2296. $this->img->Line($x1,$h,$x2,$h);
  2297. }
  2298. elseif( $this->titlebackground_framestyle == TITLEBKG_FRAME_BEVEL ) {
  2299. $this->img->Bevel($x1,$y1,$x2,$h,$this->titlebackground_bevelheight);
  2300. }
  2301. $this->img->PopColor();
  2302. // This is clumsy. But we neeed to stroke the whole graph frame if it is
  2303. // set to bevel to get the bevel shading on top of the text background
  2304. if( $this->framebevel && $this->doframe &&
  2305. $this->titlebackground_style === 3 ) {
  2306. $this->img->Bevel(1,1,$this->img->width-2,$this->img->height-2,
  2307. $this->framebeveldepth,
  2308. $this->framebevelcolor1,$this->framebevelcolor2);
  2309. if( $this->framebevelborder ) {
  2310. $this->img->SetColor($this->framebevelbordercolor);
  2311. $this->img->Rectangle(0,0,$this->img->width-1,$this->img->height-1);
  2312. }
  2313. }
  2314. }
  2315. // Stroke title
  2316. $y = $this->title->margin;
  2317. if( $this->title->halign == 'center' )
  2318. $this->title->Center(0,$this->img->width,$y);
  2319. elseif( $this->title->halign == 'left' ) {
  2320. $this->title->SetPos($this->title->margin+2,$y);
  2321. }
  2322. elseif( $this->title->halign == 'right' ) {
  2323. $indent = 0;
  2324. if( $this->doshadow )
  2325. $indent = $this->shadow_width+2;
  2326. $this->title->SetPos($this->img->width-$this->title->margin-$indent,$y,'right');
  2327. }
  2328. $this->title->Stroke($this->img);
  2329. // ... and subtitle
  2330. $y += $this->title->GetTextHeight($this->img) + $margin + $this->subtitle->margin;
  2331. if( $this->subtitle->halign == 'center' )
  2332. $this->subtitle->Center(0,$this->img->width,$y);
  2333. elseif( $this->subtitle->halign == 'left' ) {
  2334. $this->subtitle->SetPos($this->subtitle->margin+2,$y);
  2335. }
  2336. elseif( $this->subtitle->halign == 'right' ) {
  2337. $indent = 0;
  2338. if( $this->doshadow )
  2339. $indent = $this->shadow_width+2;
  2340. $this->subtitle->SetPos($this->img->width-$this->subtitle->margin-$indent,$y,'right');
  2341. }
  2342. $this->subtitle->Stroke($this->img);
  2343. // ... and subsubtitle
  2344. $y += $this->subtitle->GetTextHeight($this->img) + $margin + $this->subsubtitle->margin;
  2345. if( $this->subsubtitle->halign == 'center' )
  2346. $this->subsubtitle->Center(0,$this->img->width,$y);
  2347. elseif( $this->subsubtitle->halign == 'left' ) {
  2348. $this->subsubtitle->SetPos($this->subsubtitle->margin+2,$y);
  2349. }
  2350. elseif( $this->subsubtitle->halign == 'right' ) {
  2351. $indent = 0;
  2352. if( $this->doshadow )
  2353. $indent = $this->shadow_width+2;
  2354. $this->subsubtitle->SetPos($this->img->width-$this->subsubtitle->margin-$indent,$y,'right');
  2355. }
  2356. $this->subsubtitle->Stroke($this->img);
  2357. // ... and fancy title
  2358. $this->tabtitle->Stroke($this->img);
  2359. }
  2360. function StrokeTexts() {
  2361. // Stroke any user added text objects
  2362. if( $this->texts != null ) {
  2363. for($i=0; $i < count($this->texts); ++$i) {
  2364. $this->texts[$i]->StrokeWithScale($this->img,$this->xscale,$this->yscale);
  2365. }
  2366. }
  2367. if( $this->y2texts != null && $this->y2scale != null ) {
  2368. for($i=0; $i < count($this->y2texts); ++$i) {
  2369. $this->y2texts[$i]->StrokeWithScale($this->img,$this->xscale,$this->y2scale);
  2370. }
  2371. }
  2372. }
  2373. function DisplayClientSideaImageMapAreas() {
  2374. // Debug stuff - display the outline of the image map areas
  2375. $csim='';
  2376. foreach ($this->plots as $p) {
  2377. $csim.= $p->GetCSIMareas();
  2378. }
  2379. $csim .= $this->legend->GetCSIMareas();
  2380. if (preg_match_all("/area shape=\"(\w+)\" coords=\"([0-9\, ]+)\"/", $csim, $coords)) {
  2381. $this->img->SetColor($this->csimcolor);
  2382. for ($i=0; $i<count($coords[0]); $i++) {
  2383. if ($coords[1][$i]=="poly") {
  2384. preg_match_all('/\s*([0-9]+)\s*,\s*([0-9]+)\s*,*/',$coords[2][$i],$pts);
  2385. $this->img->SetStartPoint($pts[1][count($pts[0])-1],$pts[2][count($pts[0])-1]);
  2386. for ($j=0; $j<count($pts[0]); $j++) {
  2387. $this->img->LineTo($pts[1][$j],$pts[2][$j]);
  2388. }
  2389. } else if ($coords[1][$i]=="rect") {
  2390. $pts = preg_split('/,/', $coords[2][$i]);
  2391. $this->img->SetStartPoint($pts[0],$pts[1]);
  2392. $this->img->LineTo($pts[2],$pts[1]);
  2393. $this->img->LineTo($pts[2],$pts[3]);
  2394. $this->img->LineTo($pts[0],$pts[3]);
  2395. $this->img->LineTo($pts[0],$pts[1]);
  2396. }
  2397. }
  2398. }
  2399. }
  2400. function AdjustSaturationBrightnessContrast() {
  2401. // Adjust the brightness and contrast of the image
  2402. if( $this->image_contr || $this->image_bright )
  2403. $this->img->AdjBrightContrast($this->image_bright,$this->image_contr);
  2404. if( $this->image_sat )
  2405. $this->img->AdjSat($this->image_sat);
  2406. }
  2407. // Text scale offset in world coordinates
  2408. function SetTextScaleOff($aOff) {
  2409. $this->text_scale_off = $aOff;
  2410. $this->xscale->text_scale_off = $aOff;
  2411. }
  2412. // Get Y min and max values for added lines
  2413. function GetLinesYMinMax( $aLines ) {
  2414. $n = count($aLines);
  2415. if( $n == 0 ) return false;
  2416. $min = $aLines[0]->scaleposition ;
  2417. $max = $min ;
  2418. $flg = false;
  2419. for( $i=0; $i < $n; ++$i ) {
  2420. if( $aLines[$i]->direction == HORIZONTAL ) {
  2421. $flg = true ;
  2422. $v = $aLines[$i]->scaleposition ;
  2423. if( $min > $v ) $min = $v ;
  2424. if( $max < $v ) $max = $v ;
  2425. }
  2426. }
  2427. return $flg ? array($min,$max) : false ;
  2428. }
  2429. // Get X min and max values for added lines
  2430. function GetLinesXMinMax( $aLines ) {
  2431. $n = count($aLines);
  2432. if( $n == 0 ) return false ;
  2433. $min = $aLines[0]->scaleposition ;
  2434. $max = $min ;
  2435. $flg = false;
  2436. for( $i=0; $i < $n; ++$i ) {
  2437. if( $aLines[$i]->direction == VERTICAL ) {
  2438. $flg = true ;
  2439. $v = $aLines[$i]->scaleposition ;
  2440. if( $min > $v ) $min = $v ;
  2441. if( $max < $v ) $max = $v ;
  2442. }
  2443. }
  2444. return $flg ? array($min,$max) : false ;
  2445. }
  2446. // Get min and max values for all included plots
  2447. function GetPlotsYMinMax(&$aPlots) {
  2448. $n = count($aPlots);
  2449. $i=0;
  2450. do {
  2451. list($xmax,$max) = $aPlots[$i]->Max();
  2452. } while( ++$i < $n && !is_numeric($max) );
  2453. $i=0;
  2454. do {
  2455. list($xmin,$min) = $aPlots[$i]->Min();
  2456. } while( ++$i < $n && !is_numeric($min) );
  2457. if( !is_numeric($min) || !is_numeric($max) ) {
  2458. JpGraphError::Raise('Cannot use autoscaling since it is impossible to determine a valid min/max value of the Y-axis (only null values).');
  2459. }
  2460. list($xmax,$max) = $aPlots[0]->Max();
  2461. list($xmin,$min) = $aPlots[0]->Min();
  2462. for($i=0; $i < count($aPlots); ++$i ) {
  2463. list($xmax,$ymax)=$aPlots[$i]->Max();
  2464. list($xmin,$ymin)=$aPlots[$i]->Min();
  2465. if (is_numeric($ymax)) $max=max($max,$ymax);
  2466. if (is_numeric($ymin)) $min=min($min,$ymin);
  2467. }
  2468. if( $min == '' ) $min = 0;
  2469. if( $max == '' ) $max = 0;
  2470. if( $min == 0 && $max == 0 ) {
  2471. // Special case if all values are 0
  2472. $min=0;$max=1;
  2473. }
  2474. return array($min,$max);
  2475. }
  2476. } // Class
  2477. //===================================================
  2478. // CLASS TTF
  2479. // Description: Handle TTF font names
  2480. //===================================================
  2481. class TTF {
  2482. var $font_files,$style_names;
  2483. //---------------
  2484. // CONSTRUCTOR
  2485. function TTF() {
  2486. $this->style_names=array(FS_NORMAL=>'normal',FS_BOLD=>'bold',FS_ITALIC=>'italic',FS_BOLDITALIC=>'bolditalic');
  2487. // File names for available fonts
  2488. $this->font_files=array(
  2489. FF_COURIER => array(FS_NORMAL=>'cour.ttf', FS_BOLD=>'courbd.ttf', FS_ITALIC=>'couri.ttf', FS_BOLDITALIC=>'courbi.ttf' ),
  2490. FF_GEORGIA => array(FS_NORMAL=>'georgia.ttf', FS_BOLD=>'georgiab.ttf', FS_ITALIC=>'georgiai.ttf', FS_BOLDITALIC=>'' ),
  2491. FF_TREBUCHE =>array(FS_NORMAL=>'trebuc.ttf', FS_BOLD=>'trebucbd.ttf', FS_ITALIC=>'trebucit.ttf', FS_BOLDITALIC=>'trebucbi.ttf' ),
  2492. FF_VERDANA => array(FS_NORMAL=>'verdana.ttf', FS_BOLD=>'verdanab.ttf', FS_ITALIC=>'verdanai.ttf', FS_BOLDITALIC=>'' ),
  2493. FF_TIMES => array(FS_NORMAL=>'times.ttf', FS_BOLD=>'timesbd.ttf', FS_ITALIC=>'timesi.ttf', FS_BOLDITALIC=>'timesbi.ttf' ),
  2494. FF_COMIC => array(FS_NORMAL=>'comic.ttf', FS_BOLD=>'comicbd.ttf', FS_ITALIC=>'', FS_BOLDITALIC=>'' ),
  2495. FF_ARIAL => array(FS_NORMAL=>'arial.ttf', FS_BOLD=>'arialbd.ttf', FS_ITALIC=>'ariali.ttf', FS_BOLDITALIC=>'arialbi.ttf' ) ,
  2496. FF_VERA => array(FS_NORMAL=>'Vera.ttf', FS_BOLD=>'VeraBd.ttf', FS_ITALIC=>'VeraIt.ttf', FS_BOLDITALIC=>'VeraBI.ttf' ),
  2497. FF_VERAMONO => array(FS_NORMAL=>'VeraMono.ttf', FS_BOLD=>'VeraMoBd.ttf', FS_ITALIC=>'VeraMoIt.ttf', FS_BOLDITALIC=>'VeraMoBI.ttf' ),
  2498. FF_VERASERIF => array(FS_NORMAL=>'VeraSe.ttf', FS_BOLD=>'VeraSeBd.ttf', FS_ITALIC=>'', FS_BOLDITALIC=>'' ) ,
  2499. FF_SIMSUN => array(FS_NORMAL=>'simsun.ttc', FS_BOLD=>'simhei.ttf', FS_ITALIC=>'', FS_BOLDITALIC=>'' ),
  2500. FF_CHINESE => array(FS_NORMAL=>CHINESE_TTF_FONT, FS_BOLD=>'', FS_ITALIC=>'', FS_BOLDITALIC=>'' ),
  2501. FF_MINCHO => array(FS_NORMAL=>MINCHO_TTF_FONT, FS_BOLD=>'', FS_ITALIC=>'', FS_BOLDITALIC=>'' ),
  2502. FF_PMINCHO => array(FS_NORMAL=>PMINCHO_TTF_FONT, FS_BOLD=>'', FS_ITALIC=>'', FS_BOLDITALIC=>'' ),
  2503. FF_GOTHIC => array(FS_NORMAL=>GOTHIC_TTF_FONT, FS_BOLD=>'', FS_ITALIC=>'', FS_BOLDITALIC=>'' ),
  2504. FF_PGOTHIC => array(FS_NORMAL=>PGOTHIC_TTF_FONT, FS_BOLD=>'', FS_ITALIC=>'', FS_BOLDITALIC=>'' ),
  2505. FF_MINCHO => array(FS_NORMAL=>PMINCHO_TTF_FONT, FS_BOLD=>'', FS_ITALIC=>'', FS_BOLDITALIC=>'' )
  2506. );
  2507. }
  2508. //---------------
  2509. // PUBLIC METHODS
  2510. // Create the TTF file from the font specification
  2511. function File($family,$style=FS_NORMAL) {
  2512. if( $family == FF_HANDWRT || $family==FF_BOOK ) {
  2513. JpGraphError::Raise('Font families FF_HANDWRT and FF_BOOK are no longer available due to copyright problem with these fonts. Fonts can no longer be distributed with JpGraph. Please download fonts from http://corefonts.sourceforge.net/');
  2514. }
  2515. $fam = @$this->font_files[$family];
  2516. if( !$fam ) {
  2517. JpGraphError::Raise(
  2518. "Specified TTF font family (id=$family) is unknown or does not exist. ".
  2519. "Please note that TTF fonts are not distributed with JpGraph for copyright reasons.".
  2520. " You can find the MS TTF WEB-fonts (arial, courier etc) for download at ".
  2521. " http://corefonts.sourceforge.net/");
  2522. }
  2523. $f = @$fam[$style];
  2524. if( $f==='' )
  2525. JpGraphError::Raise('Style "'.$this->style_names[$style].'" is not available for font family '.$this->font_files[$family][FS_NORMAL].'.');
  2526. if( !$f ) {
  2527. JpGraphError::Raise("Unknown font style specification [$fam].");
  2528. }
  2529. if ($family >= FF_MINCHO && $family <= FF_PGOTHIC) {
  2530. $f = MBTTF_DIR.$f;
  2531. } else {
  2532. $f = TTF_DIR.$f;
  2533. }
  2534. if( file_exists($f) === false || is_readable($f) === false ) {
  2535. JpGraphError::Raise("Font file \"$f\" is not readable or does not exist.");
  2536. }
  2537. return $f;
  2538. }
  2539. } // Class
  2540. //===================================================
  2541. // CLASS LineProperty
  2542. // Description: Holds properties for a line
  2543. //===================================================
  2544. class LineProperty {
  2545. var $iWeight=1, $iColor="black",$iStyle="solid";
  2546. var $iShow=true;
  2547. //---------------
  2548. // PUBLIC METHODS
  2549. function SetColor($aColor) {
  2550. $this->iColor = $aColor;
  2551. }
  2552. function SetWeight($aWeight) {
  2553. $this->iWeight = $aWeight;
  2554. }
  2555. function SetStyle($aStyle) {
  2556. $this->iStyle = $aStyle;
  2557. }
  2558. function Show($aShow=true) {
  2559. $this->iShow=$aShow;
  2560. }
  2561. function Stroke($aImg,$aX1,$aY1,$aX2,$aY2) {
  2562. if( $this->iShow ) {
  2563. $aImg->PushColor($this->iColor);
  2564. $oldls = $aImg->line_style;
  2565. $oldlw = $aImg->line_weight;
  2566. $aImg->SetLineWeight($this->iWeight);
  2567. $aImg->SetLineStyle($this->iStyle);
  2568. $aImg->StyleLine($aX1,$aY1,$aX2,$aY2);
  2569. $aImg->PopColor($this->iColor);
  2570. $aImg->line_style = $oldls;
  2571. $aImg->line_weight = $oldlw;
  2572. }
  2573. }
  2574. }
  2575. //===================================================
  2576. // CLASS Text
  2577. // Description: Arbitrary text object that can be added to the graph
  2578. //===================================================
  2579. class Text {
  2580. var $t,$x=0,$y=0,$halign="left",$valign="top",$color=array(0,0,0);
  2581. var $font_family=FF_FONT1,$font_style=FS_NORMAL,$font_size=12;
  2582. var $hide=false, $dir=0;
  2583. var $boxed=false; // Should the text be boxed
  2584. var $paragraph_align="left";
  2585. var $margin=0;
  2586. var $icornerradius=0,$ishadowwidth=3;
  2587. var $iScalePosY=null,$iScalePosX=null;
  2588. var $iWordwrap=0;
  2589. var $fcolor='white',$bcolor='black',$shadow=false;
  2590. var $iCSIMarea='',$iCSIMalt='',$iCSIMtarget='';
  2591. //---------------
  2592. // CONSTRUCTOR
  2593. // Create new text at absolute pixel coordinates
  2594. function Text($aTxt="",$aXAbsPos=0,$aYAbsPos=0) {
  2595. if( ! is_string($aTxt) ) {
  2596. JpGraphError::Raise('First argument to Text::Text() must be s atring.');
  2597. }
  2598. $this->t = $aTxt;
  2599. $this->x = round($aXAbsPos);
  2600. $this->y = round($aYAbsPos);
  2601. $this->margin = 0;
  2602. }
  2603. //---------------
  2604. // PUBLIC METHODS
  2605. // Set the string in the text object
  2606. function Set($aTxt) {
  2607. $this->t = $aTxt;
  2608. }
  2609. // Alias for Pos()
  2610. function SetPos($aXAbsPos=0,$aYAbsPos=0,$aHAlign="left",$aVAlign="top") {
  2611. $this->Pos($aXAbsPos,$aYAbsPos,$aHAlign,$aVAlign);
  2612. }
  2613. // Specify the position and alignment for the text object
  2614. function Pos($aXAbsPos=0,$aYAbsPos=0,$aHAlign="left",$aVAlign="top") {
  2615. $this->x = $aXAbsPos;
  2616. $this->y = $aYAbsPos;
  2617. $this->halign = $aHAlign;
  2618. $this->valign = $aVAlign;
  2619. }
  2620. function SetScalePos($aX,$aY) {
  2621. $this->iScalePosX = $aX;
  2622. $this->iScalePosY = $aY;
  2623. }
  2624. // Specify alignment for the text
  2625. function Align($aHAlign,$aVAlign="top",$aParagraphAlign="") {
  2626. $this->halign = $aHAlign;
  2627. $this->valign = $aVAlign;
  2628. if( $aParagraphAlign != "" )
  2629. $this->paragraph_align = $aParagraphAlign;
  2630. }
  2631. // Alias
  2632. function SetAlign($aHAlign,$aVAlign="top",$aParagraphAlign="") {
  2633. $this->Align($aHAlign,$aVAlign,$aParagraphAlign);
  2634. }
  2635. // Specifies the alignment for a multi line text
  2636. function ParagraphAlign($aAlign) {
  2637. $this->paragraph_align = $aAlign;
  2638. }
  2639. // Specifies the alignment for a multi line text
  2640. function SetParagraphAlign($aAlign) {
  2641. $this->paragraph_align = $aAlign;
  2642. }
  2643. function SetShadow($aShadowColor='gray',$aShadowWidth=3) {
  2644. $this->ishadowwidth=$aShadowWidth;
  2645. $this->shadow=$aShadowColor;
  2646. $this->boxed=true;
  2647. }
  2648. function SetWordWrap($aCol) {
  2649. $this->iWordwrap = $aCol ;
  2650. }
  2651. // Specify that the text should be boxed. fcolor=frame color, bcolor=border color,
  2652. // $shadow=drop shadow should be added around the text.
  2653. function SetBox($aFrameColor=array(255,255,255),$aBorderColor=array(0,0,0),$aShadowColor=false,$aCornerRadius=4,$aShadowWidth=3) {
  2654. if( $aFrameColor==false )
  2655. $this->boxed=false;
  2656. else
  2657. $this->boxed=true;
  2658. $this->fcolor=$aFrameColor;
  2659. $this->bcolor=$aBorderColor;
  2660. // For backwards compatibility when shadow was just true or false
  2661. if( $aShadowColor === true )
  2662. $aShadowColor = 'gray';
  2663. $this->shadow=$aShadowColor;
  2664. $this->icornerradius=$aCornerRadius;
  2665. $this->ishadowwidth=$aShadowWidth;
  2666. }
  2667. // Hide the text
  2668. function Hide($aHide=true) {
  2669. $this->hide=$aHide;
  2670. }
  2671. // This looks ugly since it's not a very orthogonal design
  2672. // but I added this "inverse" of Hide() to harmonize
  2673. // with some classes which I designed more recently (especially)
  2674. // jpgraph_gantt
  2675. function Show($aShow=true) {
  2676. $this->hide=!$aShow;
  2677. }
  2678. // Specify font
  2679. function SetFont($aFamily,$aStyle=FS_NORMAL,$aSize=10) {
  2680. $this->font_family=$aFamily;
  2681. $this->font_style=$aStyle;
  2682. $this->font_size=$aSize;
  2683. }
  2684. // Center the text between $left and $right coordinates
  2685. function Center($aLeft,$aRight,$aYAbsPos=false) {
  2686. $this->x = $aLeft + ($aRight-$aLeft )/2;
  2687. $this->halign = "center";
  2688. if( is_numeric($aYAbsPos) )
  2689. $this->y = $aYAbsPos;
  2690. }
  2691. // Set text color
  2692. function SetColor($aColor) {
  2693. $this->color = $aColor;
  2694. }
  2695. function SetAngle($aAngle) {
  2696. $this->SetOrientation($aAngle);
  2697. }
  2698. // Orientation of text. Note only TTF fonts can have an arbitrary angle
  2699. function SetOrientation($aDirection=0) {
  2700. if( is_numeric($aDirection) )
  2701. $this->dir=$aDirection;
  2702. elseif( $aDirection=="h" )
  2703. $this->dir = 0;
  2704. elseif( $aDirection=="v" )
  2705. $this->dir = 90;
  2706. else JpGraphError::Raise(" Invalid direction specified for text.");
  2707. }
  2708. // Total width of text
  2709. function GetWidth($aImg) {
  2710. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  2711. $w = $aImg->GetTextWidth($this->t,$this->dir);
  2712. return $w;
  2713. }
  2714. // Hight of font
  2715. function GetFontHeight($aImg) {
  2716. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  2717. $h = $aImg->GetFontHeight();
  2718. return $h;
  2719. }
  2720. function GetTextHeight($aImg) {
  2721. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  2722. $h = $aImg->GetTextHeight($this->t,$this->dir);
  2723. return $h;
  2724. }
  2725. function GetHeight($aImg) {
  2726. // Synonym for GetTextHeight()
  2727. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  2728. $h = $aImg->GetTextHeight($this->t,$this->dir);
  2729. return $h;
  2730. }
  2731. // Set the margin which will be interpretated differently depending
  2732. // on the context.
  2733. function SetMargin($aMarg) {
  2734. $this->margin = $aMarg;
  2735. }
  2736. function StrokeWithScale($aImg,$axscale,$ayscale) {
  2737. if( $this->iScalePosX === null ||
  2738. $this->iScalePosY === null ) {
  2739. $this->Stroke($aImg);
  2740. }
  2741. else {
  2742. $this->Stroke($aImg,
  2743. round($axscale->Translate($this->iScalePosX)),
  2744. round($ayscale->Translate($this->iScalePosY)));
  2745. }
  2746. }
  2747. function SetCSIMTarget($aTarget,$aAlt=null) {
  2748. $this->iCSIMtarget = $aTarget;
  2749. $this->iCSIMalt = $aAlt;
  2750. }
  2751. function GetCSIMareas() {
  2752. if( $this->iCSIMtarget !== '' )
  2753. return $this->iCSIMarea;
  2754. else
  2755. return '';
  2756. }
  2757. // Display text in image
  2758. function Stroke($aImg,$x=null,$y=null) {
  2759. if( !empty($x) ) $this->x = round($x);
  2760. if( !empty($y) ) $this->y = round($y);
  2761. // Insert newlines
  2762. if( $this->iWordwrap > 0 ) {
  2763. $this->t = wordwrap($this->t,$this->iWordwrap,"\n");
  2764. }
  2765. // If position been given as a fraction of the image size
  2766. // calculate the absolute position
  2767. if( $this->x < 1 && $this->x > 0 ) $this->x *= $aImg->width;
  2768. if( $this->y < 1 && $this->y > 0 ) $this->y *= $aImg->height;
  2769. $aImg->PushColor($this->color);
  2770. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  2771. $aImg->SetTextAlign($this->halign,$this->valign);
  2772. if( $this->boxed ) {
  2773. if( $this->fcolor=="nofill" )
  2774. $this->fcolor=false;
  2775. $aImg->SetLineWeight(1);
  2776. $bbox = $aImg->StrokeBoxedText($this->x,$this->y,$this->t,
  2777. $this->dir,$this->fcolor,$this->bcolor,$this->shadow,
  2778. $this->paragraph_align,5,5,$this->icornerradius,
  2779. $this->ishadowwidth);
  2780. }
  2781. else {
  2782. $bbox = $aImg->StrokeText($this->x,$this->y,$this->t,$this->dir,$this->paragraph_align);
  2783. }
  2784. // Create CSIM targets
  2785. $coords = $bbox[0].','.$bbox[1].','.$bbox[2].','.$bbox[3].','.$bbox[4].','.$bbox[5].','.$bbox[6].','.$bbox[7];
  2786. $this->iCSIMarea = "<area shape=\"poly\" coords=\"$coords\" href=\"".$this->iCSIMtarget."\"";
  2787. $this->iCSIMarea .= " alt=\"".$this->iCSIMalt."\" title=\"".$this->iCSIMalt."\" >\n";
  2788. $aImg->PopColor($this->color);
  2789. }
  2790. } // Class
  2791. class GraphTabTitle extends Text{
  2792. var $corner = 6 , $posx = 7, $posy = 4;
  2793. var $color='darkred',$fillcolor='lightyellow',$bordercolor='black';
  2794. var $align = 'left', $width=TABTITLE_WIDTHFIT;
  2795. function GraphTabTitle() {
  2796. $this->t = '';
  2797. $this->font_style = FS_BOLD;
  2798. $this->hide = true;
  2799. }
  2800. function SetColor($aTxtColor,$aFillColor='lightyellow',$aBorderColor='black') {
  2801. $this->color = $aTxtColor;
  2802. $this->fillcolor = $aFillColor;
  2803. $this->bordercolor = $aBorderColor;
  2804. }
  2805. function SetFillColor($aFillColor) {
  2806. $this->fillcolor = $aFillColor;
  2807. }
  2808. function SetTabAlign($aAlign) {
  2809. // Synonym for SetPos
  2810. $this->align = $aAlign;
  2811. }
  2812. function SetPos($aAlign) {
  2813. $this->align = $aAlign;
  2814. }
  2815. function SetWidth($aWidth) {
  2816. $this->width = $aWidth ;
  2817. }
  2818. function Set($t) {
  2819. $this->t = $t;
  2820. $this->hide = false;
  2821. }
  2822. function SetCorner($aD) {
  2823. $this->corner = $aD ;
  2824. }
  2825. function Stroke($aImg) {
  2826. if( $this->hide )
  2827. return;
  2828. $this->boxed = false;
  2829. $w = $this->GetWidth($aImg) + 2*$this->posx;
  2830. $h = $this->GetTextHeight($aImg) + 2*$this->posy;
  2831. $x = $aImg->left_margin;
  2832. $y = $aImg->top_margin;
  2833. if( $this->width === TABTITLE_WIDTHFIT ) {
  2834. if( $this->align == 'left' ) {
  2835. $p = array($x, $y,
  2836. $x, $y-$h+$this->corner,
  2837. $x + $this->corner,$y-$h,
  2838. $x + $w - $this->corner, $y-$h,
  2839. $x + $w, $y-$h+$this->corner,
  2840. $x + $w, $y);
  2841. }
  2842. elseif( $this->align == 'center' ) {
  2843. $x += round($aImg->plotwidth/2) - round($w/2);
  2844. $p = array($x, $y,
  2845. $x, $y-$h+$this->corner,
  2846. $x + $this->corner, $y-$h,
  2847. $x + $w - $this->corner, $y-$h,
  2848. $x + $w, $y-$h+$this->corner,
  2849. $x + $w, $y);
  2850. }
  2851. else {
  2852. $x += $aImg->plotwidth -$w;
  2853. $p = array($x, $y,
  2854. $x, $y-$h+$this->corner,
  2855. $x + $this->corner,$y-$h,
  2856. $x + $w - $this->corner, $y-$h,
  2857. $x + $w, $y-$h+$this->corner,
  2858. $x + $w, $y);
  2859. }
  2860. }
  2861. else {
  2862. if( $this->width === TABTITLE_WIDTHFULL )
  2863. $w = $aImg->plotwidth ;
  2864. else
  2865. $w = $this->width ;
  2866. // Make the tab fit the width of the plot area
  2867. $p = array($x, $y,
  2868. $x, $y-$h+$this->corner,
  2869. $x + $this->corner,$y-$h,
  2870. $x + $w - $this->corner, $y-$h,
  2871. $x + $w, $y-$h+$this->corner,
  2872. $x + $w, $y);
  2873. }
  2874. if( $this->halign == 'left' ) {
  2875. $aImg->SetTextAlign('left','bottom');
  2876. $x += $this->posx;
  2877. $y -= $this->posy;
  2878. }
  2879. elseif( $this->halign == 'center' ) {
  2880. $aImg->SetTextAlign('center','bottom');
  2881. $x += $w/2;
  2882. $y -= $this->posy;
  2883. }
  2884. else {
  2885. $aImg->SetTextAlign('right','bottom');
  2886. $x += $w - $this->posx;
  2887. $y -= $this->posy;
  2888. }
  2889. $aImg->SetColor($this->fillcolor);
  2890. $aImg->FilledPolygon($p);
  2891. $aImg->SetColor($this->bordercolor);
  2892. $aImg->Polygon($p,true);
  2893. $aImg->SetColor($this->color);
  2894. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  2895. $aImg->StrokeText($x,$y,$this->t,0,'center');
  2896. }
  2897. }
  2898. //===================================================
  2899. // CLASS SuperScriptText
  2900. // Description: Format a superscript text
  2901. //===================================================
  2902. class SuperScriptText extends Text {
  2903. var $iSuper="";
  2904. var $sfont_family="",$sfont_style="",$sfont_size=8;
  2905. var $iSuperMargin=2,$iVertOverlap=4,$iSuperScale=0.65;
  2906. var $iSDir=0;
  2907. var $iSimple=false;
  2908. function SuperScriptText($aTxt="",$aSuper="",$aXAbsPos=0,$aYAbsPos=0) {
  2909. parent::Text($aTxt,$aXAbsPos,$aYAbsPos);
  2910. $this->iSuper = $aSuper;
  2911. }
  2912. function FromReal($aVal,$aPrecision=2) {
  2913. // Convert a floating point number to scientific notation
  2914. $neg=1.0;
  2915. if( $aVal < 0 ) {
  2916. $neg = -1.0;
  2917. $aVal = -$aVal;
  2918. }
  2919. $l = floor(log10($aVal));
  2920. $a = sprintf("%0.".$aPrecision."f",round($aVal / pow(10,$l),$aPrecision));
  2921. $a *= $neg;
  2922. if( $this->iSimple && ($a == 1 || $a==-1) ) $a = '';
  2923. if( $a != '' )
  2924. $this->t = $a.' * 10';
  2925. else {
  2926. if( $neg == 1 )
  2927. $this->t = '10';
  2928. else
  2929. $this->t = '-10';
  2930. }
  2931. $this->iSuper = $l;
  2932. }
  2933. function Set($aTxt,$aSuper="") {
  2934. $this->t = $aTxt;
  2935. $this->iSuper = $aSuper;
  2936. }
  2937. function SetSuperFont($aFontFam,$aFontStyle=FS_NORMAL,$aFontSize=8) {
  2938. $this->sfont_family = $aFontFam;
  2939. $this->sfont_style = $aFontStyle;
  2940. $this->sfont_size = $aFontSize;
  2941. }
  2942. // Total width of text
  2943. function GetWidth(&$aImg) {
  2944. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  2945. $w = $aImg->GetTextWidth($this->t);
  2946. $aImg->SetFont($this->sfont_family,$this->sfont_style,$this->sfont_size);
  2947. $w += $aImg->GetTextWidth($this->iSuper);
  2948. $w += $this->iSuperMargin;
  2949. return $w;
  2950. }
  2951. // Hight of font (approximate the height of the text)
  2952. function GetFontHeight(&$aImg) {
  2953. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  2954. $h = $aImg->GetFontHeight();
  2955. $aImg->SetFont($this->sfont_family,$this->sfont_style,$this->sfont_size);
  2956. $h += $aImg->GetFontHeight();
  2957. return $h;
  2958. }
  2959. // Hight of text
  2960. function GetTextHeight(&$aImg) {
  2961. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  2962. $h = $aImg->GetTextHeight($this->t);
  2963. $aImg->SetFont($this->sfont_family,$this->sfont_style,$this->sfont_size);
  2964. $h += $aImg->GetTextHeight($this->iSuper);
  2965. return $h;
  2966. }
  2967. function Stroke($aImg,$ax=-1,$ay=-1) {
  2968. // To position the super script correctly we need different
  2969. // cases to handle the alignmewnt specified since that will
  2970. // determine how we can interpret the x,y coordinates
  2971. $w = parent::GetWidth($aImg);
  2972. $h = parent::GetTextHeight($aImg);
  2973. switch( $this->valign ) {
  2974. case 'top':
  2975. $sy = $this->y;
  2976. break;
  2977. case 'center':
  2978. $sy = $this->y - $h/2;
  2979. break;
  2980. case 'bottom':
  2981. $sy = $this->y - $h;
  2982. break;
  2983. default:
  2984. JpGraphError::Raise('PANIC: Internal error in SuperScript::Stroke(). Unknown vertical alignment for text');
  2985. exit();
  2986. }
  2987. switch( $this->halign ) {
  2988. case 'left':
  2989. $sx = $this->x + $w;
  2990. break;
  2991. case 'center':
  2992. $sx = $this->x + $w/2;
  2993. break;
  2994. case 'right':
  2995. $sx = $this->x;
  2996. break;
  2997. default:
  2998. JpGraphError::Raise('PANIC: Internal error in SuperScript::Stroke(). Unknown horizontal alignment for text');
  2999. exit();
  3000. }
  3001. $sx += $this->iSuperMargin;
  3002. $sy += $this->iVertOverlap;
  3003. // Should we automatically determine the font or
  3004. // has the user specified it explicetly?
  3005. if( $this->sfont_family == "" ) {
  3006. if( $this->font_family <= FF_FONT2 ) {
  3007. if( $this->font_family == FF_FONT0 ) {
  3008. $sff = FF_FONT0;
  3009. }
  3010. elseif( $this->font_family == FF_FONT1 ) {
  3011. if( $this->font_style == FS_NORMAL )
  3012. $sff = FF_FONT0;
  3013. else
  3014. $sff = FF_FONT1;
  3015. }
  3016. else {
  3017. $sff = FF_FONT1;
  3018. }
  3019. $sfs = $this->font_style;
  3020. $sfz = $this->font_size;
  3021. }
  3022. else {
  3023. // TTF fonts
  3024. $sff = $this->font_family;
  3025. $sfs = $this->font_style;
  3026. $sfz = floor($this->font_size*$this->iSuperScale);
  3027. if( $sfz < 8 ) $sfz = 8;
  3028. }
  3029. $this->sfont_family = $sff;
  3030. $this->sfont_style = $sfs;
  3031. $this->sfont_size = $sfz;
  3032. }
  3033. else {
  3034. $sff = $this->sfont_family;
  3035. $sfs = $this->sfont_style;
  3036. $sfz = $this->sfont_size;
  3037. }
  3038. parent::Stroke($aImg,$ax,$ay);
  3039. // For the builtin fonts we need to reduce the margins
  3040. // since the bounding bx reported for the builtin fonts
  3041. // are much larger than for the TTF fonts.
  3042. if( $sff <= FF_FONT2 ) {
  3043. $sx -= 2;
  3044. $sy += 3;
  3045. }
  3046. $aImg->SetTextAlign('left','bottom');
  3047. $aImg->SetFont($sff,$sfs,$sfz);
  3048. $aImg->PushColor($this->color);
  3049. $aImg->StrokeText($sx,$sy,$this->iSuper,$this->iSDir,'left');
  3050. $aImg->PopColor();
  3051. }
  3052. }
  3053. //===================================================
  3054. // CLASS Grid
  3055. // Description: responsible for drawing grid lines in graph
  3056. //===================================================
  3057. class Grid {
  3058. var $img;
  3059. var $scale;
  3060. var $grid_color='#DDDDDD',$grid_mincolor='#DDDDDD';
  3061. var $type="solid";
  3062. var $show=false, $showMinor=false,$weight=1;
  3063. var $fill=false,$fillcolor=array('#EFEFEF','#BBCCFF');
  3064. //---------------
  3065. // CONSTRUCTOR
  3066. function Grid(&$aAxis) {
  3067. $this->scale = &$aAxis->scale;
  3068. $this->img = &$aAxis->img;
  3069. }
  3070. //---------------
  3071. // PUBLIC METHODS
  3072. function SetColor($aMajColor,$aMinColor=false) {
  3073. $this->grid_color=$aMajColor;
  3074. if( $aMinColor === false )
  3075. $aMinColor = $aMajColor ;
  3076. $this->grid_mincolor = $aMinColor;
  3077. }
  3078. function SetWeight($aWeight) {
  3079. $this->weight=$aWeight;
  3080. }
  3081. // Specify if grid should be dashed, dotted or solid
  3082. function SetLineStyle($aType) {
  3083. $this->type = $aType;
  3084. }
  3085. // Decide if both major and minor grid should be displayed
  3086. function Show($aShowMajor=true,$aShowMinor=false) {
  3087. $this->show=$aShowMajor;
  3088. $this->showMinor=$aShowMinor;
  3089. }
  3090. function SetFill($aFlg=true,$aColor1='lightgray',$aColor2='lightblue') {
  3091. $this->fill = $aFlg;
  3092. $this->fillcolor = array( $aColor1, $aColor2 );
  3093. }
  3094. // Display the grid
  3095. function Stroke() {
  3096. if( $this->showMinor ) {
  3097. $tmp = $this->grid_color;
  3098. $this->grid_color = $this->grid_mincolor;
  3099. $this->DoStroke($this->scale->ticks->ticks_pos);
  3100. $this->grid_color = $tmp;
  3101. $this->DoStroke($this->scale->ticks->maj_ticks_pos);
  3102. }
  3103. else {
  3104. $this->DoStroke($this->scale->ticks->maj_ticks_pos);
  3105. }
  3106. }
  3107. //--------------
  3108. // Private methods
  3109. // Draw the grid
  3110. function DoStroke(&$aTicksPos) {
  3111. if( !$this->show )
  3112. return;
  3113. $nbrgrids = count($aTicksPos);
  3114. if( $this->scale->type=="y" ) {
  3115. $xl=$this->img->left_margin;
  3116. $xr=$this->img->width-$this->img->right_margin;
  3117. if( $this->fill ) {
  3118. // Draw filled areas
  3119. $y2 = $aTicksPos[0];
  3120. $i=1;
  3121. while( $i < $nbrgrids ) {
  3122. $y1 = $y2;
  3123. $y2 = $aTicksPos[$i++];
  3124. $this->img->SetColor($this->fillcolor[$i & 1]);
  3125. $this->img->FilledRectangle($xl,$y1,$xr,$y2);
  3126. }
  3127. }
  3128. $this->img->SetColor($this->grid_color);
  3129. $this->img->SetLineWeight($this->weight);
  3130. // Draw grid lines
  3131. for($i=0; $i<$nbrgrids; ++$i) {
  3132. $y=$aTicksPos[$i];
  3133. if( $this->type == "solid" )
  3134. $this->img->Line($xl,$y,$xr,$y);
  3135. elseif( $this->type == "dotted" )
  3136. $this->img->DashedLine($xl,$y,$xr,$y,1,6);
  3137. elseif( $this->type == "dashed" )
  3138. $this->img->DashedLine($xl,$y,$xr,$y,2,4);
  3139. elseif( $this->type == "longdashed" )
  3140. $this->img->DashedLine($xl,$y,$xr,$y,8,6);
  3141. }
  3142. }
  3143. elseif( $this->scale->type=="x" ) {
  3144. $yu=$this->img->top_margin;
  3145. $yl=$this->img->height-$this->img->bottom_margin;
  3146. $limit=$this->img->width-$this->img->right_margin;
  3147. if( $this->fill ) {
  3148. // Draw filled areas
  3149. $x2 = $aTicksPos[0];
  3150. $i=1;
  3151. while( $i < $nbrgrids ) {
  3152. $x1 = $x2;
  3153. $x2 = min($aTicksPos[$i++],$limit) ;
  3154. $this->img->SetColor($this->fillcolor[$i & 1]);
  3155. $this->img->FilledRectangle($x1,$yu,$x2,$yl);
  3156. }
  3157. }
  3158. $this->img->SetColor($this->grid_color);
  3159. $this->img->SetLineWeight($this->weight);
  3160. // We must also test for limit since we might have
  3161. // an offset and the number of ticks is calculated with
  3162. // assumption offset==0 so we might end up drawing one
  3163. // to many gridlines
  3164. $i=0;
  3165. $x=$aTicksPos[$i];
  3166. while( $i<count($aTicksPos) && ($x=$aTicksPos[$i]) <= $limit ) {
  3167. if( $this->type == "solid" )
  3168. $this->img->Line($x,$yl,$x,$yu);
  3169. elseif( $this->type == "dotted" )
  3170. $this->img->DashedLine($x,$yl,$x,$yu,1,6);
  3171. elseif( $this->type == "dashed" )
  3172. $this->img->DashedLine($x,$yl,$x,$yu,2,4);
  3173. elseif( $this->type == "longdashed" )
  3174. $this->img->DashedLine($x,$yl,$x,$yu,8,6);
  3175. ++$i;
  3176. }
  3177. }
  3178. else {
  3179. JpGraphError::Raise('Internal error: Unknown grid axis ['.$this->scale->type.']');
  3180. }
  3181. return true;
  3182. }
  3183. } // Class
  3184. //===================================================
  3185. // CLASS Axis
  3186. // Description: Defines X and Y axis. Notes that at the
  3187. // moment the code is not really good since the axis on
  3188. // several occasion must know wheter it's an X or Y axis.
  3189. // This was a design decision to make the code easier to
  3190. // follow.
  3191. //===================================================
  3192. class Axis {
  3193. var $pos = false;
  3194. var $weight=1;
  3195. var $color=array(0,0,0),$label_color=array(0,0,0);
  3196. var $img=null,$scale=null;
  3197. var $hide=false;
  3198. var $ticks_label=false, $ticks_label_colors=null;
  3199. var $show_first_label=true,$show_last_label=true;
  3200. var $label_step=1; // Used by a text axis to specify what multiple of major steps
  3201. // should be labeled.
  3202. var $tick_step=1;
  3203. var $labelPos=0; // Which side of the axis should the labels be?
  3204. var $title=null,$title_adjust,$title_margin,$title_side=SIDE_LEFT;
  3205. var $font_family=FF_FONT1,$font_style=FS_NORMAL,$font_size=12,$label_angle=0;
  3206. var $tick_label_margin=5;
  3207. var $label_halign = '',$label_valign = '', $label_para_align='left';
  3208. var $hide_line=false,$hide_labels=false;
  3209. var $iDeltaAbsPos=0;
  3210. //var $hide_zero_label=false;
  3211. //---------------
  3212. // CONSTRUCTOR
  3213. function Axis(&$img,&$aScale,$color=array(0,0,0)) {
  3214. $this->img = &$img;
  3215. $this->scale = &$aScale;
  3216. $this->color = $color;
  3217. $this->title=new Text("");
  3218. if( $aScale->type=="y" ) {
  3219. $this->title_margin = 25;
  3220. $this->title_adjust="middle";
  3221. $this->title->SetOrientation(90);
  3222. $this->tick_label_margin=7;
  3223. $this->labelPos=SIDE_LEFT;
  3224. //$this->SetLabelFormat('%.1f');
  3225. }
  3226. else {
  3227. $this->title_margin = 5;
  3228. $this->title_adjust="high";
  3229. $this->title->SetOrientation(0);
  3230. $this->tick_label_margin=3;
  3231. $this->labelPos=SIDE_DOWN;
  3232. //$this->SetLabelFormat('%.0f');
  3233. }
  3234. }
  3235. //---------------
  3236. // PUBLIC METHODS
  3237. function SetLabelFormat($aFormStr) {
  3238. $this->scale->ticks->SetLabelFormat($aFormStr);
  3239. }
  3240. function SetLabelFormatString($aFormStr) {
  3241. $this->scale->ticks->SetLabelFormat($aFormStr);
  3242. }
  3243. function SetLabelFormatCallback($aFuncName) {
  3244. $this->scale->ticks->SetFormatCallback($aFuncName);
  3245. }
  3246. function SetLabelAlign($aHAlign,$aVAlign="top",$aParagraphAlign='left') {
  3247. $this->label_halign = $aHAlign;
  3248. $this->label_valign = $aVAlign;
  3249. $this->label_para_align = $aParagraphAlign;
  3250. }
  3251. // Don't display the first label
  3252. function HideFirstTickLabel($aShow=false) {
  3253. $this->show_first_label=$aShow;
  3254. }
  3255. function HideLastTickLabel($aShow=false) {
  3256. $this->show_last_label=$aShow;
  3257. }
  3258. function HideTicks($aHideMinor=true,$aHideMajor=true) {
  3259. $this->scale->ticks->SupressMinorTickMarks($aHideMinor);
  3260. $this->scale->ticks->SupressTickMarks($aHideMajor);
  3261. }
  3262. // Hide zero label
  3263. function HideZeroLabel($aFlag=true) {
  3264. $this->scale->ticks->SupressZeroLabel();
  3265. //$this->hide_zero_label = $aFlag;
  3266. }
  3267. function HideFirstLastLabel() {
  3268. // The two first calls to ticks method will supress
  3269. // automatically generated scale values. However, that
  3270. // will not affect manually specified value, e.g text-scales.
  3271. // therefor we also make a kludge here to supress manually
  3272. // specified scale labels.
  3273. $this->scale->ticks->SupressLast();
  3274. $this->scale->ticks->SupressFirst();
  3275. $this->show_first_label = false;
  3276. $this->show_last_label = false;
  3277. }
  3278. // Hide the axis
  3279. function Hide($aHide=true) {
  3280. $this->hide=$aHide;
  3281. }
  3282. // Hide the actual axis-line, but still print the labels
  3283. function HideLine($aHide=true) {
  3284. $this->hide_line = $aHide;
  3285. }
  3286. function HideLabels($aHide=true) {
  3287. $this->hide_labels = $aHide;
  3288. }
  3289. // Weight of axis
  3290. function SetWeight($aWeight) {
  3291. $this->weight = $aWeight;
  3292. }
  3293. // Axis color
  3294. function SetColor($aColor,$aLabelColor=false) {
  3295. $this->color = $aColor;
  3296. if( !$aLabelColor ) $this->label_color = $aColor;
  3297. else $this->label_color = $aLabelColor;
  3298. }
  3299. // Title on axis
  3300. function SetTitle($aTitle,$aAdjustAlign="high") {
  3301. $this->title->Set($aTitle);
  3302. $this->title_adjust=$aAdjustAlign;
  3303. }
  3304. // Specify distance from the axis
  3305. function SetTitleMargin($aMargin) {
  3306. $this->title_margin=$aMargin;
  3307. }
  3308. // Which side of the axis should the axis title be?
  3309. function SetTitleSide($aSideOfAxis) {
  3310. $this->title_side = $aSideOfAxis;
  3311. }
  3312. // Utility function to set the direction for tick marks
  3313. function SetTickDirection($aDir) {
  3314. // Will be deprecated from 1.7
  3315. if( ERR_DEPRECATED )
  3316. JpGraphError::Raise('Axis::SetTickDirection() is deprecated. Use Axis::SetTickSide() instead');
  3317. $this->scale->ticks->SetSide($aDir);
  3318. }
  3319. function SetTickSide($aDir) {
  3320. $this->scale->ticks->SetSide($aDir);
  3321. }
  3322. // Specify text labels for the ticks. One label for each data point
  3323. function SetTickLabels($aLabelArray,$aLabelColorArray=null) {
  3324. $this->ticks_label = $aLabelArray;
  3325. $this->ticks_label_colors = $aLabelColorArray;
  3326. }
  3327. // How far from the axis should the labels be drawn
  3328. function SetTickLabelMargin($aMargin) {
  3329. if( ERR_DEPRECATED )
  3330. JpGraphError::Raise('SetTickLabelMargin() is deprecated. Use Axis::SetLabelMargin() instead.');
  3331. $this->tick_label_margin=$aMargin;
  3332. }
  3333. function SetLabelMargin($aMargin) {
  3334. $this->tick_label_margin=$aMargin;
  3335. }
  3336. // Specify that every $step of the ticks should be displayed starting
  3337. // at $start
  3338. // DEPRECATED FUNCTION: USE SetTextTickInterval() INSTEAD
  3339. function SetTextTicks($step,$start=0) {
  3340. JpGraphError::Raise(" SetTextTicks() is deprecated. Use SetTextTickInterval() instead.");
  3341. }
  3342. // Specify that every $step of the ticks should be displayed starting
  3343. // at $start
  3344. function SetTextTickInterval($aStep,$aStart=0) {
  3345. $this->scale->ticks->SetTextLabelStart($aStart);
  3346. $this->tick_step=$aStep;
  3347. }
  3348. // Specify that every $step tick mark should have a label
  3349. // should be displayed starting
  3350. function SetTextLabelInterval($aStep) {
  3351. if( $aStep < 1 )
  3352. JpGraphError::Raise(" Text label interval must be specified >= 1.");
  3353. $this->label_step=$aStep;
  3354. }
  3355. // Which side of the axis should the labels be on?
  3356. function SetLabelPos($aSidePos) {
  3357. // This will be deprecated from 1.7
  3358. if( ERR_DEPRECATED )
  3359. JpGraphError::Raise('SetLabelPos() is deprecated. Use Axis::SetLabelSide() instead.');
  3360. $this->labelPos=$aSidePos;
  3361. }
  3362. function SetLabelSide($aSidePos) {
  3363. $this->labelPos=$aSidePos;
  3364. }
  3365. // Set the font
  3366. function SetFont($aFamily,$aStyle=FS_NORMAL,$aSize=10) {
  3367. $this->font_family = $aFamily;
  3368. $this->font_style = $aStyle;
  3369. $this->font_size = $aSize;
  3370. }
  3371. // Position for axis line on the "other" scale
  3372. function SetPos($aPosOnOtherScale) {
  3373. $this->pos=$aPosOnOtherScale;
  3374. }
  3375. // Set the position of the axis to be X-pixels delta to the right
  3376. // of the max X-position (used to position the multiple Y-axis)
  3377. function SetPosAbsDelta($aDelta) {
  3378. $this->iDeltaAbsPos=$aDelta;
  3379. }
  3380. // Specify the angle for the tick labels
  3381. function SetLabelAngle($aAngle) {
  3382. $this->label_angle = $aAngle;
  3383. }
  3384. // Stroke the axis.
  3385. function Stroke($aOtherAxisScale,$aStrokeLabels=true) {
  3386. if( $this->hide ) return;
  3387. if( is_numeric($this->pos) ) {
  3388. $pos=$aOtherAxisScale->Translate($this->pos);
  3389. }
  3390. else { // Default to minimum of other scale if pos not set
  3391. if( ($aOtherAxisScale->GetMinVal() >= 0 && $this->pos==false) || $this->pos=="min" ) {
  3392. $pos = $aOtherAxisScale->scale_abs[0];
  3393. }
  3394. elseif($this->pos == "max") {
  3395. $pos = $aOtherAxisScale->scale_abs[1];
  3396. }
  3397. else { // If negative set x-axis at 0
  3398. $this->pos=0;
  3399. $pos=$aOtherAxisScale->Translate(0);
  3400. }
  3401. }
  3402. $pos += $this->iDeltaAbsPos;
  3403. $this->img->SetLineWeight($this->weight);
  3404. $this->img->SetColor($this->color);
  3405. $this->img->SetFont($this->font_family,$this->font_style,$this->font_size);
  3406. if( $this->scale->type == "x" ) {
  3407. if( !$this->hide_line )
  3408. $this->img->FilledRectangle($this->img->left_margin,$pos,
  3409. $this->img->width-$this->img->right_margin,$pos+$this->weight-1);
  3410. $y=$pos+$this->img->GetFontHeight()+$this->title_margin+$this->title->margin;
  3411. if( $this->title_adjust=="high" )
  3412. $this->title->Pos($this->img->width-$this->img->right_margin,$y,"right","top");
  3413. elseif( $this->title_adjust=="middle" || $this->title_adjust=="center" )
  3414. $this->title->Pos(($this->img->width-$this->img->left_margin-$this->img->right_margin)/2+$this->img->left_margin,$y,"center","top");
  3415. elseif($this->title_adjust=="low")
  3416. $this->title->Pos($this->img->left_margin,$y,"left","top");
  3417. else {
  3418. JpGraphError::Raise('Unknown alignment specified for X-axis title. ('.$this->title_adjust.')');
  3419. }
  3420. }
  3421. elseif( $this->scale->type == "y" ) {
  3422. // Add line weight to the height of the axis since
  3423. // the x-axis could have a width>1 and we want the axis to fit nicely together.
  3424. if( !$this->hide_line )
  3425. $this->img->FilledRectangle($pos-$this->weight+1,$this->img->top_margin,
  3426. $pos,$this->img->height-$this->img->bottom_margin+$this->weight-1);
  3427. $x=$pos ;
  3428. if( $this->title_side == SIDE_LEFT ) {
  3429. $x -= $this->title_margin;
  3430. $x -= $this->title->margin;
  3431. $halign="right";
  3432. }
  3433. else {
  3434. $x += $this->title_margin;
  3435. $x += $this->title->margin;
  3436. $halign="left";
  3437. }
  3438. // If the user has manually specified an hor. align
  3439. // then we override the automatic settings with this
  3440. // specifed setting. Since default is 'left' we compare
  3441. // with that. (This means a manually set 'left' align
  3442. // will have no effect.)
  3443. if( $this->title->halign != 'left' )
  3444. $halign = $this->title->halign;
  3445. if( $this->title_adjust=="high" )
  3446. $this->title->Pos($x,$this->img->top_margin,$halign,"top");
  3447. elseif($this->title_adjust=="middle" || $this->title_adjust=="center")
  3448. $this->title->Pos($x,($this->img->height-$this->img->top_margin-$this->img->bottom_margin)/2+$this->img->top_margin,$halign,"center");
  3449. elseif($this->title_adjust=="low")
  3450. $this->title->Pos($x,$this->img->height-$this->img->bottom_margin,$halign,"bottom");
  3451. else
  3452. JpGraphError::Raise('Unknown alignment specified for Y-axis title. ('.$this->title_adjust.')');
  3453. }
  3454. $this->scale->ticks->Stroke($this->img,$this->scale,$pos);
  3455. if( !$this->hide_labels && $aStrokeLabels ) {
  3456. $this->StrokeLabels($pos);
  3457. }
  3458. $this->title->Stroke($this->img);
  3459. }
  3460. //---------------
  3461. // PRIVATE METHODS
  3462. // Draw all the tick labels on major tick marks
  3463. function StrokeLabels($aPos,$aMinor=false,$aAbsLabel=false) {
  3464. $this->img->SetColor($this->label_color);
  3465. $this->img->SetFont($this->font_family,$this->font_style,$this->font_size);
  3466. $yoff=$this->img->GetFontHeight()/2;
  3467. // Only draw labels at major tick marks
  3468. $nbr = count($this->scale->ticks->maj_ticks_label);
  3469. // We have the option to not-display the very first mark
  3470. // (Usefull when the first label might interfere with another
  3471. // axis.)
  3472. $i = $this->show_first_label ? 0 : 1 ;
  3473. if( !$this->show_last_label ) --$nbr;
  3474. // Now run through all labels making sure we don't overshoot the end
  3475. // of the scale.
  3476. $ncolor=0;
  3477. if( isset($this->ticks_label_colors) )
  3478. $ncolor=count($this->ticks_label_colors);
  3479. while( $i<$nbr ) {
  3480. // $tpos holds the absolute text position for the label
  3481. $tpos=$this->scale->ticks->maj_ticklabels_pos[$i];
  3482. // Note. the $limit is only used for the x axis since we
  3483. // might otherwise overshoot if the scale has been centered
  3484. // This is due to us "loosing" the last tick mark if we center.
  3485. if( $this->scale->type=="x" && $tpos > $this->img->width-$this->img->right_margin+1 ) {
  3486. return;
  3487. }
  3488. // we only draw every $label_step label
  3489. if( ($i % $this->label_step)==0 ) {
  3490. // Set specific label color if specified
  3491. if( $ncolor > 0 )
  3492. $this->img->SetColor($this->ticks_label_colors[$i % $ncolor]);
  3493. // If the label has been specified use that and in other case
  3494. // just label the mark with the actual scale value
  3495. $m=$this->scale->ticks->GetMajor();
  3496. // ticks_label has an entry for each data point and is the array
  3497. // that holds the labels set by the user. If the user hasn't
  3498. // specified any values we use whats in the automatically asigned
  3499. // labels in the maj_ticks_label
  3500. if( isset($this->ticks_label[$i*$m]) )
  3501. $label=$this->ticks_label[$i*$m];
  3502. else {
  3503. if( $aAbsLabel )
  3504. $label=abs($this->scale->ticks->maj_ticks_label[$i]);
  3505. else
  3506. $label=$this->scale->ticks->maj_ticks_label[$i];
  3507. if( $this->scale->textscale && $this->scale->ticks->label_formfunc == '' ) {
  3508. ++$label;
  3509. }
  3510. }
  3511. //if( $this->hide_zero_label && $label==0.0 ) {
  3512. // ++$i;
  3513. // continue;
  3514. //}
  3515. if( $this->scale->type == "x" ) {
  3516. if( $this->labelPos == SIDE_DOWN ) {
  3517. if( $this->label_angle==0 || $this->label_angle==90 ) {
  3518. if( $this->label_halign=='' && $this->label_valign=='')
  3519. $this->img->SetTextAlign('center','top');
  3520. else
  3521. $this->img->SetTextAlign($this->label_halign,$this->label_valign);
  3522. }
  3523. else {
  3524. if( $this->label_halign=='' && $this->label_valign=='')
  3525. $this->img->SetTextAlign("right","top");
  3526. else
  3527. $this->img->SetTextAlign($this->label_halign,$this->label_valign);
  3528. }
  3529. $this->img->StrokeText($tpos,$aPos+$this->tick_label_margin,$label,
  3530. $this->label_angle,$this->label_para_align);
  3531. }
  3532. else {
  3533. if( $this->label_angle==0 || $this->label_angle==90 ) {
  3534. if( $this->label_halign=='' && $this->label_valign=='')
  3535. $this->img->SetTextAlign("center","bottom");
  3536. else
  3537. $this->img->SetTextAlign($this->label_halign,$this->label_valign);
  3538. }
  3539. else {
  3540. if( $this->label_halign=='' && $this->label_valign=='')
  3541. $this->img->SetTextAlign("right","bottom");
  3542. else
  3543. $this->img->SetTextAlign($this->label_halign,$this->label_valign);
  3544. }
  3545. $this->img->StrokeText($tpos,$aPos-$this->tick_label_margin,$label,
  3546. $this->label_angle,$this->label_para_align);
  3547. }
  3548. }
  3549. else {
  3550. // scale->type == "y"
  3551. //if( $this->label_angle!=0 )
  3552. //JpGraphError::Raise(" Labels at an angle are not supported on Y-axis");
  3553. if( $this->labelPos == SIDE_LEFT ) { // To the left of y-axis
  3554. if( $this->label_halign=='' && $this->label_valign=='')
  3555. $this->img->SetTextAlign("right","center");
  3556. else
  3557. $this->img->SetTextAlign($this->label_halign,$this->label_valign);
  3558. $this->img->StrokeText($aPos-$this->tick_label_margin,$tpos,$label,$this->label_angle,$this->label_para_align);
  3559. }
  3560. else { // To the right of the y-axis
  3561. if( $this->label_halign=='' && $this->label_valign=='')
  3562. $this->img->SetTextAlign("left","center");
  3563. else
  3564. $this->img->SetTextAlign($this->label_halign,$this->label_valign);
  3565. $this->img->StrokeText($aPos+$this->tick_label_margin,$tpos,$label,$this->label_angle,$this->label_para_align);
  3566. }
  3567. }
  3568. }
  3569. ++$i;
  3570. }
  3571. }
  3572. } // Class
  3573. //===================================================
  3574. // CLASS Ticks
  3575. // Description: Abstract base class for drawing linear and logarithmic
  3576. // tick marks on axis
  3577. //===================================================
  3578. class Ticks {
  3579. var $minor_abs_size=3, $major_abs_size=5;
  3580. var $direction=1; // Should ticks be in(=1) the plot area or outside (=-1)?
  3581. var $scale;
  3582. var $is_set=false;
  3583. var $precision;
  3584. var $supress_zerolabel=false,$supress_first=false;
  3585. var $supress_last=false,$supress_tickmarks=false,$supress_minor_tickmarks=false;
  3586. var $mincolor="",$majcolor="";
  3587. var $weight=1;
  3588. var $label_formatstr=''; // C-style format string to use for labels
  3589. var $label_formfunc='';
  3590. var $label_dateformatstr='';
  3591. //---------------
  3592. // CONSTRUCTOR
  3593. function Ticks(&$aScale) {
  3594. $this->scale=&$aScale;
  3595. $this->precision = -1;
  3596. }
  3597. //---------------
  3598. // PUBLIC METHODS
  3599. // Set format string for automatic labels
  3600. function SetLabelFormat($aFormatString) {
  3601. $this->label_formatstr=$aFormatString;
  3602. }
  3603. function SetLabelDateFormat($aFormatString) {
  3604. $this->label_dateformatstr=$aFormatString;
  3605. }
  3606. function SetFormatCallback($aCallbackFuncName) {
  3607. $this->label_formfunc = $aCallbackFuncName;
  3608. }
  3609. // Don't display the first zero label
  3610. function SupressZeroLabel($aFlag=true) {
  3611. $this->supress_zerolabel=$aFlag;
  3612. }
  3613. // Don't display minor tick marks
  3614. function SupressMinorTickMarks($aHide=true) {
  3615. $this->supress_minor_tickmarks=$aHide;
  3616. }
  3617. // Don't display major tick marks
  3618. function SupressTickMarks($aHide=true) {
  3619. $this->supress_tickmarks=$aHide;
  3620. }
  3621. // Hide the first tick mark
  3622. function SupressFirst($aHide=true) {
  3623. $this->supress_first=$aHide;
  3624. }
  3625. // Hide the last tick mark
  3626. function SupressLast($aHide=true) {
  3627. $this->supress_last=$aHide;
  3628. }
  3629. // Size (in pixels) of minor tick marks
  3630. function GetMinTickAbsSize() {
  3631. return $this->minor_abs_size;
  3632. }
  3633. // Size (in pixels) of major tick marks
  3634. function GetMajTickAbsSize() {
  3635. return $this->major_abs_size;
  3636. }
  3637. function SetSize($aMajSize,$aMinSize=3) {
  3638. $this->major_abs_size = $aMajSize;
  3639. $this->minor_abs_size = $aMinSize;
  3640. }
  3641. // Have the ticks been specified
  3642. function IsSpecified() {
  3643. return $this->is_set;
  3644. }
  3645. // Set the distance between major and minor tick marks
  3646. function Set($aMaj,$aMin) {
  3647. // "Virtual method"
  3648. // Should be implemented by the concrete subclass
  3649. // if any action is wanted.
  3650. }
  3651. // Specify number of decimals in automatic labels
  3652. // Deprecated from 1.4. Use SetFormatString() instead
  3653. function SetPrecision($aPrecision) {
  3654. if( ERR_DEPRECATED )
  3655. JpGraphError::Raise('Ticks::SetPrecision() is deprecated. Use Ticks::SetLabelFormat() (or Ticks::SetFormatCallback()) instead');
  3656. $this->precision=$aPrecision;
  3657. }
  3658. function SetSide($aSide) {
  3659. $this->direction=$aSide;
  3660. }
  3661. // Which side of the axis should the ticks be on
  3662. function SetDirection($aSide=SIDE_RIGHT) {
  3663. $this->direction=$aSide;
  3664. }
  3665. // Set colors for major and minor tick marks
  3666. function SetMarkColor($aMajorColor,$aMinorColor="") {
  3667. $this->SetColor($aMajorColor,$aMinorColor);
  3668. }
  3669. function SetColor($aMajorColor,$aMinorColor="") {
  3670. $this->majcolor=$aMajorColor;
  3671. // If not specified use same as major
  3672. if( $aMinorColor=="" )
  3673. $this->mincolor=$aMajorColor;
  3674. else
  3675. $this->mincolor=$aMinorColor;
  3676. }
  3677. function SetWeight($aWeight) {
  3678. $this->weight=$aWeight;
  3679. }
  3680. } // Class
  3681. //===================================================
  3682. // CLASS LinearTicks
  3683. // Description: Draw linear ticks on axis
  3684. //===================================================
  3685. class LinearTicks extends Ticks {
  3686. var $minor_step=1, $major_step=2;
  3687. var $xlabel_offset=0,$xtick_offset=0;
  3688. var $label_offset=0; // What offset should the displayed label have
  3689. // i.e should we display 0,1,2 or 1,2,3,4 or 2,3,4 etc
  3690. var $text_label_start=0;
  3691. //---------------
  3692. // CONSTRUCTOR
  3693. function LinearTicks() {
  3694. $this->precision = -1;
  3695. }
  3696. //---------------
  3697. // PUBLIC METHODS
  3698. // Return major step size in world coordinates
  3699. function GetMajor() {
  3700. return $this->major_step;
  3701. }
  3702. // Return minor step size in world coordinates
  3703. function GetMinor() {
  3704. return $this->minor_step;
  3705. }
  3706. // Set Minor and Major ticks (in world coordinates)
  3707. function Set($aMajStep,$aMinStep=false) {
  3708. if( $aMinStep==false )
  3709. $aMinStep=$aMajStep;
  3710. if( $aMajStep <= 0 || $aMinStep <= 0 ) {
  3711. JpGraphError::Raise(" Minor or major step size is 0. Check that you haven't
  3712. got an accidental SetTextTicks(0) in your code.<p>
  3713. If this is not the case you might have stumbled upon a bug in JpGraph.
  3714. Please report this and if possible include the data that caused the
  3715. problem.");
  3716. }
  3717. $this->major_step=$aMajStep;
  3718. $this->minor_step=$aMinStep;
  3719. $this->is_set = true;
  3720. }
  3721. // Draw linear ticks
  3722. function Stroke(&$img,&$scale,$pos) {
  3723. $maj_step_abs = $scale->scale_factor*$this->major_step;
  3724. $min_step_abs = $scale->scale_factor*$this->minor_step;
  3725. if( $min_step_abs==0 || $maj_step_abs==0 )
  3726. JpGraphError::Raise("A plot has an illegal scale. This could for example be that you are trying to use text autoscaling to draw a line plot with only one point or that the plot area is too small. It could also be that no input data value is numeric (perhaps only '-' or 'x')");
  3727. $limit = $scale->scale_abs[1];
  3728. $nbrmajticks=floor(1.000001*(($scale->GetMaxVal()-$scale->GetMinVal())/$this->major_step))+1;
  3729. $first=0;
  3730. // If precision hasn't been specified set it to a sensible value
  3731. if( $this->precision==-1 ) {
  3732. $t = log10($this->minor_step);
  3733. if( $t > 0 )
  3734. $precision = 0;
  3735. else
  3736. $precision = -floor($t);
  3737. }
  3738. else
  3739. $precision = $this->precision;
  3740. $img->SetLineWeight($this->weight);
  3741. // Handle ticks on X-axis
  3742. if( $scale->type == "x" ) {
  3743. // Draw the minor tick marks
  3744. $yu = $pos - $this->direction*$this->GetMinTickAbsSize();
  3745. $label = $scale->GetMinVal();
  3746. $x=$scale->scale_abs[0];
  3747. $i=0;
  3748. $j=0;
  3749. $step = round($maj_step_abs/$min_step_abs);
  3750. while( $x < $limit ) {
  3751. $this->ticks_pos[]=$x;
  3752. $this->ticks_label[]=$label;
  3753. $label+=$this->minor_step;
  3754. if( !$this->supress_tickmarks && !$this->supress_minor_tickmarks) {
  3755. if( $this->mincolor!="" ) $img->PushColor($this->mincolor);
  3756. $img->Line($x,$pos,$x,$yu);
  3757. if( $this->mincolor!="" ) $img->PopColor();
  3758. }
  3759. if( $i % $step == 0 ) {
  3760. $this->maj_ticks_pos[$j]=round($x);//$xtick;
  3761. ++$j;
  3762. }
  3763. ++$i;
  3764. $x += $min_step_abs;
  3765. }
  3766. $this->maj_ticks_pos[$j]=$x;
  3767. // Draw the major tick marks
  3768. $yu = $pos - $this->direction*$this->GetMajTickAbsSize();
  3769. // TODO: Add logic to set label_offset for text labels
  3770. $label = (float)$scale->GetMinVal()+$this->text_label_start+$this->label_offset;
  3771. $start_abs=$scale->scale_factor*$this->text_label_start;
  3772. $nbrmajticks=ceil(($scale->GetMaxVal()-$scale->GetMinVal()-$this->text_label_start )/$this->major_step)+1;
  3773. $x = $scale->scale_abs[0]+$start_abs+$this->xlabel_offset*$min_step_abs;
  3774. for( $i=0; $label <= $scale->GetMaxVal()+$this->label_offset; ++$i ) {
  3775. // Apply format
  3776. if( $this->label_formfunc != "" ) {
  3777. $f=$this->label_formfunc;
  3778. $l = call_user_func($f,$label);
  3779. }
  3780. elseif( $this->label_formatstr != '' )
  3781. $l = sprintf($this->label_formatstr,$label);
  3782. elseif( $this->label_dateformatstr != '' ) {
  3783. $l = date($this->label_dateformatstr,$label);
  3784. }
  3785. else {
  3786. $v = round($label,$precision);
  3787. $l = sprintf("%01.".$precision."f",$v);
  3788. }
  3789. if( ($this->supress_zerolabel && $l==0) ||
  3790. ($this->supress_first && $i==0) ||
  3791. ($this->supress_last && $i==$nbrmajticks-1) ) {
  3792. $l="";
  3793. }
  3794. $this->maj_ticks_label[$i]=$l;
  3795. $label+=$this->major_step;
  3796. $this->maj_ticklabels_pos[$i] = $x;
  3797. // $this->maj_ticklabels_pos[$i] = $this->maj_ticks_pos[$i];
  3798. // The x-position of the tick marks can be different from the labels.
  3799. // Note that we record the tick position (not the label) so that the grid
  3800. // happen upon tick marks and not labels.
  3801. $xtick=$scale->scale_abs[0]+$start_abs+$this->xtick_offset*$min_step_abs+$i*$maj_step_abs;
  3802. $this->maj_ticks_pos[$i]=$xtick;
  3803. if(!($this->xtick_offset > 0 && $i==$nbrmajticks-1) &&
  3804. !$this->supress_tickmarks) {
  3805. if( $this->majcolor!="" ) $img->PushColor($this->majcolor);
  3806. $img->Line($this->maj_ticks_pos[$i],$pos,$this->maj_ticks_pos[$i],$yu);
  3807. if( $this->majcolor!="" ) $img->PopColor();
  3808. }
  3809. $x += $maj_step_abs;
  3810. }
  3811. }
  3812. elseif( $scale->type == "y" ) {
  3813. // Draw the major tick marks
  3814. $xr = $pos + $this->direction*$this->GetMajTickAbsSize();
  3815. $label = $scale->GetMinVal();
  3816. $tmpmaj=array();
  3817. $tmpmin=array();
  3818. for( $i=0; $i<$nbrmajticks; ++$i) {
  3819. $y=$scale->scale_abs[0]+$i*$maj_step_abs;
  3820. $tmpmaj[]=$y;
  3821. // THe following two lines might seem to be unecessary but they are not!
  3822. // The reason being that for X-axis we separate the position of the labels
  3823. // and the tick marks which we don't do for the Y-axis.
  3824. // We therefore need to make sure both arrays are corcectly filled
  3825. // since Axis::StrokeLabels() uses the label positions and Grid::Stroke() uses
  3826. // the tick positions.
  3827. $this->maj_ticklabels_pos[$i]=$y;
  3828. $this->maj_ticks_pos[$i]=$y;
  3829. if( $this->label_formfunc != "" ) {
  3830. $f=$this->label_formfunc;
  3831. $l = call_user_func($f,$label);
  3832. }
  3833. elseif( $this->label_formatstr != "" )
  3834. $l = sprintf($this->label_formatstr,$label);
  3835. else
  3836. $l = sprintf("%01.".$precision."f",round($label,$precision));
  3837. if( ($this->supress_zerolabel && ($l + 0)==0) || ($this->supress_first && $i==0) ||
  3838. ($this->supress_last && $i==$nbrmajticks-1) ) {
  3839. $l="";
  3840. }
  3841. $this->maj_ticks_label[$i]=$l;
  3842. $label+=$this->major_step;
  3843. if( !$this->supress_tickmarks ) {
  3844. if( $this->majcolor!="" ) $img->PushColor($this->majcolor);
  3845. $img->Line($pos,$y,$xr,$y);
  3846. if( $this->majcolor!="" ) $img->PopColor();
  3847. }
  3848. }
  3849. // Draw the minor tick marks
  3850. $xr = $pos + $this->direction*$this->GetMinTickAbsSize();
  3851. $label = $scale->GetMinVal();
  3852. for( $i=0,$y=$scale->scale_abs[0]; $y>=$limit; ) {
  3853. $tmpmin[]=$y;
  3854. $this->ticks_pos[$i]=$y;
  3855. $this->ticks_label[$i]=$label;
  3856. $label+=$this->minor_step;
  3857. if( !$this->supress_tickmarks && !$this->supress_minor_tickmarks) {
  3858. if( $this->mincolor!="" ) $img->PushColor($this->mincolor);
  3859. $img->Line($pos,$y,$xr,$y);
  3860. if( $this->mincolor!="" ) $img->PopColor();
  3861. }
  3862. ++$i;
  3863. $y=$scale->scale_abs[0]+$i*$min_step_abs;
  3864. }
  3865. }
  3866. }
  3867. //---------------
  3868. // PRIVATE METHODS
  3869. // Spoecify the offset of the displayed tick mark with the tick "space"
  3870. // Legal values for $o is [0,1] used to adjust where the tick marks and label
  3871. // should be positioned within the major tick-size
  3872. // $lo specifies the label offset and $to specifies the tick offset
  3873. // this comes in handy for example in bar graphs where we wont no offset for the
  3874. // tick but have the labels displayed halfway under the bars.
  3875. function SetXLabelOffset($aLabelOff,$aTickOff=-1) {
  3876. $this->xlabel_offset=$aLabelOff;
  3877. if( $aTickOff==-1 ) // Same as label offset
  3878. $this->xtick_offset=$aLabelOff;
  3879. else
  3880. $this->xtick_offset=$aTickOff;
  3881. if( $aLabelOff>0 )
  3882. $this->SupressLast(); // The last tick wont fit
  3883. }
  3884. // Which tick label should we start with?
  3885. function SetTextLabelStart($aTextLabelOff) {
  3886. $this->text_label_start=$aTextLabelOff;
  3887. }
  3888. } // Class
  3889. //===================================================
  3890. // CLASS LinearScale
  3891. // Description: Handle linear scaling between screen and world
  3892. //===================================================
  3893. class LinearScale {
  3894. var $scale=array(0,0);
  3895. var $scale_abs=array(0,0);
  3896. var $scale_factor; // Scale factor between world and screen
  3897. var $world_size; // Plot area size in world coordinates
  3898. var $world_abs_size; // Plot area size in pixels
  3899. var $off; // Offset between image edge and plot area
  3900. var $type; // is this x or y scale ?
  3901. var $ticks=null; // Store ticks
  3902. var $autoscale_min=false; // Forced minimum value, auto determine max
  3903. var $autoscale_max=false; // Forced maximum value, auto determine min
  3904. var $gracetop=0,$gracebottom=0;
  3905. var $intscale=false; // Restrict autoscale to integers
  3906. var $textscale=false; // Just a flag to let the Plot class find out if
  3907. // we are a textscale or not. This is a cludge since
  3908. // this ionformatyion is availabale in Graph::axtype but
  3909. // we don't have access to the graph object in the Plots
  3910. // stroke method. So we let graph store the status here
  3911. // when the linear scale is created. A real cludge...
  3912. var $text_scale_off = 0;
  3913. var $auto_ticks=false; // When using manual scale should the ticks be automatically set?
  3914. var $name = 'lin';
  3915. //---------------
  3916. // CONSTRUCTOR
  3917. function LinearScale($aMin=0,$aMax=0,$aType="y") {
  3918. assert($aType=="x" || $aType=="y" );
  3919. assert($aMin<=$aMax);
  3920. $this->type=$aType;
  3921. $this->scale=array($aMin,$aMax);
  3922. $this->world_size=$aMax-$aMin;
  3923. $this->ticks = new LinearTicks();
  3924. }
  3925. //---------------
  3926. // PUBLIC METHODS
  3927. // Check if scale is set or if we should autoscale
  3928. // We should do this is either scale or ticks has not been set
  3929. function IsSpecified() {
  3930. if( $this->GetMinVal()==$this->GetMaxVal() ) { // Scale not set
  3931. return false;
  3932. }
  3933. return true;
  3934. }
  3935. // Set the minimum data value when the autoscaling is used.
  3936. // Usefull if you want a fix minimum (like 0) but have an
  3937. // automatic maximum
  3938. function SetAutoMin($aMin) {
  3939. $this->autoscale_min=$aMin;
  3940. }
  3941. // Set the minimum data value when the autoscaling is used.
  3942. // Usefull if you want a fix minimum (like 0) but have an
  3943. // automatic maximum
  3944. function SetAutoMax($aMax) {
  3945. $this->autoscale_max=$aMax;
  3946. }
  3947. // If the user manually specifies a scale should the ticks
  3948. // still be set automatically?
  3949. function SetAutoTicks($aFlag=true) {
  3950. $this->auto_ticks = $aFlag;
  3951. }
  3952. // Specify scale "grace" value (top and bottom)
  3953. function SetGrace($aGraceTop,$aGraceBottom=0) {
  3954. if( $aGraceTop<0 || $aGraceBottom < 0 )
  3955. JpGraphError::Raise(" Grace must be larger then 0");
  3956. $this->gracetop=$aGraceTop;
  3957. $this->gracebottom=$aGraceBottom;
  3958. }
  3959. // Get the minimum value in the scale
  3960. function GetMinVal() {
  3961. return $this->scale[0];
  3962. }
  3963. // get maximum value for scale
  3964. function GetMaxVal() {
  3965. return $this->scale[1];
  3966. }
  3967. // Specify a new min/max value for sclae
  3968. function Update(&$aImg,$aMin,$aMax) {
  3969. $this->scale=array($aMin,$aMax);
  3970. $this->world_size=$aMax-$aMin;
  3971. $this->InitConstants($aImg);
  3972. }
  3973. // Translate between world and screen
  3974. function Translate($aCoord) {
  3975. if( !is_numeric($aCoord) ) {
  3976. if( $aCoord != '' && $aCoord != '-' && $aCoord != 'x' )
  3977. JpGraphError::Raise('Your data contains non-numeric values.');
  3978. return 0;
  3979. }
  3980. else {
  3981. return $this->off + ($aCoord - $this->scale[0])*$this->scale_factor;
  3982. }
  3983. }
  3984. // Relative translate (don't include offset) usefull when we just want
  3985. // to know the relative position (in pixels) on the axis
  3986. function RelTranslate($aCoord) {
  3987. if( !is_numeric($aCoord) ) {
  3988. if( $aCoord != '' && $aCoord != '-' && $aCoord != 'x' )
  3989. JpGraphError::Raise('Your data contains non-numeric values.');
  3990. return 0;
  3991. }
  3992. else {
  3993. return ($aCoord - $this->scale[0]) * $this->scale_factor;
  3994. }
  3995. }
  3996. // Restrict autoscaling to only use integers
  3997. function SetIntScale($aIntScale=true) {
  3998. $this->intscale=$aIntScale;
  3999. }
  4000. // Calculate an integer autoscale
  4001. function IntAutoScale(&$img,$min,$max,$maxsteps,$majend=true) {
  4002. // Make sure limits are integers
  4003. $min=floor($min);
  4004. $max=ceil($max);
  4005. if( abs($min-$max)==0 ) {
  4006. --$min; ++$max;
  4007. }
  4008. $maxsteps = floor($maxsteps);
  4009. $gracetop=round(($this->gracetop/100.0)*abs($max-$min));
  4010. $gracebottom=round(($this->gracebottom/100.0)*abs($max-$min));
  4011. if( is_numeric($this->autoscale_min) ) {
  4012. $min = ceil($this->autoscale_min);
  4013. if( $min >= $max ) {
  4014. JpGraphError::Raise('You have specified a min value with SetAutoMin() which is larger than the maximum value used for the scale. This is not possible.');
  4015. die();
  4016. }
  4017. }
  4018. if( is_numeric($this->autoscale_max) ) {
  4019. $max = ceil($this->autoscale_max);
  4020. if( $min >= $max ) {
  4021. JpGraphError::Raise('You have specified a max value with SetAutoMax() which is smaller than the miminum value used for the scale. This is not possible.');
  4022. die();
  4023. }
  4024. }
  4025. if( abs($min-$max ) == 0 ) {
  4026. ++$max;
  4027. --$min;
  4028. }
  4029. $min -= $gracebottom;
  4030. $max += $gracetop;
  4031. // First get tickmarks as multiples of 1, 10, ...
  4032. if( $majend ) {
  4033. list($num1steps,$adj1min,$adj1max,$maj1step) =
  4034. $this->IntCalcTicks($maxsteps,$min,$max,1);
  4035. }
  4036. else {
  4037. $adj1min = $min;
  4038. $adj1max = $max;
  4039. list($num1steps,$maj1step) =
  4040. $this->IntCalcTicksFreeze($maxsteps,$min,$max,1);
  4041. }
  4042. if( abs($min-$max) > 2 ) {
  4043. // Then get tick marks as 2:s 2, 20, ...
  4044. if( $majend ) {
  4045. list($num2steps,$adj2min,$adj2max,$maj2step) =
  4046. $this->IntCalcTicks($maxsteps,$min,$max,5);
  4047. }
  4048. else {
  4049. $adj2min = $min;
  4050. $adj2max = $max;
  4051. list($num2steps,$maj2step) =
  4052. $this->IntCalcTicksFreeze($maxsteps,$min,$max,5);
  4053. }
  4054. }
  4055. else {
  4056. $num2steps = 10000; // Dummy high value so we don't choose this
  4057. }
  4058. if( abs($min-$max) > 5 ) {
  4059. // Then get tickmarks as 5:s 5, 50, 500, ...
  4060. if( $majend ) {
  4061. list($num5steps,$adj5min,$adj5max,$maj5step) =
  4062. $this->IntCalcTicks($maxsteps,$min,$max,2);
  4063. }
  4064. else {
  4065. $adj5min = $min;
  4066. $adj5max = $max;
  4067. list($num5steps,$maj5step) =
  4068. $this->IntCalcTicksFreeze($maxsteps,$min,$max,2);
  4069. }
  4070. }
  4071. else {
  4072. $num5steps = 10000; // Dummy high value so we don't choose this
  4073. }
  4074. // Check to see whichof 1:s, 2:s or 5:s fit better with
  4075. // the requested number of major ticks
  4076. $match1=abs($num1steps-$maxsteps);
  4077. $match2=abs($num2steps-$maxsteps);
  4078. if( !empty($maj5step) && $maj5step > 1 )
  4079. $match5=abs($num5steps-$maxsteps);
  4080. else
  4081. $match5=10000; // Dummy high value
  4082. // Compare these three values and see which is the closest match
  4083. // We use a 0.6 weight to gravitate towards multiple of 5:s
  4084. if( $match1 < $match2 ) {
  4085. if( $match1 < $match5 )
  4086. $r=1;
  4087. else
  4088. $r=3;
  4089. }
  4090. else {
  4091. if( $match2 < $match5 )
  4092. $r=2;
  4093. else
  4094. $r=3;
  4095. }
  4096. // Minsteps are always the same as maxsteps for integer scale
  4097. switch( $r ) {
  4098. case 1:
  4099. $this->Update($img,$adj1min,$adj1max);
  4100. $this->ticks->Set($maj1step,$maj1step);
  4101. break;
  4102. case 2:
  4103. $this->Update($img,$adj2min,$adj2max);
  4104. $this->ticks->Set($maj2step,$maj2step);
  4105. break;
  4106. case 3:
  4107. $this->Update($img,$adj5min,$adj5max);
  4108. $this->ticks->Set($maj5step,$maj2step);
  4109. break;
  4110. }
  4111. }
  4112. // Calculate autoscale. Used if user hasn't given a scale and ticks
  4113. // $maxsteps is the maximum number of major tickmarks allowed.
  4114. function AutoScale(&$img,$min,$max,$maxsteps,$majend=true) {
  4115. if( $this->intscale ) {
  4116. $this->IntAutoScale($img,$min,$max,$maxsteps,$majend);
  4117. return;
  4118. }
  4119. if( abs($min-$max) < 0.00001 ) {
  4120. // We need some difference to be able to autoscale
  4121. // make it 5% above and 5% below value
  4122. if( $min==0 && $max==0 ) { // Special case
  4123. $min=-1; $max=1;
  4124. }
  4125. else {
  4126. $delta = (abs($max)+abs($min))*0.005;
  4127. $min -= $delta;
  4128. $max += $delta;
  4129. }
  4130. }
  4131. $gracetop=($this->gracetop/100.0)*abs($max-$min);
  4132. $gracebottom=($this->gracebottom/100.0)*abs($max-$min);
  4133. if( is_numeric($this->autoscale_min) ) {
  4134. $min = $this->autoscale_min;
  4135. if( $min >= $max ) {
  4136. JpGraphError::Raise('You have specified a min value with SetAutoMin() which is larger than the maximum value used for the scale. This is not possible.');
  4137. die();
  4138. }
  4139. if( abs($min-$max ) < 0.00001 )
  4140. $max *= 1.2;
  4141. }
  4142. if( is_numeric($this->autoscale_max) ) {
  4143. $max = $this->autoscale_max;
  4144. if( $min >= $max ) {
  4145. JpGraphError::Raise('You have specified a max value with SetAutoMax() which is smaller than the miminum value used for the scale. This is not possible.');
  4146. die();
  4147. }
  4148. if( abs($min-$max ) < 0.00001 )
  4149. $min *= 0.8;
  4150. }
  4151. $min -= $gracebottom;
  4152. $max += $gracetop;
  4153. // First get tickmarks as multiples of 0.1, 1, 10, ...
  4154. if( $majend ) {
  4155. list($num1steps,$adj1min,$adj1max,$min1step,$maj1step) =
  4156. $this->CalcTicks($maxsteps,$min,$max,1,2);
  4157. }
  4158. else {
  4159. $adj1min=$min;
  4160. $adj1max=$max;
  4161. list($num1steps,$min1step,$maj1step) =
  4162. $this->CalcTicksFreeze($maxsteps,$min,$max,1,2,false);
  4163. }
  4164. // Then get tick marks as 2:s 0.2, 2, 20, ...
  4165. if( $majend ) {
  4166. list($num2steps,$adj2min,$adj2max,$min2step,$maj2step) =
  4167. $this->CalcTicks($maxsteps,$min,$max,5,2);
  4168. }
  4169. else {
  4170. $adj2min=$min;
  4171. $adj2max=$max;
  4172. list($num2steps,$min2step,$maj2step) =
  4173. $this->CalcTicksFreeze($maxsteps,$min,$max,5,2,false);
  4174. }
  4175. // Then get tickmarks as 5:s 0.05, 0.5, 5, 50, ...
  4176. if( $majend ) {
  4177. list($num5steps,$adj5min,$adj5max,$min5step,$maj5step) =
  4178. $this->CalcTicks($maxsteps,$min,$max,2,5);
  4179. }
  4180. else {
  4181. $adj5min=$min;
  4182. $adj5max=$max;
  4183. list($num5steps,$min5step,$maj5step) =
  4184. $this->CalcTicksFreeze($maxsteps,$min,$max,2,5,false);
  4185. }
  4186. // Check to see whichof 1:s, 2:s or 5:s fit better with
  4187. // the requested number of major ticks
  4188. $match1=abs($num1steps-$maxsteps);
  4189. $match2=abs($num2steps-$maxsteps);
  4190. $match5=abs($num5steps-$maxsteps);
  4191. // Compare these three values and see which is the closest match
  4192. // We use a 0.8 weight to gravitate towards multiple of 5:s
  4193. $r=$this->MatchMin3($match1,$match2,$match5,0.8);
  4194. switch( $r ) {
  4195. case 1:
  4196. $this->Update($img,$adj1min,$adj1max);
  4197. $this->ticks->Set($maj1step,$min1step);
  4198. break;
  4199. case 2:
  4200. $this->Update($img,$adj2min,$adj2max);
  4201. $this->ticks->Set($maj2step,$min2step);
  4202. break;
  4203. case 3:
  4204. $this->Update($img,$adj5min,$adj5max);
  4205. $this->ticks->Set($maj5step,$min5step);
  4206. break;
  4207. }
  4208. }
  4209. //---------------
  4210. // PRIVATE METHODS
  4211. // This method recalculates all constants that are depending on the
  4212. // margins in the image. If the margins in the image are changed
  4213. // this method should be called for every scale that is registred with
  4214. // that image. Should really be installed as an observer of that image.
  4215. function InitConstants(&$img) {
  4216. if( $this->type=="x" ) {
  4217. $this->world_abs_size=$img->width - $img->left_margin - $img->right_margin;
  4218. $this->off=$img->left_margin;
  4219. $this->scale_factor = 0;
  4220. if( $this->world_size > 0 )
  4221. $this->scale_factor=$this->world_abs_size/($this->world_size*1.0);
  4222. }
  4223. else { // y scale
  4224. $this->world_abs_size=$img->height - $img->top_margin - $img->bottom_margin;
  4225. $this->off=$img->top_margin+$this->world_abs_size;
  4226. $this->scale_factor = 0;
  4227. if( $this->world_size > 0 ) {
  4228. $this->scale_factor=-$this->world_abs_size/($this->world_size*1.0);
  4229. }
  4230. }
  4231. $size = $this->world_size * $this->scale_factor;
  4232. $this->scale_abs=array($this->off,$this->off + $size);
  4233. }
  4234. // Initialize the conversion constants for this scale
  4235. // This tries to pre-calculate as much as possible to speed up the
  4236. // actual conversion (with Translate()) later on
  4237. // $start =scale start in absolute pixels (for x-scale this is an y-position
  4238. // and for an y-scale this is an x-position
  4239. // $len =absolute length in pixels of scale
  4240. function SetConstants($aStart,$aLen) {
  4241. $this->world_abs_size=$aLen;
  4242. $this->off=$aStart;
  4243. if( $this->world_size<=0 ) {
  4244. // This should never ever happen !!
  4245. JpGraphError::Raise("JpGraph Fatal Error:<br>
  4246. You have unfortunately stumbled upon a bug in JpGraph. <br>
  4247. It seems like the scale range is ".$this->world_size." [for ".
  4248. $this->type." scale] <br>
  4249. Please report Bug #01 to jpgraph@aditus.nu and include the script
  4250. that gave this error. <br>
  4251. This problem could potentially be caused by trying to use \"illegal\"
  4252. values in the input data arrays (like trying to send in strings or
  4253. only NULL values) which causes the autoscaling to fail.");
  4254. }
  4255. // scale_factor = number of pixels per world unit
  4256. $this->scale_factor=$this->world_abs_size/($this->world_size*1.0);
  4257. // scale_abs = start and end points of scale in absolute pixels
  4258. $this->scale_abs=array($this->off,$this->off+$this->world_size*$this->scale_factor);
  4259. }
  4260. // Calculate number of ticks steps with a specific division
  4261. // $a is the divisor of 10**x to generate the first maj tick intervall
  4262. // $a=1, $b=2 give major ticks with multiple of 10, ...,0.1,1,10,...
  4263. // $a=5, $b=2 give major ticks with multiple of 2:s ...,0.2,2,20,...
  4264. // $a=2, $b=5 give major ticks with multiple of 5:s ...,0.5,5,50,...
  4265. // We return a vector of
  4266. // [$numsteps,$adjmin,$adjmax,$minstep,$majstep]
  4267. // If $majend==true then the first and last marks on the axis will be major
  4268. // labeled tick marks otherwise it will be adjusted to the closest min tick mark
  4269. function CalcTicks($maxsteps,$min,$max,$a,$b,$majend=true) {
  4270. $diff=$max-$min;
  4271. if( $diff==0 )
  4272. $ld=0;
  4273. else
  4274. $ld=floor(log10($diff));
  4275. // Gravitate min towards zero if we are close
  4276. if( $min>0 && $min < pow(10,$ld) ) $min=0;
  4277. //$majstep=pow(10,$ld-1)/$a;
  4278. $majstep=pow(10,$ld)/$a;
  4279. $minstep=$majstep/$b;
  4280. $adjmax=ceil($max/$minstep)*$minstep;
  4281. $adjmin=floor($min/$minstep)*$minstep;
  4282. $adjdiff = $adjmax-$adjmin;
  4283. $numsteps=$adjdiff/$majstep;
  4284. while( $numsteps>$maxsteps ) {
  4285. $majstep=pow(10,$ld)/$a;
  4286. $numsteps=$adjdiff/$majstep;
  4287. ++$ld;
  4288. }
  4289. $minstep=$majstep/$b;
  4290. $adjmin=floor($min/$minstep)*$minstep;
  4291. $adjdiff = $adjmax-$adjmin;
  4292. if( $majend ) {
  4293. $adjmin = floor($min/$majstep)*$majstep;
  4294. $adjdiff = $adjmax-$adjmin;
  4295. $adjmax = ceil($adjdiff/$majstep)*$majstep+$adjmin;
  4296. }
  4297. else
  4298. $adjmax=ceil($max/$minstep)*$minstep;
  4299. return array($numsteps,$adjmin,$adjmax,$minstep,$majstep);
  4300. }
  4301. function CalcTicksFreeze($maxsteps,$min,$max,$a,$b) {
  4302. // Same as CalcTicks but don't adjust min/max values
  4303. $diff=$max-$min;
  4304. if( $diff==0 )
  4305. $ld=0;
  4306. else
  4307. $ld=floor(log10($diff));
  4308. //$majstep=pow(10,$ld-1)/$a;
  4309. $majstep=pow(10,$ld)/$a;
  4310. $minstep=$majstep/$b;
  4311. $numsteps=floor($diff/$majstep);
  4312. while( $numsteps > $maxsteps ) {
  4313. $majstep=pow(10,$ld)/$a;
  4314. $numsteps=floor($diff/$majstep);
  4315. ++$ld;
  4316. }
  4317. $minstep=$majstep/$b;
  4318. return array($numsteps,$minstep,$majstep);
  4319. }
  4320. function IntCalcTicks($maxsteps,$min,$max,$a,$majend=true) {
  4321. $diff=$max-$min;
  4322. if( $diff==0 )
  4323. JpGraphError::Raise('Can\'t automatically determine ticks since min==max.');
  4324. else
  4325. $ld=floor(log10($diff));
  4326. // Gravitate min towards zero if we are close
  4327. if( $min>0 && $min < pow(10,$ld) ) $min=0;
  4328. if( $ld == 0 ) $ld=1;
  4329. if( $a == 1 )
  4330. $majstep = 1;
  4331. else
  4332. $majstep=pow(10,$ld)/$a;
  4333. $adjmax=ceil($max/$majstep)*$majstep;
  4334. $adjmin=floor($min/$majstep)*$majstep;
  4335. $adjdiff = $adjmax-$adjmin;
  4336. $numsteps=$adjdiff/$majstep;
  4337. while( $numsteps>$maxsteps ) {
  4338. $majstep=pow(10,$ld)/$a;
  4339. $numsteps=$adjdiff/$majstep;
  4340. ++$ld;
  4341. }
  4342. $adjmin=floor($min/$majstep)*$majstep;
  4343. $adjdiff = $adjmax-$adjmin;
  4344. if( $majend ) {
  4345. $adjmin = floor($min/$majstep)*$majstep;
  4346. $adjdiff = $adjmax-$adjmin;
  4347. $adjmax = ceil($adjdiff/$majstep)*$majstep+$adjmin;
  4348. }
  4349. else
  4350. $adjmax=ceil($max/$majstep)*$majstep;
  4351. return array($numsteps,$adjmin,$adjmax,$majstep);
  4352. }
  4353. function IntCalcTicksFreeze($maxsteps,$min,$max,$a) {
  4354. // Same as IntCalcTick but don't change min/max values
  4355. $diff=$max-$min;
  4356. if( $diff==0 )
  4357. JpGraphError::Raise('Can\'t automatically determine ticks since min==max.');
  4358. else
  4359. $ld=floor(log10($diff));
  4360. if( $ld == 0 ) $ld=1;
  4361. if( $a == 1 )
  4362. $majstep = 1;
  4363. else
  4364. $majstep=pow(10,$ld)/$a;
  4365. $numsteps=floor($diff/$majstep);
  4366. while( $numsteps > $maxsteps ) {
  4367. $majstep=pow(10,$ld)/$a;
  4368. $numsteps=floor($diff/$majstep);
  4369. ++$ld;
  4370. }
  4371. return array($numsteps,$majstep);
  4372. }
  4373. // Determine the minimum of three values witha weight for last value
  4374. function MatchMin3($a,$b,$c,$weight) {
  4375. if( $a < $b ) {
  4376. if( $a < ($c*$weight) )
  4377. return 1; // $a smallest
  4378. else
  4379. return 3; // $c smallest
  4380. }
  4381. elseif( $b < ($c*$weight) )
  4382. return 2; // $b smallest
  4383. return 3; // $c smallest
  4384. }
  4385. } // Class
  4386. //===================================================
  4387. // CLASS RGB
  4388. // Description: Color definitions as RGB triples
  4389. //===================================================
  4390. class RGB {
  4391. var $rgb_table;
  4392. var $img;
  4393. function RGB($aImg=null) {
  4394. $this->img = $aImg;
  4395. // Conversion array between color names and RGB
  4396. $this->rgb_table = array(
  4397. "aqua"=> array(0,255,255),
  4398. "lime"=> array(0,255,0),
  4399. "teal"=> array(0,128,128),
  4400. "whitesmoke"=>array(245,245,245),
  4401. "gainsboro"=>array(220,220,220),
  4402. "oldlace"=>array(253,245,230),
  4403. "linen"=>array(250,240,230),
  4404. "antiquewhite"=>array(250,235,215),
  4405. "papayawhip"=>array(255,239,213),
  4406. "blanchedalmond"=>array(255,235,205),
  4407. "bisque"=>array(255,228,196),
  4408. "peachpuff"=>array(255,218,185),
  4409. "navajowhite"=>array(255,222,173),
  4410. "moccasin"=>array(255,228,181),
  4411. "cornsilk"=>array(255,248,220),
  4412. "ivory"=>array(255,255,240),
  4413. "lemonchiffon"=>array(255,250,205),
  4414. "seashell"=>array(255,245,238),
  4415. "mintcream"=>array(245,255,250),
  4416. "azure"=>array(240,255,255),
  4417. "aliceblue"=>array(240,248,255),
  4418. "lavender"=>array(230,230,250),
  4419. "lavenderblush"=>array(255,240,245),
  4420. "mistyrose"=>array(255,228,225),
  4421. "white"=>array(255,255,255),
  4422. "black"=>array(0,0,0),
  4423. "darkslategray"=>array(47,79,79),
  4424. "dimgray"=>array(105,105,105),
  4425. "slategray"=>array(112,128,144),
  4426. "lightslategray"=>array(119,136,153),
  4427. "gray"=>array(190,190,190),
  4428. "lightgray"=>array(211,211,211),
  4429. "midnightblue"=>array(25,25,112),
  4430. "navy"=>array(0,0,128),
  4431. "cornflowerblue"=>array(100,149,237),
  4432. "darkslateblue"=>array(72,61,139),
  4433. "slateblue"=>array(106,90,205),
  4434. "mediumslateblue"=>array(123,104,238),
  4435. "lightslateblue"=>array(132,112,255),
  4436. "mediumblue"=>array(0,0,205),
  4437. "royalblue"=>array(65,105,225),
  4438. "blue"=>array(0,0,255),
  4439. "dodgerblue"=>array(30,144,255),
  4440. "deepskyblue"=>array(0,191,255),
  4441. "skyblue"=>array(135,206,235),
  4442. "lightskyblue"=>array(135,206,250),
  4443. "steelblue"=>array(70,130,180),
  4444. "lightred"=>array(211,167,168),
  4445. "lightsteelblue"=>array(176,196,222),
  4446. "lightblue"=>array(173,216,230),
  4447. "powderblue"=>array(176,224,230),
  4448. "paleturquoise"=>array(175,238,238),
  4449. "darkturquoise"=>array(0,206,209),
  4450. "mediumturquoise"=>array(72,209,204),
  4451. "turquoise"=>array(64,224,208),
  4452. "cyan"=>array(0,255,255),
  4453. "lightcyan"=>array(224,255,255),
  4454. "cadetblue"=>array(95,158,160),
  4455. "mediumaquamarine"=>array(102,205,170),
  4456. "aquamarine"=>array(127,255,212),
  4457. "darkgreen"=>array(0,100,0),
  4458. "darkolivegreen"=>array(85,107,47),
  4459. "darkseagreen"=>array(143,188,143),
  4460. "seagreen"=>array(46,139,87),
  4461. "mediumseagreen"=>array(60,179,113),
  4462. "lightseagreen"=>array(32,178,170),
  4463. "palegreen"=>array(152,251,152),
  4464. "springgreen"=>array(0,255,127),
  4465. "lawngreen"=>array(124,252,0),
  4466. "green"=>array(0,255,0),
  4467. "chartreuse"=>array(127,255,0),
  4468. "mediumspringgreen"=>array(0,250,154),
  4469. "greenyellow"=>array(173,255,47),
  4470. "limegreen"=>array(50,205,50),
  4471. "yellowgreen"=>array(154,205,50),
  4472. "forestgreen"=>array(34,139,34),
  4473. "olivedrab"=>array(107,142,35),
  4474. "darkkhaki"=>array(189,183,107),
  4475. "khaki"=>array(240,230,140),
  4476. "palegoldenrod"=>array(238,232,170),
  4477. "lightgoldenrodyellow"=>array(250,250,210),
  4478. "lightyellow"=>array(255,255,200),
  4479. "yellow"=>array(255,255,0),
  4480. "gold"=>array(255,215,0),
  4481. "lightgoldenrod"=>array(238,221,130),
  4482. "goldenrod"=>array(218,165,32),
  4483. "darkgoldenrod"=>array(184,134,11),
  4484. "rosybrown"=>array(188,143,143),
  4485. "indianred"=>array(205,92,92),
  4486. "saddlebrown"=>array(139,69,19),
  4487. "sienna"=>array(160,82,45),
  4488. "peru"=>array(205,133,63),
  4489. "burlywood"=>array(222,184,135),
  4490. "beige"=>array(245,245,220),
  4491. "wheat"=>array(245,222,179),
  4492. "sandybrown"=>array(244,164,96),
  4493. "tan"=>array(210,180,140),
  4494. "chocolate"=>array(210,105,30),
  4495. "firebrick"=>array(178,34,34),
  4496. "brown"=>array(165,42,42),
  4497. "darksalmon"=>array(233,150,122),
  4498. "salmon"=>array(250,128,114),
  4499. "lightsalmon"=>array(255,160,122),
  4500. "orange"=>array(255,165,0),
  4501. "darkorange"=>array(255,140,0),
  4502. "coral"=>array(255,127,80),
  4503. "lightcoral"=>array(240,128,128),
  4504. "tomato"=>array(255,99,71),
  4505. "orangered"=>array(255,69,0),
  4506. "red"=>array(255,0,0),
  4507. "hotpink"=>array(255,105,180),
  4508. "deeppink"=>array(255,20,147),
  4509. "pink"=>array(255,192,203),
  4510. "lightpink"=>array(255,182,193),
  4511. "palevioletred"=>array(219,112,147),
  4512. "maroon"=>array(176,48,96),
  4513. "mediumvioletred"=>array(199,21,133),
  4514. "violetred"=>array(208,32,144),
  4515. "magenta"=>array(255,0,255),
  4516. "violet"=>array(238,130,238),
  4517. "plum"=>array(221,160,221),
  4518. "orchid"=>array(218,112,214),
  4519. "mediumorchid"=>array(186,85,211),
  4520. "darkorchid"=>array(153,50,204),
  4521. "darkviolet"=>array(148,0,211),
  4522. "blueviolet"=>array(138,43,226),
  4523. "purple"=>array(160,32,240),
  4524. "mediumpurple"=>array(147,112,219),
  4525. "thistle"=>array(216,191,216),
  4526. "snow1"=>array(255,250,250),
  4527. "snow2"=>array(238,233,233),
  4528. "snow3"=>array(205,201,201),
  4529. "snow4"=>array(139,137,137),
  4530. "seashell1"=>array(255,245,238),
  4531. "seashell2"=>array(238,229,222),
  4532. "seashell3"=>array(205,197,191),
  4533. "seashell4"=>array(139,134,130),
  4534. "AntiqueWhite1"=>array(255,239,219),
  4535. "AntiqueWhite2"=>array(238,223,204),
  4536. "AntiqueWhite3"=>array(205,192,176),
  4537. "AntiqueWhite4"=>array(139,131,120),
  4538. "bisque1"=>array(255,228,196),
  4539. "bisque2"=>array(238,213,183),
  4540. "bisque3"=>array(205,183,158),
  4541. "bisque4"=>array(139,125,107),
  4542. "peachPuff1"=>array(255,218,185),
  4543. "peachpuff2"=>array(238,203,173),
  4544. "peachpuff3"=>array(205,175,149),
  4545. "peachpuff4"=>array(139,119,101),
  4546. "navajowhite1"=>array(255,222,173),
  4547. "navajowhite2"=>array(238,207,161),
  4548. "navajowhite3"=>array(205,179,139),
  4549. "navajowhite4"=>array(139,121,94),
  4550. "lemonchiffon1"=>array(255,250,205),
  4551. "lemonchiffon2"=>array(238,233,191),
  4552. "lemonchiffon3"=>array(205,201,165),
  4553. "lemonchiffon4"=>array(139,137,112),
  4554. "ivory1"=>array(255,255,240),
  4555. "ivory2"=>array(238,238,224),
  4556. "ivory3"=>array(205,205,193),
  4557. "ivory4"=>array(139,139,131),
  4558. "honeydew"=>array(193,205,193),
  4559. "lavenderblush1"=>array(255,240,245),
  4560. "lavenderblush2"=>array(238,224,229),
  4561. "lavenderblush3"=>array(205,193,197),
  4562. "lavenderblush4"=>array(139,131,134),
  4563. "mistyrose1"=>array(255,228,225),
  4564. "mistyrose2"=>array(238,213,210),
  4565. "mistyrose3"=>array(205,183,181),
  4566. "mistyrose4"=>array(139,125,123),
  4567. "azure1"=>array(240,255,255),
  4568. "azure2"=>array(224,238,238),
  4569. "azure3"=>array(193,205,205),
  4570. "azure4"=>array(131,139,139),
  4571. "slateblue1"=>array(131,111,255),
  4572. "slateblue2"=>array(122,103,238),
  4573. "slateblue3"=>array(105,89,205),
  4574. "slateblue4"=>array(71,60,139),
  4575. "royalblue1"=>array(72,118,255),
  4576. "royalblue2"=>array(67,110,238),
  4577. "royalblue3"=>array(58,95,205),
  4578. "royalblue4"=>array(39,64,139),
  4579. "dodgerblue1"=>array(30,144,255),
  4580. "dodgerblue2"=>array(28,134,238),
  4581. "dodgerblue3"=>array(24,116,205),
  4582. "dodgerblue4"=>array(16,78,139),
  4583. "steelblue1"=>array(99,184,255),
  4584. "steelblue2"=>array(92,172,238),
  4585. "steelblue3"=>array(79,148,205),
  4586. "steelblue4"=>array(54,100,139),
  4587. "deepskyblue1"=>array(0,191,255),
  4588. "deepskyblue2"=>array(0,178,238),
  4589. "deepskyblue3"=>array(0,154,205),
  4590. "deepskyblue4"=>array(0,104,139),
  4591. "skyblue1"=>array(135,206,255),
  4592. "skyblue2"=>array(126,192,238),
  4593. "skyblue3"=>array(108,166,205),
  4594. "skyblue4"=>array(74,112,139),
  4595. "lightskyblue1"=>array(176,226,255),
  4596. "lightskyblue2"=>array(164,211,238),
  4597. "lightskyblue3"=>array(141,182,205),
  4598. "lightskyblue4"=>array(96,123,139),
  4599. "slategray1"=>array(198,226,255),
  4600. "slategray2"=>array(185,211,238),
  4601. "slategray3"=>array(159,182,205),
  4602. "slategray4"=>array(108,123,139),
  4603. "lightsteelblue1"=>array(202,225,255),
  4604. "lightsteelblue2"=>array(188,210,238),
  4605. "lightsteelblue3"=>array(162,181,205),
  4606. "lightsteelblue4"=>array(110,123,139),
  4607. "lightblue1"=>array(191,239,255),
  4608. "lightblue2"=>array(178,223,238),
  4609. "lightblue3"=>array(154,192,205),
  4610. "lightblue4"=>array(104,131,139),
  4611. "lightcyan1"=>array(224,255,255),
  4612. "lightcyan2"=>array(209,238,238),
  4613. "lightcyan3"=>array(180,205,205),
  4614. "lightcyan4"=>array(122,139,139),
  4615. "paleturquoise1"=>array(187,255,255),
  4616. "paleturquoise2"=>array(174,238,238),
  4617. "paleturquoise3"=>array(150,205,205),
  4618. "paleturquoise4"=>array(102,139,139),
  4619. "cadetblue1"=>array(152,245,255),
  4620. "cadetblue2"=>array(142,229,238),
  4621. "cadetblue3"=>array(122,197,205),
  4622. "cadetblue4"=>array(83,134,139),
  4623. "turquoise1"=>array(0,245,255),
  4624. "turquoise2"=>array(0,229,238),
  4625. "turquoise3"=>array(0,197,205),
  4626. "turquoise4"=>array(0,134,139),
  4627. "cyan1"=>array(0,255,255),
  4628. "cyan2"=>array(0,238,238),
  4629. "cyan3"=>array(0,205,205),
  4630. "cyan4"=>array(0,139,139),
  4631. "darkslategray1"=>array(151,255,255),
  4632. "darkslategray2"=>array(141,238,238),
  4633. "darkslategray3"=>array(121,205,205),
  4634. "darkslategray4"=>array(82,139,139),
  4635. "aquamarine1"=>array(127,255,212),
  4636. "aquamarine2"=>array(118,238,198),
  4637. "aquamarine3"=>array(102,205,170),
  4638. "aquamarine4"=>array(69,139,116),
  4639. "darkseagreen1"=>array(193,255,193),
  4640. "darkseagreen2"=>array(180,238,180),
  4641. "darkseagreen3"=>array(155,205,155),
  4642. "darkseagreen4"=>array(105,139,105),
  4643. "seagreen1"=>array(84,255,159),
  4644. "seagreen2"=>array(78,238,148),
  4645. "seagreen3"=>array(67,205,128),
  4646. "seagreen4"=>array(46,139,87),
  4647. "palegreen1"=>array(154,255,154),
  4648. "palegreen2"=>array(144,238,144),
  4649. "palegreen3"=>array(124,205,124),
  4650. "palegreen4"=>array(84,139,84),
  4651. "springgreen1"=>array(0,255,127),
  4652. "springgreen2"=>array(0,238,118),
  4653. "springgreen3"=>array(0,205,102),
  4654. "springgreen4"=>array(0,139,69),
  4655. "chartreuse1"=>array(127,255,0),
  4656. "chartreuse2"=>array(118,238,0),
  4657. "chartreuse3"=>array(102,205,0),
  4658. "chartreuse4"=>array(69,139,0),
  4659. "olivedrab1"=>array(192,255,62),
  4660. "olivedrab2"=>array(179,238,58),
  4661. "olivedrab3"=>array(154,205,50),
  4662. "olivedrab4"=>array(105,139,34),
  4663. "darkolivegreen1"=>array(202,255,112),
  4664. "darkolivegreen2"=>array(188,238,104),
  4665. "darkolivegreen3"=>array(162,205,90),
  4666. "darkolivegreen4"=>array(110,139,61),
  4667. "khaki1"=>array(255,246,143),
  4668. "khaki2"=>array(238,230,133),
  4669. "khaki3"=>array(205,198,115),
  4670. "khaki4"=>array(139,134,78),
  4671. "lightgoldenrod1"=>array(255,236,139),
  4672. "lightgoldenrod2"=>array(238,220,130),
  4673. "lightgoldenrod3"=>array(205,190,112),
  4674. "lightgoldenrod4"=>array(139,129,76),
  4675. "yellow1"=>array(255,255,0),
  4676. "yellow2"=>array(238,238,0),
  4677. "yellow3"=>array(205,205,0),
  4678. "yellow4"=>array(139,139,0),
  4679. "gold1"=>array(255,215,0),
  4680. "gold2"=>array(238,201,0),
  4681. "gold3"=>array(205,173,0),
  4682. "gold4"=>array(139,117,0),
  4683. "goldenrod1"=>array(255,193,37),
  4684. "goldenrod2"=>array(238,180,34),
  4685. "goldenrod3"=>array(205,155,29),
  4686. "goldenrod4"=>array(139,105,20),
  4687. "darkgoldenrod1"=>array(255,185,15),
  4688. "darkgoldenrod2"=>array(238,173,14),
  4689. "darkgoldenrod3"=>array(205,149,12),
  4690. "darkgoldenrod4"=>array(139,101,8),
  4691. "rosybrown1"=>array(255,193,193),
  4692. "rosybrown2"=>array(238,180,180),
  4693. "rosybrown3"=>array(205,155,155),
  4694. "rosybrown4"=>array(139,105,105),
  4695. "indianred1"=>array(255,106,106),
  4696. "indianred2"=>array(238,99,99),
  4697. "indianred3"=>array(205,85,85),
  4698. "indianred4"=>array(139,58,58),
  4699. "sienna1"=>array(255,130,71),
  4700. "sienna2"=>array(238,121,66),
  4701. "sienna3"=>array(205,104,57),
  4702. "sienna4"=>array(139,71,38),
  4703. "burlywood1"=>array(255,211,155),
  4704. "burlywood2"=>array(238,197,145),
  4705. "burlywood3"=>array(205,170,125),
  4706. "burlywood4"=>array(139,115,85),
  4707. "wheat1"=>array(255,231,186),
  4708. "wheat2"=>array(238,216,174),
  4709. "wheat3"=>array(205,186,150),
  4710. "wheat4"=>array(139,126,102),
  4711. "tan1"=>array(255,165,79),
  4712. "tan2"=>array(238,154,73),
  4713. "tan3"=>array(205,133,63),
  4714. "tan4"=>array(139,90,43),
  4715. "chocolate1"=>array(255,127,36),
  4716. "chocolate2"=>array(238,118,33),
  4717. "chocolate3"=>array(205,102,29),
  4718. "chocolate4"=>array(139,69,19),
  4719. "firebrick1"=>array(255,48,48),
  4720. "firebrick2"=>array(238,44,44),
  4721. "firebrick3"=>array(205,38,38),
  4722. "firebrick4"=>array(139,26,26),
  4723. "brown1"=>array(255,64,64),
  4724. "brown2"=>array(238,59,59),
  4725. "brown3"=>array(205,51,51),
  4726. "brown4"=>array(139,35,35),
  4727. "salmon1"=>array(255,140,105),
  4728. "salmon2"=>array(238,130,98),
  4729. "salmon3"=>array(205,112,84),
  4730. "salmon4"=>array(139,76,57),
  4731. "lightsalmon1"=>array(255,160,122),
  4732. "lightsalmon2"=>array(238,149,114),
  4733. "lightsalmon3"=>array(205,129,98),
  4734. "lightsalmon4"=>array(139,87,66),
  4735. "orange1"=>array(255,165,0),
  4736. "orange2"=>array(238,154,0),
  4737. "orange3"=>array(205,133,0),
  4738. "orange4"=>array(139,90,0),
  4739. "darkorange1"=>array(255,127,0),
  4740. "darkorange2"=>array(238,118,0),
  4741. "darkorange3"=>array(205,102,0),
  4742. "darkorange4"=>array(139,69,0),
  4743. "coral1"=>array(255,114,86),
  4744. "coral2"=>array(238,106,80),
  4745. "coral3"=>array(205,91,69),
  4746. "coral4"=>array(139,62,47),
  4747. "tomato1"=>array(255,99,71),
  4748. "tomato2"=>array(238,92,66),
  4749. "tomato3"=>array(205,79,57),
  4750. "tomato4"=>array(139,54,38),
  4751. "orangered1"=>array(255,69,0),
  4752. "orangered2"=>array(238,64,0),
  4753. "orangered3"=>array(205,55,0),
  4754. "orangered4"=>array(139,37,0),
  4755. "deeppink1"=>array(255,20,147),
  4756. "deeppink2"=>array(238,18,137),
  4757. "deeppink3"=>array(205,16,118),
  4758. "deeppink4"=>array(139,10,80),
  4759. "hotpink1"=>array(255,110,180),
  4760. "hotpink2"=>array(238,106,167),
  4761. "hotpink3"=>array(205,96,144),
  4762. "hotpink4"=>array(139,58,98),
  4763. "pink1"=>array(255,181,197),
  4764. "pink2"=>array(238,169,184),
  4765. "pink3"=>array(205,145,158),
  4766. "pink4"=>array(139,99,108),
  4767. "lightpink1"=>array(255,174,185),
  4768. "lightpink2"=>array(238,162,173),
  4769. "lightpink3"=>array(205,140,149),
  4770. "lightpink4"=>array(139,95,101),
  4771. "palevioletred1"=>array(255,130,171),
  4772. "palevioletred2"=>array(238,121,159),
  4773. "palevioletred3"=>array(205,104,137),
  4774. "palevioletred4"=>array(139,71,93),
  4775. "maroon1"=>array(255,52,179),
  4776. "maroon2"=>array(238,48,167),
  4777. "maroon3"=>array(205,41,144),
  4778. "maroon4"=>array(139,28,98),
  4779. "violetred1"=>array(255,62,150),
  4780. "violetred2"=>array(238,58,140),
  4781. "violetred3"=>array(205,50,120),
  4782. "violetred4"=>array(139,34,82),
  4783. "magenta1"=>array(255,0,255),
  4784. "magenta2"=>array(238,0,238),
  4785. "magenta3"=>array(205,0,205),
  4786. "magenta4"=>array(139,0,139),
  4787. "mediumred"=>array(140,34,34),
  4788. "orchid1"=>array(255,131,250),
  4789. "orchid2"=>array(238,122,233),
  4790. "orchid3"=>array(205,105,201),
  4791. "orchid4"=>array(139,71,137),
  4792. "plum1"=>array(255,187,255),
  4793. "plum2"=>array(238,174,238),
  4794. "plum3"=>array(205,150,205),
  4795. "plum4"=>array(139,102,139),
  4796. "mediumorchid1"=>array(224,102,255),
  4797. "mediumorchid2"=>array(209,95,238),
  4798. "mediumorchid3"=>array(180,82,205),
  4799. "mediumorchid4"=>array(122,55,139),
  4800. "darkorchid1"=>array(191,62,255),
  4801. "darkorchid2"=>array(178,58,238),
  4802. "darkorchid3"=>array(154,50,205),
  4803. "darkorchid4"=>array(104,34,139),
  4804. "purple1"=>array(155,48,255),
  4805. "purple2"=>array(145,44,238),
  4806. "purple3"=>array(125,38,205),
  4807. "purple4"=>array(85,26,139),
  4808. "mediumpurple1"=>array(171,130,255),
  4809. "mediumpurple2"=>array(159,121,238),
  4810. "mediumpurple3"=>array(137,104,205),
  4811. "mediumpurple4"=>array(93,71,139),
  4812. "thistle1"=>array(255,225,255),
  4813. "thistle2"=>array(238,210,238),
  4814. "thistle3"=>array(205,181,205),
  4815. "thistle4"=>array(139,123,139),
  4816. "gray1"=>array(10,10,10),
  4817. "gray2"=>array(40,40,30),
  4818. "gray3"=>array(70,70,70),
  4819. "gray4"=>array(100,100,100),
  4820. "gray5"=>array(130,130,130),
  4821. "gray6"=>array(160,160,160),
  4822. "gray7"=>array(190,190,190),
  4823. "gray8"=>array(210,210,210),
  4824. "gray9"=>array(240,240,240),
  4825. "darkgray"=>array(100,100,100),
  4826. "darkblue"=>array(0,0,139),
  4827. "darkcyan"=>array(0,139,139),
  4828. "darkmagenta"=>array(139,0,139),
  4829. "darkred"=>array(139,0,0),
  4830. "silver"=>array(192, 192, 192),
  4831. "eggplant"=>array(144,176,168),
  4832. "lightgreen"=>array(144,238,144));
  4833. }
  4834. //----------------
  4835. // PUBLIC METHODS
  4836. // Colors can be specified as either
  4837. // 1. #xxxxxx HTML style
  4838. // 2. "colorname" as a named color
  4839. // 3. array(r,g,b) RGB triple
  4840. // This function translates this to a native RGB format and returns an
  4841. // RGB triple.
  4842. function Color($aColor) {
  4843. if (is_string($aColor)) {
  4844. // Strip of any alpha factor
  4845. $pos = strpos($aColor,'@');
  4846. if( $pos === false ) {
  4847. $alpha = 0;
  4848. }
  4849. else {
  4850. $pos2 = strpos($aColor,':');
  4851. if( $pos2===false )
  4852. $pos2 = $pos-1; // Sentinel
  4853. if( $pos > $pos2 ) {
  4854. $alpha = substr($aColor,$pos+1);
  4855. $aColor = substr($aColor,0,$pos);
  4856. }
  4857. else {
  4858. $alpha = substr($aColor,$pos+1,$pos2-$pos-1);
  4859. $aColor = substr($aColor,0,$pos).substr($aColor,$pos2);
  4860. }
  4861. }
  4862. // Extract potential adjustment figure at end of color
  4863. // specification
  4864. $pos = strpos($aColor,":");
  4865. if( $pos === false ) {
  4866. $adj = 1.0;
  4867. }
  4868. else {
  4869. $adj = 0.0 + substr($aColor,$pos+1);
  4870. $aColor = substr($aColor,0,$pos);
  4871. }
  4872. if( $adj < 0 )
  4873. JpGraphError::Raise('Adjustment factor for color must be > 0');
  4874. if (substr($aColor, 0, 1) == "#") {
  4875. $r = hexdec(substr($aColor, 1, 2));
  4876. $g = hexdec(substr($aColor, 3, 2));
  4877. $b = hexdec(substr($aColor, 5, 2));
  4878. } else {
  4879. if(!isset($this->rgb_table[$aColor]) )
  4880. JpGraphError::Raise(" Unknown color: $aColor");
  4881. $tmp=$this->rgb_table[$aColor];
  4882. $r = $tmp[0];
  4883. $g = $tmp[1];
  4884. $b = $tmp[2];
  4885. }
  4886. // Scale adj so that an adj=2 always
  4887. // makes the color 100% white (i.e. 255,255,255.
  4888. // and adj=1 neutral and adj=0 black.
  4889. if( $adj > 1 ) {
  4890. $m = ($adj-1.0)*(255-min(255,min($r,min($g,$b))));
  4891. return array(min(255,$r+$m), min(255,$g+$m), min(255,$b+$m),$alpha);
  4892. }
  4893. elseif( $adj < 1 ) {
  4894. $m = ($adj-1.0)*max(255,max($r,max($g,$b)));
  4895. return array(max(0,$r+$m), max(0,$g+$m), max(0,$b+$m),$alpha);
  4896. }
  4897. else {
  4898. return array($r,$g,$b,$alpha);
  4899. }
  4900. } elseif( is_array($aColor) ) {
  4901. if( count($aColor)==3 ) {
  4902. $aColor[3]=0;
  4903. return $aColor;
  4904. }
  4905. else
  4906. return $aColor;
  4907. }
  4908. else
  4909. JpGraphError::Raise(" Unknown color specification: $aColor , size=".count($aColor));
  4910. }
  4911. // Compare two colors
  4912. // return true if equal
  4913. function Equal($aCol1,$aCol2) {
  4914. $c1 = $this->Color($aCol1);
  4915. $c2 = $this->Color($aCol2);
  4916. if( $c1[0]==$c2[0] && $c1[1]==$c2[1] && $c1[2]==$c2[2] )
  4917. return true;
  4918. else
  4919. return false;
  4920. }
  4921. // Allocate a new color in the current image
  4922. // Return new color index, -1 if no more colors could be allocated
  4923. function Allocate($aColor,$aAlpha=0.0) {
  4924. list ($r, $g, $b, $a) = $this->color($aColor);
  4925. // If alpha is specified in the color string then this
  4926. // takes precedence over the second argument
  4927. if( $a > 0 )
  4928. $aAlpha = $a;
  4929. if( $GLOBALS['gd2'] ) {
  4930. if( $aAlpha < 0 || $aAlpha > 1 ) {
  4931. JpGraphError::Raise('Alpha parameter for color must be between 0.0 and 1.0');
  4932. exit(1);
  4933. }
  4934. return imagecolorresolvealpha($this->img, $r, $g, $b, round($aAlpha * 127));
  4935. } else {
  4936. $index = imagecolorexact($this->img, $r, $g, $b);
  4937. if ($index == -1) {
  4938. $index = imagecolorallocate($this->img, $r, $g, $b);
  4939. if( USE_APPROX_COLORS && $index == -1 )
  4940. $index = imagecolorresolve($this->img, $r, $g, $b);
  4941. }
  4942. return $index;
  4943. }
  4944. }
  4945. } // Class
  4946. //===================================================
  4947. // CLASS Image
  4948. // Description: Wrapper class with some goodies to form the
  4949. // Interface to low level image drawing routines.
  4950. //===================================================
  4951. class Image {
  4952. var $img_format;
  4953. var $expired=true;
  4954. var $img=null;
  4955. var $left_margin=30,$right_margin=30,$top_margin=20,$bottom_margin=30;
  4956. var $plotwidth=0,$plotheight=0;
  4957. var $rgb=null;
  4958. var $current_color,$current_color_name;
  4959. var $lastx=0, $lasty=0;
  4960. var $width=0, $height=0;
  4961. var $line_weight=1;
  4962. var $line_style=1; // Default line style is solid
  4963. var $obs_list=array();
  4964. var $font_size=12,$font_family=FF_FONT1, $font_style=FS_NORMAL;
  4965. var $font_file='';
  4966. var $text_halign="left",$text_valign="bottom";
  4967. var $ttf=null;
  4968. var $use_anti_aliasing=false;
  4969. var $quality=null;
  4970. var $colorstack=array(),$colorstackidx=0;
  4971. var $canvascolor = 'white' ;
  4972. var $langconv = null ;
  4973. //---------------
  4974. // CONSTRUCTOR
  4975. function Image($aWidth,$aHeight,$aFormat=DEFAULT_GFORMAT) {
  4976. $this->CreateImgCanvas($aWidth,$aHeight);
  4977. $this->SetAutoMargin();
  4978. if( !$this->SetImgFormat($aFormat) ) {
  4979. JpGraphError::Raise("JpGraph: Selected graphic format is either not supported or unknown [$aFormat]");
  4980. }
  4981. $this->ttf = new TTF();
  4982. $this->langconv = new LanguageConv();
  4983. }
  4984. // Should we use anti-aliasing. Note: This really slows down graphics!
  4985. function SetAntiAliasing() {
  4986. $this->use_anti_aliasing=true;
  4987. }
  4988. function CreateRawCanvas($aWidth=0,$aHeight=0) {
  4989. if( $aWidth <= 1 || $aHeight <= 1 ) {
  4990. JpGraphError::Raise("Illegal sizes specified for width or height when creating an image, (width=$aWidth, height=$aHeight)");
  4991. }
  4992. if( @$GLOBALS['gd2']==true && USE_TRUECOLOR ) {
  4993. $this->img = @imagecreatetruecolor($aWidth, $aHeight);
  4994. if( $this->img < 1 ) {
  4995. die("<b>JpGraph Error:</b> Can't create truecolor image. Check that you really have GD2 library installed.");
  4996. }
  4997. $this->SetAlphaBlending();
  4998. } else {
  4999. $this->img = @imagecreate($aWidth, $aHeight);
  5000. if( $this->img < 1 ) {
  5001. die("<b>JpGraph Error:</b> Can't create image. Check that you really have the GD library installed.");
  5002. }
  5003. }
  5004. if( $this->rgb != null )
  5005. $this->rgb->img = $this->img ;
  5006. else
  5007. $this->rgb = new RGB($this->img);
  5008. }
  5009. function CloneCanvasH() {
  5010. $oldimage = $this->img;
  5011. $this->CreateRawCanvas($this->width,$this->height);
  5012. imagecopy($this->img,$oldimage,0,0,0,0,$this->width,$this->height);
  5013. return $oldimage;
  5014. }
  5015. function CreateImgCanvas($aWidth=0,$aHeight=0) {
  5016. $old = array($this->img,$this->width,$this->height);
  5017. $aWidth = round($aWidth);
  5018. $aHeight = round($aHeight);
  5019. $this->width=$aWidth;
  5020. $this->height=$aHeight;
  5021. if( $aWidth==0 || $aHeight==0 ) {
  5022. // We will set the final size later.
  5023. // Note: The size must be specified before any other
  5024. // img routines that stroke anything are called.
  5025. $this->img = null;
  5026. $this->rgb = null;
  5027. return $old;
  5028. }
  5029. $this->CreateRawCanvas($aWidth,$aHeight);
  5030. // Set canvas color (will also be the background color for a
  5031. // a pallett image
  5032. $this->SetColor($this->canvascolor);
  5033. $this->FilledRectangle(0,0,$aWidth,$aHeight);
  5034. return $old ;
  5035. }
  5036. function CopyCanvasH($aToHdl,$aFromHdl,$aToX,$aToY,$aFromX,$aFromY,$aWidth,$aHeight,$aw=-1,$ah=-1) {
  5037. if( $aw === -1 ) {
  5038. $aw = $aWidth;
  5039. $ah = $aHeight;
  5040. $f = 'imagecopyresized';
  5041. }
  5042. else {
  5043. $f = $GLOBALS['copyfunc'] ;
  5044. }
  5045. $f($aToHdl,$aFromHdl,
  5046. $aToX,$aToY,$aFromX,$aFromY, $aWidth,$aHeight,$aw,$ah);
  5047. }
  5048. function Copy($fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth=-1,$fromHeight=-1) {
  5049. $this->CopyCanvasH($this->img,$fromImg,$toX,$toY,$fromX,$fromY,
  5050. $toWidth,$toHeight,$fromWidth,$fromHeight);
  5051. }
  5052. function CopyMerge($fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth=-1,$fromHeight=-1,$aMix=100) {
  5053. if( $aMix == 100 ) {
  5054. $this->CopyCanvasH($this->img,$fromImg,
  5055. $toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth,$fromHeight);
  5056. }
  5057. else {
  5058. if( ($fromWidth != -1 && ($fromWidth != $toWidth)) ||
  5059. ($fromHeight != -1 && ($fromHeight != $fromHeight)) ) {
  5060. // Create a new canvas that will hold the re-scaled original from image
  5061. if( $toWidth <= 1 || $toHeight <= 1 ) {
  5062. JpGraphError::Raise('Illegal image size when copying image. Size for copied to image is 1 pixel or less.');
  5063. }
  5064. if( @$GLOBALS['gd2']==true && USE_TRUECOLOR ) {
  5065. $tmpimg = @imagecreatetruecolor($toWidth, $toHeight);
  5066. } else {
  5067. $tmpimg = @imagecreate($toWidth, $toHeight);
  5068. }
  5069. if( $tmpimg < 1 ) {
  5070. JpGraphError::Raise('Failed to create temporary GD canvas. Out of memory ?');
  5071. }
  5072. $this->CopyCanvasH($tmpimg,$fromImg,0,0,0,0,
  5073. $toWidth,$toHeight,$fromWidth,$fromHeight);
  5074. $fromImg = $tmpimg;
  5075. }
  5076. imagecopymerge($this->img,$fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$aMix);
  5077. }
  5078. }
  5079. function GetWidth($aImg=null) {
  5080. if( $aImg === null )
  5081. $aImg = $this->img;
  5082. return imagesx($aImg);
  5083. }
  5084. function GetHeight($aImg=null) {
  5085. if( $aImg === null )
  5086. $aImg = $this->img;
  5087. return imagesy($aImg);
  5088. }
  5089. function CreateFromString($aStr) {
  5090. return imagecreatefromstring($aStr);
  5091. }
  5092. function SetCanvasH($aHdl) {
  5093. $this->img = $aHdl;
  5094. $this->rgb->img = $aHdl;
  5095. }
  5096. function SetCanvasColor($aColor) {
  5097. $this->canvascolor = $aColor ;
  5098. }
  5099. function SetAlphaBlending($aFlg=true) {
  5100. if( $GLOBALS['gd2'] )
  5101. ImageAlphaBlending($this->img,$aFlg);
  5102. else
  5103. JpGraphError::Raise('You only seem to have GD 1.x installed. To enable Alphablending requires GD 2.x or higher. Please install GD or make sure the constant USE_GD2 is specified correctly to reflect your installation. By default it tries to autodetect what version of GD you have installed. On some very rare occasions it may falsely detect GD2 where only GD1 is installed. You must then set USE_GD2 to false.');
  5104. }
  5105. function SetAutoMargin() {
  5106. GLOBAL $gJpgBrandTiming;
  5107. $min_bm=0;
  5108. /*
  5109. if( $gJpgBrandTiming )
  5110. $min_bm=15;
  5111. */
  5112. $lm = max(0,$this->width/7);
  5113. $rm = max(0,$this->width/10);
  5114. $tm = max(0,$this->height/7);
  5115. $bm = max($min_bm,$this->height/7);
  5116. $this->SetMargin($lm,$rm,$tm,$bm);
  5117. }
  5118. //---------------
  5119. // PUBLIC METHODS
  5120. function SetFont($family,$style=FS_NORMAL,$size=10) {
  5121. $this->font_family=$family;
  5122. $this->font_style=$style;
  5123. $this->font_size=$size;
  5124. $this->font_file='';
  5125. if( ($this->font_family==FF_FONT1 || $this->font_family==FF_FONT2) && $this->font_style==FS_BOLD ){
  5126. ++$this->font_family;
  5127. }
  5128. if( $this->font_family > FF_FONT2+1 ) { // A TTF font so get the font file
  5129. // Check that this PHP has support for TTF fonts
  5130. if( !function_exists('imagettfbbox') ) {
  5131. JpGraphError::Raise('This PHP build has not been configured with TTF support. You need to recompile your PHP installation with FreeType support.');
  5132. exit();
  5133. }
  5134. $this->font_file = $this->ttf->File($this->font_family,$this->font_style);
  5135. }
  5136. }
  5137. // Get the specific height for a text string
  5138. function GetTextHeight($txt="",$angle=0) {
  5139. $tmp = split("\n",$txt);
  5140. $n = count($tmp);
  5141. $m=0;
  5142. for($i=0; $i< $n; ++$i)
  5143. $m = max($m,strlen($tmp[$i]));
  5144. if( $this->font_family <= FF_FONT2+1 ) {
  5145. if( $angle==0 ) {
  5146. $h = imagefontheight($this->font_family);
  5147. if( $h === false ) {
  5148. JpGraphError::Raise('You have a misconfigured GD font support. The call to imagefontwidth() fails.');
  5149. }
  5150. return $n*$h;
  5151. }
  5152. else {
  5153. $w = @imagefontwidth($this->font_family);
  5154. if( $w === false ) {
  5155. JpGraphError::Raise('You have a misconfigured GD font support. The call to imagefontwidth() fails.');
  5156. }
  5157. return $m*$w;
  5158. }
  5159. }
  5160. else {
  5161. $bbox = $this->GetTTFBBox($txt,$angle);
  5162. return $bbox[1]-$bbox[5];
  5163. }
  5164. }
  5165. // Estimate font height
  5166. function GetFontHeight($angle=0) {
  5167. $txt = "XOMg";
  5168. return $this->GetTextHeight($txt,$angle);
  5169. }
  5170. // Approximate font width with width of letter "O"
  5171. function GetFontWidth($angle=0) {
  5172. $txt = 'O';
  5173. return $this->GetTextWidth($txt,$angle);
  5174. }
  5175. // Get actual width of text in absolute pixels
  5176. function GetTextWidth($txt,$angle=0) {
  5177. $tmp = split("\n",$txt);
  5178. $n = count($tmp);
  5179. if( $this->font_family <= FF_FONT2+1 ) {
  5180. $m=0;
  5181. for($i=0; $i < $n; ++$i) {
  5182. $l=strlen($tmp[$i]);
  5183. if( $l > $m ) {
  5184. $m = $l;
  5185. }
  5186. }
  5187. if( $angle==0 ) {
  5188. $w = @imagefontwidth($this->font_family);
  5189. if( $w === false ) {
  5190. JpGraphError::Raise('You have a misconfigured GD font support. The call to imagefontwidth() fails.');
  5191. }
  5192. return $m*$w;
  5193. }
  5194. else {
  5195. // 90 degrees internal so height becomes width
  5196. $h = @imagefontheight($this->font_family);
  5197. if( $h === false ) {
  5198. JpGraphError::Raise('You have a misconfigured GD font support. The call to imagefontheight() fails.');
  5199. }
  5200. return $n*$h;
  5201. }
  5202. }
  5203. else {
  5204. // For TTF fonts we must walk through a lines and find the
  5205. // widest one which we use as the width of the multi-line
  5206. // paragraph
  5207. $m=0;
  5208. for( $i=0; $i < $n; ++$i ) {
  5209. $bbox = $this->GetTTFBBox($tmp[$i],$angle);
  5210. $mm = $bbox[2] - $bbox[0];
  5211. if( $mm > $m )
  5212. $m = $mm;
  5213. }
  5214. return $m;
  5215. }
  5216. }
  5217. // Draw text with a box around it
  5218. function StrokeBoxedText($x,$y,$txt,$dir=0,$fcolor="white",$bcolor="black",
  5219. $shadowcolor=false,$paragraph_align="left",
  5220. $xmarg=6,$ymarg=4,$cornerradius=0,$dropwidth=3) {
  5221. if( !is_numeric($dir) ) {
  5222. if( $dir=="h" ) $dir=0;
  5223. elseif( $dir=="v" ) $dir=90;
  5224. else JpGraphError::Raise(" Unknown direction specified in call to StrokeBoxedText() [$dir]");
  5225. }
  5226. if( $this->font_family >= FF_FONT0 && $this->font_family <= FF_FONT2+1) {
  5227. $width=$this->GetTextWidth($txt,$dir) ;
  5228. $height=$this->GetTextHeight($txt,$dir) ;
  5229. }
  5230. else {
  5231. $width=$this->GetBBoxWidth($txt,$dir) ;
  5232. $height=$this->GetBBoxHeight($txt,$dir) ;
  5233. }
  5234. $height += 2*$ymarg;
  5235. $width += 2*$xmarg;
  5236. if( $this->text_halign=="right" ) $x -= $width;
  5237. elseif( $this->text_halign=="center" ) $x -= $width/2;
  5238. if( $this->text_valign=="bottom" ) $y -= $height;
  5239. elseif( $this->text_valign=="center" ) $y -= $height/2;
  5240. if( $shadowcolor ) {
  5241. $this->PushColor($shadowcolor);
  5242. $this->FilledRoundedRectangle($x-$xmarg+$dropwidth,$y-$ymarg+$dropwidth,
  5243. $x+$width+$dropwidth,$y+$height-$ymarg+$dropwidth,
  5244. $cornerradius);
  5245. $this->PopColor();
  5246. $this->PushColor($fcolor);
  5247. $this->FilledRoundedRectangle($x-$xmarg,$y-$ymarg,
  5248. $x+$width,$y+$height-$ymarg,
  5249. $cornerradius);
  5250. $this->PopColor();
  5251. $this->PushColor($bcolor);
  5252. $this->RoundedRectangle($x-$xmarg,$y-$ymarg,
  5253. $x+$width,$y+$height-$ymarg,$cornerradius);
  5254. $this->PopColor();
  5255. }
  5256. else {
  5257. if( $fcolor ) {
  5258. $oc=$this->current_color;
  5259. $this->SetColor($fcolor);
  5260. $this->FilledRoundedRectangle($x-$xmarg,$y-$ymarg,$x+$width,$y+$height-$ymarg,$cornerradius);
  5261. $this->current_color=$oc;
  5262. }
  5263. if( $bcolor ) {
  5264. $oc=$this->current_color;
  5265. $this->SetColor($bcolor);
  5266. $this->RoundedRectangle($x-$xmarg,$y-$ymarg,$x+$width,$y+$height-$ymarg,$cornerradius);
  5267. $this->current_color=$oc;
  5268. }
  5269. }
  5270. $h=$this->text_halign;
  5271. $v=$this->text_valign;
  5272. $this->SetTextAlign("left","top");
  5273. $this->StrokeText($x, $y, $txt, $dir, $paragraph_align);
  5274. $bb = array($x-$xmarg,$y+$height-$ymarg,$x+$width,$y+$height-$ymarg,
  5275. $x+$width,$y-$ymarg,$x-$xmarg,$y-$ymarg);
  5276. $this->SetTextAlign($h,$v);
  5277. return $bb;
  5278. }
  5279. // Set text alignment
  5280. function SetTextAlign($halign,$valign="bottom") {
  5281. $this->text_halign=$halign;
  5282. $this->text_valign=$valign;
  5283. }
  5284. function _StrokeBuiltinFont($x,$y,$txt,$dir=0,$paragraph_align="left",&$aBoundingBox,$aDebug=false) {
  5285. if( is_numeric($dir) && $dir!=90 && $dir!=0)
  5286. JpGraphError::Raise(" Internal font does not support drawing text at arbitrary angle. Use TTF fonts instead.");
  5287. $h=$this->GetTextHeight($txt);
  5288. $fh=$this->GetFontHeight();
  5289. $w=$this->GetTextWidth($txt);
  5290. if( $this->text_halign=="right")
  5291. $x -= $dir==0 ? $w : $h;
  5292. elseif( $this->text_halign=="center" ) {
  5293. // For center we subtract 1 pixel since this makes the middle
  5294. // be prefectly in the middle
  5295. $x -= $dir==0 ? $w/2-1 : $h/2;
  5296. }
  5297. if( $this->text_valign=="top" )
  5298. $y += $dir==0 ? $h : $w;
  5299. elseif( $this->text_valign=="center" )
  5300. $y += $dir==0 ? $h/2 : $w/2;
  5301. if( $dir==90 ) {
  5302. imagestringup($this->img,$this->font_family,$x,$y,$txt,$this->current_color);
  5303. $aBoundingBox = array(round($x),round($y),round($x),round($y-$w),round($x+$h),round($y-$w),round($x+$h),round($y));
  5304. if( $aDebug ) {
  5305. // Draw bounding box
  5306. $this->PushColor('green');
  5307. $this->Polygon($aBoundingBox,true);
  5308. $this->PopColor();
  5309. }
  5310. }
  5311. else {
  5312. if( ereg("\n",$txt) ) {
  5313. $tmp = split("\n",$txt);
  5314. for($i=0; $i < count($tmp); ++$i) {
  5315. $w1 = $this->GetTextWidth($tmp[$i]);
  5316. if( $paragraph_align=="left" ) {
  5317. imagestring($this->img,$this->font_family,$x,$y-$h+1+$i*$fh,$tmp[$i],$this->current_color);
  5318. }
  5319. elseif( $paragraph_align=="right" ) {
  5320. imagestring($this->img,$this->font_family,$x+($w-$w1),
  5321. $y-$h+1+$i*$fh,$tmp[$i],$this->current_color);
  5322. }
  5323. else {
  5324. imagestring($this->img,$this->font_family,$x+$w/2-$w1/2,
  5325. $y-$h+1+$i*$fh,$tmp[$i],$this->current_color);
  5326. }
  5327. }
  5328. }
  5329. else {
  5330. //Put the text
  5331. imagestring($this->img,$this->font_family,$x,$y-$h+1,$txt,$this->current_color);
  5332. }
  5333. if( $aDebug ) {
  5334. // Draw the bounding rectangle and the bounding box
  5335. $p1 = array(round($x),round($y),round($x),round($y-$h),round($x+$w),round($y-$h),round($x+$w),round($y));
  5336. // Draw bounding box
  5337. $this->PushColor('green');
  5338. $this->Polygon($p1,true);
  5339. $this->PopColor();
  5340. }
  5341. $aBoundingBox=array(round($x),round($y),round($x),round($y-$h),round($x+$w),round($y-$h),round($x+$w),round($y));
  5342. }
  5343. }
  5344. function AddTxtCR($aTxt) {
  5345. // If the user has just specified a '\n'
  5346. // instead of '\n\t' we have to add '\r' since
  5347. // the width will be too muchy otherwise since when
  5348. // we print we stroke the individually lines by hand.
  5349. $e = explode("\n",$aTxt);
  5350. $n = count($e);
  5351. for($i=0; $i<$n; ++$i) {
  5352. $e[$i]=str_replace("\r","",$e[$i]);
  5353. }
  5354. return implode("\n\r",$e);
  5355. }
  5356. function GetTTFBBox($aTxt,$aAngle=0) {
  5357. $bbox = @ImageTTFBBox($this->font_size,$aAngle,$this->font_file,$aTxt);
  5358. if( $bbox === false ) {
  5359. JpGraphError::Raise("There is either a configuration problem with TrueType or a problem reading font file (".$this->font_file."). Make sure file exists and is in a readable place for the HTTP process. (If 'basedir' restriction is enabled in PHP then the font file must be located in the document root.). It might also be a wrongly installed FreeType library. Try uppgrading to at least FreeType 2.1.13 and recompile GD with the correct setup so it can find the new FT library.");
  5360. }
  5361. return $bbox;
  5362. }
  5363. function GetBBoxTTF($aTxt,$aAngle=0) {
  5364. // Normalize the bounding box to become a minimum
  5365. // enscribing rectangle
  5366. $aTxt = $this->AddTxtCR($aTxt);
  5367. if( !is_readable($this->font_file) ) {
  5368. JpGraphError::Raise('Can not read font file ('.$this->font_file.') in call to Image::GetBBoxTTF. Please make sure that you have set a font before calling this method and that the font is installed in the TTF directory.');
  5369. }
  5370. $bbox = $this->GetTTFBBox($aTxt,$aAngle);
  5371. if( $aAngle==0 )
  5372. return $bbox;
  5373. if( $aAngle >= 0 ) {
  5374. if( $aAngle <= 90 ) { //<=0
  5375. $bbox = array($bbox[6],$bbox[1],$bbox[2],$bbox[1],
  5376. $bbox[2],$bbox[5],$bbox[6],$bbox[5]);
  5377. }
  5378. elseif( $aAngle <= 180 ) { //<= 2
  5379. $bbox = array($bbox[4],$bbox[7],$bbox[0],$bbox[7],
  5380. $bbox[0],$bbox[3],$bbox[4],$bbox[3]);
  5381. }
  5382. elseif( $aAngle <= 270 ) { //<= 3
  5383. $bbox = array($bbox[2],$bbox[5],$bbox[6],$bbox[5],
  5384. $bbox[6],$bbox[1],$bbox[2],$bbox[1]);
  5385. }
  5386. else {
  5387. $bbox = array($bbox[0],$bbox[3],$bbox[4],$bbox[3],
  5388. $bbox[4],$bbox[7],$bbox[0],$bbox[7]);
  5389. }
  5390. }
  5391. elseif( $aAngle < 0 ) {
  5392. if( $aAngle <= -270 ) { // <= -3
  5393. $bbox = array($bbox[6],$bbox[1],$bbox[2],$bbox[1],
  5394. $bbox[2],$bbox[5],$bbox[6],$bbox[5]);
  5395. }
  5396. elseif( $aAngle <= -180 ) { // <= -2
  5397. $bbox = array($bbox[0],$bbox[3],$bbox[4],$bbox[3],
  5398. $bbox[4],$bbox[7],$bbox[0],$bbox[7]);
  5399. }
  5400. elseif( $aAngle <= -90 ) { // <= -1
  5401. $bbox = array($bbox[2],$bbox[5],$bbox[6],$bbox[5],
  5402. $bbox[6],$bbox[1],$bbox[2],$bbox[1]);
  5403. }
  5404. else {
  5405. $bbox = array($bbox[0],$bbox[3],$bbox[4],$bbox[3],
  5406. $bbox[4],$bbox[7],$bbox[0],$bbox[7]);
  5407. }
  5408. }
  5409. return $bbox;
  5410. }
  5411. function GetBBoxHeight($aTxt,$aAngle=0) {
  5412. $box = $this->GetBBoxTTF($aTxt,$aAngle);
  5413. return $box[1]-$box[7]+1;
  5414. }
  5415. function GetBBoxWidth($aTxt,$aAngle=0) {
  5416. $box = $this->GetBBoxTTF($aTxt,$aAngle);
  5417. return $box[2]-$box[0]+1;
  5418. }
  5419. function _StrokeTTF($x,$y,$txt,$dir=0,$paragraph_align="left",&$aBoundingBox,$debug=false) {
  5420. // Setupo default inter line margin for paragraphs to
  5421. // 25% of the font height.
  5422. $ConstLineSpacing = 0.25 ;
  5423. // Remember the anchor point before adjustment
  5424. if( $debug ) {
  5425. $ox=$x;
  5426. $oy=$y;
  5427. }
  5428. if( !ereg("\n",$txt) || ($dir>0 && ereg("\n",$txt)) ) {
  5429. // Format a single line
  5430. $txt = $this->AddTxtCR($txt);
  5431. $bbox=$this->GetBBoxTTF($txt,$dir);
  5432. // Align x,y ot lower left corner of bbox
  5433. $x -= $bbox[0];
  5434. $y -= $bbox[1];
  5435. // Note to self: "topanchor" is deprecated after we changed the
  5436. // bopunding box stuff.
  5437. if( $this->text_halign=="right" || $this->text_halign=="topanchor" )
  5438. $x -= $bbox[2]-$bbox[0];
  5439. elseif( $this->text_halign=="center" ) $x -= ($bbox[2]-$bbox[0])/2;
  5440. if( $this->text_valign=="top" ) $y += abs($bbox[5])+$bbox[1];
  5441. elseif( $this->text_valign=="center" ) $y -= ($bbox[5]-$bbox[1])/2;
  5442. ImageTTFText ($this->img, $this->font_size, $dir, $x, $y,
  5443. $this->current_color,$this->font_file,$txt);
  5444. // Calculate and return the co-ordinates for the bounding box
  5445. $box=@ImageTTFBBox($this->font_size,$dir,$this->font_file,$txt);
  5446. $p1 = array();
  5447. for($i=0; $i < 4; ++$i) {
  5448. $p1[] = round($box[$i*2]+$x);
  5449. $p1[] = round($box[$i*2+1]+$y);
  5450. }
  5451. $aBoundingBox = $p1;
  5452. // Debugging code to highlight the bonding box and bounding rectangle
  5453. // For text at 0 degrees the bounding box and bounding rectangle are the
  5454. // same
  5455. if( $debug ) {
  5456. // Draw the bounding rectangle and the bounding box
  5457. $box=@ImageTTFBBox($this->font_size,$dir,$this->font_file,$txt);
  5458. $p = array();
  5459. $p1 = array();
  5460. for($i=0; $i < 4; ++$i) {
  5461. $p[] = $bbox[$i*2]+$x;
  5462. $p[] = $bbox[$i*2+1]+$y;
  5463. $p1[] = $box[$i*2]+$x;
  5464. $p1[] = $box[$i*2+1]+$y;
  5465. }
  5466. // Draw bounding box
  5467. $this->PushColor('green');
  5468. $this->Polygon($p1,true);
  5469. $this->PopColor();
  5470. // Draw bounding rectangle
  5471. $this->PushColor('darkgreen');
  5472. $this->Polygon($p,true);
  5473. $this->PopColor();
  5474. // Draw a cross at the anchor point
  5475. $this->PushColor('red');
  5476. $this->Line($ox-15,$oy,$ox+15,$oy);
  5477. $this->Line($ox,$oy-15,$ox,$oy+15);
  5478. $this->PopColor();
  5479. }
  5480. }
  5481. else {
  5482. // Format a text paragraph
  5483. $fh=$this->GetFontHeight();
  5484. // Line margin is 25% of font height
  5485. $linemargin=round($fh*$ConstLineSpacing);
  5486. $fh += $linemargin;
  5487. $w=$this->GetTextWidth($txt);
  5488. $y -= $linemargin/2;
  5489. $tmp = split("\n",$txt);
  5490. $nl = count($tmp);
  5491. $h = $nl * $fh;
  5492. if( $this->text_halign=="right")
  5493. $x -= $dir==0 ? $w : $h;
  5494. elseif( $this->text_halign=="center" ) {
  5495. $x -= $dir==0 ? $w/2 : $h/2;
  5496. }
  5497. if( $this->text_valign=="top" )
  5498. $y += $dir==0 ? $h : $w;
  5499. elseif( $this->text_valign=="center" )
  5500. $y += $dir==0 ? $h/2 : $w/2;
  5501. // Here comes a tricky bit.
  5502. // Since we have to give the position for the string at the
  5503. // baseline this means thaht text will move slightly up
  5504. // and down depending on any of it's character descend below
  5505. // the baseline, for example a 'g'. To adjust the Y-position
  5506. // we therefore adjust the text with the baseline Y-offset
  5507. // as used for the current font and size. This will keep the
  5508. // baseline at a fixed positoned disregarding the actual
  5509. // characters in the string.
  5510. $standardbox = $this->GetTTFBBox('Gg',$dir);
  5511. $yadj = $standardbox[1];
  5512. $xadj = $standardbox[0];
  5513. $aBoundingBox = array();
  5514. for($i=0; $i < $nl; ++$i) {
  5515. $wl = $this->GetTextWidth($tmp[$i]);
  5516. $bbox = $this->GetTTFBBox($tmp[$i],$dir);
  5517. if( $paragraph_align=="left" ) {
  5518. $xl = $x;
  5519. }
  5520. elseif( $paragraph_align=="right" ) {
  5521. $xl = $x + ($w-$wl);
  5522. }
  5523. else {
  5524. // Center
  5525. $xl = $x + $w/2 - $wl/2 ;
  5526. }
  5527. $xl -= $bbox[0];
  5528. $yl = $y - $yadj;
  5529. $xl = $xl - $xadj;
  5530. ImageTTFText ($this->img, $this->font_size, $dir,
  5531. $xl, $yl-($h-$fh)+$fh*$i,
  5532. $this->current_color,$this->font_file,$tmp[$i]);
  5533. if( $debug ) {
  5534. // Draw the bounding rectangle around each line
  5535. $box=@ImageTTFBBox($this->font_size,$dir,$this->font_file,$tmp[$i]);
  5536. $p = array();
  5537. for($j=0; $j < 4; ++$j) {
  5538. $p[] = $bbox[$j*2]+$xl;
  5539. $p[] = $bbox[$j*2+1]+$yl-($h-$fh)+$fh*$i;
  5540. }
  5541. // Draw bounding rectangle
  5542. $this->PushColor('darkgreen');
  5543. $this->Polygon($p,true);
  5544. $this->PopColor();
  5545. }
  5546. }
  5547. // Get the bounding box
  5548. $bbox = $this->GetBBoxTTF($txt,$dir);
  5549. for($j=0; $j < 4; ++$j) {
  5550. $bbox[$j*2]+= round($x);
  5551. $bbox[$j*2+1]+= round($y - ($h-$fh) - $yadj);
  5552. }
  5553. $aBoundingBox = $bbox;
  5554. if( $debug ) {
  5555. // Draw a cross at the anchor point
  5556. $this->PushColor('red');
  5557. $this->Line($ox-25,$oy,$ox+25,$oy);
  5558. $this->Line($ox,$oy-25,$ox,$oy+25);
  5559. $this->PopColor();
  5560. }
  5561. }
  5562. }
  5563. function StrokeText($x,$y,$txt,$dir=0,$paragraph_align="left",$debug=false) {
  5564. $x = round($x);
  5565. $y = round($y);
  5566. // Do special language encoding
  5567. $txt = $this->langconv->Convert($txt,$this->font_family);
  5568. if( !is_numeric($dir) )
  5569. JpGraphError::Raise(" Direction for text most be given as an angle between 0 and 90.");
  5570. if( $this->font_family >= FF_FONT0 && $this->font_family <= FF_FONT2+1) {
  5571. $this->_StrokeBuiltinFont($x,$y,$txt,$dir,$paragraph_align,$boundingbox,$debug);
  5572. }
  5573. elseif($this->font_family >= _FF_FIRST && $this->font_family <= _FF_LAST) {
  5574. $this->_StrokeTTF($x,$y,$txt,$dir,$paragraph_align,$boundingbox,$debug);
  5575. }
  5576. else
  5577. JpGraphError::Raise(" Unknown font font family specification. ");
  5578. return $boundingbox;
  5579. }
  5580. function SetMargin($lm,$rm,$tm,$bm) {
  5581. $this->left_margin=$lm;
  5582. $this->right_margin=$rm;
  5583. $this->top_margin=$tm;
  5584. $this->bottom_margin=$bm;
  5585. $this->plotwidth=$this->width - $this->left_margin-$this->right_margin ;
  5586. $this->plotheight=$this->height - $this->top_margin-$this->bottom_margin ;
  5587. if( $this->width > 0 && $this->height > 0 ) {
  5588. if( $this->plotwidth < 0 || $this->plotheight < 0 )
  5589. JpGraphError::raise("To small plot area. ($lm,$rm,$tm,$bm : $this->plotwidth x $this->plotheight). With the given image size and margins there is to little space left for the plot. Increase the plot size or reduce the margins.");
  5590. }
  5591. }
  5592. function SetTransparent($color) {
  5593. imagecolortransparent ($this->img,$this->rgb->allocate($color));
  5594. }
  5595. function SetColor($color,$aAlpha=0) {
  5596. $this->current_color_name = $color;
  5597. $this->current_color=$this->rgb->allocate($color,$aAlpha);
  5598. if( $this->current_color == -1 ) {
  5599. $tc=imagecolorstotal($this->img);
  5600. JpGraphError::Raise("Can't allocate any more colors.
  5601. Image has already allocated maximum of <b>$tc colors</b>.
  5602. This might happen if you have anti-aliasing turned on
  5603. together with a background image or perhaps gradient fill
  5604. since this requires many, many colors. Try to turn off
  5605. anti-aliasing.<p>
  5606. If there is still a problem try downgrading the quality of
  5607. the background image to use a smaller pallete to leave some
  5608. entries for your graphs. You should try to limit the number
  5609. of colors in your background image to 64.<p>
  5610. If there is still problem set the constant
  5611. <pre>
  5612. DEFINE(\"USE_APPROX_COLORS\",true);
  5613. </pre>
  5614. in jpgraph.php This will use approximative colors
  5615. when the palette is full.
  5616. <p>
  5617. Unfortunately there is not much JpGraph can do about this
  5618. since the palette size is a limitation of current graphic format and
  5619. what the underlying GD library suppports.");
  5620. }
  5621. return $this->current_color;
  5622. }
  5623. function PushColor($color) {
  5624. if( $color != "" ) {
  5625. $this->colorstack[$this->colorstackidx]=$this->current_color_name;
  5626. $this->colorstack[$this->colorstackidx+1]=$this->current_color;
  5627. $this->colorstackidx+=2;
  5628. $this->SetColor($color);
  5629. }
  5630. else {
  5631. JpGraphError::Raise("Color specified as empty string in PushColor().");
  5632. }
  5633. }
  5634. function PopColor() {
  5635. if($this->colorstackidx<1)
  5636. JpGraphError::Raise(" Negative Color stack index. Unmatched call to PopColor()");
  5637. $this->current_color=$this->colorstack[--$this->colorstackidx];
  5638. $this->current_color_name=$this->colorstack[--$this->colorstackidx];
  5639. }
  5640. // Why this duplication? Because this way we can call this method
  5641. // for any image and not only the current objsct
  5642. function AdjSat($sat) {
  5643. if( $GLOBALS['gd2'] && USE_TRUECOLOR )
  5644. return;
  5645. $this->_AdjSat($this->img,$sat);
  5646. }
  5647. function _AdjSat($img,$sat) {
  5648. $nbr = imagecolorstotal ($img);
  5649. for( $i=0; $i<$nbr; ++$i ) {
  5650. $colarr = imagecolorsforindex ($img,$i);
  5651. $rgb[0]=$colarr["red"];
  5652. $rgb[1]=$colarr["green"];
  5653. $rgb[2]=$colarr["blue"];
  5654. $rgb = $this->AdjRGBSat($rgb,$sat);
  5655. imagecolorset ($img, $i, $rgb[0], $rgb[1], $rgb[2]);
  5656. }
  5657. }
  5658. function AdjBrightContrast($bright,$contr=0) {
  5659. if( $GLOBALS['gd2'] && USE_TRUECOLOR )
  5660. return;
  5661. $this->_AdjBrightContrast($this->img,$bright,$contr);
  5662. }
  5663. function _AdjBrightContrast($img,$bright,$contr=0) {
  5664. if( $bright < -1 || $bright > 1 || $contr < -1 || $contr > 1 )
  5665. JpGraphError::Raise(" Parameters for brightness and Contrast out of range [-1,1]");
  5666. $nbr = imagecolorstotal ($img);
  5667. for( $i=0; $i<$nbr; ++$i ) {
  5668. $colarr = imagecolorsforindex ($img,$i);
  5669. $r = $this->AdjRGBBrightContrast($colarr["red"],$bright,$contr);
  5670. $g = $this->AdjRGBBrightContrast($colarr["green"],$bright,$contr);
  5671. $b = $this->AdjRGBBrightContrast($colarr["blue"],$bright,$contr);
  5672. imagecolorset ($img, $i, $r, $g, $b);
  5673. }
  5674. }
  5675. // Private helper function for adj sat
  5676. // Adjust saturation for RGB array $u. $sat is a value between -1 and 1
  5677. // Note: Due to GD inability to handle true color the RGB values are only between
  5678. // 8 bit. This makes saturation quite sensitive for small increases in parameter sat.
  5679. //
  5680. // Tip: To get a grayscale picture set sat=-100, values <-100 changes the colors
  5681. // to it's complement.
  5682. //
  5683. // Implementation note: The saturation is implemented directly in the RGB space
  5684. // by adjusting the perpendicular distance between the RGB point and the "grey"
  5685. // line (1,1,1). Setting $sat>0 moves the point away from the line along the perp.
  5686. // distance and a negative value moves the point closer to the line.
  5687. // The values are truncated when the color point hits the bounding box along the
  5688. // RGB axis.
  5689. // DISCLAIMER: I'm not 100% sure this is he correct way to implement a color
  5690. // saturation function in RGB space. However, it looks ok and has the expected effect.
  5691. function AdjRGBSat($rgb,$sat) {
  5692. // TODO: Should be moved to the RGB class
  5693. // Grey vector
  5694. $v=array(1,1,1);
  5695. // Dot product
  5696. $dot = $rgb[0]*$v[0]+$rgb[1]*$v[1]+$rgb[2]*$v[2];
  5697. // Normalize dot product
  5698. $normdot = $dot/3; // dot/|v|^2
  5699. // Direction vector between $u and its projection onto $v
  5700. for($i=0; $i<3; ++$i)
  5701. $r[$i] = $rgb[$i] - $normdot*$v[$i];
  5702. // Adjustment factor so that sat==1 sets the highest RGB value to 255
  5703. if( $sat > 0 ) {
  5704. $m=0;
  5705. for( $i=0; $i<3; ++$i) {
  5706. if( sign($r[$i]) == 1 && $r[$i]>0)
  5707. $m=max($m,(255-$rgb[$i])/$r[$i]);
  5708. }
  5709. $tadj=$m;
  5710. }
  5711. else
  5712. $tadj=1;
  5713. $tadj = $tadj*$sat;
  5714. for($i=0; $i<3; ++$i) {
  5715. $un[$i] = round($rgb[$i] + $tadj*$r[$i]);
  5716. if( $un[$i]<0 ) $un[$i]=0; // Truncate color when they reach 0
  5717. if( $un[$i]>255 ) $un[$i]=255;// Avoid potential rounding error
  5718. }
  5719. return $un;
  5720. }
  5721. // Private helper function for AdjBrightContrast
  5722. function AdjRGBBrightContrast($rgb,$bright,$contr) {
  5723. // TODO: Should be moved to the RGB class
  5724. // First handle contrast, i.e change the dynamic range around grey
  5725. if( $contr <= 0 ) {
  5726. // Decrease contrast
  5727. $adj = abs($rgb-128) * (-$contr);
  5728. if( $rgb < 128 ) $rgb += $adj;
  5729. else $rgb -= $adj;
  5730. }
  5731. else { // $contr > 0
  5732. // Increase contrast
  5733. if( $rgb < 128 ) $rgb = $rgb - ($rgb * $contr);
  5734. else $rgb = $rgb + ((255-$rgb) * $contr);
  5735. }
  5736. // Add (or remove) various amount of white
  5737. $rgb += $bright*255;
  5738. $rgb=min($rgb,255);
  5739. $rgb=max($rgb,0);
  5740. return $rgb;
  5741. }
  5742. function SetLineWeight($weight) {
  5743. $this->line_weight = $weight;
  5744. }
  5745. function SetStartPoint($x,$y) {
  5746. $this->lastx=round($x);
  5747. $this->lasty=round($y);
  5748. }
  5749. function Arc($cx,$cy,$w,$h,$s,$e) {
  5750. // GD Arc doesn't like negative angles
  5751. while( $s < 0) $s += 360;
  5752. while( $e < 0) $e += 360;
  5753. imagearc($this->img,round($cx),round($cy),round($w),round($h),
  5754. $s,$e,$this->current_color);
  5755. }
  5756. function FilledArc($xc,$yc,$w,$h,$s,$e,$style="") {
  5757. if( $GLOBALS['gd2'] ) {
  5758. while( $s < 0 ) $s += 360;
  5759. while( $e < 0 ) $e += 360;
  5760. if( $style=="" )
  5761. $style=IMG_ARC_PIE;
  5762. imagefilledarc($this->img,round($xc),round($yc),round($w),round($h),
  5763. round($s),round($e),$this->current_color,$style);
  5764. return;
  5765. }
  5766. // In GD 1.x we have to do it ourself interesting enough there is surprisingly
  5767. // little difference in time between doing it PHP and using the optimised GD
  5768. // library (roughly ~20%) I had expected it to be at least 100% slower doing it
  5769. // manually with a polygon approximation in PHP.....
  5770. $fillcolor = $this->current_color_name;
  5771. $w /= 2; // We use radius in our calculations instead
  5772. $h /= 2;
  5773. // Setup the angles so we have the same conventions as the builtin
  5774. // FilledArc() which is a little bit strange if you ask me....
  5775. $s = 360-$s;
  5776. $e = 360-$e;
  5777. if( $e > $s ) {
  5778. $e = $e - 360;
  5779. $da = $s - $e;
  5780. }
  5781. $da = $s-$e;
  5782. // We use radians
  5783. $s *= M_PI/180;
  5784. $e *= M_PI/180;
  5785. $da *= M_PI/180;
  5786. // Calculate a polygon approximation
  5787. $p[0] = $xc;
  5788. $p[1] = $yc;
  5789. // Heuristic on how many polygons we need to make the
  5790. // arc look good
  5791. $numsteps = round(8 * abs($da) * ($w+$h)*($w+$h)/1500);
  5792. if( $numsteps == 0 ) return;
  5793. if( $numsteps < 7 ) $numsteps=7;
  5794. $delta = abs($da)/$numsteps;
  5795. $pa=array();
  5796. $a = $s;
  5797. for($i=1; $i<=$numsteps; ++$i ) {
  5798. $p[2*$i] = round($xc + $w*cos($a));
  5799. $p[2*$i+1] = round($yc - $h*sin($a));
  5800. //$a = $s + $i*$delta;
  5801. $a -= $delta;
  5802. $pa[2*($i-1)] = $p[2*$i];
  5803. $pa[2*($i-1)+1] = $p[2*$i+1];
  5804. }
  5805. // Get the last point at the exact ending angle to avoid
  5806. // any rounding errors.
  5807. $p[2*$i] = round($xc + $w*cos($e));
  5808. $p[2*$i+1] = round($yc - $h*sin($e));
  5809. $pa[2*($i-1)] = $p[2*$i];
  5810. $pa[2*($i-1)+1] = $p[2*$i+1];
  5811. $i++;
  5812. $p[2*$i] = $xc;
  5813. $p[2*$i+1] = $yc;
  5814. if( $fillcolor != "" ) {
  5815. $this->PushColor($fillcolor);
  5816. imagefilledpolygon($this->img,$p,count($p)/2,$this->current_color);
  5817. $this->PopColor();
  5818. }
  5819. }
  5820. function FilledCakeSlice($cx,$cy,$w,$h,$s,$e) {
  5821. $this->CakeSlice($cx,$cy,$w,$h,$s,$e,$this->current_color_name);
  5822. }
  5823. function CakeSlice($xc,$yc,$w,$h,$s,$e,$fillcolor="",$arccolor="") {
  5824. $s = round($s); $e = round($e);
  5825. $w = round($w); $h = round($h);
  5826. $xc = round($xc); $yc = round($yc);
  5827. $this->PushColor($fillcolor);
  5828. $this->FilledArc($xc,$yc,2*$w,2*$h,$s,$e);
  5829. $this->PopColor();
  5830. if( $arccolor != "" ) {
  5831. $this->PushColor($arccolor);
  5832. // We add 2 pixels to make the Arc() better aligned with
  5833. // the filled arc.
  5834. if( $GLOBALS['gd2'] ) {
  5835. imagefilledarc($this->img,$xc,$yc,2*$w,2*$h,$s,$e,$this->current_color_name,
  5836. IMG_ARC_NOFILL | IMG_ARC_EDGED ) ;
  5837. }
  5838. else {
  5839. $this->Arc($xc,$yc,2*$w+2,2*$h+2,$s,$e);
  5840. $xx = $w * cos(2*M_PI - $s*M_PI/180) + $xc;
  5841. $yy = $yc - $h * sin(2*M_PI - $s*M_PI/180);
  5842. $this->Line($xc,$yc,$xx,$yy);
  5843. $xx = $w * cos(2*M_PI - $e*M_PI/180) + $xc;
  5844. $yy = $yc - $h * sin(2*M_PI - $e*M_PI/180);
  5845. $this->Line($xc,$yc,$xx,$yy);
  5846. }
  5847. $this->PopColor();
  5848. }
  5849. }
  5850. function Ellipse($xc,$yc,$w,$h) {
  5851. $this->Arc($xc,$yc,$w,$h,0,360);
  5852. }
  5853. // Breseham circle gives visually better result then using GD
  5854. // built in arc(). It takes some more time but gives better
  5855. // accuracy.
  5856. function BresenhamCircle($xc,$yc,$r) {
  5857. $d = 3-2*$r;
  5858. $x = 0;
  5859. $y = $r;
  5860. while($x<=$y) {
  5861. $this->Point($xc+$x,$yc+$y);
  5862. $this->Point($xc+$x,$yc-$y);
  5863. $this->Point($xc-$x,$yc+$y);
  5864. $this->Point($xc-$x,$yc-$y);
  5865. $this->Point($xc+$y,$yc+$x);
  5866. $this->Point($xc+$y,$yc-$x);
  5867. $this->Point($xc-$y,$yc+$x);
  5868. $this->Point($xc-$y,$yc-$x);
  5869. if( $d<0 ) $d += 4*$x+6;
  5870. else {
  5871. $d += 4*($x-$y)+10;
  5872. --$y;
  5873. }
  5874. ++$x;
  5875. }
  5876. }
  5877. function Circle($xc,$yc,$r) {
  5878. if( USE_BRESENHAM )
  5879. $this->BresenhamCircle($xc,$yc,$r);
  5880. else {
  5881. /*
  5882. // Some experimental code snippet to see if we can get a decent
  5883. // result doing a trig-circle
  5884. // Create an approximated circle with 0.05 rad resolution
  5885. $end = 2*M_PI;
  5886. $l = $r/10;
  5887. if( $l < 3 ) $l=3;
  5888. $step_size = 2*M_PI/(2*$r*M_PI/$l);
  5889. $pts = array();
  5890. $pts[] = $r + $xc;
  5891. $pts[] = $yc;
  5892. for( $a=$step_size; $a <= $end; $a += $step_size ) {
  5893. $pts[] = round($xc + $r*cos($a));
  5894. $pts[] = round($yc - $r*sin($a));
  5895. }
  5896. imagepolygon($this->img,$pts,count($pts)/2,$this->current_color);
  5897. */
  5898. $this->Arc($xc,$yc,$r*2,$r*2,0,360);
  5899. // For some reason imageellipse() isn't in GD 2.0.1, PHP 4.1.1
  5900. //imageellipse($this->img,$xc,$yc,$r,$r,$this->current_color);
  5901. }
  5902. }
  5903. function FilledCircle($xc,$yc,$r) {
  5904. if( $GLOBALS['gd2'] ) {
  5905. imagefilledellipse($this->img,round($xc),round($yc),
  5906. 2*$r,2*$r,$this->current_color);
  5907. }
  5908. else {
  5909. for( $i=1; $i < 2*$r; $i += 2 ) {
  5910. // To avoid moire patterns we have to draw some
  5911. // 1 extra "skewed" filled circles
  5912. $this->Arc($xc,$yc,$i,$i,0,360);
  5913. $this->Arc($xc,$yc,$i+1,$i,0,360);
  5914. $this->Arc($xc,$yc,$i+1,$i+1,0,360);
  5915. }
  5916. }
  5917. }
  5918. // Linear Color InterPolation
  5919. function lip($f,$t,$p) {
  5920. $p = round($p,1);
  5921. $r = $f[0] + ($t[0]-$f[0])*$p;
  5922. $g = $f[1] + ($t[1]-$f[1])*$p;
  5923. $b = $f[2] + ($t[2]-$f[2])*$p;
  5924. return array($r,$g,$b);
  5925. }
  5926. // Anti-aliased line.
  5927. // Note that this is roughly 8 times slower then a normal line!
  5928. function WuLine($x1,$y1,$x2,$y2) {
  5929. // Get foreground line color
  5930. $lc = imagecolorsforindex($this->img,$this->current_color);
  5931. $lc = array($lc["red"],$lc["green"],$lc["blue"]);
  5932. $dx = $x2-$x1;
  5933. $dy = $y2-$y1;
  5934. if( abs($dx) > abs($dy) ) {
  5935. if( $dx<0 ) {
  5936. $dx = -$dx;$dy = -$dy;
  5937. $tmp=$x2;$x2=$x1;$x1=$tmp;
  5938. $tmp=$y2;$y2=$y1;$y1=$tmp;
  5939. }
  5940. $x=$x1<<16; $y=$y1<<16;
  5941. $yinc = ($dy*65535)/$dx;
  5942. while( ($x >> 16) < $x2 ) {
  5943. $bc = @imagecolorsforindex($this->img,imagecolorat($this->img,$x>>16,$y>>16));
  5944. if( $bc <= 0 ) {
  5945. JpGraphError::Raise('Problem with color palette and your GD setup. Please disable anti-aliasing or use GD2 with true-color. If you have GD2 library installed please make sure that you have set the USE_GD2 constant to true and that truecolor is enabled.');
  5946. }
  5947. $bc=array($bc["red"],$bc["green"],$bc["blue"]);
  5948. $this->SetColor($this->lip($lc,$bc,($y & 0xFFFF)/65535));
  5949. imagesetpixel($this->img,$x>>16,$y>>16,$this->current_color);
  5950. $this->SetColor($this->lip($lc,$bc,(~$y & 0xFFFF)/65535));
  5951. imagesetpixel($this->img,$x>>16,($y>>16)+1,$this->current_color);
  5952. $x += 65536; $y += $yinc;
  5953. }
  5954. }
  5955. else {
  5956. if( $dy<0 ) {
  5957. $dx = -$dx;$dy = -$dy;
  5958. $tmp=$x2;$x2=$x1;$x1=$tmp;
  5959. $tmp=$y2;$y2=$y1;$y1=$tmp;
  5960. }
  5961. $x=$x1<<16; $y=$y1<<16;
  5962. $xinc = ($dx*65535)/$dy;
  5963. while( ($y >> 16) < $y2 ) {
  5964. $bc = @imagecolorsforindex($this->img,imagecolorat($this->img,$x>>16,$y>>16));
  5965. if( $bc <= 0 ) {
  5966. JpGraphError::Raise('Problem with color palette and your GD setup. Please disable anti-aliasing or use GD2 with true-color. If you have GD2 library installed please make sure that you have set the USE_GD2 constant to true and truecolor is enabled.');
  5967. }
  5968. $bc=array($bc["red"],$bc["green"],$bc["blue"]);
  5969. $this->SetColor($this->lip($lc,$bc,($x & 0xFFFF)/65535));
  5970. imagesetpixel($this->img,$x>>16,$y>>16,$this->current_color);
  5971. $this->SetColor($this->lip($lc,$bc,(~$x & 0xFFFF)/65535));
  5972. imagesetpixel($this->img,($x>>16)+1,$y>>16,$this->current_color);
  5973. $y += 65536; $x += $xinc;
  5974. }
  5975. }
  5976. $this->SetColor($lc);
  5977. imagesetpixel($this->img,$x2,$y2,$this->current_color);
  5978. imagesetpixel($this->img,$x1,$y1,$this->current_color);
  5979. }
  5980. // Set line style dashed, dotted etc
  5981. function SetLineStyle($s) {
  5982. if( is_numeric($s) ) {
  5983. if( $s<1 || $s>4 )
  5984. JpGraphError::Raise(" Illegal numeric argument to SetLineStyle(): ($s)");
  5985. }
  5986. elseif( is_string($s) ) {
  5987. if( $s == "solid" ) $s=1;
  5988. elseif( $s == "dotted" ) $s=2;
  5989. elseif( $s == "dashed" ) $s=3;
  5990. elseif( $s == "longdashed" ) $s=4;
  5991. else JpGraphError::Raise(" Illegal string argument to SetLineStyle(): $s");
  5992. }
  5993. else JpGraphError::Raise(" Illegal argument to SetLineStyle $s");
  5994. $this->line_style=$s;
  5995. }
  5996. // Same as Line but take the line_style into account
  5997. function StyleLine($x1,$y1,$x2,$y2) {
  5998. switch( $this->line_style ) {
  5999. case 1:// Solid
  6000. $this->Line($x1,$y1,$x2,$y2);
  6001. break;
  6002. case 2: // Dotted
  6003. $this->DashedLine($x1,$y1,$x2,$y2,1,6);
  6004. break;
  6005. case 3: // Dashed
  6006. $this->DashedLine($x1,$y1,$x2,$y2,2,4);
  6007. break;
  6008. case 4: // Longdashes
  6009. $this->DashedLine($x1,$y1,$x2,$y2,8,6);
  6010. break;
  6011. default:
  6012. JpGraphError::Raise(" Unknown line style: $this->line_style ");
  6013. break;
  6014. }
  6015. }
  6016. function Line($x1,$y1,$x2,$y2) {
  6017. $x1 = round($x1);
  6018. $x2 = round($x2);
  6019. $y1 = round($y1);
  6020. $y2 = round($y2);
  6021. if( $this->line_weight==0 ) return;
  6022. if( $this->use_anti_aliasing ) {
  6023. $dx = $x2-$x1;
  6024. $dy = $y2-$y1;
  6025. // Vertical, Horizontal or 45 lines don't need anti-aliasing
  6026. if( $dx!=0 && $dy!=0 && $dx!=$dy ) {
  6027. $this->WuLine($x1,$y1,$x2,$y2);
  6028. return;
  6029. }
  6030. }
  6031. if( $this->line_weight==1 ) {
  6032. imageline($this->img,$x1,$y1,$x2,$y2,$this->current_color);
  6033. }
  6034. elseif( $x1==$x2 ) { // Special case for vertical lines
  6035. imageline($this->img,$x1,$y1,$x2,$y2,$this->current_color);
  6036. $w1=floor($this->line_weight/2);
  6037. $w2=floor(($this->line_weight-1)/2);
  6038. for($i=1; $i<=$w1; ++$i)
  6039. imageline($this->img,$x1+$i,$y1,$x2+$i,$y2,$this->current_color);
  6040. for($i=1; $i<=$w2; ++$i)
  6041. imageline($this->img,$x1-$i,$y1,$x2-$i,$y2,$this->current_color);
  6042. }
  6043. elseif( $y1==$y2 ) { // Special case for horizontal lines
  6044. imageline($this->img,$x1,$y1,$x2,$y2,$this->current_color);
  6045. $w1=floor($this->line_weight/2);
  6046. $w2=floor(($this->line_weight-1)/2);
  6047. for($i=1; $i<=$w1; ++$i)
  6048. imageline($this->img,$x1,$y1+$i,$x2,$y2+$i,$this->current_color);
  6049. for($i=1; $i<=$w2; ++$i)
  6050. imageline($this->img,$x1,$y1-$i,$x2,$y2-$i,$this->current_color);
  6051. }
  6052. else { // General case with a line at an angle
  6053. $a = atan2($y1-$y2,$x2-$x1);
  6054. // Now establish some offsets from the center. This gets a little
  6055. // bit involved since we are dealing with integer functions and we
  6056. // want the apperance to be as smooth as possible and never be thicker
  6057. // then the specified width.
  6058. // We do the trig stuff to make sure that the endpoints of the line
  6059. // are perpendicular to the line itself.
  6060. $dx=(sin($a)*$this->line_weight/2);
  6061. $dy=(cos($a)*$this->line_weight/2);
  6062. $pnts = array($x2+$dx,$y2+$dy,$x2-$dx,$y2-$dy,$x1-$dx,$y1-$dy,$x1+$dx,$y1+$dy);
  6063. imagefilledpolygon($this->img,$pnts,count($pnts)/2,$this->current_color);
  6064. }
  6065. $this->lastx=$x2; $this->lasty=$y2;
  6066. }
  6067. function Polygon($p,$closed=FALSE,$fast=FALSE) {
  6068. if( $this->line_weight==0 ) return;
  6069. $n=count($p);
  6070. $oldx = $p[0];
  6071. $oldy = $p[1];
  6072. if( $fast ) {
  6073. for( $i=2; $i < $n; $i+=2 ) {
  6074. imageline($this->img,$oldx,$oldy,$p[$i],$p[$i+1],$this->current_color);
  6075. $oldx = $p[$i];
  6076. $oldy = $p[$i+1];
  6077. }
  6078. if( $closed ) {
  6079. imageline($this->img,$p[$n*2-2],$p[$n*2-1],$p[0],$p[1],$this->current_color);
  6080. }
  6081. }
  6082. else {
  6083. for( $i=2; $i < $n; $i+=2 ) {
  6084. $this->StyleLine($oldx,$oldy,$p[$i],$p[$i+1]);
  6085. $oldx = $p[$i];
  6086. $oldy = $p[$i+1];
  6087. }
  6088. }
  6089. if( $closed )
  6090. $this->Line($oldx,$oldy,$p[0],$p[1]);
  6091. }
  6092. function FilledPolygon($pts) {
  6093. $n=count($pts);
  6094. if( $n == 0 ) {
  6095. JpGraphError::Raise('NULL data specified for a filled polygon. Check that your data is not NULL.');
  6096. }
  6097. for($i=0; $i < $n; ++$i)
  6098. $pts[$i] = round($pts[$i]);
  6099. imagefilledpolygon($this->img,$pts,count($pts)/2,$this->current_color);
  6100. }
  6101. function Rectangle($xl,$yu,$xr,$yl) {
  6102. $this->Polygon(array($xl,$yu,$xr,$yu,$xr,$yl,$xl,$yl,$xl,$yu));
  6103. }
  6104. function FilledRectangle($xl,$yu,$xr,$yl) {
  6105. $this->FilledPolygon(array($xl,$yu,$xr,$yu,$xr,$yl,$xl,$yl));
  6106. }
  6107. function FilledRectangle2($xl,$yu,$xr,$yl,$color1,$color2,$style=1) {
  6108. // Fill a rectangle with lines of two colors
  6109. if( $style===1 ) {
  6110. // Horizontal stripe
  6111. if( $yl < $yu ) {
  6112. $t = $yl; $yl=$yu; $yu=$t;
  6113. }
  6114. for( $y=$yu; $y <= $yl; ++$y) {
  6115. $this->SetColor($color1);
  6116. $this->Line($xl,$y,$xr,$y);
  6117. ++$y;
  6118. $this->SetColor($color2);
  6119. $this->Line($xl,$y,$xr,$y);
  6120. }
  6121. }
  6122. else {
  6123. if( $xl < $xl ) {
  6124. $t = $xl; $xl=$xr; $xr=$t;
  6125. }
  6126. for( $x=$xl; $x <= $xr; ++$x) {
  6127. $this->SetColor($color1);
  6128. $this->Line($x,$yu,$x,$yl);
  6129. ++$x;
  6130. $this->SetColor($color2);
  6131. $this->Line($x,$yu,$x,$yl);
  6132. }
  6133. }
  6134. }
  6135. function ShadowRectangle($xl,$yu,$xr,$yl,$fcolor=false,$shadow_width=3,$shadow_color=array(102,102,102)) {
  6136. // This is complicated by the fact that we must also handle the case where
  6137. // the reactangle has no fill color
  6138. $this->PushColor($shadow_color);
  6139. $this->FilledRectangle($xr-$shadow_width,$yu+$shadow_width,$xr,$yl-$shadow_width-1);
  6140. $this->FilledRectangle($xl+$shadow_width,$yl-$shadow_width,$xr,$yl);
  6141. //$this->FilledRectangle($xl+$shadow_width,$yu+$shadow_width,$xr,$yl);
  6142. $this->PopColor();
  6143. if( $fcolor==false )
  6144. $this->Rectangle($xl,$yu,$xr-$shadow_width-1,$yl-$shadow_width-1);
  6145. else {
  6146. $this->PushColor($fcolor);
  6147. $this->FilledRectangle($xl,$yu,$xr-$shadow_width-1,$yl-$shadow_width-1);
  6148. $this->PopColor();
  6149. $this->Rectangle($xl,$yu,$xr-$shadow_width-1,$yl-$shadow_width-1);
  6150. }
  6151. }
  6152. function FilledRoundedRectangle($xt,$yt,$xr,$yl,$r=5) {
  6153. if( $r==0 ) {
  6154. $this->FilledRectangle($xt,$yt,$xr,$yl);
  6155. return;
  6156. }
  6157. // To avoid overlapping fillings (which will look strange
  6158. // when alphablending is enabled) we have no choice but
  6159. // to fill the five distinct areas one by one.
  6160. // Center square
  6161. $this->FilledRectangle($xt+$r,$yt+$r,$xr-$r,$yl-$r);
  6162. // Top band
  6163. $this->FilledRectangle($xt+$r,$yt,$xr-$r,$yt+$r-1);
  6164. // Bottom band
  6165. $this->FilledRectangle($xt+$r,$yl-$r+1,$xr-$r,$yl);
  6166. // Left band
  6167. $this->FilledRectangle($xt,$yt+$r+1,$xt+$r-1,$yl-$r);
  6168. // Right band
  6169. $this->FilledRectangle($xr-$r+1,$yt+$r,$xr,$yl-$r);
  6170. // Topleft & Topright arc
  6171. $this->FilledArc($xt+$r,$yt+$r,$r*2,$r*2,180,270);
  6172. $this->FilledArc($xr-$r,$yt+$r,$r*2,$r*2,270,360);
  6173. // Bottomleft & Bottom right arc
  6174. $this->FilledArc($xt+$r,$yl-$r,$r*2,$r*2,90,180);
  6175. $this->FilledArc($xr-$r,$yl-$r,$r*2,$r*2,0,90);
  6176. }
  6177. function RoundedRectangle($xt,$yt,$xr,$yl,$r=5) {
  6178. if( $r==0 ) {
  6179. $this->Rectangle($xt,$yt,$xr,$yl);
  6180. return;
  6181. }
  6182. // Top & Bottom line
  6183. $this->Line($xt+$r,$yt,$xr-$r,$yt);
  6184. $this->Line($xt+$r,$yl,$xr-$r,$yl);
  6185. // Left & Right line
  6186. $this->Line($xt,$yt+$r,$xt,$yl-$r);
  6187. $this->Line($xr,$yt+$r,$xr,$yl-$r);
  6188. // Topleft & Topright arc
  6189. $this->Arc($xt+$r,$yt+$r,$r*2,$r*2,180,270);
  6190. $this->Arc($xr-$r,$yt+$r,$r*2,$r*2,270,360);
  6191. // Bottomleft & Bottomright arc
  6192. $this->Arc($xt+$r,$yl-$r,$r*2,$r*2,90,180);
  6193. $this->Arc($xr-$r,$yl-$r,$r*2,$r*2,0,90);
  6194. }
  6195. function FilledBevel($x1,$y1,$x2,$y2,$depth=2,$color1='white@0.4',$color2='darkgray@0.4') {
  6196. $this->FilledRectangle($x1,$y1,$x2,$y2);
  6197. $this->Bevel($x1,$y1,$x2,$y2,$depth,$color1,$color2);
  6198. }
  6199. function Bevel($x1,$y1,$x2,$y2,$depth=2,$color1='white@0.4',$color2='black@0.5') {
  6200. $this->PushColor($color1);
  6201. for( $i=0; $i < $depth; ++$i ) {
  6202. $this->Line($x1+$i,$y1+$i,$x1+$i,$y2-$i);
  6203. $this->Line($x1+$i,$y1+$i,$x2-$i,$y1+$i);
  6204. }
  6205. $this->PopColor();
  6206. $this->PushColor($color2);
  6207. for( $i=0; $i < $depth; ++$i ) {
  6208. $this->Line($x1+$i,$y2-$i,$x2-$i,$y2-$i);
  6209. $this->Line($x2-$i,$y1+$i,$x2-$i,$y2-$i-1);
  6210. }
  6211. $this->PopColor();
  6212. }
  6213. function StyleLineTo($x,$y) {
  6214. $this->StyleLine($this->lastx,$this->lasty,$x,$y);
  6215. $this->lastx=$x;
  6216. $this->lasty=$y;
  6217. }
  6218. function LineTo($x,$y) {
  6219. $this->Line($this->lastx,$this->lasty,$x,$y);
  6220. $this->lastx=$x;
  6221. $this->lasty=$y;
  6222. }
  6223. function Point($x,$y) {
  6224. imagesetpixel($this->img,round($x),round($y),$this->current_color);
  6225. }
  6226. function Fill($x,$y) {
  6227. imagefill($this->img,round($x),round($y),$this->current_color);
  6228. }
  6229. function FillToBorder($x,$y,$aBordColor) {
  6230. $bc = $this->rgb->allocate($aBordColor);
  6231. if( $bc == -1 ) {
  6232. JpGraphError::Raise('Image::FillToBorder : Can not allocate more colors');
  6233. exit();
  6234. }
  6235. imagefilltoborder($this->img,round($x),round($y),$bc,$this->current_color);
  6236. }
  6237. function DashedLine($x1,$y1,$x2,$y2,$dash_length=1,$dash_space=4) {
  6238. // Code based on, but not identical to, work by Ariel Garza and James Pine
  6239. $line_length = ceil (sqrt(pow(($x2 - $x1),2) + pow(($y2 - $y1),2)) );
  6240. $dx = ($line_length) ? ($x2 - $x1) / $line_length : 0;
  6241. $dy = ($line_length) ? ($y2 - $y1) / $line_length : 0;
  6242. $lastx = $x1; $lasty = $y1;
  6243. $xmax = max($x1,$x2);
  6244. $xmin = min($x1,$x2);
  6245. $ymax = max($y1,$y2);
  6246. $ymin = min($y1,$y2);
  6247. for ($i = 0; $i < $line_length; $i += ($dash_length + $dash_space)) {
  6248. $x = ($dash_length * $dx) + $lastx;
  6249. $y = ($dash_length * $dy) + $lasty;
  6250. // The last section might overshoot so we must take a computational hit
  6251. // and check this.
  6252. if( $x>$xmax ) $x=$xmax;
  6253. if( $y>$ymax ) $y=$ymax;
  6254. if( $x<$xmin ) $x=$xmin;
  6255. if( $y<$ymin ) $y=$ymin;
  6256. $this->Line($lastx,$lasty,$x,$y);
  6257. $lastx = $x + ($dash_space * $dx);
  6258. $lasty = $y + ($dash_space * $dy);
  6259. }
  6260. }
  6261. function SetExpired($aFlg=true) {
  6262. $this->expired = $aFlg;
  6263. }
  6264. // Generate image header
  6265. function Headers() {
  6266. // In case we are running from the command line with the client version of
  6267. // PHP we can't send any headers.
  6268. $sapi = php_sapi_name();
  6269. if( $sapi == 'cli' )
  6270. return;
  6271. if( headers_sent() ) {
  6272. echo "<table border=1><tr><td><font color=darkred size=4><b>JpGraph Error:</b>
  6273. HTTP headers have already been sent.</font></td></tr><tr><td><b>Explanation:</b><br>HTTP headers have already been sent back to the browser indicating the data as text before the library got a chance to send it's image HTTP header to this browser. This makes it impossible for the library to send back image data to the browser (since that would be interpretated as text by the browser and show up as junk text).<p>Most likely you have some text in your script before the call to <i>Graph::Stroke()</i>. If this texts gets sent back to the browser the browser will assume that all data is plain text. Look for any text, even spaces and newlines, that might have been sent back to the browser. <p>For example it is a common mistake to leave a blank line before the opening \"<b>&lt;?php</b>\".</td></tr></table>";
  6274. die();
  6275. }
  6276. if ($this->expired) {
  6277. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  6278. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
  6279. header("Cache-Control: no-cache, must-revalidate");
  6280. header("Pragma: no-cache");
  6281. }
  6282. header("Content-type: image/$this->img_format");
  6283. }
  6284. // Adjust image quality for formats that allow this
  6285. function SetQuality($q) {
  6286. $this->quality = $q;
  6287. }
  6288. // Stream image to browser or to file
  6289. function Stream($aFile="") {
  6290. $func="image".$this->img_format;
  6291. if( $this->img_format=="jpeg" && $this->quality != null ) {
  6292. $res = @$func($this->img,$aFile,$this->quality);
  6293. }
  6294. else {
  6295. if( $aFile != "" ) {
  6296. $res = @$func($this->img,$aFile);
  6297. }
  6298. else
  6299. $res = @$func($this->img);
  6300. }
  6301. if( !$res )
  6302. JpGraphError::Raise("Can't create or stream image to file $aFile Check that PHP has enough permission to write a file to the current directory.");
  6303. }
  6304. // Clear resource tide up by image
  6305. function Destroy() {
  6306. imagedestroy($this->img);
  6307. }
  6308. // Specify image format. Note depending on your installation
  6309. // of PHP not all formats may be supported.
  6310. function SetImgFormat($aFormat) {
  6311. $aFormat = strtolower($aFormat);
  6312. $tst = true;
  6313. $supported = imagetypes();
  6314. if( $aFormat=="auto" ) {
  6315. if( $supported & IMG_PNG )
  6316. $this->img_format="png";
  6317. elseif( $supported & IMG_JPG )
  6318. $this->img_format="jpeg";
  6319. elseif( $supported & IMG_GIF )
  6320. $this->img_format="gif";
  6321. else
  6322. JpGraphError::Raise(" Your PHP (and GD-lib) installation does not appear to support any known graphic formats.".
  6323. "You need to first make sure GD is compiled as a module to PHP. If you also want to use JPEG images".
  6324. "you must get the JPEG library. Please see the PHP docs for details.");
  6325. return true;
  6326. }
  6327. else {
  6328. if( $aFormat=="jpeg" || $aFormat=="png" || $aFormat=="gif" ) {
  6329. if( $aFormat=="jpeg" && !($supported & IMG_JPG) )
  6330. $tst=false;
  6331. elseif( $aFormat=="png" && !($supported & IMG_PNG) )
  6332. $tst=false;
  6333. elseif( $aFormat=="gif" && !($supported & IMG_GIF) )
  6334. $tst=false;
  6335. else {
  6336. $this->img_format=$aFormat;
  6337. return true;
  6338. }
  6339. }
  6340. else
  6341. $tst=false;
  6342. if( !$tst )
  6343. JpGraphError::Raise(" Your PHP installation does not support the chosen graphic format: $aFormat");
  6344. }
  6345. }
  6346. } // CLASS
  6347. //===================================================
  6348. // CLASS RotImage
  6349. // Description: Exactly as Image but draws the image at
  6350. // a specified angle around a specified rotation point.
  6351. //===================================================
  6352. class RotImage extends Image {
  6353. var $m=array();
  6354. var $a=0;
  6355. var $dx=0,$dy=0,$transx=0,$transy=0;
  6356. function RotImage($aWidth,$aHeight,$a=0,$aFormat=DEFAULT_GFORMAT) {
  6357. $this->Image($aWidth,$aHeight,$aFormat);
  6358. $this->dx=$this->left_margin+$this->plotwidth/2;
  6359. $this->dy=$this->top_margin+$this->plotheight/2;
  6360. $this->SetAngle($a);
  6361. }
  6362. function SetCenter($dx,$dy) {
  6363. $old_dx = $this->dx;
  6364. $old_dy = $this->dy;
  6365. $this->dx=$dx;
  6366. $this->dy=$dy;
  6367. $this->SetAngle($this->a);
  6368. return array($old_dx,$old_dy);
  6369. }
  6370. function SetTranslation($dx,$dy) {
  6371. $old = array($this->transx,$this->transy);
  6372. $this->transx = $dx;
  6373. $this->transy = $dy;
  6374. return $old;
  6375. }
  6376. function UpdateRotMatrice() {
  6377. $a = $this->a;
  6378. $a *= M_PI/180;
  6379. $sa=sin($a); $ca=cos($a);
  6380. // Create the rotation matrix
  6381. $this->m[0][0] = $ca;
  6382. $this->m[0][1] = -$sa;
  6383. $this->m[0][2] = $this->dx*(1-$ca) + $sa*$this->dy ;
  6384. $this->m[1][0] = $sa;
  6385. $this->m[1][1] = $ca;
  6386. $this->m[1][2] = $this->dy*(1-$ca) - $sa*$this->dx ;
  6387. }
  6388. function SetAngle($a) {
  6389. $tmp = $this->a;
  6390. $this->a = $a;
  6391. $this->UpdateRotMatrice();
  6392. return $tmp;
  6393. }
  6394. function Circle($xc,$yc,$r) {
  6395. // Circle get's rotated through the Arc() call
  6396. // made in the parent class
  6397. parent::Circle($xc,$yc,$r);
  6398. }
  6399. function FilledCircle($xc,$yc,$r) {
  6400. // If we use GD1 then Image::FilledCircle will use a
  6401. // call to Arc so it will get rotated through the Arc
  6402. // call.
  6403. if( $GLOBALS['gd2'] ) {
  6404. list($xc,$yc) = $this->Rotate($xc,$yc);
  6405. }
  6406. parent::FilledCircle($xc,$yc,$r);
  6407. }
  6408. function Arc($xc,$yc,$w,$h,$s,$e) {
  6409. list($xc,$yc) = $this->Rotate($xc,$yc);
  6410. $s += $this->a;
  6411. $e += $this->a;
  6412. parent::Arc($xc,$yc,$w,$h,$s,$e);
  6413. }
  6414. function FilledArc($xc,$yc,$w,$h,$s,$e) {
  6415. list($xc,$yc) = $this->Rotate($xc,$yc);
  6416. $s += $this->a;
  6417. $e += $this->a;
  6418. parent::FilledArc($xc,$yc,$w,$h,$s,$e);
  6419. }
  6420. function SetMargin($lm,$rm,$tm,$bm) {
  6421. parent::SetMargin($lm,$rm,$tm,$bm);
  6422. $this->dx=$this->left_margin+$this->plotwidth/2;
  6423. $this->dy=$this->top_margin+$this->plotheight/2;
  6424. $this->UpdateRotMatrice();
  6425. }
  6426. function Rotate($x,$y) {
  6427. // Optimization. Ignore rotation if Angle==0 || ANgle==360
  6428. if( $this->a == 0 || $this->a == 360 ) {
  6429. return array($x + $this->transx, $y + $this->transy );
  6430. }
  6431. else {
  6432. $x1=round($this->m[0][0]*$x + $this->m[0][1]*$y,1) + $this->m[0][2] + $this->transx;
  6433. $y1=round($this->m[1][0]*$x + $this->m[1][1]*$y,1) + $this->m[1][2] + $this->transy;
  6434. return array($x1,$y1);
  6435. }
  6436. }
  6437. function CopyMerge($fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth=-1,$fromHeight=-1,$aMix=100) {
  6438. list($toX,$toY) = $this->Rotate($toX,$toY);
  6439. parent::CopyMerge($fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth,$fromHeight,$aMix);
  6440. }
  6441. function ArrRotate($pnts) {
  6442. for($i=0; $i < count($pnts)-1; $i+=2)
  6443. list($pnts[$i],$pnts[$i+1]) = $this->Rotate($pnts[$i],$pnts[$i+1]);
  6444. return $pnts;
  6445. }
  6446. function Line($x1,$y1,$x2,$y2) {
  6447. list($x1,$y1) = $this->Rotate($x1,$y1);
  6448. list($x2,$y2) = $this->Rotate($x2,$y2);
  6449. parent::Line($x1,$y1,$x2,$y2);
  6450. }
  6451. function Rectangle($x1,$y1,$x2,$y2) {
  6452. // Rectangle uses Line() so it will be rotated through that call
  6453. parent::Rectangle($x1,$y1,$x2,$y2);
  6454. }
  6455. function FilledRectangle($x1,$y1,$x2,$y2) {
  6456. if( $y1==$y2 || $x1==$x2 )
  6457. $this->Line($x1,$y1,$x2,$y2);
  6458. else
  6459. $this->FilledPolygon(array($x1,$y1,$x2,$y1,$x2,$y2,$x1,$y2));
  6460. }
  6461. function Polygon($pnts,$closed=FALSE,$fast=false) {
  6462. //Polygon uses Line() so it will be rotated through that call
  6463. parent::Polygon($pnts,$closed,$fast);
  6464. }
  6465. function FilledPolygon($pnts) {
  6466. parent::FilledPolygon($this->ArrRotate($pnts));
  6467. }
  6468. function Point($x,$y) {
  6469. list($xp,$yp) = $this->Rotate($x,$y);
  6470. parent::Point($xp,$yp);
  6471. }
  6472. function StrokeText($x,$y,$txt,$dir=0,$paragraph_align="left",$debug=false) {
  6473. list($xp,$yp) = $this->Rotate($x,$y);
  6474. return parent::StrokeText($xp,$yp,$txt,$dir,$paragraph_align,$debug);
  6475. }
  6476. }
  6477. //===================================================
  6478. // CLASS ImgStreamCache
  6479. // Description: Handle caching of graphs to files
  6480. //===================================================
  6481. class ImgStreamCache {
  6482. var $cache_dir;
  6483. var $img=null;
  6484. var $timeout=0; // Infinite timeout
  6485. //---------------
  6486. // CONSTRUCTOR
  6487. function ImgStreamCache(&$aImg, $aCacheDir=CACHE_DIR) {
  6488. $this->img = &$aImg;
  6489. $this->cache_dir = $aCacheDir;
  6490. }
  6491. //---------------
  6492. // PUBLIC METHODS
  6493. // Specify a timeout (in minutes) for the file. If the file is older then the
  6494. // timeout value it will be overwritten with a newer version.
  6495. // If timeout is set to 0 this is the same as infinite large timeout and if
  6496. // timeout is set to -1 this is the same as infinite small timeout
  6497. function SetTimeout($aTimeout) {
  6498. $this->timeout=$aTimeout;
  6499. }
  6500. // Output image to browser and also write it to the cache
  6501. function PutAndStream(&$aImage,$aCacheFileName,$aInline,$aStrokeFileName) {
  6502. // Some debugging code to brand the image with numbe of colors
  6503. // used
  6504. GLOBAL $gJpgBrandTiming;
  6505. if( $gJpgBrandTiming ) {
  6506. global $tim;
  6507. $t=$tim->Pop()/1000.0;
  6508. $c=$aImage->SetColor("black");
  6509. $t=sprintf(BRAND_TIME_FORMAT,round($t,3));
  6510. imagestring($this->img->img,2,5,$this->img->height-20,$t,$c);
  6511. }
  6512. // Check if we should stroke the image to an arbitrary file
  6513. if( _FORCE_IMGTOFILE ) {
  6514. $aStrokeFileName = _FORCE_IMGDIR.GenImgName();
  6515. }
  6516. if( $aStrokeFileName!="" ) {
  6517. if( $aStrokeFileName == "auto" )
  6518. $aStrokeFileName = GenImgName();
  6519. if( file_exists($aStrokeFileName) ) {
  6520. // Delete the old file
  6521. if( !@unlink($aStrokeFileName) )
  6522. JpGraphError::Raise(" Can't delete cached image $aStrokeFileName. Permission problem?");
  6523. }
  6524. $aImage->Stream($aStrokeFileName);
  6525. return;
  6526. }
  6527. if( $aCacheFileName != "" && USE_CACHE) {
  6528. $aCacheFileName = $this->cache_dir . $aCacheFileName;
  6529. if( file_exists($aCacheFileName) ) {
  6530. if( !$aInline ) {
  6531. // If we are generating image off-line (just writing to the cache)
  6532. // and the file exists and is still valid (no timeout)
  6533. // then do nothing, just return.
  6534. $diff=time()-filemtime($aCacheFileName);
  6535. if( $diff < 0 )
  6536. JpGraphError::Raise(" Cached imagefile ($aCacheFileName) has file date in the future!!");
  6537. if( $this->timeout>0 && ($diff <= $this->timeout*60) )
  6538. return;
  6539. }
  6540. if( !@unlink($aCacheFileName) )
  6541. JpGraphError::Raise(" Can't delete cached image $aStrokeFileName. Permission problem?");
  6542. $aImage->Stream($aCacheFileName);
  6543. }
  6544. else {
  6545. $this->MakeDirs(dirname($aCacheFileName));
  6546. if( !is_writeable(dirname($aCacheFileName)) ) {
  6547. JpGraphError::Raise('PHP has not enough permissions to write to the cache file '.$aCacheFileName.'. Please make sure that the user running PHP has write permission for this file if you wan to use the cache system with JpGraph.');
  6548. }
  6549. $aImage->Stream($aCacheFileName);
  6550. }
  6551. $res=true;
  6552. // Set group to specified
  6553. if( CACHE_FILE_GROUP != "" )
  6554. $res = @chgrp($aCacheFileName,CACHE_FILE_GROUP);
  6555. if( CACHE_FILE_MOD != "" )
  6556. $res = @chmod($aCacheFileName,CACHE_FILE_MOD);
  6557. if( !$res )
  6558. JpGraphError::Raise(" Can't set permission for cached image $aStrokeFileName. Permission problem?");
  6559. $aImage->Destroy();
  6560. if( $aInline ) {
  6561. if ($fh = @fopen($aCacheFileName, "rb") ) {
  6562. $this->img->Headers();
  6563. fpassthru($fh);
  6564. return;
  6565. }
  6566. else
  6567. JpGraphError::Raise(" Cant open file from cache [$aFile]");
  6568. }
  6569. }
  6570. elseif( $aInline ) {
  6571. $this->img->Headers();
  6572. $aImage->Stream();
  6573. return;
  6574. }
  6575. }
  6576. // Check if a given image is in cache and in that case
  6577. // pass it directly on to web browser. Return false if the
  6578. // image file doesn't exist or exists but is to old
  6579. function GetAndStream($aCacheFileName) {
  6580. $aCacheFileName = $this->cache_dir.$aCacheFileName;
  6581. if ( USE_CACHE && file_exists($aCacheFileName) && $this->timeout>=0 ) {
  6582. $diff=time()-filemtime($aCacheFileName);
  6583. if( $this->timeout>0 && ($diff > $this->timeout*60) ) {
  6584. return false;
  6585. }
  6586. else {
  6587. if ($fh = @fopen($aCacheFileName, "rb")) {
  6588. $this->img->Headers();
  6589. fpassthru($fh);
  6590. return true;
  6591. }
  6592. else
  6593. JpGraphError::Raise(" Can't open cached image \"$aCacheFileName\" for reading.");
  6594. }
  6595. }
  6596. return false;
  6597. }
  6598. //---------------
  6599. // PRIVATE METHODS
  6600. // Create all necessary directories in a path
  6601. function MakeDirs($aFile) {
  6602. $dirs = array();
  6603. while ( !(file_exists($aFile)) ) {
  6604. $dirs[] = $aFile;
  6605. $aFile = dirname($aFile);
  6606. }
  6607. for ($i = sizeof($dirs)-1; $i>=0; $i--) {
  6608. if(! @mkdir($dirs[$i],0777) )
  6609. JpGraphError::Raise(" Can't create directory $aFile. Make sure PHP has write permission to this directory.");
  6610. // We also specify mode here after we have changed group.
  6611. // This is necessary if Apache user doesn't belong the
  6612. // default group and hence can't specify group permission
  6613. // in the previous mkdir() call
  6614. if( CACHE_FILE_GROUP != "" ) {
  6615. $res=true;
  6616. $res =@chgrp($dirs[$i],CACHE_FILE_GROUP);
  6617. $res &= @chmod($dirs[$i],0777);
  6618. if( !$res )
  6619. JpGraphError::Raise(" Can't set permissions for $aFile. Permission problems?");
  6620. }
  6621. }
  6622. return true;
  6623. }
  6624. } // CLASS Cache
  6625. //===================================================
  6626. // CLASS Legend
  6627. // Description: Responsible for drawing the box containing
  6628. // all the legend text for the graph
  6629. //===================================================
  6630. DEFINE('_DEFAULT_LPM_SIZE',8);
  6631. class Legend {
  6632. var $color=array(0,0,0); // Default fram color
  6633. var $fill_color=array(235,235,235); // Default fill color
  6634. var $shadow=true; // Shadow around legend "box"
  6635. var $shadow_color='gray';
  6636. var $txtcol=array();
  6637. var $mark_abs_size=_DEFAULT_LPM_SIZE;
  6638. var $xmargin=5,$ymargin=3,$shadow_width=2;
  6639. var $xlmargin=2, $ylmargin='';
  6640. var $xpos=0.05, $ypos=0.15, $xabspos=-1, $yabspos=-1;
  6641. var $halign="right", $valign="top";
  6642. var $font_family=FF_FONT1,$font_style=FS_NORMAL,$font_size=12;
  6643. var $font_color='black';
  6644. var $hide=false,$layout_n=1;
  6645. var $weight=1,$frameweight=1;
  6646. var $csimareas='';
  6647. var $reverse = false ;
  6648. //---------------
  6649. // CONSTRUCTOR
  6650. function Legend() {
  6651. // Empty
  6652. }
  6653. //---------------
  6654. // PUBLIC METHODS
  6655. function Hide($aHide=true) {
  6656. $this->hide=$aHide;
  6657. }
  6658. function SetHColMargin($aXMarg) {
  6659. $this->xmargin = $aXMarg;
  6660. }
  6661. function SetVColMargin($aSpacing) {
  6662. $this->ymargin = $aSpacing ;
  6663. }
  6664. function SetLeftMargin($aXMarg) {
  6665. $this->xlmargin = $aXMarg;
  6666. }
  6667. // Synonym
  6668. function SetLineSpacing($aSpacing) {
  6669. $this->ymargin = $aSpacing ;
  6670. }
  6671. function SetShadow($aShow='gray',$aWidth=2) {
  6672. if( is_string($aShow) ) {
  6673. $this->shadow_color = $aShow;
  6674. $this->shadow=true;
  6675. }
  6676. else
  6677. $this->shadow=$aShow;
  6678. $this->shadow_width=$aWidth;
  6679. }
  6680. function SetMarkAbsSize($aSize) {
  6681. $this->mark_abs_size = $aSize ;
  6682. }
  6683. function SetLineWeight($aWeight) {
  6684. $this->weight = $aWeight;
  6685. }
  6686. function SetFrameWeight($aWeight) {
  6687. $this->frameweight = $aWeight;
  6688. }
  6689. function SetLayout($aDirection=LEGEND_VERT) {
  6690. $this->layout_n = $aDirection==LEGEND_VERT ? 1 : 99 ;
  6691. }
  6692. function SetColumns($aCols) {
  6693. $this->layout_n = $aCols ;
  6694. }
  6695. function SetReverse($f=true) {
  6696. $this->reverse = $f ;
  6697. }
  6698. // Set color on frame around box
  6699. function SetColor($aFontColor,$aColor='black') {
  6700. $this->font_color=$aFontColor;
  6701. $this->color=$aColor;
  6702. }
  6703. function SetFont($aFamily,$aStyle=FS_NORMAL,$aSize=10) {
  6704. $this->font_family = $aFamily;
  6705. $this->font_style = $aStyle;
  6706. $this->font_size = $aSize;
  6707. }
  6708. function SetPos($aX,$aY,$aHAlign="right",$aVAlign="top") {
  6709. $this->Pos($aX,$aY,$aHAlign,$aVAlign);
  6710. }
  6711. function SetAbsPos($aX,$aY,$aHAlign="right",$aVAlign="top") {
  6712. $this->xabspos=$aX;
  6713. $this->yabspos=$aY;
  6714. $this->halign=$aHAlign;
  6715. $this->valign=$aVAlign;
  6716. }
  6717. function Pos($aX,$aY,$aHAlign="right",$aVAlign="top") {
  6718. if( !($aX<1 && $aY<1) )
  6719. JpGraphError::Raise(" Position for legend must be given as percentage in range 0-1");
  6720. $this->xpos=$aX;
  6721. $this->ypos=$aY;
  6722. $this->halign=$aHAlign;
  6723. $this->valign=$aVAlign;
  6724. }
  6725. function SetFillColor($aColor) {
  6726. $this->fill_color=$aColor;
  6727. }
  6728. function Add($aTxt,$aColor,$aPlotmark="",$aLinestyle=0,$csimtarget="",$csimalt="") {
  6729. $this->txtcol[]=array($aTxt,$aColor,$aPlotmark,$aLinestyle,$csimtarget,$csimalt);
  6730. }
  6731. function GetCSIMAreas() {
  6732. return $this->csimareas;
  6733. }
  6734. function Stroke(&$aImg) {
  6735. // Constant
  6736. $fillBoxFrameWeight=1;
  6737. if( $this->hide ) return;
  6738. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  6739. if( $this->reverse ) {
  6740. $this->txtcol = array_reverse($this->txtcol);
  6741. }
  6742. $n=count($this->txtcol);
  6743. if( $n == 0 ) return;
  6744. // Find out the max width and height of each column to be able
  6745. // to size the legend box.
  6746. $numcolumns = ($n > $this->layout_n ? $this->layout_n : $n);
  6747. for( $i=0; $i < $numcolumns; ++$i ) {
  6748. $colwidth[$i] = $aImg->GetTextWidth($this->txtcol[$i][0]) +
  6749. 2*$this->xmargin + 2*$this->mark_abs_size;
  6750. $colheight[$i] = 0;
  6751. }
  6752. // Find our maximum height in each row
  6753. $rows = -1 ;
  6754. for( $i=0; $i < $n; ++$i ) {
  6755. $h = max($this->mark_abs_size,$aImg->GetTextHeight($this->txtcol[$i][0]))+$this->ymargin;
  6756. if( $i % $numcolumns == 0 ) {
  6757. $rows++;
  6758. $rowheight[$rows] = 0;
  6759. }
  6760. $rowheight[$rows] = max($rowheight[$rows],$h);
  6761. }
  6762. $abs_height = 0;
  6763. for( $i=0; $i <= $rows; ++$i ) {
  6764. $abs_height += $rowheight[$i] ;
  6765. }
  6766. // Make sure that the height is at least as high as mark size + ymargin
  6767. $abs_height = max($abs_height,$this->mark_abs_size+$this->ymargin);
  6768. $abs_height += 2*$this->ymargin + $this->mark_abs_size/2;
  6769. // Find out the maximum width in each column
  6770. for( $i=$numcolumns; $i < $n; ++$i ) {
  6771. $colwidth[$i % $numcolumns] = max(
  6772. $aImg->GetTextWidth($this->txtcol[$i][0])+2*$this->xmargin+2*$this->mark_abs_size,
  6773. $colwidth[$i % $numcolumns]);
  6774. }
  6775. // Get the total width
  6776. $mtw = 0;
  6777. for( $i=0; $i < $numcolumns; ++$i ) {
  6778. $mtw += $colwidth[$i] ;
  6779. }
  6780. // Find out maximum width we need for legend box
  6781. $abs_width = $mtw+$this->xlmargin;
  6782. if( $this->xabspos === -1 && $this->yabspos === -1 ) {
  6783. $this->xabspos = $this->xpos*$aImg->width ;
  6784. $this->yabspos = $this->ypos*$aImg->height ;
  6785. }
  6786. // Positioning of the legend box
  6787. if( $this->halign=="left" )
  6788. $xp = $this->xabspos;
  6789. elseif( $this->halign=="center" )
  6790. $xp = $this->xabspos - $abs_width/2;
  6791. else
  6792. $xp = $aImg->width - $this->xabspos - $abs_width;
  6793. $yp=$this->yabspos;
  6794. if( $this->valign=="center" )
  6795. $yp-=$abs_height/2;
  6796. elseif( $this->valign=="bottom" )
  6797. $yp-=$abs_height;
  6798. // Stroke legend box
  6799. $aImg->SetColor($this->color);
  6800. $aImg->SetLineWeight($this->frameweight);
  6801. $aImg->SetLineStyle('solid');
  6802. if( $this->shadow )
  6803. $aImg->ShadowRectangle($xp,$yp,$xp+$abs_width+$this->shadow_width,
  6804. $yp+$abs_height+$this->shadow_width,
  6805. $this->fill_color,$this->shadow_width,$this->shadow_color);
  6806. else {
  6807. $aImg->SetColor($this->fill_color);
  6808. $aImg->FilledRectangle($xp,$yp,$xp+$abs_width,$yp+$abs_height);
  6809. $aImg->SetColor($this->color);
  6810. $aImg->Rectangle($xp,$yp,$xp+$abs_width,$yp+$abs_height);
  6811. }
  6812. // x1,y1 is the position for the legend mark
  6813. $x1=$xp+$this->mark_abs_size+$this->xlmargin;
  6814. $y1=$yp + $this->mark_abs_size/2 + $this->ymargin/3;
  6815. $f2 = round($aImg->GetTextHeight('X')/2);
  6816. $grad = new Gradient($aImg);
  6817. $patternFactory = null;
  6818. // Now stroke each legend in turn
  6819. // Each plot has added the following information to the legend
  6820. // p[0] = Legend text
  6821. // p[1] = Color,
  6822. // p[2] = For markers a reference to the PlotMark object
  6823. // p[3] = For lines the line style, for gradient the negative gradient style
  6824. // p[4] = CSIM target
  6825. // p[5] = CSIM Alt text
  6826. $i = 1 ; $row = 0;
  6827. foreach($this->txtcol as $p) {
  6828. $aImg->SetLineWeight($this->weight);
  6829. $x1 = round($x1); $y1=round($y1);
  6830. if ( $p[2] != "" && $p[2]->GetType() > -1 ) {
  6831. // Make a plot mark legend
  6832. $aImg->SetColor($p[1]);
  6833. if( is_string($p[3]) || $p[3]>0 ) {
  6834. $aImg->SetLineStyle($p[3]);
  6835. $aImg->StyleLine($x1-$this->mark_abs_size,$y1+$f2,$x1+$this->mark_abs_size,$y1+$f2);
  6836. }
  6837. // Stroke a mark with the standard size
  6838. // (As long as it is not an image mark )
  6839. if( $p[2]->GetType() != MARK_IMG ) {
  6840. $p[2]->iFormatCallback = '';
  6841. // Since size for circles is specified as the radius
  6842. // this means that we must half the size to make the total
  6843. // width behave as the other marks
  6844. if( $p[2]->GetType() == MARK_FILLEDCIRCLE || $p[2]->GetType() == MARK_CIRCLE ) {
  6845. $p[2]->SetSize($this->mark_abs_size/2);
  6846. $p[2]->Stroke($aImg,$x1,$y1+$f2);
  6847. }
  6848. else {
  6849. $p[2]->SetSize($this->mark_abs_size);
  6850. $p[2]->Stroke($aImg,$x1,$y1+$f2);
  6851. }
  6852. }
  6853. }
  6854. elseif ( $p[2] != "" && (is_string($p[3]) || $p[3]>0 ) ) {
  6855. // Draw a styled line
  6856. $aImg->SetColor($p[1]);
  6857. $aImg->SetLineStyle($p[3]);
  6858. $aImg->StyleLine($x1-1,$y1+$f2,$x1+$this->mark_abs_size,$y1+$f2);
  6859. $aImg->StyleLine($x1-1,$y1+$f2+1,$x1+$this->mark_abs_size,$y1+$f2+1);
  6860. }
  6861. else {
  6862. // Draw a colored box
  6863. $color = $p[1] ;
  6864. // We make boxes slightly larger to better show
  6865. $boxsize = $this->mark_abs_size + 2 ;
  6866. $ym = round($y1 + $f2 - $boxsize/2);
  6867. // We either need to plot a gradient or a
  6868. // pattern. To differentiate we use a kludge.
  6869. // Patterns have a p[3] value of < -100
  6870. if( $p[3] < -100 ) {
  6871. // p[1][0] == iPattern, p[1][1] == iPatternColor, p[1][2] == iPatternDensity
  6872. if( $patternFactory == null ) {
  6873. $patternFactory = new RectPatternFactory();
  6874. }
  6875. $prect = $patternFactory->Create($p[1][0],$p[1][1],1);
  6876. $prect->SetBackground($p[1][3]);
  6877. $prect->SetDensity($p[1][2]+1);
  6878. $prect->SetPos(new Rectangle($x1,$ym,$boxsize,$boxsize));
  6879. $prect->Stroke($aImg);
  6880. $prect=null;
  6881. }
  6882. else {
  6883. if( is_array($color) && count($color)==2 ) {
  6884. // The client want a gradient color
  6885. $grad->FilledRectangle($x1,$ym,
  6886. $x1+$boxsize,$ym+$boxsize,
  6887. $color[0],$color[1],-$p[3]);
  6888. }
  6889. else {
  6890. $aImg->SetColor($p[1]);
  6891. $aImg->FilledRectangle($x1,$ym,$x1+$boxsize,$ym+$boxsize);
  6892. }
  6893. $aImg->SetColor($this->color);
  6894. $aImg->SetLineWeight($fillBoxFrameWeight);
  6895. $aImg->Rectangle($x1,$ym,$x1+$boxsize,$ym+$boxsize);
  6896. }
  6897. }
  6898. $aImg->SetColor($this->font_color);
  6899. $aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
  6900. $aImg->SetTextAlign("left","top");
  6901. $aImg->StrokeText(round($x1+$this->mark_abs_size+$this->xmargin),$y1,$p[0]);
  6902. // Add CSIM for Legend if defined
  6903. if( $p[4] != "" ) {
  6904. $xe = $x1 + $this->xmargin+$this->mark_abs_size+$aImg->GetTextWidth($p[0]);
  6905. $ye = $y1 + max($this->mark_abs_size,$aImg->GetTextHeight($p[0]));
  6906. $coords = "$x1,$y1,$xe,$y1,$xe,$ye,$x1,$ye";
  6907. if( ! empty($p[4]) ) {
  6908. $this->csimareas .= "<area shape=\"poly\" coords=\"$coords\" href=\"".$p[4]."\"";
  6909. if( !empty($p[5]) ) {
  6910. $tmp=sprintf($p[5],$p[0]);
  6911. $this->csimareas .= " alt=\"$tmp\" title=\"$tmp\"";
  6912. }
  6913. $this->csimareas .= ">\n";
  6914. }
  6915. }
  6916. if( $i >= $this->layout_n ) {
  6917. $x1 = $xp+$this->mark_abs_size+$this->xlmargin;
  6918. //$y1 += max($aImg->GetTextHeight($p[0]),$this->mark_abs_size)+$this->ymargin;
  6919. $y1 += $rowheight[$row++];
  6920. $i = 1;
  6921. }
  6922. else {
  6923. $x1 += $colwidth[($i-1) % $numcolumns] ;
  6924. ++$i;
  6925. }
  6926. }
  6927. }
  6928. } // Class
  6929. //===================================================
  6930. // CLASS DisplayValue
  6931. // Description: Used to print data values at data points
  6932. //===================================================
  6933. class DisplayValue {
  6934. var $show=false,$format="%.1f",$negformat="";
  6935. var $iFormCallback='';
  6936. var $angle=0;
  6937. var $ff=FF_FONT1,$fs=FS_NORMAL,$fsize=10;
  6938. var $color="navy",$negcolor="";
  6939. var $margin=5,$valign="",$halign="center";
  6940. var $iHideZero=false;
  6941. function Show($aFlag=true) {
  6942. $this->show=$aFlag;
  6943. }
  6944. function SetColor($aColor,$aNegcolor="") {
  6945. $this->color = $aColor;
  6946. $this->negcolor = $aNegcolor;
  6947. }
  6948. function SetFont($aFontFamily,$aFontStyle=FS_NORMAL,$aFontSize=10) {
  6949. $this->ff=$aFontFamily;
  6950. $this->fs=$aFontStyle;
  6951. $this->fsize=$aFontSize;
  6952. }
  6953. function SetMargin($aMargin) {
  6954. $this->margin = $aMargin;
  6955. }
  6956. function SetAngle($aAngle) {
  6957. $this->angle = $aAngle;
  6958. }
  6959. function SetAlign($aHAlign,$aVAlign='') {
  6960. $this->halign = $aHAlign;
  6961. $this->valign = $aVAlign;
  6962. }
  6963. function SetFormat($aFormat,$aNegFormat="") {
  6964. $this->format= $aFormat;
  6965. $this->negformat= $aNegFormat;
  6966. }
  6967. function SetFormatCallback($aFunc) {
  6968. $this->iFormCallback = $aFunc;
  6969. }
  6970. function HideZero($aFlag=true) {
  6971. $this->iHideZero=$aFlag;
  6972. }
  6973. function Stroke($img,$aVal,$x,$y) {
  6974. if( $this->show )
  6975. {
  6976. if( $this->negformat=="" ) $this->negformat=$this->format;
  6977. if( $this->negcolor=="" ) $this->negcolor=$this->color;
  6978. if( $aVal===NULL || (is_string($aVal) && ($aVal=="" || $aVal=="-" || $aVal=="x" ) ) )
  6979. return;
  6980. if( is_numeric($aVal) && $aVal==0 && $this->iHideZero ) {
  6981. return;
  6982. }
  6983. // Since the value is used in different cirumstances we need to check what
  6984. // kind of formatting we shall use. For example, to display values in a line
  6985. // graph we simply display the formatted value, but in the case where the user
  6986. // has already specified a text string we don't fo anything.
  6987. if( $this->iFormCallback != '' ) {
  6988. $f = $this->iFormCallback;
  6989. $sval = call_user_func($f,$aVal);
  6990. }
  6991. elseif( is_numeric($aVal) ) {
  6992. if( $aVal >= 0 )
  6993. $sval=sprintf($this->format,$aVal);
  6994. else
  6995. $sval=sprintf($this->negformat,$aVal);
  6996. }
  6997. else
  6998. $sval=$aVal;
  6999. $y = $y-sign($aVal)*$this->margin;
  7000. $txt = new Text($sval,$x,$y);
  7001. $txt->SetFont($this->ff,$this->fs,$this->fsize);
  7002. if( $this->valign == "" ) {
  7003. if( $aVal >= 0 )
  7004. $valign = "bottom";
  7005. else
  7006. $valign = "top";
  7007. }
  7008. else
  7009. $valign = $this->valign;
  7010. $txt->Align($this->halign,$valign);
  7011. $txt->SetOrientation($this->angle);
  7012. if( $aVal > 0 )
  7013. $txt->SetColor($this->color);
  7014. else
  7015. $txt->SetColor($this->negcolor);
  7016. $txt->Stroke($img);
  7017. }
  7018. }
  7019. }
  7020. //===================================================
  7021. // CLASS Plot
  7022. // Description: Abstract base class for all concrete plot classes
  7023. //===================================================
  7024. class Plot {
  7025. var $line_weight=1;
  7026. var $coords=array();
  7027. var $legend='',$hidelegend=false;
  7028. var $csimtargets=array(); // Array of targets for CSIM
  7029. var $csimareas=""; // Resultant CSIM area tags
  7030. var $csimalts=null; // ALT:s for corresponding target
  7031. var $color="black";
  7032. var $numpoints=0;
  7033. var $weight=1;
  7034. var $value;
  7035. var $center=false;
  7036. var $legendcsimtarget='';
  7037. var $legendcsimalt='';
  7038. //---------------
  7039. // CONSTRUCTOR
  7040. function Plot(&$aDatay,$aDatax=false) {
  7041. $this->numpoints = count($aDatay);
  7042. if( $this->numpoints==0 )
  7043. JpGraphError::Raise("Empty input data array specified for plot. Must have at least one data point.");
  7044. $this->coords[0]=$aDatay;
  7045. if( is_array($aDatax) )
  7046. $this->coords[1]=$aDatax;
  7047. $this->value = new DisplayValue();
  7048. }
  7049. //---------------
  7050. // PUBLIC METHODS
  7051. // Stroke the plot
  7052. // "virtual" function which must be implemented by
  7053. // the subclasses
  7054. function Stroke(&$aImg,&$aXScale,&$aYScale) {
  7055. JpGraphError::Raise("JpGraph: Stroke() must be implemented by concrete subclass to class Plot");
  7056. }
  7057. function HideLegend($f=true) {
  7058. $this->hidelegend = $f;
  7059. }
  7060. function DoLegend(&$graph) {
  7061. if( !$this->hidelegend )
  7062. $this->Legend($graph);
  7063. }
  7064. function StrokeDataValue($img,$aVal,$x,$y) {
  7065. $this->value->Stroke($img,$aVal,$x,$y);
  7066. }
  7067. // Set href targets for CSIM
  7068. function SetCSIMTargets($aTargets,$aAlts=null) {
  7069. $this->csimtargets=$aTargets;
  7070. $this->csimalts=$aAlts;
  7071. }
  7072. // Get all created areas
  7073. function GetCSIMareas() {
  7074. return $this->csimareas;
  7075. }
  7076. // "Virtual" function which gets called before any scale
  7077. // or axis are stroked used to do any plot specific adjustment
  7078. function PreStrokeAdjust(&$aGraph) {
  7079. if( substr($aGraph->axtype,0,4) == "text" && (isset($this->coords[1])) )
  7080. JpGraphError::Raise("JpGraph: You can't use a text X-scale with specified X-coords. Use a \"int\" or \"lin\" scale instead.");
  7081. return true;
  7082. }
  7083. // Get minimum values in plot
  7084. function Min() {
  7085. if( isset($this->coords[1]) )
  7086. $x=$this->coords[1];
  7087. else
  7088. $x="";
  7089. if( $x != "" && count($x) > 0 )
  7090. $xm=min($x);
  7091. else
  7092. $xm=0;
  7093. $y=$this->coords[0];
  7094. $cnt = count($y);
  7095. if( $cnt > 0 ) {
  7096. /*
  7097. if( ! isset($y[0]) ) {
  7098. JpGraphError('The input data array must have consecutive values from position 0 and forward. The given y-array starts with empty values (NULL)');
  7099. }
  7100. */
  7101. //$ym = $y[0];
  7102. $i=0;
  7103. while( $i<$cnt && !is_numeric($ym=$y[$i]) )
  7104. $i++;
  7105. while( $i < $cnt) {
  7106. if( is_numeric($y[$i]) )
  7107. $ym=min($ym,$y[$i]);
  7108. ++$i;
  7109. }
  7110. }
  7111. else
  7112. $ym="";
  7113. return array($xm,$ym);
  7114. }
  7115. // Get maximum value in plot
  7116. function Max() {
  7117. if( isset($this->coords[1]) )
  7118. $x=$this->coords[1];
  7119. else
  7120. $x="";
  7121. if( $x!="" && count($x) > 0 )
  7122. $xm=max($x);
  7123. else {
  7124. $xm = $this->numpoints-1;
  7125. }
  7126. $y=$this->coords[0];
  7127. if( count($y) > 0 ) {
  7128. /*
  7129. if( !isset($y[0]) ) {
  7130. JpGraphError::Raise('The input data array must have consecutive values from position 0 and forward. The given y-array starts with empty values (NULL)');
  7131. //$y[0] = 0;
  7132. // Change in 1.5.1 Don't treat this as an error any more. Just silently convert to 0
  7133. // Change in 1.17 Treat his as an error again !! This is the right way to do !!
  7134. }
  7135. */
  7136. $cnt = count($y);
  7137. $i=0;
  7138. while( $i<$cnt && !is_numeric($ym=$y[$i]) )
  7139. $i++;
  7140. while( $i < $cnt ) {
  7141. if( is_numeric($y[$i]) )
  7142. $ym=max($ym,$y[$i]);
  7143. ++$i;
  7144. }
  7145. }
  7146. else
  7147. $ym="";
  7148. return array($xm,$ym);
  7149. }
  7150. function SetColor($aColor) {
  7151. $this->color=$aColor;
  7152. }
  7153. function SetLegend($aLegend,$aCSIM="",$aCSIMAlt="") {
  7154. $this->legend = $aLegend;
  7155. $this->legendcsimtarget = $aCSIM;
  7156. $this->legendcsimalt = $aCSIMAlt;
  7157. }
  7158. function SetWeight($aWeight) {
  7159. $this->weight=$aWeight;
  7160. }
  7161. function SetLineWeight($aWeight=1) {
  7162. $this->line_weight=$aWeight;
  7163. }
  7164. function SetCenter($aCenter=true) {
  7165. $this->center = $aCenter;
  7166. }
  7167. // This method gets called by Graph class to plot anything that should go
  7168. // into the margin after the margin color has been set.
  7169. function StrokeMargin(&$aImg) {
  7170. return true;
  7171. }
  7172. // Framework function the chance for each plot class to set a legend
  7173. function Legend(&$aGraph) {
  7174. if( $this->legend != "" )
  7175. $aGraph->legend->Add($this->legend,$this->color,"",0,$this->legendcsimtarget,$this->legendcsimalt);
  7176. }
  7177. } // Class
  7178. //===================================================
  7179. // CLASS PlotLine
  7180. // Description:
  7181. // Data container class to hold properties for a static
  7182. // line that is drawn directly in the plot area.
  7183. // Usefull to add static borders inside a plot to show
  7184. // for example set-values
  7185. //===================================================
  7186. class PlotLine {
  7187. var $weight=1;
  7188. var $color="black";
  7189. var $direction=-1;
  7190. var $scaleposition;
  7191. //---------------
  7192. // CONSTRUCTOR
  7193. function PlotLine($aDir=HORIZONTAL,$aPos=0,$aColor="black",$aWeight=1) {
  7194. $this->direction = $aDir;
  7195. $this->color=$aColor;
  7196. $this->weight=$aWeight;
  7197. $this->scaleposition=$aPos;
  7198. }
  7199. //---------------
  7200. // PUBLIC METHODS
  7201. function SetPosition($aScalePosition) {
  7202. $this->scaleposition=$aScalePosition;
  7203. }
  7204. function SetDirection($aDir) {
  7205. $this->direction = $aDir;
  7206. }
  7207. function SetColor($aColor) {
  7208. $this->color=$aColor;
  7209. }
  7210. function SetWeight($aWeight) {
  7211. $this->weight=$aWeight;
  7212. }
  7213. function PreStrokeAdjust($aGraph) {
  7214. // Nothing to do
  7215. }
  7216. function Stroke(&$aImg,&$aXScale,&$aYScale) {
  7217. $aImg->SetColor($this->color);
  7218. $aImg->SetLineWeight($this->weight);
  7219. if( $this->direction == VERTICAL ) {
  7220. $ymin_abs=$aYScale->Translate($aYScale->GetMinVal());
  7221. $ymax_abs=$aYScale->Translate($aYScale->GetMaxVal());
  7222. $xpos_abs=$aXScale->Translate($this->scaleposition);
  7223. $aImg->Line($xpos_abs, $ymin_abs, $xpos_abs, $ymax_abs);
  7224. }
  7225. elseif( $this->direction == HORIZONTAL ) {
  7226. $xmin_abs=$aXScale->Translate($aXScale->GetMinVal());
  7227. $xmax_abs=$aXScale->Translate($aXScale->GetMaxVal());
  7228. $ypos_abs=$aYScale->Translate($this->scaleposition);
  7229. $aImg->Line($xmin_abs, $ypos_abs, $xmax_abs, $ypos_abs);
  7230. }
  7231. else
  7232. JpGraphError::Raise(" Illegal direction for static line");
  7233. }
  7234. }
  7235. // <EOF>
  7236. ?>