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