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