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