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