コード例 #1
0
ファイル: Membership.php プロジェクト: bhirsch/voipdev
/**
 * Deletes an existing contact membership
 * 
 * This API is used for deleting a contact membership
 * 
 * @param  Int  $membershipID   Id of the contact membership to be deleted
 * 
 * @return null if successfull, object of CRM_Core_Error otherwise
 * @access public
 */
function civicrm_membership_delete(&$membershipID)
{
    _civicrm_initialize();
    if (empty($membershipID)) {
        return civicrm_create_error('Membership ID cannot be empty.');
    }
    require_once 'CRM/Member/BAO/Membership.php';
    CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipID);
    $membership = new CRM_Member_BAO_Membership();
    $result = $membership->deleteMembership($membershipID);
    return $result ? civicrm_create_success() : civicrm_create_error('Error while deleting Membership');
}
コード例 #2
0
/**
 * Deletes an existing contact membership
 *
 * This API is used for deleting a contact membership
 *
 * @param  $params array  array holding id - Id of the contact membership to be deleted
 *
 * @return array api result
 * {@getfields membership_delete}
 * @access public
 */
function civicrm_api3_membership_delete($params)
{
    // membershipID should be numeric
    // this check should be done @ wrapper level
    if (!is_numeric($params['id'])) {
        return civicrm_api3_create_error('Input parameter should be numeric');
    }
    CRM_Member_BAO_Membership::deleteRelatedMemberships($params['id']);
    $membership = new CRM_Member_BAO_Membership();
    $result = $membership->deleteMembership($params['id']);
    return $result ? civicrm_api3_create_success() : civicrm_api3_create_error('Error while deleting Membership');
}
コード例 #3
0
 /**
  * Create / update / delete membership for related contacts.
  *
  * This function will create/update/delete membership for related
  * contact based on 1) contact have active membership 2) that
  * membership is is extedned by the same relationship type to that
  * of the existing relationship.
  *
  * @param int $contactId
  *   contact id.
  * @param array $params
  *   array of values submitted by POST.
  * @param array $ids
  *   array of ids.
  * @param \const|int $action which action called this function
  *
  * @param bool $active
  *
  * @throws \CRM_Core_Exception
  */
 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE)
 {
     // Check the end date and set the status of the relationship
     // accordingly.
     $status = self::CURRENT;
     $targetContact = $targetContact = CRM_Utils_Array::value('contact_check', $params, array());
     $today = date('Ymd');
     // If a relationship hasn't yet started, just return for now
     // TODO: handle edge-case of updating start_date of an existing relationship
     if (!empty($params['start_date'])) {
         $startDate = substr(CRM_Utils_Date::format($params['start_date']), 0, 8);
         if ($today < $startDate) {
             return;
         }
     }
     if (!empty($params['end_date'])) {
         $endDate = substr(CRM_Utils_Date::format($params['end_date']), 0, 8);
         if ($today > $endDate) {
             $status = self::PAST;
         }
     }
     if ($action & CRM_Core_Action::ADD && $status & self::PAST) {
         // If relationship is PAST and action is ADD, do nothing.
         return;
     }
     $rel = explode('_', $params['relationship_type_id']);
     $relTypeId = $rel[0];
     if (!empty($rel[1])) {
         $relDirection = "_{$rel[1]}_{$rel[2]}";
     } else {
         // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
         // so we can assume _a_b
         $relDirection = "_a_b";
         $targetContact = array($params['contact_id_b'] => 1);
     }
     if ($action & CRM_Core_Action::ADD || $action & CRM_Core_Action::DELETE) {
         $contact = $contactId;
     } elseif ($action & CRM_Core_Action::UPDATE) {
         $contact = $ids['contact'];
         $targetContact = array($ids['contactTarget'] => 1);
     }
     // Build the 'values' array for
     // 1. ContactA
     // 2. ContactB
     // This will allow us to check if either of the contacts in
     // relationship have active memberships.
     $values = array();
     // 1. ContactA
     $values[$contact] = array('relatedContacts' => $targetContact, 'relationshipTypeId' => $relTypeId, 'relationshipTypeDirection' => $relDirection);
     // 2. ContactB
     if (!empty($targetContact)) {
         foreach ($targetContact as $cid => $donCare) {
             $values[$cid] = array('relatedContacts' => array($contact => 1), 'relationshipTypeId' => $relTypeId);
             $relTypeParams = array('id' => $relTypeId);
             $relTypeValues = array();
             CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
             if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
                 $values[$cid]['relationshipTypeDirection'] = '_a_b';
             } else {
                 $values[$cid]['relationshipTypeDirection'] = $relDirection == '_a_b' ? '_b_a' : '_a_b';
             }
         }
     }
     // CRM-15829 UPDATES
     // If we're looking for active memberships we must consider pending (id: 5) ones too.
     // Hence we can't just call CRM_Member_BAO_Membership::getValues below with the active flag, is it would completely miss pending relatioships.
     // As suggested by @davecivicrm, the pending status id is fetched using the CRM_Member_PseudoConstant::membershipStatus() class and method, since these ids differ from system to system.
     $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant::membershipStatus());
     $query = 'SELECT * FROM `civicrm_membership_status`';
     if ($active) {
         $query .= ' WHERE `is_current_member` = 1 OR `id` = %1 ';
     }
     $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($pendingStatusId, 'Integer')));
     while ($dao->fetch()) {
         $membershipStatusRecordIds[$dao->id] = $dao->id;
     }
     // Now get the active memberships for all the contacts.
     // If contact have any valid membership(s), then add it to
     // 'values' array.
     foreach ($values as $cid => $subValues) {
         $memParams = array('contact_id' => $cid);
         $memberships = array();
         // CRM-15829 UPDATES
         // Since we want PENDING memberships as well, the $active flag needs to be set to false so that this will return all memberships and we can then filter the memberships based on the status IDs recieved above.
         CRM_Member_BAO_Membership::getValues($memParams, $memberships, FALSE, TRUE);
         // CRM-15829 UPDATES
         // filter out the memberships returned by CRM_Member_BAO_Membership::getValues based on the status IDs fetched on line ~1462
         foreach ($memberships as $key => $membership) {
             if (!isset($memberships[$key]['status_id'])) {
                 continue;
             }
             $membershipStatusId = $memberships[$key]['status_id'];
             if (!isset($membershipStatusRecordIds[$membershipStatusId])) {
                 unset($memberships[$key]);
             }
         }
         if (empty($memberships)) {
             continue;
         }
         //get ownerMembershipIds for related Membership
         //this is to handle memberships being deleted and recreated
         if (!empty($memberships['owner_membership_ids'])) {
             $ownerMemIds[$cid] = $memberships['owner_membership_ids'];
             unset($memberships['owner_membership_ids']);
         }
         $values[$cid]['memberships'] = $memberships;
     }
     $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
     // done with 'values' array.
     // Finally add / edit / delete memberships for the related contacts
     foreach ($values as $cid => $details) {
         if (!array_key_exists('memberships', $details)) {
             continue;
         }
         $relatedContacts = array_keys(CRM_Utils_Array::value('relatedContacts', $details, array()));
         $mainRelatedContactId = reset($relatedContacts);
         foreach ($details['memberships'] as $membershipId => $membershipValues) {
             $relTypeIds = array();
             if ($action & CRM_Core_Action::DELETE) {
                 // Delete memberships of the related contacts only if relationship type exists for membership type
                 $query = "\nSELECT relationship_type_id, relationship_direction\n  FROM civicrm_membership_type\n WHERE id = {$membershipValues['membership_type_id']}";
                 $dao = CRM_Core_DAO::executeQuery($query);
                 $relTypeDirs = array();
                 while ($dao->fetch()) {
                     $relTypeId = $dao->relationship_type_id;
                     $relDirection = $dao->relationship_direction;
                 }
                 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $relTypeId);
                 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
                     CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
                 }
                 continue;
             }
             if ($action & CRM_Core_Action::UPDATE && $status & self::PAST && $membershipValues['owner_membership_id']) {
                 // If relationship is PAST and action is UPDATE
                 // then delete the RELATED membership
                 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
                 continue;
             }
             // add / edit the memberships for related
             // contacts.
             // Get the Membership Type Details.
             $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']);
             // Check if contact's relationship type exists in membership type
             $relTypeDirs = array();
             if (!empty($membershipType['relationship_type_id'])) {
                 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
             }
             if (!empty($membershipType['relationship_direction'])) {
                 $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
             }
             foreach ($relTypeIds as $key => $value) {
                 $relTypeDirs[] = $value . '_' . $relDirections[$key];
             }
             $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
             if (in_array($relTypeDir, $relTypeDirs)) {
                 // Check if relationship being created/updated is
                 // similar to that of membership type's
                 // relationship.
                 $membershipValues['owner_membership_id'] = $membershipId;
                 unset($membershipValues['id']);
                 unset($membershipValues['membership_contact_id']);
                 unset($membershipValues['contact_id']);
                 unset($membershipValues['membership_id']);
                 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
                     $membershipValues['contact_id'] = $relatedContactId;
                     if ($deceasedStatusId && CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')) {
                         $membershipValues['status_id'] = $deceasedStatusId;
                         $membershipValues['skipStatusCal'] = TRUE;
                     }
                     foreach (array('join_date', 'start_date', 'end_date') as $dateField) {
                         if (!empty($membershipValues[$dateField])) {
                             $membershipValues[$dateField] = CRM_Utils_Date::processDate($membershipValues[$dateField]);
                         }
                     }
                     if ($action & CRM_Core_Action::UPDATE) {
                         //if updated relationship is already related to contact don't delete existing inherited membership
                         if (in_array($relTypeId, $relTypeIds) && !empty($values[$relatedContactId]['memberships']) && !empty($ownerMemIds) && in_array($membershipValues['owner_membership_id'], $ownerMemIds[$relatedContactId])) {
                             continue;
                         }
                         //delete the membership record for related
                         //contact before creating new membership record.
                         CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
                     }
                     // check whether we have some related memberships still available
                     $query = "\nSELECT count(*)\n  FROM civicrm_membership\n    LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)\n WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}\n    AND is_current_member = 1";
                     $result = CRM_Core_DAO::singleValueQuery($query);
                     if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
                         CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray);
                     }
                 }
             } elseif ($action & CRM_Core_Action::UPDATE) {
                 // if action is update and updated relationship do
                 // not match with the existing
                 // membership=>relationship then we need to
                 // change the status of the membership record to expired for
                 // previous relationship -- CRM-12078.
                 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
                 if (empty($params['relationship_ids']) && !empty($params['id'])) {
                     $relIds = array($params['id']);
                 } else {
                     $relIds = CRM_Utils_Array::value('relationship_ids', $params);
                 }
                 if (self::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
                     $membershipValues['status_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
                     $type = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
                     CRM_Member_BAO_Membership::add($membershipValues);
                     CRM_Core_Session::setStatus(ts("Inherited membership {$type} status was changed to Expired due to the change in relationship type."), ts('Record Updated'), 'alert');
                 }
             }
         }
     }
 }
コード例 #4
0
 /**
  * function to create memberships for related contacts
  *
  * @param  array      $params       array of key - value pairs
  * @param  object     $membership   membership object
  *
  * @return null|relatedMembership     array of memberships if created
  * @static
  * @access public
  */
 static function createRelatedMemberships(&$params, &$membership)
 {
     static $relatedContactIds = array();
     // required since create method doesn't return all the
     // parameters in the returned membership object
     if (!$membership->find(true)) {
         return;
     }
     require_once 'CRM/Member/PseudoConstant.php';
     $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
     $allRelatedContacts = array();
     $relatedContacts = array();
     if (!is_a($membership, 'CRM_Core_Error')) {
         $allRelatedContacts = CRM_Member_BAO_Membership::checkMembershipRelationship($membership->id, $membership->contact_id, CRM_Utils_Array::value('action', $params));
     }
     // check for loops. CRM-4213
     // remove repeated related contacts, which already inherited membership.
     $relatedContactIds[$membership->contact_id] = true;
     foreach ($allRelatedContacts as $cid => $status) {
         if (!CRM_Utils_Array::value($cid, $relatedContactIds)) {
             $relatedContactIds[$cid] = true;
             //don't create membership again for owner contact.
             $nestedRelationship = false;
             if ($membership->owner_membership_id) {
                 $nestedRelMembership = new CRM_Member_DAO_Membership();
                 $nestedRelMembership->id = $membership->owner_membership_id;
                 $nestedRelMembership->contact_id = $cid;
                 $nestedRelationship = $nestedRelMembership->find(true);
                 $nestedRelMembership->free();
             }
             if (!$nestedRelationship) {
                 $relatedContacts[$cid] = $status;
             }
         }
     }
     //lets cleanup related membership if any.
     if (empty($relatedContacts)) {
         require_once 'CRM/Member/BAO/Membership.php';
         CRM_Member_BAO_Membership::deleteRelatedMemberships($membership->id);
     } else {
         // Edit the params array
         unset($params['id']);
         // Reminder should be sent only to the direct membership
         unset($params['reminder_date']);
         // unset the custom value ids
         if (is_array(CRM_Utils_Array::value('custom', $params))) {
             foreach ($params['custom'] as $k => $v) {
                 unset($params['custom'][$k]['id']);
             }
         }
         if (!isset($params['membership_type_id'])) {
             $params['membership_type_id'] = $membership->membership_type_id;
         }
         foreach ($relatedContacts as $contactId => $relationshipStatus) {
             //use existing membership record.
             $relMembership = new CRM_Member_DAO_Membership();
             $relMembership->contact_id = $contactId;
             $relMembership->owner_membership_id = $membership->id;
             $relMemIds = array();
             if ($relMembership->find(true)) {
                 $params['id'] = $relMemIds['membership'] = $relMembership->id;
             }
             $params['contact_id'] = $contactId;
             $params['owner_membership_id'] = $membership->id;
             // set status_id as it might have been changed for
             // past relationship
             $params['status_id'] = $membership->status_id;
             if ($deceasedStatusId && CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')) {
                 $params['status_id'] = $deceasedStatusId;
             } else {
                 if (CRM_Utils_Array::value('action', $params) & CRM_Core_Action::UPDATE && $relationshipStatus == CRM_Contact_BAO_Relationship::PAST) {
                     // FIXME : While updating/ renewing the
                     // membership, if the relationship is PAST then
                     // the membership of the related contact must be
                     // expired.
                     // For that, getting Membership Status for which
                     // is_current_member is 0. It works for the
                     // generated data as there is only one membership
                     // status having is_current_member = 0.
                     // But this wont work exactly if there will be
                     // more than one status having is_current_member = 0.
                     require_once 'CRM/Member/DAO/MembershipStatus.php';
                     $membershipStatus = new CRM_Member_DAO_MembershipStatus();
                     $membershipStatus->is_current_member = 0;
                     if ($membershipStatus->find(true)) {
                         $params['status_id'] = $membershipStatus->id;
                     }
                 }
             }
             //don't calculate status again in create( );
             $params['skipStatusCal'] = true;
             //do create activity if we changed status.
             if ($params['status_id'] != $relMembership->status_id) {
                 $params['createActivity'] = true;
             }
             // we should not created contribution record for related contacts, CRM-3371
             unset($params['contribution_status_id']);
             CRM_Member_BAO_Membership::create($params, $relMemIds);
         }
     }
 }
コード例 #5
0
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::deleteRelatedMemberships($this->_id);
         CRM_Member_BAO_Membership::deleteMembership($this->_id);
         return;
     }
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $params = $ids = array();
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && CRM_Utils_Array::value('auto_renew', $this->_params)) {
         $params['is_recur'] = $this->_params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
         // unset send-receipt option, since receipt will be sent when ipn is received.
         unset($this->_params['send_receipt'], $formValues['send_receipt']);
     }
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = NULL;
     if (!($priceSetId = CRM_Utils_Array::value('price_set_id', $formValues))) {
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
     }
     if ($priceSetId) {
         CRM_Price_BAO_Set::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]);
         $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (!CRM_Utils_Array::value('is_override', $params)) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date');
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach ($dates as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
             //$params[$d] = CRM_Utils_Date::processDate( $date );
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     foreach ($this->_memTypeSelected as $memType) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $memType);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     }
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-10223 - allow contribution to be recorded against different contact
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (CRM_Utils_Array::value('honor_type_id', $this->_params)) {
             $params['honor_type_id'] = $this->_params['honor_type_id'];
             $params['honor_contact_id'] = $params['contact_id'];
         }
     }
     if (CRM_Utils_Array::value('record_contribution', $formValues)) {
         $recordContribution = array('total_amount', 'honor_type_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
         }
         if (!CRM_Utils_Array::value('is_override', $params) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $allStatus = CRM_Member_PseudoConstant::membershipStatus();
             $params['status_id'] = array_search('Pending', $allStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (CRM_Utils_Array::value('receive_date', $params)) {
             $formValues['receive_date'] = $params['receive_date'] = CRM_Utils_Date::processDate($params['receive_date']);
         }
         if (CRM_Utils_Array::value('send_receipt', $formValues)) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $params);
         }
         //insert contribution type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $formValues['contribution_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     //crm_core_error::debug('params', $params );
     //crm_core_error::debug('formValue', $formValues );
     //exit;
     $createdMemberships = array();
     if ($this->_mode) {
         if (empty($formValues['total_amount']) && !$priceSetId) {
             // if total amount not provided minimum for membership type is used
             $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'minimum_fee');
         } else {
             $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         }
         if ($priceSetId) {
             $params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'contribution_type_id');
         } else {
             $params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', end($this->_memTypeSelected), 'contribution_type_id');
         }
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $formValues["email-5"] = $formValues["email-Primary"] = $this->_memberEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         //here we are setting up the billing contact - if different from the member they are already created
         // but they will get billing details assigned
         CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         $this->_params['contribution_type_id'] = $params['contribution_type_id'];
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         $paymentParams['contactID'] = $this->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (CRM_Utils_Array::value('honor_type_id', $this->_params)) {
                 $paymentParams['honor_contact_id'] = $this->_contactID;
                 $paymentParams['honor_type_id'] = $this->_params['honor_type_id'];
             }
         }
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recuring records.
         $result = NULL;
         if (CRM_Utils_Array::value('is_recur', $paymentParams)) {
             $allStatus = CRM_Member_PseudoConstant::membershipStatus();
             $contributionType = new CRM_Contribute_DAO_ContributionType();
             $contributionType->id = $params['contribution_type_id'];
             if (!$contributionType->find(TRUE)) {
                 CRM_Core_Error::fatal('Could not find a system table');
             }
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $paymentParams, $result, $this->_contributorContactID, $contributionType, FALSE, TRUE, FALSE);
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->contribution_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
             $params['status_id'] = array_search('Pending', $allStatus);
             $params['skipStatusCal'] = TRUE;
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dp => $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         if ($params['total_amount'] > 0.0) {
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             $result =& $payment->doDirectPayment($paymentParams);
         }
         if (is_a($result, 'CRM_Core_Error')) {
             //make sure to cleanup db for recurring case.
             if (CRM_Utils_Array::value('contributionID', $paymentParams)) {
                 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
             }
             if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) {
                 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
             //assign amount to template if payment was successful
             $this->assign('amount', $params['total_amount']);
         }
         $params['contribution_status_id'] = CRM_Utils_Array::value('is_recur', $paymentParams) ? 2 : 1;
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
         if (!CRM_Utils_Array::value('is_recur', $params) && $params['total_amount'] > 0.0) {
             $contribution = new CRM_Contribute_BAO_Contribution();
             $contribution->trxn_id = CRM_Utils_Array::value('trxn_id', $result);
             if ($contribution->find(TRUE)) {
                 // next create the transaction record
                 $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['total_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['total_amount']), 'currency' => $config->defaultCurrency, 'payment_processor' => $this->_paymentProcessor['payment_processor_type'], 'trxn_id' => CRM_Utils_Array::value('trxn_id', $result));
                 $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
             }
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && CRM_Utils_Array::value('record_contribution', $formValues)) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && CRM_Utils_Array::value('contribution_id', $params)) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution');
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $fieldType = NULL;
                 if ($itemId && CRM_Utils_Array::value('price_field_id', $lineItems[$itemId])) {
                     $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'html_type');
                 }
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 CRM_Contribute_Form_AdditionalInfo::processPriceSet($params['contribution_id'], $lineItem);
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 $membershipStatues = CRM_Member_PseudoConstant::membershipStatus();
                 if (!in_array($membership->status_id, array(array_search('Cancelled', $membershipStatues), array_search('Expired', $membershipStatues)))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             // FIX ME: need to recheck this
             // here we might updated dates, so get from object.
             foreach ($calcDates[$membership->membership_type_id] as $date => &$val) {
                 if ($membership->{$date}) {
                     $val = $membership->{$date};
                 }
             }
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && CRM_Utils_Array::value('record_contribution', $formValues) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem)) {
         foreach ($lineItem[$priceSetId] as &$priceFieldOp) {
             if (CRM_Utils_Array::value('membership_type_id', $priceFieldOp)) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%d%f %b, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%d%f %b, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
         }
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         $receiptSend = TRUE;
         $formValues['contact_id'] = $this->_contactID;
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         //end date can be modified by hooks, so if end date is set then use it.
         $endDate = $membership->end_date ? $membership->end_date : $endDate;
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
         if ($endDate && $endDate !== 'null') {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         // FIX ME: fix status messages
         $statusMsg = array();
         foreach ($membershipTypes as $memType => $membershipType) {
             $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(1 => $membershipType, 2 => $this->_memberDisplayName));
             $membership = $createdMemberships[$memType];
             $memEndDate = $membership->end_date ? $membership->end_date : $endDate;
             //get the end date from calculated dates.
             if (!$memEndDate && !CRM_Utils_Array::value('is_recur', $params)) {
                 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
             }
             if ($memEndDate && $memEndDate !== 'null') {
                 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
                 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
             }
         }
         $statusMsg = implode('<br/>', $statusMsg);
         if ($receiptSend && $mailSend) {
             $statusMsg .= '<br/>' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     CRM_Core_Session::setStatus($statusMsg);
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
     }
 }
コード例 #6
0
ファイル: Relationship.php プロジェクト: hguru/224Civi
 /**
  * Function to create / update / delete membership for related contacts.
  *
  * This function will create/update/delete membership for related
  * contact based on 1) contact have active membership 2) that
  * membership is is extedned by the same relationship type to that
  * of the existing relationship.
  *
  * @param $contactId  Int     contact id
  * @param $params     array   array of values submitted by POST
  * @param $ids        array   array of ids
  * @param $action             which action called this function
  *
  * @static
  *
  */
 static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE)
 {
     // Check the end date and set the status of the relationship
     // accrodingly.
     $status = self::CURRENT;
     if (!empty($params['end_date'])) {
         $endDate = CRM_Utils_Date::setDateDefaults(CRM_Utils_Date::format($params['end_date']), NULL, 'Ymd');
         $today = date('Ymd');
         if ($today > $endDate) {
             $status = self::PAST;
         }
     }
     if ($action & CRM_Core_Action::ADD && $status & self::PAST) {
         // if relationship is PAST and action is ADD, no qustion
         // of creating RELATED membership and return back to
         // calling method
         return;
     }
     $rel = explode('_', $params['relationship_type_id']);
     $relTypeId = $rel[0];
     $relDirection = "_{$rel[1]}_{$rel[2]}";
     $targetContact = array();
     if ($action & CRM_Core_Action::ADD || $action & CRM_Core_Action::DELETE) {
         $contact = $contactId;
         $targetContact = CRM_Utils_Array::value('contact_check', $params);
     } elseif ($action & CRM_Core_Action::UPDATE) {
         $contact = $ids['contact'];
         $targetContact = array($ids['contactTarget'] => 1);
     }
     // Build the 'values' array for
     // 1. ContactA
     // 2. ContactB
     // This will allow us to check if either of the contacts in
     // relationship have active memberships.
     $values = array();
     // 1. ContactA
     $values[$contact] = array('relatedContacts' => $targetContact, 'relationshipTypeId' => $relTypeId, 'relationshipTypeDirection' => $relDirection);
     // 2. ContactB
     if (!empty($targetContact)) {
         foreach ($targetContact as $cid => $donCare) {
             $values[$cid] = array('relatedContacts' => array($contact => 1), 'relationshipTypeId' => $relTypeId);
             $relTypeParams = array('id' => $relTypeId);
             $relTypeValues = array();
             CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
             if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
                 $values[$cid]['relationshipTypeDirection'] = '_a_b';
             } else {
                 $values[$cid]['relationshipTypeDirection'] = $relDirection == '_a_b' ? '_b_a' : '_a_b';
             }
         }
     }
     // Now get the active memberships for all the contacts.
     // If contact have any valid membership(s), then add it to
     // 'values' array.
     foreach ($values as $cid => $subValues) {
         $memParams = array('contact_id' => $cid);
         $memberships = array();
         CRM_Member_BAO_Membership::getValues($memParams, $memberships, $active);
         if (empty($memberships)) {
             continue;
         }
         $values[$cid]['memberships'] = $memberships;
     }
     $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
     // done with 'values' array.
     // Finally add / edit / delete memberships for the related contacts
     foreach ($values as $cid => $details) {
         if (!array_key_exists('memberships', $details)) {
             continue;
         }
         $mainRelatedContactId = key(CRM_Utils_Array::value('relatedContacts', $details, array()));
         foreach ($details['memberships'] as $membershipId => $membershipValues) {
             $relTypeIds = array();
             if ($action & CRM_Core_Action::DELETE) {
                 // Delete memberships of the related contacts only if relationship type exists for membership type
                 $query = "\nSELECT relationship_type_id, relationship_direction\n  FROM civicrm_membership_type\n WHERE id = {$membershipValues['membership_type_id']}";
                 $dao = CRM_Core_DAO::executeQuery($query);
                 $relTypeDirs = array();
                 while ($dao->fetch()) {
                     $relTypeId = $dao->relationship_type_id;
                     $relDirection = $dao->relationship_direction;
                 }
                 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $relTypeId);
                 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
                     CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
                 }
                 continue;
             }
             if ($action & CRM_Core_Action::UPDATE && $status & self::PAST && $membershipValues['owner_membership_id']) {
                 // If relationship is PAST and action is UPDATE
                 // then delete the RELATED membership
                 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
                 continue;
             }
             // add / edit the memberships for related
             // contacts.
             // Get the Membership Type Details.
             $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']);
             // Check if contact's relationship type exists in membership type
             $relTypeDirs = array();
             if (CRM_Utils_Array::value('relationship_type_id', $membershipType)) {
                 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
             }
             if (CRM_Utils_Array::value('relationship_direction', $membershipType)) {
                 $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
             }
             foreach ($relTypeIds as $key => $value) {
                 $relTypeDirs[] = $value . '_' . $relDirections[$key];
             }
             $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
             if (in_array($relTypeDir, $relTypeDirs)) {
                 // Check if relationship being created/updated is
                 // similar to that of membership type's
                 // relationship.
                 $membershipValues['owner_membership_id'] = $membershipId;
                 unset($membershipValues['id']);
                 unset($membershipValues['membership_contact_id']);
                 unset($membershipValues['contact_id']);
                 unset($membershipValues['membership_id']);
                 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
                     $membershipValues['contact_id'] = $relatedContactId;
                     if ($deceasedStatusId && CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')) {
                         $membershipValues['status_id'] = $deceasedStatusId;
                         $membershipValues['skipStatusCal'] = TRUE;
                     }
                     foreach (array('join_date', 'start_date', 'end_date') as $dateField) {
                         if (CRM_Utils_Array::value($dateField, $membershipValues)) {
                             $membershipValues[$dateField] = CRM_Utils_Date::processDate($membershipValues[$dateField]);
                         }
                     }
                     if ($action & CRM_Core_Action::UPDATE) {
                         //delete the membership record for related
                         //contact before creating new membership record.
                         CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
                     }
                     // check whether we have some related memberships still available
                     $query = "\nSELECT count(*)\n  FROM civicrm_membership\n    LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)\n WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}\n    AND is_current_member = 1";
                     $result = CRM_Core_DAO::singleValueQuery($query);
                     if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
                         CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray);
                     }
                 }
             } elseif ($action & CRM_Core_Action::UPDATE) {
                 // if action is update and updated relationship do
                 // not match with the existing
                 // membership=>relationship then we need to
                 // delete the membership record created for
                 // previous relationship.
                 if (self::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array::value('relationship_ids', $params))) {
                     CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
                 }
             }
         }
     }
 }
コード例 #7
0
 /**
  * Delete related memberships.
  */
 public function testdeleteRelatedMemberships()
 {
     $contactId = Contact::createIndividual();
     $params = array('contact_id' => $contactId, 'membership_type_id' => $this->_membershipTypeID, 'join_date' => date('Ymd', strtotime('2006-01-21')), 'start_date' => date('Ymd', strtotime('2006-01-21')), 'end_date' => date('Ymd', strtotime('2006-12-21')), 'source' => 'Payment', 'is_override' => 1, 'status_id' => $this->_membershipStatusID);
     $ids = array();
     CRM_Member_BAO_Membership::create($params, $ids);
     $membershipId = $this->assertDBNotNull('CRM_Member_BAO_Membership', $contactId, 'id', 'contact_id', 'Database check for created membership.');
     CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId);
     $this->membershipDelete($membershipId);
     Contact::delete($contactId);
 }
コード例 #8
0
ファイル: Membership.php プロジェクト: ksecor/civicrm
 /**
  * function to create memberships for related contacts
  *
  * @param  array      $params       array of key - value pairs
  * @param  object     $membership   membership object
  *
  * @return null|relatedMembership     array of memberships if created
  * @static
  * @access public
  */
 static function createRelatedMemberships(&$params, &$membership)
 {
     static $relatedContactIds = array();
     // required since create method doesn't return all the
     // parameters in the returned membership object
     if (!$membership->find(true)) {
         return;
     }
     $allRelatedContacts = array();
     $relatedContacts = array();
     if (!is_a($membership, 'CRM_Core_Error')) {
         $allRelatedContacts = CRM_Member_BAO_Membership::checkMembershipRelationship($membership->id, $membership->contact_id, CRM_Utils_Array::value('action', $params));
     }
     // check for loops. CRM-4213
     // remove repeated related contacts, which already inherited membership.
     $relatedContactIds[$membership->contact_id] = true;
     foreach ($allRelatedContacts as $cid => $status) {
         if (!CRM_Utils_Array::value($cid, $relatedContactIds)) {
             $relatedContacts[$cid] = $status;
             $relatedContactIds[$cid] = true;
         }
     }
     if (!empty($relatedContacts)) {
         // delete all the related membership records before creating
         CRM_Member_BAO_Membership::deleteRelatedMemberships($membership->id);
         // Edit the params array
         unset($params['id']);
         // Reminder should be sent only to the direct membership
         unset($params['reminder_date']);
         // unset the custom value ids
         if (is_array(CRM_Utils_Array::value('custom', $params))) {
             foreach ($params['custom'] as $k => $v) {
                 unset($params['custom'][$k]['id']);
             }
         }
         if (!isset($params['membership_type_id'])) {
             $params['membership_type_id'] = $membership->membership_type_id;
         }
         foreach ($relatedContacts as $contactId => $relationshipStatus) {
             $params['contact_id'] = $contactId;
             $params['owner_membership_id'] = $membership->id;
             // set status_id as it might have been changed for
             // past relationship
             $params['status_id'] = $membership->status_id;
             if (CRM_Utils_Array::value('action', $params) & CRM_Core_Action::UPDATE && $relationshipStatus == CRM_Contact_BAO_Relationship::PAST) {
                 // FIXME : While updating/ renewing the
                 // membership, if the relationship is PAST then
                 // the membership of the related contact must be
                 // expired.
                 // For that, getting Membership Status for which
                 // is_current_member is 0. It works for the
                 // generated data as there is only one membership
                 // status having is_current_member = 0.
                 // But this wont work exactly if there will be
                 // more than one status having is_current_member = 0.
                 require_once 'CRM/Member/DAO/MembershipStatus.php';
                 $membership = new CRM_Member_DAO_MembershipStatus();
                 $membership->is_current_member = 0;
                 if ($membership->find(true)) {
                     $params['status_id'] = $membership->id;
                 }
             }
             // we should not created contribution record for related contacts, CRM-3371
             unset($params['contribution_status_id']);
             CRM_Member_BAO_Membership::create($params, CRM_Core_DAO::$_nullArray);
         }
     }
 }
コード例 #9
0
ファイル: Membership.php プロジェクト: bhirsch/voipdev
/**
 * Deletes an existing contact membership
 * 
 * This API is used for deleting a contact membership
 * 
 * @param  Int  $membershipID   Id of the contact membership to be deleted
 * 
 * @return null if successfull, object of CRM_Core_Error otherwise
 * @access public
 */
function crm_delete_membership($membershipID)
{
    _crm_initialize();
    if (empty($membershipID)) {
        return _crm_error('Invalid value for membershipID');
    }
    require_once 'CRM/Member/BAO/Membership.php';
    CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipID);
    $membership = new CRM_Member_BAO_Membership();
    $result = $membership->deleteMembership($membershipID);
    return $result ? null : _crm_error('Error while deleting Membership');
}
コード例 #10
0
ファイル: Relationship.php プロジェクト: bhirsch/voipdev
 /**
  * Function to create / update / delete membership for related contacts.
  * 
  * This function will create/update/delete membership for related
  * contact based on 1) contact have active membership 2) that
  * membership is is extedned by the same relationship type to that
  * of the existing relationship.
  * 
  * @param $contactId  Int     contact id
  * @param $params     array   array of values submitted by POST
  * @param $ids        array   array of ids
  * @param $action             which action called this function
  * 
  * @static
  *
  */
 static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = true)
 {
     // Check the end date and set the status of the relationship
     // accrodingly.
     $status = self::CURRENT;
     if (!empty($params['end_date'])) {
         $endDate = CRM_Utils_Date::setDateDefaults($params['end_date'], null, 'Ymd');
         $today = date('Ymd');
         if ($today > $endDate) {
             $status = self::PAST;
         }
     }
     if ($action & CRM_Core_Action::ADD && $status & self::PAST) {
         // if relationship is PAST and action is ADD, no qustion
         // of creating RELATED membership and return back to
         // calling method
         return;
     }
     $rel = explode("_", $params['relationship_type_id']);
     $relTypeId = $rel[0];
     $relDirection = "_{$rel[1]}_{$rel[2]}";
     $targetContact = array();
     if ($action & CRM_Core_Action::ADD || $action & CRM_Core_Action::DELETE) {
         $contact = $contactId;
         $targetContact = CRM_Utils_Array::value('contact_check', $params);
     } else {
         if ($action & CRM_Core_Action::UPDATE) {
             $contact = $ids['contact'];
             $targetContact = array($ids['contactTarget'] => 1);
         }
     }
     // Build the 'values' array for
     // 1. ContactA
     // 2. ContactB
     // This will allow us to check if either of the contacts in
     // relationship have active memberships.
     $values = array();
     // 1. ContactA
     $values[$contact] = array('relatedContacts' => $targetContact, 'relationshipTypeId' => $relTypeId, 'relationshipTypeDirection' => $relDirection);
     // 2. ContactB
     if (!empty($targetContact)) {
         foreach ($targetContact as $cid => $donCare) {
             $values[$cid] = array('relatedContacts' => array($contact => 1), 'relationshipTypeId' => $relTypeId);
             $relTypeParams = array('id' => $relTypeId);
             $relTypeValues = array();
             require_once 'CRM/Contact/BAO/RelationshipType.php';
             CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
             if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
                 $values[$cid]['relationshipTypeDirection'] = '_a_b';
             } else {
                 $values[$cid]['relationshipTypeDirection'] = $relDirection == '_a_b' ? '_b_a' : '_a_b';
             }
         }
     }
     // Now get the active memberships for all the contacts.
     // If contact have any valid membership(s), then add it to
     // 'values' array.
     foreach ($values as $cid => $subValues) {
         $memParams = array('contact_id' => $cid);
         $memberships = array();
         require_once 'CRM/Member/BAO/Membership.php';
         CRM_Member_BAO_Membership::getValues($memParams, $memberships, $active);
         if (empty($memberships)) {
             continue;
         }
         $values[$cid]['memberships'] = $memberships;
     }
     // done with 'values' array.
     // Finally add / edit / delete memberships for the related contacts
     foreach ($values as $cid => $details) {
         if (!array_key_exists('memberships', $details)) {
             continue;
         }
         require_once 'CRM/Member/BAO/MembershipType.php';
         foreach ($details['memberships'] as $membershipId => $membershipValues) {
             if ($action & CRM_Core_Action::DELETE) {
                 // delete memberships of the related contacts.
                 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId);
                 continue;
             }
             if ($action & CRM_Core_Action::UPDATE && $status & self::PAST && $membershipValues['owner_membership_id']) {
                 // If relationship is PAST and action is UPDATE
                 // then delete the RELATED membership
                 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
                 continue;
             }
             // add / edit the memberships for related
             // contacts.
             // Get the Membership Type Details.
             $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']);
             if ("{$details['relationshipTypeId']}{$details['relationshipTypeDirection']}" == CRM_Utils_Array::value('relationship_type_id', $membershipType) . "_" . CRM_Utils_Array::value('relationship_direction', $membershipType)) {
                 // Check if relationship being created/updated is
                 // similar to that of membership type's
                 // relationship.
                 $membershipValues['owner_membership_id'] = $membershipId;
                 unset($membershipValues['id']);
                 unset($membershipValues['membership_contact_id']);
                 unset($membershipValues['contact_id']);
                 unset($membershipValues['membership_id']);
                 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
                     $membershipValues['contact_id'] = $relatedContactId;
                     if ($action & CRM_Core_Action::UPDATE) {
                         //delete the membership record for related
                         //contact before creating new membership record.
                         CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
                     }
                     CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray);
                 }
             } else {
                 if ($action & CRM_Core_Action::UPDATE) {
                     // if action is update and updated relationship do
                     // not match with the existing
                     // membership=>relationship then we need to
                     // delete the membership record created for
                     // previous relationship.
                     CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $ids['contactTarget']);
                 }
             }
         }
     }
 }
コード例 #11
0
ファイル: Membership.php プロジェクト: ksecor/civicrm
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     require_once 'CRM/Member/BAO/Membership.php';
     require_once 'CRM/Member/BAO/MembershipType.php';
     require_once 'CRM/Member/BAO/MembershipStatus.php';
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::deleteRelatedMemberships($this->_id);
         CRM_Member_BAO_Membership::deleteMembership($this->_id);
         return;
     }
     $config =& CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $params = array();
     $ids = array();
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $formValues)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $formValues);
     }
     $params['contact_id'] = $this->_contactID;
     // we need to retrieve email address
     if ($this->_context == 'standalone' && CRM_Utils_Array::value('send_receipt', $formValues)) {
         require_once 'CRM/Contact/BAO/Contact/Location.php';
         list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
     }
     $fields = array('status_id', 'source', 'is_override');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (!CRM_Utils_Array::value('is_override', $params)) {
         $params['exclude_is_admin'] = true;
     }
     $params['membership_type_id'] = $formValues['membership_type_id'][1];
     $joinDate = CRM_Utils_Date::processDate($formValues['join_date']);
     $startDate = CRM_Utils_Date::processDate($formValues['start_date']);
     $endDate = CRM_Utils_Date::processDate($formValues['end_date']);
     $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($params['membership_type_id'], $joinDate, $startDate, $endDate);
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date', 'receive_date');
     $currentTime = getDate();
     foreach ($dates as $d) {
         if (isset($formValues[$d]) && !CRM_Utils_System::isNull($formValues[$d])) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d]);
         } else {
             if (isset($calcDates[$d])) {
                 $params[$d] = CRM_Utils_Date::processDate($calcDates[$d]);
             }
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     $customFields = CRM_Core_BAO_CustomField::getFields('Membership', false, false, CRM_Utils_Array::value('membership_type_id', $params));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', false, false, null, null, true));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     require_once 'CRM/Contact/BAO/Contact/Location.php';
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     if (CRM_Utils_Array::value('record_contribution', $formValues)) {
         $recordContribution = array('total_amount', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1]);
         if (!$this->_onlinePendingContributionId) {
             $params['contribution_source'] = "{$membershipType} Membership: Offline membership signup (by {$userName})";
         }
         if ($formValues['send_receipt']) {
             $params['receipt_date'] = $params['receive_date'];
         }
         //insert contribution type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $formValues['contribution_type_id']);
     }
     if ($this->_mode) {
         $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id'], 'minimum_fee');
         $params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id'], 'contribution_type_id');
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $formValues["email-5"] = $formValues["email-Primary"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contactID, null, null, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $params['contribution_status_id'] = 1;
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('Online Membership: Admin Interface');
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = $result['trxn_id'];
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         $membership =& CRM_Member_BAO_Membership::create($params, $ids);
         $contribution = new CRM_Contribute_BAO_Contribution();
         $contribution->trxn_id = $result['trxn_id'];
         if ($contribution->find(true)) {
             // next create the transaction record
             $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['total_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['total_amount']), 'currency' => $config->defaultCurrency, 'payment_processor' => $this->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id']);
             require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
             $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && CRM_Utils_Array::value('record_contribution', $formValues)) {
             // update membership as well as contribution object, CRM-4395
             require_once 'CRM/Contribute/Form/Contribution.php';
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, true);
             //carry updated membership object.
             $membership =& new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(true);
             $cancelled = true;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 require_once 'CRM/Member/PseudoConstant.php';
                 $membershipStatues = CRM_Member_PseudoConstant::membershipStatus();
                 if (!in_array($membership->status_id, array(array_search('Cancelled', $membershipStatues), array_search('Expired', $membershipStatues)))) {
                     $cancelled = false;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
         } else {
             $membership =& CRM_Member_BAO_Membership::create($params, $ids);
         }
     }
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         require_once 'CRM/Core/DAO.php';
         CRM_Core_DAO::setFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id'], 'receipt_text_signup', $formValues['receipt_text_signup']);
     }
     $receiptSend = false;
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         $receiptSend = true;
         $receiptFrom = "{$userName} <{$userEmail}>";
         if (CRM_Utils_Array::value('payment_instrument_id', $formValues)) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
         }
         // retrieve custom data
         require_once "CRM/Core/BAO/UFGroup.php";
         $customFields = $customValues = array();
         foreach ($this->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
         $members = array(array('member_id', '=', $membership->id, 0, 0));
         // check whether its a test drive
         if ($this->_mode) {
             $members[] = array('member_test', '=', 1, 0, 0);
         }
         CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, false, $members);
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $this->_params)) {
                 $name = $this->_params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $this->_params)) {
                 $name .= " {$this->_params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $this->_params)) {
                 $name .= " {$this->_params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($this->_params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number']));
             $this->assign('credit_card_type', $this->_params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('module', 'Membership');
         $this->assign('contactID', $this->_contactID);
         $this->assign('membershipID', $params['membership_id']);
         $this->assign('receiptType', 'membership signup');
         $this->assign('receive_date', $params['receive_date']);
         $this->assign('formValues', $formValues);
         $this->assign('mem_start_date', CRM_Utils_Date::customFormat($calcDates['start_date']));
         $this->assign('mem_end_date', CRM_Utils_Date::customFormat($calcDates['end_date']));
         $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1]));
         $this->assign('customValues', $customValues);
         require_once 'CRM/Core/BAO/MessageTemplates.php';
         list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_offline_receipt', 'contactId' => $this->_contactID, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => (bool) ($this->_action & CRM_Core_Action::PREVIEW)));
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($endDate) {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         require_once 'CRM/Core/DAO.php';
         $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id']);
         $statusMsg = ts('%1 membership for %2 has been added.', array(1 => $memType, 2 => $this->_contributorDisplayName));
         //get the end date from calculated dates.
         $endDate = $endDate ? $endDate : CRM_Utils_Array::value('end_date', $calcDates);
         if ($endDate) {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend && $mailSend) {
             $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     CRM_Core_Session::setStatus($statusMsg);
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
         }
     }
 }