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