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