Merge pull request #15495 from civicrm/5.19
[civicrm-core.git] / CRM / Utils / Chart.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * Build various graphs using the dc chart library.
36 */
37 class CRM_Utils_Chart {
38
39 /**
40 * Colours.
41 * @var array
42 */
43 private static $_colours = [
44 "#C3CC38",
45 "#C8B935",
46 "#CEA632",
47 "#D3932F",
48 "#D9802C",
49 "#FA6900",
50 "#DC9B57",
51 "#F78F01",
52 "#5AB56E",
53 "#6F8069",
54 "#C92200",
55 "#EB6C5C",
56 ];
57
58 /**
59 * Build The Bar Gharph.
60 *
61 * @param array $params
62 * Assoc array of name/value pairs.
63 *
64 * @return object
65 * $chart object of open flash chart.
66 */
67 public static function barChart($params) {
68 $output = static::commonParamsManipulation($params);
69 if (empty($output)) {
70 return NULL;
71 }
72 $output['type'] = 'barchart';
73 // Default title
74 $output += ['title' => ts('Bar Chart')];
75
76 // ? Not sure what reports use this, but it's not implemented.
77 // call user define function to handle on click event.
78 // if ($onClickFunName = CRM_Utils_Array::value('on_click_fun_name', $params)) {
79 // $bars[$barCount]->set_on_click($onClickFunName);
80 // }
81
82 //// get the currency to set in tooltip.
83 //$tooltip = CRM_Utils_Array::value('tip', $params, "$symbol #val#");
84
85 return $output;
86 }
87
88 /**
89 * Build a pie chart.
90 *
91 * @param array $params
92 * Assoc array of name/value pairs.
93 *
94 * @return array
95 */
96 public static function pieChart($params) {
97 $output = static::commonParamsManipulation($params);
98 if (empty($output)) {
99 return NULL;
100 }
101 $output['type'] = 'piechart';
102 $output += ['title' => ts('Pie Chart')];
103
104 // ? Not sure what reports use this, but it's not implemented.
105 // call user define function to handle on click event.
106 // if ($onClickFunName = CRM_Utils_Array::value('on_click_fun_name', $params)) {
107 // $bars[$barCount]->set_on_click($onClickFunName);
108 // }
109
110 //// get the currency to set in tooltip.
111 //$tooltip = CRM_Utils_Array::value('tip', $params, "$symbol #val#");
112
113 return $output;
114 }
115
116 /**
117 * Common data manipulation for charts.
118 *
119 * @param array $params
120 * Assoc array of name/value pairs.
121 *
122 * @return array
123 */
124 public static function commonParamsManipulation($params) {
125 if (empty($params)) {
126 return NULL;
127 }
128 $output = [];
129 if (empty($params['multiValues'])) {
130 $params['multiValues'] = [$params['values']];
131 }
132
133 $output['values'] = [];
134 foreach ($params['multiValues'] as $i => $dataSet) {
135 $output['values'][$i] = [];
136 foreach ($dataSet as $k => $v) {
137 $output['values'][$i][] = ['label' => $k, 'value' => (double) $v];
138 }
139 }
140 if (!$output['values']) {
141 return NULL;
142 }
143
144 // Ensure there's a legend (title)
145 if (!empty($params['legend'])) {
146 $output['title'] = $params['legend'];
147 }
148
149 $output['symbol'] = CRM_Core_BAO_Country::defaultCurrencySymbol();
150
151 // ? Not sure what reports use this, but it's not implemented.
152 // call user define function to handle on click event.
153 // if ($onClickFunName = CRM_Utils_Array::value('on_click_fun_name', $params)) {
154 // $bars[$barCount]->set_on_click($onClickFunName);
155 // }
156
157 //// get the currency to set in tooltip.
158 //$tooltip = CRM_Utils_Array::value('tip', $params, "$symbol #val#");
159
160 return $output;
161 }
162
163 /**
164 * @param $rows
165 * @param $chart
166 * @param $interval
167 *
168 * @return array
169 */
170 public static function chart($rows, $chart, $interval) {
171 $lcInterval = strtolower($interval);
172 $label = ucfirst($lcInterval);
173 $chartData = $dateKeys = [];
174 $intervalLabels = [
175 'year' => ts('Yearly'),
176 'fiscalyear' => ts('Yearly (Fiscal)'),
177 'month' => ts('Monthly'),
178 'quarter' => ts('Quarterly'),
179 'week' => ts('Weekly'),
180 'yearweek' => ts('Weekly'),
181 ];
182
183 switch ($lcInterval) {
184 case 'month':
185 case 'quarter':
186 case 'week':
187 case 'yearweek':
188 foreach ($rows['receive_date'] as $key => $val) {
189 list($year, $month) = explode('-', $val);
190 $dateKeys[] = substr($rows[$interval][$key], 0, 3) . ' of ' . $year;
191 }
192 $legend = $intervalLabels[$lcInterval];
193 break;
194
195 default:
196 foreach ($rows['receive_date'] as $key => $val) {
197 list($year, $month) = explode('-', $val);
198 $dateKeys[] = $year;
199 }
200 $legend = ts("%1", [1 => $label]);
201 if (!empty($intervalLabels[$lcInterval])) {
202 $legend = $intervalLabels[$lcInterval];
203 }
204 break;
205 }
206
207 if (!empty($dateKeys)) {
208 $graph = [];
209 if (!array_key_exists('multiValue', $rows)) {
210 $rows['multiValue'] = [$rows['value']];
211 }
212 foreach ($rows['multiValue'] as $key => $val) {
213 $graph[$key] = array_combine($dateKeys, $rows['multiValue'][$key]);
214 }
215 $chartData = [
216 'legend' => "$legend " . CRM_Utils_Array::value('legend', $rows, ts('Contribution')) . ' ' . ts('Summary'),
217 'values' => $graph[0],
218 'multiValues' => $graph,
219 'barKeys' => CRM_Utils_Array::value('barKeys', $rows, []),
220 ];
221 }
222
223 // rotate the x labels.
224 $chartData['xLabelAngle'] = CRM_Utils_Array::value('xLabelAngle', $rows, 0);
225 if (!empty($rows['tip'])) {
226 $chartData['tip'] = $rows['tip'];
227 }
228
229 // legend
230 $chartData['xname'] = CRM_Utils_Array::value('xname', $rows);
231 $chartData['yname'] = CRM_Utils_Array::value('yname', $rows);
232
233 // carry some chart params if pass.
234 foreach ([
235 'xSize',
236 'ySize',
237 'divName',
238 ] as $f) {
239 if (!empty($rows[$f])) {
240 $chartData[$f] = $rows[$f];
241 }
242 }
243
244 return self::buildChart($chartData, $chart);
245 }
246
247 /**
248 * @param $rows
249 * @param $chart
250 * @param $interval
251 * @param $chartInfo
252 *
253 * @return array
254 */
255 public static function reportChart($rows, $chart, $interval, &$chartInfo) {
256 foreach ($interval as $key => $val) {
257 $graph[$val] = $rows['value'][$key];
258 }
259
260 $chartData = [
261 'values' => $graph,
262 'legend' => $chartInfo['legend'],
263 'xname' => $chartInfo['xname'],
264 'yname' => $chartInfo['yname'],
265 ];
266
267 // rotate the x labels.
268 $chartData['xLabelAngle'] = CRM_Utils_Array::value('xLabelAngle', $chartInfo, 20);
269 if (!empty($chartInfo['tip'])) {
270 $chartData['tip'] = $chartInfo['tip'];
271 }
272
273 // carry some chart params if pass.
274 foreach ([
275 'xSize',
276 'ySize',
277 'divName',
278 ] as $f) {
279 if (!empty($rows[$f])) {
280 $chartData[$f] = $rows[$f];
281 }
282 }
283
284 return self::buildChart($chartData, $chart);
285 }
286
287 /**
288 * @param array $params
289 * @param $chart
290 *
291 * @return array
292 */
293 public static function buildChart(&$params, $chart) {
294 $theChart = [];
295 if ($chart && is_array($params) && !empty($params)) {
296 // build the chart objects.
297 $chartObj = CRM_Utils_Chart::$chart($params);
298
299 if ($chartObj) {
300 // calculate chart size.
301 $xSize = CRM_Utils_Array::value('xSize', $params, 400);
302 $ySize = CRM_Utils_Array::value('ySize', $params, 300);
303 if ($chart == 'barChart') {
304 $ySize = CRM_Utils_Array::value('ySize', $params, 250);
305 $xSize = 60 * count($params['values']);
306 // hack to show tooltip.
307 if ($xSize < 200) {
308 $xSize = (count($params['values']) > 1) ? 100 * count($params['values']) : 170;
309 }
310 elseif ($xSize > 600 && count($params['values']) > 1) {
311 $xSize = (count($params['values']) + 400 / count($params['values'])) * count($params['values']);
312 }
313 }
314
315 // generate unique id for this chart instance
316 $uniqueId = md5(uniqid(rand(), TRUE));
317
318 $theChart["chart_{$uniqueId}"]['size'] = ['xSize' => $xSize, 'ySize' => $ySize];
319 $theChart["chart_{$uniqueId}"]['object'] = $chartObj;
320
321 // assign chart data to template
322 $template = CRM_Core_Smarty::singleton();
323 $template->assign('uniqueId', $uniqueId);
324 $template->assign("chartData", json_encode($theChart ?? []));
325 }
326 }
327
328 return $theChart;
329 }
330
331 }