PageRenderTime 90ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 2ms

/plugins/stats/images/phplot/phplot.php

https://github.com/xong/rexsearch
PHP | 5338 lines | 3148 code | 684 blank | 1506 comment | 755 complexity | dc202a8d08392ca09306badf7e537cd3 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /* $Id: phplot.php,v 1.167 2009/12/23 22:37:47 lbayuk Exp $ */
  3. /*
  4. * PHPLOT Version 5.1.0
  5. *
  6. * A PHP class for creating scientific and business charts
  7. * Visit http://sourceforge.net/projects/phplot/
  8. * for PHPlot documentation, downloads, and discussions.
  9. * ---------------------------------------------------------------------
  10. * Copyright (C) 1998-2009 Afan Ottenheimer
  11. *
  12. * This is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation;
  15. * version 2.1 of the License.
  16. *
  17. * This software is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with this software; if not, write to the Free Software
  24. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25. * ---------------------------------------------------------------------
  26. *
  27. * Co-author and maintainer (2003-2005)
  28. * Miguel de Benito Delgado <nonick AT vodafone DOT es>
  29. *
  30. * Maintainer (2006-present)
  31. * <lbayuk AT users DOT sourceforge DOT net>
  32. *
  33. * Requires PHP 5.2.x or later. (PHP 4 is unsupported as of Jan 2008)
  34. */
  35. class PHPlot {
  36. /* Declare class variables which are initialized to static values. Many more class variables
  37. * are used, defined as needed, but are unset by default.
  38. * All these are declared as public. While it is tempting to make them private or protected, this
  39. * is avoided for two reasons. First, it will break existing code, since all member variables
  40. * were public in PHP4 and who knows what internal variables people used. Second, it makes
  41. * testing harder and less effective. Nevertheless, your code should not modify these.
  42. */
  43. public $is_inline = FALSE; // FALSE = Sends headers, TRUE = sends just raw image data
  44. public $browser_cache = FALSE; // FALSE = Sends headers for browser to not cache the image,
  45. // (only if is_inline = FALSE also)
  46. public $print_image = TRUE; // DrawGraph calls PrintImage. See SetPrintImage
  47. public $background_done = FALSE; // TRUE after background image is drawn once
  48. public $safe_margin = 5; // Extra margin used in several places, in pixels
  49. public $x_axis_position = ''; // Where to draw both axis (world coordinates),
  50. public $y_axis_position = ''; // leave blank for X axis at 0 and Y axis at left of plot.
  51. public $xscale_type = 'linear'; // linear, log
  52. public $yscale_type = 'linear';
  53. //Fonts
  54. public $use_ttf = FALSE; // Use True Type Fonts by default?
  55. public $ttf_path = '.'; // Default path to look in for TT Fonts.
  56. public $default_ttfont = 'benjamingothic.ttf';
  57. public $line_spacing = 4; // Controls line spacing of multi-line labels
  58. // Label angles: 0 or 90 degrees for fixed fonts, any for TTF
  59. public $x_label_angle = 0; // For X tick labels
  60. // public $x_data_label_angle; // For X data labels; defaults to x_label_angle - see CheckLabels()
  61. public $y_label_angle = 0; // For Y tick labels
  62. public $y_data_label_angle = 0; // For Y data labels
  63. //Formats
  64. public $file_format = 'png';
  65. public $output_file = ''; // For output to a file instead of stdout
  66. //Data
  67. public $data_type = 'text-data'; // text-data, data-data-error, data-data, text-data-single
  68. public $plot_type= 'linepoints'; // bars, lines, linepoints, area, points, pie, thinbarline, squared
  69. public $label_scale_position = 0.5; // Shifts data labels in pie charts. 1 = top, 0 = bottom
  70. public $group_frac_width = 0.7; // Bars use this fraction (0 to 1) of a group's space
  71. public $bar_extra_space = 0.5; // Number of extra bar's worth of space in a group
  72. public $bar_width_adjust = 1; // 1 = bars of normal width, must be > 0
  73. // Titles
  74. public $title_txt = '';
  75. public $x_title_txt = '';
  76. public $x_title_pos = 'none'; // plotdown, plotup, both, none
  77. public $y_title_txt = '';
  78. public $y_title_pos = 'none'; // plotleft, plotright, both, none
  79. //Labels
  80. // There are two types of labels in PHPlot:
  81. // Tick labels: they follow the grid, next to ticks in axis.
  82. // they are drawn at grid drawing time, by DrawXTicks() and DrawYTicks()
  83. // Data labels: they follow the data points, and can be placed on the axis or the plot (x/y)
  84. // they are drawn at graph plotting time, by Draw*DataLabel(), called by DrawLines(), etc.
  85. // Draw*DataLabel() also draws H/V lines to datapoints depending on draw_*_data_label_lines
  86. // Tick Labels
  87. // x_tick_label_pos and x_data_label_pos are not initialized, because PHPlot needs
  88. // to determine if they were defaulted or set by the user. See CheckLabels().
  89. // public $x_tick_label_pos = 'plotdown'; // plotdown, plotup, both, xaxis, none
  90. public $y_tick_label_pos = 'plotleft'; // plotleft, plotright, both, yaxis, none
  91. // Data Labels:
  92. // public $x_data_label_pos = 'plotdown'; // plotdown, plotup, both, plot, all, none
  93. public $y_data_label_pos = 'none'; // plotleft, plotright, both, plot, all, plotin, none
  94. public $draw_x_data_label_lines = FALSE; // Draw a line from the data point to the axis?
  95. // Label format controls: (for tick, data and plot labels)
  96. // Unset by default, these array members are used as needed for 'x' (x tick labels), 'xd' (x data
  97. // labels), 'y' (y tick labels), and 'yd' (y data labels).
  98. // type, precision, prefix, suffix, time_format, printf_format, custom_callback, custom_arg.
  99. // These replace the former: x_label_type, x_time_format, x_precision (similar for y), data_units_text.
  100. public $label_format = array('x' => array(), 'xd' => array(), 'y' => array(), 'yd' => array());
  101. // data_units_text is retained for backward compatibility, because there was never a function
  102. // to set it. Use the 'suffix' argument to Set[XY]LabelType instead.
  103. public $data_units_text = ''; // Units text for 'data' labels (i.e: '¤', '$', etc.)
  104. // Legend
  105. public $legend = ''; // An array with legend titles
  106. // These variables are unset to take default values:
  107. // public $legend_x_pos; // User-specified upper left coordinates of legend box
  108. // public $legend_y_pos;
  109. // public $legend_xy_world; // If set, legend_x/y_pos are world coords, else pixel coords
  110. // public $legend_text_align; // left or right, Unset means right
  111. // public $legend_colorbox_align; // left, right, or none; Unset means same as text_align
  112. //Ticks
  113. public $x_tick_length = 5; // tick length in pixels for upper/lower axis
  114. public $y_tick_length = 5; // tick length in pixels for left/right axis
  115. public $x_tick_cross = 3; // ticks cross x axis this many pixels
  116. public $y_tick_cross = 3; // ticks cross y axis this many pixels
  117. public $x_tick_pos = 'plotdown'; // plotdown, plotup, both, xaxis, none
  118. public $y_tick_pos = 'plotleft'; // plotright, plotleft, both, yaxis, none
  119. public $num_x_ticks = '';
  120. public $num_y_ticks = '';
  121. public $x_tick_inc = ''; // Set num_x_ticks or x_tick_inc, not both.
  122. public $y_tick_inc = ''; // Set num_y_ticks or y_tick_inc, not both.
  123. public $skip_top_tick = FALSE;
  124. public $skip_bottom_tick = FALSE;
  125. public $skip_left_tick = FALSE;
  126. public $skip_right_tick = FALSE;
  127. //Grid Formatting
  128. public $draw_x_grid = FALSE;
  129. public $draw_y_grid = TRUE;
  130. public $dashed_grid = TRUE;
  131. public $grid_at_foreground = FALSE; // Chooses whether to draw the grid below or above the graph
  132. //Colors and styles (all colors can be array (R,G,B) or named color)
  133. public $color_array = 'small'; // 'small', 'large' or array (define your own colors)
  134. // See rgb.inc.php and SetRGBArray()
  135. public $i_border = array(194, 194, 194);
  136. public $plot_bg_color = 'white';
  137. public $bg_color = 'white';
  138. public $label_color = 'black';
  139. public $text_color = 'black';
  140. public $grid_color = 'black';
  141. public $light_grid_color = 'gray';
  142. public $tick_color = 'black';
  143. public $title_color = 'black';
  144. public $default_colors = array( // The default colors for data and error bars
  145. 'SkyBlue', 'green', 'orange', 'blue', 'red', 'DarkGreen', 'purple', 'peru',
  146. 'cyan', 'salmon', 'SlateBlue', 'YellowGreen', 'magenta', 'aquamarine1', 'gold', 'violet');
  147. // data_colors and error_bar_colors are initialized to default_colors by SetDefaultStyles.
  148. // public $data_colors; // Data colors
  149. // public $error_bar_colors; // Error bar colors
  150. // data_border_colors is initialized to black by SetDefaultStyles.
  151. // public $data_border_colors; // Data border colors
  152. public $line_widths = 1; // single value or array
  153. public $line_styles = array('solid', 'solid', 'dashed'); // single value or array
  154. public $dashed_style = '2-4'; // colored dots-transparent dots
  155. public $point_sizes = array(6); // Array of sizes for points. See CheckPointParams()
  156. public $point_shapes = array( // Array of point shapes. See SetPointShapes() and DrawDot()
  157. 'diamond', 'dot', 'delta', 'home', 'yield', 'box', 'circle', 'up', 'down', 'cross'
  158. );
  159. public $error_bar_size = 5; // right and left size of tee
  160. public $error_bar_shape = 'tee'; // 'tee' or 'line'
  161. public $error_bar_line_width = 1; // single value (or array TODO)
  162. public $plot_border_type = 'sides'; // left, sides, none, full
  163. public $image_border_type = 'none'; // 'raised', 'plain', 'none'
  164. public $shading = 5; // 0 for no shading, > 0 is size of shadows in pixels
  165. public $draw_plot_area_background = FALSE;
  166. public $draw_broken_lines = FALSE; // Tells not to draw lines for missing Y data.
  167. //Miscellaneous
  168. public $callbacks = array( // Valid callback reasons (see SetCallBack)
  169. 'draw_setup' => NULL,
  170. 'draw_image_background' => NULL,
  171. 'draw_plotarea_background' => NULL,
  172. 'draw_titles' => NULL,
  173. 'draw_axes' => NULL,
  174. 'draw_graph' => NULL,
  175. 'draw_border' => NULL,
  176. 'draw_legend' => NULL,
  177. 'draw_all' => NULL,
  178. 'debug_textbox' => NULL, // For testing/debugging text box alignment
  179. 'debug_scale' => NULL, // For testing/debugging scale setup
  180. );
  181. //////////////////////////////////////////////////////
  182. //BEGIN CODE
  183. //////////////////////////////////////////////////////
  184. /*!
  185. * Constructor: Setup img resource, colors and size of the image, and font sizes.
  186. *
  187. * \param which_width int Image width in pixels.
  188. * \param which_height int Image height in pixels.
  189. * \param which_output_file string Filename for output.
  190. * \param which_input_file string Path to a file to be used as background.
  191. */
  192. function PHPlot($which_width=600, $which_height=400, $which_output_file=NULL, $which_input_file=NULL)
  193. {
  194. $this->SetRGBArray($this->color_array);
  195. if ($which_output_file)
  196. $this->SetOutputFile($which_output_file);
  197. if ($which_input_file)
  198. $this->SetInputFile($which_input_file);
  199. else {
  200. $this->image_width = $which_width;
  201. $this->image_height = $which_height;
  202. $this->img = ImageCreate($this->image_width, $this->image_height);
  203. if (! $this->img)
  204. return $this->PrintError('PHPlot(): Could not create image resource.');
  205. }
  206. $this->SetDefaultStyles();
  207. $this->SetDefaultFonts();
  208. }
  209. /*!
  210. * Reads an image file. Stores width and height, and returns the image
  211. * resource. On error, calls PrintError and returns False.
  212. * This is used by the constructor via SetInputFile, and by tile_img().
  213. */
  214. protected function GetImage($image_filename, &$width, &$height)
  215. {
  216. $error = '';
  217. $size = getimagesize($image_filename);
  218. if (!$size) {
  219. $error = "Unable to query image file $image_filename";
  220. } else {
  221. $image_type = $size[2];
  222. switch($image_type) {
  223. case IMAGETYPE_GIF:
  224. $img = @ ImageCreateFromGIF ($image_filename);
  225. break;
  226. case IMAGETYPE_PNG:
  227. $img = @ ImageCreateFromPNG ($image_filename);
  228. break;
  229. case IMAGETYPE_JPEG:
  230. $img = @ ImageCreateFromJPEG ($image_filename);
  231. break;
  232. default:
  233. $error = "Unknown image type ($image_type) for image file $image_filename";
  234. break;
  235. }
  236. }
  237. if (empty($error) && !$img) {
  238. # getimagesize is OK, but GD won't read it. Maybe unsupported format.
  239. $error = "Failed to read image file $image_filename";
  240. }
  241. if (!empty($error)) {
  242. return $this->PrintError("GetImage(): $error");
  243. }
  244. $width = $size[0];
  245. $height = $size[1];
  246. return $img;
  247. }
  248. /*!
  249. * Selects an input file to be used as background for the whole graph.
  250. * This resets the graph size to the image's size.
  251. * Note: This is used by the constructor. It is deprecated for direct use.
  252. */
  253. function SetInputFile($which_input_file)
  254. {
  255. $im = $this->GetImage($which_input_file, $this->image_width, $this->image_height);
  256. if (!$im)
  257. return FALSE; // GetImage already produced an error message.
  258. // Deallocate any resources previously allocated
  259. if (isset($this->img))
  260. imagedestroy($this->img);
  261. $this->img = $im;
  262. // Do not overwrite the input file with the background color.
  263. $this->background_done = TRUE;
  264. return TRUE;
  265. }
  266. /////////////////////////////////////////////
  267. ////////////// COLORS
  268. /////////////////////////////////////////////
  269. /*!
  270. * Returns an index to a color passed in as anything (string, hex, rgb)
  271. *
  272. * \param which_color * Color (can be '#AABBCC', 'Colorname', or array(r,g,b))
  273. * Returns a GD color index (integer >= 0), or NULL on error.
  274. */
  275. function SetIndexColor($which_color)
  276. {
  277. list ($r, $g, $b) = $this->SetRGBColor($which_color); //Translate to RGB
  278. if (!isset($r)) return NULL;
  279. return ImageColorResolve($this->img, $r, $g, $b);
  280. }
  281. /*!
  282. * Returns an index to a slightly darker color than the one requested.
  283. * Returns a GD color index (integer >= 0), or NULL on error.
  284. */
  285. protected function SetIndexDarkColor($which_color)
  286. {
  287. list ($r, $g, $b) = $this->SetRGBColor($which_color);
  288. if (!isset($r)) return NULL;
  289. $r = max(0, $r - 0x30);
  290. $g = max(0, $g - 0x30);
  291. $b = max(0, $b - 0x30);
  292. return ImageColorResolve($this->img, $r, $g, $b);
  293. }
  294. /*!
  295. * Sets/reverts all colors and styles to their defaults.
  296. */
  297. protected function SetDefaultStyles()
  298. {
  299. /* Some of the Set*() functions use default values when they get no parameters. */
  300. $this->SetDefaultDashedStyle($this->dashed_style);
  301. $this->SetImageBorderColor($this->i_border);
  302. $this->SetPlotBgColor($this->plot_bg_color);
  303. $this->SetBackgroundColor($this->bg_color);
  304. $this->SetLabelColor($this->label_color);
  305. $this->SetTextColor($this->text_color);
  306. $this->SetGridColor($this->grid_color);
  307. $this->SetLightGridColor($this->light_grid_color);
  308. $this->SetTickColor($this->tick_color);
  309. $this->SetTitleColor($this->title_color);
  310. $this->SetDataColors();
  311. $this->SetErrorBarColors();
  312. $this->SetDataBorderColors();
  313. return TRUE;
  314. }
  315. /*
  316. *
  317. */
  318. function SetBackgroundColor($which_color)
  319. {
  320. $this->bg_color= $which_color;
  321. $this->ndx_bg_color= $this->SetIndexColor($this->bg_color);
  322. return isset($this->ndx_bg_color);
  323. }
  324. /*
  325. *
  326. */
  327. function SetPlotBgColor($which_color)
  328. {
  329. $this->plot_bg_color= $which_color;
  330. $this->ndx_plot_bg_color= $this->SetIndexColor($this->plot_bg_color);
  331. return isset($this->ndx_plot_bg_color);
  332. }
  333. /*
  334. *
  335. */
  336. function SetTitleColor($which_color)
  337. {
  338. $this->title_color= $which_color;
  339. $this->ndx_title_color= $this->SetIndexColor($this->title_color);
  340. return isset($this->ndx_title_color);
  341. }
  342. /*
  343. *
  344. */
  345. function SetTickColor ($which_color)
  346. {
  347. $this->tick_color= $which_color;
  348. $this->ndx_tick_color= $this->SetIndexColor($this->tick_color);
  349. return isset($this->ndx_tick_color);
  350. }
  351. /*
  352. * Do not use. Use SetTitleColor instead.
  353. */
  354. function SetLabelColor ($which_color)
  355. {
  356. $this->label_color = $which_color;
  357. $this->ndx_title_color= $this->SetIndexColor($this->label_color);
  358. return isset($this->ndx_title_color);
  359. }
  360. /*
  361. *
  362. */
  363. function SetTextColor ($which_color)
  364. {
  365. $this->text_color= $which_color;
  366. $this->ndx_text_color= $this->SetIndexColor($this->text_color);
  367. return isset($this->ndx_text_color);
  368. }
  369. /*
  370. *
  371. */
  372. function SetLightGridColor ($which_color)
  373. {
  374. $this->light_grid_color= $which_color;
  375. $this->ndx_light_grid_color= $this->SetIndexColor($this->light_grid_color);
  376. return isset($this->ndx_light_grid_color);
  377. }
  378. /*
  379. *
  380. */
  381. function SetGridColor ($which_color)
  382. {
  383. $this->grid_color = $which_color;
  384. $this->ndx_grid_color= $this->SetIndexColor($this->grid_color);
  385. return isset($this->ndx_grid_color);
  386. }
  387. /*
  388. *
  389. */
  390. function SetImageBorderColor($which_color)
  391. {
  392. $this->i_border = $which_color;
  393. $this->ndx_i_border = $this->SetIndexColor($this->i_border);
  394. $this->ndx_i_border_dark = $this->SetIndexDarkColor($this->i_border);
  395. return isset($this->ndx_i_border);
  396. }
  397. /*
  398. *
  399. */
  400. function SetTransparentColor($which_color)
  401. {
  402. $ndx = $this->SetIndexColor($which_color);
  403. if (!isset($ndx))
  404. return FALSE;
  405. ImageColorTransparent($this->img, $ndx);
  406. return TRUE;
  407. }
  408. /*!
  409. * Sets the array of colors to be used. It can be user defined, a small predefined one
  410. * or a large one included from 'rgb.inc.php'.
  411. *
  412. * \param which_color_array If an array, the used as color array. If a string can
  413. * be one of 'small' or 'large'.
  414. */
  415. function SetRGBArray ($which_color_array)
  416. {
  417. if ( is_array($which_color_array) ) { // User defined array
  418. $this->rgb_array = $which_color_array;
  419. return TRUE;
  420. } elseif ($which_color_array == 'small') { // Small predefined color array
  421. $this->rgb_array = array(
  422. 'white' => array(255, 255, 255),
  423. 'snow' => array(255, 250, 250),
  424. 'PeachPuff' => array(255, 218, 185),
  425. 'ivory' => array(255, 255, 240),
  426. 'lavender' => array(230, 230, 250),
  427. 'black' => array( 0, 0, 0),
  428. 'DimGrey' => array(105, 105, 105),
  429. 'gray' => array(190, 190, 190),
  430. 'grey' => array(190, 190, 190),
  431. 'navy' => array( 0, 0, 128),
  432. 'SlateBlue' => array(106, 90, 205),
  433. 'blue' => array( 0, 0, 255),
  434. 'SkyBlue' => array(135, 206, 235),
  435. 'cyan' => array( 0, 255, 255),
  436. 'DarkGreen' => array( 0, 100, 0),
  437. 'green' => array( 0, 255, 0),
  438. 'YellowGreen' => array(154, 205, 50),
  439. 'yellow' => array(255, 255, 0),
  440. 'orange' => array(255, 165, 0),
  441. 'gold' => array(255, 215, 0),
  442. 'peru' => array(205, 133, 63),
  443. 'beige' => array(245, 245, 220),
  444. 'wheat' => array(245, 222, 179),
  445. 'tan' => array(210, 180, 140),
  446. 'brown' => array(165, 42, 42),
  447. 'salmon' => array(250, 128, 114),
  448. 'red' => array(255, 0, 0),
  449. 'pink' => array(255, 192, 203),
  450. 'maroon' => array(176, 48, 96),
  451. 'magenta' => array(255, 0, 255),
  452. 'violet' => array(238, 130, 238),
  453. 'plum' => array(221, 160, 221),
  454. 'orchid' => array(218, 112, 214),
  455. 'purple' => array(160, 32, 240),
  456. 'azure1' => array(240, 255, 255),
  457. 'aquamarine1' => array(127, 255, 212)
  458. );
  459. return TRUE;
  460. } elseif ($which_color_array === 'large') { // Large color array
  461. if (!@include('rgb.inc.php')) {
  462. return $this->PrintError("SetRGBArray(): Large color map could not be loaded\n"
  463. . "from 'rgb.inc.php'.");
  464. }
  465. $this->rgb_array = $ColorArray;
  466. } else { // Default to black and white only.
  467. $this->rgb_array = array('white' => array(255, 255, 255), 'black' => array(0, 0, 0));
  468. }
  469. return TRUE;
  470. }
  471. /*!
  472. * Returns an array in R, G, B format 0-255
  473. *
  474. * \param color_asked array(R,G,B) or string (named color or '#AABBCC')
  475. * Note: This method should be 'protected', but is called from test script(s).
  476. */
  477. function SetRGBColor($color_asked)
  478. {
  479. if (empty($color_asked)) {
  480. $ret_val = array(0, 0, 0);
  481. } elseif (count($color_asked) == 3 ) { // already array of 3 rgb
  482. $ret_val = $color_asked;
  483. } elseif ($color_asked[0] == '#') { // Hex RGB notation #RRGGBB
  484. $ret_val = array(hexdec(substr($color_asked, 1, 2)),
  485. hexdec(substr($color_asked, 3, 2)),
  486. hexdec(substr($color_asked, 5, 2)));
  487. } elseif (isset($this->rgb_array[$color_asked])) { // Color by name
  488. $ret_val = $this->rgb_array[$color_asked];
  489. } else {
  490. return $this->PrintError("SetRGBColor(): Color '$color_asked' is not valid.");
  491. }
  492. return $ret_val;
  493. }
  494. /*!
  495. * Sets the colors for the data.
  496. * Cases are:
  497. * SetDataColors(array(...)) : Use the supplied array as the color map.
  498. * SetDataColors(colorname) : Use an array of just colorname as the color map.
  499. * SetDataColors() or SetDataColors(NULL) : Load default color map if no color map is already set.
  500. * SetDataColors('') or SetDataColors(False) : Load default color map (even if one is already set).
  501. */
  502. function SetDataColors($which_data = NULL, $which_border = NULL)
  503. {
  504. if (is_array($which_data)) {
  505. $this->data_colors = $which_data; // Use supplied array
  506. } elseif (!empty($which_data)) {
  507. $this->data_colors = array($which_data); // Use supplied single color
  508. } elseif (empty($this->data_colors) || !is_null($which_data)) {
  509. $this->data_colors = $this->default_colors; // Use default color array
  510. } // Else do nothing: which_data is NULL or missing and a color array is already set.
  511. $i = 0;
  512. foreach ($this->data_colors as $col) {
  513. $ndx = $this->SetIndexColor($col);
  514. if (!isset($ndx))
  515. return FALSE;
  516. $this->ndx_data_colors[$i] = $ndx;
  517. $this->ndx_data_dark_colors[$i] = $this->SetIndexDarkColor($col);
  518. $i++;
  519. }
  520. // For past compatibility:
  521. return $this->SetDataBorderColors($which_border);
  522. } // function SetDataColors()
  523. /*!
  524. * Set the colors for the bars and stacked bars outlines.
  525. * Argument usage is similar to SetDataColors(), except the default is just black.
  526. */
  527. function SetDataBorderColors($which_br = NULL)
  528. {
  529. if (is_array($which_br)) {
  530. $this->data_border_colors = $which_br; // Use supplied array
  531. } elseif (!empty($which_br)) {
  532. $this->data_border_colors = array($which_br); // Use supplied single color
  533. } elseif (empty($this->data_border_colors) || !is_null($which_br)) {
  534. $this->data_border_colors = array('black'); // Use default
  535. } // Else do nothing: which_br is NULL or missing and a color array is already set.
  536. $i = 0;
  537. foreach($this->data_border_colors as $col) {
  538. $ndx = $this->SetIndexColor($col);
  539. if (!isset($ndx))
  540. return FALSE;
  541. $this->ndx_data_border_colors[$i] = $ndx;
  542. $i++;
  543. }
  544. return TRUE;
  545. } // function SetDataBorderColors()
  546. /*!
  547. * Sets the colors for the data error bars.
  548. * Argument usage is the same as SetDataColors().
  549. */
  550. function SetErrorBarColors($which_err = NULL)
  551. {
  552. if (is_array($which_err)) {
  553. $this->error_bar_colors = $which_err; // Use supplied array
  554. } elseif (!empty($which_err)) {
  555. $this->error_bar_colors = array($which_err); // Use supplied single color
  556. } elseif (empty($this->error_bar_colors) || !is_null($which_err)) {
  557. $this->error_bar_colors = $this->default_colors; // Use default color array
  558. } // Else do nothing: which_err is NULL or missing and a color array is already set.
  559. $i = 0;
  560. foreach($this->error_bar_colors as $col) {
  561. $ndx = $this->SetIndexColor($col);
  562. if (!isset($ndx))
  563. return FALSE;
  564. $this->ndx_error_bar_colors[$i] = $ndx;
  565. $i++;
  566. }
  567. return TRUE;
  568. } // function SetErrorBarColors()
  569. /*!
  570. * Sets the default dashed style.
  571. * \param which_style A string specifying order of colored and transparent dots,
  572. * i.e: '4-3' means 4 colored, 3 transparent;
  573. * '2-3-1-2' means 2 colored, 3 transparent, 1 colored, 2 transparent.
  574. */
  575. function SetDefaultDashedStyle($which_style)
  576. {
  577. // String: "numcol-numtrans-numcol-numtrans..."
  578. $asked = explode('-', $which_style);
  579. if (count($asked) < 2) {
  580. return $this->PrintError("SetDefaultDashedStyle(): Wrong parameter '$which_style'.");
  581. }
  582. // Build the string to be eval()uated later by SetDashedStyle()
  583. $this->default_dashed_style = 'array( ';
  584. $t = 0;
  585. foreach($asked as $s) {
  586. if ($t % 2 == 0) {
  587. $this->default_dashed_style .= str_repeat('$which_ndxcol,', $s);
  588. } else {
  589. $this->default_dashed_style .= str_repeat('IMG_COLOR_TRANSPARENT,', $s);
  590. }
  591. $t++;
  592. }
  593. // Remove trailing comma and add closing parenthesis
  594. $this->default_dashed_style = substr($this->default_dashed_style, 0, -1);
  595. $this->default_dashed_style .= ')';
  596. return TRUE;
  597. }
  598. /*!
  599. * Sets the style before drawing a dashed line. Defaults to $this->default_dashed_style
  600. * \param which_ndxcol Color index to be used.
  601. */
  602. protected function SetDashedStyle($which_ndxcol)
  603. {
  604. // See SetDefaultDashedStyle() to understand this.
  605. eval ("\$style = $this->default_dashed_style;");
  606. return imagesetstyle($this->img, $style);
  607. }
  608. /*!
  609. * Sets line widths on a per-line basis.
  610. */
  611. function SetLineWidths($which_lw=NULL)
  612. {
  613. if (is_null($which_lw)) {
  614. // Do nothing, use default value.
  615. } else if (is_array($which_lw)) {
  616. // Did we get an array with line widths?
  617. $this->line_widths = $which_lw;
  618. } else {
  619. $this->line_widths = array($which_lw);
  620. }
  621. return TRUE;
  622. }
  623. /*!
  624. *
  625. */
  626. function SetLineStyles($which_ls=NULL)
  627. {
  628. if (is_null($which_ls)) {
  629. // Do nothing, use default value.
  630. } else if ( is_array($which_ls)) {
  631. // Did we get an array with line styles?
  632. $this->line_styles = $which_ls;
  633. } else {
  634. $this->line_styles = ($which_ls) ? array($which_ls) : array('solid');
  635. }
  636. return TRUE;
  637. }
  638. /////////////////////////////////////////////
  639. ////////////// TEXT and FONTS
  640. /////////////////////////////////////////////
  641. /*!
  642. * Controls the line spacing of multi-line labels.
  643. * For GD text, this is the number of pixels between lines.
  644. * For TTF text, it controls line spacing in proportion to the normal
  645. * spacing defined by the font.
  646. */
  647. function SetLineSpacing($which_spc)
  648. {
  649. $this->line_spacing = $which_spc;
  650. return TRUE;
  651. }
  652. /*!
  653. * Select the default font type to use.
  654. * $which_ttf : True to default to TrueType, False to default to GD (fixed) fonts.
  655. * This also resets all font settings to the defaults.
  656. */
  657. function SetUseTTF($which_ttf)
  658. {
  659. $this->use_ttf = $which_ttf;
  660. return $this->SetDefaultFonts();
  661. }
  662. /*!
  663. * Sets the directory name to look into for TrueType fonts.
  664. */
  665. function SetTTFPath($which_path)
  666. {
  667. // Maybe someone needs really dynamic config. He'll need this:
  668. // clearstatcache();
  669. if (is_dir($which_path) && is_readable($which_path)) {
  670. $this->ttf_path = $which_path;
  671. return TRUE;
  672. }
  673. return $this->PrintError("SetTTFPath(): $which_path is not a valid path.");
  674. }
  675. /*!
  676. * Sets the default TrueType font and updates all fonts to that.
  677. * The default font might be a full path, or relative to the TTFPath,
  678. * so let SetFont check that it exists.
  679. * Side effects: Enables use of TrueType fonts as the default font type,
  680. * and resets all font settings.
  681. */
  682. function SetDefaultTTFont($which_font)
  683. {
  684. $this->default_ttfont = $which_font;
  685. return $this->SetUseTTF(TRUE);
  686. }
  687. /*!
  688. * Sets fonts to their defaults
  689. */
  690. protected function SetDefaultFonts()
  691. {
  692. // TTF:
  693. if ($this->use_ttf) {
  694. return $this->SetFont('generic', '', 8)
  695. && $this->SetFont('title', '', 14)
  696. && $this->SetFont('legend', '', 8)
  697. && $this->SetFont('x_label', '', 6)
  698. && $this->SetFont('y_label', '', 6)
  699. && $this->SetFont('x_title', '', 10)
  700. && $this->SetFont('y_title', '', 10);
  701. }
  702. // Fixed GD Fonts:
  703. return $this->SetFont('generic', 2)
  704. && $this->SetFont('title', 5)
  705. && $this->SetFont('legend', 2)
  706. && $this->SetFont('x_label', 1)
  707. && $this->SetFont('y_label', 1)
  708. && $this->SetFont('x_title', 3)
  709. && $this->SetFont('y_title', 3);
  710. }
  711. /*
  712. * Select a fixed (GD) font for an element.
  713. * This allows using a fixed font, even with SetUseTTF(True).
  714. * $which_elem : The element whose font is to be changed.
  715. * One of: title legend generic x_label y_label x_title y_title
  716. * $which_font : A GD font number 1-5
  717. * $which_spacing (optional) : Line spacing factor
  718. */
  719. function SetFontGD($which_elem, $which_font, $which_spacing = NULL)
  720. {
  721. if ($which_font < 1 || 5 < $which_font) {
  722. return $this->PrintError(__FUNCTION__ . ': Font size must be 1, 2, 3, 4 or 5');
  723. }
  724. if (!$this->CheckOption($which_elem,
  725. 'generic, title, legend, x_label, y_label, x_title, y_title',
  726. __FUNCTION__)) {
  727. return FALSE;
  728. }
  729. # Store the font parameters: name/size, char cell height and width.
  730. $this->fonts[$which_elem] = array('ttf' => FALSE,
  731. 'font' => $which_font,
  732. 'height' => ImageFontHeight($which_font),
  733. 'width' => ImageFontWidth($which_font),
  734. 'line_spacing' => $which_spacing);
  735. return TRUE;
  736. }
  737. /*
  738. * Select a TrueType font for an element.
  739. * This allows using a TrueType font, even with SetUseTTF(False).
  740. * $which_elem : The element whose font is to be changed.
  741. * One of: title legend generic x_label y_label x_title y_title
  742. * $which_font : A TrueType font filename or pathname.
  743. * $which_size : Font point size.
  744. * $which_spacing (optional) : Line spacing factor
  745. */
  746. function SetFontTTF($which_elem, $which_font, $which_size = 12, $which_spacing = NULL)
  747. {
  748. if (!$this->CheckOption($which_elem,
  749. 'generic, title, legend, x_label, y_label, x_title, y_title',
  750. __FUNCTION__)) {
  751. return FALSE;
  752. }
  753. # Empty font name means use the default font.
  754. if (empty($which_font))
  755. $which_font = $this->default_ttfont;
  756. $path = $which_font;
  757. # First try the font name directly, if not then try with path.
  758. if (!is_file($path) || !is_readable($path)) {
  759. $path = $this->ttf_path . DIRECTORY_SEPARATOR . $which_font;
  760. if (!is_file($path) || !is_readable($path)) {
  761. return $this->PrintError(__FUNCTION__ . ": Can't find TrueType font $which_font");
  762. }
  763. }
  764. # Calculate the font height and inherent line spacing. TrueType fonts have this information
  765. # internally, but PHP/GD has no way to directly access it. So get the bounding box size of
  766. # an upper-case character without descenders, and the baseline-to-baseline height.
  767. # Note: In practice, $which_size = $height, maybe +/-1 . But which_size is in points,
  768. # and height is in pixels, and someday GD may be able to tell the difference.
  769. # The character width is saved too, but not used by the normal text drawing routines - it
  770. # isn't necessarily a fixed-space font. It is used in DrawLegend.
  771. $bbox = ImageTTFBBox($which_size, 0, $path, "E");
  772. $height = $bbox[1] - $bbox[5];
  773. $width = $bbox[2] - $bbox[0];
  774. $bbox = ImageTTFBBox($which_size, 0, $path, "E\nE");
  775. $spacing = $bbox[1] - $bbox[5] - 2 * $height;
  776. # Store the font parameters:
  777. $this->fonts[$which_elem] = array('ttf' => TRUE,
  778. 'font' => $path,
  779. 'size' => $which_size,
  780. 'height' => $height,
  781. 'width' => $width,
  782. 'spacing' => $spacing,
  783. 'line_spacing' => $which_spacing);
  784. return TRUE;
  785. }
  786. /*
  787. * Select Fixed/TrueType font for an element. Which type of font is
  788. * selected depends on the $use_ttf class variable (see SetUseTTF()).
  789. * Before PHPlot supported mixing font types, only this function and
  790. * SetUseTTF were available to select an overall font type, but now
  791. * SetFontGD() and SetFontTTF() can be used for mixing font types.
  792. * $which_elem : The element whose font is to be changed.
  793. * One of: title legend generic x_label y_label x_title y_title
  794. * $which_font : A number 1-5 for fixed fonts, or a TrueType font.
  795. * $which_size : Ignored for Fixed fonts, point size for TrueType.
  796. * $which_spacing (optional) : Line spacing factor
  797. */
  798. function SetFont($which_elem, $which_font, $which_size = 12, $line_spacing = NULL)
  799. {
  800. if ($this->use_ttf)
  801. return $this->SetFontTTF($which_elem, $which_font, $which_size, $line_spacing);
  802. return $this->SetFontGD($which_elem, $which_font, $line_spacing);
  803. }
  804. /*
  805. * Return the inter-line spacing for a font.
  806. * This is an internal function, used by ProcessText* and DrawLegend.
  807. * $font : A font array variable.
  808. * Returns: Spacing, in pixels, between text lines.
  809. */
  810. protected function GetLineSpacing($font)
  811. {
  812. # Use the per-font line spacing preference, if set, else the global value:
  813. if (isset($font['line_spacing']))
  814. $line_spacing = $font['line_spacing'];
  815. else
  816. $line_spacing = $this->line_spacing;
  817. # For GD fonts, that is the spacing in pixels.
  818. # For TTF, adjust based on the 'natural' font spacing (see SetFontTTF):
  819. if ($font['ttf']) {
  820. $line_spacing = (int)($line_spacing * $font['spacing'] / 6.0);
  821. }
  822. return $line_spacing;
  823. }
  824. /*!
  825. * Text drawing and sizing functions:
  826. * ProcessText is meant for use only by DrawText and SizeText.
  827. * ProcessText(True, ...) - Draw a block of text
  828. * ProcessText(False, ...) - Just return ($width, $height) of
  829. * the orthogonal bounding box containing the text.
  830. * ProcessText is further split into separate functions for GD and TTF
  831. * text, due to the size of the code.
  832. *
  833. * Horizontal and vertical alignment are relative to the drawing. That is:
  834. * vertical text (90 deg) gets centered along Y position with
  835. * v_align = 'center', and adjusted to the right of X position with
  836. * h_align = 'right'. Another way to look at this is to say
  837. * that text rotation happens first, then alignment.
  838. *
  839. * Original multiple lines code submitted by Remi Ricard.
  840. * Original vertical code submitted by Marlin Viss.
  841. *
  842. * Text routines rewritten by ljb to fix alignment and position problems.
  843. * Here is my explanation and notes. More information and pictures will be
  844. * placed in the PHPlot Reference Manual.
  845. *
  846. * + Process TTF text one line at a time, not as a block. (See below)
  847. * + Flipped top vs bottom vertical alignment. The usual interpretation
  848. * is: bottom align means bottom of the text is at the specified Y
  849. * coordinate. For some reason, PHPlot did left/right the correct way,
  850. * but had top/bottom reversed. I fixed it, and left the default valign
  851. * argument as bottom, but the meaning of the default value changed.
  852. *
  853. * For GD font text, only single-line text is handled by GD, and the
  854. * basepoint is the upper left corner of each text line.
  855. * For TTF text, multi-line text could be handled by GD, with the text
  856. * basepoint at the lower left corner of the first line of text.
  857. * (Behavior of TTF drawing routines on multi-line text is not documented.)
  858. * But you cannot do left/center/right alignment on each line that way,
  859. * or proper line spacing.
  860. * Therefore, for either text type, we have to break up the text into
  861. * lines and position each line independently.
  862. *
  863. * There are 9 alignment modes: Horizontal = left, center, or right, and
  864. * Vertical = top, center, or bottom. Alignment is interpreted relative to
  865. * the image, not as the text is read. This makes sense when you consider
  866. * for example X axis labels. They need to be centered below the marks
  867. * (center, top alignment) regardless of the text angle.
  868. * 'Bottom' alignment really means baseline alignment.
  869. *
  870. * GD font text is supported (by libgd) at 0 degrees and 90 degrees only.
  871. * Multi-line or single line text works with any of the 9 alignment modes.
  872. *
  873. * TTF text can be at any angle. The 9 alignment modes work for all angles,
  874. * but the results might not be what you expect for multi-line text. See
  875. * the PHPlot Reference Manual for pictures and details. In short, alignment
  876. * applies to the orthogonal (aligned with X and Y axes) bounding box that
  877. * contains the text, and to each line in the multi-line text box. Since
  878. * alignment is relative to the image, 45 degree multi-line text aligns
  879. * differently from 46 degree text.
  880. *
  881. * Note that PHPlot allows multi-line text for the 3 titles, and they
  882. * are only drawn at 0 degrees (main and X titles) or 90 degrees (Y title).
  883. * Data labels can also be multi-line, and they can be drawn at any angle.
  884. * -ljb 2007-11-03
  885. *
  886. */
  887. /*
  888. * ProcessTextGD() - Draw or size GD fixed-font text.
  889. * This is intended for use only by ProcessText().
  890. * $draw_it : True to draw the text, False to just return the orthogonal width and height.
  891. * $font : PHPlot font array (with 'ttf' = False) - see SetFontGD()
  892. * $angle : Text angle in degrees. GD only supports 0 and 90. We treat >= 45 as 90, else 0.
  893. * $x, $y : Reference point for the text (ignored if !$draw_it)
  894. * $color : GD color index to use for drawing the text (ignored if !$draw_it)
  895. * $text : The text to draw or size. Put a newline between lines.
  896. * $h_factor : Horizontal alignment factor: 0(left), .5(center), or 1(right) (ignored if !$draw_it)
  897. * $v_factor : Vertical alignment factor: 0(top), .5(center), or 1(bottom) (ignored if !$draw_it)
  898. * Returns: True, if drawing text, or an array of ($width, $height) if not.
  899. */
  900. protected function ProcessTextGD($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor)
  901. {
  902. # Extract font parameters:
  903. $font_number = $font['font'];
  904. $font_width = $font['width'];
  905. $font_height = $font['height'];
  906. $line_spacing = $this->GetLineSpacing($font);
  907. # Break up the text into lines, trim whitespace, find longest line.
  908. # Save the lines and length for drawing below.
  909. $longest = 0;
  910. foreach (explode("\n", $text) as $each_line) {
  911. $lines[] = $line = trim($each_line);
  912. $line_lens[] = $line_len = strlen($line);
  913. if ($line_len > $longest) $longest = $line_len;
  914. }
  915. $n_lines = count($lines);
  916. # Width, height are based on font size and longest line, line count respectively.
  917. # These are relative to the text angle.
  918. $total_width = $longest * $font_width;
  919. $total_height = $n_lines * $font_height + ($n_lines - 1) * $line_spacing;
  920. if (!$draw_it) {
  921. if ($angle < 45) return array($total_width, $total_height);
  922. return array($total_height, $total_width);
  923. }
  924. $interline_step = $font_height + $line_spacing; // Line-to-line step
  925. if ($angle >= 45) {
  926. // Vertical text (90 degrees):
  927. // (Remember the alignment convention with vertical text)
  928. // For 90 degree text, alignment factors change like this:
  929. $temp = $v_factor;
  930. $v_factor = $h_factor;
  931. $h_factor = 1 - $temp;
  932. $draw_func = 'ImageStringUp';
  933. // Rotation matrix "R" for 90 degrees (with Y pointing down):
  934. $r00 = 0; $r01 = 1;
  935. $r10 = -1; $r11 = 0;
  936. } else {
  937. // Horizontal text (0 degrees):
  938. $draw_func = 'ImageString';
  939. // Rotation matrix "R" for 0 degrees:
  940. $r00 = 1; $r01 = 0;
  941. $r10 = 0; $r11 = 1;
  942. }
  943. // Adjust for vertical alignment (horizontal text) or horizontal alignment (vertical text):
  944. $factor = (int)($total_height * $v_factor);
  945. $xpos = $x - $r01 * $factor;
  946. $ypos = $y - $r11 * $factor;
  947. # Debug callback provides the bounding box:
  948. if ($this->GetCallback('debug_textbox')) {
  949. if ($angle >= 45) {
  950. $bbox_width = $total_height;
  951. $bbox_height = $total_width;
  952. $px = $xpos;
  953. $py = $ypos - (1 - $h_factor) * $total_width;
  954. } else {
  955. $bbox_width = $total_width;
  956. $bbox_height = $total_height;
  957. $px = $xpos - $h_factor * $total_width;
  958. $py = $ypos;
  959. }
  960. $this->DoCallback('debug_textbox', $px, $py, $bbox_width, $bbox_height);
  961. }
  962. for ($i = 0; $i < $n_lines; $i++) {
  963. // Adjust for alignment of this line within the text block:
  964. $factor = (int)($line_lens[$i] * $font_width * $h_factor);
  965. $x = $xpos - $r00 * $factor;
  966. $y = $ypos - $r10 * $factor;
  967. // Call ImageString or ImageStringUp:
  968. $draw_func($this->img, $font_number, $x, $y, $lines[$i], $color);
  969. // Step to the next line of text. This is a rotation of (x=0, y=interline_spacing)
  970. $xpos += $r01 * $interline_step;
  971. $ypos += $r11 * $interline_step;
  972. }
  973. return TRUE;
  974. }
  975. /*
  976. * ProcessTextTTF() - Draw or size TTF text.
  977. * This is intended for use only by ProcessText().
  978. * $draw_it : True to draw the text, False to just return the orthogonal width and height.
  979. * $font : PHPlot font array (with 'ttf' = True) - see SetFontTTF()
  980. * $angle : Text angle in degrees.
  981. * $x, $y : Reference point for the text (ignored if !$draw_it)
  982. * $color : GD color index to use for drawing the text (ignored if !$draw_it)
  983. * $text : The text to draw or size. Put a newline between lines.
  984. * $h_factor : Horizontal alignment factor: 0(left), .5(center), or 1(right) (ignored if !$draw_it)
  985. * $v_factor : Vertical alignment factor: 0(top), .5(center), or 1(bottom) (ignored if !$draw_it)
  986. * Returns: True, if drawing text, or an array of ($width, $height) if not.
  987. */
  988. protected function ProcessTextTTF($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor)
  989. {
  990. # Extract font parameters (see SetFontTTF):
  991. $font_file = $font['font'];
  992. $font_size = $font['size'];
  993. $font_height = $font['height'];
  994. $line_spacing = $this->GetLineSpacing($font);
  995. # Break up the text into lines, trim whitespace.
  996. # Calculate the total width and height of the text box at 0 degrees.
  997. # Save the trimmed lines and their widths for later when drawing.
  998. # To get uniform spacing, don't use the actual line heights.
  999. # Total height = Font-specific line heights plus inter-line spacing.
  1000. # Total width = width of widest line.
  1001. # Last Line Descent is the offset from the bottom to the text baseline.
  1002. # Note: For some reason, ImageTTFBBox uses (-1,-1) as the reference point.
  1003. # So 1+bbox[1] is the baseline to bottom distance.
  1004. $total_width = 0;
  1005. $lastline_descent = 0;
  1006. foreach (explode("\n", $text) as $each_line) {
  1007. $lines[] = $line = trim($each_line);
  1008. $bbox = ImageTTFBBox($font_size, 0, $font_file, $line);
  1009. $line_widths[] = $width = $bbox[2] - $bbox[0];
  1010. if ($width > $total_width) $total_width = $width;
  1011. $lastline_descent = 1 + $bbox[1];
  1012. }
  1013. $n_lines = count($lines);
  1014. $total_height = $n_lines * $font_height + ($n_lines - 1) * $line_spacing;
  1015. # Calculate the rotation matrix for the text's angle. Remember that GD points Y down,
  1016. # so the sin() terms change sign.
  1017. $theta = deg2rad($angle);
  1018. $cos_t = cos($theta);
  1019. $sin_t = sin($theta);
  1020. $r00 = $cos_t; $r01 = $sin_t;
  1021. $r10 = -$sin_t; $r11 = $cos_t;
  1022. # Make a bounding box of the right size, with upper left corner at (0,0).
  1023. # By convention, the point order is: LL, LR, UR, UL.
  1024. # Note this is still working with the text at 0 degrees.
  1025. # When sizing text (SizeText), use the overall size with descenders.
  1026. # This tells the caller how much room to leave for the text.
  1027. # When drawing text (DrawText), use the size without descenders - that
  1028. # is, down to the baseline. This is for accurate positioning.
  1029. $b[0] = 0;
  1030. if ($draw_it) {
  1031. $b[1] = $total_height;
  1032. } else {
  1033. $b[1] = $total_height + $lastline_descent;
  1034. }
  1035. $b[2] = $total_width; $b[3] = $b[1];
  1036. $b[4] = $total_width; $b[5] = 0;
  1037. $b[6] = 0; $b[7] = 0;
  1038. # Rotate the bounding box, then offset to the reference point:
  1039. for ($i = 0; $i < 8; $i += 2) {
  1040. $x_b = $b[$i];
  1041. $y_b = $b[$i+1];
  1042. $c[$i] = $x + $r00 * $x_b + $r01 * $y_b;
  1043. $c[$i+1] = $y + $r10 * $x_b + $r11 * $y_b;
  1044. }
  1045. # Get an orthogonal (aligned with X and Y axes) bounding box around it, by
  1046. # finding the min and max X and Y:
  1047. $bbox_ref_x = $bbox_max_x = $c[0];
  1048. $bbox_ref_y = $bbox_max_y = $c[1];
  1049. for ($i = 2; $i < 8; $i += 2) {
  1050. $x_b = $c[$i];
  1051. if ($x_b < $bbox_ref_x) $bbox_ref_x = $x_b;
  1052. elseif ($bbox_max_x < $x_b) $bbox_max_x = $x_b;
  1053. $y_b = $c[$i+1];
  1054. if ($y_b < $bbox_ref_y) $bbox_ref_y = $y_b;
  1055. elseif ($bbox_max_y < $y_b) $bbox_max_y = $y_b;
  1056. }
  1057. $bbox_width = $bbox_max_x - $bbox_ref_x;
  1058. $bbox_height = $bbox_max_y - $bbox_ref_y;
  1059. if (!$draw_it) {
  1060. # Return the bounding box, rounded up (so it always contains the text):
  1061. return array((int)ceil($bbox_width), (int)ceil($bbox_height));
  1062. }
  1063. $interline_step = $font_height + $line_spacing; // Line-to-line step
  1064. # Calculate the offsets from the supplied reference point to the
  1065. # upper-left corner of the text.
  1066. # Start at the reference point at the upper left corner of the bounding
  1067. # box (bbox_ref_x, bbox_ref_y) then adjust it for the 9 point alignment.
  1068. # h,v_factor are 0,0 for top,left, .5,.5 for center,center, 1,1 for bottom,right.
  1069. # $off_x = $bbox_ref_x + $bbox_width * $h_factor - $x;
  1070. # $off_y = $bbox_ref_y + $bbox_height * $v_factor - $y;
  1071. # Then use that offset to calculate back to the supplied reference point x, y
  1072. # to get the text base point.
  1073. # $qx = $x - $off_x;
  1074. # $qy = $y - $off_y;
  1075. # Reduces to:
  1076. $qx = 2 * $x - $bbox_ref_x - $bbox_width * $h_factor;
  1077. $qy = 2 * $y - $bbox_ref_y - $bbox_height * $v_factor;
  1078. # Check for debug callback. Don't calculate bounding box unless it is wanted.
  1079. if ($this->GetCallback('debug_textbox')) {
  1080. # Calculate the orthogonal bounding box coordinates for debug testing.
  1081. # qx, qy is upper left corner relative to the text.
  1082. # Calculate px,py: upper left corner (absolute) of the bounding box.
  1083. # There are 4 equation sets for this, depending on the quadrant:
  1084. if ($sin_t > 0) {
  1085. if ($cos_t > 0) {
  1086. # Quadrant: 0d - 90d:
  1087. $px = $qx; $py = $qy - $total_width * $sin_t;
  1088. } else {
  1089. # Quadrant: 90d - 180d:
  1090. $px = $qx + $total_width * $cos_t; $py = $qy - $bbox_height;
  1091. }
  1092. } else {
  1093. if ($cos_t < 0) {
  1094. # Quadrant: 180d - 270d:
  1095. $px = $qx - $bbox_width; $py = $qy + $total_height * $cos_t;
  1096. } else {
  1097. # Quadrant: 270d - 360d:
  1098. $px = $qx + $total_height * $sin_t; $py = $qy;
  1099. }
  1100. }
  1101. $this->DoCallback('debug_textbox', $px, $py, $bbox_width, $bbox_height);
  1102. }
  1103. # Since alignment is applied after rotation, which parameter is used
  1104. # to control alignment of each line within the text box varies with
  1105. # the angle.
  1106. # Angle (degrees): Line alignment controlled by:
  1107. # -45 < angle <= 45 h_align
  1108. # 45 < angle <= 135 reversed v_align
  1109. # 135 < angle <= 225 reversed h_align
  1110. # 225 < angle <= 315 v_align
  1111. if ($cos_t >= $sin_t) {
  1112. if ($cos_t >= -$sin_t) $line_align_factor = $h_factor;
  1113. else $line_align_factor = $v_factor;
  1114. } else {
  1115. if ($cos_t >= -$sin_t) $line_align_factor = 1-$v_factor;
  1116. else $line_align_factor = 1-$h_factor;
  1117. }
  1118. # Now we have the start point, spacing and in-line alignment factor.
  1119. # We are finally ready to start drawing the text, line by line.
  1120. for ($i = 0; $i < $n_lines; $i++) {
  1121. # For drawing TTF text, the reference point is the left edge of the
  1122. # text baseline (not the lower left corner of the bounding box).
  1123. # The following also adjusts for horizontal (relative to
  1124. # the text) alignment of the current line within the box.
  1125. # What is happening is rotation of this vector by the text angle:
  1126. # (x = (total_width - line_width) * factor, y = font_height)
  1127. $width_factor = ($total_width - $line_widths[$i]) * $line_align_factor;
  1128. $rx = $qx + $r00 * $width_factor + $r01 * $font_height;
  1129. $ry = $qy + $r10 * $width_factor + $r11 * $font_height;
  1130. # Finally, draw the text:
  1131. ImageTTFText($this->img, $font_size, $angle, $rx, $ry, $color, $font_file, $lines[$i]);
  1132. # Step to position of next line.
  1133. # This is a rotation of (x=0,y=height+line_spacing) by $angle:
  1134. $qx += $r01 * $interline_step;
  1135. $qy += $r11 * $interline_step;
  1136. }
  1137. return True;
  1138. }
  1139. /*
  1140. * ProcessText() - Wrapper for ProcessTextTTF() and ProcessTextGD(). See notes above.
  1141. * This is intended for use from within PHPlot only, and only by DrawText() and SizeText().
  1142. * $draw_it : True to draw the text, False to just return the orthogonal width and height.
  1143. * $font : PHPlot font array, or NULL or empty string to use 'generic'
  1144. * $angle : Text angle in degrees
  1145. * $x, $y : Reference point for the text (ignored if !$draw_it)
  1146. * $color : GD color index to use for drawing the text (ignored if !$draw_it)
  1147. * $text : The text to draw or size. Put a newline between lines.
  1148. * $halign : Horizontal alignment: left, center, or right (ignored if !$draw_it)
  1149. * $valign : Vertical alignment: top, center, or bottom (ignored if !$draw_it)
  1150. * Note: Alignment is relative to the image, not the text.
  1151. * Returns: True, if drawing text, or an array of ($width, $height) if not.
  1152. */
  1153. protected function ProcessText($draw_it, $font, $angle, $x, $y, $color, $text, $halign, $valign)
  1154. {
  1155. # Empty text case:
  1156. if ($text === '') {
  1157. if ($draw_it) return TRUE;
  1158. return array(0, 0);
  1159. }
  1160. # Calculate width and height offset factors using the alignment args:
  1161. if ($valign == 'top') $v_factor = 0;
  1162. elseif ($valign == 'center') $v_factor = 0.5;
  1163. else $v_factor = 1.0; # 'bottom'
  1164. if ($halign == 'left') $h_factor = 0;
  1165. elseif ($halign == 'center') $h_factor = 0.5;
  1166. else $h_factor = 1.0; # 'right'
  1167. # Apply a default font. This is mostly for external (callback) users.
  1168. if (empty($font)) $font = $this->fonts['generic'];
  1169. if ($font['ttf']) {
  1170. return $this->ProcessTextTTF($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor);
  1171. }
  1172. return $this->ProcessTextGD($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor);
  1173. }
  1174. /*
  1175. * Draws a block of text. See comments above before ProcessText().
  1176. * $which_font : PHPlot font array, or NULL or empty string to use 'generic'
  1177. * $which_angle : Text angle in degrees
  1178. * $which_xpos, $which_ypos: Reference point for the text
  1179. * $which_color : GD color index to use for drawing the text
  1180. * $which_text : The text to draw, with newlines (\n) between lines.
  1181. * $which_halign : Horizontal (relative to the image) alignment: left, center, or right.
  1182. * $which_valign : Vertical (relative to the image) alignment: top, center, or bottom.
  1183. */
  1184. function DrawText($which_font, $which_angle, $which_xpos, $which_ypos, $which_color, $which_text,
  1185. $which_halign = 'left', $which_valign = 'bottom')
  1186. {
  1187. return $this->ProcessText(True,
  1188. $which_font, $which_angle, $which_xpos, $which_ypos,
  1189. $which_color, $which_text, $which_halign, $which_valign);
  1190. }
  1191. /*
  1192. * Returns the size of block of text. This is the orthogonal width and height of a bounding
  1193. * box aligned with the X and Y axes of the text. Only for angle=0 is this the actual
  1194. * width and height of the text block, but for any angle it is the amount of space needed
  1195. * to contain the text.
  1196. * $which_font : PHPlot font array, or NULL or empty string to use 'generic'
  1197. * $which_angle : Text angle in degrees
  1198. * $which_text : The text to draw, with newlines (\n) between lines.
  1199. * Returns a two element array with: $width, $height.
  1200. * This is just a wrapper for ProcessText() - see above.
  1201. */
  1202. function SizeText($which_font, $which_angle, $which_text)
  1203. {
  1204. // Color, position, and alignment are not used when calculating the size.
  1205. return $this->ProcessText(False,
  1206. $which_font, $which_angle, 0, 0, 1, $which_text, '', '');
  1207. }
  1208. /////////////////////////////////////////////
  1209. /////////// INPUT / OUTPUT CONTROL
  1210. /////////////////////////////////////////////
  1211. /*!
  1212. * Sets output file format.
  1213. */
  1214. function SetFileFormat($format)
  1215. {
  1216. $asked = $this->CheckOption($format, 'jpg, png, gif, wbmp', __FUNCTION__);
  1217. if (!$asked) return False;
  1218. switch ($asked) {
  1219. case 'jpg':
  1220. $format_test = IMG_JPG;
  1221. break;
  1222. case 'png':
  1223. $format_test = IMG_PNG;
  1224. break;
  1225. case 'gif':
  1226. $format_test = IMG_GIF;
  1227. break;
  1228. case 'wbmp':
  1229. $format_test = IMG_WBMP;
  1230. break;
  1231. }
  1232. if (!(imagetypes() & $format_test)) {
  1233. return $this->PrintError("SetFileFormat(): File format '$format' not supported");
  1234. }
  1235. $this->file_format = $asked;
  1236. return TRUE;
  1237. }
  1238. /*!
  1239. * Selects an input file to be used as graph background and scales or tiles this image
  1240. * to fit the sizes.
  1241. * \param input_file string Path to the file to be used (jpeg, png and gif accepted)
  1242. * \param mode string 'centeredtile', 'tile', 'scale' (the image to the graph's size)
  1243. */
  1244. function SetBgImage($input_file, $mode='centeredtile')
  1245. {
  1246. $this->bgmode = $this->CheckOption($mode, 'tile, centeredtile, scale', __FUNCTION__);
  1247. $this->bgimg = $input_file;
  1248. return (boolean)$this->bgmode;
  1249. }
  1250. /*!
  1251. * Selects an input file to be used as plot area background and scales or tiles this image
  1252. * to fit the sizes.
  1253. * \param input_file string Path to the file to be used (jpeg, png and gif accepted)
  1254. * \param mode string 'centeredtile', 'tile', 'scale' (the image to the graph's size)
  1255. */
  1256. function SetPlotAreaBgImage($input_file, $mode='tile')
  1257. {
  1258. $this->plotbgmode = $this->CheckOption($mode, 'tile, centeredtile, scale', __FUNCTION__);
  1259. $this->plotbgimg = $input_file;
  1260. return (boolean)$this->plotbgmode;
  1261. }
  1262. /*!
  1263. * Sets the name of the file to be used as output file.
  1264. */
  1265. function SetOutputFile($which_output_file)
  1266. {
  1267. $this->output_file = $which_output_file;
  1268. return TRUE;
  1269. }
  1270. /*!
  1271. * Sets the output image as 'inline', that is: no Content-Type headers are sent
  1272. * to the browser. Needed if you want to embed the images.
  1273. */
  1274. function SetIsInline($which_ii)
  1275. {
  1276. $this->is_inline = (bool)$which_ii;
  1277. return TRUE;
  1278. }
  1279. /*!
  1280. * Performs the actual outputting of the generated graph.
  1281. */
  1282. function PrintImage()
  1283. {
  1284. // Browser cache stuff submitted by Thiemo Nagel
  1285. if ( (! $this->browser_cache) && (! $this->is_inline)) {
  1286. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  1287. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
  1288. header('Cache-Control: no-cache, must-revalidate');
  1289. header('Pragma: no-cache');
  1290. }
  1291. switch($this->file_format) {
  1292. case 'png':
  1293. if (! $this->is_inline) {
  1294. Header('Content-type: image/png');
  1295. }
  1296. if ($this->is_inline && $this->output_file != '') {
  1297. ImagePng($this->img, $this->output_file);
  1298. } else {
  1299. ImagePng($this->img);
  1300. }
  1301. break;
  1302. case 'jpg':
  1303. if (! $this->is_inline) {
  1304. Header('Content-type: image/jpeg');
  1305. }
  1306. if ($this->is_inline && $this->output_file != '') {
  1307. ImageJPEG($this->img, $this->output_file);
  1308. } else {
  1309. ImageJPEG($this->img);
  1310. }
  1311. break;
  1312. case 'gif':
  1313. if (! $this->is_inline) {
  1314. Header('Content-type: image/gif');
  1315. }
  1316. if ($this->is_inline && $this->output_file != '') {
  1317. ImageGIF($this->img, $this->output_file);
  1318. } else {
  1319. ImageGIF($this->img);
  1320. }
  1321. break;
  1322. case 'wbmp': // wireless bitmap, 2 bit.
  1323. if (! $this->is_inline) {
  1324. Header('Content-type: image/wbmp');
  1325. }
  1326. if ($this->is_inline && $this->output_file != '') {
  1327. ImageWBMP($this->img, $this->output_file);
  1328. } else {
  1329. ImageWBMP($this->img);
  1330. }
  1331. break;
  1332. default:
  1333. return $this->PrintError('PrintImage(): Please select an image type!');
  1334. }
  1335. return TRUE;
  1336. }
  1337. /*!
  1338. * Error handling for 'fatal' errors:
  1339. * $error_message Text of the error message
  1340. * Standard output from PHPlot is expected to be an image file, such as
  1341. * when handling an <img> tag browser request. So it is not permitted to
  1342. * output text to standard output. (You should have display_errors=off)
  1343. * Here is how PHPlot handles fatal errors:
  1344. * + Write the error message into an image, and output the image.
  1345. * + If no image can be output, write nothing and produce an HTTP
  1346. * error header.
  1347. * + Trigger a user-level error containing the error message.
  1348. * If no error handler was set up, the script will log the
  1349. * error and exit with non-zero status.
  1350. *
  1351. * PrintError() and DrawError() are now equivalent. Both are provided for
  1352. * compatibility. (In earlier releases, PrintError sent the message to
  1353. * stdout only, and DrawError sent it in an image only.)
  1354. *
  1355. * This function does not return, unless the calling script has set up
  1356. * an error handler which does not exit. In that case, PrintError will
  1357. * return False. But not all of PHPlot will handle this correctly, so
  1358. * it is probably a bad idea for an error handler to return.
  1359. */
  1360. protected function PrintError($error_message)
  1361. {
  1362. // Be sure not to loop recursively, e.g. PrintError - PrintImage - PrintError.
  1363. if (isset($this->in_error)) return FALSE;
  1364. $this->in_error = TRUE;
  1365. // Output an image containing the error message:
  1366. if (!empty($this->img)) {
  1367. $ypos = $this->image_height/2;
  1368. $xpos = $this->image_width/2;
  1369. $bgcolor = ImageColorResolve($this->img, 255, 255, 255);
  1370. $fgcolor = ImageColorResolve($this->img, 0, 0, 0);
  1371. ImageFilledRectangle($this->img, 0, 0, $this->image_width, $this->image_height, $bgcolor);
  1372. // Switch to built-in fonts, in case of error with TrueType fonts:
  1373. $this->SetUseTTF(FALSE);
  1374. $this->DrawText($this->fonts['generic'], 0, $xpos, $ypos, $fgcolor,
  1375. wordwrap($error_message), 'center', 'center');
  1376. $this->PrintImage();
  1377. } elseif (! $this->is_inline) {
  1378. Header('HTTP/1.0 500 Internal Server Error');
  1379. }
  1380. trigger_error($error_message, E_USER_ERROR);
  1381. unset($this->in_error);
  1382. return FALSE; # In case error handler returns, rather than doing exit().
  1383. }
  1384. /*!
  1385. * Display an error message and exit.
  1386. * This is provided for backward compatibility only. Use PrintError() instead.
  1387. * $error_message Text of the error message
  1388. * $where_x, $where_y Ignored, provided for compatibility.
  1389. */
  1390. protected function DrawError($error_message, $where_x = NULL, $where_y = NULL)
  1391. {
  1392. return $this->PrintError($error_message);
  1393. }
  1394. /////////////////////////////////////////////
  1395. /////////// LABELS
  1396. /////////////////////////////////////////////
  1397. /*!
  1398. * Sets position for X labels following data points.
  1399. */
  1400. function SetXDataLabelPos($which_xdlp)
  1401. {
  1402. $which_xdlp = $this->CheckOption($which_xdlp, 'plotdown, plotup, both, xaxis, all, none',
  1403. __FUNCTION__);
  1404. if (!$which_xdlp) return FALSE;
  1405. $this->x_data_label_pos = $which_xdlp;
  1406. return TRUE;
  1407. }
  1408. /*!
  1409. * Sets position for Y labels near data points.
  1410. * For past compatibility we accept plotleft, ...but pass it to SetTickLabelPos
  1411. * eventually to specify how far up/down or left/right of the data point
  1412. */
  1413. function SetYDataLabelPos($which_ydlp, $which_distance_from_point=0)
  1414. {
  1415. $which_ydlp = $this->CheckOption($which_ydlp, 'plotleft, plotright, both, yaxis, all, plotin, none',
  1416. __FUNCTION__);
  1417. if (!$which_ydlp) return FALSE;
  1418. $this->y_data_label_pos = $which_ydlp;
  1419. //This bit in SetYDataLabelPos about plotleft is for those who were
  1420. //using this function to set SetYTickLabelPos.
  1421. if ( ($which_ydlp == 'plotleft') || ($which_ydlp == 'plotright') ||
  1422. ($which_ydlp == 'both') || ($which_ydlp == 'yaxis') ) {
  1423. //Call sety_TICK_labelpos instead of sety_DATA_labelpos
  1424. $this->SetYTickLabelPos($which_ydlp);
  1425. } elseif ($which_ydlp != 'none') {
  1426. //right now its plotin or none
  1427. $this->y_data_label_pos = 'plotin';
  1428. }
  1429. return TRUE;
  1430. }
  1431. /*!
  1432. * Sets position for X labels following ticks (hence grid lines)
  1433. */
  1434. function SetXTickLabelPos($which_xtlp)
  1435. {
  1436. $which_xtlp = $this->CheckOption($which_xtlp, 'plotdown, plotup, both, xaxis, all, none',
  1437. __FUNCTION__);
  1438. if (!$which_xtlp) return FALSE;
  1439. $this->x_tick_label_pos = $which_xtlp;
  1440. return TRUE;
  1441. }
  1442. /*!
  1443. * Sets position for Y labels following ticks (hence grid lines)
  1444. */
  1445. function SetYTickLabelPos($which_ytlp)
  1446. {
  1447. $this->y_tick_label_pos = $this->CheckOption($which_ytlp, 'plotleft, plotright, both, yaxis, all, none',
  1448. __FUNCTION__);
  1449. return (boolean)$this->y_tick_label_pos;
  1450. }
  1451. /*!
  1452. * Sets type for tick and data labels on X or Y axis. This is meant for use by
  1453. * SetXLabelType and SetYLabelType, but can also be called directly.
  1454. * $mode : 'x', 'y', 'xd', or 'yd' - which type of label to configure.
  1455. * 'x' and 'y' set the type for tick labels, and the default type for data labels
  1456. * if they are not separately configured. 'xd' and 'yd' set the type for data labels.
  1457. * $args : Variable arguments, passed as an array.
  1458. * [0] = $type (required) : Label type. 'data', 'time', 'printf', or 'custom'.
  1459. * For type 'data':
  1460. * [1] = $precision (optional). Numeric precision. Can also be set by SetPrecision[XY]().
  1461. * [2] = $prefix (optional) - prefix string for labels.
  1462. * [3] = $suffix (optional) - suffix string for labels. This replaces data_units_text.
  1463. * For type 'time':
  1464. * [1] = $format for strftime (optional). Can also be set by Set[XY]TimeFormat().
  1465. * For type 'printf':
  1466. * [1] = $format (optional) for sprintf.
  1467. * For type 'custom':
  1468. * [1] = $callback (required) - Custom function or array of (instance,method) to call.
  1469. * [2] = $argument (optional) - Pass-through argument for the formatting function.
  1470. */
  1471. protected function SetLabelType($mode, $args)
  1472. {
  1473. if (!$this->CheckOption($mode, 'x, y, xd, yd', __FUNCTION__))
  1474. return FALSE;
  1475. $type = isset($args[0]) ? $args[0] : '';
  1476. $format =& $this->label_format[$mode]; // Shorthand reference to format storage variables
  1477. switch ($type) {
  1478. case 'data':
  1479. if (isset($args[1]))
  1480. $format['precision'] = $args[1];
  1481. elseif (!isset($format['precision']))
  1482. $format['precision'] = 1;
  1483. $format['prefix'] = isset($args[2]) ? $args[2] : '';
  1484. $format['suffix'] = isset($args[3]) ? $args[3] : '';
  1485. break;
  1486. case 'time':
  1487. if (isset($args[1]))
  1488. $format['time_format'] = $args[1];
  1489. elseif (!isset($format['time_format']))
  1490. $format['time_format'] = '%H:%M:%S';
  1491. break;
  1492. case 'printf':
  1493. if (isset($args[1]))
  1494. $format['printf_format'] = $args[1];
  1495. elseif (!isset($format['printf_format']))
  1496. $format['printf_format'] = '%e';
  1497. break;
  1498. case 'custom':
  1499. if (isset($args[1])) {
  1500. $format['custom_callback'] = $args[1];
  1501. $format['custom_arg'] = isset($args[2]) ? $args[2] : NULL;
  1502. } else {
  1503. $type = ''; // Error, 'custom' without a function, set to no-format mode.
  1504. }
  1505. break;
  1506. case '':
  1507. case 'title': // Retained for backwards compatibility?
  1508. break;
  1509. default:
  1510. $this->CheckOption($type, 'data, time, printf, custom', __FUNCTION__);
  1511. $type = '';
  1512. }
  1513. $format['type'] = $type;
  1514. return (boolean)$type;
  1515. }
  1516. /*
  1517. * Select label formating for X tick labels, and for X data labels
  1518. * (unless SetXDataLabelType was called).
  1519. * See SetLabelType() for details.
  1520. */
  1521. function SetXLabelType() // Variable arguments: $type, ...
  1522. {
  1523. $args = func_get_args();
  1524. return $this->SetLabelType('x', $args);
  1525. }
  1526. /*
  1527. * Select label formatting for X data labels, overriding SetXLabelType.
  1528. */
  1529. function SetXDataLabelType() // Variable arguments: $type, ...
  1530. {
  1531. $args = func_get_args();
  1532. return $this->SetLabelType('xd', $args);
  1533. }
  1534. /*
  1535. * Select label formating for Y tick labels, and for Y data labels
  1536. * (unless SetYDataLabelType was called).
  1537. * See SetLabelType() for details.
  1538. */
  1539. function SetYLabelType() // Variable arguments: $type, ...
  1540. {
  1541. $args = func_get_args();
  1542. return $this->SetLabelType('y', $args);
  1543. }
  1544. /*
  1545. * Select label formatting for Y data labels, overriding SetYLabelType.
  1546. */
  1547. function SetYDataLabelType() // Variable arguments: $type, ...
  1548. {
  1549. $args = func_get_args();
  1550. return $this->SetLabelType('yd', $args);
  1551. }
  1552. function SetXTimeFormat($which_xtf)
  1553. {
  1554. $this->label_format['x']['time_format'] = $which_xtf;
  1555. return TRUE;
  1556. }
  1557. function SetYTimeFormat($which_ytf)
  1558. {
  1559. $this->label_format['y']['time_format'] = $which_ytf;
  1560. return TRUE;
  1561. }
  1562. function SetNumberFormat($decimal_point, $thousands_sep)
  1563. {
  1564. $this->decimal_point = $decimal_point;
  1565. $this->thousands_sep = $thousands_sep;
  1566. return TRUE;
  1567. }
  1568. function SetXLabelAngle($which_xla)
  1569. {
  1570. $this->x_label_angle = $which_xla;
  1571. return TRUE;
  1572. }
  1573. function SetYLabelAngle($which_yla)
  1574. {
  1575. $this->y_label_angle = $which_yla;
  1576. return TRUE;
  1577. }
  1578. // If used, this sets the angle for X Data Labels only, separately from tick labels.
  1579. function SetXDataLabelAngle($which_xdla)
  1580. {
  1581. $this->x_data_label_angle = $which_xdla;
  1582. return TRUE;
  1583. }
  1584. // Sets the angle for Y Data Labels. Unlike X Data Labels, these default to zero.
  1585. function SetYDataLabelAngle($which_ydla)
  1586. {
  1587. $this->y_data_label_angle = $which_ydla;
  1588. return TRUE;
  1589. }
  1590. /////////////////////////////////////////////
  1591. /////////// MISC
  1592. /////////////////////////////////////////////
  1593. /*!
  1594. * Checks the validity of an option.
  1595. * $which_opt String to check, such as the provided value of a function argument.
  1596. * $which_acc String of accepted choices. Must be lower-case, and separated
  1597. * by exactly ', ' (comma, space).
  1598. * $which_func Name of the calling function, for error messages.
  1599. * Returns the supplied option value, downcased and trimmed, if it is valid.
  1600. * Reports an error if the supplied option is not valid.
  1601. */
  1602. protected function CheckOption($which_opt, $which_acc, $which_func)
  1603. {
  1604. $asked = strtolower(trim($which_opt));
  1605. # Look for the supplied value in a comma/space separated list.
  1606. if (strpos(", $which_acc,", ", $asked,") !== False)
  1607. return $asked;
  1608. $this->PrintError("$which_func(): '$which_opt' not in available choices: '$which_acc'.");
  1609. return NULL;
  1610. }
  1611. /*!
  1612. * \note Submitted by Thiemo Nagel
  1613. */
  1614. function SetBrowserCache($which_browser_cache)
  1615. {
  1616. $this->browser_cache = $which_browser_cache;
  1617. return TRUE;
  1618. }
  1619. /*!
  1620. * Whether to show the final image or not
  1621. */
  1622. function SetPrintImage($which_pi)
  1623. {
  1624. $this->print_image = $which_pi;
  1625. return TRUE;
  1626. }
  1627. /*!
  1628. * Sets the graph's legend. If argument is not an array, appends it to the legend.
  1629. */
  1630. function SetLegend($which_leg)
  1631. {
  1632. if (is_array($which_leg)) { // use array
  1633. $this->legend = $which_leg;
  1634. } elseif (! is_null($which_leg)) { // append string
  1635. $this->legend[] = $which_leg;
  1636. } else {
  1637. return $this->PrintError("SetLegend(): argument must not be null.");
  1638. }
  1639. return TRUE;
  1640. }
  1641. /*!
  1642. * Specifies the position of the legend's upper/leftmost corner,
  1643. * in pixel (device) coordinates.
  1644. */
  1645. function SetLegendPixels($which_x, $which_y)
  1646. {
  1647. $this->legend_x_pos = $which_x;
  1648. $this->legend_y_pos = $which_y;
  1649. // Make sure this is unset, meaning we have pixel coords:
  1650. unset($this->legend_xy_world);
  1651. return TRUE;
  1652. }
  1653. /*!
  1654. * Specifies the position of the legend's upper/leftmost corner,
  1655. * in world (data space) coordinates.
  1656. * Since the scale factor to convert world to pixel coordinates
  1657. * is probably not available, set a flag and defer conversion
  1658. * to later.
  1659. */
  1660. function SetLegendWorld($which_x, $which_y)
  1661. {
  1662. $this->legend_x_pos = $which_x;
  1663. $this->legend_y_pos = $which_y;
  1664. $this->legend_xy_world = True;
  1665. return TRUE;
  1666. }
  1667. /*
  1668. * Set legend text alignment, color box alignment, and style options
  1669. * $text_align accepts 'left' or 'right'.
  1670. * $colorbox_align accepts 'left', 'right', 'none', or missing/empty. If missing or empty,
  1671. * the same alignment as $text_align is used. Color box is positioned first.
  1672. * $style is reserved for future use.
  1673. */
  1674. function SetLegendStyle($text_align, $colorbox_align = '', $style = '')
  1675. {
  1676. $this->legend_text_align = $this->CheckOption($text_align, 'left, right', __FUNCTION__);
  1677. if (empty($colorbox_align))
  1678. $this->legend_colorbox_align = $this->legend_text_align;
  1679. else
  1680. $this->legend_colorbox_align = $this->CheckOption($colorbox_align, 'left, right, none', __FUNCTION__);
  1681. return ((boolean)$this->legend_text_align && (boolean)$this->legend_colorbox_align);
  1682. }
  1683. /*!
  1684. * Accepted values are: left, sides, none, full
  1685. */
  1686. function SetPlotBorderType($pbt)
  1687. {
  1688. $this->plot_border_type = $this->CheckOption($pbt, 'left, sides, none, full', __FUNCTION__);
  1689. return (boolean)$this->plot_border_type;
  1690. }
  1691. /*!
  1692. * Accepted values are: raised, plain
  1693. */
  1694. function SetImageBorderType($sibt)
  1695. {
  1696. $this->image_border_type = $this->CheckOption($sibt, 'raised, plain, none', __FUNCTION__);
  1697. return (boolean)$this->image_border_type;
  1698. }
  1699. /*!
  1700. * \param dpab bool
  1701. */
  1702. function SetDrawPlotAreaBackground($dpab)
  1703. {
  1704. $this->draw_plot_area_background = (bool)$dpab;
  1705. return TRUE;
  1706. }
  1707. /*!
  1708. * \param dyg bool
  1709. */
  1710. function SetDrawYGrid($dyg)
  1711. {
  1712. $this->draw_y_grid = (bool)$dyg;
  1713. return TRUE;
  1714. }
  1715. /*!
  1716. * \param dxg bool
  1717. */
  1718. function SetDrawXGrid($dxg)
  1719. {
  1720. $this->draw_x_grid = (bool)$dxg;
  1721. return TRUE;
  1722. }
  1723. /*!
  1724. * \param ddg bool
  1725. */
  1726. function SetDrawDashedGrid($ddg)
  1727. {
  1728. $this->dashed_grid = (bool)$ddg;
  1729. return TRUE;
  1730. }
  1731. /*!
  1732. * \param dxdl bool
  1733. */
  1734. function SetDrawXDataLabelLines($dxdl)
  1735. {
  1736. $this->draw_x_data_label_lines = (bool)$dxdl;
  1737. return TRUE;
  1738. }
  1739. /*!
  1740. * Sets the graph's title.
  1741. * TODO: add parameter to choose title placement: left, right, centered=
  1742. */
  1743. function SetTitle($which_title)
  1744. {
  1745. $this->title_txt = $which_title;
  1746. return TRUE;
  1747. }
  1748. /*!
  1749. * Sets the X axis title and position.
  1750. */
  1751. function SetXTitle($which_xtitle, $which_xpos = 'plotdown')
  1752. {
  1753. if ($which_xtitle == '')
  1754. $which_xpos = 'none';
  1755. $this->x_title_pos = $this->CheckOption($which_xpos, 'plotdown, plotup, both, none', __FUNCTION__);
  1756. if (!$this->x_title_pos) return FALSE;
  1757. $this->x_title_txt = $which_xtitle;
  1758. return TRUE;
  1759. }
  1760. /*!
  1761. * Sets the Y axis title and position.
  1762. */
  1763. function SetYTitle($which_ytitle, $which_ypos = 'plotleft')
  1764. {
  1765. if ($which_ytitle == '')
  1766. $which_ypos = 'none';
  1767. $this->y_title_pos = $this->CheckOption($which_ypos, 'plotleft, plotright, both, none', __FUNCTION__);
  1768. if (!$this->y_title_pos) return FALSE;
  1769. $this->y_title_txt = $which_ytitle;
  1770. return TRUE;
  1771. }
  1772. /*!
  1773. * Sets the size of the drop shadow for bar and pie charts.
  1774. * \param which_s int Size in pixels.
  1775. */
  1776. function SetShading($which_s)
  1777. {
  1778. $this->shading = (int)$which_s;
  1779. return TRUE;
  1780. }
  1781. function SetPlotType($which_pt)
  1782. {
  1783. $this->plot_type = $this->CheckOption($which_pt,
  1784. 'bars, stackedbars, lines, linepoints, area, points, pie, thinbarline, squared',
  1785. __FUNCTION__);
  1786. return (boolean)$this->plot_type;
  1787. }
  1788. /*!
  1789. * Sets the position of Y axis.
  1790. * \param pos int Position in world coordinates.
  1791. */
  1792. function SetYAxisPosition($pos)
  1793. {
  1794. $this->y_axis_position = (int)$pos;
  1795. return TRUE;
  1796. }
  1797. /*!
  1798. * Sets the position of X axis.
  1799. * \param pos int Position in world coordinates.
  1800. */
  1801. function SetXAxisPosition($pos)
  1802. {
  1803. $this->x_axis_position = (int)$pos;
  1804. return TRUE;
  1805. }
  1806. function SetXScaleType($which_xst)
  1807. {
  1808. $this->xscale_type = $this->CheckOption($which_xst, 'linear, log', __FUNCTION__);
  1809. return (boolean)$this->xscale_type;
  1810. }
  1811. function SetYScaleType($which_yst)
  1812. {
  1813. $this->yscale_type = $this->CheckOption($which_yst, 'linear, log', __FUNCTION__);
  1814. return (boolean)$this->yscale_type;
  1815. }
  1816. function SetPrecisionX($which_prec)
  1817. {
  1818. return $this->SetXLabelType('data', $which_prec);
  1819. }
  1820. function SetPrecisionY($which_prec)
  1821. {
  1822. return $this->SetYLabelType('data', $which_prec);
  1823. }
  1824. function SetErrorBarLineWidth($which_seblw)
  1825. {
  1826. $this->error_bar_line_width = $which_seblw;
  1827. return TRUE;
  1828. }
  1829. function SetLabelScalePosition($which_blp)
  1830. {
  1831. //0 to 1
  1832. $this->label_scale_position = $which_blp;
  1833. return TRUE;
  1834. }
  1835. function SetErrorBarSize($which_ebs)
  1836. {
  1837. //in pixels
  1838. $this->error_bar_size = $which_ebs;
  1839. return TRUE;
  1840. }
  1841. /*!
  1842. * Can be one of: 'tee', 'line'
  1843. */
  1844. function SetErrorBarShape($which_ebs)
  1845. {
  1846. $this->error_bar_shape = $this->CheckOption($which_ebs, 'tee, line', __FUNCTION__);
  1847. return (boolean)$this->error_bar_shape;
  1848. }
  1849. /*
  1850. * Synchronize the point shape and point size arrays.
  1851. * This is called just before drawing any plot that needs 'points'.
  1852. */
  1853. protected function CheckPointParams()
  1854. {
  1855. // Make both point_shapes and point_sizes the same size, by padding the smaller.
  1856. $ps = count($this->point_sizes);
  1857. $pt = count($this->point_shapes);
  1858. if ($ps < $pt) {
  1859. $this->pad_array($this->point_sizes, $pt);
  1860. $this->point_counts = $pt;
  1861. } else if ($ps > $pt) {
  1862. $this->pad_array($this->point_shapes, $ps);
  1863. $this->point_counts = $ps;
  1864. }
  1865. // Note: PHPlot used to check and adjust point_sizes to be an even number here,
  1866. // for all 'diamond' and 'triangle' shapes. The reason for this having been
  1867. // lost, and the current maintainer seeing no sense it doing this for only
  1868. // some shapes, the code has been removed. But see what DrawDot() does.
  1869. }
  1870. /*!
  1871. * Sets point shape for each data set via an array.
  1872. * For a list of valid shapes, see the CheckOption call below.
  1873. * The point shape and point sizes arrays are synchronized before drawing a graph
  1874. * that uses points. See CheckPointParams()
  1875. */
  1876. function SetPointShapes($which_pt)
  1877. {
  1878. if (is_array($which_pt)) {
  1879. // Use provided array:
  1880. $this->point_shapes = $which_pt;
  1881. } elseif (!is_null($which_pt)) {
  1882. // Make the single value into an array:
  1883. $this->point_shapes = array($which_pt);
  1884. }
  1885. // Validate all the shapes. This list must agree with DrawDot().
  1886. foreach ($this->point_shapes as $shape)
  1887. {
  1888. if (!$this->CheckOption($shape, 'halfline, line, plus, cross, rect, circle, dot,'
  1889. . ' diamond, triangle, trianglemid, delta, yield, star, hourglass,'
  1890. . ' bowtie, target, box, home, up, down, none', __FUNCTION__))
  1891. return FALSE;
  1892. }
  1893. return TRUE;
  1894. }
  1895. /*!
  1896. * Sets the point size for point plots.
  1897. * The point shape and point sizes arrays are synchronized before drawing a graph
  1898. * that uses points. See CheckPointParams()
  1899. */
  1900. function SetPointSizes($which_ps)
  1901. {
  1902. if (is_array($which_ps)) {
  1903. // Use provided array:
  1904. $this->point_sizes = $which_ps;
  1905. } elseif (!is_null($which_ps)) {
  1906. // Make the single value into an array:
  1907. $this->point_sizes = array($which_ps);
  1908. }
  1909. return TRUE;
  1910. }
  1911. /*!
  1912. * Tells not to draw lines for missing Y data. Only works with 'lines' and 'squared' plots.
  1913. * \param bl bool
  1914. */
  1915. function SetDrawBrokenLines($bl)
  1916. {
  1917. $this->draw_broken_lines = (bool)$bl;
  1918. return TRUE;
  1919. }
  1920. /*!
  1921. * text-data: ('label', y1, y2, y3, ...)
  1922. * text-data-single: ('label', data), for some pie charts.
  1923. * data-data: ('label', x, y1, y2, y3, ...)
  1924. * data-data-error: ('label', x1, y1, e1+, e2-, y2, e2+, e2-, y3, e3+, e3-, ...)
  1925. */
  1926. function SetDataType($which_dt)
  1927. {
  1928. //The next four lines are for past compatibility.
  1929. if ($which_dt == 'text-linear') { $which_dt = 'text-data'; }
  1930. elseif ($which_dt == 'linear-linear') { $which_dt = 'data-data'; }
  1931. elseif ($which_dt == 'linear-linear-error') { $which_dt = 'data-data-error'; }
  1932. elseif ($which_dt == 'text-data-pie') { $which_dt = 'text-data-single'; }
  1933. $this->data_type = $this->CheckOption($which_dt, 'text-data, text-data-single, '.
  1934. 'data-data, data-data-error', __FUNCTION__);
  1935. return (boolean)$this->data_type;
  1936. }
  1937. /*!
  1938. * Copy the array passed as data values. We convert to numerical indexes, for its
  1939. * use for (or while) loops, which sometimes are faster. Performance improvements
  1940. * vary from 28% in DrawLines() to 49% in DrawArea() for plot drawing functions.
  1941. */
  1942. function SetDataValues(&$which_dv)
  1943. {
  1944. $this->num_data_rows = count($which_dv);
  1945. $this->total_records = 0; // Perform some useful calculations.
  1946. $this->records_per_group = 1;
  1947. for ($i = 0, $recs = 0; $i < $this->num_data_rows; $i++) {
  1948. // Copy
  1949. $this->data[$i] = array_values($which_dv[$i]); // convert to numerical indices.
  1950. // Compute some values
  1951. $recs = count($this->data[$i]);
  1952. $this->total_records += $recs;
  1953. if ($recs > $this->records_per_group)
  1954. $this->records_per_group = $recs;
  1955. $this->num_recs[$i] = $recs;
  1956. }
  1957. return TRUE;
  1958. }
  1959. /*!
  1960. * Pad styles arrays for later use by plot drawing functions:
  1961. * This removes the need for $max_data_colors, etc. and $color_index = $color_index % $max_data_colors
  1962. * in DrawBars(), DrawLines(), etc.
  1963. */
  1964. protected function PadArrays()
  1965. {
  1966. $this->pad_array($this->line_widths, $this->records_per_group);
  1967. $this->pad_array($this->line_styles, $this->records_per_group);
  1968. $this->pad_array($this->data_colors, $this->records_per_group);
  1969. $this->pad_array($this->data_border_colors, $this->records_per_group);
  1970. $this->pad_array($this->error_bar_colors, $this->records_per_group);
  1971. $this->SetDataColors();
  1972. $this->SetDataBorderColors();
  1973. $this->SetErrorBarColors();
  1974. return TRUE;
  1975. }
  1976. /*!
  1977. * Pads an array with itself. This only works on 0-based sequential integer indexed arrays.
  1978. * \param arr array Original array (reference), or scalar.
  1979. * \param size int Minimum size of the resulting array.
  1980. * If $arr is a scalar, it will be converted first to a single element array.
  1981. * If $arr has at least $size elements, it is unchanged.
  1982. * Otherwise, append elements of $arr to itself until it reaches $size elements.
  1983. */
  1984. protected function pad_array(&$arr, $size)
  1985. {
  1986. if (! is_array($arr)) {
  1987. $arr = array($arr);
  1988. }
  1989. $n = count($arr);
  1990. $base = 0;
  1991. while ($n < $size) $arr[$n++] = $arr[$base++];
  1992. }
  1993. /*
  1994. * Format a floating-point number.
  1995. * This is like PHP's number_format, but uses class variables for separators.
  1996. * The separators will default to locale-specific values, if available.
  1997. * Note: This method should be 'protected', but is called from test script(s).
  1998. */
  1999. function number_format($number, $decimals=0)
  2000. {
  2001. if (!isset($this->decimal_point) || !isset($this->thousands_sep)) {
  2002. // Load locale-specific values from environment, unless disabled:
  2003. if (empty($this->locale_override))
  2004. @setlocale(LC_ALL, '');
  2005. // Fetch locale settings:
  2006. $locale = @localeconv();
  2007. if (!empty($locale) && isset($locale['decimal_point']) &&
  2008. isset($locale['thousands_sep'])) {
  2009. $this->decimal_point = $locale['decimal_point'];
  2010. $this->thousands_sep = $locale['thousands_sep'];
  2011. } else {
  2012. // Locale information not available.
  2013. $this->decimal_point = '.';
  2014. $this->thousands_sep = ',';
  2015. }
  2016. }
  2017. return number_format($number, $decimals, $this->decimal_point, $this->thousands_sep);
  2018. }
  2019. /*
  2020. * Register a callback (hook) function
  2021. * reason - A pre-defined name where a callback can be defined.
  2022. * function - The name of a function to register for callback, or an instance/method
  2023. * pair in an array (see 'callbacks' in the PHP reference manual).
  2024. * arg - Optional argument to supply to the callback function when it is triggered.
  2025. * (Often called "clientData")
  2026. * Returns: True if the callback reason is valid, else False.
  2027. */
  2028. function SetCallback($reason, $function, $arg = NULL)
  2029. {
  2030. // Use array_key_exists because valid reason keys have NULL as value.
  2031. if (!array_key_exists($reason, $this->callbacks))
  2032. return False;
  2033. $this->callbacks[$reason] = array($function, $arg);
  2034. return True;
  2035. }
  2036. /*
  2037. * Return the name of a function registered for callback. See SetCallBack.
  2038. * reason - A pre-defined name where a callback can be defined.
  2039. * Returns the current callback function (name or array) for the given reason,
  2040. * or False if there was no active callback or the reason is not valid.
  2041. * Note you can safely test the return value with a simple 'if', as
  2042. * no valid function name evaluates to false.
  2043. */
  2044. function GetCallback($reason)
  2045. {
  2046. if (isset($this->callbacks[$reason]))
  2047. return $this->callbacks[$reason][0];
  2048. return False;
  2049. }
  2050. /*
  2051. * Un-register (remove) a function registered for callback.
  2052. * reason - A pre-defined name where a callback can be defined.
  2053. * Returns: True if it was a valid callback reason, else False.
  2054. * Note: Returns True whether or not there was a callback registered.
  2055. */
  2056. function RemoveCallback($reason)
  2057. {
  2058. if (!array_key_exists($reason, $this->callbacks))
  2059. return False;
  2060. $this->callbacks[$reason] = NULL;
  2061. return True;
  2062. }
  2063. /*
  2064. * Invoke a callback, if one is registered.
  2065. * Accepts a variable number of arguments >= 1:
  2066. * reason : A string naming the callback.
  2067. * ... : Zero or more additional arguments to be passed to the
  2068. * callback function, after the passthru argument:
  2069. * callback_function($image, $passthru, ...)
  2070. * Returns: nothing.
  2071. */
  2072. protected function DoCallback() # Note: Variable arguments
  2073. {
  2074. $args = func_get_args();
  2075. $reason = $args[0];
  2076. if (!isset($this->callbacks[$reason]))
  2077. return;
  2078. list($function, $args[0]) = $this->callbacks[$reason];
  2079. array_unshift($args, $this->img);
  2080. # Now args[] looks like: img, passthru, extra args...
  2081. call_user_func_array($function, $args);
  2082. }
  2083. //////////////////////////////////////////////////////////
  2084. /////////// DATA ANALYSIS, SCALING AND TRANSLATION
  2085. //////////////////////////////////////////////////////////
  2086. /*!
  2087. * Analyzes data and sets up internal maxima and minima
  2088. * Needed by: CalcMargins(), ...
  2089. * Data type text-data has: title, Y1, Y2, ... (with X implied)
  2090. * Data type data-data has: title, X, Y1, Y2, ...
  2091. * Data type data-data-error: has title, X, Y1, Y1err+, Y1err-, Y2, Y2err+, Y2err-, ...
  2092. * Plot type 'stackedbars' is a special case because the bars always start at 0, and the
  2093. * Y values in each row accumulate.
  2094. * Note: This method should be 'protected', but is called from test script(s).
  2095. */
  2096. function FindDataLimits()
  2097. {
  2098. # Determine how to process the data array:
  2099. $process_x = ($this->data_type == 'data-data' || $this->data_type == 'data-data-error');
  2100. $process_err_bars = ($this->data_type == 'data-data-error');
  2101. $process_stacked_bars = ($this->plot_type == 'stackedbars');
  2102. # These need to be initialized in case there are multiple plots and
  2103. # missing data points.
  2104. $this->data_miny = array();
  2105. $this->data_maxy = array();
  2106. # X values are in the data array or assumed?
  2107. if ($process_x) {
  2108. $all_x = array();
  2109. } else {
  2110. $all_x = array(0, $this->num_data_rows - 1);
  2111. }
  2112. # Process all rows of data:
  2113. for ($i = 0; $i < $this->num_data_rows; $i++) {
  2114. $n_vals = $this->num_recs[$i];
  2115. $j = 1; # Skips label at [0]
  2116. if ($process_x) {
  2117. $all_x[] = (double)$this->data[$i][$j++];
  2118. }
  2119. if ($process_stacked_bars) {
  2120. $all_y = array(0, 0); # Min (always 0) and max
  2121. } else {
  2122. $all_y = array();
  2123. }
  2124. while ($j < $n_vals) {
  2125. if (is_numeric($this->data[$i][$j])) {
  2126. $val = (double)$this->data[$i][$j++];
  2127. if ($process_err_bars) {
  2128. $all_y[] = $val + (double)$this->data[$i][$j++];
  2129. $all_y[] = $val - (double)$this->data[$i][$j++];
  2130. } elseif ($process_stacked_bars) {
  2131. $all_y[1] += $val;
  2132. } else {
  2133. $all_y[] = $val;
  2134. }
  2135. } else { # Missing Y value
  2136. $j++;
  2137. if ($process_err_bars) $j += 2;
  2138. }
  2139. }
  2140. if (!empty($all_y)) {
  2141. $this->data_miny[$i] = min($all_y); # Store per-row Y range
  2142. $this->data_maxy[$i] = max($all_y);
  2143. }
  2144. }
  2145. $this->min_x = min($all_x); # Store X range
  2146. $this->max_x = max($all_x);
  2147. if (empty($this->data_miny)) { # Guard against regressive case: No Y at all
  2148. $this->min_y = 0;
  2149. $this->max_y = 0;
  2150. } else {
  2151. $this->min_y = min($this->data_miny); # Store global Y range
  2152. $this->max_y = max($this->data_maxy);
  2153. }
  2154. if ($this->GetCallback('debug_scale')) {
  2155. $this->DoCallback('debug_scale', __FUNCTION__, array(
  2156. 'min_x' => $this->min_x, 'min_y' => $this->min_y,
  2157. 'max_x' => $this->max_x, 'max_y' => $this->max_y));
  2158. }
  2159. return TRUE;
  2160. }
  2161. /*!
  2162. * Calculates image margins on the fly from title positions and sizes,
  2163. * and tick labels positions and sizes.
  2164. *
  2165. * A picture of the locations of elements and spacing can be found in the
  2166. * PHPlot Reference Manual.
  2167. *
  2168. * Calculates the following (class variables unless noted):
  2169. *
  2170. * Plot area margins (see note below):
  2171. * y_top_margin
  2172. * y_bot_margin
  2173. * x_left_margin
  2174. * x_right_margin
  2175. *
  2176. * Title sizes (these are now local, not class variables, since they are not used elsewhere):
  2177. * title_height : Height of main title
  2178. * x_title_height : Height of X axis title, 0 if no X title
  2179. * y_title_width : Width of Y axis title, 0 if no Y title
  2180. *
  2181. * Tick/Data label offsets, relative to plot_area:
  2182. * x_label_top_offset, x_label_bot_offset, x_label_axis_offset
  2183. * y_label_left_offset, y_label_right_offset, y_label_axis_offset
  2184. *
  2185. * Title offsets, relative to plot area:
  2186. * x_title_top_offset, x_title_bot_offset
  2187. * y_title_left_offset, y_title_left_offset
  2188. *
  2189. * Note: The margins are calculated, but not stored, if margins or plot area were
  2190. * set by the user with SetPlotAreaPixels or SetMarginsPixels. The margin
  2191. * calculation is mixed in with the offset variables, so it doesn't seem worth the
  2192. * trouble to separate them.
  2193. *
  2194. * If the $maximize argument is true, we use the full image size, minus safe_margin
  2195. * and main title, for the plot. This is for pie charts which have no axes or X/Y titles.
  2196. */
  2197. protected function CalcMargins($maximize)
  2198. {
  2199. // This is the line-to-line or line-to-text spacing:
  2200. $gap = $this->safe_margin;
  2201. // Minimum margin on each side. This reduces the chance that the
  2202. // right-most tick label (for example) will run off the image edge
  2203. // if there are no titles on that side.
  2204. $min_margin = 3 * $gap;
  2205. // Calculate the title sizes:
  2206. list($unused, $title_height) = $this->SizeText($this->fonts['title'], 0, $this->title_txt);
  2207. list($unused, $x_title_height) = $this->SizeText($this->fonts['x_title'], 0, $this->x_title_txt);
  2208. list($y_title_width, $unused) = $this->SizeText($this->fonts['y_title'], 90, $this->y_title_txt);
  2209. // Special case for maximum area usage with no X/Y titles or labels, only main title:
  2210. if ($maximize) {
  2211. if (!isset($this->x_left_margin))
  2212. $this->x_left_margin = $gap;
  2213. if (!isset($this->x_right_margin))
  2214. $this->x_right_margin = $gap;
  2215. if (!isset($this->y_top_margin)) {
  2216. $this->y_top_margin = $gap;
  2217. if ($title_height > 0)
  2218. $this->y_top_margin += $title_height + $gap;
  2219. }
  2220. if (!isset($this->y_bot_margin))
  2221. $this->y_bot_margin = $gap;
  2222. return TRUE;
  2223. }
  2224. // Make local variables for these. (They get used a lot and I'm tired of this, this, this.)
  2225. $x_tick_label_pos = $this->x_tick_label_pos;
  2226. $x_data_label_pos = $this->x_data_label_pos;
  2227. $x_tick_pos = $this->x_tick_pos;
  2228. $x_tick_len = $this->x_tick_length;
  2229. $y_tick_label_pos = $this->y_tick_label_pos;
  2230. $y_tick_pos = $this->y_tick_pos;
  2231. $y_tick_len = $this->y_tick_length;
  2232. // For X/Y tick and label position of 'xaxis' or 'yaxis', determine if the axis happens to be
  2233. // on an edge of a plot. If it is, we need to account for the margins there.
  2234. if ($this->x_axis_position <= $this->plot_min_y)
  2235. $x_axis_pos = 'bottom';
  2236. elseif ($this->x_axis_position >= $this->plot_max_y)
  2237. $x_axis_pos = 'top';
  2238. else
  2239. $x_axis_pos = 'none';
  2240. if ($this->y_axis_position <= $this->plot_min_x)
  2241. $y_axis_pos = 'left';
  2242. elseif ($this->y_axis_position >= $this->plot_max_x)
  2243. $y_axis_pos = 'right';
  2244. else
  2245. $y_axis_pos = 'none';
  2246. // Calculate the heights for X tick and data labels, and the max (used if they are overlaid):
  2247. $x_data_label_height = ($x_data_label_pos == 'none') ? 0 : $this->CalcMaxDataLabelSize();
  2248. $x_tick_label_height = ($x_tick_label_pos == 'none') ? 0 : $this->CalcMaxTickLabelSize('x');
  2249. $x_max_label_height = max($x_data_label_height, $x_tick_label_height);
  2250. // Calcualte the width for Y tick labels, if on:
  2251. $y_label_width = ($y_tick_label_pos == 'none') ? 0 : $this->CalcMaxTickLabelSize('y');
  2252. // Calculate the space needed above and below the plot for X tick and X data labels:
  2253. // Above the plot:
  2254. $tick_labels_above = ($x_tick_label_pos == 'plotup' || $x_tick_label_pos == 'both'
  2255. || ($x_tick_label_pos == 'xaxis' && $x_axis_pos == 'top'));
  2256. $data_labels_above = ($x_data_label_pos == 'plotup' || $x_data_label_pos == 'both');
  2257. if ($tick_labels_above) {
  2258. if ($data_labels_above) {
  2259. $label_height_above = $x_max_label_height;
  2260. } else {
  2261. $label_height_above = $x_tick_label_height;
  2262. }
  2263. } elseif ($data_labels_above) {
  2264. $label_height_above = $x_data_label_height;
  2265. } else {
  2266. $label_height_above = 0;
  2267. }
  2268. // Below the plot:
  2269. $tick_labels_below = ($x_tick_label_pos == 'plotdown' || $x_tick_label_pos == 'both'
  2270. || ($x_tick_label_pos == 'xaxis' && $x_axis_pos == 'bottom'));
  2271. $data_labels_below = ($x_data_label_pos == 'plotdown' || $x_data_label_pos == 'both');
  2272. if ($tick_labels_below) {
  2273. if ($data_labels_below) {
  2274. $label_height_below = $x_max_label_height;
  2275. } else {
  2276. $label_height_below = $x_tick_label_height;
  2277. }
  2278. } elseif ($data_labels_below) {
  2279. $label_height_below = $x_data_label_height;
  2280. } else {
  2281. $label_height_below = 0;
  2282. }
  2283. // Calculate the space needed left and right of the plot for Y tick labels:
  2284. // (This is simpler than X, because Y data labels don't enter the picture.)
  2285. // Left of the plot:
  2286. if ($y_tick_label_pos == 'plotleft' || $y_tick_label_pos == 'both'
  2287. || ($y_tick_label_pos == 'yaxis' && $y_axis_pos == 'left')) {
  2288. $label_width_left = $y_label_width;
  2289. } else {
  2290. $label_width_left = 0;
  2291. }
  2292. // Right of the plot:
  2293. if ($y_tick_label_pos == 'plotright' || $y_tick_label_pos == 'both'
  2294. || ($y_tick_label_pos == 'yaxis' && $y_axis_pos == 'right')) {
  2295. $label_width_right = $y_label_width;
  2296. } else {
  2297. $label_width_right = 0;
  2298. }
  2299. ///////// Calculate margins:
  2300. // Calculating Top and Bottom margins:
  2301. // y_top_margin: Main title, Upper X title, X ticks and tick labels, and X data labels:
  2302. // y_bot_margin: Lower title, ticks and tick labels, and data labels:
  2303. $top_margin = $gap;
  2304. $bot_margin = $gap;
  2305. $this->x_title_top_offset = $gap;
  2306. $this->x_title_bot_offset = $gap;
  2307. // Space for main title?
  2308. if ($title_height > 0)
  2309. $top_margin += $title_height + $gap;
  2310. // Space for X Title?
  2311. if ($x_title_height > 0) {
  2312. $pos = $this->x_title_pos;
  2313. if ($pos == 'plotup' || $pos == 'both')
  2314. $top_margin += $x_title_height + $gap;
  2315. if ($pos == 'plotdown' || $pos == 'both')
  2316. $bot_margin += $x_title_height + $gap;
  2317. }
  2318. // Space for X Labels above the plot?
  2319. if ($label_height_above > 0) {
  2320. $top_margin += $label_height_above + $gap;
  2321. $this->x_title_top_offset += $label_height_above + $gap;
  2322. }
  2323. // Space for X Labels below the plot?
  2324. if ($label_height_below > 0) {
  2325. $bot_margin += $label_height_below + $gap;
  2326. $this->x_title_bot_offset += $label_height_below + $gap;
  2327. }
  2328. // Space for X Ticks above the plot?
  2329. if ($x_tick_pos == 'plotup' || $x_tick_pos == 'both'
  2330. || ($x_tick_pos == 'xaxis' && $x_axis_pos == 'top')) {
  2331. $top_margin += $x_tick_len;
  2332. $this->x_label_top_offset = $x_tick_len + $gap;
  2333. $this->x_title_top_offset += $x_tick_len;
  2334. } else {
  2335. // No X Ticks above the plot:
  2336. $this->x_label_top_offset = $gap;
  2337. }
  2338. // Space for X Ticks below the plot?
  2339. if ($x_tick_pos == 'plotdown' || $x_tick_pos == 'both'
  2340. || ($x_tick_pos == 'xaxis' && $x_axis_pos == 'bottom')) {
  2341. $bot_margin += $x_tick_len;
  2342. $this->x_label_bot_offset = $x_tick_len + $gap;
  2343. $this->x_title_bot_offset += $x_tick_len;
  2344. } else {
  2345. // No X Ticks below the plot:
  2346. $this->x_label_bot_offset = $gap;
  2347. }
  2348. // Label offsets for on-axis ticks:
  2349. if ($x_tick_pos == 'xaxis') {
  2350. $this->x_label_axis_offset = $x_tick_len + $gap;
  2351. } else {
  2352. $this->x_label_axis_offset = $gap;
  2353. }
  2354. // Calculating Left and Right margins:
  2355. // x_left_margin: Left Y title, Y ticks and tick labels:
  2356. // x_right_margin: Right Y title, Y ticks and tick labels:
  2357. $left_margin = $gap;
  2358. $right_margin = $gap;
  2359. $this->y_title_left_offset = $gap;
  2360. $this->y_title_right_offset = $gap;
  2361. // Space for Y Title?
  2362. if ($y_title_width > 0) {
  2363. $pos = $this->y_title_pos;
  2364. if ($pos == 'plotleft' || $pos == 'both')
  2365. $left_margin += $y_title_width + $gap;
  2366. if ($pos == 'plotright' || $pos == 'both')
  2367. $right_margin += $y_title_width + $gap;
  2368. }
  2369. // Space for Y Labels left of the plot?
  2370. if ($label_width_left > 0) {
  2371. $left_margin += $label_width_left + $gap;
  2372. $this->y_title_left_offset += $label_width_left + $gap;
  2373. }
  2374. // Space for Y Labels right of the plot?
  2375. if ($label_width_right > 0) {
  2376. $right_margin += $label_width_right + $gap;
  2377. $this->y_title_right_offset += $label_width_right + $gap;
  2378. }
  2379. // Space for Y Ticks left of plot?
  2380. if ($y_tick_pos == 'plotleft' || $y_tick_pos == 'both'
  2381. || ($y_tick_pos == 'yaxis' && $y_axis_pos == 'left')) {
  2382. $left_margin += $y_tick_len;
  2383. $this->y_label_left_offset = $y_tick_len + $gap;
  2384. $this->y_title_left_offset += $y_tick_len;
  2385. } else {
  2386. // No Y Ticks left of plot:
  2387. $this->y_label_left_offset = $gap;
  2388. }
  2389. // Space for Y Ticks right of plot?
  2390. if ($y_tick_pos == 'plotright' || $y_tick_pos == 'both'
  2391. || ($y_tick_pos == 'yaxis' && $y_axis_pos == 'right')) {
  2392. $right_margin += $y_tick_len;
  2393. $this->y_label_right_offset = $y_tick_len + $gap;
  2394. $this->y_title_right_offset += $y_tick_len;
  2395. } else {
  2396. // No Y Ticks right of plot:
  2397. $this->y_label_right_offset = $gap;
  2398. }
  2399. // Label offsets for on-axis ticks:
  2400. if ($x_tick_pos == 'yaxis') {
  2401. $this->y_label_axis_offset = $y_tick_len + $gap;
  2402. } else {
  2403. $this->y_label_axis_offset = $gap;
  2404. }
  2405. // Apply the minimum margins and store in the object.
  2406. // Do not set margins which were user-defined (see note at top of function).
  2407. if (!isset($this->y_top_margin))
  2408. $this->y_top_margin = max($min_margin, $top_margin);
  2409. if (!isset($this->y_bot_margin))
  2410. $this->y_bot_margin = max($min_margin, $bot_margin);
  2411. if (!isset($this->x_left_margin))
  2412. $this->x_left_margin = max($min_margin, $left_margin);
  2413. if (!isset($this->x_right_margin))
  2414. $this->x_right_margin = max($min_margin, $right_margin);
  2415. if ($this->GetCallback('debug_scale')) {
  2416. // (Too bad compact() doesn't work on class member variables...)
  2417. $this->DoCallback('debug_scale', __FUNCTION__, array(
  2418. 'label_height_above' => $label_height_above,
  2419. 'label_height_below' => $label_height_below,
  2420. 'label_width_left' => $label_width_left,
  2421. 'label_width_right' => $label_width_right,
  2422. 'x_tick_len' => $x_tick_len,
  2423. 'y_tick_len' => $y_tick_len,
  2424. 'x_left_margin' => $this->x_left_margin,
  2425. 'x_right_margin' => $this->x_right_margin,
  2426. 'y_top_margin' => $this->y_top_margin,
  2427. 'y_bot_margin' => $this->y_bot_margin,
  2428. 'x_label_top_offset' => $this->x_label_top_offset,
  2429. 'x_label_bot_offset' => $this->x_label_bot_offset,
  2430. 'y_label_left_offset' => $this->y_label_left_offset,
  2431. 'y_label_right_offset' => $this->y_label_right_offset,
  2432. 'x_title_top_offset' => $this->x_title_top_offset,
  2433. 'x_title_bot_offset' => $this->x_title_bot_offset,
  2434. 'y_title_left_offset' => $this->y_title_left_offset,
  2435. 'y_title_right_offset' => $this->y_title_right_offset));
  2436. }
  2437. return TRUE;
  2438. }
  2439. /*
  2440. * Calculate the plot area (device coordinates) from the margins.
  2441. * (This used to be part of SetPlotAreaPixels.)
  2442. * The margins might come from SetMarginsPixels, SetPlotAreaPixels,
  2443. * or CalcMargins.
  2444. */
  2445. protected function CalcPlotAreaPixels()
  2446. {
  2447. $this->plot_area = array($this->x_left_margin, $this->y_top_margin,
  2448. $this->image_width - $this->x_right_margin,
  2449. $this->image_height - $this->y_bot_margin);
  2450. $this->plot_area_width = $this->plot_area[2] - $this->plot_area[0];
  2451. $this->plot_area_height = $this->plot_area[3] - $this->plot_area[1];
  2452. $this->DoCallback('debug_scale', __FUNCTION__, $this->plot_area);
  2453. return TRUE;
  2454. }
  2455. /*!
  2456. * Set the margins in pixels (left, right, top, bottom)
  2457. * This determines the plot area, equivalent to SetPlotAreaPixels().
  2458. * Deferred calculations now occur in CalcPlotAreaPixels().
  2459. */
  2460. function SetMarginsPixels($which_lm = NULL, $which_rm = NULL, $which_tm = NULL, $which_bm = NULL)
  2461. {
  2462. $this->x_left_margin = $which_lm;
  2463. $this->x_right_margin = $which_rm;
  2464. $this->y_top_margin = $which_tm;
  2465. $this->y_bot_margin = $which_bm;
  2466. return TRUE;
  2467. }
  2468. /*!
  2469. * Sets the limits for the plot area.
  2470. * This stores the margins, not the area. That may seem odd, but
  2471. * the idea is to make SetPlotAreaPixels and SetMarginsPixels two
  2472. * ways to accomplish the same thing, and the deferred calculations
  2473. * in CalcMargins and CalcPlotAreaPixels don't need to know which
  2474. * was used.
  2475. * (x1, y1) - Upper left corner of the plot area
  2476. * (x2, y2) - Lower right corner of the plot area
  2477. */
  2478. function SetPlotAreaPixels($x1 = NULL, $y1 = NULL, $x2 = NULL, $y2 = NULL)
  2479. {
  2480. $this->x_left_margin = $x1;
  2481. if (isset($x2)) $this->x_right_margin = $this->image_width - $x2;
  2482. else unset($this->x_right_margin);
  2483. $this->y_top_margin = $y1;
  2484. if (isset($y2)) $this->y_bot_margin = $this->image_height - $y2;
  2485. else unset($this->y_bot_margin);
  2486. return TRUE;
  2487. }
  2488. /*
  2489. * Calculate the World Coordinate limits of the plot area.
  2490. * This goes with SetPlotAreaWorld, but the calculations are
  2491. * deferred until the graph is being drawn.
  2492. * Uses: plot_min_x, plot_max_x, plot_min_y, plot_max_y
  2493. * which can be user-supplied or NULL to auto-calculate.
  2494. * Pre-requisites: FindDataLimits()
  2495. */
  2496. protected function CalcPlotAreaWorld()
  2497. {
  2498. if (isset($this->plot_min_x) && $this->plot_min_x !== '')
  2499. $xmin = $this->plot_min_x;
  2500. elseif ($this->data_type == 'text-data') // Valid for data without X values only.
  2501. $xmin = 0;
  2502. else
  2503. $xmin = $this->min_x;
  2504. if (isset($this->plot_max_x) && $this->plot_max_x !== '')
  2505. $xmax = $this->plot_max_x;
  2506. elseif ($this->data_type == 'text-data') // Valid for data without X values only.
  2507. $xmax = $this->max_x + 1;
  2508. else
  2509. $xmax = $this->max_x;
  2510. // Leave room above and below the highest and lowest data points.
  2511. if (!isset($this->plot_min_y) || $this->plot_min_y === '')
  2512. $ymin = floor($this->min_y - abs($this->min_y) * 0.1);
  2513. else
  2514. $ymin = $this->plot_min_y;
  2515. if (!isset($this->plot_max_y) || $this->plot_max_y === '')
  2516. $ymax = ceil($this->max_y + abs($this->max_y) * 0.1);
  2517. else
  2518. $ymax = $this->plot_max_y;
  2519. // Error checking
  2520. if ($ymin == $ymax)
  2521. $ymax++;
  2522. if ($xmin == $xmax)
  2523. $xmax++;
  2524. if ($this->yscale_type == 'log') {
  2525. if ($ymin <= 0) {
  2526. $ymin = 1;
  2527. }
  2528. if ($ymax <= 0) {
  2529. // Note: Error messages reference the user function, not this function.
  2530. return $this->PrintError('SetPlotAreaWorld(): Log plots need data greater than 0');
  2531. }
  2532. }
  2533. if ($ymax <= $ymin) {
  2534. return $this->PrintError('SetPlotAreaWorld(): Error in data - max not greater than min');
  2535. }
  2536. $this->plot_min_x = $xmin;
  2537. $this->plot_max_x = $xmax;
  2538. $this->plot_min_y = $ymin;
  2539. $this->plot_max_y = $ymax;
  2540. if ($this->GetCallback('debug_scale')) {
  2541. $this->DoCallback('debug_scale', __FUNCTION__, array(
  2542. 'plot_min_x' => $this->plot_min_x, 'plot_min_y' => $this->plot_min_y,
  2543. 'plot_max_x' => $this->plot_max_x, 'plot_max_y' => $this->plot_max_y));
  2544. }
  2545. return TRUE;
  2546. }
  2547. /*!
  2548. * Stores the desired World Coordinate range of the plot.
  2549. * The user calls this to force one or more of the range limits to
  2550. * specific values. Anything not set will be calculated in CalcPlotAreaWorld().
  2551. */
  2552. function SetPlotAreaWorld($xmin=NULL, $ymin=NULL, $xmax=NULL, $ymax=NULL)
  2553. {
  2554. $this->plot_min_x = $xmin;
  2555. $this->plot_max_x = $xmax;
  2556. $this->plot_min_y = $ymin;
  2557. $this->plot_max_y = $ymax;
  2558. return TRUE;
  2559. } //function SetPlotAreaWorld
  2560. /*!
  2561. * For bar plots, which have equally spaced x variables.
  2562. */
  2563. protected function CalcBarWidths()
  2564. {
  2565. // group_width is the width of a group, including padding
  2566. $group_width = $this->plot_area_width / $this->num_data_rows;
  2567. // Actual number of bar spaces in the group. This includes the drawn bars, and
  2568. // 'bar_extra_space'-worth of extra bars.
  2569. // Note that 'records_per_group' includes the label, so subtract one to get
  2570. // the number of points in the group. 'stackedbars' have 1 bar space per group.
  2571. if ($this->plot_type == 'stackedbars') {
  2572. $num_spots = 1 + $this->bar_extra_space;
  2573. } else {
  2574. $num_spots = $this->records_per_group - 1 + $this->bar_extra_space;
  2575. }
  2576. // record_bar_width is the width of each bar's allocated area.
  2577. // If bar_width_adjust=1 this is the width of the bar, otherwise
  2578. // the bar is centered inside record_bar_width.
  2579. // The equation is:
  2580. // group_frac_width * group_width = record_bar_width * num_spots
  2581. $this->record_bar_width = $this->group_frac_width * $group_width / $num_spots;
  2582. // Note that the extra space due to group_frac_width and bar_extra_space will be
  2583. // evenly divided on each side of the group: the drawn bars are centered in the group.
  2584. // Within each bar's allocated space, if bar_width_adjust=1 the bar fills the
  2585. // space, otherwise it is centered.
  2586. // This is the actual drawn bar width:
  2587. $this->actual_bar_width = $this->record_bar_width * $this->bar_width_adjust;
  2588. // This is the gap on each side of the bar (0 if bar_width_adjust=1):
  2589. $this->bar_adjust_gap = ($this->record_bar_width - $this->actual_bar_width) / 2;
  2590. return TRUE;
  2591. }
  2592. /*
  2593. * Calculate X and Y Axis Positions, world coordinates.
  2594. * This needs the min/max x/y range set by CalcPlotAreaWorld.
  2595. * It adjusts or sets x_axis_position and y_axis_position per the data.
  2596. * Empty string means the values need to be calculated; otherwise they
  2597. * are supplied but need to be validated against the World area.
  2598. *
  2599. * Note: This used to be in CalcTranslation, but CalcMargins needs it too.
  2600. * This does not calculate the pixel values of the axes. That happens in
  2601. * CalcTranslation, after scaling is set up (which has to happen after
  2602. * margins are set up).
  2603. */
  2604. protected function CalcAxisPositions()
  2605. {
  2606. // If no user-provided Y axis position, default to axis on left side.
  2607. // Otherwise, make sure user-provided position is inside the plot area.
  2608. if ($this->y_axis_position === '')
  2609. $this->y_axis_position = $this->plot_min_x;
  2610. else
  2611. $this->y_axis_position = min(max($this->plot_min_x, $this->y_axis_position), $this->plot_max_x);
  2612. // If no user-provided X axis position, default to axis at Y=0 (if in range), or min_y
  2613. // if the range does not include 0, or 1 for log plots.
  2614. // Otherwise, make sure user-provided position is inside the plot area.
  2615. if ($this->x_axis_position === '') {
  2616. if ($this->yscale_type == 'log')
  2617. $this->x_axis_position = 1;
  2618. elseif ($this->plot_min_y <= 0 && 0 <= $this->plot_max_y)
  2619. $this->x_axis_position = 0;
  2620. else
  2621. $this->x_axis_position = $this->plot_min_y;
  2622. } else
  2623. $this->x_axis_position = min(max($this->plot_min_y, $this->x_axis_position), $this->plot_max_y);
  2624. if ($this->GetCallback('debug_scale')) {
  2625. $this->DoCallback('debug_scale', __FUNCTION__, array(
  2626. 'x_axis_position' => $this->x_axis_position,
  2627. 'y_axis_position' => $this->y_axis_position));
  2628. }
  2629. return TRUE;
  2630. }
  2631. /*!
  2632. * Calculates scaling stuff...
  2633. */
  2634. protected function CalcTranslation()
  2635. {
  2636. if ($this->plot_max_x - $this->plot_min_x == 0) { // Check for div by 0
  2637. $this->xscale = 0;
  2638. } else {
  2639. if ($this->xscale_type == 'log') {
  2640. $this->xscale = ($this->plot_area_width)/(log10($this->plot_max_x) - log10($this->plot_min_x));
  2641. } else {
  2642. $this->xscale = ($this->plot_area_width)/($this->plot_max_x - $this->plot_min_x);
  2643. }
  2644. }
  2645. if ($this->plot_max_y - $this->plot_min_y == 0) { // Check for div by 0
  2646. $this->yscale = 0;
  2647. } else {
  2648. if ($this->yscale_type == 'log') {
  2649. $this->yscale = ($this->plot_area_height)/(log10($this->plot_max_y) - log10($this->plot_min_y));
  2650. } else {
  2651. $this->yscale = ($this->plot_area_height)/($this->plot_max_y - $this->plot_min_y);
  2652. }
  2653. }
  2654. // GD defines x = 0 at left and y = 0 at TOP so -/+ respectively
  2655. if ($this->xscale_type == 'log') {
  2656. $this->plot_origin_x = $this->plot_area[0] - ($this->xscale * log10($this->plot_min_x) );
  2657. } else {
  2658. $this->plot_origin_x = $this->plot_area[0] - ($this->xscale * $this->plot_min_x);
  2659. }
  2660. if ($this->yscale_type == 'log') {
  2661. $this->plot_origin_y = $this->plot_area[3] + ($this->yscale * log10($this->plot_min_y));
  2662. } else {
  2663. $this->plot_origin_y = $this->plot_area[3] + ($this->yscale * $this->plot_min_y);
  2664. }
  2665. // Convert axis positions to device coordinates:
  2666. $this->y_axis_x_pixels = $this->xtr($this->y_axis_position);
  2667. $this->x_axis_y_pixels = $this->ytr($this->x_axis_position);
  2668. if ($this->GetCallback('debug_scale')) {
  2669. $this->DoCallback('debug_scale', __FUNCTION__, array(
  2670. 'xscale' => $this->xscale, 'yscale' => $this->yscale,
  2671. 'plot_origin_x' => $this->plot_origin_x, 'plot_origin_y' => $this->plot_origin_y,
  2672. 'y_axis_x_pixels' => $this->y_axis_x_pixels,
  2673. 'x_axis_y_pixels' => $this->x_axis_y_pixels));
  2674. }
  2675. return TRUE;
  2676. } // function CalcTranslation()
  2677. /*!
  2678. * Translate X world coordinate into pixel coordinate
  2679. * See CalcTranslation() for calculation of xscale.
  2680. */
  2681. function xtr($x_world)
  2682. {
  2683. if ($this->xscale_type == 'log') {
  2684. $x_pixels = $this->plot_origin_x + log10($x_world) * $this->xscale ;
  2685. } else {
  2686. $x_pixels = $this->plot_origin_x + $x_world * $this->xscale ;
  2687. }
  2688. return round($x_pixels);
  2689. }
  2690. /*!
  2691. * Translate Y world coordinate into pixel coordinate.
  2692. * See CalcTranslation() for calculation of yscale.
  2693. */
  2694. function ytr($y_world)
  2695. {
  2696. if ($this->yscale_type == 'log') {
  2697. //minus because GD defines y = 0 at top. doh!
  2698. $y_pixels = $this->plot_origin_y - log10($y_world) * $this->yscale ;
  2699. } else {
  2700. $y_pixels = $this->plot_origin_y - $y_world * $this->yscale ;
  2701. }
  2702. return round($y_pixels);
  2703. }
  2704. /* A public interface to xtr and ytr. Translates (x,y) in world coordinates
  2705. * to (x,y) in device coordinates and returns them as an array.
  2706. * Usage is: list($x_pixel, $y_pixel) = $plot->GetDeviceXY($x_world, $y_world)
  2707. */
  2708. function GetDeviceXY($x_world, $y_world)
  2709. {
  2710. if (!isset($this->xscale)) {
  2711. return $this->PrintError("GetDeviceXY() was called before translation factors were calculated");
  2712. }
  2713. return array($this->xtr($x_world), $this->ytr($y_world));
  2714. }
  2715. /*
  2716. * Calculate tick parameters: Start, end, and delta values. This is used
  2717. * by both DrawXTicks() and DrawYTicks().
  2718. * This currently uses the same simplistic method previously used by
  2719. * PHPlot (basically just range/10), but splitting this out into its
  2720. * own function is the first step in replacing the method.
  2721. * This is also used by CalcMaxTickSize() for CalcMargins().
  2722. *
  2723. * $which : 'x' or 'y' : Which tick parameters to calculate
  2724. *
  2725. * Returns an array of 3 elements: tick_start, tick_end, tick_step
  2726. */
  2727. protected function CalcTicks($which)
  2728. {
  2729. if ($which == 'x') {
  2730. $num_ticks = $this->num_x_ticks;
  2731. $tick_inc = $this->x_tick_inc;
  2732. $data_max = $this->plot_max_x;
  2733. $data_min = $this->plot_min_x;
  2734. $skip_lo = $this->skip_left_tick;
  2735. $skip_hi = $this->skip_right_tick;
  2736. } elseif ($which == 'y') {
  2737. $num_ticks = $this->num_y_ticks;
  2738. $tick_inc = $this->y_tick_inc;
  2739. $data_max = $this->plot_max_y;
  2740. $data_min = $this->plot_min_y;
  2741. $skip_lo = $this->skip_bottom_tick;
  2742. $skip_hi = $this->skip_top_tick;
  2743. } else {
  2744. return $this->PrintError("CalcTicks: Invalid usage ($which)");
  2745. }
  2746. if (!empty($tick_inc)) {
  2747. $tick_step = $tick_inc;
  2748. } elseif (!empty($num_ticks)) {
  2749. $tick_step = ($data_max - $data_min) / $num_ticks;
  2750. } else {
  2751. $tick_step = ($data_max - $data_min) / 10;
  2752. }
  2753. // NOTE: When working with floats, because of approximations when adding $tick_step,
  2754. // the value may not quite reach the end, or may exceed it very slightly.
  2755. // So apply a "fudge" factor.
  2756. $tick_start = (double)$data_min;
  2757. $tick_end = (double)$data_max + ($data_max - $data_min) / 10000.0;
  2758. if ($skip_lo)
  2759. $tick_start += $tick_step;
  2760. if ($skip_hi)
  2761. $tick_end -= $tick_step;
  2762. return array($tick_start, $tick_end, $tick_step);
  2763. }
  2764. /*
  2765. * Calculate the size of the biggest tick label. This is used by CalcMargins().
  2766. * For 'x' ticks, it returns the height . For 'y' ticks, it returns the width.
  2767. * This means height along Y, or width along X - not relative to the text angle.
  2768. * That is what we need to calculate the needed margin space.
  2769. * (Previous versions of PHPlot estimated this, using the maximum X or Y value,
  2770. * or maybe the longest string. That doesn't work. -10 is longer than 9, etc.
  2771. * So this gets the actual size of each label, slow as that may be.
  2772. */
  2773. protected function CalcMaxTickLabelSize($which)
  2774. {
  2775. list($tick_start, $tick_end, $tick_step) = $this->CalcTicks($which);
  2776. if ($which == 'x') {
  2777. $font = $this->fonts['x_label'];
  2778. $angle = $this->x_label_angle;
  2779. } elseif ($which == 'y') {
  2780. $font = $this->fonts['y_label'];
  2781. $angle = $this->y_label_angle;
  2782. } else {
  2783. return $this->PrintError("CalcMaxTickLabelSize: Invalid usage ($which)");
  2784. }
  2785. $max_width = 0;
  2786. $max_height = 0;
  2787. // Loop over ticks, same as DrawXTicks and DrawYTicks:
  2788. // Avoid cumulative round-off errors from $val += $delta
  2789. $n = 0;
  2790. $tick_val = $tick_start;
  2791. while ($tick_val <= $tick_end) {
  2792. $tick_label = $this->FormatLabel($which, $tick_val);
  2793. list($width, $height) = $this->SizeText($font, $angle, $tick_label);
  2794. if ($width > $max_width) $max_width = $width;
  2795. if ($height > $max_height) $max_height = $height;
  2796. $tick_val = $tick_start + ++$n * $tick_step;
  2797. }
  2798. if ($this->GetCallback('debug_scale')) {
  2799. $this->DoCallback('debug_scale', __FUNCTION__, array(
  2800. 'which' => $which, 'height' => $max_height, 'width' => $max_width));
  2801. }
  2802. if ($which == 'x')
  2803. return $max_height;
  2804. return $max_width;
  2805. }
  2806. /*
  2807. * Calculate the size of the biggest X data label. This is used by CalcMargins().
  2808. * Returns the height along Y axis of the biggest X data label.
  2809. * (This calculates width and height, but only height is used at present.)
  2810. */
  2811. protected function CalcMaxDataLabelSize()
  2812. {
  2813. $font = $this->fonts['x_label'];
  2814. $angle = $this->x_data_label_angle;
  2815. $max_width = 0;
  2816. $max_height = 0;
  2817. // Loop over all data labels and find the biggest:
  2818. for ($i = 0; $i < $this->num_data_rows; $i++) {
  2819. $label = $this->FormatLabel('xd', $this->data[$i][0]);
  2820. list($width, $height) = $this->SizeText($font, $angle, $label);
  2821. if ($width > $max_width) $max_width = $width;
  2822. if ($height > $max_height) $max_height = $height;
  2823. }
  2824. if ($this->GetCallback('debug_scale')) {
  2825. $this->DoCallback('debug_scale', __FUNCTION__, array(
  2826. 'height' => $max_height, 'width' => $max_width));
  2827. }
  2828. return $max_height;
  2829. }
  2830. /*
  2831. * Check and set label parameters. This handles deferred processing for label
  2832. * positioning and other label-related parameters.
  2833. * Copy label_format from 'x' to 'xd', and 'y' to 'yd', if not already set.
  2834. * Set x_data_label_angle from x_label_angle, if not already set.
  2835. * Apply defaults to X tick and data label positions.
  2836. */
  2837. protected function CheckLabels()
  2838. {
  2839. // The X and Y data labels are formatted the same as X and Y tick labels,
  2840. // unless overridden. Check and apply defaults for FormatLabel here:
  2841. if (empty($this->label_format['xd']) && !empty($this->label_format['x']))
  2842. $this->label_format['xd'] = $this->label_format['x'];
  2843. if (empty($this->label_format['yd']) && !empty($this->label_format['y']))
  2844. $this->label_format['yd'] = $this->label_format['y'];
  2845. // The X tick label angle setting controls X data label angles too,
  2846. // unless overridden. Check and apply the default here:
  2847. if (!isset($this->x_data_label_angle))
  2848. $this->x_data_label_angle = $this->x_label_angle;
  2849. // Note: Y data label angle defaults to zero, unlike X,
  2850. // for compatibility with older releases.
  2851. // X Label position fixups, for x_data_label_pos and x_tick_label_pos:
  2852. if (isset($this->x_data_label_pos)) {
  2853. if (!isset($this->x_tick_label_pos)) {
  2854. // Case: data_label_pos is set, tick_label_pos needs a default:
  2855. if ($this->x_data_label_pos == 'none')
  2856. $this->x_tick_label_pos = 'plotdown';
  2857. else
  2858. $this->x_tick_label_pos = 'none';
  2859. }
  2860. } elseif (isset($this->x_tick_label_pos)) {
  2861. // Case: tick_label_pos is set, data_label_pos needs a default:
  2862. if ($this->x_tick_label_pos == 'none')
  2863. $this->x_data_label_pos = 'plotdown';
  2864. else
  2865. $this->x_data_label_pos = 'none';
  2866. } else {
  2867. // Case: Neither tick_label_pos nor data_label_pos is set.
  2868. // We do not want them to be both on (as PHPlot used to do in this case).
  2869. // Turn on data labels if any were supplied, else tick labels.
  2870. $data_labels_empty = TRUE;
  2871. for ($i = 0; $data_labels_empty && $i < $this->num_data_rows; $i++)
  2872. $data_labels_empty = ($this->data[$i][0] === '');
  2873. if ($data_labels_empty) {
  2874. $this->x_data_label_pos = 'none';
  2875. $this->x_tick_label_pos = 'plotdown';
  2876. } else {
  2877. $this->x_data_label_pos = 'plotdown';
  2878. $this->x_tick_label_pos = 'none';
  2879. }
  2880. }
  2881. return TRUE;
  2882. }
  2883. /*!
  2884. * Formats a tick or data label.
  2885. * which_pos - 'x', 'xd', 'y', or 'yd', selects formatting controls.
  2886. * x, y are for tick labels; xd, yd are for data labels.
  2887. * which_lab - String to format as a label.
  2888. * Credits: Time formatting suggested by Marlin Viss
  2889. * Custom formatting suggested by zer0x333
  2890. * Notes:
  2891. * Type 'title' is obsolete and retained for compatibility.
  2892. * Class variable 'data_units_text' is retained as a suffix for 'data' type formatting for
  2893. * backward compatibility. Since there was never a function/method to set it, there
  2894. * could be somebody out there who sets it directly in the object.
  2895. */
  2896. protected function FormatLabel($which_pos, $which_lab)
  2897. {
  2898. // Assign a reference shortcut to the label format controls.
  2899. // Note CheckLabels() made sure the 'xd' and 'yd' arrays are set.
  2900. $format =& $this->label_format[$which_pos];
  2901. // Don't format empty strings (especially as time or numbers), or if no type was set.
  2902. if ($which_lab !== '' && !empty($format['type'])) {
  2903. switch ($format['type']) {
  2904. case 'title': // Note: This is obsolete
  2905. $which_lab = @ $this->data[$which_lab][0];
  2906. break;
  2907. case 'data':
  2908. $which_lab = $format['prefix']
  2909. . $this->number_format($which_lab, $format['precision'])
  2910. . $this->data_units_text // Obsolete
  2911. . $format['suffix'];
  2912. break;
  2913. case 'time':
  2914. $which_lab = strftime($format['time_format'], $which_lab);
  2915. break;
  2916. case 'printf':
  2917. $which_lab = sprintf($format['printf_format'], $which_lab);
  2918. break;
  2919. case 'custom':
  2920. $which_lab = call_user_func($format['custom_callback'], $which_lab, $format['custom_arg']);
  2921. break;
  2922. }
  2923. }
  2924. return $which_lab;
  2925. } //function FormatLabel
  2926. /////////////////////////////////////////////
  2927. /////////////// TICKS
  2928. /////////////////////////////////////////////
  2929. /*!
  2930. * Use either this or SetNumXTicks() to set where to place x tick marks
  2931. */
  2932. function SetXTickIncrement($which_ti='')
  2933. {
  2934. $this->x_tick_inc = $which_ti;
  2935. if (!empty($which_ti)) {
  2936. $this->num_x_ticks = ''; //either use num_x_ticks or x_tick_inc, not both
  2937. }
  2938. return TRUE;
  2939. }
  2940. /*!
  2941. * Use either this or SetNumYTicks() to set where to place y tick marks
  2942. */
  2943. function SetYTickIncrement($which_ti='')
  2944. {
  2945. $this->y_tick_inc = $which_ti;
  2946. if (!empty($which_ti)) {
  2947. $this->num_y_ticks = ''; //either use num_y_ticks or y_tick_inc, not both
  2948. }
  2949. return TRUE;
  2950. }
  2951. function SetNumXTicks($which_nt)
  2952. {
  2953. $this->num_x_ticks = $which_nt;
  2954. if (!empty($which_nt)) {
  2955. $this->x_tick_inc = ''; //either use num_x_ticks or x_tick_inc, not both
  2956. }
  2957. return TRUE;
  2958. }
  2959. function SetNumYTicks($which_nt)
  2960. {
  2961. $this->num_y_ticks = $which_nt;
  2962. if (!empty($which_nt)) {
  2963. $this->y_tick_inc = ''; //either use num_y_ticks or y_tick_inc, not both
  2964. }
  2965. return TRUE;
  2966. }
  2967. /*!
  2968. *
  2969. */
  2970. function SetYTickPos($which_tp)
  2971. {
  2972. $this->y_tick_pos = $this->CheckOption($which_tp, 'plotleft, plotright, both, yaxis, none', __FUNCTION__);
  2973. return (boolean)$this->y_tick_pos;
  2974. }
  2975. /*!
  2976. *
  2977. */
  2978. function SetXTickPos($which_tp)
  2979. {
  2980. $this->x_tick_pos = $this->CheckOption($which_tp, 'plotdown, plotup, both, xaxis, none', __FUNCTION__);
  2981. return (boolean)$this->x_tick_pos;
  2982. }
  2983. /*!
  2984. * \param skip bool
  2985. */
  2986. function SetSkipTopTick($skip)
  2987. {
  2988. $this->skip_top_tick = (bool)$skip;
  2989. return TRUE;
  2990. }
  2991. /*!
  2992. * \param skip bool
  2993. */
  2994. function SetSkipBottomTick($skip)
  2995. {
  2996. $this->skip_bottom_tick = (bool)$skip;
  2997. return TRUE;
  2998. }
  2999. /*!
  3000. * \param skip bool
  3001. */
  3002. function SetSkipLeftTick($skip)
  3003. {
  3004. $this->skip_left_tick = (bool)$skip;
  3005. return TRUE;
  3006. }
  3007. /*!
  3008. * \param skip bool
  3009. */
  3010. function SetSkipRightTick($skip)
  3011. {
  3012. $this->skip_right_tick = (bool)$skip;
  3013. return TRUE;
  3014. }
  3015. function SetXTickLength($which_xln)
  3016. {
  3017. $this->x_tick_length = $which_xln;
  3018. return TRUE;
  3019. }
  3020. function SetYTickLength($which_yln)
  3021. {
  3022. $this->y_tick_length = $which_yln;
  3023. return TRUE;
  3024. }
  3025. function SetXTickCrossing($which_xc)
  3026. {
  3027. $this->x_tick_cross = $which_xc;
  3028. return TRUE;
  3029. }
  3030. function SetYTickCrossing($which_yc)
  3031. {
  3032. $this->y_tick_cross = $which_yc;
  3033. return TRUE;
  3034. }
  3035. /////////////////////////////////////////////
  3036. //////////////////// GENERIC DRAWING
  3037. /////////////////////////////////////////////
  3038. /*!
  3039. * Fills the background.
  3040. * Note: This method should be 'protected', but is called from test script(s).
  3041. */
  3042. function DrawBackground()
  3043. {
  3044. // Don't draw this twice if drawing two plots on one image
  3045. if (! $this->background_done) {
  3046. if (isset($this->bgimg)) { // If bgimg is defined, use it
  3047. $this->tile_img($this->bgimg, 0, 0, $this->image_width, $this->image_height, $this->bgmode);
  3048. } else { // Else use solid color
  3049. ImageFilledRectangle($this->img, 0, 0, $this->image_width, $this->image_height,
  3050. $this->ndx_bg_color);
  3051. }
  3052. $this->background_done = TRUE;
  3053. }
  3054. return TRUE;
  3055. }
  3056. /*!
  3057. * Fills the plot area background.
  3058. */
  3059. protected function DrawPlotAreaBackground()
  3060. {
  3061. if (isset($this->plotbgimg)) {
  3062. $this->tile_img($this->plotbgimg, $this->plot_area[0], $this->plot_area[1],
  3063. $this->plot_area_width, $this->plot_area_height, $this->plotbgmode);
  3064. }
  3065. else {
  3066. if ($this->draw_plot_area_background) {
  3067. ImageFilledRectangle($this->img, $this->plot_area[0], $this->plot_area[1],
  3068. $this->plot_area[2], $this->plot_area[3], $this->ndx_plot_bg_color);
  3069. }
  3070. }
  3071. return TRUE;
  3072. }
  3073. /*!
  3074. * Tiles an image at some given coordinates.
  3075. *
  3076. * \param $file string Filename of the picture to be used as tile.
  3077. * \param $xorig int X coordinate of the plot where the tile is to begin.
  3078. * \param $yorig int Y coordinate of the plot where the tile is to begin.
  3079. * \param $width int Width of the area to be tiled.
  3080. * \param $height int Height of the area to be tiled.
  3081. * \param $mode string One of 'centeredtile', 'tile', 'scale'.
  3082. */
  3083. protected function tile_img($file, $xorig, $yorig, $width, $height, $mode)
  3084. {
  3085. $im = $this->GetImage($file, $tile_width, $tile_height);
  3086. if (!$im)
  3087. return FALSE; // GetImage already produced an error message.
  3088. if ($mode == 'scale') {
  3089. imagecopyresized($this->img, $im, $xorig, $yorig, 0, 0, $width, $height, $tile_width, $tile_height);
  3090. return TRUE;
  3091. } else if ($mode == 'centeredtile') {
  3092. $x0 = - floor($tile_width/2); // Make the tile look better
  3093. $y0 = - floor($tile_height/2);
  3094. } else if ($mode = 'tile') {
  3095. $x0 = 0;
  3096. $y0 = 0;
  3097. }
  3098. // Actually draw the tile
  3099. // But first on a temporal image.
  3100. $tmp = ImageCreate($width, $height);
  3101. if (! $tmp)
  3102. return $this->PrintError('tile_img(): Could not create image resource.');
  3103. for ($x = $x0; $x < $width; $x += $tile_width)
  3104. for ($y = $y0; $y < $height; $y += $tile_height)
  3105. imagecopy($tmp, $im, $x, $y, 0, 0, $tile_width, $tile_height);
  3106. // Copy the temporal image onto the final one.
  3107. imagecopy($this->img, $tmp, $xorig, $yorig, 0,0, $width, $height);
  3108. // Free resources
  3109. imagedestroy($tmp);
  3110. imagedestroy($im);
  3111. return TRUE;
  3112. } // function tile_img
  3113. /*!
  3114. * Draws a border around the final image.
  3115. */
  3116. protected function DrawImageBorder()
  3117. {
  3118. switch ($this->image_border_type) {
  3119. case 'raised':
  3120. ImageLine($this->img, 0, 0, $this->image_width-1, 0, $this->ndx_i_border);
  3121. ImageLine($this->img, 1, 1, $this->image_width-2, 1, $this->ndx_i_border);
  3122. ImageLine($this->img, 0, 0, 0, $this->image_height-1, $this->ndx_i_border);
  3123. ImageLine($this->img, 1, 1, 1, $this->image_height-2, $this->ndx_i_border);
  3124. ImageLine($this->img, $this->image_width-1, 0, $this->image_width-1,
  3125. $this->image_height-1, $this->ndx_i_border_dark);
  3126. ImageLine($this->img, 0, $this->image_height-1, $this->image_width-1,
  3127. $this->image_height-1, $this->ndx_i_border_dark);
  3128. ImageLine($this->img, $this->image_width-2, 1, $this->image_width-2,
  3129. $this->image_height-2, $this->ndx_i_border_dark);
  3130. ImageLine($this->img, 1, $this->image_height-2, $this->image_width-2,
  3131. $this->image_height-2, $this->ndx_i_border_dark);
  3132. break;
  3133. case 'plain':
  3134. ImageLine($this->img, 0, 0, $this->image_width-1, 0, $this->ndx_i_border_dark);
  3135. ImageLine($this->img, $this->image_width-1, 0, $this->image_width-1,
  3136. $this->image_height-1, $this->ndx_i_border_dark);
  3137. ImageLine($this->img, $this->image_width-1, $this->image_height-1, 0, $this->image_height-1,
  3138. $this->ndx_i_border_dark);
  3139. ImageLine($this->img, 0, 0, 0, $this->image_height-1, $this->ndx_i_border_dark);
  3140. break;
  3141. case 'none':
  3142. break;
  3143. default:
  3144. return $this->PrintError("DrawImageBorder(): unknown image_border_type: '$this->image_border_type'");
  3145. }
  3146. return TRUE;
  3147. }
  3148. /*!
  3149. * Adds the title to the graph.
  3150. */
  3151. protected function DrawTitle()
  3152. {
  3153. // Center of the plot area
  3154. //$xpos = ($this->plot_area[0] + $this->plot_area_width )/ 2;
  3155. // Center of the image:
  3156. //$xpos = $this->image_width / 2;
  3157. $xpos = 0;
  3158. // Place it at almost at the top
  3159. $ypos = $this->safe_margin;
  3160. $this->DrawText($this->fonts['title'], 0, $xpos, $ypos,
  3161. $this->ndx_title_color, $this->title_txt, 'left', 'top');
  3162. return TRUE;
  3163. }
  3164. /*!
  3165. * Draws the X-Axis Title
  3166. */
  3167. protected function DrawXTitle()
  3168. {
  3169. if ($this->x_title_pos == 'none')
  3170. return TRUE;
  3171. // Center of the plot
  3172. $xpos = ($this->plot_area[2] + $this->plot_area[0]) / 2;
  3173. // Upper title
  3174. if ($this->x_title_pos == 'plotup' || $this->x_title_pos == 'both') {
  3175. $ypos = $this->plot_area[1] - $this->x_title_top_offset;
  3176. $this->DrawText($this->fonts['x_title'], 0, $xpos, $ypos, $this->ndx_title_color,
  3177. $this->x_title_txt, 'center', 'bottom');
  3178. }
  3179. // Lower title
  3180. if ($this->x_title_pos == 'plotdown' || $this->x_title_pos == 'both') {
  3181. $ypos = $this->plot_area[3] + $this->x_title_bot_offset;
  3182. $this->DrawText($this->fonts['x_title'], 0, $xpos, $ypos, $this->ndx_title_color,
  3183. $this->x_title_txt, 'center', 'top');
  3184. }
  3185. return TRUE;
  3186. }
  3187. /*!
  3188. * Draws the Y-Axis Title
  3189. */
  3190. protected function DrawYTitle()
  3191. {
  3192. if ($this->y_title_pos == 'none')
  3193. return TRUE;
  3194. // Center the title vertically to the plot area
  3195. $ypos = ($this->plot_area[3] + $this->plot_area[1]) / 2;
  3196. if ($this->y_title_pos == 'plotleft' || $this->y_title_pos == 'both') {
  3197. $xpos = $this->plot_area[0] - $this->y_title_left_offset;
  3198. $this->DrawText($this->fonts['y_title'], 90, $xpos, $ypos, $this->ndx_title_color,
  3199. $this->y_title_txt, 'right', 'center');
  3200. }
  3201. if ($this->y_title_pos == 'plotright' || $this->y_title_pos == 'both') {
  3202. $xpos = $this->plot_area[2] + $this->y_title_right_offset;
  3203. $this->DrawText($this->fonts['y_title'], 90, $xpos, $ypos, $this->ndx_title_color,
  3204. $this->y_title_txt, 'left', 'center');
  3205. }
  3206. return TRUE;
  3207. }
  3208. /*
  3209. * \note Horizontal grid lines overwrite horizontal axis with y=0, so call this first, then DrawXAxis()
  3210. */
  3211. protected function DrawYAxis()
  3212. {
  3213. // Draw ticks, labels and grid, if any
  3214. $this->DrawYTicks();
  3215. // Draw Y axis at X = y_axis_x_pixels
  3216. ImageLine($this->img, $this->y_axis_x_pixels, $this->plot_area[1],
  3217. $this->y_axis_x_pixels, $this->plot_area[3], $this->ndx_grid_color);
  3218. return TRUE;
  3219. }
  3220. /*
  3221. *
  3222. */
  3223. protected function DrawXAxis()
  3224. {
  3225. // Draw ticks, labels and grid
  3226. $this->DrawXTicks();
  3227. /* This tick and label tend to overlap with regular Y Axis labels,
  3228. * as Mike Pullen pointed out.
  3229. *
  3230. //Draw Tick and Label for X axis
  3231. if (! $this->skip_bottom_tick) {
  3232. $ylab =$this->FormatLabel('y', $this->x_axis_position);
  3233. $this->DrawYTick($ylab, $this->x_axis_y_pixels);
  3234. }
  3235. */
  3236. //Draw X Axis at Y = x_axis_y_pixels
  3237. ImageLine($this->img, $this->plot_area[0]+1, $this->x_axis_y_pixels,
  3238. $this->plot_area[2]-1, $this->x_axis_y_pixels, $this->ndx_grid_color);
  3239. return TRUE;
  3240. }
  3241. /*!
  3242. * Draw one Y tick mark and its tick label. Called from DrawYTicks() and DrawXAxis()
  3243. */
  3244. protected function DrawYTick($which_ylab, $which_ypix)
  3245. {
  3246. // Ticks on Y axis
  3247. if ($this->y_tick_pos == 'yaxis') {
  3248. ImageLine($this->img, $this->y_axis_x_pixels - $this->y_tick_length, $which_ypix,
  3249. $this->y_axis_x_pixels + $this->y_tick_cross, $which_ypix, $this->ndx_tick_color);
  3250. }
  3251. // Ticks to the left of the Plot Area
  3252. if (($this->y_tick_pos == 'plotleft') || ($this->y_tick_pos == 'both') ) {
  3253. ImageLine($this->img, $this->plot_area[0] - $this->y_tick_length, $which_ypix,
  3254. $this->plot_area[0] + $this->y_tick_cross, $which_ypix, $this->ndx_tick_color);
  3255. }
  3256. // Ticks to the right of the Plot Area
  3257. if (($this->y_tick_pos == 'plotright') || ($this->y_tick_pos == 'both') ) {
  3258. ImageLine($this->img, $this->plot_area[2] + $this->y_tick_length, $which_ypix,
  3259. $this->plot_area[2] - $this->y_tick_cross, $which_ypix, $this->ndx_tick_color);
  3260. }
  3261. // Labels on Y axis
  3262. if ($this->y_tick_label_pos == 'yaxis') {
  3263. $this->DrawText($this->fonts['y_label'], $this->y_label_angle,
  3264. $this->y_axis_x_pixels - $this->y_label_axis_offset, $which_ypix,
  3265. $this->ndx_text_color, $which_ylab, 'right', 'center');
  3266. }
  3267. // Labels to the left of the plot area
  3268. if ($this->y_tick_label_pos == 'plotleft' || $this->y_tick_label_pos == 'both') {
  3269. $this->DrawText($this->fonts['y_label'], $this->y_label_angle,
  3270. $this->plot_area[0] - $this->y_label_left_offset, $which_ypix,
  3271. $this->ndx_text_color, $which_ylab, 'right', 'center');
  3272. }
  3273. // Labels to the right of the plot area
  3274. if ($this->y_tick_label_pos == 'plotright' || $this->y_tick_label_pos == 'both') {
  3275. $this->DrawText($this->fonts['y_label'], $this->y_label_angle,
  3276. $this->plot_area[2] + $this->y_label_right_offset, $which_ypix,
  3277. $this->ndx_text_color, $which_ylab, 'left', 'center');
  3278. }
  3279. return TRUE;
  3280. } // Function DrawYTick()
  3281. /*!
  3282. * Draws Grid, Ticks and Tick Labels along Y-Axis
  3283. * Ticks and ticklabels can be left of plot only, right of plot only,
  3284. * both on the left and right of plot, or crossing a user defined Y-axis
  3285. */
  3286. protected function DrawYTicks()
  3287. {
  3288. // Sets the line style for IMG_COLOR_STYLED lines (grid)
  3289. if ($this->dashed_grid) {
  3290. $this->SetDashedStyle($this->ndx_light_grid_color);
  3291. $style = IMG_COLOR_STYLED;
  3292. } else {
  3293. $style = $this->ndx_light_grid_color;
  3294. }
  3295. // Calculate the tick start, end, and step:
  3296. list($y_start, $y_end, $delta_y) = $this->CalcTicks('y');
  3297. // Loop, avoiding cumulative round-off errors from $y_tmp += $delta_y
  3298. $n = 0;
  3299. $y_tmp = $y_start;
  3300. while ($y_tmp <= $y_end) {
  3301. $ylab = $this->FormatLabel('y', $y_tmp);
  3302. $y_pixels = $this->ytr($y_tmp);
  3303. // Horizontal grid line
  3304. if ($this->draw_y_grid) {
  3305. ImageLine($this->img, $this->plot_area[0]+1, $y_pixels, $this->plot_area[2]-1, $y_pixels, $style);
  3306. }
  3307. // Draw tick mark(s)
  3308. $this->DrawYTick($ylab, $y_pixels);
  3309. // Step to next Y, without accumulating error
  3310. $y_tmp = $y_start + ++$n * $delta_y;
  3311. }
  3312. return TRUE;
  3313. } // function DrawYTicks
  3314. /*!
  3315. * Draw one X tick mark and its tick label.
  3316. */
  3317. protected function DrawXTick($which_xlab, $which_xpix)
  3318. {
  3319. // Ticks on X axis
  3320. if ($this->x_tick_pos == 'xaxis') {
  3321. ImageLine($this->img, $which_xpix, $this->x_axis_y_pixels - $this->x_tick_cross,
  3322. $which_xpix, $this->x_axis_y_pixels + $this->x_tick_length, $this->ndx_tick_color);
  3323. }
  3324. // Ticks on top of the Plot Area
  3325. if ($this->x_tick_pos == 'plotup' || $this->x_tick_pos == 'both') {
  3326. ImageLine($this->img, $which_xpix, $this->plot_area[1] - $this->x_tick_length,
  3327. $which_xpix, $this->plot_area[1] + $this->x_tick_cross, $this->ndx_tick_color);
  3328. }
  3329. // Ticks on bottom of Plot Area
  3330. if ($this->x_tick_pos == 'plotdown' || $this->x_tick_pos == 'both') {
  3331. ImageLine($this->img, $which_xpix, $this->plot_area[3] + $this->x_tick_length,
  3332. $which_xpix, $this->plot_area[3] - $this->x_tick_cross, $this->ndx_tick_color);
  3333. }
  3334. // Label on X axis
  3335. if ($this->x_tick_label_pos == 'xaxis') {
  3336. $this->DrawText($this->fonts['x_label'], $this->x_label_angle,
  3337. $which_xpix, $this->x_axis_y_pixels + $this->x_label_axis_offset,
  3338. $this->ndx_text_color, $which_xlab, 'center', 'top');
  3339. }
  3340. // Label on top of the Plot Area
  3341. if ($this->x_tick_label_pos == 'plotup' || $this->x_tick_label_pos == 'both') {
  3342. $this->DrawText($this->fonts['x_label'], $this->x_label_angle,
  3343. $which_xpix, $this->plot_area[1] - $this->x_label_top_offset,
  3344. $this->ndx_text_color, $which_xlab, 'center', 'bottom');
  3345. }
  3346. // Label on bottom of the Plot Area
  3347. if ($this->x_tick_label_pos == 'plotdown' || $this->x_tick_label_pos == 'both') {
  3348. $this->DrawText($this->fonts['x_label'], $this->x_label_angle,
  3349. $which_xpix, $this->plot_area[3] + $this->x_label_bot_offset,
  3350. $this->ndx_text_color, $which_xlab, 'center', 'top');
  3351. }
  3352. return TRUE;
  3353. }
  3354. /*!
  3355. * Draws Grid, Ticks and Tick Labels along X-Axis
  3356. * Ticks and tick labels can be down of plot only, up of plot only,
  3357. * both on up and down of plot, or crossing a user defined X-axis
  3358. *
  3359. * \note Original vertical code submitted by Marlin Viss
  3360. */
  3361. protected function DrawXTicks()
  3362. {
  3363. // Sets the line style for IMG_COLOR_STYLED lines (grid)
  3364. if ($this->dashed_grid) {
  3365. $this->SetDashedStyle($this->ndx_light_grid_color);
  3366. $style = IMG_COLOR_STYLED;
  3367. } else {
  3368. $style = $this->ndx_light_grid_color;
  3369. }
  3370. // Calculate the tick start, end, and step:
  3371. list($x_start, $x_end, $delta_x) = $this->CalcTicks('x');
  3372. // Loop, avoiding cumulative round-off errors from $x_tmp += $delta_x
  3373. $n = 0;
  3374. $x_tmp = $x_start;
  3375. while ($x_tmp <= $x_end) {
  3376. $xlab = $this->FormatLabel('x', $x_tmp);
  3377. $x_pixels = $this->xtr($x_tmp);
  3378. // Vertical grid lines
  3379. if ($this->draw_x_grid) {
  3380. ImageLine($this->img, $x_pixels, $this->plot_area[1], $x_pixels, $this->plot_area[3], $style);
  3381. }
  3382. // Draw tick mark(s)
  3383. $this->DrawXTick($xlab, $x_pixels);
  3384. // Step to next X, without accumulating error
  3385. $x_tmp = $x_start + ++$n * $delta_x;
  3386. }
  3387. return TRUE;
  3388. } // function DrawXTicks
  3389. /*!
  3390. *
  3391. */
  3392. protected function DrawPlotBorder()
  3393. {
  3394. switch ($this->plot_border_type) {
  3395. case 'left': // for past compatibility
  3396. case 'plotleft':
  3397. ImageLine($this->img, $this->plot_area[0], $this->ytr($this->plot_min_y),
  3398. $this->plot_area[0], $this->ytr($this->plot_max_y), $this->ndx_grid_color);
  3399. break;
  3400. case 'right':
  3401. case 'plotright':
  3402. ImageLine($this->img, $this->plot_area[2], $this->ytr($this->plot_min_y),
  3403. $this->plot_area[2], $this->ytr($this->plot_max_y), $this->ndx_grid_color);
  3404. break;
  3405. case 'both':
  3406. case 'sides':
  3407. ImageLine($this->img, $this->plot_area[0], $this->ytr($this->plot_min_y),
  3408. $this->plot_area[0], $this->ytr($this->plot_max_y), $this->ndx_grid_color);
  3409. ImageLine($this->img, $this->plot_area[2], $this->ytr($this->plot_min_y),
  3410. $this->plot_area[2], $this->ytr($this->plot_max_y), $this->ndx_grid_color);
  3411. break;
  3412. case 'none':
  3413. //Draw No Border
  3414. break;
  3415. case 'full':
  3416. default:
  3417. ImageRectangle($this->img, $this->plot_area[0], $this->ytr($this->plot_min_y),
  3418. $this->plot_area[2], $this->ytr($this->plot_max_y), $this->ndx_grid_color);
  3419. break;
  3420. }
  3421. return TRUE;
  3422. }
  3423. /*!
  3424. * Draws the data label associated with a point in the plot at specified x/y world position.
  3425. * This is currently only used for Y data labels for bar charts.
  3426. */
  3427. protected function DrawDataLabel($which_font, $which_angle, $x_world, $y_world, $which_color, $which_text,
  3428. $which_halign = 'center', $which_valign = 'bottom', $x_adjustment=0, $y_adjustment=0)
  3429. {
  3430. $this->DrawText($which_font, $which_angle,
  3431. $this->xtr($x_world) + $x_adjustment, $this->ytr($y_world) + $y_adjustment,
  3432. $which_color, $this->FormatLabel('yd', $which_text), $which_halign, $which_valign);
  3433. return TRUE;
  3434. }
  3435. /*!
  3436. * Draws the data label associated with a point in the plot.
  3437. * This is different from x_labels drawn by DrawXTicks() and care
  3438. * should be taken not to draw both, as they'd probably overlap.
  3439. * Calling of this function in DrawLines(), etc is decided after x_data_label_pos value.
  3440. * Leave the last parameter out, to avoid the drawing of vertical lines, no matter
  3441. * what the setting is (for plots that need it, like DrawSquared())
  3442. */
  3443. protected function DrawXDataLabel($xlab, $xpos, $row=FALSE)
  3444. {
  3445. $xlab = $this->FormatLabel('xd', $xlab);
  3446. // Labels below the plot area
  3447. if ($this->x_data_label_pos == 'plotdown' || $this->x_data_label_pos == 'both')
  3448. $this->DrawText($this->fonts['x_label'], $this->x_data_label_angle,
  3449. $xpos, $this->plot_area[3] + $this->x_label_bot_offset,
  3450. $this->ndx_text_color, $xlab, 'center', 'top');
  3451. // Labels above the plot area
  3452. if ($this->x_data_label_pos == 'plotup' || $this->x_data_label_pos == 'both')
  3453. $this->DrawText($this->fonts['x_label'], $this->x_data_label_angle,
  3454. $xpos, $this->plot_area[1] - $this->x_label_top_offset,
  3455. $this->ndx_text_color, $xlab, 'center', 'bottom');
  3456. // $row=0 means this is the first row. $row=FALSE means don't do any rows.
  3457. if ($row !== FALSE && $this->draw_x_data_label_lines)
  3458. $this->DrawXDataLine($xpos, $row);
  3459. return TRUE;
  3460. }
  3461. /*!
  3462. * Draws Vertical lines from data points up and down.
  3463. * Which lines are drawn depends on the value of x_data_label_pos,
  3464. * and whether this is at all done or not, on draw_x_data_label_lines
  3465. *
  3466. * \param xpos int position in pixels of the line.
  3467. * \param row int index of the data row being drawn.
  3468. */
  3469. protected function DrawXDataLine($xpos, $row)
  3470. {
  3471. // Sets the line style for IMG_COLOR_STYLED lines (grid)
  3472. if($this->dashed_grid) {
  3473. $this->SetDashedStyle($this->ndx_light_grid_color);
  3474. $style = IMG_COLOR_STYLED;
  3475. } else {
  3476. $style = $this->ndx_light_grid_color;
  3477. }
  3478. // Lines from the bottom up
  3479. if ($this->x_data_label_pos == 'both') {
  3480. ImageLine($this->img, $xpos, $this->plot_area[3], $xpos, $this->plot_area[1], $style);
  3481. }
  3482. // Lines from the bottom of the plot up to the max Y value at this X:
  3483. else if ($this->x_data_label_pos == 'plotdown' && isset($this->data_maxy[$row])) {
  3484. $ypos = $this->ytr($this->data_maxy[$row]);
  3485. ImageLine($this->img, $xpos, $ypos, $xpos, $this->plot_area[3], $style);
  3486. }
  3487. // Lines from the top of the plot down to the min Y value at this X:
  3488. else if ($this->x_data_label_pos == 'plotup' && isset($this->data_miny[$row])) {
  3489. $ypos = $this->ytr($this->data_miny[$row]);
  3490. ImageLine($this->img, $xpos, $this->plot_area[1], $xpos, $ypos, $style);
  3491. }
  3492. return TRUE;
  3493. }
  3494. /*!
  3495. * Draws the graph legend
  3496. *
  3497. * \note Base code submitted by Marlin Viss
  3498. */
  3499. protected function DrawLegend()
  3500. {
  3501. $font = &$this->fonts['legend'];
  3502. // Find maximum legend label line width.
  3503. $max_width = 0;
  3504. foreach ($this->legend as $line) {
  3505. list($width, $unused) = $this->SizeText($font, 0, $line);
  3506. if ($width > $max_width) $max_width = $width;
  3507. }
  3508. // Use the font parameters to size the color boxes:
  3509. $char_w = $font['width'];
  3510. $char_h = $font['height'];
  3511. $line_spacing = $this->GetLineSpacing($font);
  3512. // Normalize text alignment and colorbox alignment variables:
  3513. $text_align = isset($this->legend_text_align) ? $this->legend_text_align : 'right';
  3514. $colorbox_align = isset($this->legend_colorbox_align) ? $this->legend_colorbox_align : 'right';
  3515. // Sizing parameters:
  3516. $v_margin = $char_h/2; // Between vertical borders and labels
  3517. $dot_height = $char_h + $line_spacing; // Height of the small colored boxes
  3518. // Overall legend box width e.g.: | space colorbox space text space |
  3519. // where colorbox and each space are 1 char width.
  3520. if ($colorbox_align != 'none') {
  3521. $width = $max_width + 4 * $char_w;
  3522. $draw_colorbox = True;
  3523. } else {
  3524. $width = $max_width + 2 * $char_w;
  3525. $draw_colorbox = False;
  3526. }
  3527. //////// Calculate box position
  3528. // User-defined position specified?
  3529. if ( !isset($this->legend_x_pos) || !isset($this->legend_y_pos)) {
  3530. // No, use default
  3531. $box_start_x = $this->plot_area[2] - $width - $this->safe_margin;
  3532. $box_start_y = $this->plot_area[1] + $this->safe_margin;
  3533. } elseif (isset($this->legend_xy_world)) {
  3534. // User-defined position in world-coordinates (See SetLegendWorld).
  3535. $box_start_x = $this->xtr($this->legend_x_pos);
  3536. $box_start_y = $this->ytr($this->legend_y_pos);
  3537. unset($this->legend_xy_world);
  3538. } else {
  3539. // User-defined position in pixel coordinates.
  3540. $box_start_x = $this->legend_x_pos;
  3541. $box_start_y = $this->legend_y_pos;
  3542. }
  3543. // Lower right corner
  3544. $box_end_y = $box_start_y + $dot_height*(count($this->legend)) + 2*$v_margin;
  3545. $box_end_x = $box_start_x + $width;
  3546. // Draw outer box
  3547. ImageFilledRectangle($this->img, $box_start_x, $box_start_y, $box_end_x, $box_end_y, $this->ndx_bg_color);
  3548. ImageRectangle($this->img, $box_start_x, $box_start_y, $box_end_x, $box_end_y, $this->ndx_grid_color);
  3549. $color_index = 0;
  3550. $max_color_index = count($this->ndx_data_colors) - 1;
  3551. // Calculate color box and text horizontal positions.
  3552. if (!$draw_colorbox) {
  3553. if ($text_align == 'left')
  3554. $x_pos = $box_start_x + $char_w;
  3555. else
  3556. $x_pos = $box_end_x - $char_w;
  3557. } elseif ($colorbox_align == 'left') {
  3558. $dot_left_x = $box_start_x + $char_w;
  3559. $dot_right_x = $dot_left_x + $char_w;
  3560. if ($text_align == 'left')
  3561. $x_pos = $dot_left_x + 2 * $char_w;
  3562. else
  3563. $x_pos = $box_end_x - $char_w;
  3564. } else {
  3565. $dot_left_x = $box_end_x - 2 * $char_w;
  3566. $dot_right_x = $dot_left_x + $char_w;
  3567. if ($text_align == 'left')
  3568. $x_pos = $box_start_x + $char_w;
  3569. else
  3570. $x_pos = $dot_left_x - $char_w;
  3571. }
  3572. // Calculate starting position of first text line. The bottom of each color box
  3573. // lines up with the bottom (baseline) of its text line.
  3574. $y_pos = $box_start_y + $v_margin + $dot_height;
  3575. foreach ($this->legend as $leg) {
  3576. // Draw text with requested alignment:
  3577. $this->DrawText($font, 0, $x_pos, $y_pos, $this->ndx_text_color, $leg, $text_align, 'bottom');
  3578. if ($draw_colorbox) {
  3579. // Draw a box in the data color
  3580. $y1 = $y_pos - $dot_height + 1;
  3581. $y2 = $y_pos - 1;
  3582. ImageFilledRectangle($this->img, $dot_left_x, $y1, $dot_right_x, $y2,
  3583. $this->ndx_data_colors[$color_index]);
  3584. // Draw a rectangle around the box
  3585. ImageRectangle($this->img, $dot_left_x, $y1, $dot_right_x, $y2,
  3586. $this->ndx_text_color);
  3587. }
  3588. $y_pos += $dot_height;
  3589. $color_index++;
  3590. if ($color_index > $max_color_index)
  3591. $color_index = 0;
  3592. }
  3593. return TRUE;
  3594. } // Function DrawLegend()
  3595. /////////////////////////////////////////////
  3596. //////////////////// PLOT DRAWING
  3597. /////////////////////////////////////////////
  3598. /*!
  3599. * Draws a pie chart. Data is 'text-data', 'data-data', or 'text-data-single'.
  3600. *
  3601. * For text-data-single, the data array contains records with an ignored label,
  3602. * and one Y value. Each record defines a sector of the pie, as a portion of
  3603. * the sum of all Y values.
  3604. *
  3605. * For text-data and data-data, the data array contains records with an ignored label,
  3606. * an ignored X value (for data-data only), and N (N>=1) Y values per record.
  3607. * The pie chart will be produced with N segments. The relative size of the first
  3608. * sector of the pie is the sum of the first Y data value in each record, etc.
  3609. *
  3610. * Note: With text-data-single, the data labels could be used, but are not currently.
  3611. *
  3612. * If there are no valid data points > 0 at all, just draw nothing. It may seem more correct to
  3613. * raise an error, but all of the other plot types handle it this way implicitly. DrawGraph
  3614. * checks for an empty data array, but this is different: a non-empty data array with no Y values,
  3615. * or all Y=0.
  3616. */
  3617. protected function DrawPieChart()
  3618. {
  3619. $xpos = $this->plot_area[0] + $this->plot_area_width/2;
  3620. $ypos = $this->plot_area[1] + $this->plot_area_height/2;
  3621. $diameter = min($this->plot_area_width, $this->plot_area_height);
  3622. $radius = $diameter/2;
  3623. // Get sum of each column? One pie slice per column
  3624. if ($this->data_type == 'text-data') {
  3625. $num_slices = $this->records_per_group - 1; // records_per_group is the maximum row size
  3626. if ($num_slices < 1) return TRUE; // Give up early if there is no data at all.
  3627. $sumarr = array_fill(0, $num_slices, 0);
  3628. for ($i = 0; $i < $this->num_data_rows; $i++) {
  3629. for ($j = 1; $j < $this->num_recs[$i]; $j++) { // Skip label at [0]
  3630. if (is_numeric($this->data[$i][$j]))
  3631. $sumarr[$j-1] += abs($this->data[$i][$j]);
  3632. }
  3633. }
  3634. }
  3635. // Or only one column per row, one pie slice per row?
  3636. else if ($this->data_type == 'text-data-single') {
  3637. $num_slices = $this->num_data_rows;
  3638. if ($num_slices < 1) return TRUE; // Give up early if there is no data at all.
  3639. $sumarr = array_fill(0, $num_slices, 0);
  3640. for ($i = 0; $i < $num_slices; $i++) {
  3641. // $legend[$i] = $this->data[$i][0]; // Note: Labels are not used yet
  3642. if (is_numeric($this->data[$i][1]))
  3643. $sumarr[$i] = abs($this->data[$i][1]);
  3644. }
  3645. }
  3646. else if ($this->data_type == 'data-data') {
  3647. $num_slices = $this->records_per_group - 2; // records_per_group is the maximum row size
  3648. if ($num_slices < 1) return TRUE; // Give up early if there is no data at all.
  3649. $sumarr = array_fill(0, $num_slices, 0);
  3650. for ($i = 0; $i < $this->num_data_rows; $i++) {
  3651. for ($j = 2; $j < $this->num_recs[$i]; $j++) { // Skip label at [0] an X and [1]
  3652. if (is_numeric($this->data[$i][$j]))
  3653. $sumarr[$j-2] += abs($this->data[$i][$j]);
  3654. }
  3655. }
  3656. }
  3657. else {
  3658. return $this->PrintError("DrawPieChart(): Data type '$this->data_type' not supported.");
  3659. }
  3660. $total = array_sum($sumarr);
  3661. if ($total == 0) {
  3662. // There are either no valid data points, or all are 0.
  3663. // See top comment about why not to make this an error.
  3664. return TRUE;
  3665. }
  3666. if ($this->shading) {
  3667. $diam2 = $diameter / 2;
  3668. } else {
  3669. $diam2 = $diameter;
  3670. }
  3671. $max_data_colors = count ($this->data_colors);
  3672. // Use the Y label format precision, with default value:
  3673. if (isset($this->label_format['y']['precision']))
  3674. $precision = $this->label_format['y']['precision'];
  3675. else
  3676. $precision = 1;
  3677. for ($h = $this->shading; $h >= 0; $h--) {
  3678. $color_index = 0;
  3679. $start_angle = 0;
  3680. $end_angle = 0;
  3681. for ($j = 0; $j < $num_slices; $j++) {
  3682. $val = $sumarr[$j];
  3683. // For shaded pies: the last one (at the top of the "stack") has a brighter color:
  3684. if ($h == 0)
  3685. $slicecol = $this->ndx_data_colors[$color_index];
  3686. else
  3687. $slicecol = $this->ndx_data_dark_colors[$color_index];
  3688. $label_txt = $this->number_format(($val / $total * 100), $precision) . '%';
  3689. $val = 360 * ($val / $total);
  3690. // NOTE that imagefilledarc measures angles CLOCKWISE (go figure why),
  3691. // so the pie chart would start clockwise from 3 o'clock, would it not be
  3692. // for the reversal of start and end angles in imagefilledarc()
  3693. // Also note ImageFilledArc only takes angles in integer degrees, and if the
  3694. // the start and end angles match then you get a full circle not a zero-width
  3695. // pie. This is bad. So skip any zero-size wedge. On the other hand, we cannot
  3696. // let cumulative error from rounding to integer result in missing wedges. So
  3697. // keep the running total as a float, and round the angles. It should not
  3698. // be necessary to check that the last wedge ends at 360 degrees.
  3699. $start_angle = $end_angle;
  3700. $end_angle += $val;
  3701. // This method of conversion to integer - truncate after reversing it - was
  3702. // chosen to match the implicit method of PHPlot<=5.0.4 to get the same slices.
  3703. $arc_start_angle = (int)(360 - $start_angle);
  3704. $arc_end_angle = (int)(360 - $end_angle);
  3705. if ($arc_start_angle > $arc_end_angle) {
  3706. $mid_angle = deg2rad($end_angle - ($val / 2));
  3707. // Draw the slice
  3708. ImageFilledArc($this->img, $xpos, $ypos+$h, $diameter, $diam2,
  3709. $arc_end_angle, $arc_start_angle,
  3710. $slicecol, IMG_ARC_PIE);
  3711. // Draw the labels only once
  3712. if ($h == 0) {
  3713. // Draw the outline
  3714. if (! $this->shading)
  3715. ImageFilledArc($this->img, $xpos, $ypos+$h, $diameter, $diam2,
  3716. $arc_end_angle, $arc_start_angle,
  3717. $this->ndx_grid_color, IMG_ARC_PIE | IMG_ARC_EDGED |IMG_ARC_NOFILL);
  3718. // The '* 1.2' trick is to get labels out of the pie chart so there are more
  3719. // chances they can be seen in small sectors.
  3720. $label_x = $xpos + ($diameter * 1.2 * cos($mid_angle)) * $this->label_scale_position;
  3721. $label_y = $ypos+$h - ($diam2 * 1.2 * sin($mid_angle)) * $this->label_scale_position;
  3722. $this->DrawText($this->fonts['generic'], 0, $label_x, $label_y, $this->ndx_grid_color,
  3723. $label_txt, 'center', 'center');
  3724. }
  3725. }
  3726. if (++$color_index >= $max_data_colors)
  3727. $color_index = 0;
  3728. } // end for
  3729. } // end for
  3730. return TRUE;
  3731. }
  3732. /*!
  3733. * Supported data formats: data-data-error, text-data-error (doesn't exist yet)
  3734. * ( data comes in as array("title", x, y, error+, error-, y2, error2+, error2-, ...) )
  3735. */
  3736. protected function DrawDotsError()
  3737. {
  3738. if ($this->data_type != 'data-data-error') {
  3739. return $this->PrintError("DrawDotsError(): Data type '$this->data_type' not supported.");
  3740. }
  3741. // Adjust the point shapes and point sizes arrays:
  3742. $this->CheckPointParams();
  3743. // Suppress duplicate X data labels in linepoints mode; let DrawLinesError() do them.
  3744. $do_labels = ($this->plot_type != 'linepoints');
  3745. for($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
  3746. $record = 1; // Skip record #0 (title)
  3747. $x_now = $this->data[$row][$record++]; // Read it, advance record index
  3748. $x_now_pixels = $this->xtr($x_now); // Absolute coordinates.
  3749. // Draw X Data labels?
  3750. if ($this->x_data_label_pos != 'none' && $do_labels)
  3751. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  3752. // Now go for Y, E+, E-
  3753. for ($idx = 0; $record < $this->num_recs[$row]; $idx++) {
  3754. if (is_numeric($this->data[$row][$record])) { // Allow for missing Y data
  3755. // Y:
  3756. $y_now = $this->data[$row][$record++];
  3757. $this->DrawDot($x_now, $y_now, $idx, $this->ndx_data_colors[$idx]);
  3758. // Error +
  3759. $val = $this->data[$row][$record++];
  3760. $this->DrawYErrorBar($x_now, $y_now, $val, $this->error_bar_shape,
  3761. $this->ndx_error_bar_colors[$idx]);
  3762. // Error -
  3763. $val = $this->data[$row][$record++];
  3764. $this->DrawYErrorBar($x_now, $y_now, -$val, $this->error_bar_shape,
  3765. $this->ndx_error_bar_colors[$idx]);
  3766. } else {
  3767. $record += 3; // Skip over missing Y and its error values
  3768. }
  3769. }
  3770. }
  3771. return TRUE;
  3772. } // function DrawDotsError()
  3773. /*
  3774. * Supported data types:
  3775. * - data-data ("title", x, y1, y2, y3, ...)
  3776. * - text-data ("title", y1, y2, y3, ...)
  3777. */
  3778. protected function DrawDots()
  3779. {
  3780. if (!$this->CheckOption($this->data_type, 'text-data, data-data', __FUNCTION__))
  3781. return FALSE;
  3782. // Adjust the point shapes and point sizes arrays:
  3783. $this->CheckPointParams();
  3784. // Suppress duplicate X data labels in linepoints mode; let DrawLines() do them.
  3785. $do_labels = ($this->plot_type != 'linepoints');
  3786. for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
  3787. $rec = 1; // Skip record #0 (data label)
  3788. // Do we have a value for X?
  3789. if ($this->data_type == 'data-data')
  3790. $x_now = $this->data[$row][$rec++]; // Read it, advance record index
  3791. else
  3792. $x_now = 0.5 + $cnt++; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  3793. $x_now_pixels = $this->xtr($x_now);
  3794. // Draw X Data labels?
  3795. if ($this->x_data_label_pos != 'none' && $do_labels)
  3796. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  3797. // Proceed with Y values
  3798. for($idx = 0;$rec < $this->num_recs[$row]; $rec++, $idx++) {
  3799. if (is_numeric($this->data[$row][$rec])) { // Allow for missing Y data
  3800. $this->DrawDot($x_now, $this->data[$row][$rec],
  3801. $idx, $this->ndx_data_colors[$idx]);
  3802. }
  3803. }
  3804. }
  3805. return TRUE;
  3806. } //function DrawDots
  3807. /*!
  3808. * A clean, fast routine for when you just want charts like stock volume charts
  3809. */
  3810. protected function DrawThinBarLines()
  3811. {
  3812. if (!$this->CheckOption($this->data_type, 'text-data, data-data', __FUNCTION__))
  3813. return FALSE;
  3814. for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
  3815. $rec = 1; // Skip record #0 (data label)
  3816. // Do we have a value for X?
  3817. if ($this->data_type == 'data-data')
  3818. $x_now = $this->data[$row][$rec++]; // Read it, advance record index
  3819. else
  3820. $x_now = 0.5 + $cnt++; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  3821. $x_now_pixels = $this->xtr($x_now);
  3822. // Draw X Data labels?
  3823. if ($this->x_data_label_pos != 'none')
  3824. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels);
  3825. // Proceed with Y values
  3826. for($idx = 0;$rec < $this->num_recs[$row]; $rec++, $idx++) {
  3827. if (is_numeric($this->data[$row][$rec])) { // Allow for missing Y data
  3828. ImageSetThickness($this->img, $this->line_widths[$idx]);
  3829. // Draws a line from user defined x axis position up to ytr($val)
  3830. ImageLine($this->img, $x_now_pixels, $this->x_axis_y_pixels, $x_now_pixels,
  3831. $this->ytr($this->data[$row][$rec]), $this->ndx_data_colors[$idx]);
  3832. }
  3833. }
  3834. }
  3835. ImageSetThickness($this->img, 1);
  3836. return TRUE;
  3837. } //function DrawThinBarLines
  3838. /*!
  3839. *
  3840. */
  3841. protected function DrawYErrorBar($x_world, $y_world, $error_height, $error_bar_type, $color)
  3842. {
  3843. /*
  3844. // TODO: add a parameter to show datalabels next to error bars?
  3845. // something like this:
  3846. if ($this->x_data_label_pos == 'plot')
  3847. $this->DrawText($this->fonts['error'], 90, $x1, $y2,
  3848. $color, $label, 'center', 'bottom');
  3849. */
  3850. $x1 = $this->xtr($x_world);
  3851. $y1 = $this->ytr($y_world);
  3852. $y2 = $this->ytr($y_world+$error_height) ;
  3853. ImageSetThickness($this->img, $this->error_bar_line_width);
  3854. ImageLine($this->img, $x1, $y1 , $x1, $y2, $color);
  3855. switch ($error_bar_type) {
  3856. case 'line':
  3857. break;
  3858. case 'tee':
  3859. ImageLine($this->img, $x1-$this->error_bar_size, $y2, $x1+$this->error_bar_size, $y2, $color);
  3860. break;
  3861. default:
  3862. ImageLine($this->img, $x1-$this->error_bar_size, $y2, $x1+$this->error_bar_size, $y2, $color);
  3863. break;
  3864. }
  3865. ImageSetThickness($this->img, 1);
  3866. return TRUE;
  3867. }
  3868. /*!
  3869. * Draws a styled dot. Uses world coordinates.
  3870. * The list of supported shapes can also be found in SetPointShapes().
  3871. * All shapes are drawn using a 3x3 grid, centered on the data point.
  3872. * The center is (x_mid, y_mid) and the corners are (x1, y1) and (x2, y2).
  3873. * $record is the 0-based index that selects the shape and size.
  3874. */
  3875. protected function DrawDot($x_world, $y_world, $record, $color)
  3876. {
  3877. $index = $record % $this->point_counts;
  3878. $point_size = $this->point_sizes[$index];
  3879. $half_point = (int)($point_size / 2);
  3880. $x_mid = $this->xtr($x_world);
  3881. $y_mid = $this->ytr($y_world);
  3882. $x1 = $x_mid - $half_point;
  3883. $x2 = $x_mid + $half_point;
  3884. $y1 = $y_mid - $half_point;
  3885. $y2 = $y_mid + $half_point;
  3886. switch ($this->point_shapes[$index]) {
  3887. case 'halfline':
  3888. ImageLine($this->img, $x1, $y_mid, $x_mid, $y_mid, $color);
  3889. break;
  3890. case 'line':
  3891. ImageLine($this->img, $x1, $y_mid, $x2, $y_mid, $color);
  3892. break;
  3893. case 'plus':
  3894. ImageLine($this->img, $x1, $y_mid, $x2, $y_mid, $color);
  3895. ImageLine($this->img, $x_mid, $y1, $x_mid, $y2, $color);
  3896. break;
  3897. case 'cross':
  3898. ImageLine($this->img, $x1, $y1, $x2, $y2, $color);
  3899. ImageLine($this->img, $x1, $y2, $x2, $y1, $color);
  3900. break;
  3901. case 'circle':
  3902. ImageArc($this->img, $x_mid, $y_mid, $point_size, $point_size, 0, 360, $color);
  3903. break;
  3904. case 'dot':
  3905. ImageFilledArc($this->img, $x_mid, $y_mid, $point_size, $point_size, 0, 360, $color, IMG_ARC_PIE);
  3906. break;
  3907. case 'diamond':
  3908. $arrpoints = array( $x1, $y_mid, $x_mid, $y1, $x2, $y_mid, $x_mid, $y2);
  3909. ImageFilledPolygon($this->img, $arrpoints, 4, $color);
  3910. break;
  3911. case 'triangle':
  3912. $arrpoints = array( $x1, $y_mid, $x2, $y_mid, $x_mid, $y2);
  3913. ImageFilledPolygon($this->img, $arrpoints, 3, $color);
  3914. break;
  3915. case 'trianglemid':
  3916. $arrpoints = array( $x1, $y1, $x2, $y1, $x_mid, $y_mid);
  3917. ImageFilledPolygon($this->img, $arrpoints, 3, $color);
  3918. break;
  3919. case 'yield':
  3920. $arrpoints = array( $x1, $y1, $x2, $y1, $x_mid, $y2);
  3921. ImageFilledPolygon($this->img, $arrpoints, 3, $color);
  3922. break;
  3923. case 'delta':
  3924. $arrpoints = array( $x1, $y2, $x2, $y2, $x_mid, $y1);
  3925. ImageFilledPolygon($this->img, $arrpoints, 3, $color);
  3926. break;
  3927. case 'star':
  3928. ImageLine($this->img, $x1, $y_mid, $x2, $y_mid, $color);
  3929. ImageLine($this->img, $x_mid, $y1, $x_mid, $y2, $color);
  3930. ImageLine($this->img, $x1, $y1, $x2, $y2, $color);
  3931. ImageLine($this->img, $x1, $y2, $x2, $y1, $color);
  3932. break;
  3933. case 'hourglass':
  3934. $arrpoints = array( $x1, $y1, $x2, $y1, $x1, $y2, $x2, $y2);
  3935. ImageFilledPolygon($this->img, $arrpoints, 4, $color);
  3936. break;
  3937. case 'bowtie':
  3938. $arrpoints = array( $x1, $y1, $x1, $y2, $x2, $y1, $x2, $y2);
  3939. ImageFilledPolygon($this->img, $arrpoints, 4, $color);
  3940. break;
  3941. case 'target':
  3942. ImageFilledRectangle($this->img, $x1, $y1, $x_mid, $y_mid, $color);
  3943. ImageFilledRectangle($this->img, $x_mid, $y_mid, $x2, $y2, $color);
  3944. ImageRectangle($this->img, $x1, $y1, $x2, $y2, $color);
  3945. break;
  3946. case 'box':
  3947. ImageRectangle($this->img, $x1, $y1, $x2, $y2, $color);
  3948. break;
  3949. case 'home': /* As in: "home plate" (baseball), also looks sort of like a house. */
  3950. $arrpoints = array( $x1, $y2, $x2, $y2, $x2, $y_mid, $x_mid, $y1, $x1, $y_mid);
  3951. ImageFilledPolygon($this->img, $arrpoints, 5, $color);
  3952. break;
  3953. case 'up':
  3954. ImagePolygon($this->img, array($x_mid, $y1, $x2, $y2, $x1, $y2), 3, $color);
  3955. break;
  3956. case 'down':
  3957. ImagePolygon($this->img, array($x_mid, $y2, $x1, $y1, $x2, $y1), 3, $color);
  3958. break;
  3959. case 'none': /* Special case, no point shape here */
  3960. break;
  3961. default: /* Also 'rect' */
  3962. ImageFilledRectangle($this->img, $x1, $y1, $x2, $y2, $color);
  3963. break;
  3964. }
  3965. return TRUE;
  3966. }
  3967. /*!
  3968. * Draw an area plot. Supported data types:
  3969. * 'text-data'
  3970. * 'data-data'
  3971. * NOTE: This function used to add first and last data values even on incomplete
  3972. * sets. That is not the behavior now. As for missing data in between,
  3973. * there are two possibilities: replace the point with one on the X axis (previous
  3974. * way), or forget about it and use the preceding and following ones to draw the polygon.
  3975. * There is the possibility to use both, we just need to add the method to set
  3976. * it. Something like SetMissingDataBehavior(), for example.
  3977. */
  3978. protected function DrawArea()
  3979. {
  3980. $incomplete_data_defaults_to_x_axis = FALSE; // TODO: make this configurable
  3981. for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
  3982. $rec = 1; // Skip record #0 (data label)
  3983. if ($this->data_type == 'data-data') // Do we have a value for X?
  3984. $x_now = $this->data[$row][$rec++]; // Read it, advance record index
  3985. else
  3986. $x_now = 0.5 + $cnt++; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  3987. $x_now_pixels = $this->xtr($x_now); // Absolute coordinates
  3988. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  3989. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels);
  3990. // Proceed with Y values
  3991. // Create array of points for imagefilledpolygon()
  3992. for($idx = 0; $rec < $this->num_recs[$row]; $rec++, $idx++) {
  3993. if (is_numeric($this->data[$row][$rec])) { // Allow for missing Y data
  3994. $y_now_pixels = $this->ytr($this->data[$row][$rec]);
  3995. $posarr[$idx][] = $x_now_pixels;
  3996. $posarr[$idx][] = $y_now_pixels;
  3997. $num_points[$idx] = isset($num_points[$idx]) ? $num_points[$idx]+1 : 1;
  3998. }
  3999. // If there's missing data...
  4000. else {
  4001. if (isset ($incomplete_data_defaults_to_x_axis)) {
  4002. $posarr[$idx][] = $x_now_pixels;
  4003. $posarr[$idx][] = $this->x_axis_y_pixels;
  4004. $num_points[$idx] = isset($num_points[$idx]) ? $num_points[$idx]+1 : 1;
  4005. }
  4006. }
  4007. }
  4008. } // end for
  4009. $end = count($posarr);
  4010. for ($i = 0; $i < $end; $i++) {
  4011. // Prepend initial points. X = first point's X, Y = x_axis_y_pixels
  4012. $x = $posarr[$i][0];
  4013. array_unshift($posarr[$i], $x, $this->x_axis_y_pixels);
  4014. // Append final points. X = last point's X, Y = x_axis_y_pixels
  4015. $x = $posarr[$i][count($posarr[$i])-2];
  4016. array_push($posarr[$i], $x, $this->x_axis_y_pixels);
  4017. $num_points[$i] += 2;
  4018. // Draw the polygon
  4019. ImageFilledPolygon($this->img, $posarr[$i], $num_points[$i], $this->ndx_data_colors[$i]);
  4020. }
  4021. return TRUE;
  4022. } // function DrawArea()
  4023. /*!
  4024. * Draw Lines. Supported data-types:
  4025. * 'data-data',
  4026. * 'text-data'
  4027. * NOTE: Please see the note regarding incomplete data sets on DrawArea()
  4028. */
  4029. protected function DrawLines()
  4030. {
  4031. // This will tell us if lines have already begun to be drawn.
  4032. // It is an array to keep separate information for every line, with a single
  4033. // variable we would sometimes get "undefined offset" errors and no plot...
  4034. $start_lines = array_fill(0, $this->records_per_group, FALSE);
  4035. if ($this->data_type == 'text-data') {
  4036. $lastx[0] = $this->xtr(0);
  4037. $lasty[0] = $this->xtr(0);
  4038. }
  4039. for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
  4040. $record = 1; // Skip record #0 (data label)
  4041. if ($this->data_type == 'data-data') // Do we have a value for X?
  4042. $x_now = $this->data[$row][$record++]; // Read it, advance record index
  4043. else
  4044. $x_now = 0.5 + $cnt++; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  4045. $x_now_pixels = $this->xtr($x_now); // Absolute coordinates
  4046. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  4047. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  4048. for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
  4049. if (($line_style = $this->line_styles[$idx]) == 'none')
  4050. continue; //Allow suppressing entire line, useful with linepoints
  4051. if (is_numeric($this->data[$row][$record])) { //Allow for missing Y data
  4052. $y_now_pixels = $this->ytr($this->data[$row][$record]);
  4053. if ($start_lines[$idx]) {
  4054. // Set line width, revert it to normal at the end
  4055. ImageSetThickness($this->img, $this->line_widths[$idx]);
  4056. if ($line_style == 'dashed') {
  4057. $this->SetDashedStyle($this->ndx_data_colors[$idx]);
  4058. ImageLine($this->img, $x_now_pixels, $y_now_pixels, $lastx[$idx], $lasty[$idx],
  4059. IMG_COLOR_STYLED);
  4060. } else {
  4061. ImageLine($this->img, $x_now_pixels, $y_now_pixels, $lastx[$idx], $lasty[$idx],
  4062. $this->ndx_data_colors[$idx]);
  4063. }
  4064. }
  4065. $lasty[$idx] = $y_now_pixels;
  4066. $lastx[$idx] = $x_now_pixels;
  4067. $start_lines[$idx] = TRUE;
  4068. }
  4069. // Y data missing... should we leave a blank or not?
  4070. else if ($this->draw_broken_lines) {
  4071. $start_lines[$idx] = FALSE;
  4072. }
  4073. } // end for
  4074. } // end for
  4075. ImageSetThickness($this->img, 1); // Revert to original state for lines to be drawn later.
  4076. return TRUE;
  4077. } // function DrawLines()
  4078. /*!
  4079. * Draw lines with error bars - data comes in as
  4080. * array("label", x, y, error+, error-, y2, error2+, error2-, ...);
  4081. */
  4082. protected function DrawLinesError()
  4083. {
  4084. if ($this->data_type != 'data-data-error') {
  4085. return $this->PrintError("DrawLinesError(): Data type '$this->data_type' not supported.");
  4086. }
  4087. $start_lines = array_fill(0, $this->records_per_group, FALSE);
  4088. for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
  4089. $record = 1; // Skip record #0 (data label)
  4090. $x_now = $this->data[$row][$record++]; // Read X value, advance record index
  4091. $x_now_pixels = $this->xtr($x_now); // Absolute coordinates.
  4092. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  4093. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  4094. // Now go for Y, E+, E-
  4095. for ($idx = 0; $record < $this->num_recs[$row]; $idx++) {
  4096. if (($line_style = $this->line_styles[$idx]) == 'none')
  4097. continue; //Allow suppressing entire line, useful with linepoints
  4098. if (is_numeric($this->data[$row][$record])) { // Allow for missing Y data
  4099. // Y
  4100. $y_now = $this->data[$row][$record++];
  4101. $y_now_pixels = $this->ytr($y_now);
  4102. if ($start_lines[$idx]) {
  4103. ImageSetThickness($this->img, $this->line_widths[$idx]);
  4104. if ($line_style == 'dashed') {
  4105. $this->SetDashedStyle($this->ndx_data_colors[$idx]);
  4106. ImageLine($this->img, $x_now_pixels, $y_now_pixels, $lastx[$idx], $lasty[$idx],
  4107. IMG_COLOR_STYLED);
  4108. } else {
  4109. ImageLine($this->img, $x_now_pixels, $y_now_pixels, $lastx[$idx], $lasty[$idx],
  4110. $this->ndx_data_colors[$idx]);
  4111. }
  4112. }
  4113. // Error+
  4114. $val = $this->data[$row][$record++];
  4115. $this->DrawYErrorBar($x_now, $y_now, $val, $this->error_bar_shape,
  4116. $this->ndx_error_bar_colors[$idx]);
  4117. // Error-
  4118. $val = $this->data[$row][$record++];
  4119. $this->DrawYErrorBar($x_now, $y_now, -$val, $this->error_bar_shape,
  4120. $this->ndx_error_bar_colors[$idx]);
  4121. // Update indexes:
  4122. $start_lines[$idx] = TRUE; // Tells us if we already drew the first column of points,
  4123. // thus having $lastx and $lasty ready for the next column.
  4124. $lastx[$idx] = $x_now_pixels;
  4125. $lasty[$idx] = $y_now_pixels;
  4126. } else {
  4127. $record += 3; // Skip over missing Y and its error values
  4128. if ($this->draw_broken_lines) {
  4129. $start_lines[$idx] = FALSE;
  4130. }
  4131. }
  4132. } // end for
  4133. } // end for
  4134. ImageSetThickness($this->img, 1); // Revert to original state for lines to be drawn later.
  4135. return TRUE;
  4136. } // function DrawLinesError()
  4137. /*!
  4138. * This is a mere copy of DrawLines() with one more line drawn for each point
  4139. */
  4140. protected function DrawSquared()
  4141. {
  4142. // This will tell us if lines have already begun to be drawn.
  4143. // It is an array to keep separate information for every line, for with a single
  4144. // variable we could sometimes get "undefined offset" errors and no plot...
  4145. $start_lines = array_fill(0, $this->records_per_group, FALSE);
  4146. if ($this->data_type == 'text-data') {
  4147. $lastx[0] = $this->xtr(0);
  4148. $lasty[0] = $this->xtr(0);
  4149. }
  4150. for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
  4151. $record = 1; // Skip record #0 (data label)
  4152. if ($this->data_type == 'data-data') // Do we have a value for X?
  4153. $x_now = $this->data[$row][$record++]; // Read it, advance record index
  4154. else
  4155. $x_now = 0.5 + $cnt++; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  4156. $x_now_pixels = $this->xtr($x_now); // Absolute coordinates
  4157. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  4158. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels); // notice there is no last param.
  4159. // Draw Lines
  4160. for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
  4161. if (is_numeric($this->data[$row][$record])) { // Allow for missing Y data
  4162. $y_now_pixels = $this->ytr($this->data[$row][$record]);
  4163. if ($start_lines[$idx] == TRUE) {
  4164. // Set line width, revert it to normal at the end
  4165. ImageSetThickness($this->img, $this->line_widths[$idx]);
  4166. if ($this->line_styles[$idx] == 'dashed') {
  4167. $this->SetDashedStyle($this->ndx_data_colors[$idx]);
  4168. ImageLine($this->img, $lastx[$idx], $lasty[$idx], $x_now_pixels, $lasty[$idx],
  4169. IMG_COLOR_STYLED);
  4170. ImageLine($this->img, $x_now_pixels, $lasty[$idx], $x_now_pixels, $y_now_pixels,
  4171. IMG_COLOR_STYLED);
  4172. } else {
  4173. ImageLine($this->img, $lastx[$idx], $lasty[$idx], $x_now_pixels, $lasty[$idx],
  4174. $this->ndx_data_colors[$idx]);
  4175. ImageLine($this->img, $x_now_pixels, $lasty[$idx], $x_now_pixels, $y_now_pixels,
  4176. $this->ndx_data_colors[$idx]);
  4177. }
  4178. }
  4179. $lastx[$idx] = $x_now_pixels;
  4180. $lasty[$idx] = $y_now_pixels;
  4181. $start_lines[$idx] = TRUE;
  4182. }
  4183. // Y data missing... should we leave a blank or not?
  4184. else if ($this->draw_broken_lines) {
  4185. $start_lines[$idx] = FALSE;
  4186. }
  4187. }
  4188. } // end while
  4189. ImageSetThickness($this->img, 1);
  4190. return TRUE;
  4191. } // function DrawSquared()
  4192. /*!
  4193. * Data comes in as array("title", x, y, y2, y3, ...)
  4194. */
  4195. protected function DrawBars()
  4196. {
  4197. if ($this->data_type != 'text-data') {
  4198. return $this->PrintError('DrawBars(): Bar plots must be text-data: use function SetDataType("text-data")');
  4199. }
  4200. // This is the X offset from the bar group's label center point to the left side of the first bar
  4201. // in the group. See also CalcBarWidths above.
  4202. $x_first_bar = (($this->records_per_group - 1) * $this->record_bar_width) / 2 - $this->bar_adjust_gap;
  4203. for ($row = 0; $row < $this->num_data_rows; $row++) {
  4204. $record = 1; // Skip record #0 (data label)
  4205. $x_now_pixels = $this->xtr(0.5 + $row); // Place text-data at X = 0.5, 1.5, 2.5, etc...
  4206. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  4207. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels);
  4208. // Lower left X of first bar in the group:
  4209. $x1 = $x_now_pixels - $x_first_bar;
  4210. // Draw the bars in the group:
  4211. for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
  4212. if (is_numeric($this->data[$row][$record])) { // Allow for missing Y data
  4213. $x2 = $x1 + $this->actual_bar_width;
  4214. if ($this->data[$row][$record] < $this->x_axis_position) {
  4215. $y1 = $this->x_axis_y_pixels;
  4216. $y2 = $this->ytr($this->data[$row][$record]);
  4217. $upgoing_bar = False;
  4218. } else {
  4219. $y1 = $this->ytr($this->data[$row][$record]);
  4220. $y2 = $this->x_axis_y_pixels;
  4221. $upgoing_bar = True;
  4222. }
  4223. // Draw the bar
  4224. ImageFilledRectangle($this->img, $x1, $y1, $x2, $y2, $this->ndx_data_colors[$idx]);
  4225. if ($this->shading) { // Draw the shade?
  4226. ImageFilledPolygon($this->img, array($x1, $y1,
  4227. $x1 + $this->shading, $y1 - $this->shading,
  4228. $x2 + $this->shading, $y1 - $this->shading,
  4229. $x2 + $this->shading, $y2 - $this->shading,
  4230. $x2, $y2,
  4231. $x2, $y1),
  4232. 6, $this->ndx_data_dark_colors[$idx]);
  4233. }
  4234. // Or draw a border?
  4235. else {
  4236. ImageRectangle($this->img, $x1, $y1, $x2,$y2, $this->ndx_data_border_colors[$idx]);
  4237. }
  4238. // Draw optional data labels above the bars (or below, for negative values).
  4239. if ( $this->y_data_label_pos == 'plotin') {
  4240. if ($upgoing_bar) {
  4241. $v_align = 'bottom';
  4242. $y_offset = -5 - $this->shading;
  4243. } else {
  4244. $v_align = 'top';
  4245. $y_offset = 2;
  4246. }
  4247. $this->DrawDataLabel($this->fonts['y_label'], $this->y_data_label_angle,
  4248. $row+0.5, $this->data[$row][$record], $this->ndx_title_color,
  4249. $this->data[$row][$record], 'center', $v_align,
  4250. ($idx + 0.5) * $this->record_bar_width - $x_first_bar, $y_offset);
  4251. }
  4252. }
  4253. // Step to next bar in group:
  4254. $x1 += $this->record_bar_width;
  4255. } // end for
  4256. } // end for
  4257. return TRUE;
  4258. } //function DrawBars
  4259. /*!
  4260. * Data comes in as array("title", x, y, y2, y3, ...)
  4261. * \note Original stacked bars idea by Laurent Kruk < lolok at users.sourceforge.net >
  4262. */
  4263. protected function DrawStackedBars()
  4264. {
  4265. if ($this->data_type != 'text-data') {
  4266. return $this->PrintError('DrawStackedBars(): Bar plots must be text-data: use SetDataType("text-data")');
  4267. }
  4268. // This is the X offset from the bar's label center point to the left side of the bar.
  4269. $x_first_bar = $this->record_bar_width / 2 - $this->bar_adjust_gap;
  4270. for ($row = 0; $row < $this->num_data_rows; $row++) {
  4271. $record = 1; // Skip record #0 (data label)
  4272. $x_now_pixels = $this->xtr(0.5 + $row); // Place text-data at X = 0.5, 1.5, 2.5, etc...
  4273. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  4274. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels);
  4275. // Lower left and lower right X of the bars in this group:
  4276. $x1 = $x_now_pixels - $x_first_bar;
  4277. $x2 = $x1 + $this->actual_bar_width;
  4278. // Draw the bars
  4279. $oldv = 0;
  4280. for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
  4281. if (is_numeric($this->data[$row][$record])) { // Allow for missing Y data
  4282. $y1 = $this->ytr(abs($this->data[$row][$record]) + $oldv);
  4283. $y2 = $this->ytr($this->x_axis_position + $oldv);
  4284. $oldv += abs($this->data[$row][$record]);
  4285. // Draw the bar
  4286. ImageFilledRectangle($this->img, $x1, $y1, $x2, $y2, $this->ndx_data_colors[$idx]);
  4287. if ($this->shading) { // Draw the shade?
  4288. ImageFilledPolygon($this->img, array($x1, $y1,
  4289. $x1 + $this->shading, $y1 - $this->shading,
  4290. $x2 + $this->shading, $y1 - $this->shading,
  4291. $x2 + $this->shading, $y2 - $this->shading,
  4292. $x2, $y2,
  4293. $x2, $y1),
  4294. 6, $this->ndx_data_dark_colors[$idx]);
  4295. }
  4296. // Or draw a border?
  4297. else {
  4298. ImageRectangle($this->img, $x1, $y1, $x2,$y2, $this->ndx_data_border_colors[$idx]);
  4299. }
  4300. }
  4301. } // end for
  4302. } // end for
  4303. return TRUE;
  4304. } //function DrawStackedBars
  4305. /*!
  4306. *
  4307. */
  4308. function DrawGraph()
  4309. {
  4310. // Test for missing image, missing data, empty data:
  4311. if (! $this->img) {
  4312. return $this->PrintError('DrawGraph(): No image resource allocated');
  4313. }
  4314. if (empty($this->data) || ! is_array($this->data)) {
  4315. return $this->PrintError("DrawGraph(): No data array");
  4316. }
  4317. if ($this->total_records == 0) {
  4318. return $this->PrintError('DrawGraph(): Empty data set');
  4319. }
  4320. // For pie charts: don't draw grid or border or axes, and maximize area usage.
  4321. // These controls can be split up in the future if needed.
  4322. $draw_axes = ($this->plot_type != 'pie');
  4323. // Get maxima and minima for scaling:
  4324. if (!$this->FindDataLimits())
  4325. return FALSE;
  4326. // Set plot area world values (plot_max_x, etc.):
  4327. if (!$this->CalcPlotAreaWorld())
  4328. return FALSE;
  4329. // Calculate X and Y axis positions in World Coordinates:
  4330. $this->CalcAxisPositions();
  4331. // Process label-related parameters:
  4332. $this->CheckLabels();
  4333. // Calculate the plot margins, if needed.
  4334. // For pie charts, set the $maximize argument to maximize space usage.
  4335. $this->CalcMargins(!$draw_axes);
  4336. // Calculate the actual plot area in device coordinates:
  4337. $this->CalcPlotAreaPixels();
  4338. // Calculate the mapping between world and device coordinates:
  4339. $this->CalcTranslation();
  4340. // Pad color and style arrays to fit records per group:
  4341. $this->PadArrays();
  4342. $this->DoCallback('draw_setup');
  4343. $this->DrawBackground();
  4344. $this->DrawImageBorder();
  4345. $this->DoCallback('draw_image_background');
  4346. $this->DrawPlotAreaBackground();
  4347. $this->DoCallback('draw_plotarea_background', $this->plot_area);
  4348. $this->DrawTitle();
  4349. if ($draw_axes) { // If no axes (pie chart), no axis titles either
  4350. $this->DrawXTitle();
  4351. $this->DrawYTitle();
  4352. }
  4353. $this->DoCallback('draw_titles');
  4354. if ($draw_axes && ! $this->grid_at_foreground) { // Usually one wants grids to go back, but...
  4355. $this->DrawYAxis(); // Y axis must be drawn before X axis (see DrawYAxis())
  4356. $this->DrawXAxis();
  4357. $this->DoCallback('draw_axes');
  4358. }
  4359. switch ($this->plot_type) {
  4360. case 'thinbarline':
  4361. $this->DrawThinBarLines();
  4362. break;
  4363. case 'area':
  4364. $this->DrawArea();
  4365. break;
  4366. case 'squared':
  4367. $this->DrawSquared();
  4368. break;
  4369. case 'lines':
  4370. if ( $this->data_type == 'data-data-error') {
  4371. $this->DrawLinesError();
  4372. } else {
  4373. $this->DrawLines();
  4374. }
  4375. break;
  4376. case 'linepoints':
  4377. if ( $this->data_type == 'data-data-error') {
  4378. $this->DrawLinesError();
  4379. $this->DrawDotsError();
  4380. } else {
  4381. $this->DrawLines();
  4382. $this->DrawDots();
  4383. }
  4384. break;
  4385. case 'points';
  4386. if ( $this->data_type == 'data-data-error') {
  4387. $this->DrawDotsError();
  4388. } else {
  4389. $this->DrawDots();
  4390. }
  4391. break;
  4392. case 'pie':
  4393. $this->DrawPieChart();
  4394. break;
  4395. case 'stackedbars':
  4396. $this->CalcBarWidths();
  4397. $this->DrawStackedBars();
  4398. break;
  4399. case 'bars':
  4400. default:
  4401. $this->plot_type = 'bars'; // Set it if it wasn't already set. (necessary?)
  4402. $this->CalcBarWidths();
  4403. $this->DrawBars();
  4404. break;
  4405. } // end switch
  4406. $this->DoCallback('draw_graph', $this->plot_area);
  4407. if ($draw_axes && $this->grid_at_foreground) { // Usually one wants grids to go back, but...
  4408. $this->DrawYAxis(); // Y axis must be drawn before X axis (see DrawYAxis())
  4409. $this->DrawXAxis();
  4410. $this->DoCallback('draw_axes');
  4411. }
  4412. if ($draw_axes) {
  4413. $this->DrawPlotBorder();
  4414. $this->DoCallback('draw_border');
  4415. }
  4416. if ($this->legend) {
  4417. $this->DrawLegend();
  4418. $this->DoCallback('draw_legend');
  4419. }
  4420. $this->DoCallback('draw_all', $this->plot_area);
  4421. if ($this->print_image && !$this->PrintImage())
  4422. return FALSE;
  4423. return TRUE;
  4424. } //function DrawGraph()
  4425. /////////////////////////////////////////////
  4426. ////////////////// DEPRECATED METHODS
  4427. /////////////////////////////////////////////
  4428. /*!
  4429. * Deprecated, use SetYTickPos()
  4430. */
  4431. function SetDrawVertTicks($which_dvt)
  4432. {
  4433. if ($which_dvt != 1)
  4434. $this->SetYTickPos('none');
  4435. return TRUE;
  4436. }
  4437. /*!
  4438. * Deprecated, use SetXTickPos()
  4439. */
  4440. function SetDrawHorizTicks($which_dht)
  4441. {
  4442. if ($which_dht != 1)
  4443. $this->SetXTickPos('none');
  4444. return TRUE;
  4445. }
  4446. /*!
  4447. * \deprecated Use SetNumXTicks()
  4448. */
  4449. function SetNumHorizTicks($n)
  4450. {
  4451. return $this->SetNumXTicks($n);
  4452. }
  4453. /*!
  4454. * \deprecated Use SetNumYTicks()
  4455. */
  4456. function SetNumVertTicks($n)
  4457. {
  4458. return $this->SetNumYTicks($n);
  4459. }
  4460. /*!
  4461. * \deprecated Use SetXTickIncrement()
  4462. */
  4463. function SetHorizTickIncrement($inc)
  4464. {
  4465. return $this->SetXTickIncrement($inc);
  4466. }
  4467. /*!
  4468. * \deprecated Use SetYTickIncrement()
  4469. */
  4470. function SetVertTickIncrement($inc)
  4471. {
  4472. return $this->SetYTickIncrement($inc);
  4473. }
  4474. /*!
  4475. * \deprecated Use SetYTickPos()
  4476. */
  4477. function SetVertTickPosition($which_tp)
  4478. {
  4479. return $this->SetYTickPos($which_tp);
  4480. }
  4481. /*!
  4482. * \deprecated Use SetXTickPos()
  4483. */
  4484. function SetHorizTickPosition($which_tp)
  4485. {
  4486. return $this->SetXTickPos($which_tp);
  4487. }
  4488. /*!
  4489. * \deprecated Use SetFont()
  4490. */
  4491. function SetTitleFontSize($which_size)
  4492. {
  4493. return $this->SetFont('title', $which_size);
  4494. }
  4495. /*!
  4496. * \deprecated Use SetFont()
  4497. */
  4498. function SetAxisFontSize($which_size)
  4499. {
  4500. $this->SetFont('x_label', $which_size);
  4501. $this->SetFont('y_label', $which_size);
  4502. }
  4503. /*!
  4504. * \deprecated Use SetFont()
  4505. */
  4506. function SetSmallFontSize($which_size)
  4507. {
  4508. return $this->SetFont('generic', $which_size);
  4509. }
  4510. /*!
  4511. * \deprecated Use SetFont()
  4512. */
  4513. function SetXLabelFontSize($which_size)
  4514. {
  4515. return $this->SetFont('x_title', $which_size);
  4516. }
  4517. /*!
  4518. * \deprecated Use SetFont()
  4519. */
  4520. function SetYLabelFontSize($which_size)
  4521. {
  4522. return $this->SetFont('y_title', $which_size);
  4523. }
  4524. /*!
  4525. * \deprecated Use SetXTitle()
  4526. */
  4527. function SetXLabel($which_xlab)
  4528. {
  4529. return $this->SetXTitle($which_xlab);
  4530. }
  4531. /*!
  4532. * \deprecated Use SetYTitle()
  4533. */
  4534. function SetYLabel($which_ylab)
  4535. {
  4536. return $this->SetYTitle($which_ylab);
  4537. }
  4538. /*!
  4539. * \deprecated Use SetXTickLength() and SetYTickLength() instead.
  4540. */
  4541. function SetTickLength($which_tl)
  4542. {
  4543. $this->SetXTickLength($which_tl);
  4544. $this->SetYTickLength($which_tl);
  4545. return TRUE;
  4546. }
  4547. /*!
  4548. * \deprecated Use SetYLabelType()
  4549. */
  4550. function SetYGridLabelType($which_yglt)
  4551. {
  4552. return $this->SetYLabelType($which_yglt);
  4553. }
  4554. /*!
  4555. * \deprecated Use SetXLabelType()
  4556. */
  4557. function SetXGridLabelType($which_xglt)
  4558. {
  4559. return $this->SetXLabelType($which_xglt);
  4560. }
  4561. /*!
  4562. * \deprecated Use SetYTickLabelPos()
  4563. */
  4564. function SetYGridLabelPos($which_yglp)
  4565. {
  4566. return $this->SetYTickLabelPos($which_yglp);
  4567. }
  4568. /*!
  4569. * \deprecated Use SetXTickLabelPos()
  4570. */
  4571. function SetXGridLabelPos($which_xglp)
  4572. {
  4573. return $this->SetXTickLabelPos($which_xglp);
  4574. }
  4575. /*!
  4576. * \deprecated Use SetXtitle()
  4577. */
  4578. function SetXTitlePos($xpos)
  4579. {
  4580. $this->x_title_pos = $xpos;
  4581. return TRUE;
  4582. }
  4583. /*!
  4584. * \deprecated Use SetYTitle()
  4585. */
  4586. function SetYTitlePos($xpos)
  4587. {
  4588. $this->y_title_pos = $xpos;
  4589. return TRUE;
  4590. }
  4591. /*!
  4592. * Draw Labels (not grid labels) on X Axis, following data points. Default position is
  4593. * down of plot. Care must be taken not to draw these and x_tick_labels as they'd probably overlap.
  4594. *
  4595. * \deprecated Use SetXDataLabelPos()
  4596. */
  4597. function SetDrawXDataLabels($which_dxdl)
  4598. {
  4599. if ($which_dxdl == '1' )
  4600. $this->SetXDataLabelPos('plotdown');
  4601. else
  4602. $this->SetXDataLabelPos('none');
  4603. }
  4604. /*!
  4605. * \deprecated
  4606. */
  4607. function SetNewPlotAreaPixels($x1, $y1, $x2, $y2)
  4608. {
  4609. //Like in GD 0, 0 is upper left set via pixel Coordinates
  4610. $this->plot_area = array($x1, $y1, $x2, $y2);
  4611. $this->plot_area_width = $this->plot_area[2] - $this->plot_area[0];
  4612. $this->plot_area_height = $this->plot_area[3] - $this->plot_area[1];
  4613. $this->y_top_margin = $this->plot_area[1];
  4614. if (isset($this->plot_max_x))
  4615. $this->CalcTranslation();
  4616. return TRUE;
  4617. }
  4618. /*!
  4619. * \deprecated Use _SetRGBColor()
  4620. */
  4621. function SetColor($which_color)
  4622. {
  4623. $this->SetRGBColor($which_color);
  4624. return TRUE;
  4625. }
  4626. /*
  4627. * \deprecated Use SetLineWidths().
  4628. */
  4629. function SetLineWidth($which_lw)
  4630. {
  4631. $this->SetLineWidths($which_lw);
  4632. if (!$this->error_bar_line_width) {
  4633. $this->SetErrorBarLineWidth($which_lw);
  4634. }
  4635. return TRUE;
  4636. }
  4637. /*
  4638. * \deprecated Use SetPointShapes().
  4639. */
  4640. function SetPointShape($which_pt)
  4641. {
  4642. $this->SetPointShapes($which_pt);
  4643. return TRUE;
  4644. }
  4645. /*
  4646. * \deprecated Use SetPointSizes().
  4647. */
  4648. function SetPointSize($which_ps)
  4649. {
  4650. $this->SetPointSizes($which_ps);
  4651. return TRUE;
  4652. }
  4653. } // class PHPlot