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