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