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