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