4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
32 * @copyright CiviCRM LLC (c) 2004-2014
36 class CRM_Report_Utils_Report
{
39 * @param null $instanceID
43 static function getValueFromUrl($instanceID = NULL) {
45 $optionVal = CRM_Core_DAO
::getFieldValue('CRM_Report_DAO_ReportInstance',
51 $config = CRM_Core_Config
::singleton();
52 $args = explode('/', $_GET[$config->userFrameworkURLVar
]);
54 // remove 'civicrm/report' from args
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);
66 * @param null $instanceID
70 static function getValueIDFromUrl($instanceID = NULL) {
71 $optionVal = self
::getValueFromUrl($instanceID);
74 $templateInfo = CRM_Core_OptionGroup
::getRowValues('report_template', "{$optionVal}", 'value');
75 return array(CRM_Utils_Array
::value('id', $templateInfo), $optionVal);
86 static function getInstanceIDForValue($optionVal) {
87 static $valId = array();
89 if (!array_key_exists($optionVal, $valId)) {
91 SELECT MIN(id) FROM civicrm_report_instance
92 WHERE report_id = %1";
94 $params = array(1 => array($optionVal, 'String'));
95 $valId[$optionVal] = CRM_Core_DAO
::singleValueQuery($sql, $params);
97 return $valId[$optionVal];
105 static function getInstanceIDForPath($path = NULL) {
106 static $valId = array();
108 // if $path is null, try to get it from url
109 $path = self
::getInstancePath();
111 if ($path && !array_key_exists($path, $valId)) {
113 SELECT MIN(id) FROM civicrm_report_instance
114 WHERE TRIM(BOTH '/' FROM CONCAT(report_id, '/', name)) = %1";
116 $params = array(1 => array($path, 'String'));
117 $valId[$path] = CRM_Core_DAO
::singleValueQuery($sql, $params);
119 return CRM_Utils_Array
::value($path, $valId);
124 * @param string $query
125 * @param bool $absolute
126 * @param null $instanceID
127 * @param array $drilldownReport
129 * @return bool|string
131 static function getNextUrl($urlValue, $query = 'reset=1', $absolute = FALSE, $instanceID = NULL, $drilldownReport = array()) {
133 $drilldownInstanceID = false;
134 if (array_key_exists($urlValue, $drilldownReport))
135 $drilldownInstanceID = CRM_Core_DAO
::getFieldValue('CRM_Report_DAO_ReportInstance', $instanceID, 'drilldown_id', 'id');
137 if (!$drilldownInstanceID)
138 $drilldownInstanceID = self
::getInstanceIDForValue($urlValue);
140 if ($drilldownInstanceID) {
141 return CRM_Utils_System
::url("civicrm/report/instance/{$drilldownInstanceID}",
142 "{$query}", $absolute
150 return CRM_Utils_System
::url("civicrm/report/" . trim($urlValue, '/'),
156 // get instance count for a template
160 * @return int|null|string
162 static function getInstanceCount($optionVal) {
163 if (empty($optionVal)) return 0;
166 SELECT count(inst.id)
167 FROM civicrm_report_instance inst
168 WHERE inst.report_id = %1";
170 $params = array(1 => array($optionVal, 'String'));
171 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
176 * @param $fileContent
177 * @param null $instanceID
178 * @param string $outputMode
179 * @param array $attachments
183 static function mailReport($fileContent, $instanceID = NULL, $outputMode = 'html', $attachments = array(
189 list($domainEmailName,
191 ) = CRM_Core_BAO_Domain
::getNameAndEmail();
193 $params = array('id' => $instanceID);
194 $instanceInfo = array();
195 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
201 $params['groupName'] = 'Report Email Sender';
202 $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
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();
211 $params['attachments'] = array_merge(CRM_Utils_Array
::value('attachments', $instanceInfo), $attachments);
212 $params['text'] = '';
213 $params['html'] = $fileContent;
215 return CRM_Utils_Mail
::send($params);
222 static function export2csv(&$form, &$rows) {
223 //Mark as a CSV file.
224 header('Content-Type: text/csv');
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();
234 * Utility function for export2csv and CRM_Report_Form::endPostProcess
235 * - make CSV file content and return as string.
237 static function makeCsv(&$form, &$rows) {
238 $config = CRM_Core_Config
::singleton();
241 // Add headers if this is the first row.
242 $columnHeaders = array_keys($form->_columnHeaders
);
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'])) . '"';
251 $csv .= implode($config->fieldSeparator
,
255 $displayRows = array();
257 foreach ($rows as $row) {
258 foreach ($columnHeaders as $k => $v) {
259 $value = CRM_Utils_Array
::value($v, $row);
261 // Remove HTML, unencode entities, and escape quotation marks.
262 $value = str_replace('"', '""', html_entity_decode(strip_tags($value)));
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'
268 $value = CRM_Utils_Date
::customFormat($value, $config->dateformatPartial
);
270 elseif (CRM_Utils_Array
::value('group_by', $form->_columnHeaders
[$v]) == 'YEAR') {
271 $value = CRM_Utils_Date
::customFormat($value, $config->dateformatYear
);
274 $value = CRM_Utils_Date
::customFormat($value, '%Y-%m-%d');
277 elseif (CRM_Utils_Array
::value('type', $form->_columnHeaders
[$v]) == 1024) {
278 $value = CRM_Utils_Money
::format($value);
280 $displayRows[$v] = '"' . $value . '"';
283 $displayRows[$v] = " ";
287 $csv .= implode($config->fieldSeparator
,
298 static function getInstanceID() {
300 $config = CRM_Core_Config
::singleton();
301 $arg = explode('/', $_GET[$config->userFrameworkURLVar
]);
303 if ($arg[1] == 'report' &&
304 CRM_Utils_Array
::value(2, $arg) == 'instance'
306 if (CRM_Utils_Rule
::positiveInteger($arg[3])) {
315 static function getInstancePath() {
316 $config = CRM_Core_Config
::singleton();
317 $arg = explode('/', $_GET[$config->userFrameworkURLVar
]);
319 if ($arg[1] == 'report' &&
320 CRM_Utils_Array
::value(2, $arg) == 'instance'
322 unset($arg[0], $arg[1], $arg[2]);
323 $path = trim(CRM_Utils_Type
::escape(implode('/', $arg), 'String'), '/');
333 static function isInstancePermissioned($instanceId) {
338 $instanceValues = array();
339 $params = array('id' => $instanceId);
340 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
345 if (!empty($instanceValues['permission']) &&
346 (!(CRM_Core_Permission
::check($instanceValues['permission']) ||
347 CRM_Core_Permission
::check('administer Reports')
357 * Check if the user can view a report instance based on their role(s)
359 * @instanceId string $str the report instance to check
363 * @return boolean true if yes, else false
367 static function isInstanceGroupRoleAllowed($instanceId) {
372 $instanceValues = array();
373 $params = array('id' => $instanceId);
374 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
378 //transform grouprole to array
379 if (!empty($instanceValues['grouprole'])) {
380 $grouprole_array = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
381 $instanceValues['grouprole']
383 if (!CRM_Core_Permission
::checkGroupRole($grouprole_array) &&
384 !CRM_Core_Permission
::check('administer Reports')
397 static function processReport($params) {
398 $instanceId = CRM_Utils_Array
::value('instanceId', $params);
400 // hack for now, CRM-8358
401 $_REQUEST['instanceId'] = $instanceId;
402 $_REQUEST['sendmail'] = CRM_Utils_Array
::value('sendmail', $params, 1);
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);
408 $optionVal = self
::getValueFromUrl($instanceId);
409 $messages = array("Report Mail Triggered...");
411 $templateInfo = CRM_Core_OptionGroup
::getRowValues('report_template', $optionVal, 'value');
412 $obj = new CRM_Report_Page_Instance();
414 if (strstr(CRM_Utils_Array
::value('name', $templateInfo), '_Form')) {
415 $instanceInfo = array();
416 CRM_Report_BAO_ReportInstance
::retrieve(array('id' => $instanceId), $instanceInfo);
418 if (!empty($instanceInfo['title'])) {
419 $obj->assign('reportTitle', $instanceInfo['title']);
422 $obj->assign('reportTitle', $templateInfo['label']);
425 $wrapper = new CRM_Utils_Wrapper();
427 'urlToSession' => array(
429 'urlVar' => 'instanceId',
430 'type' => 'Positive',
431 'sessionVar' => 'instanceId',
437 $messages[] = $wrapper->run($templateInfo['name'], NULL, $arguments);
442 $messages[] = 'Required parameter missing: instanceId';
445 $messages[] = 'Did not find valid instance to execute';
450 'is_error' => $is_error,
451 'messages' => implode("\n", $messages),
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.
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
464 * @return string URL query string
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();
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;
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;
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'
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;
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);
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"];
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;
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]);
527 $query_string = http_build_query($url_params);
533 return $query_string;
541 static function getInstanceList($reportUrl) {
542 static $instanceDetails = array();
544 if (!array_key_exists($reportUrl, $instanceDetails )) {
545 $instanceDetails[$reportUrl] = array();
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})";
556 return $instanceDetails[$reportUrl];