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