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