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