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