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