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