Merge branch '4.6' into 'master'
[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 * @retun 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 = 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 $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams,
1333 $premiumParams, $contactID,
1334 $financialTypeID,
1335 'membership',
1336 array(),
1337 $isTest,
1338 $isPayLater
1339 );
1340 if (is_a($result[1], 'CRM_Core_Error')) {
1341 $errors[1] = CRM_Core_Error::getMessages($result[1]);
1342 }
1343 elseif (!empty($result[1])) {
1344 // Save the contribution ID so that I can be used in email receipts
1345 // For example, if you need to generate a tax receipt for the donation only.
1346 $form->_values['contribution_other_id'] = $result[1]->id;
1347 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1348 $membershipContribution = $result[1];
1349 }
1350 }
1351
1352 if ($isProcessSeparateMembershipTransaction) {
1353 try {
1354 $lineItems = $form->_lineItem = $membershipLineItems;
1355 if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
1356 unset($membershipParams['is_recur']);
1357 }
1358 $membershipContribution = self::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
1359 }
1360 catch (CRM_Core_Exception $e) {
1361 $errors[2] = $e->getMessage();
1362 $membershipContribution = NULL;
1363 }
1364 }
1365
1366 $membership = NULL;
1367 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1368 $membershipContributionID = $membershipContribution->id;
1369 }
1370
1371 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1372 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1373 $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1374 }
1375 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1376 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1377 $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
1378 foreach ($membershipTypeIDs as $memType) {
1379 $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
1380 $createdMemberships[$memType] = self::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
1381 }
1382 if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
1383 foreach ($form->_lineItem[$form->_priceSetId] as & $priceFieldOp) {
1384 if (!empty($priceFieldOp['membership_type_id']) &&
1385 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1386 ) {
1387 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1388 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
1389 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
1390 }
1391 else {
1392 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1393 }
1394 }
1395 $form->_values['lineItem'] = $form->_lineItem;
1396 $form->assign('lineItem', $form->_lineItem);
1397 }
1398 }
1399
1400 if (!empty($errors)) {
1401 $message = self::compileErrorMessage($errors);
1402 throw new CRM_Core_Exception($message);
1403 }
1404 $form->_params['createdMembershipIDs'] = array();
1405
1406 // CRM-7851 - Moved after processing Payment Errors
1407 //@todo - the reasoning for this being here seems a little outdated
1408 foreach ($createdMemberships as $createdMembership) {
1409 CRM_Core_BAO_CustomValueTable::postProcess(
1410 $form->_params,
1411 'civicrm_membership',
1412 $createdMembership->id,
1413 'Membership'
1414 );
1415 $form->_params['createdMembershipIDs'][] = $createdMembership->id;
1416 }
1417 if (count($createdMemberships) == 1) {
1418 //presumably this is only relevant for exactly 1 membership
1419 $form->_params['membershipID'] = $createdMembership->id;
1420 }
1421
1422 //CRM-15232: Check if membership is created and on the basis of it use
1423 //membership receipt template to send payment receipt
1424 if (count($createdMemberships)) {
1425 $form->_values['isMembership'] = TRUE;
1426 }
1427 if ($form->_contributeMode == 'notify') {
1428 if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
1429 // call postProcess hook before leaving
1430 $form->postProcessHook();
1431 // this does not return
1432 $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
1433 $payment->doTransferCheckout($form->_params, 'contribute');
1434 }
1435 }
1436
1437 if (isset($membershipContributionID)) {
1438 $form->_values['contribution_id'] = $membershipContributionID;
1439 }
1440
1441 // Do not send an email if Recurring transaction is done via Direct Mode
1442 // Email will we sent when the IPN is received.
1443 if (!empty($form->_params['is_recur']) && $form->_contributeMode == 'direct') {
1444 if (!empty($membershipContribution->trxn_id)) {
1445 try {
1446 civicrm_api3('contribution', 'completetransaction', array(
1447 'id' => $membershipContribution->id,
1448 'trxn_id' => $membershipContribution->trxn_id,
1449 ));
1450 }
1451 catch (CiviCRM_API3_Exception $e) {
1452 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
1453 // so let's be gentle here
1454 CRM_Core_Error::debug_log_message('contribution ' . $membershipContribution->id . ' not completed with trxn_id ' . $membershipContribution->trxn_id . ' and message ' . $e->getMessage());
1455 }
1456 }
1457 return;
1458 }
1459
1460 //finally send an email receipt
1461 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
1462 $form->_values,
1463 $isTest, FALSE,
1464 $includeFieldTypes
1465 );
1466 }
1467
1468 /**
1469 * Function for updating a membership record's contribution_recur_id.
1470 *
1471 * @param CRM_Member_DAO_Membership $membership
1472 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1473 */
1474 static public function updateRecurMembership(CRM_Member_DAO_Membership $membership, CRM_Contribute_BAO_Contribution $contribution) {
1475
1476 if (empty($contribution->contribution_recur_id)) {
1477 return;
1478 }
1479
1480 $params = array(
1481 1 => array($contribution->contribution_recur_id, 'Integer'),
1482 2 => array($membership->id, 'Integer'),
1483 );
1484
1485 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1486 CRM_Core_DAO::executeQuery($sql, $params);
1487 }
1488
1489 /**
1490 * A wrapper for renewing memberships from a form.
1491 *
1492 * @deprecated
1493 * - including the form in the membership processing adds complexity
1494 * as the forms are being forced to pretend similarity
1495 * Try to call the renewMembership directly
1496 * @todo - this form method needs to have the interaction with the form layer removed from it
1497 * as a BAO function. Note that the api now supports membership renewals & it is not clear this function does anything
1498 * not done by the membership.create api (with a lot less unit tests)
1499 *
1500 * This method will renew / create the membership depending on
1501 * whether the given contact has a membership or not. And will add
1502 * the modified dates for membership and in the log table.
1503 *
1504 * @param int $contactID
1505 * Id of the contact.
1506 * @param int $membershipTypeID
1507 * Id of the new membership type.
1508 * @param bool $is_test
1509 * If this is test contribution or live contribution.
1510 * @param CRM_Core_Form $form
1511 * Form object.
1512 * @param null $changeToday
1513 * @param int $modifiedID
1514 * Individual contact id in case of On Behalf signup (CRM-4027 ).
1515 * @param null $customFieldsFormatted
1516 * @param int $numRenewTerms
1517 * How many membership terms are being added to end date (default is 1).
1518 * @param int $membershipID
1519 * Membership ID, this should always be passed in & optionality should be removed.
1520 *
1521 * @param bool $isPending
1522 * Is the transaction pending. We are working towards this ALWAYS being true and completion being done
1523 * in the complete transaction function, called by all types of payment processor (removing assumptions
1524 * about what they do & always doing a pending + a complete at the appropriate time).
1525 *
1526 * @return CRM_Member_BAO_Membership|CRM_Core_Error
1527 */
1528 public static function renewMembershipFormWrapper(
1529 $contactID,
1530 $membershipTypeID,
1531 $is_test,
1532 &$form,
1533 $changeToday,
1534 $modifiedID,
1535 $customFieldsFormatted,
1536 $numRenewTerms,
1537 $membershipID,
1538 $isPending
1539 ) {
1540 $statusFormat = '%Y-%m-%d';
1541 $format = '%Y%m%d';
1542 $ids = array();
1543 //@todo would be better to make $membershipID a compulsory function param & make form layer responsible for extracting it
1544 if (!$membershipID && isset($form->_membershipId)) {
1545 $membershipID = $form->_membershipId;
1546 }
1547
1548 //get all active statuses of membership.
1549 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1550
1551 $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID);
1552
1553 // check is it pending. - CRM-4555
1554 list($contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId) = self::extractFormValues($form, $changeToday);
1555 list($membership, $renewalMode, $dates) = self::renewMembership($contactID, $membershipTypeID, $is_test,
1556 $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $isPending, $allStatus,
1557 $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId);
1558 $form->set('renewal_mode', $renewalMode);
1559 if (!empty($dates)) {
1560 $form->assign('mem_start_date',
1561 CRM_Utils_Date::customFormat($dates['start_date'], $format)
1562 );
1563 $form->assign('mem_end_date',
1564 CRM_Utils_Date::customFormat($dates['end_date'], $format)
1565 );
1566 }
1567 return $membership;
1568
1569 }
1570
1571 /**
1572 * Method to fix membership status of stale membership.
1573 *
1574 * This method first checks if the membership is stale. If it is,
1575 * then status will be updated based on existing start and end
1576 * dates and log will be added for the status change.
1577 *
1578 * @param array $currentMembership
1579 * Reference to the array.
1580 * containing all values of
1581 * the current membership
1582 * @param array $changeToday
1583 * Array of month, day, year.
1584 * values in case today needs
1585 * to be customised, null otherwise
1586 */
1587 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1588 $today = NULL;
1589 if ($changeToday) {
1590 $today = CRM_Utils_Date::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1591 }
1592
1593 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(
1594 CRM_Utils_Array::value('start_date', $currentMembership),
1595 CRM_Utils_Array::value('end_date', $currentMembership),
1596 CRM_Utils_Array::value('join_date', $currentMembership),
1597 $today,
1598 TRUE,
1599 $currentMembership['membership_type_id'],
1600 $currentMembership
1601 );
1602
1603 if (empty($status) ||
1604 empty($status['id'])
1605 ) {
1606 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.'));
1607 }
1608
1609 $currentMembership['today_date'] = $today;
1610
1611 if ($status['id'] !== $currentMembership['status_id']) {
1612 $memberDAO = new CRM_Member_DAO_Membership();
1613 $memberDAO->id = $currentMembership['id'];
1614 $memberDAO->find(TRUE);
1615
1616 $memberDAO->status_id = $status['id'];
1617 $memberDAO->join_date = CRM_Utils_Date::isoToMysql($memberDAO->join_date);
1618 $memberDAO->start_date = CRM_Utils_Date::isoToMysql($memberDAO->start_date);
1619 $memberDAO->end_date = CRM_Utils_Date::isoToMysql($memberDAO->end_date);
1620 $memberDAO->save();
1621 CRM_Core_DAO::storeValues($memberDAO, $currentMembership);
1622 $memberDAO->free();
1623
1624 $currentMembership['is_current_member'] = CRM_Core_DAO::getFieldValue(
1625 'CRM_Member_DAO_MembershipStatus',
1626 $currentMembership['status_id'],
1627 'is_current_member'
1628 );
1629 $format = '%Y%m%d';
1630
1631 $logParams = array(
1632 'membership_id' => $currentMembership['id'],
1633 'status_id' => $status['id'],
1634 'start_date' => CRM_Utils_Date::customFormat(
1635 $currentMembership['start_date'],
1636 $format
1637 ),
1638 'end_date' => CRM_Utils_Date::customFormat(
1639 $currentMembership['end_date'],
1640 $format
1641 ),
1642 'modified_date' => CRM_Utils_Date::customFormat(
1643 $currentMembership['today_date'],
1644 $format
1645 ),
1646 'membership_type_id' => $currentMembership['membership_type_id'],
1647 'max_related' => CRM_Utils_Array::value('max_related', $currentMembership, 0),
1648 );
1649
1650 $session = CRM_Core_Session::singleton();
1651 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1652 if ($session->get('userID')) {
1653 $logParams['modified_id'] = $session->get('userID');
1654 }
1655 else {
1656 $logParams['modified_id'] = $currentMembership['contact_id'];
1657 }
1658 CRM_Member_BAO_MembershipLog::add($logParams, CRM_Core_DAO::$_nullArray);
1659 }
1660 }
1661
1662 /**
1663 * Get the contribution page id from the membership record.
1664 *
1665 * @param int $membershipID
1666 *
1667 * @return int
1668 * contribution page id
1669 */
1670 public static function getContributionPageId($membershipID) {
1671 $query = "
1672 SELECT c.contribution_page_id as pageID
1673 FROM civicrm_membership_payment mp, civicrm_contribution c
1674 WHERE mp.contribution_id = c.id
1675 AND c.contribution_page_id IS NOT NULL
1676 AND mp.membership_id = " . CRM_Utils_Type::escape($membershipID, 'Integer')
1677 . " ORDER BY mp.id DESC";
1678
1679 return CRM_Core_DAO::singleValueQuery($query,
1680 CRM_Core_DAO::$_nullArray
1681 );
1682 }
1683
1684 /**
1685 * Updated related memberships.
1686 *
1687 * @param int $ownerMembershipId
1688 * Owner Membership Id.
1689 * @param array $params
1690 * Formatted array of key => value.
1691 */
1692 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1693 $membership = new CRM_Member_DAO_Membership();
1694 $membership->owner_membership_id = $ownerMembershipId;
1695 $membership->find();
1696
1697 while ($membership->fetch()) {
1698 $relatedMembership = new CRM_Member_DAO_Membership();
1699 $relatedMembership->id = $membership->id;
1700 $relatedMembership->copyValues($params);
1701 $relatedMembership->save();
1702 $relatedMembership->free();
1703 }
1704
1705 $membership->free();
1706 }
1707
1708 /**
1709 * Get list of membership fields for profile.
1710 *
1711 * For now we only allow custom membership fields to be in
1712 * profile
1713 *
1714 * @param null $mode
1715 * FIXME: This param is ignored
1716 *
1717 * @return array
1718 * the list of membership fields
1719 */
1720 public static function getMembershipFields($mode = NULL) {
1721 $fields = CRM_Member_DAO_Membership::export();
1722
1723 unset($fields['membership_contact_id']);
1724 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
1725
1726 $membershipType = CRM_Member_DAO_MembershipType::export();
1727
1728 $membershipStatus = CRM_Member_DAO_MembershipStatus::export();
1729
1730 $fields = array_merge($fields, $membershipType, $membershipStatus);
1731
1732 return $fields;
1733 }
1734
1735 /**
1736 * Get the sort name of a contact for a particular membership.
1737 *
1738 * @param int $id
1739 * Id of the membership.
1740 *
1741 * @return null|string
1742 * sort name of the contact if found
1743 */
1744 public static function sortName($id) {
1745 $id = CRM_Utils_Type::escape($id, 'Integer');
1746
1747 $query = "
1748 SELECT civicrm_contact.sort_name
1749 FROM civicrm_membership, civicrm_contact
1750 WHERE civicrm_membership.contact_id = civicrm_contact.id
1751 AND civicrm_membership.id = {$id}
1752 ";
1753 return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray);
1754 }
1755
1756 /**
1757 * Create memberships for related contacts, taking into account the maximum related memberships.
1758 *
1759 * @param array $params
1760 * Array of key - value pairs.
1761 * @param CRM_Core_DAO $dao
1762 * Membership object.
1763 *
1764 * @return null|array
1765 * array of memberships if created
1766 */
1767 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1768 static $relatedContactIds = array();
1769 if ($reset) {
1770 // not sure why a static var is in use here - we need a way to reset it from the test suite
1771 $relatedContactIds = array();
1772 return FALSE;
1773 }
1774
1775 $membership = new CRM_Member_DAO_Membership();
1776 $membership->id = $dao->id;
1777
1778 // required since create method doesn't return all the
1779 // parameters in the returned membership object
1780 if (!$membership->find(TRUE)) {
1781 return;
1782 }
1783 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
1784 // FIXME : While updating/ renewing the
1785 // membership, if the relationship is PAST then
1786 // the membership of the related contact must be
1787 // expired.
1788 // For that, getting Membership Status for which
1789 // is_current_member is 0. It works for the
1790 // generated data as there is only one membership
1791 // status having is_current_member = 0.
1792 // But this wont work exactly if there will be
1793 // more than one status having is_current_member = 0.
1794 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1795 $membershipStatus->is_current_member = 0;
1796 if ($membershipStatus->find(TRUE)) {
1797 $expiredStatusId = $membershipStatus->id;
1798 }
1799 else {
1800 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant::membershipStatus());
1801 }
1802
1803 $allRelatedContacts = array();
1804 $relatedContacts = array();
1805 if (!is_a($membership, 'CRM_Core_Error')) {
1806 $allRelatedContacts = CRM_Member_BAO_Membership::checkMembershipRelationship($membership->id,
1807 $membership->contact_id,
1808 CRM_Utils_Array::value('action', $params)
1809 );
1810 }
1811
1812 // check for loops. CRM-4213
1813 // remove repeated related contacts, which already inherited membership.
1814 $relatedContactIds[$membership->contact_id] = TRUE;
1815 foreach ($allRelatedContacts as $cid => $status) {
1816 if (empty($relatedContactIds[$cid])) {
1817 $relatedContactIds[$cid] = TRUE;
1818
1819 //don't create membership again for owner contact.
1820 $nestedRelationship = FALSE;
1821 if ($membership->owner_membership_id) {
1822 $nestedRelMembership = new CRM_Member_DAO_Membership();
1823 $nestedRelMembership->id = $membership->owner_membership_id;
1824 $nestedRelMembership->contact_id = $cid;
1825 $nestedRelationship = $nestedRelMembership->find(TRUE);
1826 $nestedRelMembership->free();
1827 }
1828 if (!$nestedRelationship) {
1829 $relatedContacts[$cid] = $status;
1830 }
1831 }
1832 }
1833
1834 //lets cleanup related membership if any.
1835 if (empty($relatedContacts)) {
1836 self::deleteRelatedMemberships($membership->id);
1837 }
1838 else {
1839 // Edit the params array
1840 unset($params['id']);
1841 // Reminder should be sent only to the direct membership
1842 unset($params['reminder_date']);
1843 // unset the custom value ids
1844 if (is_array(CRM_Utils_Array::value('custom', $params))) {
1845 foreach ($params['custom'] as $k => $v) {
1846 unset($params['custom'][$k]['id']);
1847 }
1848 }
1849 if (!isset($params['membership_type_id'])) {
1850 $params['membership_type_id'] = $membership->membership_type_id;
1851 }
1852
1853 // max_related should be set in the parent membership
1854 unset($params['max_related']);
1855 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1856 $available = ($membership->max_related == NULL ? PHP_INT_MAX : $membership->max_related);
1857 // will be used to queue potential memberships to be created.
1858 $queue = array();
1859
1860 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1861 //use existing membership record.
1862 $relMembership = new CRM_Member_DAO_Membership();
1863 $relMembership->contact_id = $contactId;
1864 $relMembership->owner_membership_id = $membership->id;
1865 $relMemIds = array();
1866 if ($relMembership->find(TRUE)) {
1867 $params['id'] = $relMemIds['membership'] = $relMembership->id;
1868 }
1869 $params['contact_id'] = $contactId;
1870 $params['owner_membership_id'] = $membership->id;
1871
1872 // set status_id as it might have been changed for
1873 // past relationship
1874 $params['status_id'] = $membership->status_id;
1875
1876 if ($deceasedStatusId &&
1877 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1878 ) {
1879 $params['status_id'] = $deceasedStatusId;
1880 }
1881 elseif ((CRM_Utils_Array::value('action', $params) & CRM_Core_Action::UPDATE) &&
1882 ($relationshipStatus == CRM_Contact_BAO_Relationship::PAST)
1883 ) {
1884 $params['status_id'] = $expiredStatusId;
1885 }
1886
1887 //don't calculate status again in create( );
1888 $params['skipStatusCal'] = TRUE;
1889
1890 //do create activity if we changed status.
1891 if ($params['status_id'] != $relMembership->status_id) {
1892 $params['createActivity'] = TRUE;
1893 }
1894
1895 // we should not created contribution record for related contacts, CRM-3371
1896 unset($params['contribution_status_id']);
1897
1898 if (($params['status_id'] == $deceasedStatusId) || ($params['status_id'] == $expiredStatusId)) {
1899 // related membership is not active so does not count towards maximum
1900 CRM_Member_BAO_Membership::create($params, $relMemIds);
1901 }
1902 else {
1903 // related membership already exists, so this is just an update
1904 if (isset($params['id'])) {
1905 if ($available > 0) {
1906 CRM_Member_BAO_Membership::create($params, $relMemIds);
1907 $available--;
1908 }
1909 else {
1910 // we have run out of inherited memberships, so delete extras
1911 self::deleteMembership($params['id']);
1912 }
1913 // we need to first check if there will remain inherited memberships, so queue it up
1914 }
1915 else {
1916 $queue[] = $params;
1917 }
1918 }
1919 }
1920 // now go over the queue and create any available related memberships
1921 reset($queue);
1922 while (($available > 0) && ($params = each($queue))) {
1923 CRM_Member_BAO_Membership::create($params['value'], $relMemIds);
1924 $available--;
1925 }
1926 }
1927 }
1928
1929 /**
1930 * Delete the record that are associated with this Membership Payment.
1931 *
1932 * @param int $membershipId
1933 *
1934 * @return object
1935 * $membershipPayment deleted membership payment object
1936 */
1937 public static function deleteMembershipPayment($membershipId) {
1938
1939 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1940 $membershipPayment->membership_id = $membershipId;
1941 $membershipPayment->find();
1942
1943 while ($membershipPayment->fetch()) {
1944 CRM_Contribute_BAO_Contribution::deleteContribution($membershipPayment->contribution_id);
1945 CRM_Utils_Hook::pre('delete', 'MembershipPayment', $membershipPayment->id, $membershipPayment);
1946 $membershipPayment->delete();
1947 CRM_Utils_Hook::post('delete', 'MembershipPayment', $membershipPayment->id, $membershipPayment);
1948 }
1949 return $membershipPayment;
1950 }
1951
1952 /**
1953 * @param CRM_Core_Form $form
1954 * @param int $membershipTypeID
1955 *
1956 * @return array
1957 */
1958 public static function &buildMembershipTypeValues(&$form, $membershipTypeID = NULL) {
1959 $whereClause = " WHERE domain_id = " . CRM_Core_Config::domainID();
1960
1961 if (is_array($membershipTypeID)) {
1962 $allIDs = implode(',', $membershipTypeID);
1963 $whereClause .= " AND id IN ( $allIDs )";
1964 }
1965 elseif (is_numeric($membershipTypeID) &&
1966 $membershipTypeID > 0
1967 ) {
1968 $whereClause .= " AND id = $membershipTypeID";
1969 }
1970
1971 $query = "
1972 SELECT *
1973 FROM civicrm_membership_type
1974 $whereClause;
1975 ";
1976 $dao = CRM_Core_DAO::executeQuery($query);
1977
1978 $membershipTypeValues = array();
1979 $membershipTypeFields = array(
1980 'id',
1981 'minimum_fee',
1982 'name',
1983 'is_active',
1984 'description',
1985 'financial_type_id',
1986 'auto_renew',
1987 'member_of_contact_id',
1988 'relationship_type_id',
1989 'relationship_direction',
1990 'max_related',
1991 );
1992
1993 while ($dao->fetch()) {
1994 $membershipTypeValues[$dao->id] = array();
1995 foreach ($membershipTypeFields as $mtField) {
1996 $membershipTypeValues[$dao->id][$mtField] = $dao->$mtField;
1997 }
1998 }
1999 $dao->free();
2000
2001 CRM_Utils_Hook::membershipTypeValues($form, $membershipTypeValues);
2002
2003 if (is_numeric($membershipTypeID) &&
2004 $membershipTypeID > 0
2005 ) {
2006 return $membershipTypeValues[$membershipTypeID];
2007 }
2008 else {
2009 return $membershipTypeValues;
2010 }
2011 }
2012
2013 /**
2014 * Get membership record count for a Contact.
2015 *
2016 * @param int $contactID
2017 * @param bool $activeOnly
2018 *
2019 * @return null|string
2020 */
2021 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
2022 $select = "SELECT count(*) FROM civicrm_membership ";
2023 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
2024
2025 // CRM-6627, all status below 3 (active, pending, grace) are considered active
2026 if ($activeOnly) {
2027 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
2028 $where .= " and civicrm_membership_status.is_current_member = 1";
2029 }
2030
2031 $query = $select . $where;
2032 return CRM_Core_DAO::singleValueQuery($query);
2033 }
2034
2035 /**
2036 * Check whether payment processor supports cancellation of membership subscription.
2037 *
2038 * @param int $mid
2039 * Membership id.
2040 *
2041 * @param bool $isNotCancelled
2042 *
2043 * @return bool
2044 */
2045 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
2046 $cacheKeyString = "$mid";
2047 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2048
2049 static $supportsCancel = array();
2050
2051 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2052 $supportsCancel[$cacheKeyString] = FALSE;
2053 $isCancelled = FALSE;
2054
2055 if ($isNotCancelled) {
2056 $isCancelled = self::isSubscriptionCancelled($mid);
2057 }
2058
2059 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($mid, 'membership', 'obj');
2060 if (!empty($paymentObject)) {
2061 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2062 }
2063 }
2064 return $supportsCancel[$cacheKeyString];
2065 }
2066
2067 /**
2068 * Check whether subscription is already cancelled.
2069 *
2070 * @param int $mid
2071 * Membership id.
2072 *
2073 * @return string
2074 * contribution status
2075 */
2076 public static function isSubscriptionCancelled($mid) {
2077 $sql = "
2078 SELECT cr.contribution_status_id
2079 FROM civicrm_contribution_recur cr
2080 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
2081 WHERE mem.id = %1 LIMIT 1";
2082 $params = array(1 => array($mid, 'Integer'));
2083 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
2084 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name');
2085 if ($status == 'Cancelled') {
2086 return TRUE;
2087 }
2088 return FALSE;
2089 }
2090
2091 /**
2092 * Get membership joins for a specified membership type.
2093 *
2094 * Specifically, retrieves a count of still current memberships whose
2095 * join_date and start_date are within a specified date range. Dates match
2096 * the pattern "yyyy-mm-dd".
2097 *
2098 * @param int $membershipTypeId
2099 * Membership type id.
2100 * @param int $startDate
2101 * Date on which to start counting.
2102 * @param int $endDate
2103 * Date on which to end counting.
2104 * @param bool|int $isTest if true, membership is for a test site
2105 *
2106 * @return int
2107 * the number of members of type $membershipTypeId
2108 * whose join_date is between $startDate and $endDate and
2109 * whose start_date is between $startDate and $endDate
2110 */
2111 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2112 $testClause = 'membership.is_test = 1';
2113 if (!$isTest) {
2114 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2115 }
2116 if (!self::$_signupActType) {
2117 self::_getActTypes();
2118 }
2119
2120 if (!self::$_signupActType) {
2121 return 0;
2122 }
2123
2124 $query = "
2125 SELECT COUNT(DISTINCT membership.id) as member_count
2126 FROM civicrm_membership membership
2127 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2128 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2129 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2130 WHERE membership.membership_type_id = %2
2131 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2132 AND {$testClause}";
2133
2134 $params = array(
2135 1 => array(self::$_signupActType, 'Integer'),
2136 2 => array($membershipTypeId, 'Integer'),
2137 );
2138
2139 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
2140
2141 return (int) $memberCount;
2142 }
2143
2144 /**
2145 * Get membership renewals for a specified membership type.
2146 *
2147 * Specifically, retrieves a count of still current memberships
2148 * whose join_date is before and start_date is within a specified date
2149 * range. Dates match the pattern "yyyy-mm-dd".
2150 *
2151 * @param int $membershipTypeId
2152 * Membership type id.
2153 * @param int $startDate
2154 * Date on which to start counting.
2155 * @param int $endDate
2156 * Date on which to end counting.
2157 * @param bool|int $isTest if true, membership is for a test site
2158 *
2159 * @return int
2160 * returns the number of members of type $membershipTypeId
2161 * whose join_date is before $startDate and
2162 * whose start_date is between $startDate and $endDate
2163 */
2164 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2165 $testClause = 'membership.is_test = 1';
2166 if (!$isTest) {
2167 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2168 }
2169 if (!self::$_renewalActType) {
2170 self::_getActTypes();
2171 }
2172
2173 if (!self::$_renewalActType) {
2174 return 0;
2175 }
2176
2177 $query = "
2178 SELECT COUNT(DISTINCT membership.id) as member_count
2179 FROM civicrm_membership membership
2180 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2181 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2182 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2183 WHERE membership.membership_type_id = %2
2184 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2185 AND {$testClause}";
2186
2187 $params = array(
2188 1 => array(self::$_renewalActType, 'Integer'),
2189 2 => array($membershipTypeId, 'Integer'),
2190 );
2191 $memberCount = CRM_Core_DAO::singleValueQuery($query, $params);
2192
2193 return (int) $memberCount;
2194 }
2195
2196 /**
2197 * Where a second separate financial transaction is supported we will process it here.
2198 *
2199 * @param int $contactID
2200 * @param CRM_Contribute_Form_Contribution_Confirm $form
2201 * @param array $tempParams
2202 * @param bool $isTest
2203 * @param array $lineItems
2204 * @param $minimumFee
2205 * @param int $financialTypeID
2206 *
2207 * @throws CRM_Core_Exception
2208 * @throws Exception
2209 * @return CRM_Contribute_BAO_Contribution
2210 */
2211 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID) {
2212 $financialType = new CRM_Financial_DAO_FinancialType();
2213 $financialType->id = $financialTypeID;
2214 if (!$financialType->find(TRUE)) {
2215 CRM_Core_Error::fatal(ts("Could not find a system table"));
2216 }
2217 $tempParams['amount'] = $minimumFee;
2218 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
2219
2220 $result = NULL;
2221 if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
2222 $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
2223
2224 if ($form->_contributeMode == 'express') {
2225 $result = $payment->doExpressCheckout($tempParams);
2226 if (is_a($result, 'CRM_Core_Error')) {
2227 throw new CRM_Core_Exception(CRM_Core_Error::getMessages($result));
2228 }
2229 }
2230 else {
2231 $result = $payment->doPayment($tempParams, 'contribute');
2232 }
2233 }
2234
2235 //assign receive date when separate membership payment
2236 //and contribution amount not selected.
2237 if ($form->_amount == 0) {
2238 $now = date('YmdHis');
2239 $form->_params['receive_date'] = $now;
2240 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
2241 $form->set('params', $form->_params);
2242 $form->assign('receive_date', $receiveDate);
2243 }
2244
2245 $form->set('membership_trx_id', $result['trxn_id']);
2246 $form->set('membership_amount', $minimumFee);
2247
2248 $form->assign('membership_trx_id', $result['trxn_id']);
2249 $form->assign('membership_amount', $minimumFee);
2250
2251 // we don't need to create the user twice, so lets disable cms_create_account
2252 // irrespective of the value, CRM-2888
2253 $tempParams['cms_create_account'] = 0;
2254
2255 //CRM-16165, scenarios are
2256 // 1) If contribution is_pay_later and if contribution amount is > 0.0 we set pending = TRUE, vice-versa FALSE
2257 // 2) If not pay later but auto-renewal membership is chosen then pending = TRUE as it later triggers
2258 // pending recurring contribution, vice-versa FALSE
2259 $pending = $form->_params['is_pay_later'] ? (($minimumFee > 0.0) ? TRUE : FALSE) : (!empty($form->_params['auto_renew']) ? TRUE : FALSE);
2260
2261 //set this variable as we are not creating pledge for
2262 //separate membership payment contribution.
2263 //so for differentiating membership contribution from
2264 //main contribution.
2265 $form->_params['separate_membership_payment'] = 1;
2266 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form,
2267 $tempParams,
2268 $result,
2269 $contactID,
2270 $financialType,
2271 $pending,
2272 TRUE,
2273 $isTest,
2274 $lineItems,
2275 $form->_bltID
2276 );
2277 return $membershipContribution;
2278 }
2279
2280 /**
2281 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
2282 * refactoring step. This should be BAO functionality
2283 * @param $membership
2284 * @param $membershipContribution
2285 */
2286 public static function linkMembershipPayment($membership, $membershipContribution) {
2287 CRM_Member_BAO_MembershipPayment::create(array(
2288 'membership_id' => $membership->id,
2289 'contribution_id' => $membershipContribution->id,
2290 ));
2291 }
2292
2293 /**
2294 * @param array $membershipParams
2295 * @param int $contactID
2296 * @param $customFieldsFormatted
2297 * @param int $membershipID
2298 * @param $memType
2299 * @param bool $isTest
2300 * @param int $numTerms
2301 * @param $membershipContribution
2302 * @param CRM_Core_Form $form
2303 *
2304 * @return array
2305 */
2306 public static function createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, &$form) {
2307 $membership = self::renewMembershipFormWrapper($contactID, $memType,
2308 $isTest, $form, NULL,
2309 CRM_Utils_Array::value('cms_contactID', $membershipParams),
2310 $customFieldsFormatted, $numTerms,
2311 $membershipID,
2312 self::extractPendingFormValue($form, $memType)
2313 );
2314
2315 if (!empty($membershipContribution)) {
2316 // update recurring id for membership record
2317 self::updateRecurMembership($membership, $membershipContribution);
2318
2319 self::linkMembershipPayment($membership, $membershipContribution);
2320 }
2321 return $membership;
2322 }
2323
2324 /**
2325 * Turn array of errors into message string.
2326 *
2327 * @param array $errors
2328 *
2329 * @return string
2330 */
2331 public static function compileErrorMessage($errors) {
2332 foreach ($errors as $error) {
2333 if (is_string($error)) {
2334 $message[] = $error;
2335 }
2336 }
2337 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
2338 }
2339
2340 /**
2341 * Determine if the form has a pending status.
2342 *
2343 * This is an interim refactoring step. This information should be extracted at the form layer.
2344 *
2345 * @deprecated
2346 *
2347 * @param CRM_Core_Form $form
2348 * @param int $membershipID
2349 *
2350 * @return bool
2351 */
2352 public static function extractPendingFormValue($form, $membershipID) {
2353 $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipID);
2354 $pending = FALSE;
2355 //@todo this is a BAO function & should not inspect the form - the form should do this
2356 // & pass required params to the BAO
2357 if (CRM_Utils_Array::value('minimum_fee', $membershipTypeDetails) > 0.0) {
2358 if (((isset($form->_contributeMode) && $form->_contributeMode == 'notify') || !empty($form->_params['is_pay_later'])
2359 ) &&
2360 (($form->_values['is_monetary'] && $form->_amount > 0.0) ||
2361 CRM_Utils_Array::value('record_contribution', $form->_params)
2362 )
2363 ) {
2364 $pending = TRUE;
2365 }
2366 }
2367 return $pending;
2368 }
2369
2370 /**
2371 * Extract relevant values from the form so we can separate form logic from BAO logcis.
2372 *
2373 * @param CRM_Core_Form $form
2374 * @param $changeToday
2375 *
2376 * @return array
2377 */
2378 public static function extractFormValues($form, $changeToday) {
2379 $contributionRecurID = isset($form->_params['contributionRecurID']) ? $form->_params['contributionRecurID'] : NULL;
2380
2381 //we renew expired membership, CRM-6277
2382 if (!$changeToday) {
2383 if ($form->get('renewalDate')) {
2384 $changeToday = $form->get('renewalDate');
2385 }
2386 elseif (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') {
2387 $changeToday = date('YmdHis');
2388 }
2389 }
2390
2391 $membershipSource = NULL;
2392 if (!empty($form->_params['membership_source'])) {
2393 $membershipSource = $form->_params['membership_source'];
2394 }
2395 elseif (isset($form->_values['title']) && !empty($form->_values['title'])) {
2396 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values['title'];
2397 }
2398 $isPayLater = NULL;
2399 if (isset($form->_params)) {
2400 $isPayLater = CRM_Utils_Array::value('is_pay_later', $form->_params);
2401 }
2402 $campaignId = NULL;
2403 if (isset($form->_values) && is_array($form->_values) && !empty($form->_values)) {
2404 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_params);
2405 if (!array_key_exists('campaign_id', $form->_params)) {
2406 $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
2407 }
2408 }
2409 return array($contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId);
2410 }
2411
2412 /**
2413 * @param int $contactID
2414 * @param int $membershipTypeID
2415 * @param bool $is_test
2416 * @param $changeToday
2417 * @param int $modifiedID
2418 * @param $customFieldsFormatted
2419 * @param $numRenewTerms
2420 * @param int $membershipID
2421 * @param $pending
2422 * @param $allStatus
2423 * @param array $membershipTypeDetails
2424 * @param int $contributionRecurID
2425 * @param $format
2426 * @param $membershipSource
2427 * @param $ids
2428 * @param $statusFormat
2429 * @param $isPayLater
2430 * @param int $campaignId
2431 *
2432 * @throws CRM_Core_Exception
2433 * @return array
2434 */
2435 public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId) {
2436 $renewalMode = $updateStatusId = FALSE;
2437 $dates = array();
2438 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2439 // is the same as the parent org of an existing membership of the contact
2440 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID,
2441 $is_test, $membershipID, TRUE
2442 );
2443 if ($currentMembership) {
2444 $activityType = 'Membership Renewal';
2445 $renewalMode = TRUE;
2446
2447 // Do NOT do anything.
2448 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2449 //2. Paylater/IPN renew. CRM-4556.
2450 if ($pending || in_array($currentMembership['status_id'], array(
2451 array_search('Pending', $allStatus),
2452 // CRM-15475
2453 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2454 ))
2455 ) {
2456 $membership = new CRM_Member_DAO_Membership();
2457 $membership->id = $currentMembership['id'];
2458 $membership->find(TRUE);
2459
2460 // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed
2461 $format = '%Y%m%d';
2462 // note that we are logging the requested new membership_type_id that may be different than current membership_type_id
2463 // it will be used when payment is received to update the membership_type_id to what was paid for
2464 $logParams = array(
2465 'membership_id' => $membership->id,
2466 'status_id' => $membership->status_id,
2467 'start_date' => CRM_Utils_Date::customFormat(
2468 $membership->start_date,
2469 $format
2470 ),
2471 'end_date' => CRM_Utils_Date::customFormat(
2472 $membership->end_date,
2473 $format
2474 ),
2475 'modified_date' => CRM_Utils_Date::customFormat(
2476 date('Ymd'),
2477 $format
2478 ),
2479 'membership_type_id' => $membershipTypeID,
2480 'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL,
2481 );
2482 $session = CRM_Core_Session::singleton();
2483 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
2484 if ($session->get('userID')) {
2485 $logParams['modified_id'] = $session->get('userID');
2486 }
2487 else {
2488 $logParams['modified_id'] = $membership->contact_id;
2489 }
2490 CRM_Member_BAO_MembershipLog::add($logParams, CRM_Core_DAO::$_nullArray);
2491
2492 if (!empty($contributionRecurID)) {
2493 CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $membership->id,
2494 'contribution_recur_id', $contributionRecurID
2495 );
2496 }
2497
2498 return array($membership, $renewalMode, $dates);
2499 }
2500
2501 // Check and fix the membership if it is STALE
2502 self::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2503
2504 // Now Renew the membership
2505 if (!$currentMembership['is_current_member']) {
2506 // membership is not CURRENT
2507
2508 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2509 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
2510 $changeToday,
2511 $membershipTypeID,
2512 $numRenewTerms
2513 );
2514
2515 $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
2516 $currentMembership['start_date'] = CRM_Utils_Array::value('start_date', $dates);
2517 $currentMembership['end_date'] = CRM_Utils_Array::value('end_date', $dates);
2518 $currentMembership['is_test'] = $is_test;
2519
2520 if (!empty($membershipSource)) {
2521 $currentMembership['source'] = $membershipSource;
2522 }
2523 else {
2524 $currentMembership['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
2525 $currentMembership['id'],
2526 'source'
2527 );
2528 }
2529
2530 if (!empty($currentMembership['id'])) {
2531 $ids['membership'] = $currentMembership['id'];
2532 }
2533 $memParams = $currentMembership;
2534 $memParams['membership_type_id'] = $membershipTypeID;
2535
2536 //set the log start date.
2537 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
2538 }
2539 else {
2540
2541 // CURRENT Membership
2542 $membership = new CRM_Member_DAO_Membership();
2543 $membership->id = $currentMembership['id'];
2544 $membership->find(TRUE);
2545 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2546 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
2547 $changeToday,
2548 $membershipTypeID,
2549 $numRenewTerms
2550 );
2551
2552 // Insert renewed dates for CURRENT membership
2553 $memParams = array();
2554 $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date);
2555 $memParams['start_date'] = CRM_Utils_Date::isoToMysql($membership->start_date);
2556 $memParams['end_date'] = CRM_Utils_Array::value('end_date', $dates);
2557 $memParams['membership_type_id'] = $membershipTypeID;
2558
2559 //set the log start date.
2560 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
2561 if (empty($membership->source)) {
2562 if (!empty($membershipSource)) {
2563 $memParams['source'] = $membershipSource;
2564 }
2565 else {
2566 $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
2567 $currentMembership['id'],
2568 'source'
2569 );
2570 }
2571 }
2572
2573 if (!empty($currentMembership['id'])) {
2574 $ids['membership'] = $currentMembership['id'];
2575 }
2576 }
2577 //CRM-4555
2578 if ($pending) {
2579 $updateStatusId = array_search('Pending', $allStatus);
2580 }
2581 }
2582 else {
2583 // NEW Membership
2584
2585 $activityType = 'Membership Signup';
2586 $memParams = array(
2587 'contact_id' => $contactID,
2588 'membership_type_id' => $membershipTypeID,
2589 );
2590
2591 if (!$pending) {
2592 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2593
2594 $memParams['join_date'] = CRM_Utils_Array::value('join_date', $dates);
2595 $memParams['start_date'] = CRM_Utils_Array::value('start_date', $dates);
2596 $memParams['end_date'] = CRM_Utils_Array::value('end_date', $dates);
2597
2598 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'],
2599 $statusFormat
2600 ),
2601 CRM_Utils_Date::customFormat($dates['end_date'],
2602 $statusFormat
2603 ),
2604 CRM_Utils_Date::customFormat($dates['join_date'],
2605 $statusFormat
2606 ),
2607 'today',
2608 TRUE,
2609 $membershipTypeID,
2610 $memParams
2611 );
2612 $updateStatusId = CRM_Utils_Array::value('id', $status);
2613 }
2614 else {
2615 // if IPN/Pay-Later set status to: PENDING
2616 $updateStatusId = array_search('Pending', $allStatus);
2617 }
2618
2619 if (!empty($membershipSource)) {
2620 $memParams['source'] = $membershipSource;
2621 }
2622 $memParams['contribution_recur_id'] = $contributionRecurID;
2623
2624 $memParams['is_test'] = $is_test;
2625 $memParams['is_pay_later'] = $isPayLater;
2626 }
2627
2628 //CRM-4555
2629 //if we decided status here and want to skip status
2630 //calculation in create( ); then need to pass 'skipStatusCal'.
2631 if ($updateStatusId) {
2632 $memParams['status_id'] = $updateStatusId;
2633 $memParams['skipStatusCal'] = TRUE;
2634 }
2635
2636 //since we are renewing,
2637 //make status override false.
2638 $memParams['is_override'] = FALSE;
2639
2640 //CRM-4027, create log w/ individual contact.
2641 if ($modifiedID) {
2642 $ids['userId'] = $modifiedID;
2643 $memParams['is_for_organization'] = TRUE;
2644 }
2645 else {
2646 $ids['userId'] = $contactID;
2647 }
2648
2649 //inherit campaign from contrib page.
2650 if (isset($campaignId)) {
2651 $memParams['campaign_id'] = $campaignId;
2652 }
2653
2654 $memParams['custom'] = $customFieldsFormatted;
2655 $membership = self::create($memParams, $ids, FALSE, $activityType);
2656
2657 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2658 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2659 $membership->find(TRUE);
2660
2661 return array($membership, $renewalMode, $dates);
2662 }
2663
2664 /**
2665 * Process price set and line items.
2666 *
2667 * @param int $membershipId
2668 * @param array $lineItem
2669 */
2670 public function processPriceSet($membershipId, $lineItem) {
2671 //FIXME : need to move this too
2672 if (!$membershipId || !is_array($lineItem)
2673 || CRM_Utils_System::isNull($lineItem)
2674 ) {
2675 return;
2676 }
2677
2678 foreach ($lineItem as $priceSetId => $values) {
2679 if (!$priceSetId) {
2680 continue;
2681 }
2682 foreach ($values as $line) {
2683 $line['entity_table'] = 'civicrm_membership';
2684 $line['entity_id'] = $membershipId;
2685 CRM_Price_BAO_LineItem::create($line);
2686 }
2687 }
2688 }
2689
2690 /**
2691 * Retrieve the contribution id for the associated Membership id.
2692 * @todo we should get this off the line item
2693 *
2694 * @param int $membershipId
2695 * Membership id.
2696 *
2697 * @return int
2698 * contribution id
2699 */
2700 public static function getMembershipContributionId($membershipId) {
2701
2702 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2703 $membershipPayment->membership_id = $membershipId;
2704 if ($membershipPayment->find(TRUE)) {
2705 return $membershipPayment->contribution_id;
2706 }
2707 return NULL;
2708 }
2709
2710 /**
2711 * The function checks and updates the status of all membership records for a given domain using the
2712 * calc_membership_status and update_contact_membership APIs.
2713 *
2714 * IMPORTANT:
2715 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2716 *
2717 * @return array
2718 */
2719 public static function updateAllMembershipStatus() {
2720
2721 //get all active statuses of membership, CRM-3984
2722 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
2723 $statusLabels = CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label');
2724 $allTypes = CRM_Member_PseudoConstant::membershipType();
2725
2726 // get only memberships with active membership types
2727 $query = "
2728 SELECT civicrm_membership.id as membership_id,
2729 civicrm_membership.is_override as is_override,
2730 civicrm_membership.membership_type_id as membership_type_id,
2731 civicrm_membership.status_id as status_id,
2732 civicrm_membership.join_date as join_date,
2733 civicrm_membership.start_date as start_date,
2734 civicrm_membership.end_date as end_date,
2735 civicrm_membership.source as source,
2736 civicrm_contact.id as contact_id,
2737 civicrm_contact.is_deceased as is_deceased,
2738 civicrm_membership.owner_membership_id as owner_membership_id,
2739 civicrm_membership.contribution_recur_id as recur_id
2740 FROM civicrm_membership
2741 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2742 INNER JOIN civicrm_membership_type ON
2743 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2744 WHERE civicrm_membership.is_test = 0";
2745
2746 $params = array();
2747 $dao = CRM_Core_DAO::executeQuery($query, $params);
2748
2749 $processCount = 0;
2750 $updateCount = 0;
2751
2752 $smarty = CRM_Core_Smarty::singleton();
2753
2754 while ($dao->fetch()) {
2755 // echo ".";
2756 $processCount++;
2757
2758 // Put common parameters into array for easy access
2759 $memberParams = array(
2760 'id' => $dao->membership_id,
2761 'status_id' => $dao->status_id,
2762 'contact_id' => $dao->contact_id,
2763 'membership_type_id' => $dao->membership_type_id,
2764 'membership_type' => $allTypes[$dao->membership_type_id],
2765 'join_date' => $dao->join_date,
2766 'start_date' => $dao->start_date,
2767 'end_date' => $dao->end_date,
2768 'source' => $dao->source,
2769 'skipStatusCal' => TRUE,
2770 'skipRecentView' => TRUE,
2771 );
2772
2773 $smarty->assign_by_ref('memberParams', $memberParams);
2774
2775 //update membership record to Deceased if contact is deceased
2776 if ($dao->is_deceased) {
2777 // check for 'Deceased' membership status, CRM-5636
2778 $deceaseStatusId = array_search('Deceased', $allStatus);
2779 if (!$deceaseStatusId) {
2780 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'))));
2781 }
2782
2783 //process only when status change.
2784 if ($dao->status_id != $deceaseStatusId) {
2785 //take all params that need to save.
2786 $deceasedMembership = $memberParams;
2787 $deceasedMembership['status_id'] = $deceaseStatusId;
2788 $deceasedMembership['createActivity'] = TRUE;
2789 $deceasedMembership['version'] = 3;
2790
2791 //since there is change in status.
2792 $statusChange = array('status_id' => $deceaseStatusId);
2793 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2794 unset(
2795 $deceasedMembership['contact_id'],
2796 $deceasedMembership['membership_type_id'],
2797 $deceasedMembership['membership_type'],
2798 $deceasedMembership['join_date'],
2799 $deceasedMembership['start_date'],
2800 $deceasedMembership['end_date'],
2801 $deceasedMembership['source']
2802 );
2803
2804 //process membership record.
2805 civicrm_api('membership', 'create', $deceasedMembership);
2806 }
2807 continue;
2808 }
2809
2810 //we fetch related, since we need to check for deceased
2811 //now further processing is handle w/ main membership record.
2812 if ($dao->owner_membership_id) {
2813 continue;
2814 }
2815
2816 //update membership records where status is NOT - Pending OR Cancelled.
2817 //as well as membership is not override.
2818 //skipping Expired membership records -> reduced extra processing( kiran )
2819 if (!$dao->is_override &&
2820 !in_array($dao->status_id, array(
2821 array_search('Pending', $allStatus),
2822 // CRM-15475
2823 array_search(
2824 'Cancelled',
2825 CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2826 ),
2827 array_search('Expired', $allStatus),
2828 ))
2829 ) {
2830
2831 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2832 //get the membership status as per id.
2833 $newStatus = civicrm_api('membership_status', 'calc',
2834 array(
2835 'membership_id' => $dao->membership_id,
2836 'version' => 3,
2837 'ignore_admin_only' => FALSE,
2838 ), TRUE
2839 );
2840 $statusId = CRM_Utils_Array::value('id', $newStatus);
2841
2842 //process only when status change.
2843 if ($statusId &&
2844 $statusId != $dao->status_id
2845 ) {
2846 //take all params that need to save.
2847 $memParams = $memberParams;
2848 $memParams['status_id'] = $statusId;
2849 $memParams['createActivity'] = TRUE;
2850 $memParams['version'] = 3;
2851
2852 // Unset columns which should remain unchanged from their current saved
2853 // values. This avoids race condition in which these values may have
2854 // been changed by other processes.
2855 unset(
2856 $memParams['contact_id'],
2857 $memParams['membership_type_id'],
2858 $memParams['membership_type'],
2859 $memParams['join_date'],
2860 $memParams['start_date'],
2861 $memParams['end_date'],
2862 $memParams['source']
2863 );
2864 //since there is change in status.
2865 $statusChange = array('status_id' => $statusId);
2866 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2867
2868 //process member record.
2869 civicrm_api('membership', 'create', $memParams);
2870 $updateCount++;
2871 }
2872 }
2873 }
2874 $result['is_error'] = 0;
2875 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2876 1 => $processCount,
2877 2 => $updateCount,
2878 ));
2879 return $result;
2880 }
2881
2882 /**
2883 * Returns the membership types for a particular contact
2884 * who has lifetime membership without end date.
2885 *
2886 * @param int $contactID
2887 * @param bool $isTest
2888 * @param bool $onlyLifeTime
2889 *
2890 * @return array
2891 */
2892 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2893 $contactMembershipType = array();
2894 if (!$contactID) {
2895 return $contactMembershipType;
2896 }
2897
2898 $dao = new CRM_Member_DAO_Membership();
2899 $dao->contact_id = $contactID;
2900 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant::membershipStatus());
2901 $dao->whereAdd("status_id != $pendingStatusId");
2902
2903 if ($isTest) {
2904 $dao->is_test = $isTest;
2905 }
2906 else {
2907 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2908 }
2909
2910 if ($onlyLifeTime) {
2911 $dao->whereAdd('end_date IS NULL');
2912 }
2913
2914 $dao->find();
2915 while ($dao->fetch()) {
2916 $membership = array();
2917 CRM_Core_DAO::storeValues($dao, $membership);
2918 $contactMembershipType[$dao->membership_type_id] = $membership;
2919 }
2920 return $contactMembershipType;
2921 }
2922
2923 /**
2924 * Record contribution record associated with membership.
2925 *
2926 * @param array $params
2927 * Array of submitted params.
2928 * @param array $ids
2929 * (param in process of being removed - try to use params) array of ids.
2930 *
2931 * @return CRM_Contribute_BAO_Contribution
2932 */
2933 public static function recordMembershipContribution(&$params, $ids = array()) {
2934 $membershipId = $params['membership_id'];
2935 $contributionParams = array();
2936 $config = CRM_Core_Config::singleton();
2937 $contributionParams['currency'] = $config->defaultCurrency;
2938 $contributionParams['receipt_date'] = (CRM_Utils_Array::value('receipt_date', $params)) ? $params['receipt_date'] : 'null';
2939 $contributionParams['source'] = CRM_Utils_Array::value('contribution_source', $params);
2940 $contributionParams['non_deductible_amount'] = 'null';
2941 $contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor_id', $params);
2942 $contributionSoftParams = CRM_Utils_Array::value('soft_credit', $params);
2943 $recordContribution = array(
2944 'contact_id',
2945 'total_amount',
2946 'receive_date',
2947 'financial_type_id',
2948 'payment_instrument_id',
2949 'trxn_id',
2950 'invoice_id',
2951 'is_test',
2952 'contribution_status_id',
2953 'check_number',
2954 'campaign_id',
2955 'is_pay_later',
2956 'membership_id',
2957 'tax_amount',
2958 'skipLineItem',
2959 );
2960 foreach ($recordContribution as $f) {
2961 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
2962 }
2963
2964 // make entry in batch entity batch table
2965 if (!empty($params['batch_id'])) {
2966 $contributionParams['batch_id'] = $params['batch_id'];
2967 }
2968
2969 if (!empty($params['contribution_contact_id'])) {
2970 // deal with possibility of a different person paying for contribution
2971 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2972 }
2973
2974 if (!empty($params['processPriceSet']) &&
2975 !empty($params['lineItems'])
2976 ) {
2977 $contributionParams['line_item'] = CRM_Utils_Array::value('lineItems', $params, NULL);
2978 }
2979
2980 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
2981
2982 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2983 if (!empty($contributionSoftParams)) {
2984 if (!empty($params['batch_id'])) {
2985 foreach ($contributionSoftParams as $contributionSoft) {
2986 $contributionSoft['contribution_id'] = $contribution->id;
2987 $contributionSoft['currency'] = $contribution->currency;
2988 CRM_Contribute_BAO_ContributionSoft::add($contributionSoft);
2989 }
2990 }
2991 else {
2992 $contributionSoftParams['contribution_id'] = $contribution->id;
2993 $contributionSoftParams['currency'] = $contribution->currency;
2994 $contributionSoftParams['amount'] = $contribution->total_amount;
2995 CRM_Contribute_BAO_ContributionSoft::add($contributionSoftParams);
2996 }
2997 }
2998
2999 // store contribution id
3000 $params['contribution_id'] = $contribution->id;
3001
3002 //insert payment record for this membership
3003 if (empty($ids['contribution']) || !empty($params['is_recur'])) {
3004 CRM_Member_BAO_MembershipPayment::create(array(
3005 'membership_id' => $membershipId,
3006 'contribution_id' => $contribution->id,
3007 ));
3008 }
3009 return $contribution;
3010 }
3011
3012 /**
3013 * Record line items for default membership.
3014 *
3015 * @param CRM_Core_Form $qf
3016 * @param array $membershipType
3017 * Array with membership type and organization.
3018 * @param int $priceSetId
3019 *
3020 */
3021 public static function createLineItems(&$qf, $membershipType, &$priceSetId) {
3022 $qf->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
3023 if ($priceSetId) {
3024 $qf->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
3025 }
3026 $editedFieldParams = array(
3027 'price_set_id' => $priceSetId,
3028 'name' => $membershipType[0],
3029 );
3030 $editedResults = array();
3031 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
3032
3033 if (!empty($editedResults)) {
3034 unset($qf->_priceSet['fields']);
3035 $qf->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
3036 unset($qf->_priceSet['fields'][$editedResults['id']]['options']);
3037 $fid = $editedResults['id'];
3038 $editedFieldParams = array(
3039 'price_field_id' => $editedResults['id'],
3040 'membership_type_id' => $membershipType[1],
3041 );
3042 $editedResults = array();
3043 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
3044 $qf->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
3045 if (!empty($qf->_params['total_amount'])) {
3046 $qf->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $qf->_params['total_amount'];
3047 }
3048 }
3049
3050 $fieldID = key($qf->_priceSet['fields']);
3051 $qf->_params['price_' . $fieldID] = CRM_Utils_Array::value('id', $editedResults);
3052 }
3053
3054 /**
3055 * @todo document me - I seem a bit out of date....
3056 */
3057 public static function _getActTypes() {
3058 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
3059 self::$_renewalActType = CRM_Utils_Array::key('Membership Renewal', $activityTypes);
3060 self::$_signupActType = CRM_Utils_Array::key('Membership Signup', $activityTypes);
3061 }
3062
3063 /**
3064 * Get all Cancelled Membership(s) for a contact
3065 *
3066 * @param int $contactID
3067 * Contact id.
3068 * @param bool $isTest
3069 * Mode of payment.
3070 *
3071 * @return array
3072 * Array of membership type
3073 */
3074 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
3075 if (!$contactID) {
3076 return array();
3077 }
3078 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
3079 $queryParams = array(
3080 1 => array($contactID, 'Integer'),
3081 2 => array(
3082 // CRM-15475
3083 array_search(
3084 'Cancelled',
3085 CRM_Member_PseudoConstant::membershipStatus(
3086 NULL,
3087 " name = 'Cancelled' ",
3088 'name',
3089 FALSE,
3090 TRUE
3091 )
3092 ),
3093 'Integer',
3094 ),
3095 3 => array($isTest, 'Boolean'),
3096 );
3097
3098 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
3099 $cancelledMembershipIds = array();
3100 while ($dao->fetch()) {
3101 $cancelledMembershipIds[] = $dao->membership_type_id;
3102 }
3103 return $cancelledMembershipIds;
3104 }
3105
3106 }