3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
33 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
36 * Static field for all the membership information that we can potentially import.
40 static $_importableFields = NULL;
42 static $_renewalActType = NULL;
44 static $_signupActType = NULL;
49 public function __construct() {
50 parent
::__construct();
54 * Takes an associative array and creates a membership object.
56 * the function extracts all the params it needs to initialize the created
57 * membership object. The params array could contain additional unused name/value
60 * @param array $params
61 * (reference ) an assoc array of name/value pairs.
63 * The array that holds all the db ids.
65 * @return CRM_Member_BAO_Membership
67 public static function add(&$params, $ids = array()) {
68 $oldStatus = $oldType = NULL;
69 $params['id'] = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('membership', $ids));
71 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
74 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
77 // we do this after the hooks are called in case it has been altered
79 $membershipObj = new CRM_Member_DAO_Membership();
80 $membershipObj->id
= $id;
81 $membershipObj->find();
82 while ($membershipObj->fetch()) {
83 $oldStatus = $membershipObj->status_id
;
84 $oldType = $membershipObj->membership_type_id
;
88 if (array_key_exists('is_override', $params) && !$params['is_override']) {
89 $params['is_override'] = 'null';
92 $membership = new CRM_Member_BAO_Membership();
93 $membership->copyValues($params);
94 $membership->id
= $id;
99 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
100 // this means we are in renewal mode and are just updating the membership
101 // record or this is an API update call and all fields are not present in the update record
102 // however the hooks don't care and want all data CRM-7784
103 $tempMembership = new CRM_Member_DAO_Membership();
104 $tempMembership->id
= $membership->id
;
105 $tempMembership->find(TRUE);
106 $membership = $tempMembership;
109 //get the log start date.
110 //it is set during renewal of membership.
111 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
112 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
113 $values = self
::getStatusANDTypeValues($membership->id
);
115 $membershipLog = array(
116 'membership_id' => $membership->id
,
117 'status_id' => $membership->status_id
,
118 'start_date' => $logStartDate,
119 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
120 'modified_date' => date('Ymd'),
121 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
122 'max_related' => $membership->max_related
,
125 $session = CRM_Core_Session
::singleton();
126 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
127 if ($session->get('userID')) {
128 $membershipLog['modified_id'] = $session->get('userID');
130 elseif (!empty($ids['userId'])) {
131 $membershipLog['modified_id'] = $ids['userId'];
134 $membershipLog['modified_id'] = $membership->contact_id
;
137 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
139 // reset the group contact cache since smart groups might be affected due to this
140 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
143 if ($membership->status_id
!= $oldStatus) {
144 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
145 $activityParam = array(
146 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
147 'source_contact_id' => $membershipLog['modified_id'],
148 'target_contact_id' => $membership->contact_id
,
149 'source_record_id' => $membership->id
,
150 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'),
153 'activity_date_time' => date('Y-m-d H:i:s'),
155 civicrm_api3('activity', 'create', $activityParam);
157 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
158 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
159 $activityParam = array(
160 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
161 'source_contact_id' => $membershipLog['modified_id'],
162 'target_contact_id' => $membership->contact_id
,
163 'source_record_id' => $membership->id
,
164 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'),
167 'activity_date_time' => date('Y-m-d H:i:s'),
169 civicrm_api3('activity', 'create', $activityParam);
171 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
174 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
181 * Fetch the object and store the values in the values array.
183 * @param array $params
184 * Input parameters to find object.
185 * @param array $values
186 * Output values of the object.
187 * @param bool $active
188 * Do you want only active memberships to.
190 * @param bool $relatedMemberships
192 * @return CRM_Member_BAO_Membership|null
193 * The found object or null
195 public static function &getValues(&$params, &$values, $active = FALSE, $relatedMemberships = FALSE) {
196 if (empty($params)) {
199 $membership = new CRM_Member_BAO_Membership();
201 $membership->copyValues($params);
203 $memberships = array();
204 while ($membership->fetch()) {
206 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
207 $membership->status_id
,
214 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
215 $memberships[$membership->id
] = $membership;
216 if ($relatedMemberships && !empty($membership->owner_membership_id
)) {
217 $values['owner_membership_ids'][] = $membership->owner_membership_id
;
225 * Takes an associative array and creates a membership object.
227 * @param array $params
228 * (reference ) an assoc array of name/value pairs.
230 * Deprecated parameter The array that holds all the db ids.
231 * @param bool $skipRedirect
232 * @param string $activityType
234 * @throws CRM_Core_Exception
236 * @return CRM_Member_BAO_Membership|CRM_Core_Error
238 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup') {
239 // always calculate status if is_override/skipStatusCal is not true.
240 // giving respect to is_override during import. CRM-4012
242 // To skip status calculation we should use 'skipStatusCal'.
243 // eg pay later membership, membership update cron CRM-3984
245 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
246 $dates = array('start_date', 'end_date', 'join_date');
247 // Declare these out of courtesy as IDEs don't pick up the setting of them below.
248 $start_date = $end_date = $join_date = NULL;
249 foreach ($dates as $date) {
250 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
253 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
254 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
256 //CRM-3724 always skip is_admin if is_override != true.
257 if (!$excludeIsAdmin && empty($params['is_override'])) {
258 $excludeIsAdmin = TRUE;
261 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
262 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
264 if (empty($calcStatus)) {
265 // Redirect the form in case of error
266 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
267 // however since we have no idea how (if) this is triggered we can't safely move / remove it
268 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
269 // and am convinced form validation is complete on that form WRT this error.
270 $errorParams = array(
271 'message_title' => ts('No valid membership status for given dates.'),
272 'legacy_redirect_path' => 'civicrm/contact/view',
273 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
275 throw new CRM_Core_Exception(ts(
276 "The membership cannot be saved because the status cannot be calculated for start_date: $start_date end_date $end_date join_date $join_date as at " . date('Y-m-d H:i:s')),
281 $params['status_id'] = $calcStatus['id'];
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 (!empty($params['owner_membership_id'])) {
288 unset($params['max_related']);
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);
300 $transaction = new CRM_Core_Transaction();
302 $membership = self
::add($params, $ids);
304 if (is_a($membership, 'CRM_Core_Error')) {
305 $transaction->rollback();
309 // add custom field values
310 if (!empty($params['custom']) && is_array($params['custom'])
312 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
315 $params['membership_id'] = $membership->id
;
316 if (isset($ids['membership'])) {
317 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
324 // This code ensures a line item is created but it is recomended you pass in 'skipLineItem' or 'line_item'
325 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
326 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
328 $params['skipLineItem'] = TRUE;
330 //record contribution for this membership
331 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
332 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
333 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
336 if (!empty($params['lineItems'])) {
337 $params['line_item'] = $params['lineItems'];
340 //do cleanup line items if membership edit the Membership type.
341 if (empty($ids['contribution']) && !empty($ids['membership'])) {
342 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
345 // This could happen if there is no contribution or we are in one of many
346 // weird and wonderful flows. This is scary code. Keep adding tests.
347 if (!empty($params['line_item']) && empty($ids['contribution'])) {
349 foreach ($params['line_item'] as $priceSetId => $lineItems) {
350 foreach ($lineItems as $lineIndex => $lineItem) {
351 $lineMembershipType = CRM_Utils_Array
::value('membership_type_id', $lineItem);
352 if (CRM_Utils_Array
::value('contribution', $params)) {
353 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
355 if ($lineMembershipType && $lineMembershipType == CRM_Utils_Array
::value('membership_type_id', $params)) {
356 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
357 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
359 elseif (!$lineMembershipType && CRM_Utils_Array
::value('contribution', $params)) {
360 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
361 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
365 CRM_Price_BAO_LineItem
::processPriceSet(
367 $params['line_item'],
368 CRM_Utils_Array
::value('contribution', $params)
372 //insert payment record for this membership
373 if (!empty($params['relate_contribution_id'])) {
374 CRM_Member_BAO_MembershipPayment
::create(array(
375 'membership_id' => $membership->id
,
376 'membership_type_id' => $membership->membership_type_id
,
377 'contribution_id' => $params['relate_contribution_id'],
381 // add activity record only during create mode and renew mode
382 // also add activity if status changed CRM-3984 and CRM-2521
383 if (empty($ids['membership']) ||
384 $activityType == 'Membership Renewal' ||
!empty($params['createActivity'])
386 if (!empty($ids['membership'])) {
388 CRM_Core_DAO
::commonRetrieveAll('CRM_Member_DAO_Membership',
392 array('contact_id', 'membership_type_id', 'source')
395 $membership->contact_id
= $data[$membership->id
]['contact_id'];
396 $membership->membership_type_id
= $data[$membership->id
]['membership_type_id'];
397 $membership->source
= CRM_Utils_Array
::value('source', $data[$membership->id
]);
400 // since we are going to create activity record w/
401 // individual contact as a target in case of on behalf signup,
402 // so get the copy of organization id, CRM-5551
403 $realMembershipContactId = $membership->contact_id
;
405 // create activity source = individual, target = org CRM-4027
406 $targetContactID = NULL;
407 if (!empty($params['is_for_organization'])) {
408 $targetContactID = $membership->contact_id
;
409 $membership->contact_id
= CRM_Utils_Array
::value('userId', $ids);
412 if (empty($membership->contact_id
) && (!empty($membership->owner_membership_id
))) {
413 $membership->contact_id
= $realMembershipContactId;
416 if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
417 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
419 elseif (empty($ids['membership'])) {
420 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
423 // we might created activity record w/ individual
424 // contact as target so update membership object w/
425 // original organization id, CRM-5551
426 $membership->contact_id
= $realMembershipContactId;
429 $transaction->commit();
431 self
::createRelatedMemberships($params, $membership);
433 // do not add to recent items for import, CRM-4399
434 if (empty($params['skipRecentView'])) {
435 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
436 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
438 if (empty($membership->membership_type_id
)) {
439 // ie in an update situation.
440 $membership->find(TRUE);
442 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
443 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
445 $recentOther = array();
446 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
447 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
448 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
451 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
452 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
453 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
457 // add the recently created Membership
458 CRM_Utils_Recent
::add($title,
462 $membership->contact_id
,
472 * Check the membership extended through relationship.
474 * @param int $membershipId
476 * @param int $contactId
482 * array of contact_id of all related contacts.
484 public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action
::ADD
) {
486 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
488 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
489 $relationships = array();
490 if (isset($membershipType['relationship_type_id'])) {
491 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
492 CRM_Contact_BAO_Relationship
::CURRENT
494 if ($action & CRM_Core_Action
::UPDATE
) {
495 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
496 CRM_Contact_BAO_Relationship
::PAST
498 $relationships = array_merge($relationships, $pastRelationships);
502 if (!empty($relationships)) {
503 // check for each contact relationships
504 foreach ($relationships as $values) {
505 //get details of the relationship type
506 $relType = array('id' => $values['civicrm_relationship_type_id']);
507 $relValues = array();
508 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
509 // Check if contact's relationship type exists in membership type
510 $relTypeDirs = array();
511 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
512 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
513 $bidirectional = FALSE;
514 foreach ($relTypeIds as $key => $value) {
515 $relTypeDirs[] = $value . '_' . $relDirections[$key];
516 if (in_array($value, $relType) &&
517 $relValues['name_a_b'] == $relValues['name_b_a']
519 $bidirectional = TRUE;
523 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
524 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
525 // $values['status'] is going to have value for
526 // current or past relationships.
527 $contacts[$values['cid']] = $values['status'];
532 // Sort by contact_id ascending
538 * Retrieve DB object based on input parameters.
540 * It also stores all the retrieved values in the default array.
542 * @param array $params
543 * (reference ) an assoc array of name/value pairs.
544 * @param array $defaults
545 * (reference ) an assoc array to hold the name / value pairs.
546 * in a hierarchical manner
548 * @return CRM_Member_BAO_Membership
550 public static function retrieve(&$params, &$defaults) {
551 $membership = new CRM_Member_DAO_Membership();
553 $membership->copyValues($params);
555 if ($membership->find(TRUE)) {
556 CRM_Core_DAO
::storeValues($membership, $defaults);
558 //get the membership status and type values.
559 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
564 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
566 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
567 $defaults['active'] = TRUE;
579 * Get membership status and membership type values.
581 * @param int $membershipId
582 * Membership id of values to return.
585 * Array of key value pairs
587 public static function getStatusANDTypeValues($membershipId) {
589 if (!$membershipId) {
593 SELECT membership.id as id,
594 status.id as status_id,
595 status.label as status,
596 status.is_current_member as is_current_member,
597 type.id as membership_type_id,
598 type.name as membership_type,
599 type.relationship_type_id as relationship_type_id
600 FROM civicrm_membership membership
601 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
602 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
603 WHERE membership.id = %1';
604 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
609 'membership_type_id',
611 'relationship_type_id',
613 while ($dao->fetch()) {
614 foreach ($properties as $property) {
615 $values[$dao->id
][$property] = $dao->$property;
625 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
627 * @param int $membershipId
628 * Membership id that needs to be deleted.
631 * Id of deleted Membership on success, false otherwise.
633 public static function del($membershipId, $preserveContrib = FALSE) {
634 //delete related first and then delete parent.
635 self
::deleteRelatedMemberships($membershipId);
636 return self
::deleteMembership($membershipId, $preserveContrib);
642 * @param int $membershipId
643 * Membership id that needs to be deleted.
646 * Id of deleted Membership on success, false otherwise.
648 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
649 // CRM-12147, retrieve membership data before we delete it for hooks
650 $params = array('id' => $membershipId);
651 $memValues = array();
652 $memberships = self
::getValues($params, $memValues);
654 $membership = $memberships[$membershipId];
656 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
658 $transaction = new CRM_Core_Transaction();
661 //delete activity record
662 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
665 $deleteActivity = FALSE;
666 $membershipActivities = array(
668 'Membership Renewal',
669 'Change Membership Status',
670 'Change Membership Type',
671 'Membership Renewal Reminder',
673 foreach ($membershipActivities as $membershipActivity) {
674 $activityId = array_search($membershipActivity, $activityTypes);
676 $params['activity_type_id'][] = $activityId;
677 $deleteActivity = TRUE;
680 if ($deleteActivity) {
681 $params['source_record_id'] = $membershipId;
682 CRM_Activity_BAO_Activity
::deleteActivity($params);
684 self
::deleteMembershipPayment($membershipId, $preserveContrib);
686 $results = $membership->delete();
687 $transaction->commit();
689 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
691 // delete the recently created Membership
692 $membershipRecent = array(
693 'id' => $membershipId,
694 'type' => 'Membership',
696 CRM_Utils_Recent
::del($membershipRecent);
702 * Delete related memberships.
704 * @param int $ownerMembershipId
705 * @param int $contactId
709 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
710 if (!$ownerMembershipId && !$contactId) {
714 $membership = new CRM_Member_DAO_Membership();
715 $membership->owner_membership_id
= $ownerMembershipId;
718 $membership->contact_id
= $contactId;
722 while ($membership->fetch()) {
723 //delete related first and then delete parent.
724 self
::deleteRelatedMemberships($membership->id
);
725 self
::deleteMembership($membership->id
);
731 * Obtain active/inactive memberships from the list of memberships passed to it.
733 * @param array $memberships
734 * Membership records.
735 * @param string $status
736 * Active or inactive.
739 * array of memberships based on status
741 public static function activeMembers($memberships, $status = 'active') {
743 if ($status == 'active') {
744 foreach ($memberships as $f => $v) {
745 if (!empty($v['active'])) {
751 elseif ($status == 'inactive') {
752 foreach ($memberships as $f => $v) {
753 if (empty($v['active'])) {
763 * Return Membership Block info in Contribution Pages.
766 * Contribution page id.
770 public static function getMembershipBlock($pageID) {
771 $membershipBlock = array();
772 $dao = new CRM_Member_DAO_MembershipBlock();
773 $dao->entity_table
= 'civicrm_contribution_page';
775 $dao->entity_id
= $pageID;
777 if ($dao->find(TRUE)) {
778 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
779 if (!empty($membershipBlock['membership_types'])) {
780 $membershipTypes = unserialize($membershipBlock['membership_types']);
781 if (!is_array($membershipTypes)) {
782 return $membershipBlock;
785 foreach ($membershipTypes as $key => $value) {
786 $membershipBlock['auto_renew'][$key] = $value;
787 $memTypes[$key] = $key;
789 $membershipBlock['membership_types'] = implode(',', $memTypes);
796 return $membershipBlock;
800 * Return a current membership of given contact.
802 * NB: if more than one membership meets criteria, a randomly selected one is returned.
804 * @param int $contactID
806 * @param int $memType
807 * Membership type, null to retrieve all types.
809 * @param int $membershipId
810 * If provided, then determine if it is current.
811 * @param bool $onlySameParentOrg
812 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
816 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
817 //check for owner membership id, if it exists update that membership instead: CRM-15992
819 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
821 'owner_membership_id', 'id'
823 if ($ownerMemberId) {
824 $membershipId = $ownerMemberId;
825 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
832 $dao = new CRM_Member_DAO_Membership();
834 $dao->id
= $membershipId;
836 $dao->contact_id
= $contactID;
837 $dao->membership_type_id
= $memType;
839 //fetch proper membership record.
841 $dao->is_test
= $isTest;
844 $dao->whereAdd('is_test IS NULL OR is_test = 0');
847 //avoid pending membership as current membership: CRM-3027
848 $statusIds[] = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
849 if (!$membershipId) {
851 $statusIds[] = array_search(
853 CRM_Member_PseudoConstant
::membershipStatus(
855 " name = 'Cancelled' ",
862 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
864 // order by start date to find most recent membership first, CRM-4545
865 $dao->orderBy('start_date DESC');
868 if ($onlySameParentOrg && $memType) {
869 // require the same parent org as the $memType
870 $params = array('id' => $memType);
871 $membershipType = array();
872 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
873 $memberTypesSameParentOrg = CRM_Member_BAO_MembershipType
::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
874 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
875 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
879 if ($dao->find(TRUE)) {
880 $membership = array();
881 CRM_Core_DAO
::storeValues($dao, $membership);
882 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
883 $membership['status_id'],
884 'is_current_member', 'id'
886 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
888 'owner_membership_id', 'id'
890 if ($ownerMemberId) {
891 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
892 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
901 if ($onlySameParentOrg && $memType) {
902 // see if there is a membership that has same parent as $memType but different parent than $membershipID
903 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
904 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
911 unset($dao->membership_type_id
);
912 if ($dao->find(TRUE)) {
913 $membership = array();
914 CRM_Core_DAO
::storeValues($dao, $membership);
915 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
916 $membership['status_id'],
917 'is_current_member', 'id'
926 * Combine all the importable fields from the lower levels object.
928 * @param string $contactType
930 * @param bool $status
933 * array of importable Fields
935 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
936 if (!self
::$_importableFields) {
937 if (!self
::$_importableFields) {
938 self
::$_importableFields = array();
942 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
945 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
948 $tmpFields = CRM_Member_DAO_Membership
::import();
949 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
951 // Using new Dedupe rule.
953 'contact_type' => $contactType,
954 'used' => 'Unsupervised',
956 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
958 $tmpContactField = array();
959 if (is_array($fieldsArray)) {
960 foreach ($fieldsArray as $value) {
961 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
966 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
967 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
969 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
972 $title = $tmpContactField[trim($value)]['title'];
974 $tmpContactField[trim($value)]['title'] = $title;
977 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
978 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
980 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
982 $fields = array_merge($fields, $tmpContactField);
983 $fields = array_merge($fields, $tmpFields);
984 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
985 self
::$_importableFields = $fields;
987 return self
::$_importableFields;
991 * Get all exportable fields.
993 * @return array return array of all exportable fields
995 public static function &exportableFields() {
996 $expFieldMembership = CRM_Member_DAO_Membership
::export();
998 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
999 $fields = array_merge($expFieldMembership, $expFieldsMemType);
1000 $fields = array_merge($fields, $expFieldMembership);
1001 $membershipStatus = array(
1002 'membership_status' => array(
1003 'title' => 'Membership Status',
1004 'name' => 'membership_status',
1005 'type' => CRM_Utils_Type
::T_STRING
,
1006 'where' => 'civicrm_membership_status.name',
1009 //CRM-6161 fix for customdata export
1010 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1015 * Get membership joins/renewals for a specified membership type.
1017 * Specifically, retrieves a count of memberships whose "Membership
1018 * Signup" or "Membership Renewal" activity falls in the given date range.
1019 * Dates match the pattern "yyyy-mm-dd".
1021 * @param int $membershipTypeId
1022 * Membership type id.
1023 * @param int $startDate
1024 * Date on which to start counting.
1025 * @param int $endDate
1026 * Date on which to end counting.
1027 * @param bool|int $isTest if true, membership is for a test site
1028 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1031 * the number of members of type $membershipTypeId whose
1032 * start_date is between $startDate and $endDate
1034 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1036 $testClause = 'membership.is_test = 1';
1038 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1041 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1042 self
::_getActTypes();
1045 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1050 SELECT COUNT(DISTINCT membership.id) as member_count
1051 FROM civicrm_membership membership
1052 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1053 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1054 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1055 WHERE membership.membership_type_id = %3
1056 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1059 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1062 1 => array(self
::$_signupActType, 'Integer'),
1063 2 => array(self
::$_renewalActType, 'Integer'),
1064 3 => array($membershipTypeId, 'Integer'),
1067 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1068 return (int) $memberCount;
1072 * Get a count of membership for a specified membership type, optionally for a specified date.
1074 * The date must have the form yyyy-mm-dd.
1076 * If $date is omitted, this function counts as a member anyone whose
1077 * membership status_id indicates they're a current member.
1078 * If $date is given, this function counts as a member anyone who:
1079 * -- Has a start_date before $date and end_date after $date, or
1080 * -- Has a start_date before $date and is currently a member, as indicated
1081 * by the the membership's status_id.
1082 * The second condition takes care of records that have no end_date. These
1083 * are assumed to be lifetime memberships.
1085 * @param int $membershipTypeId
1086 * Membership type id.
1087 * @param string $date
1088 * The date for which to retrieve the count.
1089 * @param bool|int $isTest if true, membership is for a test site
1090 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1093 * the number of members of type $membershipTypeId as of $date.
1095 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1096 if (!CRM_Utils_Rule
::date($date)) {
1097 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1101 1 => array($membershipTypeId, 'Integer'),
1102 2 => array($isTest, 'Boolean'),
1104 $query = "SELECT count(civicrm_membership.id ) as member_count
1105 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1106 WHERE civicrm_membership.membership_type_id = %1
1107 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1108 AND civicrm_membership.is_test = %2";
1110 $query .= " AND civicrm_membership_status.is_current_member = 1";
1113 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1116 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1117 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1118 return (int) $memberCount;
1122 * Function check the status of the membership before adding membership for a contact.
1126 public static function statusAvailabilty() {
1127 $membership = new CRM_Member_DAO_MembershipStatus();
1128 $membership->whereAdd('is_active=1');
1129 return $membership->count();
1133 * Function for updating a membership record's contribution_recur_id.
1135 * @param CRM_Member_DAO_Membership $membership
1136 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1138 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1140 if (empty($contribution->contribution_recur_id
)) {
1145 1 => array($contribution->contribution_recur_id
, 'Integer'),
1146 2 => array($membership->id
, 'Integer'),
1149 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1150 CRM_Core_DAO
::executeQuery($sql, $params);
1154 * Method to fix membership status of stale membership.
1156 * This method first checks if the membership is stale. If it is,
1157 * then status will be updated based on existing start and end
1158 * dates and log will be added for the status change.
1160 * @param array $currentMembership
1161 * Reference to the array.
1162 * containing all values of
1163 * the current membership
1164 * @param array $changeToday
1165 * Array of month, day, year.
1166 * values in case today needs
1167 * to be customised, null otherwise
1169 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1172 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1175 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1176 CRM_Utils_Array
::value('start_date', $currentMembership),
1177 CRM_Utils_Array
::value('end_date', $currentMembership),
1178 CRM_Utils_Array
::value('join_date', $currentMembership),
1181 $currentMembership['membership_type_id'],
1185 if (empty($status) ||
1186 empty($status['id'])
1188 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.'));
1191 $currentMembership['today_date'] = $today;
1193 if ($status['id'] !== $currentMembership['status_id']) {
1194 $memberDAO = new CRM_Member_DAO_Membership();
1195 $memberDAO->id
= $currentMembership['id'];
1196 $memberDAO->find(TRUE);
1198 $memberDAO->status_id
= $status['id'];
1199 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1200 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1201 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1203 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1206 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1207 'CRM_Member_DAO_MembershipStatus',
1208 $currentMembership['status_id'],
1214 'membership_id' => $currentMembership['id'],
1215 'status_id' => $status['id'],
1216 'start_date' => CRM_Utils_Date
::customFormat(
1217 $currentMembership['start_date'],
1220 'end_date' => CRM_Utils_Date
::customFormat(
1221 $currentMembership['end_date'],
1224 'modified_date' => CRM_Utils_Date
::customFormat(
1225 $currentMembership['today_date'],
1228 'membership_type_id' => $currentMembership['membership_type_id'],
1229 'max_related' => CRM_Utils_Array
::value('max_related', $currentMembership, 0),
1232 $session = CRM_Core_Session
::singleton();
1233 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1234 if ($session->get('userID')) {
1235 $logParams['modified_id'] = $session->get('userID');
1238 $logParams['modified_id'] = $currentMembership['contact_id'];
1240 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1245 * Get the contribution page id from the membership record.
1247 * @param int $membershipID
1250 * contribution page id
1252 public static function getContributionPageId($membershipID) {
1254 SELECT c.contribution_page_id as pageID
1255 FROM civicrm_membership_payment mp, civicrm_contribution c
1256 WHERE mp.contribution_id = c.id
1257 AND c.contribution_page_id IS NOT NULL
1258 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1259 . " ORDER BY mp.id DESC";
1261 return CRM_Core_DAO
::singleValueQuery($query,
1262 CRM_Core_DAO
::$_nullArray
1267 * Updated related memberships.
1269 * @param int $ownerMembershipId
1270 * Owner Membership Id.
1271 * @param array $params
1272 * Formatted array of key => value.
1274 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1275 $membership = new CRM_Member_DAO_Membership();
1276 $membership->owner_membership_id
= $ownerMembershipId;
1277 $membership->find();
1279 while ($membership->fetch()) {
1280 $relatedMembership = new CRM_Member_DAO_Membership();
1281 $relatedMembership->id
= $membership->id
;
1282 $relatedMembership->copyValues($params);
1283 $relatedMembership->save();
1284 $relatedMembership->free();
1287 $membership->free();
1291 * Get list of membership fields for profile.
1293 * For now we only allow custom membership fields to be in
1297 * FIXME: This param is ignored
1300 * the list of membership fields
1302 public static function getMembershipFields($mode = NULL) {
1303 $fields = CRM_Member_DAO_Membership
::export();
1305 unset($fields['membership_contact_id']);
1306 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1308 $membershipType = CRM_Member_DAO_MembershipType
::export();
1310 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1312 $fields = array_merge($fields, $membershipType, $membershipStatus);
1318 * Get the sort name of a contact for a particular membership.
1321 * Id of the membership.
1323 * @return null|string
1324 * sort name of the contact if found
1326 public static function sortName($id) {
1327 $id = CRM_Utils_Type
::escape($id, 'Integer');
1330 SELECT civicrm_contact.sort_name
1331 FROM civicrm_membership, civicrm_contact
1332 WHERE civicrm_membership.contact_id = civicrm_contact.id
1333 AND civicrm_membership.id = {$id}
1335 return CRM_Core_DAO
::singleValueQuery($query);
1339 * Create memberships for related contacts, taking into account the maximum related memberships.
1341 * @param array $params
1342 * Array of key - value pairs.
1343 * @param CRM_Core_DAO $dao
1344 * Membership object.
1346 * @param bool $reset
1348 * @return array|null
1349 * Membership details, if created.
1351 * @throws \CRM_Core_Exception
1353 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1354 static $relatedContactIds = array();
1356 // not sure why a static var is in use here - we need a way to reset it from the test suite
1357 $relatedContactIds = array();
1361 $membership = new CRM_Member_DAO_Membership();
1362 $membership->id
= $dao->id
;
1364 // required since create method doesn't return all the
1365 // parameters in the returned membership object
1366 if (!$membership->find(TRUE)) {
1369 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1370 // FIXME : While updating/ renewing the
1371 // membership, if the relationship is PAST then
1372 // the membership of the related contact must be
1374 // For that, getting Membership Status for which
1375 // is_current_member is 0. It works for the
1376 // generated data as there is only one membership
1377 // status having is_current_member = 0.
1378 // But this wont work exactly if there will be
1379 // more than one status having is_current_member = 0.
1380 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1381 $membershipStatus->is_current_member
= 0;
1382 if ($membershipStatus->find(TRUE)) {
1383 $expiredStatusId = $membershipStatus->id
;
1386 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1389 $allRelatedContacts = array();
1390 $relatedContacts = array();
1391 if (!is_a($membership, 'CRM_Core_Error')) {
1392 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1393 $membership->contact_id
,
1394 CRM_Utils_Array
::value('action', $params)
1398 // check for loops. CRM-4213
1399 // remove repeated related contacts, which already inherited membership.
1400 $relatedContactIds[$membership->contact_id
] = TRUE;
1401 foreach ($allRelatedContacts as $cid => $status) {
1402 if (empty($relatedContactIds[$cid])) {
1403 $relatedContactIds[$cid] = TRUE;
1405 //don't create membership again for owner contact.
1406 $nestedRelationship = FALSE;
1407 if ($membership->owner_membership_id
) {
1408 $nestedRelMembership = new CRM_Member_DAO_Membership();
1409 $nestedRelMembership->id
= $membership->owner_membership_id
;
1410 $nestedRelMembership->contact_id
= $cid;
1411 $nestedRelationship = $nestedRelMembership->find(TRUE);
1412 $nestedRelMembership->free();
1414 if (!$nestedRelationship) {
1415 $relatedContacts[$cid] = $status;
1420 //lets cleanup related membership if any.
1421 if (empty($relatedContacts)) {
1422 self
::deleteRelatedMemberships($membership->id
);
1425 // Edit the params array
1426 unset($params['id']);
1427 // Reminder should be sent only to the direct membership
1428 unset($params['reminder_date']);
1429 // unset the custom value ids
1430 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1431 foreach ($params['custom'] as $k => $v) {
1432 unset($params['custom'][$k]['id']);
1435 if (!isset($params['membership_type_id'])) {
1436 $params['membership_type_id'] = $membership->membership_type_id
;
1439 // max_related should be set in the parent membership
1440 unset($params['max_related']);
1441 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1442 $available = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1443 // will be used to queue potential memberships to be created.
1446 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1447 //use existing membership record.
1448 $relMembership = new CRM_Member_DAO_Membership();
1449 $relMembership->contact_id
= $contactId;
1450 $relMembership->owner_membership_id
= $membership->id
;
1451 $relMemIds = array();
1452 if ($relMembership->find(TRUE)) {
1453 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1455 $params['contact_id'] = $contactId;
1456 $params['owner_membership_id'] = $membership->id
;
1458 // set status_id as it might have been changed for
1459 // past relationship
1460 $params['status_id'] = $membership->status_id
;
1462 if ($deceasedStatusId &&
1463 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1465 $params['status_id'] = $deceasedStatusId;
1467 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1468 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1470 $params['status_id'] = $expiredStatusId;
1473 //don't calculate status again in create( );
1474 $params['skipStatusCal'] = TRUE;
1476 //do create activity if we changed status.
1477 if ($params['status_id'] != $relMembership->status_id
) {
1478 $params['createActivity'] = TRUE;
1481 // we should not created contribution record for related contacts, CRM-3371
1482 unset($params['contribution_status_id']);
1484 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1485 unset($params['lineItems']);
1486 unset($params['line_item']);
1488 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1489 // related membership is not active so does not count towards maximum
1490 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1493 // related membership already exists, so this is just an update
1494 if (isset($params['id'])) {
1495 if ($available > 0) {
1496 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1500 // we have run out of inherited memberships, so delete extras
1501 self
::deleteMembership($params['id']);
1503 // we need to first check if there will remain inherited memberships, so queue it up
1510 // now go over the queue and create any available related memberships
1512 while (($available > 0) && ($params = each($queue))) {
1513 CRM_Member_BAO_Membership
::create($params['value'], $relMemIds);
1520 * Delete the record that are associated with this Membership Payment.
1522 * @param int $membershipId
1525 * $membershipPayment deleted membership payment object
1527 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1529 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1530 $membershipPayment->membership_id
= $membershipId;
1531 $membershipPayment->find();
1533 while ($membershipPayment->fetch()) {
1534 if (!$preserveContrib) {
1535 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1537 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1538 $membershipPayment->delete();
1539 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1541 return $membershipPayment;
1545 * Build an array of available membership types.
1547 * @param CRM_Core_Form $form
1548 * @param array $membershipTypeID
1549 * @param bool $activeOnly
1550 * Do we only want active ones?
1551 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1552 * behaviour unchanged).
1556 public static function buildMembershipTypeValues(&$form, $membershipTypeID = array(), $activeOnly = FALSE) {
1557 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1558 $membershipTypeIDS = (array) $membershipTypeID;
1561 $whereClause .= " AND is_active = 1 ";
1563 if (!empty($membershipTypeIDS)) {
1564 $allIDs = implode(',', $membershipTypeIDS);
1565 $whereClause .= " AND id IN ( $allIDs )";
1567 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, CRM_Core_Action
::ADD
);
1569 if ($financialTypes) {
1570 $whereClause .= " AND financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1573 $whereClause .= " AND financial_type_id IN (0)";
1578 FROM civicrm_membership_type
1581 $dao = CRM_Core_DAO
::executeQuery($query);
1583 $membershipTypeValues = array();
1584 $membershipTypeFields = array(
1590 'financial_type_id',
1592 'member_of_contact_id',
1593 'relationship_type_id',
1594 'relationship_direction',
1597 'duration_interval',
1600 while ($dao->fetch()) {
1601 $membershipTypeValues[$dao->id
] = array();
1602 foreach ($membershipTypeFields as $mtField) {
1603 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1608 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1610 if (is_numeric($membershipTypeID) &&
1611 $membershipTypeID > 0
1613 return $membershipTypeValues[$membershipTypeID];
1616 return $membershipTypeValues;
1621 * Get membership record count for a Contact.
1623 * @param int $contactID
1624 * @param bool $activeOnly
1626 * @return null|string
1628 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1629 CRM_Financial_BAO_FinancialType
::getAvailableMembershipTypes($membershipTypes);
1630 $addWhere = " AND membership_type_id IN (0)";
1631 if (!empty($membershipTypes)) {
1632 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1634 $select = "SELECT count(*) FROM civicrm_membership ";
1635 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1637 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1639 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1640 $where .= " and civicrm_membership_status.is_current_member = 1";
1643 $query = $select . $where . $addWhere;
1644 return CRM_Core_DAO
::singleValueQuery($query);
1648 * Check whether payment processor supports cancellation of membership subscription.
1653 * @param bool $isNotCancelled
1657 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1658 $cacheKeyString = "$mid";
1659 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1661 static $supportsCancel = array();
1663 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1664 $supportsCancel[$cacheKeyString] = FALSE;
1665 $isCancelled = FALSE;
1667 if ($isNotCancelled) {
1668 $isCancelled = self
::isSubscriptionCancelled($mid);
1671 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1672 if (!empty($paymentObject)) {
1673 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1676 return $supportsCancel[$cacheKeyString];
1680 * Check whether subscription is already cancelled.
1686 * contribution status
1688 public static function isSubscriptionCancelled($mid) {
1690 SELECT cr.contribution_status_id
1691 FROM civicrm_contribution_recur cr
1692 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1693 WHERE mem.id = %1 LIMIT 1";
1694 $params = array(1 => array($mid, 'Integer'));
1695 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1696 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1697 if ($status == 'Cancelled') {
1704 * Get membership joins for a specified membership type.
1706 * Specifically, retrieves a count of still current memberships whose
1707 * join_date and start_date are within a specified date range. Dates match
1708 * the pattern "yyyy-mm-dd".
1710 * @param int $membershipTypeId
1711 * Membership type id.
1712 * @param int $startDate
1713 * Date on which to start counting.
1714 * @param int $endDate
1715 * Date on which to end counting.
1716 * @param bool|int $isTest if true, membership is for a test site
1719 * the number of members of type $membershipTypeId
1720 * whose join_date is between $startDate and $endDate and
1721 * whose start_date is between $startDate and $endDate
1723 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1724 $testClause = 'membership.is_test = 1';
1726 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1728 if (!self
::$_signupActType) {
1729 self
::_getActTypes();
1732 if (!self
::$_signupActType) {
1737 SELECT COUNT(DISTINCT membership.id) as member_count
1738 FROM civicrm_membership membership
1739 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1740 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1741 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1742 WHERE membership.membership_type_id = %2
1743 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1747 1 => array(self
::$_signupActType, 'Integer'),
1748 2 => array($membershipTypeId, 'Integer'),
1751 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1753 return (int) $memberCount;
1757 * Get membership renewals for a specified membership type.
1759 * Specifically, retrieves a count of still current memberships
1760 * whose join_date is before and start_date is within a specified date
1761 * range. Dates match the pattern "yyyy-mm-dd".
1763 * @param int $membershipTypeId
1764 * Membership type id.
1765 * @param int $startDate
1766 * Date on which to start counting.
1767 * @param int $endDate
1768 * Date on which to end counting.
1769 * @param bool|int $isTest if true, membership is for a test site
1772 * returns the number of members of type $membershipTypeId
1773 * whose join_date is before $startDate and
1774 * whose start_date is between $startDate and $endDate
1776 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1777 $testClause = 'membership.is_test = 1';
1779 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1781 if (!self
::$_renewalActType) {
1782 self
::_getActTypes();
1785 if (!self
::$_renewalActType) {
1790 SELECT COUNT(DISTINCT membership.id) as member_count
1791 FROM civicrm_membership membership
1792 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1793 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1794 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1795 WHERE membership.membership_type_id = %2
1796 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1800 1 => array(self
::$_renewalActType, 'Integer'),
1801 2 => array($membershipTypeId, 'Integer'),
1803 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1805 return (int) $memberCount;
1809 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
1810 * refactoring step. This should be BAO functionality
1811 * @param $membership
1812 * @param $membershipContribution
1814 public static function linkMembershipPayment($membership, $membershipContribution) {
1815 CRM_Member_BAO_MembershipPayment
::create(array(
1816 'membership_id' => $membership->id
,
1817 'membership_type_id' => $membership->membership_type_id
,
1818 'contribution_id' => $membershipContribution->id
,
1823 * @param int $contactID
1824 * @param int $membershipTypeID
1825 * @param bool $is_test
1826 * @param $changeToday
1827 * @param int $modifiedID
1828 * @param $customFieldsFormatted
1829 * @param $numRenewTerms
1830 * @param int $membershipID
1832 * @param int $contributionRecurID
1833 * @param $membershipSource
1834 * @param $isPayLater
1835 * @param int $campaignId
1836 * @param array $formDates
1837 * @param null|CRM_Contribute_BAO_Contribution $contribution
1838 * @param array $lineItems
1841 * @throws \CRM_Core_Exception
1843 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array(), $contribution = NULL, $lineItems = array()) {
1844 $renewalMode = $updateStatusId = FALSE;
1845 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1847 $statusFormat = '%Y-%m-%d';
1848 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1851 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1852 // is the same as the parent org of an existing membership of the contact
1853 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1854 $is_test, $membershipID, TRUE
1856 if ($currentMembership) {
1857 $activityType = 'Membership Renewal';
1858 $renewalMode = TRUE;
1860 // Do NOT do anything.
1861 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1862 //2. Paylater/IPN renew. CRM-4556.
1863 if ($pending ||
in_array($currentMembership['status_id'], array(
1864 array_search('Pending', $allStatus),
1866 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1870 'id' => $currentMembership['id'],
1871 'contribution' => $contribution,
1872 'status_id' => $currentMembership['status_id'],
1873 'start_date' => $currentMembership['start_date'],
1874 'end_date' => $currentMembership['end_date'],
1875 'line_item' => $lineItems,
1876 'join_date' => $currentMembership['join_date'],
1877 'membership_type_id' => $membershipTypeID,
1878 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1880 if ($contributionRecurID) {
1881 $memParams['contribution_recur_id'] = $contributionRecurID;
1883 $membership = self
::create($memParams, $ids, FALSE, $activityType);
1884 return array($membership, $renewalMode, $dates);
1887 // Check and fix the membership if it is STALE
1888 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1890 // Now Renew the membership
1891 if (!$currentMembership['is_current_member']) {
1892 // membership is not CURRENT
1894 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1895 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1901 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1902 foreach (array('start_date', 'end_date') as $dateType) {
1903 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1904 if (empty($currentMembership[$dateType])) {
1905 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1908 $currentMembership['is_test'] = $is_test;
1910 if (!empty($membershipSource)) {
1911 $currentMembership['source'] = $membershipSource;
1914 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1915 $currentMembership['id'],
1920 if (!empty($currentMembership['id'])) {
1921 $ids['membership'] = $currentMembership['id'];
1923 $memParams = $currentMembership;
1924 $memParams['membership_type_id'] = $membershipTypeID;
1926 //set the log start date.
1927 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1931 // CURRENT Membership
1932 $membership = new CRM_Member_DAO_Membership();
1933 $membership->id
= $currentMembership['id'];
1934 $membership->find(TRUE);
1935 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1936 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1942 // Insert renewed dates for CURRENT membership
1943 $memParams = array();
1944 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1945 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $formDates, CRM_Utils_Date
::isoToMysql($membership->start_date
));
1946 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $formDates);
1947 if (empty($memParams['end_date'])) {
1948 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
1950 $memParams['membership_type_id'] = $membershipTypeID;
1952 //set the log start date.
1953 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1956 if (!empty($membershipSource)) {
1957 $memParams['source'] = $membershipSource;
1959 elseif (empty($membership->source
)) {
1960 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1961 $currentMembership['id'],
1966 if (!empty($currentMembership['id'])) {
1967 $ids['membership'] = $currentMembership['id'];
1972 $updateStatusId = array_search('Pending', $allStatus);
1978 $activityType = 'Membership Signup';
1980 'contact_id' => $contactID,
1981 'membership_type_id' => $membershipTypeID,
1985 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1987 foreach (array('join_date', 'start_date', 'end_date') as $dateType) {
1988 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1989 if (empty($memParams[$dateType])) {
1990 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1994 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1997 CRM_Utils_Date
::customFormat($dates['end_date'],
2000 CRM_Utils_Date
::customFormat($dates['join_date'],
2008 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2011 // if IPN/Pay-Later set status to: PENDING
2012 $updateStatusId = array_search('Pending', $allStatus);
2015 if (!empty($membershipSource)) {
2016 $memParams['source'] = $membershipSource;
2018 $memParams['is_test'] = $is_test;
2019 $memParams['is_pay_later'] = $isPayLater;
2021 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
2022 // perhaps shouldn't be?
2023 if ($contributionRecurID) {
2024 $memParams['contribution_recur_id'] = $contributionRecurID;
2027 //if we decided status here and want to skip status
2028 //calculation in create( ); then need to pass 'skipStatusCal'.
2029 if ($updateStatusId) {
2030 $memParams['status_id'] = $updateStatusId;
2031 $memParams['skipStatusCal'] = TRUE;
2034 //since we are renewing,
2035 //make status override false.
2036 $memParams['is_override'] = FALSE;
2038 //CRM-4027, create log w/ individual contact.
2040 $ids['userId'] = $modifiedID;
2041 $memParams['is_for_organization'] = TRUE;
2044 $ids['userId'] = $contactID;
2047 //inherit campaign from contrib page.
2048 if (isset($campaignId)) {
2049 $memParams['campaign_id'] = $campaignId;
2052 $memParams['contribution'] = $contribution;
2053 $memParams['custom'] = $customFieldsFormatted;
2054 // Load all line items & process all in membership. Don't do in contribution.
2055 // Relevant tests in api_v3_ContributionPageTest.
2056 $memParams['line_item'] = $lineItems;
2057 $membership = self
::create($memParams, $ids, FALSE, $activityType);
2059 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2060 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2061 $membership->find(TRUE);
2063 return array($membership, $renewalMode, $dates);
2067 * Get line items representing the default price set.
2069 * @param int $membershipOrg
2070 * @param int $membershipTypeID
2071 * @param float $total_amount
2072 * @param int $priceSetId
2076 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2077 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2079 // The name of the price field corresponds to the membership_type organization contact.
2081 'price_set_id' => $priceSetId,
2082 'name' => $membershipOrg,
2085 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2087 if (!empty($results)) {
2088 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2089 $fid = $results['id'];
2090 $editedFieldParams = array(
2091 'price_field_id' => $results['id'],
2092 'membership_type_id' => $membershipTypeID,
2095 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2096 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2097 if (!empty($total_amount)) {
2098 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2102 $fieldID = key($fields);
2103 $returnParams = array(
2104 'price_set_id' => $priceSetId,
2105 'price_sets' => $priceSets,
2106 'fields' => $fields,
2107 'price_fields' => array(
2108 'price_' . $fieldID => CRM_Utils_Array
::value('id', $results),
2111 return $returnParams;
2115 * Process price set and line items.
2117 * @param int $membershipId
2118 * @param array $lineItem
2120 public function processPriceSet($membershipId, $lineItem) {
2121 //FIXME : need to move this too
2122 if (!$membershipId ||
!is_array($lineItem)
2123 || CRM_Utils_System
::isNull($lineItem)
2128 foreach ($lineItem as $priceSetId => $values) {
2132 foreach ($values as $line) {
2133 $line['entity_table'] = 'civicrm_membership';
2134 $line['entity_id'] = $membershipId;
2135 CRM_Price_BAO_LineItem
::create($line);
2141 * Retrieve the contribution id for the associated Membership id.
2142 * @todo we should get this off the line item
2144 * @param int $membershipId
2150 public static function getMembershipContributionId($membershipId) {
2152 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2153 $membershipPayment->membership_id
= $membershipId;
2154 if ($membershipPayment->find(TRUE)) {
2155 return $membershipPayment->contribution_id
;
2161 * The function checks and updates the status of all membership records for a given domain using the
2162 * calc_membership_status and update_contact_membership APIs.
2165 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2169 public static function updateAllMembershipStatus() {
2171 //get all active statuses of membership, CRM-3984
2172 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2173 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2174 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2176 // get only memberships with active membership types
2178 SELECT civicrm_membership.id as membership_id,
2179 civicrm_membership.is_override as is_override,
2180 civicrm_membership.membership_type_id as membership_type_id,
2181 civicrm_membership.status_id as status_id,
2182 civicrm_membership.join_date as join_date,
2183 civicrm_membership.start_date as start_date,
2184 civicrm_membership.end_date as end_date,
2185 civicrm_membership.source as source,
2186 civicrm_contact.id as contact_id,
2187 civicrm_contact.is_deceased as is_deceased,
2188 civicrm_membership.owner_membership_id as owner_membership_id,
2189 civicrm_membership.contribution_recur_id as recur_id
2190 FROM civicrm_membership
2191 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2192 INNER JOIN civicrm_membership_type ON
2193 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2194 WHERE civicrm_membership.is_test = 0";
2197 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2202 $smarty = CRM_Core_Smarty
::singleton();
2204 while ($dao->fetch()) {
2208 // Put common parameters into array for easy access
2209 $memberParams = array(
2210 'id' => $dao->membership_id
,
2211 'status_id' => $dao->status_id
,
2212 'contact_id' => $dao->contact_id
,
2213 'membership_type_id' => $dao->membership_type_id
,
2214 'membership_type' => $allTypes[$dao->membership_type_id
],
2215 'join_date' => $dao->join_date
,
2216 'start_date' => $dao->start_date
,
2217 'end_date' => $dao->end_date
,
2218 'source' => $dao->source
,
2219 'skipStatusCal' => TRUE,
2220 'skipRecentView' => TRUE,
2223 $smarty->assign_by_ref('memberParams', $memberParams);
2225 //update membership record to Deceased if contact is deceased
2226 if ($dao->is_deceased
) {
2227 // check for 'Deceased' membership status, CRM-5636
2228 $deceaseStatusId = array_search('Deceased', $allStatus);
2229 if (!$deceaseStatusId) {
2230 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'))));
2233 //process only when status change.
2234 if ($dao->status_id
!= $deceaseStatusId) {
2235 //take all params that need to save.
2236 $deceasedMembership = $memberParams;
2237 $deceasedMembership['status_id'] = $deceaseStatusId;
2238 $deceasedMembership['createActivity'] = TRUE;
2239 $deceasedMembership['version'] = 3;
2241 //since there is change in status.
2242 $statusChange = array('status_id' => $deceaseStatusId);
2243 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2245 $deceasedMembership['contact_id'],
2246 $deceasedMembership['membership_type_id'],
2247 $deceasedMembership['membership_type'],
2248 $deceasedMembership['join_date'],
2249 $deceasedMembership['start_date'],
2250 $deceasedMembership['end_date'],
2251 $deceasedMembership['source']
2254 //process membership record.
2255 civicrm_api('membership', 'create', $deceasedMembership);
2260 //we fetch related, since we need to check for deceased
2261 //now further processing is handle w/ main membership record.
2262 if ($dao->owner_membership_id
) {
2266 //update membership records where status is NOT - Pending OR Cancelled.
2267 //as well as membership is not override.
2268 //skipping Expired membership records -> reduced extra processing( kiran )
2269 if (!$dao->is_override
&&
2270 !in_array($dao->status_id
, array(
2271 array_search('Pending', $allStatus),
2275 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2277 array_search('Expired', $allStatus),
2281 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2282 //get the membership status as per id.
2283 $newStatus = civicrm_api('membership_status', 'calc',
2285 'membership_id' => $dao->membership_id
,
2287 'ignore_admin_only' => TRUE,
2290 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2292 //process only when status change.
2294 $statusId != $dao->status_id
2296 //take all params that need to save.
2297 $memParams = $memberParams;
2298 $memParams['status_id'] = $statusId;
2299 $memParams['createActivity'] = TRUE;
2300 $memParams['version'] = 3;
2302 // Unset columns which should remain unchanged from their current saved
2303 // values. This avoids race condition in which these values may have
2304 // been changed by other processes.
2306 $memParams['contact_id'],
2307 $memParams['membership_type_id'],
2308 $memParams['membership_type'],
2309 $memParams['join_date'],
2310 $memParams['start_date'],
2311 $memParams['end_date'],
2312 $memParams['source']
2314 //since there is change in status.
2315 $statusChange = array('status_id' => $statusId);
2316 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2318 //process member record.
2319 civicrm_api('membership', 'create', $memParams);
2324 $result['is_error'] = 0;
2325 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2333 * Returns the membership types for a particular contact
2334 * who has lifetime membership without end date.
2336 * @param int $contactID
2337 * @param bool $isTest
2338 * @param bool $onlyLifeTime
2342 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2343 $contactMembershipType = array();
2345 return $contactMembershipType;
2348 $dao = new CRM_Member_DAO_Membership();
2349 $dao->contact_id
= $contactID;
2350 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2351 $dao->whereAdd("status_id != $pendingStatusId");
2354 $dao->is_test
= $isTest;
2357 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2360 if ($onlyLifeTime) {
2361 $dao->whereAdd('end_date IS NULL');
2365 while ($dao->fetch()) {
2366 $membership = array();
2367 CRM_Core_DAO
::storeValues($dao, $membership);
2368 $contactMembershipType[$dao->membership_type_id
] = $membership;
2370 return $contactMembershipType;
2374 * Record contribution record associated with membership.
2376 * @param array $params
2377 * Array of submitted params.
2379 * (param in process of being removed - try to use params) array of ids.
2381 * @return CRM_Contribute_BAO_Contribution
2383 public static function recordMembershipContribution(&$params, $ids = array()) {
2384 $membershipId = $params['membership_id'];
2385 $contributionParams = array();
2386 $config = CRM_Core_Config
::singleton();
2387 $contributionParams['currency'] = $config->defaultCurrency
;
2388 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2389 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2390 $contributionParams['non_deductible_amount'] = 'null';
2391 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2392 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2393 $recordContribution = array(
2398 'financial_type_id',
2399 'payment_instrument_id',
2403 'contribution_status_id',
2410 'contribution_recur_id',
2412 foreach ($recordContribution as $f) {
2413 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2416 // make entry in batch entity batch table
2417 if (!empty($params['batch_id'])) {
2418 $contributionParams['batch_id'] = $params['batch_id'];
2421 if (!empty($params['contribution_contact_id'])) {
2422 // deal with possibility of a different person paying for contribution
2423 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2426 if (!empty($params['processPriceSet']) &&
2427 !empty($params['lineItems'])
2429 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2432 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2434 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2435 if (!empty($contributionSoftParams)) {
2436 if (!empty($params['batch_id'])) {
2437 foreach ($contributionSoftParams as $contributionSoft) {
2438 $contributionSoft['contribution_id'] = $contribution->id
;
2439 $contributionSoft['currency'] = $contribution->currency
;
2440 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2444 $contributionSoftParams['contribution_id'] = $contribution->id
;
2445 $contributionSoftParams['currency'] = $contribution->currency
;
2446 $contributionSoftParams['amount'] = $contribution->total_amount
;
2447 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2451 // store contribution id
2452 $params['contribution_id'] = $contribution->id
;
2454 //insert payment record for this membership
2455 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2456 CRM_Member_BAO_MembershipPayment
::create(array(
2457 'membership_id' => $membershipId,
2458 'contribution_id' => $contribution->id
,
2461 return $contribution;
2465 * @todo document me - I seem a bit out of date....
2467 public static function _getActTypes() {
2468 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2469 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2470 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2474 * Get all Cancelled Membership(s) for a contact
2476 * @param int $contactID
2478 * @param bool $isTest
2482 * Array of membership type
2484 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2488 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2489 $queryParams = array(
2490 1 => array($contactID, 'Integer'),
2495 CRM_Member_PseudoConstant
::membershipStatus(
2497 " name = 'Cancelled' ",
2505 3 => array($isTest, 'Boolean'),
2508 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2509 $cancelledMembershipIds = array();
2510 while ($dao->fetch()) {
2511 $cancelledMembershipIds[] = $dao->membership_type_id
;
2513 return $cancelledMembershipIds;