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