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