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