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