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