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