/
GroupContact.php
739 lines (664 loc) · 22 KB
/
GroupContact.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
<?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 |
+--------------------------------------------------------------------+
*/
use Civi\Api4\Contact;
use Civi\Api4\SubscriptionHistory;
use Civi\Core\Event\PostEvent;
use Civi\Core\HookInterface;
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
class CRM_Contact_BAO_GroupContact extends CRM_Contact_DAO_GroupContact implements HookInterface {
use CRM_Contact_AccessTrait;
/**
* Deprecated add function
*
* @param array $params
*
* @return CRM_Contact_DAO_GroupContact
* @throws \CRM_Core_Exception
*
* @deprecated
*/
public static function add(array $params): CRM_Contact_DAO_GroupContact {
return self::writeRecord($params);
}
/**
* Callback for hook_civicrm_post().
*
* @param \Civi\Core\Event\PostEvent $event
*
* @noinspection PhpUnused
* @noinspection UnknownInspectionInspection
*/
public static function self_hook_civicrm_post(PostEvent $event): void {
if (is_object($event->object) && in_array($event->action, ['create', 'edit'], TRUE)) {
// Lookup existing info for the sake of subscription history
if ($event->action === 'edit') {
$event->object->find(TRUE);
}
try {
if (empty($event->object->group_id) || empty($event->object->contact_id) || empty($event->object->status)) {
$event->object->find(TRUE);
}
SubscriptionHistory::save(FALSE)->setRecords([
[
'group_id' => $event->object->group_id,
'contact_id' => $event->object->contact_id,
'status' => $event->object->status,
],
])->execute();
}
catch (CRM_Core_Exception $e) {
// A failure to create the history might be a deadlock or similar
// This record is not important enough to trigger a larger fail.
Civi::log()->warning('Failed to add civicrm_subscription_history record with error :error', ['error' => $e->getMessage()]);
}
}
}
/**
* Given the list of params in the params array, fetch the object
* and store the values in the values array
*
* @param array $params
* Input parameters to find object.
* @param array $values
* Output values of the object.
*
* @return array
* (reference) the values that could be potentially assigned to smarty
*/
public static function getValues($params, &$values) {
if (empty($params)) {
return NULL;
}
$values['group']['data'] = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'],
'Added',
3
);
// get the total count of groups
$values['group']['totalCount'] = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'],
'Added',
NULL,
TRUE
);
return NULL;
}
/**
* Given an array of contact ids, add all the contacts to the group
*
* @param array $contactIds
* The array of contact ids to be added.
* @param int $groupId
* The id of the group.
* @param string $method
* @param string $status
* @param int $tracking
*
* @return array
* (total, added, notAdded) count of contacts added to group
*/
public static function addContactsToGroup(
$contactIds,
$groupId,
$method = 'Admin',
$status = 'Added',
$tracking = NULL
) {
if (empty($contactIds) || empty($groupId)) {
return [];
}
CRM_Utils_Hook::pre('create', 'GroupContact', $groupId, $contactIds);
$result = self::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
CRM_Contact_BAO_GroupContactCache::invalidateGroupContactCache($groupId);
CRM_Contact_BAO_Contact_Utils::clearContactCaches();
CRM_Utils_Hook::post('create', 'GroupContact', $groupId, $contactIds);
return [count($contactIds), $result['count_added'], $result['count_not_added']];
}
/**
* Given an array of contact ids, remove all the contacts from the group
*
* @param array $contactIds
* (reference ) the array of contact ids to be removed.
* @param int $groupId
* The id of the group.
*
* @param string $method
* @param string $status
* @param string $tracking
*
* @return array
* (total, removed, notRemoved) count of contacts removed to group
*/
public static function removeContactsFromGroup(
&$contactIds,
$groupId,
$method = 'Admin',
$status = 'Removed',
$tracking = NULL
) {
if (!is_array($contactIds)) {
return [0, 0, 0];
}
if ($status == 'Removed' || $status == 'Deleted') {
$op = 'delete';
}
else {
$op = 'edit';
}
CRM_Utils_Hook::pre($op, 'GroupContact', $groupId, $contactIds);
$date = date('YmdHis');
$numContactsRemoved = 0;
$numContactsNotRemoved = 0;
$group = new CRM_Contact_DAO_Group();
$group->id = $groupId;
$group->find(TRUE);
foreach ($contactIds as $contactId) {
if ($status == 'Deleted') {
$query = "DELETE FROM civicrm_group_contact WHERE contact_id = %1 AND group_id = %2";
$dao = CRM_Core_DAO::executeQuery($query, [
1 => [$contactId, 'Positive'],
2 => [$groupId, 'Positive'],
]);
$historyParams = [
'group_id' => $groupId,
'contact_id' => $contactId,
'status' => $status,
'method' => $method,
'date' => $date,
'tracking' => $tracking,
];
CRM_Contact_BAO_SubscriptionHistory::create($historyParams);
// Removing a row from civicrm_group_contact for a smart group may mean a contact
// Is now back in a group based on criteria so we will invalidate the cache if it is there
// So that accurate group cache is created next time it is needed.
CRM_Contact_BAO_GroupContactCache::invalidateGroupContactCache($groupId);
}
else {
$groupContact = new CRM_Contact_DAO_GroupContact();
$groupContact->group_id = $groupId;
$groupContact->contact_id = $contactId;
// check if the selected contact id already a member, or if this is
// an opt-out of a smart group.
// if not a member remove to groupContact else keep the count of contacts that are not removed
if ($groupContact->find(TRUE) || $group->saved_search_id) {
// remove the contact from the group
$numContactsRemoved++;
}
else {
$numContactsNotRemoved++;
}
//now we grant the negative membership to contact if not member. CRM-3711
$historyParams = [
'group_id' => $groupId,
'contact_id' => $contactId,
'status' => $status,
'method' => $method,
'date' => $date,
'tracking' => $tracking,
];
CRM_Contact_BAO_SubscriptionHistory::create($historyParams);
$groupContact->status = $status;
$groupContact->save();
// Remove any rows from the group contact cache so it disappears straight away from smart groups.
CRM_Contact_BAO_GroupContactCache::removeContact($contactId, $groupId);
}
}
CRM_Contact_BAO_Contact_Utils::clearContactCaches();
CRM_Utils_Hook::post($op, 'GroupContact', $groupId, $contactIds);
return [count($contactIds), $numContactsRemoved, $numContactsNotRemoved];
}
/**
* Get list of all the groups and groups for a contact.
*
* @param int $contactId
* Contact id.
*
* @param bool $visibility
*
*
* @return array
* this array has key-> group id and value group title
*/
public static function getGroupList($contactId = 0, $visibility = FALSE) {
$select = 'SELECT civicrm_group.id, civicrm_group.title ';
$from = ' FROM civicrm_group ';
$where = " WHERE civicrm_group.is_active = 1 ";
if ($contactId) {
$from .= ' , civicrm_group_contact ';
$where .= " AND civicrm_group.id = civicrm_group_contact.group_id
AND civicrm_group_contact.contact_id = " . CRM_Utils_Type::escape($contactId, 'Integer');
}
if ($visibility) {
$where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
}
$groupBy = " GROUP BY civicrm_group.id";
$orderby = " ORDER BY civicrm_group.name";
$sql = $select . $from . $where . $groupBy . $orderby;
$group = CRM_Core_DAO::executeQuery($sql);
$values = [];
while ($group->fetch()) {
$values[$group->id] = $group->title;
}
return $values;
}
/**
* Get the list of groups for contact based on status of group membership.
*
* @param int $contactId
* Contact id.
* @param string $status
* State of membership.
* @param int $numGroupContact
* Number of groups for a contact that should be shown.
* @param bool $count
* True if we are interested only in the count.
* @param bool $ignorePermission
* True if we should ignore permissions for the current user.
* useful in profile where permissions are limited for the user. If left
* at false only groups viewable by the current user are returned
* @param bool $onlyPublicGroups
* True if we want to hide system groups.
*
* @param bool $excludeHidden
*
* @param int $groupId
*
* @param bool $includeSmartGroups
* Include or Exclude Smart Group(s)
* @param bool $public
* Are we returning groups for use on a public page.
*
* @return array|int
* the relevant data object values for the contact or the total count when $count is TRUE
*/
public static function getContactGroup(
$contactId,
$status = NULL,
$numGroupContact = NULL,
$count = FALSE,
$ignorePermission = FALSE,
$onlyPublicGroups = FALSE,
$excludeHidden = TRUE,
$groupId = NULL,
$includeSmartGroups = FALSE,
$public = FALSE
) {
if ($count) {
$select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
}
else {
$select = 'SELECT
civicrm_group_contact.id as civicrm_group_contact_id,
civicrm_group.title as group_title,
civicrm_group.frontend_title as group_public_title,
civicrm_group.visibility as visibility,
civicrm_group_contact.status as status,
civicrm_group.id as group_id,
civicrm_group.is_hidden as is_hidden,
civicrm_subscription_history.date as date,
civicrm_subscription_history.method as method';
}
$where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
if (!$includeSmartGroups) {
$where .= " AND saved_search_id IS NULL";
}
if ($excludeHidden) {
$where .= " AND civicrm_group.is_hidden = 0 ";
}
$params = [1 => [$contactId, 'Integer']];
if (!empty($status)) {
$where .= ' AND civicrm_group_contact.status = %2';
$params[2] = [$status, 'String'];
}
if (!empty($groupId)) {
$where .= " AND civicrm_group.id = %3 ";
$params[3] = [$groupId, 'Integer'];
}
$tables = [
'civicrm_group_contact' => 1,
'civicrm_group' => 1,
'civicrm_subscription_history' => 1,
];
$whereTables = [];
if ($ignorePermission) {
$permission = ' ( 1 ) ';
}
else {
$permission = CRM_Core_Permission::getPermissionedStaticGroupClause(CRM_Core_Permission::VIEW, $tables, $whereTables);
}
$from = CRM_Contact_BAO_Query::fromClause($tables);
$where .= " AND $permission ";
if ($onlyPublicGroups) {
$where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
}
$order = $limit = '';
if (!$count) {
$order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
if ($numGroupContact) {
$limit = " LIMIT 0, $numGroupContact";
}
}
$sql = $select . $from . $where . $order . $limit;
if ($count) {
$result = CRM_Core_DAO::singleValueQuery($sql, $params);
return $result;
}
else {
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$values = [];
while ($dao->fetch()) {
$id = $dao->civicrm_group_contact_id;
$values[$id]['id'] = $id;
$values[$id]['group_id'] = $dao->group_id;
$values[$id]['title'] = ($public && !empty($group->group_public_title) ? $group->group_public_title : $dao->group_title);
$values[$id]['visibility'] = $dao->visibility;
$values[$id]['is_hidden'] = $dao->is_hidden;
switch ($dao->status) {
case 'Added':
$prefix = 'in_';
break;
case 'Removed':
$prefix = 'out_';
break;
default:
$prefix = 'pending_';
}
$values[$id][$prefix . 'date'] = $dao->date;
$values[$id][$prefix . 'method'] = $dao->method;
if ($status == 'Removed') {
$query = "SELECT `date` as `date_added` FROM civicrm_subscription_history WHERE id = (SELECT max(id) FROM civicrm_subscription_history WHERE contact_id = %1 AND status = \"Added\" AND group_id = $dao->group_id )";
$dateDAO = CRM_Core_DAO::executeQuery($query, $params);
if ($dateDAO->fetch()) {
$values[$id]['date_added'] = $dateDAO->date_added;
}
}
}
return $values;
}
}
/**
* Returns membership details of a contact for a group.
*
* @param int $contactId
* Id of the contact.
* @param int $groupID
* Id of a particular group.
* @param string $method
* If we want the subscription history details for a specific method.
*
* @return object
* of group contact
*/
public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
$leftJoin = $where = $orderBy = NULL;
if ($method) {
//CRM-13341 add group_id clause
$leftJoin = "
LEFT JOIN civicrm_subscription_history
ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
AND civicrm_subscription_history.group_id = {$groupID} )";
$where = "AND civicrm_subscription_history.method ='Email'";
$orderBy = "ORDER BY civicrm_subscription_history.id DESC";
}
$query = "
SELECT *
FROM civicrm_group_contact
$leftJoin
WHERE civicrm_group_contact.contact_id = %1
AND civicrm_group_contact.group_id = %2
$where
$orderBy
";
$params = [
1 => [$contactId, 'Integer'],
2 => [$groupID, 'Integer'],
];
$dao = CRM_Core_DAO::executeQuery($query, $params);
$dao->fetch();
return $dao;
}
/**
* Method to get Group Id.
*
* @param int $groupContactID
* Id of a particular group.
*
*
* @return int groupID
*/
public static function getGroupId($groupContactID) {
$dao = new CRM_Contact_DAO_GroupContact();
$dao->id = $groupContactID;
$dao->find(TRUE);
return $dao->group_id;
}
/**
* Deprecated create function.
*
* @deprecated
*
* @param array $params
*
* @return CRM_Contact_DAO_GroupContact
*/
public static function create(array $params) {
// @fixme create was only called from CRM_Contact_BAO_Contact::createProfileContact
// As of Aug 2020 it's not called from anywhere so we can remove the below code after some time
CRM_Core_Error::deprecatedFunctionWarning('Use the GroupContact API');
return self::add($params);
}
/**
* Function that doesn't do much.
*
* @param int $contactID
* @param int $groupID
*
* @deprecated
* @return bool
*/
public static function isContactInGroup(int $contactID, int $groupID) {
return (bool) Contact::get(FALSE)
->addWhere('id', '=', $contactID)
->addWhere('groups', 'IN', [$groupID])
->selectRowCount()->execute()->count();
}
/**
* Function merges the groups from otherContactID to mainContactID.
* along with subscription history
*
* @param int $mainContactId
* Contact id of main contact record.
* @param int $otherContactId
* Contact id of record which is going to merge.
*
* @see CRM_Dedupe_Merger::cpTables()
*
* TODO: use the 3rd $sqls param to append sql statements rather than executing them here
*/
public static function mergeGroupContact($mainContactId, $otherContactId) {
$params = [
1 => [$mainContactId, 'Integer'],
2 => [$otherContactId, 'Integer'],
];
// find all groups that are in otherContactID but not in mainContactID, copy them over
$sql = "
SELECT cOther.group_id
FROM civicrm_group_contact cOther
LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
WHERE cOther.contact_id = %2
AND cMain.contact_id IS NULL
";
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$otherGroupIDs = [];
while ($dao->fetch()) {
$otherGroupIDs[] = $dao->group_id;
}
if (!empty($otherGroupIDs)) {
$otherGroupIDString = implode(',', $otherGroupIDs);
$sql = "
UPDATE civicrm_group_contact
SET contact_id = %1
WHERE contact_id = %2
AND group_id IN ( $otherGroupIDString )
";
CRM_Core_DAO::executeQuery($sql, $params);
$sql = "
UPDATE civicrm_subscription_history
SET contact_id = %1
WHERE contact_id = %2
AND group_id IN ( $otherGroupIDString )
";
CRM_Core_DAO::executeQuery($sql, $params);
}
$sql = "
SELECT cOther.group_id as group_id,
cOther.status as group_status
FROM civicrm_group_contact cMain
INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
WHERE cMain.contact_id = %1
AND cOther.contact_id = %2
";
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$groupIDs = [];
while ($dao->fetch()) {
// only copy it over if it has added status and migrate the history
if ($dao->group_status == 'Added') {
$groupIDs[] = $dao->group_id;
}
}
if (!empty($groupIDs)) {
$groupIDString = implode(',', $groupIDs);
$sql = "
UPDATE civicrm_group_contact
SET status = 'Added'
WHERE contact_id = %1
AND group_id IN ( $groupIDString )
";
CRM_Core_DAO::executeQuery($sql, $params);
$sql = "
UPDATE civicrm_subscription_history
SET contact_id = %1
WHERE contact_id = %2
AND group_id IN ( $groupIDString )
";
CRM_Core_DAO::executeQuery($sql, $params);
}
// delete all the other group contacts
$sql = "
DELETE
FROM civicrm_group_contact
WHERE contact_id = %2
";
CRM_Core_DAO::executeQuery($sql, $params);
$sql = "
DELETE
FROM civicrm_subscription_history
WHERE contact_id = %2
";
CRM_Core_DAO::executeQuery($sql, $params);
}
/**
* Given an array of contact ids, add all the contacts to the group
*
* @param array $contactIDs
* The array of contact ids to be added.
* @param int $groupID
* The id of the group.
* @param string $method
* @param string $status
* @param string $tracking
*
* @return array
* (total, added, notAdded) count of contacts added to group
*/
public static function bulkAddContactsToGroup(
$contactIDs,
$groupID,
$method = 'Admin',
$status = 'Added',
$tracking = NULL
) {
$numContactsAdded = 0;
$numContactsNotAdded = 0;
$contactGroupSQL = "
REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
VALUES
";
$subscriptioHistorySQL = "
INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
VALUES
";
$date = date('YmdHis');
// to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
while (!empty($contactIDs)) {
$input = array_splice($contactIDs, 0, CRM_Core_DAO::BULK_INSERT_HIGH_COUNT);
$contactStr = implode(',', $input);
// lets check their current status
$sql = "
SELECT GROUP_CONCAT(contact_id) as contactStr
FROM civicrm_group_contact
WHERE group_id = %1
AND status = %2
AND contact_id IN ( $contactStr )
";
$params = [
1 => [$groupID, 'Integer'],
2 => [$status, 'String'],
];
$presentIDs = [];
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if ($dao->fetch()) {
$presentIDs = explode(',', ($dao->contactStr ?? ''));
$presentIDs = array_flip($presentIDs);
}
$gcValues = $shValues = [];
foreach ($input as $cid) {
if (isset($presentIDs[$cid])) {
$numContactsNotAdded++;
continue;
}
$gcValues[] = "( $groupID, $cid, '$status' )";
$shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
$numContactsAdded++;
}
if (!empty($gcValues)) {
$cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
CRM_Core_DAO::executeQuery($cgSQL);
$shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
CRM_Core_DAO::executeQuery($shSQL);
}
}
return ['count_added' => $numContactsAdded, 'count_not_added' => $numContactsNotAdded];
}
/**
* Get options for a given field.
* @see CRM_Core_DAO::buildOptions
*
* @param string $fieldName
* @param string $context
* @see CRM_Core_DAO::buildOptionsContext
* @param array $props
* whatever is known about this dao object.
*
* @return array|bool
*/
public static function buildOptions($fieldName, $context = NULL, $props = []) {
$options = CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, [], $context);
// Sort group list by hierarchy
// TODO: This will only work when api.entity is "group_contact". What about others?
if (($fieldName == 'group' || $fieldName == 'group_id') && ($context == 'search' || $context == 'create')) {
$options = CRM_Contact_BAO_Group::getGroupsHierarchy($options, NULL, '- ', TRUE);
}
return $options;
}
}