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