INFRA-132 - CRM/Report - phpcbf
[civicrm-core.git] / CRM / Report / Utils / Report.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.6 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36 class CRM_Report_Utils_Report {
37
38 /**
39 * @param int $instanceID
40 *
41 * @return null|string
42 */
43 public static function getValueFromUrl($instanceID = NULL) {
44 if ($instanceID) {
45 $optionVal = CRM_Core_DAO::getFieldValue('CRM_Report_DAO_ReportInstance',
46 $instanceID,
47 'report_id'
48 );
49 }
50 else {
51 $config = CRM_Core_Config::singleton();
52 $args = explode('/', $_GET[$config->userFrameworkURLVar]);
53
54 // remove 'civicrm/report' from args
55 array_shift($args);
56 array_shift($args);
57
58 // put rest of arguement back in the form of url, which is how value
59 // is stored in option value table
60 $optionVal = implode('/', $args);
61 }
62 return $optionVal;
63 }
64
65 /**
66 * @param int $instanceID
67 *
68 * @return array|bool
69 */
70 public static function getValueIDFromUrl($instanceID = NULL) {
71 $optionVal = self::getValueFromUrl($instanceID);
72
73 if ($optionVal) {
74 $templateInfo = CRM_Core_OptionGroup::getRowValues('report_template', "{$optionVal}", 'value');
75 return array(CRM_Utils_Array::value('id', $templateInfo), $optionVal);
76 }
77
78 return FALSE;
79 }
80
81 /**
82 * @param $optionVal
83 *
84 * @return mixed
85 */
86 public static function getInstanceIDForValue($optionVal) {
87 static $valId = array();
88
89 if (!array_key_exists($optionVal, $valId)) {
90 $sql = "
91 SELECT MIN(id) FROM civicrm_report_instance
92 WHERE report_id = %1";
93
94 $params = array(1 => array($optionVal, 'String'));
95 $valId[$optionVal] = CRM_Core_DAO::singleValueQuery($sql, $params);
96 }
97 return $valId[$optionVal];
98 }
99
100 /**
101 * @param null $path
102 *
103 * @return mixed
104 */
105 public static function getInstanceIDForPath($path = NULL) {
106 static $valId = array();
107
108 // if $path is null, try to get it from url
109 $path = self::getInstancePath();
110
111 if ($path && !array_key_exists($path, $valId)) {
112 $sql = "
113 SELECT MIN(id) FROM civicrm_report_instance
114 WHERE TRIM(BOTH '/' FROM CONCAT(report_id, '/', name)) = %1";
115
116 $params = array(1 => array($path, 'String'));
117 $valId[$path] = CRM_Core_DAO::singleValueQuery($sql, $params);
118 }
119 return CRM_Utils_Array::value($path, $valId);
120 }
121
122 /**
123 * @param $urlValue
124 * @param string $query
125 * @param bool $absolute
126 * @param int $instanceID
127 * @param array $drilldownReport
128 *
129 * @return bool|string
130 */
131 public static function getNextUrl($urlValue, $query = 'reset=1', $absolute = FALSE, $instanceID = NULL, $drilldownReport = array()) {
132 if ($instanceID) {
133 $drilldownInstanceID = FALSE;
134 if (array_key_exists($urlValue, $drilldownReport)) {
135 $drilldownInstanceID = CRM_Core_DAO::getFieldValue('CRM_Report_DAO_ReportInstance', $instanceID, 'drilldown_id', 'id');
136 }
137
138 if (!$drilldownInstanceID) {
139 $drilldownInstanceID = self::getInstanceIDForValue($urlValue);
140 }
141
142 if ($drilldownInstanceID) {
143 return CRM_Utils_System::url("civicrm/report/instance/{$drilldownInstanceID}",
144 "{$query}", $absolute
145 );
146 }
147 else {
148 return FALSE;
149 }
150 }
151 else {
152 return CRM_Utils_System::url("civicrm/report/" . trim($urlValue, '/'),
153 $query, $absolute
154 );
155 }
156 }
157
158 // get instance count for a template
159 /**
160 * @param $optionVal
161 *
162 * @return int|null|string
163 */
164 public static function getInstanceCount($optionVal) {
165 if (empty($optionVal)) { return 0;
166 }
167
168 $sql = "
169 SELECT count(inst.id)
170 FROM civicrm_report_instance inst
171 WHERE 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
178 /**
179 * @param $fileContent
180 * @param int $instanceID
181 * @param string $outputMode
182 * @param array $attachments
183 *
184 * @return bool
185 */
186 public static function mailReport($fileContent, $instanceID = NULL, $outputMode = 'html', $attachments = array()) {
187 if (!$instanceID) {
188 return FALSE;
189 }
190
191 list($domainEmailName,
192 $domainEmailAddress
193 ) = CRM_Core_BAO_Domain::getNameAndEmail();
194
195 $params = array('id' => $instanceID);
196 $instanceInfo = array();
197 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
198 $params,
199 $instanceInfo
200 );
201
202 $params = array();
203 $params['groupName'] = 'Report Email Sender';
204 $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
205 //$domainEmailName;
206 $params['toName'] = "";
207 $params['toEmail'] = CRM_Utils_Array::value('email_to', $instanceInfo);
208 $params['cc'] = CRM_Utils_Array::value('email_cc', $instanceInfo);
209 $params['subject'] = CRM_Utils_Array::value('email_subject', $instanceInfo);
210 if (empty($instanceInfo['attachments'])) {
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
220 /**
221 * @param CRM_Core_Form $form
222 * @param $rows
223 */
224 public static function export2csv(&$form, &$rows) {
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 */
239 public static function makeCsv(&$form, &$rows) {
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,
254 $headers
255 ) . "\r\n";
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,
290 $displayRows
291 ) . "\r\n";
292 }
293
294 return $csv;
295 }
296
297 /**
298 * @return mixed
299 */
300 public static function getInstanceID() {
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
314 /**
315 * @return string
316 */
317 public static function getInstancePath() {
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
330 /**
331 * @param int $instanceId
332 *
333 * @return bool
334 */
335 public static function isInstancePermissioned($instanceId) {
336 if (!$instanceId) {
337 return TRUE;
338 }
339
340 $instanceValues = array();
341 $params = array('id' => $instanceId);
342 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
343 $params,
344 $instanceValues
345 );
346
347 if (!empty($instanceValues['permission']) &&
348 (!(CRM_Core_Permission::check($instanceValues['permission']) ||
349 CRM_Core_Permission::check('administer Reports')
350 ))
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 *
363 * @param int $instanceId
364 *
365 * @return boolean true if yes, else false
366 * @static
367 */
368 public static function isInstanceGroupRoleAllowed($instanceId) {
369 if (!$instanceId) {
370 return TRUE;
371 }
372
373 $instanceValues = array();
374 $params = array('id' => $instanceId);
375 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
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
393 /**
394 * @param array $params
395 *
396 * @return array
397 */
398 public static function processReport($params) {
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);
404
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');
413 $obj = new CRM_Report_Page_Instance();
414 $is_error = 0;
415 if (strstr(CRM_Utils_Array::value('name', $templateInfo), '_Form')) {
416 $instanceInfo = array();
417 CRM_Report_BAO_ReportInstance::retrieve(array('id' => $instanceId), $instanceInfo);
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();
427 $arguments = array(
428 'urlToSession' => array(
429 array(
430 'urlVar' => 'instanceId',
431 'type' => 'Positive',
432 'sessionVar' => 'instanceId',
433 'default' => 'null',
434 ),
435 ),
436 'ignoreKey' => TRUE
437 );
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 *
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.
466 *
467 * @return string URL query string
468 */
469 public static function getPreviewCriteriaQueryParams($defaults = array(), $params = array()) {
470 static $query_string;
471 if (!isset($query_string)) {
472 if (!empty($params)) {
473 $url_params = $op_values = $string_values = $process_params = array();
474
475 // We'll only use $params that are different from what's in $default.
476 foreach ($params as $field_name => $field_value) {
477 if (!array_key_exists($field_name, $defaults) || $defaults[$field_name] != $field_value) {
478 $process_params[$field_name] = $field_value;
479 }
480 }
481 // Criteria stipulated in $_GET will be in $defaults even if they're not
482 // saved, so we can't easily tell if they're saved or not. So just include them.
483 $process_params += $_GET;
484
485 // All $process_params should be passed on if they have an effective value
486 // (in other words, there's no point in propagating blank filters).
487 foreach ($process_params as $field_name => $field_value) {
488 $suffix_position = strrpos($field_name, '_');
489 $suffix = substr($field_name, $suffix_position);
490 $basename = substr($field_name, 0, $suffix_position);
491 if ($suffix == '_min' || $suffix == '_max' ||
492 $suffix == '_from' || $suffix == '_to' ||
493 $suffix == '_relative'
494 ) {
495 // For these types, we only keep them if they have a value.
496 if (!empty($field_value)) {
497 $url_params[$field_name] = $field_value;
498 }
499 }
500 elseif ($suffix == '_value') {
501 // These filters can have an effect even without a value
502 // (e.g., values for 'nll' and 'nnll' ops are blank),
503 // so store them temporarily and examine below.
504 $string_values[$basename] = $field_value;
505 $op_values[$basename] = CRM_Utils_Array::value("{$basename}_op", $params);
506 }
507 elseif ($suffix == '_op') {
508 // These filters can have an effect even without a value
509 // (e.g., values for 'nll' and 'nnll' ops are blank),
510 // so store them temporarily and examine below.
511 $op_values[$basename] = $field_value;
512 $string_values[$basename] = $params["{$basename}_value"];
513 }
514 }
515
516 // Check the *_value and *_op criteria and include them if
517 // they'll have an effective value.
518 foreach ($op_values as $basename => $field_value) {
519 if ($field_value == 'nll' || $field_value == 'nnll') {
520 // 'nll' and 'nnll' filters should be included even with empty values.
521 $url_params["{$basename}_op"] = $field_value;
522 }
523 elseif ($string_values[$basename]) {
524 // Other filters are only included if they have a value.
525 $url_params["{$basename}_op"] = $field_value;
526 $url_params["{$basename}_value"] = (is_array($string_values[$basename]) ? implode(',', $string_values[$basename]) : $string_values[$basename]);
527 }
528 }
529 $query_string = http_build_query($url_params);
530 }
531 else {
532 $query_string = '';
533 }
534 }
535 return $query_string;
536 }
537
538 /**
539 * @param $reportUrl
540 *
541 * @return mixed
542 */
543 public static function getInstanceList($reportUrl) {
544 static $instanceDetails = array();
545
546 if (!array_key_exists($reportUrl, $instanceDetails )) {
547 $instanceDetails[$reportUrl] = array();
548
549 $sql = "
550 SELECT id, title FROM civicrm_report_instance
551 WHERE report_id = %1";
552 $params = array(1 => array($reportUrl, 'String'));
553 $result = CRM_Core_DAO::executeQuery($sql, $params);
554 while( $result->fetch()) {
555 $instanceDetails[$reportUrl][$result->id] = $result->title . " (ID: {$result->id})";
556 }
557 }
558 return $instanceDetails[$reportUrl];
559 }
560 }