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