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