Merge pull request #5292 from jitendrapurohit/CRM-15933
[civicrm-core.git] / CRM / Member / BAO / Membership.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Member_BAO_Membership extends CRM_Member_DAO_Membership {
36
37 /**
fe482240 38 * Static field for all the membership information that we can potentially import.
6a488035
TO
39 *
40 * @var array
6a488035
TO
41 */
42 static $_importableFields = NULL;
8ef12e64 43
4e636a74 44 static $_renewalActType = NULL;
8ef12e64 45
4e636a74 46 static $_signupActType = NULL;
8ef12e64 47
bb3a214a 48 /**
fe482240 49 * Class constructor.
bb3a214a 50 *
bb3a214a
EM
51 * @return \CRM_Member_DAO_Membership
52 */
53 /**
bb3a214a 54 */
00be9182 55 public function __construct() {
6a488035
TO
56 parent::__construct();
57 }
58
59 /**
fe482240 60 * Takes an associative array and creates a membership object.
6a488035
TO
61 *
62 * the function extracts all the params it needs to initialize the created
63 * membership object. The params array could contain additional unused name/value
64 * pairs
65 *
b2363ea8
TO
66 * @param array $params
67 * (reference ) an assoc array of name/value pairs.
68 * @param array $ids
69 * The array that holds all the db ids.
6a488035 70 *
16b10e64 71 * @return CRM_Member_BAO_Membership
6a488035 72 */
00be9182 73 public static function add(&$params, $ids = array()) {
a5e2b32e 74 $oldStatus = $oldType = NULL;
f880fd16
EM
75 $params['id'] = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('membership', $ids));
76 if ($params['id']) {
77 CRM_Utils_Hook::pre('edit', 'Membership', $params['id'], $params);
78 }
79 else {
1acc24d5 80 CRM_Utils_Hook::pre('create', 'Membership', NULL, $params);
f880fd16
EM
81 }
82 $id = $params['id'];
83 // we do this after the hooks are called in case it has been altered
84 if ($id) {
85 $membershipObj = new CRM_Member_DAO_Membership();
86 $membershipObj->id = $id;
6a488035
TO
87 $membershipObj->find();
88 while ($membershipObj->fetch()) {
89 $oldStatus = $membershipObj->status_id;
90 $oldType = $membershipObj->membership_type_id;
91 }
92 }
6a488035
TO
93
94 if (array_key_exists('is_override', $params) && !$params['is_override']) {
95 $params['is_override'] = 'null';
96 }
97
98 $membership = new CRM_Member_BAO_Membership();
99 $membership->copyValues($params);
f880fd16 100 $membership->id = $id;
6a488035
TO
101
102 $membership->save();
103 $membership->free();
104
6a488035
TO
105 if (empty($membership->contact_id) || empty($membership->status_id)) {
106 // this means we are in renewal mode and are just updating the membership
107 // record or this is an API update call and all fields are not present in the update record
b204fd50 108 // however the hooks don't care and want all data CRM-7784
6a488035
TO
109 $tempMembership = new CRM_Member_DAO_Membership();
110 $tempMembership->id = $membership->id;
111 $tempMembership->find(TRUE);
112 $membership = $tempMembership;
113 }
114
115 //get the log start date.
116 //it is set during renewal of membership.
ca58d9b9 117 $logStartDate = CRM_Utils_Array::value('log_start_date', $params);
6a488035 118 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : CRM_Utils_Date::isoToMysql($membership->start_date);
e0556ebe 119 $values = self::getStatusANDTypeValues($membership->id);
6a488035
TO
120
121 $membershipLog = array(
122 'membership_id' => $membership->id,
123 'status_id' => $membership->status_id,
124 'start_date' => $logStartDate,
125 'end_date' => CRM_Utils_Date::isoToMysql($membership->end_date),
126 'modified_date' => date('Ymd'),
127 'membership_type_id' => $values[$membership->id]['membership_type_id'],
128 'max_related' => $membership->max_related,
129 );
130
131 $session = CRM_Core_Session::singleton();
132 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
133 if ($session->get('userID')) {
134 $membershipLog['modified_id'] = $session->get('userID');
135 }
136 elseif (!empty($ids['userId'])) {
137 $membershipLog['modified_id'] = $ids['userId'];
138 }
139 else {
140 $membershipLog['modified_id'] = $membership->contact_id;
141 }
142
143 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
144
145 // reset the group contact cache since smart groups might be affected due to this
146 CRM_Contact_BAO_GroupContactCache::remove();
147
f880fd16 148 if ($id) {
6a488035 149 if ($membership->status_id != $oldStatus) {
4d63cfde 150 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
6a488035
TO
151 $activityParam = array(
152 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
153 'source_contact_id' => $membershipLog['modified_id'],
154 'target_contact_id' => $membership->contact_id,
155 'source_record_id' => $membership->id,
4d63cfde 156 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'),
6a488035 157 'status_id' => 2,
6a488035
TO
158 'priority_id' => 2,
159 'activity_date_time' => date('Y-m-d H:i:s'),
6a488035 160 );
4d63cfde 161 civicrm_api3('activity', 'create', $activityParam);
6a488035
TO
162 }
163 if (isset($membership->membership_type_id) && $membership->membership_type_id != $oldType) {
4d63cfde 164 $membershipTypes = CRM_Member_BAO_Membership::buildOptions('membership_type_id', 'get');
6a488035
TO
165 $activityParam = array(
166 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
167 'source_contact_id' => $membershipLog['modified_id'],
168 'target_contact_id' => $membership->contact_id,
169 'source_record_id' => $membership->id,
bd38fe3f 170 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'),
6a488035 171 'status_id' => 2,
6a488035
TO
172 'priority_id' => 2,
173 'activity_date_time' => date('Y-m-d H:i:s'),
6a488035 174 );
4d63cfde 175 civicrm_api3('activity', 'create', $activityParam);
6a488035
TO
176 }
177 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
178 }
179 else {
180 CRM_Utils_Hook::post('create', 'Membership', $membership->id, $membership);
181 }
182
183 return $membership;
184 }
185
186 /**
187 * Given the list of params in the params array, fetch the object
188 * and store the values in the values array
189 *
b2363ea8
TO
190 * @param array $params
191 * Input parameters to find object.
192 * @param array $values
193 * Output values of the object.
194 * @param bool $active
195 * Do you want only active memberships to.
6a488035
TO
196 * be returned
197 *
198 * @return CRM_Member_BAO_Membership|null the found object or null
6a488035 199 */
00be9182 200 public static function &getValues(&$params, &$values, $active = FALSE) {
6a488035
TO
201 if (empty($params)) {
202 return NULL;
203 }
204 $membership = new CRM_Member_BAO_Membership();
205
206 $membership->copyValues($params);
207 $membership->find();
208 $memberships = array();
209 while ($membership->fetch()) {
210 if ($active &&
211 (!CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
e0556ebe
TO
212 $membership->status_id,
213 'is_current_member'
214 ))
6a488035
TO
215 ) {
216 continue;
217 }
218
219 CRM_Core_DAO::storeValues($membership, $values[$membership->id]);
220 $memberships[$membership->id] = $membership;
221 }
222
223 return $memberships;
224 }
225
226 /**
fe482240 227 * Takes an associative array and creates a membership object.
6a488035 228 *
b2363ea8
TO
229 * @param array $params
230 * (reference ) an assoc array of name/value pairs.
231 * @param array $ids
232 * The array that holds all the db ids.
8efea814
EM
233 * @param bool $skipRedirect
234 * @param string $activityType
235 *
236 * @throws CRM_Core_Exception
6a488035 237 *
906e6120 238 * @return CRM_Member_BAO_Membership|CRM_Core_Error
6a488035 239 */
00be9182 240 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup') {
6a488035
TO
241 // always calculate status if is_override/skipStatusCal is not true.
242 // giving respect to is_override during import. CRM-4012
243
244 // To skip status calculation we should use 'skipStatusCal'.
245 // eg pay later membership, membership update cron CRM-3984
246
8cc574cf 247 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
0042ddd9 248 $dates = array('start_date', 'end_date', 'join_date');
ca58d9b9 249 $start_date = $end_date = $join_date = NULL; // declare these out of courtesy as IDEs don't pick up the setting of them below
0042ddd9 250 foreach ($dates as $date) {
b5588874 251 $$date = $params[$date] = CRM_Utils_Date::processDate(CRM_Utils_Array::value($date, $params), NULL, TRUE, 'Ymd');
6a488035
TO
252 }
253
254 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
255 $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, FALSE);
256
257 //CRM-3724 always skip is_admin if is_override != true.
8cc574cf 258 if (!$excludeIsAdmin && empty($params['is_override'])) {
6a488035
TO
259 $excludeIsAdmin = TRUE;
260 }
261
01f6b47e 262 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($start_date, $end_date, $join_date,
5f11bbcc 263 'today', $excludeIsAdmin, CRM_Utils_Array::value('membership_type_id', $params), $params
6a488035
TO
264 );
265 if (empty($calcStatus)) {
dcc4f6a7 266 // Redirect the form in case of error
267 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
268 // however since we have no idea how (if) this is triggered we can't safely move / remove it
269 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
270 // and am convinced form validation is complete on that form WRT this error.
271 $errorParams = array(
272 'message_title' => ts('No valid membership status for given dates.'),
273 'legacy_redirect_path' => 'civicrm/contact/view',
274 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
275 );
8c33a68c 276 throw new CRM_Core_Exception(ts('The membership cannot be saved because the status cannot be calculated.'), 0, $errorParams);
6a488035
TO
277 }
278 $params['status_id'] = $calcStatus['id'];
279 }
280
281 // data cleanup only: all verifications on number of related memberships are done upstream in:
282 // CRM_Member_BAO_Membership::createRelatedMemberships()
283 // CRM_Contact_BAO_Relationship::relatedMemberships()
284 if (isset($params['owner_membership_id'])) {
285 unset($params['max_related']);
8efea814
EM
286 }
287 else {
6a488035
TO
288 // if membership allows related, default max_related to value in membership_type
289 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
290 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($params['membership_type_id']);
291 if (isset($membershipType['relationship_type_id'])) {
292 $params['max_related'] = CRM_Utils_Array::value('max_related', $membershipType);
293 }
294 }
295 }
296
297 $transaction = new CRM_Core_Transaction();
298
299 $membership = self::add($params, $ids);
300
301 if (is_a($membership, 'CRM_Core_Error')) {
302 $transaction->rollback();
303 return $membership;
304 }
305
306 // add custom field values
a7488080 307 if (!empty($params['custom']) && is_array($params['custom'])
6a488035
TO
308 ) {
309 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
310 }
311
312 $params['membership_id'] = $membership->id;
313 if (isset($ids['membership'])) {
314 $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
315 $ids['membership'],
316 'contribution_id',
317 'membership_id'
318 );
319 }
3c0201c9 320
d5b95619 321 $params['skipLineItem'] = TRUE;
3c0201c9 322
6a488035 323 //record contribution for this membership
8cc574cf 324 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
8d8bd076 325 $memInfo = array_merge($params, array('membership_id' => $membership->id));
326 $params['contribution'] = self::recordMembershipContribution($memInfo, $ids);
6a488035 327 }
3c0201c9 328
82cc6775
PN
329 if (!empty($params['lineItems'])) {
330 $params['line_item'] = $params['lineItems'];
331 }
332
333 //do cleanup line items if membership edit the Membership type.
334 if (empty($ids['contribution']) && !empty($ids['membership'])) {
335 CRM_Price_BAO_LineItem::deleteLineItems($ids['membership'], 'civicrm_membership');
336 }
3c0201c9 337
82cc6775
PN
338 if (!empty($params['line_item']) && empty($ids['contribution'])) {
339 CRM_Price_BAO_LineItem::processPriceSet($membership->id, $params['line_item'], CRM_Utils_Array::value('contribution', $params));
d5b95619 340 }
6a488035
TO
341
342 //insert payment record for this membership
a7488080 343 if (!empty($params['relate_contribution_id'])) {
e0556ebe 344 CRM_Member_BAO_MembershipPayment::create(array(
353ffa53
TO
345 'membership_id' => $membership->id,
346 'contribution_id' => $params['relate_contribution_id'],
347 ));
6a488035
TO
348 }
349
350 // add activity record only during create mode and renew mode
351 // also add activity if status changed CRM-3984 and CRM-2521
a7488080 352 if (empty($ids['membership']) ||
e0556ebe
TO
353 $activityType == 'Membership Renewal' || !empty($params['createActivity'])
354 ) {
a7488080 355 if (!empty($ids['membership'])) {
ca58d9b9 356 $data = array();
6a488035
TO
357 CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_Membership',
358 'id',
359 $membership->id,
360 $data,
361 array('contact_id', 'membership_type_id', 'source')
362 );
363
364 $membership->contact_id = $data[$membership->id]['contact_id'];
365 $membership->membership_type_id = $data[$membership->id]['membership_type_id'];
366 $membership->source = CRM_Utils_Array::value('source', $data[$membership->id]);
367 }
368
369 // since we are going to create activity record w/
370 // individual contact as a target in case of on behalf signup,
371 // so get the copy of organization id, CRM-5551
372 $realMembershipContactId = $membership->contact_id;
373
374 // create activity source = individual, target = org CRM-4027
375 $targetContactID = NULL;
a7488080 376 if (!empty($params['is_for_organization'])) {
6a488035
TO
377 $targetContactID = $membership->contact_id;
378 $membership->contact_id = CRM_Utils_Array::value('userId', $ids);
379 }
380
381 if (empty($membership->contact_id) && (!empty($membership->owner_membership_id))) {
382 $membership->contact_id = $realMembershipContactId;
383 }
384
a7488080 385 if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
6a488035 386 CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
e0556ebe
TO
387 }
388 elseif (empty($ids['membership'])) {
6a488035
TO
389 CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
390 }
391
392 // we might created activity record w/ individual
393 // contact as target so update membership object w/
394 // original organization id, CRM-5551
395 $membership->contact_id = $realMembershipContactId;
396 }
397
398 $transaction->commit();
399
400 self::createRelatedMemberships($params, $membership);
401
402 // do not add to recent items for import, CRM-4399
a7488080 403 if (empty($params['skipRecentView'])) {
6a488035
TO
404 $url = CRM_Utils_System::url('civicrm/contact/view/membership',
405 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
406 );
e0556ebe 407 if (empty($membership->membership_type_id)) {// ie in an update situation
6a488035
TO
408 $membership->find(TRUE);
409 }
410 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
411 $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id];
412
413 $recentOther = array();
414 if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
415 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
416 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
417 );
418 }
419 if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
420 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
421 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
422 );
423 }
424
425 // add the recently created Membership
426 CRM_Utils_Recent::add($title,
427 $url,
428 $membership->id,
429 'Membership',
430 $membership->contact_id,
431 NULL,
432 $recentOther
433 );
434 }
435
436 return $membership;
437 }
438
439 /**
fe482240 440 * Check the membership extended through relationship.
6a488035 441 *
b2363ea8
TO
442 * @param int $membershipId
443 * Membership id.
444 * @param int $contactId
445 * Contact id.
ada8a833 446 *
b2363ea8 447 * @param int $action
6a488035 448 *
608e6658 449 * @return array
a6c01b45 450 * array of contact_id of all related contacts.
6a488035 451 */
00be9182 452 public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action::ADD) {
6a488035
TO
453 $contacts = array();
454 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
455
456 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID);
457 $relationships = array();
458 if (isset($membershipType['relationship_type_id'])) {
459 $relationships = CRM_Contact_BAO_Relationship::getRelationship($contactId,
460 CRM_Contact_BAO_Relationship::CURRENT
461 );
462 if ($action & CRM_Core_Action::UPDATE) {
463 $pastRelationships = CRM_Contact_BAO_Relationship::getRelationship($contactId,
464 CRM_Contact_BAO_Relationship::PAST
465 );
466 $relationships = array_merge($relationships, $pastRelationships);
467 }
468 }
469
470 if (!empty($relationships)) {
471 // check for each contact relationships
472 foreach ($relationships as $values) {
473 //get details of the relationship type
474 $relType = array('id' => $values['civicrm_relationship_type_id']);
475 $relValues = array();
476 CRM_Contact_BAO_RelationshipType::retrieve($relType, $relValues);
477 // Check if contact's relationship type exists in membership type
e0556ebe
TO
478 $relTypeDirs = array();
479 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
6a488035
TO
480 $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
481 $bidirectional = FALSE;
482 foreach ($relTypeIds as $key => $value) {
483 $relTypeDirs[] = $value . '_' . $relDirections[$key];
484 if (in_array($value, $relType) &&
485 $relValues['name_a_b'] == $relValues['name_b_a']
486 ) {
487 $bidirectional = TRUE;
488 break;
489 }
490 }
491 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
492 if ($bidirectional || in_array($relTypeDir, $relTypeDirs)) {
493 // $values['status'] is going to have value for
494 // current or past relationships.
495 $contacts[$values['cid']] = $values['status'];
496 }
497 }
498 }
499
500 // Sort by contact_id ascending
501 ksort($contacts);
502 return $contacts;
503 }
504
505 /**
fe482240
EM
506 * Retrieve DB object based on input parameters.
507 *
508 * It also stores all the retrieved values in the default array.
6a488035 509 *
b2363ea8
TO
510 * @param array $params
511 * (reference ) an assoc array of name/value pairs.
512 * @param array $defaults
513 * (reference ) an assoc array to hold the name / value pairs.
6a488035 514 * in a hierarchical manner
8efea814 515 *
16b10e64 516 * @return CRM_Member_BAO_Membership
6a488035 517 */
00be9182 518 public static function retrieve(&$params, &$defaults) {
6a488035
TO
519 $membership = new CRM_Member_DAO_Membership();
520
521 $membership->copyValues($params);
522
523 if ($membership->find(TRUE)) {
524 CRM_Core_DAO::storeValues($membership, $defaults);
525
526 //get the membership status and type values.
527 $statusANDType = self::getStatusANDTypeValues($membership->id);
528 foreach (array(
e0556ebe 529 'status',
21dfd5f5 530 'membership_type',
e0556ebe 531 ) as $fld) {
6a488035
TO
532 $defaults[$fld] = CRM_Utils_Array::value($fld, $statusANDType[$membership->id]);
533 }
a7488080 534 if (!empty($statusANDType[$membership->id]['is_current_member'])) {
6a488035
TO
535 $defaults['active'] = TRUE;
536 }
537
538 $membership->free();
539
540 return $membership;
541 }
542
543 return NULL;
544 }
545
546 /**
547 *
c490a46a 548 * get membership status and membership type values
6a488035 549 *
b2363ea8
TO
550 * @param int $membershipId
551 * Membership id of values to return.
6a488035 552 *
a6c01b45 553 * @return array
16b10e64 554 * Array of key value pairs
6a488035 555 */
00be9182 556 public static function getStatusANDTypeValues($membershipId) {
6a488035
TO
557 $values = array();
558 if (!$membershipId) {
559 return $values;
560 }
561 $sql = '
562 SELECT membership.id as id,
563 status.id as status_id,
564 status.label as status,
565 status.is_current_member as is_current_member,
566 type.id as membership_type_id,
567 type.name as membership_type,
568 type.relationship_type_id as relationship_type_id
569 FROM civicrm_membership membership
570INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
571INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
572 WHERE membership.id = %1';
573 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
e0556ebe
TO
574 $properties = array(
575 'status',
576 'status_id',
577 'membership_type',
578 'membership_type_id',
579 'is_current_member',
21dfd5f5 580 'relationship_type_id',
e0556ebe 581 );
6a488035
TO
582 while ($dao->fetch()) {
583 foreach ($properties as $property) {
584 $values[$dao->id][$property] = $dao->$property;
585 }
586 }
587
588 return $values;
589 }
590
3506b6cd 591 /**
100fef9d 592 * Delete membership.
f5e53870 593 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
3506b6cd 594 *
b2363ea8
TO
595 * @param int $membershipId
596 * Membership id that needs to be deleted.
3506b6cd 597 *
3506b6cd 598 *
608e6658 599 * @return int $results id of deleted Membership on success, false otherwise
3506b6cd 600 */
00be9182 601 public static function del($membershipId) {
3506b6cd
DG
602 //delete related first and then delete parent.
603 self::deleteRelatedMemberships($membershipId);
d824fb6e 604 return self::deleteMembership($membershipId);
3506b6cd 605 }
d824fb6e 606
6a488035 607 /**
100fef9d 608 * Delete membership.
6a488035 609 *
b2363ea8
TO
610 * @param int $membershipId
611 * Membership id that needs to be deleted.
6a488035 612 *
6a488035 613 *
608e6658 614 * @return int $results id of deleted Membership on success, false otherwise
6a488035 615 */
00be9182 616 public static function deleteMembership($membershipId) {
46d8f506
DL
617 // CRM-12147, retrieve membership data before we delete it for hooks
618 $params = array('id' => $membershipId);
619 $memValues = array();
620 $memberships = self::getValues($params, $memValues);
3506b6cd 621
46d8f506
DL
622 $membership = $memberships[$membershipId];
623
624 CRM_Utils_Hook::pre('delete', 'Membership', $membershipId, $memValues);
6a488035
TO
625
626 $transaction = new CRM_Core_Transaction();
627
628 $results = NULL;
629 //delete activity record
630 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
631
632 $params = array();
e0556ebe
TO
633 $deleteActivity = FALSE;
634 $membershipActivities = array(
46d8f506
DL
635 'Membership Signup',
636 'Membership Renewal',
637 'Change Membership Status',
638 'Change Membership Type',
21dfd5f5 639 'Membership Renewal Reminder',
46d8f506 640 );
e0556ebe 641 foreach ($membershipActivities as $membershipActivity) {
6a488035
TO
642 $activityId = array_search($membershipActivity, $activityTypes);
643 if ($activityId) {
644 $params['activity_type_id'][] = $activityId;
e0556ebe 645 $deleteActivity = TRUE;
6a488035
TO
646 }
647 }
648 if ($deleteActivity) {
649 $params['source_record_id'] = $membershipId;
46d8f506 650 CRM_Activity_BAO_Activity::deleteActivity($params);
6a488035
TO
651 }
652 self::deleteMembershipPayment($membershipId);
653
d0fbc816 654 $results = $membership->delete();
6a488035
TO
655 $transaction->commit();
656
657 CRM_Utils_Hook::post('delete', 'Membership', $membership->id, $membership);
658
659 // delete the recently created Membership
660 $membershipRecent = array(
661 'id' => $membershipId,
662 'type' => 'Membership',
663 );
664 CRM_Utils_Recent::del($membershipRecent);
665
666 return $results;
667 }
668
3506b6cd 669 /**
fe482240 670 * Delete related memberships.
3506b6cd
DG
671 *
672 * @param int $ownerMembershipId
673 * @param int $contactId
674 *
675 * @return null
3506b6cd 676 */
00be9182 677 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
3506b6cd 678 if (!$ownerMembershipId && !$contactId) {
608e6658 679 return FALSE;
3506b6cd
DG
680 }
681
682 $membership = new CRM_Member_DAO_Membership();
683 $membership->owner_membership_id = $ownerMembershipId;
684
685 if ($contactId) {
686 $membership->contact_id = $contactId;
687 }
688
689 $membership->find();
690 while ($membership->fetch()) {
691 //delete related first and then delete parent.
692 self::deleteRelatedMemberships($membership->id);
693 self::deleteMembership($membership->id);
694 }
695 $membership->free();
696 }
697
6a488035 698 /**
100fef9d 699 * Obtain active/inactive memberships from the list of memberships passed to it.
6a488035 700 *
b2363ea8
TO
701 * @param array $memberships
702 * Membership records.
703 * @param string $status
704 * Active or inactive.
6a488035 705 *
a6c01b45
CW
706 * @return array
707 * array of memberships based on status
6a488035 708 */
00be9182 709 public static function activeMembers($memberships, $status = 'active') {
6a488035
TO
710 $actives = array();
711 if ($status == 'active') {
712 foreach ($memberships as $f => $v) {
a7488080 713 if (!empty($v['active'])) {
6a488035
TO
714 $actives[$f] = $v;
715 }
716 }
717 return $actives;
718 }
719 elseif ($status == 'inactive') {
720 foreach ($memberships as $f => $v) {
a7488080 721 if (empty($v['active'])) {
6a488035
TO
722 $actives[$f] = $v;
723 }
724 }
725 return $actives;
726 }
727 return NULL;
728 }
729
730 /**
fe482240 731 * Build Membership Block in Contribution Pages.
6a488035 732 *
b2363ea8
TO
733 * @param CRM_Core_Form $form
734 * Form object.
735 * @param int $pageID
736 * Unused?.
737 * @param int $cid
738 * Contact checked for having a current membership for a particular membership.
739 * @param bool $formItems
740 * @param int $selectedMembershipTypeID
741 * Selected membership id.
742 * @param bool $thankPage
743 * Thank you page.
e46e9a0b
EM
744 * @param null $isTest
745 *
a6c01b45
CW
746 * @return bool
747 * Is this a separate membership payment
6a488035 748 *
6a488035 749 */
608e6658 750 public static function buildMembershipBlock(
500cfe81 751 &$form,
353ffa53
TO
752 $pageID,
753 $cid,
754 $formItems = FALSE,
755 $selectedMembershipTypeID = NULL,
756 $thankPage = FALSE,
757 $isTest = NULL
6a488035
TO
758 ) {
759
760 $separateMembershipPayment = FALSE;
761 if ($form->_membershipBlock) {
762 $form->_currentMemberships = array();
6a488035 763
e0556ebe
TO
764 $membershipBlock = $form->_membershipBlock;
765 $membershipTypeIds = $membershipTypes = $radio = array();
6a488035
TO
766 $membershipPriceset = (!empty($form->_priceSetId) && $form->_useForMember) ? TRUE : FALSE;
767
768 $allowAutoRenewMembership = $autoRenewOption = FALSE;
769 $autoRenewMembershipTypeOptions = array();
770
771 $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
772
773 $separateMembershipPayment = CRM_Utils_Array::value('is_separate_payment', $membershipBlock);
774
775 if ($membershipPriceset) {
776 foreach ($form->_priceSet['fields'] as $pField) {
777 if (empty($pField['options'])) {
778 continue;
779 }
780 foreach ($pField['options'] as $opId => $opValues) {
a7488080 781 if (empty($opValues['membership_type_id'])) {
6a488035
TO
782 continue;
783 }
784 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
785 }
786 }
787 }
a7488080 788 elseif (!empty($membershipBlock['membership_types'])) {
6a488035
TO
789 $membershipTypeIds = explode(',', $membershipBlock['membership_types']);
790 }
791
792 if (!empty($membershipTypeIds)) {
793 //set status message if wrong membershipType is included in membershipBlock
794 if (isset($form->_mid) && !$membershipPriceset) {
795 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
796 $form->_mid,
797 'membership_type_id'
798 );
799 if (!in_array($membershipTypeID, $membershipTypeIds)) {
800 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Invalid Membership'), 'error');
801 }
802 }
803
804 $membershipTypeValues = self::buildMembershipTypeValues($form, $membershipTypeIds);
805 $form->_membershipTypeValues = $membershipTypeValues;
806 $endDate = NULL;
807 foreach ($membershipTypeIds as $value) {
808 $memType = $membershipTypeValues[$value];
809 if ($selectedMembershipTypeID != NULL) {
810 if ($memType['id'] == $selectedMembershipTypeID) {
811 $form->assign('minimum_fee',
812 CRM_Utils_Array::value('minimum_fee', $memType)
813 );
814 $form->assign('membership_name', $memType['name']);
815 if (!$thankPage && $cid) {
816 $membership = new CRM_Member_DAO_Membership();
817 $membership->contact_id = $cid;
818 $membership->membership_type_id = $memType['id'];
819 if ($membership->find(TRUE)) {
820 $form->assign('renewal_mode', TRUE);
821 $memType['current_membership'] = $membership->end_date;
822 $form->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
823 }
824 }
825 $membershipTypes[] = $memType;
826 }
827 }
828 elseif ($memType['is_active']) {
829 $javascriptMethod = NULL;
830 $allowAutoRenewOpt = 1;
e0556ebe 831 if (is_array($form->_paymentProcessors)) {
6a488035
TO
832 foreach ($form->_paymentProcessors as $id => $val) {
833 if (!$val['is_recur']) {
e0556ebe 834 $allowAutoRenewOpt = 0;
6a488035 835 continue;
e0556ebe 836 }
6a488035
TO
837 }
838 }
839
840 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
e0556ebe 841 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array::value($value, CRM_Utils_Array::value('auto_renew', $form->_membershipBlock));;
6a488035
TO
842
843 if ($allowAutoRenewOpt) {
844 $allowAutoRenewMembership = TRUE;
845 }
846
847 //add membership type.
848 $radio[$memType['id']] = $form->createElement('radio', NULL, NULL, NULL,
849 $memType['id'], $javascriptMethod
850 );
851 if ($cid) {
852 $membership = new CRM_Member_DAO_Membership();
853 $membership->contact_id = $cid;
854 $membership->membership_type_id = $memType['id'];
855
856 //show current membership, skip pending and cancelled membership records,
857 //because we take first membership record id for renewal
858 $membership->whereAdd('status_id != 5 AND status_id !=6');
859
860 if (!is_null($isTest)) {
861 $membership->is_test = $isTest;
862 }
863
864 //CRM-4297
865 $membership->orderBy('end_date DESC');
866
867 if ($membership->find(TRUE)) {
868 if (!$membership->end_date) {
869 unset($radio[$memType['id']]);
870 $form->assign('islifetime', TRUE);
871 continue;
872 }
873 $form->assign('renewal_mode', TRUE);
874 $form->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
875 $memType['current_membership'] = $membership->end_date;
876 if (!$endDate) {
877 $endDate = $memType['current_membership'];
878 $form->_defaultMemTypeId = $memType['id'];
879 }
880 if ($memType['current_membership'] < $endDate) {
881 $endDate = $memType['current_membership'];
882 $form->_defaultMemTypeId = $memType['id'];
883 }
884 }
885 }
886 $membershipTypes[] = $memType;
887 }
888 }
889 }
890
891 $form->assign('showRadio', $formItems);
892 if ($formItems) {
893 if (!$membershipPriceset) {
894 if (!$membershipBlock['is_required']) {
895 $form->assign('showRadioNoThanks', TRUE);
896 $radio[''] = $form->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
897 $form->addGroup($radio, 'selectMembership', NULL);
898 }
899 elseif ($membershipBlock['is_required'] && count($radio) == 1) {
900 $temp = array_keys($radio);
901 $form->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
902 $form->assign('singleMembership', TRUE);
903 $form->assign('showRadio', FALSE);
904 }
905 else {
906 $form->addGroup($radio, 'selectMembership', NULL);
907 }
908
909 $form->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
910 }
911 else {
9da8dc8c 912 $autoRenewOption = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($form->_priceSetId);
6a488035
TO
913 $form->assign('autoRenewOption', $autoRenewOption);
914 }
915
916 if (!$form->_values['is_pay_later'] && is_array($form->_paymentProcessors) && ($allowAutoRenewMembership || $autoRenewOption)) {
917 $form->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
918 }
919
920 }
921
922 $form->assign('membershipBlock', $membershipBlock);
923 $form->assign('membershipTypes', $membershipTypes);
924 $form->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
925 $form->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
926
927 //give preference to user submitted auto_renew value.
928 $takeUserSubmittedAutoRenew = (!empty($_POST) || $form->isSubmitted()) ? TRUE : FALSE;
929 $form->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
930 }
931
932 return $separateMembershipPayment;
933 }
934
935 /**
fe482240 936 * Return Membership Block info in Contribution Pages.
6a488035 937 *
b2363ea8
TO
938 * @param int $pageID
939 * Contribution page id.
e46e9a0b
EM
940 *
941 * @return array|null
6a488035 942 *
6a488035 943 */
00be9182 944 public static function getMembershipBlock($pageID) {
e0556ebe
TO
945 $membershipBlock = array();
946 $dao = new CRM_Member_DAO_MembershipBlock();
6a488035
TO
947 $dao->entity_table = 'civicrm_contribution_page';
948
949 $dao->entity_id = $pageID;
950 $dao->is_active = 1;
951 if ($dao->find(TRUE)) {
952 CRM_Core_DAO::storeValues($dao, $membershipBlock);
a7488080 953 if (!empty($membershipBlock['membership_types'])) {
6a488035
TO
954 $membershipTypes = unserialize($membershipBlock['membership_types']);
955 if (!is_array($membershipTypes)) {
956 return $membershipBlock;
957 }
958 $memTypes = array();
959 foreach ($membershipTypes as $key => $value) {
960 $membershipBlock['auto_renew'][$key] = $value;
961 $memTypes[$key] = $key;
962 }
963 $membershipBlock['membership_types'] = implode(',', $memTypes);
964 }
965 }
966 else {
967 return NULL;
968 }
969
970 return $membershipBlock;
971 }
972
973 /**
fe482240 974 * Return a current membership of given contact.
c490a46a 975 * NB: if more than one membership meets criteria, a randomly selected one is returned.
6a488035 976 *
b2363ea8
TO
977 * @param int $contactID
978 * Contact id.
979 * @param int $memType
980 * Membership type, null to retrieve all types.
6a488035 981 * @param int $isTest
b2363ea8
TO
982 * @param int $membershipId
983 * If provided, then determine if it is current.
984 * @param bool $onlySameParentOrg
985 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
e46e9a0b
EM
986 *
987 * @return array|bool
6a488035 988 */
00be9182 989 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
6a488035
TO
990 $dao = new CRM_Member_DAO_Membership();
991 if ($membershipId) {
992 $dao->id = $membershipId;
993 }
994 $dao->contact_id = $contactID;
995 $dao->membership_type_id = $memType;
996
997 //fetch proper membership record.
998 if ($isTest) {
999 $dao->is_test = $isTest;
1000 }
1001 else {
1002 $dao->whereAdd('is_test IS NULL OR is_test = 0');
1003 }
5624f515 1004
6a488035 1005 //avoid pending membership as current membership: CRM-3027
b5a62499
PN
1006 $statusIds[] = array_search('Pending', CRM_Member_PseudoConstant::membershipStatus());
1007 if (!$membershipId) {
7ff60806
PN
1008 // CRM-15475
1009 $statusIds[] = array_search(
4c16123d 1010 'Cancelled',
7ff60806 1011 CRM_Member_PseudoConstant::membershipStatus(
4c16123d
EM
1012 NULL,
1013 " name = 'Cancelled' ",
1014 'name',
1015 FALSE,
7ff60806
PN
1016 TRUE
1017 )
1018 );
b5a62499 1019 }
e0556ebe 1020 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
5624f515 1021
6a488035
TO
1022 // order by start date to find most recent membership first, CRM-4545
1023 $dao->orderBy('start_date DESC');
1024
1025 // CRM-8141
1026 if ($onlySameParentOrg && $memType) {
1027 // require the same parent org as the $memType
1028 $params = array('id' => $memType);
5901ddf9 1029 $membershipType = array();
6a488035
TO
1030 if (CRM_Member_BAO_MembershipType::retrieve($params, $membershipType)) {
1031 $memberTypesSameParentOrg = CRM_Member_BAO_MembershipType::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
1032 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
1033 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
1034 }
1035 }
1036
1037 if ($dao->find(TRUE)) {
1038 $membership = array();
1039 CRM_Core_DAO::storeValues($dao, $membership);
1040 $membership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
1041 $membership['status_id'],
1042 'is_current_member', 'id'
1043 );
1044 return $membership;
1045 }
1046
1047 // CRM-8141
1048 if ($onlySameParentOrg && $memType) {
1049 // see if there is a membership that has same parent as $memType but different parent than $membershipID
5682e889 1050 if ($dao->id && CRM_Core_Permission::check('edit memberships')) {
1051 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
e0556ebe 1052 $dao->whereAdd();
5682e889 1053 }
1054 else {
1055 unset($dao->id);
1056 }
6a488035
TO
1057
1058 unset($dao->membership_type_id);
1059 if ($dao->find(TRUE)) {
1060 $membership = array();
1061 CRM_Core_DAO::storeValues($dao, $membership);
1062 $membership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
1063 $membership['status_id'],
1064 'is_current_member', 'id'
1065 );
1066 return $membership;
1067 }
1068 }
1069 return FALSE;
1070 }
1071
1072 /**
fe482240 1073 * Combine all the importable fields from the lower levels object.
6a488035 1074 *
b2363ea8
TO
1075 * @param string $contactType
1076 * Contact type.
1077 * @param bool $status
6a488035 1078 *
a6c01b45
CW
1079 * @return array
1080 * array of importable Fields
6a488035 1081 */
00be9182 1082 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
6a488035
TO
1083 if (!self::$_importableFields) {
1084 if (!self::$_importableFields) {
1085 self::$_importableFields = array();
1086 }
1087
1088 if (!$status) {
1089 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
1090 }
1091 else {
1092 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
1093 }
1094
1095 $tmpFields = CRM_Member_DAO_Membership::import();
1096 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
1097
1098 // Using new Dedupe rule.
1099 $ruleParams = array(
1100 'contact_type' => $contactType,
e0556ebe 1101 'used' => 'Unsupervised',
6a488035
TO
1102 );
1103 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
1104
1105 $tmpContactField = array();
1106 if (is_array($fieldsArray)) {
1107 foreach ($fieldsArray as $value) {
1108 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
1109 $value,
1110 'id',
1111 'column_name'
1112 );
1113 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
1114 $tmpContactField[trim($value)] = CRM_Utils_Array::value(trim($value), $contactFields);
1115 if (!$status) {
1116 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
1117 }
1118 else {
1119 $title = $tmpContactField[trim($value)]['title'];
1120 }
1121 $tmpContactField[trim($value)]['title'] = $title;
1122 }
1123 }
1124 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
1125 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
1126
1127 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
1128
1129 $fields = array_merge($fields, $tmpContactField);
1130 $fields = array_merge($fields, $tmpFields);
1131 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
1132 self::$_importableFields = $fields;
1133 }
1134 return self::$_importableFields;
1135 }
1136
1137 /**
fe482240 1138 * Get all exportable fields.
6a488035
TO
1139 *
1140 * @retun array return array of all exportable fields
6a488035 1141 */
00be9182 1142 public static function &exportableFields() {
6a488035 1143 $expFieldMembership = CRM_Member_DAO_Membership::export();
6a488035
TO
1144
1145 $expFieldsMemType = CRM_Member_DAO_MembershipType::export();
e0556ebe
TO
1146 $fields = array_merge($expFieldMembership, $expFieldsMemType);
1147 $fields = array_merge($fields, $expFieldMembership);
6a488035 1148 $membershipStatus = array(
e0556ebe
TO
1149 'membership_status' => array(
1150 'title' => 'Membership Status',
6a488035
TO
1151 'name' => 'membership_status',
1152 'type' => CRM_Utils_Type::T_STRING,
1153 'where' => 'civicrm_membership_status.name',
21dfd5f5 1154 ),
e0556ebe 1155 );
6a488035
TO
1156 //CRM-6161 fix for customdata export
1157 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
1158 return $fields;
1159 }
1160
1161 /**
100fef9d 1162 * Get membership joins/renewals for a specified membership
4e636a74
AH
1163 * type. Specifically, retrieves a count of memberships whose "Membership
1164 * Signup" or "Membership Renewal" activity falls in the given date range.
8ef12e64 1165 * Dates match the pattern "yyyy-mm-dd".
6a488035 1166 *
b2363ea8
TO
1167 * @param int $membershipTypeId
1168 * Membership type id.
1169 * @param int $startDate
1170 * Date on which to start counting.
1171 * @param int $endDate
1172 * Date on which to end counting.
e46e9a0b
EM
1173 * @param bool|int $isTest if true, membership is for a test site
1174 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
6a488035 1175 *
df8d3074 1176 * @return int
a6c01b45 1177 * the number of members of type $membershipTypeId whose
688d37c6 1178 * start_date is between $startDate and $endDate
6a488035 1179 */
6a488035 1180 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
8ef12e64 1181
4e636a74
AH
1182 $testClause = 'membership.is_test = 1';
1183 if (!$isTest) {
1184 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1185 }
8ef12e64 1186
4e636a74
AH
1187 if (!self::$_signupActType || !self::$_renewalActType) {
1188 self::_getActTypes();
1189 }
8ef12e64 1190
4e636a74
AH
1191 if (!self::$_signupActType || !self::$_renewalActType) {
1192 return 0;
1193 }
1194
1195 $query = "
1196 SELECT COUNT(DISTINCT membership.id) as member_count
1197 FROM civicrm_membership membership
1198INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1199INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1200INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1201 WHERE membership.membership_type_id = %3
1202 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1203 AND {$testClause}";
8ef12e64 1204
6a488035 1205 $query .= ($isOwner) ? ' AND owner_membership_id IS NULL' : '';
4e636a74
AH
1206
1207 $params = array(
1208 1 => array(self::$_signupActType, 'Integer'),
1209 2 => array(self::$_renewalActType, 'Integer'),
8ef12e64 1210 3 => array($membershipTypeId, 'Integer'),
6a488035 1211 );
8ef12e64 1212
6a488035 1213 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
e0556ebe 1214 return (int) $memberCount;
6a488035
TO
1215 }
1216
1217 /**
100fef9d 1218 * Get a count of membership for a specified membership type,
8ef12e64 1219 * optionally for a specified date. The date must have the form yyyy-mm-dd.
6a488035
TO
1220 *
1221 * If $date is omitted, this function counts as a member anyone whose
1222 * membership status_id indicates they're a current member.
1223 * If $date is given, this function counts as a member anyone who:
1224 * -- Has a start_date before $date and end_date after $date, or
1225 * -- Has a start_date before $date and is currently a member, as indicated
1226 * by the the membership's status_id.
1227 * The second condition takes care of records that have no end_date. These
1228 * are assumed to be lifetime memberships.
1229 *
b2363ea8
TO
1230 * @param int $membershipTypeId
1231 * Membership type id.
1232 * @param string $date
1233 * The date for which to retrieve the count.
e46e9a0b
EM
1234 * @param bool|int $isTest if true, membership is for a test site
1235 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
6a488035 1236 *
72b3a70c
CW
1237 * @return int
1238 * the number of members of type $membershipTypeId as of $date.
6a488035
TO
1239 */
1240 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
4e636a74
AH
1241 if (!CRM_Utils_Rule::date($date)) {
1242 CRM_Core_Error::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
6a488035
TO
1243 }
1244
e0556ebe
TO
1245 $params = array(
1246 1 => array($membershipTypeId, 'Integer'),
6a488035
TO
1247 2 => array($isTest, 'Boolean'),
1248 );
1249 $query = "SELECT count(civicrm_membership.id ) as member_count
1250FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1251WHERE civicrm_membership.membership_type_id = %1
1252AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1253AND civicrm_membership.is_test = %2";
1254 if (!$date) {
1255 $query .= " AND civicrm_membership_status.is_current_member = 1";
1256 }
1257 else {
6a488035
TO
1258 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1259 }
1260 // LCD
1261 $query .= ($isOwner) ? ' AND owner_membership_id IS NULL' : '';
1262 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
e0556ebe 1263 return (int) $memberCount;
6a488035
TO
1264 }
1265
1266 /**
fe482240 1267 * Function check the status of the membership before adding membership for a contact.
6a488035 1268 *
b2363ea8
TO
1269 * @param int $contactId
1270 * Contact id.
6a488035 1271 *
e46e9a0b 1272 * @return int
6a488035 1273 */
00be9182 1274 public static function statusAvailabilty($contactId) {
6a488035
TO
1275 $membership = new CRM_Member_DAO_MembershipStatus();
1276 $membership->whereAdd('is_active=1');
c905ba98 1277 return $membership->count();
6a488035
TO
1278 }
1279
1280 /**
fe482240 1281 * Process the Memberships.
6a488035 1282 *
b2363ea8
TO
1283 * @param array $membershipParams
1284 * Array of membership fields.
1285 * @param int $contactID
1286 * Contact id.
1287 * @param CRM_Contribute_Form_Contribution_Confirm $form
1288 * Confirmation form object.
e46e9a0b 1289 *
100fef9d 1290 * @param array $premiumParams
e46e9a0b
EM
1291 * @param null $customFieldsFormatted
1292 * @param null $includeFieldTypes
6a488035 1293 *
fa9d0451 1294 * @param array $membershipDetails
705b4205 1295 *
d25e4224 1296 * @param array $membershipTypeIDs
fa9d0451
EM
1297 *
1298 * @param bool $isPaidMembership
d25e4224 1299 * @param array $membershipID
705b4205 1300 *
38b4a5fe
EM
1301 * @param $isProcessSeparateMembershipTransaction
1302 *
100fef9d 1303 * @param int $defaultContributionTypeID
b2363ea8
TO
1304 * @param array $membershipLineItems
1305 * Line items specific to membership payment that is separate to contribution.
c2b5a0af 1306 * @param $isPayLater
705b4205 1307 *
c2b5a0af 1308 * @throws \CRM_Core_Exception
6a488035 1309 */
500cfe81
TO
1310 public static function postProcessMembership(
1311 $membershipParams, $contactID, &$form, $premiumParams,
353ffa53
TO
1312 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1313 $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems, $isPayLater) {
e0556ebe
TO
1314 $result = $membershipContribution = NULL;
1315 $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
f5d25ee9 1316 $errors = $createdMemberships = array();
3c0201c9 1317
cc789d46
EM
1318 //@todo move this into the calling function & pass in the correct financialTypeID
1319 if (isset($paymentParams['financial_type'])) {
1320 $financialTypeID = $paymentParams['financial_type'];
1321 }
1322 else {
1323 $financialTypeID = $defaultContributionTypeID;
1324 }
1325
f990d7e8 1326 if (CRM_Utils_Array::value('membership_source', $form->_params)) {
1327 $membershipParams['contribution_source'] = $form->_params['membership_source'];
1328 }
1329
fa9d0451 1330 if ($isPaidMembership) {
6a488035
TO
1331 $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams,
1332 $premiumParams, $contactID,
cc789d46
EM
1333 $financialTypeID,
1334 'membership',
1335 array(),
1336 $isTest,
1337 $isPayLater
6a488035 1338 );
d45686b0
EM
1339 if (is_a($result[1], 'CRM_Core_Error')) {
1340 $errors[1] = CRM_Core_Error::getMessages($result[1]);
6a488035 1341 }
d45686b0
EM
1342 elseif (!empty($result[1])) {
1343 // Save the contribution ID so that I can be used in email receipts
1344 // For example, if you need to generate a tax receipt for the donation only.
1345 $form->_values['contribution_other_id'] = $result[1]->id;
1346 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1347 $membershipContribution = $result[1];
6a488035 1348 }
6a488035 1349 }
6a488035 1350
38b4a5fe 1351 if ($isProcessSeparateMembershipTransaction) {
d45686b0 1352 try {
866f6e8e 1353 $lineItems = $form->_lineItem = $membershipLineItems;
5624f515 1354 $membershipContribution = self::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
6a488035 1355 }
d45686b0
EM
1356 catch (CRM_Core_Exception $e) {
1357 $errors[2] = $e->getMessage();
1358 $membershipContribution = NULL;
6a488035
TO
1359 }
1360 }
1361
8d65cef7 1362 $membership = NULL;
423c9872 1363 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
dd9e2b05
EM
1364 $membershipContributionID = $membershipContribution->id;
1365 }
423c9872
C
1366
1367 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1368 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1369 $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1370 }
1371 //@todo it should no longer be possible for it to get to this point & membership to not be an array
6e92ff36 1372 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
423c9872 1373 $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
d25e4224 1374 foreach ($membershipTypeIDs as $memType) {
423c9872
C
1375 $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
1376 $createdMemberships[$memType] = self::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
6a488035 1377 }
423c9872
C
1378 if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
1379 foreach ($form->_lineItem[$form->_priceSetId] as & $priceFieldOp) {
1380 if (!empty($priceFieldOp['membership_type_id']) &&
1381 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1382 ) {
1383 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
3b85fc04
PN
1384 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
1385 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
423c9872
C
1386 }
1387 else {
1388 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
6a488035 1389 }
6a488035 1390 }
423c9872
C
1391 $form->_values['lineItem'] = $form->_lineItem;
1392 $form->assign('lineItem', $form->_lineItem);
6a488035 1393 }
6a488035
TO
1394 }
1395
1396 if (!empty($errors)) {
15c3308b 1397 $message = self::compileErrorMessage($errors);
93a11cd6 1398 throw new CRM_Core_Exception($message);
6a488035 1399 }
8d65cef7
AC
1400 $form->_params['createdMembershipIDs'] = array();
1401
1402 // CRM-7851 - Moved after processing Payment Errors
15c3308b 1403 //@todo - the reasoning for this being here seems a little outdated
8d65cef7
AC
1404 foreach ($createdMemberships as $createdMembership) {
1405 CRM_Core_BAO_CustomValueTable::postProcess(
1406 $form->_params,
1407 CRM_Core_DAO::$_nullArray,
1408 'civicrm_membership',
1409 $createdMembership->id,
1410 'Membership'
1411 );
1412 $form->_params['createdMembershipIDs'][] = $createdMembership->id;
1413 }
e0556ebe 1414 if (count($createdMemberships) == 1) {
1f4d7bcb 1415 //presumably this is only relevant for exactly 1 membership
12dac866 1416 $form->_params['membershipID'] = $createdMembership->id;
1f4d7bcb 1417 }
6a488035 1418
12dac866 1419 //CRM-15232: Check if membership is created and on the basis of it use
1420 //membership reciept template to send payment reciept
1421 if (count($createdMemberships)) {
1422 $form->_values['isMembership'] = TRUE;
1423 }
6a488035
TO
1424 if ($form->_contributeMode == 'notify') {
1425 if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
dd9e2b05 1426 // call postProcess hook before leaving
6a488035
TO
1427 $form->postProcessHook();
1428 // this does not return
1429 $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
1430 $payment->doTransferCheckout($form->_params, 'contribute');
1431 }
1432 }
1433
dd9e2b05
EM
1434 if (isset($membershipContributionID)) {
1435 $form->_values['contribution_id'] = $membershipContributionID;
6a488035
TO
1436 }
1437
1438 // Do not send an email if Recurring transaction is done via Direct Mode
1439 // Email will we sent when the IPN is received.
a7488080 1440 if (!empty($form->_params['is_recur']) && $form->_contributeMode == 'direct') {
a7a33651
EM
1441 if (!empty($membershipContribution->trxn_id)) {
1442 try {
e0556ebe 1443 civicrm_api3('contribution', 'completetransaction', array(
353ffa53
TO
1444 'id' => $membershipContribution->id,
1445 'trxn_id' => $membershipContribution->trxn_id,
1446 ));
a7a33651
EM
1447 }
1448 catch (CiviCRM_API3_Exception $e) {
1449 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
1450 // so let's be gentle here
1451 CRM_Core_Error::debug_log_message('contribution ' . $membershipContribution->id . ' not completed with trxn_id ' . $membershipContribution->trxn_id . ' and message ' . $e->getMessage());
1452 }
1453 }
5901ddf9 1454 return;
6a488035
TO
1455 }
1456
1457 //finally send an email receipt
1458 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
1459 $form->_values,
1460 $isTest, FALSE,
1461 $includeFieldTypes
1462 );
1463 }
1464
cd125a40
FG
1465 /**
1466 * Function for updating a membership record's contribution_recur_id
1467 *
c866eb5f 1468 * @param CRM_Member_DAO_Membership $membership
5901ddf9 1469 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
cd125a40
FG
1470 *
1471 * @return void
cd125a40 1472 */
c866eb5f 1473 static public function updateRecurMembership(CRM_Member_DAO_Membership $membership, CRM_Contribute_BAO_Contribution $contribution) {
cd125a40
FG
1474
1475 if (empty($contribution->contribution_recur_id)) {
1476 return;
1477 }
1478
1479 $params = array(
1480 1 => array($contribution->contribution_recur_id, 'Integer'),
1481 2 => array($membership->id, 'Integer'),
1482 );
1483
1484 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1485 CRM_Core_DAO::executeQuery($sql, $params);
1486 }
1487
6a488035 1488 /**
c98997b9
EM
1489 * @deprecated
1490 * A wrapper for renewing memberships from a form - including the form in the membership processing adds complexity
1491 * as the forms are being forced to pretend similarity
1492 * Try to call the renewMembership directly
e0efd2d0 1493 * @todo - this form method needs to have the interaction with the form layer removed from it
1494 * as a BAO function. Note that the api now supports membership renewals & it is not clear this function does anything
1495 * not done by the membership.create api (with a lot less unit tests)
1496 *
6a488035
TO
1497 * This method will renew / create the membership depending on
1498 * whether the given contact has a membership or not. And will add
1499 * the modified dates for membership and in the log table.
1500 *
b2363ea8
TO
1501 * @param int $contactID
1502 * Id of the contact.
1503 * @param int $membershipTypeID
1504 * Id of the new membership type.
1505 * @param bool $is_test
1506 * If this is test contribution or live contribution.
1507 * @param CRM_Core_Form $form
1508 * Form object.
e46e9a0b 1509 * @param null $changeToday
b2363ea8
TO
1510 * @param int $modifiedID
1511 * Individual contact id in case of On Behalf signup (CRM-4027 ).
e46e9a0b 1512 * @param null $customFieldsFormatted
b2363ea8
TO
1513 * @param int $numRenewTerms
1514 * How many membership terms are being added to end date (default is 1).
1515 * @param int $membershipID
1516 * Membership ID, this should always be passed in & optionality should be removed.
fa9d0451
EM
1517 *
1518 * @throws CRM_Core_Exception
6a488035 1519 *
e46e9a0b 1520 */
608e6658 1521 public static function renewMembershipFormWrapper(
6a488035
TO
1522 $contactID,
1523 $membershipTypeID,
1524 $is_test,
1525 &$form,
1526 $changeToday = NULL,
1527 $modifiedID = NULL,
1528 $customFieldsFormatted = NULL,
fa9d0451
EM
1529 $numRenewTerms = 1,
1530 $membershipID = NULL
6a488035
TO
1531 ) {
1532 $statusFormat = '%Y-%m-%d';
e0556ebe
TO
1533 $format = '%Y%m%d';
1534 $ids = array();
fa9d0451 1535 //@todo would be better to make $membershipID a compulsory function param & make form layer responsible for extracting it
e0556ebe 1536 if (!$membershipID && isset($form->_membershipId)) {
fa9d0451
EM
1537 $membershipID = $form->_membershipId;
1538 }
6a488035
TO
1539
1540 //get all active statuses of membership.
1541 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1542
1543 $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID);
1544
1545 // check is it pending. - CRM-4555
c98997b9
EM
1546 list($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId) = self::extractFormValues($form, $changeToday, $membershipTypeDetails);
1547 list($membership, $renewalMode, $dates) = self::renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId);
1f4d7bcb 1548 $form->set('renewal_mode', $renewalMode);
6a488035
TO
1549 if (!empty($dates)) {
1550 $form->assign('mem_start_date',
1551 CRM_Utils_Date::customFormat($dates['start_date'], $format)
1552 );
1553 $form->assign('mem_end_date',
1554 CRM_Utils_Date::customFormat($dates['end_date'], $format)
1555 );
1556 }
6a488035 1557 return $membership;
c98997b9 1558
6a488035
TO
1559 }
1560
1561 /**
fe482240 1562 * Method to fix membership status of stale membership.
6a488035
TO
1563 *
1564 * This method first checks if the membership is stale. If it is,
1565 * then status will be updated based on existing start and end
1566 * dates and log will be added for the status change.
1567 *
b2363ea8
TO
1568 * @param array $currentMembership
1569 * Reference to the array.
688d37c6
CW
1570 * containing all values of
1571 * the current membership
b2363ea8
TO
1572 * @param array $changeToday
1573 * Array of month, day, year.
688d37c6
CW
1574 * values in case today needs
1575 * to be customised, null otherwise
6a488035
TO
1576 *
1577 * @return void
6a488035 1578 */
00be9182 1579 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
6a488035
TO
1580 $today = NULL;
1581 if ($changeToday) {
1582 $today = CRM_Utils_Date::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1583 }
1584
1585 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(
1586 CRM_Utils_Array::value('start_date', $currentMembership),
1587 CRM_Utils_Array::value('end_date', $currentMembership),
1588 CRM_Utils_Array::value('join_date', $currentMembership),
1589 $today,
5f11bbcc
EM
1590 TRUE,
1591 $currentMembership['membership_type_id'],
1592 $currentMembership
6a488035
TO
1593 );
1594
1595 if (empty($status) ||
1596 empty($status['id'])
1597 ) {
1598 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.'));
1599 }
1600
1601 $currentMembership['today_date'] = $today;
1602
1603 if ($status['id'] !== $currentMembership['status_id']) {
1604 $memberDAO = new CRM_Member_DAO_Membership();
1605 $memberDAO->id = $currentMembership['id'];
1606 $memberDAO->find(TRUE);
1607
1608 $memberDAO->status_id = $status['id'];
1609 $memberDAO->join_date = CRM_Utils_Date::isoToMysql($memberDAO->join_date);
1610 $memberDAO->start_date = CRM_Utils_Date::isoToMysql($memberDAO->start_date);
1611 $memberDAO->end_date = CRM_Utils_Date::isoToMysql($memberDAO->end_date);
1612 $memberDAO->save();
1613 CRM_Core_DAO::storeValues($memberDAO, $currentMembership);
1614 $memberDAO->free();
1615
1616 $currentMembership['is_current_member'] = CRM_Core_DAO::getFieldValue(
1617 'CRM_Member_DAO_MembershipStatus',
1618 $currentMembership['status_id'],
1619 'is_current_member'
1620 );
1621 $format = '%Y%m%d';
1622
1623 $logParams = array(
1624 'membership_id' => $currentMembership['id'],
1625 'status_id' => $status['id'],
1626 'start_date' => CRM_Utils_Date::customFormat(
1627 $currentMembership['start_date'],
1628 $format
1629 ),
1630 'end_date' => CRM_Utils_Date::customFormat(
1631 $currentMembership['end_date'],
1632 $format
1633 ),
1634 'modified_date' => CRM_Utils_Date::customFormat(
1635 $currentMembership['today_date'],
1636 $format
1637 ),
1638 'membership_type_id' => $currentMembership['membership_type_id'],
1639 'max_related' => $currentMembership['max_related'],
1640 );
1641
1642 $session = CRM_Core_Session::singleton();
1643 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1644 if ($session->get('userID')) {
1645 $logParams['modified_id'] = $session->get('userID');
1646 }
1647 else {
1648 $logParams['modified_id'] = $currentMembership['contact_id'];
1649 }
1650 CRM_Member_BAO_MembershipLog::add($logParams, CRM_Core_DAO::$_nullArray);
1651 }
1652 }
1653
1654 /**
fe482240 1655 * Get the contribution page id from the membership record.
6a488035 1656 *
688d37c6 1657 * @param int $membershipID
6a488035 1658 *
a6c01b45 1659 * @return int
688d37c6 1660 * contribution page id
6a488035 1661 */
00be9182 1662 public static function getContributionPageId($membershipID) {
6a488035
TO
1663 $query = "
1664SELECT c.contribution_page_id as pageID
1665 FROM civicrm_membership_payment mp, civicrm_contribution c
1666 WHERE mp.contribution_id = c.id
1667 AND c.contribution_page_id IS NOT NULL
1668 AND mp.membership_id = " . CRM_Utils_Type::escape($membershipID, 'Integer')
e0556ebe 1669 . " ORDER BY mp.id DESC";
6a488035
TO
1670
1671 return CRM_Core_DAO::singleValueQuery($query,
1672 CRM_Core_DAO::$_nullArray
1673 );
1674 }
1675
6a488035 1676 /**
fe482240 1677 * Updated related memberships.
6a488035 1678 *
b2363ea8
TO
1679 * @param int $ownerMembershipId
1680 * Owner Membership Id.
1681 * @param array $params
1682 * Formatted array of key => value.
6a488035 1683 */
00be9182 1684 public static function updateRelatedMemberships($ownerMembershipId, $params) {
6a488035
TO
1685 $membership = new CRM_Member_DAO_Membership();
1686 $membership->owner_membership_id = $ownerMembershipId;
1687 $membership->find();
1688
1689 while ($membership->fetch()) {
1690 $relatedMembership = new CRM_Member_DAO_Membership();
1691 $relatedMembership->id = $membership->id;
1692 $relatedMembership->copyValues($params);
1693 $relatedMembership->save();
1694 $relatedMembership->free();
1695 }
1696
1697 $membership->free();
1698 }
1699
1700 /**
fe482240 1701 * Get list of membership fields for profile.
6a488035
TO
1702 * For now we only allow custom membership fields to be in
1703 * profile
1704 *
e46e9a0b 1705 * @param null $mode
688d37c6 1706 * FIXME: This param is ignored
e46e9a0b 1707 *
a6c01b45
CW
1708 * @return array
1709 * the list of membership fields
6a488035 1710 */
00be9182 1711 public static function getMembershipFields($mode = NULL) {
6a488035
TO
1712 $fields = CRM_Member_DAO_Membership::export();
1713
6a488035
TO
1714 unset($fields['membership_contact_id']);
1715 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
1716
1717 $membershipType = CRM_Member_DAO_MembershipType::export();
1718
1719 $membershipStatus = CRM_Member_DAO_MembershipStatus::export();
1720
1721 $fields = array_merge($fields, $membershipType, $membershipStatus);
1722
1723 return $fields;
1724 }
1725
1726 /**
fe482240 1727 * Get the sort name of a contact for a particular membership.
6a488035 1728 *
b2363ea8
TO
1729 * @param int $id
1730 * Id of the membership.
6a488035 1731 *
72b3a70c
CW
1732 * @return null|string
1733 * sort name of the contact if found
6a488035 1734 */
00be9182 1735 public static function sortName($id) {
6a488035
TO
1736 $id = CRM_Utils_Type::escape($id, 'Integer');
1737
1738 $query = "
1739SELECT civicrm_contact.sort_name
1740FROM civicrm_membership, civicrm_contact
1741WHERE civicrm_membership.contact_id = civicrm_contact.id
1742 AND civicrm_membership.id = {$id}
1743";
1744 return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray);
1745 }
1746
1747 /**
fe482240 1748 * Create memberships for related contacts.
6a488035
TO
1749 * takes into account the maximum related memberships
1750 *
b2363ea8
TO
1751 * @param array $params
1752 * Array of key - value pairs.
1753 * @param CRM_Core_DAO $dao
1754 * Membership object.
6a488035 1755 *
72b3a70c
CW
1756 * @return null|array
1757 * array of memberships if created
6a488035 1758 */
00be9182 1759 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
6a488035 1760 static $relatedContactIds = array();
6d8a45ed
EM
1761 if ($reset) {
1762 // not sure why a static var is in use here - we need a way to reset it from the test suite
1763 $relatedContactIds = array();
608e6658 1764 return FALSE;
6d8a45ed 1765 }
6a488035
TO
1766
1767 $membership = new CRM_Member_DAO_Membership();
1768 $membership->id = $dao->id;
1769
1770 // required since create method doesn't return all the
1771 // parameters in the returned membership object
1772 if (!$membership->find(TRUE)) {
1773 return;
1774 }
1775 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
1776 // FIXME : While updating/ renewing the
1777 // membership, if the relationship is PAST then
1778 // the membership of the related contact must be
1779 // expired.
1780 // For that, getting Membership Status for which
1781 // is_current_member is 0. It works for the
1782 // generated data as there is only one membership
1783 // status having is_current_member = 0.
1784 // But this wont work exactly if there will be
1785 // more than one status having is_current_member = 0.
1786 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1787 $membershipStatus->is_current_member = 0;
1788 if ($membershipStatus->find(TRUE)) {
1789 $expiredStatusId = $membershipStatus->id;
e0556ebe
TO
1790 }
1791 else {
6a488035
TO
1792 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant::membershipStatus());
1793 }
1794
1795 $allRelatedContacts = array();
1796 $relatedContacts = array();
1797 if (!is_a($membership, 'CRM_Core_Error')) {
1798 $allRelatedContacts = CRM_Member_BAO_Membership::checkMembershipRelationship($membership->id,
1799 $membership->contact_id,
1800 CRM_Utils_Array::value('action', $params)
1801 );
1802 }
1803
1804 // check for loops. CRM-4213
1805 // remove repeated related contacts, which already inherited membership.
1806 $relatedContactIds[$membership->contact_id] = TRUE;
1807 foreach ($allRelatedContacts as $cid => $status) {
a7488080 1808 if (empty($relatedContactIds[$cid])) {
6a488035
TO
1809 $relatedContactIds[$cid] = TRUE;
1810
1811 //don't create membership again for owner contact.
1812 $nestedRelationship = FALSE;
1813 if ($membership->owner_membership_id) {
1814 $nestedRelMembership = new CRM_Member_DAO_Membership();
1815 $nestedRelMembership->id = $membership->owner_membership_id;
1816 $nestedRelMembership->contact_id = $cid;
1817 $nestedRelationship = $nestedRelMembership->find(TRUE);
1818 $nestedRelMembership->free();
1819 }
1820 if (!$nestedRelationship) {
1821 $relatedContacts[$cid] = $status;
1822 }
1823 }
1824 }
1825
1826 //lets cleanup related membership if any.
1827 if (empty($relatedContacts)) {
3506b6cd 1828 self::deleteRelatedMemberships($membership->id);
6a488035
TO
1829 }
1830 else {
1831 // Edit the params array
1832 unset($params['id']);
1833 // Reminder should be sent only to the direct membership
1834 unset($params['reminder_date']);
1835 // unset the custom value ids
1836 if (is_array(CRM_Utils_Array::value('custom', $params))) {
1837 foreach ($params['custom'] as $k => $v) {
1838 unset($params['custom'][$k]['id']);
1839 }
1840 }
1841 if (!isset($params['membership_type_id'])) {
1842 $params['membership_type_id'] = $membership->membership_type_id;
1843 }
1844
1845 // max_related should be set in the parent membership
1846 unset($params['max_related']);
1847 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1848 $available = ($membership->max_related == NULL ? PHP_INT_MAX : $membership->max_related);
1849 $queue = array(); // will be used to queue potential memberships to be created
1850
1851 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1852 //use existing membership record.
1853 $relMembership = new CRM_Member_DAO_Membership();
1854 $relMembership->contact_id = $contactId;
1855 $relMembership->owner_membership_id = $membership->id;
1856 $relMemIds = array();
1857 if ($relMembership->find(TRUE)) {
1858 $params['id'] = $relMemIds['membership'] = $relMembership->id;
1859 }
1860 $params['contact_id'] = $contactId;
1861 $params['owner_membership_id'] = $membership->id;
1862
1863 // set status_id as it might have been changed for
1864 // past relationship
1865 $params['status_id'] = $membership->status_id;
1866
1867 if ($deceasedStatusId &&
1868 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1869 ) {
1870 $params['status_id'] = $deceasedStatusId;
1871 }
1872 elseif ((CRM_Utils_Array::value('action', $params) & CRM_Core_Action::UPDATE) &&
1873 ($relationshipStatus == CRM_Contact_BAO_Relationship::PAST)
1874 ) {
e0556ebe
TO
1875 $params['status_id'] = $expiredStatusId;
1876 }
6a488035
TO
1877
1878 //don't calculate status again in create( );
1879 $params['skipStatusCal'] = TRUE;
1880
1881 //do create activity if we changed status.
1882 if ($params['status_id'] != $relMembership->status_id) {
1883 $params['createActivity'] = TRUE;
1884 }
1885
1886 // we should not created contribution record for related contacts, CRM-3371
1887 unset($params['contribution_status_id']);
1888
1889 if (($params['status_id'] == $deceasedStatusId) || ($params['status_id'] == $expiredStatusId)) {
1890 // related membership is not active so does not count towards maximum
1891 CRM_Member_BAO_Membership::create($params, $relMemIds);
8efea814
EM
1892 }
1893 else {
6a488035
TO
1894 // related membership already exists, so this is just an update
1895 if (isset($params['id'])) {
1896 if ($available > 0) {
e0556ebe
TO
1897 CRM_Member_BAO_Membership::create($params, $relMemIds);
1898 $available--;
1899 }
608e6658 1900 else {
1901 // we have run out of inherited memberships, so delete extras
f5e53870 1902 self::deleteMembership($params['id']);
6a488035 1903 }
e0556ebe
TO
1904 // we need to first check if there will remain inherited memberships, so queue it up
1905 }
1906 else {
6a488035
TO
1907 $queue[] = $params;
1908 }
1909 }
1910 }
1911 // now go over the queue and create any available related memberships
1912 reset($queue);
1913 while (($available > 0) && ($params = each($queue))) {
1914 CRM_Member_BAO_Membership::create($params['value'], $relMemIds);
e0556ebe 1915 $available--;
6a488035
TO
1916 }
1917 }
1918 }
1919
1920 /**
fe482240 1921 * Delete the record that are associated with this Membership Payment.
6a488035 1922 *
b2363ea8 1923 * @param int $membershipId
6a488035 1924 *
608e6658 1925 * @return object
1926 * $membershipPayment deleted membership payment object
6a488035 1927 */
00be9182 1928 public static function deleteMembershipPayment($membershipId) {
6a488035 1929
608e6658 1930 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1931 $membershipPayment->membership_id = $membershipId;
1932 $membershipPayment->find();
6a488035 1933
608e6658 1934 while ($membershipPayment->fetch()) {
1935 CRM_Contribute_BAO_Contribution::deleteContribution($membershipPayment->contribution_id);
1936 CRM_Utils_Hook::pre('delete', 'MembershipPayment', $membershipPayment->id, $membershipPayment);
061a8a1e 1937 $membershipPayment->delete();
608e6658 1938 CRM_Utils_Hook::post('delete', 'MembershipPayment', $membershipPayment->id, $membershipPayment);
6a488035 1939 }
608e6658 1940 return $membershipPayment;
6a488035
TO
1941 }
1942
bb3a214a 1943 /**
c490a46a 1944 * @param CRM_Core_Form $form
100fef9d 1945 * @param int $membershipTypeID
bb3a214a
EM
1946 *
1947 * @return array
1948 */
00be9182 1949 public static function &buildMembershipTypeValues(&$form, $membershipTypeID = NULL) {
e0556ebe 1950 $whereClause = " WHERE domain_id = " . CRM_Core_Config::domainID();
6a488035
TO
1951
1952 if (is_array($membershipTypeID)) {
1953 $allIDs = implode(',', $membershipTypeID);
1954 $whereClause .= " AND id IN ( $allIDs )";
1955 }
1956 elseif (is_numeric($membershipTypeID) &&
1957 $membershipTypeID > 0
1958 ) {
1959 $whereClause .= " AND id = $membershipTypeID";
1960 }
1961
1962 $query = "
1963SELECT *
1964FROM civicrm_membership_type
1965 $whereClause;
1966";
1967 $dao = CRM_Core_DAO::executeQuery($query);
1968
1969 $membershipTypeValues = array();
1970 $membershipTypeFields = array(
e0556ebe
TO
1971 'id',
1972 'minimum_fee',
1973 'name',
1974 'is_active',
1975 'description',
1976 'financial_type_id',
1977 'auto_renew',
1978 'member_of_contact_id',
1979 'relationship_type_id',
1980 'relationship_direction',
1981 'max_related',
6a488035
TO
1982 );
1983
1984 while ($dao->fetch()) {
1985 $membershipTypeValues[$dao->id] = array();
1986 foreach ($membershipTypeFields as $mtField) {
1987 $membershipTypeValues[$dao->id][$mtField] = $dao->$mtField;
1988 }
1989 }
1990 $dao->free();
1991
1992 CRM_Utils_Hook::membershipTypeValues($form, $membershipTypeValues);
1993
1994 if (is_numeric($membershipTypeID) &&
1995 $membershipTypeID > 0
1996 ) {
1997 return $membershipTypeValues[$membershipTypeID];
1998 }
1999 else {
2000 return $membershipTypeValues;
2001 }
2002 }
2003
2004 /**
fe482240 2005 * Get membership record count for a Contact.
6a488035 2006 *
c490a46a 2007 * @param int $contactID
b2363ea8 2008 * @param bool $activeOnly
6a488035 2009 *
c490a46a 2010 * @return null|string
6a488035 2011 */
00be9182 2012 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
6a488035 2013 $select = "SELECT count(*) FROM civicrm_membership ";
e0556ebe 2014 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
6a488035
TO
2015
2016 // CRM-6627, all status below 3 (active, pending, grace) are considered active
2017 if ($activeOnly) {
2018 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
e0556ebe 2019 $where .= " and civicrm_membership_status.is_current_member = 1";
6a488035
TO
2020 }
2021
2022 $query = $select . $where;
2023 return CRM_Core_DAO::singleValueQuery($query);
2024 }
2025
2026 /**
100fef9d 2027 * Check whether payment processor supports
6a488035
TO
2028 * cancellation of membership subscription
2029 *
b2363ea8
TO
2030 * @param int $mid
2031 * Membership id.
6a488035 2032 *
e46e9a0b
EM
2033 * @param bool $isNotCancelled
2034 *
608e6658 2035 * @return bool
6a488035 2036 */
00be9182 2037 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
6a488035
TO
2038 $cacheKeyString = "$mid";
2039 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2040
2041 static $supportsCancel = array();
2042
2043 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2044 $supportsCancel[$cacheKeyString] = FALSE;
2045 $isCancelled = FALSE;
2046
2047 if ($isNotCancelled) {
2048 $isCancelled = self::isSubscriptionCancelled($mid);
2049 }
2050
2051 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($mid, 'membership', 'obj');
2052 if (!empty($paymentObject)) {
2053 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2054 }
2055 }
2056 return $supportsCancel[$cacheKeyString];
2057 }
2058
2059 /**
fe482240 2060 * Check whether subscription is already cancelled.
6a488035 2061 *
b2363ea8
TO
2062 * @param int $mid
2063 * Membership id.
6a488035 2064 *
a6c01b45
CW
2065 * @return string
2066 * contribution status
6a488035 2067 */
00be9182 2068 public static function isSubscriptionCancelled($mid) {
6a488035
TO
2069 $sql = "
2070 SELECT cr.contribution_status_id
2071 FROM civicrm_contribution_recur cr
2072LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
2073 WHERE mem.id = %1 LIMIT 1";
e0556ebe 2074 $params = array(1 => array($mid, 'Integer'));
6a488035 2075 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
e0556ebe 2076 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name');
6a488035
TO
2077 if ($status == 'Cancelled') {
2078 return TRUE;
2079 }
2080 return FALSE;
2081 }
2082
2083 /**
100fef9d 2084 * Get membership joins for a specified membership
6a488035 2085 * type. Specifically, retrieves a count of still current memberships whose
4e636a74 2086 * join_date and start_date are within a specified date range. Dates match
8ef12e64 2087 * the pattern "yyyy-mm-dd".
6a488035 2088 *
b2363ea8
TO
2089 * @param int $membershipTypeId
2090 * Membership type id.
2091 * @param int $startDate
2092 * Date on which to start counting.
2093 * @param int $endDate
2094 * Date on which to end counting.
e46e9a0b 2095 * @param bool|int $isTest if true, membership is for a test site
6a488035 2096 *
72b3a70c
CW
2097 * @return int
2098 * the number of members of type $membershipTypeId
2099 * whose join_date is between $startDate and $endDate and
2100 * whose start_date is between $startDate and $endDate
6a488035 2101 */
00be9182 2102 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
6a488035
TO
2103 $testClause = 'membership.is_test = 1';
2104 if (!$isTest) {
2105 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2106 }
4e636a74
AH
2107 if (!self::$_signupActType) {
2108 self::_getActTypes();
2109 }
8ef12e64 2110
4e636a74
AH
2111 if (!self::$_signupActType) {
2112 return 0;
2113 }
6a488035
TO
2114
2115 $query = "
8ef12e64 2116 SELECT COUNT(DISTINCT membership.id) as member_count
6a488035 2117 FROM civicrm_membership membership
8ef12e64 2118INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
6a488035 2119INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
4e636a74
AH
2120INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2121 WHERE membership.membership_type_id = %2
2122 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
6a488035
TO
2123 AND {$testClause}";
2124
4e636a74
AH
2125 $params = array(
2126 1 => array(self::$_signupActType, 'Integer'),
2127 2 => array($membershipTypeId, 'Integer'),
2128 );
2129
6a488035
TO
2130 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
2131
e0556ebe 2132 return (int) $memberCount;
6a488035
TO
2133 }
2134
2135 /**
100fef9d 2136 * Get membership renewals for a specified membership
4e636a74 2137 * type. Specifically, retrieves a count of still current memberships
8ef12e64 2138 * whose join_date is before and start_date is within a specified date
4e636a74 2139 * range. Dates match the pattern "yyyy-mm-dd".
6a488035 2140 *
b2363ea8
TO
2141 * @param int $membershipTypeId
2142 * Membership type id.
2143 * @param int $startDate
2144 * Date on which to start counting.
2145 * @param int $endDate
2146 * Date on which to end counting.
e46e9a0b 2147 * @param bool|int $isTest if true, membership is for a test site
6a488035 2148 *
df8d3074 2149 * @return int
a6c01b45 2150 * returns the number of members of type $membershipTypeId
688d37c6
CW
2151 * whose join_date is before $startDate and
2152 * whose start_date is between $startDate and $endDate
6a488035 2153 */
00be9182 2154 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
6a488035
TO
2155 $testClause = 'membership.is_test = 1';
2156 if (!$isTest) {
2157 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2158 }
4e636a74
AH
2159 if (!self::$_renewalActType) {
2160 self::_getActTypes();
2161 }
8ef12e64 2162
4e636a74
AH
2163 if (!self::$_renewalActType) {
2164 return 0;
2165 }
6a488035
TO
2166
2167 $query = "
8ef12e64 2168 SELECT COUNT(DISTINCT membership.id) as member_count
6a488035 2169 FROM civicrm_membership membership
4e636a74 2170INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
6a488035
TO
2171INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2172INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
4e636a74 2173 WHERE membership.membership_type_id = %2
8ef12e64 2174 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
6a488035
TO
2175 AND {$testClause}";
2176
4e636a74
AH
2177 $params = array(
2178 1 => array(self::$_renewalActType, 'Integer'),
2179 2 => array($membershipTypeId, 'Integer'),
2180 );
6a488035
TO
2181 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
2182
e0556ebe 2183 return (int) $memberCount;
6a488035
TO
2184 }
2185
7273a245 2186 /**
fe482240 2187 * Where a second separate financial transaction is supported we will process it here.
236a2274 2188 *
100fef9d 2189 * @param int $contactID
5624f515 2190 * @param CRM_Contribute_Form_Contribution_Confirm $form
100fef9d 2191 * @param array $tempParams
7273a245 2192 * @param $isTest
100fef9d 2193 * @param array $lineItems
d25e4224 2194 * @param $minimumFee
100fef9d 2195 * @param int $financialTypeID
d25e4224 2196 *
5624f515 2197 * @throws CRM_Core_Exception
d25e4224 2198 * @throws Exception
236a2274 2199 * @return CRM_Contribute_BAO_Contribution
7273a245 2200 */
5624f515 2201 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID) {
2883c2b2
EM
2202 $financialType = new CRM_Financial_DAO_FinancialType();
2203 $financialType->id = $financialTypeID;
2204 if (!$financialType->find(TRUE)) {
7273a245
EM
2205 CRM_Core_Error::fatal(ts("Could not find a system table"));
2206 }
2207 $tempParams['amount'] = $minimumFee;
2208 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
2209
2210 $result = NULL;
2211 if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
2212 $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
2213
2214 if ($form->_contributeMode == 'express') {
2215 $result = $payment->doExpressCheckout($tempParams);
a19183c1
EM
2216 if (is_a($result, 'CRM_Core_Error')) {
2217 throw new CRM_Core_Exception(CRM_Core_Error::getMessages($result));
2218 }
7273a245
EM
2219 }
2220 else {
a19183c1 2221 $result = $payment->doPayment($tempParams, 'contribute');
7273a245
EM
2222 }
2223 }
2224
a19183c1
EM
2225 //assign receive date when separate membership payment
2226 //and contribution amount not selected.
2227 if ($form->_amount == 0) {
2228 $now = date('YmdHis');
2229 $form->_params['receive_date'] = $now;
2230 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
2231 $form->set('params', $form->_params);
2232 $form->assign('receive_date', $receiveDate);
7273a245 2233 }
7273a245 2234
a19183c1
EM
2235 $form->set('membership_trx_id', $result['trxn_id']);
2236 $form->set('membership_amount', $minimumFee);
2237
2238 $form->assign('membership_trx_id', $result['trxn_id']);
2239 $form->assign('membership_amount', $minimumFee);
2240
2241 // we don't need to create the user twice, so lets disable cms_create_account
2242 // irrespective of the value, CRM-2888
2243 $tempParams['cms_create_account'] = 0;
2244
2245 $pending = $form->_params['is_pay_later'] ? (($minimumFee > 0.0) ? TRUE : FALSE) : FALSE;
2246
2247 //set this variable as we are not creating pledge for
2248 //separate membership payment contribution.
2249 //so for differentiating membership contribution from
2250 //main contribution.
2251 $form->_params['separate_membership_payment'] = 1;
2252 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($form,
2253 $tempParams,
2254 $result,
2255 $contactID,
2883c2b2 2256 $financialType,
a19183c1
EM
2257 $pending,
2258 TRUE,
2259 $isTest,
2260 $lineItems
2261 );
2262 return $membershipContribution;
7273a245
EM
2263 }
2264
0547ad7d
EM
2265 /**
2266 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
2267 * refactoring step. This should be BAO functionality
2268 * @param $membership
2269 * @param $membershipContribution
2270 */
2271 public static function linkMembershipPayment($membership, $membershipContribution) {
e0556ebe 2272 CRM_Member_BAO_MembershipPayment::create(array(
353ffa53
TO
2273 'membership_id' => $membership->id,
2274 'contribution_id' => $membershipContribution->id,
2275 ));
0547ad7d
EM
2276 }
2277
8dde2f13 2278 /**
100fef9d
CW
2279 * @param array $membershipParams
2280 * @param int $contactID
8dde2f13 2281 * @param $customFieldsFormatted
100fef9d 2282 * @param int $membershipID
8dde2f13
EM
2283 * @param $memType
2284 * @param $isTest
2285 * @param $numTerms
2286 * @param $membershipContribution
c490a46a 2287 * @param CRM_Core_Form $form
8dde2f13
EM
2288 *
2289 * @return array
2290 */
e0556ebe 2291 public static function createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, &$form) {
c98997b9 2292 $membership = self::renewMembershipFormWrapper($contactID, $memType,
8dde2f13
EM
2293 $isTest, $form, NULL,
2294 CRM_Utils_Array::value('cms_contactID', $membershipParams),
2295 $customFieldsFormatted, $numTerms,
2296 $membershipID
2297 );
2298
8dde2f13 2299 if (!empty($membershipContribution)) {
423c9872
C
2300 // update recurring id for membership record
2301 self::updateRecurMembership($membership, $membershipContribution);
2302
8dde2f13
EM
2303 self::linkMembershipPayment($membership, $membershipContribution);
2304 }
2305 return $membership;
2306 }
2307
15c3308b 2308 /**
fe482240 2309 * Turn array of errors into message string.
15c3308b
EM
2310 *
2311 * @param array $errors
2312 *
15c3308b
EM
2313 * @return string
2314 */
e0556ebe
TO
2315 public static function compileErrorMessage($errors) {
2316 foreach ($errors as $error) {
15c3308b
EM
2317 if (is_string($error)) {
2318 $message[] = $error;
2319 }
2320 }
2321 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
2322 }
2323
c98997b9 2324 /**
fe482240 2325 * Extract relevant values from the form so we can separate form logic from BAO logcis.
688d37c6 2326 *
c490a46a 2327 * @param CRM_Core_Form $form
c98997b9
EM
2328 * @param $changeToday
2329 * @param $membershipTypeDetails
2330 *
2331 * @return array
2332 */
e0556ebe 2333 public static function extractFormValues($form, $changeToday, $membershipTypeDetails) {
c98997b9
EM
2334 $pending = FALSE;
2335 //@todo this is a BAO function & should not inspect the form - the form should do this
2336 // & pass required params to the BAO
2337 if (CRM_Utils_Array::value('minimum_fee', $membershipTypeDetails) > 0.0) {
2338 if (((isset($form->_contributeMode) && $form->_contributeMode == 'notify') || !empty($form->_params['is_pay_later']) ||
2339 (!empty($form->_params['is_recur']) && $form->_contributeMode == 'direct'
2340 )
2341 ) &&
2342 (($form->_values['is_monetary'] && $form->_amount > 0.0) || !empty($form->_params['separate_membership_payment']) ||
2343 CRM_Utils_Array::value('record_contribution', $form->_params)
2344 )
2345 ) {
2346 $pending = TRUE;
2347 }
2348 }
2349 $contributionRecurID = isset($form->_params['contributionRecurID']) ? $form->_params['contributionRecurID'] : NULL;
2350
2351 //we renew expired membership, CRM-6277
2352 if (!$changeToday) {
2353 if ($form->get('renewalDate')) {
2354 $changeToday = $form->get('renewalDate');
2355 }
2356 elseif (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') {
2357 $changeToday = date('YmdHis');
2358 }
2359 }
2360
c352e9fc 2361 $membershipSource = NULL;
c98997b9
EM
2362 if (!empty($form->_params['membership_source'])) {
2363 $membershipSource = $form->_params['membership_source'];
2364 }
2365 elseif (isset($form->_values['title']) && !empty($form->_values['title'])) {
2366 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values['title'];
2367 }
c352e9fc 2368 $isPayLater = NULL;
e0556ebe 2369 if (isset($form->_params)) {
c352e9fc
C
2370 $isPayLater = CRM_Utils_Array::value('is_pay_later', $form->_params);
2371 }
c98997b9
EM
2372 $campaignId = NULL;
2373 if (isset($form->_values) && is_array($form->_values) && !empty($form->_values)) {
2374 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_params);
2375 if (!array_key_exists('campaign_id', $form->_params)) {
2376 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
2377 }
2378 }
2379 return array($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId);
2380 }
2381
2382 /**
b2363ea8 2383 * @param int $contactID
100fef9d 2384 * @param int $membershipTypeID
c98997b9
EM
2385 * @param bool $is_test
2386 * @param $changeToday
b2363ea8 2387 * @param int $modifiedID
c98997b9
EM
2388 * @param $customFieldsFormatted
2389 * @param $numRenewTerms
100fef9d 2390 * @param int $membershipID
c98997b9
EM
2391 * @param $pending
2392 * @param $allStatus
2393 * @param array $membershipTypeDetails
b2363ea8 2394 * @param int $contributionRecurID
c98997b9
EM
2395 * @param $format
2396 * @param $membershipSource
2397 * @param $ids
2398 * @param $statusFormat
2399 * @param $isPayLater
b2363ea8 2400 * @param int $campaignId
c98997b9
EM
2401 *
2402 * @throws CRM_Core_Exception
2403 * @return array
2404 */
2405 public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId) {
2406 $renewalMode = $updateStatusId = FALSE;
2407 $dates = array();
d81c67a2 2408 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
c98997b9
EM
2409 // is the same as the parent org of an existing membership of the contact
2410 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID,
2411 $is_test, $membershipID, TRUE
2412 );
2413 if ($currentMembership) {
2414 $activityType = 'Membership Renewal';
2415 $renewalMode = TRUE;
2416
2417 // Do NOT do anything.
2418 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2419 //2. Paylater/IPN renew. CRM-4556.
e0556ebe
TO
2420 if ($pending || in_array($currentMembership['status_id'], array(
2421 array_search('Pending', $allStatus),
7ff60806
PN
2422 // CRM-15475
2423 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
c98997b9
EM
2424 ))
2425 ) {
2426 $membership = new CRM_Member_DAO_Membership();
2427 $membership->id = $currentMembership['id'];
2428 $membership->find(TRUE);
2429
2430 // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed
2431 $format = '%Y%m%d';
2432 // note that we are logging the requested new membership_type_id that may be different than current membership_type_id
2433 // it will be used when payment is received to update the membership_type_id to what was paid for
2434 $logParams = array(
2435 'membership_id' => $membership->id,
2436 'status_id' => $membership->status_id,
2437 'start_date' => CRM_Utils_Date::customFormat(
2438 $membership->start_date,
2439 $format
2440 ),
2441 'end_date' => CRM_Utils_Date::customFormat(
2442 $membership->end_date,
2443 $format
2444 ),
2445 'modified_date' => CRM_Utils_Date::customFormat(
2446 date('Ymd'),
2447 $format
2448 ),
2449 'membership_type_id' => $membershipTypeID,
ef0abb4c 2450 'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL,
c98997b9
EM
2451 );
2452 $session = CRM_Core_Session::singleton();
2453 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
2454 if ($session->get('userID')) {
2455 $logParams['modified_id'] = $session->get('userID');
2456 }
2457 else {
2458 $logParams['modified_id'] = $membership->contact_id;
2459 }
2460 CRM_Member_BAO_MembershipLog::add($logParams, CRM_Core_DAO::$_nullArray);
2461
2462 if (!empty($contributionRecurID)) {
2463 CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $membership->id,
2464 'contribution_recur_id', $contributionRecurID
2465 );
2466 }
2467
f82cf0ed 2468 return array($membership, $renewalMode, $dates);
c98997b9
EM
2469 }
2470
2471 // Check and fix the membership if it is STALE
2472 self::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2473
2474 // Now Renew the membership
2475 if (!$currentMembership['is_current_member']) {
2476 // membership is not CURRENT
2477
2478 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2479 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
2480 $changeToday,
2481 $membershipTypeID,
2482 $numRenewTerms
2483 );
2484
2485 $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
2486 $currentMembership['start_date'] = CRM_Utils_Array::value('start_date', $dates);
2487 $currentMembership['end_date'] = CRM_Utils_Array::value('end_date', $dates);
2488 $currentMembership['is_test'] = $is_test;
2489
2490 if (!empty($membershipSource)) {
2491 $currentMembership['source'] = $membershipSource;
2492 }
2493 else {
2494 $currentMembership['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
2495 $currentMembership['id'],
2496 'source'
2497 );
2498 }
2499
2500 if (!empty($currentMembership['id'])) {
2501 $ids['membership'] = $currentMembership['id'];
2502 }
2503 $memParams = $currentMembership;
2504 $memParams['membership_type_id'] = $membershipTypeID;
2505
2506 //set the log start date.
2507 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
2508 }
2509 else {
2510
2511 // CURRENT Membership
2512 $membership = new CRM_Member_DAO_Membership();
2513 $membership->id = $currentMembership['id'];
2514 $membership->find(TRUE);
2515 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2516 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
2517 $changeToday,
2518 $membershipTypeID,
2519 $numRenewTerms
2520 );
2521
2522 // Insert renewed dates for CURRENT membership
2523 $memParams = array();
2524 $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date);
2525 $memParams['start_date'] = CRM_Utils_Date::isoToMysql($membership->start_date);
2526 $memParams['end_date'] = CRM_Utils_Array::value('end_date', $dates);
2527 $memParams['membership_type_id'] = $membershipTypeID;
2528
2529 //set the log start date.
2530 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
2531 if (empty($membership->source)) {
2532 if (!empty($membershipSource)) {
2533 $memParams['source'] = $membershipSource;
2534 }
2535 else {
2536 $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
2537 $currentMembership['id'],
2538 'source'
2539 );
2540 }
2541 }
2542
2543 if (!empty($currentMembership['id'])) {
2544 $ids['membership'] = $currentMembership['id'];
2545 }
2546 }
2547 //CRM-4555
2548 if ($pending) {
2549 $updateStatusId = array_search('Pending', $allStatus);
2550 }
2551 }
2552 else {
2553 // NEW Membership
2554
2555 $activityType = 'Membership Signup';
2556 $memParams = array(
2557 'contact_id' => $contactID,
2558 'membership_type_id' => $membershipTypeID,
2559 );
2560
2561 if (!$pending) {
2562 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2563
2564 $memParams['join_date'] = CRM_Utils_Array::value('join_date', $dates);
2565 $memParams['start_date'] = CRM_Utils_Array::value('start_date', $dates);
2566 $memParams['end_date'] = CRM_Utils_Array::value('end_date', $dates);
2567
2568 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'],
2569 $statusFormat
2570 ),
2571 CRM_Utils_Date::customFormat($dates['end_date'],
2572 $statusFormat
2573 ),
2574 CRM_Utils_Date::customFormat($dates['join_date'],
2575 $statusFormat
2576 ),
2577 'today',
2578 TRUE,
2579 $membershipTypeID,
2580 $memParams
2581 );
2582 $updateStatusId = CRM_Utils_Array::value('id', $status);
2583 }
2584 else {
2585 // if IPN/Pay-Later set status to: PENDING
2586 $updateStatusId = array_search('Pending', $allStatus);
2587 }
2588
2589 if (!empty($membershipSource)) {
2590 $memParams['source'] = $membershipSource;
2591 }
2592 $memParams['contribution_recur_id'] = $contributionRecurID;
2593
2594 $memParams['is_test'] = $is_test;
2595 $memParams['is_pay_later'] = $isPayLater;
2596 }
2597
2598 //CRM-4555
2599 //if we decided status here and want to skip status
2600 //calculation in create( ); then need to pass 'skipStatusCal'.
2601 if ($updateStatusId) {
2602 $memParams['status_id'] = $updateStatusId;
2603 $memParams['skipStatusCal'] = TRUE;
2604 }
2605
2606 //since we are renewing,
2607 //make status override false.
2608 $memParams['is_override'] = FALSE;
2609
2610 //CRM-4027, create log w/ individual contact.
2611 if ($modifiedID) {
2612 $ids['userId'] = $modifiedID;
2613 $memParams['is_for_organization'] = TRUE;
2614 }
2615 else {
2616 $ids['userId'] = $contactID;
2617 }
2618
2619 //inherit campaign from contrib page.
2620 if (isset($campaignId)) {
2621 $memParams['campaign_id'] = $campaignId;
2622 }
2623
2624 $memParams['custom'] = $customFieldsFormatted;
2625 $membership = self::create($memParams, $ids, FALSE, $activityType);
2626
2627 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2628 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2629 $membership->find(TRUE);
2630
2631 return array($membership, $renewalMode, $dates);
2632 }
2633
6a488035 2634 /**
100fef9d 2635 * Process price set and line items.
6a488035 2636 *
100fef9d 2637 * @param int $membershipId
e46e9a0b
EM
2638 * @param $lineItem
2639 *
355ba699 2640 * @return void
6a488035 2641 */
00be9182 2642 public function processPriceSet($membershipId, $lineItem) {
6a488035
TO
2643 //FIXME : need to move this too
2644 if (!$membershipId || !is_array($lineItem)
ca58d9b9 2645 || CRM_Utils_System::isNull($lineItem)
6a488035
TO
2646 ) {
2647 return;
2648 }
2649
2650 foreach ($lineItem as $priceSetId => $values) {
2651 if (!$priceSetId) {
2652 continue;
2653 }
2654 foreach ($values as $line) {
2655 $line['entity_table'] = 'civicrm_membership';
2656 $line['entity_id'] = $membershipId;
2657 CRM_Price_BAO_LineItem::create($line);
2658 }
2659 }
2660 }
2661
2662 /**
fe482240 2663 * Retrieve the contribution id for the associated Membership id.
ca266339 2664 * @todo we should get this off the line item
6a488035 2665 *
b2363ea8
TO
2666 * @param int $membershipId
2667 * Membership id.
6a488035 2668 *
df8d3074 2669 * @return int
a6c01b45 2670 * contribution id
6a488035 2671 */
00be9182 2672 public static function getMembershipContributionId($membershipId) {
6a488035 2673
ca266339
EM
2674 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2675 $membershipPayment->membership_id = $membershipId;
2676 if ($membershipPayment->find(TRUE)) {
2677 return $membershipPayment->contribution_id;
6a488035
TO
2678 }
2679 return NULL;
2680 }
2681
2682 /**
e0556ebe
TO
2683 * The function checks and updates the status of all membership records for a given domain using the
2684 * calc_membership_status and update_contact_membership APIs.
2685 *
2686 * IMPORTANT:
2687 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2688 *
a6c01b45 2689 * @return array
e0556ebe 2690 */
00be9182 2691 public static function updateAllMembershipStatus() {
6a488035
TO
2692
2693 //get all active statuses of membership, CRM-3984
e0556ebe
TO
2694 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
2695 $statusLabels = CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label');
2696 $allTypes = CRM_Member_PseudoConstant::membershipType();
6a488035 2697
85b6e9a2 2698 // get only memberships with active membership types
6a488035
TO
2699 $query = "
2700SELECT civicrm_membership.id as membership_id,
2701 civicrm_membership.is_override as is_override,
2702 civicrm_membership.membership_type_id as membership_type_id,
2703 civicrm_membership.status_id as status_id,
2704 civicrm_membership.join_date as join_date,
2705 civicrm_membership.start_date as start_date,
2706 civicrm_membership.end_date as end_date,
2707 civicrm_membership.source as source,
2708 civicrm_contact.id as contact_id,
2709 civicrm_contact.is_deceased as is_deceased,
2710 civicrm_membership.owner_membership_id as owner_membership_id,
2711 civicrm_membership.contribution_recur_id as recur_id
2712FROM civicrm_membership
2713INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
85b6e9a2
DL
2714INNER JOIN civicrm_membership_type ON
2715 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
6a488035
TO
2716WHERE civicrm_membership.is_test = 0";
2717
2718 $params = array();
2719 $dao = CRM_Core_DAO::executeQuery($query, $params);
2720
e0556ebe
TO
2721 $processCount = 0;
2722 $updateCount = 0;
6a488035
TO
2723
2724 $smarty = CRM_Core_Smarty::singleton();
2725
2726 while ($dao->fetch()) {
2727 // echo ".";
2728 $processCount++;
2729
6a488035
TO
2730 // Put common parameters into array for easy access
2731 $memberParams = array(
2732 'id' => $dao->membership_id,
2733 'status_id' => $dao->status_id,
2734 'contact_id' => $dao->contact_id,
2735 'membership_type_id' => $dao->membership_type_id,
2736 'membership_type' => $allTypes[$dao->membership_type_id],
2737 'join_date' => $dao->join_date,
2738 'start_date' => $dao->start_date,
2739 'end_date' => $dao->end_date,
2740 'source' => $dao->source,
2741 'skipStatusCal' => TRUE,
2742 'skipRecentView' => TRUE,
2743 );
2744
2745 $smarty->assign_by_ref('memberParams', $memberParams);
2746
2747 //update membership record to Deceased if contact is deceased
2748 if ($dao->is_deceased) {
2749 // check for 'Deceased' membership status, CRM-5636
2750 $deceaseStatusId = array_search('Deceased', $allStatus);
2751 if (!$deceaseStatusId) {
2752 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'))));
2753 }
2754
2755 //process only when status change.
2756 if ($dao->status_id != $deceaseStatusId) {
2757 //take all params that need to save.
2758 $deceasedMembership = $memberParams;
2759 $deceasedMembership['status_id'] = $deceaseStatusId;
2760 $deceasedMembership['createActivity'] = TRUE;
2761 $deceasedMembership['version'] = 3;
2762
2763 //since there is change in status.
2764 $statusChange = array('status_id' => $deceaseStatusId);
2765 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
68cf2de1 2766 unset(
2767 $deceasedMembership['contact_id'],
2768 $deceasedMembership['membership_type_id'],
2769 $deceasedMembership['membership_type'],
2770 $deceasedMembership['join_date'],
2771 $deceasedMembership['start_date'],
2772 $deceasedMembership['end_date'],
2773 $deceasedMembership['source']
2774 );
6a488035
TO
2775
2776 //process membership record.
2777 civicrm_api('membership', 'create', $deceasedMembership);
2778 }
2779 continue;
2780 }
2781
2782 //we fetch related, since we need to check for deceased
2783 //now further processing is handle w/ main membership record.
2784 if ($dao->owner_membership_id) {
2785 continue;
2786 }
2787
2788 //update membership records where status is NOT - Pending OR Cancelled.
2789 //as well as membership is not override.
2790 //skipping Expired membership records -> reduced extra processing( kiran )
2791 if (!$dao->is_override &&
e0556ebe
TO
2792 !in_array($dao->status_id, array(
2793 array_search('Pending', $allStatus),
2794 // CRM-15475
2795 array_search(
2796 'Cancelled',
2797 CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2798 ),
2799 array_search('Expired', $allStatus),
2800 ))
6a488035
TO
2801 ) {
2802
2803 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2804 //get the membership status as per id.
2805 $newStatus = civicrm_api('membership_status', 'calc',
2806 array(
e0556ebe
TO
2807 'membership_id' => $dao->membership_id,
2808 'version' => 3,
21dfd5f5 2809 'ignore_admin_only' => FALSE,
e0556ebe 2810 ), TRUE
6a488035
TO
2811 );
2812 $statusId = CRM_Utils_Array::value('id', $newStatus);
2813
2814 //process only when status change.
2815 if ($statusId &&
2816 $statusId != $dao->status_id
2817 ) {
2818 //take all params that need to save.
2819 $memParams = $memberParams;
2820 $memParams['status_id'] = $statusId;
2821 $memParams['createActivity'] = TRUE;
2822 $memParams['version'] = 3;
2823
4daee127 2824 // Unset columns which should remain unchanged from their current saved
2825 // values. This avoids race condition in which these values may have
2826 // been changed by other processes.
2827 unset(
2828 $memParams['contact_id'],
2829 $memParams['membership_type_id'],
2830 $memParams['membership_type'],
2831 $memParams['join_date'],
2832 $memParams['start_date'],
2833 $memParams['end_date'],
2834 $memParams['source']
2835 );
6a488035
TO
2836 //since there is change in status.
2837 $statusChange = array('status_id' => $statusId);
2838 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2839
2840 //process member record.
2841 civicrm_api('membership', 'create', $memParams);
2842 $updateCount++;
2843 }
2844 }
6a488035
TO
2845 }
2846 $result['is_error'] = 0;
e0556ebe 2847 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
353ffa53
TO
2848 1 => $processCount,
2849 2 => $updateCount,
2850 ));
6a488035
TO
2851 return $result;
2852 }
2853
e46e9a0b 2854 /**
688d37c6 2855 * Returns the membership types for a particular contact
6a488035
TO
2856 * who has lifetime membership without end date.
2857 *
100fef9d 2858 * @param int $contactID
e46e9a0b
EM
2859 * @param bool $isTest
2860 * @param bool $onlyLifeTime
6a488035 2861 *
e46e9a0b 2862 * @return array
6a488035 2863 */
00be9182 2864 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
6a488035
TO
2865 $contactMembershipType = array();
2866 if (!$contactID) {
2867 return $contactMembershipType;
2868 }
2869
e0556ebe 2870 $dao = new CRM_Member_DAO_Membership();
6a488035
TO
2871 $dao->contact_id = $contactID;
2872 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant::membershipStatus());
2873 $dao->whereAdd("status_id != $pendingStatusId");
2874
2875 if ($isTest) {
2876 $dao->is_test = $isTest;
2877 }
2878 else {
2879 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2880 }
2881
2882 if ($onlyLifeTime) {
2883 $dao->whereAdd('end_date IS NULL');
2884 }
2885
2886 $dao->find();
2887 while ($dao->fetch()) {
2888 $membership = array();
2889 CRM_Core_DAO::storeValues($dao, $membership);
2890 $contactMembershipType[$dao->membership_type_id] = $membership;
2891 }
2892 return $contactMembershipType;
2893 }
2894
2895 /**
fe482240 2896 * Record contribution record associated with membership.
6a488035 2897 *
b2363ea8
TO
2898 * @param array $params
2899 * Array of submitted params.
2900 * @param array $ids
2901 * (param in process of being removed - try to use params) array of ids.
6a488035 2902 *
02af3683 2903 * @return CRM_Contribute_BAO_Contribution
6a488035 2904 */
e0556ebe 2905 public static function recordMembershipContribution(&$params, $ids = array()) {
d824fb6e 2906 $membershipId = $params['membership_id'];
6a488035
TO
2907 $contributionParams = array();
2908 $config = CRM_Core_Config::singleton();
2909 $contributionParams['currency'] = $config->defaultCurrency;
2910 $contributionParams['receipt_date'] = (CRM_Utils_Array::value('receipt_date', $params)) ? $params['receipt_date'] : 'null';
2911 $contributionParams['source'] = CRM_Utils_Array::value('contribution_source', $params);
6a488035 2912 $contributionParams['non_deductible_amount'] = 'null';
dcb032dc 2913 $contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor_id', $params);
d80dbc14 2914 $contributionSoftParams = CRM_Utils_Array::value('soft_credit', $params);
6a488035 2915 $recordContribution = array(
e0556ebe
TO
2916 'contact_id',
2917 'total_amount',
2918 'receive_date',
2919 'financial_type_id',
2920 'payment_instrument_id',
2921 'trxn_id',
2922 'invoice_id',
2923 'is_test',
2924 'contribution_status_id',
2925 'check_number',
2926 'campaign_id',
2927 'is_pay_later',
2928 'membership_id',
2929 'tax_amount',
21dfd5f5 2930 'skipLineItem',
6a488035
TO
2931 );
2932 foreach ($recordContribution as $f) {
2933 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
2934 }
2935
2936 // make entry in batch entity batch table
a7488080 2937 if (!empty($params['batch_id'])) {
6a488035
TO
2938 $contributionParams['batch_id'] = $params['batch_id'];
2939 }
2940
91ef9be0 2941 if (!empty($params['contribution_contact_id'])) {
2942 // deal with possibility of a different person paying for contribution
2943 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2944 }
2945
a7488080 2946 if (!empty($params['processPriceSet']) &&
6a488035
TO
2947 !empty($params['lineItems'])
2948 ) {
2949 $contributionParams['line_item'] = CRM_Utils_Array::value('lineItems', $params, NULL);
2950 }
2951
2952 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
2953
c206647d 2954 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
d80dbc14 2955 if (!empty($contributionSoftParams)) {
9e1854a1 2956 if (!empty($params['batch_id'])) {
2957 foreach ($contributionSoftParams as $contributionSoft) {
2958 $contributionSoft['contribution_id'] = $contribution->id;
2959 $contributionSoft['currency'] = $contribution->currency;
2960 CRM_Contribute_BAO_ContributionSoft::add($contributionSoft);
2961 }
2962 }
2963 else {
e0556ebe
TO
2964 $contributionSoftParams['contribution_id'] = $contribution->id;
2965 $contributionSoftParams['currency'] = $contribution->currency;
2966 $contributionSoftParams['amount'] = $contribution->total_amount;
2967 CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams);
a54e2c55 2968 }
d80dbc14 2969 }
2970
6a488035
TO
2971 // store contribution id
2972 $params['contribution_id'] = $contribution->id;
2973
6a488035 2974 //insert payment record for this membership
8cc574cf 2975 if (empty($ids['contribution']) || !empty($params['is_recur'])) {
e0556ebe 2976 CRM_Member_BAO_MembershipPayment::create(array(
353ffa53
TO
2977 'membership_id' => $membershipId,
2978 'contribution_id' => $contribution->id,
2979 ));
6a488035
TO
2980 }
2981 return $contribution;
2982 }
2983
2984 /**
fe482240 2985 * Record line items for default membership.
6a488035 2986 *
c490a46a 2987 * @param CRM_Core_Form $qf
b2363ea8
TO
2988 * @param array $membershipType
2989 * Array with membership type and organization.
c490a46a 2990 * @param int $priceSetId
e46e9a0b 2991 *
6a488035 2992 */
00be9182 2993 public static function createLineItems(&$qf, $membershipType, &$priceSetId) {
9da8dc8c 2994 $qf->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
6a488035 2995 if ($priceSetId) {
9da8dc8c 2996 $qf->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
6a488035
TO
2997 }
2998 $editedFieldParams = array(
2999 'price_set_id' => $priceSetId,
3000 'name' => $membershipType[0],
3001 );
3002 $editedResults = array();
9da8dc8c 3003 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
6a488035
TO
3004
3005 if (!empty($editedResults)) {
3006 unset($qf->_priceSet['fields']);
3007 $qf->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
3008 unset($qf->_priceSet['fields'][$editedResults['id']]['options']);
3009 $fid = $editedResults['id'];
3010 $editedFieldParams = array(
3011 'price_field_id' => $editedResults['id'],
3012 'membership_type_id' => $membershipType[1],
3013 );
3014 $editedResults = array();
9da8dc8c 3015 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
6a488035 3016 $qf->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
a7488080 3017 if (!empty($qf->_params['total_amount'])) {
6a488035
TO
3018 $qf->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $qf->_params['total_amount'];
3019 }
3020 }
3021
3022 $fieldID = key($qf->_priceSet['fields']);
3023 $qf->_params['price_' . $fieldID] = CRM_Utils_Array::value('id', $editedResults);
3024 }
8ef12e64 3025
e46e9a0b
EM
3026 /**
3027 * @todo document me - I seem a bit out of date....
3028 */
00be9182 3029 public static function _getActTypes() {
4e636a74
AH
3030 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
3031 self::$_renewalActType = CRM_Utils_Array::key('Membership Renewal', $activityTypes);
3032 self::$_signupActType = CRM_Utils_Array::key('Membership Signup', $activityTypes);
3033 }
5624f515 3034
b5a62499
PN
3035 /**
3036 * Get all Cancelled Membership(s) for a contact
3037 *
b2363ea8
TO
3038 * @param int $contactID
3039 * Contact id.
3040 * @param bool $isTest
3041 * Mode of payment.
b5a62499 3042 *
a6c01b45 3043 * @return array
16b10e64 3044 * Array of membership type
b5a62499 3045 */
00be9182 3046 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
b5a62499
PN
3047 if (!$contactID) {
3048 return array();
5624f515 3049 }
b5a62499
PN
3050 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
3051 $queryParams = array(
3052 1 => array($contactID, 'Integer'),
7ff60806
PN
3053 2 => array(
3054 // CRM-15475
3055 array_search(
4c16123d 3056 'Cancelled',
7ff60806 3057 CRM_Member_PseudoConstant::membershipStatus(
4c16123d
EM
3058 NULL,
3059 " name = 'Cancelled' ",
3060 'name',
3061 FALSE,
7ff60806
PN
3062 TRUE
3063 )
4c16123d 3064 ),
21dfd5f5 3065 'Integer',
7ff60806 3066 ),
b5a62499
PN
3067 3 => array($isTest, 'Boolean'),
3068 );
5624f515 3069
b5a62499
PN
3070 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
3071 $cancelledMembershipIds = array();
3072 while ($dao->fetch()) {
3073 $cancelledMembershipIds[] = $dao->membership_type_id;
3074 }
3075 return $cancelledMembershipIds;
3076 }
96025800 3077
6a488035 3078}