Switch membership BAO to use non-deprecated cached functions to get membershipType...
[civicrm-core.git] / CRM / Member / BAO / Membership.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Member_BAO_Membership extends CRM_Member_DAO_Membership {
18
19 /**
20 * Static field for all the membership information that we can potentially import.
21 *
22 * @var array
23 */
24 public static $_importableFields = NULL;
25
26 public static $_renewalActType = NULL;
27
28 public static $_signupActType = NULL;
29
30 /**
31 * Class constructor.
32 */
33 public function __construct() {
34 parent::__construct();
35 }
36
37 /**
38 * Takes an associative array and creates a membership object.
39 *
40 * the function extracts all the params it needs to initialize the created
41 * membership object. The params array could contain additional unused name/value
42 * pairs
43 *
44 * @param array $params
45 * (reference ) an assoc array of name/value pairs.
46 *
47 * @return CRM_Member_BAO_Membership
48 * @throws \CiviCRM_API3_Exception
49 */
50 public static function add(&$params) {
51 $oldStatus = $oldType = NULL;
52 if ($params['id']) {
53 CRM_Utils_Hook::pre('edit', 'Membership', $params['id'], $params);
54 }
55 else {
56 CRM_Utils_Hook::pre('create', 'Membership', NULL, $params);
57 }
58 $id = $params['id'];
59 // we do this after the hooks are called in case it has been altered
60 if ($id) {
61 $membershipObj = new CRM_Member_DAO_Membership();
62 $membershipObj->id = $id;
63 $membershipObj->find();
64 while ($membershipObj->fetch()) {
65 $oldStatus = $membershipObj->status_id;
66 $oldType = $membershipObj->membership_type_id;
67 }
68 }
69
70 if (array_key_exists('is_override', $params) && !$params['is_override']) {
71 $params['is_override'] = 'null';
72 }
73
74 $membership = new CRM_Member_BAO_Membership();
75 $membership->copyValues($params);
76 $membership->id = $id;
77
78 $membership->save();
79
80 if (empty($membership->contact_id) || empty($membership->status_id)) {
81 // this means we are in renewal mode and are just updating the membership
82 // record or this is an API update call and all fields are not present in the update record
83 // however the hooks don't care and want all data CRM-7784
84 $tempMembership = new CRM_Member_DAO_Membership();
85 $tempMembership->id = $membership->id;
86 $tempMembership->find(TRUE);
87 $membership = $tempMembership;
88 }
89
90 //get the log start date.
91 //it is set during renewal of membership.
92 $logStartDate = $params['log_start_date'] ?? NULL;
93 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : CRM_Utils_Date::isoToMysql($membership->start_date);
94 $values = self::getStatusANDTypeValues($membership->id);
95
96 $membershipLog = [
97 'membership_id' => $membership->id,
98 'status_id' => $membership->status_id,
99 'start_date' => $logStartDate,
100 'end_date' => CRM_Utils_Date::isoToMysql($membership->end_date),
101 'modified_date' => date('Ymd'),
102 'membership_type_id' => $values[$membership->id]['membership_type_id'],
103 'max_related' => $membership->max_related,
104 ];
105
106 if (!empty($params['modified_id'])) {
107 $membershipLog['modified_id'] = $params['modified_id'];
108 }
109 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
110 elseif (CRM_Core_Session::singleton()->get('userID')) {
111 $membershipLog['modified_id'] = CRM_Core_Session::singleton()->get('userID');
112 }
113 else {
114 $membershipLog['modified_id'] = $membership->contact_id;
115 }
116
117 CRM_Member_BAO_MembershipLog::add($membershipLog);
118
119 // reset the group contact cache since smart groups might be affected due to this
120 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
121
122 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
123 $activityParams = [
124 'status_id' => $params['membership_activity_status'] ?? 'Completed',
125 ];
126 if (in_array($allStatus[$membership->status_id], ['Pending', 'Grace'])) {
127 $activityParams['status_id'] = 'Scheduled';
128 }
129 $activityParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
130
131 $targetContactID = $membership->contact_id;
132 if (!empty($params['is_for_organization'])) {
133 // @todo - deprecate is_for_organization, require modified_id
134 $targetContactID = $params['modified_id'] ?? NULL;
135 }
136
137 // add custom field values
138 if (!empty($params['custom']) && is_array($params['custom'])
139 ) {
140 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
141 }
142
143 if ($id) {
144 if ($membership->status_id != $oldStatus) {
145 CRM_Activity_BAO_Activity::addActivity($membership,
146 'Change Membership Status',
147 NULL,
148 [
149 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
150 'source_contact_id' => $membershipLog['modified_id'],
151 'priority_id' => 'Normal',
152 ]
153 );
154 }
155 if (isset($membership->membership_type_id) && $membership->membership_type_id != $oldType) {
156 $membershipTypes = CRM_Member_BAO_Membership::buildOptions('membership_type_id', 'get');
157 CRM_Activity_BAO_Activity::addActivity($membership,
158 'Change Membership Type',
159 NULL,
160 [
161 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
162 'source_contact_id' => $membershipLog['modified_id'],
163 'priority_id' => 'Normal',
164 ]
165 );
166 }
167
168 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
169 $activityParams['id'] = civicrm_api3('Activity', 'Get', [
170 'source_record_id' => $membership->id,
171 'activity_type_id' => $activityType,
172 'status_id' => 'Scheduled',
173 ])['id'] ?? NULL;
174 // 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership
175 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
176 if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) || $activityType == 'Membership Renewal')) {
177 CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID, $activityParams);
178 break;
179 }
180 }
181
182 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
183 }
184 else {
185 CRM_Activity_BAO_Activity::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams);
186 CRM_Utils_Hook::post('create', 'Membership', $membership->id, $membership);
187 }
188
189 return $membership;
190 }
191
192 /**
193 * Fetch the object and store the values in the values array.
194 *
195 * @param array $params
196 * Input parameters to find object.
197 * @param array $values
198 * Output values of the object.
199 * @param bool $active
200 * Do you want only active memberships to.
201 * be returned
202 *
203 * @return CRM_Member_BAO_Membership|null
204 * The found object or null
205 */
206 public static function &getValues(&$params, &$values, $active = FALSE) {
207 if (empty($params)) {
208 return NULL;
209 }
210 $membership = new CRM_Member_BAO_Membership();
211
212 $membership->copyValues($params);
213 $membership->find();
214 $memberships = [];
215 while ($membership->fetch()) {
216 if ($active &&
217 (!CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
218 $membership->status_id,
219 'is_current_member'
220 ))
221 ) {
222 continue;
223 }
224
225 CRM_Core_DAO::storeValues($membership, $values[$membership->id]);
226 $memberships[$membership->id] = $membership;
227 }
228
229 return $memberships;
230 }
231
232 /**
233 * Takes an associative array and creates a membership object.
234 *
235 * @param array $params
236 * (reference ) an assoc array of name/value pairs.
237 * @param array $ids
238 * Deprecated parameter The array that holds all the db ids.
239 *
240 * @return CRM_Member_BAO_Membership|CRM_Core_Error
241 * @throws \CiviCRM_API3_Exception
242 *
243 * @throws CRM_Core_Exception
244 */
245 public static function create(&$params, &$ids = []) {
246 // always calculate status if is_override/skipStatusCal is not true.
247 // giving respect to is_override during import. CRM-4012
248
249 // To skip status calculation we should use 'skipStatusCal'.
250 // eg pay later membership, membership update cron CRM-3984
251
252 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
253 // @todo - we should be able to count on dates being correctly formatted by they time they hit the BAO.
254 // Maybe do some tests & throw some deprecation warnings if they aren't?
255 $params['start_date'] = trim($params['start_date']) ? date('Ymd', strtotime(trim($params['start_date']))) : 'null';
256 $params['end_date'] = trim($params['end_date']) ? date('Ymd', strtotime(trim($params['end_date']))) : 'null';
257 $params['join_date'] = trim($params['join_date']) ? date('Ymd', strtotime(trim($params['join_date']))) : 'null';
258
259 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
260 $excludeIsAdmin = $params['exclude_is_admin'] ?? FALSE;
261
262 //CRM-3724 always skip is_admin if is_override != true.
263 if (!$excludeIsAdmin && empty($params['is_override'])) {
264 $excludeIsAdmin = TRUE;
265 }
266
267 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($params['start_date'], $params['end_date'], $params['join_date'],
268 'now', $excludeIsAdmin, $params['membership_type_id'] ?? NULL, $params
269 );
270 if (empty($calcStatus)) {
271 throw new CRM_Core_Exception(ts("The membership cannot be saved because the status cannot be calculated for start_date: {$params['start_date']} end_date {$params['end_date']} join_date {$params['join_date']} as at " . date('Y-m-d H:i:s')));
272 }
273 $params['status_id'] = $calcStatus['id'];
274 }
275
276 // data cleanup only: all verifications on number of related memberships are done upstream in:
277 // CRM_Member_BAO_Membership::createRelatedMemberships()
278 // CRM_Contact_BAO_Relationship::relatedMemberships()
279 if (!empty($params['owner_membership_id'])) {
280 unset($params['max_related']);
281 }
282 else {
283 // if membership allows related, default max_related to value in membership_type
284 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
285 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($params['membership_type_id']);
286 if (isset($membershipType['relationship_type_id'])) {
287 $params['max_related'] = $membershipType['max_related'] ?? NULL;
288 }
289 }
290 }
291
292 $transaction = new CRM_Core_Transaction();
293
294 $params['id'] = $params['id'] ?? $ids['membership'] ?? NULL;
295 $membership = self::add($params);
296
297 if (is_a($membership, 'CRM_Core_Error')) {
298 $transaction->rollback();
299 return $membership;
300 }
301
302 $params['membership_id'] = $membership->id;
303 // @todo further cleanup required to remove use of $ids['contribution'] from here
304 if (isset($ids['membership'])) {
305 $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
306 $membership->id,
307 'contribution_id',
308 'membership_id'
309 );
310 // @todo this is a temporary step to removing $ids['contribution'] completely
311 if (empty($params['contribution_id']) && !empty($ids['contribution'])) {
312 $params['contribution_id'] = $ids['contribution'];
313 }
314 }
315
316 // This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
317 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
318 CRM_Price_BAO_LineItem::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
319 }
320 $params['skipLineItem'] = TRUE;
321
322 // Record contribution for this membership and create a MembershipPayment
323 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
324 $memInfo = array_merge($params, ['membership_id' => $membership->id]);
325 $params['contribution'] = self::recordMembershipContribution($memInfo);
326 }
327
328 // Add/update MembershipPayment record for this membership if it is a related contribution
329 if (!empty($params['relate_contribution_id'])) {
330 $membershipPaymentParams = [
331 'membership_id' => $membership->id,
332 'membership_type_id' => $membership->membership_type_id,
333 'contribution_id' => $params['relate_contribution_id'],
334 ];
335 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
336 }
337
338 if (!empty($params['lineItems'])) {
339 $params['line_item'] = $params['lineItems'];
340 }
341
342 // do cleanup line items if membership edit the Membership type.
343 if (empty($ids['contribution']) && !empty($ids['membership'])) {
344 CRM_Price_BAO_LineItem::deleteLineItems($ids['membership'], 'civicrm_membership');
345 }
346 // @todo - we should ONLY do the below if a contribution is created. Let's
347 // get some deprecation notices in here & see where it's hit & work to eliminate.
348 // This could happen if there is no contribution or we are in one of many
349 // weird and wonderful flows. This is scary code. Keep adding tests.
350 if (!empty($params['line_item']) && empty($ids['contribution']) && empty($params['contribution_id'])) {
351
352 foreach ($params['line_item'] as $priceSetId => $lineItems) {
353 foreach ($lineItems as $lineIndex => $lineItem) {
354 $lineMembershipType = $lineItem['membership_type_id'] ?? NULL;
355 if (!empty($params['contribution'])) {
356 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id;
357 }
358 if ($lineMembershipType && $lineMembershipType == ($params['membership_type_id'] ?? NULL)) {
359 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id;
360 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
361 }
362 elseif (!$lineMembershipType && !empty($params['contribution'])) {
363 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id;
364 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
365 }
366 }
367 }
368 CRM_Price_BAO_LineItem::processPriceSet(
369 $membership->id,
370 $params['line_item'],
371 $params['contribution'] ?? NULL
372 );
373 }
374
375 $transaction->commit();
376
377 self::createRelatedMemberships($params, $membership);
378
379 if (empty($params['skipRecentView'])) {
380 self::addToRecentItems($membership);
381 }
382
383 return $membership;
384 }
385
386 /**
387 * @param \CRM_Member_DAO_Membership $membership
388 */
389 private static function addToRecentItems($membership) {
390 $url = CRM_Utils_System::url('civicrm/contact/view/membership',
391 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
392 );
393 if (empty($membership->membership_type_id)) {
394 // ie in an update situation.
395 $membership->find(TRUE);
396 }
397 $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:')
398 . ' ' . CRM_Core_PseudoConstant::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $membership->membership_type_id);
399
400 $recentOther = [];
401 if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
402 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
403 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
404 );
405 }
406 if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
407 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
408 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
409 );
410 }
411
412 // add the recently created Membership
413 CRM_Utils_Recent::add($title,
414 $url,
415 $membership->id,
416 'Membership',
417 $membership->contact_id,
418 NULL,
419 $recentOther
420 );
421 }
422
423 /**
424 * Check the membership extended through relationship.
425 *
426 * @param int $membershipTypeID
427 * Membership type id.
428 * @param int $contactId
429 * Contact id.
430 *
431 * @param int $action
432 *
433 * @return array
434 * array of contact_id of all related contacts.
435 *
436 * @throws \CRM_Core_Exception
437 * @throws \CiviCRM_API3_Exception
438 */
439 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action::ADD) {
440 $contacts = [];
441
442 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
443
444 $relationships = [];
445 if (isset($membershipType['relationship_type_id'])) {
446 $relationships = CRM_Contact_BAO_Relationship::getRelationship($contactId,
447 CRM_Contact_BAO_Relationship::CURRENT
448 );
449 if ($action & CRM_Core_Action::UPDATE) {
450 $pastRelationships = CRM_Contact_BAO_Relationship::getRelationship($contactId,
451 CRM_Contact_BAO_Relationship::PAST
452 );
453 $relationships = array_merge($relationships, $pastRelationships);
454 }
455 }
456
457 if (!empty($relationships)) {
458 // check for each contact relationships
459 foreach ($relationships as $values) {
460 //get details of the relationship type
461 $relType = ['id' => $values['civicrm_relationship_type_id']];
462 $relValues = [];
463 CRM_Contact_BAO_RelationshipType::retrieve($relType, $relValues);
464 // Check if contact's relationship type exists in membership type
465 $relTypeDirs = [];
466 $bidirectional = FALSE;
467 foreach ($membershipType['relationship_type_id'] as $key => $value) {
468 $relTypeDirs[] = $value . '_' . $membershipType['relationship_direction'][$key];
469 if (in_array($value, $relType) &&
470 $relValues['name_a_b'] == $relValues['name_b_a']
471 ) {
472 $bidirectional = TRUE;
473 break;
474 }
475 }
476 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
477 if ($bidirectional || in_array($relTypeDir, $relTypeDirs)) {
478 // $values['status'] is going to have value for
479 // current or past relationships.
480 $contacts[$values['cid']] = $values['status'];
481 }
482 }
483 }
484
485 // Sort by contact_id ascending
486 ksort($contacts);
487 return $contacts;
488 }
489
490 /**
491 * Retrieve DB object based on input parameters.
492 *
493 * It also stores all the retrieved values in the default array.
494 *
495 * @param array $params
496 * (reference ) an assoc array of name/value pairs.
497 * @param array $defaults
498 * (reference ) an assoc array to hold the name / value pairs.
499 * in a hierarchical manner
500 *
501 * @return CRM_Member_BAO_Membership
502 */
503 public static function retrieve(&$params, &$defaults) {
504 $membership = new CRM_Member_DAO_Membership();
505
506 $membership->copyValues($params);
507
508 if ($membership->find(TRUE)) {
509 CRM_Core_DAO::storeValues($membership, $defaults);
510
511 //get the membership status and type values.
512 $statusANDType = self::getStatusANDTypeValues($membership->id);
513 foreach (['status', 'membership_type'] as $fld) {
514 $defaults[$fld] = $statusANDType[$membership->id][$fld] ?? NULL;
515 }
516 if (!empty($statusANDType[$membership->id]['is_current_member'])) {
517 $defaults['active'] = TRUE;
518 }
519
520 return $membership;
521 }
522
523 return NULL;
524 }
525
526 /**
527 * Get membership status and membership type values.
528 *
529 * @param int $membershipId
530 * Membership id of values to return.
531 *
532 * @return array
533 * Array of key value pairs
534 */
535 public static function getStatusANDTypeValues($membershipId) {
536 $values = [];
537 if (!$membershipId) {
538 return $values;
539 }
540 $sql = '
541 SELECT membership.id as id,
542 status.id as status_id,
543 status.label as status,
544 status.is_current_member as is_current_member,
545 type.id as membership_type_id,
546 type.name as membership_type,
547 type.relationship_type_id as relationship_type_id
548 FROM civicrm_membership membership
549 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
550 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
551 WHERE membership.id = %1';
552 $dao = CRM_Core_DAO::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
553 $properties = [
554 'status',
555 'status_id',
556 'membership_type',
557 'membership_type_id',
558 'is_current_member',
559 'relationship_type_id',
560 ];
561 while ($dao->fetch()) {
562 foreach ($properties as $property) {
563 $values[$dao->id][$property] = $dao->$property;
564 }
565 }
566
567 return $values;
568 }
569
570 /**
571 * Delete membership.
572 *
573 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
574 *
575 * @param int $membershipId
576 * Membership id that needs to be deleted.
577 * @param bool $preserveContrib
578 *
579 * @return int
580 * Id of deleted Membership on success, false otherwise.
581 */
582 public static function del($membershipId, $preserveContrib = FALSE) {
583 //delete related first and then delete parent.
584 self::deleteRelatedMemberships($membershipId);
585 return self::deleteMembership($membershipId, $preserveContrib);
586 }
587
588 /**
589 * Delete membership.
590 *
591 * @param int $membershipId
592 * Membership id that needs to be deleted.
593 * @param bool $preserveContrib
594 *
595 * @return int
596 * Id of deleted Membership on success, false otherwise.
597 */
598 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
599 // CRM-12147, retrieve membership data before we delete it for hooks
600 $params = ['id' => $membershipId];
601 $memValues = [];
602 $memberships = self::getValues($params, $memValues);
603
604 $membership = $memberships[$membershipId];
605
606 CRM_Utils_Hook::pre('delete', 'Membership', $membershipId, $memValues);
607
608 $transaction = new CRM_Core_Transaction();
609
610 $results = NULL;
611 //delete activity record
612 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
613
614 $params = [];
615 $deleteActivity = FALSE;
616 $membershipActivities = [
617 'Membership Signup',
618 'Membership Renewal',
619 'Change Membership Status',
620 'Change Membership Type',
621 'Membership Renewal Reminder',
622 ];
623 foreach ($membershipActivities as $membershipActivity) {
624 $activityId = array_search($membershipActivity, $activityTypes);
625 if ($activityId) {
626 $params['activity_type_id'][] = $activityId;
627 $deleteActivity = TRUE;
628 }
629 }
630 if ($deleteActivity) {
631 $params['source_record_id'] = $membershipId;
632 CRM_Activity_BAO_Activity::deleteActivity($params);
633 }
634 self::deleteMembershipPayment($membershipId, $preserveContrib);
635 CRM_Price_BAO_LineItem::deleteLineItems($membershipId, 'civicrm_membership');
636
637 $results = $membership->delete();
638 $transaction->commit();
639
640 CRM_Utils_Hook::post('delete', 'Membership', $membership->id, $membership);
641
642 // delete the recently created Membership
643 $membershipRecent = [
644 'id' => $membershipId,
645 'type' => 'Membership',
646 ];
647 CRM_Utils_Recent::del($membershipRecent);
648
649 return $results;
650 }
651
652 /**
653 * Delete related memberships.
654 *
655 * @param int $ownerMembershipId
656 * @param int $contactId
657 *
658 * @return null
659 */
660 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
661 if (!$ownerMembershipId && !$contactId) {
662 return FALSE;
663 }
664
665 $membership = new CRM_Member_DAO_Membership();
666 $membership->owner_membership_id = $ownerMembershipId;
667
668 if ($contactId) {
669 $membership->contact_id = $contactId;
670 }
671
672 $membership->find();
673 while ($membership->fetch()) {
674 //delete related first and then delete parent.
675 self::deleteRelatedMemberships($membership->id);
676 self::deleteMembership($membership->id);
677 }
678 }
679
680 /**
681 * Obtain active/inactive memberships from the list of memberships passed to it.
682 *
683 * @param array $memberships
684 * Membership records.
685 * @param string $status
686 * Active or inactive.
687 *
688 * @return array
689 * array of memberships based on status
690 */
691 public static function activeMembers($memberships, $status = 'active') {
692 $actives = [];
693 if ($status == 'active') {
694 foreach ($memberships as $f => $v) {
695 if (!empty($v['active'])) {
696 $actives[$f] = $v;
697 }
698 }
699 return $actives;
700 }
701 elseif ($status == 'inactive') {
702 foreach ($memberships as $f => $v) {
703 if (empty($v['active'])) {
704 $actives[$f] = $v;
705 }
706 }
707 return $actives;
708 }
709 return NULL;
710 }
711
712 /**
713 * Return Membership Block info in Contribution Pages.
714 *
715 * @param int $pageID
716 * Contribution page id.
717 *
718 * @return array|null
719 */
720 public static function getMembershipBlock($pageID) {
721 $membershipBlock = [];
722 $dao = new CRM_Member_DAO_MembershipBlock();
723 $dao->entity_table = 'civicrm_contribution_page';
724
725 $dao->entity_id = $pageID;
726 $dao->is_active = 1;
727 if ($dao->find(TRUE)) {
728 CRM_Core_DAO::storeValues($dao, $membershipBlock);
729 if (!empty($membershipBlock['membership_types'])) {
730 $membershipTypes = CRM_Utils_String::unserialize($membershipBlock['membership_types']);
731 if (!is_array($membershipTypes)) {
732 return $membershipBlock;
733 }
734 $memTypes = [];
735 foreach ($membershipTypes as $key => $value) {
736 $membershipBlock['auto_renew'][$key] = $value;
737 $memTypes[$key] = $key;
738 }
739 $membershipBlock['membership_types'] = implode(',', $memTypes);
740 }
741 }
742 else {
743 return NULL;
744 }
745
746 return $membershipBlock;
747 }
748
749 /**
750 * Return a current membership of given contact.
751 *
752 * NB: if more than one membership meets criteria, a randomly selected one is returned.
753 *
754 * @param int $contactID
755 * Contact id.
756 * @param int $memType
757 * Membership type, null to retrieve all types.
758 * @param int $isTest
759 * @param int $membershipId
760 * If provided, then determine if it is current.
761 * @param bool $onlySameParentOrg
762 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
763 *
764 * @return array|bool
765 * @throws \CiviCRM_API3_Exception
766 */
767 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
768 //check for owner membership id, if it exists update that membership instead: CRM-15992
769 if ($membershipId) {
770 $ownerMemberId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
771 $membershipId,
772 'owner_membership_id', 'id'
773 );
774 if ($ownerMemberId) {
775 $membershipId = $ownerMemberId;
776 $contactID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
777 $membershipId,
778 'contact_id', 'id'
779 );
780 }
781 }
782
783 $dao = new CRM_Member_DAO_Membership();
784 if ($membershipId) {
785 $dao->id = $membershipId;
786 }
787 $dao->contact_id = $contactID;
788 $dao->membership_type_id = $memType;
789
790 //fetch proper membership record.
791 if ($isTest) {
792 $dao->is_test = $isTest;
793 }
794 else {
795 $dao->whereAdd('is_test IS NULL OR is_test = 0');
796 }
797
798 //avoid pending membership as current membership: CRM-3027
799 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant::membershipStatus())];
800 if (!$membershipId) {
801 // CRM-15475
802 $statusIds[] = array_search(
803 'Cancelled',
804 CRM_Member_PseudoConstant::membershipStatus(
805 NULL,
806 " name = 'Cancelled' ",
807 'name',
808 FALSE,
809 TRUE
810 )
811 );
812 }
813 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
814
815 // order by start date to find most recent membership first, CRM-4545
816 $dao->orderBy('start_date DESC');
817
818 // CRM-8141
819 if ($onlySameParentOrg && $memType) {
820 // require the same parent org as the $memType
821 $params = ['id' => $memType];
822 $membershipType = [];
823 if (CRM_Member_BAO_MembershipType::retrieve($params, $membershipType)) {
824 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
825 'member_of_contact_id' => $membershipType['member_of_contact_id'],
826 'options' => [
827 'limit' => 0,
828 ],
829 ]);
830 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg['values'] ?? []));
831 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
832 }
833 }
834
835 if ($dao->find(TRUE)) {
836 $membership = [];
837 CRM_Core_DAO::storeValues($dao, $membership);
838 $membership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
839 $membership['status_id'],
840 'is_current_member', 'id'
841 );
842 $ownerMemberId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
843 $membership['id'],
844 'owner_membership_id', 'id'
845 );
846 if ($ownerMemberId) {
847 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
848 $membership['membership_contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
849 $membership['id'],
850 'contact_id', 'id'
851 );
852 }
853 return $membership;
854 }
855
856 // CRM-8141
857 if ($onlySameParentOrg && $memType) {
858 // see if there is a membership that has same parent as $memType but different parent than $membershipID
859 if ($dao->id && CRM_Core_Permission::check('edit memberships')) {
860 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
861 $dao->whereAdd();
862 }
863 else {
864 unset($dao->id);
865 }
866
867 unset($dao->membership_type_id);
868 if ($dao->find(TRUE)) {
869 $membership = [];
870 CRM_Core_DAO::storeValues($dao, $membership);
871 $membership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
872 $membership['status_id'],
873 'is_current_member', 'id'
874 );
875 return $membership;
876 }
877 }
878 return FALSE;
879 }
880
881 /**
882 * Combine all the importable fields from the lower levels object.
883 *
884 * @param string $contactType
885 * Contact type.
886 * @param bool $status
887 *
888 * @return array
889 * array of importable Fields
890 * @throws \CRM_Core_Exception
891 */
892 public static function importableFields($contactType = 'Individual', $status = TRUE) {
893 $fields = Civi::cache('fields')->get('membership_importable_fields' . $contactType . $status);
894 if (!$fields) {
895 if (!$status) {
896 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
897 }
898 else {
899 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
900 }
901
902 $tmpFields = CRM_Member_DAO_Membership::import();
903 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
904
905 // Using new Dedupe rule.
906 $ruleParams = [
907 'contact_type' => $contactType,
908 'used' => 'Unsupervised',
909 ];
910 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
911
912 $tmpContactField = [];
913 if (is_array($fieldsArray)) {
914 foreach ($fieldsArray as $value) {
915 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
916 $value,
917 'id',
918 'column_name'
919 );
920 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
921 $tmpContactField[trim($value)] = $contactFields[trim($value)] ?? NULL;
922 if (!$status) {
923 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
924 }
925 else {
926 $title = $tmpContactField[trim($value)]['title'];
927 }
928 $tmpContactField[trim($value)]['title'] = $title;
929 }
930 }
931 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
932 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
933
934 $tmpFields['membership_contact_id']['title'] .= ' ' . ts('(match to contact)');
935
936 $fields = array_merge($fields, $tmpContactField);
937 $fields = array_merge($fields, $tmpFields);
938 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
939 Civi::cache('fields')->set('membership_importable_fields' . $contactType . $status, $fields);
940 }
941 return $fields;
942 }
943
944 /**
945 * Get all exportable fields.
946 *
947 * @return array return array of all exportable fields
948 */
949 public static function &exportableFields() {
950 $expFieldMembership = CRM_Member_DAO_Membership::export();
951
952 $expFieldsMemType = CRM_Member_DAO_MembershipType::export();
953 $fields = array_merge($expFieldMembership, $expFieldsMemType);
954 $fields = array_merge($fields, $expFieldMembership);
955 $membershipStatus = [
956 'membership_status' => [
957 'title' => ts('Membership Status'),
958 'name' => 'membership_status',
959 'type' => CRM_Utils_Type::T_STRING,
960 'where' => 'civicrm_membership_status.name',
961 ],
962 ];
963 //CRM-6161 fix for customdata export
964 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
965 $fields['membership_status_id'] = $membershipStatus['membership_status'];
966 return $fields;
967 }
968
969 /**
970 * Get membership joins/renewals for a specified membership type.
971 *
972 * Specifically, retrieves a count of memberships whose "Membership
973 * Signup" or "Membership Renewal" activity falls in the given date range.
974 * Dates match the pattern "yyyy-mm-dd".
975 *
976 * @param int $membershipTypeId
977 * Membership type id.
978 * @param int $startDate
979 * Date on which to start counting.
980 * @param int $endDate
981 * Date on which to end counting.
982 * @param bool|int $isTest if true, membership is for a test site
983 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
984 *
985 * @return int
986 * the number of members of type $membershipTypeId whose
987 * start_date is between $startDate and $endDate
988 */
989 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
990 // Ensure that the dates that are passed to the query are in the format of yyyy-mm-dd
991 $dates = ['startDate', 'endDate'];
992 foreach ($dates as $date) {
993 if (strlen($$date) === 8) {
994 $$date = date('Y-m-d', strtotime($$date));
995 }
996 }
997
998 $testClause = 'membership.is_test = 1';
999 if (!$isTest) {
1000 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1001 }
1002
1003 if (!self::$_signupActType || !self::$_renewalActType) {
1004 self::_getActTypes();
1005 }
1006
1007 if (!self::$_signupActType || !self::$_renewalActType) {
1008 return 0;
1009 }
1010
1011 $query = "
1012 SELECT COUNT(DISTINCT membership.id) as member_count
1013 FROM civicrm_membership membership
1014 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1015 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1016 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1017 WHERE membership.membership_type_id = %3
1018 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1019 AND {$testClause}";
1020
1021 $query .= ($isOwner) ? ' AND owner_membership_id IS NULL' : '';
1022
1023 $params = [
1024 1 => [self::$_signupActType, 'Integer'],
1025 2 => [self::$_renewalActType, 'Integer'],
1026 3 => [$membershipTypeId, 'Integer'],
1027 ];
1028
1029 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
1030 return (int) $memberCount;
1031 }
1032
1033 /**
1034 * Get a count of membership for a specified membership type, optionally for a specified date.
1035 *
1036 * The date must have the form yyyy-mm-dd.
1037 *
1038 * If $date is omitted, this function counts as a member anyone whose
1039 * membership status_id indicates they're a current member.
1040 * If $date is given, this function counts as a member anyone who:
1041 * -- Has a start_date before $date and end_date after $date, or
1042 * -- Has a start_date before $date and is currently a member, as indicated
1043 * by the the membership's status_id.
1044 * The second condition takes care of records that have no end_date. These
1045 * are assumed to be lifetime memberships.
1046 *
1047 * @param int $membershipTypeId
1048 * Membership type id.
1049 * @param string $date
1050 * The date for which to retrieve the count.
1051 * @param bool|int $isTest if true, membership is for a test site
1052 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1053 *
1054 * @return int
1055 * the number of members of type $membershipTypeId as of $date.
1056 */
1057 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1058 if (!CRM_Utils_Rule::date($date)) {
1059 throw new CRM_Core_Exception(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1060 }
1061
1062 $params = [
1063 1 => [$membershipTypeId, 'Integer'],
1064 2 => [$isTest, 'Boolean'],
1065 ];
1066 $query = "SELECT count(civicrm_membership.id ) as member_count
1067 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1068 WHERE civicrm_membership.membership_type_id = %1
1069 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1070 AND civicrm_membership.is_test = %2";
1071 if (!$date) {
1072 $query .= " AND civicrm_membership_status.is_current_member = 1";
1073 }
1074 else {
1075 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1076 }
1077 // LCD
1078 $query .= ($isOwner) ? ' AND owner_membership_id IS NULL' : '';
1079 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
1080 return (int) $memberCount;
1081 }
1082
1083 /**
1084 * Function check the status of the membership before adding membership for a contact.
1085 *
1086 * @return int
1087 */
1088 public static function statusAvailabilty() {
1089 $membership = new CRM_Member_DAO_MembershipStatus();
1090 $membership->whereAdd('is_active=1');
1091 return $membership->count();
1092 }
1093
1094 /**
1095 * @deprecated This is not used anywhere and should be removed soon!
1096 * Function for updating a membership record's contribution_recur_id.
1097 *
1098 * @param CRM_Member_DAO_Membership $membership
1099 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1100 */
1101 public static function updateRecurMembership(CRM_Member_DAO_Membership $membership, CRM_Contribute_BAO_Contribution $contribution) {
1102 CRM_Core_Error::deprecatedFunctionWarning('Use the API instead');
1103
1104 if (empty($contribution->contribution_recur_id)) {
1105 return;
1106 }
1107
1108 $params = [
1109 1 => [$contribution->contribution_recur_id, 'Integer'],
1110 2 => [$membership->id, 'Integer'],
1111 ];
1112
1113 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1114 CRM_Core_DAO::executeQuery($sql, $params);
1115 }
1116
1117 /**
1118 * Method to fix membership status of stale membership.
1119 *
1120 * This method first checks if the membership is stale. If it is,
1121 * then status will be updated based on existing start and end
1122 * dates and log will be added for the status change.
1123 *
1124 * @param array $currentMembership
1125 * Reference to the array.
1126 * containing all values of
1127 * the current membership
1128 * @param string $changeToday
1129 * In case today needs
1130 * to be customised, null otherwise
1131 *
1132 * @throws \CRM_Core_Exception
1133 */
1134 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1135 $today = 'now';
1136 if ($changeToday) {
1137 $today = CRM_Utils_Date::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1138 }
1139
1140 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(
1141 $currentMembership['start_date'] ?? NULL,
1142 $currentMembership['end_date'] ?? NULL,
1143 $currentMembership['join_date'] ?? NULL,
1144 $today,
1145 TRUE,
1146 $currentMembership['membership_type_id'],
1147 $currentMembership
1148 );
1149
1150 if (empty($status) || empty($status['id'])) {
1151 throw new CRM_Core_Exception(ts('Oops, it looks like there is no valid membership status corresponding to the membership start and end dates for this membership. Contact the site administrator for assistance.'));
1152 }
1153
1154 $currentMembership['today_date'] = $today;
1155
1156 if ($status['id'] !== $currentMembership['status_id']) {
1157 $oldStatus = $currentMembership['status_id'];
1158 $memberDAO = new CRM_Member_DAO_Membership();
1159 $memberDAO->id = $currentMembership['id'];
1160 $memberDAO->find(TRUE);
1161
1162 $memberDAO->status_id = $status['id'];
1163 $memberDAO->save();
1164 CRM_Core_DAO::storeValues($memberDAO, $currentMembership);
1165
1166 $currentMembership['is_current_member'] = CRM_Core_DAO::getFieldValue(
1167 'CRM_Member_DAO_MembershipStatus',
1168 $currentMembership['status_id'],
1169 'is_current_member'
1170 );
1171 $format = '%Y%m%d';
1172
1173 $logParams = [
1174 'membership_id' => $currentMembership['id'],
1175 'status_id' => $status['id'],
1176 'start_date' => CRM_Utils_Date::customFormat(
1177 $currentMembership['start_date'],
1178 $format
1179 ),
1180 'end_date' => CRM_Utils_Date::customFormat(
1181 $currentMembership['end_date'],
1182 $format
1183 ),
1184 'modified_date' => CRM_Utils_Date::customFormat(
1185 $currentMembership['today_date'],
1186 $format
1187 ),
1188 'membership_type_id' => $currentMembership['membership_type_id'],
1189 'max_related' => $currentMembership['max_related'] ?? 0,
1190 ];
1191
1192 $session = CRM_Core_Session::singleton();
1193 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1194 if ($session->get('userID')) {
1195 $logParams['modified_id'] = $session->get('userID');
1196 }
1197 else {
1198 $logParams['modified_id'] = $currentMembership['contact_id'];
1199 }
1200
1201 //Create activity for status change.
1202 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
1203 CRM_Activity_BAO_Activity::addActivity($memberDAO,
1204 'Change Membership Status',
1205 NULL,
1206 [
1207 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1208 'source_contact_id' => $logParams['modified_id'],
1209 'priority_id' => 'Normal',
1210 ]
1211 );
1212
1213 CRM_Member_BAO_MembershipLog::add($logParams);
1214 }
1215 }
1216
1217 /**
1218 * Get the contribution page id from the membership record.
1219 *
1220 * @param int $membershipID
1221 *
1222 * @return int
1223 * contribution page id
1224 */
1225 public static function getContributionPageId($membershipID) {
1226 $query = "
1227 SELECT c.contribution_page_id as pageID
1228 FROM civicrm_membership_payment mp, civicrm_contribution c
1229 WHERE mp.contribution_id = c.id
1230 AND c.contribution_page_id IS NOT NULL
1231 AND mp.membership_id = " . CRM_Utils_Type::escape($membershipID, 'Integer')
1232 . " ORDER BY mp.id DESC";
1233
1234 return CRM_Core_DAO::singleValueQuery($query);
1235 }
1236
1237 /**
1238 * Updated related memberships.
1239 *
1240 * @param int $ownerMembershipId
1241 * Owner Membership Id.
1242 * @param array $params
1243 * Formatted array of key => value.
1244 */
1245 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1246 $membership = new CRM_Member_DAO_Membership();
1247 $membership->owner_membership_id = $ownerMembershipId;
1248 $membership->find();
1249
1250 while ($membership->fetch()) {
1251 $relatedMembership = new CRM_Member_DAO_Membership();
1252 $relatedMembership->id = $membership->id;
1253 $relatedMembership->copyValues($params);
1254 $relatedMembership->save();
1255 }
1256
1257 }
1258
1259 /**
1260 * Get list of membership fields for profile.
1261 *
1262 * For now we only allow custom membership fields to be in
1263 * profile
1264 *
1265 * @param null $mode
1266 * FIXME: This param is ignored
1267 *
1268 * @return array
1269 * the list of membership fields
1270 */
1271 public static function getMembershipFields($mode = NULL) {
1272 $fields = CRM_Member_DAO_Membership::export();
1273
1274 unset($fields['membership_contact_id']);
1275 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
1276
1277 $membershipType = CRM_Member_DAO_MembershipType::export();
1278
1279 $membershipStatus = CRM_Member_DAO_MembershipStatus::export();
1280
1281 $fields = array_merge($fields, $membershipType, $membershipStatus);
1282
1283 return $fields;
1284 }
1285
1286 /**
1287 * Get the sort name of a contact for a particular membership.
1288 *
1289 * @param int $id
1290 * Id of the membership.
1291 *
1292 * @return null|string
1293 * sort name of the contact if found
1294 */
1295 public static function sortName($id) {
1296 $id = CRM_Utils_Type::escape($id, 'Integer');
1297
1298 $query = "
1299 SELECT civicrm_contact.sort_name
1300 FROM civicrm_membership, civicrm_contact
1301 WHERE civicrm_membership.contact_id = civicrm_contact.id
1302 AND civicrm_membership.id = {$id}
1303 ";
1304 return CRM_Core_DAO::singleValueQuery($query);
1305 }
1306
1307 /**
1308 * Create memberships for related contacts, taking into account the maximum related memberships.
1309 *
1310 * @param array $params
1311 * Array of key - value pairs.
1312 * @param CRM_Core_DAO $dao
1313 * Membership object.
1314 *
1315 * @throws \CRM_Core_Exception
1316 * @throws \CiviCRM_API3_Exception
1317 */
1318 public static function createRelatedMemberships($params, $dao) {
1319
1320 $membership = new CRM_Member_DAO_Membership();
1321 $membership->id = $dao->id;
1322
1323 // required since create method doesn't return all the
1324 // parameters in the returned membership object
1325 if (!$membership->find(TRUE)) {
1326 return;
1327 }
1328 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
1329 // FIXME : While updating/ renewing the
1330 // membership, if the relationship is PAST then
1331 // the membership of the related contact must be
1332 // expired.
1333 // For that, getting Membership Status for which
1334 // is_current_member is 0. It works for the
1335 // generated data as there is only one membership
1336 // status having is_current_member = 0.
1337 // But this wont work exactly if there will be
1338 // more than one status having is_current_member = 0.
1339 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1340 $membershipStatus->is_current_member = 0;
1341 if ($membershipStatus->find(TRUE)) {
1342 $expiredStatusId = $membershipStatus->id;
1343 }
1344 else {
1345 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant::membershipStatus());
1346 }
1347
1348 $relatedContacts = [];
1349 $allRelatedContacts = CRM_Member_BAO_Membership::checkMembershipRelationship($membership->membership_type_id,
1350 $membership->contact_id,
1351 $params['action'] ?? NULL
1352 );
1353
1354 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1355 // Remove repeated related contacts, which already inherited membership of this type$relatedContactIds[$membership->contact_id][$membership->membership_type_id] = TRUE;
1356 foreach ($allRelatedContacts as $cid => $status) {
1357 // relatedContactIDs is always empty now - will remove next roud because of whitespace readability.
1358 if (empty($relatedContactIds[$cid]) || empty($relatedContactIds[$cid][$membership->membership_type_id])) {
1359 $relatedContactIds[$cid][$membership->membership_type_id] = TRUE;
1360
1361 //don't create membership again for owner contact.
1362 $nestedRelationship = FALSE;
1363 if ($membership->owner_membership_id) {
1364 $nestedRelMembership = new CRM_Member_DAO_Membership();
1365 $nestedRelMembership->id = $membership->owner_membership_id;
1366 $nestedRelMembership->contact_id = $cid;
1367 $nestedRelationship = $nestedRelMembership->find(TRUE);
1368 }
1369 if (!$nestedRelationship) {
1370 $relatedContacts[$cid] = $status;
1371 }
1372 }
1373 }
1374
1375 //lets cleanup related membership if any.
1376 if (empty($relatedContacts)) {
1377 self::deleteRelatedMemberships($membership->id);
1378 }
1379 else {
1380 // Edit the params array
1381 unset($params['id']);
1382 // Reminder should be sent only to the direct membership
1383 unset($params['reminder_date']);
1384 // unset the custom value ids
1385 if (isset($params['custom']) && is_array($params['custom'])) {
1386 foreach ($params['custom'] as $k => $values) {
1387 foreach ($values as $i => $value) {
1388 unset($params['custom'][$k][$i]['id']);
1389 }
1390 }
1391 }
1392 if (!isset($params['membership_type_id'])) {
1393 $params['membership_type_id'] = $membership->membership_type_id;
1394 }
1395
1396 // max_related should be set in the parent membership
1397 unset($params['max_related']);
1398 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1399 $numRelatedAvailable = ($membership->max_related == NULL ? PHP_INT_MAX : $membership->max_related);
1400 // will be used to queue potential memberships to be created.
1401 $queue = [];
1402
1403 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1404 //use existing membership record.
1405 $relMembership = new CRM_Member_DAO_Membership();
1406 $relMembership->contact_id = $contactId;
1407 $relMembership->owner_membership_id = $membership->id;
1408
1409 if ($relMembership->find(TRUE)) {
1410 $params['id'] = $relMembership->id;
1411 }
1412 else {
1413 unset($params['id']);
1414 }
1415
1416 $params['contact_id'] = $contactId;
1417 $params['owner_membership_id'] = $membership->id;
1418
1419 // set status_id as it might have been changed for
1420 // past relationship
1421 $params['status_id'] = $membership->status_id;
1422
1423 if ($deceasedStatusId &&
1424 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1425 ) {
1426 $params['status_id'] = $deceasedStatusId;
1427 }
1428 elseif ((($params['action'] ?? NULL) & CRM_Core_Action::UPDATE) &&
1429 ($relationshipStatus == CRM_Contact_BAO_Relationship::PAST)
1430 ) {
1431 $params['status_id'] = $expiredStatusId;
1432 }
1433
1434 //don't calculate status again in create( );
1435 $params['skipStatusCal'] = TRUE;
1436
1437 //do create activity if we changed status.
1438 if ($params['status_id'] != $relMembership->status_id) {
1439 $params['createActivity'] = TRUE;
1440 }
1441
1442 //CRM-20707 - include start/end date
1443 $params['start_date'] = $membership->start_date;
1444 $params['end_date'] = $membership->end_date;
1445
1446 // we should not created contribution record for related contacts, CRM-3371
1447 unset($params['contribution_status_id']);
1448
1449 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1450 unset($params['lineItems']);
1451 unset($params['line_item']);
1452
1453 // CRM-20966: Do not create membership_payment record for inherited membership.
1454 unset($params['relate_contribution_id']);
1455
1456 $ids = [];
1457 if (($params['status_id'] == $deceasedStatusId) || ($params['status_id'] == $expiredStatusId)) {
1458 // related membership is not active so does not count towards maximum
1459 if (!self::hasExistingInheritedMembership($params)) {
1460 CRM_Member_BAO_Membership::create($params);
1461 }
1462 }
1463 else {
1464 // related membership already exists, so this is just an update
1465 if (isset($params['id'])) {
1466 if ($numRelatedAvailable > 0) {
1467 CRM_Member_BAO_Membership::create($params);
1468 $numRelatedAvailable--;
1469 }
1470 else {
1471 // we have run out of inherited memberships, so delete extras
1472 self::deleteMembership($params['id']);
1473 }
1474 // we need to first check if there will remain inherited memberships, so queue it up
1475 }
1476 else {
1477 $queue[] = $params;
1478 }
1479 }
1480 }
1481 // now go over the queue and create any available related memberships
1482 foreach ($queue as $params) {
1483 if ($numRelatedAvailable <= 0) {
1484 break;
1485 }
1486 if (!self::hasExistingInheritedMembership($params)) {
1487 CRM_Member_BAO_Membership::create($params);
1488 }
1489 $numRelatedAvailable--;
1490 }
1491 }
1492 }
1493
1494 /**
1495 * Delete the record that are associated with this Membership Payment.
1496 *
1497 * @param int $membershipId
1498 * @param bool $preserveContrib
1499 *
1500 * @return object
1501 * $membershipPayment deleted membership payment object
1502 */
1503 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1504
1505 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1506 $membershipPayment->membership_id = $membershipId;
1507 $membershipPayment->find();
1508
1509 while ($membershipPayment->fetch()) {
1510 if (!$preserveContrib) {
1511 CRM_Contribute_BAO_Contribution::deleteContribution($membershipPayment->contribution_id);
1512 }
1513 CRM_Utils_Hook::pre('delete', 'MembershipPayment', $membershipPayment->id, $membershipPayment);
1514 $membershipPayment->delete();
1515 CRM_Utils_Hook::post('delete', 'MembershipPayment', $membershipPayment->id, $membershipPayment);
1516 }
1517 return $membershipPayment;
1518 }
1519
1520 /**
1521 * Build an array of available membership types.
1522 *
1523 * @param CRM_Core_Form $form
1524 * @param array $membershipTypeID
1525 * @param bool $activeOnly
1526 * Do we only want active ones?
1527 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1528 * behaviour unchanged).
1529 *
1530 * @return array
1531 *
1532 * @throws \CiviCRM_API3_Exception
1533 */
1534 public static function buildMembershipTypeValues($form, $membershipTypeID = [], $activeOnly = FALSE) {
1535 $membershipTypeIDS = (array) $membershipTypeID;
1536 $membershipTypeValues = CRM_Member_BAO_MembershipType::getPermissionedMembershipTypes();
1537
1538 // MembershipTypes are already filtered by domain, filter as appropriate by is_active & a passed in list of ids.
1539 foreach ($membershipTypeValues as $id => $type) {
1540 if (($activeOnly && empty($type['is_active']))
1541 || (!empty($membershipTypeIDS) && !in_array($id, $membershipTypeIDS, FALSE))
1542 ) {
1543 unset($membershipTypeValues[$id]);
1544 }
1545 }
1546
1547 CRM_Utils_Hook::membershipTypeValues($form, $membershipTypeValues);
1548
1549 if (is_numeric($membershipTypeID) &&
1550 $membershipTypeID > 0
1551 ) {
1552 CRM_Core_Error::deprecatedFunctionWarning('Non arrays deprecated');
1553 return $membershipTypeValues[$membershipTypeID];
1554 }
1555 return $membershipTypeValues;
1556 }
1557
1558 /**
1559 * Get membership record count for a Contact.
1560 *
1561 * @param int $contactID
1562 * @param bool $activeOnly
1563 *
1564 * @return null|string
1565 */
1566 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1567 CRM_Financial_BAO_FinancialType::getAvailableMembershipTypes($membershipTypes);
1568 $addWhere = " AND membership_type_id IN (0)";
1569 if (!empty($membershipTypes)) {
1570 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1571 }
1572 $select = "SELECT count(*) FROM civicrm_membership ";
1573 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1574
1575 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1576 if ($activeOnly) {
1577 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1578 $where .= " and civicrm_membership_status.is_current_member = 1";
1579 }
1580
1581 $query = $select . $where . $addWhere;
1582 return CRM_Core_DAO::singleValueQuery($query);
1583 }
1584
1585 /**
1586 * Check whether payment processor supports cancellation of membership subscription.
1587 *
1588 * @param int $mid
1589 * Membership id.
1590 *
1591 * @param bool $isNotCancelled
1592 *
1593 * @return bool
1594 */
1595 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1596 $cacheKeyString = "$mid";
1597 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
1598
1599 static $supportsCancel = [];
1600
1601 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1602 $supportsCancel[$cacheKeyString] = FALSE;
1603 $isCancelled = FALSE;
1604
1605 if ($isNotCancelled) {
1606 $isCancelled = self::isSubscriptionCancelled($mid);
1607 }
1608
1609 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($mid, 'membership', 'obj');
1610 if (!empty($paymentObject)) {
1611 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1612 }
1613 }
1614 return $supportsCancel[$cacheKeyString];
1615 }
1616
1617 /**
1618 * Check whether subscription is already cancelled.
1619 *
1620 * @param int $mid
1621 * Membership id.
1622 *
1623 * @return string
1624 * contribution status
1625 */
1626 public static function isSubscriptionCancelled($mid) {
1627 $sql = "
1628 SELECT cr.contribution_status_id
1629 FROM civicrm_contribution_recur cr
1630 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1631 WHERE mem.id = %1 LIMIT 1";
1632 $params = [1 => [$mid, 'Integer']];
1633 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
1634 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name');
1635 if ($status == 'Cancelled') {
1636 return TRUE;
1637 }
1638 return FALSE;
1639 }
1640
1641 /**
1642 * Get membership joins for a specified membership type.
1643 *
1644 * Specifically, retrieves a count of still current memberships whose
1645 * join_date and start_date are within a specified date range. Dates match
1646 * the pattern "yyyy-mm-dd".
1647 *
1648 * @param int $membershipTypeId
1649 * Membership type id.
1650 * @param int $startDate
1651 * Date on which to start counting.
1652 * @param int $endDate
1653 * Date on which to end counting.
1654 * @param bool|int $isTest if true, membership is for a test site
1655 *
1656 * @return int
1657 * the number of members of type $membershipTypeId
1658 * whose join_date is between $startDate and $endDate and
1659 * whose start_date is between $startDate and $endDate
1660 */
1661 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1662 $testClause = 'membership.is_test = 1';
1663 if (!$isTest) {
1664 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1665 }
1666 if (!self::$_signupActType) {
1667 self::_getActTypes();
1668 }
1669
1670 if (!self::$_signupActType) {
1671 return 0;
1672 }
1673
1674 $query = "
1675 SELECT COUNT(DISTINCT membership.id) as member_count
1676 FROM civicrm_membership membership
1677 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1678 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1679 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1680 WHERE membership.membership_type_id = %2
1681 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1682 AND {$testClause}";
1683
1684 $params = [
1685 1 => [self::$_signupActType, 'Integer'],
1686 2 => [$membershipTypeId, 'Integer'],
1687 ];
1688
1689 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
1690
1691 return (int) $memberCount;
1692 }
1693
1694 /**
1695 * Get membership renewals for a specified membership type.
1696 *
1697 * Specifically, retrieves a count of still current memberships
1698 * whose join_date is before and start_date is within a specified date
1699 * range. Dates match the pattern "yyyy-mm-dd".
1700 *
1701 * @param int $membershipTypeId
1702 * Membership type id.
1703 * @param int $startDate
1704 * Date on which to start counting.
1705 * @param int $endDate
1706 * Date on which to end counting.
1707 * @param bool|int $isTest if true, membership is for a test site
1708 *
1709 * @return int
1710 * returns the number of members of type $membershipTypeId
1711 * whose join_date is before $startDate and
1712 * whose start_date is between $startDate and $endDate
1713 */
1714 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1715 $testClause = 'membership.is_test = 1';
1716 if (!$isTest) {
1717 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1718 }
1719 if (!self::$_renewalActType) {
1720 self::_getActTypes();
1721 }
1722
1723 if (!self::$_renewalActType) {
1724 return 0;
1725 }
1726
1727 $query = "
1728 SELECT COUNT(DISTINCT membership.id) as member_count
1729 FROM civicrm_membership membership
1730 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1731 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1732 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1733 WHERE membership.membership_type_id = %2
1734 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1735 AND {$testClause}";
1736
1737 $params = [
1738 1 => [self::$_renewalActType, 'Integer'],
1739 2 => [$membershipTypeId, 'Integer'],
1740 ];
1741 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
1742
1743 return (int) $memberCount;
1744 }
1745
1746 /**
1747 * @param int $contactID
1748 * @param int $membershipTypeID
1749 * @param bool $is_test
1750 * @param string $changeToday
1751 * @param int $modifiedID
1752 * @param $customFieldsFormatted
1753 * @param $numRenewTerms
1754 * @param int $membershipID
1755 * @param $pending
1756 * @param int $contributionRecurID
1757 * @param $membershipSource
1758 * @param $isPayLater
1759 * @param int $campaignId
1760 * @param array $formDates
1761 * @param null|CRM_Contribute_BAO_Contribution $contribution
1762 * @param array $lineItems
1763 *
1764 * @return array
1765 * @throws \CRM_Core_Exception
1766 * @throws \CiviCRM_API3_Exception
1767 */
1768 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = [], $contribution = NULL, $lineItems = []) {
1769 $renewalMode = $updateStatusId = FALSE;
1770 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1771 $format = '%Y%m%d';
1772 $statusFormat = '%Y-%m-%d';
1773 $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
1774 $dates = [];
1775 $ids = [];
1776
1777 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1778 // is the same as the parent org of an existing membership of the contact
1779 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID,
1780 $is_test, $membershipID, TRUE
1781 );
1782 if ($currentMembership) {
1783 $renewalMode = TRUE;
1784
1785 // Do NOT do anything.
1786 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1787 //2. Paylater/IPN renew. CRM-4556.
1788 if ($pending || in_array($currentMembership['status_id'], [
1789 array_search('Pending', $allStatus),
1790 // CRM-15475
1791 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1792 ])) {
1793
1794 $memParams = [
1795 'id' => $currentMembership['id'],
1796 'contribution' => $contribution,
1797 'status_id' => $currentMembership['status_id'],
1798 'start_date' => $currentMembership['start_date'],
1799 'end_date' => $currentMembership['end_date'],
1800 'line_item' => $lineItems,
1801 'join_date' => $currentMembership['join_date'],
1802 'membership_type_id' => $membershipTypeID,
1803 'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL,
1804 'membership_activity_status' => ($pending || $isPayLater) ? 'Scheduled' : 'Completed',
1805 ];
1806 if ($contributionRecurID) {
1807 $memParams['contribution_recur_id'] = $contributionRecurID;
1808 }
1809
1810 $membership = self::create($memParams);
1811 return [$membership, $renewalMode, $dates];
1812 }
1813
1814 // Check and fix the membership if it is STALE
1815 self::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1816
1817 // Now Renew the membership
1818 if (!$currentMembership['is_current_member']) {
1819 // membership is not CURRENT
1820
1821 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1822 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
1823 $changeToday,
1824 $membershipTypeID,
1825 $numRenewTerms
1826 );
1827
1828 $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1829 foreach (['start_date', 'end_date'] as $dateType) {
1830 $currentMembership[$dateType] = $formDates[$dateType] ?? NULL;
1831 if (empty($currentMembership[$dateType])) {
1832 $currentMembership[$dateType] = $dates[$dateType] ?? NULL;
1833 }
1834 }
1835 $currentMembership['is_test'] = $is_test;
1836
1837 if (!empty($membershipSource)) {
1838 $currentMembership['source'] = $membershipSource;
1839 }
1840
1841 if (!empty($currentMembership['id'])) {
1842 $ids['membership'] = $currentMembership['id'];
1843 }
1844 $memParams = $currentMembership;
1845 $memParams['membership_type_id'] = $membershipTypeID;
1846
1847 //set the log start date.
1848 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
1849 }
1850 else {
1851
1852 // CURRENT Membership
1853 $membership = new CRM_Member_DAO_Membership();
1854 $membership->id = $currentMembership['id'];
1855 $membership->find(TRUE);
1856 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1857 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
1858 $changeToday,
1859 $membershipTypeID,
1860 $numRenewTerms
1861 );
1862
1863 // Insert renewed dates for CURRENT membership
1864 $memParams = [];
1865 $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date);
1866 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date::isoToMysql($membership->start_date);
1867 $memParams['end_date'] = $formDates['end_date'] ?? NULL;
1868 if (empty($memParams['end_date'])) {
1869 $memParams['end_date'] = $dates['end_date'] ?? NULL;
1870 }
1871 $memParams['membership_type_id'] = $membershipTypeID;
1872
1873 //set the log start date.
1874 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
1875
1876 //CRM-18067
1877 if (!empty($membershipSource)) {
1878 $memParams['source'] = $membershipSource;
1879 }
1880 elseif (empty($membership->source)) {
1881 $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
1882 $currentMembership['id'],
1883 'source'
1884 );
1885 }
1886
1887 if (!empty($currentMembership['id'])) {
1888 $ids['membership'] = $currentMembership['id'];
1889 }
1890 $memParams['membership_activity_status'] = ($pending || $isPayLater) ? 'Scheduled' : 'Completed';
1891 }
1892 }
1893 else {
1894 // NEW Membership
1895 $memParams = [
1896 'contact_id' => $contactID,
1897 'membership_type_id' => $membershipTypeID,
1898 ];
1899
1900 if (!$pending) {
1901 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1902
1903 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1904 $memParams[$dateType] = $formDates[$dateType] ?? NULL;
1905 if (empty($memParams[$dateType])) {
1906 $memParams[$dateType] = $dates[$dateType] ?? NULL;
1907 }
1908 }
1909
1910 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'],
1911 $statusFormat
1912 ),
1913 CRM_Utils_Date::customFormat($dates['end_date'],
1914 $statusFormat
1915 ),
1916 CRM_Utils_Date::customFormat($dates['join_date'],
1917 $statusFormat
1918 ),
1919 'now',
1920 TRUE,
1921 $membershipTypeID,
1922 $memParams
1923 );
1924 $updateStatusId = $status['id'] ?? NULL;
1925 }
1926 else {
1927 // if IPN/Pay-Later set status to: PENDING
1928 $updateStatusId = array_search('Pending', $allStatus);
1929 }
1930
1931 if (!empty($membershipSource)) {
1932 $memParams['source'] = $membershipSource;
1933 }
1934 $memParams['is_test'] = $is_test;
1935 $memParams['is_pay_later'] = $isPayLater;
1936 }
1937 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1938 // perhaps shouldn't be?
1939 if ($contributionRecurID) {
1940 $memParams['contribution_recur_id'] = $contributionRecurID;
1941 }
1942 //CRM-4555
1943 //if we decided status here and want to skip status
1944 //calculation in create( ); then need to pass 'skipStatusCal'.
1945 if ($updateStatusId) {
1946 $memParams['status_id'] = $updateStatusId;
1947 $memParams['skipStatusCal'] = TRUE;
1948 }
1949
1950 //since we are renewing,
1951 //make status override false.
1952 $memParams['is_override'] = FALSE;
1953
1954 //CRM-4027, create log w/ individual contact.
1955 if ($modifiedID) {
1956 // @todo this param is likely unused now.
1957 $memParams['is_for_organization'] = TRUE;
1958 }
1959 $params['modified_id'] = $modifiedID ?? $contactID;
1960
1961 //inherit campaign from contrib page.
1962 if (isset($campaignId)) {
1963 $memParams['campaign_id'] = $campaignId;
1964 }
1965
1966 $memParams['contribution'] = $contribution;
1967 $memParams['custom'] = $customFieldsFormatted;
1968 // Load all line items & process all in membership. Don't do in contribution.
1969 // Relevant tests in api_v3_ContributionPageTest.
1970 $memParams['line_item'] = $lineItems;
1971 // @todo stop passing $ids (membership and userId may be set by this point)
1972 $membership = self::create($memParams, $ids);
1973
1974 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1975 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1976 $membership->find(TRUE);
1977
1978 return [$membership, $renewalMode, $dates];
1979 }
1980
1981 /**
1982 * Get line items representing the default price set.
1983 *
1984 * @param int $membershipOrg
1985 * @param int $membershipTypeID
1986 * @param float $total_amount
1987 * @param int $priceSetId
1988 *
1989 * @return array
1990 */
1991 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
1992 $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1993
1994 // The name of the price field corresponds to the membership_type organization contact.
1995 $params = [
1996 'price_set_id' => $priceSetId,
1997 'name' => $membershipOrg,
1998 ];
1999 $results = [];
2000 CRM_Price_BAO_PriceField::retrieve($params, $results);
2001
2002 if (!empty($results)) {
2003 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2004 $fid = $results['id'];
2005 $editedFieldParams = [
2006 'price_field_id' => $results['id'],
2007 'membership_type_id' => $membershipTypeID,
2008 ];
2009 $results = [];
2010 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $results);
2011 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2012 if (!empty($total_amount)) {
2013 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2014 }
2015 }
2016
2017 $fieldID = key($fields);
2018 $returnParams = [
2019 'price_set_id' => $priceSetId,
2020 'price_sets' => $priceSets,
2021 'fields' => $fields,
2022 'price_fields' => [
2023 'price_' . $fieldID => $results['id'] ?? NULL,
2024 ],
2025 ];
2026 return $returnParams;
2027 }
2028
2029 /**
2030 * Update the status of all deceased members to deceased.
2031 *
2032 * @return int
2033 * Count of updated contacts.
2034 *
2035 * @throws \CiviCRM_API3_Exception
2036 * @throws \CRM_Core_Exception
2037 */
2038 protected static function updateDeceasedMembersStatuses() {
2039 $count = 0;
2040
2041 $deceasedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2042
2043 // 'create' context for buildOptions returns only if enabled.
2044 $allStatus = self::buildOptions('status_id', 'create');
2045 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2046 // Deceased status is an admin status & is required. We want to fail early if
2047 // it is not present or active.
2048 // We could make the case 'some databases just don't use deceased so we will check
2049 // for the presence of a deceased contact in the DB before rejecting.
2050 if (CRM_Core_DAO::singleValueQuery('
2051 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2052 )) {
2053 throw new CRM_Core_Exception(
2054 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2055 [1 => CRM_Utils_System::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2056 ));
2057 }
2058 }
2059 $deceasedDAO = CRM_Core_DAO::executeQuery(
2060 $baseQuery = "
2061 SELECT membership.id as membership_id
2062 FROM civicrm_membership membership
2063 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2064 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2065 AND civicrm_membership_type.is_active = 1
2066 WHERE membership.is_test = 0
2067 AND civicrm_contact.is_deceased = 1
2068 AND membership.status_id <> %1
2069 ",
2070 [1 => [$deceasedStatusId, 'Integer']]
2071 );
2072 while ($deceasedDAO->fetch()) {
2073 civicrm_api3('membership', 'create', [
2074 'id' => $deceasedDAO->membership_id,
2075 'status_id' => $deceasedStatusId,
2076 'createActivity' => TRUE,
2077 'skipStatusCal' => TRUE,
2078 'skipRecentView' => TRUE,
2079 ]);
2080 $count++;
2081 }
2082 return $count;
2083 }
2084
2085 /**
2086 * Does the existing membership match the required membership.
2087 *
2088 * Check before updating that the params are not a match - this is part of avoiding
2089 * a loop if we have already updated.
2090 *
2091 * https://issues.civicrm.org/jira/browse/CRM-4213
2092 * @param array $params
2093 *
2094 * @param array $membership
2095 *
2096 * @return bool
2097 */
2098 protected static function matchesRequiredMembership($params, $membership) {
2099 foreach (['start_date', 'end_date'] as $date) {
2100 if (strtotime($params[$date]) !== strtotime($membership[$date])) {
2101 return FALSE;
2102 }
2103 if ((int) $params['status_id'] !== (int) $membership['status_id']) {
2104 return FALSE;
2105 }
2106 if ((int) $params['membership_type_id'] !== (int) $membership['membership_type_id']) {
2107 return FALSE;
2108 }
2109 }
2110 return TRUE;
2111 }
2112
2113 /**
2114 * Params of new membership.
2115 *
2116 * @param array $params
2117 *
2118 * @return bool
2119 * @throws \CiviCRM_API3_Exception
2120 */
2121 protected static function hasExistingInheritedMembership($params) {
2122 foreach (civicrm_api3('Membership', 'get', ['contact_id' => $params['contact_id']])['values'] as $membership) {
2123 if (!empty($membership['owner_membership_id'])
2124 && $membership['membership_type_id'] === $params['membership_type_id']
2125 && (int) $params['owner_membership_id'] !== (int) $membership['owner_membership_id']
2126 ) {
2127 // Inheriting it from another contact, don't update here.
2128 return TRUE;
2129 }
2130 if (self::matchesRequiredMembership($params, $membership)) {
2131 return TRUE;
2132 }
2133 }
2134 return FALSE;
2135 }
2136
2137 /**
2138 * Process price set and line items.
2139 *
2140 * @param int $membershipId
2141 * @param array $lineItem
2142 *
2143 * @throws \CiviCRM_API3_Exception
2144 */
2145 public function processPriceSet($membershipId, $lineItem) {
2146 //FIXME : need to move this too
2147 if (!$membershipId || !is_array($lineItem)
2148 || CRM_Utils_System::isNull($lineItem)
2149 ) {
2150 return;
2151 }
2152
2153 foreach ($lineItem as $priceSetId => $values) {
2154 if (!$priceSetId) {
2155 continue;
2156 }
2157 foreach ($values as $line) {
2158 $line['entity_table'] = 'civicrm_membership';
2159 $line['entity_id'] = $membershipId;
2160 CRM_Price_BAO_LineItem::create($line);
2161 }
2162 }
2163 }
2164
2165 /**
2166 * Retrieve the contribution id for the associated Membership id.
2167 * @todo we should get this off the line item
2168 *
2169 * @param int $membershipId
2170 * Membership id.
2171 * @param bool $all
2172 * if more than one payment associated with membership id need to be returned.
2173 *
2174 * @return int|int[]
2175 * contribution id
2176 * @todo we should get this off the line item
2177 *
2178 */
2179 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2180
2181 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2182 $membershipPayment->membership_id = $membershipId;
2183 if ($all && $membershipPayment->find()) {
2184 $contributionIds = [];
2185 while ($membershipPayment->fetch()) {
2186 $contributionIds[] = $membershipPayment->contribution_id;
2187 }
2188 return $contributionIds;
2189 }
2190
2191 if ($membershipPayment->find(TRUE)) {
2192 return $membershipPayment->contribution_id;
2193 }
2194 return NULL;
2195 }
2196
2197 /**
2198 * The function checks and updates the status of all membership records for a given domain using the
2199 * calc_membership_status and update_contact_membership APIs.
2200 *
2201 * IMPORTANT:
2202 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2203 *
2204 * @param array $params
2205 * only_active_membership_types, exclude_test_memberships, exclude_membership_status_ids
2206 *
2207 * @return array
2208 *
2209 * @throws \CiviCRM_API3_Exception
2210 * @throws \CRM_Core_Exception
2211 */
2212 public static function updateAllMembershipStatus($params = []) {
2213 // We want all of the statuses as id => name, even the disabled ones (cf.
2214 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2215 // Expired.
2216 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'validate');
2217 if (empty($params['exclude_membership_status_ids'])) {
2218 $params['exclude_membership_status_ids'] = [
2219 array_search('Pending', $allStatus),
2220 array_search('Cancelled', $allStatus),
2221 array_search('Expired', $allStatus) ?: 0,
2222 array_search('Deceased', $allStatus),
2223 ];
2224 }
2225 // Deceased is *always* excluded because it is has very specific processing below.
2226 elseif (!in_array(array_search('Deceased', $allStatus), $params['exclude_membership_status_ids'])) {
2227 $params['exclude_membership_status_ids'][] = array_search('Deceased', $allStatus);
2228 }
2229
2230 for ($index = 0; $index < count($params['exclude_membership_status_ids']); $index++) {
2231 $queryParams[$index] = [$params['exclude_membership_status_ids'][$index], 'Integer'];
2232 }
2233 $membershipStatusClause = 'civicrm_membership.status_id NOT IN (%' . implode(', %', array_keys($queryParams)) . ')';
2234
2235 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2236
2237 $updateCount = $processCount = self::updateDeceasedMembersStatuses();
2238
2239 $whereClauses[] = 'civicrm_contact.is_deceased = 0';
2240 if ($params['exclude_test_memberships']) {
2241 $whereClauses[] = 'civicrm_membership.is_test = 0';
2242 }
2243 $whereClause = implode(' AND ', $whereClauses);
2244 $activeMembershipClause = '';
2245 if ($params['only_active_membership_types']) {
2246 $activeMembershipClause = ' AND civicrm_membership_type.is_active = 1';
2247 }
2248
2249 // This query retrieves ALL memberships of active types.
2250 $baseQuery = "
2251 SELECT civicrm_membership.id as membership_id,
2252 civicrm_membership.is_override as is_override,
2253 civicrm_membership.status_override_end_date as status_override_end_date,
2254 civicrm_membership.membership_type_id as membership_type_id,
2255 civicrm_membership.status_id as status_id,
2256 civicrm_membership.join_date as join_date,
2257 civicrm_membership.start_date as start_date,
2258 civicrm_membership.end_date as end_date,
2259 civicrm_membership.source as source,
2260 civicrm_contact.id as contact_id,
2261 civicrm_membership.owner_membership_id as owner_membership_id,
2262 civicrm_membership.contribution_recur_id as recur_id
2263 FROM civicrm_membership
2264 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2265 INNER JOIN civicrm_membership_type ON
2266 (civicrm_membership.membership_type_id = civicrm_membership_type.id {$activeMembershipClause})
2267 WHERE {$whereClause}";
2268
2269 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2270 $dao1 = CRM_Core_DAO::executeQuery($query);
2271 while ($dao1->fetch()) {
2272 self::processOverriddenUntilDateMembership($dao1);
2273 }
2274
2275 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2276 AND {$membershipStatusClause}
2277 AND civicrm_membership.owner_membership_id IS NULL ";
2278
2279 $allMembershipTypes = CRM_Member_BAO_MembershipType::getAllMembershipTypes();
2280
2281 $dao2 = CRM_Core_DAO::executeQuery($query, $queryParams);
2282
2283 while ($dao2->fetch()) {
2284 $processCount++;
2285
2286 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2287 //get the membership status as per id.
2288 $newStatus = civicrm_api3('membership_status', 'calc',
2289 [
2290 'membership_id' => $dao2->membership_id,
2291 'ignore_admin_only' => TRUE,
2292 ], TRUE
2293 );
2294 $statusId = $newStatus['id'] ?? NULL;
2295
2296 //process only when status change.
2297 if ($statusId &&
2298 $statusId != $dao2->status_id
2299 ) {
2300 $memberParams = [
2301 'id' => $dao2->membership_id,
2302 'skipStatusCal' => TRUE,
2303 'skipRecentView' => TRUE,
2304 'status_id' => $statusId,
2305 'createActivity' => TRUE,
2306 ];
2307
2308 //process member record.
2309 civicrm_api3('membership', 'create', $memberParams);
2310 $updateCount++;
2311 }
2312 }
2313 $result['is_error'] = 0;
2314 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2315 1 => $processCount,
2316 2 => $updateCount,
2317 ]);
2318 return $result;
2319 }
2320
2321 /**
2322 * Set is_override for the 'overridden until date' membership to
2323 * False and clears the 'until date' field in case the 'until date'
2324 * is equal or after today date.
2325 *
2326 * @param CRM_Core_DAO $membership
2327 * The membership to be processed
2328 *
2329 * @throws \CiviCRM_API3_Exception
2330 */
2331 private static function processOverriddenUntilDateMembership($membership) {
2332 $isOverriddenUntilDate = !empty($membership->is_override) && !empty($membership->status_override_end_date);
2333 if (!$isOverriddenUntilDate) {
2334 return;
2335 }
2336
2337 $todayDate = new DateTime();
2338 $todayDate->setTime(0, 0);
2339
2340 $overrideEndDate = new DateTime($membership->status_override_end_date);
2341 $overrideEndDate->setTime(0, 0);
2342
2343 $datesDifference = $todayDate->diff($overrideEndDate);
2344 $daysDifference = (int) $datesDifference->format('%R%a');
2345 if ($daysDifference <= 0) {
2346 $params = [
2347 'id' => $membership->membership_id,
2348 'is_override' => FALSE,
2349 'status_override_end_date' => 'null',
2350 ];
2351 civicrm_api3('membership', 'create', $params);
2352 }
2353 }
2354
2355 /**
2356 * Returns the membership types for a particular contact
2357 * who has lifetime membership without end date.
2358 *
2359 * @param int $contactID
2360 * @param bool $isTest
2361 * @param bool $onlyLifeTime
2362 *
2363 * @return array
2364 */
2365 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2366 $contactMembershipType = [];
2367 if (!$contactID) {
2368 return $contactMembershipType;
2369 }
2370
2371 $dao = new CRM_Member_DAO_Membership();
2372 $dao->contact_id = $contactID;
2373 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant::membershipStatus());
2374 $dao->whereAdd("status_id != $pendingStatusId");
2375
2376 if ($isTest) {
2377 $dao->is_test = $isTest;
2378 }
2379 else {
2380 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2381 }
2382
2383 if ($onlyLifeTime) {
2384 $dao->whereAdd('end_date IS NULL');
2385 }
2386
2387 $dao->find();
2388 while ($dao->fetch()) {
2389 $membership = [];
2390 CRM_Core_DAO::storeValues($dao, $membership);
2391 $contactMembershipType[$dao->membership_type_id] = $membership;
2392 }
2393 return $contactMembershipType;
2394 }
2395
2396 /**
2397 * Record contribution record associated with membership.
2398 * This will update an existing contribution if $params['contribution_id'] is passed in.
2399 * This will create a MembershipPayment to link the contribution and membership
2400 *
2401 * @param array $params
2402 * Array of submitted params.
2403 *
2404 * @return CRM_Contribute_BAO_Contribution
2405 * @throws \CRM_Core_Exception
2406 * @throws \CiviCRM_API3_Exception
2407 */
2408 public static function recordMembershipContribution(&$params) {
2409 $membershipId = $params['membership_id'];
2410 $contributionParams = [];
2411 $config = CRM_Core_Config::singleton();
2412 $contributionParams['currency'] = $config->defaultCurrency;
2413 $contributionParams['receipt_date'] = !empty($params['receipt_date']) ? $params['receipt_date'] : 'null';
2414 $contributionParams['source'] = $params['contribution_source'] ?? NULL;
2415 $contributionParams['non_deductible_amount'] = 'null';
2416 $contributionParams['skipCleanMoney'] = TRUE;
2417 $contributionParams['payment_processor'] = $params['payment_processor_id'] ?? NULL;
2418 $contributionSoftParams = $params['soft_credit'] ?? NULL;
2419 $recordContribution = [
2420 'contact_id',
2421 'fee_amount',
2422 'total_amount',
2423 'receive_date',
2424 'financial_type_id',
2425 'payment_instrument_id',
2426 'trxn_id',
2427 'invoice_id',
2428 'is_test',
2429 'contribution_status_id',
2430 'check_number',
2431 'campaign_id',
2432 'is_pay_later',
2433 'membership_id',
2434 'tax_amount',
2435 'skipLineItem',
2436 'contribution_recur_id',
2437 'pan_truncation',
2438 'card_type_id',
2439 ];
2440 foreach ($recordContribution as $f) {
2441 $contributionParams[$f] = $params[$f] ?? NULL;
2442 }
2443
2444 if (!empty($params['contribution_id'])) {
2445 $contributionParams['id'] = $params['contribution_id'];
2446 }
2447 // make entry in batch entity batch table
2448 if (!empty($params['batch_id'])) {
2449 $contributionParams['batch_id'] = $params['batch_id'];
2450 }
2451
2452 if (!empty($params['contribution_contact_id'])) {
2453 // deal with possibility of a different person paying for contribution
2454 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2455 }
2456
2457 if (!empty($params['processPriceSet']) &&
2458 !empty($params['lineItems'])
2459 ) {
2460 $contributionParams['line_item'] = $params['lineItems'] ?? NULL;
2461 }
2462
2463 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams);
2464
2465 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2466 if (!empty($contributionSoftParams)) {
2467 if (!empty($params['batch_id'])) {
2468 foreach ($contributionSoftParams as $contributionSoft) {
2469 $contributionSoft['contribution_id'] = $contribution->id;
2470 $contributionSoft['currency'] = $contribution->currency;
2471 CRM_Contribute_BAO_ContributionSoft::add($contributionSoft);
2472 }
2473 }
2474 else {
2475 $contributionSoftParams['contribution_id'] = $contribution->id;
2476 $contributionSoftParams['currency'] = $contribution->currency;
2477 $contributionSoftParams['amount'] = $contribution->total_amount;
2478 CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams);
2479 }
2480 }
2481
2482 // store contribution id
2483 $params['contribution_id'] = $contribution->id;
2484
2485 // Create membership payment if it does not already exist
2486 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2487 'contribution_id' => $contribution->id,
2488 ]);
2489 if (empty($membershipPayment['count'])) {
2490 civicrm_api3('MembershipPayment', 'create', [
2491 'membership_id' => $membershipId,
2492 'contribution_id' => $contribution->id,
2493 ]);
2494 }
2495
2496 return $contribution;
2497 }
2498
2499 /**
2500 * @todo document me - I seem a bit out of date....
2501 */
2502 public static function _getActTypes() {
2503 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
2504 self::$_renewalActType = CRM_Utils_Array::key('Membership Renewal', $activityTypes);
2505 self::$_signupActType = CRM_Utils_Array::key('Membership Signup', $activityTypes);
2506 }
2507
2508 /**
2509 * Get all Cancelled Membership(s) for a contact
2510 *
2511 * @param int $contactID
2512 * Contact id.
2513 * @param bool $isTest
2514 * Mode of payment.
2515 *
2516 * @return array
2517 * Array of membership type
2518 */
2519 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2520 if (!$contactID) {
2521 return [];
2522 }
2523 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2524 $queryParams = [
2525 1 => [$contactID, 'Integer'],
2526 2 => [
2527 // CRM-15475
2528 array_search(
2529 'Cancelled',
2530 CRM_Member_PseudoConstant::membershipStatus(
2531 NULL,
2532 " name = 'Cancelled' ",
2533 'name',
2534 FALSE,
2535 TRUE
2536 )
2537 ),
2538 'Integer',
2539 ],
2540 3 => [$isTest, 'Boolean'],
2541 ];
2542
2543 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
2544 $cancelledMembershipIds = [];
2545 while ($dao->fetch()) {
2546 $cancelledMembershipIds[] = $dao->membership_type_id;
2547 }
2548 return $cancelledMembershipIds;
2549 }
2550
2551 /**
2552 * Merges the memberships from otherContactID to mainContactID.
2553 *
2554 * General idea is to merge memberships in regards to their type. We
2555 * move the other contact’s contributions to the main contact’s
2556 * membership which has the same type (if any) and then we update
2557 * membership to avoid loosing `join_date`, `end_date`, and
2558 * `status_id`. In this function, we don’t touch the contributions
2559 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2560 * of it).
2561 *
2562 * This function adds new SQL queries to the $sqlQueries parameter.
2563 *
2564 * @param int $mainContactID
2565 * Contact id of main contact record.
2566 * @param int $otherContactID
2567 * Contact id of record which is going to merge.
2568 * @param array $sqlQueries
2569 * (reference) array of SQL queries to be executed.
2570 * @param array $tables
2571 * List of tables that have to be merged.
2572 * @param array $tableOperations
2573 * Special options/params for some tables to be merged.
2574 *
2575 * @see CRM_Dedupe_Merger::cpTables()
2576 */
2577 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2578 /*
2579 * If the user requests not to merge memberships but to add them,
2580 * just attribute the `civicrm_membership` to the
2581 * `$mainContactID`. We have to do this here since the general
2582 * merge process is bypassed by this function.
2583 */
2584 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2585 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2586 return;
2587 }
2588
2589 /*
2590 * Retrieve all memberships that belongs to each contacts and
2591 * keep track of each membership type.
2592 */
2593 $mainContactMemberships = [];
2594 $otherContactMemberships = [];
2595
2596 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2597 $dao = CRM_Core_DAO::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2598 while ($dao->fetch()) {
2599 $mainContactMemberships[$dao->id] = $dao->membership_type_id;
2600 }
2601
2602 $dao = CRM_Core_DAO::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2603 while ($dao->fetch()) {
2604 $otherContactMemberships[$dao->id] = $dao->membership_type_id;
2605 }
2606
2607 /*
2608 * For each membership, move related contributions to the main
2609 * contact’s membership (by updating `membership_payments`). Then,
2610 * update membership’s `join_date` (if the other membership’s
2611 * join_date is older) and `end_date` (if the other membership’s
2612 * `end_date` is newer) and `status_id` (if the newly calculated
2613 * status is different).
2614 *
2615 * FIXME: what should we do if we have multiple memberships with
2616 * the same type (currently we only take the first one)?
2617 */
2618 $newSql = [];
2619 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2620 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2621
2622 /*
2623 * Move other membership’s contributions to the main one only
2624 * if user requested to merge contributions.
2625 */
2626 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2627 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2628 }
2629
2630 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2631
2632 $newMembership = CRM_Member_DAO_Membership::findById($newMembershipId);
2633 $otherMembership = CRM_Member_DAO_Membership::findById($otherMembershipId);
2634
2635 $updates = [];
2636 if (new DateTime($otherMembership->join_date) < new DateTime($newMembership->join_date)) {
2637 $updates["join_date"] = $otherMembership->join_date;
2638 }
2639
2640 if (new DateTime($otherMembership->end_date) > new DateTime($newMembership->end_date)) {
2641 $updates["end_date"] = $otherMembership->end_date;
2642 }
2643
2644 if (count($updates)) {
2645
2646 /*
2647 * Update status
2648 */
2649 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(
2650 $updates["start_date"] ?? $newMembership->start_date,
2651 $updates["end_date"] ?? $newMembership->end_date,
2652 $updates["join_date"] ?? $newMembership->join_date,
2653 'now',
2654 FALSE,
2655 $newMembershipId,
2656 $newMembership
2657 );
2658
2659 if (!empty($status['id']) and $status['id'] != $newMembership->status_id) {
2660 $updates['status_id'] = $status['id'];
2661 }
2662
2663 $updates_sql = [];
2664 foreach ($updates as $k => $v) {
2665 $updates_sql[] = "$k = '{$v}'";
2666 }
2667
2668 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2669 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2670 }
2671
2672 }
2673 }
2674
2675 $sqlQueries = array_merge($sqlQueries, $newSql);
2676 }
2677
2678 /**
2679 * Update membership status to deceased.
2680 * function return the status message for updated membership.
2681 *
2682 * @param array $deceasedParams
2683 * - contact id
2684 * - is_deceased
2685 * - deceased_date
2686 *
2687 * @param string $contactType
2688 *
2689 * @return null|string
2690 * $updateMembershipMsg string status message for updated membership.
2691 */
2692 public static function updateMembershipStatus($deceasedParams, $contactType) {
2693 $updateMembershipMsg = NULL;
2694 $contactId = $deceasedParams['contact_id'];
2695 $deceasedDate = $deceasedParams['deceased_date'];
2696
2697 // process to set membership status to deceased for both active/inactive membership
2698 if ($contactId &&
2699 $contactType === 'Individual' &&
2700 !empty($deceasedParams['is_deceased'])
2701 ) {
2702
2703 $userId = CRM_Core_Session::getLoggedInContactID() ?: $contactId;
2704
2705 // get deceased status id
2706 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
2707 $deceasedStatusId = array_search('Deceased', $allStatus);
2708 if (!$deceasedStatusId) {
2709 return $updateMembershipMsg;
2710 }
2711
2712 $today = time();
2713 if ($deceasedDate && strtotime($deceasedDate) > $today) {
2714 return $updateMembershipMsg;
2715 }
2716
2717 // get non deceased membership
2718 $dao = new CRM_Member_DAO_Membership();
2719 $dao->contact_id = $contactId;
2720 $dao->whereAdd("status_id != $deceasedStatusId");
2721 $dao->find();
2722 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
2723 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
2724 $memCount = 0;
2725 while ($dao->fetch()) {
2726 // update status to deceased (for both active/inactive membership )
2727 CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $dao->id,
2728 'status_id', $deceasedStatusId
2729 );
2730
2731 // add membership log
2732 $membershipLog = [
2733 'membership_id' => $dao->id,
2734 'status_id' => $deceasedStatusId,
2735 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
2736 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
2737 'modified_id' => $userId,
2738 'modified_date' => date('Ymd'),
2739 'membership_type_id' => $dao->membership_type_id,
2740 'max_related' => $dao->max_related,
2741 ];
2742
2743 CRM_Member_BAO_MembershipLog::add($membershipLog);
2744
2745 //create activity when membership status is changed
2746 $activityParam = [
2747 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
2748 'source_contact_id' => $userId,
2749 'target_contact_id' => $dao->contact_id,
2750 'source_record_id' => $dao->id,
2751 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
2752 'status_id' => 2,
2753 'version' => 3,
2754 'priority_id' => 2,
2755 'activity_date_time' => date('Y-m-d H:i:s'),
2756 'is_auto' => 0,
2757 'is_current_revision' => 1,
2758 'is_deleted' => 0,
2759 ];
2760 civicrm_api('activity', 'create', $activityParam);
2761
2762 $memCount++;
2763 }
2764
2765 // set status msg
2766 if ($memCount) {
2767 CRM_Core_Session::setStatus(ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
2768 [1 => $memCount]
2769 ));
2770 }
2771 }
2772 return $updateMembershipMsg;
2773 }
2774
2775 }