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