Merge pull request #6922 from eileenmcnaughton/CRM-17000
[civicrm-core.git] / CRM / Report / Form / Activity.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
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 */
33class CRM_Report_Form_Activity extends CRM_Report_Form {
1f220d30 34 protected $_selectAliasesTotal = array();
6a488035
TO
35
36 protected $_customGroupExtends = array(
21dfd5f5 37 'Activity',
430ae6dd
TO
38 );
39
09febbae 40 protected $_nonDisplayFields = array();
41
74cf4551 42 /**
ab432335 43 * Class constructor.
74cf4551 44 */
00be9182 45 public function __construct() {
7116d719 46 // There could be multiple contacts. We not clear on which contact id to display.
83e74860
DS
47 // Lets hide it for now.
48 $this->_exposeContactID = FALSE;
49
6a488035
TO
50 $config = CRM_Core_Config::singleton();
51 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
52 if ($campaignEnabled) {
53 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
54 $this->activeCampaigns = $getCampaigns['campaigns'];
55 asort($this->activeCampaigns);
56 $this->engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
57 }
58 $this->activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'label', TRUE);
59 asort($this->activityTypes);
60
61 $this->_columns = array(
af9b09df
TO
62 'civicrm_contact' => array(
63 'dao' => 'CRM_Contact_DAO_Contact',
64 'fields' => array(
65 'contact_source' => array(
66 'name' => 'sort_name',
67 'title' => ts('Source Contact Name'),
68 'alias' => 'civicrm_contact_source',
69 'no_repeat' => TRUE,
6a488035 70 ),
af9b09df
TO
71 'contact_assignee' => array(
72 'name' => 'sort_name',
73 'title' => ts('Assignee Contact Name'),
74 'alias' => 'civicrm_contact_assignee',
75 'dbAlias' => "civicrm_contact_assignee.sort_name",
76 'default' => TRUE,
77 ),
78 'contact_target' => array(
79 'name' => 'sort_name',
80 'title' => ts('Target Contact Name'),
81 'alias' => 'civicrm_contact_target',
82 'dbAlias' => "civicrm_contact_target.sort_name",
83 'default' => TRUE,
84 ),
85 'contact_source_id' => array(
86 'name' => 'id',
87 'alias' => 'civicrm_contact_source',
88 'dbAlias' => "civicrm_contact_source.id",
89 'no_display' => TRUE,
90 'default' => TRUE,
91 'required' => TRUE,
92 ),
93 'contact_assignee_id' => array(
94 'name' => 'id',
95 'alias' => 'civicrm_contact_assignee',
96 'dbAlias' => "civicrm_contact_assignee.id",
97 'no_display' => TRUE,
98 'default' => TRUE,
99 'required' => TRUE,
100 ),
101 'contact_target_id' => array(
102 'name' => 'id',
103 'alias' => 'civicrm_contact_target',
104 'dbAlias' => "civicrm_contact_target.id",
105 'no_display' => TRUE,
106 'default' => TRUE,
107 'required' => TRUE,
482691e1 108 ),
6a488035 109 ),
af9b09df
TO
110 'filters' => array(
111 'contact_source' => array(
112 'name' => 'sort_name',
113 'alias' => 'civicrm_contact_source',
114 'title' => ts('Source Contact Name'),
115 'operator' => 'like',
116 'type' => CRM_Report_Form::OP_STRING,
6a488035 117 ),
af9b09df
TO
118 'contact_assignee' => array(
119 'name' => 'sort_name',
120 'alias' => 'civicrm_contact_assignee',
121 'title' => ts('Assignee Contact Name'),
122 'operator' => 'like',
123 'type' => CRM_Report_Form::OP_STRING,
124 ),
125 'contact_target' => array(
126 'name' => 'sort_name',
127 'alias' => 'civicrm_contact_target',
128 'title' => ts('Target Contact Name'),
129 'operator' => 'like',
130 'type' => CRM_Report_Form::OP_STRING,
131 ),
132 'current_user' => array(
133 'name' => 'current_user',
134 'title' => ts('Limit To Current User'),
135 'type' => CRM_Utils_Type::T_INT,
136 'operatorType' => CRM_Report_Form::OP_SELECT,
137 'options' => array('0' => ts('No'), '1' => ts('Yes')),
6a488035
TO
138 ),
139 ),
af9b09df
TO
140 'grouping' => 'contact-fields',
141 ),
142 'civicrm_email' => array(
143 'dao' => 'CRM_Core_DAO_Email',
144 'fields' => array(
145 'contact_source_email' => array(
146 'name' => 'email',
147 'title' => ts('Source Contact Email'),
148 'alias' => 'civicrm_email_source',
6a488035 149 ),
af9b09df
TO
150 'contact_assignee_email' => array(
151 'name' => 'email',
152 'title' => ts('Assignee Contact Email'),
153 'alias' => 'civicrm_email_assignee',
6a488035 154 ),
af9b09df
TO
155 'contact_target_email' => array(
156 'name' => 'email',
157 'title' => ts('Target Contact Email'),
158 'alias' => 'civicrm_email_target',
6a488035
TO
159 ),
160 ),
af9b09df
TO
161 'order_bys' => array(
162 'source_contact_email' => array(
163 'name' => 'email',
164 'title' => ts('Source Contact Email'),
165 'dbAlias' => 'civicrm_email_contact_source_email',
6a488035
TO
166 ),
167 ),
af9b09df
TO
168 ),
169 'civicrm_activity' => array(
170 'dao' => 'CRM_Activity_DAO_Activity',
171 'fields' => array(
172 'id' => array(
173 'no_display' => TRUE,
174 'title' => ts('Activity ID'),
175 'required' => TRUE,
176 ),
177 'source_record_id' => array(
178 'no_display' => TRUE,
179 'required' => TRUE,
180 ),
181 'activity_type_id' => array(
182 'title' => ts('Activity Type'),
183 'required' => TRUE,
184 'type' => CRM_Utils_Type::T_STRING,
185 ),
186 'activity_subject' => array(
187 'title' => ts('Subject'),
188 'default' => TRUE,
189 ),
190 'activity_date_time' => array(
191 'title' => ts('Activity Date'),
192 'required' => TRUE,
193 ),
194 'status_id' => array(
195 'title' => ts('Activity Status'),
196 'default' => TRUE,
197 'type' => CRM_Utils_Type::T_STRING,
198 ),
199 'duration' => array(
200 'title' => ts('Duration'),
201 'type' => CRM_Utils_Type::T_INT,
667abe3a 202 ),
1efec7ff
DG
203 'details' => array(
204 'title' => ts('Activity Details'),
af9b09df 205 ),
6a488035 206 ),
1efec7ff
DG
207 'filters' => array(
208 'activity_date_time' => array(
6a488035
TO
209 'default' => 'this.month',
210 'operatorType' => CRM_Report_Form::OP_DATE,
211 ),
af9b09df
TO
212 'activity_subject' => array('title' => ts('Activity Subject')),
213 'activity_type_id' => array(
214 'title' => ts('Activity Type'),
215 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
216 'options' => $this->activityTypes,
217 ),
218 'status_id' => array(
219 'title' => ts('Activity Status'),
220 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
221 'options' => CRM_Core_PseudoConstant::activityStatus(),
222 ),
1efec7ff
DG
223 'details' => array(
224 'title' => ts('Activity Details'),
225 'type' => CRM_Utils_Type::T_TEXT,
af9b09df
TO
226 ),
227 ),
228 'order_bys' => array(
229 'activity_date_time' => array(
230 'title' => ts('Activity Date'),
231 'default_weight' => '1',
232 'dbAlias' => 'civicrm_activity_activity_date_time',
233 ),
234 'activity_type_id' => array(
235 'title' => ts('Activity Type'),
236 'default_weight' => '2',
56bbb442 237 'dbAlias' => 'field(civicrm_activity_activity_type_id, ' . implode(', ', array_keys($this->activityTypes)) . ')',
af9b09df
TO
238 ),
239 ),
240 'grouping' => 'activity-fields',
241 'alias' => 'activity',
242 ),
56bbb442 243 // Hack to get $this->_alias populated for the table.
af9b09df
TO
244 'civicrm_activity_contact' => array(
245 'dao' => 'CRM_Activity_DAO_ActivityContact',
a0375fa3 246 'fields' => array(),
247 ),
248 ) + $this->addressFields(TRUE);
6a488035
TO
249
250 if ($campaignEnabled) {
251 // Add display column and filter for Survey Results, Campaign and Engagement Index if CiviCampaign is enabled
252
253 $this->_columns['civicrm_activity']['fields']['result'] = array(
254 'title' => 'Survey Result',
255 'default' => 'false',
256 );
9d72cede
EM
257 $this->_columns['civicrm_activity']['filters']['result'] = array(
258 'title' => ts('Survey Result'),
6a488035
TO
259 'operator' => 'like',
260 'type' => CRM_Utils_Type::T_STRING,
261 );
262 if (!empty($this->activeCampaigns)) {
263 $this->_columns['civicrm_activity']['fields']['campaign_id'] = array(
264 'title' => 'Campaign',
265 'default' => 'false',
266 );
9d72cede
EM
267 $this->_columns['civicrm_activity']['filters']['campaign_id'] = array(
268 'title' => ts('Campaign'),
6a488035
TO
269 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
270 'options' => $this->activeCampaigns,
271 );
272 }
273 if (!empty($this->engagementLevels)) {
274 $this->_columns['civicrm_activity']['fields']['engagement_level'] = array(
275 'title' => 'Engagement Index',
276 'default' => 'false',
277 );
9d72cede
EM
278 $this->_columns['civicrm_activity']['filters']['engagement_level'] = array(
279 'title' => ts('Engagement Index'),
6a488035
TO
280 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
281 'options' => $this->engagementLevels,
282 );
283 }
284 }
285 $this->_groupFilter = TRUE;
286 $this->_tagFilter = TRUE;
ed795723 287 $this->_tagFilterTable = 'civicrm_activity';
6a488035
TO
288 parent::__construct();
289 }
290
be2e0c6a
TO
291 /**
292 * Adding address fields with dbAlias for order clause.
ab432335
EM
293 *
294 * @param bool $orderBy
295 *
a6c01b45 296 * @return array
ab432335 297 * Address fields
667abe3a 298 */
00be9182 299 public function addressFields($orderBy = FALSE) {
667abe3a 300 $address = parent::addAddressFields(FALSE, TRUE);
301 if ($orderBy) {
302 foreach ($address['civicrm_address']['order_bys'] as $fieldName => $field) {
303 $address['civicrm_address']['order_bys'][$fieldName]['dbAlias'] = "civicrm_address_{$fieldName}";
304 }
305 }
306 return $address;
307 }
308
74cf4551 309 /**
a0375fa3 310 * Build select clause.
311 *
74cf4551
EM
312 * @param null $recordType
313 */
00be9182 314 public function select($recordType = NULL) {
9d72cede
EM
315 if (!array_key_exists("contact_{$recordType}", $this->_params['fields']) &&
316 $recordType != 'final'
317 ) {
09febbae 318 $this->_nonDisplayFields[] = "civicrm_contact_contact_{$recordType}";
09febbae 319 }
1f220d30 320 parent::select();
1f220d30 321
09febbae 322 if ($recordType == 'final' && !empty($this->_nonDisplayFields)) {
323 foreach ($this->_nonDisplayFields as $fieldName) {
324 unset($this->_columnHeaders[$fieldName]);
325 }
326 }
327
1f220d30
DS
328 if (empty($this->_selectAliasesTotal)) {
329 $this->_selectAliasesTotal = $this->_selectAliases;
330 }
331
332 $removeKeys = array();
333 if ($recordType == 'target') {
334 foreach ($this->_selectClauses as $key => $clause) {
7116d719 335 if (strstr($clause, 'civicrm_contact_assignee.') ||
1f220d30
DS
336 strstr($clause, 'civicrm_contact_source.') ||
337 strstr($clause, 'civicrm_email_assignee.') ||
338 strstr($clause, 'civicrm_email_source.')
339 ) {
340 $removeKeys[] = $key;
341 unset($this->_selectClauses[$key]);
342 }
343 }
9d72cede 344 }
4c9b6178 345 elseif ($recordType == 'assignee') {
1f220d30 346 foreach ($this->_selectClauses as $key => $clause) {
7116d719 347 if (strstr($clause, 'civicrm_contact_target.') ||
1f220d30
DS
348 strstr($clause, 'civicrm_contact_source.') ||
349 strstr($clause, 'civicrm_email_target.') ||
482691e1 350 strstr($clause, 'civicrm_email_source.')
1f220d30
DS
351 ) {
352 $removeKeys[] = $key;
353 unset($this->_selectClauses[$key]);
354 }
355 }
9d72cede 356 }
4c9b6178 357 elseif ($recordType == 'source') {
1f220d30 358 foreach ($this->_selectClauses as $key => $clause) {
7116d719 359 if (strstr($clause, 'civicrm_contact_target.') ||
1f220d30
DS
360 strstr($clause, 'civicrm_contact_assignee.') ||
361 strstr($clause, 'civicrm_email_target.') ||
482691e1 362 strstr($clause, 'civicrm_email_assignee.')
1f220d30
DS
363 ) {
364 $removeKeys[] = $key;
365 unset($this->_selectClauses[$key]);
366 }
367 }
9d72cede 368 }
4c9b6178 369 elseif ($recordType == 'final') {
1f220d30
DS
370 $this->_selectClauses = $this->_selectAliasesTotal;
371 foreach ($this->_selectClauses as $key => $clause) {
7116d719 372 if (strstr($clause, 'civicrm_contact_contact_target') ||
1f220d30 373 strstr($clause, 'civicrm_contact_contact_assignee') ||
9d72cede
EM
374 strstr($clause, 'civicrm_contact_contact_source')
375 ) {
482691e1 376 $this->_selectClauses[$key] = "GROUP_CONCAT($clause SEPARATOR ';') as $clause";
6a488035
TO
377 }
378 }
379 }
380
1f220d30
DS
381 if ($recordType) {
382 foreach ($removeKeys as $key) {
383 unset($this->_selectAliases[$key]);
384 }
385
667abe3a 386 if ($recordType != 'final') {
387 foreach ($this->_columns['civicrm_address']['order_bys'] as $fieldName => $field) {
388 $orderByFld = $this->_columns['civicrm_address']['order_bys'][$fieldName];
389 $fldInfo = $this->_columns['civicrm_address']['fields'][$fieldName];
390 $this->_selectAliases[] = $orderByFld['dbAlias'];
391 $this->_selectClauses[] = "{$fldInfo['dbAlias']} as {$orderByFld['dbAlias']}";
392 }
667abe3a 393 $this->_selectAliases = array_unique($this->_selectAliases);
394 $this->_selectClauses = array_unique($this->_selectClauses);
395 }
1f220d30 396 $this->_select = "SELECT " . implode(', ', $this->_selectClauses) . " ";
1f220d30 397 }
6a488035
TO
398 }
399
74cf4551 400 /**
a0375fa3 401 * Build from clause.
402 *
403 * @param string $recordType
74cf4551 404 */
00be9182 405 public function from($recordType) {
e7e657f0 406 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
667abe3a 407 $activityTypeId = CRM_Core_DAO::getFieldValue("CRM_Core_DAO_OptionGroup", 'activity_type', 'id', 'name');
9e74e3ce 408 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
9d72cede
EM
409 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
410 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
6a488035 411
2f4b4d54
DS
412 if ($recordType == 'target') {
413 $this->_from = "
414 FROM civicrm_activity {$this->_aliases['civicrm_activity']}
1f220d30
DS
415 INNER JOIN civicrm_activity_contact {$this->_aliases['civicrm_activity_contact']}
416 ON {$this->_aliases['civicrm_activity']}.id = {$this->_aliases['civicrm_activity_contact']}.activity_id AND
417 {$this->_aliases['civicrm_activity_contact']}.record_type_id = {$targetID}
2f4b4d54 418 INNER JOIN civicrm_contact civicrm_contact_target
1f220d30 419 ON {$this->_aliases['civicrm_activity_contact']}.contact_id = civicrm_contact_target.id
2f4b4d54
DS
420 {$this->_aclFrom}";
421
422 if ($this->isTableSelected('civicrm_email')) {
423 $this->_from .= "
1f220d30
DS
424 LEFT JOIN civicrm_email civicrm_email_target
425 ON {$this->_aliases['civicrm_activity_contact']}.contact_id = civicrm_email_target.contact_id AND
426 civicrm_email_target.is_primary = 1";
2f4b4d54 427 }
1f220d30 428 $this->_aliases['civicrm_contact'] = 'civicrm_contact_target';
2f4b4d54
DS
429 }
430
431 if ($recordType == 'assignee') {
432 $this->_from = "
433 FROM civicrm_activity {$this->_aliases['civicrm_activity']}
1f220d30
DS
434 INNER JOIN civicrm_activity_contact {$this->_aliases['civicrm_activity_contact']}
435 ON {$this->_aliases['civicrm_activity']}.id = {$this->_aliases['civicrm_activity_contact']}.activity_id AND
436 {$this->_aliases['civicrm_activity_contact']}.record_type_id = {$assigneeID}
2f4b4d54 437 INNER JOIN civicrm_contact civicrm_contact_assignee
1f220d30 438 ON {$this->_aliases['civicrm_activity_contact']}.contact_id = civicrm_contact_assignee.id
2f4b4d54
DS
439 {$this->_aclFrom}";
440
441 if ($this->isTableSelected('civicrm_email')) {
442 $this->_from .= "
1f220d30
DS
443 LEFT JOIN civicrm_email civicrm_email_assignee
444 ON {$this->_aliases['civicrm_activity_contact']}.contact_id = civicrm_email_assignee.contact_id AND
445 civicrm_email_assignee.is_primary = 1";
2f4b4d54 446 }
482691e1 447 $this->_aliases['civicrm_contact'] = 'civicrm_contact_assignee';
2f4b4d54
DS
448 }
449
450 if ($recordType == 'source') {
451 $this->_from = "
452 FROM civicrm_activity {$this->_aliases['civicrm_activity']}
1f220d30
DS
453 INNER JOIN civicrm_activity_contact {$this->_aliases['civicrm_activity_contact']}
454 ON {$this->_aliases['civicrm_activity']}.id = {$this->_aliases['civicrm_activity_contact']}.activity_id AND
455 {$this->_aliases['civicrm_activity_contact']}.record_type_id = {$sourceID}
2f4b4d54 456 INNER JOIN civicrm_contact civicrm_contact_source
1f220d30 457 ON {$this->_aliases['civicrm_activity_contact']}.contact_id = civicrm_contact_source.id
2f4b4d54
DS
458 {$this->_aclFrom}";
459
460 if ($this->isTableSelected('civicrm_email')) {
461 $this->_from .= "
1f220d30
DS
462 LEFT JOIN civicrm_email civicrm_email_source
463 ON {$this->_aliases['civicrm_activity_contact']}.contact_id = civicrm_email_source.contact_id AND
464 civicrm_email_source.is_primary = 1";
2f4b4d54 465 }
482691e1 466 $this->_aliases['civicrm_contact'] = 'civicrm_contact_source';
6a488035 467 }
56bbb442 468
482691e1 469 $this->addAddressFromClause();
6a488035
TO
470 }
471
74cf4551 472 /**
a0375fa3 473 * Build where clause.
474 *
475 * @param string $recordType
74cf4551 476 */
00be9182 477 public function where($recordType = NULL) {
2f4b4d54 478 $this->_where = " WHERE {$this->_aliases['civicrm_activity']}.is_test = 0 AND
6a488035
TO
479 {$this->_aliases['civicrm_activity']}.is_deleted = 0 AND
480 {$this->_aliases['civicrm_activity']}.is_current_revision = 1";
481
482 $clauses = array();
483 foreach ($this->_columns as $tableName => $table) {
484 if (array_key_exists('filters', $table)) {
485
486 foreach ($table['filters'] as $fieldName => $field) {
487 $clause = NULL;
7116d719 488 if ($fieldName != 'contact_' . $recordType &&
489 (strstr($fieldName, '_target') ||
490 strstr($fieldName, '_assignee') ||
491 strstr($fieldName, '_source')
492 )
493 ) {
7116d719 494 continue;
495 }
6a488035
TO
496 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
497 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
9d72cede
EM
498 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
499 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
6a488035
TO
500
501 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
502 }
503 else {
504 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
389cfee7 505 if ($op && ($op != 'nnll' || $op != 'nll')) {
6a488035
TO
506 $clause = $this->whereClause($field,
507 $op,
508 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
509 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
510 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
511 );
9d72cede
EM
512 if ($fieldName == 'activity_type_id' &&
513 empty($this->_params['activity_type_id_value'])
514 ) {
42b3be07 515 $actTypes = array_flip(CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'label', TRUE));
6c552737 516 $clause = "( {$this->_aliases['civicrm_activity']}.activity_type_id IN (" .
9d72cede 517 implode(',', $actTypes) . ") )";
42b3be07 518 }
6a488035
TO
519 }
520 }
521
522 if ($field['name'] == 'current_user') {
9d72cede
EM
523 if (CRM_Utils_Array::value("{$fieldName}_value", $this->_params) ==
524 1
525 ) {
6a488035
TO
526 // get current user
527 $session = CRM_Core_Session::singleton();
528 if ($contactID = $session->get('userID')) {
389cfee7 529 $clause = "{$this->_aliases['civicrm_activity_contact']}.activity_id IN
530 (SELECT activity_id FROM civicrm_activity_contact WHERE contact_id = {$contactID})";
6a488035
TO
531 }
532 else {
533 $clause = NULL;
534 }
535 }
536 else {
537 $clause = NULL;
538 }
539 }
540 if (!empty($clause)) {
541 $clauses[] = $clause;
542 }
543 }
544 }
545 }
546
547 if (empty($clauses)) {
b6cab294 548 $this->_where .= " ";
6a488035
TO
549 }
550 else {
b6cab294 551 $this->_where .= " AND " . implode(' AND ', $clauses);
6a488035
TO
552 }
553
554 if ($this->_aclWhere) {
555 $this->_where .= " AND {$this->_aclWhere} ";
556 }
557 }
558
a0375fa3 559 /**
560 * Override group by function.
561 */
00be9182 562 public function groupBy() {
6a488035
TO
563 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_activity']}.id";
564 }
565
74cf4551 566 /**
a0375fa3 567 * Build ACL clause.
568 *
74cf4551
EM
569 * @param string $tableAlias
570 */
00be9182 571 public function buildACLClause($tableAlias = 'contact_a') {
2a3c101f 572 //override for ACL( Since Contact may be source
6a488035
TO
573 //contact/assignee or target also it may be null )
574
575 if (CRM_Core_Permission::check('view all contacts')) {
576 $this->_aclFrom = $this->_aclWhere = NULL;
577 return;
578 }
579
580 $session = CRM_Core_Session::singleton();
581 $contactID = $session->get('userID');
582 if (!$contactID) {
583 $contactID = 0;
584 }
585 $contactID = CRM_Utils_Type::escape($contactID, 'Integer');
586
587 CRM_Contact_BAO_Contact_Permission::cache($contactID);
588 $clauses = array();
589 foreach ($tableAlias as $k => $alias) {
590 $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 ";
591 }
592
593 $this->_aclFrom = implode(" ", $clauses);
594 $this->_aclWhere = NULL;
595 }
596
74cf4551 597 /**
100fef9d 598 * @param int $groupID
74cf4551
EM
599 *
600 * @throws Exception
601 */
00be9182 602 public function add2group($groupID) {
9a2f601e 603 if (CRM_Utils_Array::value("contact_target_op", $this->_params) == 'nll') {
604 CRM_Core_Error::fatal(ts('Current filter criteria didn\'t have any target contact to add to group'));
605 }
606
7f6464a0
JM
607 $new_select = 'AS addtogroup_contact_id';
608 $select = str_ireplace('AS civicrm_contact_contact_target_id', $new_select, $this->_select);
609 $new_having = ' addtogroup_contact_id';
610 $having = str_ireplace(' civicrm_contact_contact_target_id', $new_having, $this->_having);
611 $query = "$select
9a2f601e 612FROM civireport_activity_temp_target tar
7f6464a0 613GROUP BY civicrm_activity_id $having {$this->_orderBy}";
9a2f601e 614 $select = 'AS addtogroup_contact_id';
615 $query = str_ireplace('AS civicrm_contact_contact_target_id', $select, $query);
616 $dao = CRM_Core_DAO::executeQuery($query);
617
618 $contactIDs = array();
619 // Add resulting contacts to group
620 while ($dao->fetch()) {
621 if ($dao->addtogroup_contact_id) {
622 $contact_id = explode(';', $dao->addtogroup_contact_id);
623 if ($contact_id[0]) {
7bb16323 624 $contactIDs[$contact_id[0]] = $contact_id[0];
9a2f601e 625 }
626 }
627 }
628
9d72cede 629 if (!empty($contactIDs)) {
9a2f601e 630 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIDs, $groupID);
631 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
632 }
633 else {
634 CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
635 }
636 }
637
00be9182 638 public function postProcess() {
2f4b4d54
DS
639 $this->beginPostProcess();
640
389cfee7 641 //Assign those recordtype to array which have filter operator as 'Is not empty' or 'Is empty'
642 $nullFilters = array();
b6cab294 643 foreach (array('target', 'source', 'assignee') as $type) {
9d72cede
EM
644 if (CRM_Utils_Array::value("contact_{$type}_op", $this->_params) ==
645 'nnll' || !empty($this->_params["contact_{$type}_value"])
646 ) {
3ae89fd7 647 $nullFilters[] = " civicrm_contact_contact_{$type}_id IS NOT NULL ";
389cfee7 648 }
4c9b6178 649 elseif (CRM_Utils_Array::value("contact_{$type}_op", $this->_params) ==
9d72cede
EM
650 'nll'
651 ) {
3ae89fd7 652 $nullFilters[] = " civicrm_contact_contact_{$type}_id IS NULL ";
b6cab294 653 }
654 }
655
9d72cede 656 // 1. fill temp table with target results
6e5e50a9 657 $this->buildACLClause(array('civicrm_contact_target'));
1f220d30 658 $this->select('target');
2f4b4d54 659 $this->from('target');
5b1ba2b8 660 $this->customDataFrom();
389cfee7 661 $this->where('target');
1f220d30 662 $insertCols = implode(',', $this->_selectAliases);
9d72cede 663 $tempQuery = "CREATE TEMPORARY TABLE civireport_activity_temp_target CHARACTER SET utf8 COLLATE utf8_unicode_ci AS
482691e1 664{$this->_select} {$this->_from} {$this->_where} ";
2f4b4d54 665 CRM_Core_DAO::executeQuery($tempQuery);
2f4b4d54 666
1f220d30
DS
667 // 2. add new columns to hold assignee and source results
668 // fixme: add when required
669 $tempQuery = "
670 ALTER TABLE civireport_activity_temp_target
671 ADD COLUMN civicrm_contact_contact_assignee VARCHAR(128),
672 ADD COLUMN civicrm_contact_contact_source VARCHAR(128),
7116d719 673 ADD COLUMN civicrm_contact_contact_assignee_id VARCHAR(128),
482691e1 674 ADD COLUMN civicrm_contact_contact_source_id VARCHAR(128),
1f220d30
DS
675 ADD COLUMN civicrm_email_contact_assignee_email VARCHAR(128),
676 ADD COLUMN civicrm_email_contact_source_email VARCHAR(128)";
677 CRM_Core_DAO::executeQuery($tempQuery);
678
679 // 3. fill temp table with assignee results
6e5e50a9 680 $this->buildACLClause(array('civicrm_contact_assignee'));
389cfee7 681 $this->select('assignee');
682 $this->from('assignee');
683 $this->customDataFrom();
684 $this->where('assignee');
685 $insertCols = implode(',', $this->_selectAliases);
9d72cede 686 $tempQuery = "INSERT INTO civireport_activity_temp_target ({$insertCols})
1f220d30 687{$this->_select}
83e74860 688{$this->_from} {$this->_where}";
389cfee7 689 CRM_Core_DAO::executeQuery($tempQuery);
2f4b4d54 690
1f220d30 691 // 4. fill temp table with source results
6e5e50a9 692 $this->buildACLClause(array('civicrm_contact_source'));
389cfee7 693 $this->select('source');
694 $this->from('source');
695 $this->customDataFrom();
696 $this->where('source');
697 $insertCols = implode(',', $this->_selectAliases);
9d72cede 698 $tempQuery = "INSERT INTO civireport_activity_temp_target ({$insertCols})
1f220d30 699{$this->_select}
83e74860 700{$this->_from} {$this->_where}";
389cfee7 701 CRM_Core_DAO::executeQuery($tempQuery);
2f4b4d54 702
1f220d30 703 // 5. show final result set from temp table
2f4b4d54 704 $rows = array();
1f220d30 705 $this->select('final');
389cfee7 706 $this->_having = "";
707 if (!empty($nullFilters)) {
708 $this->_having = "HAVING " . implode(' AND ', $nullFilters);
709 }
83e74860 710 $this->orderBy();
1f220d30 711 $this->limit();
7116d719 712 $sql = "{$this->_select}
713FROM civireport_activity_temp_target tar
389cfee7 714GROUP BY civicrm_activity_id {$this->_having} {$this->_orderBy} {$this->_limit}";
2f4b4d54
DS
715 $this->buildRows($sql, $rows);
716
717 // format result set.
1f220d30 718 $this->formatDisplay($rows);
2f4b4d54
DS
719
720 // assign variables to templates
721 $this->doTemplateAssignment($rows);
722
723 // do print / pdf / instance stuff if needed
724 $this->endPostProcess($rows);
6a488035
TO
725 }
726
74cf4551 727 /**
4b62bc4f
EM
728 * Alter display of rows.
729 *
730 * Iterate through the rows retrieved via SQL and make changes for display purposes,
731 * such as rendering contacts as links.
732 *
733 * @param array $rows
734 * Rows generated by SQL, with an array for each row.
74cf4551 735 */
00be9182 736 public function alterDisplay(&$rows) {
9d72cede
EM
737 $entryFound = FALSE;
738 $activityType = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6a488035 739 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
9d72cede 740 $viewLinks = FALSE;
9d72cede
EM
741 $context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'report');
742 $actUrl = '';
6a488035
TO
743
744 if (CRM_Core_Permission::check('access CiviCRM')) {
9d72cede
EM
745 $viewLinks = TRUE;
746 $onHover = ts('View Contact Summary for this Contact');
6a488035
TO
747 $onHoverAct = ts('View Activity Record');
748 }
6a488035 749
38ba593b 750 foreach ($rows as $rowNum => $row) {
1efec7ff 751 // if we have an activity type, format the View Activity link for use in various columns
9d72cede
EM
752 if ($viewLinks &&
753 array_key_exists('civicrm_activity_activity_type_id', $row)
754 ) {
1efec7ff
DG
755 // Check for target contact id(s) and use the first contact id in that list for view activity link if found,
756 // else use source contact id
757 if (!empty($rows[$rowNum]['civicrm_contact_contact_target_id'])) {
758 $targets = explode(';', $rows[$rowNum]['civicrm_contact_contact_target_id']);
759 $cid = $targets[0];
760 }
761 else {
762 $cid = $rows[$rowNum]['civicrm_contact_contact_source_id'];
763 }
764
765 $actActionLinks = CRM_Activity_Selector_Activity::actionLinks($row['civicrm_activity_activity_type_id'],
766 CRM_Utils_Array::value('civicrm_activity_source_record_id', $rows[$rowNum]),
767 FALSE,
768 $rows[$rowNum]['civicrm_activity_id']
769 );
770
771 $actLinkValues = array(
772 'id' => $rows[$rowNum]['civicrm_activity_id'],
773 'cid' => $cid,
774 'cxt' => $context,
775 );
776 $actUrl = CRM_Utils_System::url($actActionLinks[CRM_Core_Action::VIEW]['url'],
777 CRM_Core_Action::replace($actActionLinks[CRM_Core_Action::VIEW]['qs'], $actLinkValues), TRUE
778 );
779 }
780
482691e1
RN
781 if (array_key_exists('civicrm_contact_contact_source', $row)) {
782 if ($value = $row['civicrm_contact_contact_source_id']) {
783 if ($viewLinks) {
784 $url = CRM_Utils_System::url("civicrm/contact/view",
785 'reset=1&cid=' . $value,
786 $this->_absoluteUrl
787 );
788 $rows[$rowNum]['civicrm_contact_contact_source_link'] = $url;
789 $rows[$rowNum]['civicrm_contact_contact_source_hover'] = $onHover;
790 }
791 $entryFound = TRUE;
792 }
793 }
794
795 if (array_key_exists('civicrm_contact_contact_assignee', $row)) {
796 $assigneeNames = explode(';', $row['civicrm_contact_contact_assignee']);
797 if ($value = $row['civicrm_contact_contact_assignee_id']) {
798 $assigneeContactIds = explode(';', $value);
799 $link = array();
800 if ($viewLinks) {
801 foreach ($assigneeContactIds as $id => $value) {
802 if (isset($value) && isset($assigneeNames[$id])) {
803 $url = CRM_Utils_System::url("civicrm/contact/view",
804 'reset=1&cid=' . $value,
805 $this->_absoluteUrl
806 );
9d72cede
EM
807 $link[] = "<a title='" . $onHover . "' href='" . $url .
808 "'>{$assigneeNames[$id]}</a>";
482691e1
RN
809 }
810 }
811 $rows[$rowNum]['civicrm_contact_contact_assignee'] = implode('; ', $link);
812 }
813 $entryFound = TRUE;
814 }
815 }
816
817 if (array_key_exists('civicrm_contact_contact_target', $row)) {
818 $targetNames = explode(';', $row['civicrm_contact_contact_target']);
819 if ($value = $row['civicrm_contact_contact_target_id']) {
820 $targetContactIds = explode(';', $value);
821 $link = array();
822 if ($viewLinks) {
823 foreach ($targetContactIds as $id => $value) {
824 if (isset($value) && isset($targetNames[$id])) {
825 $url = CRM_Utils_System::url("civicrm/contact/view",
826 'reset=1&cid=' . $value,
827 $this->_absoluteUrl
828 );
9d72cede
EM
829 $link[] = "<a title='" . $onHover . "' href='" . $url .
830 "'>{$targetNames[$id]}</a>";
482691e1
RN
831 }
832 }
833 $rows[$rowNum]['civicrm_contact_contact_target'] = implode('; ', $link);
834 }
835 $entryFound = TRUE;
836 }
837 }
838
6a488035
TO
839 if (array_key_exists('civicrm_activity_activity_type_id', $row)) {
840 if ($value = $row['civicrm_activity_activity_type_id']) {
841 $rows[$rowNum]['civicrm_activity_activity_type_id'] = $activityType[$value];
482691e1 842 if ($viewLinks) {
1efec7ff 843 $rows[$rowNum]['civicrm_activity_activity_type_id_link'] = $actUrl;
482691e1
RN
844 $rows[$rowNum]['civicrm_activity_activity_type_id_hover'] = $onHoverAct;
845 }
6a488035
TO
846 $entryFound = TRUE;
847 }
848 }
849
850 if (array_key_exists('civicrm_activity_status_id', $row)) {
851 if ($value = $row['civicrm_activity_status_id']) {
852 $rows[$rowNum]['civicrm_activity_status_id'] = $activityStatus[$value];
853 $entryFound = TRUE;
854 }
855 }
856
34e0bdb6 857 if (array_key_exists('civicrm_activity_details', $row) && $this->_outputMode == 'html') {
1efec7ff
DG
858 if ($value = $row['civicrm_activity_details']) {
859 $fullDetails = $rows[$rowNum]['civicrm_activity_details'];
860 $rows[$rowNum]['civicrm_activity_details'] = substr($fullDetails, 0, strrpos(substr($fullDetails, 0, 80), ' '));
861 if ($actUrl) {
6e5e50a9 862 $rows[$rowNum]['civicrm_activity_details'] .= " <a href='{$actUrl}' title='{$onHoverAct}'>(more)</a>";
1efec7ff
DG
863 }
864 $entryFound = TRUE;
865 }
866 }
867
6a488035
TO
868 if (array_key_exists('civicrm_activity_campaign_id', $row)) {
869 if ($value = $row['civicrm_activity_campaign_id']) {
870 $rows[$rowNum]['civicrm_activity_campaign_id'] = $this->activeCampaigns[$value];
871 $entryFound = TRUE;
872 }
873 }
874
875 if (array_key_exists('civicrm_activity_engagement_level', $row)) {
876 if ($value = $row['civicrm_activity_engagement_level']) {
877 $rows[$rowNum]['civicrm_activity_engagement_level'] = $this->engagementLevels[$value];
878 $entryFound = TRUE;
879 }
880 }
881
9d72cede
EM
882 if (array_key_exists('civicrm_activity_activity_date_time', $row) &&
883 array_key_exists('civicrm_activity_status_id', $row)
884 ) {
6a488035
TO
885 if (CRM_Utils_Date::overdue($rows[$rowNum]['civicrm_activity_activity_date_time']) &&
886 $activityStatus[$row['civicrm_activity_status_id']] != 'Completed'
887 ) {
888 $rows[$rowNum]['class'] = "status-overdue";
889 $entryFound = TRUE;
890 }
891 }
892
482691e1
RN
893 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'activity', 'List all activities for this ') ? TRUE : $entryFound;
894
6a488035
TO
895 if (!$entryFound) {
896 break;
897 }
898 }
899 }
667abe3a 900
00be9182 901 public function sectionTotals() {
667abe3a 902 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
903 if (empty($this->_selectAliases)) {
904 return;
905 }
906
907 if (!empty($this->_sections)) {
908 // pull section aliases out of $this->_sections
909 $sectionAliases = array_keys($this->_sections);
910
911 $ifnulls = array();
912 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
913 $ifnulls[] = "ifnull($alias, '') as $alias";
914 }
915
916 $query = "select " . implode(", ", $ifnulls) .
e13b3d8e 917 ", count(DISTINCT civicrm_activity_id) as ct from civireport_activity_temp_target group by " .
667abe3a 918 implode(", ", $sectionAliases);
919
920 // initialize array of total counts
921 $totals = array();
922 $dao = CRM_Core_DAO::executeQuery($query);
923 while ($dao->fetch()) {
924 // let $this->_alterDisplay translate any integer ids to human-readable values.
925 $rows[0] = $dao->toArray();
926 $this->alterDisplay($rows);
927 $row = $rows[0];
928
929 // add totals for all permutations of section values
930 $values = array();
931 $i = 1;
932 $aliasCount = count($sectionAliases);
933 foreach ($sectionAliases as $alias) {
934 $values[] = $row[$alias];
935 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
936 if ($i == $aliasCount) {
937 // the last alias is the lowest-level section header; use count as-is
938 $totals[$key] = $dao->ct;
939 }
940 else {
941 // other aliases are higher level; roll count into their total
942 $totals[$key] += $dao->ct;
943 }
944 }
945 }
946 $this->assign('sectionTotals', $totals);
947 }
948 }
96025800 949
6a488035 950}