/** * Function to actually build the form * * @return void * @access public */ public function buildQuickForm() { require_once 'CRM/Member/BAO/MembershipType.php'; $membershipTypes = CRM_Member_BAO_MembershipType::getMembershipTypes(); if (!empty($membershipTypes)) { $this->addElement('checkbox', 'is_active', ts('Membership Section Enabled?'), null, array('onclick' => "memberBlock(this);")); $this->addElement('text', 'new_title', ts('Title - New Membership'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipBlock', 'new_title')); $this->addWysiwyg('new_text', ts('Introductory Message - New Memberships'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipBlock', 'new_text')); $this->addElement('text', 'renewal_title', ts('Title - Renewals'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipBlock', 'renewal_title')); $this->addWysiwyg('renewal_text', ts('Introductory Message - Renewals'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipBlock', 'renewal_text')); $this->addElement('checkbox', 'is_required', ts('Require Membership Signup')); $this->addElement('checkbox', 'display_min_fee', ts('Display Membership Fee')); $this->addElement('checkbox', 'is_separate_payment', ts('Separate Membership Payment')); $membership = array(); $membershipDefault = array(); foreach ($membershipTypes as $k => $v) { $membership[] = HTML_QuickForm::createElement('advcheckbox', $k, null, $v); $membershipDefault[] = HTML_QuickForm::createElement('radio', null, null, null, $k); } $this->addGroup($membership, 'membership_type', ts('Membership Types')); $this->addGroup($membershipDefault, 'membership_type_default', ts('Membership Types Default')); $this->addFormRule(array('CRM_Member_Form_MembershipBlock', 'formRule'), $this->_id); } $session =& CRM_Core_Session::singleton(); $single = $session->get('singleForm'); if ($single) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'spacing' => ' ', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel')))); } else { parent::buildQuickForm(); } //$session->set('single', false ); }
/** * Helper function to create membership type. */ public function createMembershipType() { $orgId = Contact::createOrganisation(); $ids = array('memberOfContact' => $orgId); $params = array('name' => 'Test Type', 'description' => 'test membership type', 'minimum_fee' => 111, 'duration_unit' => 'year', 'period_type' => 'rolling', 'duration_interval' => 1, 'member_org' => NULL, 'fixed_period_start_day' => NULL, 'fixed_period_rollover_day' => NULL, 'action' => 1, 'financial_type_id' => 1, 'relationship_type_id' => 4, 'visibility' => 'Public', 'weight' => 4, 'is_active' => 1, 'contact_check' => 1, 'relationship_direction' => 'a_b', 'member_of_contact_id' => $orgId); $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids); $membershipType->orgnizationID = $orgId; return $membershipType; }
function setUp() { parent::setUp(); $this->_relationshipTypeId = $this->relationshipTypeCreate($params); $this->_orgContactID = $this->organizationCreate(); $this->_contributionTypeId = $this->contributionTypeCreate(); $ids = array('memberOfContact' => $this->_orgContactID); $params = array('name' => 'test type', 'description' => null, 'minimum_fee' => 10, 'duration_unit' => 'year', 'period_type' => 'fixed', 'duration_interval' => 1, 'contribution_type_id' => $this->_contributionTypeId, 'relationship_type_id' => $this->_relationshipTypeId, 'visibility' => 'Public'); $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids); $this->_membershipTypeID = $membershipType->id; $this->_mebershipStatusID = $this->membershipStatusCreate('test status'); }
function setUp() { parent::setUp(); $params = array('contact_type_a' => 'Individual', 'contact_type_b' => 'Organization', 'name_a_b' => 'Test Employee of', 'name_b_a' => 'Test Employer of'); $this->_relationshipTypeId = $this->relationshipTypeCreate($params); $this->_orgContactID = $this->organizationCreate(); $this->_financialTypeId = 1; $params = array('name' => 'test type', 'description' => NULL, 'minimum_fee' => 10, 'duration_unit' => 'year', 'member_of_contact_id' => $this->_orgContactID, 'period_type' => 'fixed', 'duration_interval' => 1, 'financial_type_id' => $this->_financialTypeId, 'relationship_type_id' => $this->_relationshipTypeId, 'visibility' => 'Public', 'is_active' => 1); $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids); $this->_membershipTypeID = $membershipType->id; $this->_mebershipStatusID = $this->membershipStatusCreate('test status'); }
/** * API to Create or update a Membership Type * * @param array $params an associative array of name/value property values of civicrm_membership_type * * @return array $result newly created or updated membership type property values. * @access public * {getfields MembershipType_get} */ function civicrm_api3_membership_type_create($params) { $ids['membershipType'] = CRM_Utils_Array::value('id', $params); $ids['memberOfContact'] = CRM_Utils_Array::value('member_of_contact_id', $params); $ids['contributionType'] = CRM_Utils_Array::value('financial_type_id', $params); $membershipTypeBAO = CRM_Member_BAO_MembershipType::add($params, $ids); $membershipType = array(); _civicrm_api3_object_to_array($membershipTypeBAO, $membershipType[$membershipTypeBAO->id]); CRM_Member_PseudoConstant::membershipType(NULL, TRUE); civicrm_api3('membership', 'getfields', array('cache_clear' => 1, 'fieldname' => 'membership_type_id')); civicrm_api3('profile', 'getfields', array('action' => 'submit', 'cache_clear' => 1)); return civicrm_api3_create_success($membershipType, $params, 'membership_type', 'create', $membershipTypeBAO); }
/** * Function to actually build the form * * @return void * @access public */ public function buildQuickForm() { require_once 'CRM/Member/BAO/MembershipType.php'; $membershipTypes = CRM_Member_BAO_MembershipType::getMembershipTypes(); if (!empty($membershipTypes)) { $this->addElement('checkbox', 'is_active', ts('Membership Section Enabled?'), null, array('onclick' => "memberBlock(this);")); $this->addElement('text', 'new_title', ts('Title - New Membership'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipBlock', 'new_title')); $this->addWysiwyg('new_text', ts('Introductory Message - New Memberships'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipBlock', 'new_text')); $this->addElement('text', 'renewal_title', ts('Title - Renewals'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipBlock', 'renewal_title')); $this->addWysiwyg('renewal_text', ts('Introductory Message - Renewals'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipBlock', 'renewal_text')); $this->addElement('checkbox', 'is_required', ts('Require Membership Signup')); $this->addElement('checkbox', 'display_min_fee', ts('Display Membership Fee')); $this->addElement('checkbox', 'is_separate_payment', ts('Separate Membership Payment')); $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(false, false, 'is_recur = 1'); $paymentProcessorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_id, 'payment_processor_id'); $isRecur = false; $membership = array(); $membershipDefault = array(); foreach ($membershipTypes as $k => $v) { $membership[] = HTML_QuickForm::createElement('advcheckbox', $k, null, $v); $membershipDefault[] = HTML_QuickForm::createElement('radio', null, null, null, $k); if (is_array($paymentProcessor) && CRM_Utils_Array::value($paymentProcessorId, $paymentProcessor)) { $isRecur = true; $autoRenew = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $k, 'auto_renew'); $autoRenewOptions = array(); if ($autoRenew) { $autoRenewOptions = array(ts('Not offered'), ts('Give option'), ts('Required')); $this->addElement('select', "auto_renew_{$k}", ts('Auto-renew'), $autoRenewOptions); $this->_renewOption[$k] = $autoRenew; } } else { $isRecur = false; } } $this->assign('is_recur', $isRecur); $this->assign('auto_renew', $this->_renewOption); $this->addGroup($membership, 'membership_type', ts('Membership Types')); $this->addGroup($membershipDefault, 'membership_type_default', ts('Membership Types Default')); $this->addFormRule(array('CRM_Member_Form_MembershipBlock', 'formRule'), $this->_id); } $session = CRM_Core_Session::singleton(); $single = $session->get('singleForm'); if ($single) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'spacing' => ' ', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel')))); } else { parent::buildQuickForm(); } //$session->set('single', false ); }
function setUp() { parent::setUp(); $params = array('contact_type_a' => 'Individual', 'contact_type_b' => 'Organization', 'name_a_b' => 'Test Employee of', 'name_b_a' => 'Test Employer of'); $this->_relationshipTypeId = $this->relationshipTypeCreate($params); $this->_orgContactID = $this->organizationCreate(); $this->_financialTypeId = 1; $this->_membershipTypeName = 'Mickey Mouse Club Member'; $params = array('name' => $this->_membershipTypeName, 'description' => NULL, 'minimum_fee' => 10, 'duration_unit' => 'year', 'member_of_contact_id' => $this->_orgContactID, 'period_type' => 'fixed', 'duration_interval' => 1, 'financial_type_id' => $this->_financialTypeId, 'relationship_type_id' => $this->_relationshipTypeId, 'visibility' => 'Public', 'is_active' => 1, 'fixed_period_start_day' => 101, 'fixed_period_rollover_day' => 1231); $ids = array(); $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids); $this->_membershipTypeID = $membershipType->id; $this->_mebershipStatusID = $this->membershipStatusCreate('test status'); $session = CRM_Core_Session::singleton(); $session->set('dateTypes', 1); }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { require_once 'CRM/Member/BAO/Membership.php'; require_once 'CRM/Member/BAO/MembershipType.php'; require_once 'CRM/Core/BAO/CustomGroup.php'; $values = array(); $id = CRM_Utils_Request::retrieve('id', 'Positive', $this); // Make sure context is assigned to template for condition where we come here view civicrm/membership/view $context = CRM_Utils_Request::retrieve('context', 'String', $this); $this->assign('context', $context); if ($id) { $params = array('id' => $id); CRM_Member_BAO_Membership::retrieve($params, $values); // build associated contributions require_once 'CRM/Member/Page/Tab.php'; CRM_Member_Page_Tab::associatedContribution($values['contact_id'], $id); //Provide information about membership source when it is the result of a relationship (CRM-1901) $values['owner_membership_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $id, 'owner_membership_id'); if (isset($values['owner_membership_id'])) { $values['owner_contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $values['owner_membership_id'], 'contact_id', 'id'); $values['owner_display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['owner_contact_id'], 'display_name', 'id'); $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($values['membership_type_id']); $direction = strrev($membershipType['relationship_direction']); $values['relationship'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $membershipType['relationship_type_id'], "name_{$direction}", 'id'); } $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['contact_id'], 'display_name'); $this->assign('displayName', $displayName); // add viewed membership to recent items list require_once 'CRM/Utils/Recent.php'; $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}"); $title = $displayName . ' - ' . ts('Membership Type:') . ' ' . $values['membership_type']; CRM_Utils_Recent::add($title, $url, $values['id'], 'Membership', $values['contact_id'], null); CRM_Member_Page_Tab::setContext($values['contact_id']); $memType = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $id, "membership_type_id"); $groupTree =& CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $id, 0, $memType); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); } if ($values['is_test']) { $values['membership_type'] .= ' (test) '; } $this->assign($values); }
/** * Heart of the viewing process. The runner gets all the meta data for * the contact and calls the appropriate type of page to view. * * @return void * @access public * */ function preProcess() { //CRM-13901 don't show dashboard to contacts with limited view writes & it does not relect //what they have access to //@todo implement acls on dashboard querys (preferably via api to enhance that at the same time) if (!CRM_Core_Permission::check(array('view all contacts', 'edit all contacts'))) { $this->showMembershipSummary = FALSE; $this->assign('membershipSummary', FALSE); return; } $this->assign('membershipSummary', TRUE); CRM_Utils_System::setTitle(ts('CiviMember')); $membershipSummary = array(); $preMonth = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))); $preMonthEnd = date("Y-m-t", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))); $preMonthYear = mktime(0, 0, 0, substr($preMonth, 4, 2), 1, substr($preMonth, 0, 4)); $today = getdate(); $date = CRM_Utils_Date::getToday(); $isCurrentMonth = 0; // You can force the dashboard to display based upon a certain date $ym = CRM_Utils_Array::value('date', $_GET); if ($ym) { if (preg_match('/^\\d{6}$/', $ym) == 0 || !checkdate(substr($ym, 4, 2), 1, substr($ym, 0, 4)) || substr($ym, 0, 1) == 0) { CRM_Core_Error::fatal(ts('Invalid date query "%1" in URL (valid syntax is yyyymm).', array(1 => $ym))); } $isPreviousMonth = 0; $isCurrentMonth = substr($ym, 0, 4) == $today['year'] && substr($ym, 4, 2) == $today['mon']; $ymd = date('Y-m-d', mktime(0, 0, -1, substr($ym, 4, 2) + 1, 1, substr($ym, 0, 4))); $monthStartTs = mktime(0, 0, 0, substr($ym, 4, 2), 1, substr($ym, 0, 4)); $current = CRM_Utils_Date::customFormat($date, '%Y-%m-%d'); $ym = substr($ym, 0, 4) . '-' . substr($ym, 4, 2); } else { $ym = sprintf("%04d-%02d", $today['year'], $today['mon']); $ymd = sprintf("%04d-%02d-%02d", $today['year'], $today['mon'], $today['mday']); $monthStartTs = mktime(0, 0, 0, $today['mon'], 1, $today['year']); $current = CRM_Utils_Date::customFormat($date, '%Y-%m-%d'); $isCurrentMonth = 1; $isPreviousMonth = 1; } $monthStart = $ym . '-01'; $yearStart = substr($ym, 0, 4) . '-01-01'; $membershipTypes = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE); // added //$membership = new CRM_Member_BAO_Membership; foreach ($membershipTypes as $key => $value) { $membershipSummary[$key]['premonth']['new'] = array('count' => CRM_Member_BAO_Membership::getMembershipJoins($key, $preMonth, $preMonthEnd), 'name' => $value); $membershipSummary[$key]['premonth']['renew'] = array('count' => CRM_Member_BAO_Membership::getMembershipRenewals($key, $preMonth, $preMonthEnd), 'name' => $value); $membershipSummary[$key]['premonth']['total'] = array('count' => CRM_Member_BAO_Membership::getMembershipStarts($key, $preMonth, $preMonthEnd), 'name' => $value); $membershipSummary[$key]['month']['new'] = array('count' => CRM_Member_BAO_Membership::getMembershipJoins($key, $monthStart, $ymd), 'name' => $value); $membershipSummary[$key]['month']['renew'] = array('count' => CRM_Member_BAO_Membership::getMembershipRenewals($key, $monthStart, $ymd), 'name' => $value); $membershipSummary[$key]['month']['total'] = array('count' => CRM_Member_BAO_Membership::getMembershipStarts($key, $monthStart, $ymd), 'name' => $value); $membershipSummary[$key]['year']['new'] = array('count' => CRM_Member_BAO_Membership::getMembershipJoins($key, $yearStart, $ymd), 'name' => $value); $membershipSummary[$key]['year']['renew'] = array('count' => CRM_Member_BAO_Membership::getMembershipRenewals($key, $yearStart, $ymd), 'name' => $value); $membershipSummary[$key]['year']['total'] = array('count' => CRM_Member_BAO_Membership::getMembershipStarts($key, $yearStart, $ymd), 'name' => $value); $membershipSummary[$key]['current']['total'] = array('count' => CRM_Member_BAO_Membership::getMembershipCount($key, $current), 'name' => $value); $membershipSummary[$key]['total']['total'] = array('count' => CRM_Member_BAO_Membership::getMembershipCount($key, $ymd)); //LCD also get summary stats for membership owners $membershipSummary[$key]['premonth_owner']['premonth_owner'] = array('count' => CRM_Member_BAO_Membership::getMembershipStarts($key, $preMonth, $preMonthEnd, 0, 1), 'name' => $value); $membershipSummary[$key]['month_owner']['month_owner'] = array('count' => CRM_Member_BAO_Membership::getMembershipStarts($key, $monthStart, $ymd, 0, 1), 'name' => $value); $membershipSummary[$key]['year_owner']['year_owner'] = array('count' => CRM_Member_BAO_Membership::getMembershipStarts($key, $yearStart, $ymd, 0, 1), 'name' => $value); $membershipSummary[$key]['current_owner']['current_owner'] = array('count' => CRM_Member_BAO_Membership::getMembershipCount($key, $current, 0, 1), 'name' => $value); $membershipSummary[$key]['total_owner']['total_owner'] = array('count' => CRM_Member_BAO_Membership::getMembershipCount($key, $ymd, 0, 1)); //LCD end } // LCD debug //CRM_Core_Error::debug($membershipSummary); $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusCurrent(); $status = implode(',', $status); /* Disabled for lack of appropriate search The Membership search isn't able to properly filter by join or renewal events. Until that works properly, the subtotals shouldn't get links. foreach ($membershipSummary as $typeID => $details) { foreach ($details as $key => $value) { switch ($key) { case 'premonth': $membershipSummary[$typeID][$key]['new']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&join=$preMonth&joinEnd=$preMonthEnd&start=$preMonth&end=$preMonthEnd"); $membershipSummary[$typeID][$key]['renew']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&joinEnd=$prePreMonthEnd&start=$preMonth&end=$preMonthEnd"); $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$preMonth&end=$preMonthEnd"); break; case 'month': $membershipSummary[$typeID][$key]['new']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&join=$monthStart&joinEnd=$ymd&start=$monthStart&end=$ymd"); $membershipSummary[$typeID][$key]['renew']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&joinEnd=$preMonthStart&start=$monthStart&end=$ymd"); $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$monthStart&end=$ymd"); break; case 'year': $membershipSummary[$typeID][$key]['new']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&join=$yearStart&joinEnd=$ymd&start=$yearStart&end=$ymd"); $membershipSummary[$typeID][$key]['renew']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&joinEnd=$preYearStart&start=$yearStart&end=$ymd"); $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$yearStart&end=$ymd"); break; case 'current': $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID"); break; case 'total': if (!$isCurrentMonth) { $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&start=&end=$ymd&status=$status&type=$typeID" ); } else { $membershipSummary[$typeID][$key]['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status" ); } break; //LCD add owner urls case 'premonth_owner': $membershipSummary[$typeID][$key]['premonth_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$preMonth&end=$preMonthEnd&owner=1"); break; case 'month_owner': $membershipSummary[$typeID][$key]['month_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$monthStart&end=$ymd&owner=1"); break; case 'year_owner': $membershipSummary[$typeID][$key]['year_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&start=$yearStart&end=$ymd&owner=1"); break; case 'current_owner': $membershipSummary[$typeID][$key]['current_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&type=$typeID&owner=1"); break; case 'total_owner': if (!$isCurrentMonth) { $membershipSummary[$typeID][$key]['total_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&start=&end=$ymd&status=$status&type=$typeID&owner=1"); } else { $membershipSummary[$typeID][$key]['total_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status=$status&owner=1"); } break; //LCD end } } } */ // Temporary replacement for current totals column foreach ($membershipSummary as $typeID => $details) { if (!$isCurrentMonth) { $membershipSummary[$typeID]['total']['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&start=&end={$ymd}&status={$status}&type={$typeID}"); $membershipSummary[$typeID]['total_owner']['total_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&start=&end={$ymd}&status={$status}&type={$typeID}&owner=1"); } else { $membershipSummary[$typeID]['total']['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status={$status}"); $membershipSummary[$typeID]['total_owner']['total_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status={$status}&owner=1"); } $membershipSummary[$typeID]['current']['total']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status={$status}&type={$typeID}"); $membershipSummary[$typeID]['current_owner']['current_owner']['url'] = CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status={$status}&type={$typeID}&owner=1"); } $totalCount = array(); $newCountPreMonth = $newCountMonth = $newCountYear = 0; $renewCountPreMonth = $renewCountMonth = $renewCountYear = 0; $totalCountPreMonth = $totalCountMonth = $totalCountYear = $totalCountCurrent = $totalCountTotal = 0; $totalCountPreMonth_owner = $totalCountMonth_owner = $totalCountYear_owner = $totalCountCurrent_owner = $totalCountTotal_owner = 0; foreach ($membershipSummary as $key => $value) { $newCountPreMonth = $newCountPreMonth + $value['premonth']['new']['count']; $renewCountPreMonth = $renewCountPreMonth + $value['premonth']['renew']['count']; $totalCountPreMonth = $totalCountPreMonth + $value['premonth']['total']['count']; $newCountMonth = $newCountMonth + $value['month']['new']['count']; $renewCountMonth = $renewCountMonth + $value['month']['renew']['count']; $totalCountMonth = $totalCountMonth + $value['month']['total']['count']; $newCountYear = $newCountYear + $value['year']['new']['count']; $renewCountYear = $renewCountYear + $value['year']['renew']['count']; $totalCountYear = $totalCountYear + $value['year']['total']['count']; $totalCountCurrent = $totalCountCurrent + $value['current']['total']['count']; $totalCountTotal = $totalCountTotal + $value['total']['total']['count']; //LCD add owner values $totalCountPreMonth_owner = $totalCountPreMonth_owner + $value['premonth_owner']['premonth_owner']['count']; $totalCountMonth_owner = $totalCountMonth_owner + $value['month_owner']['month_owner']['count']; $totalCountYear_owner = $totalCountYear_owner + $value['year_owner']['year_owner']['count']; $totalCountCurrent_owner = $totalCountCurrent_owner + $value['current_owner']['current_owner']['count']; $totalCountTotal_owner = $totalCountTotal_owner + $value['total_owner']['total_owner']['count']; } $totalCount['premonth']['new'] = array('count' => $newCountPreMonth); $totalCount['premonth']['renew'] = array('count' => $renewCountPreMonth); $totalCount['premonth']['total'] = array('count' => $totalCountPreMonth); $totalCount['month']['new'] = array('count' => $newCountMonth); $totalCount['month']['renew'] = array('count' => $renewCountMonth); $totalCount['month']['total'] = array('count' => $totalCountMonth); $totalCount['year']['new'] = array('count' => $newCountYear); $totalCount['year']['renew'] = array('count' => $renewCountYear); $totalCount['year']['total'] = array('count' => $totalCountYear); $totalCount['current']['total'] = array('count' => $totalCountCurrent, 'url' => CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status={$status}")); $totalCount['total']['total'] = array('count' => $totalCountTotal, 'url' => CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status={$status}")); if (!$isCurrentMonth) { $totalCount['total']['total'] = array('count' => $totalCountTotal, 'url' => CRM_Utils_System::url('civicrm/member/search', "reset=1&force=1&status={$status}&start=&end={$ymd}")); } // Activity search also unable to handle owner vs. inherited //LCD add owner values $totalCount['premonth_owner']['premonth_owner'] = array('count' => $totalCountPreMonth_owner); $totalCount['month_owner']['month_owner'] = array('count' => $totalCountMonth_owner); $totalCount['year_owner']['year_owner'] = array('count' => $totalCountYear_owner); $totalCount['current_owner']['current_owner'] = array('count' => $totalCountCurrent_owner); $totalCount['total_owner']['total_owner'] = array('count' => $totalCountTotal_owner); if (!$isCurrentMonth) { $totalCount['total_owner']['total_owner'] = array('count' => $totalCountTotal_owner); } //LCD end $this->assign('membershipSummary', $membershipSummary); $this->assign('totalCount', $totalCount); $this->assign('month', date('F', $monthStartTs)); $this->assign('year', date('Y', $monthStartTs)); $this->assign('premonth', date('F', strtotime($preMonth))); $this->assign('currentMonth', date('F')); $this->assign('currentYear', date('Y')); $this->assign('isCurrent', $isCurrentMonth); $this->assign('preMonth', $isPreviousMonth); }
/** * Global form rule. * * @param array $fields * The input form values. * @param array $files * The uploaded files if any. * @param CRM_Core_Form $self * * @return bool|array * true if no errors, else array of errors */ public static function formRule($fields, $files, $self) { $errors = array(); $amount = self::computeAmount($fields, $self->_values); if (CRM_Utils_Array::value('auto_renew', $fields) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) { $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.'); } if (!empty($fields['selectMembership']) && $fields['selectMembership'] != 'no_thanks' || !empty($fields['priceSetId']) && $self->_useForMember) { $isTest = $self->_action & CRM_Core_Action::PREVIEW ? TRUE : FALSE; $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, $isTest, TRUE); $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization(); $unallowedOrgs = array(); foreach (array_keys($lifeMember) as $memTypeId) { $unallowedOrgs[] = $membershipOrgDetails[$memTypeId]; } } //check for atleast one pricefields should be selected if (!empty($fields['priceSetId']) && empty($self->_ccid)) { $priceField = new CRM_Price_DAO_PriceField(); $priceField->price_set_id = $fields['priceSetId']; $priceField->orderBy('weight'); $priceField->find(); $check = array(); $membershipIsActive = TRUE; $previousId = $otherAmount = FALSE; while ($priceField->fetch()) { if ($self->_quickConfig && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) { $previousId = $priceField->id; if ($priceField->name == 'membership_amount' && !$priceField->is_active) { $membershipIsActive = FALSE; } } if ($priceField->name == 'other_amount') { if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) && array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])) { $otherAmount = $priceField->id; } elseif (!empty($fields["price_{$priceField->id}"])) { $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]); $min = CRM_Utils_Array::value('min_amount', $self->_values); $max = CRM_Utils_Array::value('max_amount', $self->_values); if ($min && $otherAmountVal < $min) { $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1', array(1 => $min)); } if ($max && $otherAmountVal > $max) { $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.', array(1 => $max)); } } } if (!empty($fields["price_{$priceField->id}"]) || $previousId == $priceField->id && isset($fields["price_{$previousId}"]) && empty($fields["price_{$previousId}"])) { $check[] = $priceField->id; } } $currentMemberships = NULL; if ($membershipIsActive) { $is_test = $self->_mode != 'live' ? 1 : 0; $memContactID = $self->_membershipContactID; // For anonymous user check using dedupe rule // if user has Cancelled Membership if (!$memContactID) { $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual'); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual'); // if we find more than one contact, use the first one $memContactID = CRM_Utils_Array::value(0, $ids); } $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID, $is_test); $errorText = 'Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.'; foreach ($self->_values['fee'] as $fieldKey => $fieldValue) { if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) { if (!is_array($fields['price_' . $fieldKey]) && isset($fieldValue['options'][$fields['price_' . $fieldKey]])) { if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]]) && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)) { $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id']))); } } else { if (is_array($fields['price_' . $fieldKey])) { foreach (array_keys($fields['price_' . $fieldKey]) as $key) { if (array_key_exists('membership_type_id', $fieldValue['options'][$key]) && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)) { $errors['price_' . $fieldKey] = ts($errorText, array(1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id']))); } } } } } } } // CRM-12233 if ($membershipIsActive && !$self->_membershipBlock['is_required'] && $self->_values['amount_block_is_active']) { $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL; foreach ($self->_values['fee'] as $fieldKey => $fieldValue) { // if 'No thank you' membership is selected then set $membershipFieldId if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) { $membershipFieldId = $fieldKey; } elseif ($membershipFieldId) { if ($fieldValue['name'] == 'other_amount') { $otherFieldId = $fieldKey; } elseif ($fieldValue['name'] == 'contribution_amount') { $contributionFieldId = $fieldKey; } if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') { $errorKey = $fieldKey; } } } // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) { $errors["price_{$errorKey}"] = ts('Additional Contribution is required.'); } } if (empty($check) && empty($self->_ccid)) { if ($self->_useForMember == 1 && $membershipIsActive) { $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).'); } else { $errors['_qf_default'] = ts('Select at least one option from Contribution(s).'); } } if ($otherAmount && !empty($check)) { $errors["price_{$otherAmount}"] = ts('Amount is required field.'); } if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) { $priceFieldIDS = array(); $priceFieldMemTypes = array(); foreach ($self->_priceSet['fields'] as $priceId => $value) { if (!empty($fields['price_' . $priceId]) || $self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required'])) { if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) { foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) { if ($isSet) { $priceFieldIDS[] = $priceFldVal; } } } elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) { // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577 $priceFieldIDS[] = $fields['price_' . $priceId]; } if (!empty($value['options'])) { foreach ($value['options'] as $val) { if (!empty($val['membership_type_id']) && ($fields['price_' . $priceId] == $val['id'] || isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))) { $priceFieldMemTypes[] = $val['membership_type_id']; } } } } } if (!empty($lifeMember)) { foreach ($priceFieldIDS as $priceFieldId) { if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) && in_array($membershipOrgDetails[$id], $unallowedOrgs)) { $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.'); break; } } } if (!empty($priceFieldIDS)) { $ids = implode(',', $priceFieldIDS); $priceFieldIDS['id'] = $fields['priceSetId']; $self->set('memberPriceFieldIDS', $priceFieldIDS); $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids); foreach ($count as $id => $occurrence) { if ($occurrence > 1) { $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.'); } } } if (empty($priceFieldMemTypes) && $self->_membershipBlock['is_required'] == 1) { $errors['_qf_default'] = ts('Please select at least one membership option.'); } } CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem); if ($fields['amount'] < 0) { $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly'); } $amount = $fields['amount']; } if (isset($fields['selectProduct']) && $fields['selectProduct'] != 'no_thanks') { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $fields['selectProduct']; $productDAO->find(TRUE); $min_amount = $productDAO->min_contribution; if ($amount < $min_amount) { $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', array(1 => CRM_Utils_Money::format($min_amount))); CRM_Core_Session::setStatus($errors['selectProduct']); } } //CRM-16285 - Function to handle validation errors on form, for recurring contribution field. CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors); if (!empty($fields['is_recur']) && CRM_Utils_Array::value('payment_processor_id', $fields) == 0) { $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.'); } // validate PCP fields - if not anonymous, we need a nick name value if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) && CRM_Utils_Array::value('pcp_is_anonymous', $fields) == 0 && CRM_Utils_Array::value('pcp_roll_nickname', $fields) == '') { $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.'); } // return if this is express mode $config = CRM_Core_Config::singleton(); if ($self->_paymentProcessor && $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) { if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) || CRM_Utils_Array::value($self->_expressButtonName, $fields)) { return $errors; } } //validate the pledge fields. if (!empty($self->_values['pledge_block_id'])) { //validation for pledge payment. if (!empty($self->_values['pledge_id'])) { if (empty($fields['pledge_amount'])) { $errors['pledge_amount'] = ts('At least one payment option needs to be checked.'); } } elseif (!empty($fields['is_pledge'])) { if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) { $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.'); } else { if (CRM_Utils_Array::value('pledge_installments', $fields) == NULL) { $errors['pledge_installments'] = ts('Pledge Installments is required field.'); } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 1) { $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.'); } elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 0) { $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.'); } } //validation for Pledge Frequency Interval. if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) { $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.'); } else { if (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == NULL) { $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.'); } elseif (CRM_Utils_Array::value('pledge_frequency_interval', $fields) == 0) { $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0'); } } } } // if the user has chosen a free membership or the amount is less than zero // i.e. we don't need to validate payment related fields or profiles. if ((double) $amount <= 0.0) { return $errors; } if (CRM_Utils_Array::value('payment_processor_id', $fields) == NULL) { $errors['payment_processor_id'] = ts('Payment Method is a required field.'); } else { CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, !$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing'); } foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) { $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name'); if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) { $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.', array(1 => ucwords(str_replace('_', " ", $greeting)))); } } } return empty($errors) ? TRUE : $errors; }
function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) { $contribution =& $objects['contribution']; $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id; $memberships =& $objects['membership']; if (is_numeric($memberships)) { $memberships = array($objects['membership']); } $participant =& $objects['participant']; $event =& $objects['event']; $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now); $recurContrib =& $objects['contributionRecur']; $values = array(); if (isset($input['is_email_receipt'])) { $values['is_email_receipt'] = $input['is_email_receipt']; } $source = NULL; if ($input['component'] == 'contribute') { if ($contribution->contribution_page_id) { CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values); $source = ts('Online Contribution') . ': ' . $values['title']; } elseif ($recurContrib && $recurContrib->id) { $contribution->contribution_page_id = NULL; $values['amount'] = $recurContrib->amount; $values['financial_type_id'] = $objects['contributionType']->id; $values['title'] = $source = ts('Offline Recurring Contribution'); $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $values['receipt_from_name'] = $domainValues[0]; $values['receipt_from_email'] = $domainValues[1]; } if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) { //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden. $values['is_email_receipt'] = $recurContrib->is_email_receipt; } $contribution->source = $source; if (CRM_Utils_Array::value('is_email_receipt', $values)) { $contribution->receipt_date = self::$_now; } if (!empty($memberships)) { $membershipsUpdate = array(); foreach ($memberships as $membershipTypeIdKey => $membership) { if ($membership) { $format = '%Y%m%d'; $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id); // CRM-8141 update the membership type with the value recorded in log when membership created/renewed // this picks up membership type changes during renewals $sql = "\nSELECT membership_type_id\nFROM civicrm_membership_log\nWHERE membership_id={$membership->id}\nORDER BY id DESC\nLIMIT 1;"; $dao = new CRM_Core_DAO(); $dao->query($sql); if ($dao->fetch()) { if (!empty($dao->membership_type_id)) { $membership->membership_type_id = $dao->membership_type_id; $membership->save(); } // else fall back to using current membership type } // else fall back to using current membership type $dao->free(); $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID); if ($currentMembership) { /* * Fixed FOR CRM-4433 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status * when Contribution mode is notify and membership is for renewal ) */ CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday); // @todo - we should pass membership_type_id instead of null here but not // adding as not sure of testing $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, NULL, $num_terms); $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); } else { $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms); } //get the status for membership. $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership); $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format)); //we might be renewing membership, //so make status override false. $formatedParams['is_override'] = FALSE; $membership->copyValues($formatedParams); $membership->save(); //updating the membership log $membershipLog = array(); $membershipLog = $formatedParams; $logStartDate = $formatedParams['start_date']; if (CRM_Utils_Array::value('log_start_date', $dates)) { $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate); } $membershipLog['start_date'] = $logStartDate; $membershipLog['membership_id'] = $membership->id; $membershipLog['modified_id'] = $membership->contact_id; $membershipLog['modified_date'] = date('Ymd'); $membershipLog['membership_type_id'] = $membership->membership_type_id; CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); //update related Memberships. CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams); //update the membership type key of membership relatedObjects array //if it has changed after membership update if ($membershipTypeIdKey != $membership->membership_type_id) { $membershipsUpdate[$membership->membership_type_id] = $membership; $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership; unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]); unset($memberships[$membershipTypeIdKey]); } } } //update the memberships object with updated membershipTypeId data //if membershipTypeId has changed after membership update if (!empty($membershipsUpdate)) { $memberships = $memberships + $membershipsUpdate; } } } else { // event $eventParams = array('id' => $objects['event']->id); $values['event'] = array(); CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); //get location details $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event'); $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent'); list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $values['custom_pre_id'] = $custom_pre_id; $values['custom_post_id'] = $custom_post_ids; //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case //and cases involving status updation through ipn $values['totalAmount'] = $input['amount']; $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title']; if ($values['event']['is_email_confirm']) { $contribution->receipt_date = self::$_now; $values['is_email_receipt'] = 1; } if (!CRM_Utils_Array::value('skipComponentSync', $input)) { $participant->status_id = 1; } $participant->save(); } if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) { $input['net_amount'] = $input['amount'] - $input['fee_amount']; } // This complete transaction function is being overloaded to create new contributions too. // here we record if it is a new contribution. // @todo separate the 2 more appropriately. $isNewContribution = FALSE; if (empty($contribution->id)) { $isNewContribution = TRUE; if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) { $contribution->total_amount = $input['amount']; // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner) // so we have to handle net_amount in this (naughty) code. if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) { $contribution->fee_amount = $input['fee_amount']; } $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount; } if (!empty($input['campaign_id'])) { $contribution->campaign_id = $input['campaign_id']; } } $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1)); // @todo this section should call the api in order to have hooks called & // because all this 'messiness' setting variables could be avoided // by letting the api resolve pseudoconstants & copy set values and format dates. $contribution->contribution_status_id = $contributionStatuses['Completed']; $contribution->is_test = $input['is_test']; // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out. if (isset($input['net_amount'])) { $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0); } if (isset($input['net_amount'])) { $contribution->net_amount = $input['net_amount']; } $contribution->trxn_id = $input['trxn_id']; $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date); $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date); $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date); $contribution->cancel_date = 'null'; if (CRM_Utils_Array::value('check_number', $input)) { $contribution->check_number = $input['check_number']; } if (CRM_Utils_Array::value('payment_instrument_id', $input)) { $contribution->payment_instrument_id = $input['payment_instrument_id']; } if (!empty($contribution->id)) { $contributionId['id'] = $contribution->id; $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); } $contribution->save(); //add line items for recurring payments if (!empty($contribution->contribution_recur_id)) { if ($isNewContribution) { $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution); } else { // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear $input['line_item'] = array(); } if (!empty($memberships) && $primaryContributionID != $contribution->id) { foreach ($memberships as $membership) { try { $membershipPayment = array('membership_id' => $membership->id, 'contribution_id' => $contribution->id); if (!civicrm_api3('membership_payment', 'getcount', $membershipPayment)) { civicrm_api3('membership_payment', 'create', $membershipPayment); } } catch (CiviCRM_API3_Exception $e) { echo $e->getMessage(); // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated } } } } //copy initial contribution custom fields for recurring contributions if ($recurContrib && $recurContrib->id) { $this->copyCustomValues($recurContrib->id, $contribution->id); } // next create the transaction record $paymentProcessor = $paymentProcessorId = ''; if (isset($objects['paymentProcessor'])) { if (is_array($objects['paymentProcessor'])) { $paymentProcessor = $objects['paymentProcessor']['payment_processor_type']; $paymentProcessorId = $objects['paymentProcessor']['id']; } else { $paymentProcessor = $objects['paymentProcessor']->payment_processor_type; $paymentProcessorId = $objects['paymentProcessor']->id; } } //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above // which raised the question as to whether this check preceded line 511 & if so whether something could be broken // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code // it would be good if someone added some comments or refactored this if ($contribution->id) { $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) { $input['payment_processor'] = $paymentProcessorId; } $input['contribution_status_id'] = array_search('Completed', $contributionStatuses); $input['total_amount'] = $input['amount']; $input['contribution'] = $contribution; $input['financial_type_id'] = $contribution->financial_type_id; if (CRM_Utils_Array::value('participant', $contribution->_relatedObjects)) { $input['contribution_mode'] = 'participant'; $input['participant_id'] = $contribution->_relatedObjects['participant']->id; $input['skipLineItem'] = 1; } //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second // and subsequent payments. In this case the line items are created at $this->addRecurLineItems // and since the contribution is saved prior to this line there is always a contribution-id, // however there is never a prevContribution (which appears to mean original contribution not previous // contribution - or preUpdateContributionObject most accurately) // so, this is always called & only appears to succeed when prevContribution exists - which appears // to mean "are we updating an exisitng pending contribution" //I was able to make the unit test complete as fataling here doesn't prevent // the contribution being created - but activities would not be created or emails sent CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL); } self::updateRecurLinkedPledge($contribution); // create an activity record if ($input['component'] == 'contribute') { //CRM-4027 $targetContactID = NULL; if (CRM_Utils_Array::value('related_contact', $ids)) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $ids['related_contact']; } CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); // event } else { CRM_Activity_BAO_Activity::addActivity($participant); } CRM_Core_Error::debug_log_message("Contribution record updated successfully"); $transaction->commit(); // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) { self::sendMail($input, $ids, $objects, $values, $recur, FALSE); CRM_Core_Error::debug_log_message("Receipt sent"); } CRM_Core_Error::debug_log_message("Success: Database updated"); }
/** * Browse all membership types. * * * @return void * @access public * @static */ function browse() { // get all membership types sorted by weight $membershipType = array(); require_once 'CRM/Member/DAO/MembershipType.php'; $dao =& new CRM_Member_DAO_MembershipType(); $dao->orderBy('weight'); $dao->find(); require_once 'CRM/Utils/Money.php'; while ($dao->fetch()) { $membershipType[$dao->id] = array(); CRM_Core_DAO::storeValues($dao, $membershipType[$dao->id]); // fix the display of the monetary value, CRM-4038 if (CRM_Utils_Array::value('minimum_fee', $membershipType[$dao->id])) { $membershipType[$dao->id]['minimum_fee'] = CRM_Utils_Money::format($membershipType[$dao->id]['minimum_fee'], null, '%a'); } //adding column for relationship type label. CRM-4178. if ($dao->relationship_type_id) { $relationshipName = 'label_' . $dao->relationship_direction; $membershipType[$dao->id]['relationshipTypeName'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $dao->relationship_type_id, $relationshipName); } // form all action links $action = array_sum(array_keys($this->links())); // update enable/disable links depending on if it is is_reserved or is_active if (!isset($dao->is_reserved)) { if ($dao->is_active) { $action -= CRM_Core_Action::ENABLE; } else { $action -= CRM_Core_Action::DISABLE; } $membershipType[$dao->id]['order'] = $membershipType[$dao->id]['weight']; $membershipType[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, array('id' => $dao->id)); } } $returnURL = CRM_Utils_System::url('civicrm/admin/member/membershipType', "reset=1&action=browse"); require_once 'CRM/Utils/Weight.php'; CRM_Utils_Weight::addOrder($membershipType, 'CRM_Member_DAO_MembershipType', 'id', $returnURL); CRM_Member_BAO_MembershipType::convertDayFormat($membershipType); $this->assign('rows', $membershipType); }
/** * handle the values in import mode * * @param int $onDuplicate the code for what action to take on duplicates * @param array $values the array of values belonging to this line * * @return boolean the result of this processing * @access public */ function import($onDuplicate, &$values) { try { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); //assign join date equal to start date if join date is not provided if (!CRM_Utils_Array::value('join_date', $params) && CRM_Utils_Array::value('membership_start_date', $params)) { $params['join_date'] = $params['membership_start_date']; } $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); $formatted = array(); $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params)); // don't add to recent items, CRM-4399 $formatted['skipRecentView'] = TRUE; $dateLabels = array('join_date' => ts('Member Since'), 'membership_start_date' => ts('Start Date'), 'membership_end_date' => ts('End Date')); foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'join_date': case 'membership_start_date': case 'membership_end_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage); } } else { CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage); } break; case 'membership_type_id': if (!is_numeric($val)) { unset($params['membership_type_id']); $params['membership_type'] = $val; } break; case 'status_id': if (!is_numeric($val)) { unset($params['status_id']); $params['membership_status'] = $val; } break; case 'is_override': $params[$key] = CRM_Utils_String::strtobool($val); break; } if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } else { if ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } } } //date-Format part ends static $indieFields = NULL; if ($indieFields == NULL) { $tempIndieFields = CRM_Member_DAO_Membership::import(); $indieFields = $tempIndieFields; } $formatValues = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } $formatValues[$key] = $field; } //format params to meet api v2 requirements. //@todo find a way to test removing this formatting $formatError = $this->membership_format_params($formatValues, $formatted, TRUE); if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, NULL, 'Membership'); } else { //fix for CRM-2219 Update Membership // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) { array_unshift($values, 'Required parameter missing: Status'); return CRM_Import_Parser::ERROR; } if (!empty($formatValues['membership_id'])) { $dao = new CRM_Member_BAO_Membership(); $dao->id = $formatValues['membership_id']; $dates = array('join_date', 'start_date', 'end_date'); foreach ($dates as $v) { if (!CRM_Utils_Array::value($v, $formatted)) { $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v); } } $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership'); if ($dao->find(TRUE)) { $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID')); $newMembership = CRM_Member_BAO_Membership::create($formatted, $ids, TRUE); if (civicrm_error($newMembership)) { array_unshift($values, $newMembership['is_error'] . ' for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } else { $this->_newMemberships[] = $newMembership->id; return CRM_Import_Parser::VALID; } } else { array_unshift($values, 'Matching Membership record not found for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } } } //Format dates $startDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $formatted), '%Y-%m-%d'); $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $formatted), '%Y-%m-%d'); $joinDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $formatted), '%Y-%m-%d'); if ($this->_contactIdIndex < 0) { //retrieve contact id using contact dedupe rule $formatValues['contact_type'] = $this->_contactType; $formatValues['version'] = 3; require_once 'CRM/Utils/DeprecatedUtils.php'; $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) > 1) { array_unshift($values, 'Multiple matching contact records detected for this row. The membership was not imported'); return CRM_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $formatted['contact_id'] = $cid; //fix for CRM-1924 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate); self::formattedDates($calcDates, $formatted); //fix for CRM-3570, exclude the statuses those having is_admin = 1 //now user can import is_admin if is override is true. $excludeIsAdmin = FALSE; if (!CRM_Utils_Array::value('is_override', $formatted)) { $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE; } $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted); if (!CRM_Utils_Array::value('status_id', $formatted)) { $formatted['status_id'] = $calcStatus['id']; } elseif (!CRM_Utils_Array::value('is_override', $formatted)) { if (empty($calcStatus)) { array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.'); return CRM_Import_Parser::ERROR; } elseif ($formatted['status_id'] != $calcStatus['id']) { //Status Hold" is either NOT mapped or is FALSE array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.'); return CRM_Import_Parser::ERROR; } } $newMembership = civicrm_api3('membership', 'create', $formatted); $this->_newMemberships[] = $newMembership['id']; return CRM_Import_Parser::VALID; } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised'); $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); $disp = ''; foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (CRM_Utils_Array::value('external_identifier', $params)) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, 'No matching Contact found for (' . $disp . ')'); return CRM_Import_Parser::ERROR; } } else { if (CRM_Utils_Array::value('external_identifier', $formatValues)) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $formatValues['external_identifier']; $checkCid->find(TRUE); if ($checkCid->id != $formatted['contact_id']) { array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']); return CRM_Import_Parser::ERROR; } } //to calculate dates $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate); self::formattedDates($calcDates, $formatted); //end of date calculation part //fix for CRM-3570, exclude the statuses those having is_admin = 1 //now user can import is_admin if is override is true. $excludeIsAdmin = FALSE; if (!CRM_Utils_Array::value('is_override', $formatted)) { $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE; } $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted); if (!CRM_Utils_Array::value('status_id', $formatted)) { $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus); } elseif (!CRM_Utils_Array::value('is_override', $formatted)) { if (empty($calcStatus)) { array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.'); return CRM_Import_Parser::ERROR; } elseif ($formatted['status_id'] != $calcStatus['id']) { //Status Hold" is either NOT mapped or is FALSE array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.'); return CRM_Import_Parser::ERROR; } } $newMembership = civicrm_api3('membership', 'create', $formatted); $this->_newMemberships[] = $newMembership['id']; return CRM_Import_Parser::VALID; } } catch (Exception $e) { array_unshift($values, $e->getMessage()); return CRM_Import_Parser::ERROR; } }
/** * Process the form submission. * * * @return void */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { CRM_Member_BAO_Membership::del($this->_id); return; } $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus(); $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(); $isTest = $this->_mode == 'test' ? 1 : 0; $lineItems = NULL; if (!empty($this->_lineItem)) { $lineItems = $this->_lineItem; } $config = CRM_Core_Config::singleton(); // get the submitted form values. $this->_params = $formValues = $this->controller->exportValues($this->_name); $this->convertDateFieldsToMySQL($formValues); $params = $softParams = $ids = array(); $membershipTypeValues = array(); foreach ($this->_memTypeSelected as $memType) { $membershipTypeValues[$memType]['membership_type_id'] = $memType; } //take the required membership recur values. if ($this->_mode && !empty($this->_params['auto_renew'])) { $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++; } } // 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); } $isQuickConfig = 0; if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) { $isQuickConfig = 1; } $termsByType = array(); if ($priceSetId) { CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]); if (CRM_Utils_Array::value('tax_amount', $this->_params)) { $params['tax_amount'] = $this->_params['tax_amount']; } $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params); $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues); if (!empty($lineItem[$priceSetId])) { foreach ($lineItem[$priceSetId] as &$li) { if (!empty($li['membership_type_id'])) { if (!empty($li['membership_num_terms'])) { $termsByType[$li['membership_type_id']] = $li['membership_num_terms']; } } ///CRM-11529 for quick config backoffice transactions //when financial_type_id is passed in form, update the //lineitems with the financial type selected in form if ($isQuickConfig && $submittedFinancialType) { $li['financial_type_id'] = $submittedFinancialType; } } } } $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 (empty($params['is_override'])) { $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]); } $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL; $calcDates = array(); foreach ($this->_memTypeSelected as $memType) { if (empty($memTypeNumTerms)) { $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1); } $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms); } foreach ($calcDates as $memType => $calcDate) { foreach (array_keys($dateTypes) 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 ); } } // max related memberships - take from form or inherit from membership type foreach ($this->_memTypeSelected as $memType) { if (array_key_exists('max_related', $formValues)) { $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues); } } 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-13981, allow different person as a soft-contributor of chosen type if ($this->_contributorContactID != $this->_contactID) { $params['contribution_contact_id'] = $this->_contributorContactID; if (!empty($this->_params['soft_credit_type_id'])) { $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id']; $softParams['contact_id'] = $this->_contactID; } } if (!empty($formValues['record_contribution'])) { $recordContribution = array('total_amount', 'financial_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) { if (empty($formValues['source'])) { $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName)); } else { $params['contribution_source'] = $formValues['source']; } } if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) { $params['status_id'] = array_search('Pending', $allMemberStatus); $params['skipStatusCal'] = TRUE; $params['is_pay_later'] = 1; $this->assign('is_pay_later', 1); } if (!empty($formValues['send_receipt'])) { $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues); } //insert financial type name in receipt. $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']); } // process line items, until no previous line items. if (!empty($lineItem)) { $params['lineItems'] = $lineItem; $params['processPriceSet'] = TRUE; } $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 && !$isQuickConfig) { $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'financial_type_id'); } else { $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues); } $this->_paymentProcessor = CRM_Financial_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; //ensure we don't over-write the payer's email with the member's email if ($this->_contributorContactID == $this->_contactID) { $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; } } if ($this->_contributorContactID == $this->_contactID) { //see CRM-12869 for discussion of why we don't do this for separate payee payments CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype); } // add all the additional 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['description'] = ts('Office Credit Card Membership Signup Contribution'); $this->_params['payment_action'] = 'Sale'; $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE)); $this->_params['financial_type_id'] = $params['financial_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 (!empty($this->_params['soft_credit_type_id'])) { $softParams['contact_id'] = $params['contact_id']; $softParams['soft_credit_type_id'] = $this->_params['soft_credit_type_id']; } } if (!empty($this->_params['send_receipt'])) { $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 (!empty($paymentParams['is_recur'])) { $contributionType = new CRM_Financial_DAO_FinancialType(); $contributionType->id = $params['financial_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, TRUE, FALSE, $isTest, $lineItems); //create new soft-credit record, CRM-13981 if ($softParams) { $softParams['contribution_id'] = $contribution->id; $softParams['currency'] = $contribution->currency; $softParams['amount'] = $contribution->total_amount; CRM_Contribute_BAO_ContributionSoft::add($softParams); } $paymentParams['contactID'] = $this->_contactID; $paymentParams['contributionID'] = $contribution->id; $paymentParams['contributionTypeID'] = $contribution->financial_type_id; $paymentParams['contributionPageID'] = $contribution->contribution_page_id; $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id; $ids['contribution'] = $contribution->id; $params['contribution_recur_id'] = $paymentParams['contributionRecurID']; } 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 (!empty($paymentParams['contributionID'])) { CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']); } if (!empty($paymentParams['contributionRecurID'])) { 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']); } // if the payment processor returns a contribution_status_id -> use it! if (isset($result['contribution_status_id'])) { $result['payment_status_id'] = $result['contribution_status_id']; } if (isset($result['payment_status_id'])) { // CRM-16737 $result['contribution_status_id'] is deprecated in favour // of payment_status_id as the payment processor only knows whether the payment is complete // not whether payment completes the contribution $params['contribution_status_id'] = $result['payment_status_id']; } else { $params['contribution_status_id'] = !empty($paymentParams['is_recur']) ? 2 : 1; } if ($params['contribution_status_id'] != array_search('Completed', $allContributionStatus)) { $params['status_id'] = array_search('Pending', $allMemberStatus); $params['skipStatusCal'] = TRUE; // unset send-receipt option, since receipt will be sent when ipn is received. unset($this->_params['send_receipt'], $formValues['send_receipt']); //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; } } } $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 (!empty($this->_params['send_receipt'])) { $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); //CRM-15366 if (!empty($softParams) && empty($paymentParams['is_recur'])) { $membershipParams['soft_credit'] = $softParams; } if (!empty($paymentParams['is_recur']) && CRM_Utils_Array::value('payment_status_id', $result) == 1) { // CRM-16993 we have a situation where line items have already been created. unset($membershipParams['lineItems']); } $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids); $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams); unset($params['lineItems']); $this->_membershipIDs[] = $membership->id; $createdMemberships[$memType] = $membership; $count++; } } else { $params['action'] = $this->_action; if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) { // 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) && !empty($params['contribution_id'])) { $lineItem = array(); $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE); $itemId = key($lineItems); $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id'); $fieldType = NULL; if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) { $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $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; $contributionBAO = new CRM_Contribute_BAO_Contribution(); $contributionBAO->id = $params['contribution_id']; $contributionBAO->contact_id = $params['contact_id']; $contributionBAO->find(); CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership'); //create new soft-credit record, CRM-13981 if ($softParams) { $softParams['contribution_id'] = $params['contribution_id']; while ($contributionBAO->fetch()) { $softParams['currency'] = $contributionBAO->currency; $softParams['amount'] = $contributionBAO->total_amount; } CRM_Contribute_BAO_ContributionSoft::add($softParams); } } //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; if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) { $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 && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) { $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution; } $membershipParams = array_merge($params, $membershipTypeValues[$memType]); if (!empty($formValues['int_amount'])) { $init_amount = array(); foreach ($formValues as $key => $value) { if (strstr($key, 'txt-price')) { $init_amount[$key] = $value; } } $membershipParams['init_amount'] = $init_amount; } if (!empty($softParams)) { $membershipParams['soft_credit'] = $softParams; } $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids); $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams); unset($params['lineItems']); $this->_membershipIDs[] = $membership->id; $createdMemberships[$memType] = $membership; $count++; } } } if (!empty($lineItem[$priceSetId])) { $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); $taxAmount = FALSE; $totalTaxAmount = 0; foreach ($lineItem[$priceSetId] as &$priceFieldOp) { if (!empty($priceFieldOp['membership_type_id'])) { $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-'; $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-'; } else { $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A'; } if ($invoicing && isset($priceFieldOp['tax_amount'])) { $taxAmount = TRUE; $totalTaxAmount += $priceFieldOp['tax_amount']; } } if ($invoicing) { $dataArray = array(); foreach ($lineItem[$priceSetId] as $key => $value) { if (isset($value['tax_amount']) && isset($value['tax_rate'])) { if (isset($dataArray[$value['tax_rate']])) { $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value); } else { $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value); } } } if ($taxAmount) { $this->assign('totalTaxAmount', $totalTaxAmount); $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings)); } $this->assign('dataArray', $dataArray); } } $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE); $receiptSend = FALSE; $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id); $membershipIds = $this->_membershipIDs; if ($contributionId && !empty($membershipIds)) { $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs); if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') { $receiptSend = TRUE; } } if (!empty($formValues['send_receipt']) && $receiptSend) { $formValues['contact_id'] = $this->_contactID; $formValues['contribution_id'] = $contributionId; // 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 && empty($params['is_recur'])) { $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 && !empty($mailSend)) { $statusMsg .= ' ' . 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, ts('Complete'), 'success'); $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}")); } }
function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) { $contribution =& $objects['contribution']; $memberships =& $objects['membership']; if (is_numeric($memberships)) { $memberships = array($objects['membership']); } $participant =& $objects['participant']; $event =& $objects['event']; $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now); $recurContrib =& $objects['contributionRecur']; $values = array(); if ($input['component'] == 'contribute') { if ($contribution->contribution_page_id) { CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values); $source = ts('Online Contribution') . ': ' . $values['title']; } elseif ($recurContrib->id) { $contribution->contribution_page_id = NULL; $values['amount'] = $recurContrib->amount; $values['contribution_type_id'] = $objects['contributionType']->id; $values['title'] = $source = ts('Offline Recurring Contribution'); $values['is_email_receipt'] = $recurContrib->is_email_receipt; $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $values['receipt_from_name'] = $domainValues[0]; $values['receipt_from_email'] = $domainValues[1]; } $contribution->source = $source; if (CRM_Utils_Array::value('is_email_receipt', $values)) { $contribution->receipt_date = self::$_now; } if (!empty($memberships)) { foreach ($memberships as $membershipTypeIdKey => $membership) { if ($membership) { $format = '%Y%m%d'; $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id); // CRM-8141 update the membership type with the value recorded in log when membership created/renewed // this picks up membership type changes during renewals $sql = "\nSELECT membership_type_id\nFROM civicrm_membership_log\nWHERE membership_id={$membership->id}\nORDER BY id DESC\nLIMIT 1;"; $dao = new CRM_Core_DAO(); $dao->query($sql); if ($dao->fetch()) { if (!empty($dao->membership_type_id)) { $membership->membership_type_id = $dao->membership_type_id; $membership->save(); } // else fall back to using current membership type } // else fall back to using current membership type $dao->free(); if ($currentMembership) { /* * Fixed FOR CRM-4433 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status * when Contribution mode is notify and membership is for renewal ) */ CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday); $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday); $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); } else { $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id); } //get the status for membership. $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE); $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format), 'reminder_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('reminder_date', $dates), $format)); //we might be renewing membership, //so make status override false. $formatedParams['is_override'] = FALSE; $membership->copyValues($formatedParams); $membership->save(); //updating the membership log $membershipLog = array(); $membershipLog = $formatedParams; $logStartDate = $formatedParams['start_date']; if (CRM_Utils_Array::value('log_start_date', $dates)) { $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate); } $membershipLog['start_date'] = $logStartDate; $membershipLog['membership_id'] = $membership->id; $membershipLog['modified_id'] = $membership->contact_id; $membershipLog['modified_date'] = date('Ymd'); $membershipLog['membership_type_id'] = $membership->membership_type_id; CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); //update related Memberships. CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams); //update the membership type key of membership relatedObjects array //if it has changed after membership update if ($membershipTypeIdKey != $membership->membership_type_id) { $memberships[$membership->membership_type_id] = $membership; $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership; unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]); unset($memberships[$membershipTypeIdKey]); } } } } } else { // event $eventParams = array('id' => $objects['event']->id); $values['event'] = array(); CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); $eventParams = array('id' => $objects['event']->id); $values['event'] = array(); CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); //get location details $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event'); $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent'); list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $values['custom_pre_id'] = $custom_pre_id; $values['custom_post_id'] = $custom_post_ids; $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title']; if ($values['event']['is_email_confirm']) { $contribution->receipt_date = self::$_now; $values['is_email_receipt'] = 1; } $participant->status_id = 1; $participant->save(); } if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) { $input['net_amount'] = $input['amount'] - $input['fee_amount']; } $addLineItems = FALSE; if (empty($contribution->id)) { $addLineItems = TRUE; } $contribution->contribution_status_id = 1; $contribution->is_test = $input['is_test']; $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0); $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0); $contribution->trxn_id = $input['trxn_id']; $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date); $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date); $contribution->cancel_date = 'null'; if (CRM_Utils_Array::value('check_number', $input)) { $contribution->check_number = $input['check_number']; } if (CRM_Utils_Array::value('payment_instrument_id', $input)) { $contribution->payment_instrument_id = $input['payment_instrument_id']; } $contribution->save(); //add lineitems for recurring payments if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) { $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id); } // next create the transaction record $paymentProcessor = ''; if (isset($objects['paymentProcessor'])) { if (is_array($objects['paymentProcessor'])) { $paymentProcessor = $objects['paymentProcessor']['payment_processor_type']; } else { $paymentProcessor = $objects['paymentProcessor']->payment_processor_type; } } if ($contribution->trxn_id) { $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => isset($input['trxn_date']) ? $input['trxn_date'] : self::$_now, 'trxn_type' => 'Debit', 'total_amount' => $input['amount'], 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => $paymentProcessor, 'trxn_id' => $contribution->trxn_id); $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); } self::updateRecurLinkedPledge($contribution); // create an activity record if ($input['component'] == 'contribute') { //CRM-4027 $targetContactID = NULL; if (CRM_Utils_Array::value('related_contact', $ids)) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $ids['related_contact']; } CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); // event } else { CRM_Activity_BAO_Activity::addActivity($participant); } CRM_Core_Error::debug_log_message("Contribution record updated successfully"); $transaction->commit(); // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) { self::sendMail($input, $ids, $objects, $values, $recur, FALSE); } CRM_Core_Error::debug_log_message("Success: Database updated and mail sent"); }
/** * Browse all custom data groups. * * @param string $action the action to be invoked * * @return void * @access public */ function browse($action = NULL) { // get all custom groups sorted by weight $customGroup = array(); $dao = new CRM_Core_DAO_CustomGroup(); $dao->orderBy('weight, title'); $dao->find(); while ($dao->fetch()) { $customGroup[$dao->id] = array(); CRM_Core_DAO::storeValues($dao, $customGroup[$dao->id]); // form all action links $action = array_sum(array_keys($this->actionLinks())); // update enable/disable links depending on custom_group properties. if ($dao->is_active) { $action -= CRM_Core_Action::ENABLE; } else { $action -= CRM_Core_Action::DISABLE; } $customGroup[$dao->id]['order'] = $customGroup[$dao->id]['weight']; $customGroup[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id)); } $customGroupExtends = CRM_Core_SelectValues::customGroupExtends(); foreach ($customGroup as $key => $array) { CRM_Core_DAO_CustomGroup::addDisplayEnums($customGroup[$key]); $customGroup[$key]['extends_display'] = $customGroupExtends[$customGroup[$key]['extends']]; } //fix for Displaying subTypes $subTypes = array(); $subTypes['Activity'] = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE); $subTypes['Contribution'] = CRM_Contribute_PseudoConstant::contributionType(); $subTypes['Membership'] = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE); $subTypes['Event'] = CRM_Core_OptionGroup::values('event_type'); $subTypes['Grant'] = CRM_Core_OptionGroup::values('grant_type'); $subTypes['Campaign'] = CRM_Campaign_PseudoConstant::campaignType(); $subTypes['Participant'] = array(); $subTypes['ParticipantRole'] = CRM_Core_OptionGroup::values('participant_role'); $subTypes['ParticipantEventName'] = CRM_Event_PseudoConstant::event(); $subTypes['ParticipantEventType'] = CRM_Core_OptionGroup::values('event_type'); $subTypes['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL); $subTypes['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL); $subTypes['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL); $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual'); $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization'); $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household'); $allRelationshipType = array(); $allRelationshipType = array_merge($relTypeInd, $relTypeOrg); $allRelationshipType = array_merge($allRelationshipType, $relTypeHou); //adding subtype specific relationships CRM-5256 $relSubType = CRM_Contact_BAO_ContactType::subTypeInfo(); foreach ($relSubType as $subType => $val) { $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType); $allRelationshipType = array_merge($allRelationshipType, $subTypeRelationshipTypes); } $subTypes['Relationship'] = $allRelationshipType; $cSubTypes = CRM_Core_Component::contactSubTypes(); $contactSubTypes = array(); foreach ($cSubTypes as $key => $value) { $contactSubTypes[$key] = $key; } $subTypes['Contact'] = $contactSubTypes; CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($subTypes); foreach ($customGroup as $key => $values) { $subValue = CRM_Utils_Array::value('extends_entity_column_value', $customGroup[$key]); $subName = CRM_Utils_Array::value('extends_entity_column_id', $customGroup[$key]); $type = CRM_Utils_Array::value('extends', $customGroup[$key]); if ($subValue) { $subValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($subValue, 1, -1)); $colValue = NULL; foreach ($subValue as $sub) { if ($sub) { if ($type == 'Participant') { if ($subName == 1) { $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantRole'][$sub] : $subTypes['ParticipantRole'][$sub]; } elseif ($subName == 2) { $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventName'][$sub] : $subTypes['ParticipantEventName'][$sub]; } elseif ($subName == 3) { $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventType'][$sub] : $subTypes['ParticipantEventType'][$sub]; } } elseif ($type == 'Relationship') { $colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_a_b'] : $subTypes[$type][$sub . '_a_b']; if (isset($subTypes[$type][$sub . '_b_a'])) { $colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_b_a'] : $subTypes[$type][$sub . '_b_a']; } } else { $colValue = $colValue ? $colValue . (isset($subTypes[$type][$sub]) ? ', ' . $subTypes[$type][$sub] : '') : (isset($subTypes[$type][$sub]) ? $subTypes[$type][$sub] : ''); } } } $customGroup[$key]["extends_entity_column_value"] = $colValue; } else { if (is_array(CRM_Utils_Array::value($type, $subTypes))) { $customGroup[$key]["extends_entity_column_value"] = ts("Any"); } } } $returnURL = CRM_Utils_System::url('civicrm/admin/custom/group', "reset=1&action=browse"); CRM_Utils_Weight::addOrder($customGroup, 'CRM_Core_DAO_CustomGroup', 'id', $returnURL); $this->assign('rows', $customGroup); }
/** * handle the values in import mode * * @param int $onDuplicate the code for what action to take on duplicates * @param array $values the array of values belonging to this line * * @return boolean the result of this processing * @access public */ function import($onDuplicate, &$values) { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Member_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); //assign join date equal to start date if join date is not provided if (!$params['join_date'] && $params['membership_start_date']) { $params['join_date'] = $params['membership_start_date']; } $session =& CRM_Core_Session::singleton(); $dateType = $session->get("dateTypes"); $formatted = array(); $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params)); // don't add to recent items, CRM-4399 $formatted['skipRecentView'] = true; foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'join_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('Join Date', $errorMessage); } break; case 'membership_start_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage); } break; case 'membership_end_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage); } } else { CRM_Import_Parser_Contact::addToErrorMsg('End Date', $errorMessage); } break; case 'is_override': $params[$key] = CRM_Utils_String::strtobool($val); break; } if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID][2] == 'Date') { CRM_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } else { if ($customFields[$customFieldID][2] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } } } //date-Format part ends static $indieFields = null; if ($indieFields == null) { require_once 'CRM/Member/DAO/Membership.php'; $tempIndieFields =& CRM_Member_DAO_Membership::import(); $indieFields = $tempIndieFields; } $formatValues = array(); foreach ($params as $key => $field) { if ($field == null || $field === '') { continue; } $formatValues[$key] = $field; } $formatError = _civicrm_membership_formatted_param($formatValues, $formatted, true); if ($formatError) { array_unshift($values, $formatError['error_message']); return CRM_Member_Import_Parser::ERROR; } if ($onDuplicate != CRM_Member_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, null, 'Membership'); } else { //fix for CRM-2219 Update Membership // onDuplicate == CRM_Member_Import_Parser::DUPLICATE_UPDATE if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) { array_unshift($values, "Required parameter missing: Status"); return CRM_Member_Import_Parser::ERROR; } if ($formatValues['membership_id']) { require_once 'CRM/Member/BAO/Membership.php'; $dao = new CRM_Member_BAO_Membership(); $dao->id = $formatValues['membership_id']; $dates = array('join_date', 'start_date', 'end_date'); foreach ($dates as $v) { if (!$formatted[$v]) { $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v); } } $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership'); if ($dao->find(true)) { $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID')); $newMembership =& CRM_Member_BAO_Membership::create($formatted, $ids, true); if (civicrm_error($newMembership)) { array_unshift($values, $newMembership['is_error'] . " for Membership ID " . $formatValues['membership_id'] . ". Row was skipped."); return CRM_Member_Import_Parser::ERROR; } else { $this->_newMemberships[] = $newMembership->id; return CRM_Member_Import_Parser::VALID; } } else { array_unshift($values, "Matching Membership record not found for Membership ID " . $formatValues['membership_id'] . ". Row was skipped."); return CRM_Member_Import_Parser::ERROR; } } } //Format dates $startDate = CRM_Utils_Date::customFormat($formatted['start_date'], '%Y-%m-%d'); $endDate = CRM_Utils_Date::customFormat($formatted['end_date'], '%Y-%m-%d'); $joinDate = CRM_Utils_Date::customFormat($formatted['join_date'], '%Y-%m-%d'); if ($this->_contactIdIndex < 0) { //retrieve contact id using contact dedupe rule $formatValues['contact_type'] = $this->_contactType; $error = civicrm_check_contact_dedupe($formatValues); if (civicrm_duplicate($error)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) > 1) { array_unshift($values, "Multiple matching contact records detected for this row. The membership was not imported"); return CRM_Member_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $formatted['contact_id'] = $cid; //fix for CRM-1924 require_once 'CRM/Member/BAO/MembershipStatus.php'; require_once 'CRM/Member/BAO/MembershipType.php'; require_once 'CRM/Member/PseudoConstant.php'; $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate); self::formattedDates($calcDates, $formatted); //fix for CRM-3570, exclude the statuses those having is_admin = 1 //now user can import is_admin if is override is true. $excludeIsAdmin = false; if (!CRM_Utils_Array::value('is_override', $formatted)) { $formatted['exclude_is_admin'] = $excludeIsAdmin = true; } $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin); if (!$formatted['status_id']) { $formatted['status_id'] = $calcStatus['id']; } elseif (!CRM_Utils_Array::value('is_override', $formatted)) { if (empty($calcStatus)) { array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules. Record was not imported."); return CRM_Member_Import_Parser::ERROR; } else { if ($formatted['status_id'] != $calcStatus['id']) { //Status Hold" is either NOT mapped or is FALSE array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules (" . $calcStatus['name'] . "). Record was not imported."); return CRM_Member_Import_Parser::ERROR; } } } $newMembership = civicrm_contact_membership_create($formatted); if (civicrm_error($newMembership)) { array_unshift($values, $newMembership['error_message']); return CRM_Member_Import_Parser::ERROR; } $this->_newMemberships[] = $newMembership['id']; return CRM_Member_Import_Parser::VALID; } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'level' => 'Strict'); require_once 'CRM/Dedupe/BAO/Rule.php'; $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (CRM_Utils_Array::value('external_identifier', $params)) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, "No matching Contact found for (" . $disp . ")"); return CRM_Member_Import_Parser::ERROR; } } else { if ($formatValues['external_identifier']) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $formatValues['external_identifier']; $checkCid->find(true); if ($checkCid->id != $formatted['contact_id']) { array_unshift($values, "Mismatch of External identifier :" . $formatValues['external_identifier'] . " and Contact Id:" . $formatted['contact_id']); return CRM_Member_Import_Parser::ERROR; } } //to calculate dates require_once 'CRM/Member/BAO/MembershipType.php'; $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate); self::formattedDates($calcDates, $formatted); //end of date calculation part //fix for CRM-3570, exclude the statuses those having is_admin = 1 //now user can import is_admin if is override is true. $excludeIsAdmin = false; if (!CRM_Utils_Array::value('is_override', $formatted)) { $formatted['exclude_is_admin'] = $excludeIsAdmin = true; } require_once 'CRM/Member/BAO/MembershipStatus.php'; $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin); if (!$formatted['status_id']) { $formatted['status_id'] = $calcStatus['id']; } else { if (!CRM_Utils_Array::value('is_override', $formatted)) { if (empty($calcStatus)) { array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules. Record was not imported."); return CRM_Member_Import_Parser::ERROR; } else { if ($formatted['status_id'] != $calcStatus['id']) { //Status Hold" is either NOT mapped or is FALSE array_unshift($values, "Status in import row (" . $formatValues['status_id'] . ") does not match calculated status based on your configured Membership Status Rules (" . $calcStatus['name'] . "). Record was not imported."); return CRM_Member_Import_Parser::ERROR; } } } } $newMembership = civicrm_contact_membership_create($formatted); if (civicrm_error($newMembership)) { array_unshift($values, $newMembership['error_message']); return CRM_Member_Import_Parser::ERROR; } $this->_newMemberships[] = $newMembership['id']; return CRM_Member_Import_Parser::VALID; } }
/** * This method will renew / create the membership depending on * whether the given contact has membership or not. And will add * the modified dates for mebership and in the log table. * * @param int $contactID id of the contact * @param int $membershipTypeID id of the membership type * @param boolean $is_test if this is test contribution or live contribution * @param object $form form object * @param array $ipnParams array of name value pairs, to be used (for e.g source) when $form not present * @param int $modifiedID individual contact id in case of On Behalf signup (CRM-4027 ) * * @return object $membership object of membership * * @static * @access public * **/ static function renewMembership($contactID, $membershipTypeID, $is_test, &$form, $changeToday = null, $modifiedID = null) { require_once 'CRM/Utils/Hook.php'; $statusFormat = '%Y-%m-%d'; $format = '%Y%m%d'; $ids = array(); //get all active statuses of membership. require_once 'CRM/Member/PseudoConstant.php'; $allStatus = CRM_Member_PseudoConstant::membershipStatus(); // check is it pending. - CRM-4555 $pending = false; if (($form->_contributeMode == 'notify' || $form->_params['is_pay_later'] || $form->_params['is_recur'] && $form->_contributeMode == 'direct') && ($form->_values['is_monetary'] && $form->_amount > 0.0)) { $pending = true; } //decide status here, if needed. $updateStatusId = null; if ($currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID, $is_test, $form->_membershipId)) { $activityType = 'Membership Renewal'; $form->set("renewal_mode", true); // Do NOT do anything. //1. membership with status : PENDING/CANCELLED (CRM-2395) //2. Paylater/IPN renew. CRM-4556. if ($pending || in_array($currentMembership['status_id'], array(array_search('Pending', $allStatus), array_search('Cancelled', $allStatus)))) { $membership = new CRM_Member_DAO_Membership(); $membership->id = $currentMembership['id']; $membership->find(true); return $membership; } //we might renew expired membership, CRM-6277 if (!$changeToday) { if ($form->get('renewDate')) { $changeToday = $form->get('renewDate'); } else { if (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') { $changeToday = date('YmdHis'); } } } // Check and fix the membership if it is STALE self::fixMembershipStatusBeforeRenew($currentMembership, $changeToday); // Now Renew the membership if (!$currentMembership['is_current_member']) { // membership is not CURRENT $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'], $changeToday); $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); $currentMembership['start_date'] = CRM_Utils_Array::value('start_date', $dates); $currentMembership['end_date'] = CRM_Utils_Array::value('end_date', $dates); $currentMembership['reminder_date'] = CRM_Utils_Array::value('reminder_date', $dates); $currentMembership['is_test'] = $is_test; if ($form->_params['membership_source']) { $currentMembership['source'] = $form->_params['membership_source']; } else { if ($form->_values['title']) { $currentMembership['source'] = ts('Online Contribution:') . ' ' . $form->_values['title']; } else { $currentMembership['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $currentMembership['id'], 'source'); } } if (CRM_Utils_Array::value('id', $currentMembership)) { $ids['membership'] = $currentMembership['id']; } $memParams = $currentMembership; //set the log start date. $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); } else { // CURRENT Membership $membership = new CRM_Member_DAO_Membership(); $membership->id = $currentMembership['id']; $membership->find(true); require_once 'CRM/Member/BAO/MembershipType.php'; $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday); // Insert renewed dates for CURRENT membership $memParams = array(); $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date); $memParams['start_date'] = CRM_Utils_Date::isoToMysql($membership->start_date); $memParams['end_date'] = CRM_Utils_Array::value('end_date', $dates); $memParams['reminder_date'] = CRM_Utils_Array::value('reminder_date', $dates); //set the log start date. $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); if (empty($membership->source)) { if (CRM_Utils_Array::value('membership_source', $form->_params)) { $currentMembership['source'] = $form->_params['membership_source']; } else { if (CRM_Utils_Array::value('title', $form->_values)) { $currentMembership['source'] = ts('Online Contribution:') . ' ' . $form->_values['title']; } else { $currentMembership['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $currentMembership['id'], 'source'); } } } if (CRM_Utils_Array::value('id', $currentMembership)) { $ids['membership'] = $currentMembership['id']; } } //CRM-4555 if ($pending) { $updateStatusId = array_search('Pending', $allStatus); } } else { // NEW Membership $activityType = 'Membership Signup'; $memParams = array('contact_id' => $contactID, 'membership_type_id' => $membershipTypeID); if (!$pending) { require_once 'CRM/Member/BAO/MembershipType.php'; $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID); $memParams['join_date'] = CRM_Utils_Array::value('join_date', $dates); $memParams['start_date'] = CRM_Utils_Array::value('start_date', $dates); $memParams['end_date'] = CRM_Utils_Array::value('end_date', $dates); $memParams['reminder_date'] = CRM_Utils_Array::value('reminder_date', $dates); require_once 'CRM/Member/BAO/MembershipStatus.php'; $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'], $statusFormat), CRM_Utils_Date::customFormat($dates['end_date'], $statusFormat), CRM_Utils_Date::customFormat($dates['join_date'], $statusFormat), 'today', true); $updateStatusId = CRM_Utils_Array::value('id', $status); } else { // if IPN/Pay-Later set status to: PENDING $updateStatusId = array_search('Pending', $allStatus); } if (CRM_Utils_Array::value('membership_source', $form->_params)) { $memParams['source'] = $form->_params['membership_source']; } else { $memParams['source'] = ts('Online Contribution:') . ' ' . $form->_values['title']; } $memParams['contribution_recur_id'] = CRM_Utils_Array::value('contributionRecurID', $form->_params); $memParams['is_test'] = $is_test; $memParams['is_pay_later'] = $form->_params['is_pay_later']; } //CRM-4555 //if we decided status here and want to skip status //calculation in create( ); than need to pass 'skipStatusCal'. if ($updateStatusId) { $memParams['status_id'] = $updateStatusId; $memParams['skipStatusCal'] = true; } //since we are renewing, //make status override false. $memParams['is_override'] = false; //CRM-4027, create log w/ individual contact. if ($modifiedID) { $ids['userId'] = $modifiedID; $memParams['is_for_organization'] = true; } else { $ids['userId'] = $contactID; } $membership =& self::create($memParams, $ids, false, $activityType); // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072 $membership->find(true); if (!empty($dates)) { $form->assign('mem_start_date', CRM_Utils_Date::customFormat($dates['start_date'], $format)); $form->assign('mem_end_date', CRM_Utils_Date::customFormat($dates['end_date'], $format)); } return $membership; }
/** * Function to retrieve organization and associated membership * types * * @return array * arrays of organization and membership types * */ public static function getMembershipTypeInfo() { if (!self::$_membershipTypeInfo) { $orgs = $types = array(); $query = 'SELECT memType.id, memType.name, memType.member_of_contact_id, c.sort_name FROM civicrm_membership_type memType INNER JOIN civicrm_contact c ON c.id = memType.member_of_contact_id WHERE memType.is_active = 1 '; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $orgs[$dao->member_of_contact_id] = $dao->sort_name; $types[$dao->member_of_contact_id][$dao->id] = $dao->name; } self::$_membershipTypeInfo = array($orgs, $types); } return self::$_membershipTypeInfo; }
/** * Set variables up before form is built. * * @return void */ public function preProcess() { $values = array(); $id = CRM_Utils_Request::retrieve('id', 'Positive', $this); // Make sure context is assigned to template for condition where we come here view civicrm/membership/view $context = CRM_Utils_Request::retrieve('context', 'String', $this); $this->assign('context', $context); if ($id) { $params = array('id' => $id); CRM_Member_BAO_Membership::retrieve($params, $values); $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($values['membership_type_id']); // Do the action on related Membership if needed $relAction = CRM_Utils_Request::retrieve('relAction', 'String', $this); if ($relAction) { $this->relAction($relAction, $values); } // build associated contributions $this->assign('accessContribution', FALSE); if (CRM_Core_Permission::access('CiviContribute')) { $this->assign('accessContribution', TRUE); CRM_Member_Page_Tab::associatedContribution($values['contact_id'], $id); } //Provide information about membership source when it is the result of a relationship (CRM-1901) $values['owner_membership_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $id, 'owner_membership_id'); if (isset($values['owner_membership_id'])) { $values['owner_contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $values['owner_membership_id'], 'contact_id', 'id'); $values['owner_display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $values['owner_contact_id'], 'display_name', 'id'); $direction = strrev($membershipType['relationship_direction']); // To display relationship type in view membership page $relTypeIds = str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ",", $membershipType['relationship_type_id']); $sql = "\nSELECT relationship_type_id,\n CASE\n WHEN contact_id_a = {$values['owner_contact_id']} AND contact_id_b = {$values['contact_id']} THEN 'b_a'\n WHEN contact_id_b = {$values['owner_contact_id']} AND contact_id_a = {$values['contact_id']} THEN 'a_b'\nEND AS 'relType'\n FROM civicrm_relationship\n WHERE relationship_type_id IN ({$relTypeIds})"; $dao = CRM_Core_DAO::executeQuery($sql); $values['relationship'] = NULL; while ($dao->fetch()) { $typeId = $dao->relationship_type_id; $direction = $dao->relType; if ($direction && $typeId) { if ($values['relationship']) { $values['relationship'] .= ','; } $values['relationship'] .= CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $typeId, "name_{$direction}", 'id'); } } } $this->assign('has_related', FALSE); // if membership can be granted, and we are the owner of the membership if (!empty($membershipType['relationship_type_id']) && empty($values['owner_membership_id'])) { // display related contacts/membership block $this->assign('has_related', TRUE); $this->assign('max_related', CRM_Utils_Array::value('max_related', $values, ts('Unlimited'))); // split the relations in 2 arrays based on direction $relTypeId = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']); $relDirection = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']); foreach ($relTypeId as $rid) { $dir = each($relDirection); $relTypeDir[substr($dir['value'], 0, 1)][] = $rid; } // build query in 2 parts with a UNION if necessary // _x and _y are replaced with _a and _b first, then vice-versa // comment is a qualifier for the relationship - now just job_title $select = "\nSELECT r.id, c.id as cid, c.display_name as name, c.job_title as comment,\n rt.name_x_y as relation, r.start_date, r.end_date,\n m.id as mid, ms.is_current_member, ms.label as status\n FROM civicrm_relationship r\n LEFT JOIN civicrm_relationship_type rt ON rt.id = r.relationship_type_id\n LEFT JOIN civicrm_contact c ON c.id = r.contact_id_x\n LEFT JOIN civicrm_membership m ON (m.owner_membership_id = {$values['id']}\n AND m.contact_id = r.contact_id_x AND m.is_test = 0)\n LEFT JOIN civicrm_membership_status ms ON ms.id = m.status_id\n WHERE r.contact_id_y = {$values['contact_id']} AND r.is_active = 1 AND c.is_deleted = 0"; $query = ''; foreach (array('a', 'b') as $dir) { if (isset($relTypeDir[$dir])) { $query .= ($query ? ' UNION ' : '') . str_replace('_y', '_' . $dir, str_replace('_x', '_' . ($dir == 'a' ? 'b' : 'a'), $select)) . ' AND r.relationship_type_id IN (' . implode(',', $relTypeDir[$dir]) . ')'; } } $query .= " ORDER BY is_current_member DESC"; $dao = CRM_Core_DAO::executeQuery($query); $related = array(); $relatedRemaining = CRM_Utils_Array::value('max_related', $values, PHP_INT_MAX); $rowElememts = array('id', 'cid', 'name', 'comment', 'relation', 'mid', 'start_date', 'end_date', 'is_current_member', 'status'); while ($dao->fetch()) { $row = array(); foreach ($rowElememts as $field) { $row[$field] = $dao->{$field}; } if ($row['mid'] && $row['is_current_member'] == 1) { $relatedRemaining--; $row['action'] = CRM_Core_Action::formLink(self::links(), CRM_Core_Action::DELETE, array('id' => CRM_Utils_Request::retrieve('id', 'Positive', $this), 'cid' => $row['cid'], 'mid' => $row['mid']), ts('more'), FALSE, 'membership.relationship.action', 'Relationship', CRM_Utils_Request::retrieve('id', 'Positive', $this)); } else { if ($relatedRemaining > 0) { $row['action'] = CRM_Core_Action::formLink(self::links(), CRM_Core_Action::ADD, array('id' => CRM_Utils_Request::retrieve('id', 'Positive', $this), 'cid' => $row['cid'], 'rid' => $row['cid']), ts('more'), FALSE, 'membership.relationship.action', 'Relationship', CRM_Utils_Request::retrieve('id', 'Positive', $this)); } } $related[] = $row; } $this->assign('related', $related); if ($relatedRemaining <= 0) { $this->assign('related_text', ts('None available')); } else { if ($relatedRemaining < 100000) { $this->assign('related_text', ts('%1 available', array(1 => $relatedRemaining))); } else { $this->assign('related_text', ts('Unlimited', array(1 => $relatedRemaining))); } } } $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']); $this->assign('displayName', $displayName); // Check if this is default domain contact CRM-10482 if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) { $displayName .= ' (' . ts('default organization') . ')'; } // omitting contactImage from title for now since the summary overlay css doesn't work outside crm-container CRM_Utils_System::setTitle(ts('View Membership for') . ' ' . $displayName); // add viewed membership to recent items list $recentTitle = $displayName . ' - ' . ts('Membership Type:') . ' ' . $values['membership_type']; $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); $recentOther = array(); if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) { $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); } if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) { $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"); } CRM_Utils_Recent::add($recentTitle, $url, $values['id'], 'Membership', $values['contact_id'], NULL, $recentOther); CRM_Member_Page_Tab::setContext($this, $values['contact_id']); $memType = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $id, "membership_type_id"); $groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $id, 0, $memType); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); $isRecur = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $id, 'contribution_recur_id'); $autoRenew = $isRecur ? TRUE : FALSE; } if (!empty($values['is_test'])) { $values['membership_type'] .= ' (test) '; } $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($id); $values['auto_renew'] = $autoRenew && !$subscriptionCancelled ? 'Yes' : 'No'; //do check for campaigns if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) { $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId); $values['campaign'] = $campaigns[$campaignId]; } $this->assign($values); }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { $config = CRM_Core_Config::singleton(); $session = CRM_Core_Session::singleton(); // current contribution page id $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this); if (!$this->_id) { // seems like the session is corrupted and/or we lost the id trail // lets just bump this to a regular session error and redirect user to main page $this->controller->invalidKeyRedirect(); } // this was used prior to the cleverer this_>getContactID - unsure now $this->_userID = $session->get('userID'); $this->_contactID = $this->_membershipContactID = $this->getContactID(); $this->_mid = NULL; if ($this->_contactID) { $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this); if ($this->_mid) { $membership = new CRM_Member_DAO_Membership(); $membership->id = $this->_mid; if ($membership->find(TRUE)) { $this->_defaultMemTypeId = $membership->membership_type_id; if ($membership->contact_id != $this->_contactID) { $validMembership = FALSE; $employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($this->_userID); if (!empty($employers) && array_key_exists($membership->contact_id, $employers)) { $this->_membershipContactID = $membership->contact_id; $this->assign('membershipContactID', $this->_membershipContactID); $this->assign('membershipContactName', $employers[$this->_membershipContactID]['name']); $validMembership = TRUE; } else { $membershipType = new CRM_Member_BAO_MembershipType(); $membershipType->id = $membership->membership_type_id; if ($membershipType->find(TRUE)) { // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values. // Convert to commma separated list. $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ','); $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id); if (array_key_exists($membership->contact_id, $permContacts)) { $this->_membershipContactID = $membership->contact_id; $validMembership = TRUE; } } } if (!$validMembership) { CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert'); } } } else { CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert'); } unset($membership); } } // we do not want to display recently viewed items, so turn off $this->assign('displayRecent', FALSE); // Contribution page values are cleared from session, so can't use normal Printer Friendly view. // Use Browser Print instead. $this->assign('browserPrint', TRUE); // action $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add'); $this->assign('action', $this->_action); // current mode $this->_mode = $this->_action == 1024 ? 'test' : 'live'; $this->_values = $this->get('values'); $this->_fields = $this->get('fields'); $this->_bltID = $this->get('bltID'); $this->_paymentProcessor = $this->get('paymentProcessor'); $this->_priceSetId = $this->get('priceSetId'); $this->_priceSet = $this->get('priceSet'); if (!$this->_values) { // get all the values from the dao object $this->_values = array(); $this->_fields = array(); CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values); // check if form is active if (!CRM_Utils_Array::value('is_active', $this->_values)) { // form is inactive, die a fatal death CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.')); } // also check for billing informatin // get the billing location type $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate'); // CRM-8108 remove ts around Billing location type //$this->_bltID = array_search( ts('Billing'), $locationTypes ); $this->_bltID = array_search('Billing', $locationTypes); if (!$this->_bltID) { CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing'))); } $this->set('bltID', $this->_bltID); // check for is_monetary status $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values); $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_values); //FIXME: to support multiple payment processors if ($isMonetary && (!$isPayLater || CRM_Utils_Array::value('payment_processor', $this->_values))) { $ppID = CRM_Utils_Array::value('payment_processor', $this->_values); if (!$ppID) { CRM_Core_Error::fatal(ts('A payment processor must be selected for this contribution page (contact the site administrator for assistance).')); } $ppIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ppID); $this->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPayments($ppIds, $this->_mode); $this->set('paymentProcessors', $this->_paymentProcessors); //set default payment processor if (!empty($this->_paymentProcessors) && empty($this->_paymentProcessor)) { foreach ($this->_paymentProcessors as $ppId => $values) { if ($values['is_default'] == 1 || count($this->_paymentProcessors) == 1) { $defaultProcessorId = $ppId; break; } } } if (isset($defaultProcessorId)) { $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($defaultProcessorId, $this->_mode); $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor); } if (!CRM_Utils_System::isNull($this->_paymentProcessors)) { foreach ($this->_paymentProcessors as $eachPaymentProcessor) { // check selected payment processor is active if (empty($eachPaymentProcessor)) { CRM_Core_Error::fatal(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).')); } // ensure that processor has a valid config $this->_paymentObject =& CRM_Core_Payment::singleton($this->_mode, $eachPaymentProcessor, $this); $error = $this->_paymentObject->checkConfig(); if (!empty($error)) { CRM_Core_Error::fatal($error); } } } } // get price info // CRM-5095 CRM_Price_BAO_PriceSet::initSet($this, $this->_id, 'civicrm_contribution_page'); // this avoids getting E_NOTICE errors in php $setNullFields = array('amount_block_is_active', 'honor_block_is_active', 'is_allow_other_amount', 'footer_text'); foreach ($setNullFields as $f) { if (!isset($this->_values[$f])) { $this->_values[$f] = NULL; } } //check if Membership Block is enabled, if Membership Fields are included in profile //get membership section for this contribution page $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id); $this->set('membershipBlock', $this->_membershipBlock); if ($this->_values['custom_pre_id']) { $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']); } if ($this->_values['custom_post_id']) { $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']); } if ((isset($postProfileType) && $postProfileType == 'Membership' || isset($preProfileType) && $preProfileType == 'Membership') && !$this->_membershipBlock['is_active']) { CRM_Core_Error::fatal(ts('This page includes a Profile with Membership fields - but the Membership Block is NOT enabled. Please notify the site administrator.')); } $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id); if ($pledgeBlock) { $this->_values['pledge_block_id'] = CRM_Utils_Array::value('id', $pledgeBlock); $this->_values['max_reminders'] = CRM_Utils_Array::value('max_reminders', $pledgeBlock); $this->_values['initial_reminder_day'] = CRM_Utils_Array::value('initial_reminder_day', $pledgeBlock); $this->_values['additional_reminder_day'] = CRM_Utils_Array::value('additional_reminder_day', $pledgeBlock); //set pledge id in values $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this); //authenticate pledge user for pledge payment. if ($pledgeId) { $this->_values['pledge_id'] = $pledgeId; //lets override w/ pledge campaign. $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeId, 'campaign_id'); self::authenticatePledgeUser(); } } $this->set('values', $this->_values); $this->set('fields', $this->_fields); } // Handle PCP $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this); if ($pcpId) { $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values); $this->_pcpId = $pcp['pcpId']; $this->_pcpBlock = $pcp['pcpBlock']; $this->_pcpInfo = $pcp['pcpInfo']; } // Link (button) for users to create their own Personal Campaign page if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) { $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign', "action=add&reset=1&pageId={$this->_id}&component=contribute", FALSE, NULL, TRUE); $this->assign('linkTextUrl', $linkTextUrl); $this->assign('linkText', $linkText); } //set pledge block if block id is set if (CRM_Utils_Array::value('pledge_block_id', $this->_values)) { $this->assign('pledgeBlock', TRUE); } // check if one of the (amount , membership) bloks is active or not $this->_membershipBlock = $this->get('membershipBlock'); if (!$this->_values['amount_block_is_active'] && !$this->_membershipBlock['is_active'] && !$this->_priceSetId) { CRM_Core_Error::fatal(ts('The requested online contribution page is missing a required Contribution Amount section or Membership section or Price Set. Please check with the site administrator for assistance.')); } if ($this->_values['amount_block_is_active']) { $this->set('amount_block_is_active', $this->_values['amount_block_is_active']); } $this->_contributeMode = $this->get('contributeMode'); $this->assign('contributeMode', $this->_contributeMode); //assigning is_monetary and is_email_receipt to template $this->assign('is_monetary', $this->_values['is_monetary']); $this->assign('is_email_receipt', $this->_values['is_email_receipt']); $this->assign('bltID', $this->_bltID); //assign cancelSubscription URL to templates $this->assign('cancelSubscriptionUrl', CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values)); // assigning title to template in case someone wants to use it, also setting CMS page title if ($this->_pcpId) { $this->assign('title', $this->_pcpInfo['title']); CRM_Utils_System::setTitle($this->_pcpInfo['title']); } else { $this->assign('title', $this->_values['title']); CRM_Utils_System::setTitle($this->_values['title']); } $this->_defaults = array(); $this->_amount = $this->get('amount'); //CRM-6907 $config = CRM_Core_Config::singleton(); $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values, $config->defaultCurrency); //lets allow user to override campaign. $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this); if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) { $this->_values['campaign_id'] = $campID; } //do check for cancel recurring and clean db, CRM-7696 if (CRM_Utils_Request::retrieve('cancel', 'Boolean', CRM_Core_DAO::$_nullObject)) { self::cancelRecurring(); } }
/** * Global validation rules for the form. * * @param array $fields * Posted values of the form. * * @param $files * @param CRM_Core_Form $form * * @return array * if errors then list of errors to be posted back to the form, * true otherwise */ public static function formRule($fields, $files, $form) { // all option fields are of type "money" $errors = array(); /** Check the option values entered * Appropriate values are required for the selected datatype * Incomplete row checking is also required. */ if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) && $fields['html_type'] == 'Text' && $fields['price'] == NULL) { $errors['price'] = ts('Price is a required field'); } if (($form->_action & CRM_Core_Action::ADD || $form->_action & CRM_Core_Action::UPDATE) && $fields['html_type'] == 'Text' && $fields['financial_type_id'] == '') { $errors['financial_type_id'] = ts('Financial Type is a required field'); } //avoid the same price field label in Within PriceSet $priceFieldLabel = new CRM_Price_DAO_PriceField(); $priceFieldLabel->label = $fields['label']; $priceFieldLabel->price_set_id = $form->_sid; $dupeLabel = FALSE; if ($priceFieldLabel->find(TRUE) && $form->_fid != $priceFieldLabel->id) { $dupeLabel = TRUE; } if ($dupeLabel) { $errors['label'] = ts('Name already exists in Database.'); } if (is_numeric(CRM_Utils_Array::value('count', $fields)) && CRM_Utils_Array::value('count', $fields) == 0 && CRM_Utils_Array::value('html_type', $fields) == 'Text') { $errors['count'] = ts('Participant Count must be greater than zero.'); } if ($form->_action & CRM_Core_Action::ADD) { if ($fields['html_type'] != 'Text') { $countemptyrows = 0; $_flagOption = $_rowError = 0; $_showHide = new CRM_Core_ShowHideBlocks('', ''); for ($index = 1; $index <= self::NUM_OPTION; $index++) { $noLabel = $noAmount = $noWeight = 1; if (!empty($fields['option_label'][$index])) { $noLabel = 0; $duplicateIndex = CRM_Utils_Array::key($fields['option_label'][$index], $fields['option_label']); if (!($duplicateIndex === FALSE) && !($duplicateIndex == $index)) { $errors["option_label[{$index}]"] = ts('Duplicate label value'); $_flagOption = 1; } } if ($form->_useForMember) { if (!empty($fields['membership_type_id'][$index])) { $memTypesIDS[] = $fields['membership_type_id'][$index]; } } // allow for 0 value. if (!empty($fields['option_amount'][$index]) || strlen($fields['option_amount'][$index]) > 0) { $noAmount = 0; } if (!empty($fields['option_weight'][$index])) { $noWeight = 0; $duplicateIndex = CRM_Utils_Array::key($fields['option_weight'][$index], $fields['option_weight']); if (!($duplicateIndex === FALSE) && !($duplicateIndex == $index)) { $errors["option_weight[{$index}]"] = ts('Duplicate weight value'); $_flagOption = 1; } } if (!$noLabel && !$noAmount && !empty($fields['option_financial_type_id']) && $fields['option_financial_type_id'][$index] == '' && $fields['html_type'] != 'Text') { $errors["option_financial_type_id[{$index}]"] = ts('Financial Type is a Required field.'); } if ($noLabel && !$noAmount) { $errors["option_label[{$index}]"] = ts('Label cannot be empty.'); $_flagOption = 1; } if (!$noLabel && $noAmount) { $errors["option_amount[{$index}]"] = ts('Amount cannot be empty.'); $_flagOption = 1; } if ($noLabel && $noAmount) { $countemptyrows++; $_emptyRow = 1; } elseif (!empty($fields['option_max_value'][$index]) && !empty($fields['option_count'][$index]) && $fields['option_count'][$index] > $fields['option_max_value'][$index]) { $errors["option_max_value[{$index}]"] = ts('Participant count can not be greater than max participants.'); $_flagOption = 1; } $showBlocks = 'optionField_' . $index; if ($_flagOption) { $_showHide->addShow($showBlocks); $_rowError = 1; } if (!empty($_emptyRow)) { $_showHide->addHide($showBlocks); } else { $_showHide->addShow($showBlocks); } if ($index == self::NUM_OPTION) { $hideBlock = 'additionalOption'; $_showHide->addHide($hideBlock); } $_flagOption = $_emptyRow = 0; } if (!empty($memTypesIDS)) { // check for checkboxes allowing user to select multiple memberships from same membership organization if ($fields['html_type'] == 'CheckBox') { $foundDuplicate = FALSE; $orgIds = array(); foreach ($memTypesIDS as $key => $val) { $org = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization($val); if (in_array($org[$val], $orgIds)) { $foundDuplicate = TRUE; break; } $orgIds[$val] = $org[$val]; } if ($foundDuplicate) { $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity.'); } } // CRM-10390 - Only one price field in a set can include auto-renew membership options $foundAutorenew = FALSE; foreach ($memTypesIDS as $key => $val) { // see if any price field option values in this price field are for memberships with autorenew $memTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($val); if (!empty($memTypeDetails['auto_renew'])) { $foundAutorenew = TRUE; break; } } if ($foundAutorenew) { // if so, check for other fields in this price set which also have auto-renew membership options $otherFieldAutorenew = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($form->_sid); if ($otherFieldAutorenew) { $errors['_qf_default'] = ts('You can include auto-renew membership choices for only one price field in a price set. Another field in this set already contains one or more auto-renew membership options.'); } } } $_showHide->addToTemplate(); if ($countemptyrows == 15) { $errors['option_label[1]'] = $errors['option_amount[1]'] = ts('Label and value cannot be empty.'); $_flagOption = 1; } } elseif (!empty($fields['max_value']) && !empty($fields['count']) && $fields['count'] > $fields['max_value']) { $errors['max_value'] = ts('Participant count can not be greater than max participants.'); } // do not process if no option rows were submitted if (empty($fields['option_amount']) && empty($fields['option_label'])) { return TRUE; } if (empty($fields['option_name'])) { $fields['option_amount'] = array(); } if (empty($fields['option_label'])) { $fields['option_label'] = array(); } } return empty($errors) ? TRUE : $errors; }
/** * This function update contribution as well as related objects. */ function transitionComponents($params, $processContributionObject = false) { // get minimum required values. $contactId = CRM_Utils_Array::value('contact_id', $params); $componentId = CRM_Utils_Array::value('component_id', $params); $componentName = CRM_Utils_Array::value('componentName', $params); $contributionId = CRM_Utils_Array::value('contribution_id', $params); $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params); // if we already processed contribution object pass previous status id. $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params); $updateResult = array(); require_once 'CRM/Contribute/PseudoConstant.php'; $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name'); // we process only ( Completed, Cancelled, or Failed ) contributions. if (!$contributionId || !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses), array_search('Cancelled', $contributionStatuses), array_search('Failed', $contributionStatuses)))) { return $updateResult; } if (!$componentName || !$componentId) { // get the related component details. $componentDetails = self::getComponentDetails($contributionId); } else { $componentDetails['contact_id'] = $contactId; $componentDetails['component'] = $componentName; if ($componentName = 'event') { $componentDetails['participant'] = $componentId; } else { $componentDetails['membership'] = $componentId; } } if (CRM_Utils_Array::value('contact_id', $componentDetails)) { $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id'); } // do check for required ids. if (!CRM_Utils_Array::value('membership', $componentDetails) && !CRM_Utils_Array::value('participant', $componentDetails) && !CRM_Utils_Array::value('pledge_payment', $componentDetails) || !CRM_Utils_Array::value('contact_id', $componentDetails)) { return $updateResult; } //now we are ready w/ required ids, start processing. require_once 'CRM/Core/Payment/BaseIPN.php'; $baseIPN = new CRM_Core_Payment_BaseIPN(); $input = $ids = $objects = array(); $input['component'] = CRM_Utils_Array::value('component', $componentDetails); $ids['contribution'] = $contributionId; $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails); $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails); $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails); $ids['event'] = CRM_Utils_Array::value('event', $componentDetails); $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails); $ids['contributionRecur'] = null; $ids['contributionPage'] = null; if (!$baseIPN->validateData($input, $ids, $objects, false)) { CRM_Core_Error::fatal(); } $membership =& $objects['membership']; $participant =& $objects['participant']; $pledgePayment =& $objects['pledge_payment']; $contribution =& $objects['contribution']; if ($pledgePayment) { require_once 'CRM/Pledge/BAO/Payment.php'; $pledgePaymentIDs = array(); foreach ($pledgePayment as $key => $object) { $pledgePaymentIDs[] = $object->id; } $pledgeID = $pledgePayment[0]->pledge_id; } require_once 'CRM/Event/PseudoConstant.php'; require_once 'CRM/Event/BAO/Participant.php'; require_once 'CRM/Pledge/BAO/Pledge.php'; require_once 'CRM/Member/PseudoConstant.php'; require_once 'CRM/Member/BAO/Membership.php'; $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus(); if ($participant) { $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); $oldStatus = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participant->id, 'status_id'); } // we might want to process contribution object. $processContribution = false; if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) { if ($membership) { $membership->status_id = array_search('Cancelled', $membershipStatuses); $membership->save(); $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; if ($processContributionObject) { $processContribution = true; } } if ($participant) { $updatedStatusId = array_search('Cancelled', $participantStatuses); CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true); $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; if ($processContributionObject) { $processContribution = true; } } if ($pledgePayment) { CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; if ($processContributionObject) { $processContribution = true; } } } else { if ($contributionStatusId == array_search('Failed', $contributionStatuses)) { if ($membership) { $membership->status_id = array_search('Expired', $membershipStatuses); $membership->save(); $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; if ($processContributionObject) { $processContribution = true; } } if ($participant) { $updatedStatusId = array_search('Cancelled', $participantStatuses); CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true); $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; if ($processContributionObject) { $processContribution = true; } } if ($pledgePayment) { CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; if ($processContributionObject) { $processContribution = true; } } } else { if ($contributionStatusId == array_search('Completed', $contributionStatuses)) { // only pending contribution related object processed. if ($previousContriStatusId && $previousContriStatusId != array_search('Pending', $contributionStatuses)) { // this is case when we already processed contribution object. return $updateResult; } else { if (!$previousContriStatusId && $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) { // this is case when we will going to process contribution object. return $updateResult; } } if ($membership) { $format = '%Y%m%d'; require_once 'CRM/Member/BAO/MembershipType.php'; //CRM-4523 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id); if ($currentMembership) { CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday = null); $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday = null); $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); } else { $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id); } //get the status for membership. require_once 'CRM/Member/BAO/MembershipStatus.php'; $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', true); $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, array_search('Current', $membershipStatuses)), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), 'reminder_date' => CRM_Utils_Date::customFormat($dates['reminder_date'], $format)); $membership->copyValues($formatedParams); $membership->save(); //updating the membership log $membershipLog = array(); $membershipLog = $formatedParams; $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date']; $membershipLog['start_date'] = $logStartDate; $membershipLog['membership_id'] = $membership->id; $membershipLog['modified_id'] = $membership->contact_id; $membershipLog['modified_date'] = date('Ymd'); require_once 'CRM/Member/BAO/MembershipLog.php'; CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); //update related Memberships. CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams); $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], '%B %E%f, %Y'); $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; if ($processContributionObject) { $processContribution = true; } } if ($participant) { $updatedStatusId = array_search('Registered', $participantStatuses); CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true); $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; if ($processContributionObject) { $processContribution = true; } } if ($pledgePayment) { CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; if ($processContributionObject) { $processContribution = true; } } } } } // process contribution object. if ($processContribution) { require_once 'CRM/Contribute/BAO/Contribution.php'; $contributionParams = array(); $fields = array('contact_id', 'total_amount', 'receive_date', 'is_test', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'contribution_type_id', 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number'); foreach ($fields as $field) { if (!CRM_Utils_Array::value($field, $params)) { continue; } $contributionParams[$field] = $params[$field]; } $ids = array('contribution' => $contributionId); require_once 'CRM/Contribute/BAO/Contribution.php'; $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); } return $updateResult; }
/** * Process the form. * * @return void */ public function postProcess() { // get the submitted form values. $params = $this->controller->exportValues($this->_name); $deletePriceSet = 0; if ($params['membership_type']) { // we do this in case the user has hit the forward/back button $dao = new CRM_Member_DAO_MembershipBlock(); $dao->entity_table = 'civicrm_contribution_page'; $dao->entity_id = $this->_id; $dao->find(TRUE); $membershipID = $dao->id; if ($membershipID) { $params['id'] = $membershipID; } $membershipTypes = array(); if (is_array($params['membership_type'])) { foreach ($params['membership_type'] as $k => $v) { if ($v) { $membershipTypes[$k] = CRM_Utils_Array::value("auto_renew_{$k}", $params); } } } if ($this->_id && !empty($params['member_price_set_id'])) { CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_id, 'amount_block_is_active', 0); } // check for price set. $priceSetID = CRM_Utils_Array::value('member_price_set_id', $params); if (!empty($params['member_is_active']) && is_array($membershipTypes) && !$priceSetID) { $usedPriceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 2); if (empty($params['mem_price_field_id']) && !$usedPriceSetId) { $pageTitle = strtolower(CRM_Utils_String::munge($this->_values['title'], '_', 245)); $setParams['title'] = $this->_values['title']; if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $pageTitle, 'id', 'name')) { $setParams['name'] = $pageTitle; } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $pageTitle . '_' . $this->_id, 'id', 'name')) { $setParams['name'] = $pageTitle . '_' . $this->_id; } else { $timeSec = explode(".", microtime(TRUE)); $setParams['name'] = $pageTitle . '_' . date('is', $timeSec[0]) . $timeSec[1]; } $setParams['is_quick_config'] = 1; $setParams['extends'] = CRM_Core_Component::getComponentID('CiviMember'); $setParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_values); $priceSet = CRM_Price_BAO_PriceSet::create($setParams); $priceSetID = $priceSet->id; $fieldParams['price_set_id'] = $priceSet->id; } elseif ($usedPriceSetId) { $setParams['extends'] = CRM_Core_Component::getComponentID('CiviMember'); $setParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_values); $setParams['id'] = $usedPriceSetId; $priceSet = CRM_Price_BAO_PriceSet::create($setParams); $priceSetID = $priceSet->id; $fieldParams['price_set_id'] = $priceSet->id; } else { $fieldParams['id'] = CRM_Utils_Array::value('mem_price_field_id', $params); $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('mem_price_field_id', $params), 'price_set_id'); } $editedFieldParams = array('price_set_id' => $priceSetID, 'name' => 'membership_amount'); $editedResults = array(); CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults); if (empty($editedResults['id'])) { $fieldParams['name'] = strtolower(CRM_Utils_String::munge('Membership Amount', '_', 245)); if (empty($params['mem_price_field_id'])) { CRM_Utils_Weight::updateOtherWeights('CRM_Price_DAO_PriceField', 0, 1, array('price_set_id' => $priceSetID)); } $fieldParams['weight'] = 1; } else { $fieldParams['id'] = CRM_Utils_Array::value('id', $editedResults); } $fieldParams['label'] = !empty($params['membership_type_label']) ? $params['membership_type_label'] : ts('Membership'); $fieldParams['is_active'] = 1; $fieldParams['html_type'] = 'Radio'; $fieldParams['is_required'] = !empty($params['is_required']) ? 1 : 0; $fieldParams['is_display_amounts'] = !empty($params['display_min_fee']) ? 1 : 0; $rowCount = 1; $options = array(); if (!empty($fieldParams['id'])) { CRM_Core_PseudoConstant::populate($options, 'CRM_Price_DAO_PriceFieldValue', TRUE, 'membership_type_id', NULL, " price_field_id = {$fieldParams['id']} "); } foreach ($membershipTypes as $memType => $memAutoRenew) { if ($priceFieldID = CRM_Utils_Array::key($memType, $options)) { $fieldParams['option_id'][$rowCount] = $priceFieldID; unset($options[$priceFieldID]); } $membetype = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($memType); $fieldParams['option_label'][$rowCount] = CRM_Utils_Array::value('name', $membetype); $fieldParams['option_amount'][$rowCount] = CRM_Utils_Array::value('minimum_fee', $membetype, 0); $fieldParams['option_weight'][$rowCount] = CRM_Utils_Array::value('weight', $membetype); $fieldParams['option_description'][$rowCount] = CRM_Utils_Array::value('description', $membetype); $fieldParams['default_option'] = CRM_Utils_Array::value('membership_type_default', $params); $fieldParams['option_financial_type_id'][$rowCount] = CRM_Utils_Array::value('financial_type_id', $membetype); $fieldParams['membership_type_id'][$rowCount] = $memType; // [$rowCount] = $membetype['']; $rowCount++; } foreach ($options as $priceFieldID => $memType) { CRM_Price_BAO_PriceFieldValue::setIsActive($priceFieldID, '0'); } $priceField = CRM_Price_BAO_PriceField::create($fieldParams); } elseif (!$priceSetID) { $deletePriceSet = 1; } $params['is_required'] = CRM_Utils_Array::value('is_required', $params, FALSE); $params['is_active'] = CRM_Utils_Array::value('member_is_active', $params, FALSE); if ($priceSetID) { $params['membership_types'] = 'null'; $params['membership_type_default'] = CRM_Utils_Array::value('membership_type_default', $params, 'null'); $params['membership_types'] = serialize($membershipTypes); $params['display_min_fee'] = CRM_Utils_Array::value('display_min_fee', $params, FALSE); $params['is_separate_payment'] = CRM_Utils_Array::value('is_separate_payment', $params, FALSE); } $params['entity_table'] = 'civicrm_contribution_page'; $params['entity_id'] = $this->_id; $dao = new CRM_Member_DAO_MembershipBlock(); $dao->copyValues($params); $dao->save(); if ($priceSetID && $params['is_active']) { CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $this->_id, $priceSetID); } if ($deletePriceSet || !CRM_Utils_Array::value('member_is_active', $params, FALSE)) { if ($this->_memPriceSetId) { $pFIDs = array(); $conditionParams = array('price_set_id' => $this->_memPriceSetId, 'html_type' => 'radio', 'name' => 'contribution_amount'); CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $conditionParams, $pFIDs); if (empty($pFIDs['id'])) { CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution_page', $this->_id); CRM_Price_BAO_PriceSet::setIsQuickConfig($this->_memPriceSetId, '0'); } else { CRM_Price_BAO_PriceField::setIsActive($params['mem_price_field_id'], '0'); } } } } parent::endPostProcess(); }
/** * process membership records * * @param array $params associated array of submitted values * * @access public * * @return bool */ private function processMembership(&$params) { $dateTypes = array('join_date' => 'joinDate', 'membership_start_date' => 'startDate', 'membership_end_date' => 'endDate'); $dates = array('join_date', 'start_date', 'end_date', 'reminder_date'); // get the price set associated with offline memebership $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name'); $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId)); if (isset($params['field'])) { $customFields = array(); foreach ($params['field'] as $key => $value) { // if contact is not selected we should skip the row if (empty($params['primary_contact_id'][$key])) { continue; } $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']); // update contact information $this->updateContactInfo($value); $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1]; foreach ($dateTypes as $dateField => $dateVariable) { ${$dateVariable} = CRM_Utils_Date::processDate($value[$dateField]); } $calcDates = array(); $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId, $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, $value); if (!$date) { $date = CRM_Utils_Array::value($d, $calcDate); } $value[$d] = CRM_Utils_Date::processDate($date); } } if (!empty($value['send_receipt'])) { $value['receipt_date'] = date('Y-m-d His'); } if (!empty($value['membership_source'])) { $value['source'] = $value['membership_source']; } unset($value['membership_source']); //Get the membership status if (!empty($value['membership_status'])) { $value['status_id'] = $value['membership_status']; unset($value['membership_status']); } if (empty($customFields)) { // membership type custom data $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId); $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE)); } //check for custom data $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $customFields, $key, 'Membership', $membershipTypeId); if (!empty($value['financial_type'])) { $value['financial_type_id'] = $value['financial_type']; } if (!empty($value['payment_instrument'])) { $value['payment_instrument_id'] = $value['payment_instrument']; } // handle soft credit if (is_array(CRM_Utils_Array::value('soft_credit_contact_id', $params)) && !empty($params['soft_credit_contact_id'][$key]) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])) { $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key]; $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]); } if (!empty($value['receive_date'])) { $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE); } $params['actualBatchTotal'] += $value['total_amount']; unset($value['financial_type']); unset($value['payment_instrument']); $value['batch_id'] = $this->_batchId; $value['skipRecentView'] = TRUE; // make entry in line item for contribution $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => $value['membership_type'][0]); $editedResults = array(); CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults); if (!empty($editedResults)) { unset($this->_priceSet['fields']); $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']]; unset($this->_priceSet['fields'][$editedResults['id']]['options']); $fid = $editedResults['id']; $editedFieldParams = array('price_field_id' => $editedResults['id'], 'membership_type_id' => $value['membership_type_id']); $editedResults = array(); CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults); $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']]; if (!empty($value['total_amount'])) { $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount']; } $fieldID = key($this->_priceSet['fields']); $value['price_' . $fieldID] = $editedResults['id']; $lineItem = array(); CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]); //CRM-11529 for backoffice transactions //when financial_type_id is passed in form, update the //lineitems with the financial type selected in form if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) { foreach ($lineItem[$priceSetId] as &$values) { $values['financial_type_id'] = $value['financial_type_id']; } } $value['lineItems'] = $lineItem; $value['processPriceSet'] = TRUE; } // end of contribution related section unset($value['membership_type']); unset($value['membership_start_date']); unset($value['membership_end_date']); $value['is_renew'] = false; if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) { $this->_params = $params; $value['is_renew'] = true; $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($value['contact_id'], $value['membership_type_id'], FALSE, $this, NULL, NULL, $value['custom']); // make contribution entry CRM_Member_BAO_Membership::recordMembershipContribution(array_merge($value, array('membership_id' => $membership->id))); } else { $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray); } //process premiums if (!empty($value['product_name'])) { if ($value['product_name'][0] > 0) { list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo(); $value['hidden_Premium'] = 1; $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]); $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => $value['contribution_id'], 'product_option' => $value['product_option'], 'quantity' => 1); CRM_Contribute_BAO_Contribution::addPremium($premiumParams); } } // end of premium //send receipt mail. if ($membership->id && !empty($value['send_receipt'])) { // add the domain email id $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail(); $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>"; $value['from_email_address'] = $domainEmail; $value['membership_id'] = $membership->id; CRM_Member_Form_Membership::emailReceipt($this, $value, $membership); } } } return TRUE; }
/** * Function to process the form * * @access public * * @return None */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { CRM_Utils_Weight::delWeight('CRM_Member_DAO_MembershipType', $this->_id); CRM_Member_BAO_MembershipType::del($this->_id); CRM_Core_Session::setStatus(ts('Selected membership type has been deleted.')); } else { $buttonName = $this->controller->getButtonName(); $submitted = $this->controller->exportValues($this->_name); $this->set('searchDone', 0); if ($buttonName == '_qf_MembershipType_refresh') { $this->search($submitted); $this->set('searchDone', 1); return; } $fields = array('name', 'weight', 'is_active', 'member_org', 'visibility', 'period_type', 'minimum_fee', 'description', 'auto_renew', 'autorenewal_msg_id', 'duration_unit', 'renewal_msg_id', 'duration_interval', 'renewal_reminder_day', 'contribution_type_id', 'fixed_period_start_day', 'fixed_period_rollover_day'); $params = $ids = array(); foreach ($fields as $fld) { $params[$fld] = CRM_Utils_Array::value($fld, $submitted, 'NULL'); } //clean money. if ($params['minimum_fee']) { $params['minimum_fee'] = CRM_Utils_Rule::cleanMoney($params['minimum_fee']); } $hasRelTypeVal = FALSE; if (!CRM_Utils_System::isNull($submitted['relationship_type_id'])) { // To insert relation ids and directions with value separator $relTypeDirs = $submitted['relationship_type_id']; $relIds = $relDirection = array(); foreach ($relTypeDirs as $key => $value) { $relationId = explode('_', $value); if (count($relationId) == 3 && is_numeric($relationId[0])) { $relIds[] = $relationId[0]; $relDirection[] = $relationId[1] . '_' . $relationId[2]; } } if (!empty($relIds)) { $hasRelTypeVal = TRUE; $params['relationship_type_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relIds); $params['relationship_direction'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $relDirection); } } if (!$hasRelTypeVal) { $params['relationship_type_id'] = $params['relationship_direction'] = 'NULL'; } if ($params['duration_unit'] == 'lifetime' && empty($params['duration_interval'])) { $params['duration_interval'] = 1; } $config = CRM_Core_Config::singleton(); $periods = array('fixed_period_start_day', 'fixed_period_rollover_day'); foreach ($periods as $per) { if (CRM_Utils_Array::value('M', $params[$per]) && CRM_Utils_Array::value('d', $params[$per])) { $mon = $params[$per]['M']; $dat = $params[$per]['d']; $mon = $mon < 9 ? '0' . $mon : $mon; $dat = $dat < 9 ? '0' . $dat : $dat; $params[$per] = $mon . $dat; } else { $params[$per] = 'NULL'; } } $oldWeight = NULL; $ids['memberOfContact'] = CRM_Utils_Array::value('contact_check', $submitted); if ($this->_id) { $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_id, 'weight', 'id'); } $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Member_DAO_MembershipType', $oldWeight, $params['weight']); if ($this->_action & CRM_Core_Action::UPDATE) { $ids['membershipType'] = $this->_id; } $membershipType = CRM_Member_BAO_MembershipType::add($params, $ids); CRM_Core_Session::setStatus(ts('The membership type \'%1\' has been saved.', array(1 => $membershipType->name))); $session = CRM_Core_Session::singleton(); if ($buttonName == $this->getButtonName('upload', 'new')) { CRM_Core_Session::setStatus(ts(' You can add another membership type.')); $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin/member/membershipType', 'action=add&reset=1')); } } }
/** * Function to build the form * * @return None * @access public */ public function buildQuickForm() { parent::buildQuickForm(); if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::COPY)) { return; } $this->applyFilter('__ALL__', 'trim'); $element = $this->add('text', 'code', ts('Discount Code'), CRM_Core_DAO::getAttribute('CRM_CiviDiscount_DAO_Item', 'code'), TRUE); $this->addRule('code', ts('Code already exists in Database.'), 'objectExists', array('CRM_CiviDiscount_DAO_Item', $this->_id, 'code')); $this->addRule('code', ts('Code can only consist of alpha-numeric characters'), 'variable'); if ($this->_action & CRM_Core_Action::UPDATE) { $element->freeze(); } $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_CiviDiscount_DAO_Item', 'description')); $this->addMoney('amount', ts('Discount Amount'), TRUE, CRM_Core_DAO::getAttribute('CRM_CiviDiscount_DAO_Item', 'amount'), FALSE); $this->add('select', 'amount_type', NULL, array(1 => ts('Percent'), 2 => ts('Fixed Amount')), TRUE); $this->add('text', 'count_max', ts('Usage Limit'), CRM_Core_DAO::getAttribute('CRM_CiviDiscount_DAO_Item', 'count_max') + array('min' => 1)); $this->addRule('count_max', ts('Must be an integer'), 'integer'); $this->addDate('active_on', ts('Activation Date'), FALSE); $this->addDate('expire_on', ts('Expiration Date'), FALSE); $this->addEntityRef('organization_id', ts('Organization'), array('api' => array('params' => array('contact_type' => 'Organization')))); // is this discount active ? $this->addElement('checkbox', 'is_active', ts('Is this discount active?')); $this->addElement('checkbox', 'discount_msg_enabled', ts('Display a message to users not eligible for this discount?')); $this->add('textarea', 'discount_msg', ts('Message to non-eligible users'), array('class' => 'big')); // add memberships, events, pricesets $membershipTypes = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE); if (!empty($membershipTypes)) { $this->add('select', 'memberships', ts('Memberships'), $membershipTypes, FALSE, $this->select2style); } $this->assignAutoDiscountFields(); $this->addElement('text', 'advanced_autodiscount_filter_entity', ts('Specify entity for advanced autodiscount')); $this->addElement('text', 'advanced_autodiscount_filter_string', ts('Specify api string for advanced filter'), array('class' => 'huge')); $events = CRM_CiviDiscount_Utils::getEvents(); if (!empty($events)) { $events = array(ts('--any event--')) + $events; $this->_multiValued['events'] = $events; $this->add('select', 'events', ts('Events'), $events, FALSE, $this->select2style); $eventTypes = $this->getOptions('event', 'event_type_id'); $this->_multiValued['eventtypes'] = $eventTypes; $this->add('select', 'event_type_id', ts('Event Types'), $eventTypes, FALSE, $this->select2style); } $pricesets = CRM_CiviDiscount_Utils::getNestedPriceSets(); if (!empty($pricesets)) { $this->_multiValued['pricesets'] = $pricesets; $this->add('select', 'pricesets', ts('Price Field Options'), $pricesets, FALSE, array('placeholder' => ts('- any -')) + $this->select2style); } }
/** * 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'); } } } } }
/** * @param int $contactID * @param int $membershipTypeID * @param bool $is_test * @param $changeToday * @param int $modifiedID * @param $customFieldsFormatted * @param $numRenewTerms * @param int $membershipID * @param $pending * @param int $contributionRecurID * @param $membershipSource * @param $isPayLater * @param int $campaignId * @param array $formDates * * @throws CRM_Core_Exception * @return array */ public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array()) { $renewalMode = $updateStatusId = FALSE; $allStatus = CRM_Member_PseudoConstant::membershipStatus(); $format = '%Y%m%d'; $statusFormat = '%Y-%m-%d'; $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID); $dates = array(); // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType // is the same as the parent org of an existing membership of the contact $currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID, $is_test, $membershipID, TRUE); if ($currentMembership) { $activityType = 'Membership Renewal'; $renewalMode = TRUE; // Do NOT do anything. //1. membership with status : PENDING/CANCELLED (CRM-2395) //2. Paylater/IPN renew. CRM-4556. if ($pending || in_array($currentMembership['status_id'], array(array_search('Pending', $allStatus), array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE))))) { $membership = new CRM_Member_DAO_Membership(); $membership->id = $currentMembership['id']; $membership->find(TRUE); // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed $format = '%Y%m%d'; // note that we are logging the requested new membership_type_id that may be different than current membership_type_id // it will be used when payment is received to update the membership_type_id to what was paid for $logParams = array('membership_id' => $membership->id, 'status_id' => $membership->status_id, 'start_date' => CRM_Utils_Date::customFormat($membership->start_date, $format), 'end_date' => CRM_Utils_Date::customFormat($membership->end_date, $format), 'modified_date' => CRM_Utils_Date::customFormat(date('Ymd'), $format), 'membership_type_id' => $membershipTypeID, 'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL); $session = CRM_Core_Session::singleton(); // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id if ($session->get('userID')) { $logParams['modified_id'] = $session->get('userID'); } else { $logParams['modified_id'] = $membership->contact_id; } CRM_Member_BAO_MembershipLog::add($logParams); if ($contributionRecurID) { CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $membership->id, 'contribution_recur_id', $contributionRecurID); } return array($membership, $renewalMode, $dates); } // Check and fix the membership if it is STALE self::fixMembershipStatusBeforeRenew($currentMembership, $changeToday); // Now Renew the membership if (!$currentMembership['is_current_member']) { // membership is not CURRENT // CRM-7297 Membership Upsell - calculate dates based on new membership type $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'], $changeToday, $membershipTypeID, $numRenewTerms); $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); foreach (array('start_date', 'end_date') as $dateType) { $currentMembership[$dateType] = CRM_Utils_Array::value($dateType, $formDates); if (empty($currentMembership[$dateType])) { $currentMembership[$dateType] = CRM_Utils_Array::value($dateType, $dates); } } $currentMembership['is_test'] = $is_test; if (!empty($membershipSource)) { $currentMembership['source'] = $membershipSource; } else { $currentMembership['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $currentMembership['id'], 'source'); } if (!empty($currentMembership['id'])) { $ids['membership'] = $currentMembership['id']; } $memParams = $currentMembership; $memParams['membership_type_id'] = $membershipTypeID; //set the log start date. $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); } else { // CURRENT Membership $membership = new CRM_Member_DAO_Membership(); $membership->id = $currentMembership['id']; $membership->find(TRUE); // CRM-7297 Membership Upsell - calculate dates based on new membership type $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, $membershipTypeID, $numRenewTerms); // Insert renewed dates for CURRENT membership $memParams = array(); $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date); $memParams['start_date'] = CRM_Utils_Date::isoToMysql($membership->start_date); $memParams['end_date'] = CRM_Utils_Array::value('end_date', $formDates); if (empty($memParams['end_date'])) { $memParams['end_date'] = CRM_Utils_Array::value('end_date', $dates); } $memParams['membership_type_id'] = $membershipTypeID; //set the log start date. $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); if (empty($membership->source)) { if (!empty($membershipSource)) { $memParams['source'] = $membershipSource; } else { $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $currentMembership['id'], 'source'); } } if (!empty($currentMembership['id'])) { $ids['membership'] = $currentMembership['id']; } } //CRM-4555 if ($pending) { $updateStatusId = array_search('Pending', $allStatus); } } else { // NEW Membership $activityType = 'Membership Signup'; $memParams = array('contact_id' => $contactID, 'membership_type_id' => $membershipTypeID); if (!$pending) { $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms); foreach (array('join_date', 'start_date', 'end_date') as $dateType) { $memParams[$dateType] = CRM_Utils_Array::value($dateType, $formDates); if (empty($memParams[$dateType])) { $memParams[$dateType] = CRM_Utils_Array::value($dateType, $dates); } } $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'], $statusFormat), CRM_Utils_Date::customFormat($dates['end_date'], $statusFormat), CRM_Utils_Date::customFormat($dates['join_date'], $statusFormat), 'today', TRUE, $membershipTypeID, $memParams); $updateStatusId = CRM_Utils_Array::value('id', $status); } else { // if IPN/Pay-Later set status to: PENDING $updateStatusId = array_search('Pending', $allStatus); } if (!empty($membershipSource)) { $memParams['source'] = $membershipSource; } $memParams['is_test'] = $is_test; $memParams['is_pay_later'] = $isPayLater; } // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but // perhaps shouldn't be? if ($contributionRecurID) { $memParams['contribution_recur_id'] = $contributionRecurID; } //CRM-4555 //if we decided status here and want to skip status //calculation in create( ); then need to pass 'skipStatusCal'. if ($updateStatusId) { $memParams['status_id'] = $updateStatusId; $memParams['skipStatusCal'] = TRUE; } //since we are renewing, //make status override false. $memParams['is_override'] = FALSE; //CRM-4027, create log w/ individual contact. if ($modifiedID) { $ids['userId'] = $modifiedID; $memParams['is_for_organization'] = TRUE; } else { $ids['userId'] = $contactID; } //inherit campaign from contrib page. if (isset($campaignId)) { $memParams['campaign_id'] = $campaignId; } $memParams['custom'] = $customFieldsFormatted; $membership = self::create($memParams, $ids, FALSE, $activityType); // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072 $membership->find(TRUE); return array($membership, $renewalMode, $dates); }
/** * Complete an order. * * Do not call this directly - use the contribution.completetransaction api as this function is being refactored. * * Currently overloaded to complete a transaction & repeat a transaction - fix! * * Moving it out of the BaseIPN class is just the first step. * * @param array $input * @param array $ids * @param array $objects * @param CRM_Core_Transaction $transaction * @param int $recur * @param CRM_Contribute_BAO_Contribution $contribution * @param bool $isRecurring * Duplication of param needs review. Only used by AuthorizeNetIPN * @param int $isFirstOrLastRecurringPayment * Deprecated param only used by AuthorizeNetIPN. */ public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) { $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id; // The previous details are used when calculating line items so keep it before any code that 'does something' if (!empty($contribution->id)) { $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); } $inputContributionWhiteList = array('fee_amount', 'net_amount', 'trxn_id', 'check_number', 'payment_instrument_id', 'is_test', 'campaign_id', 'receive_date'); $contributionParams = array_merge(array('contribution_status_id' => 'Completed'), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1))); $participant = CRM_Utils_Array::value('participant', $objects); $memberships = CRM_Utils_Array::value('membership', $objects); $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects); if (!empty($recurContrib->id)) { $contributionParams['contribution_recur_id'] = $recurContrib->id; } self::repeatTransaction($contribution, $input, $contributionParams); if (is_numeric($memberships)) { $memberships = array($objects['membership']); } $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis')); $values = array(); if (isset($input['is_email_receipt'])) { $values['is_email_receipt'] = $input['is_email_receipt']; } if ($input['component'] == 'contribute') { if ($contribution->contribution_page_id) { CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values); $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title']; } elseif ($recurContrib && $recurContrib->id) { $contributionParams['contribution_page_id'] = NULL; $values['amount'] = $recurContrib->amount; $values['financial_type_id'] = $objects['contributionType']->id; $values['title'] = $source = ts('Offline Recurring Contribution'); $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $values['receipt_from_name'] = $domainValues[0]; $values['receipt_from_email'] = $domainValues[1]; } if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) { //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden. $values['is_email_receipt'] = $recurContrib->is_email_receipt; } if (!empty($values['is_email_receipt'])) { $contributionParams['receipt_date'] = $changeDate; } if (!empty($memberships)) { foreach ($memberships as $membershipTypeIdKey => $membership) { if ($membership) { $membershipParams = array('id' => $membership->id, 'contact_id' => $membership->contact_id, 'is_test' => $membership->is_test, 'membership_type_id' => $membership->membership_type_id); $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], $membershipParams['membership_type_id'], $membershipParams['is_test'], $membershipParams['id']); // CRM-8141 update the membership type with the value recorded in log when membership created/renewed // this picks up membership type changes during renewals $sql = "\nSELECT membership_type_id\nFROM civicrm_membership_log\nWHERE membership_id={$membershipParams['id']}\nORDER BY id DESC\nLIMIT 1;"; $dao = CRM_Core_DAO::executeQuery($sql); if ($dao->fetch()) { if (!empty($dao->membership_type_id)) { $membershipParams['membership_type_id'] = $dao->membership_type_id; } } $dao->free(); $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType($membershipParams['membership_type_id'], $primaryContributionID); $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL); if ($currentMembership) { /* * Fixed FOR CRM-4433 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status * when Contribution mode is notify and membership is for renewal ) */ CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate); // @todo - we should pass membership_type_id instead of null here but not // adding as not sure of testing $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], $changeDate, NULL, $membershipParams['num_terms']); $dates['join_date'] = $currentMembership['join_date']; } //get the status for membership. $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membershipParams['membership_type_id'], $membershipParams); $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New'); //we might be renewing membership, //so make status override false. $membershipParams['is_override'] = FALSE; civicrm_api3('Membership', 'create', $membershipParams); //update related Memberships. CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $membershipParams); } } } } else { if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) { $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id)); $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title']; if ($eventDetail['is_email_confirm']) { // @todo this should be set by the function that sends the mail after sending. $contributionParams['receipt_date'] = $changeDate; } $participantParams['id'] = $participant->id; $participantParams['status_id'] = 'Registered'; civicrm_api3('Participant', 'create', $participantParams); } } $contributionParams['id'] = $contribution->id; civicrm_api3('Contribution', 'create', $contributionParams); // Add new soft credit against current $contribution. if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) { CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id); } $paymentProcessorId = ''; if (isset($objects['paymentProcessor'])) { if (is_array($objects['paymentProcessor'])) { $paymentProcessorId = $objects['paymentProcessor']['id']; } else { $paymentProcessorId = $objects['paymentProcessor']->id; } } $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1)); if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending']) { $input['payment_processor'] = $paymentProcessorId; } $input['contribution_status_id'] = $contributionStatuses['Completed']; $input['total_amount'] = $input['amount']; $input['contribution'] = $contribution; $input['financial_type_id'] = $contribution->financial_type_id; if (!empty($contribution->_relatedObjects['participant'])) { $input['contribution_mode'] = 'participant'; $input['participant_id'] = $contribution->_relatedObjects['participant']->id; $input['skipLineItem'] = 1; } elseif (!empty($contribution->_relatedObjects['membership'])) { $input['skipLineItem'] = TRUE; $input['contribution_mode'] = 'membership'; } //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second // and subsequent payments. In this case the line items are created at // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems // and since the contribution is saved prior to this line there is always a contribution-id, // however there is never a prevContribution (which appears to mean original contribution not previous // contribution - or preUpdateContributionObject most accurately) // so, this is always called & only appears to succeed when prevContribution exists - which appears // to mean "are we updating an exisitng pending contribution" //I was able to make the unit test complete as fataling here doesn't prevent // the contribution being created - but activities would not be created or emails sent CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL); CRM_Core_Error::debug_log_message("Contribution record updated successfully"); $transaction->commit(); CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution); // create an activity record if ($input['component'] == 'contribute') { //CRM-4027 $targetContactID = NULL; if (!empty($ids['related_contact'])) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $ids['related_contact']; } CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); // event } else { CRM_Activity_BAO_Activity::addActivity($participant); } // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) { self::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE); CRM_Core_Error::debug_log_message("Receipt sent"); } CRM_Core_Error::debug_log_message("Success: Database updated"); if ($isRecurring) { CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment); } }