-
-
Notifications
You must be signed in to change notification settings - Fork 824
/
Copy pathActivity.php
1190 lines (1093 loc) · 44 KB
/
Activity.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
class CRM_Report_Form_Activity extends CRM_Report_Form {
protected $_selectAliasesTotal = [];
protected $_customGroupExtends = [
'Activity',
];
protected $_nonDisplayFields = [];
/**
* This report has not been optimised for group filtering.
*
* The functionality for group filtering has been improved but not
* all reports have been adjusted to take care of it. This report has not
* and will run an inefficient query until fixed.
*
* CRM-19170
*
* @var bool
*/
protected $groupFilterNotOptimised = TRUE;
/**
* Class constructor.
*/
public function __construct() {
// There could be multiple contacts. We not clear on which contact id to display.
// Lets hide it for now.
$this->_exposeContactID = FALSE;
// if navigated from count link of activity summary reports.
$this->_resetDateFilter = CRM_Utils_Request::retrieve('resetDateFilter', 'Boolean');
$config = CRM_Core_Config::singleton();
$campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
$caseEnabled = in_array("CiviCase", $config->enableComponents);
if ($campaignEnabled) {
$this->engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel();
}
$components = CRM_Core_Component::getEnabledComponents();
foreach ($components as $componentName => $componentInfo) {
// CRM-19201: Add support for reporting CiviCampaign activities
// For CiviCase, "access all cases and activities" is required here
// rather than "access my cases and activities" to prevent those with
// only the later permission from seeing a list of all cases which might
// present a privacy issue.
if (CRM_Core_Permission::access($componentName, TRUE, TRUE)) {
$accessAllowed[] = $componentInfo->componentID;
}
}
$include = '';
if (!empty($accessAllowed)) {
$include = 'OR v.component_id IN (' . implode(', ', $accessAllowed) . ')';
}
$condition = " AND ( v.component_id IS NULL {$include} )";
$this->activityTypes = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $condition);
asort($this->activityTypes);
// @todo split the 3 different contact tables into their own array items.
// this will massively simplify the needs of this report.
$this->_columns = [
'civicrm_contact' => [
'dao' => 'CRM_Contact_DAO_Contact',
'fields' => [
'contact_source' => [
'name' => 'sort_name',
'title' => ts('Source Name'),
'alias' => 'civicrm_contact_source',
'no_repeat' => TRUE,
],
'contact_assignee' => [
'name' => 'sort_name',
'title' => ts('Assignee Name'),
'alias' => 'civicrm_contact_assignee',
'dbAlias' => "civicrm_contact_assignee.sort_name",
'default' => TRUE,
],
'contact_target' => [
'name' => 'sort_name',
'title' => ts('Target Name'),
'alias' => 'civicrm_contact_target',
'dbAlias' => "civicrm_contact_target.sort_name",
'default' => TRUE,
],
'contact_source_id' => [
'name' => 'id',
'alias' => 'civicrm_contact_source',
'dbAlias' => "civicrm_contact_source.id",
'no_display' => TRUE,
'default' => TRUE,
'required' => TRUE,
],
'contact_assignee_id' => [
'name' => 'id',
'alias' => 'civicrm_contact_assignee',
'dbAlias' => "civicrm_contact_assignee.id",
'no_display' => TRUE,
'default' => TRUE,
'required' => TRUE,
],
'contact_target_id' => [
'name' => 'id',
'alias' => 'civicrm_contact_target',
'dbAlias' => "civicrm_contact_target.id",
'no_display' => TRUE,
'default' => TRUE,
'required' => TRUE,
],
],
'filters' => [
'contact_source' => [
'name' => 'sort_name',
'alias' => 'civicrm_contact_source',
'title' => ts('Source Name'),
'operator' => 'like',
'type' => CRM_Report_Form::OP_STRING,
],
'contact_assignee' => [
'name' => 'sort_name',
'alias' => 'civicrm_contact_assignee',
'title' => ts('Assignee Name'),
'operator' => 'like',
'type' => CRM_Report_Form::OP_STRING,
],
'contact_target' => [
'name' => 'sort_name',
'alias' => 'civicrm_contact_target',
'title' => ts('Target Name'),
'operator' => 'like',
'type' => CRM_Report_Form::OP_STRING,
],
'current_user' => [
'name' => 'current_user',
'title' => ts('Limit To Current User'),
'type' => CRM_Utils_Type::T_INT,
'operatorType' => CRM_Report_Form::OP_SELECT,
'options' => ['0' => ts('No'), '1' => ts('Yes')],
],
],
'grouping' => 'contact-fields',
],
'civicrm_email' => [
'dao' => 'CRM_Core_DAO_Email',
'fields' => [
'contact_source_email' => [
'name' => 'email',
'title' => ts('Source Email'),
'alias' => 'civicrm_email_source',
],
'contact_assignee_email' => [
'name' => 'email',
'title' => ts('Assignee Email'),
'alias' => 'civicrm_email_assignee',
],
'contact_target_email' => [
'name' => 'email',
'title' => ts('Target Email'),
'alias' => 'civicrm_email_target',
],
],
'order_bys' => [
'source_contact_email' => [
'name' => 'email',
'title' => ts('Source Email'),
'dbAlias' => 'civicrm_email_contact_source_email',
],
],
],
'civicrm_phone' => [
'dao' => 'CRM_Core_DAO_Phone',
'fields' => [
'contact_source_phone' => [
'name' => 'phone',
'title' => ts('Source Phone'),
'alias' => 'civicrm_phone_source',
],
'contact_assignee_phone' => [
'name' => 'phone',
'title' => ts('Assignee Phone'),
'alias' => 'civicrm_phone_assignee',
],
'contact_target_phone' => [
'name' => 'phone',
'title' => ts('Target Phone'),
'alias' => 'civicrm_phone_target',
],
],
],
'civicrm_activity' => [
'dao' => 'CRM_Activity_DAO_Activity',
'fields' => [
'id' => [
'no_display' => TRUE,
'title' => ts('Activity ID'),
'required' => TRUE,
],
'source_record_id' => [
'no_display' => TRUE,
'required' => TRUE,
],
'activity_type_id' => [
'title' => ts('Activity Type'),
'required' => TRUE,
'type' => CRM_Utils_Type::T_STRING,
],
'activity_subject' => [
'title' => ts('Subject'),
'default' => TRUE,
],
'activity_date_time' => [
'title' => ts('Activity Date'),
'required' => TRUE,
],
'status_id' => [
'title' => ts('Activity Status'),
'default' => TRUE,
'type' => CRM_Utils_Type::T_STRING,
],
'duration' => [
'title' => ts('Duration'),
'type' => CRM_Utils_Type::T_INT,
],
'location' => [
'title' => ts('Location'),
'type' => CRM_Utils_Type::T_STRING,
],
'details' => [
'title' => ts('Activity Details'),
],
'priority_id' => [
'title' => ts('Priority'),
'default' => TRUE,
'type' => CRM_Utils_Type::T_STRING,
],
],
'filters' => [
'activity_date_time' => [
'default' => 'this.month',
'operatorType' => CRM_Report_Form::OP_DATE,
],
'activity_subject' => ['title' => ts('Activity Subject')],
'activity_type_id' => [
'title' => ts('Activity Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => $this->activityTypes,
],
'status_id' => [
'title' => ts('Activity Status'),
'type' => CRM_Utils_Type::T_STRING,
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_PseudoConstant::activityStatus(),
],
'location' => [
'title' => ts('Location'),
'type' => CRM_Utils_Type::T_TEXT,
],
'details' => [
'title' => ts('Activity Details'),
'type' => CRM_Utils_Type::T_TEXT,
],
'priority_id' => [
'title' => ts('Activity Priority'),
'type' => CRM_Utils_Type::T_STRING,
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id'),
],
],
'order_bys' => [
'activity_date_time' => [
'title' => ts('Activity Date'),
'default_weight' => '1',
'dbAlias' => 'civicrm_activity_activity_date_time',
],
'activity_type_id' => [
'title' => ts('Activity Type'),
'default_weight' => '2',
'dbAlias' => 'field(civicrm_activity_activity_type_id, ' . implode(', ', array_keys($this->activityTypes)) . ')',
],
],
'grouping' => 'activity-fields',
'alias' => 'activity',
],
// Hack to get $this->_alias populated for the table.
'civicrm_activity_contact' => [
'dao' => 'CRM_Activity_DAO_ActivityContact',
'fields' => [],
],
] + $this->addressFields(TRUE);
if ($caseEnabled && CRM_Core_Permission::check('access all cases and activities')) {
$this->_columns['civicrm_activity']['filters']['include_case_activities'] = [
'name' => 'include_case_activities',
'title' => ts('Include Case Activities'),
'type' => CRM_Utils_Type::T_INT,
'operatorType' => CRM_Report_Form::OP_SELECT,
'options' => ['0' => ts('No'), '1' => ts('Yes')],
];
}
if ($campaignEnabled) {
// Add display column and filter for Survey Results, Campaign and Engagement Index if CiviCampaign is enabled
$this->_columns['civicrm_activity']['fields']['result'] = [
'title' => ts('Survey Result'),
'default' => 'false',
];
$this->_columns['civicrm_activity']['filters']['result'] = [
'title' => ts('Survey Result'),
'operator' => 'like',
'type' => CRM_Utils_Type::T_STRING,
];
// If we have campaigns enabled, add those elements to both the fields, filters.
$this->addCampaignFields('civicrm_activity');
if (!empty($this->engagementLevels)) {
$this->_columns['civicrm_activity']['fields']['engagement_level'] = [
'title' => ts('Engagement Index'),
'default' => 'false',
];
$this->_columns['civicrm_activity']['filters']['engagement_level'] = [
'title' => ts('Engagement Index'),
'type' => CRM_Utils_Type::T_INT,
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => $this->engagementLevels,
];
}
}
$this->_groupFilter = TRUE;
$this->_tagFilter = TRUE;
$this->_tagFilterTable = 'civicrm_activity';
parent::__construct();
}
protected static function addCaseActivityColumns($columns) {
$columns['civicrm_case_activity'] = [
'dao' => 'CRM_Case_DAO_CaseActivity',
'fields' => [
'case_id' => [
'no_display' => TRUE,
'required' => TRUE,
],
],
];
return $columns;
}
public function preProcess() {
// Is "Include Case Activities" selected? If yes, include the case_id as a hidden column
$formToUse = $this->noController ? NULL : $this;
$includeCaseActivities = CRM_Utils_Request::retrieve('include_case_activities_value', 'Boolean', $formToUse);
if (!empty($includeCaseActivities)) {
$this->_columns = self::addCaseActivityColumns($this->_columns);
}
parent::preProcess();
}
/**
* Adding address fields with dbAlias for order clause.
*
* @param bool $orderBy
*
* @return array
* Address fields
*/
public function addressFields($orderBy = FALSE) {
$address = parent::addAddressFields(FALSE, TRUE);
if ($orderBy) {
foreach ($address['civicrm_address']['order_bys'] as $fieldName => $field) {
$address['civicrm_address']['order_bys'][$fieldName]['dbAlias'] = "civicrm_address_{$fieldName}";
}
}
return $address;
}
/**
* Build select clause.
*
* @todo get rid of $recordType param. It's only because 3 separate contact tables
* are mis-declared as one that we need it.
*
* @param null $recordType deprecated
* Parameter to hack around the bad decision made in construct to misrepresent
* different tables as the same table.
*/
public function select($recordType = 'target') {
if (!array_key_exists("contact_{$recordType}", $this->_params['fields']) &&
$recordType != 'final'
) {
$this->_nonDisplayFields[] = "civicrm_contact_contact_{$recordType}";
}
parent::select();
if ($recordType == 'final' && !empty($this->_nonDisplayFields)) {
foreach ($this->_nonDisplayFields as $fieldName) {
unset($this->_columnHeaders[$fieldName]);
}
}
if (empty($this->_selectAliasesTotal)) {
$this->_selectAliasesTotal = $this->_selectAliases;
}
$removeKeys = [];
if ($recordType == 'target') {
// @todo - fix up the way the tables are declared in construct & remove this.
foreach ($this->_selectClauses as $key => $clause) {
if (strstr($clause, 'civicrm_contact_assignee.') ||
strstr($clause, 'civicrm_contact_source.') ||
strstr($clause, 'civicrm_email_assignee.') ||
strstr($clause, 'civicrm_email_source.') ||
strstr($clause, 'civicrm_phone_assignee.') ||
strstr($clause, 'civicrm_phone_source.')
) {
$removeKeys[] = $key;
unset($this->_selectClauses[$key]);
}
}
}
elseif ($recordType == 'assignee') {
// @todo - fix up the way the tables are declared in construct & remove this.
foreach ($this->_selectClauses as $key => $clause) {
if (strstr($clause, 'civicrm_contact_target.') ||
strstr($clause, 'civicrm_contact_source.') ||
strstr($clause, 'civicrm_email_target.') ||
strstr($clause, 'civicrm_email_source.') ||
strstr($clause, 'civicrm_phone_target.') ||
strstr($clause, 'civicrm_phone_source.') ||
strstr($clause, 'civicrm_address_')
) {
$removeKeys[] = $key;
unset($this->_selectClauses[$key]);
}
}
}
elseif ($recordType == 'source') {
// @todo - fix up the way the tables are declared in construct & remove this.
foreach ($this->_selectClauses as $key => $clause) {
if (strstr($clause, 'civicrm_contact_target.') ||
strstr($clause, 'civicrm_contact_assignee.') ||
strstr($clause, 'civicrm_email_target.') ||
strstr($clause, 'civicrm_email_assignee.') ||
strstr($clause, 'civicrm_phone_target.') ||
strstr($clause, 'civicrm_phone_assignee.') ||
strstr($clause, 'civicrm_address_')
) {
$removeKeys[] = $key;
unset($this->_selectClauses[$key]);
}
}
}
elseif ($recordType == 'final') {
$this->_selectClauses = $this->_selectAliasesTotal;
foreach ($this->_selectClauses as $key => $clause) {
// @todo - fix up the way the tables are declared in construct & remove this.
if (strstr($clause, 'civicrm_contact_contact_target') ||
strstr($clause, 'civicrm_contact_contact_assignee') ||
strstr($clause, 'civicrm_contact_contact_source') ||
strstr($clause, 'civicrm_phone_contact_source_phone') ||
strstr($clause, 'civicrm_phone_contact_assignee_phone') ||
strstr($clause, 'civicrm_email_contact_source_email') ||
strstr($clause, 'civicrm_email_contact_assignee_email') ||
strstr($clause, 'civicrm_email_contact_target_email') ||
strstr($clause, 'civicrm_phone_contact_target_phone') ||
strstr($clause, 'civicrm_address_')
) {
$this->_selectClauses[$key] = "GROUP_CONCAT(DISTINCT $clause SEPARATOR ';') as $clause";
}
}
}
if ($recordType) {
foreach ($removeKeys as $key) {
unset($this->_selectAliases[$key]);
}
if ($recordType == 'target') {
foreach ($this->_columns['civicrm_address']['order_bys'] as $fieldName => $field) {
$orderByFld = $this->_columns['civicrm_address']['order_bys'][$fieldName];
$fldInfo = $this->_columns['civicrm_address']['fields'][$fieldName];
$this->_selectAliases[] = $orderByFld['dbAlias'];
$this->_selectClauses[] = "{$fldInfo['dbAlias']} as {$orderByFld['dbAlias']}";
}
$this->_selectAliases = array_unique($this->_selectAliases);
$this->_selectClauses = array_unique($this->_selectClauses);
}
$this->_select = "SELECT " . implode(', ', $this->_selectClauses) . " ";
}
}
/**
* Build from clause.
* @todo remove this function & declare the 3 contact tables separately
*/
public function from() {
$this->buildFrom('target');
}
/**
* Build where clause.
*
* @todo get rid of $recordType param. It's only because 3 separate contact tables
* are mis-declared as one that we need it.
*
* @param string $recordType
*/
public function where($recordType = NULL) {
$this->_where = " WHERE {$this->_aliases['civicrm_activity']}.is_test = 0 AND
{$this->_aliases['civicrm_activity']}.is_deleted = 0 AND
{$this->_aliases['civicrm_activity']}.is_current_revision = 1";
$clauses = [];
foreach ($this->_columns as $tableName => $table) {
if (array_key_exists('filters', $table)) {
foreach ($table['filters'] as $fieldName => $field) {
$clause = NULL;
if ($fieldName != 'contact_' . $recordType &&
(strstr($fieldName, '_target') ||
strstr($fieldName, '_assignee') ||
strstr($fieldName, '_source')
)
) {
continue;
}
if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
$relative = $this->_params["{$fieldName}_relative"] ?? NULL;
$from = $this->_params["{$fieldName}_from"] ?? NULL;
$to = $this->_params["{$fieldName}_to"] ?? NULL;
$clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type']);
}
else {
$op = $this->_params["{$fieldName}_op"] ?? NULL;
if ($op && !($fieldName == "contact_{$recordType}" && ($op != 'nnll' || $op != 'nll'))) {
$clause = $this->whereClause($field,
$op,
CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
);
if ($field['name'] == 'include_case_activities') {
$clause = NULL;
}
if ($fieldName == 'activity_type_id' &&
empty($this->_params['activity_type_id_value'])
) {
if (empty($this->_params['include_case_activities_value'])) {
$this->activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'label', TRUE);
}
$actTypes = array_flip($this->activityTypes);
$clause = "( {$this->_aliases['civicrm_activity']}.activity_type_id IN (" .
implode(',', $actTypes) . ") )";
}
}
}
if ($field['name'] == 'current_user') {
if (CRM_Utils_Array::value("{$fieldName}_value", $this->_params) ==
1
) {
// get current user
$session = CRM_Core_Session::singleton();
if ($contactID = $session->get('userID')) {
$clause = "{$this->_aliases['civicrm_activity_contact']}.activity_id IN
(SELECT activity_id FROM civicrm_activity_contact WHERE contact_id = {$contactID})";
}
else {
$clause = NULL;
}
}
else {
$clause = NULL;
}
}
if (!empty($clause)) {
$clauses[] = $clause;
}
}
}
}
if (empty($clauses)) {
$this->_where .= " ";
}
else {
$this->_where .= " AND " . implode(' AND ', $clauses);
}
if ($this->_aclWhere) {
$this->_where .= " AND {$this->_aclWhere} ";
}
}
/**
* Override group by function.
*/
public function groupBy() {
$this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, "{$this->_aliases['civicrm_activity']}.id");
}
/**
* Build ACL clause.
*
* @param string $tableAlias
*/
public function buildACLClause($tableAlias = 'contact_a') {
//override for ACL( Since Contact may be source
//contact/assignee or target also it may be null )
if (CRM_Core_Permission::check('view all contacts')) {
$this->_aclFrom = $this->_aclWhere = NULL;
return;
}
$session = CRM_Core_Session::singleton();
$contactID = $session->get('userID');
if (!$contactID) {
$contactID = 0;
}
$contactID = CRM_Utils_Type::escape($contactID, 'Integer');
CRM_Contact_BAO_Contact_Permission::cache($contactID);
$clauses = [];
foreach ($tableAlias as $k => $alias) {
$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 ";
}
$this->_aclFrom = implode(" ", $clauses);
$this->_aclWhere = NULL;
}
/**
* @param int $groupID
*
* @throws Exception
*/
public function add2group($groupID) {
if (CRM_Utils_Array::value("contact_target_op", $this->_params) == 'nll') {
CRM_Core_Error::fatal(ts('Current filter criteria didn\'t have any target contact to add to group'));
}
$new_select = 'AS addtogroup_contact_id';
$select = str_ireplace('AS civicrm_contact_contact_target_id', $new_select, $this->_select);
$new_having = ' addtogroup_contact_id';
$having = str_ireplace(' civicrm_contact_contact_target_id', $new_having, $this->_having);
$query = "$select
FROM {$this->temporaryTables['activity_temp_table']['name']} tar
GROUP BY civicrm_activity_id $having {$this->_orderBy}";
$select = 'AS addtogroup_contact_id';
$query = str_ireplace('AS civicrm_contact_contact_target_id', $select, $query);
CRM_Core_DAO::disableFullGroupByMode();
$dao = $this->executeReportQuery($query);
CRM_Core_DAO::reenableFullGroupByMode();
$contactIDs = [];
// Add resulting contacts to group
while ($dao->fetch()) {
if ($dao->addtogroup_contact_id) {
$contact_id = explode(';', $dao->addtogroup_contact_id);
if ($contact_id[0]) {
$contactIDs[$contact_id[0]] = $contact_id[0];
}
}
}
if (!empty($contactIDs)) {
CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIDs, $groupID);
CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
}
else {
CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
}
}
/**
* @param $fields
* @param $files
* @param $self
*
* @return array
*/
public static function formRule($fields, $files, $self) {
$errors = [];
$config = CRM_Core_Config::singleton();
if (in_array("CiviCase", $config->enableComponents)) {
$componentId = CRM_Core_Component::getComponentID('CiviCase');
$caseActivityTypes = CRM_Core_OptionGroup::values('activity_type', TRUE, FALSE, FALSE, " AND v.component_id={$componentId}");
if (!empty($fields['activity_type_id_value']) && is_array($fields['activity_type_id_value']) && empty($fields['include_case_activities_value'])) {
foreach ($fields['activity_type_id_value'] as $activityTypeId) {
if (in_array($activityTypeId, $caseActivityTypes)) {
$errors['fields'] = ts("Please enable 'Include Case Activities' to filter with Case Activity types.");
}
}
}
}
return $errors;
}
/**
* @param $applyLimit
*
* @return string
*/
public function buildQuery($applyLimit = TRUE) {
$activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
$sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
//Assign those recordtype to array which have filter operator as 'Is not empty' or 'Is empty'
$nullFilters = [];
foreach (['target', 'source', 'assignee'] as $type) {
if (CRM_Utils_Array::value("contact_{$type}_op", $this->_params) ==
'nnll' || !empty($this->_params["contact_{$type}_value"])
) {
$nullFilters[] = " civicrm_contact_contact_{$type}_id IS NOT NULL ";
}
elseif (CRM_Utils_Array::value("contact_{$type}_op", $this->_params) ==
'nll'
) {
$nullFilters[] = " civicrm_contact_contact_{$type}_id IS NULL ";
}
}
if (!empty($this->_params['include_case_activities_value']) && array_key_exists('civicrm_case_activity', $this->_aliases) === FALSE) {
$columns = self::addCaseActivityColumns($this->_columns);
$this->setTableAlias($columns['civicrm_case_activity'], 'civicrm_case_activity');
$columns['civicrm_case_activity']['fields']['case_id']['dbAlias'] = $this->_aliases['civicrm_case_activity'] . '.case_id';
$this->_columns = $columns;
}
// @todo - all this temp table stuff is here because pre 4.4 the activity contact
// form did not exist.
// Fixing the way the construct method declares them will make all this redundant.
// 1. fill temp table with target results
$this->buildACLClause(['civicrm_contact_target']);
$this->select('target');
$this->from();
$this->customDataFrom();
$this->where('target');
$tempTableName = $this->createTemporaryTable('activity_temp_table', "{$this->_select} {$this->_from} {$this->_where}");
// 2. add new columns to hold assignee and source results
// fixme: add when required
$tempQuery = "
ALTER TABLE $tempTableName
MODIFY COLUMN civicrm_contact_contact_target_id VARCHAR(128),
ADD COLUMN civicrm_contact_contact_assignee VARCHAR(128),
ADD COLUMN civicrm_contact_contact_source VARCHAR(128),
ADD COLUMN civicrm_contact_contact_assignee_id VARCHAR(128),
ADD COLUMN civicrm_contact_contact_source_id VARCHAR(128),
ADD COLUMN civicrm_phone_contact_assignee_phone VARCHAR(128),
ADD COLUMN civicrm_phone_contact_source_phone VARCHAR(128),
ADD COLUMN civicrm_email_contact_assignee_email VARCHAR(128),
ADD COLUMN civicrm_email_contact_source_email VARCHAR(128)";
$this->executeReportQuery($tempQuery);
// 3. fill temp table with assignee results
$this->buildACLClause(['civicrm_contact_assignee']);
$this->select('assignee');
$this->buildAssigneeFrom();
$this->customDataFrom();
$this->where('assignee');
$insertCols = implode(',', $this->_selectAliases);
$tempQuery = "INSERT INTO $tempTableName ({$insertCols})
{$this->_select}
{$this->_from} {$this->_where}";
$this->executeReportQuery($tempQuery);
// 4. fill temp table with source results
$this->buildACLClause(['civicrm_contact_source']);
$this->select('source');
$this->buildSourceFrom();
$this->customDataFrom();
$this->where('source');
$insertCols = implode(',', $this->_selectAliases);
$tempQuery = "INSERT INTO $tempTableName ({$insertCols})
{$this->_select}
{$this->_from} {$this->_where}";
$this->executeReportQuery($tempQuery);
// 5. show final result set from temp table
$rows = [];
$this->select('final');
$this->_having = "";
if (!empty($nullFilters)) {
$this->_having = "HAVING " . implode(' AND ', $nullFilters);
}
$this->orderBy();
foreach ($this->_sections as $alias => $section) {
if (!empty($section) && $section['name'] == 'activity_date_time') {
$this->alterSectionHeaderForDateTime($tempTableName, $section['tplField']);
}
}
if ($applyLimit) {
$this->limit();
}
$groupByFromSelect = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, 'civicrm_activity_id');
$this->_where = " WHERE (1)";
$this->buildPermissionClause();
if ($this->_aclWhere) {
$this->_where .= " AND {$this->_aclWhere} ";
}
$caseJoin = '';
if (!empty($this->_params['include_case_activities_value'])) {
$caseJoin = "LEFT JOIN civicrm_case_activity {$this->_aliases['civicrm_case_activity']} ON {$this->_aliases['civicrm_activity']}.id = {$this->_aliases['civicrm_case_activity']}.activity_id";
}
$sql = "{$this->_select}
FROM $tempTableName tar
INNER JOIN civicrm_activity {$this->_aliases['civicrm_activity']} ON {$this->_aliases['civicrm_activity']}.id = tar.civicrm_activity_id
INNER JOIN civicrm_activity_contact {$this->_aliases['civicrm_activity_contact']} ON {$this->_aliases['civicrm_activity_contact']}.activity_id = {$this->_aliases['civicrm_activity']}.id
AND {$this->_aliases['civicrm_activity_contact']}.record_type_id = {$sourceID}
LEFT JOIN civicrm_contact contact_civireport ON contact_civireport.id = {$this->_aliases['civicrm_activity_contact']}.contact_id
{$caseJoin}
{$this->_where} {$groupByFromSelect} {$this->_having} {$this->_orderBy} {$this->_limit}";
CRM_Utils_Hook::alterReportVar('sql', $this, $this);
$this->addToDeveloperTab($sql);
return $sql;
}
public function postProcess() {
//reset value of activity_date
if (!empty($this->_resetDateFilter)) {
$this->_formValues["activity_date_time_relative"] = NULL;
}
$this->beginPostProcess();
$sql = $this->buildQuery(TRUE);
$this->buildRows($sql, $rows);
// format result set.
$this->formatDisplay($rows);
// assign variables to templates
$this->doTemplateAssignment($rows);
// do print / pdf / instance stuff if needed
$this->endPostProcess($rows);
}
/**
* Alter display of rows.
*
* Iterate through the rows retrieved via SQL and make changes for display purposes,
* such as rendering contacts as links.
*
* @param array $rows
* Rows generated by SQL, with an array for each row.
*/
public function alterDisplay(&$rows) {
$entryFound = FALSE;
$activityType = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
$activityStatus = CRM_Core_PseudoConstant::activityStatus();
$priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
$viewLinks = FALSE;
// Would we ever want to retrieve from the form controller??
$form = $this->noController ? NULL : $this;
$context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $form, FALSE, 'report');
$actUrl = '';
if (CRM_Core_Permission::check('access CiviCRM')) {
$viewLinks = TRUE;
$onHover = ts('View Contact Summary for this Contact');
$onHoverAct = ts('View Activity Record');
}
foreach ($rows as $rowNum => $row) {
// if we have an activity type, format the View Activity link for use in various columns
if ($viewLinks &&
array_key_exists('civicrm_activity_activity_type_id', $row)
) {
// Check for target contact id(s) and use the first contact id in that list for view activity link if found,
// else use source contact id
if (!empty($rows[$rowNum]['civicrm_contact_contact_target_id'])) {
$targets = explode(';', $rows[$rowNum]['civicrm_contact_contact_target_id']);
$cid = $targets[0];
}
else {
$cid = $rows[$rowNum]['civicrm_contact_contact_source_id'];
}
if (empty($this->_params['include_case_activities_value']) || empty($rows[$rowNum]['civicrm_case_activity_case_id'])) {
// Generate a "view activity" link
$actActionLinks = CRM_Activity_Selector_Activity::actionLinks($row['civicrm_activity_activity_type_id'],
CRM_Utils_Array::value('civicrm_activity_source_record_id', $rows[$rowNum]),
FALSE,
$rows[$rowNum]['civicrm_activity_id']
);
$actLinkValues = [
'id' => $rows[$rowNum]['civicrm_activity_id'],
'cid' => $cid,
'cxt' => $context,
];
$actUrl = CRM_Utils_System::url($actActionLinks[CRM_Core_Action::VIEW]['url'],
CRM_Core_Action::replace($actActionLinks[CRM_Core_Action::VIEW]['qs'], $actLinkValues), TRUE
);
}
else {
// Generate a "view case activity" link
$caseActionLinks = CRM_Case_Selector_Search::actionLinks();
$caseLinkValues = [
'aid' => $rows[$rowNum]['civicrm_activity_id'],
'caseid' => $rows[$rowNum]['civicrm_case_activity_case_id'],
'cid' => $cid,
'cxt' => $context,
];
$actUrl = CRM_Utils_System::url($caseActionLinks[CRM_Core_Action::VIEW]['url'],
CRM_Core_Action::replace($caseActionLinks[CRM_Core_Action::VIEW]['qs'], $caseLinkValues), TRUE
);
}
}
if (array_key_exists('civicrm_contact_contact_source', $row)) {
if ($value = $row['civicrm_contact_contact_source_id']) {
if ($viewLinks) {
$url = CRM_Utils_System::url("civicrm/contact/view",
'reset=1&cid=' . $value,
$this->_absoluteUrl
);
$rows[$rowNum]['civicrm_contact_contact_source_link'] = $url;
$rows[$rowNum]['civicrm_contact_contact_source_hover'] = $onHover;
}
$entryFound = TRUE;
}
}
if (array_key_exists('civicrm_contact_contact_assignee', $row)) {
$assigneeNames = explode(';', $row['civicrm_contact_contact_assignee']);
if ($value = $row['civicrm_contact_contact_assignee_id']) {
$assigneeContactIds = explode(';', $value);
$link = [];
if ($viewLinks) {
foreach ($assigneeContactIds as $id => $value) {
if (isset($value) && isset($assigneeNames[$id])) {
$url = CRM_Utils_System::url("civicrm/contact/view",
'reset=1&cid=' . $value,
$this->_absoluteUrl
);
$link[] = "<a title='" . $onHover . "' href='" . $url .
"'>{$assigneeNames[$id]}</a>";
}
}
$rows[$rowNum]['civicrm_contact_contact_assignee'] = implode('; ', $link);
}
$entryFound = TRUE;
}
}
if (array_key_exists('civicrm_contact_contact_target', $row)) {
$targetNames = explode(';', $row['civicrm_contact_contact_target']);
if ($value = $row['civicrm_contact_contact_target_id']) {
$targetContactIds = explode(';', $value);
$link = [];
if ($viewLinks) {
foreach ($targetContactIds as $id => $value) {
if (isset($value) && isset($targetNames[$id])) {
$url = CRM_Utils_System::url("civicrm/contact/view",
'reset=1&cid=' . $value,
$this->_absoluteUrl
);
$link[] = "<a title='" . $onHover . "' href='" . $url .
"'>{$targetNames[$id]}</a>";
}
}
$rows[$rowNum]['civicrm_contact_contact_target'] = implode('; ', $link);
}
$entryFound = TRUE;
}
}
if (array_key_exists('civicrm_activity_activity_type_id', $row)) {
if ($value = $row['civicrm_activity_activity_type_id']) {
$rows[$rowNum]['civicrm_activity_activity_type_id'] = $activityType[$value];
if ($viewLinks) {
$rows[$rowNum]['civicrm_activity_activity_type_id_link'] = $actUrl;