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