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