Merge pull request #9632 from yashodha/CRM-19795
[civicrm-core.git] / CRM / Report / Form / ActivitySummary.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33class CRM_Report_Form_ActivitySummary extends CRM_Report_Form {
34
35 protected $_emailField = FALSE;
430ae6dd 36 protected $_phoneField = FALSE;
3832d330
KJ
37 protected $_tempTableName;
38 protected $_tempDurationSumTableName;
430ae6dd 39
74cf4551 40 /**
1728e9a0 41 * This report has not been optimised for group filtering.
42 *
43 * The functionality for group filtering has been improved but not
44 * all reports have been adjusted to take care of it. This report has not
45 * and will run an inefficient query until fixed.
46 *
47 * CRM-19170
48 *
49 * @var bool
74cf4551 50 */
1728e9a0 51 protected $groupFilterNotOptimised = TRUE;
52
74cf4551 53 /**
73b448bf 54 * Class constructor.
74cf4551 55 */
00be9182 56 public function __construct() {
6a488035 57 $this->_columns = array(
a8c87952 58 'civicrm_contact' => array(
6a488035 59 'dao' => 'CRM_Contact_DAO_Contact',
a8c87952
EM
60 'fields' => array(
61 'id' => array(
6a488035
TO
62 'required' => TRUE,
63 'no_display' => TRUE,
64 ),
a8c87952
EM
65 'sort_name' => array(
66 'title' => ts('Contact Name'),
6a488035
TO
67 'no_repeat' => TRUE,
68 ),
69 ),
a8c87952
EM
70 'filters' => array(
71 'sort_name' => array(
72 'title' => ts('Contact Name'),
6a488035
TO
73 ),
74 ),
a8c87952
EM
75 'group_bys' => array(
76 'sort_name' => array(
6a488035
TO
77 'name' => 'id',
78 'title' => ts('Contact'),
6a488035
TO
79 ),
80 ),
a8c87952
EM
81 'order_bys' => array(
82 'sort_name' => array(
21dfd5f5 83 'title' => ts('Contact Name'),
a8c87952 84 ),
6a488035
TO
85 ),
86 'grouping' => 'contact-fields',
87 ),
a8c87952 88 'civicrm_email' => array(
6a488035 89 'dao' => 'CRM_Core_DAO_Email',
a8c87952
EM
90 'fields' => array(
91 'email' => array(
ccc29f8e 92 'title' => ts('Email'),
6a488035
TO
93 ),
94 ),
a8c87952
EM
95 'order_bys' => array(
96 'email' => array(
21dfd5f5 97 'title' => ts('Email'),
a8c87952 98 ),
6a488035
TO
99 ),
100 'grouping' => 'contact-fields',
101 ),
a8c87952 102 'civicrm_phone' => array(
6a488035 103 'dao' => 'CRM_Core_DAO_Email',
a8c87952
EM
104 'fields' => array(
105 'phone' => array(
ccc29f8e 106 'title' => ts('Phone'),
a8c87952 107 ),
6a488035
TO
108 ),
109 'grouping' => 'contact-fields',
110 ),
a8c87952 111 'civicrm_activity' => array(
6a488035 112 'dao' => 'CRM_Activity_DAO_Activity',
a8c87952
EM
113 'fields' => array(
114 'activity_type_id' => array(
115 'title' => ts('Activity Type'),
96a1ef05
SB
116 'required' => TRUE,
117 'type' => CRM_Utils_Type::T_STRING,
118 ),
119 'status_id' => array(
fdee8d8d 120 'title' => ts('Activity Status'),
6a488035
TO
121 'default' => TRUE,
122 'type' => CRM_Utils_Type::T_STRING,
123 ),
a8c87952 124 'duration' => array(
96495cc0 125 'title' => ts('Duration'),
d17ad0af 126 'default' => TRUE,
6a488035 127 ),
a8c87952 128 'id' => array(
96495cc0 129 'title' => ts('Total Activities'),
6a488035 130 'required' => TRUE,
a8c87952 131 'statistics' => array(
96a1ef05 132 'count' => ts('Count'),
6a488035
TO
133 ),
134 ),
135 ),
a8c87952
EM
136 'filters' => array(
137 'activity_date_time' => array(
21dfd5f5 138 'operatorType' => CRM_Report_Form::OP_DATE,
a8c87952
EM
139 ),
140 'activity_type_id' => array(
141 'title' => ts('Activity Type'),
96495cc0 142 'default' => 0,
6a488035
TO
143 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
144 'options' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE),
145 ),
a8c87952
EM
146 'status_id' => array(
147 'title' => ts('Activity Status'),
8ee006e7 148 'type' => CRM_Utils_Type::T_STRING,
6a488035
TO
149 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
150 'options' => CRM_Core_PseudoConstant::activityStatus(),
151 ),
a8c87952
EM
152 'priority_id' => array(
153 'title' => ts('Priority'),
8ee006e7 154 'type' => CRM_Utils_Type::T_INT,
6a488035 155 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
cbf48754 156 'options' => CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id'),
6a488035
TO
157 ),
158 ),
a8c87952 159 'group_bys' => array(
9d72cede 160 'activity_date_time' => array(
353ffa53
TO
161 'title' => ts('Activity Date'),
162 'frequency' => TRUE,
163 ),
a8c87952
EM
164 'activity_type_id' => array(
165 'title' => ts('Activity Type'),
6a488035
TO
166 'default' => TRUE,
167 ),
96a1ef05 168 'status_id' => array(
fdee8d8d 169 'title' => ts('Activity Status'),
96a1ef05
SB
170 'default' => TRUE,
171 ),
6a488035 172 ),
a8c87952
EM
173 'order_bys' => array(
174 'activity_date_time' => array(
21dfd5f5 175 'title' => ts('Activity Date'),
a8c87952
EM
176 ),
177 'activity_type_id' => array(
21dfd5f5 178 'title' => ts('Activity Type'),
a8c87952 179 ),
6a488035
TO
180 ),
181 'grouping' => 'activity-fields',
182 'alias' => 'activity',
183 ),
184 );
96a1ef05 185 $this->_groupFilter = TRUE;
6a488035
TO
186
187 parent::__construct();
188 }
189
00be9182 190 public function select() {
6a488035
TO
191 $select = array();
192 $this->_columnHeaders = array();
193 foreach ($this->_columns as $tableName => $table) {
194 if (array_key_exists('group_bys', $table)) {
195 foreach ($table['group_bys'] as $fieldName => $field) {
a7488080 196 if (!empty($this->_params['group_bys'][$fieldName])) {
96a1ef05
SB
197 //include column in report when selected in group by but not in column section.
198 if (empty($this->_params['fields'][$fieldName])) {
199 $this->_params['fields'][$fieldName] = TRUE;
200 }
6221462f 201 if (isset($this->_params['group_bys_freq']) && !empty($this->_params['group_bys_freq'][$fieldName])) {
a8c87952
EM
202 switch ($this->_params['group_bys_freq'][$fieldName]) {
203 case 'YEARWEEK':
204 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
205
206 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
207 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
208 $field['title'] = 'Week';
209 break;
210
211 case 'YEAR':
212 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
213 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
214 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
215 $field['title'] = 'Year';
216 break;
217
218 case 'MONTH':
219 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
220 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
221 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
222 $field['title'] = 'Month';
223 break;
224
225 case 'QUARTER':
226 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
227 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
228 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
229 $field['title'] = 'Quarter';
230 break;
231 }
6a488035
TO
232 $this->_interval = $field['title'];
233 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
234 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
235 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
236
b44e3f84 237 // just to make sure these values are transferred to rows.
6a488035
TO
238 // since we need that for calculation purpose,
239 // e.g making subtotals look nicer or graphs
240 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
241 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
242 }
243 }
244 }
245 }
246 if (array_key_exists('fields', $table)) {
247 foreach ($table['fields'] as $fieldName => $field) {
8cc574cf 248 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
6a488035
TO
249 if ($tableName == 'civicrm_email') {
250 $this->_emailField = TRUE;
251 }
252 if ($tableName == 'civicrm_phone') {
253 $this->_phoneField = TRUE;
254 }
a7488080 255 if (!empty($field['statistics'])) {
6a488035
TO
256 foreach ($field['statistics'] as $stat => $label) {
257 switch (strtolower($stat)) {
258 case 'count':
259 $select[] = "COUNT(DISTINCT({$field['dbAlias']})) as {$tableName}_{$fieldName}_{$stat}";
260 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
261 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
262 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
263 break;
6a488035
TO
264 }
265 }
266 }
267 elseif ($fieldName == 'activity_type_id') {
a7488080 268 if (empty($this->_params['group_bys']['activity_type_id'])) {
6a488035
TO
269 $select[] = "GROUP_CONCAT(DISTINCT {$field['dbAlias']} ORDER BY {$field['dbAlias']} ) as {$tableName}_{$fieldName}";
270 }
271 else {
272 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
273 }
274 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
275 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
276 $this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = CRM_Utils_Array::value('no_display', $field);
277 }
278 else {
279 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
280 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
281 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
282 $this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = CRM_Utils_Array::value('no_display', $field);
283 }
284 }
285 }
286 }
287 }
d1641c51 288 $this->_selectClauses = $select;
6a488035
TO
289
290 $this->_select = "SELECT " . implode(', ', $select) . " ";
291 }
292
70599df6 293 /**
294 * Generate from clause.
295 *
296 * @param bool|FALSE $durationMode
297 */
96495cc0 298 public function from($durationMode = FALSE) {
ecaec004
RN
299 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
300 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
301 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
302 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
6a488035 303
96495cc0
KJ
304 if (!$durationMode) {
305 $this->_from = "
306 FROM civicrm_activity {$this->_aliases['civicrm_activity']}
307
308 LEFT JOIN civicrm_activity_contact target_activity
309 ON {$this->_aliases['civicrm_activity']}.id = target_activity.activity_id AND
310 target_activity.record_type_id = {$targetID}
311 LEFT JOIN civicrm_activity_contact assignment_activity
312 ON {$this->_aliases['civicrm_activity']}.id = assignment_activity.activity_id AND
313 assignment_activity.record_type_id = {$assigneeID}
314 LEFT JOIN civicrm_activity_contact source_activity
315 ON {$this->_aliases['civicrm_activity']}.id = source_activity.activity_id AND
316 source_activity.record_type_id = {$sourceID}
317 LEFT JOIN civicrm_contact contact_civireport
318 ON target_activity.contact_id = contact_civireport.id
319 LEFT JOIN civicrm_contact civicrm_contact_assignee
320 ON assignment_activity.contact_id = civicrm_contact_assignee.id
321 LEFT JOIN civicrm_contact civicrm_contact_source
322 ON source_activity.contact_id = civicrm_contact_source.id
323 {$this->_aclFrom}
324 LEFT JOIN civicrm_option_value
325 ON ( {$this->_aliases['civicrm_activity']}.activity_type_id = civicrm_option_value.value )
326 LEFT JOIN civicrm_option_group
327 ON civicrm_option_group.id = civicrm_option_value.option_group_id
328 LEFT JOIN civicrm_case_activity
329 ON civicrm_case_activity.activity_id = {$this->_aliases['civicrm_activity']}.id
330 LEFT JOIN civicrm_case
331 ON civicrm_case_activity.case_id = civicrm_case.id
332 LEFT JOIN civicrm_case_contact
333 ON civicrm_case_contact.case_id = civicrm_case.id ";
334
335 if ($this->_emailField) {
336 $this->_from .= "
337 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
338 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
339 {$this->_aliases['civicrm_email']}.is_primary = 1 ";
340 }
d5c61232 341
96495cc0
KJ
342 if ($this->_phoneField) {
343 $this->_from .= "
344 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
345 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
346 {$this->_aliases['civicrm_phone']}.is_primary = 1 ";
347 }
348 }
349 else {
350 $this->_from = "
9099266e
WM
351 FROM civicrm_activity {$this->_aliases['civicrm_activity']}
352 LEFT JOIN civicrm_activity_contact target_activity
353 ON {$this->_aliases['civicrm_activity']}.id = target_activity.activity_id AND
354 target_activity.record_type_id = {$targetID}
355 LEFT JOIN civicrm_contact contact_civireport
356 ON target_activity.contact_id = contact_civireport.id
357 {$this->_aclFrom}";
6a488035
TO
358 }
359 }
360
70599df6 361 /**
362 * Generate where clause.
363 *
364 * @param bool|FALSE $durationMode
365 */
96495cc0
KJ
366 public function where($durationMode = FALSE) {
367 $optionGroupClause = '';
368 if (!$durationMode) {
369 $optionGroupClause = 'civicrm_option_group.name = "activity_type" AND ';
370 }
371 $this->_where = " WHERE {$optionGroupClause}
372 {$this->_aliases['civicrm_activity']}.is_test = 0 AND
373 {$this->_aliases['civicrm_activity']}.is_deleted = 0 AND
374 {$this->_aliases['civicrm_activity']}.is_current_revision = 1";
6a488035
TO
375
376 $clauses = array();
377 foreach ($this->_columns as $tableName => $table) {
378 if (array_key_exists('filters', $table)) {
379
380 foreach ($table['filters'] as $fieldName => $field) {
381 $clause = NULL;
382 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
383 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
a8c87952
EM
384 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
385 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
6a488035
TO
386
387 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
388 }
389 else {
390 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
391 if ($op) {
392 $clause = $this->whereClause($field,
393 $op,
394 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
395 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
396 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
397 );
398 }
399 }
400
401 if (!empty($clause)) {
402 $clauses[] = $clause;
403 }
404 }
405 }
406 }
407
408 if (empty($clauses)) {
409 $this->_where .= " ";
410 }
411 else {
412 $this->_where .= " AND " . implode(' AND ', $clauses);
413 }
414
96495cc0 415 if ($this->_aclWhere && !$durationMode) {
3f1f2db0 416 $this->_where .= " AND ({$this->_aclWhere} OR civicrm_contact_source.is_deleted=0 OR civicrm_contact_assignee.is_deleted=0)";
6a488035
TO
417 }
418 }
419
d1641c51 420 public function groupBy($includeSelectCol = TRUE) {
6a488035 421 $this->_groupBy = array();
229d3c71 422 if (!empty($this->_params['group_bys']) &&
96495cc0 423 is_array($this->_params['group_bys'])) {
6a488035
TO
424 foreach ($this->_columns as $tableName => $table) {
425 if (array_key_exists('group_bys', $table)) {
426 foreach ($table['group_bys'] as $fieldName => $field) {
a7488080
CW
427 if (!empty($this->_params['group_bys'][$fieldName])) {
428 if (!empty($field['chart'])) {
6a488035
TO
429 $this->assign('chartSupported', TRUE);
430 }
a8c87952
EM
431 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
432 !empty($this->_params['group_bys_freq'][$fieldName])
433 ) {
6a488035
TO
434
435 $append = "YEAR({$field['dbAlias']}),";
436 if (in_array(strtolower($this->_params['group_bys_freq'][$fieldName]),
a8c87952
EM
437 array('year')
438 )) {
6a488035
TO
439 $append = '';
440 }
441 $this->_groupBy[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
442 $append = TRUE;
443 }
444 else {
445 $this->_groupBy[] = $field['dbAlias'];
446 }
447 }
448 }
449 }
450 }
d1641c51 451 $groupBy = $this->_groupBy;
6a488035
TO
452 $this->_groupBy = "GROUP BY " . implode(', ', $this->_groupBy);
453 }
454 else {
d1641c51 455 $groupBy = "{$this->_aliases['civicrm_activity']}.id";
96495cc0 456 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_activity']}.id ";
6a488035 457 }
d1641c51 458 if ($includeSelectCol) {
b708c08d 459 $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, $groupBy);
d1641c51 460 }
6a488035
TO
461 }
462
74cf4551
EM
463 /**
464 * @param $fields
465 * @param $files
466 * @param $self
467 *
468 * @return array
469 */
52628c99 470 public static function formRule($fields, $files, $self) {
6a488035
TO
471 $errors = array();
472 $contactFields = array('sort_name', 'email', 'phone');
a7488080 473 if (!empty($fields['group_bys'])) {
a7488080
CW
474 if (!empty($fields['group_bys']['activity_date_time'])) {
475 if (!empty($fields['group_bys']['sort_name'])) {
6a488035
TO
476 $errors['fields'] = ts("Please do not select GroupBy 'Activity Date' with GroupBy 'Contact'");
477 }
478 else {
479 foreach ($fields['fields'] as $fieldName => $val) {
480 if (in_array($fieldName, $contactFields)) {
481 $errors['fields'] = ts("Please do not select any Contact Fields with GroupBy 'Activity Date'");
482 break;
483 }
484 }
485 }
486 }
487 }
d5c61232
KJ
488
489 // don't allow add to group action unless contact fields are selected.
490 if (isset($fields['_qf_ActivitySummary_submit_group'])) {
491 $contactFieldSelected = FALSE;
492 foreach ($fields['fields'] as $fieldName => $val) {
493 if (in_array($fieldName, $contactFields)) {
494 $contactFieldSelected = TRUE;
495 break;
496 }
497 }
498
499 if (!$contactFieldSelected) {
500 $errors['fields'] = ts('You cannot use "Add Contacts to Group" action unless contacts fields are selected.');
501 }
502 }
6a488035
TO
503 return $errors;
504 }
505
00be9182 506 public function postProcess() {
6a488035
TO
507 // get the acl clauses built before we assemble the query
508 $this->buildACLClause($this->_aliases['civicrm_contact']);
96495cc0
KJ
509
510 // get ready with post process params
511 $this->beginPostProcess();
512
513 // build query
514 $sql = $this->buildQuery();
515
516 // main sql statement
517 $this->select();
518 $this->from();
519 $this->customDataFrom();
520 $this->where();
521 $this->groupBy();
522 $this->orderBy();
523
524 // order_by columns not selected for display need to be included in SELECT
525 $unselectedSectionColumns = $this->unselectedSectionColumns();
526 foreach ($unselectedSectionColumns as $alias => $section) {
527 $this->_select .= ", {$section['dbAlias']} as {$alias}";
528 }
529
530 if (!empty($applyLimit) && empty($this->_params['charts'])) {
531 $this->limit();
532 }
533 CRM_Utils_Hook::alterReportVar('sql', $this, $this);
534
535 // store the duration count in temp table
536 $this->_tempTableName = CRM_Core_DAO::createTempTableName('civicrm_activity');
537
538 // build temporary table column names base on column headers of result
539 $dbColumns = array();
540 foreach ($this->_columnHeaders as $fieldName => $dontCare) {
541 $dbColumns[] = $fieldName . ' VARCHAR(128)';
542 }
543
544 // create temp table to store main result
545 $tempQuery = "CREATE TEMPORARY TABLE {$this->_tempTableName} (
9099266e
WM
546 id int unsigned NOT NULL AUTO_INCREMENT, " . implode(', ', $dbColumns) . ' , PRIMARY KEY (id))'
547 . $this->_databaseAttributes;
96495cc0
KJ
548 CRM_Core_DAO::executeQuery($tempQuery);
549
550 // build main report query
551 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
552
553 // store the result in temporary table
554 $insertCols = '';
555 $insertQuery = "INSERT INTO {$this->_tempTableName} ( " . implode(',', array_keys($this->_columnHeaders)) . " )
556{$sql}";
557 CRM_Core_DAO::executeQuery($insertQuery);
558
559 // now build the query for duration sum
560 $this->from(TRUE);
96495cc0 561 $this->where(TRUE);
d1641c51 562 $this->groupBy(FALSE);
96495cc0
KJ
563
564 // build the query to calulate duration sum
565 $sql = "SELECT SUM(activity_civireport.duration) as civicrm_activity_duration_total {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
566
567 // create temp table to store duration
568 $this->_tempDurationSumTableName = CRM_Core_DAO::createTempTableName('civicrm_activity');
569 $tempQuery = "CREATE TEMPORARY TABLE {$this->_tempDurationSumTableName} (
9099266e
WM
570 id int unsigned NOT NULL AUTO_INCREMENT, civicrm_activity_duration_total VARCHAR(128), PRIMARY KEY (id))"
571 . $this->_databaseAttributes;
96495cc0
KJ
572 CRM_Core_DAO::executeQuery($tempQuery);
573
574 // store the result in temporary table
575 $insertQuery = "INSERT INTO {$this->_tempDurationSumTableName} (civicrm_activity_duration_total)
576 {$sql}";
577 CRM_Core_DAO::executeQuery($insertQuery);
578
579 // build array of result based on column headers. This method also allows
580 // modifying column headers before using it to build result set i.e $rows.
581 $rows = array();
582 $query = "SELECT {$this->_tempTableName}.*, {$this->_tempDurationSumTableName}.civicrm_activity_duration_total
583 FROM {$this->_tempTableName} INNER JOIN {$this->_tempDurationSumTableName}
584 ON ({$this->_tempTableName}.id = {$this->_tempDurationSumTableName}.id)";
585
586 // finally add duration total to column headers
587 $this->_columnHeaders['civicrm_activity_duration_total'] = array('no_display' => 1);
588
589 $this->buildRows($query, $rows);
590
591 // format result set.
592 $this->formatDisplay($rows);
593
594 // assign variables to templates
595 $this->doTemplateAssignment($rows);
596
baa8595a
KJ
597 //reset the sql building to default, which is used / called during other actions like "add to group"
598 // now build the query for duration sum
599 $this->from();
600 $this->where();
601
96495cc0
KJ
602 // do print / pdf / instance stuff if needed
603 $this->endPostProcess($rows);
6a488035
TO
604 }
605
96a1ef05
SB
606 /**
607 * @param $rows
608 *
609 * @return array
610 */
611 public function statistics(&$rows) {
612 $statistics = parent::statistics($rows);
613 $totalType = $totalActivity = $totalDuration = 0;
614
96495cc0
KJ
615 $query = "SELECT {$this->_tempTableName}.civicrm_activity_activity_type_id,
616 {$this->_tempTableName}.civicrm_activity_id_count,
617 {$this->_tempDurationSumTableName}.civicrm_activity_duration_total
618 FROM {$this->_tempTableName} INNER JOIN {$this->_tempDurationSumTableName}
619 ON ({$this->_tempTableName}.id = {$this->_tempDurationSumTableName}.id)";
96a1ef05 620
96495cc0 621 $actDAO = CRM_Core_DAO::executeQuery($query);
028df0a9 622
96495cc0 623 $activityTypesCount = array();
d5c61232 624 while ($actDAO->fetch()) {
96495cc0
KJ
625 if (!in_array($actDAO->civicrm_activity_activity_type_id, $activityTypesCount)) {
626 $activityTypesCount[] = $actDAO->civicrm_activity_activity_type_id;
627 }
628
629 $totalActivity += $actDAO->civicrm_activity_id_count;
630 $totalDuration += $actDAO->civicrm_activity_duration_total;
96a1ef05
SB
631 }
632
96495cc0
KJ
633 $totalType = count($activityTypesCount);
634
96a1ef05
SB
635 $statistics['counts']['type'] = array(
636 'title' => ts('Total Types'),
637 'value' => $totalType,
638 );
639 $statistics['counts']['activities'] = array(
640 'title' => ts('Total Number of Activities'),
641 'value' => $totalActivity,
642 );
643 $statistics['counts']['duration'] = array(
644 'title' => ts('Total Duration (in Minutes)'),
645 'value' => $totalDuration,
646 );
647 return $statistics;
648 }
649
fdee8d8d
SB
650 public function modifyColumnHeaders() {
651 //CRM-16719 modify name of column
652 if (!empty($this->_columnHeaders['civicrm_activity_status_id'])) {
ccc29f8e 653 $this->_columnHeaders['civicrm_activity_status_id']['title'] = ts('Status');
fdee8d8d
SB
654 }
655 }
656
74cf4551 657 /**
4b62bc4f
EM
658 * Alter display of rows.
659 *
660 * Iterate through the rows retrieved via SQL and make changes for display purposes,
661 * such as rendering contacts as links.
662 *
663 * @param array $rows
664 * Rows generated by SQL, with an array for each row.
74cf4551 665 */
00be9182 666 public function alterDisplay(&$rows) {
a8c87952 667 $entryFound = FALSE;
6a488035 668 $activityType = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
96a1ef05 669 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
6a488035
TO
670 $onHover = ts('View Contact Summary for this Contact');
671 foreach ($rows as $rowNum => $row) {
96a1ef05
SB
672 // make count columns point to activity detail report
673 if (!empty($row['civicrm_activity_id_count'])) {
3ff6c3c0 674 $url = array();
fdee8d8d
SB
675 $urlParams = array('activity_type_id', 'gid', 'status_id', 'contact_id');
676 foreach ($urlParams as $field) {
3ff6c3c0 677 if (!empty($row['civicrm_activity_' . $field])) {
96a1ef05
SB
678 $url[] = "{$field}_op=in&{$field}_value={$row['civicrm_activity_'.$field]}";
679 }
3ff6c3c0
SB
680 elseif (!empty($this->_params[$field . '_value'])) {
681 $val = implode(",", $this->_params[$field . '_value']);
fdee8d8d
SB
682 $url[] = "{$field}_op=in&{$field}_value={$val}";
683 }
684 }
685 $date_suffixes = array('relative', 'from', 'to');
686 while (list(, $suffix) = each($date_suffixes)) {
687 if (!empty($this->_params['activity_date_time_' . $suffix])) {
96a1ef05
SB
688 list($from, $to)
689 = $this->getFromTo(
690 CRM_Utils_Array::value("activity_date_time_relative", $this->_params),
691 CRM_Utils_Array::value("activity_date_time_from", $this->_params),
692 CRM_Utils_Array::value("activity_date_time_to", $this->_params)
3ff6c3c0 693 );
96a1ef05 694 $url[] = "activity_date_time_from={$from}&activity_date_time_to={$to}";
fdee8d8d 695 break;
96a1ef05
SB
696 }
697 }
8f621a01 698 // reset date filter on activity reports.
699 $url[] = "resetDateFilter=1";
3ff6c3c0
SB
700 $url = implode('&', $url);
701 $url = CRM_Report_Utils_Report::getNextUrl('activity', "reset=1&force=1&{$url}",
96a1ef05
SB
702 $this->_absoluteUrl,
703 $this->_id,
704 $this->_drilldownReport);
705 $rows[$rowNum]['civicrm_activity_id_count_link'] = $url;
706 $rows[$rowNum]['civicrm_activity_id_count_hover'] = ts('List all activity(s) for this row.');
707 $entryFound = TRUE;
708 }
6a488035
TO
709
710 if (array_key_exists('civicrm_contact_sort_name', $row) && $this->_outputMode != 'csv') {
711 if ($value = $row['civicrm_contact_id']) {
712
0555ce4f
WM
713 // unset the name, email and phone fields if the contact is the same as the previous contact
714 if (isset($previousContact) && $previousContact == $value) {
6a488035
TO
715 $rows[$rowNum]['civicrm_contact_sort_name'] = "";
716
717 if (array_key_exists('civicrm_email_email', $row)) {
718 $rows[$rowNum]['civicrm_email_email'] = "";
719 }
720 if (array_key_exists('civicrm_phone_phone', $row)) {
721 $rows[$rowNum]['civicrm_phone_phone'] = "";
722 }
723 }
724 else {
725 $url = CRM_Utils_System::url('civicrm/contact/view',
726 'reset=1&cid=' . $value,
727 $this->_absoluteUrl
728 );
729
a8c87952
EM
730 $rows[$rowNum]['civicrm_contact_sort_name'] = "<a href='$url'>" . $row['civicrm_contact_sort_name'] .
731 '</a>';
6a488035 732 }
0555ce4f
WM
733
734 // store the contact ID of this contact
735 $previousContact = $value;
6a488035
TO
736 $entryFound = TRUE;
737 }
738 }
739
740 if (array_key_exists('civicrm_activity_activity_type_id', $row)) {
741 if ($value = $row['civicrm_activity_activity_type_id']) {
742
743 $value = explode(',', $value);
744 foreach ($value as $key => $id) {
745 $value[$key] = $activityType[$id];
746 }
747
748 $rows[$rowNum]['civicrm_activity_activity_type_id'] = implode(' , ', $value);
749 $entryFound = TRUE;
750 }
751 }
752
96a1ef05
SB
753 if (array_key_exists('civicrm_activity_status_id', $row)) {
754 if ($value = $row['civicrm_activity_status_id']) {
755 $rows[$rowNum]['civicrm_activity_status_id'] = $activityStatus[$value];
756 $entryFound = TRUE;
757 }
758 }
759
e6143637
KJ
760 if (array_key_exists('civicrm_activity_duration', $row)) {
761 if ($value = $row['civicrm_activity_duration']) {
96495cc0 762 $rows[$rowNum]['civicrm_activity_duration'] = $rows[$rowNum]['civicrm_activity_duration_total'];
e6143637
KJ
763 $entryFound = TRUE;
764 }
765 }
766
6a488035
TO
767 if (!$entryFound) {
768 break;
769 }
770 }
771 }
96025800 772
6a488035 773}