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