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