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