Merge pull request #6892 from eileenmcnaughton/CRM-17225-report-save
[civicrm-core.git] / CRM / Report / Utils / Report.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Report_Utils_Report {
36
74cf4551 37 /**
100fef9d 38 * @param int $instanceID
74cf4551
EM
39 *
40 * @return null|string
41 */
00be9182 42 public static function getValueFromUrl($instanceID = NULL) {
6a488035 43 if ($instanceID) {
0b25329b 44 $optionVal = CRM_Core_DAO::getFieldValue('CRM_Report_DAO_ReportInstance',
6a488035
TO
45 $instanceID,
46 'report_id'
47 );
48 }
49 else {
50 $config = CRM_Core_Config::singleton();
51 $args = explode('/', $_GET[$config->userFrameworkURLVar]);
52
53 // remove 'civicrm/report' from args
54 array_shift($args);
55 array_shift($args);
56
b44e3f84 57 // put rest of argument back in the form of url, which is how value
6a488035
TO
58 // is stored in option value table
59 $optionVal = implode('/', $args);
60 }
61 return $optionVal;
62 }
63
74cf4551 64 /**
100fef9d 65 * @param int $instanceID
74cf4551
EM
66 *
67 * @return array|bool
68 */
00be9182 69 public static function getValueIDFromUrl($instanceID = NULL) {
6a488035
TO
70 $optionVal = self::getValueFromUrl($instanceID);
71
72 if ($optionVal) {
73 $templateInfo = CRM_Core_OptionGroup::getRowValues('report_template', "{$optionVal}", 'value');
877022f7 74 return array(CRM_Utils_Array::value('id', $templateInfo), $optionVal);
6a488035
TO
75 }
76
77 return FALSE;
78 }
79
74cf4551
EM
80 /**
81 * @param $optionVal
82 *
83 * @return mixed
84 */
00be9182 85 public static function getInstanceIDForValue($optionVal) {
6a488035
TO
86 static $valId = array();
87
88 if (!array_key_exists($optionVal, $valId)) {
89 $sql = "
90SELECT MIN(id) FROM civicrm_report_instance
91WHERE report_id = %1";
92
93 $params = array(1 => array($optionVal, 'String'));
94 $valId[$optionVal] = CRM_Core_DAO::singleValueQuery($sql, $params);
95 }
96 return $valId[$optionVal];
97 }
98
74cf4551
EM
99 /**
100 * @param null $path
101 *
102 * @return mixed
103 */
00be9182 104 public static function getInstanceIDForPath($path = NULL) {
6a488035
TO
105 static $valId = array();
106
107 // if $path is null, try to get it from url
108 $path = self::getInstancePath();
109
110 if ($path && !array_key_exists($path, $valId)) {
111 $sql = "
112SELECT MIN(id) FROM civicrm_report_instance
113WHERE TRIM(BOTH '/' FROM CONCAT(report_id, '/', name)) = %1";
114
115 $params = array(1 => array($path, 'String'));
116 $valId[$path] = CRM_Core_DAO::singleValueQuery($sql, $params);
117 }
118 return CRM_Utils_Array::value($path, $valId);
119 }
120
74cf4551
EM
121 /**
122 * @param $urlValue
123 * @param string $query
124 * @param bool $absolute
100fef9d 125 * @param int $instanceID
74cf4551
EM
126 * @param array $drilldownReport
127 *
128 * @return bool|string
129 */
00be9182 130 public static function getNextUrl($urlValue, $query = 'reset=1', $absolute = FALSE, $instanceID = NULL, $drilldownReport = array()) {
6a488035 131 if ($instanceID) {
84178120
TO
132 $drilldownInstanceID = FALSE;
133 if (array_key_exists($urlValue, $drilldownReport)) {
0b25329b 134 $drilldownInstanceID = CRM_Core_DAO::getFieldValue('CRM_Report_DAO_ReportInstance', $instanceID, 'drilldown_id', 'id');
84178120 135 }
6a488035 136
84178120 137 if (!$drilldownInstanceID) {
6a488035 138 $drilldownInstanceID = self::getInstanceIDForValue($urlValue);
84178120 139 }
6a488035
TO
140
141 if ($drilldownInstanceID) {
142 return CRM_Utils_System::url("civicrm/report/instance/{$drilldownInstanceID}",
143 "{$query}", $absolute
144 );
145 }
146 else {
147 return FALSE;
148 }
149 }
150 else {
151 return CRM_Utils_System::url("civicrm/report/" . trim($urlValue, '/'),
152 $query, $absolute
153 );
154 }
155 }
156
74cf4551 157 /**
fe482240 158 * get instance count for a template.
74cf4551
EM
159 * @param $optionVal
160 *
161 * @return int|null|string
162 */
00be9182 163 public static function getInstanceCount($optionVal) {
4f99ca55
TO
164 if (empty($optionVal)) {
165 return 0;
84178120 166 }
ae555e90 167
6a488035
TO
168 $sql = "
169SELECT count(inst.id)
170FROM civicrm_report_instance inst
171WHERE inst.report_id = %1";
172
173 $params = array(1 => array($optionVal, 'String'));
174 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
175 return $count;
176 }
177
74cf4551
EM
178 /**
179 * @param $fileContent
100fef9d 180 * @param int $instanceID
74cf4551
EM
181 * @param string $outputMode
182 * @param array $attachments
183 *
184 * @return bool
185 */
00be9182 186 public static function mailReport($fileContent, $instanceID = NULL, $outputMode = 'html', $attachments = array()) {
6a488035
TO
187 if (!$instanceID) {
188 return FALSE;
189 }
190
191 list($domainEmailName,
192 $domainEmailAddress
353ffa53 193 ) = CRM_Core_BAO_Domain::getNameAndEmail();
6a488035
TO
194
195 $params = array('id' => $instanceID);
196 $instanceInfo = array();
0b25329b 197 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
6a488035
TO
198 $params,
199 $instanceInfo
200 );
201
353ffa53 202 $params = array();
6a488035 203 $params['groupName'] = 'Report Email Sender';
353ffa53 204 $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
6a488035 205 //$domainEmailName;
353ffa53 206 $params['toName'] = "";
6a488035 207 $params['toEmail'] = CRM_Utils_Array::value('email_to', $instanceInfo);
353ffa53 208 $params['cc'] = CRM_Utils_Array::value('email_cc', $instanceInfo);
6a488035 209 $params['subject'] = CRM_Utils_Array::value('email_subject', $instanceInfo);
a7488080 210 if (empty($instanceInfo['attachments'])) {
6a488035
TO
211 $instanceInfo['attachments'] = array();
212 }
213 $params['attachments'] = array_merge(CRM_Utils_Array::value('attachments', $instanceInfo), $attachments);
214 $params['text'] = '';
215 $params['html'] = $fileContent;
216
217 return CRM_Utils_Mail::send($params);
218 }
219
74cf4551 220 /**
c490a46a 221 * @param CRM_Core_Form $form
74cf4551
EM
222 * @param $rows
223 */
00be9182 224 public static function export2csv(&$form, &$rows) {
6a488035 225 //Mark as a CSV file.
d42a224c 226 CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv');
6a488035
TO
227
228 //Force a download and name the file using the current timestamp.
229 $datetime = date('Ymd-Gi', $_SERVER['REQUEST_TIME']);
d42a224c 230 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=Report_' . $datetime . '.csv');
6a488035
TO
231 echo self::makeCsv($form, $rows);
232 CRM_Utils_System::civiExit();
233 }
234
235 /**
236 * Utility function for export2csv and CRM_Report_Form::endPostProcess
237 * - make CSV file content and return as string.
ea3ddccf 238 *
239 * @param CRM_Core_Form $form
240 * @param array $rows
241 *
242 * @return string
6a488035 243 */
00be9182 244 public static function makeCsv(&$form, &$rows) {
6a488035
TO
245 $config = CRM_Core_Config::singleton();
246 $csv = '';
247
248 // Add headers if this is the first row.
249 $columnHeaders = array_keys($form->_columnHeaders);
250
251 // Replace internal header names with friendly ones, where available.
252 foreach ($columnHeaders as $header) {
253 if (isset($form->_columnHeaders[$header])) {
254 $headers[] = '"' . html_entity_decode(strip_tags($form->_columnHeaders[$header]['title'])) . '"';
255 }
256 }
257 // Add the headers.
258 $csv .= implode($config->fieldSeparator,
353ffa53
TO
259 $headers
260 ) . "\r\n";
6a488035
TO
261
262 $displayRows = array();
263 $value = NULL;
264 foreach ($rows as $row) {
265 foreach ($columnHeaders as $k => $v) {
266 $value = CRM_Utils_Array::value($v, $row);
267 if (isset($value)) {
268 // Remove HTML, unencode entities, and escape quotation marks.
269 $value = str_replace('"', '""', html_entity_decode(strip_tags($value)));
270
271 if (CRM_Utils_Array::value('type', $form->_columnHeaders[$v]) & 4) {
272 if (CRM_Utils_Array::value('group_by', $form->_columnHeaders[$v]) == 'MONTH' ||
273 CRM_Utils_Array::value('group_by', $form->_columnHeaders[$v]) == 'QUARTER'
274 ) {
275 $value = CRM_Utils_Date::customFormat($value, $config->dateformatPartial);
276 }
277 elseif (CRM_Utils_Array::value('group_by', $form->_columnHeaders[$v]) == 'YEAR') {
278 $value = CRM_Utils_Date::customFormat($value, $config->dateformatYear);
279 }
908a11e7
EM
280 elseif ($form->_columnHeaders[$v]['type'] == 12) {
281 // This is a datetime format
282 $value = CRM_Utils_Date::customFormat($value, '%Y-%m-%d %H:%i');
283 }
6a488035
TO
284 else {
285 $value = CRM_Utils_Date::customFormat($value, '%Y-%m-%d');
286 }
287 }
288 elseif (CRM_Utils_Array::value('type', $form->_columnHeaders[$v]) == 1024) {
39d06e38 289 $value = CRM_Utils_Money::format($value, $row['civicrm_contribution_currency']);
6a488035
TO
290 }
291 $displayRows[$v] = '"' . $value . '"';
292 }
293 else {
b5be5afe 294 $displayRows[$v] = "";
6a488035
TO
295 }
296 }
297 // Add the data row.
298 $csv .= implode($config->fieldSeparator,
353ffa53
TO
299 $displayRows
300 ) . "\r\n";
6a488035
TO
301 }
302
303 return $csv;
304 }
305
74cf4551
EM
306 /**
307 * @return mixed
308 */
00be9182 309 public static function getInstanceID() {
6a488035
TO
310
311 $config = CRM_Core_Config::singleton();
312 $arg = explode('/', $_GET[$config->userFrameworkURLVar]);
313
314 if ($arg[1] == 'report' &&
315 CRM_Utils_Array::value(2, $arg) == 'instance'
316 ) {
317 if (CRM_Utils_Rule::positiveInteger($arg[3])) {
318 return $arg[3];
319 }
320 }
321 }
322
74cf4551
EM
323 /**
324 * @return string
325 */
00be9182 326 public static function getInstancePath() {
6a488035
TO
327 $config = CRM_Core_Config::singleton();
328 $arg = explode('/', $_GET[$config->userFrameworkURLVar]);
329
330 if ($arg[1] == 'report' &&
331 CRM_Utils_Array::value(2, $arg) == 'instance'
332 ) {
333 unset($arg[0], $arg[1], $arg[2]);
334 $path = trim(CRM_Utils_Type::escape(implode('/', $arg), 'String'), '/');
335 return $path;
336 }
337 }
338
74cf4551 339 /**
100fef9d 340 * @param int $instanceId
74cf4551
EM
341 *
342 * @return bool
343 */
00be9182 344 public static function isInstancePermissioned($instanceId) {
6a488035
TO
345 if (!$instanceId) {
346 return TRUE;
347 }
348
349 $instanceValues = array();
350 $params = array('id' => $instanceId);
0b25329b 351 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
6a488035
TO
352 $params,
353 $instanceValues
354 );
355
356 if (!empty($instanceValues['permission']) &&
357 (!(CRM_Core_Permission::check($instanceValues['permission']) ||
353ffa53
TO
358 CRM_Core_Permission::check('administer Reports')
359 ))
6a488035
TO
360 ) {
361 return FALSE;
362 }
363
364 return TRUE;
365 }
366
367 /**
368 * Check if the user can view a report instance based on their role(s)
369 *
370 * @instanceId string $str the report instance to check
371 *
100fef9d 372 * @param int $instanceId
fd31fa4c 373 *
acb1052e 374 * @return bool
a6c01b45 375 * true if yes, else false
6a488035 376 */
00be9182 377 public static function isInstanceGroupRoleAllowed($instanceId) {
6a488035
TO
378 if (!$instanceId) {
379 return TRUE;
380 }
381
382 $instanceValues = array();
383 $params = array('id' => $instanceId);
0b25329b 384 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
6a488035
TO
385 $params,
386 $instanceValues
387 );
388 //transform grouprole to array
389 if (!empty($instanceValues['grouprole'])) {
390 $grouprole_array = explode(CRM_Core_DAO::VALUE_SEPARATOR,
391 $instanceValues['grouprole']
392 );
393 if (!CRM_Core_Permission::checkGroupRole($grouprole_array) &&
394 !CRM_Core_Permission::check('administer Reports')
395 ) {
396 return FALSE;
397 }
398 }
399 return TRUE;
400 }
401
74cf4551 402 /**
c490a46a 403 * @param array $params
74cf4551
EM
404 *
405 * @return array
406 */
00be9182 407 public static function processReport($params) {
6a488035
TO
408 $instanceId = CRM_Utils_Array::value('instanceId', $params);
409
410 // hack for now, CRM-8358
411 $_REQUEST['instanceId'] = $instanceId;
412 $_REQUEST['sendmail'] = CRM_Utils_Array::value('sendmail', $params, 1);
884605ca 413
6a488035
TO
414 // if cron is run from terminal --output is reserved, and therefore we would provide another name 'format'
415 $_REQUEST['output'] = CRM_Utils_Array::value('format', $params, CRM_Utils_Array::value('output', $params, 'pdf'));
416 $_REQUEST['reset'] = CRM_Utils_Array::value('reset', $params, 1);
417
418 $optionVal = self::getValueFromUrl($instanceId);
419 $messages = array("Report Mail Triggered...");
420
421 $templateInfo = CRM_Core_OptionGroup::getRowValues('report_template', $optionVal, 'value');
353ffa53
TO
422 $obj = new CRM_Report_Page_Instance();
423 $is_error = 0;
6a488035
TO
424 if (strstr(CRM_Utils_Array::value('name', $templateInfo), '_Form')) {
425 $instanceInfo = array();
0b25329b 426 CRM_Report_BAO_ReportInstance::retrieve(array('id' => $instanceId), $instanceInfo);
6a488035
TO
427
428 if (!empty($instanceInfo['title'])) {
429 $obj->assign('reportTitle', $instanceInfo['title']);
430 }
431 else {
432 $obj->assign('reportTitle', $templateInfo['label']);
433 }
434
435 $wrapper = new CRM_Utils_Wrapper();
884605ca
DL
436 $arguments = array(
437 'urlToSession' => array(
438 array(
439 'urlVar' => 'instanceId',
440 'type' => 'Positive',
441 'sessionVar' => 'instanceId',
442 'default' => 'null',
443 ),
6001af1f 444 ),
21dfd5f5 445 'ignoreKey' => TRUE,
6001af1f 446 );
6a488035
TO
447 $messages[] = $wrapper->run($templateInfo['name'], NULL, $arguments);
448 }
449 else {
450 $is_error = 1;
451 if (!$instanceId) {
452 $messages[] = 'Required parameter missing: instanceId';
453 }
454 else {
455 $messages[] = 'Did not find valid instance to execute';
456 }
457 }
458
459 $result = array(
460 'is_error' => $is_error,
461 'messages' => implode("\n", $messages),
462 );
463 return $result;
464 }
465
466 /**
467 * Build a URL query string containing all report filter criteria that are
468 * stipulated in $_GET or in a report Preview, but which haven't yet been
469 * saved in the report instance.
470 *
7e06c9f5
TO
471 * @param array $defaults
472 * The report criteria that aren't coming in as submitted form values, as in CRM_Report_Form::_defaults.
473 * @param array $params
474 * All effective report criteria, as in CRM_Report_Form::_params.
6a488035 475 *
a6c01b45
CW
476 * @return string
477 * URL query string
6a488035 478 */
00be9182 479 public static function getPreviewCriteriaQueryParams($defaults = array(), $params = array()) {
6a488035
TO
480 static $query_string;
481 if (!isset($query_string)) {
482 if (!empty($params)) {
483 $url_params = $op_values = $string_values = $process_params = array();
484
485 // We'll only use $params that are different from what's in $default.
486 foreach ($params as $field_name => $field_value) {
487 if (!array_key_exists($field_name, $defaults) || $defaults[$field_name] != $field_value) {
488 $process_params[$field_name] = $field_value;
489 }
490 }
491 // Criteria stipulated in $_GET will be in $defaults even if they're not
492 // saved, so we can't easily tell if they're saved or not. So just include them.
493 $process_params += $_GET;
494
495 // All $process_params should be passed on if they have an effective value
496 // (in other words, there's no point in propagating blank filters).
497 foreach ($process_params as $field_name => $field_value) {
498 $suffix_position = strrpos($field_name, '_');
353ffa53
TO
499 $suffix = substr($field_name, $suffix_position);
500 $basename = substr($field_name, 0, $suffix_position);
6a488035
TO
501 if ($suffix == '_min' || $suffix == '_max' ||
502 $suffix == '_from' || $suffix == '_to' ||
503 $suffix == '_relative'
504 ) {
505 // For these types, we only keep them if they have a value.
506 if (!empty($field_value)) {
507 $url_params[$field_name] = $field_value;
508 }
509 }
510 elseif ($suffix == '_value') {
511 // These filters can have an effect even without a value
512 // (e.g., values for 'nll' and 'nnll' ops are blank),
513 // so store them temporarily and examine below.
514 $string_values[$basename] = $field_value;
515 $op_values[$basename] = CRM_Utils_Array::value("{$basename}_op", $params);
516 }
517 elseif ($suffix == '_op') {
518 // These filters can have an effect even without a value
519 // (e.g., values for 'nll' and 'nnll' ops are blank),
520 // so store them temporarily and examine below.
521 $op_values[$basename] = $field_value;
522 $string_values[$basename] = $params["{$basename}_value"];
523 }
524 }
525
526 // Check the *_value and *_op criteria and include them if
527 // they'll have an effective value.
528 foreach ($op_values as $basename => $field_value) {
529 if ($field_value == 'nll' || $field_value == 'nnll') {
530 // 'nll' and 'nnll' filters should be included even with empty values.
531 $url_params["{$basename}_op"] = $field_value;
532 }
533 elseif ($string_values[$basename]) {
534 // Other filters are only included if they have a value.
535 $url_params["{$basename}_op"] = $field_value;
536 $url_params["{$basename}_value"] = (is_array($string_values[$basename]) ? implode(',', $string_values[$basename]) : $string_values[$basename]);
537 }
538 }
539 $query_string = http_build_query($url_params);
540 }
541 else {
542 $query_string = '';
543 }
544 }
545 return $query_string;
546 }
547
74cf4551
EM
548 /**
549 * @param $reportUrl
550 *
551 * @return mixed
552 */
00be9182 553 public static function getInstanceList($reportUrl) {
6a488035 554 static $instanceDetails = array();
6001af1f 555
481a74f4 556 if (!array_key_exists($reportUrl, $instanceDetails)) {
6a488035
TO
557 $instanceDetails[$reportUrl] = array();
558
559 $sql = "
560SELECT id, title FROM civicrm_report_instance
561WHERE report_id = %1";
562 $params = array(1 => array($reportUrl, 'String'));
563 $result = CRM_Core_DAO::executeQuery($sql, $params);
22e263ad 564 while ($result->fetch()) {
6a488035
TO
565 $instanceDetails[$reportUrl][$result->id] = $result->title . " (ID: {$result->id})";
566 }
567 }
568 return $instanceDetails[$reportUrl];
569 }
96025800 570
6a488035 571}