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