INFRA-132 - Drupal.Classes.ClassDeclaration
[civicrm-core.git] / CRM / Report / Utils / Report.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
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
57 // put rest of arguement back in the form of url, which is how value
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 /**
4f1f1f2a 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
TO
225 //Mark as a CSV file.
226 header('Content-Type: text/csv');
227
228 //Force a download and name the file using the current timestamp.
229 $datetime = date('Ymd-Gi', $_SERVER['REQUEST_TIME']);
230 header('Content-Disposition: attachment; filename=Report_' . $datetime . '.csv');
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.
238 */
00be9182 239 public static function makeCsv(&$form, &$rows) {
6a488035
TO
240 $config = CRM_Core_Config::singleton();
241 $csv = '';
242
243 // Add headers if this is the first row.
244 $columnHeaders = array_keys($form->_columnHeaders);
245
246 // Replace internal header names with friendly ones, where available.
247 foreach ($columnHeaders as $header) {
248 if (isset($form->_columnHeaders[$header])) {
249 $headers[] = '"' . html_entity_decode(strip_tags($form->_columnHeaders[$header]['title'])) . '"';
250 }
251 }
252 // Add the headers.
253 $csv .= implode($config->fieldSeparator,
353ffa53
TO
254 $headers
255 ) . "\r\n";
6a488035
TO
256
257 $displayRows = array();
258 $value = NULL;
259 foreach ($rows as $row) {
260 foreach ($columnHeaders as $k => $v) {
261 $value = CRM_Utils_Array::value($v, $row);
262 if (isset($value)) {
263 // Remove HTML, unencode entities, and escape quotation marks.
264 $value = str_replace('"', '""', html_entity_decode(strip_tags($value)));
265
266 if (CRM_Utils_Array::value('type', $form->_columnHeaders[$v]) & 4) {
267 if (CRM_Utils_Array::value('group_by', $form->_columnHeaders[$v]) == 'MONTH' ||
268 CRM_Utils_Array::value('group_by', $form->_columnHeaders[$v]) == 'QUARTER'
269 ) {
270 $value = CRM_Utils_Date::customFormat($value, $config->dateformatPartial);
271 }
272 elseif (CRM_Utils_Array::value('group_by', $form->_columnHeaders[$v]) == 'YEAR') {
273 $value = CRM_Utils_Date::customFormat($value, $config->dateformatYear);
274 }
275 else {
276 $value = CRM_Utils_Date::customFormat($value, '%Y-%m-%d');
277 }
278 }
279 elseif (CRM_Utils_Array::value('type', $form->_columnHeaders[$v]) == 1024) {
280 $value = CRM_Utils_Money::format($value);
281 }
282 $displayRows[$v] = '"' . $value . '"';
283 }
284 else {
285 $displayRows[$v] = " ";
286 }
287 }
288 // Add the data row.
289 $csv .= implode($config->fieldSeparator,
353ffa53
TO
290 $displayRows
291 ) . "\r\n";
6a488035
TO
292 }
293
294 return $csv;
295 }
296
74cf4551
EM
297 /**
298 * @return mixed
299 */
00be9182 300 public static function getInstanceID() {
6a488035
TO
301
302 $config = CRM_Core_Config::singleton();
303 $arg = explode('/', $_GET[$config->userFrameworkURLVar]);
304
305 if ($arg[1] == 'report' &&
306 CRM_Utils_Array::value(2, $arg) == 'instance'
307 ) {
308 if (CRM_Utils_Rule::positiveInteger($arg[3])) {
309 return $arg[3];
310 }
311 }
312 }
313
74cf4551
EM
314 /**
315 * @return string
316 */
00be9182 317 public static function getInstancePath() {
6a488035
TO
318 $config = CRM_Core_Config::singleton();
319 $arg = explode('/', $_GET[$config->userFrameworkURLVar]);
320
321 if ($arg[1] == 'report' &&
322 CRM_Utils_Array::value(2, $arg) == 'instance'
323 ) {
324 unset($arg[0], $arg[1], $arg[2]);
325 $path = trim(CRM_Utils_Type::escape(implode('/', $arg), 'String'), '/');
326 return $path;
327 }
328 }
329
74cf4551 330 /**
100fef9d 331 * @param int $instanceId
74cf4551
EM
332 *
333 * @return bool
334 */
00be9182 335 public static function isInstancePermissioned($instanceId) {
6a488035
TO
336 if (!$instanceId) {
337 return TRUE;
338 }
339
340 $instanceValues = array();
341 $params = array('id' => $instanceId);
0b25329b 342 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
6a488035
TO
343 $params,
344 $instanceValues
345 );
346
347 if (!empty($instanceValues['permission']) &&
348 (!(CRM_Core_Permission::check($instanceValues['permission']) ||
353ffa53
TO
349 CRM_Core_Permission::check('administer Reports')
350 ))
6a488035
TO
351 ) {
352 return FALSE;
353 }
354
355 return TRUE;
356 }
357
358 /**
359 * Check if the user can view a report instance based on their role(s)
360 *
361 * @instanceId string $str the report instance to check
362 *
100fef9d 363 * @param int $instanceId
fd31fa4c 364 *
acb1052e 365 * @return bool
a6c01b45 366 * true if yes, else false
6a488035 367 */
00be9182 368 public static function isInstanceGroupRoleAllowed($instanceId) {
6a488035
TO
369 if (!$instanceId) {
370 return TRUE;
371 }
372
373 $instanceValues = array();
374 $params = array('id' => $instanceId);
0b25329b 375 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
6a488035
TO
376 $params,
377 $instanceValues
378 );
379 //transform grouprole to array
380 if (!empty($instanceValues['grouprole'])) {
381 $grouprole_array = explode(CRM_Core_DAO::VALUE_SEPARATOR,
382 $instanceValues['grouprole']
383 );
384 if (!CRM_Core_Permission::checkGroupRole($grouprole_array) &&
385 !CRM_Core_Permission::check('administer Reports')
386 ) {
387 return FALSE;
388 }
389 }
390 return TRUE;
391 }
392
74cf4551 393 /**
c490a46a 394 * @param array $params
74cf4551
EM
395 *
396 * @return array
397 */
00be9182 398 public static function processReport($params) {
6a488035
TO
399 $instanceId = CRM_Utils_Array::value('instanceId', $params);
400
401 // hack for now, CRM-8358
402 $_REQUEST['instanceId'] = $instanceId;
403 $_REQUEST['sendmail'] = CRM_Utils_Array::value('sendmail', $params, 1);
884605ca 404
6a488035
TO
405 // if cron is run from terminal --output is reserved, and therefore we would provide another name 'format'
406 $_REQUEST['output'] = CRM_Utils_Array::value('format', $params, CRM_Utils_Array::value('output', $params, 'pdf'));
407 $_REQUEST['reset'] = CRM_Utils_Array::value('reset', $params, 1);
408
409 $optionVal = self::getValueFromUrl($instanceId);
410 $messages = array("Report Mail Triggered...");
411
412 $templateInfo = CRM_Core_OptionGroup::getRowValues('report_template', $optionVal, 'value');
353ffa53
TO
413 $obj = new CRM_Report_Page_Instance();
414 $is_error = 0;
6a488035
TO
415 if (strstr(CRM_Utils_Array::value('name', $templateInfo), '_Form')) {
416 $instanceInfo = array();
0b25329b 417 CRM_Report_BAO_ReportInstance::retrieve(array('id' => $instanceId), $instanceInfo);
6a488035
TO
418
419 if (!empty($instanceInfo['title'])) {
420 $obj->assign('reportTitle', $instanceInfo['title']);
421 }
422 else {
423 $obj->assign('reportTitle', $templateInfo['label']);
424 }
425
426 $wrapper = new CRM_Utils_Wrapper();
884605ca
DL
427 $arguments = array(
428 'urlToSession' => array(
429 array(
430 'urlVar' => 'instanceId',
431 'type' => 'Positive',
432 'sessionVar' => 'instanceId',
433 'default' => 'null',
434 ),
6001af1f 435 ),
21dfd5f5 436 'ignoreKey' => TRUE,
6001af1f 437 );
6a488035
TO
438 $messages[] = $wrapper->run($templateInfo['name'], NULL, $arguments);
439 }
440 else {
441 $is_error = 1;
442 if (!$instanceId) {
443 $messages[] = 'Required parameter missing: instanceId';
444 }
445 else {
446 $messages[] = 'Did not find valid instance to execute';
447 }
448 }
449
450 $result = array(
451 'is_error' => $is_error,
452 'messages' => implode("\n", $messages),
453 );
454 return $result;
455 }
456
457 /**
458 * Build a URL query string containing all report filter criteria that are
459 * stipulated in $_GET or in a report Preview, but which haven't yet been
460 * saved in the report instance.
461 *
7e06c9f5
TO
462 * @param array $defaults
463 * The report criteria that aren't coming in as submitted form values, as in CRM_Report_Form::_defaults.
464 * @param array $params
465 * All effective report criteria, as in CRM_Report_Form::_params.
6a488035 466 *
a6c01b45
CW
467 * @return string
468 * URL query string
6a488035 469 */
00be9182 470 public static function getPreviewCriteriaQueryParams($defaults = array(), $params = array()) {
6a488035
TO
471 static $query_string;
472 if (!isset($query_string)) {
473 if (!empty($params)) {
474 $url_params = $op_values = $string_values = $process_params = array();
475
476 // We'll only use $params that are different from what's in $default.
477 foreach ($params as $field_name => $field_value) {
478 if (!array_key_exists($field_name, $defaults) || $defaults[$field_name] != $field_value) {
479 $process_params[$field_name] = $field_value;
480 }
481 }
482 // Criteria stipulated in $_GET will be in $defaults even if they're not
483 // saved, so we can't easily tell if they're saved or not. So just include them.
484 $process_params += $_GET;
485
486 // All $process_params should be passed on if they have an effective value
487 // (in other words, there's no point in propagating blank filters).
488 foreach ($process_params as $field_name => $field_value) {
489 $suffix_position = strrpos($field_name, '_');
353ffa53
TO
490 $suffix = substr($field_name, $suffix_position);
491 $basename = substr($field_name, 0, $suffix_position);
6a488035
TO
492 if ($suffix == '_min' || $suffix == '_max' ||
493 $suffix == '_from' || $suffix == '_to' ||
494 $suffix == '_relative'
495 ) {
496 // For these types, we only keep them if they have a value.
497 if (!empty($field_value)) {
498 $url_params[$field_name] = $field_value;
499 }
500 }
501 elseif ($suffix == '_value') {
502 // These filters can have an effect even without a value
503 // (e.g., values for 'nll' and 'nnll' ops are blank),
504 // so store them temporarily and examine below.
505 $string_values[$basename] = $field_value;
506 $op_values[$basename] = CRM_Utils_Array::value("{$basename}_op", $params);
507 }
508 elseif ($suffix == '_op') {
509 // These filters can have an effect even without a value
510 // (e.g., values for 'nll' and 'nnll' ops are blank),
511 // so store them temporarily and examine below.
512 $op_values[$basename] = $field_value;
513 $string_values[$basename] = $params["{$basename}_value"];
514 }
515 }
516
517 // Check the *_value and *_op criteria and include them if
518 // they'll have an effective value.
519 foreach ($op_values as $basename => $field_value) {
520 if ($field_value == 'nll' || $field_value == 'nnll') {
521 // 'nll' and 'nnll' filters should be included even with empty values.
522 $url_params["{$basename}_op"] = $field_value;
523 }
524 elseif ($string_values[$basename]) {
525 // Other filters are only included if they have a value.
526 $url_params["{$basename}_op"] = $field_value;
527 $url_params["{$basename}_value"] = (is_array($string_values[$basename]) ? implode(',', $string_values[$basename]) : $string_values[$basename]);
528 }
529 }
530 $query_string = http_build_query($url_params);
531 }
532 else {
533 $query_string = '';
534 }
535 }
536 return $query_string;
537 }
538
74cf4551
EM
539 /**
540 * @param $reportUrl
541 *
542 * @return mixed
543 */
00be9182 544 public static function getInstanceList($reportUrl) {
6a488035 545 static $instanceDetails = array();
6001af1f 546
481a74f4 547 if (!array_key_exists($reportUrl, $instanceDetails)) {
6a488035
TO
548 $instanceDetails[$reportUrl] = array();
549
550 $sql = "
551SELECT id, title FROM civicrm_report_instance
552WHERE report_id = %1";
553 $params = array(1 => array($reportUrl, 'String'));
554 $result = CRM_Core_DAO::executeQuery($sql, $params);
22e263ad 555 while ($result->fetch()) {
6a488035
TO
556 $instanceDetails[$reportUrl][$result->id] = $result->title . " (ID: {$result->id})";
557 }
558 }
559 return $instanceDetails[$reportUrl];
560 }
96025800 561
6a488035 562}