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