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