Merge pull request #22720 from JKingsnorth/patch-19
[civicrm-core.git] / CRM / Contact / BAO / GroupContact.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Contact_BAO_GroupContact extends CRM_Contact_DAO_GroupContact {
18
19 /**
20 * Takes an associative array and creates a groupContact object.
21 *
22 * the function extract all the params it needs to initialize the create a
23 * group object. the params array could contain additional unused name/value
24 * pairs
25 *
26 * @param array $params
27 * (reference ) an assoc array of name/value pairs.
28 *
29 * @return CRM_Contact_BAO_GroupContact
30 */
31 public static function add($params) {
32 $hook = empty($params['id']) ? 'create' : 'edit';
33 CRM_Utils_Hook::pre($hook, 'GroupContact', CRM_Utils_Array::value('id', $params), $params);
34
35 if (!self::dataExists($params)) {
36 return NULL;
37 }
38
39 $groupContact = new CRM_Contact_BAO_GroupContact();
40 $groupContact->copyValues($params);
41 $groupContact->save();
42
43 // Lookup existing info for the sake of subscription history
44 if (!empty($params['id'])) {
45 $groupContact->find(TRUE);
46 $params = $groupContact->toArray();
47 }
48 CRM_Contact_BAO_SubscriptionHistory::create($params);
49
50 CRM_Utils_Hook::post($hook, 'GroupContact', $groupContact->id, $groupContact);
51
52 return $groupContact;
53 }
54
55 /**
56 * Check if there is data to create the object.
57 *
58 * @param array $params
59 * (reference ) an assoc array of name/value pairs.
60 *
61 * @return bool
62 */
63 public static function dataExists(&$params) {
64 return (!empty($params['id']) || (!empty($params['group_id']) && !empty($params['contact_id'])));
65 }
66
67 /**
68 * Given the list of params in the params array, fetch the object
69 * and store the values in the values array
70 *
71 * @param array $params
72 * Input parameters to find object.
73 * @param array $values
74 * Output values of the object.
75 *
76 * @return array
77 * (reference) the values that could be potentially assigned to smarty
78 */
79 public static function getValues($params, &$values) {
80 if (empty($params)) {
81 return NULL;
82 }
83 $values['group']['data'] = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'],
84 'Added',
85 3
86 );
87
88 // get the total count of groups
89 $values['group']['totalCount'] = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'],
90 'Added',
91 NULL,
92 TRUE
93 );
94
95 return NULL;
96 }
97
98 /**
99 * Given an array of contact ids, add all the contacts to the group
100 *
101 * @param array $contactIds
102 * The array of contact ids to be added.
103 * @param int $groupId
104 * The id of the group.
105 * @param string $method
106 * @param string $status
107 * @param int $tracking
108 *
109 * @return array
110 * (total, added, notAdded) count of contacts added to group
111 */
112 public static function addContactsToGroup(
113 $contactIds,
114 $groupId,
115 $method = 'Admin',
116 $status = 'Added',
117 $tracking = NULL
118 ) {
119 if (empty($contactIds) || empty($groupId)) {
120 return [];
121 }
122
123 CRM_Utils_Hook::pre('create', 'GroupContact', $groupId, $contactIds);
124
125 $result = self::bulkAddContactsToGroup($contactIds, $groupId, $method, $status, $tracking);
126 CRM_Contact_BAO_GroupContactCache::invalidateGroupContactCache($groupId);
127 CRM_Contact_BAO_Contact_Utils::clearContactCaches();
128
129 CRM_Utils_Hook::post('create', 'GroupContact', $groupId, $contactIds);
130
131 return [count($contactIds), $result['count_added'], $result['count_not_added']];
132 }
133
134 /**
135 * Given an array of contact ids, remove all the contacts from the group
136 *
137 * @param array $contactIds
138 * (reference ) the array of contact ids to be removed.
139 * @param int $groupId
140 * The id of the group.
141 *
142 * @param string $method
143 * @param string $status
144 * @param string $tracking
145 *
146 * @return array
147 * (total, removed, notRemoved) count of contacts removed to group
148 */
149 public static function removeContactsFromGroup(
150 &$contactIds,
151 $groupId,
152 $method = 'Admin',
153 $status = 'Removed',
154 $tracking = NULL
155 ) {
156 if (!is_array($contactIds)) {
157 return [0, 0, 0];
158 }
159 if ($status == 'Removed' || $status == 'Deleted') {
160 $op = 'delete';
161 }
162 else {
163 $op = 'edit';
164 }
165
166 CRM_Utils_Hook::pre($op, 'GroupContact', $groupId, $contactIds);
167
168 $date = date('YmdHis');
169 $numContactsRemoved = 0;
170 $numContactsNotRemoved = 0;
171
172 $group = new CRM_Contact_DAO_Group();
173 $group->id = $groupId;
174 $group->find(TRUE);
175
176 foreach ($contactIds as $contactId) {
177 if ($status == 'Deleted') {
178 $query = "DELETE FROM civicrm_group_contact WHERE contact_id = %1 AND group_id = %2";
179 $dao = CRM_Core_DAO::executeQuery($query, [
180 1 => [$contactId, 'Positive'],
181 2 => [$groupId, 'Positive'],
182 ]);
183 $historyParams = [
184 'group_id' => $groupId,
185 'contact_id' => $contactId,
186 'status' => $status,
187 'method' => $method,
188 'date' => $date,
189 'tracking' => $tracking,
190 ];
191 CRM_Contact_BAO_SubscriptionHistory::create($historyParams);
192 // Removing a row from civicrm_group_contact for a smart group may mean a contact
193 // Is now back in a group based on criteria so we will invalidate the cache if it is there
194 // So that accurate group cache is created next time it is needed.
195 CRM_Contact_BAO_GroupContactCache::invalidateGroupContactCache($groupId);
196 }
197 else {
198 $groupContact = new CRM_Contact_DAO_GroupContact();
199 $groupContact->group_id = $groupId;
200 $groupContact->contact_id = $contactId;
201 // check if the selected contact id already a member, or if this is
202 // an opt-out of a smart group.
203 // if not a member remove to groupContact else keep the count of contacts that are not removed
204 if ($groupContact->find(TRUE) || $group->saved_search_id) {
205 // remove the contact from the group
206 $numContactsRemoved++;
207 }
208 else {
209 $numContactsNotRemoved++;
210 }
211
212 //now we grant the negative membership to contact if not member. CRM-3711
213 $historyParams = [
214 'group_id' => $groupId,
215 'contact_id' => $contactId,
216 'status' => $status,
217 'method' => $method,
218 'date' => $date,
219 'tracking' => $tracking,
220 ];
221 CRM_Contact_BAO_SubscriptionHistory::create($historyParams);
222 $groupContact->status = $status;
223 $groupContact->save();
224 // Remove any rows from the group contact cache so it disappears straight away from smart groups.
225 CRM_Contact_BAO_GroupContactCache::removeContact($contactId, $groupId);
226 }
227 }
228
229 CRM_Contact_BAO_Contact_Utils::clearContactCaches();
230
231 CRM_Utils_Hook::post($op, 'GroupContact', $groupId, $contactIds);
232
233 return [count($contactIds), $numContactsRemoved, $numContactsNotRemoved];
234 }
235
236 /**
237 * Get list of all the groups and groups for a contact.
238 *
239 * @param int $contactId
240 * Contact id.
241 *
242 * @param bool $visibility
243 *
244 *
245 * @return array
246 * this array has key-> group id and value group title
247 */
248 public static function getGroupList($contactId = 0, $visibility = FALSE) {
249 $select = 'SELECT civicrm_group.id, civicrm_group.title ';
250 $from = ' FROM civicrm_group ';
251 $where = " WHERE civicrm_group.is_active = 1 ";
252 if ($contactId) {
253 $from .= ' , civicrm_group_contact ';
254 $where .= " AND civicrm_group.id = civicrm_group_contact.group_id
255 AND civicrm_group_contact.contact_id = " . CRM_Utils_Type::escape($contactId, 'Integer');
256 }
257
258 if ($visibility) {
259 $where .= " AND civicrm_group.visibility != 'User and User Admin Only'";
260 }
261 $groupBy = " GROUP BY civicrm_group.id";
262
263 $orderby = " ORDER BY civicrm_group.name";
264 $sql = $select . $from . $where . $groupBy . $orderby;
265
266 $group = CRM_Core_DAO::executeQuery($sql);
267
268 $values = [];
269 while ($group->fetch()) {
270 $values[$group->id] = $group->title;
271 }
272
273 return $values;
274 }
275
276 /**
277 * Get the list of groups for contact based on status of group membership.
278 *
279 * @param int $contactId
280 * Contact id.
281 * @param string $status
282 * State of membership.
283 * @param int $numGroupContact
284 * Number of groups for a contact that should be shown.
285 * @param bool $count
286 * True if we are interested only in the count.
287 * @param bool $ignorePermission
288 * True if we should ignore permissions for the current user.
289 * useful in profile where permissions are limited for the user. If left
290 * at false only groups viewable by the current user are returned
291 * @param bool $onlyPublicGroups
292 * True if we want to hide system groups.
293 *
294 * @param bool $excludeHidden
295 *
296 * @param int $groupId
297 *
298 * @param bool $includeSmartGroups
299 * Include or Exclude Smart Group(s)
300 * @param bool $public
301 * Are we returning groups for use on a public page.
302 *
303 * @return array|int
304 * the relevant data object values for the contact or the total count when $count is TRUE
305 */
306 public static function getContactGroup(
307 $contactId,
308 $status = NULL,
309 $numGroupContact = NULL,
310 $count = FALSE,
311 $ignorePermission = FALSE,
312 $onlyPublicGroups = FALSE,
313 $excludeHidden = TRUE,
314 $groupId = NULL,
315 $includeSmartGroups = FALSE,
316 $public = FALSE
317 ) {
318 if ($count) {
319 $select = 'SELECT count(DISTINCT civicrm_group_contact.id)';
320 }
321 else {
322 $select = 'SELECT
323 civicrm_group_contact.id as civicrm_group_contact_id,
324 civicrm_group.title as group_title,
325 civicrm_group.frontend_title as group_public_title,
326 civicrm_group.visibility as visibility,
327 civicrm_group_contact.status as status,
328 civicrm_group.id as group_id,
329 civicrm_group.is_hidden as is_hidden,
330 civicrm_subscription_history.date as date,
331 civicrm_subscription_history.method as method';
332 }
333
334 $where = " WHERE contact_a.id = %1 AND civicrm_group.is_active = 1";
335 if (!$includeSmartGroups) {
336 $where .= " AND saved_search_id IS NULL";
337 }
338 if ($excludeHidden) {
339 $where .= " AND civicrm_group.is_hidden = 0 ";
340 }
341 $params = [1 => [$contactId, 'Integer']];
342 if (!empty($status)) {
343 $where .= ' AND civicrm_group_contact.status = %2';
344 $params[2] = [$status, 'String'];
345 }
346 if (!empty($groupId)) {
347 $where .= " AND civicrm_group.id = %3 ";
348 $params[3] = [$groupId, 'Integer'];
349 }
350 $tables = [
351 'civicrm_group_contact' => 1,
352 'civicrm_group' => 1,
353 'civicrm_subscription_history' => 1,
354 ];
355 $whereTables = [];
356 if ($ignorePermission) {
357 $permission = ' ( 1 ) ';
358 }
359 else {
360 $permission = CRM_Core_Permission::getPermissionedStaticGroupClause(CRM_Core_Permission::VIEW, $tables, $whereTables);
361 }
362
363 $from = CRM_Contact_BAO_Query::fromClause($tables);
364
365 $where .= " AND $permission ";
366
367 if ($onlyPublicGroups) {
368 $where .= " AND civicrm_group.visibility != 'User and User Admin Only' ";
369 }
370
371 $order = $limit = '';
372 if (!$count) {
373 $order = ' ORDER BY civicrm_group.title, civicrm_subscription_history.date ASC';
374
375 if ($numGroupContact) {
376 $limit = " LIMIT 0, $numGroupContact";
377 }
378 }
379
380 $sql = $select . $from . $where . $order . $limit;
381
382 if ($count) {
383 $result = CRM_Core_DAO::singleValueQuery($sql, $params);
384 return $result;
385 }
386 else {
387 $dao = CRM_Core_DAO::executeQuery($sql, $params);
388 $values = [];
389 while ($dao->fetch()) {
390 $id = $dao->civicrm_group_contact_id;
391 $values[$id]['id'] = $id;
392 $values[$id]['group_id'] = $dao->group_id;
393 $values[$id]['title'] = ($public && !empty($group->group_public_title) ? $group->group_public_title : $dao->group_title);
394 $values[$id]['visibility'] = $dao->visibility;
395 $values[$id]['is_hidden'] = $dao->is_hidden;
396 switch ($dao->status) {
397 case 'Added':
398 $prefix = 'in_';
399 break;
400
401 case 'Removed':
402 $prefix = 'out_';
403 break;
404
405 default:
406 $prefix = 'pending_';
407 }
408 $values[$id][$prefix . 'date'] = $dao->date;
409 $values[$id][$prefix . 'method'] = $dao->method;
410 if ($status == 'Removed') {
411 $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 )";
412 $dateDAO = CRM_Core_DAO::executeQuery($query, $params);
413 if ($dateDAO->fetch()) {
414 $values[$id]['date_added'] = $dateDAO->date_added;
415 }
416 }
417 }
418 return $values;
419 }
420 }
421
422 /**
423 * Returns membership details of a contact for a group.
424 *
425 * @param int $contactId
426 * Id of the contact.
427 * @param int $groupID
428 * Id of a particular group.
429 * @param string $method
430 * If we want the subscription history details for a specific method.
431 *
432 * @return object
433 * of group contact
434 */
435 public static function getMembershipDetail($contactId, $groupID, $method = 'Email') {
436 $leftJoin = $where = $orderBy = NULL;
437
438 if ($method) {
439 //CRM-13341 add group_id clause
440 $leftJoin = "
441 LEFT JOIN civicrm_subscription_history
442 ON ( civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
443 AND civicrm_subscription_history.group_id = {$groupID} )";
444 $where = "AND civicrm_subscription_history.method ='Email'";
445 $orderBy = "ORDER BY civicrm_subscription_history.id DESC";
446 }
447 $query = "
448 SELECT *
449 FROM civicrm_group_contact
450 $leftJoin
451 WHERE civicrm_group_contact.contact_id = %1
452 AND civicrm_group_contact.group_id = %2
453 $where
454 $orderBy
455 ";
456
457 $params = [
458 1 => [$contactId, 'Integer'],
459 2 => [$groupID, 'Integer'],
460 ];
461 $dao = CRM_Core_DAO::executeQuery($query, $params);
462 $dao->fetch();
463 return $dao;
464 }
465
466 /**
467 * Method to get Group Id.
468 *
469 * @param int $groupContactID
470 * Id of a particular group.
471 *
472 *
473 * @return int groupID
474 */
475 public static function getGroupId($groupContactID) {
476 $dao = new CRM_Contact_DAO_GroupContact();
477 $dao->id = $groupContactID;
478 $dao->find(TRUE);
479 return $dao->group_id;
480 }
481
482 /**
483 * Deprecated create function.
484 *
485 * @deprecated
486 *
487 * @param array $params
488 *
489 * @return CRM_Contact_BAO_GroupContact
490 */
491 public static function create(array $params) {
492 // @fixme create was only called from CRM_Contact_BAO_Contact::createProfileContact
493 // As of Aug 2020 it's not called from anywhere so we can remove the below code after some time
494
495 CRM_Core_Error::deprecatedFunctionWarning('Use the GroupContact API');
496 return self::add($params);
497 }
498
499 /**
500 * @param int $contactID
501 * @param int $groupID
502 *
503 * @return bool
504 */
505 public static function isContactInGroup($contactID, $groupID) {
506 if (!CRM_Utils_Rule::positiveInteger($contactID) ||
507 !CRM_Utils_Rule::positiveInteger($groupID)
508 ) {
509 return FALSE;
510 }
511
512 $params = [
513 ['group', 'IN', [$groupID], 0, 0],
514 ['contact_id', '=', $contactID, 0, 0],
515 ];
516 [$contacts] = CRM_Contact_BAO_Query::apiQuery($params, ['contact_id']);
517
518 if (!empty($contacts)) {
519 return TRUE;
520 }
521 return FALSE;
522 }
523
524 /**
525 * Function merges the groups from otherContactID to mainContactID.
526 * along with subscription history
527 *
528 * @param int $mainContactId
529 * Contact id of main contact record.
530 * @param int $otherContactId
531 * Contact id of record which is going to merge.
532 *
533 * @see CRM_Dedupe_Merger::cpTables()
534 *
535 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
536 */
537 public static function mergeGroupContact($mainContactId, $otherContactId) {
538 $params = [
539 1 => [$mainContactId, 'Integer'],
540 2 => [$otherContactId, 'Integer'],
541 ];
542
543 // find all groups that are in otherContactID but not in mainContactID, copy them over
544 $sql = "
545 SELECT cOther.group_id
546 FROM civicrm_group_contact cOther
547 LEFT JOIN civicrm_group_contact cMain ON cOther.group_id = cMain.group_id AND cMain.contact_id = %1
548 WHERE cOther.contact_id = %2
549 AND cMain.contact_id IS NULL
550 ";
551 $dao = CRM_Core_DAO::executeQuery($sql, $params);
552
553 $otherGroupIDs = [];
554 while ($dao->fetch()) {
555 $otherGroupIDs[] = $dao->group_id;
556 }
557
558 if (!empty($otherGroupIDs)) {
559 $otherGroupIDString = implode(',', $otherGroupIDs);
560
561 $sql = "
562 UPDATE civicrm_group_contact
563 SET contact_id = %1
564 WHERE contact_id = %2
565 AND group_id IN ( $otherGroupIDString )
566 ";
567 CRM_Core_DAO::executeQuery($sql, $params);
568
569 $sql = "
570 UPDATE civicrm_subscription_history
571 SET contact_id = %1
572 WHERE contact_id = %2
573 AND group_id IN ( $otherGroupIDString )
574 ";
575 CRM_Core_DAO::executeQuery($sql, $params);
576 }
577
578 $sql = "
579 SELECT cOther.group_id as group_id,
580 cOther.status as group_status
581 FROM civicrm_group_contact cMain
582 INNER JOIN civicrm_group_contact cOther ON cMain.group_id = cOther.group_id
583 WHERE cMain.contact_id = %1
584 AND cOther.contact_id = %2
585 ";
586 $dao = CRM_Core_DAO::executeQuery($sql, $params);
587
588 $groupIDs = [];
589 while ($dao->fetch()) {
590 // only copy it over if it has added status and migrate the history
591 if ($dao->group_status == 'Added') {
592 $groupIDs[] = $dao->group_id;
593 }
594 }
595
596 if (!empty($groupIDs)) {
597 $groupIDString = implode(',', $groupIDs);
598
599 $sql = "
600 UPDATE civicrm_group_contact
601 SET status = 'Added'
602 WHERE contact_id = %1
603 AND group_id IN ( $groupIDString )
604 ";
605 CRM_Core_DAO::executeQuery($sql, $params);
606
607 $sql = "
608 UPDATE civicrm_subscription_history
609 SET contact_id = %1
610 WHERE contact_id = %2
611 AND group_id IN ( $groupIDString )
612 ";
613 CRM_Core_DAO::executeQuery($sql, $params);
614 }
615
616 // delete all the other group contacts
617 $sql = "
618 DELETE
619 FROM civicrm_group_contact
620 WHERE contact_id = %2
621 ";
622 CRM_Core_DAO::executeQuery($sql, $params);
623
624 $sql = "
625 DELETE
626 FROM civicrm_subscription_history
627 WHERE contact_id = %2
628 ";
629 CRM_Core_DAO::executeQuery($sql, $params);
630 }
631
632 /**
633 * Given an array of contact ids, add all the contacts to the group
634 *
635 * @param array $contactIDs
636 * The array of contact ids to be added.
637 * @param int $groupID
638 * The id of the group.
639 * @param string $method
640 * @param string $status
641 * @param string $tracking
642 *
643 * @return array
644 * (total, added, notAdded) count of contacts added to group
645 */
646 public static function bulkAddContactsToGroup(
647 $contactIDs,
648 $groupID,
649 $method = 'Admin',
650 $status = 'Added',
651 $tracking = NULL
652 ) {
653
654 $numContactsAdded = 0;
655 $numContactsNotAdded = 0;
656
657 $contactGroupSQL = "
658 REPLACE INTO civicrm_group_contact ( group_id, contact_id, status )
659 VALUES
660 ";
661 $subscriptioHistorySQL = "
662 INSERT INTO civicrm_subscription_history( group_id, contact_id, date, method, status, tracking )
663 VALUES
664 ";
665
666 $date = date('YmdHis');
667
668 // to avoid long strings, lets do BULK_INSERT_HIGH_COUNT values at a time
669 while (!empty($contactIDs)) {
670 $input = array_splice($contactIDs, 0, CRM_Core_DAO::BULK_INSERT_HIGH_COUNT);
671 $contactStr = implode(',', $input);
672
673 // lets check their current status
674 $sql = "
675 SELECT GROUP_CONCAT(contact_id) as contactStr
676 FROM civicrm_group_contact
677 WHERE group_id = %1
678 AND status = %2
679 AND contact_id IN ( $contactStr )
680 ";
681 $params = [
682 1 => [$groupID, 'Integer'],
683 2 => [$status, 'String'],
684 ];
685
686 $presentIDs = [];
687 $dao = CRM_Core_DAO::executeQuery($sql, $params);
688 if ($dao->fetch()) {
689 $presentIDs = explode(',', $dao->contactStr);
690 $presentIDs = array_flip($presentIDs);
691 }
692
693 $gcValues = $shValues = [];
694 foreach ($input as $cid) {
695 if (isset($presentIDs[$cid])) {
696 $numContactsNotAdded++;
697 continue;
698 }
699
700 $gcValues[] = "( $groupID, $cid, '$status' )";
701 $shValues[] = "( $groupID, $cid, '$date', '$method', '$status', '$tracking' )";
702 $numContactsAdded++;
703 }
704
705 if (!empty($gcValues)) {
706 $cgSQL = $contactGroupSQL . implode(",\n", $gcValues);
707 CRM_Core_DAO::executeQuery($cgSQL);
708
709 $shSQL = $subscriptioHistorySQL . implode(",\n", $shValues);
710 CRM_Core_DAO::executeQuery($shSQL);
711 }
712 }
713
714 return ['count_added' => $numContactsAdded, 'count_not_added' => $numContactsNotAdded];
715 }
716
717 /**
718 * Get options for a given field.
719 * @see CRM_Core_DAO::buildOptions
720 *
721 * @param string $fieldName
722 * @param string $context
723 * @see CRM_Core_DAO::buildOptionsContext
724 * @param array $props
725 * whatever is known about this dao object.
726 *
727 * @return array|bool
728 */
729 public static function buildOptions($fieldName, $context = NULL, $props = []) {
730 $options = CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, [], $context);
731
732 // Sort group list by hierarchy
733 // TODO: This will only work when api.entity is "group_contact". What about others?
734 if (($fieldName == 'group' || $fieldName == 'group_id') && ($context == 'search' || $context == 'create')) {
735 $options = CRM_Contact_BAO_Group::getGroupsHierarchy($options, NULL, '- ', TRUE);
736 }
737
738 return $options;
739 }
740
741 }