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