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