Merge pull request #18891 from civicrm/5.31
[civicrm-core.git] / CRM / Report / Form / Activity.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17class CRM_Report_Form_Activity extends CRM_Report_Form {
be2fb01f 18 protected $_selectAliasesTotal = [];
6a488035 19
f0100b85 20 protected $_customGroupExtends = ['Activity'];
430ae6dd 21
be2fb01f 22 protected $_nonDisplayFields = [];
09febbae 23
1728e9a0 24 /**
25 * This report has not been optimised for group filtering.
26 *
27 * The functionality for group filtering has been improved but not
28 * all reports have been adjusted to take care of it. This report has not
29 * and will run an inefficient query until fixed.
30 *
1728e9a0 31 * @var bool
0e480632 32 * @see https://issues.civicrm.org/jira/browse/CRM-19170
1728e9a0 33 */
34 protected $groupFilterNotOptimised = TRUE;
35
74cf4551 36 /**
ab432335 37 * Class constructor.
f0100b85 38 *
39 * @throws \CRM_Core_Exception
74cf4551 40 */
00be9182 41 public function __construct() {
7116d719 42 // There could be multiple contacts. We not clear on which contact id to display.
83e74860
DS
43 // Lets hide it for now.
44 $this->_exposeContactID = FALSE;
8f621a01 45 // if navigated from count link of activity summary reports.
a3d827a7 46 $this->_resetDateFilter = CRM_Utils_Request::retrieve('resetDateFilter', 'Boolean');
83e74860 47
1023b3bc 48 $components = CRM_Core_Component::getEnabledComponents();
f0100b85 49 $campaignEnabled = !empty($components['CiviCampaign']);
50 $caseEnabled = !empty($components['CiviCase']);
51
1023b3bc 52 foreach ($components as $componentName => $componentInfo) {
d3e6c71f 53 // CRM-19201: Add support for reporting CiviCampaign activities
44d17ec8
BS
54 // For CiviCase, "access all cases and activities" is required here
55 // rather than "access my cases and activities" to prevent those with
56 // only the later permission from seeing a list of all cases which might
57 // present a privacy issue.
58 if (CRM_Core_Permission::access($componentName, TRUE, TRUE)) {
1023b3bc 59 $accessAllowed[] = $componentInfo->componentID;
60 }
61 }
62
63 $include = '';
64 if (!empty($accessAllowed)) {
65 $include = 'OR v.component_id IN (' . implode(', ', $accessAllowed) . ')';
66 }
67 $condition = " AND ( v.component_id IS NULL {$include} )";
68 $this->activityTypes = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $condition);
69 asort($this->activityTypes);
d47468d0 70
71 // @todo split the 3 different contact tables into their own array items.
72 // this will massively simplify the needs of this report.
be2fb01f
CW
73 $this->_columns = [
74 'civicrm_contact' => [
af9b09df 75 'dao' => 'CRM_Contact_DAO_Contact',
be2fb01f
CW
76 'fields' => [
77 'contact_source' => [
af9b09df 78 'name' => 'sort_name',
8c0ff2a6 79 'title' => ts('Source Name'),
af9b09df
TO
80 'alias' => 'civicrm_contact_source',
81 'no_repeat' => TRUE,
be2fb01f
CW
82 ],
83 'contact_assignee' => [
af9b09df 84 'name' => 'sort_name',
8c0ff2a6 85 'title' => ts('Assignee Name'),
af9b09df
TO
86 'alias' => 'civicrm_contact_assignee',
87 'dbAlias' => "civicrm_contact_assignee.sort_name",
88 'default' => TRUE,
be2fb01f
CW
89 ],
90 'contact_target' => [
af9b09df 91 'name' => 'sort_name',
8c0ff2a6 92 'title' => ts('Target Name'),
af9b09df
TO
93 'alias' => 'civicrm_contact_target',
94 'dbAlias' => "civicrm_contact_target.sort_name",
95 'default' => TRUE,
be2fb01f 96 ],
e49e8a17 97 'contact_target_birth' => [
98 'name' => 'birth_date',
99 'title' => ts('Target Birth Date'),
100 'alias' => 'civicrm_contact_target',
101 'dbAlias' => "civicrm_contact_target.birth_date",
102 ],
bb5737d0 103 'contact_target_gender' => [
104 'name' => 'gender_id',
105 'title' => ts('Target Gender'),
106 'alias' => 'civicrm_contact_target',
107 'dbAlias' => "civicrm_contact_target.gender_id",
108 'default' => TRUE,
109 ],
be2fb01f 110 'contact_source_id' => [
af9b09df
TO
111 'name' => 'id',
112 'alias' => 'civicrm_contact_source',
113 'dbAlias' => "civicrm_contact_source.id",
114 'no_display' => TRUE,
115 'default' => TRUE,
116 'required' => TRUE,
be2fb01f
CW
117 ],
118 'contact_assignee_id' => [
af9b09df
TO
119 'name' => 'id',
120 'alias' => 'civicrm_contact_assignee',
121 'dbAlias' => "civicrm_contact_assignee.id",
122 'no_display' => TRUE,
123 'default' => TRUE,
124 'required' => TRUE,
be2fb01f
CW
125 ],
126 'contact_target_id' => [
af9b09df
TO
127 'name' => 'id',
128 'alias' => 'civicrm_contact_target',
129 'dbAlias' => "civicrm_contact_target.id",
130 'no_display' => TRUE,
131 'default' => TRUE,
132 'required' => TRUE,
be2fb01f
CW
133 ],
134 ],
135 'filters' => [
136 'contact_source' => [
af9b09df
TO
137 'name' => 'sort_name',
138 'alias' => 'civicrm_contact_source',
8c0ff2a6 139 'title' => ts('Source Name'),
af9b09df
TO
140 'operator' => 'like',
141 'type' => CRM_Report_Form::OP_STRING,
be2fb01f
CW
142 ],
143 'contact_assignee' => [
af9b09df
TO
144 'name' => 'sort_name',
145 'alias' => 'civicrm_contact_assignee',
8c0ff2a6 146 'title' => ts('Assignee Name'),
af9b09df
TO
147 'operator' => 'like',
148 'type' => CRM_Report_Form::OP_STRING,
be2fb01f
CW
149 ],
150 'contact_target' => [
af9b09df
TO
151 'name' => 'sort_name',
152 'alias' => 'civicrm_contact_target',
8c0ff2a6 153 'title' => ts('Target Name'),
af9b09df
TO
154 'operator' => 'like',
155 'type' => CRM_Report_Form::OP_STRING,
be2fb01f
CW
156 ],
157 'current_user' => [
af9b09df
TO
158 'name' => 'current_user',
159 'title' => ts('Limit To Current User'),
160 'type' => CRM_Utils_Type::T_INT,
161 'operatorType' => CRM_Report_Form::OP_SELECT,
be2fb01f
CW
162 'options' => ['0' => ts('No'), '1' => ts('Yes')],
163 ],
164 ],
af9b09df 165 'grouping' => 'contact-fields',
be2fb01f
CW
166 ],
167 'civicrm_email' => [
af9b09df 168 'dao' => 'CRM_Core_DAO_Email',
be2fb01f
CW
169 'fields' => [
170 'contact_source_email' => [
af9b09df 171 'name' => 'email',
8c0ff2a6 172 'title' => ts('Source Email'),
af9b09df 173 'alias' => 'civicrm_email_source',
be2fb01f
CW
174 ],
175 'contact_assignee_email' => [
af9b09df 176 'name' => 'email',
8c0ff2a6 177 'title' => ts('Assignee Email'),
af9b09df 178 'alias' => 'civicrm_email_assignee',
be2fb01f
CW
179 ],
180 'contact_target_email' => [
af9b09df 181 'name' => 'email',
8c0ff2a6 182 'title' => ts('Target Email'),
af9b09df 183 'alias' => 'civicrm_email_target',
be2fb01f
CW
184 ],
185 ],
186 'order_bys' => [
187 'source_contact_email' => [
af9b09df 188 'name' => 'email',
8c0ff2a6 189 'title' => ts('Source Email'),
af9b09df 190 'dbAlias' => 'civicrm_email_contact_source_email',
be2fb01f
CW
191 ],
192 ],
193 ],
194 'civicrm_phone' => [
8c0ff2a6 195 'dao' => 'CRM_Core_DAO_Phone',
be2fb01f
CW
196 'fields' => [
197 'contact_source_phone' => [
8c0ff2a6 198 'name' => 'phone',
199 'title' => ts('Source Phone'),
200 'alias' => 'civicrm_phone_source',
be2fb01f
CW
201 ],
202 'contact_assignee_phone' => [
8c0ff2a6 203 'name' => 'phone',
204 'title' => ts('Assignee Phone'),
205 'alias' => 'civicrm_phone_assignee',
be2fb01f
CW
206 ],
207 'contact_target_phone' => [
8c0ff2a6 208 'name' => 'phone',
2afe8e0c 209 'title' => ts('Target Phone'),
8c0ff2a6 210 'alias' => 'civicrm_phone_target',
be2fb01f
CW
211 ],
212 ],
213 ],
214 'civicrm_activity' => [
af9b09df 215 'dao' => 'CRM_Activity_DAO_Activity',
be2fb01f
CW
216 'fields' => [
217 'id' => [
af9b09df
TO
218 'no_display' => TRUE,
219 'title' => ts('Activity ID'),
220 'required' => TRUE,
be2fb01f
CW
221 ],
222 'source_record_id' => [
af9b09df
TO
223 'no_display' => TRUE,
224 'required' => TRUE,
be2fb01f
CW
225 ],
226 'activity_type_id' => [
af9b09df
TO
227 'title' => ts('Activity Type'),
228 'required' => TRUE,
229 'type' => CRM_Utils_Type::T_STRING,
be2fb01f
CW
230 ],
231 'activity_subject' => [
af9b09df
TO
232 'title' => ts('Subject'),
233 'default' => TRUE,
be2fb01f
CW
234 ],
235 'activity_date_time' => [
af9b09df
TO
236 'title' => ts('Activity Date'),
237 'required' => TRUE,
be2fb01f
CW
238 ],
239 'status_id' => [
af9b09df
TO
240 'title' => ts('Activity Status'),
241 'default' => TRUE,
242 'type' => CRM_Utils_Type::T_STRING,
be2fb01f
CW
243 ],
244 'duration' => [
af9b09df
TO
245 'title' => ts('Duration'),
246 'type' => CRM_Utils_Type::T_INT,
be2fb01f
CW
247 ],
248 'location' => [
c02f870b
JM
249 'title' => ts('Location'),
250 'type' => CRM_Utils_Type::T_STRING,
be2fb01f
CW
251 ],
252 'details' => [
1efec7ff 253 'title' => ts('Activity Details'),
be2fb01f
CW
254 ],
255 'priority_id' => [
da236f9a 256 'title' => ts('Priority'),
257 'default' => TRUE,
258 'type' => CRM_Utils_Type::T_STRING,
be2fb01f
CW
259 ],
260 ],
261 'filters' => [
262 'activity_date_time' => [
1a6c8513 263 'default' => 'this.month',
6a488035 264 'operatorType' => CRM_Report_Form::OP_DATE,
be2fb01f
CW
265 ],
266 'activity_subject' => ['title' => ts('Activity Subject')],
267 'activity_type_id' => [
af9b09df
TO
268 'title' => ts('Activity Type'),
269 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
270 'options' => $this->activityTypes,
be2fb01f
CW
271 ],
272 'status_id' => [
af9b09df 273 'title' => ts('Activity Status'),
8ee006e7 274 'type' => CRM_Utils_Type::T_STRING,
af9b09df
TO
275 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
276 'options' => CRM_Core_PseudoConstant::activityStatus(),
be2fb01f
CW
277 ],
278 'location' => [
c02f870b
JM
279 'title' => ts('Location'),
280 'type' => CRM_Utils_Type::T_TEXT,
be2fb01f
CW
281 ],
282 'details' => [
1efec7ff
DG
283 'title' => ts('Activity Details'),
284 'type' => CRM_Utils_Type::T_TEXT,
be2fb01f
CW
285 ],
286 'priority_id' => [
71c30391 287 'title' => ts('Activity Priority'),
410e8105 288 'type' => CRM_Utils_Type::T_STRING,
71c30391 289 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
290 'options' => CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id'),
be2fb01f
CW
291 ],
292 ],
293 'order_bys' => [
294 'activity_date_time' => [
af9b09df
TO
295 'title' => ts('Activity Date'),
296 'default_weight' => '1',
297 'dbAlias' => 'civicrm_activity_activity_date_time',
be2fb01f
CW
298 ],
299 'activity_type_id' => [
af9b09df
TO
300 'title' => ts('Activity Type'),
301 'default_weight' => '2',
56bbb442 302 'dbAlias' => 'field(civicrm_activity_activity_type_id, ' . implode(', ', array_keys($this->activityTypes)) . ')',
be2fb01f
CW
303 ],
304 ],
af9b09df
TO
305 'grouping' => 'activity-fields',
306 'alias' => 'activity',
be2fb01f 307 ],
56bbb442 308 // Hack to get $this->_alias populated for the table.
be2fb01f 309 'civicrm_activity_contact' => [
af9b09df 310 'dao' => 'CRM_Activity_DAO_ActivityContact',
be2fb01f
CW
311 'fields' => [],
312 ],
313 ] + $this->addressFields(TRUE);
6a488035 314
d6c3d40f 315 if ($caseEnabled && CRM_Core_Permission::check('access all cases and activities')) {
be2fb01f 316 $this->_columns['civicrm_activity']['filters']['include_case_activities'] = [
d6c3d40f 317 'name' => 'include_case_activities',
318 'title' => ts('Include Case Activities'),
319 'type' => CRM_Utils_Type::T_INT,
320 'operatorType' => CRM_Report_Form::OP_SELECT,
be2fb01f
CW
321 'options' => ['0' => ts('No'), '1' => ts('Yes')],
322 ];
07d4be20
SL
323 $this->_columns['civicrm_case_activity'] = [
324 'dao' => 'CRM_Case_DAO_CaseActivity',
325 'fields' => [],
326 ];
d6c3d40f 327 }
328
6a488035
TO
329 if ($campaignEnabled) {
330 // Add display column and filter for Survey Results, Campaign and Engagement Index if CiviCampaign is enabled
331
be2fb01f 332 $this->_columns['civicrm_activity']['fields']['result'] = [
fd6a6828 333 'title' => ts('Survey Result'),
6a488035 334 'default' => 'false',
be2fb01f
CW
335 ];
336 $this->_columns['civicrm_activity']['filters']['result'] = [
9d72cede 337 'title' => ts('Survey Result'),
6a488035
TO
338 'operator' => 'like',
339 'type' => CRM_Utils_Type::T_STRING,
be2fb01f 340 ];
254ca428
SL
341 // If we have campaigns enabled, add those elements to both the fields, filters.
342 $this->addCampaignFields('civicrm_activity');
f0100b85 343 $this->engagementLevels = $campaignEnabled ? CRM_Campaign_PseudoConstant::engagementLevel() : [];
6a488035 344 if (!empty($this->engagementLevels)) {
be2fb01f 345 $this->_columns['civicrm_activity']['fields']['engagement_level'] = [
fd6a6828 346 'title' => ts('Engagement Index'),
6a488035 347 'default' => 'false',
be2fb01f
CW
348 ];
349 $this->_columns['civicrm_activity']['filters']['engagement_level'] = [
9d72cede 350 'title' => ts('Engagement Index'),
09b5cdcf 351 'type' => CRM_Utils_Type::T_INT,
6a488035
TO
352 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
353 'options' => $this->engagementLevels,
be2fb01f 354 ];
6a488035
TO
355 }
356 }
357 $this->_groupFilter = TRUE;
358 $this->_tagFilter = TRUE;
ed795723 359 $this->_tagFilterTable = 'civicrm_activity';
b811ac0b 360
6a488035
TO
361 parent::__construct();
362 }
363
07d4be20
SL
364 protected static function addCaseActivityColumns($columns) {
365 $columns['civicrm_case_activity']['fields'] = [
366 'case_id' => [
367 'title' => ts('Case ID'),
368 'required' => TRUE,
369 'dbAlias' => $columns['civicrm_case_activity']['alias'] . '.case_id',
370 'type' => CRM_Utils_Type::T_INT,
371 ],
372 ];
373 return $columns;
b811ac0b
MWMC
374 }
375
be2e0c6a
TO
376 /**
377 * Adding address fields with dbAlias for order clause.
ab432335
EM
378 *
379 * @param bool $orderBy
380 *
a6c01b45 381 * @return array
ab432335 382 * Address fields
667abe3a 383 */
00be9182 384 public function addressFields($orderBy = FALSE) {
667abe3a 385 $address = parent::addAddressFields(FALSE, TRUE);
386 if ($orderBy) {
387 foreach ($address['civicrm_address']['order_bys'] as $fieldName => $field) {
388 $address['civicrm_address']['order_bys'][$fieldName]['dbAlias'] = "civicrm_address_{$fieldName}";
389 }
390 }
391 return $address;
392 }
393
74cf4551 394 /**
a0375fa3 395 * Build select clause.
396 *
d47468d0 397 * @todo get rid of $recordType param. It's only because 3 separate contact tables
398 * are mis-declared as one that we need it.
399 *
400 * @param null $recordType deprecated
401 * Parameter to hack around the bad decision made in construct to misrepresent
402 * different tables as the same table.
74cf4551 403 */
3ede1c56 404 public function select($recordType = 'target') {
9d72cede
EM
405 if (!array_key_exists("contact_{$recordType}", $this->_params['fields']) &&
406 $recordType != 'final'
407 ) {
09febbae 408 $this->_nonDisplayFields[] = "civicrm_contact_contact_{$recordType}";
09febbae 409 }
1f220d30 410 parent::select();
1f220d30 411
09febbae 412 if ($recordType == 'final' && !empty($this->_nonDisplayFields)) {
413 foreach ($this->_nonDisplayFields as $fieldName) {
414 unset($this->_columnHeaders[$fieldName]);
415 }
416 }
417
1f220d30
DS
418 if (empty($this->_selectAliasesTotal)) {
419 $this->_selectAliasesTotal = $this->_selectAliases;
420 }
421
be2fb01f 422 $removeKeys = [];
1f220d30 423 if ($recordType == 'target') {
d47468d0 424 // @todo - fix up the way the tables are declared in construct & remove this.
1f220d30 425 foreach ($this->_selectClauses as $key => $clause) {
7116d719 426 if (strstr($clause, 'civicrm_contact_assignee.') ||
1f220d30
DS
427 strstr($clause, 'civicrm_contact_source.') ||
428 strstr($clause, 'civicrm_email_assignee.') ||
8c0ff2a6 429 strstr($clause, 'civicrm_email_source.') ||
430 strstr($clause, 'civicrm_phone_assignee.') ||
431 strstr($clause, 'civicrm_phone_source.')
1f220d30
DS
432 ) {
433 $removeKeys[] = $key;
434 unset($this->_selectClauses[$key]);
435 }
436 }
9d72cede 437 }
4c9b6178 438 elseif ($recordType == 'assignee') {
d47468d0 439 // @todo - fix up the way the tables are declared in construct & remove this.
1f220d30 440 foreach ($this->_selectClauses as $key => $clause) {
7116d719 441 if (strstr($clause, 'civicrm_contact_target.') ||
1f220d30
DS
442 strstr($clause, 'civicrm_contact_source.') ||
443 strstr($clause, 'civicrm_email_target.') ||
8c0ff2a6 444 strstr($clause, 'civicrm_email_source.') ||
445 strstr($clause, 'civicrm_phone_target.') ||
c00963a1 446 strstr($clause, 'civicrm_phone_source.') ||
447 strstr($clause, 'civicrm_address_')
1f220d30
DS
448 ) {
449 $removeKeys[] = $key;
450 unset($this->_selectClauses[$key]);
451 }
452 }
9d72cede 453 }
4c9b6178 454 elseif ($recordType == 'source') {
d47468d0 455 // @todo - fix up the way the tables are declared in construct & remove this.
1f220d30 456 foreach ($this->_selectClauses as $key => $clause) {
7116d719 457 if (strstr($clause, 'civicrm_contact_target.') ||
1f220d30
DS
458 strstr($clause, 'civicrm_contact_assignee.') ||
459 strstr($clause, 'civicrm_email_target.') ||
8c0ff2a6 460 strstr($clause, 'civicrm_email_assignee.') ||
461 strstr($clause, 'civicrm_phone_target.') ||
c00963a1 462 strstr($clause, 'civicrm_phone_assignee.') ||
463 strstr($clause, 'civicrm_address_')
1f220d30
DS
464 ) {
465 $removeKeys[] = $key;
466 unset($this->_selectClauses[$key]);
467 }
468 }
9d72cede 469 }
4c9b6178 470 elseif ($recordType == 'final') {
1f220d30
DS
471 $this->_selectClauses = $this->_selectAliasesTotal;
472 foreach ($this->_selectClauses as $key => $clause) {
d47468d0 473 // @todo - fix up the way the tables are declared in construct & remove this.
7116d719 474 if (strstr($clause, 'civicrm_contact_contact_target') ||
1f220d30 475 strstr($clause, 'civicrm_contact_contact_assignee') ||
8c0ff2a6 476 strstr($clause, 'civicrm_contact_contact_source') ||
477 strstr($clause, 'civicrm_phone_contact_source_phone') ||
478 strstr($clause, 'civicrm_phone_contact_assignee_phone') ||
479 strstr($clause, 'civicrm_email_contact_source_email') ||
480 strstr($clause, 'civicrm_email_contact_assignee_email') ||
481 strstr($clause, 'civicrm_email_contact_target_email') ||
66ad82d6 482 strstr($clause, 'civicrm_phone_contact_target_phone') ||
483 strstr($clause, 'civicrm_address_')
9d72cede 484 ) {
66ad82d6 485 $this->_selectClauses[$key] = "GROUP_CONCAT(DISTINCT $clause SEPARATOR ';') as $clause";
6a488035
TO
486 }
487 }
488 }
489
1f220d30
DS
490 if ($recordType) {
491 foreach ($removeKeys as $key) {
492 unset($this->_selectAliases[$key]);
493 }
494
c00963a1 495 if ($recordType == 'target') {
667abe3a 496 foreach ($this->_columns['civicrm_address']['order_bys'] as $fieldName => $field) {
497 $orderByFld = $this->_columns['civicrm_address']['order_bys'][$fieldName];
498 $fldInfo = $this->_columns['civicrm_address']['fields'][$fieldName];
499 $this->_selectAliases[] = $orderByFld['dbAlias'];
500 $this->_selectClauses[] = "{$fldInfo['dbAlias']} as {$orderByFld['dbAlias']}";
501 }
667abe3a 502 $this->_selectAliases = array_unique($this->_selectAliases);
503 $this->_selectClauses = array_unique($this->_selectClauses);
504 }
1f220d30 505 $this->_select = "SELECT " . implode(', ', $this->_selectClauses) . " ";
1f220d30 506 }
6a488035
TO
507 }
508
74cf4551 509 /**
a0375fa3 510 * Build from clause.
d47468d0 511 * @todo remove this function & declare the 3 contact tables separately
74cf4551 512 */
d47468d0 513 public function from() {
b811ac0b 514 $this->buildFrom('target');
6a488035
TO
515 }
516
74cf4551 517 /**
a0375fa3 518 * Build where clause.
519 *
d47468d0 520 * @todo get rid of $recordType param. It's only because 3 separate contact tables
521 * are mis-declared as one that we need it.
522 *
a0375fa3 523 * @param string $recordType
74cf4551 524 */
00be9182 525 public function where($recordType = NULL) {
2f4b4d54 526 $this->_where = " WHERE {$this->_aliases['civicrm_activity']}.is_test = 0 AND
6a488035
TO
527 {$this->_aliases['civicrm_activity']}.is_deleted = 0 AND
528 {$this->_aliases['civicrm_activity']}.is_current_revision = 1";
529
be2fb01f 530 $clauses = [];
6a488035
TO
531 foreach ($this->_columns as $tableName => $table) {
532 if (array_key_exists('filters', $table)) {
533
534 foreach ($table['filters'] as $fieldName => $field) {
535 $clause = NULL;
7116d719 536 if ($fieldName != 'contact_' . $recordType &&
537 (strstr($fieldName, '_target') ||
538 strstr($fieldName, '_assignee') ||
539 strstr($fieldName, '_source')
540 )
541 ) {
7116d719 542 continue;
543 }
6a488035 544 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
9c1bc317
CW
545 $relative = $this->_params["{$fieldName}_relative"] ?? NULL;
546 $from = $this->_params["{$fieldName}_from"] ?? NULL;
547 $to = $this->_params["{$fieldName}_to"] ?? NULL;
6a488035 548
c44cb2b8 549 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type']);
6a488035
TO
550 }
551 else {
9c1bc317 552 $op = $this->_params["{$fieldName}_op"] ?? NULL;
54df7b0b 553 if ($op && !($fieldName === "contact_{$recordType}" && ($op === 'nnll' || $op === 'nll'))) {
6a488035
TO
554 $clause = $this->whereClause($field,
555 $op,
556 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
557 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
558 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
559 );
d6c3d40f 560 if ($field['name'] == 'include_case_activities') {
561 $clause = NULL;
562 }
9d72cede
EM
563 if ($fieldName == 'activity_type_id' &&
564 empty($this->_params['activity_type_id_value'])
565 ) {
355b8a20 566 if (empty($this->_params['include_case_activities_value'])) {
567 $this->activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'label', TRUE);
568 }
1023b3bc 569 $actTypes = array_flip($this->activityTypes);
6c552737 570 $clause = "( {$this->_aliases['civicrm_activity']}.activity_type_id IN (" .
9d72cede 571 implode(',', $actTypes) . ") )";
42b3be07 572 }
6a488035
TO
573 }
574 }
575
576 if ($field['name'] == 'current_user') {
9d72cede
EM
577 if (CRM_Utils_Array::value("{$fieldName}_value", $this->_params) ==
578 1
579 ) {
6a488035 580 // get current user
f0c3f9bc 581 if ($contactID = CRM_Core_Session::getLoggedInContactID()) {
389cfee7 582 $clause = "{$this->_aliases['civicrm_activity_contact']}.activity_id IN
583 (SELECT activity_id FROM civicrm_activity_contact WHERE contact_id = {$contactID})";
6a488035
TO
584 }
585 else {
586 $clause = NULL;
587 }
588 }
589 else {
590 $clause = NULL;
591 }
592 }
593 if (!empty($clause)) {
594 $clauses[] = $clause;
595 }
596 }
597 }
598 }
599
600 if (empty($clauses)) {
b6cab294 601 $this->_where .= " ";
6a488035
TO
602 }
603 else {
b6cab294 604 $this->_where .= " AND " . implode(' AND ', $clauses);
6a488035
TO
605 }
606
607 if ($this->_aclWhere) {
608 $this->_where .= " AND {$this->_aclWhere} ";
609 }
610 }
611
a0375fa3 612 /**
613 * Override group by function.
614 */
00be9182 615 public function groupBy() {
b708c08d 616 $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, "{$this->_aliases['civicrm_activity']}.id");
6a488035
TO
617 }
618
74cf4551 619 /**
a0375fa3 620 * Build ACL clause.
621 *
74cf4551 622 * @param string $tableAlias
f0c3f9bc 623 *
624 * @throws \CRM_Core_Exception
74cf4551 625 */
00be9182 626 public function buildACLClause($tableAlias = 'contact_a') {
2a3c101f 627 //override for ACL( Since Contact may be source
6a488035
TO
628 //contact/assignee or target also it may be null )
629
630 if (CRM_Core_Permission::check('view all contacts')) {
631 $this->_aclFrom = $this->_aclWhere = NULL;
632 return;
633 }
634
f0c3f9bc 635 $contactID = CRM_Core_Session::getLoggedInContactID();
6a488035
TO
636 if (!$contactID) {
637 $contactID = 0;
638 }
639 $contactID = CRM_Utils_Type::escape($contactID, 'Integer');
640
641 CRM_Contact_BAO_Contact_Permission::cache($contactID);
be2fb01f 642 $clauses = [];
6a488035
TO
643 foreach ($tableAlias as $k => $alias) {
644 $clauses[] = " INNER JOIN civicrm_acl_contact_cache aclContactCache_{$k} ON ( {$alias}.id = aclContactCache_{$k}.contact_id OR {$alias}.id IS NULL ) AND aclContactCache_{$k}.user_id = $contactID ";
645 }
646
647 $this->_aclFrom = implode(" ", $clauses);
648 $this->_aclWhere = NULL;
649 }
650
74cf4551 651 /**
100fef9d 652 * @param int $groupID
74cf4551
EM
653 *
654 * @throws Exception
655 */
00be9182 656 public function add2group($groupID) {
9a2f601e 657 if (CRM_Utils_Array::value("contact_target_op", $this->_params) == 'nll') {
7980012b 658 CRM_Core_Error::statusBounce(ts('Current filter criteria didn\'t have any target contact to add to group'));
9a2f601e 659 }
660
7f6464a0
JM
661 $new_select = 'AS addtogroup_contact_id';
662 $select = str_ireplace('AS civicrm_contact_contact_target_id', $new_select, $this->_select);
663 $new_having = ' addtogroup_contact_id';
664 $having = str_ireplace(' civicrm_contact_contact_target_id', $new_having, $this->_having);
665 $query = "$select
a8b58e72 666FROM {$this->temporaryTables['activity_temp_table']['name']} tar
7f6464a0 667GROUP BY civicrm_activity_id $having {$this->_orderBy}";
9a2f601e 668 $select = 'AS addtogroup_contact_id';
669 $query = str_ireplace('AS civicrm_contact_contact_target_id', $select, $query);
dfb264b2 670 CRM_Core_DAO::disableFullGroupByMode();
f38e3c19 671 $dao = $this->executeReportQuery($query);
dfb264b2 672 CRM_Core_DAO::reenableFullGroupByMode();
9a2f601e 673
be2fb01f 674 $contactIDs = [];
9a2f601e 675 // Add resulting contacts to group
676 while ($dao->fetch()) {
677 if ($dao->addtogroup_contact_id) {
678 $contact_id = explode(';', $dao->addtogroup_contact_id);
679 if ($contact_id[0]) {
7bb16323 680 $contactIDs[$contact_id[0]] = $contact_id[0];
9a2f601e 681 }
682 }
683 }
684
9d72cede 685 if (!empty($contactIDs)) {
9a2f601e 686 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIDs, $groupID);
687 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
688 }
689 else {
690 CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
691 }
692 }
693
d6c3d40f 694 /**
695 * @param $fields
696 * @param $files
697 * @param $self
698 *
699 * @return array
700 */
701 public static function formRule($fields, $files, $self) {
be2fb01f 702 $errors = [];
355b8a20 703 $config = CRM_Core_Config::singleton();
704 if (in_array("CiviCase", $config->enableComponents)) {
705 $componentId = CRM_Core_Component::getComponentID('CiviCase');
706 $caseActivityTypes = CRM_Core_OptionGroup::values('activity_type', TRUE, FALSE, FALSE, " AND v.component_id={$componentId}");
707 if (!empty($fields['activity_type_id_value']) && is_array($fields['activity_type_id_value']) && empty($fields['include_case_activities_value'])) {
708 foreach ($fields['activity_type_id_value'] as $activityTypeId) {
709 if (in_array($activityTypeId, $caseActivityTypes)) {
710 $errors['fields'] = ts("Please enable 'Include Case Activities' to filter with Case Activity types.");
711 }
d6c3d40f 712 }
713 }
714 }
715 return $errors;
716 }
717
a1bf1058
ML
718 /**
719 * @param $applyLimit
720 *
721 * @return string
722 */
723 public function buildQuery($applyLimit = TRUE) {
44f817d4 724 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
52272965 725 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2f4b4d54 726
389cfee7 727 //Assign those recordtype to array which have filter operator as 'Is not empty' or 'Is empty'
be2fb01f
CW
728 $nullFilters = [];
729 foreach (['target', 'source', 'assignee'] as $type) {
9d72cede
EM
730 if (CRM_Utils_Array::value("contact_{$type}_op", $this->_params) ==
731 'nnll' || !empty($this->_params["contact_{$type}_value"])
732 ) {
3ae89fd7 733 $nullFilters[] = " civicrm_contact_contact_{$type}_id IS NOT NULL ";
389cfee7 734 }
4c9b6178 735 elseif (CRM_Utils_Array::value("contact_{$type}_op", $this->_params) ==
9d72cede
EM
736 'nll'
737 ) {
3ae89fd7 738 $nullFilters[] = " civicrm_contact_contact_{$type}_id IS NULL ";
b6cab294 739 }
740 }
741
07d4be20
SL
742 if (!empty($this->_params['include_case_activities_value'])) {
743 $this->_columns = self::addCaseActivityColumns($this->_columns);
744 }
745
d47468d0 746 // @todo - all this temp table stuff is here because pre 4.4 the activity contact
747 // form did not exist.
748 // Fixing the way the construct method declares them will make all this redundant.
9d72cede 749 // 1. fill temp table with target results
be2fb01f 750 $this->buildACLClause(['civicrm_contact_target']);
1f220d30 751 $this->select('target');
d47468d0 752 $this->from();
5b1ba2b8 753 $this->customDataFrom();
389cfee7 754 $this->where('target');
5a14305b 755 $tempTableName = $this->createTemporaryTable('activity_temp_table', "{$this->_select} {$this->_from} {$this->_where}");
2f4b4d54 756
1f220d30
DS
757 // 2. add new columns to hold assignee and source results
758 // fixme: add when required
759 $tempQuery = "
5a14305b 760 ALTER TABLE $tempTableName
e7b3275b 761 MODIFY COLUMN civicrm_contact_contact_target_id VARCHAR(128),
1f220d30
DS
762 ADD COLUMN civicrm_contact_contact_assignee VARCHAR(128),
763 ADD COLUMN civicrm_contact_contact_source VARCHAR(128),
7116d719 764 ADD COLUMN civicrm_contact_contact_assignee_id VARCHAR(128),
482691e1 765 ADD COLUMN civicrm_contact_contact_source_id VARCHAR(128),
8c0ff2a6 766 ADD COLUMN civicrm_phone_contact_assignee_phone VARCHAR(128),
767 ADD COLUMN civicrm_phone_contact_source_phone VARCHAR(128),
1f220d30
DS
768 ADD COLUMN civicrm_email_contact_assignee_email VARCHAR(128),
769 ADD COLUMN civicrm_email_contact_source_email VARCHAR(128)";
f38e3c19 770 $this->executeReportQuery($tempQuery);
1f220d30
DS
771
772 // 3. fill temp table with assignee results
be2fb01f 773 $this->buildACLClause(['civicrm_contact_assignee']);
389cfee7 774 $this->select('assignee');
d47468d0 775 $this->buildAssigneeFrom();
776
389cfee7 777 $this->customDataFrom();
778 $this->where('assignee');
779 $insertCols = implode(',', $this->_selectAliases);
5a14305b 780 $tempQuery = "INSERT INTO $tempTableName ({$insertCols})
1f220d30 781{$this->_select}
83e74860 782{$this->_from} {$this->_where}";
f38e3c19 783 $this->executeReportQuery($tempQuery);
2f4b4d54 784
1f220d30 785 // 4. fill temp table with source results
be2fb01f 786 $this->buildACLClause(['civicrm_contact_source']);
389cfee7 787 $this->select('source');
d47468d0 788 $this->buildSourceFrom();
389cfee7 789 $this->customDataFrom();
790 $this->where('source');
791 $insertCols = implode(',', $this->_selectAliases);
5a14305b 792 $tempQuery = "INSERT INTO $tempTableName ({$insertCols})
1f220d30 793{$this->_select}
83e74860 794{$this->_from} {$this->_where}";
f38e3c19 795 $this->executeReportQuery($tempQuery);
2f4b4d54 796
1f220d30 797 // 5. show final result set from temp table
be2fb01f 798 $rows = [];
1f220d30 799 $this->select('final');
389cfee7 800 $this->_having = "";
801 if (!empty($nullFilters)) {
802 $this->_having = "HAVING " . implode(' AND ', $nullFilters);
803 }
83e74860 804 $this->orderBy();
ecf1e543 805 foreach ($this->_sections as $alias => $section) {
806 if (!empty($section) && $section['name'] == 'activity_date_time') {
5a14305b 807 $this->alterSectionHeaderForDateTime($tempTableName, $section['tplField']);
ecf1e543 808 }
e06df9af 809 }
a1bf1058
ML
810
811 if ($applyLimit) {
812 $this->limit();
813 }
814
d1641c51 815 $groupByFromSelect = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, 'civicrm_activity_id');
52272965 816
cbbc16ec 817 $this->_where = " WHERE (1)";
52272965 818 $this->buildPermissionClause();
cbbc16ec
TS
819 if ($this->_aclWhere) {
820 $this->_where .= " AND {$this->_aclWhere} ";
821 }
52272965 822
b811ac0b
MWMC
823 $caseJoin = '';
824 if (!empty($this->_params['include_case_activities_value'])) {
825 $caseJoin = "LEFT JOIN civicrm_case_activity {$this->_aliases['civicrm_case_activity']} ON {$this->_aliases['civicrm_activity']}.id = {$this->_aliases['civicrm_case_activity']}.activity_id";
826 }
827
7116d719 828 $sql = "{$this->_select}
5a14305b 829 FROM $tempTableName tar
52272965
E
830 INNER JOIN civicrm_activity {$this->_aliases['civicrm_activity']} ON {$this->_aliases['civicrm_activity']}.id = tar.civicrm_activity_id
831 INNER JOIN civicrm_activity_contact {$this->_aliases['civicrm_activity_contact']} ON {$this->_aliases['civicrm_activity_contact']}.activity_id = {$this->_aliases['civicrm_activity']}.id
832 AND {$this->_aliases['civicrm_activity_contact']}.record_type_id = {$sourceID}
cbbc16ec 833 LEFT JOIN civicrm_contact contact_civireport ON contact_civireport.id = {$this->_aliases['civicrm_activity_contact']}.contact_id
b811ac0b 834 {$caseJoin}
cbbc16ec 835 {$this->_where} {$groupByFromSelect} {$this->_having} {$this->_orderBy} {$this->_limit}";
52272965 836
a1bf1058 837 CRM_Utils_Hook::alterReportVar('sql', $this, $this);
cbbc16ec 838 $this->addToDeveloperTab($sql);
a1bf1058
ML
839
840 return $sql;
841 }
842
c6f4d60c 843 /**
844 * Override parent to reset value of activity_date.
845 */
846 public function beginPostProcessCommon() {
a1bf1058 847 if (!empty($this->_resetDateFilter)) {
c6f4d60c 848 $this->_formValues['activity_date_time_relative'] = NULL;
a1bf1058 849 }
6a488035
TO
850 }
851
74cf4551 852 /**
4b62bc4f
EM
853 * Alter display of rows.
854 *
855 * Iterate through the rows retrieved via SQL and make changes for display purposes,
856 * such as rendering contacts as links.
857 *
858 * @param array $rows
859 * Rows generated by SQL, with an array for each row.
c6f4d60c 860 *
861 * @throws \CRM_Core_Exception
74cf4551 862 */
00be9182 863 public function alterDisplay(&$rows) {
9d72cede
EM
864 $entryFound = FALSE;
865 $activityType = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6a488035 866 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
410e8105 867 $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
bb5737d0 868 $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
9d72cede 869 $viewLinks = FALSE;
f2e37338 870
d47468d0 871 // Would we ever want to retrieve from the form controller??
872 $form = $this->noController ? NULL : $this;
873 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $form, FALSE, 'report');
9d72cede 874 $actUrl = '';
6a488035
TO
875
876 if (CRM_Core_Permission::check('access CiviCRM')) {
9d72cede
EM
877 $viewLinks = TRUE;
878 $onHover = ts('View Contact Summary for this Contact');
6a488035
TO
879 $onHoverAct = ts('View Activity Record');
880 }
38ba593b 881 foreach ($rows as $rowNum => $row) {
1efec7ff 882 // if we have an activity type, format the View Activity link for use in various columns
9d72cede
EM
883 if ($viewLinks &&
884 array_key_exists('civicrm_activity_activity_type_id', $row)
885 ) {
1efec7ff
DG
886 // Check for target contact id(s) and use the first contact id in that list for view activity link if found,
887 // else use source contact id
888 if (!empty($rows[$rowNum]['civicrm_contact_contact_target_id'])) {
889 $targets = explode(';', $rows[$rowNum]['civicrm_contact_contact_target_id']);
890 $cid = $targets[0];
891 }
892 else {
893 $cid = $rows[$rowNum]['civicrm_contact_contact_source_id'];
894 }
895
b811ac0b
MWMC
896 if (empty($this->_params['include_case_activities_value']) || empty($rows[$rowNum]['civicrm_case_activity_case_id'])) {
897 // Generate a "view activity" link
898 $actActionLinks = CRM_Activity_Selector_Activity::actionLinks($row['civicrm_activity_activity_type_id'],
899 CRM_Utils_Array::value('civicrm_activity_source_record_id', $rows[$rowNum]),
900 FALSE,
901 $rows[$rowNum]['civicrm_activity_id']
902 );
903
904 $actLinkValues = [
905 'id' => $rows[$rowNum]['civicrm_activity_id'],
906 'cid' => $cid,
907 'cxt' => $context,
908 ];
909 $actUrl = CRM_Utils_System::url($actActionLinks[CRM_Core_Action::VIEW]['url'],
910 CRM_Core_Action::replace($actActionLinks[CRM_Core_Action::VIEW]['qs'], $actLinkValues), TRUE
911 );
912 }
913 else {
914 // Generate a "view case activity" link
915 $caseActionLinks = CRM_Case_Selector_Search::actionLinks();
916 $caseLinkValues = [
917 'aid' => $rows[$rowNum]['civicrm_activity_id'],
918 'caseid' => $rows[$rowNum]['civicrm_case_activity_case_id'],
919 'cid' => $cid,
920 'cxt' => $context,
921 ];
922 $actUrl = CRM_Utils_System::url($caseActionLinks[CRM_Core_Action::VIEW]['url'],
923 CRM_Core_Action::replace($caseActionLinks[CRM_Core_Action::VIEW]['qs'], $caseLinkValues), TRUE
924 );
925 }
1efec7ff
DG
926 }
927
482691e1
RN
928 if (array_key_exists('civicrm_contact_contact_source', $row)) {
929 if ($value = $row['civicrm_contact_contact_source_id']) {
930 if ($viewLinks) {
931 $url = CRM_Utils_System::url("civicrm/contact/view",
932 'reset=1&cid=' . $value,
933 $this->_absoluteUrl
934 );
935 $rows[$rowNum]['civicrm_contact_contact_source_link'] = $url;
936 $rows[$rowNum]['civicrm_contact_contact_source_hover'] = $onHover;
937 }
938 $entryFound = TRUE;
939 }
940 }
941
942 if (array_key_exists('civicrm_contact_contact_assignee', $row)) {
943 $assigneeNames = explode(';', $row['civicrm_contact_contact_assignee']);
944 if ($value = $row['civicrm_contact_contact_assignee_id']) {
945 $assigneeContactIds = explode(';', $value);
be2fb01f 946 $link = [];
482691e1
RN
947 if ($viewLinks) {
948 foreach ($assigneeContactIds as $id => $value) {
949 if (isset($value) && isset($assigneeNames[$id])) {
950 $url = CRM_Utils_System::url("civicrm/contact/view",
951 'reset=1&cid=' . $value,
952 $this->_absoluteUrl
953 );
9d72cede
EM
954 $link[] = "<a title='" . $onHover . "' href='" . $url .
955 "'>{$assigneeNames[$id]}</a>";
482691e1
RN
956 }
957 }
958 $rows[$rowNum]['civicrm_contact_contact_assignee'] = implode('; ', $link);
959 }
960 $entryFound = TRUE;
961 }
962 }
963
964 if (array_key_exists('civicrm_contact_contact_target', $row)) {
965 $targetNames = explode(';', $row['civicrm_contact_contact_target']);
966 if ($value = $row['civicrm_contact_contact_target_id']) {
967 $targetContactIds = explode(';', $value);
be2fb01f 968 $link = [];
482691e1
RN
969 if ($viewLinks) {
970 foreach ($targetContactIds as $id => $value) {
971 if (isset($value) && isset($targetNames[$id])) {
972 $url = CRM_Utils_System::url("civicrm/contact/view",
973 'reset=1&cid=' . $value,
974 $this->_absoluteUrl
975 );
9d72cede
EM
976 $link[] = "<a title='" . $onHover . "' href='" . $url .
977 "'>{$targetNames[$id]}</a>";
482691e1
RN
978 }
979 }
980 $rows[$rowNum]['civicrm_contact_contact_target'] = implode('; ', $link);
981 }
982 $entryFound = TRUE;
983 }
984 }
985
6a488035
TO
986 if (array_key_exists('civicrm_activity_activity_type_id', $row)) {
987 if ($value = $row['civicrm_activity_activity_type_id']) {
988 $rows[$rowNum]['civicrm_activity_activity_type_id'] = $activityType[$value];
482691e1 989 if ($viewLinks) {
1efec7ff 990 $rows[$rowNum]['civicrm_activity_activity_type_id_link'] = $actUrl;
482691e1
RN
991 $rows[$rowNum]['civicrm_activity_activity_type_id_hover'] = $onHoverAct;
992 }
6a488035
TO
993 $entryFound = TRUE;
994 }
995 }
996
997 if (array_key_exists('civicrm_activity_status_id', $row)) {
998 if ($value = $row['civicrm_activity_status_id']) {
999 $rows[$rowNum]['civicrm_activity_status_id'] = $activityStatus[$value];
1000 $entryFound = TRUE;
1001 }
1002 }
1003
410e8105 1004 if (array_key_exists('civicrm_activity_priority_id', $row)) {
1005 if ($value = $row['civicrm_activity_priority_id']) {
1006 $rows[$rowNum]['civicrm_activity_priority_id'] = $priority[$value];
1007 $entryFound = TRUE;
1008 }
1009 }
1010
34e0bdb6 1011 if (array_key_exists('civicrm_activity_details', $row) && $this->_outputMode == 'html') {
1efec7ff
DG
1012 if ($value = $row['civicrm_activity_details']) {
1013 $fullDetails = $rows[$rowNum]['civicrm_activity_details'];
1014 $rows[$rowNum]['civicrm_activity_details'] = substr($fullDetails, 0, strrpos(substr($fullDetails, 0, 80), ' '));
1015 if ($actUrl) {
6e5e50a9 1016 $rows[$rowNum]['civicrm_activity_details'] .= " <a href='{$actUrl}' title='{$onHoverAct}'>(more)</a>";
1efec7ff
DG
1017 }
1018 $entryFound = TRUE;
1019 }
1020 }
1021
6a488035
TO
1022 if (array_key_exists('civicrm_activity_campaign_id', $row)) {
1023 if ($value = $row['civicrm_activity_campaign_id']) {
254ca428 1024 $rows[$rowNum]['civicrm_activity_campaign_id'] = $this->campaigns[$value];
6a488035
TO
1025 $entryFound = TRUE;
1026 }
1027 }
1028
1029 if (array_key_exists('civicrm_activity_engagement_level', $row)) {
1030 if ($value = $row['civicrm_activity_engagement_level']) {
1031 $rows[$rowNum]['civicrm_activity_engagement_level'] = $this->engagementLevels[$value];
1032 $entryFound = TRUE;
1033 }
1034 }
1035
9d72cede
EM
1036 if (array_key_exists('civicrm_activity_activity_date_time', $row) &&
1037 array_key_exists('civicrm_activity_status_id', $row)
1038 ) {
6a488035
TO
1039 if (CRM_Utils_Date::overdue($rows[$rowNum]['civicrm_activity_activity_date_time']) &&
1040 $activityStatus[$row['civicrm_activity_status_id']] != 'Completed'
1041 ) {
1042 $rows[$rowNum]['class'] = "status-overdue";
1043 $entryFound = TRUE;
bb5737d0 1044 }
1045 }
1046
1047 if (array_key_exists('civicrm_contact_contact_target_gender', $row)) {
1048 if ($value = $row['civicrm_contact_contact_target_gender']) {
1049 $rows[$rowNum]['civicrm_contact_contact_target_gender'] = $genders[$value];
1050 $entryFound = TRUE;
6a488035
TO
1051 }
1052 }
1053
66ad82d6 1054 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'activity', 'List all activities for this', ';') ? TRUE : $entryFound;
482691e1 1055
6a488035
TO
1056 if (!$entryFound) {
1057 break;
1058 }
1059 }
1060 }
667abe3a 1061
00be9182 1062 public function sectionTotals() {
667abe3a 1063 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
1064 if (empty($this->_selectAliases)) {
1065 return;
1066 }
1067
1068 if (!empty($this->_sections)) {
1069 // pull section aliases out of $this->_sections
1070 $sectionAliases = array_keys($this->_sections);
1071
be2fb01f 1072 $ifnulls = [];
667abe3a 1073 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
1074 $ifnulls[] = "ifnull($alias, '') as $alias";
1075 }
b708c08d 1076 $this->_select = "SELECT " . implode(", ", $ifnulls);
36d2f4d5 1077 $this->_select = CRM_Contact_BAO_Query::appendAnyValueToSelect($ifnulls, $sectionAliases);
667abe3a 1078
b708c08d 1079 $query = $this->_select .
ab663ec4 1080 ", count(DISTINCT civicrm_activity_id) as ct from {$this->temporaryTables['activity_temp_table']['name']} group by " .
667abe3a 1081 implode(", ", $sectionAliases);
1082
1083 // initialize array of total counts
be2fb01f 1084 $totals = [];
f38e3c19 1085 $dao = $this->executeReportQuery($query);
667abe3a 1086 while ($dao->fetch()) {
1087 // let $this->_alterDisplay translate any integer ids to human-readable values.
1088 $rows[0] = $dao->toArray();
1089 $this->alterDisplay($rows);
1090 $row = $rows[0];
1091
1092 // add totals for all permutations of section values
be2fb01f 1093 $values = [];
667abe3a 1094 $i = 1;
1095 $aliasCount = count($sectionAliases);
1096 foreach ($sectionAliases as $alias) {
1097 $values[] = $row[$alias];
1098 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
1099 if ($i == $aliasCount) {
1100 // the last alias is the lowest-level section header; use count as-is
1101 $totals[$key] = $dao->ct;
1102 }
1103 else {
1104 // other aliases are higher level; roll count into their total
1105 $totals[$key] += $dao->ct;
1106 }
1107 }
1108 }
1109 $this->assign('sectionTotals', $totals);
1110 }
1111 }
96025800 1112
d47468d0 1113 /**
1114 * @todo remove this function & declare the 3 contact tables separately
1115 *
1116 * (Currently the construct method incorrectly melds them - this is an interim
1117 * refactor in order to get this under ReportTemplateTests)
1118 */
1119 protected function buildAssigneeFrom() {
b811ac0b 1120 $this->buildFrom('assignee');
d47468d0 1121 }
1122
1123 /**
1124 * @todo remove this function & declare the 3 contact tables separately
1125 *
1126 * (Currently the construct method incorrectly melds them - this is an interim
1127 * refactor in order to get this under ReportTemplateTests)
1128 */
1129 protected function buildSourceFrom() {
b811ac0b
MWMC
1130 $this->buildFrom('source');
1131 }
1132
1133 /**
1134 * Shared function to build the from clause
1135 *
1136 * @param string $recordType (one of 'source', 'activity', 'target')
1137 */
1138 protected function buildFrom($recordType) {
d47468d0 1139 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
b811ac0b
MWMC
1140 switch ($recordType) {
1141 case 'target':
1142 $recordTypeID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1143 break;
1144
1145 case 'source':
1146 $recordTypeID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1147 break;
1148
1149 case 'assignee':
1150 $recordTypeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
1151 break;
1152
1153 }
1154
d47468d0 1155 $this->_from = "
b811ac0b
MWMC
1156 FROM civicrm_activity {$this->_aliases['civicrm_activity']}
1157 INNER JOIN civicrm_activity_contact {$this->_aliases['civicrm_activity_contact']}
1158 ON {$this->_aliases['civicrm_activity']}.id = {$this->_aliases['civicrm_activity_contact']}.activity_id AND
1159 {$this->_aliases['civicrm_activity_contact']}.record_type_id = {$recordTypeID}
1160 INNER JOIN civicrm_contact civicrm_contact_{$recordType}
1161 ON {$this->_aliases['civicrm_activity_contact']}.contact_id = civicrm_contact_{$recordType}.id
1162 {$this->_aclFrom}";
1163 if (!empty($this->_params['include_case_activities_value'])) {
1164 $this->_from .= "
1165 LEFT JOIN civicrm_case_activity {$this->_aliases['civicrm_case_activity']}
1166 ON {$this->_aliases['civicrm_case_activity']}.activity_id = {$this->_aliases['civicrm_activity']}.id";
1167 }
d47468d0 1168
1169 if ($this->isTableSelected('civicrm_email')) {
1170 $this->_from .= "
b811ac0b
MWMC
1171 LEFT JOIN civicrm_email civicrm_email_{$recordType}
1172 ON {$this->_aliases['civicrm_activity_contact']}.contact_id = civicrm_email_{$recordType}.contact_id AND
1173 civicrm_email_{$recordType}.is_primary = 1";
d47468d0 1174 }
b811ac0b 1175
d47468d0 1176 if ($this->isTableSelected('civicrm_phone')) {
1177 $this->_from .= "
b811ac0b
MWMC
1178 LEFT JOIN civicrm_phone civicrm_phone_{$recordType}
1179 ON {$this->_aliases['civicrm_activity_contact']}.contact_id = civicrm_phone_{$recordType}.contact_id AND
1180 civicrm_phone_{$recordType}.is_primary = 1 ";
d47468d0 1181 }
b811ac0b
MWMC
1182 $this->_aliases['civicrm_contact'] = "civicrm_contact_{$recordType}";
1183
d47468d0 1184 $this->joinAddressFromContact();
1185 }
1186
6a488035 1187}