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