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