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