3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class generates form components for offline membership form.
37 class CRM_Member_Form_Membership
extends CRM_Member_Form
{
39 protected $_memType = NULL;
41 protected $_onlinePendingContributionId;
45 public $_contributeMode = 'direct';
47 protected $_recurMembershipTypes;
49 protected $_memTypeSelected;
52 * Display name of the member.
56 protected $_memberDisplayName = NULL;
59 * email of the person paying for the membership (used for receipts)
62 protected $_memberEmail = NULL;
65 * Contact ID of the member.
69 public $_contactID = NULL;
72 * Display name of the person paying for the membership (used for receipts)
76 protected $_contributorDisplayName = NULL;
79 * email of the person paying for the membership (used for receipts)
82 protected $_contributorEmail = NULL;
85 * email of the person paying for the membership (used for receipts)
89 protected $_contributorContactID = NULL;
92 * ID of the person the receipt is to go to.
96 protected $_receiptContactId = NULL;
99 * Keep a class variable for ALL membership IDs so
100 * postProcess hook function can do something with it
104 protected $_membershipIDs = [];
107 * Set entity fields to be assigned to the form.
109 protected function setEntityFields() {
110 $this->entityFields
= [
112 'name' => 'join_date',
113 'description' => ts('Member Since'),
116 'name' => 'start_date',
117 'description' => ts('Start Date'),
120 'name' => 'end_date',
121 'description' => ts('End Date'),
127 * Set the delete message.
129 * We do this from the constructor in order to do a translation.
131 public function setDeleteMessage() {
132 $this->deleteMessage
= '<span class="font-red bold">'
133 . ts("WARNING: Deleting this membership will also delete any related payment (contribution) records." . ts("This action cannot be undone.")
135 . ts("Consider modifying the membership status instead if you want to maintain an audit trail and avoid losing payment data. You can set the status to Cancelled by editing the membership and clicking the Status Override checkbox.")
137 . ts("Click 'Delete' if you want to continue.") . '</p>');
141 * Overriding this entity trait function as not yet tested.
143 * We continue to rely on legacy handling.
145 public function addCustomDataToForm() {}
148 * Overriding this entity trait function as not yet tested.
150 * We continue to rely on legacy handling.
152 public function addFormButtons() {}
155 * Get selected membership type from the form values.
157 * @param array $priceSet
158 * @param array $params
162 public static function getSelectedMemberships($priceSet, $params) {
163 $memTypeSelected = [];
164 $priceFieldIDS = self
::getPriceFieldIDs($params, $priceSet);
165 if (isset($params['membership_type_id']) && !empty($params['membership_type_id'][1])) {
166 $memTypeSelected = [$params['membership_type_id'][1] => $params['membership_type_id'][1]];
169 foreach ($priceFieldIDS as $priceFieldId) {
170 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
171 $memTypeSelected[$id] = $id;
175 return $memTypeSelected;
179 * Extract price set fields and values from $params.
181 * @param array $params
182 * @param array $priceSet
186 public static function getPriceFieldIDs($params, $priceSet) {
188 if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
189 foreach ($priceSet['fields'] as $fieldId => $field) {
190 if (!empty($params['price_' . $fieldId])) {
191 if (is_array($params['price_' . $fieldId])) {
192 foreach ($params['price_' . $fieldId] as $priceFldVal => $isSet) {
194 $priceFieldIDS[] = $priceFldVal;
198 elseif (!$field['is_enter_qty']) {
199 $priceFieldIDS[] = $params['price_' . $fieldId];
204 return $priceFieldIDS;
208 * Form preProcess function.
212 public function preProcess() {
213 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
214 $this->assign('formClass', 'membership');
215 parent
::preProcess();
216 if ($this->isUpdateToExistingRecurringMembership()) {
217 $this->entityFields
['end_date']['is_freeze'] = TRUE;
220 $this->_priceSetId
= CRM_Utils_Array
::value('priceSetId', $_GET);
221 $this->set('priceSetId', $this->_priceSetId
);
222 $this->assign('priceSetId', $this->_priceSetId
);
224 if ($this->_action
& CRM_Core_Action
::DELETE
) {
225 $contributionID = CRM_Member_BAO_Membership
::getMembershipContributionId($this->_id
);
226 // check delete permission for contribution
227 if ($this->_id
&& $contributionID && !CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
228 CRM_Core_Error
::fatal(ts("This Membership is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
232 if ($this->_action
& CRM_Core_Action
::ADD
) {
233 if ($this->_contactID
) {
234 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
235 $contactMemberships = [];
236 $memParams = ['contact_id' => $this->_contactID
];
237 CRM_Member_BAO_Membership
::getValues($memParams, $contactMemberships, TRUE);
239 foreach ($contactMemberships as $mem) {
240 $cMemTypes[] = $mem['membership_type_id'];
242 if (count($cMemTypes) > 0) {
243 $memberorgs = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($cMemTypes);
245 foreach ($contactMemberships as $mem) {
246 $mem['member_of_contact_id'] = CRM_Utils_Array
::value($mem['membership_type_id'], $memberorgs);
247 if (!empty($mem['membership_end_date'])) {
248 $mem['membership_end_date'] = CRM_Utils_Date
::customformat($mem['membership_end_date']);
250 $mem['membership_type'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
251 $mem['membership_type_id'],
254 $mem['membership_status'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
258 $mem['renewUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
259 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
260 . ($this->_mode ?
'&mode=live' : '')
262 $mem['membershipTab'] = CRM_Utils_System
::url('civicrm/contact/view',
263 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
265 $mems_by_org[$mem['member_of_contact_id']] = $mem;
267 $this->assign('existingContactMemberships', $mems_by_org);
271 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
272 $resources = CRM_Core_Resources
::singleton();
273 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
275 'typeorgs' => CRM_Member_BAO_MembershipType
::getMembershipTypeOrganization(),
276 'memtypes' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'membership_type_id'),
277 'statuses' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'status_id'),
279 $resources->addSetting(['existingMems' => $passthru]);
283 if (!$this->_memType
) {
284 $params = CRM_Utils_Request
::exportValues();
285 if (!empty($params['membership_type_id'][1])) {
286 $this->_memType
= $params['membership_type_id'][1];
290 // Add custom data to form
291 CRM_Custom_Form_CustomData
::addToForm($this, $this->_memType
);
293 // CRM-4395, get the online pending contribution id.
294 $this->_onlinePendingContributionId
= NULL;
295 if (!$this->_mode
&& $this->_id
&& ($this->_action
& CRM_Core_Action
::UPDATE
)) {
296 $this->_onlinePendingContributionId
= CRM_Contribute_BAO_Contribution
::checkOnlinePendingContribution($this->_id
,
300 $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId
);
302 $this->setPageTitle(ts('Membership'));
306 * Set default values for the form.
308 public function setDefaultValues() {
310 if ($this->_priceSetId
) {
311 return CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $defaults);
314 $defaults = parent
::setDefaultValues();
316 //setting default join date and receive date
317 if ($this->_action
== CRM_Core_Action
::ADD
) {
318 $defaults['receive_date'] = date('Y-m-d H:i:s');
321 $defaults['num_terms'] = 1;
323 if (!empty($defaults['id'])) {
324 if ($this->_onlinePendingContributionId
) {
325 $defaults['record_contribution'] = $this->_onlinePendingContributionId
;
328 $contributionId = CRM_Core_DAO
::singleValueQuery("
329 SELECT contribution_id
330 FROM civicrm_membership_payment
331 WHERE membership_id = $this->_id
332 ORDER BY contribution_id
335 if ($contributionId) {
336 $defaults['record_contribution'] = $contributionId;
341 //set Soft Credit Type to Gift by default
342 $scTypes = CRM_Core_OptionGroup
::values("soft_credit_type");
343 $defaults['soft_credit_type_id'] = CRM_Utils_Array
::value(ts('Gift'), array_flip($scTypes));
345 if (!empty($defaults['record_contribution']) && !$this->_mode
) {
346 $contributionParams = ['id' => $defaults['record_contribution']];
347 $contributionIds = [];
349 //keep main object campaign in hand.
350 $memberCampaignId = CRM_Utils_Array
::value('campaign_id', $defaults);
352 CRM_Contribute_BAO_Contribution
::getValues($contributionParams, $defaults, $contributionIds);
354 //get back original object campaign id.
355 $defaults['campaign_id'] = $memberCampaignId;
357 // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it.
358 if (!empty($defaults['membership_source'])) {
359 $defaults['source'] = $defaults['membership_source'];
363 if (empty($defaults['payment_instrument_id'])) {
364 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
367 // User must explicitly choose to send a receipt in both add and update mode.
368 $defaults['send_receipt'] = 0;
370 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
371 // in this mode by default uncheck this checkbox
372 unset($defaults['record_contribution']);
375 $subscriptionCancelled = FALSE;
376 if (!empty($defaults['id'])) {
377 $subscriptionCancelled = CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
);
380 $alreadyAutoRenew = FALSE;
381 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
382 $defaults['auto_renew'] = 1;
383 $alreadyAutoRenew = TRUE;
385 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
387 $this->assign('member_is_test', CRM_Utils_Array
::value('member_is_test', $defaults));
389 $this->assign('membership_status_id', CRM_Utils_Array
::value('status_id', $defaults));
391 if (!empty($defaults['is_pay_later'])) {
392 $this->assign('is_pay_later', TRUE);
395 $defaults = $this->getBillingDefaults($defaults);
396 // hack to simplify credit card entry for testing
397 // $defaults['credit_card_type'] = 'Visa';
398 // $defaults['credit_card_number'] = '4807731747657838';
399 // $defaults['cvv2'] = '000';
400 // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
403 //setting default join date if there is no join date
404 if (empty($defaults['join_date'])) {
405 $defaults['join_date'] = date('Y-m-d');
408 if (!empty($defaults['membership_end_date'])) {
409 $this->assign('endDate', $defaults['membership_end_date']);
416 * Build the form object.
418 public function buildQuickForm() {
420 $this->buildQuickEntityForm();
421 $this->assign('currency', CRM_Core_BAO_Country
::defaultCurrencySymbol());
422 $isUpdateToExistingRecurringMembership = $this->isUpdateToExistingRecurringMembership();
423 // build price set form.
424 $buildPriceSet = FALSE;
425 if ($this->_priceSetId ||
!empty($_POST['price_set_id'])) {
426 if (!empty($_POST['price_set_id'])) {
427 $buildPriceSet = TRUE;
429 $getOnlyPriceSetElements = TRUE;
430 if (!$this->_priceSetId
) {
431 $this->_priceSetId
= $_POST['price_set_id'];
432 $getOnlyPriceSetElements = FALSE;
435 $this->set('priceSetId', $this->_priceSetId
);
436 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
438 $optionsMembershipTypes = [];
439 foreach ($this->_priceSet
['fields'] as $pField) {
440 if (empty($pField['options'])) {
443 foreach ($pField['options'] as $opId => $opValues) {
444 $optionsMembershipTypes[$opId] = CRM_Utils_Array
::value('membership_type_id', $opValues, 0);
448 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
));
450 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
451 $this->assign('contributionType', CRM_Utils_Array
::value('financial_type_id', $this->_priceSet
));
453 // get only price set form elements.
454 if ($getOnlyPriceSetElements) {
459 // use to build form during form rule.
460 $this->assign('buildPriceSet', $buildPriceSet);
462 if ($this->_action
& CRM_Core_Action
::ADD
) {
463 $buildPriceSet = FALSE;
464 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviMember');
465 if (!empty($priceSets)) {
466 $buildPriceSet = TRUE;
469 if ($buildPriceSet) {
470 $this->add('select', 'price_set_id', ts('Choose price set'),
472 '' => ts('Choose price set'),
474 NULL, ['onchange' => "buildAmount( this.value );"]
477 $this->assign('hasPriceSets', $buildPriceSet);
480 if ($this->_action
& CRM_Core_Action
::DELETE
) {
484 'name' => ts('Delete'),
485 'spacing' => ' ',
490 'name' => ts('Cancel'),
496 if ($this->_context
== 'standalone') {
497 $this->addEntityRef('contact_id', ts('Contact'), [
499 'api' => ['extra' => ['email']],
503 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
505 // Throw status bounce when no Membership type or priceset is present
506 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
507 && empty($this->allMembershipTypeDetails
) && empty($priceSets)
509 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
511 // retrieve all memberships
512 $allMembershipInfo = [];
513 foreach ($this->allMembershipTypeDetails
as $key => $values) {
514 if ($this->_mode
&& empty($values['minimum_fee'])) {
518 $memberOfContactId = CRM_Utils_Array
::value('member_of_contact_id', $values);
519 if (empty($selMemTypeOrg[$memberOfContactId])) {
520 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
526 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
528 if (empty($selOrgMemType[$memberOfContactId][$key])) {
529 $selOrgMemType[$memberOfContactId][$key] = CRM_Utils_Array
::value('name', $values);
532 $totalAmount = CRM_Utils_Array
::value('minimum_fee', $values);
533 //CRM-18827 - override the default value if total_amount is submitted
534 if (!empty($this->_submitValues
['total_amount'])) {
535 $totalAmount = $this->_submitValues
['total_amount'];
537 // build membership info array, which is used when membership type is selected to:
538 // - set the payment information block
539 // - set the max related block
540 $allMembershipInfo[$key] = [
541 'financial_type_id' => CRM_Utils_Array
::value('financial_type_id', $values),
542 'total_amount' => CRM_Utils_Money
::format($totalAmount, NULL, '%a'),
543 'total_amount_numeric' => $totalAmount,
544 'auto_renew' => CRM_Utils_Array
::value('auto_renew', $values),
545 'has_related' => isset($values['relationship_type_id']),
546 'max_related' => CRM_Utils_Array
::value('max_related', $values),
550 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
552 // show organization by default, if only one organization in
554 if (count($selMemTypeOrg) == 2) {
555 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
557 //sort membership organization and type, CRM-6099
558 natcasesort($selMemTypeOrg);
559 foreach ($selOrgMemType as $index => $orgMembershipType) {
560 natcasesort($orgMembershipType);
561 $selOrgMemType[$index] = $orgMembershipType;
565 'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
568 if (!empty($this->_recurPaymentProcessors
)) {
569 $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . " buildAutoRenew(this.value, null, '{$this->_mode}');";
572 $this->add('text', 'max_related', ts('Max related'),
573 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'max_related')
576 $sel = &$this->addElement('hierselect',
577 'membership_type_id',
578 ts('Membership Organization and Type'),
582 $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
583 if ($isUpdateToExistingRecurringMembership) {
587 if ($this->_action
& CRM_Core_Action
::ADD
) {
588 $this->add('number', 'num_terms', ts('Number of Terms'), ['size' => 6]);
591 $this->add('text', 'source', ts('Source'),
592 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'source')
595 //CRM-7362 --add campaigns.
598 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'campaign_id');
600 CRM_Campaign_BAO_Campaign
::addCampaign($this, $campaignId);
603 $this->add('select', 'status_id', ts('Membership Status'),
604 ['' => ts('- select -')] + CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label')
607 $statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
608 CRM_Member_StatusOverrideTypes
::getSelectOptions()
610 if ($statusOverride && $isUpdateToExistingRecurringMembership) {
611 $statusOverride->freeze();
614 $this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, ['minDate' => time(), 'time' => FALSE]);
616 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
618 $this->add('text', 'total_amount', ts('Amount'));
619 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
621 $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
623 $this->add('select', 'payment_instrument_id',
624 ts('Payment Method'),
625 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::paymentInstrument(),
626 FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
628 $this->add('text', 'trxn_id', ts('Transaction ID'));
629 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
631 'CRM_Contribute_DAO_Contribution',
637 $this->add('select', 'contribution_status_id',
638 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils
::getContributionStatuses('membership')
640 $this->add('text', 'check_number', ts('Check Number'),
641 CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
645 //add field for amount to allow an amount to be entered that differs from minimum
646 $this->add('text', 'total_amount', ts('Amount'));
648 $this->add('select', 'financial_type_id',
649 ts('Financial Type'),
650 ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
)
653 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
655 $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
656 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
658 $this->addElement('checkbox',
660 ts('Send Confirmation and Receipt?'), NULL,
661 ['onclick' => "showEmailOptions()"]
664 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
666 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
668 // Retrieve the name and email of the contact - this will be the TO for receipt email
669 if ($this->_contactID
) {
670 list($this->_memberDisplayName
,
672 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
674 $this->assign('emailExists', $this->_memberEmail
);
675 $this->assign('displayName', $this->_memberDisplayName
);
678 if ($isUpdateToExistingRecurringMembership && CRM_Member_BAO_Membership
::isCancelSubscriptionSupported($this->_id
)) {
679 $this->assign('cancelAutoRenew',
680 CRM_Utils_System
::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
684 $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
686 $this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
687 $mailingInfo = Civi
::settings()->get('mailing_backend');
688 $this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
690 parent
::buildQuickForm();
696 * @param array $params
697 * (ref.) an assoc array of name/value pairs.
699 * @param array $files
700 * @param CRM_Member_Form_Membership $self
702 * @throws CiviCRM_API3_Exception
704 * mixed true or array of errors
706 public static function formRule($params, $files, $self) {
709 $priceSetId = self
::getPriceSetID($params);
710 $priceSetDetails = self
::getPriceSetDetails($params);
712 $selectedMemberships = self
::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
714 if (!empty($params['price_set_id'])) {
715 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $params, $errors);
717 $priceFieldIDS = self
::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
719 if (!empty($priceFieldIDS)) {
720 $ids = implode(',', $priceFieldIDS);
722 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
723 foreach ($count as $occurrence) {
724 if ($occurrence > 1) {
725 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
729 // Return error if empty $self->_memTypeSelected
730 if (empty($errors) && empty($selectedMemberships)) {
731 $errors['_qf_default'] = ts('Select at least one membership option.');
733 if (!$self->_mode
&& empty($params['record_contribution'])) {
734 $errors['record_contribution'] = ts('Record Membership Payment is required when you use a price set.');
738 if (empty($params['membership_type_id'][1])) {
739 $errors['membership_type_id'] = ts('Please select a membership type.');
741 $numterms = CRM_Utils_Array
::value('num_terms', $params);
742 if ($numterms && intval($numterms) != $numterms) {
743 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
746 if (($self->_mode ||
isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
747 $errors['financial_type_id'] = ts('Please enter the financial Type.');
751 if (!empty($errors) && (count($selectedMemberships) > 1)) {
752 $memberOfContacts = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($selectedMemberships);
753 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
754 foreach ($duplicateMemberOfContacts as $countDuplicate) {
755 if ($countDuplicate > 1) {
756 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
761 if (!empty($errors)) {
765 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
766 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
769 if (!empty($params['is_different_contribution_contact'])) {
770 if (empty($params['soft_credit_type_id'])) {
771 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
773 if (empty($params['soft_credit_contact_id'])) {
774 $errors['soft_credit_contact_id'] = ts('Please select a contact');
778 if (!empty($params['payment_processor_id'])) {
779 // validate payment instrument (e.g. credit card number)
780 CRM_Core_Payment_Form
::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, NULL);
784 if (!empty($params['join_date'])) {
786 $joinDate = CRM_Utils_Date
::processDate($params['join_date']);
788 foreach ($selectedMemberships as $memType) {
790 if (!empty($params['start_date'])) {
791 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
794 // if end date is set, ensure that start date is also set
795 // and that end date is later than start date
797 if (!empty($params['end_date'])) {
798 $endDate = CRM_Utils_Date
::processDate($params['end_date']);
801 $membershipDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($memType);
803 if ($startDate && CRM_Utils_Array
::value('period_type', $membershipDetails) == 'rolling') {
804 if ($startDate < $joinDate) {
805 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
810 if ($membershipDetails['duration_unit'] == 'lifetime') {
811 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
812 // process to update status based on end-date. The user must change the status now.
813 $result = civicrm_api3('MembershipStatus', 'get', [
815 'is_current_member' => 0,
817 $tmp_statuses = $result['values'];
819 foreach ($tmp_statuses as $cur_stat) {
820 $status_ids[] = $cur_stat['id'];
823 if (empty($params['status_id']) ||
in_array($params['status_id'], $status_ids) == FALSE) {
824 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
827 if (!empty($params['is_override']) && !CRM_Member_StatusOverrideTypes
::isPermanent($params['is_override'])) {
828 $errors['is_override'] = ts('Because you set an End Date for a lifetime membership, This must be set to "Override Permanently"');
833 $errors['start_date'] = ts('Start date must be set if end date is set.');
835 if ($endDate < $startDate) {
836 $errors['end_date'] = ts('End date must be the same or later than start date.');
841 // Default values for start and end dates if not supplied on the form.
842 $defaultDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
849 $startDate = CRM_Utils_Array
::value('start_date',
854 $endDate = CRM_Utils_Array
::value('end_date',
859 //CRM-3724, check for availability of valid membership status.
860 if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes
::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
861 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($startDate,
869 if (empty($calcStatus)) {
870 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
871 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
872 $status = ts('Oops, it looks like there is no valid membership status available for the given membership dates. You can <a href="%1">Configure Membership Status Rules</a>.', [1 => $url]);
874 $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
876 CRM_Core_Session
::setStatus($status, ts('Membership Status Error'), 'error');
882 $errors['join_date'] = ts('Please enter the Member Since.');
885 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes
::isOverridden($params['is_override']) && empty($params['status_id'])) {
886 $errors['status_id'] = ts('Please enter the Membership status.');
889 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes
::isUntilDate($params['is_override'])) {
890 if (empty($params['status_override_end_date'])) {
891 $errors['status_override_end_date'] = ts('Please enter the Membership override end date.');
895 //total amount condition arise when membership type having no
897 if (isset($params['record_contribution'])) {
898 if (CRM_Utils_System
::isNull($params['total_amount'])) {
899 $errors['total_amount'] = ts('Please enter the contribution.');
903 // validate contribution status for 'Failed'.
904 if ($self->_onlinePendingContributionId
&& !empty($params['record_contribution']) &&
905 (CRM_Utils_Array
::value('contribution_status_id', $params) ==
906 array_search('Failed', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
909 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
912 return empty($errors) ?
TRUE : $errors;
916 * Process the form submission.
918 public function postProcess() {
919 if ($this->_action
& CRM_Core_Action
::DELETE
) {
920 CRM_Member_BAO_Membership
::del($this->_id
);
923 // get the submitted form values.
924 $this->_params
= $this->controller
->exportValues($this->_name
);
925 $this->prepareStatusOverrideValues();
929 $this->setUserContext();
933 * Prepares the values related to status override.
935 private function prepareStatusOverrideValues() {
936 $this->setOverrideDateValue();
937 $this->convertIsOverrideValue();
941 * Sets status override end date to empty value if
942 * the selected override option is not 'until date'.
944 private function setOverrideDateValue() {
945 if (!CRM_Member_StatusOverrideTypes
::isUntilDate(CRM_Utils_Array
::value('is_override', $this->_params
))) {
946 $this->_params
['status_override_end_date'] = '';
951 * Convert the value of selected (status override?)
952 * option to TRUE if it indicate an overridden status
953 * or FALSE otherwise.
955 private function convertIsOverrideValue() {
956 $this->_params
['is_override'] = CRM_Member_StatusOverrideTypes
::isOverridden($this->_params
['is_override']);
960 * Send email receipt.
963 * This function is shared with Batch_Entry which has limited overlap
964 * & needs rationalising.
966 * @param CRM_Core_Form $form
968 * @param array $formValues
969 * @param object $membership
971 * @param array $customValues
974 * true if mail was sent successfully
976 public static function emailReceipt(&$form, &$formValues, &$membership, $customValues = NULL) {
977 // retrieve 'from email id' for acknowledgement
978 $receiptFrom = CRM_Utils_Array
::value('from_email_address', $formValues);
980 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
981 if (!empty($formValues['payment_instrument_id'])) {
982 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
983 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
986 $form->assign('customValues', $customValues);
989 // @todo move this outside shared code as Batch entry just doesn't
990 $form->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
995 $date = CRM_Utils_Date
::format($form->_params
['credit_card_exp_date']);
996 $date = CRM_Utils_Date
::mysqlToIso($date);
997 $form->assign('credit_card_exp_date', $date);
998 $form->assign('credit_card_number',
999 CRM_Utils_System
::mungeCreditCard($form->_params
['credit_card_number'])
1001 $form->assign('credit_card_type', $form->_params
['credit_card_type']);
1002 $form->assign('contributeMode', 'direct');
1003 $form->assign('isAmountzero', 0);
1004 $form->assign('is_pay_later', 0);
1005 $form->assign('isPrimary', 1);
1008 $form->assign('module', 'Membership');
1009 $form->assign('contactID', $formValues['contact_id']);
1011 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
1013 if (!empty($formValues['contribution_id'])) {
1014 $form->assign('contributionID', $formValues['contribution_id']);
1016 elseif (isset($form->_onlinePendingContributionId
)) {
1017 $form->assign('contributionID', $form->_onlinePendingContributionId
);
1020 if (!empty($formValues['contribution_status_id'])) {
1021 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
1022 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
1025 if (!empty($formValues['is_renew'])) {
1026 $form->assign('receiptType', 'membership renewal');
1029 $form->assign('receiptType', 'membership signup');
1031 $form->assign('receive_date', CRM_Utils_Array
::value('receive_date', $formValues));
1032 $form->assign('formValues', $formValues);
1034 if (empty($lineItem)) {
1035 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($membership->start_date
, '%B %E%f, %Y'));
1036 if (!CRM_Utils_System
::isNull($membership->end_date
)) {
1037 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($membership->end_date
, '%B %E%f, %Y'));
1039 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
1042 // @todo - if we have to figure out if this is for batch processing it doesn't belong in the shared function.
1043 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1044 if ((empty($form->_contributorDisplayName
) ||
empty($form->_contributorEmail
)) ||
$isBatchProcess) {
1045 // in this case the form is being called statically from the batch editing screen
1046 // having one class in the form layer call another statically is not greate
1047 // & we should aim to move this function to the BAO layer in future.
1048 // however, we can assume that the contact_id passed in by the batch
1049 // function will be the recipient
1050 list($form->_contributorDisplayName
, $form->_contributorEmail
)
1051 = CRM_Contact_BAO_Contact_Location
::getEmailDetails($formValues['contact_id']);
1052 if (empty($form->_receiptContactId
) ||
$isBatchProcess) {
1053 $form->_receiptContactId
= $formValues['contact_id'];
1056 // @todo determine isEmailPdf in calling function.
1057 $template = CRM_Core_Smarty
::singleton();
1058 $taxAmt = $template->get_template_vars('dataArray');
1059 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
1060 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
1061 $invoicing = CRM_Utils_Array
::value('invoicing', $prefixValue);
1062 if ((!empty($taxAmt) ||
isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1066 $isEmailPdf = FALSE;
1069 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1071 'groupName' => 'msg_tpl_workflow_membership',
1072 'valueName' => 'membership_offline_receipt',
1073 'contactId' => $form->_receiptContactId
,
1074 'from' => $receiptFrom,
1075 'toName' => $form->_contributorDisplayName
,
1076 'toEmail' => $form->_contributorEmail
,
1077 'PDFFilename' => ts('receipt') . '.pdf',
1078 'isEmailPdf' => $isEmailPdf,
1079 'contributionId' => $formValues['contribution_id'],
1080 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
),
1090 * This is also accessed by unit tests.
1092 public function submit() {
1093 $isTest = ($this->_mode
== 'test') ?
1 : 0;
1094 $this->storeContactFields($this->_params
);
1095 $this->beginPostProcess();
1096 $joinDate = $startDate = $endDate = NULL;
1097 $membershipTypes = $membership = $calcDate = [];
1098 $membershipType = NULL;
1099 $paymentInstrumentID = $this->_paymentProcessor
['object']->getPaymentInstrumentID();
1100 $params = $softParams = $ids = [];
1103 $this->processBillingAddress();
1104 $formValues = $this->_params
;
1105 $formValues = $this->setPriceSetParameters($formValues);
1108 $ids['membership'] = $params['id'] = $this->_id
;
1110 $ids['userId'] = CRM_Core_Session
::singleton()->get('userID');
1112 // Set variables that we normally get from context.
1113 // In form mode these are set in preProcess.
1114 //TODO: set memberships, fixme
1115 $this->setContextVariables($formValues);
1117 $this->_memTypeSelected
= self
::getSelectedMemberships(
1121 if (empty($formValues['financial_type_id'])) {
1122 $formValues['financial_type_id'] = $this->_priceSet
['financial_type_id'];
1125 $config = CRM_Core_Config
::singleton();
1127 $membershipTypeValues = [];
1128 foreach ($this->_memTypeSelected
as $memType) {
1129 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1132 //take the required membership recur values.
1133 if ($this->_mode
&& !empty($formValues['auto_renew'])) {
1134 $params['is_recur'] = $formValues['is_recur'] = TRUE;
1136 'frequency_interval' => 'duration_interval',
1137 'frequency_unit' => 'duration_unit',
1141 foreach ($this->_memTypeSelected
as $memType) {
1142 $recurMembershipTypeValues = CRM_Utils_Array
::value($memType,
1143 $this->_recurMembershipTypes
, []
1145 foreach ($mapping as $mapVal => $mapParam) {
1146 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array
::value($mapParam,
1147 $recurMembershipTypeValues
1150 $formValues[$mapVal] = CRM_Utils_Array
::value($mapParam,
1151 $recurMembershipTypeValues
1159 $isQuickConfig = $this->_priceSet
['is_quick_config'];
1163 $lineItem = [$this->_priceSetId
=> []];
1165 // BEGIN Fix for dev/core/issues/860
1166 // Prepare $feeBlock for call to buildAmount hook - code based on
1167 // CRM_Price_BAO_PriceSet::buildPriceSet().
1168 $feeBlock = &$this->_priceSet
['fields'];
1169 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1170 foreach ($feeBlock as $key => $value) {
1171 foreach ($value['options'] as $k => $options) {
1172 if (!CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($options['financial_type_id']))) {
1173 unset($feeBlock[$key]['options'][$k]);
1176 if (empty($feeBlock[$key]['options'])) {
1177 unset($feeBlock[$key]);
1181 // Call buildAmount hook.
1182 CRM_Utils_Hook
::buildAmount('membership', $this, $feeBlock);
1183 // END Fix for dev/core/issues/860
1185 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1186 $formValues, $lineItem[$this->_priceSetId
], NULL, $this->_priceSetId
);
1188 if (CRM_Utils_Array
::value('tax_amount', $formValues)) {
1189 $params['tax_amount'] = $formValues['tax_amount'];
1191 $params['total_amount'] = CRM_Utils_Array
::value('amount', $formValues);
1192 if (!empty($lineItem[$this->_priceSetId
])) {
1193 foreach ($lineItem[$this->_priceSetId
] as &$li) {
1194 if (!empty($li['membership_type_id'])) {
1195 if (!empty($li['membership_num_terms'])) {
1196 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1200 ///CRM-11529 for quick config backoffice transactions
1201 //when financial_type_id is passed in form, update the
1202 //lineitems with the financial type selected in form
1203 $submittedFinancialType = CRM_Utils_Array
::value('financial_type_id', $formValues);
1204 if ($isQuickConfig && $submittedFinancialType) {
1205 $li['financial_type_id'] = $submittedFinancialType;
1210 $params['contact_id'] = $this->_contactID
;
1216 'status_override_end_date',
1220 foreach ($fields as $f) {
1221 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1225 // when is_override false ignore is_admin statuses during membership
1226 // status calculation. similarly we did fix for import in CRM-3570.
1227 if (empty($params['is_override'])) {
1228 $params['exclude_is_admin'] = TRUE;
1231 // process date params to mysql date format.
1233 'join_date' => 'joinDate',
1234 'start_date' => 'startDate',
1235 'end_date' => 'endDate',
1237 foreach ($dateTypes as $dateField => $dateVariable) {
1238 $
$dateVariable = CRM_Utils_Date
::processDate($formValues[$dateField]);
1241 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array
::value('num_terms', $formValues) : NULL;
1244 foreach ($this->_memTypeSelected
as $memType) {
1245 if (empty($memTypeNumTerms)) {
1246 $memTypeNumTerms = CRM_Utils_Array
::value($memType, $termsByType, 1);
1248 $calcDates[$memType] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
1249 $joinDate, $startDate, $endDate, $memTypeNumTerms
1253 foreach ($calcDates as $memType => $calcDate) {
1254 foreach (array_keys($dateTypes) as $d) {
1255 //first give priority to form values then calDates.
1256 $date = CRM_Utils_Array
::value($d, $formValues);
1258 $date = CRM_Utils_Array
::value($d, $calcDate);
1261 $membershipTypeValues[$memType][$d] = CRM_Utils_Date
::processDate($date);
1265 foreach ($this->_memTypeSelected
as $memType) {
1266 if (array_key_exists('max_related', $formValues)) {
1267 // max related memberships - take from form or inherit from membership type
1268 $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array
::value('max_related', $formValues);
1270 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
1274 $membershipTypes[$memType] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1279 $membershipType = implode(', ', $membershipTypes);
1281 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1282 list($userName) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($ids['userId']);
1284 //CRM-13981, allow different person as a soft-contributor of chosen type
1285 if ($this->_contributorContactID
!= $this->_contactID
) {
1286 $params['contribution_contact_id'] = $this->_contributorContactID
;
1287 if (!empty($formValues['soft_credit_type_id'])) {
1288 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1289 $softParams['contact_id'] = $this->_contactID
;
1293 $pendingMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
1295 if (!empty($formValues['record_contribution'])) {
1296 $recordContribution = [
1298 'financial_type_id',
1299 'payment_instrument_id',
1301 'contribution_status_id',
1309 foreach ($recordContribution as $f) {
1310 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
1313 if (!$this->_onlinePendingContributionId
) {
1314 if (empty($formValues['source'])) {
1315 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', [
1316 1 => $membershipType,
1321 $params['contribution_source'] = $formValues['source'];
1325 $completedContributionStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1326 if (empty($params['is_override']) &&
1327 CRM_Utils_Array
::value('contribution_status_id', $params) != $completedContributionStatusId
1329 $params['status_id'] = $pendingMembershipStatusId;
1330 $params['skipStatusCal'] = TRUE;
1331 $params['is_pay_later'] = 1;
1332 $this->assign('is_pay_later', 1);
1335 if (!empty($formValues['send_receipt'])) {
1336 $params['receipt_date'] = CRM_Utils_Array
::value('receive_date', $formValues);
1339 //insert financial type name in receipt.
1340 $formValues['contributionType_name'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
1341 $formValues['financial_type_id']
1345 // process line items, until no previous line items.
1346 if (!empty($lineItem)) {
1347 $params['lineItems'] = $lineItem;
1348 $params['processPriceSet'] = TRUE;
1350 $createdMemberships = [];
1352 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $formValues, 0);
1354 //CRM-20264 : Store CC type and number (last 4 digit) during backoffice or online payment
1355 $params['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $this->_params
);
1356 $params['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $this->_params
);
1358 if (!$isQuickConfig) {
1359 $params['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet',
1365 $params['financial_type_id'] = CRM_Utils_Array
::value('financial_type_id', $formValues);
1368 //get the payment processor id as per mode. Try removing in favour of beginPostProcess.
1369 $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1370 $params['register_date'] = date('YmdHis');
1372 // add all the additional payment params we need
1373 $formValues['amount'] = $params['total_amount'];
1374 // @todo this is a candidate for beginPostProcessFunction.
1375 $formValues['currencyID'] = $config->defaultCurrency
;
1376 $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
1377 $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
1378 $formValues['financial_type_id'] = $params['financial_type_id'];
1380 // at this point we've created a contact and stored its address etc
1381 // all the payment processors expect the name and address to be in the
1382 // so we copy stuff over to first_name etc.
1383 $paymentParams = $formValues;
1384 $paymentParams['contactID'] = $this->_contributorContactID
;
1385 //CRM-10377 if payment is by an alternate contact then we need to set that person
1386 // as the contact in the payment params
1387 if ($this->_contributorContactID
!= $this->_contactID
) {
1388 if (!empty($formValues['soft_credit_type_id'])) {
1389 $softParams['contact_id'] = $params['contact_id'];
1390 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1393 if (!empty($formValues['send_receipt'])) {
1394 $paymentParams['email'] = $this->_contributorEmail
;
1397 // This is a candidate for shared beginPostProcess function.
1398 // @todo Do we need this now we have $this->formatParamsForPaymentProcessor() ?
1399 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $formValues, $paymentParams, TRUE);
1400 // CRM-7137 -for recurring membership,
1401 // we do need contribution and recurring records.
1403 if (!empty($paymentParams['is_recur'])) {
1404 $financialType = new CRM_Financial_DAO_FinancialType();
1405 $financialType->id
= $params['financial_type_id'];
1406 $financialType->find(TRUE);
1407 $this->_params
= $formValues;
1409 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1413 'contact_id' => $this->_contributorContactID
,
1414 'line_item' => $lineItem,
1415 'is_test' => $isTest,
1416 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $paymentParams),
1417 'contribution_page_id' => CRM_Utils_Array
::value('contribution_page_id', $formValues),
1418 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1419 'thankyou_date' => CRM_Utils_Array
::value('thankyou_date', $paymentParams),
1420 'payment_instrument_id' => $paymentInstrumentID,
1428 //create new soft-credit record, CRM-13981
1430 $softParams['contribution_id'] = $contribution->id
;
1431 $softParams['currency'] = $contribution->currency
;
1432 $softParams['amount'] = $contribution->total_amount
;
1433 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1436 $paymentParams['contactID'] = $this->_contactID
;
1437 $paymentParams['contributionID'] = $contribution->id
;
1438 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1439 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1440 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1441 $params['contribution_id'] = $paymentParams['contributionID'];
1442 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1444 $paymentStatus = NULL;
1446 if ($params['total_amount'] > 0.0) {
1447 $payment = $this->_paymentProcessor
['object'];
1449 $result = $payment->doPayment($paymentParams);
1450 $formValues = array_merge($formValues, $result);
1451 $paymentStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $formValues['payment_status_id']);
1452 // Assign amount to template if payment was successful.
1453 $this->assign('amount', $params['total_amount']);
1455 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
1456 if (!empty($paymentParams['contributionID'])) {
1457 CRM_Contribute_BAO_Contribution
::failPayment($paymentParams['contributionID'], $this->_contactID
,
1460 if (!empty($paymentParams['contributionRecurID'])) {
1461 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1464 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
1465 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/view/membership',
1466 "reset=1&action=add&cid={$this->_contactID}&context=membership&mode={$this->_mode}"
1472 if ($paymentStatus !== 'Completed') {
1473 $params['status_id'] = $pendingMembershipStatusId;
1474 $params['skipStatusCal'] = TRUE;
1475 // unset send-receipt option, since receipt will be sent when ipn is received.
1476 unset($formValues['send_receipt'], $formValues['send_receipt']);
1477 //as membership is pending set dates to null.
1479 'join_date' => 'joinDate',
1480 'start_date' => 'startDate',
1481 'end_date' => 'endDate',
1483 foreach ($memberDates as $dv) {
1485 foreach ($this->_memTypeSelected
as $memType) {
1486 $membershipTypeValues[$memType][$dv] = NULL;
1490 $now = date('YmdHis');
1491 $params['receive_date'] = date('Y-m-d H:i:s');
1492 $params['invoice_id'] = $formValues['invoiceID'];
1493 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1494 [1 => $membershipType, 2 => $userName]
1496 $params['source'] = $formValues['source'] ?
$formValues['source'] : $params['contribution_source'];
1497 $params['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $result);
1498 $params['is_test'] = ($this->_mode
== 'live') ?
0 : 1;
1499 if (!empty($formValues['send_receipt'])) {
1500 $params['receipt_date'] = $now;
1503 $params['receipt_date'] = NULL;
1506 $this->set('params', $formValues);
1507 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
1508 $this->assign('receive_date',
1509 CRM_Utils_Date
::mysqlToIso($params['receive_date'])
1512 // required for creating membership for related contacts
1513 $params['action'] = $this->_action
;
1515 //create membership record.
1517 foreach ($this->_memTypeSelected
as $memType) {
1519 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1521 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1524 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1526 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1527 $membershipParams['soft_credit'] = $softParams;
1529 if (isset($result['fee_amount'])) {
1530 $membershipParams['fee_amount'] = $result['fee_amount'];
1532 // This is required to trigger the recording of the membership contribution in the
1533 // CRM_Member_BAO_Membership::Create function.
1534 // @todo stop setting this & 'teach' the create function to respond to something
1535 // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
1537 // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
1538 $membershipParams['contribution_status_id'] = CRM_Utils_Array
::value('payment_status_id', $result);
1539 if (!empty($paymentParams['is_recur'])) {
1540 // The earlier process created the line items (although we want to get rid of the earlier one in favour
1541 // of a single path!
1542 unset($membershipParams['lineItems']);
1544 $membershipParams['payment_instrument_id'] = $paymentInstrumentID;
1545 // @todo stop passing $ids (membership and userId only are set above)
1546 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1547 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1548 unset($params['lineItems']);
1549 $this->_membershipIDs
[] = $membership->id
;
1550 $createdMemberships[$memType] = $membership;
1556 $params['action'] = $this->_action
;
1557 if ($this->_onlinePendingContributionId
&& !empty($formValues['record_contribution'])) {
1559 // update membership as well as contribution object, CRM-4395
1560 $params['contribution_id'] = $this->_onlinePendingContributionId
;
1561 $params['componentId'] = $params['id'];
1562 $params['componentName'] = 'contribute';
1563 $result = CRM_Contribute_BAO_Contribution
::transitionComponents($params, TRUE);
1564 if (!empty($result) && !empty($params['contribution_id'])) {
1566 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution_id']);
1567 $itemId = key($lineItems);
1568 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1570 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1571 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1572 $lineItems[$itemId]['id'] = $itemId;
1573 $lineItem[$priceSetId] = $lineItems;
1574 $contributionBAO = new CRM_Contribute_BAO_Contribution();
1575 $contributionBAO->id
= $params['contribution_id'];
1576 $contributionBAO->contact_id
= $params['contact_id'];
1577 $contributionBAO->find();
1578 CRM_Price_BAO_LineItem
::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
1580 //create new soft-credit record, CRM-13981
1582 $softParams['contribution_id'] = $params['contribution_id'];
1583 while ($contributionBAO->fetch()) {
1584 $softParams['currency'] = $contributionBAO->currency
;
1585 $softParams['amount'] = $contributionBAO->total_amount
;
1587 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1591 //carry updated membership object.
1592 $membership = new CRM_Member_DAO_Membership();
1593 $membership->id
= $this->_id
;
1594 $membership->find(TRUE);
1597 if ($membership->end_date
) {
1598 //display end date w/ status message.
1599 $endDate = $membership->end_date
;
1601 if (!in_array($membership->status_id
, [
1603 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1604 array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus()),
1610 // suppress form values in template.
1611 $this->assign('cancelled', $cancelled);
1613 $createdMemberships[] = $membership;
1617 foreach ($this->_memTypeSelected
as $memType) {
1618 if ($count && !empty($formValues['record_contribution']) &&
1619 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1621 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1624 // @todo figure out why recieve_date isn't being set right here.
1625 if (empty($params['receive_date'])) {
1626 $params['receive_date'] = date('Y-m-d H:i:s');
1628 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
1629 if (!empty($formValues['int_amount'])) {
1631 foreach ($formValues as $key => $value) {
1632 if (strstr($key, 'txt-price')) {
1633 $init_amount[$key] = $value;
1636 $membershipParams['init_amount'] = $init_amount;
1639 if (!empty($softParams)) {
1640 $membershipParams['soft_credit'] = $softParams;
1642 // @todo stop passing $ids (membership and userId only are set above)
1643 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1644 $params['contribution'] = CRM_Utils_Array
::value('contribution', $membershipParams);
1645 unset($params['lineItems']);
1646 // skip line item creation for next interation since line item(s) are already created.
1647 $params['skipLineItem'] = TRUE;
1649 $this->_membershipIDs
[] = $membership->id
;
1650 $createdMemberships[$memType] = $membership;
1655 $isRecur = CRM_Utils_Array
::value('is_recur', $params);
1656 if (($this->_action
& CRM_Core_Action
::UPDATE
)) {
1657 $this->addStatusMessage($this->getStatusMessageForUpdate($membership, $endDate));
1659 elseif (($this->_action
& CRM_Core_Action
::ADD
)) {
1660 $this->addStatusMessage($this->getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
1661 $isRecur, $calcDates));
1664 if (!empty($lineItem[$this->_priceSetId
])) {
1665 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
1666 $invoicing = CRM_Utils_Array
::value('invoicing', $invoiceSettings);
1668 $totalTaxAmount = 0;
1669 foreach ($lineItem[$this->_priceSetId
] as & $priceFieldOp) {
1670 if (!empty($priceFieldOp['membership_type_id'])) {
1671 $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') : '-';
1672 $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') : '-';
1675 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1677 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1679 $totalTaxAmount +
= $priceFieldOp['tax_amount'];
1684 foreach ($lineItem[$this->_priceSetId
] as $key => $value) {
1685 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1686 if (isset($dataArray[$value['tax_rate']])) {
1687 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
1690 $dataArray[$value['tax_rate']] = CRM_Utils_Array
::value('tax_amount', $value);
1695 $this->assign('totalTaxAmount', $totalTaxAmount);
1696 // Not sure why would need this on Submit.... unless it's being used when sending mails in which case this is the wrong place
1697 $this->assign('taxTerm', $this->getSalesTaxTerm());
1699 $this->assign('dataArray', $dataArray);
1702 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1704 $receiptSend = FALSE;
1705 $contributionId = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
);
1706 $membershipIds = $this->_membershipIDs
;
1707 if ($contributionId && !empty($membershipIds)) {
1708 $contributionDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails(
1709 CRM_Export_Form_Select
::MEMBER_EXPORT
, $this->_membershipIDs
);
1710 if ($contributionDetails[$membership->id
]['contribution_status'] == 'Completed') {
1711 $receiptSend = TRUE;
1715 $receiptSent = FALSE;
1716 if (!empty($formValues['send_receipt']) && $receiptSend) {
1717 $formValues['contact_id'] = $this->_contactID
;
1718 $formValues['contribution_id'] = $contributionId;
1719 // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
1720 // handled in the receipt. But by setting one we avoid breaking templates for now
1721 // although at some point we should switch in the templates.
1722 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
1723 // send email receipt
1724 $this->assignBillingName();
1725 $mailSend = $this->emailMembershipReceipt($formValues, $membership);
1726 $receiptSent = TRUE;
1729 // finally set membership id if already not set
1731 $this->_id
= $membership->id
;
1734 $this->updateContributionOnMembershipTypeChange($params, $membership);
1735 if ($receiptSent && $mailSend) {
1736 $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail
]));
1739 CRM_Core_Session
::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
1740 $this->setStatusMessage($membership);
1744 * Update related contribution of a membership if update_contribution_on_membership_type_change
1745 * contribution setting is enabled and type is changed on edit
1747 * @param array $inputParams
1748 * submitted form values
1749 * @param CRM_Member_DAO_Membership $membership
1750 * Updated membership object
1753 protected function updateContributionOnMembershipTypeChange($inputParams, $membership) {
1754 if (Civi
::settings()->get('update_contribution_on_membership_type_change') &&
1756 ($this->_action
& CRM_Core_Action
::UPDATE
) &&
1759 // if selected membership doesn't match with earlier membership
1760 !in_array($this->_memType
, $this->_memTypeSelected
)
1762 if (CRM_Utils_Array
::value('is_recur', $inputParams)) {
1763 CRM_Core_Session
::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
1767 // fetch lineitems by updated membership ID
1768 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($membership->id
, 'membership');
1769 // retrieve the related contribution ID
1770 $contributionID = CRM_Core_DAO
::getFieldValue(
1771 'CRM_Member_DAO_MembershipPayment',
1776 // get price fields of chosen price-set
1777 $priceSetDetails = CRM_Utils_Array
::value(
1779 CRM_Price_BAO_PriceSet
::getSetDetail(
1786 // add price field information in $inputParams
1787 self
::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $membership->membership_type_id
);
1789 // update related contribution and financial records
1790 CRM_Price_BAO_LineItem
::changeFeeSelections(
1795 $priceSetDetails['fields'],
1798 CRM_Core_Session
::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
1803 * Add selected price field information in $formValues
1805 * @param array $formValues
1806 * submitted form values
1807 * @param array $priceFields
1808 * Price fields of selected Priceset ID
1809 * @param int $membershipTypeID
1810 * Selected membership type ID
1813 public static function addPriceFieldByMembershipType(&$formValues, $priceFields, $membershipTypeID) {
1814 foreach ($priceFields as $priceFieldID => $priceField) {
1815 if (isset($priceField['options']) && count($priceField['options'])) {
1816 foreach ($priceField['options'] as $option) {
1817 if ($option['membership_type_id'] == $membershipTypeID) {
1818 $formValues["price_{$priceFieldID}"] = $option['id'];
1827 * Set context in session.
1829 protected function setUserContext() {
1830 $buttonName = $this->controller
->getButtonName();
1831 $session = CRM_Core_Session
::singleton();
1833 if ($this->_context
== 'standalone') {
1834 if ($buttonName == $this->getButtonName('upload', 'new')) {
1835 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/member/add',
1836 'reset=1&action=add&context=standalone'
1840 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1841 "reset=1&cid={$this->_contactID}&selectedChild=member"
1845 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1846 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/membership',
1847 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1853 * Get status message for updating membership.
1855 * @param CRM_Member_BAO_Membership $membership
1856 * @param string $endDate
1860 protected function getStatusMessageForUpdate($membership, $endDate) {
1861 // End date can be modified by hooks, so if end date is set then use it.
1862 $endDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1864 $statusMsg = ts('Membership for %1 has been updated.', [1 => $this->_memberDisplayName
]);
1865 if ($endDate && $endDate !== 'null') {
1866 $endDate = CRM_Utils_Date
::customFormat($endDate);
1867 $statusMsg .= ' ' . ts('The membership End Date is %1.', [1 => $endDate]);
1873 * Get status message for create action.
1875 * @param string $endDate
1876 * @param array $membershipTypes
1877 * @param array $createdMemberships
1878 * @param bool $isRecur
1879 * @param array $calcDates
1881 * @return array|string
1883 protected function getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
1884 $isRecur, $calcDates) {
1885 // FIX ME: fix status messages
1888 foreach ($membershipTypes as $memType => $membershipType) {
1889 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', [
1890 1 => $membershipType,
1891 2 => $this->_memberDisplayName
,
1894 $membership = $createdMemberships[$memType];
1895 $memEndDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1897 //get the end date from calculated dates.
1898 if (!$memEndDate && !$isRecur) {
1899 $memEndDate = CRM_Utils_Array
::value('end_date', $calcDates[$memType]);
1902 if ($memEndDate && $memEndDate !== 'null') {
1903 $memEndDate = CRM_Utils_Date
::customFormat($memEndDate);
1904 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', [1 => $memEndDate]);
1907 $statusMsg = implode('<br/>', $statusMsg);
1912 * @param $membership
1914 protected function setStatusMessage($membership) {
1916 // display message when membership type is changed
1917 if (($this->_action
& CRM_Core_Action
::UPDATE
) && $this->_id
&& !in_array($this->_memType
, $this->_memTypeSelected
)) {
1918 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'membership');
1919 $maxID = max(array_keys($lineItem));
1920 $lineItem = $lineItem[$maxID];
1921 $membershipTypeDetails = $this->allMembershipTypeDetails
[$membership->membership_type_id
];
1922 if ($membershipTypeDetails['financial_type_id'] != $lineItem['financial_type_id']) {
1923 CRM_Core_Session
::setStatus(
1924 ts('The financial types associated with the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its financial type.'),
1928 if ($membershipTypeDetails['minimum_fee'] != $lineItem['line_total']) {
1929 CRM_Core_Session
::setStatus(
1930 ts('The cost of the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its amount.'),
1940 protected function isUpdateToExistingRecurringMembership() {
1942 if ($this->_action
& CRM_Core_Action
::UPDATE
1943 && CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
1944 'contribution_recur_id')
1945 && !CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->getEntityId())) {
1953 * Send a receipt for the membership.
1955 * @param array $formValues
1956 * @param \CRM_Member_BAO_Membership $membership
1960 protected function emailMembershipReceipt($formValues, $membership) {
1961 $customValues = $this->getCustomValuesForReceipt($formValues, $membership);
1963 return self
::emailReceipt($this, $formValues, $membership, $customValues);
1967 * Filter the custom values from the input parameters (for display in the email).
1969 * @todo figure out why the scary code this calls does & document.
1971 * @param array $formValues
1972 * @param \CRM_Member_BAO_Membership $membership
1975 protected function getCustomValuesForReceipt($formValues, $membership) {
1976 $customFields = $customValues = [];
1977 if (property_exists($this, '_groupTree')
1978 && !empty($this->_groupTree
)
1980 foreach ($this->_groupTree
as $groupID => $group) {
1981 if ($groupID == 'info') {
1984 foreach ($group['fields'] as $k => $field) {
1985 $field['title'] = $field['label'];
1986 $customFields["custom_{$k}"] = $field;
1991 $members = [['member_id', '=', $membership->id
, 0, 0]];
1992 // check whether its a test drive
1993 if ($this->_mode
== 'test') {
1994 $members[] = ['member_test', '=', 1, 0, 0];
1997 CRM_Core_BAO_UFGroup
::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1998 return $customValues;