62de36c2b2dee56dc090387f24c2b4907e52f1cd
[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 if (!$drilldownInstanceID)
138 $drilldownInstanceID = self::getInstanceIDForValue($urlValue);
139
140 if ($drilldownInstanceID) {
141 return CRM_Utils_System::url("civicrm/report/instance/{$drilldownInstanceID}",
142 "{$query}", $absolute
143 );
144 }
145 else {
146 return FALSE;
147 }
148 }
149 else {
150 return CRM_Utils_System::url("civicrm/report/" . trim($urlValue, '/'),
151 $query, $absolute
152 );
153 }
154 }
155
156 // get instance count for a template
157 /**
158 * @param $optionVal
159 *
160 * @return int|null|string
161 */
162 public static function getInstanceCount($optionVal) {
163 if (empty($optionVal)) return 0;
164
165 $sql = "
166 SELECT count(inst.id)
167 FROM civicrm_report_instance inst
168 WHERE inst.report_id = %1";
169
170 $params = array(1 => array($optionVal, 'String'));
171 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
172 return $count;
173 }
174
175 /**
176 * @param $fileContent
177 * @param int $instanceID
178 * @param string $outputMode
179 * @param array $attachments
180 *
181 * @return bool
182 */
183 public static function mailReport($fileContent, $instanceID = NULL, $outputMode = 'html', $attachments = array()) {
184 if (!$instanceID) {
185 return FALSE;
186 }
187
188 list($domainEmailName,
189 $domainEmailAddress
190 ) = CRM_Core_BAO_Domain::getNameAndEmail();
191
192 $params = array('id' => $instanceID);
193 $instanceInfo = array();
194 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
195 $params,
196 $instanceInfo
197 );
198
199 $params = array();
200 $params['groupName'] = 'Report Email Sender';
201 $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
202 //$domainEmailName;
203 $params['toName'] = "";
204 $params['toEmail'] = CRM_Utils_Array::value('email_to', $instanceInfo);
205 $params['cc'] = CRM_Utils_Array::value('email_cc', $instanceInfo);
206 $params['subject'] = CRM_Utils_Array::value('email_subject', $instanceInfo);
207 if (empty($instanceInfo['attachments'])) {
208 $instanceInfo['attachments'] = array();
209 }
210 $params['attachments'] = array_merge(CRM_Utils_Array::value('attachments', $instanceInfo), $attachments);
211 $params['text'] = '';
212 $params['html'] = $fileContent;
213
214 return CRM_Utils_Mail::send($params);
215 }
216
217 /**
218 * @param CRM_Core_Form $form
219 * @param $rows
220 */
221 public static function export2csv(&$form, &$rows) {
222 //Mark as a CSV file.
223 header('Content-Type: text/csv');
224
225 //Force a download and name the file using the current timestamp.
226 $datetime = date('Ymd-Gi', $_SERVER['REQUEST_TIME']);
227 header('Content-Disposition: attachment; filename=Report_' . $datetime . '.csv');
228 echo self::makeCsv($form, $rows);
229 CRM_Utils_System::civiExit();
230 }
231
232 /**
233 * Utility function for export2csv and CRM_Report_Form::endPostProcess
234 * - make CSV file content and return as string.
235 */
236 public static function makeCsv(&$form, &$rows) {
237 $config = CRM_Core_Config::singleton();
238 $csv = '';
239
240 // Add headers if this is the first row.
241 $columnHeaders = array_keys($form->_columnHeaders);
242
243 // Replace internal header names with friendly ones, where available.
244 foreach ($columnHeaders as $header) {
245 if (isset($form->_columnHeaders[$header])) {
246 $headers[] = '"' . html_entity_decode(strip_tags($form->_columnHeaders[$header]['title'])) . '"';
247 }
248 }
249 // Add the headers.
250 $csv .= implode($config->fieldSeparator,
251 $headers
252 ) . "\r\n";
253
254 $displayRows = array();
255 $value = NULL;
256 foreach ($rows as $row) {
257 foreach ($columnHeaders as $k => $v) {
258 $value = CRM_Utils_Array::value($v, $row);
259 if (isset($value)) {
260 // Remove HTML, unencode entities, and escape quotation marks.
261 $value = str_replace('"', '""', html_entity_decode(strip_tags($value)));
262
263 if (CRM_Utils_Array::value('type', $form->_columnHeaders[$v]) & 4) {
264 if (CRM_Utils_Array::value('group_by', $form->_columnHeaders[$v]) == 'MONTH' ||
265 CRM_Utils_Array::value('group_by', $form->_columnHeaders[$v]) == 'QUARTER'
266 ) {
267 $value = CRM_Utils_Date::customFormat($value, $config->dateformatPartial);
268 }
269 elseif (CRM_Utils_Array::value('group_by', $form->_columnHeaders[$v]) == 'YEAR') {
270 $value = CRM_Utils_Date::customFormat($value, $config->dateformatYear);
271 }
272 else {
273 $value = CRM_Utils_Date::customFormat($value, '%Y-%m-%d');
274 }
275 }
276 elseif (CRM_Utils_Array::value('type', $form->_columnHeaders[$v]) == 1024) {
277 $value = CRM_Utils_Money::format($value);
278 }
279 $displayRows[$v] = '"' . $value . '"';
280 }
281 else {
282 $displayRows[$v] = " ";
283 }
284 }
285 // Add the data row.
286 $csv .= implode($config->fieldSeparator,
287 $displayRows
288 ) . "\r\n";
289 }
290
291 return $csv;
292 }
293
294 /**
295 * @return mixed
296 */
297 public static function getInstanceID() {
298
299 $config = CRM_Core_Config::singleton();
300 $arg = explode('/', $_GET[$config->userFrameworkURLVar]);
301
302 if ($arg[1] == 'report' &&
303 CRM_Utils_Array::value(2, $arg) == 'instance'
304 ) {
305 if (CRM_Utils_Rule::positiveInteger($arg[3])) {
306 return $arg[3];
307 }
308 }
309 }
310
311 /**
312 * @return string
313 */
314 public static function getInstancePath() {
315 $config = CRM_Core_Config::singleton();
316 $arg = explode('/', $_GET[$config->userFrameworkURLVar]);
317
318 if ($arg[1] == 'report' &&
319 CRM_Utils_Array::value(2, $arg) == 'instance'
320 ) {
321 unset($arg[0], $arg[1], $arg[2]);
322 $path = trim(CRM_Utils_Type::escape(implode('/', $arg), 'String'), '/');
323 return $path;
324 }
325 }
326
327 /**
328 * @param int $instanceId
329 *
330 * @return bool
331 */
332 public static function isInstancePermissioned($instanceId) {
333 if (!$instanceId) {
334 return TRUE;
335 }
336
337 $instanceValues = array();
338 $params = array('id' => $instanceId);
339 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
340 $params,
341 $instanceValues
342 );
343
344 if (!empty($instanceValues['permission']) &&
345 (!(CRM_Core_Permission::check($instanceValues['permission']) ||
346 CRM_Core_Permission::check('administer Reports')
347 ))
348 ) {
349 return FALSE;
350 }
351
352 return TRUE;
353 }
354
355 /**
356 * Check if the user can view a report instance based on their role(s)
357 *
358 * @instanceId string $str the report instance to check
359 *
360 * @param int $instanceId
361 *
362 * @return boolean true if yes, else false
363 * @static
364 */
365 public static function isInstanceGroupRoleAllowed($instanceId) {
366 if (!$instanceId) {
367 return TRUE;
368 }
369
370 $instanceValues = array();
371 $params = array('id' => $instanceId);
372 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
373 $params,
374 $instanceValues
375 );
376 //transform grouprole to array
377 if (!empty($instanceValues['grouprole'])) {
378 $grouprole_array = explode(CRM_Core_DAO::VALUE_SEPARATOR,
379 $instanceValues['grouprole']
380 );
381 if (!CRM_Core_Permission::checkGroupRole($grouprole_array) &&
382 !CRM_Core_Permission::check('administer Reports')
383 ) {
384 return FALSE;
385 }
386 }
387 return TRUE;
388 }
389
390 /**
391 * @param array $params
392 *
393 * @return array
394 */
395 public static function processReport($params) {
396 $instanceId = CRM_Utils_Array::value('instanceId', $params);
397
398 // hack for now, CRM-8358
399 $_REQUEST['instanceId'] = $instanceId;
400 $_REQUEST['sendmail'] = CRM_Utils_Array::value('sendmail', $params, 1);
401
402 // if cron is run from terminal --output is reserved, and therefore we would provide another name 'format'
403 $_REQUEST['output'] = CRM_Utils_Array::value('format', $params, CRM_Utils_Array::value('output', $params, 'pdf'));
404 $_REQUEST['reset'] = CRM_Utils_Array::value('reset', $params, 1);
405
406 $optionVal = self::getValueFromUrl($instanceId);
407 $messages = array("Report Mail Triggered...");
408
409 $templateInfo = CRM_Core_OptionGroup::getRowValues('report_template', $optionVal, 'value');
410 $obj = new CRM_Report_Page_Instance();
411 $is_error = 0;
412 if (strstr(CRM_Utils_Array::value('name', $templateInfo), '_Form')) {
413 $instanceInfo = array();
414 CRM_Report_BAO_ReportInstance::retrieve(array('id' => $instanceId), $instanceInfo);
415
416 if (!empty($instanceInfo['title'])) {
417 $obj->assign('reportTitle', $instanceInfo['title']);
418 }
419 else {
420 $obj->assign('reportTitle', $templateInfo['label']);
421 }
422
423 $wrapper = new CRM_Utils_Wrapper();
424 $arguments = array(
425 'urlToSession' => array(
426 array(
427 'urlVar' => 'instanceId',
428 'type' => 'Positive',
429 'sessionVar' => 'instanceId',
430 'default' => 'null',
431 ),
432 ),
433 'ignoreKey' => TRUE
434 );
435 $messages[] = $wrapper->run($templateInfo['name'], NULL, $arguments);
436 }
437 else {
438 $is_error = 1;
439 if (!$instanceId) {
440 $messages[] = 'Required parameter missing: instanceId';
441 }
442 else {
443 $messages[] = 'Did not find valid instance to execute';
444 }
445 }
446
447 $result = array(
448 'is_error' => $is_error,
449 'messages' => implode("\n", $messages),
450 );
451 return $result;
452 }
453
454 /**
455 * Build a URL query string containing all report filter criteria that are
456 * stipulated in $_GET or in a report Preview, but which haven't yet been
457 * saved in the report instance.
458 *
459 * @param array $defaults
460 * The report criteria that aren't coming in as submitted form values, as in CRM_Report_Form::_defaults.
461 * @param array $params
462 * All effective report criteria, as in CRM_Report_Form::_params.
463 *
464 * @return string URL query string
465 */
466 public static function getPreviewCriteriaQueryParams($defaults = array(), $params = array()) {
467 static $query_string;
468 if (!isset($query_string)) {
469 if (!empty($params)) {
470 $url_params = $op_values = $string_values = $process_params = array();
471
472 // We'll only use $params that are different from what's in $default.
473 foreach ($params as $field_name => $field_value) {
474 if (!array_key_exists($field_name, $defaults) || $defaults[$field_name] != $field_value) {
475 $process_params[$field_name] = $field_value;
476 }
477 }
478 // Criteria stipulated in $_GET will be in $defaults even if they're not
479 // saved, so we can't easily tell if they're saved or not. So just include them.
480 $process_params += $_GET;
481
482 // All $process_params should be passed on if they have an effective value
483 // (in other words, there's no point in propagating blank filters).
484 foreach ($process_params as $field_name => $field_value) {
485 $suffix_position = strrpos($field_name, '_');
486 $suffix = substr($field_name, $suffix_position);
487 $basename = substr($field_name, 0, $suffix_position);
488 if ($suffix == '_min' || $suffix == '_max' ||
489 $suffix == '_from' || $suffix == '_to' ||
490 $suffix == '_relative'
491 ) {
492 // For these types, we only keep them if they have a value.
493 if (!empty($field_value)) {
494 $url_params[$field_name] = $field_value;
495 }
496 }
497 elseif ($suffix == '_value') {
498 // These filters can have an effect even without a value
499 // (e.g., values for 'nll' and 'nnll' ops are blank),
500 // so store them temporarily and examine below.
501 $string_values[$basename] = $field_value;
502 $op_values[$basename] = CRM_Utils_Array::value("{$basename}_op", $params);
503 }
504 elseif ($suffix == '_op') {
505 // These filters can have an effect even without a value
506 // (e.g., values for 'nll' and 'nnll' ops are blank),
507 // so store them temporarily and examine below.
508 $op_values[$basename] = $field_value;
509 $string_values[$basename] = $params["{$basename}_value"];
510 }
511 }
512
513 // Check the *_value and *_op criteria and include them if
514 // they'll have an effective value.
515 foreach ($op_values as $basename => $field_value) {
516 if ($field_value == 'nll' || $field_value == 'nnll') {
517 // 'nll' and 'nnll' filters should be included even with empty values.
518 $url_params["{$basename}_op"] = $field_value;
519 }
520 elseif ($string_values[$basename]) {
521 // Other filters are only included if they have a value.
522 $url_params["{$basename}_op"] = $field_value;
523 $url_params["{$basename}_value"] = (is_array($string_values[$basename]) ? implode(',', $string_values[$basename]) : $string_values[$basename]);
524 }
525 }
526 $query_string = http_build_query($url_params);
527 }
528 else {
529 $query_string = '';
530 }
531 }
532 return $query_string;
533 }
534
535 /**
536 * @param $reportUrl
537 *
538 * @return mixed
539 */
540 public static function getInstanceList($reportUrl) {
541 static $instanceDetails = array();
542
543 if (!array_key_exists($reportUrl, $instanceDetails )) {
544 $instanceDetails[$reportUrl] = array();
545
546 $sql = "
547 SELECT id, title FROM civicrm_report_instance
548 WHERE report_id = %1";
549 $params = array(1 => array($reportUrl, 'String'));
550 $result = CRM_Core_DAO::executeQuery($sql, $params);
551 while( $result->fetch()) {
552 $instanceDetails[$reportUrl][$result->id] = $result->title . " (ID: {$result->id})";
553 }
554 }
555 return $instanceDetails[$reportUrl];
556 }
557 }