4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.4 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
36 class CRM_Report_Utils_Report
{
38 static function getValueFromUrl($instanceID = NULL) {
40 $optionVal = CRM_Core_DAO
::getFieldValue('CRM_Report_DAO_ReportInstance',
46 $config = CRM_Core_Config
::singleton();
47 $args = explode('/', $_GET[$config->userFrameworkURLVar
]);
49 // remove 'civicrm/report' from args
53 // put rest of arguement back in the form of url, which is how value
54 // is stored in option value table
55 $optionVal = implode('/', $args);
60 static function getValueIDFromUrl($instanceID = NULL) {
61 $optionVal = self
::getValueFromUrl($instanceID);
64 $templateInfo = CRM_Core_OptionGroup
::getRowValues('report_template', "{$optionVal}", 'value');
65 return array(CRM_Utils_Array
::value('id', $templateInfo), $optionVal);
71 static function getInstanceIDForValue($optionVal) {
72 static $valId = array();
74 if (!array_key_exists($optionVal, $valId)) {
76 SELECT MIN(id) FROM civicrm_report_instance
77 WHERE report_id = %1";
79 $params = array(1 => array($optionVal, 'String'));
80 $valId[$optionVal] = CRM_Core_DAO
::singleValueQuery($sql, $params);
82 return $valId[$optionVal];
85 static function getInstanceIDForPath($path = NULL) {
86 static $valId = array();
88 // if $path is null, try to get it from url
89 $path = self
::getInstancePath();
91 if ($path && !array_key_exists($path, $valId)) {
93 SELECT MIN(id) FROM civicrm_report_instance
94 WHERE TRIM(BOTH '/' FROM CONCAT(report_id, '/', name)) = %1";
96 $params = array(1 => array($path, 'String'));
97 $valId[$path] = CRM_Core_DAO
::singleValueQuery($sql, $params);
99 return CRM_Utils_Array
::value($path, $valId);
102 static function getNextUrl($urlValue, $query = 'reset=1', $absolute = FALSE, $instanceID = NULL, $drilldownReport = array()) {
104 $drilldownInstanceID = false;
105 if (array_key_exists($urlValue, $drilldownReport))
106 $drilldownInstanceID = CRM_Core_DAO
::getFieldValue('CRM_Report_DAO_ReportInstance', $instanceID, 'drilldown_id', 'id');
108 if (!$drilldownInstanceID)
109 $drilldownInstanceID = self
::getInstanceIDForValue($urlValue);
111 if ($drilldownInstanceID) {
112 return CRM_Utils_System
::url("civicrm/report/instance/{$drilldownInstanceID}",
113 "{$query}", $absolute
121 return CRM_Utils_System
::url("civicrm/report/" . trim($urlValue, '/'),
127 // get instance count for a template
128 static function getInstanceCount($optionVal) {
129 if (empty($optionVal)) return 0;
132 SELECT count(inst.id)
133 FROM civicrm_report_instance inst
134 WHERE inst.report_id = %1";
136 $params = array(1 => array($optionVal, 'String'));
137 $count = CRM_Core_DAO
::singleValueQuery($sql, $params);
141 static function mailReport($fileContent, $instanceID = NULL, $outputMode = 'html', $attachments = array(
147 list($domainEmailName,
149 ) = CRM_Core_BAO_Domain
::getNameAndEmail();
151 $params = array('id' => $instanceID);
152 $instanceInfo = array();
153 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
159 $params['groupName'] = 'Report Email Sender';
160 $params['from'] = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>';
162 $params['toName'] = "";
163 $params['toEmail'] = CRM_Utils_Array
::value('email_to', $instanceInfo);
164 $params['cc'] = CRM_Utils_Array
::value('email_cc', $instanceInfo);
165 $params['subject'] = CRM_Utils_Array
::value('email_subject', $instanceInfo);
166 if (!CRM_Utils_Array
::value('attachments', $instanceInfo)) {
167 $instanceInfo['attachments'] = array();
169 $params['attachments'] = array_merge(CRM_Utils_Array
::value('attachments', $instanceInfo), $attachments);
170 $params['text'] = '';
171 $params['html'] = $fileContent;
173 return CRM_Utils_Mail
::send($params);
176 static function export2csv(&$form, &$rows) {
177 //Mark as a CSV file.
178 header('Content-Type: text/csv');
180 //Force a download and name the file using the current timestamp.
181 $datetime = date('Ymd-Gi', $_SERVER['REQUEST_TIME']);
182 header('Content-Disposition: attachment; filename=Report_' . $datetime . '.csv');
183 echo self
::makeCsv($form, $rows);
184 CRM_Utils_System
::civiExit();
188 * Utility function for export2csv and CRM_Report_Form::endPostProcess
189 * - make CSV file content and return as string.
191 static function makeCsv(&$form, &$rows) {
192 $config = CRM_Core_Config
::singleton();
195 // Add headers if this is the first row.
196 $columnHeaders = array_keys($form->_columnHeaders
);
198 // Replace internal header names with friendly ones, where available.
199 foreach ($columnHeaders as $header) {
200 if (isset($form->_columnHeaders
[$header])) {
201 $headers[] = '"' . html_entity_decode(strip_tags($form->_columnHeaders
[$header]['title'])) . '"';
205 $csv .= implode($config->fieldSeparator
,
209 $displayRows = array();
211 foreach ($rows as $row) {
212 foreach ($columnHeaders as $k => $v) {
213 $value = CRM_Utils_Array
::value($v, $row);
215 // Remove HTML, unencode entities, and escape quotation marks.
216 $value = str_replace('"', '""', html_entity_decode(strip_tags($value)));
218 if (CRM_Utils_Array
::value('type', $form->_columnHeaders
[$v]) & 4) {
219 if (CRM_Utils_Array
::value('group_by', $form->_columnHeaders
[$v]) == 'MONTH' ||
220 CRM_Utils_Array
::value('group_by', $form->_columnHeaders
[$v]) == 'QUARTER'
222 $value = CRM_Utils_Date
::customFormat($value, $config->dateformatPartial
);
224 elseif (CRM_Utils_Array
::value('group_by', $form->_columnHeaders
[$v]) == 'YEAR') {
225 $value = CRM_Utils_Date
::customFormat($value, $config->dateformatYear
);
228 $value = CRM_Utils_Date
::customFormat($value, '%Y-%m-%d');
231 elseif (CRM_Utils_Array
::value('type', $form->_columnHeaders
[$v]) == 1024) {
232 $value = CRM_Utils_Money
::format($value);
234 $displayRows[$v] = '"' . $value . '"';
237 $displayRows[$v] = " ";
241 $csv .= implode($config->fieldSeparator
,
249 static function getInstanceID() {
251 $config = CRM_Core_Config
::singleton();
252 $arg = explode('/', $_GET[$config->userFrameworkURLVar
]);
254 if ($arg[1] == 'report' &&
255 CRM_Utils_Array
::value(2, $arg) == 'instance'
257 if (CRM_Utils_Rule
::positiveInteger($arg[3])) {
263 static function getInstancePath() {
264 $config = CRM_Core_Config
::singleton();
265 $arg = explode('/', $_GET[$config->userFrameworkURLVar
]);
267 if ($arg[1] == 'report' &&
268 CRM_Utils_Array
::value(2, $arg) == 'instance'
270 unset($arg[0], $arg[1], $arg[2]);
271 $path = trim(CRM_Utils_Type
::escape(implode('/', $arg), 'String'), '/');
276 static function isInstancePermissioned($instanceId) {
281 $instanceValues = array();
282 $params = array('id' => $instanceId);
283 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
288 if (!empty($instanceValues['permission']) &&
289 (!(CRM_Core_Permission
::check($instanceValues['permission']) ||
290 CRM_Core_Permission
::check('administer Reports')
300 * Check if the user can view a report instance based on their role(s)
302 * @instanceId string $str the report instance to check
304 * @return boolean true if yes, else false
308 static function isInstanceGroupRoleAllowed($instanceId) {
313 $instanceValues = array();
314 $params = array('id' => $instanceId);
315 CRM_Core_DAO
::commonRetrieve('CRM_Report_DAO_ReportInstance',
319 //transform grouprole to array
320 if (!empty($instanceValues['grouprole'])) {
321 $grouprole_array = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
322 $instanceValues['grouprole']
324 if (!CRM_Core_Permission
::checkGroupRole($grouprole_array) &&
325 !CRM_Core_Permission
::check('administer Reports')
333 static function processReport($params) {
334 $instanceId = CRM_Utils_Array
::value('instanceId', $params);
336 // hack for now, CRM-8358
337 $_REQUEST['instanceId'] = $instanceId;
338 $_REQUEST['sendmail'] = CRM_Utils_Array
::value('sendmail', $params, 1);
340 // if cron is run from terminal --output is reserved, and therefore we would provide another name 'format'
341 $_REQUEST['output'] = CRM_Utils_Array
::value('format', $params, CRM_Utils_Array
::value('output', $params, 'pdf'));
342 $_REQUEST['reset'] = CRM_Utils_Array
::value('reset', $params, 1);
344 $optionVal = self
::getValueFromUrl($instanceId);
345 $messages = array("Report Mail Triggered...");
347 $templateInfo = CRM_Core_OptionGroup
::getRowValues('report_template', $optionVal, 'value');
348 $obj = new CRM_Report_Page_Instance();
350 if (strstr(CRM_Utils_Array
::value('name', $templateInfo), '_Form')) {
351 $instanceInfo = array();
352 CRM_Report_BAO_ReportInstance
::retrieve(array('id' => $instanceId), $instanceInfo);
354 if (!empty($instanceInfo['title'])) {
355 $obj->assign('reportTitle', $instanceInfo['title']);
358 $obj->assign('reportTitle', $templateInfo['label']);
361 $wrapper = new CRM_Utils_Wrapper();
363 'urlToSession' => array(
365 'urlVar' => 'instanceId',
366 'type' => 'Positive',
367 'sessionVar' => 'instanceId',
373 $messages[] = $wrapper->run($templateInfo['name'], NULL, $arguments);
378 $messages[] = 'Required parameter missing: instanceId';
381 $messages[] = 'Did not find valid instance to execute';
386 'is_error' => $is_error,
387 'messages' => implode("\n", $messages),
393 * Build a URL query string containing all report filter criteria that are
394 * stipulated in $_GET or in a report Preview, but which haven't yet been
395 * saved in the report instance.
397 * @param array $defaults The report criteria that aren't coming in as submitted form values, as in CRM_Report_Form::_defaults
398 * @param array $params All effective report criteria, as in CRM_Report_Form::_params
400 * @return string URL query string
402 static function getPreviewCriteriaQueryParams($defaults = array(
403 ), $params = array()) {
404 static $query_string;
405 if (!isset($query_string)) {
406 if (!empty($params)) {
407 $url_params = $op_values = $string_values = $process_params = array();
409 // We'll only use $params that are different from what's in $default.
410 foreach ($params as $field_name => $field_value) {
411 if (!array_key_exists($field_name, $defaults) ||
$defaults[$field_name] != $field_value) {
412 $process_params[$field_name] = $field_value;
415 // Criteria stipulated in $_GET will be in $defaults even if they're not
416 // saved, so we can't easily tell if they're saved or not. So just include them.
417 $process_params +
= $_GET;
419 // All $process_params should be passed on if they have an effective value
420 // (in other words, there's no point in propagating blank filters).
421 foreach ($process_params as $field_name => $field_value) {
422 $suffix_position = strrpos($field_name, '_');
423 $suffix = substr($field_name, $suffix_position);
424 $basename = substr($field_name, 0, $suffix_position);
425 if ($suffix == '_min' ||
$suffix == '_max' ||
426 $suffix == '_from' ||
$suffix == '_to' ||
427 $suffix == '_relative'
429 // For these types, we only keep them if they have a value.
430 if (!empty($field_value)) {
431 $url_params[$field_name] = $field_value;
434 elseif ($suffix == '_value') {
435 // These filters can have an effect even without a value
436 // (e.g., values for 'nll' and 'nnll' ops are blank),
437 // so store them temporarily and examine below.
438 $string_values[$basename] = $field_value;
439 $op_values[$basename] = CRM_Utils_Array
::value("{$basename}_op", $params);
441 elseif ($suffix == '_op') {
442 // These filters can have an effect even without a value
443 // (e.g., values for 'nll' and 'nnll' ops are blank),
444 // so store them temporarily and examine below.
445 $op_values[$basename] = $field_value;
446 $string_values[$basename] = $params["{$basename}_value"];
450 // Check the *_value and *_op criteria and include them if
451 // they'll have an effective value.
452 foreach ($op_values as $basename => $field_value) {
453 if ($field_value == 'nll' ||
$field_value == 'nnll') {
454 // 'nll' and 'nnll' filters should be included even with empty values.
455 $url_params["{$basename}_op"] = $field_value;
457 elseif ($string_values[$basename]) {
458 // Other filters are only included if they have a value.
459 $url_params["{$basename}_op"] = $field_value;
460 $url_params["{$basename}_value"] = (is_array($string_values[$basename]) ?
implode(',', $string_values[$basename]) : $string_values[$basename]);
463 $query_string = http_build_query($url_params);
469 return $query_string;
472 static function getInstanceList($reportUrl) {
473 static $instanceDetails = array();
475 if (!array_key_exists($reportUrl, $instanceDetails )) {
476 $instanceDetails[$reportUrl] = array();
479 SELECT id, title FROM civicrm_report_instance
480 WHERE report_id = %1";
481 $params = array(1 => array($reportUrl, 'String'));
482 $result = CRM_Core_DAO
::executeQuery($sql, $params);
483 while( $result->fetch()) {
484 $instanceDetails[$reportUrl][$result->id
] = $result->title
. " (ID: {$result->id})";
487 return $instanceDetails[$reportUrl];